Repository navigation
feat: internationalize navigation, API keys, appearance settings, and operation logs - #8073
Conversation
| <el-button v-if="perm.system.appearance.edit()" type="primary" @click="handleSaveTheme">{{ t('appearance.saveAndApply') }}</el-button> | ||
| </component> | ||
| </template> | ||
| </MkViewLayout> |
There was a problem hiding this comment.
Here are the issues and suggestions:
Bugs / Potential Issues
-
THEME_IMAGE_SETTINGStype mismatch: It wasThemeImageSetting[](plain), now it's areactivearray whoselabel/descriptionfields areComputedRef<string>instead ofstring. This breaks theThemeImageSettingcontract. If anything reads these as strings (e.g., rendering directly in template without unwrapping, or passing to APIs), it will fail. Either update the interface to acceptstring | ComputedRef<string>, or don't make them computed — a plaincomputed(() => THEME_IMAGE_SETTINGS)mapping to strings is safer. -
reactiveon computed is unnecessary: The array itself has no reactive nested state you mutate; wrapping inreactivejust makes it deeply reactive for no benefit. Considerconst THEME_IMAGE_SETTINGS = computed<ThemeImageSetting[]>(() => [...])instead. Note that.valueaccess would then be needed in template auto-unwrap only at top level — verify all consumers. -
formRuleschanged from object toComputedRef: Fine for reactivity with i18n locale switches, but ensure:rules="formRules"still works (Element Plus accepts a ref in template auto-unwrapping — OK). However, adding:validate-on-rule-change="false"was necessary; good catch, but double-check validation still triggers on blur/submit after locale change. -
i18n keys used in JS before component context may resolve early:
t(...)insideformRulescomputed is lazy (good), butTHEME_IMAGE_SETTINGSstring templating like${t('auth.login.label')} Logowill not be reactive inside the string concat unless wrapped in the outercomputed. Verify each entry is fully wrapped in its owncomputed.
Correctness / Robustness
-
Hardcoded
10 MBvsMAX_IMAGE_SIZE: The message interpolates{ size: 10 }while the actual limit isMAX_IMAGE_SIZE = 10MB. Derive the number:{ size: MAX_IMAGE_SIZE / 1024 / 1024 }to avoid drift. -
Interpolation params in description strings:
dimensions: '48*48',vector: '1728*1117'etc. are hardcoded in the component. If translations need different unit formats, consider passing through translation keys or keeping numeric values consistent across locales. -
reactivearray +ThemeImageFieldindexing:themeSetting[field]writes — fine — but confirmfieldvalues (icon,loginLogo,loginImage) exist inThemeSettingForm. -
Missing i18n for
THEME_OPTIONSlabels: Thoselabelvalues (e.g., theme color names) remain hardcoded Chinese. Inconsistent with the rest of the localization effort. -
useI18n({ useScope: 'global' }): Ensure the global scope contains all the referenced keys (appearance.*,common.options.custom,layout.userManual, etc.), and thatauth.login.label,common.messages.saveSuccessexist. Missing keys will render raw key strings silently. -
MsgSuccess(t('common.messages.saveSuccess'))inside.thenchain: Sincetis captured at setup, it's fine — but if locale changes mid-flight, message uses latest locale (acceptable). No issue. -
el-radio-button :labeldeprecation: In recent Element Plus,valuereplaceslabelfor the bound value andlabelis slot text. You kept:label="t('common.options.custom')" value="custom"— correct for new API, but verify your Element Plus version matches; mixed usage elsewhere (:labelon other radio buttons still passing label as both) could be inconsistent. -
Accessibility: Localized strings used as
placeholdermay be longer/shorter in other languages;maxlengthunchanged is fine, but noaria-labeladditions — optional.
Optimization Suggestions
-
Prefer
const THEME_IMAGE_SETTINGS = computed(() => [...])and read.valueexplicitly where needed, rather thanreactive, to avoid confusing unwrapping semantics. -
Extract repeated
${t('x')} Logopatterns into helper functions/keys (e.g.,appearance.websiteLogoLabel) so translators control full phrasing/word order (important for languages where "Logo 网站" ordering differs). This is the main i18n concern — string concatenation breaks RTL and word-order localization. -
Centralize the size limit: derive both
MAX_IMAGE_SIZE(or display) from one constant. -
Consider
const { t } = useI18n()default scope if all keys are global; explicituseScope: 'global'is fine but be consistent across components. -
Add a lightweight dev-time guard (e.g.,
import.meta.env.DEV && console.warn) when required i18n keys are missing — helps catch typos likeappearance.name.requiredMessagevsappearance.name.label.
Summary of highest priority fixes
- Type mismatch of
THEME_IMAGE_SETTINGS(ComputedRefvsstring). - Replace string-concatenated labels with dedicated i18n keys.
- Derive size numbers from
MAX_IMAGE_SIZE. - Localize remaining hardcoded
THEME_OPTIONSlabels.
| <el-table-column prop="username" :label="t('common.labels.creator')" min-width="100" show-overflow-tooltip /> | ||
| </MkTable> | ||
| </template> | ||
| </MkDrawer> |
There was a problem hiding this comment.
Here is the analysis of the code changes, focusing on irregularities, potential issues, and optimization suggestions.
1. Critical Issue: Incorrect Usage of reactive with computed
Issue:
The code wraps objects containing computed properties inside reactive. This is often unnecessary and can lead to confusion or unexpected behavior regarding reactivity depth and performance.
// Current (Problematic/Odd):
const resourceLabels = reactive({
[RESOURCE_TYPE.APPLICATION]: computed(() => t('application.title')),
// ...
})
const searchFields = reactive([
{ label: computed(() => t('common.name.label')), value: 'resource_name' },
// ...
])Why it's problematic:
- Redundancy:
computedreturns a ref-like object. When accessed inside a template or another computed property, Vue automatically unwraps refs. Wrapping them inreactiveadds an extra proxy layer without significant benefit for static structures like these arrays/objects (they aren't mutated dynamically). - Access Pattern: In the template, you access
resourceLabels[resourceType]. IfresourceLabelsisreactive, accessing a nestedcomputedmight require.valuehandling depending on the context, though Vue 3 templates usually handle deep unwrapping well. However, mixingreactivewrappers around simple translation maps is over-engineering.
Optimization/Suggestion:
Use plain constants or computed for the whole object/array if they need to be reactive globally. Since t() values change when the locale changes, wrapping the entire array/object in computed is cleaner and more idiomatic than using reactive with individual computed items inside.
Refactored Approach:
import { computed } from 'vue'
// Option A: Computed Maps (Preferred)
const resourceLabelMap = computed(() => ({
[RESOURCE_TYPE.APPLICATION]: t('application.title'),
[RESOURCE_TYPE.KNOWLEDGE]: t('knowledge.title'),
[RESOURCE_TYPE.TOOL]: t('tool.title'),
[RESOURCE_TYPE.MODEL]: t('model.title'),
}))
const resourceTypeOptions = computed(() =>
Object.entries(resourceLabelMap.value).map(([value, label]) => ({ value, label }))
)
const searchFields = computed(() => [
{ label: t('common.name.label'), value: 'resource_name' },
{ label: t('common.labels.creator'), value: 'user_name' },
])
const relationTabs = computed(() => [
{ value: 'dependency', label: t('resource.relations.dependency') },
{ value: 'dependent', label: t('resource.relations.dependent') },
])If you use this approach, update template usages:
- Change
resourceLabels[resourceType]toresourceLabelMap[resourceType](or keep the nameresourceLabelsand make itcomputed). - Remove
reactiveimport from the top if no other reactive state exists.
2. Potential Logic Error: Resource Mapping in Template
Issue:
In the table column "Type" (el-table-column):
<template #default="{ row }">{{ resourceLabels[row.resourceType as ResourceType] }}</template>With the current reactive implementation, row.resourceType is a key (e.g., 'application'). resourceLabels['application'] returns a ComputedRefImpl. Depending on how strictly you rely on Vue's auto-unwrapping in complex expressions, this might render [object Object] or fail if not unwrapped correctly in certain edge cases or if passed down.
However, if you adopt the computed map approach suggested above, resourceLabelMap[row.resourceType] will directly return the string, which is safer and clearer.
3. Naming Convention & Consistency
Observation:
searchFieldsuses keys like'resource_name'and'user_name'.- Table columns use props
prop="name"andprop="username".
Potential Mismatch:
Ensure that the backend API accepts the filter parameters sent by MkTableFilter.
- The filter option value is
'resource_name'. - The table prop for name is
'name'. - The filter option value for creator is
'user_name'. - The table prop for creator is
'username'.
Double-check that your @change="handleFilterChange" logic correctly maps these filter values (resource_name, user_name) to the actual API query parameters. Sometimes, frontend UI props differ from backend API keys. If the table sorts/filters based on internal data keys, ensure the filter component passes the correct key to the API handler.
4. Import Management
Suggestion:
You added useI18n and reactive. If you refactor away from reactive (as suggested in point #1), remember to remove the reactive import to avoid linting errors.
-import { computed, onBeforeUnmount, reactive, ref } from 'vue'
+import { computed, onBeforeUnmount, ref } from 'vue'5. Template Cleanup
The template changes themselves are good (using :title, :label, etc.). No syntax errors detected there.
Summary of Recommended Actions
- Replace
reactivewithcomputedforresourceLabels,searchFields, andrelationTabs. It is more performant (cached until deps change) and semantically correct for derived data. - Verify Filter Keys: Ensure
valuefields insearchFieldsmatch the parameter names expected by yourhandleFilterChange/ API call logic. - Clean Imports: Remove
reactiveif it's no longer used after refactoring.
Example Refactor for Script Block
<script setup lang="ts">
import { computed, onBeforeUnmount, ref } from 'vue' // Removed reactive
import { cloneDeep } from 'lodash'
import { useI18n } from 'vue-i18n'
// ... other imports
defineOptions({ name: 'RelatedResourcesDrawer' })
const { t } = useI18n()
// ... props, stores, etc.
// Use computed for translated data sources
const resourceLabels = computed(() => ({
[RESOURCE_TYPE.APPLICATION]: t('application.title'),
[RESOURCE_TYPE.KNOWLEDGE]: t('knowledge.title'),
[RESOURCE_TYPE.TOOL]: t('tool.title'),
[RESOURCE_TYPE.MODEL]: t('model.title'),
}) as Record<string, string>) // Type assertion helps TS
const resourceTypeOptions = computed(() =>
Object.entries(resourceLabels.value).map(([value, label]) => ({ value, label }))
)
const searchFields = computed(() => [
{ label: t('common.name.label'), value: 'resource_name' },
{ label: t('common.labels.creator'), value: 'user_name' },
])
const relationTabs = computed(() => [
{ value: 'dependency', label: t('resource.relations.dependency') },
{ value: 'dependent', label: t('resource.relations.dependent') },
])
// ... rest of script
</script>| <MkTooltip effect="dark" :content="t('operateLog.apiDetails')" placement="top"> | ||
| <el-button type="primary" text @click.stop="handleOpenDetail(row)"> | ||
| <MkIcon name="icon_describe_outlined" /> | ||
| </el-button> |
There was a problem hiding this comment.
Here is a code review of the provided diff, focusing on irregularities, potential issues, and optimization suggestions.
1. Critical Issue: reactive with computed in Arrays
Location: searchFields and statusOptions definitions.
const searchFields: OptionItem<string>[] = reactive([
{ label: computed(() => t('operateLog.operationDetails')), value: 'operate' },
// ...
])Problem:
Wrapping an array of objects containing computed refs inside reactive() is unnecessary and potentially problematic.
- Unnecessary Reactivity:
computedvalues are already reactive. They will automatically update when their dependencies (in this case,tvialocale) change. You do not need the parent object/array to bereactivefor thelabelto reactively bind in the template. - Performance Overhead:
reactive()deeply tracks all properties. This adds unnecessary overhead. - Potential Unwrapping Issues: Depending on how
OptionItemis passed to child components (e.g.,MkTableFilter), the child component might expect plain strings forlabelorref<string>, notComputedRef<string>. If the child component expects a plain string, this will break unless.valueis used everywhere, which defeats the purpose. If the child component expectsRef|ComputedRef, it might work, but it's fragile.
Recommendation:
Remove reactive(). Keep the array as a plain constant (or ref if the structure changes dynamically). The computed labels will update automatically because Vue's reactivity system tracks useI18n's internal state.
// ✅ Correct Approach: Plain array with computed properties
const searchFields: OptionItem<string>[] = [
{ label: computed(() => t('operateLog.operationDetails')), value: 'operate' },
{ label: computed(() => t('operateLog.operator')), value: 'user' },
{ label: computed(() => t('operateLog.ipAddress')), value: 'ip_address' },
]
const statusOptions: OptionItem<number>[] = [
{ label: computed(() => t('common.status.success')), value: 200 },
{ label: computed(() => t('common.status.failure')), value: 500 },
]Note: Ensure that MkTableFilter and other components receiving these options can handle label: ComputedRef<string>. If they cannot, you must access .label.value or use a different pattern.
2. Unnecessary Import
Location: import { ..., reactive, ... } from 'vue'
Since you should remove the reactive() calls from the examples above, the reactive import becomes unused. Remove it to keep imports clean.
3. Watcher Optimization & Performance
Location: watch(locale, ...)
watch(locale, () => {
loadOperateLogs()
loadOperateMenuOptions()
})Potential Issue: This watcher triggers both API calls immediately upon locale change. If loadOperateLogs() depends on data fetched by loadOperateMenuOptions() (e.g., menu IDs), calling them in parallel might cause race conditions or redundant requests. Additionally, changing language shouldn't necessarily require refetching all data if only translations are needed, but since you mention "re-fetch server-side translated logs," this implies backend-dependent localization.
Suggestions:
- Check Dependencies: If
loadOperateMenuOptions()doesn't affectloadOperateLogs(), consider if both are truly needed. Often, table data can remain the same while UI labels change locally via i18n. Only refetch if the data itself (e.g., log descriptions) is localized by the backend based onAccept-Language. - Debounce/Throttle: Language switches can trigger multiple times during navigation or setup. Consider adding
{ flush: 'post' }or debouncing if performance is a concern. - Initial Load Conflict:
onMountedalready calls these functions. EnsureuseI18n'slocaledoesn't trigger the watch immediately on mount due to default value setting, causing duplicate requests. Adding{ immediate: false }(which is default) is fine, but verify behavior.
4. Template Best Practices
A. Accessing Computed Labels in Template
If you follow Recommendation #1 (removing reactive), ensure your child components (MkTableFilter) support ComputedRef for props. If they don't, you'll see [object Object] instead of the text. A safer, more compatible approach if children don't support refs:
// Alternative: Use simple variables updated by watch if child components are strict
const searchFieldLabels = reactive({
operate: '',
user: '',
ip_address: ''
})
watch(locale, () => {
searchFieldLabels.operate = t('operateLog.operationDetails')
// ... update others
}, { immediate: true })However, modern Vue components usually handle ComputedRef well. Stick to #1 if possible.
B. Hardcoded Width Changes
You increased menu column width from 140 to 160 and operation from 70 to 80. Ensure this accommodates translated languages like German or Russian, which are often wider than English/Chinese. Test with long translations.
5. Code Consistency
- Good: Replacing hardcoded Chinese strings with
t('...')throughout the template is correct and aligns with i18n best practices. - Good: Adding
:title="t('operateLog.title')"to layout header improves consistency.
Summary of Recommended Changes
- Remove
reactive()fromsearchFieldsandstatusOptionsarrays. - Remove
reactivefrom imports. - Verify that
MkTableFilterand other components acceptComputedRefin their props. - Test the
watch(locale)logic to ensure no duplicate initial loads and that backend refetching is actually required for all listed items.
Corrected Script Snippet Example
<script setup lang="ts">
import { computed, onMounted, ref, useTemplateRef, watch } from 'vue' // Removed 'reactive'
import { useI18n } from 'vue-i18n'
// ... other imports
const { locale, t } = useI18n({ useScope: 'global' })
// ...
// ✅ Correct: No reactive wrapper needed for static structure + computed labels
const searchFields: OptionItem<string>[] = [
{ label: computed(() => t('operateLog.operationDetails')), value: 'operate' },
{ label: computed(() => t('operateLog.operator')), value: 'user' },
{ label: computed(() => t('operateLog.ipAddress')), value: 'ip_address' },
]
// ✅ Correct
const statusOptions: OptionItem<number>[] = [
{ label: computed(() => t('common.status.success')), value: 200 },
{ label: computed(() => t('common.status.failure')), value: 500 },
]
// ...
// ✅ Consider adding options to avoid double-fetch if locale is initialized early
watch(locale, async () => {
// Optional: await first call before second if dependent
await Promise.allSettled([loadOperateLogs(), loadOperateMenuOptions()]);
}, {
// Ensure it doesn't run twice on mount if locale sets up sync
flush: 'sync'
})
</script>
feat: internationalize navigation, API keys, appearance settings, and operation logs