Repository navigation
perf: Optimize file - #7969
perf: Optimize file#7969
Conversation
| <span>{{ folderEntries.all.name }}</span> | ||
| </MkListItem> | ||
| </div> | ||
|
|
There was a problem hiding this comment.
Overall
The refactor is clean and the as const satisfies Record<FolderSource, …> exhaustiveness check is a nice improvement. I found no outright bugs, but there are a few maintainability and reactivity subtleties worth addressing.
Medium-priority concerns
-
Duplicated source of truth for the i18n keys.
getFolderEntry(in@/constants/folder) already knew the mapping source → id + label key. The keysapplication.categories.all, etc. now live in two places. If a locale key or aRESOURCE_TYPEchanges, the two can silently drift.
Recommendation: movefolderEntryKeysinto@/constants/folderand re-implementgetFolderEntryon top of it (or export a typedgetFolderEntryName(source, kind, t)), then import it here. That keeps one authoritative map and still lets you useFOLDER_ENTRY_ID.*directly. -
Verify the IDs are identical to what
getFolderEntryreturned.
The code now assumesgetFolderEntry(source, 'all').id === FOLDER_ENTRY_ID.ALLand the same forshared. IfgetFolderEntryever returned a different/prefixed id (or extra fields likeparentId,isRoot,children),resolveCurrentFolderconsumers would break. The previous code narrowed to{ id, name }so the shape is unchanged, but the id equality is worth a one-line confirmation/test. -
t()andprops.rootLabelare now read outside the computed's tracking scope.
They are only touched inside theget name()accessors, sofolderEntrieswill not re-evaluate when the locale orrootLabelchanges — only whenprops.sourcechanges. In the template this still works (the render effect trackstandrootLabelwhen the getter is invoked), but:watch(() => folderEntries.value.all.name, …)will never fire on locale change.- Reading
.namein a non-reactive context (event handler, exported snapshot, state serialization) captures a stale/untracked value. - Any consumer that memoizes on
folderEntriesidentity will miss locale changes.
Recommendation: if the entries are only used in the template, this is fine — add a short comment. If not, compute the names eagerly inside thecomputedbody instead of using getters.
-
Potential
undefinedonfolderEntryKeys[props.source].
satisfiesprotects you at compile time, but ifprops.sourceoriginates from a route/query param cast toFolderSource, an unexpected value yieldsundefinedandkeys.allthrows. A small guard or a?? fallbackwould make this defensive.
Low-priority / optimizations
-
Hoist
folderEntryKeysout of the setup body. In<script setup>this object literal is allocated once per component instance. Since it is static, move it to module scope (or, preferably, to the constants module per point 1). -
as constis redundant withsatisfieshere. The values are already literal strings, so thesatisfiesclause gives you the key/type checking you want.as constonly addsreadonly, which is harmless — but you can drop it for brevity. -
Template duplication. The two
MkListItemblocks differ only by id/name/icon/active state. A computed list such as
[{ id, name, icon, activeIcon, active }, …]rendered withv-forwould remove the repetition and make future entries (e.g. a "favorites" pseudo-folder) trivial to add. -
Naming.
folderEntries.allis slightly ambiguous for a pseudo-root;root/allRootmight read better. Also consider aligning the name with the existinggetFolderEntryvocabulary so future readers connect the two. -
Do not spread these entries (
{ ...folderEntries.value.all }) anywhere — spreading would eagerly invoke the getters and freeze the translated name. -
Clean up
getFolderEntryif now unused. If no other module imports it after this change, either delete it or mark it deprecated so there is exactly one implementation of the mapping.
| @loaded="handleFolderSelect" | ||
| @select="handleFolderSelect" | ||
| /> | ||
| </template> |
There was a problem hiding this comment.
Reviewed the diff. No obvious critical bug, but there are several points worth checking.
Potential issues
-
Fallback object may not satisfy
FolderItemconst currentFolder = computed<FolderItem>(() => selectedFolder.value ?? { id: FOLDER_ENTRY_ID.ALL, name: t('application.categories.all'), } )
If
FolderItemhas required fields beyondidandname, this will either fail type-checking or create an incomplete object at runtime. This is the main risk of removinggetFolderEntry().Safer options:
- Keep using
getFolderEntry()to build the default folder. - Or create a dedicated helper that returns a valid
FolderItem. - Avoid
as FolderItemunless the missing fields are deliberately irrelevant.
- Keep using
-
currentFolderIdduplicatescurrentFolder.id
currentFolderIdis still mutable state:const currentFolderId = ref<string>(FOLDER_ENTRY_ID.ALL)
but it is always derived from
currentFolder.value.idinsidehandleFolderSelect. This can become inconsistent ifselectedFolderis changed elsewhere.Prefer:
const currentFolderId = computed(() => currentFolder.value.id)
Then remove the assignment in
handleFolderSelect. -
@loaded="handleFolderSelect"relies on the event payload contract
The old code had:function handleFolderLoaded(folder?: FolderItem) { handleFolderSelect(folder ?? allApplicationsFolder.value) }
The new code directly binds:
@loaded="handleFolderSelect"
This is fine if
loadedemitsundefinedwhen there is no folder and you intentionally want the computed fallback. But ifloadedcan emitnull, an array, or fire after a user selection, the behavior may be surprising.If the contract is not guaranteed, keep a small adapter:
function handleFolderLoaded(folder?: FolderItem | null) { handleFolderSelect(folder ?? undefined) }
-
selectedFolderis typed asFolderItem | undefined, but the template may passnull
If theloadedevent emitsnull, TypeScript may not catch it through the template. Normalize it:selectedFolder.value = folder ?? undefined
-
No refresh when folder ID is the same but folder metadata changes
if (previousFolderId !== currentFolderId.value) { cancelBatchSelection() refreshApplications() }
This matches the old behavior, so it is not a regression. But if folder name/permissions can change while the ID stays the same, the UI may need to update more state.
Optimization suggestions
- Derive
currentFolderIdfromcurrentFolderinstead of storing it separately. - Reuse a valid default
FolderItemhelper instead of constructing an inline fallback object. - Consider separating
@loadedand@selecthandlers if their semantics differ. - If
currentFolderis only used foridandname, consider narrowing its type instead of forcingFolderItem.
Example cleanup:
const selectedFolder = ref<FolderItem>()
const currentFolder = computed<FolderItem>(() =>
selectedFolder.value ?? getFolderEntry(RESOURCE_TYPE.APPLICATION, 'all', t)
)
const currentFolderId = computed(() => currentFolder.value.id)
function handleFolderSelect(folder?: FolderItem | null) {
const previousFolderId = currentFolder.value.id
selectedFolder.value = folder ?? undefined
if (previousFolderId !== currentFolder.value.id) {
cancelBatchSelection()
refreshApplications()
}
}Overall, the refactor is reasonable, but the inline fallback FolderItem and duplicated currentFolderId state are the two things I would address before merging.
| @loaded="handleFolderSelect" | ||
| @select="handleFolderSelect" | ||
| /> | ||
| </template> |
There was a problem hiding this comment.
Reviewed. The logic is mostly coherent, but there are a few risks and cleanup opportunities.
-
Fallback
FolderItemmay be incomplete{ id: FOLDER_ENTRY_ID.ALL, name: t('knowledge.categories.all') }
If
FolderItemrequires additional fields such astype,source,parentId,children, permissions, etc., this will either fail TypeScript checking or break consumers that expect a full folder object. The previousgetFolderEntry(...)likely returned a complete object. -
Fallback object is recreated on every
currentFolder.valueaccess
This can cause object identity churn and unnecessary watcher/rendering updates. Prefer a stable computed fallback:const allKnowledgeFolder = computed<FolderItem>(() => getFolderEntry(RESOURCE_TYPE.KNOWLEDGE, 'all', t) ) const selectedFolder = ref<FolderItem>() const currentFolder = computed<FolderItem>( () => selectedFolder.value ?? allKnowledgeFolder.value )
Or, if avoiding
getFolderEntry, define a complete stable fallback object. -
handleFolderSelectcan be clearer and avoid extra computed reads
Compute the next id once:function handleFolderSelect(folder?: FolderItem) { const previousFolderId = currentFolder.value.id const nextFolderId = folder?.id ?? FOLDER_ENTRY_ID.ALL selectedFolder.value = folder currentFolderId.value = nextFolderId if (previousFolderId !== nextFolderId) { cancelBatchSelection() refreshKnowledge() } }
This avoids relying on
currentFolder.valueafter mutatingselectedFolder. -
Check
@loadedsemantics
ReusinghandleFolderSelectfor@loadedmeans aloadedevent withundefinedresets the selection toALLand may callrefreshKnowledge()if the previous folder was notALL. Ifloadedcan fire more than once or after a user selection, this could unexpectedly clear the selection or trigger a duplicate refresh. Ifloadedonly fires once during initialization, this is fine. -
currentFolderis now read-only
It was previously aref, so any other code assigningcurrentFolder.value = ...would now fail or silently need refactoring. Make sure there are no remaining assignments outside this diff. -
Duplicated translation/label logic
Hardcodingt('knowledge.categories.all')duplicates whatgetFolderEntrycentralizes. If the label or folder metadata changes, this fallback may drift. ReusinggetFolderEntryis safer unless there is a clear reason to remove it. -
Potential state duplication
selectedFolderandcurrentFolderIdare two sources of truth. IfFolderTreeupdatesv-model="currentFolderId"without emittingselect, they can become inconsistent. Ensureselectis always emitted, or derive one from the other.
Overall: the approach is reasonable, but I would keep a stable/full FolderItem fallback and verify the loaded event behavior.
perf: Optimize file