Skip to content

feat: internationalize navigation, API keys, appearance settings, and operation logs - #8073

Merged
wangdan-fit2cloud merged 1 commit into
v3from
pr@v3@feat_translation_admin
Nov 21, 2026
Merged

wangdan-fit2cloud merged 1 commit into
v3from
pr@v3@feat_translation_admin

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

feat: internationalize navigation, API keys, appearance settings, and operation logs

<el-button v-if="perm.system.appearance.edit()" type="primary" @click="handleSaveTheme">{{ t('appearance.saveAndApply') }}</el-button>
</component>
</template>
</MkViewLayout>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here are the issues and suggestions:

Bugs / Potential Issues

  1. THEME_IMAGE_SETTINGS type mismatch: It was ThemeImageSetting[] (plain), now it's a reactive array whose label/description fields are ComputedRef<string> instead of string. This breaks the ThemeImageSetting contract. 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 accept string | ComputedRef<string>, or don't make them computed — a plain computed(() => THEME_IMAGE_SETTINGS) mapping to strings is safer.

  2. reactive on computed is unnecessary: The array itself has no reactive nested state you mutate; wrapping in reactive just makes it deeply reactive for no benefit. Consider const THEME_IMAGE_SETTINGS = computed<ThemeImageSetting[]>(() => [...]) instead. Note that .value access would then be needed in template auto-unwrap only at top level — verify all consumers.

  3. formRules changed from object to ComputedRef: 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.

  4. i18n keys used in JS before component context may resolve early: t(...) inside formRules computed is lazy (good), but THEME_IMAGE_SETTINGS string templating like ${t('auth.login.label')} Logo will not be reactive inside the string concat unless wrapped in the outer computed. Verify each entry is fully wrapped in its own computed.

Correctness / Robustness

  1. Hardcoded 10 MB vs MAX_IMAGE_SIZE: The message interpolates { size: 10 } while the actual limit is MAX_IMAGE_SIZE = 10MB. Derive the number: { size: MAX_IMAGE_SIZE / 1024 / 1024 } to avoid drift.

  2. 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.

  3. reactive array + ThemeImageField indexing: themeSetting[field] writes — fine — but confirm field values (icon, loginLogo, loginImage) exist in ThemeSettingForm.

  4. Missing i18n for THEME_OPTIONS labels: Those label values (e.g., theme color names) remain hardcoded Chinese. Inconsistent with the rest of the localization effort.

  5. useI18n({ useScope: 'global' }): Ensure the global scope contains all the referenced keys (appearance.*, common.options.custom, layout.userManual, etc.), and that auth.login.label, common.messages.saveSuccess exist. Missing keys will render raw key strings silently.

  6. MsgSuccess(t('common.messages.saveSuccess')) inside .then chain: Since t is captured at setup, it's fine — but if locale changes mid-flight, message uses latest locale (acceptable). No issue.

  7. el-radio-button :label deprecation: In recent Element Plus, value replaces label for the bound value and label is 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 (:label on other radio buttons still passing label as both) could be inconsistent.

  8. Accessibility: Localized strings used as placeholder may be longer/shorter in other languages; maxlength unchanged is fine, but no aria-label additions — optional.

Optimization Suggestions

  1. Prefer const THEME_IMAGE_SETTINGS = computed(() => [...]) and read .value explicitly where needed, rather than reactive, to avoid confusing unwrapping semantics.

  2. Extract repeated ${t('x')} Logo patterns 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.

  3. Centralize the size limit: derive both MAX_IMAGE_SIZE (or display) from one constant.

  4. Consider const { t } = useI18n() default scope if all keys are global; explicit useScope: 'global' is fine but be consistent across components.

  5. Add a lightweight dev-time guard (e.g., import.meta.env.DEV && console.warn) when required i18n keys are missing — helps catch typos like appearance.name.requiredMessage vs appearance.name.label.

Summary of highest priority fixes

  • Type mismatch of THEME_IMAGE_SETTINGS (ComputedRef vs string).
  • Replace string-concatenated labels with dedicated i18n keys.
  • Derive size numbers from MAX_IMAGE_SIZE.
  • Localize remaining hardcoded THEME_OPTIONS labels.

<el-table-column prop="username" :label="t('common.labels.creator')" min-width="100" show-overflow-tooltip />
</MkTable>
</template>
</MkDrawer>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Redundancy: computed returns a ref-like object. When accessed inside a template or another computed property, Vue automatically unwraps refs. Wrapping them in reactive adds an extra proxy layer without significant benefit for static structures like these arrays/objects (they aren't mutated dynamically).
  2. Access Pattern: In the template, you access resourceLabels[resourceType]. If resourceLabels is reactive, accessing a nested computed might require .value handling depending on the context, though Vue 3 templates usually handle deep unwrapping well. However, mixing reactive wrappers 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] to resourceLabelMap[resourceType] (or keep the name resourceLabels and make it computed).
  • Remove reactive import 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:

  • searchFields uses keys like 'resource_name' and 'user_name'.
  • Table columns use props prop="name" and prop="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

  1. Replace reactive with computed for resourceLabels, searchFields, and relationTabs. It is more performant (cached until deps change) and semantically correct for derived data.
  2. Verify Filter Keys: Ensure value fields in searchFields match the parameter names expected by your handleFilterChange / API call logic.
  3. Clean Imports: Remove reactive if 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>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

  1. Unnecessary Reactivity: computed values are already reactive. They will automatically update when their dependencies (in this case, t via locale) change. You do not need the parent object/array to be reactive for the label to reactively bind in the template.
  2. Performance Overhead: reactive() deeply tracks all properties. This adds unnecessary overhead.
  3. Potential Unwrapping Issues: Depending on how OptionItem is passed to child components (e.g., MkTableFilter), the child component might expect plain strings for label or ref<string>, not ComputedRef<string>. If the child component expects a plain string, this will break unless .value is used everywhere, which defeats the purpose. If the child component expects Ref|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:

  1. Check Dependencies: If loadOperateMenuOptions() doesn't affect loadOperateLogs(), 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 on Accept-Language.
  2. Debounce/Throttle: Language switches can trigger multiple times during navigation or setup. Consider adding { flush: 'post' } or debouncing if performance is a concern.
  3. Initial Load Conflict: onMounted already calls these functions. Ensure useI18n's locale doesn'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

  1. Remove reactive() from searchFields and statusOptions arrays.
  2. Remove reactive from imports.
  3. Verify that MkTableFilter and other components accept ComputedRef in their props.
  4. 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>

@wangdan-fit2cloud
wangdan-fit2cloud merged commit 5c953df into v3 Nov 21, 2026
3 of 4 checks passed
@wangdan-fit2cloud
wangdan-fit2cloud deleted the pr@v3@feat_translation_admin branch November 21, 2026 06:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants