Repository navigation
feat: internationalize knowledge base settings - #7993
Conversation
| {{ t('common.actions.save') }} | ||
| </el-button> | ||
| </div> | ||
| </template> |
There was a problem hiding this comment.
Review of the diff
Correctness / functional issues
-
knowledgeTypeKeymay produce an invalid i18n key —KNOWLEDGE_TYPE_MAP[knowledge.value.type].toLowerCase()assumes the mapped value is a string that matches your i18n key namespace (e.g.base,web). If the map ever yields something likeweb_siteor an enum name,t('knowledge.<x>.label')silently falls back to the raw key. Consider asserting this at compile time with a typed union, or keep a mapping constant for keys. -
i18n fallback noise — if
knowledgeTypeKeyis''(whenknowledge.valueis null before mount), you callt('knowledge..label'). The template already guards onknowledge.type, but the computed can still emit a bad key once. Returnnull/guard instead. -
settingRulesconverted tocomputed— since it now depends ont, it is reactive to locale changes, which is good. However Element Plus caches validation messages in some paths; adding:validate-on-rule-change="false"is a sensible mitigation, but confirm that re-validation on locale switch isn't desired (otherwise flip it totrue). -
Nested label interpolation —
t('common.validation.inputFieldRequired', { label: 'App ID' })hardcodes English labels inside Chinese sentences ("请输入 App ID"). ForFolder Token,App Secretetc. verify the translated target sentence reads naturally; better to make these proper i18n keys (e.g.knowledge.fields.appId.label) rather than passing literals. -
Removed static rule message for
source_url— previously there was also a distinct required message; nowt('knowledge.fields.webRootUrl.requiredMessage')must exist, otherwise the user sees a raw key. Check the resource file. -
Locale change + existing validation state — when the user switches locale while the form has errors, previously displayed error messages don't re-render from the
computedrules; only new validations use the new text. Not a bug but worth documenting or triggeringsettingFormRef.value?.clearValidate()on locale change if consistent messaging matters. -
Missing
watchon locale forsetTingRulesside effects — no issue for rules (they're read at validation time), but thet()calls insidehandleSave(MsgConfirm) run at click time so they always use the current locale — fine. -
useI18n({ useScope: 'global' })— correct for global messages, but if the component's originals were resolved under a component scope, the keys may not resolve. Verify all keys exist in the global locale files (not scoped blocks).
Minor / style
- Placeholder count in removed code:
placeholder="默认为 body..."→t('knowledge.fields.selector.placeholder')— ensure the defaultbodyhint survives translation. - Inconsistent spacing:
(MB)kept as literal afterfileSizeLimit.label; consider embedding unit in translation for locales where the unit placement differs. - Named import order — a stylistic note: importing
useI18nafterlodashbreaks any alphabetized import convention; run your linter/formatter. - Trailing comma / formatting — the multi-line
folder_tokenrule array is fetched by prettier-normal conventions; verify prettier passes.
Performance
settingRulescomputed recreates rule objects every time any reactive dep changes; since it only depends on the locale normally, this is negligible. No further optimization needed.- No unnecessary
watchadded — good.
Optimization suggestions
- Introduce a strongly-typed helper for field-label translations to avoid repeat
'App ID'literal strings:const fieldLabel = (key: string) => t(`knowledge.fields.${key}.label`)
- Add a lint rule / TS check ensuring every
t('...')key appears in the AST-scanned key list (most projects have one); it would have caught build(deps): bump the pip group across 1 directory with 2 updates #1/关于页面优化 #5. - Consider centralizing the knowledge-type → i18n-key mapping in
@/constants/knowledgeso the view doesn't rely on.toLowerCase().
Overall
No blockers in what's shown, but items #1, #2, #4, #5 are the highest risk (bad keys or mixed-language strings). The rest are quality improvements.
| {{ t('common.actions.save') }} | ||
| </el-button> | ||
| </el-form> | ||
| </div> |
There was a problem hiding this comment.
Code Review
Potential Issues
-
t()overload misuse (likely a bug)t('knowledge.scheduledSync.interval.minHoursMessage', { count: minimum }, minimum)
The third argument
minimumis passed but i18next/vue-i18n typically ignores it. If the intent was pluralization, use the options form:t('...', { count: minimum })
Also confirm the translation string uses
{{count}}and not positional interpolation. -
Computed invalidation of
scheduleOptionsdepends on locale
computedre-evaluates only when its reactive deps change.t(...)here is called inside a computed — verify thattinternally accesses reactive locale state (vue-i18n does vialocale.value), otherwise labels won't update on language switch. In vue-i18n v9 this works; in some setups (e.g., usingi18n.global.t), you must referencelocale.value. -
period.labelKeyfallback logic inconsistent with children
Top-level falls back toperiod.label, children fall back tooption.label. Verify bothlabelKey/labelexist on all entries, otherwise a cascader option may renderundefined. -
Monthly label assumes day suffix format
`${option.value} ${t('common.schedule.day')}`Hardcoding value before translated unit loses flexibility (e.g., RTL languages or languages where the unit precedes the number). Prefer an interpolated key:
t('common.schedule.dayValue', { day: option.value }). -
Nested ternary readability
The month/cron branch is hard to parse. Extract to a helper:const resolveChildLabel = (period, option) => period.value === SCHEDULE_TYPE.MONTHLY ? t('common.schedule.dayValue', { day: option.value }) : t(option.labelKey ?? '', option.label ?? '')
-
Rule:
daysmax for MONTHLY uses 31 — correct, but weekly max7
Weekly max of 7 is fine if days are 1–7 (ISO), but ensure backend/logic agrees (some systems use 0–6). Confirm off-by-one. -
Custom validator locale capture
The validator closure callst(). If rules are defined at module/setup top-level once, error messages won't refresh on locale change until a new validation run. TriggerformRef.value?.clearValidate()(or re-validate) on locale change if you want live updates. -
Optional chaining on
cron_expression
setting.cron_expression?.trim().split(/\s+/).length !== 5— ifcron_expressionis'',.trim().split()yields['']length 1, still fails as intended. Fine, but consider an explicit empty check for a clearer message. -
Number.isInteger(setting.interval_value)— ifinterval_valuecomes from an input as string, this rejects valid numeric input. Ensure model type isnumberor coerce first.
Minor / Suggestions
- Extract magic regex:
const TIME_REGEX = /^([01]\d|2[0-3]):[0-5]\d$/
- Repeated
syncSetting.schedule_type === SCHEDULE_TYPE.CRONin template — compute once:Reduces noise and improves template readability.const isCronMode = computed(() => syncSetting.value.schedule_type === SCHEDULE_TYPE.CRON)
MsgSuccess(t('common.messages.saveSuccess'))— good, keep consistent. Check other literal strings in the same file (comments, tooltips) for missed translations.SCHEDULE_OPTIONimmutability — mapping creates new objects each time ({...period}); sincescheduleOptionsis recomputed frequently, considermemoize-style approach keyed onlocale.valueif this list is large. Not urgent.- Validator returns
Error(error)— could just becallback(error || undefined).FormRulesaccepts string too; usingnew Erroris fine but unnecessary. - Placeholder on
el-cascaderwith clearable: after clearing, cascader shows placeholder correctly; ensurescheduleValuegetter handles the cleared case (returning[]) without throwing.
Overall
The i18n refactor is clean and consistent. The main concerns are (a) the third argument passed to t() in interval messages, (b) reactivity of scheduleOptions under locale changes, (c) nested-ternary readability, and (d) verifying day index ranges match the backend contract.
| <el-table-column :label="t('common.labels.duration')" width="110"> | ||
| <template #default="{ row }">{{ (row.duration_seconds ?? row.duration_ms / 1000).toFixed(2) }}s</template> | ||
| </el-table-column> | ||
| </MkTable> |
There was a problem hiding this comment.
Code Review
Issues Found
1. Bug: syncStatusOptions was made computed but is still indexed directly as an object
<MkStatusLabel v-if="syncStatusOptions[row.status ...]" v-bind="syncStatusOptions[row.status ...]" />Since syncStatusOptions is now a Ref<...>, in the template you must access .value (or rely on auto-unwrap). Vue auto‑unwraps top‑level refs only when used directly, so syncStatusOptions[someKey] indexes into the ref object itself, not the unwrapped value — this will evaluate to undefined. Fix by explicitly unwrapping:
const statusMap = computed(...) // or keep name
// template:
v-if="syncStatusOptions[row.status]" // broken
v-if="syncStatusOptions.value[row.status]" // still broken in template? see belowActually Vue's template compiler does auto‑unwrap top‑level refs even for property/index access in <script setup> templates, so syncStatusOptions[x] may work — but it's fragile and confusing. Safer: destructure a plain getter:
const syncStatusOptions = computed(() => ({...}))and in template use syncStatusOptions.value[...] explicitly, or better, add a small helper:
function getStatusOption(status: KnowledgeSyncStatus) {
return syncStatusOptions.value[status]
}2. Possible bug: string interpolation in documents i18n key
return `${t('knowledge.stats.documents', log.total_count)}: ${log.total_count} (...)`t(..., log.total_count)passes a number as the params argument. Many i18n libs (vue-i18n) require an object ({ count: n }) or named params; passing a raw number may fail silently or produce{[object Object]}.- You then append
: ${log.total_count}again — the count appears twice if the translation already includes it (e.g. "共 {count} 个文档"). This likely yields"共 5 个文档: 5 (...)".
Fix:
return t('knowledge.syncLog.counts.summary', {
total: log.total_count,
details: counts.join(', '),
}) with a translation like "共 {total} 个文档 ({details})".
3. Inconsistent separator / locale handling
- Original used Chinese
,; new code hardcodes', '. Fine for English but not locale‑aware. Consider using an i18n list separator or the existing translation strings.
4. Fragile message matching still hardcoded in Chinese‑independent logic
if (/already running|still running|already queued/.test(log.message))
if (log.message === 'Scheduled synchronization is disabled')These match against raw backend English messages. That's okay, but:
- The regex doesn't account for case (
/imissing) or minor wording changes. - Better: have the backend return a stable error/status code (e.g.
skip_reason: 'task_in_progress' | 'scheduled_disabled') and switch on that instead of parsing text. This decouples UI from message wording.
5. Repeated row.status as KnowledgeSyncStatus cast
The cast is repeated three times in the template. Extract once:
<template #default="{ row }">
<MkStatusLabel
v-if="getStatusOption(row.status)"
v-bind="getStatusOption(row.status)"
/>
</template>6. t() inside computed — reactivity of locale
Good change overall (makes labels locale‑reactive), but ensure t is reactive in your setup (vue-i18n's useI18n() t is). If t was imported statically (not from useI18n), the computed won't re‑run on locale change. Verify.
7. Magic widths (width="200", "400", "120", "110")
Unchanged, but consider extracting layout constants or using responsive/min‑width where appropriate. Minor.
8. Minor formatting nit
Aligned diff lines are fine, but the object literal inside computed is now several long lines — consider multi‑line formatting for readability.
Summary Table
| # | Severity | Item |
|---|---|---|
| 1 | High | syncStatusOptions[...] indexing on a Ref — verify auto‑unwrap |
| 2 | High | t(key, number) param + duplicated count in output |
| 3 | Low | Hardcoded ', ' separator not locale‑aware |
| 4 | Medium | Regex/string matching on backend messages — prefer codes |
| 5 | Low | Repeated cast — extract helper |
| 6 | Medium | Confirm t is from useI18n (reactive) |
| 7 | Low | Magic numbers for column widths |
The most important fix is #2 (double count / wrong i18n params) and confirming #1 behaves correctly at runtime with your Vue/i18n versions.
feat: internationalize knowledge base settings