Skip to content

feat: internationalize dynamic forms - #7958

Merged
wangdan-fit2cloud merged 1 commit into
v3from
pr@v3@feat_model_i18n2
Nov 17, 2026
Merged

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

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

feat: internationalize dynamic forms

v-if="assignmentMethod === 'custom'"
prop="default_value"
:rules="[defaultValueRule]"
>

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.

Issues & Suggestions

1. Potential reactivity bug — defaultValueDrafts is not reactive

const defaultValueDrafts: Record<AssignmentMethod, DynamicFormValue> = { custom: {}, ref_variables: [] }

This is a plain object, so mutations to it won't trigger re-renders if any code ever reads from it reactively. Wrap in reactive() (or use ref) for safety:

const defaultValueDrafts = reactive<Record<AssignmentMethod, DynamicFormValue>>({
  custom: {}, ref_variables: [],
})

2. Aliasing risk: formValue.value.default_value shares reference with the draft

defaultValueDrafts[assignmentMethod.value] = formValue.value.default_value
formValue.value.default_value = defaultValueDrafts[method]

You assign the same reference into/from the draft map. If NodeCascader or JsonInput mutate the array/object in place, you may unintentionally mutate the stored draft. Consider cloning on read/write:

set: (method) => {
  const prev = assignmentMethod.value
  defaultValueDrafts[prev] = cloneDeep(formValue.value.default_value)
  formValue.value.default_value_assignment_method = method
  formValue.value.default_value = cloneDeep(defaultValueDrafts[method])
}

Alternatively use structuredClone / JSON.parse(JSON.stringify(...)).

3. Initial value of default_value when switching methods

When the user switches from custom → ref_variables, the draft starts as []. But there is no guard ensuring the existing formValue.default_value (which might be an object for the custom case) doesn't leak into NodeCascader on first switch. Since the setter assigns defaultValueDrafts[method] explicitly, this is OK — but be aware that initial state before any toggle leaves default_value as whatever was loaded.

4. validator return value removed

The old validator returned true; the new one relies purely on callback. In Element Plus async-validators this is fine as long as callback is always invoked — which it is here (both branches). ✅ Just confirm no caller depends on the boolean return.

5. isReferencePath stricter than previous check

Old check: Array.isArray(value) && value.length > 1.
New check also requires every element to be a non-empty string. This is stricter — good for correctness, but verify downstream code (NodeCascader data shape) always yields strings and that a legitimate reference like ['a', 'b'] doesn't fail due to non-string elements (e.g., numeric IDs). If numeric segments exist, relax to part != null && String(part).length > 0.

6. render resets drafts unconditionally

defaultValueDrafts.custom = {}
defaultValueDrafts.ref_variables = []

Resetting to plain objects is fine, but if these are meant to persist across renders, this wipes them. Confirm intent — looks like intended reset-on-load. If so, add an inline comment clarifying "reset drafts on external load."

Also note: the guard on render uses isReferencePath(formData.default_value) but only when current method is ref_variables. If a form is loaded whose default_value_assignment_method says custom but default_value happens to be an array, it's assigned as-is — probably intentional, but worth a comment.

7. Missing type safety on formValue.value.default_value

DynamicFormValue seemingly allows both {} (custom) and string[] (ref). Consider a discriminated union keyed by default_value_assignment_method so TS can catch mistakes at compile time.

8. trigger: 'blur' for referenceVariableRule may not fire

NodeCascader is a cascader-like picker; validations often need trigger: 'change' instead of 'blur'. If validation seems unresponsive when the user selects a path, switch to 'change' (or use ['blur', 'change']).

9. Minor: naming

assignmentMethod computed as a two-way binding via getter/setter works but hides side effects (mutating formValue). A short JSDoc comment explaining the draft-swap behavior would help maintainability.

10. Optimization: avoid recomputing getters repeatedly in template

The template now uses assignmentMethod (a computed) multiple times — good, cached. Previously used formValue.value.default_value_assignment_method (non-cached path evaluation). This change is an improvement. ✅


Summary of priority fixes: #1 (reactivity), #2 (aliasing), #5 (numeric parts), #8 (cascader validation trigger).

@wangdan-fit2cloud
wangdan-fit2cloud merged commit 0dca97b into v3 Nov 17, 2026
3 of 4 checks passed
@wangdan-fit2cloud
wangdan-fit2cloud deleted the pr@v3@feat_model_i18n2 branch November 17, 2026 01:27

export function inferFieldType(fieldPath: [string, string] | string[], leftOptions?: VisibilityFieldOption[]): InferredFieldType {
return getFieldConfig(fieldPath, leftOptions)?.input_type
}

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's my review of the code:

Summary

The added function getComparisonValueControl is straightforward but has a few things worth reviewing.

Potential Issues & Suggestions

  1. Incomplete mapping / silent defaults

    • Fields not listed (e.g., Date, DateTime, Number, Checkbox, Boolean, etc.) silently fall back to 'input'. If those field types require a different control (e.g., date picker, numeric input), this will produce incorrect UI with no warning. Consider explicitly enumerating all known types, or logging in dev mode when the fallback is hit.
  2. Magic strings / missing enum

    • Both the fieldType values and returned control names are string literals. These are likely reused elsewhere ('SingleSelect', 'singleSelect', etc.). Strongly recommend extracting them into a shared enum or as const union type:
      export type ComparisonControl = 'singleSelect' | 'multiSelect' | 'treeSelect' | 'input'
    • Return type should be explicit rather than inferred as string, so callers get autocomplete and compile-time safety:
      export function getComparisonValueControl(fieldType?: string): ComparisonControl { ... }
  3. Case sensitivity

    • fieldType comparison is case-sensitive. If the upstream source ever emits 'singleselect' or varies casing, the default branch will be taken. Normalize if that risk exists.
  4. Name clarity

    • The return values 'singleSelect' / 'multiSelect' / 'treeSelect' / 'input' look like control identifiers. Renaming the function to something like getComparisonControlType or documenting the expected use would improve readability.
  5. Consider a lookup map instead of switch
    For a simple 1:1 mapping, an object literal is more concise and easier to extend:

    const CONTROL_BY_FIELD_TYPE: Record<string, ComparisonControl> = {
      SingleSelect: 'singleSelect',
      RadioCard: 'singleSelect',
      RadioRow: 'singleSelect',
      MultiSelect: 'multiSelect',
      TreeSelect: 'treeSelect',
    }
    export function getComparisonValueControl(fieldType?: string): ComparisonControl {
      return (fieldType && CONTROL_BY_FIELD_TYPE[fieldType]) || 'input'
    }
  6. Undefined fieldType falls through to default
    This is functionally fine, but if an undefined type should be treated differently from "unknown type", that logic should be made explicit.

  7. No unit tests visible
    Given it's a pure mapping function, a small parameterized test covering each case plus the default is cheap insurance against regressions when new field types are introduced.

Minor/style notes

  • Diff comment references ../../type — unrelated to the change, so no concern there.
  • Function placement just above inferFieldType is fine, though grouping related helpers (or co-locating with other field-type utilities) may aid discoverability.

v-else-if="comparisonControl === 'treeSelect'"
v-model="condition.value"
:data="condition._treeData || []"
:multiple="condition._treeMultiple"

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.

Review (English):

Issues / Potential Problems

  1. Reactivity of _fieldType: The computed depends on condition.value._fieldType. If condition.value is replaced (e.g., whole object reassigned by parent) reactivity works, but if _fieldType is set after field change via a mutation outside Vue's reactive tracking, the computed could go stale. Confirm _fieldType is always updated reactively and before render.

  2. Unhandled control type (default/fallback missing): Previously the template used explicit v-if/v-else-if; now every branch depends on comparisonControl. Make sure there is still an v-else fallback (e.g., plain input) for unknown types—otherwise nothing renders silently when getComparisonValueControl returns undefined.

  3. String vs. enum typing: comparisonControl is compared with string literals ('singleSelect', etc.). If getComparisonValueControl returns an enum/union type, these string comparisons may fail type-check or be fragile. Prefer importing and using the returned type/enum constants.

  4. Naming semantics: Old checks used field type names ('SingleSelect'); new uses UI control names. Ensure getComparisonValueControl maps every relevant field type consistently (e.g., does RadioCard/RadioRow map to singleSelect? Does any type map to treeSelect?). A mismatch here silently changes behavior.

  5. computed import added but verify tree-shaking/bundle: trivial, no issue.

  6. Missing as const / union narrowing in template: In <script setup>, template type narrowing on computed string unions works only if the computed has a narrow literal union return type. Annotate the util's return type explicitly (e.g., type ComparisonControl = 'singleSelect' | 'multiSelect' | 'treeSelect' | ...).

  7. Test coverage: This refactor centralizes mapping logic — add unit tests for getComparisonValueControl covering all field types (including unknown/null) to prevent regressions from the previous inline conditions.

  8. SSR / initial render: condition.value may be undefined briefly; guard inside the util or computed (condition.value?._fieldType) to avoid runtime errors on first paint.

  9. Performance: Negligible; computed caching is fine. No memoization concerns.

  10. Consistency: The outer v-if="!['is_true','is_not_true'].includes(condition.compare)" still hardcodes compare ops. Consider moving this into the same config/util for consistency with the new abstraction.

Summary: Good refactor direction (centralizing control resolution), but verify: (a) exhaustive/typed return values, (b) a default/fallback branch in template, (c) reactive freshness of _fieldType, (d) null-safety, and (e) test coverage for the new util.

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