Skip to content
This repository was archived by the owner on Nov 4, 2026. It is now read-only.

Commit 1422a92

Browse files
feat(types,plugin-dashboard): dashboard header and globalFilters state the spec member on both faces (objectui#7759 group A) (#10744)
Part of #7759 Clause-②: yes This PR covers group A of objectui#7759 only: the `header` / `globalFilters` row of the `complex.zod.ts#DashboardComponentSchema` pair. The card stays open for group C (`FormSchema.layout`), which this PR does not touch. Dev session: `https://claude.ai/code/session_014fWVhLzhxR8qrFsJ5o8TYW` (PM seat `domain:spec#1`, claim comment 5851963524). ## Determination per key (ruling 5617465269) `@objectstack/spec` declares both keys, so principle 1 governs both: the zod mirror and the TypeScript declaration both follow the spec, in both directions. The stop condition did not fire on either key. It covers the case where principle 1 and the objectui#4580 route point opposite ways. Here the spec types every nested label involved as `I18nLabel` (a string or an inline per-locale map), which is exactly the objectui#4580 form. So the two routes agree on the label, and principle 1 alone decides the remaining members. | key | does the spec declare it? | before | after | |---|---|---|---| | `header` | **yes**. `DashboardSchema` has `header: DashboardHeaderSchema.optional()`. In `DashboardHeaderActionSchema`, `label` is `I18nLabelSchema`, `actionUrl` is `z.string()` (required), and `actionType` is `WidgetActionTypeSchema.optional()`, the spec's `ActionType` | mirror: the spec's member, by reference. Declaration: a hand-written restatement whose actions were typed `label: string`, `actionUrl?: string`, `actionType?: string` | the declaration drops the extra `'header'` omission and inherits the spec's member through the Omit projection its other spec-owned keys use | | `globalFilters` | **yes**. `DashboardSchema` has `globalFilters: z.array(GlobalFilterSchema).optional()`. In `GlobalFilterSchema`, each `options` item is a strict `{ value, label: I18nLabelSchema }` pair. In `GlobalFilterOptionsFromSchema`, `labelField` is `z.string()` (required) and `filter` is `FilterConditionSchema.optional()` | declaration: `SpecGlobalFilter[]`, already by reference (objectui#4032). Mirror: the spec's shape spread into a local `z.object`, with `options` and `optionsFrom` restated | the mirror's `GlobalFilterSchema` is `stripImportedDefaults(SpecGlobalFilterSchema)`, the spec's schema whole. The TypeScript face is unchanged | The pair is also in the ledger's `SPEC_DERIVED_PAIRS`. **grep evidence.** Measured on the installed pin, `@objectstack/spec` 17.4.0, against its `src/ui/dashboard.zod.ts`: ``` grep -nE 'header: DashboardHeaderSchema|globalFilters: z.array\(GlobalFilterSchema\)|label: I18nLabelSchema|actionUrl: z.string|labelField: z.string|filter: FilterConditionSchema' src/ui/dashboard.zod.ts ``` - **Pin (17.4.0):** the command hits all six members. - **objectstack `main` (`8d1f7ab`):** the same file, read with `git show`, declares the same shape for both schemas. The only difference is an added `.meta({ title })` on several members, which does not change the input type. ## Measured on BASE `5c61e5241`, before any edit: both keys were DISJOINT I measured with a throwaway probe (deleted afterwards). It checked the type face with `@ts-expect-error` legs and ran `safeParse` on the mirror: | spelling | mirror (safeParse) | declaration (tsc) | |---|---|---| | header action `label: { en: … }` | accepted | refused | | header action with no `actionUrl` | refused | accepted | | header action `actionType: 'bogus'` | refused | accepted | | filter `options: ['EMEA']` (bare-string shorthand) | accepted | refused | | filter option with no `label` | accepted | refused | | `optionsFrom` with no `labelField` | accepted | refused | | `optionsFrom.filter` as an array | accepted | accepted (the declared `FilterCondition` type has an index signature, so it admits an array; the spec's runtime schema refuses one) | | unknown key inside a filter | accepted, and stripped without a message | n/a | | filter option `label: { en: … }` | **refused** | accepted | ## Premise check (the dispatch's H1–H5) - **H1: partly false.** The ledger docblock said both keys "carry the inline-locale widening one level down". That holds for `header` only. `globalFilters` measured WIDER for a different reason: the objectui-local option shorthand and the relaxed `optionsFrom`. Its locale arm ran the other way: the mirror refused the map, which puts it on the `KnownDrift` side. The card body's group-A table inherits the same wording. The row was correct to exist; only its description was wrong. - **H2: held.** `globalFilters` is declared as `SpecGlobalFilter[]`. `header` was omitted from the spec projection and re-declared locally, and the spec does declare it (see the table above). - **H3: held.** The `DashboardComponentSchema` mirror line is `globalFilters: z.array(GlobalFilterSchema)`. The `z.array(z.any())` line belongs to `DashboardConfigSchema`, a different pair, which this PR leaves alone. - **H4: held.** The pin and objectstack `main` agree on both shapes. - **H5: held.** Both rows were retired because the pair now measures clean in both directions. `KnownDrift` keeps `widgets` for this pair, because it still measures as drift. ## What changed - **`packages/types/src/complex.ts`**: `DashboardComponentSchema` extends the Omit projection over `DASHBOARD_SPEC_EXCLUDED` alone. The hand-written `header` is deleted, and the docblock records what it was and why it went. - **`packages/types/src/zod/complex.zod.ts`**: `GlobalFilterSchema = stripImportedDefaults(SpecGlobalFilterSchema)`. The local `options` / `optionsFrom` restatement and its delegated `superRefine` are gone. The spec's own object-level refinement (the date `defaultValue` check) arrives with the schema. The `SpecDashboardFields` docblock no longer calls the filter config "deliberately looser than spec's". - **`packages/plugin-dashboard/src/DashboardRenderer.tsx`**: principle 1 requires the read site to implement every arm the spec declares. `tActionLabel` now collapses the `I18nLabel` to the active language with `pickLocalized` before using it, either as button text or as the `dashboardActionLabel` fallback. The `ActionDef` built for each header action carries the resolved label too; that memo depends on `language` rather than on a memoised resolver's identity (AGENTS.md #10). The `handleClick` fallback `actionUrl || label` was unreachable, because the guard above it already returns when `actionUrl` is empty; it is now `executeAction(actionUrl)`. - **Red-first on BASE source:** both new renderer cases threw `Objects are not valid as a React child (found: object with keys {en, zh-CN})`. The mirror accepted that exact document. - **`packages/types/src/__tests__/zod-mirror-parity.test.ts`**: - `WiderThanDeclared` loses the pair's entry whole, and a departure note replaces it. `WIDER_ARMS` loses the pair's two rows. - `KnownDrift` for the pair goes from `'header' | 'widgets' | 'globalFilters'` to `'widgets'`. - The header figures move from 7 / 9 / 9 (split 5 / 4 / 0 / 0) to 6 / 7 / 7 (5 / 2 / 0 / 0) for `WiderThanDeclared`, and from 46 / 86 to 46 / 84 for `KnownDrift`. Each move is recorded in the sentence beside its figure. - **New pin, `packages/types/src/__tests__/dashboard-header-global-filters-spec-7759.test.ts`**, with checks on both faces for each key: - `Equal` rows showing the declaration and the mirror input each equal the spec member, plus a control row showing the old restatement is not the spec member; - `@ts-expect-error` legs for each refused spelling; - `safeParse` legs that assert the issue envelope (`code` plus `path`); - a check that no `scope` default is authored, and a control document. - **Existing pins whose premise this PR removes** (fixture triage): - `twins-spec-by-reference-9736.test.ts`: `header` is no longer a twin-only omission. The case now asserts it equals the spec member; the `slots` half stays as it was. - `p1-spec-alignment.test.ts`: the fixture `{ label: 'Refresh', actionType: 'refresh' }` was legal only under the removed restatement, and the spec and the mirror both refuse it. It is replaced by a spec-legal action that uses a locale-map label, plus an `@ts-expect-error` leg for `refresh`. - `report-chart-query-spec-parity.test.ts`: the "pinned divergences" block, which asserted the local schema accepts what the spec refuses, now asserts both schemas give the same verdict on the same literals. The case that pinned the old composition is replaced by one that shows the date refinement still applies when the options are spec-legal. - **Docs** (AGENTS.md #2; ruling principle 3): - `content/docs/plugins/plugin-dashboard.mdx` gives header actions the spec's shape. - `content/docs/guide/dashboard-filters.md` says objectui's own validator refuses what the platform refuses, and that `labelField` is required. - The `packages/plugin-dashboard/README.md` example comment adds `labelField`. Before this PR it taught an `optionsFrom` the platform refuses at publish. - **`.changeset/7759-dashboard-header-global-filters-spec.md`**: `@object-ui/types` **minor**, because the validator's `globalFilters` accept set narrows and the `header` interface narrows `actionUrl` / `actionType`. `@object-ui/plugin-dashboard` **patch**, for the renderer fix. The changeset lists the breaking semantics in full. ## Accept-set delta (why Clause-② is yes) - **Validator, narrowed:** - the bare-string option shorthand is refused: `invalid_type` at `globalFilters.N.options.M`; - a label-less option is refused: `invalid_union` at `….options.M.label`; - an `optionsFrom` with no `labelField` is refused: `invalid_type` at `….optionsFrom.labelField`; - an array `optionsFrom.filter` is refused; - an unknown key in a filter is now refused by name with `unrecognized_keys` at `globalFilters.N`, where before it was stripped without a message. - **Validator, widened:** an option `label` may be an inline per-locale map. The spec has always allowed it, and the filter bar already resolves it with `pickLocalized`. - **Interface, narrowed:** `header.actions[].actionUrl` is required, and `actionType` is limited to the spec's `ActionType`. - **Interface, widened:** `header.actions[].label` accepts `I18nLabel`. - **Runtime, deliberately unchanged:** `@object-ui/core`'s `normalizeFilterOptions` still converts a STORED bare-string option on read and logs its deprecation warning, on the objectstack#7917 option-② window ("the spec stays strict; the renderer's lift retires behind a survey"). This is the split objectui#4165 established: the schema refuses the legacy spelling and the read path lifts it. The filter bar also still falls back to `valueField` when `labelField` is absent. Renderers never parse through the mirror; the only runtime callers of `safeValidateSchema` are the CLI's `validate` / `check`, which is the authoring door. ## File surface beyond the claim, declared The claim listed `complex.ts`, `complex.zod.ts`, this pair's ledger rows, one pin and one changeset. Measurement took this PR further, as the dispatch allows ("若实测表明…按生产者侧修,落点与理由写进报告和 PR 正文"): - **`DashboardRenderer.tsx` and its test.** Aligning the declaration with the spec is the forced consequence: without the read-site change, a spec-legal document the mirror accepts would still crash the renderer, and principle 1 requires the read site to implement the spec's arm. objectui#9092 / PR #9364 set the same precedent for `plugin-grid`. - **The three existing `packages/types` pins listed above.** Each one pinned the removed restatement or divergence. - **Three docs files.** They follow the implementation. The PM should re-derive serial constraints on `packages/plugin-dashboard/src/DashboardRenderer.tsx`; I did not scan other open PRs (dev contract). ## Tests and gates at head `70d26a8` The final union ran after the last commit, and after merging `main`, which brought in PR #10730 cleanly. | command | reading | |---|---| | `pnpm --filter @object-ui/types type-check` | exit 0 (VERDICT command-exit 0) | | `pnpm exec vitest run packages/types/` | 242 files / 5294 tests passed | | `pnpm --filter @object-ui/core type-check` / `plugin-dashboard` / `plugin-designer` / `plugin-list` | exit 0 each, script name echoed. The dependency closure was built first with `turbo run build --concurrency=2`, and the rebuilt `types` dist was checked for the change | | `pnpm exec vitest run packages/core/` | 173 / 3504 passed | | `pnpm exec vitest run packages/plugin-dashboard/` | 136 / 1283 passed | | `pnpm exec vitest run packages/plugin-designer/` | 24 / 175 passed | | `pnpm exec vitest run examples/schema-catalog/` | 34 / 2198 passed | | CLI `retired-view-dashboard-key-9533` / `app-generator` plus app-shell `dashboard-schema` / `DashboardWidgetInspector` | 4 files / 77 tests passed | | `eslint --no-inline-config --format json` on the 9 changed TS files | 9 files, 0 errors, 21 warnings; the same files at BASE carry the same 21 | | `node scripts/check-changeset-presence.mjs` / `check-changeset-no-major.mjs` | exit 0 / exit 0 | | `pnpm check:new-line-citations` | exit 0: "0 new citation(s)" | | `pnpm check:control-bytes` / `check:spec-symbols` / `check:test-path-roots` | exit 0 each. `check:spec-symbols` first caught my local alias named `DashboardHeaderAction`, a spec export name; it was renamed `DashboardNodeHeaderAction` | | `pnpm check:doc-types` / `doc-snippets` / `doc-examples` / `doc-fences` / `doc-example-ids` / `docs-route-closure` / `readme-exports` / `doc-example-readers` / `shell-escape-residue` | exit 0 each; doc snippets "676 of 676 block(s) judged, 0 failed" (after the gate's own scoped build) | | `pnpm check:changeset-claims` / `pending-changeset-literals` / `installed-pin-claims` / `handler-key-reads` | exit 0 each | | `node scripts/check-governed-queue-guard.mjs --test` over the 13 branch paths | NOT GOVERNED | **Consumer direction.** The dependents checked were `core`, `plugin-dashboard`, `plugin-designer` and `plugin-list`: the packages the census found importing `DashboardComponentSchema`. `plugin-list`'s hit is a comment. `examples/schema-catalog` and the CLI / app-shell dashboard files cover the validator's accept set. **Cross-package reverse check.** I pasted a header action with `actionType: 'refresh'` into a probe in `plugin-dashboard`'s test project. It gave `TS2322` against the rebuilt `packages/types/dist`, which shows the consumer reads the new `.d.ts`. The probe was then removed. ## Reverse verification on committed HEAD Each mutation went through `ablation-replace.mjs`, and each restore was proven the same way: the blob equals HEAD and `git diff HEAD` is empty. The expected direction was registered before each run. - **A. Mirror: `GlobalFilterSchema` back to the local override** (blob `72d0b6a85b32` to `e52ba4acbdfe`). - `tsc -p tsconfig.test.json` exit 2. The failures: the pin's mirror and local `Equal` rows, `assertionDriftMatchesLedger` and `assertionWiderMatchesLedger` (both naming `complex.zod.ts#DashboardComponentSchema`), and `assertionWiderLedgerRecordsEveryKey` (naming `globalFilters`). - vitest: 6 failed / 48 passed. - Restored to `72d0b6a85b32`. - **B. Declaration: hand-written `header` restored** (blob `ace7e75f2ade` to `cfb61c54e999`). - `tsc` exit 2, with 10 errors. They cover: the pin's declared `Equal` row and its locale-map literal; two unused `@ts-expect-error` legs; the twins pin; `p1-spec-alignment`; and the three ledger reconciliations, which name the pair and the key `header`. - The runtime legs stayed 9 / 9 passed, as registered: the mirror does not move under this mutation. - Restored. - **C. Renderer: `tActionLabel` passes the authored label through unresolved.** vitest: 2 failed / 8 passed, with `Objects are not valid as a React child`. Restored. ## NOT MEASURED - **Spec Main Shape Gate** (`scripts/spec-main-shape-gate.mjs`). Reason: its workflow builds `@objectstack/spec` from objectstack `main`, injects it, and runs `TURBO_FORCE=true pnpm type-check` across the whole workspace. That is farm-scale, and CI owns it. Mitigation: a source comparison of both touched spec schemas, pin 17.4.0 against `main` `8d1f7ab`, shows no shape difference. - **`pnpm check:spec-floors`.** A prerequisite failure, not a finding: all 9 findings were `[no-artifact]` for packages outside the built closure. This diff does not move any `@objectstack/spec` range. - **Repo-wide `pnpm lint` and the full `pnpm test` farm.** Left to CI. The ESLint run above is a narrowed run. Three facts make it a measurement: the population is eslint's own `**/*.{ts,tsx}` config; the file count, 9, comes from the `--format json` output; and `eslint.config.js` declares no `parserOptions` / `projectService`, and no custom `eslint-rules/*` rule reads the filesystem, so type-aware linting is off and this diff cannot move a verdict in an untouched file. ## Acceptance notes - **Runtime lift kept.** `normalizeFilterOptions`, the bare-string lift in `@object-ui/core`, remains. For a validated document it is now a read-path tolerance only, and its retirement stays on objectstack#7917's schedule. It is not touched here. - **`labelField` fallback kept.** `DashboardFilterBar`'s `from.labelField ? … : …` fallback to `valueField` is unreachable for a validated document and was left in place for stored ones; nobody is assigned to carry it. - **`name` fallback kept.** The `headerActionDefs` fallback `name: a.actionUrl || label` survives only for a stored action with no `actionUrl`, which the mirror has always refused. It was left in place, matching the click guard. - **Card body.** The card body's group-A table calls the `globalFilters` difference "inline-locale widening". Measured, it is the local shorthand, and the locale arm ran the other way (see H1). This is recorded so the group-C round does not inherit the wording. - **Commit trailers.** The first commit carries only the `Claude-Session:` trailer. The later commits carry a model-free `Co-Authored-By: Claude` / `Claude-Session:` pair. History was not rewritten. - **Scope.** Group C (`FormSchema.layout`) is untouched and remains on the card, which stays open. --- _Generated by [Claude Code](https://claude.ai/code/session_014fWVhLzhxR8qrFsJ5o8TYW)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7b395d8 commit 1422a92

13 files changed

Lines changed: 482 additions & 212 deletions
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
---
2+
'@object-ui/types': minor
3+
'@object-ui/plugin-dashboard': patch
4+
---
5+
6+
`DashboardComponentSchema.header` and `.globalFilters` now state
7+
`@objectstack/spec`'s `DashboardSchema` member on both faces, the TypeScript
8+
interface and the Zod validator (objectui#7759 group A). Both keys are declared
9+
by the spec, and each face used to refuse something the other accepted.
10+
11+
**`header` (TypeScript interface).** The hand-written restatement is gone. The
12+
interface inherits the spec's `DashboardHeader` through the same
13+
`Omit` projection of the spec `Dashboard` type as its other spec-owned keys. Breaking for code
14+
that builds header actions in TypeScript:
15+
16+
- `actions[].label` is `I18nLabel`: a string or an inline per-locale map. It used
17+
to be `string`.
18+
- `actions[].actionUrl` is required. It used to be optional.
19+
- `actions[].actionType` is the spec's `ActionType` (`url`, `script`, `modal`,
20+
`flow`, `api` or `form`). It used to be any string.
21+
22+
The validator is unchanged here: it always took the spec's `header`.
23+
24+
**`globalFilters` (Zod validator).** `GlobalFilterSchema` is now the spec's
25+
`GlobalFilterSchema` by reference, and its local `options` / `optionsFrom`
26+
restatement is gone. Breaking for documents that relied on the looser validator:
27+
28+
- the bare-string option shorthand (`options: ['EMEA']`) is refused with
29+
`invalid_type` at `globalFilters.N.options.M`. Write
30+
`{ "value": "EMEA", "label": "EMEA" }`;
31+
- an option with no `label` is refused at `globalFilters.N.options.M.label`;
32+
- an `optionsFrom` with no `labelField` is refused with `invalid_type` at
33+
`globalFilters.N.optionsFrom.labelField`. Name the value field again if the
34+
options have no separate label column;
35+
- an `optionsFrom.filter` must be a filter-condition object. An array is
36+
refused;
37+
- an unknown key in a filter is refused with `unrecognized_keys` at
38+
`globalFilters.N`. It used to be removed without a message.
39+
40+
Widening: an option `label` may now be an inline per-locale map, which the spec
41+
has always allowed and the filter bar already resolves. The TypeScript type is
42+
unchanged, because it already bound the spec's `GlobalFilter`. The runtime is
43+
unchanged too: `@object-ui/core` still converts a STORED bare-string option into
44+
a pair when it reads the document, and logs a deprecation warning. That
45+
conversion keeps its own retirement schedule (objectstack#7917).
46+
47+
**`@object-ui/plugin-dashboard`.** Before this change, a header action whose
48+
`label` was an inline per-locale map crashed the renderer: React reported
49+
`Objects are not valid as a React child`. The mirror accepted that document.
50+
`DashboardRenderer` now shows the label in the active language, both as the
51+
button text and as the fallback for the
52+
`dashboards.NAME.actions.KEY.label` bundle lookup.

‎content/docs/guide/dashboard-filters.md‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,9 +173,12 @@ deliberately not compared as-is: `field = "last_7_dayz"` matches no row, and
173173
the widget would render a perfectly healthy-looking `0`.
174174

175175
Static `options` are `@objectstack/spec` object pairs —
176-
`{ "value": "amer", "label": "AMER" }`. This is the only form the platform
177-
accepts: a dashboard is validated against `GlobalFilterSchema` when it is
178-
published, and anything else is refused there.
176+
`{ "value": "amer", "label": "AMER" }`, where `label` is a string or an inline
177+
per-locale map (`{ "en": "AMER", "zh-CN": "美洲" }`). This is the only form the
178+
platform accepts: a dashboard is validated against `GlobalFilterSchema` when it is
179+
published, and anything else is refused there. objectui's own validator
180+
(`@object-ui/types`, which `objectui validate` runs) uses the same spec schema, so
181+
it refuses the same documents before they reach the platform.
179182

180183
> **Deprecated: the bare-string shorthand.** `"options": ["EMEA", "APAC"]` is
181184
> still lifted by the runtime to `{ "value": "EMEA", "label": "EMEA" }` pairs so
@@ -202,6 +205,11 @@ Options can also be fetched from an object at runtime:
202205
}
203206
```
204207

208+
`object`, `valueField` and `labelField` are all required; when the options have
209+
no separate label column, name the value field again, as above. An optional
210+
`filter` narrows the source records and is a filter-condition object
211+
(`{ "status": "active" }`), not an array.
212+
205213
With a dataset-capable data source, `optionsFrom` resolves distinct values
206214
**server-side** (a GROUP BY over the source object), so the option list is
207215
complete regardless of row count. Data sources without dataset queries fall

‎content/docs/plugins/plugin-dashboard.mdx‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,12 @@ npm install @object-ui/plugin-dashboard
4343
header?: { // Header block — strict: exactly these keys
4444
showTitle?: boolean,
4545
showDescription?: boolean,
46-
actions?: { label, actionUrl?, actionType?, icon? }[]
46+
actions?: {
47+
label: string | LocaleMap, // button text; a map resolves to the active language
48+
actionUrl: string, // required: the URL, or the target the action runner dispatches
49+
actionType?: 'url' | 'script' | 'modal' | 'flow' | 'api' | 'form',
50+
icon?: string // Lucide icon name
51+
}[]
4752
},
4853
globalFilters?: GlobalFilter[], // Dashboard-level filter bar — see "Dashboard-level filters"
4954
dateRange?: { // Built-in date-range filter — see "Dashboard-level filters"

‎packages/plugin-dashboard/README.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -387,14 +387,16 @@ into each bound widget's inline query (`AND`-combined with the widget's own
387387
// optional "object": the object `field` lives on — its fields.<object>.<field> / fieldOptions.<object>.<field>.<value> bundle entries then win, "label" is the fallback
388388
"type": "select", // text | select | date | number | lookup
389389
// Canonical @objectstack/spec pair form — the only form the platform
390-
// accepts at publish. The bare-string shorthand (["EMEA", …]) is
391-
// deprecated: still lifted at runtime, now warns (objectui#4356).
390+
// accepts at publish, and the only form `@object-ui/types` validates
391+
// (objectui#7759). The bare-string shorthand (["EMEA", …]) is
392+
// deprecated: a STORED one is still lifted at runtime, and warns (objectui#4356).
392393
"options": [
393394
{ "value": "EMEA", "label": "EMEA" },
394395
{ "value": "APAC", "label": "APAC" },
395396
{ "value": "AMER", "label": "AMER" }
396397
]
397-
// or dynamic: "optionsFrom": { "object": "accounts", "valueField": "region" }
398+
// or dynamic: "optionsFrom": { "object": "accounts", "valueField": "region", "labelField": "region" }
399+
// (`labelField` is required by the spec, even when it names the value field)
398400
}
399401
],
400402
"widgets": [

‎packages/plugin-dashboard/src/DashboardRenderer.tsx‎

Lines changed: 46 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,15 @@ import { DatasetWidget } from './DatasetWidget';
4747
import { useWidgetSubCaption } from './widgetSubCaption';
4848
import { DashboardFilterBar } from './DashboardFilterBar';
4949

50+
/**
51+
* One `header.actions[]` entry, as the node's declaration types it: the spec's
52+
* `DashboardHeaderAction` by reference since objectui#7759, so `label` is an
53+
* `I18nLabel` and `actionUrl` is required. Named for the node, not the spec
54+
* type, because it is read off `DashboardComponentSchema` and a local alias may
55+
* not wear a spec export's name (`check:spec-symbols`).
56+
*/
57+
type DashboardNodeHeaderAction = NonNullable<NonNullable<DashboardComponentSchema['header']>['actions']>[number];
58+
5059
interface SortableWidgetWrapperProps {
5160
id: string;
5261
disabled?: boolean;
@@ -273,19 +282,6 @@ const DashboardRendererInner = forwardRef<HTMLDivElement, DashboardRendererProps
273282
);
274283
const { variables: filterValues, setVariable: setFilterValue, resetVariables: resetFilterValues } = usePageVariables();
275284

276-
// Build ActionDef[] from header actions so useActionEngine can dispatch by name.
277-
const headerActionDefs = useMemo<ActionDef[]>(() => {
278-
const actions = schema.header?.actions ?? [];
279-
return actions.map((a: { label: string; actionUrl?: string; actionType?: string; icon?: string }) => ({
280-
name: a.actionUrl || a.label,
281-
type: (a.actionType as ActionDef['type']) || 'url',
282-
target: a.actionUrl,
283-
label: a.label,
284-
}));
285-
}, [schema.header?.actions]);
286-
287-
const { executeAction, engine } = useActionEngine({ actions: headerActionDefs });
288-
289285
// ── i18n: convention-based label resolution for dashboard / widget /
290286
// action text. The dashboard name (`schema.name`) keys all lookups; when
291287
// it's missing we silently degrade to the raw English fallbacks.
@@ -340,18 +336,44 @@ const DashboardRendererInner = forwardRef<HTMLDivElement, DashboardRendererProps
340336
/**
341337
* Translate a header-action label using the
342338
* `{ns}.dashboards.{dashName}.actions.{actionKey}.label` convention.
343-
* Falls back to the action's English label when no translation exists or
339+
* Falls back to the action's authored label when no translation exists or
344340
* the dashboard schema has no `name`.
341+
*
342+
* The authored label is the spec's `I18nLabel` — a string or an inline
343+
* per-locale map — so it is collapsed to the active language BEFORE it is
344+
* used as the fallback or the button text (objectui#7759). This read used
345+
* to return the authored value as-is, typed `string` by a hand-written
346+
* restatement of `header`, and a map reached React as a button child.
345347
*/
346348
const tActionLabel = useCallback(
347-
(action: { label: string; actionUrl?: string }): string => {
348-
if (!dashName) return action.label;
349-
const key = action.actionUrl || action.label;
350-
return dashboardActionLabel(dashName, key, action.label);
349+
(action: DashboardNodeHeaderAction): string => {
350+
const authored = pickLocalized(action.label, language) || '';
351+
if (!dashName) return authored;
352+
const key = action.actionUrl || authored;
353+
return dashboardActionLabel(dashName, key, authored);
351354
},
352-
[dashName, dashboardActionLabel],
355+
[dashName, dashboardActionLabel, language],
353356
);
354357

358+
// Build ActionDef[] from header actions so useActionEngine can dispatch by
359+
// name. `ActionDef.label` is a `string`, so the def carries the label
360+
// resolved against the active language, exactly as the button shows it.
361+
// Keyed on `language`, not on a memoised resolver's identity (AGENTS.md #10).
362+
const headerActionDefs = useMemo<ActionDef[]>(() => {
363+
const actions = schema.header?.actions ?? [];
364+
return actions.map((a) => {
365+
const label = pickLocalized(a.label, language) || undefined;
366+
return {
367+
name: a.actionUrl || label,
368+
type: (a.actionType as ActionDef['type']) || 'url',
369+
target: a.actionUrl,
370+
label,
371+
};
372+
});
373+
}, [schema.header?.actions, language]);
374+
375+
const { executeAction, engine } = useActionEngine({ actions: headerActionDefs });
376+
355377
/**
356378
* Translate a widget title / description using the
357379
* `{ns}.dashboards.{dashName}.widgets.{widgetId}.title|description`
@@ -1067,10 +1089,10 @@ const DashboardRendererInner = forwardRef<HTMLDivElement, DashboardRendererProps
10671089
)}
10681090
{headerActions.length > 0 && (
10691091
<div className="flex gap-2 mt-3">
1070-
{headerActions.map((action: { label: string; actionUrl?: string; actionType?: string; icon?: string }, i: number) => {
1092+
{headerActions.map((action, i) => {
10711093
const Icon = resolveLucideIcon(action.icon);
10721094
const handleClick = async () => {
1073-
const { actionType, actionUrl, label } = action;
1095+
const { actionType, actionUrl } = action;
10741096
if (!actionType || !actionUrl) {
10751097
console.warn('[DashboardRenderer] Header action missing actionType/actionUrl:', action);
10761098
return;
@@ -1092,7 +1114,9 @@ const DashboardRendererInner = forwardRef<HTMLDivElement, DashboardRendererProps
10921114
// never dispatched — a screen flow could not even be launched
10931115
// from a dashboard (framework#3528). The runner reports an
10941116
// unknown type itself, so there is nothing to second-guess here.
1095-
const result = await executeAction(actionUrl || label);
1117+
// `actionUrl` is non-empty here (the guard above returns
1118+
// otherwise), and it is the name the def registered under.
1119+
const result = await executeAction(actionUrl);
10961120
if (!result?.success) console.warn('[DashboardRenderer] action failed', result?.error);
10971121
};
10981122
return (

‎packages/plugin-dashboard/src/__tests__/DashboardRenderer.headerActions.test.tsx‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import { render, screen, cleanup, waitFor } from '@testing-library/react';
3232
import userEvent from '@testing-library/user-event';
3333
import type { DashboardComponentSchema } from '@object-ui/types';
3434
import { ActionProvider } from '@object-ui/react';
35+
import { I18nProvider } from '@object-ui/i18n';
3536
import { DashboardRenderer } from '../DashboardRenderer';
3637

3738
afterEach(cleanup);
@@ -84,6 +85,53 @@ describe('DashboardRenderer header actions', () => {
8485
});
8586
});
8687

88+
/**
89+
* A header action's `label` is the spec's `I18nLabel` — a plain string OR an
90+
* inline per-locale map (`DashboardHeaderActionSchema.label`), and the zod
91+
* mirror has always admitted the map because it takes the spec's `header` by
92+
* reference. The TypeScript twin restated it as `string` until objectui#7759
93+
* group A, so this read site handed the authored value straight to React: an
94+
* unnamed dashboard rendered the map as a button child, a named one passed it
95+
* as the bundle lookup's `fallback`. Both render the resolved string now.
96+
*/
97+
function localizedActionDashboard(name?: string): DashboardComponentSchema {
98+
return {
99+
type: 'dashboard',
100+
...(name ? { name } : {}),
101+
label: 'Ops',
102+
widgets: [],
103+
header: {
104+
actions: [{
105+
label: { en: 'Convert Lead', 'zh-CN': '转换线索' },
106+
actionUrl: 'convert_lead_wizard',
107+
actionType: 'flow',
108+
}],
109+
},
110+
} satisfies DashboardComponentSchema;
111+
}
112+
113+
describe('DashboardRenderer header actions — inline per-locale label (objectui#7759)', () => {
114+
it.each([
115+
['an unnamed dashboard', undefined],
116+
['a named dashboard with no bundle entry', 'ops_board'],
117+
])('renders the active-language string for %s, and dispatches by actionUrl', async (_what, name) => {
118+
const handler = vi.fn().mockResolvedValue({ success: true });
119+
render(
120+
<I18nProvider config={{ defaultLanguage: 'zh', detectBrowserLanguage: false, resources: {} }}>
121+
<ActionProvider handlers={{ flow: handler }}>
122+
<DashboardRenderer schema={localizedActionDashboard(name)} />
123+
</ActionProvider>
124+
</I18nProvider>,
125+
);
126+
127+
const button = screen.getByRole('button', { name: '转换线索' });
128+
expect(button.textContent).not.toContain('[object Object]');
129+
await userEvent.setup().click(button);
130+
await waitFor(() => expect(handler).toHaveBeenCalledTimes(1));
131+
expect(handler.mock.calls[0][0]).toMatchObject({ type: 'flow', target: 'convert_lead_wizard' });
132+
});
133+
});
134+
87135
/**
88136
* A dashboard authored the way the flagship exemplar authors them: `header`
89137
* declared with both text flags ON, because a standalone embed genuinely does

0 commit comments

Comments
 (0)