Repository navigation
refactor: finalize internationalization cleanup - #8075
Conversation
| ], | ||
| }, | ||
| } satisfies Record<string, LogicFlow.GraphConfigData> | ||
| }) satisfies Record<string, LogicFlow.GraphConfigData> |
There was a problem hiding this comment.
Review of the Changes
1. reactive() wrapping breaks satisfies semantics — type issue
export const applicationTemplate = reactive({...}) satisfies Record<string, LogicFlow.GraphConfigData>reactive() returns a UnwrapNestedRefs<T> type. In practice, Vue's reactive proxy unwraps refs on access, but at the type level the computed() refs are still stored as ComputedRef. This means:
- Any code reading
applicationTemplate.assistant.nodes[0].properties.stepNamewill get aComputedRef<string>(typed), not a string — downstream typing gets messy. - Serialization (
JSON.stringify) of areactiveobject containing computed refs will not produce the underlying string; it will likely output an empty/opaque object or throw depending on Vue's version. If this template is ever persisted or sent to an API, this is a bug.
Recommendation: Keep the template as a plain factory function that evaluates translations at call time:
export const createApplicationTemplate = () =>
({ blank: {...}, assistant: {...} }) satisfies Record<string, LogicFlow.GraphConfigData>This gives fresh translated values per instantiation, keeps it plain-data (serializable), and avoids reactive-ref leakage into consumers.
2. Translation timing / reactivity
If you intend these labels to update on locale change, using static computed() at module load binds them once — but since they're captured in a plain object, they won't re-render unless consumers read .value inside the template. Given the earlier serialization concern, a factory returns the freshly-translated value per use, which is usually the desired behavior for templates.
3. Inconsistent node-id interpolation via translation
knowledgeReference: `{{${t('workflow.searchKnowledge.label')}.data}}`
questionReference: START_NODE_REFERENCES.question,- Using a translated label to build a node reference (
{{知识库检索.data}}) is fragile: if the locale changes the label, the reference no longer matches the actual node id/stepName. Node references should be stable identifiers, not localized labels. Similarly,START_NODE_REFERENCES.questionsuggests a constant exists — apply the same pattern for the knowledge node. - Mixing hard-coded
{{...}}string construction withSTART_NODE_REFERENCESis inconsistent.
Fix: Define both references as constants (e.g., KNOWLEDGE_NODE_REFERENCES.data, START_NODE_REFERENCES.question) and pass them through i18n only if the prompt text itself needs localization, keeping the reference tokens language-independent.
4. Translation key for step name concatenation
stepName: computed(() => `${t('workflow.reply.label')}1`)Concatenating a numeral onto a translated string is locale-fragile (word order, pluralization, separators). Prefer a dedicated key like workflow.reply.label1 or a parameterized t('workflow.reply.labels.copy', { index: 1 }).
5. Removed unnecessary reactive() (good)
- reactive({ label: computed(...), value: 'answer' }),
+ { label: computed(...), value: 'answer' },Correct cleanup — nested plain objects don't need their own reactive. The top-level reactive already deep-proxies.
6. defaultApplicationNodes shared reference
blank: { edges: [], nodes: defaultApplicationNodes },Still shares a reference to defaultApplicationNodes. With reactive, mutations via one template may leak across consumers. Deep-clone or use a getter/factory: nodes: structuredClone(defaultApplicationNodes) (or your project's clone utility).
7. Missing fields / possible copy-paste issues
chatFields: []retained alongside populatedfields/globalFields— verify intended.- The
replynode usesfields: []withcontentset — confirm the reply content isn't expected infields. - Double-check that every new i18n key (
workflow.searchKnowledge.segmentList,application.template.assistant.userPrompt, etc.) actually exists in all locale files, otherwise users see raw keys.
8. Minor
- Consider extracting the repeated
computed(() => t('workflow.history.label'))into a local helper (const labelOf = (key) => computed(() => t(key))) to reduce noise and typos across ~30 occurrences.
Summary of Priority Fixes
- High: Don't build node references from translated labels; use stable id constants (both start & knowledge nodes).
- High: Reconsider
reactive()around a static config — prefer a factory returning plain serializable data. - Medium: Avoid string concatenation on translated text (
stepName+1). - Medium: Clone
defaultApplicationNodesto avoid shared mutation. - Low: Verify all i18n keys exist; extract a
labelOfhelper.
| ], | ||
| }, | ||
| } satisfies Record<string, LogicFlow.GraphConfigData> | ||
| }) satisfies Record<string, LogicFlow.GraphConfigData> |
There was a problem hiding this comment.
Here is an analysis of the code changes, highlighting potential issues and optimization suggestions.
1. Critical Issue: Invalid computed Usage in Data Structures
Problem: The most significant issue is placing Vue's computed() directly inside a plain object structure that is then passed to reactive().
- How
computedworks: In Vue 3,computed()returns a ref/object that represents a computation logic, not the value itself. However, the third party library (LogicFlow) likely expects thepropertiesof nodes/edges to be plain data objects (strings, numbers, etc.) at the time of initialization or during reactive updates. - The Problem:
stepName: computed(() => ...)results instepNamebeing a ComputedRef object (e.g.,{ _value: ..., _dirty: ... }), not a string.- Unless
LogicFlowexplicitly supports Vue Refs/Computed values in its configuration schema (which is rare for generic graph libraries), it will fail to render labels, treat them as[object Object], or crash. - Wrapping the entire exported constant with
reactive()does not automatically unwrap nestedcomputedrefs when passed to external libraries unless the library uses deep unwrapping (which typical Canvas/SVG rendering libraries do not).
Recommendation:
Do not use computed() inside static template data structures intended for graph engines like LogicFlow. Instead, handle localization at the rendering layer or ensure the data passed to LogicFlow is plain strings.
If you must keep the structure reactive:
Option A (Recommended): Keep the original structure plain and transform it before passing to LogicFlow.
Option B: If LogicFlow supports custom reactive props (unlikely), ensure the component using LogicFlow accesses .value properly, but this is fragile.
2. Type Safety & TypeScript Issues
Problem:
export const knowledgeTemplate = reactive({ ... }) satisfies Record<string, LogicFlow.GraphConfigData>satisfieswithreactive()can cause type inference mismatches if the shape ofreactive's return type doesn't strictly matchGraphConfigDatadue to Vue's internal proxies or ifcomputedrefs interfere with the expected string types forlabel/name.- Since
computed()returns aComputedRef<string>, TypeScript will complain ifLogicFlow.GraphConfigDataexpectsstepName?: string. This confirms the type mismatch noted in point build(deps): bump the pip group across 1 directory with 2 updates #1.
Recommendation:
Define the base template as a type-aligned constant (without Vue reactivity) first, then create a separate computed getter that generates a localized copy for the UI.
3. Unnecessary Reactivity / Performance Overhead
Problem:
Wrapping a large, mostly static configuration object with reactive() is performance-intensive and semantically incorrect.
reactive()creates a Proxy over all deeply nested properties. For a complex graph definition, this adds unnecessary overhead.- These templates are likely constants that don't change per-instance unless the language changes. They do not need global reactive tracking on every single field (
height,width,type, etc.). Only the text fields need localization.
Recommendation:
Keep the base template as a plain object.
4. Localization Strategy Flaw
Problem:
The current approach mixes translation logic directly into the template data structure. If t() depends on the current locale, and the locale changes at runtime, LogicFlow might not reactively update the canvas unless it manually polls these values.
Recommendation:
Use a factory function or a computed wrapper outside the template.
Suggested Refactor Pattern
Instead of modifying the raw template export, create a hook or computed property that generates the localized version:
import { computed, unref } from 'vue'
import type LogicFlow from '@logicflow/core'
import { t } from '@/locales'
// 1. Keep the raw template as plain data (no Vue imports, no reactive/computed inside)
export const rawKnowledgeTemplate = {
default: {
nodes: [
{
// ... other props
properties: {
stepName: 'common.labels.basicInfo', // Store Translation KEY, not t() result
displayText: null // placeholder
}
},
// ... rest of nodes
]
}
} satisfies Record<string, LogicFlow.GraphConfigData>
// 2. Create a helper to inject translations
function replaceLabels(node: any): any {
if (!node.properties) return node
// Helper to resolve translation keys
const resolveProp = (obj: any, key: string, locKey: string) => {
if (obj[key] && typeof obj[key] === 'string') {
// Assume the stored string is a translation key if it looks like one,
// or add a specific field like 'i18nKey' to distinguish.
// Better practice: Add a separate `i18nStepName` field in your interface
}
}
// More robust approach: Modify data structure to hold i18n keys separately
return {
...node,
properties: {
...node.properties,
// Assuming you added an i18n key field in your raw template
stepName: node.properties.i18nStepName
? t(node.properties.i18nStepName)
: node.properties.stepName
}
}
}
// 3. Export a localized version (computed based on language)
export const localizedKnowledgeTemplate = computed(() => {
// Deep clone and map translations
const lang = t('lang.current') || 'en' // Access language to trigger reactivity
return cloneAndTranslate(rawKnowledgeTemplate)
})Summary of Actions
- Revert
computed()usage: Do not putcomputed()inside theknowledgeTemplateobject. It breaks type safety and library compatibility. - Store Keys, Not Values: In the raw template, store translation keys (e.g.,
'common.labels.basicInfo') instead of callingt(). - Transform Before Use: Create a
computedproperty or function that takes the raw template, traverses it, replaces keys witht(key), and passes the resulting plain object to LogicFlow.
| config: { fields: [{ label: computed(() => t('workflow.document.list')), value: 'document_list' }] }, | ||
| }, | ||
| }) | ||
|
|
There was a problem hiding this comment.
The provided diff demonstrates a refactoring effort to centralize i18n keys and reduce redundancy, but there are specific points of concern and optimization suggestions.
1. Consistency & Irregularities
-
Inconsistent Key Naming:
- Most changes replace node-specific result labels (e.g.,
workflow.node.result) with a global one (common.labels.result). This is good for consistency. - However, in
searchDocumentNodeanddocumentExtractNode, the "document list" label is changed toworkflow.document.list. - Issue: Why isn't
document_listusing a common key likecommon.labels.documentsor similar? It mixesknowledge.list(seemingly from a different domain namespace) andworkflow.document.list. Ensureworkflow.document.listexists and is correctly translated. - Suggestion: If "document list" is used across multiple nodes outside of just the workflow context, consider moving it to
commonas well. If it's strictly workflow-specific, keep it as is, but ensureknowledge.listis also checked for consistency (why useknowledge.listinstead ofworkflow.knowledge.listorcommon.knowledge.list?).
- Most changes replace node-specific result labels (e.g.,
-
Missing i18n Keys Check:
- Verify that
t('common.labels.result'),t('knowledge.list'), andt('workflow.document.list')exist in your locale files (e.g.,en.json,zh-CN.json). Missing keys will result in raw keys being displayed in the UI.
- Verify that
2. Potential Issues
- Loss of Contextual Specificity (Minor):
- Changing
workflow.searchDocument.documentList->knowledge.listmight remove contextual clarity if "knowledge list" is interpreted differently in other parts of the app. Ensure this label accurately represents the data passed fromsearchDocumentNode.
- Changing
- Reactive Object Performance (Negligible but Noted):
- You are using
computed()insidereactive()objects forlabelandstepName. This is correct for Vue 3 reactivity. However, creating many computed properties adds slight overhead. Sincet()(i18n function) is likely already reactive or stable after initialization, ensuretis not unnecessarily triggering re-renders. In most i18n setups (likevue-i18n),tis reactive only when language changes, so this is safe.
- You are using
3. Optimization Suggestions
A. Reduce Boilerplate with a Helper Function
There is significant repetition in:
config: { fields: [{ label: computed(() => t('...')), value: '...' }] }Suggestion: Create a helper function to generate these field definitions.
// Example helper
import type { ComputedRef } from 'vue';
function createResultField(labelKey: string, value: string = 'result') {
return {
label: computed(() => t(labelKey)),
value,
};
}
// Usage
export const speechToTextNode = reactive({
// ... other props
properties: {
stepName: computed(() => t('workflow.speechToText.label')),
config: {
fields: [createResultField('common.labels.result')]
},
},
})B. Centralize Common Configs
Since many nodes now use the exact same config structure (fields: [{ label: ..., value: 'result' }]), consider defining reusable config objects if they are identical.
C. Validate Translation Keys
Run a script to check if all new keys (common.labels.result, workflow.document.list, knowledge.list) are present in all locale files to prevent missing translations in production.
Summary of Changes Review
| Change | Verdict | Notes |
|---|---|---|
workflow.node.result → common.labels.result |
✅ Good | Improves consistency; reduces duplication. |
workflow.searchDocument.knowledgeList → knowledge.list |
Ensure namespace knowledge is appropriate here. Is it a global domain or workflow-specific? |
|
workflow.*.documentList → workflow.document.list |
✅ Neutral | Standardizes under workflow.document. |
Repeated computed(() => t(...)) |
💡 Optimize | Use a helper function to reduce code redundancy. |
Final Recommendation: The change is logically sound for maintainability. Proceed after verifying that all referenced translation keys exist in your i18n resources.
refactor: finalize internationalization cleanup