Skip to content
Merged
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 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.
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,11 @@ 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';
import { toast as sonnerToast } from '../../../ui/sonner';
// Module-scope side-effect imports: the registry must hold both renderers when
// `SchemaRenderer` resolves the type, and the light `dom` project does not load
// the components graph. Module scope, not a `beforeAll`, per AGENTS.md 测试纪律.
Expand Down Expand Up @@ -606,3 +608,104 @@ 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('an object label never reaches the auto-trigger refusal notice', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const notice = vi.spyOn(sonnerToast, 'warning').mockImplementation(() => 'id');
try {
// `SchemaRenderer`'s node gate hides the node before the renderer mounts, so
// the refusal path is reached the way `action:bar` reaches it: the renderer
// mounted directly, its own `visible` gate failing.
const Renderer = ComponentRegistry.get('action:button') as React.ComponentType<Record<string, unknown>>;
render(
<ActionProvider handlers={{ run }} onToast={toast} onNavigate={nav} onConfirm={confirm}>
<PredicateScopeProvider scope={{ data: DATA }}>
<Renderer
schema={{ ...node('action:button', { label: LOCALE_MAP, autoTrigger: true, visible: false }) }}
data-obj-id="label_guard_auto"
/>
</PredicateScopeProvider>
</ActionProvider>,
);
await waitFor(() => expect(notice).toHaveBeenCalledTimes(1));
const [message, options] = notice.mock.calls[0] as [unknown, { id?: string } | undefined];
expect(String(message)).not.toContain('[object Object]');
expect(String(message)).toContain('probe_action');
expect(String(options?.id)).not.toContain('[object Object]');
expect(warn.mock.calls.some((args) => String(args[0]).includes('[object Object]'))).toBe(false);
expect(run).not.toHaveBeenCalled();
} finally {
notice.mockRestore();
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('购买额度');
});
});
48 changes: 42 additions & 6 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,16 @@ 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');
// The auto-trigger reads the label for its refusal notice, so it is handed
// the guarded one too. Memoized for cost only: the hook's once-only refs
// make a fresh object harmless.
const autoTriggerSubject = React.useMemo(
() => (label === schema.label ? schema : { ...schema, label }),
[schema, label],
);

// 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 +215,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 +328,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 +447,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 All @@ -425,7 +461,7 @@ const ActionButtonRenderer = forwardRef<
// It is handed this button's own `visible` verdict — the one the early
// return below consults — because the action's declared gate outranks the
// flag (objectui#4191): a hidden action is refused and reported, not run.
useAutoTriggerOnce(schema, isVisible, handleClick);
useAutoTriggerOnce(autoTriggerSubject, isVisible, handleClick);

// A declared boolean `visible: false` is a verdict, not a missing gate —
// truthiness classified it as "ungated" and rendered the action for
Expand Down Expand Up @@ -482,8 +518,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