Repository navigation
fix: permission for debug and save buttons - #8095
Conversation
| <el-button v-if="canEdit" type="primary" :disabled="disabled || !hasChanges || applying" @click="handleSave">{{ t('common.actions.save') }}</el-button> | ||
| </div> | ||
| </div> | ||
| </template> |
There was a problem hiding this comment.
Here is the review of the code changes, covering potential issues, logic irregularities, and optimization suggestions.
1. Critical Logic Bug: Redundant/Incorrect done() Call
Location: Inside handleBeforeClose, specifically within the .then() block of the main confirmation dialog (lines ~215-216).
.then(() => {
handleSave()
done() // <-- POTENTIAL ISSUE HERE
})- Issue: In Element Plus (and similar modal libraries), the
before-closefunction receives adonecallback to close the dialog. If you calldone()inside a promise chain after an asynchronous action (likehandleSave), you are manually closing the dialog. However, typicallyhandleSaveemits an event, which might trigger parent component logic. - The Bug: If
handleSavefails or is blocked by validation/prompting in the parent, callingdone()immediately closes the UI without handling the error state properly. More importantly, in many patterns, if you emit a save event and the parent handles the closing, you should not calldone()here. If you do want to close it locally, ensurehandleSavedoesn't rely on async success confirmation before closing. - Specific Irregularity: The original code likely relied on the user clicking "Cancel" in the confirm dialog or letting the dialog stay open until the parent updated it. Adding
done()forces closure. IfhandleSaveis synchronous emission, this is fine. But ifhandleSavetriggers an API call, closing the modal immediately prevents showing loading states or errors related to saving within this modal context. - Recommendation: Verify if
handleSavereturns a promise or if the parent needs to confirm closure. If the goal is simply to close the UI, it's okay, but ensure UX consistency (no sudden close if save fails elsewhere).
2. Logical Inconsistency in handleBeforeClose
Location: The new if (!props.canEdit) block vs. the existing block.
// 无编辑权限:只保留「直接关闭」,不提供保存,任何关闭方式都直接丢弃改动。
if (!props.canEdit) {
return MsgConfirm(t('common.dialogs.notice'), t('workflow.defaultModel.unsavedMessage'), {
confirmButtonText: t('workflow.defaultModel.closeDirectly'),
showCancelButton: false,
confirmButtonType: 'primary',
})
.then(() => done())
.catch(() => done())
}- Irregularity: When
canEditisfalse, there is a warning about "unsavedMessage", but the buttons say "Close Directly". This implies that even read-only users might have accidental changes? No, ifcanEditis false, inputs should presumably be disabled. - Potential Issue: If inputs are truly disabled/read-only,
hasChanges.valueshould always befalse. If so, thebefore-closehook shouldn't even be trying to warn about unsaved changes. You might want to checkif (!props.canEdit || !hasChanges.value)at the start ofhandleBeforeCloseto justreturn done()immediately without any confirmation dialog for read-only view. Showing a confirmation dialog to a read-only user who didn't touch anything is bad UX.
3. Prop Definition & Type Safety
Location: withDefaults(defineProps<...>(), { canEdit: true })
- Positive: Good practice using
withDefaults. - Suggestion: Ensure
modelApiusage is consistent. The typetypeof ModelApi | typeof SystemModelApi ...suggests these are classes. Verify thatnew modelApi()ormodelApi.method()is handled correctly downstream based on the union type. TypeScript might complain about method access if signatures differ significantly between APIs.
4. Template Optimization & UX
Location: Footer template changes.
<el-button plain v-if="canEdit" :disabled="disabled" ...>{{ ... }}</el-button>- Suggestion: Instead of just hiding buttons with
v-if="canEdit", consider if they should be:disabled="!canEdit"and shown greyed out. Hidden controls can be confusing for users wondering why the layout shifts or where the save button went. However, if read-only mode is strict, hiding them is cleaner. - Consistency: Cancel button remains visible even when
canEditis false (presumably to allow closing). Save/Apply-to-all are hidden. This is logically sound for a strict read-only mode.
5. handleSave Guard
Location:
function handleSave() {
if (props.disabled || !props.canEdit || !hasChanges.value) return
emit('save', cloneDeep(modelSettings.value))
}- Good: Correctly guards against saving when
!canEdit. - Note: Since
canEditis used in the template to hide the Save button, this guard in JS is technically redundant unlesshandleSaveis exposed or called programmatically viadefineExpose. It is good defensive coding though.
Summary of Recommendations
- Check
done()placement in.then(): Ensure that forcing the dialog closed immediately after emitting 'save' aligns with your application's global state management. If the parent component usually controls closing, removedone()there. - Simplify Read-Only Experience: Add an early return in
handleBeforeCloseif!props.canEdit && !hasChanges.value(or just!props.canEdit) to bypass the confirmation dialog entirely for read-only users, assuming inputs are disabled. A confirmation dialog for "No Changes / Cannot Edit" is often unnecessary noise. - TypeScript Check: Run
tscto ensure that calling methods onprops.modelApiworks with the union type definition without excessive casting.
| <el-button v-if="canEdit" type="primary" :loading="loading" @click="handleSubmit">{{ t('common.actions.save') }}</el-button> | ||
| </template> | ||
| </MkDrawer> | ||
| </template> |
There was a problem hiding this comment.
Here are the issues and suggestions:
Issues
1. currentModelId used before definition (potential bug)
The canEdit computed references currentModelId.value, but in the diff snippet, currentModelId is not defined until later (it's not visible in the shown context — likely defined below). If currentModelId is declared after the canEdit computed (i.e., with const currentModelId = ref(...) lower in the file), this throws a ReferenceError / TDZ error at setup time when the computed is first evaluated. Move canEdit below currentModelId's declaration.
2. Props/emits ordering & placement
canEdit is now declared between useI18n and defineProps. While functionally fine, it's cleaner to keep defineProps/defineEmits/defineOptions grouped near the top and put computed logic after all reactive state (currentModelId, loading, etc.) has been declared.
3. Button hidden vs disabled
Hiding the Save button (v-if="canEdit") changes UX: users without permissions see an editable form (assuming inputs aren't also gated by canEdit) but no Save button — confusing. Consider:
- Either disable the whole form when
!canEdit(best UX), or - Keep the button but
:disabled="!canEdit".
Currently the form fields appear editable but cannot be saved, which is inconsistent.
4. Submit bypass risk
handleSubmit itself should still guard: if (!canEdit.value) return. Hiding the button is UI-only; programmatic calls (e.g. keyboard Enter, external open flow, tests) could still trigger submit. Defense-in-depth: re-check permission inside handleSubmit.
5. computed import
Ensure computed is imported from vue. The diff doesn't show it being added — if not already imported above line 11, this will break.
6. Permission reactivity
perm.model.system.modify() etc. — confirm these are reactive accessor functions that re-evaluate. If they read non-reactive nuqs/permission state, canEdit may not update on permission changes. Also isSystemResource() / isSystemSharedResource() — verify these are reactive (computed-backed) and don't rely on mutable globals read once.
7. Ordering of permission checks
isSystemResource() is checked before isSystemSharedResource(). If a model can be both system and shared, only the system branch runs. Confirm precedence is intended (usually system is a superset/most restrictive, so this is likely fine — just document it).
Optimization
-
Simplify with early return into a single expression if branches are mutually exclusive:
const canEdit = computed(() => { if (!currentModelId.value) return false if (isSystemResource()) return perm.model.system.modify() if (isSystemSharedResource()) return perm.model.share.modify() return perm.model.workspace.modify(currentModelId.value) })
This is already clear — no change needed there; just fix placement (issue build(deps): bump the pip group across 1 directory with 2 updates #1).
-
Consider memoizing nothing here;
computedalready caches. Fine.
Summary of required fixes
- Move
canEditaftercurrentModelIddeclaration. - Verify
computedis imported. - Add a permission guard inside
handleSubmit. - Decide UX: prefer disabling the form/button over hiding the button, to avoid an editable-but-unsavable form.
| :can-edit="canEdit" | ||
| @save="emit('save', $event)" | ||
| @apply-to-all="emit('applyToAll', $event)" | ||
| @closed="handleDrawerClosed" |
There was a problem hiding this comment.
This code snippet is a Vue 3 Composition API update. Here are the observations:
1. Correctness & Consistency (Good)
- The change is consistent:
canEditis properly added to thepropstype definition, given a default value (true) inwithDefaults, and bound to the child component template using the kebab-case syntax (:can-edit). This follows Vue conventions.
2. Potential Issues
- Redundant Prop Transmission: The parent passes both
disabledandcanEditto the child. These concepts often overlap (e.g., if something is disabled, it usually cannot be edited). If the child component only needs to know "is this view/editable?", sending two boolean flags might lead to inconsistent states (e.g.,disabled=truebutcanEdit=true). Consider consolidating these into a single prop or ensuring the child logic strictly prioritizes one over the other. - Default Value Ambiguity: Defaults to
true. Ensure that when consumers omitcanEdit, the intended behavior is indeed "editable by default." If the component is sensitive (e.g., admin settings),false(read-only by default) is often safer.
3. Optimization/Style Suggestions
- Typing: If
ModelApi,SystemModelApi, andSharedModelApishare a common interface for the properties used by the component, consider using that shared interface instead of the union of specific classes. This simplifies types and reduces coupling. - Prop Naming:
getGraphDataas a prop name suggests a function is being passed. While valid, ensure this is intentional (dependency injection pattern) rather than passing data directly. If it's just to fetch fresh data on demand, consider usingprovide/injector Pinia/Vuex for cleaner state management if applicable.
Verdict: No syntax errors. The main concern is logical consistency between disabled and canEdit.
fix: permission for debug and save buttons