Repository navigation
feat: internationalize model - #7955
Conversation
| <el-button type="primary" @click="submitEdit">{{ t('common.actions.save') }}</el-button> | ||
| </template> | ||
| </MkDialog> | ||
| </template> |
There was a problem hiding this comment.
Review of the Diff
Overall this is a clean i18n refactor. Below are observations grouped by category.
✅ Correct / Fine
- Consistent use of
t()for all user-facing strings (messages, labels, placeholders, buttons). - Interpolated parameter
{ label }indeleteConfirmis correct. - The
blur: 'change'and other option keys left untouched — good.
⚠️ Potential Issues
-
useI18nimport path & scopeconst { t } = useI18n({ useScope: 'global' })
- If the project already uses a globally-injected
$t, callinguseI18ninside<script setup>at the top level is fine, but verify that a global scope i18n instance actually exists. IfcreateI18nwas configured withlegacy: falseand noglobalInjection, this is required; if it's legacy mode,useI18nmay not be available. Double-check the Vue I18n version (v9 vs v8). - Consider whether
useScope: 'global'is needed at all — the default behavior may already suffice.
- If the project already uses a globally-injected
-
Keys reused across namespaces unexpectedly
t('common.messages.saveSuccess')used for both add and edit — fine semantically, but make sure the key exists incommon.t('common.actions.edit')is used as a dialog title. Using an action verb as a noun-title is common but check that translation (e.g. "Edit" vs "编辑") reads naturally as a title in all locales.
-
MsgWarning(t('dynamicForm.messages.completeOption'))vs previous text- Original: "请至少填写一条完整数据" (please fill at least one complete row). Key name
completeOptionimplies a single option, which may mismatch the meaning ("row"). Verify the translation conveys "at least one complete row".
- Original: "请至少填写一条完整数据" (please fill at least one complete row). Key name
-
Rule message reactivity
:rules="[{ required: true, message: t('...') }]"—t()is evaluated once at render setup. If locale changes at runtime, the rule message won't update unless the component re-renders. Usually acceptable (forms are short-lived), but worth noting. If you need reactive rules, wrap incomputed.
-
:labelonel-checkbox:label="t('dynamicForm.options.multiple')"— in Element Plus ≥ 2.6,labelserves as the value forv-modeluse cases and can conflict. Since here it's used as display text with string model values, verify version-specific behavior. Prefer explicit slot (<el-checkbox>...text...</el-checkbox>) or:labelonly when it's the bound value.
-
Long line formatting
- The
MkDialogbutton/label lines andel-form-item :rulesline are now very long. Consider breaking them (Prettier default is often 100–120). Not a bug, just readability.
- The
-
Missing i18n on remaining hardcoded strings?
- No hardcoded Chinese remains — good. Ensure all new keys (
dynamicForm.messages.*,dynamicForm.fields.*,common.*) exist in every locale file.
- No hardcoded Chinese remains — good. Ensure all new keys (
🔧 Optimization Suggestions
- Extract a small helper or keep
tdestructured once — current approach is fine. - For repeated
t('dynamicForm.fields.optionLabel.label')blocks, no change needed, but some teams prefer computed properties to reduce clutter. - Consider adding a comment for the
useScope: 'global'decision. - Add a lint rule (
vue-i18n/no-raw-text) to prevent future regressions.
Summary
No functional bugs introduced. Main follow-ups: verify useI18n version compatibility and global-scope availability, confirm locale files contain all new keys, and optionally make validation rules reactive to locale changes.
| {{ t('common.actions.delete') }} | ||
| </MkDropdownItem> | ||
| </MkTableMoreDropdown> | ||
| </div> |
There was a problem hiding this comment.
Here are the issues and suggestions:
Bugs / Irregularities
-
Wrong signature for
t()with count — inhandleDeleteModel:t('model.delete.description', { count: model.resource_count }, model.resource_count)
t()doesn't take a third numeric argument. If you need pluralization, use{ count }only (vue-i18n picks the plural form fromcount). The extra arg should be removed. -
Type-safety of
MODEL_TYPE_MESSAGE_KEYS[row.model_type]— you cast with!and guard with a ternary. Since it's aRecord<string, string>, indexing always returnsstring(notundefined) under non-strict index checks; the!is redundant, or if typed asRecord<string, string | undefined>, keep the guard but drop the!. Also consider using optional fallback via?? row.model_typefor clarity:{{ MODEL_TYPE_MESSAGE_KEYS[row.model_type] ? t(MODEL_TYPE_MESSAGE_KEYS[row.model_type]) : row.model_type }}
-
labelhardcoded keys not verified — e.g.t('model.fields.name.label')vst('common.labels.name')inconsistency: the search field usesmodel.fields.name.labelwhile the column usescommon.labels.name. Confirm both keys exist and intend to mean the same thing; if identical text, reuse one key. -
modelTypeOptionsnow depends ont— good that it'scomputed, butsearchFieldsalso becomes reactive viat. Ensure locale changes retrigger UI update (they will, sincetfromuseI18n({ useScope: 'global' })is reactive). No action needed, but confirm the global scope is what you want (vs local). -
MkViewLayout :title="t('model.title')"— minor: iftitleprop already existed internally (template slot destructurestitle), ensure the newtitleprop doesn't conflict/shadow the slot-providedtitle. -
Removed
import { MODEL_TYPE_LABELS } from '@/constants'— ensure no other usage ofMODEL_TYPE_LABELSremains elsewhere breaking import paths.
Optimization suggestions
-
Extract
MODEL_TYPE_MESSAGE_KEYS[row.model_type]lookup into a helper/computed method to avoid the repeated inline ternary in the template:const modelTypeLabel = (type: string) => { const key = MODEL_TYPE_MESSAGE_KEYS[type] return key ? t(key) : type }
Then
{{ modelTypeLabel(row.model_type) }}. -
Cache
t(...)results for static labels (columns, actions) in acomputedor const at setup time rather than callingt()dozens of times per render. A singleconst labels = computed(() => ({ name: t(...), ... }))reduces overhead. -
providerOptions/workspaceOptions— confirm they are alreadycomputedso they react to locale changes if their labels are translated (currently untouched in the diff, but worth checking).
Style / consistency
- Naming asymmetry:
model.provider.labelvscommon.labels.creator,model.fields.type.labelvscommon.labels.name— standardize key naming (model.fields.provider.label?) for maintainability. - Comments still in Chinese (e.g.
<!-- 编辑模型 -->) while user-facing strings are i18n'd — fine, but consider consistency if codebase enforces English comments.
|
|
||
| return createMenuItems(detailRoot?.children ?? [], route.params) | ||
| return createMenuItems(detailRoot?.children ?? [], route.params, translateTitle) | ||
| } |
There was a problem hiding this comment.
Review
Overall the change is low-risk and reasonable. Issues and suggestions below.
1. Behavior: translateTitle result used for label, but empty/undefined isn't guarded
label: translateTitle ? translateTitle(route.meta!.title!) : route.meta!.title!,- If
translateTitlereturns an empty string orundefined(a common i18n fallback behavior), the menu label will be blank even though a title existed. Consider falling back:
const rawTitle = route.meta!.title!
const label = translateTitle ? translateTitle(rawTitle) || rawTitle : rawTitle- Also note the original filter uses
route.meta?.titletruthiness; iftitleis a translation key, that's fine, but if a caller ever passes a function that expects a non-string (e.g., i18n key objects), the type here forcesstring. Fine as long as titles are strings, but worth confirming.
2. i18n reactivity
translateTitle is invoked at menu-build time. If the app supports runtime locale switching, this menu list will not re-render automatically unless the parent recomputes it when the locale changes (e.g., computed depends on i18n.locale.value). Worth documenting this contract in the JSDoc — currently the comment only says "convert routes to Layout menu" and doesn't mention localization.
3. Duplicated permission logic
The permission predicate is built twice in different shapes (once in filter for detailParams, once in map for LayoutMenuItem['permission']). Extracting a small helper avoids drift:
const buildPermission = (meta, detailParams) =>
detailParams && meta?.permission
? () => (meta.permission as (r: { params: RouteParamsGeneric }) => boolean)({ params: detailParams })
: (meta?.permission as LayoutMenuItem['permission'])Not required, but reduces the double cast and makes the fallback branch easier to reason about.
4. Recursive pass-through of translateTitle
Passing translateTitle through every recursive call is fine, but since it's constant across the whole recursion, you could instead close over it inside a nested helper or use a module-level context. Minor style only — no functional issue.
5. Unnecessary wrapping parentheses
The new outer return ( ... ) around the chain is stylistic; there is no multi-line JSX/expression requiring it. Harmless, just noise in the diff.
6. Nullish handling in children filter
Unchanged from before, but note:
.filter((menuItem) => !detailParams || !menuItem.children || menuItem.children.length > 0)If detailParams is provided and children is an empty array allocated by route.children ? ... : [] (note: route.children?.length ? children : undefined can emit []? Actually no—when route.children.length === 0 it becomes undefined, so [] only appears briefly). This edge case is fine today, but tightening to menuItem.children?.length would make the intent clearer.
7. Type safety / casts
route.meta!.title!androute.name!rely on earlier filters — acceptable, but a singleif (!route.name || !route.meta?.title) returnwon't help inside.map; alternatively use a typed narrowing.flatMap. Low priority.translateTitle?: (title: string) => stringis good; consider typing it againstRouteMeta['title']if that type is stricter thanstring.
8. Missing memoization consideration
Every call (per route navigation, potentially) rebuilds the full menu tree and re-runs translations. For large route trees, wrap getChildRouteList results in a computed/cache keyed by (scope, locale).
9. No issues found
- Signature additions are backward compatible (optional param).
- Sorting and filtering semantics unchanged.
- Recursive pass-through is correct.
- Comment still accurate.
Summary: The change is safe. Address items 1–2 (correctness/UX for i18n) as they are the most likely real bugs; 3–8 are optional improvements.
feat: internationalize model