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/37266-action-renderers-label-guard.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@object-ui/components': patch
---

fix(components): `action:menu`, `action:group` and `action:icon` render no text for a label that is not a string, instead of crashing or printing `[object Object]`

Clause-②: no
Metadata-protocol: none

An action `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" from an `action:menu` trigger, an `action:group` member or dropdown trigger, and an `action:icon` with no icon; an `action:icon` with an icon wrote `[object Object]` into its accessible name. These three renderers now read every label, their own and each member's, through the same guard `action:button` uses, so a non-string label renders as no label: the menu trigger keeps its "More actions" name, a group dropdown shows "Actions", a menu or dropdown member shows its `name`, an icon shows "?" and is named by its `name`. The action still runs, and the runner is handed no label. A development build logs one warning per component that names the bundle key. The node-level-params warning names a nameless action by its guarded label too. 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 @@ -37,7 +37,7 @@
* read for stored documents.
*/

import { describe, it, expect, vi, beforeEach, afterEach, type Mock } from 'vitest';
import { describe, it, expect, vi, beforeEach, afterEach, type Mock, type MockInstance } from 'vitest';
import { render, screen, fireEvent, waitFor, within, cleanup } from '@testing-library/react';
import '@testing-library/jest-dom';
import React from 'react';
Expand Down Expand Up @@ -389,3 +389,168 @@ describe('action:menu — the member shape of `actions` (the MEMBER-PIN directio
expect(run.mock.calls[0][0]).toMatchObject({ type: 'run', name: 'go', target: 'member-target', objectName: 'account' });
});
});

// ── objectstack#37266 — the shared label guard ──────────────────────────────
//
// `action:menu` and `action:group` read every label, their own and each
// member's, through `renderableLabel` (`../renderable-label.ts`), the guard
// `action:button` reads through (ruling A on objectstack#36717). A locale map
// reaches a renderer only from metadata that skipped `validateComponentProps`;
// it renders no label text, prints no `[object Object]`, is not translated,
// and the menu no longer throws. Text and accessible names only: both
// renderers spread undeclared node keys onto the DOM as attributes.

describe('action:group — a non-string label renders no text and never throws (objectstack#37266)', () => {
// Scoped to this describe: the label pins read every `console.warn`, and the
// file's own `beforeEach` spies only on `console.error`.
const LOCALE_MAP = { en: 'Approve', 'zh-CN': '批准' };
let warn: MockInstance<(...args: unknown[]) => void>;
beforeEach(() => {
warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
warn.mockRestore();
});
const labelWarnings = () => warn.mock.calls.filter((args) => String(args[0]).includes('non-string label'));
const assertNothingLeaked = () => {
// Text and accessible names only: the host's undeclared-prop spread writes every
// node key onto the DOM as an attribute (`actions="[object Object]"` on main for
// any group), which is not a label read and is out of this guard's reach.
expect(document.body.textContent).not.toContain('[object Object]');
for (const el of document.querySelectorAll('[aria-label]')) {
expect(el.getAttribute('aria-label')).not.toContain('[object Object]');
}
expect(document.body.textContent).not.toContain('批准');
expect(document.body.textContent).not.toContain('Approve');
};

it('inline: a locale-map member label renders a button with no text, which still runs with no label', async () => {
mount({
type: 'action:group',
id: 'group_label_inline',
actions: [{ name: 'approve', label: LOCALE_MAP, type: 'run' }],
});
const button = screen.getByRole('button');
expect(button.textContent).toBe('');
assertNothingLeaked();

fireEvent.click(button);
await waitFor(() => expect(run).toHaveBeenCalledTimes(1));
expect((run.mock.calls[0][0] as ActionDef).label).toBeUndefined();

const warned = labelWarnings().map((args) => String(args[0]));
expect(warned).toHaveLength(1);
expect(warned[0]).toContain('action:group "approve"');
});

it('dropdown: a locale-map label on the group and on a member falls back to the defaults', async () => {
mount({
type: 'action:group',
id: 'group_label_dropdown',
display: 'dropdown',
label: LOCALE_MAP,
actions: [{ name: 'approve', label: LOCALE_MAP, type: 'run' }],
});
// The trigger's unlabelled default, and the member's `name`.
const trigger = screen.getByRole('button');
expect(trigger).toHaveTextContent('Actions');
await openMenu(trigger);
expect(screen.getByRole('menuitem')).toHaveTextContent('approve');
assertNothingLeaked();

const warned = labelWarnings().map((args) => String(args[0]));
expect(warned.some((m) => m.includes('action:group "group_label_dropdown"'))).toBe(true);
});

it('CONTROL: string labels render as written in both display modes', async () => {
mount({
type: 'action:group',
id: 'group_label_string',
actions: [{ name: 'approve', label: 'Approve', type: 'run' }],
});
expect(screen.getByRole('button')).toHaveTextContent('Approve');
cleanup();

mount({
type: 'action:group',
id: 'group_label_string_dd',
display: 'dropdown',
label: 'Row',
actions: [{ name: 'approve', label: 'Approve', type: 'run' }],
});
const trigger = screen.getByRole('button');
expect(trigger).toHaveTextContent('Row');
await openMenu(trigger);
expect(screen.getByRole('menuitem')).toHaveTextContent('Approve');
expect(labelWarnings()).toHaveLength(0);
});
});

describe('action:menu — a non-string label renders no text and never throws (objectstack#37266)', () => {
// Scoped to this describe: the label pins read every `console.warn`, and the
// file's own `beforeEach` spies only on `console.error`.
const LOCALE_MAP = { en: 'Approve', 'zh-CN': '批准' };
let warn: MockInstance<(...args: unknown[]) => void>;
beforeEach(() => {
warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
warn.mockRestore();
});
const labelWarnings = () => warn.mock.calls.filter((args) => String(args[0]).includes('non-string label'));

it('a locale-map label on the menu and on a member: no throw, no `[object Object]`, nothing translated', async () => {
mount({
type: 'action:menu',
id: 'menu_label_guard',
label: LOCALE_MAP,
actions: [{ name: 'approve', label: LOCALE_MAP, type: 'run' }],
});

// The trigger falls back to its default accessible name, with no label text.
const trigger = screen.getByRole('button', { name: 'More actions' });
expect(trigger.textContent).toBe('');

// The member falls back to its `name`, as an unlabelled member always has.
const menu = await openMenu(trigger);
const item = screen.getByRole('menuitem');
expect(item).toHaveTextContent('approve');
expect(menu.textContent).not.toContain('[object Object]');
// Text and accessible names only: the host's undeclared-prop spread writes every
// node key onto the DOM as an attribute (`actions="[object Object]"` on main for
// any menu), which is not a label read and is out of this guard's reach.
expect(document.body.textContent).not.toContain('[object Object]');
expect(trigger.getAttribute('aria-label')).toBe('More actions');
expect(document.body.textContent).not.toContain('批准');
expect(document.body.textContent).not.toContain('Approve');

// The member still runs, and the runner is handed no label.
fireEvent.click(item);
await waitFor(() => expect(run).toHaveBeenCalledTimes(1));
expect((run.mock.calls[0][0] as ActionDef).label).toBeUndefined();

// One development warning per component: the menu, and its member.
const warned = labelWarnings().map((args) => String(args[0]));
expect(warned).toHaveLength(2);
expect(warned.some((m) => m.includes('action:menu "menu_label_guard"'))).toBe(true);
expect(warned.some((m) => m.includes('action:menu "approve"'))).toBe(true);
});

it('CONTROL: string labels render as written, and the runner is handed the member label', async () => {
mount({
type: 'action:menu',
id: 'menu_label_string',
label: 'Row',
actions: [{ name: 'approve', label: 'Approve', type: 'run' }],
});
const trigger = screen.getByRole('button', { name: 'Row' });
expect(trigger).toHaveTextContent('Row');
await openMenu(trigger);
const item = screen.getByRole('menuitem');
expect(item).toHaveTextContent('Approve');
fireEvent.click(item);
await waitFor(() => expect(run).toHaveBeenCalledTimes(1));
expect((run.mock.calls[0][0] as ActionDef).label).toBe('Approve');
expect(labelWarnings()).toHaveLength(0);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,14 @@
* spilled into the menu would be run by the menu, not by the icon.
*/

import { describe, it, expect, vi, beforeEach, afterEach, type Mock } from 'vitest';
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach, afterEach, type Mock, type MockInstance } from 'vitest';
import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react';
import '@testing-library/jest-dom';
import React from 'react';
import { ComponentRegistry } from '@object-ui/core';
import type { ActionContext, ActionDef, ActionResult } from '@object-ui/core';
import { ActionProvider } from '@object-ui/react';
import { ActionProvider, SchemaRenderer } from '@object-ui/react';
import { undeclaredNode } from '@object-ui/test-support';
// Module-scope side-effect imports — `action:bar` resolves its members through
// the ComponentRegistry at render time, and the light `dom` project does not
// load the `@object-ui/components` graph. Module scope, not a `beforeAll`, per
Expand All @@ -52,6 +54,7 @@ import '../action-bar';
import '../action-button';
import '../action-icon';
import { toast } from '../../../ui/sonner';
import { resetStaticParamsWarnings } from '../static-params';

type Handler = Mock<(action: ActionDef, ctx: ActionContext) => Promise<ActionResult>>;

Expand Down Expand Up @@ -238,3 +241,84 @@ describe("the icon's own declared visible gate outranks the flag (objectui#4191,
function renderBar(actions: Member[]) {
return render(tree(actions));
}

// ── objectstack#37266 — the shared label guard ──────────────────────────────
//
// `action:icon` reads its label through `renderableLabel`
// (`../renderable-label.ts`), the guard `action:button` reads through (ruling A
// on objectstack#36717), and so does the node-level-params warning in
// `../static-params.ts`. Unguarded, an icon with no `icon` threw on
// `label.charAt` and one with an icon wrote `[object Object]` into its
// `aria-label`.

describe('action:icon — a non-string label renders no text and never throws (objectstack#37266)', () => {
// Scoped to this describe. The file's own rows drive `action:icon` as an
// `action:bar` member with an `api` handler; these mount the icon node alone
// through `SchemaRenderer` with a `run` handler, as a page does.
const LOCALE_MAP = { en: 'Approve', 'zh-CN': '批准' };
let run: Handler;
let warn: MockInstance<(...args: unknown[]) => void>;
beforeEach(() => {
run = vi.fn(async () => ({ success: true }));
warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
resetStaticParamsWarnings();
});
afterEach(() => {
warn.mockRestore();
cleanup();
});
function mount(schema: Record<string, unknown>) {
return render(
<ActionProvider handlers={{ run }} onToast={vi.fn()}>
<SchemaRenderer schema={undeclaredNode(schema)} />
</ActionProvider>,
);
}
const labelWarnings = () => warn.mock.calls.filter((args) => String(args[0]).includes('non-string label'));
const assertNothingLeaked = () => {
expect(document.body.innerHTML).not.toContain('[object Object]');
expect(document.body.textContent).not.toContain('批准');
expect(document.body.textContent).not.toContain('Approve');
};

it('no `icon`: renders the unlabelled initial, named by `name`, and still runs with no label', async () => {
mount({ type: 'action:icon', id: 'icon_label_guard', name: 'approve', actionType: 'run', label: LOCALE_MAP });
const button = screen.getByRole('button', { name: 'approve' });
expect(button.textContent).toBe('?');
assertNothingLeaked();

fireEvent.click(button);
await waitFor(() => expect(run).toHaveBeenCalledTimes(1));
expect((run.mock.calls[0][0] as ActionDef).label).toBeUndefined();

const warned = labelWarnings().map((args) => String(args[0]));
expect(warned).toHaveLength(1);
expect(warned[0]).toContain('action:icon "icon_label_guard"');
});

it('with an `icon`: the accessible name is `name`, never `[object Object]`', () => {
mount({ type: 'action:icon', id: 'icon_label_named', name: 'approve', icon: 'check', actionType: 'run', label: LOCALE_MAP });
expect(screen.getByRole('button')).toHaveAttribute('aria-label', 'approve');
assertNothingLeaked();
});

it('a nameless action with node-level object `params`: the static-params warning prints no `[object Object]`', async () => {
mount({ type: 'action:icon', actionType: 'run', label: LOCALE_MAP, params: { stage: 'won' } });
fireEvent.click(screen.getByRole('button'));
await waitFor(() => expect(run).toHaveBeenCalledTimes(1));
const paramsWarning = warn.mock.calls.map((args) => String(args[0])).find((m) => m.includes('node-level'));
expect(paramsWarning).toBeDefined();
expect(paramsWarning).toContain('action "(unnamed)"');
expect(warn.mock.calls.some((args) => String(args[0]).includes('[object Object]'))).toBe(false);
});

it('CONTROL: a string label is the initial, the accessible name, and the runner label', async () => {
mount({ type: 'action:icon', id: 'icon_label_string', name: 'approve', actionType: 'run', label: 'Approve' });
const button = screen.getByRole('button', { name: 'Approve' });
expect(button.textContent).toBe('A');
fireEvent.click(button);
await waitFor(() => expect(run).toHaveBeenCalledTimes(1));
expect((run.mock.calls[0][0] as ActionDef).label).toBe('Approve');
expect(labelWarnings()).toHaveLength(0);
});
});
27 changes: 1 addition & 26 deletions ui/packages/components/src/renderers/action/action-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { resolveIcon } from './resolve-icon';
import { hasDeclaredVisibilityGate } from './visibility-gate';
import { useAutoTriggerOnce } from './auto-trigger';
import { readStaticParamValues } from './static-params';
import { renderableLabel } from './renderable-label';
import { toButtonVariant, toRunnerVariant } from './runner-variant';
import { DisabledReasonTrigger, describedByWithReason, useDisabledReason } from './disabled-reason';
import type { RendererHostProps } from '../../lib/renderer-host-props';
Expand All @@ -42,32 +43,6 @@ 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
19 changes: 17 additions & 2 deletions ui/packages/components/src/renderers/action/action-group.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import { Loader2, ChevronDown } from 'lucide-react';
import { resolveIcon } from './resolve-icon';
import { hasDeclaredVisibilityGate } from './visibility-gate';
import { readActionEntryParamValues } from './static-params';
import { withRenderableLabel } from './renderable-label';
import { toButtonVariant, toRunnerVariant } from './runner-variant';
import {
DisabledReasonMenuLabel,
Expand Down Expand Up @@ -285,7 +286,7 @@ DropdownActionItem.displayName = 'DropdownActionItem';
// host-EVALUATED enablement verdict, declared rather than left to the index
// signature, as `ActionButtonRendererProps` declares it (objectui#9131).
const ActionGroupRenderer = forwardRef<HTMLDivElement, { schema: ActionGroupSchema; className?: string }>(
({ schema, className, ...props }: { schema: ActionGroupSchema; className?: string; disabled?: boolean; [key: string]: unknown } & RendererHostProps, ref) => {
({ schema: declaredSchema, className, ...props }: { schema: ActionGroupSchema; className?: string; disabled?: boolean; [key: string]: unknown } & RendererHostProps, ref) => {
const {
'data-obj-id': dataObjId,
'data-obj-type': dataObjType,
Expand All @@ -306,6 +307,16 @@ const ActionGroupRenderer = forwardRef<HTMLDivElement, { schema: ActionGroupSche
...rest
} = props;

// Every label read in this group goes through the shared guard (see
// `renderableLabel`): the group's own label here (its `visible` diagnostic
// and the dropdown trigger), and each member's below where `actions` is
// built, so both leaves and the runner's `label` read a guarded one.
const groupKey = dataObjId ?? 'action:group';
const schema = React.useMemo(
() => withRenderableLabel(declaredSchema, groupKey, 'action:group'),
[declaredSchema, groupKey],
);

const { execute } = useAction();
const [dropdownLoading, setDropdownLoading] = useState(false);

Expand All @@ -329,7 +340,11 @@ const ActionGroupRenderer = forwardRef<HTMLDivElement, { schema: ActionGroupSche
// read. The local restates the declared type; both `.map()` callbacks
// below still infer from it.
const declaredActions: UIActionSchema[] = schema.actions || [];
const actions = declaredActions.filter(a => actionRendersAt(a, schema.location));
const actions = declaredActions
.filter(a => actionRendersAt(a, schema.location))
.map((action, index) =>
withRenderableLabel(action, action.name ?? `${groupKey}#${index}`, 'action:group'),
);

const handleExecute = useCallback(
async (action: UIActionSchema) => {
Expand Down
Loading
Loading