diff --git a/.changeset/37266-action-renderers-label-guard.md b/.changeset/37266-action-renderers-label-guard.md new file mode 100644 index 00000000000..6ef31c72d13 --- /dev/null +++ b/.changeset/37266-action-renderers-label-guard.md @@ -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. diff --git a/ui/packages/components/src/renderers/action/__tests__/action-group-menu-inputs-11168.test.tsx b/ui/packages/components/src/renderers/action/__tests__/action-group-menu-inputs-11168.test.tsx index 06d2b560792..b5cab5874bc 100644 --- a/ui/packages/components/src/renderers/action/__tests__/action-group-menu-inputs-11168.test.tsx +++ b/ui/packages/components/src/renderers/action/__tests__/action-group-menu-inputs-11168.test.tsx @@ -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'; @@ -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); + }); +}); diff --git a/ui/packages/components/src/renderers/action/__tests__/action-icon-autotrigger.test.tsx b/ui/packages/components/src/renderers/action/__tests__/action-icon-autotrigger.test.tsx index ca817e0aea3..9d6b3c01b03 100644 --- a/ui/packages/components/src/renderers/action/__tests__/action-icon-autotrigger.test.tsx +++ b/ui/packages/components/src/renderers/action/__tests__/action-icon-autotrigger.test.tsx @@ -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 @@ -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>; @@ -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) { + return render( + + + , + ); + } + 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); + }); +}); diff --git a/ui/packages/components/src/renderers/action/action-button.tsx b/ui/packages/components/src/renderers/action/action-button.tsx index 64cebc32710..4d30ccc9349 100644 --- a/ui/packages/components/src/renderers/action/action-button.tsx +++ b/ui/packages/components/src/renderers/action/action-button.tsx @@ -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'; @@ -42,32 +43,6 @@ function asRecord(value: unknown): Record | undefined { : undefined; } -/** Components already warned about a non-string label, so each warns once. */ -const warnedNonStringLabel = new Set(); - -/** - * 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 diff --git a/ui/packages/components/src/renderers/action/action-group.tsx b/ui/packages/components/src/renderers/action/action-group.tsx index 23a007410eb..10b7f6f0923 100644 --- a/ui/packages/components/src/renderers/action/action-group.tsx +++ b/ui/packages/components/src/renderers/action/action-group.tsx @@ -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, @@ -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( - ({ 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, @@ -306,6 +307,16 @@ const ActionGroupRenderer = forwardRef withRenderableLabel(declaredSchema, groupKey, 'action:group'), + [declaredSchema, groupKey], + ); + const { execute } = useAction(); const [dropdownLoading, setDropdownLoading] = useState(false); @@ -329,7 +340,11 @@ const ActionGroupRenderer = forwardRef 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) => { diff --git a/ui/packages/components/src/renderers/action/action-icon.tsx b/ui/packages/components/src/renderers/action/action-icon.tsx index b23b5f49ab7..0682a7b6d21 100644 --- a/ui/packages/components/src/renderers/action/action-icon.tsx +++ b/ui/packages/components/src/renderers/action/action-icon.tsx @@ -26,6 +26,7 @@ import { Loader2 } from 'lucide-react'; import { resolveIcon } from './resolve-icon'; import { hasDeclaredVisibilityGate } from './visibility-gate'; import { useAutoTriggerOnce } from './auto-trigger'; +import { withRenderableLabel } from './renderable-label'; import { readStaticParamValues } from './static-params'; import { toButtonVariant, toRunnerVariant } from './runner-variant'; import { DisabledReasonTrigger, describedByWithReason, useDisabledReason } from './disabled-reason'; @@ -70,7 +71,7 @@ const ActionIconRenderer = forwardRef< context?: ActionIconRendererProps['context']; } >( - ({ schema, className, context: localContext, ...props }: ActionIconRendererProps, ref) => { + ({ schema: declaredSchema, className, context: localContext, ...props }: ActionIconRendererProps, ref) => { const { 'data-obj-id': dataObjId, 'data-obj-type': dataObjType, @@ -95,6 +96,16 @@ const ActionIconRenderer = forwardRef< ...rest } = props; + // Every label read below goes through the shared guard (see `renderableLabel`): + // the `visible` diagnostic, the runner's `label`, `aria-label`, the no-icon + // initial, the tooltip, the static-params warning and the auto-trigger's + // refusal notice all read this schema, whose non-string label is no label. + // `data-obj-id` is the component id `SchemaRenderer` hands down. + const schema = React.useMemo( + () => withRenderableLabel(declaredSchema, dataObjId ?? declaredSchema.name ?? 'action:icon', 'action:icon'), + [declaredSchema, dataObjId], + ); + const { execute } = useAction(); const [loading, setLoading] = useState(false); diff --git a/ui/packages/components/src/renderers/action/action-menu.tsx b/ui/packages/components/src/renderers/action/action-menu.tsx index 0cd06bde0ea..5148e0ab065 100644 --- a/ui/packages/components/src/renderers/action/action-menu.tsx +++ b/ui/packages/components/src/renderers/action/action-menu.tsx @@ -33,6 +33,7 @@ import { Loader2, MoreHorizontal } from 'lucide-react'; import { resolveIcon } from './resolve-icon'; import { hasDeclaredVisibilityGate } from './visibility-gate'; import { useAutoTriggerOnce } from './auto-trigger'; +import { withRenderableLabel } from './renderable-label'; import { readActionEntryParamValues } from './static-params'; import { toButtonVariant, toRunnerVariant } from './runner-variant'; import { DisabledReasonMenuLabel, menuItemReasonAria, useDisabledReason } from './disabled-reason'; @@ -213,7 +214,7 @@ ActionAutoTrigger.displayName = 'ActionAutoTrigger'; // host-EVALUATED enablement verdict, declared rather than left to the index // signature, as `ActionButtonRendererProps` declares it (objectui#9131). const ActionMenuRenderer = forwardRef( - ({ schema, className, ...props }: { schema: ActionMenuSchema; className?: string; disabled?: boolean; [key: string]: unknown } & RendererHostProps, ref) => { + ({ schema: declaredSchema, className, ...props }: { schema: ActionMenuSchema; className?: string; disabled?: boolean; [key: string]: unknown } & RendererHostProps, ref) => { const { 'data-obj-id': dataObjId, 'data-obj-type': dataObjType, @@ -235,6 +236,17 @@ const ActionMenuRenderer = forwardRef withRenderableLabel(declaredSchema, menuKey, 'action:menu'), + [declaredSchema, menuKey], + ); + const { execute } = useAction(); const [loading, setLoading] = useState(false); const moreActionsLabel = useMoreActionsLabel(); @@ -357,7 +369,9 @@ const ActionMenuRenderer = forwardRef + withRenderableLabel(action, action.name ?? `${menuKey}#${index}`, 'action:menu'), + ); if (actions.length === 0) return null; return ( diff --git a/ui/packages/components/src/renderers/action/renderable-label.ts b/ui/packages/components/src/renderers/action/renderable-label.ts new file mode 100644 index 00000000000..0e979351f9c --- /dev/null +++ b/ui/packages/components/src/renderers/action/renderable-label.ts @@ -0,0 +1,64 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The one label guard every action renderer in this directory reads its label + * through: `action:button`, `action:menu`, `action:group`, `action:icon`, and + * the static-params warning. One module, so the four renderers cannot drift + * into four answers to the same off-contract value. + */ + +/** Components already warned about a non-string label, so each warns once. */ +const warnedNonStringLabel = new Set(); + +/** + * The label a renderer 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 renderer 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. + * + * `componentType` names the renderer in the warning; it defaults to + * `action:button`, the renderer this guard was written for. + */ +export function renderableLabel( + label: unknown, + componentKey: string, + componentType = 'action:button', +): string | undefined { + if (label == null || typeof label === 'string') return label ?? undefined; + const memo = `${componentType}:${componentKey}`; + if (process.env.NODE_ENV !== 'production' && !warnedNonStringLabel.has(memo)) { + warnedNonStringLabel.add(memo); + console.warn( + `[object-ui] ${componentType} "${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; +} + +/** + * `subject` with its label passed through `renderableLabel`: the SAME object + * when the label is a string or absent, otherwise a copy whose `label` is + * `undefined`. For a renderer that hands the whole action on (to a leaf, to the + * runner, to `useAutoTriggerOnce`), so every downstream read sees the guarded + * label and none has to repeat the guard. + */ +export function withRenderableLabel( + subject: T, + componentKey: string, + componentType: string, +): T { + const label = renderableLabel(subject.label, componentKey, componentType); + return label === subject.label ? subject : { ...subject, label }; +} diff --git a/ui/packages/components/src/renderers/action/static-params.ts b/ui/packages/components/src/renderers/action/static-params.ts index 283b7d772b7..b3be4c26780 100644 --- a/ui/packages/components/src/renderers/action/static-params.ts +++ b/ui/packages/components/src/renderers/action/static-params.ts @@ -48,6 +48,7 @@ */ import { isConfigBag } from '@object-ui/react'; +import { renderableLabel } from './renderable-label'; /** The two keys this module reads off an action node. */ export interface StaticParamsSubject { @@ -68,7 +69,9 @@ export function resetStaticParamsWarnings(): void { function warnNodeLevelObjectParams(subject: StaticParamsSubject, where: string): void { if (process.env.NODE_ENV === 'production') return; - const name = String(subject.name ?? subject.label ?? '(unnamed)'); + // A nameless action is named by its label, read through the shared guard: an + // inline locale map would otherwise print `[object Object]` here. + const name = String(subject.name ?? renderableLabel(subject.label, '(unnamed)', where) ?? '(unnamed)'); const memo = `${where}:${name}`; if (warned.has(memo)) return; warned.add(memo);