Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/36717-action-button-label-guard.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@object-ui/components': patch
---

fix(components): an `action:button` whose label is not a string renders no text instead of crashing the page

Clause-②: no
Metadata-protocol: none

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, still runs its action, never prints `[object Object]`, and a development build logs one warning per component that names the bundle key. The value is not translated: a locale map stays refused by the contract. A string label renders and translates exactly as before.
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ import {
useAction,
} from '@object-ui/react';
import { ComponentPropsMap } from '@objectstack/spec/ui';
import { translatePage } from '@objectstack/spec/system';
import { manifestFromConfigs, validateTree } from '@objectstack/sdui-parser';
import type { SchemaElement } from '@objectstack/sdui-parser';
import { buttonVariants } from '../../../ui/button';
Expand Down Expand Up @@ -606,3 +607,73 @@ describe('action:button — `size` publishes the five sizes the spec row declare
expect(diagnoseCodes({ type: 'action:button', size: 'xl' })).toContain('invalid-enum');
});
});

describe('action:button — a non-string label renders no text and never throws (#36717)', () => {
// The contract's `label` is `z.string()`, localized through the translation
// bundle entry for the component id. A locale map reaches the renderer only
// from metadata that skipped `validateComponentProps`; it must not
// white-screen the page, print `[object Object]`, or be translated.
const LOCALE_MAP = { en: 'Buy credits', 'zh-CN': '购买额度' };

it('an object label renders the button with no text, and a development warning fires once', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
mount(node('action:button', { id: 'label_guard_object', label: LOCALE_MAP, icon: undefined }));
const button = screen.getByRole('button');
expect(button.textContent).toBe('');
expect(document.body.textContent).not.toContain('[object Object]');
expect(document.body.textContent).not.toContain('购买额度');
expect(document.body.textContent).not.toContain('Buy credits');
cleanup();
// The same component again: still no throw, and no second warning.
mount(node('action:button', { id: 'label_guard_object', label: LOCALE_MAP, icon: undefined }));
expect(screen.getByRole('button').textContent).toBe('');
const labelWarnings = warn.mock.calls.filter((args) => String(args[0]).includes('non-string label'));
expect(labelWarnings).toHaveLength(1);
expect(String(labelWarnings[0][0])).toContain('label_guard_object');
} finally {
warn.mockRestore();
}
});

it('an object label still runs the action, and the runner is handed no label', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
mount(node('action:button', { id: 'label_guard_press', label: LOCALE_MAP }));
press();
await waitFor(() => expect(run).toHaveBeenCalledTimes(1));
expect((run.mock.calls[0][0] as ActionDef).label).toBeUndefined();
} finally {
warn.mockRestore();
}
});

it('CONTROL: a string label renders as written, and the runner is handed it', async () => {
mount(node('action:button', { id: 'label_guard_string', label: 'Buy credits' }));
expect(screen.getByRole('button')).toHaveTextContent('Buy credits');
press();
await waitFor(() => expect(run).toHaveBeenCalledTimes(1));
expect((run.mock.calls[0][0] as ActionDef).label).toBe('Buy credits');
});

it('CONTROL: a string label translated through the bundle key for its component id renders translated', () => {
const page = {
name: 'billing',
label: 'Billing',
type: 'app' as const,
regions: [
{
name: 'main',
components: [
{ id: 'buy_credits', type: 'action:button', properties: { label: 'Buy credits', actionType: 'run' } },
],
},
],
};
const bundle = { 'zh-CN': { pages: { billing: { components: { buy_credits: { label: '购买额度' } } } } } };
const translated = translatePage(page, bundle as never, { locale: 'zh-CN' });
const component = translated.regions[0].components[0] as Record<string, unknown>;
mount(component);
expect(screen.getByRole('button')).toHaveTextContent('购买额度');
});
});
39 changes: 34 additions & 5 deletions ui/packages/components/src/renderers/action/action-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,32 @@ function asRecord(value: unknown): Record<string, unknown> | undefined {
: undefined;
}

/** Components already warned about a non-string label, so each warns once. */
const warnedNonStringLabel = new Set<string>();

/**
* The label this button may print: the contract's `label` is `z.string()`, and
* a string is returned as it came. Anything else — typically an inline locale
* map from metadata that never passed `validateComponentProps` — is returned as
* `undefined`, so the button renders no text instead of throwing "Objects are
* not valid as a React child" or printing `[object Object]`. The value is never
* translated here: localization is the translation bundle's entry for the
* component id, and a value the contract refuses is not given a meaning.
* A development build warns once per component.
*/
function renderableLabel(label: unknown, componentKey: string): string | undefined {
if (label == null || typeof label === 'string') return label ?? undefined;
if (process.env.NODE_ENV !== 'production' && !warnedNonStringLabel.has(componentKey)) {
warnedNonStringLabel.add(componentKey);
console.warn(
`[object-ui] action:button "${componentKey}" has a non-string label (${Array.isArray(label) ? 'array' : typeof label}); ` +
'the label was not rendered. The label must be a string: localize it through the translation bundle entry ' +
'pages.PAGE.components.COMPONENT_ID.label, not an inline locale map.',
);
}
return undefined;
}

/**
* The static values this button hands the runner, with the record in scope
* attached as the Undo baseline when the action is an `undoable` update of that
Expand Down Expand Up @@ -156,6 +182,9 @@ const ActionButtonRenderer = forwardRef<

const { execute } = useAction();
const [loading, setLoading] = useState(false);
// Every read of the label below goes through this guard (see `renderableLabel`);
// `data-obj-id` is the component id `SchemaRenderer` hands down.
const label = renderableLabel(schema.label, dataObjId ?? schema.name ?? 'action:button');

// Record data may be passed from SchemaRenderer (e.g. DetailView passes
// record data), bound the three canonical ways — `record.status`, bare
Expand All @@ -179,7 +208,7 @@ const ActionButtonRenderer = forwardRef<
// hide the action, not silently show one whose guard is broken.
const isVisible = useCondition(toPredicateInput(schema.visible), recordData, {
throwOnError: true,
label: `action "${schema.name ?? schema.label ?? 'action:button'}" (visible)`,
label: `action "${schema.name ?? label ?? 'action:button'}" (visible)`,
});
// Spec field is `disabled` (boolean | CEL predicate — disabled when TRUE).
// It previously had zero consumers (the renderer only read a non-spec
Expand Down Expand Up @@ -292,7 +321,7 @@ const ActionButtonRenderer = forwardRef<
// Forward the human label/description so a param-collection dialog
// can title itself as the action ("Create Environment") instead of a
// generic "Action parameters" prompt.
label: schema.label,
label,
description: (schema as any).description,
// The param dialog's submit-button verb, read by the same dialog.
submitText: schema.submitText,
Expand Down Expand Up @@ -411,7 +440,7 @@ const ActionButtonRenderer = forwardRef<
} finally {
setLoading(false);
}
}, [schema, execute, loading, localContext, recordInScope]);
}, [schema, label, execute, loading, localContext, recordInScope]);

// Client-side auto-trigger (#844): a caller (e.g. a welcome-page CTA that
// deep-links into "create") can mark an action `autoTrigger: true` to run
Expand Down Expand Up @@ -482,8 +511,8 @@ const ActionButtonRenderer = forwardRef<
{...{ 'data-obj-id': dataObjId, 'data-obj-type': dataObjType, style }}
>
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{!loading && Icon && <Icon className={cn('h-4 w-4', schema.label && 'mr-2')} />}
{schema.label}
{!loading && Icon && <Icon className={cn('h-4 w-4', label && 'mr-2')} />}
{label}
</Button>
);
// A predicate-disabled button is wrapped in the trigger that carries its
Expand Down
Loading