Skip to content

Commit 08bf7d2

Browse files
fix(components): action:button renders no text for a non-string label instead of crashing the page (#37262)
Fixes #36717 Clause-②: no Metadata-protocol: none ## 维护者速读 - 页面上的操作按钮,文字若不是字符串(例如代码注册、没过校验的页面里写成多语言对象),以前整页白屏;现在按钮照常显示并可点击,只是不显示文字,开发环境会提示一次。字符串文字的显示与翻译和以前完全一样。 - 执行维护者裁决「保持走翻译包」(选项 A):按钮文字仍只接受字符串,靠翻译包里该组件的条目翻译;本次只加渲染防护,不翻译多语言对象,也不改协议。 - 出错的后果:最坏是那个按钮没有文字,页面其余部分不受影响;改动可直接撤回。另有一处行为变化:以前写成数字的按钮文字会照样显示,现在同样不显示并提示一次(协议本来就只接受字符串)。 - 要你做的:无。 ## What changes `ui/packages/components/src/renderers/action/action-button.tsx`: every read of `schema.label` goes through one guard, `renderableLabel`. A string label is returned unchanged. Any other value (an inline locale map from metadata that skipped `validateComponentProps`) becomes no label: the button renders with no text and still runs its action, nothing prints `[object Object]`, and a development build logs one `console.warn` per component, keyed on the component id, naming the bundle key `pages.PAGE.components.COMPONENT_ID.label`. The dev warning follows the existing `process.env.NODE_ENV !== 'production'` pattern in `auto-trigger.ts`. The value is never translated, so a value the contract refuses gets no meaning. The guard covers all five label reads in the file: the `visible` diagnostic label, the `label` forwarded to the runner (the param dialog's title), the icon spacing class, the rendered text, and the subject handed to `useAutoTriggerOnce`. That hook builds its user-facing refusal toast and toast id from the label, so it now gets the guarded label (`{ ...schema, label }` when they differ). Ruling: option A (7118756694), the maintainer's 「保持走翻译包」. `label` stays `z.string()` and `packages/spec` is untouched. Responsibility: - whose code: the platform's own `@object-ui/components` `action:button` renderer; - existing platform path: the translation bundle key for the component id, which is the contract and already translates a string label; - who reaches it: pages whose metadata skipped `validateComponentProps` (for example code-registered pages) and carry a non-string label. ## Tests A new top-level `describe` for #36717 in the existing action-button harness `action-button-icon-inputs-11168.test.tsx`, which mounts the node through the real `SchemaRenderer` and `ActionProvider`: - an object label renders the button with empty text, shows no `[object Object]` and neither locale string, and a second mount of the same component does not warn again (exactly one warning, which names the component id); - an object label still runs the action, and the runner gets no label; - an object label on a hidden `autoTrigger` button gives a refusal toast whose message and id carry no `[object Object]` (it names the action by `name`), and no console warning carries it either; - CONTROL: a string label renders and is forwarded to the runner; - CONTROL: a string label translated by `translatePage` through `pages.billing.components.buy_credits.label` renders `购买额度`. ## Acceptance notes - Behaviour change: a numeric label (for example `5`) rendered as text before this PR. It is now dropped like any other non-string label, with the same dev warning. The contract (`z.string()`) already refuses it, so this follows ruling A. - Same defect family, out of this card's reach: `action:menu`, `action:group` and `action:icon` also render a non-string label raw, and `action:menu` throws on a locale map. The follow-up is #37266. - The dev warning is keyed on the component id, then `name`. A button with neither shares the fallback key `action:button`, so only the first such button warns. - A button with a non-string label and no icon has no accessible name. That follows from the ruling's "render no text", and the dev warning names the fix. ## Verification Two-minute check: `pnpm --dir ui exec vitest run packages/components/src/renderers/action/__tests__/action-button-icon-inputs-11168.test.tsx -t "non-string label"`. Expected: 5 passed. <details><summary>Ablation of the auto-trigger hand-off (head fce37f7)</summary> `node scripts/ablation-replace.mjs` put back `useAutoTriggerOnce(schema, isVisible, handleClick)` (anchor 1 to 0, blob 60bb1f1 to 426c38142ef3). Result: 1 failed, 4 passed. The failure: `expected '"[object Object]" is not available on…' not to contain '[object Object]'`. After the restore, the blob equals HEAD (60bb1f1) and `git diff HEAD` is empty. The first version of this pin (da40a35) mounted the node through `SchemaRenderer`. Its node gate hides a `visible: false` node before the renderer mounts, so the hook never ran and the toast was never called; that failed the same way locally and in CI. It was a mounting error, not timing. The pin now mounts the registered renderer directly, which is the path `action:bar` takes. </details> <details><summary>Ablation (guard reverted, head e8894fd)</summary> `node scripts/ablation-replace.mjs` replaced the guard's string check with `return label as string | undefined;`. The anchor went from 1 to 0 hits and the blob from 212e689 to 4aa3e1708bd4. Result: 2 failed, 2 passed. Both object-label tests threw "Objects are not valid as a React child (found: object with keys {en, zh-CN})", which is the defect as it is on main. Both controls stayed green. After the restore, the blob equals HEAD (212e689) and `git diff HEAD` is empty. </details> <details><summary>Suites and gates (round 1 head e13c940; round 2 head fce37f7 below)</summary> - Round 2 at fce37f7: `pnpm --filter @object-ui/components type-check && vitest run packages/components/src/renderers/action/` gave 37 files and 619 tests passed (VERDICT command-exit 0). The harness file gave 60/60. - `pnpm --filter @object-ui/components type-check` passed, chained with `&&` before `vitest run packages/components/src/renderers/action/` (38 files, 626 tests passed). VERDICT command-exit 0. - Full `packages/components/` suite on e8894fd: 510 files passed, 1 skipped; 4970 tests passed. The only later code change is the warning key (`dataObjId`), and the action-renderer directory was re-run on the final head. - `dispatch-gates --commands`: 38 families derived and run; `--ran` accounted for all 38. 37 exited 0 on e13c940. `vitest run scripts/` had one 15 s timeout under box contention (`js-comment-mask-returns-interpolation-9424`). That file passed on re-run under the lock on the final head. - NOT MEASURED locally: the CI type-check lanes the derivation lists as CI-only, the CI-measured-only families, and Test UI shards beyond `packages/components`. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYmRepQK9DkZeU7F53D)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QSeKYmRepQK9DkZeU7F53D <!-- signed: repo:objectstack#4 · os-justin · session_01QSeKYmRepQK9DkZeU7F53D --> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 4fb03eb commit 08bf7d2

3 files changed

Lines changed: 155 additions & 6 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/components': patch
3+
---
4+
5+
fix(components): an `action:button` whose label is not a string renders no text instead of crashing the page
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The `action:button` `label` is a string, localized through the translation bundle entry for the component id (`pages.PAGE.components.COMPONENT_ID.label`). A non-string label, such as an inline locale map from code-registered page metadata that never passed `validateComponentProps`, used to throw "Objects are not valid as a React child" and white-screen the whole page. The button now renders with no text and still runs its action. Every read of the label goes through the same guard, including the auto-trigger refusal notice, so `[object Object]` is never shown. A development build logs one warning per component that names the bundle key. A numeric label, which the contract also refuses, used to render as text and is now dropped with the same warning. The value is not translated: a locale map stays refused by the contract. A string label renders and translates exactly as before.

‎ui/packages/components/src/renderers/action/__tests__/action-button-icon-inputs-11168.test.tsx‎

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,11 @@ import {
6767
useAction,
6868
} from '@object-ui/react';
6969
import { ComponentPropsMap } from '@objectstack/spec/ui';
70+
import { translatePage } from '@objectstack/spec/system';
7071
import { manifestFromConfigs, validateTree } from '@objectstack/sdui-parser';
7172
import type { SchemaElement } from '@objectstack/sdui-parser';
7273
import { buttonVariants } from '../../../ui/button';
74+
import { toast as sonnerToast } from '../../../ui/sonner';
7375
// Module-scope side-effect imports: the registry must hold both renderers when
7476
// `SchemaRenderer` resolves the type, and the light `dom` project does not load
7577
// the components graph. Module scope, not a `beforeAll`, per AGENTS.md 测试纪律.
@@ -606,3 +608,104 @@ describe('action:button — `size` publishes the five sizes the spec row declare
606608
expect(diagnoseCodes({ type: 'action:button', size: 'xl' })).toContain('invalid-enum');
607609
});
608610
});
611+
612+
describe('action:button — a non-string label renders no text and never throws (#36717)', () => {
613+
// The contract's `label` is `z.string()`, localized through the translation
614+
// bundle entry for the component id. A locale map reaches the renderer only
615+
// from metadata that skipped `validateComponentProps`; it must not
616+
// white-screen the page, print `[object Object]`, or be translated.
617+
const LOCALE_MAP = { en: 'Buy credits', 'zh-CN': '购买额度' };
618+
619+
it('an object label renders the button with no text, and a development warning fires once', () => {
620+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
621+
try {
622+
mount(node('action:button', { id: 'label_guard_object', label: LOCALE_MAP, icon: undefined }));
623+
const button = screen.getByRole('button');
624+
expect(button.textContent).toBe('');
625+
expect(document.body.textContent).not.toContain('[object Object]');
626+
expect(document.body.textContent).not.toContain('购买额度');
627+
expect(document.body.textContent).not.toContain('Buy credits');
628+
cleanup();
629+
// The same component again: still no throw, and no second warning.
630+
mount(node('action:button', { id: 'label_guard_object', label: LOCALE_MAP, icon: undefined }));
631+
expect(screen.getByRole('button').textContent).toBe('');
632+
const labelWarnings = warn.mock.calls.filter((args) => String(args[0]).includes('non-string label'));
633+
expect(labelWarnings).toHaveLength(1);
634+
expect(String(labelWarnings[0][0])).toContain('label_guard_object');
635+
} finally {
636+
warn.mockRestore();
637+
}
638+
});
639+
640+
it('an object label still runs the action, and the runner is handed no label', async () => {
641+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
642+
try {
643+
mount(node('action:button', { id: 'label_guard_press', label: LOCALE_MAP }));
644+
press();
645+
await waitFor(() => expect(run).toHaveBeenCalledTimes(1));
646+
expect((run.mock.calls[0][0] as ActionDef).label).toBeUndefined();
647+
} finally {
648+
warn.mockRestore();
649+
}
650+
});
651+
652+
it('an object label never reaches the auto-trigger refusal notice', async () => {
653+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
654+
const notice = vi.spyOn(sonnerToast, 'warning').mockImplementation(() => 'id');
655+
try {
656+
// `SchemaRenderer`'s node gate hides the node before the renderer mounts, so
657+
// the refusal path is reached the way `action:bar` reaches it: the renderer
658+
// mounted directly, its own `visible` gate failing.
659+
const Renderer = ComponentRegistry.get('action:button') as React.ComponentType<Record<string, unknown>>;
660+
render(
661+
<ActionProvider handlers={{ run }} onToast={toast} onNavigate={nav} onConfirm={confirm}>
662+
<PredicateScopeProvider scope={{ data: DATA }}>
663+
<Renderer
664+
schema={{ ...node('action:button', { label: LOCALE_MAP, autoTrigger: true, visible: false }) }}
665+
data-obj-id="label_guard_auto"
666+
/>
667+
</PredicateScopeProvider>
668+
</ActionProvider>,
669+
);
670+
await waitFor(() => expect(notice).toHaveBeenCalledTimes(1));
671+
const [message, options] = notice.mock.calls[0] as [unknown, { id?: string } | undefined];
672+
expect(String(message)).not.toContain('[object Object]');
673+
expect(String(message)).toContain('probe_action');
674+
expect(String(options?.id)).not.toContain('[object Object]');
675+
expect(warn.mock.calls.some((args) => String(args[0]).includes('[object Object]'))).toBe(false);
676+
expect(run).not.toHaveBeenCalled();
677+
} finally {
678+
notice.mockRestore();
679+
warn.mockRestore();
680+
}
681+
});
682+
683+
it('CONTROL: a string label renders as written, and the runner is handed it', async () => {
684+
mount(node('action:button', { id: 'label_guard_string', label: 'Buy credits' }));
685+
expect(screen.getByRole('button')).toHaveTextContent('Buy credits');
686+
press();
687+
await waitFor(() => expect(run).toHaveBeenCalledTimes(1));
688+
expect((run.mock.calls[0][0] as ActionDef).label).toBe('Buy credits');
689+
});
690+
691+
it('CONTROL: a string label translated through the bundle key for its component id renders translated', () => {
692+
const page = {
693+
name: 'billing',
694+
label: 'Billing',
695+
type: 'app' as const,
696+
regions: [
697+
{
698+
name: 'main',
699+
components: [
700+
{ id: 'buy_credits', type: 'action:button', properties: { label: 'Buy credits', actionType: 'run' } },
701+
],
702+
},
703+
],
704+
};
705+
const bundle = { 'zh-CN': { pages: { billing: { components: { buy_credits: { label: '购买额度' } } } } } };
706+
const translated = translatePage(page, bundle as never, { locale: 'zh-CN' });
707+
const component = translated.regions[0].components[0] as Record<string, unknown>;
708+
mount(component);
709+
expect(screen.getByRole('button')).toHaveTextContent('购买额度');
710+
});
711+
});

‎ui/packages/components/src/renderers/action/action-button.tsx‎

Lines changed: 42 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,32 @@ function asRecord(value: unknown): Record<string, unknown> | undefined {
4242
: undefined;
4343
}
4444

45+
/** Components already warned about a non-string label, so each warns once. */
46+
const warnedNonStringLabel = new Set<string>();
47+
48+
/**
49+
* The label this button may print: the contract's `label` is `z.string()`, and
50+
* a string is returned as it came. Anything else — typically an inline locale
51+
* map from metadata that never passed `validateComponentProps` — is returned as
52+
* `undefined`, so the button renders no text instead of throwing "Objects are
53+
* not valid as a React child" or printing `[object Object]`. The value is never
54+
* translated here: localization is the translation bundle's entry for the
55+
* component id, and a value the contract refuses is not given a meaning.
56+
* A development build warns once per component.
57+
*/
58+
function renderableLabel(label: unknown, componentKey: string): string | undefined {
59+
if (label == null || typeof label === 'string') return label ?? undefined;
60+
if (process.env.NODE_ENV !== 'production' && !warnedNonStringLabel.has(componentKey)) {
61+
warnedNonStringLabel.add(componentKey);
62+
console.warn(
63+
`[object-ui] action:button "${componentKey}" has a non-string label (${Array.isArray(label) ? 'array' : typeof label}); ` +
64+
'the label was not rendered. The label must be a string: localize it through the translation bundle entry ' +
65+
'pages.PAGE.components.COMPONENT_ID.label, not an inline locale map.',
66+
);
67+
}
68+
return undefined;
69+
}
70+
4571
/**
4672
* The static values this button hands the runner, with the record in scope
4773
* attached as the Undo baseline when the action is an `undoable` update of that
@@ -156,6 +182,16 @@ const ActionButtonRenderer = forwardRef<
156182

157183
const { execute } = useAction();
158184
const [loading, setLoading] = useState(false);
185+
// Every read of the label below goes through this guard (see `renderableLabel`);
186+
// `data-obj-id` is the component id `SchemaRenderer` hands down.
187+
const label = renderableLabel(schema.label, dataObjId ?? schema.name ?? 'action:button');
188+
// The auto-trigger reads the label for its refusal notice, so it is handed
189+
// the guarded one too. Memoized for cost only: the hook's once-only refs
190+
// make a fresh object harmless.
191+
const autoTriggerSubject = React.useMemo(
192+
() => (label === schema.label ? schema : { ...schema, label }),
193+
[schema, label],
194+
);
159195

160196
// Record data may be passed from SchemaRenderer (e.g. DetailView passes
161197
// record data), bound the three canonical ways — `record.status`, bare
@@ -179,7 +215,7 @@ const ActionButtonRenderer = forwardRef<
179215
// hide the action, not silently show one whose guard is broken.
180216
const isVisible = useCondition(toPredicateInput(schema.visible), recordData, {
181217
throwOnError: true,
182-
label: `action "${schema.name ?? schema.label ?? 'action:button'}" (visible)`,
218+
label: `action "${schema.name ?? label ?? 'action:button'}" (visible)`,
183219
});
184220
// Spec field is `disabled` (boolean | CEL predicate — disabled when TRUE).
185221
// It previously had zero consumers (the renderer only read a non-spec
@@ -292,7 +328,7 @@ const ActionButtonRenderer = forwardRef<
292328
// Forward the human label/description so a param-collection dialog
293329
// can title itself as the action ("Create Environment") instead of a
294330
// generic "Action parameters" prompt.
295-
label: schema.label,
331+
label,
296332
description: (schema as any).description,
297333
// The param dialog's submit-button verb, read by the same dialog.
298334
submitText: schema.submitText,
@@ -411,7 +447,7 @@ const ActionButtonRenderer = forwardRef<
411447
} finally {
412448
setLoading(false);
413449
}
414-
}, [schema, execute, loading, localContext, recordInScope]);
450+
}, [schema, label, execute, loading, localContext, recordInScope]);
415451

416452
// Client-side auto-trigger (#844): a caller (e.g. a welcome-page CTA that
417453
// deep-links into "create") can mark an action `autoTrigger: true` to run
@@ -425,7 +461,7 @@ const ActionButtonRenderer = forwardRef<
425461
// It is handed this button's own `visible` verdict — the one the early
426462
// return below consults — because the action's declared gate outranks the
427463
// flag (objectui#4191): a hidden action is refused and reported, not run.
428-
useAutoTriggerOnce(schema, isVisible, handleClick);
464+
useAutoTriggerOnce(autoTriggerSubject, isVisible, handleClick);
429465

430466
// A declared boolean `visible: false` is a verdict, not a missing gate —
431467
// truthiness classified it as "ungated" and rendered the action for
@@ -485,8 +521,8 @@ const ActionButtonRenderer = forwardRef<
485521
{...{ 'data-obj-id': dataObjId, 'data-obj-type': dataObjType, style }}
486522
>
487523
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
488-
{!loading && Icon && <Icon className={cn('h-4 w-4', schema.label && 'mr-2')} />}
489-
{schema.label}
524+
{!loading && Icon && <Icon className={cn('h-4 w-4', label && 'mr-2')} />}
525+
{label}
490526
</Button>
491527
);
492528
// A predicate-disabled button is wrapped in the trigger that carries its

0 commit comments

Comments
 (0)