Skip to content

Commit 7f60e9d

Browse files
fix(core): refuse a single-record action's row count before its dialog, and translate the refusal (objectui#13384) (#13395)
Closes #13384 Clause-②: yes (widening: ActionRunnerHandler / ServerActionHandler gain optional refuseBeforeInput; ServerActionRecordIdResolution gains optional errorKey; nothing is refused) ## What changed A single-record action launched from a list toolbar with 0 or 2+ rows selected is now refused before any confirmation or param dialog opens. It gets the same toast as before and sends nothing. With exactly one row the dialog behaves as before. The refusal is also translated now: it read English under zh-CN. - **`@object-ui/core` `ActionRunner`**: `ActionRunnerHandler` gains an optional `refuseBeforeInput(action, context)`. `execute` asks the handler it will dispatch to, after the `condition` / `disabled` gates and before `confirmText` and the param collection. A refusal goes through the usual post-execution (error toast, `onFailure`), and nothing is dispatched. If the refusal names an `errorKey`, the runner translates it through `setTranslator`'s translator, with the English as default. This is the same channel the runner's own `RUNNER_TEXT` uses, so core still takes no i18n dependency. - **`@object-ui/core` `serverActionHandler`**: - The two refusal strings come from a keyed table (`actions.selectExactlyOneRow`, `actions.selectRowFirst`). - `resolveServerActionRecordId` returns the key as `errorKey` beside the English `error`. - `createServerActionHandler` attaches `refuseBeforeInput`, which runs the same resolver the dispatch runs, including an injected `resolveRecordId`. So a record page, which resolves against its own record, is never refused. - It skips the early check when the dialog itself collects a param named `recordId`. - The check at dispatch time stays for callers that invoke the handler directly. - **`@object-ui/app-shell` `createConsoleServerActionHandler`**: forwards `refuseBeforeInput` from core's handler, which it builds with the wrapper's own `resolveRecordId`. Without the forward the runner never saw the member and the console kept its dialog-first order. - **`@object-ui/i18n`**: both keys are added to all ten packs. No German low-high quote span is added, so the `de-quote-pairing-3876` counts are unchanged. - One changeset: core, i18n and app-shell, patch. Why the runner asks the handler instead of holding the row rule itself: on a record page, a related-list grid publishes `selectedRecords: []` into the page's runner context. A runner-side copy of the rule would refuse every `record_header` action there. Only the handler knows its own resolver. ## Tests Run on head `024092b03`: - `pnpm exec vitest run --maxWorkers=2` over `packages/core/src/actions/__tests__/`, `packages/i18n/`, and the 21 app-shell test files that read `consoleServerAction`, `resolveServerActionRecordId` or `toolbarScriptSelection`: **146/146 files, 2113 passed, 13 skipped**. - New `ActionRunner.recordRowGuard-13384` (core): - 0 rows and 2 rows: the toast shows, no param dialog and no confirmation open, and nothing is sent. - 1 row: the dialog opens and the one request carries that row. - Controls: an object-level toolbar action with 0 rows still opens its dialog; an injected record resolver is not refused; a dialog that collects `recordId` is not judged early. - The translator is asked by key, with the English default; an empty answer falls back to English. - `serverActionHandler.test.ts`: pins for `errorKey` and `refuseBeforeInput`. - `consoleServerAction.test.tsx`: pins the forward, both alone and through a real `ActionRunner`. 0 and 2 rows open no dialog, pre-open no tab and send nothing. 1 row opens the dialog. - `ObjectView.toolbarScriptSelection-12331`: its five 0- and 2-row cases now also assert that no dialog opened, beside the toast and the absent request. Every other claim in that suite is unchanged. - New `recordSelectionRefusal-13384` (i18n): pins the zh-CN text; every other pack defines both keys with its own text. - Type-check, `NODE_OPTIONS=--max-old-space-size=8192 pnpm exec turbo run type-check --concurrency=2`: - `--filter=@object-ui/core`: 3/3 tasks - `--filter=@object-ui/app-shell`: 30/30 tasks, including `tsc -p tsconfig.test.json` - `pnpm check:i18n-keys`, `check:i18n-drift`, `check:i18n-dead-keys`: exit 0. Dead-keys is report-only. It lists the two new keys as needs-review, the same class as their `actions.*` siblings, which are also reached only through a key table. - eslint on the touched files: 0 errors. The warnings are pre-existing `no-explicit-any`; none is added. - `check:new-line-citations`: 0 new. `check-changeset-presence`: pass. ### Ablation Each run used `ablation-replace` with on-disk proof, and was restored to `git diff HEAD` empty: | Mutation | Result | |---|---| | The runner's early refusal disabled | 5 core cases red (0 rows, 2 rows, confirmation, two translator cases) | | `errorKey` dropped from the refusal | 4 red | | The console wrapper's forward deleted | 8 red: 3 in `consoleServerAction.test.tsx`, plus all five 0- and 2-row cases of `ObjectView.toolbarScriptSelection-12331` | ## Acceptance notes - **Out of scope, still open:** the console `flowHandler` in `useConsoleActionRuntime.tsx` calls `resolveServerActionRecordId` directly and is not a forwarded handler. A `type: 'flow'` action with params, launched from a list toolbar with 0 or 2+ rows, still opens its dialog first, and its refusal still reads English. It could read the new `errorKey`. That file belongs to objectui#13379's claim, so it was not touched here. - **Out of scope, still open:** the console wrapper's own `newTabUrl` fast-path refusal ("This action runs on a single record — no record id available.") is still a hard-coded English string with no pack key. - [x] Adds no product-specific widget, dialog, hook or string (see AGENTS.md › Product-neutral renderer) Session: `https://claude.ai/code/session_01WJozybDmRH8z2c5SD7vJkj` 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WJozybDmRH8z2c5SD7vJkj --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d9aff15 commit 7f60e9d

20 files changed

Lines changed: 585 additions & 28 deletions
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@object-ui/core': patch
3+
'@object-ui/i18n': patch
4+
'@object-ui/app-shell': patch
5+
---
6+
7+
A single-record action launched with 0 or several rows selected is refused before any dialog opens, and the refusal is translated (objectui#13384).
8+
9+
`ActionRunner` now asks the handler it will dispatch to for an early refusal (`ActionRunnerHandler`'s optional `refuseBeforeInput`) before the confirmation and the param dialog. The handlers `createServerActionHandler` builds answer it with the row-count check the dispatch already runs, so "select a row first" and "select exactly one row" are shown before the user fills anything in, and nothing is sent. With exactly one row the dialog behaves as before. A host that wraps the built handler in its own function keeps the early refusal only by forwarding `refuseBeforeInput`; the console's `createConsoleServerActionHandler` now forwards it, so on a list page (HotCRM's "Add to Campaign" on My Leads) the refusal toast shows and no dialog opens.
10+
11+
Both refusals now carry a pack key (`actions.selectRowFirst`, `actions.selectExactlyOneRow`, defined in every shipped pack). `resolveServerActionRecordId` returns it as `errorKey` beside the English `error`, and the runner's early refusal goes through its translator by that key.

‎packages/app-shell/src/utils/__tests__/consoleServerAction.test.tsx‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ vi.mock('sonner', () => {
2121
});
2222

2323
import { toast } from 'sonner';
24+
import { ActionRunner } from '@object-ui/core';
2425
import { createConsoleServerActionHandler } from '../consoleServerAction';
2526

2627
/** A pre-openable tab stub with the surface the wrapper drives. */
@@ -419,3 +420,75 @@ describe('a declared onSuccess block defers to the runner (objectui#5221)', () =
419420
expect(openSpy).toHaveBeenCalledWith('/app/crm/contacts/rec_42', '_blank');
420421
});
421422
});
423+
424+
describe('the early record-id refusal is forwarded to the runner (objectui#13384)', () => {
425+
const ADD_TO_CAMPAIGN = {
426+
type: 'script',
427+
name: 'add_to_campaign',
428+
objectName: 'crm_lead',
429+
locations: ['list_toolbar', 'list_item'],
430+
actionParams: [{ name: 'campaign', label: 'Campaign', type: 'text', required: true }],
431+
};
432+
const launch = () => JSON.parse(JSON.stringify(ADD_TO_CAMPAIGN));
433+
434+
it("the wrapper answers core's refusal, with its pack key, and nothing for one row", () => {
435+
const { handler } = makeHandler();
436+
437+
expect(handler.refuseBeforeInput?.(launch(), { selectedRecords: [] })).toEqual({
438+
error: 'This action runs on a single record — select a row first.',
439+
errorKey: 'actions.selectRowFirst',
440+
});
441+
expect(handler.refuseBeforeInput?.(launch(), { selectedRecords: [{ id: 'a' }, { id: 'b' }] })).toEqual({
442+
error: 'This action runs on a single record — select exactly one row.',
443+
errorKey: 'actions.selectExactlyOneRow',
444+
});
445+
expect(handler.refuseBeforeInput?.(launch(), { selectedRecords: [{ id: 'a' }] })).toBeUndefined();
446+
});
447+
448+
it('an injected resolveRecordId (record-page policy) decides the early refusal too', () => {
449+
const { handler } = makeHandler({ resolveRecordId: () => ({ recordId: 'page_rec_1' }) });
450+
451+
expect(handler.refuseBeforeInput?.(launch(), { selectedRecords: [] })).toBeUndefined();
452+
});
453+
454+
it.each([
455+
['0 rows', [] as Record<string, unknown>[], 'This action runs on a single record — select a row first.'],
456+
['2 rows', [{ id: 'a' }, { id: 'b' }], 'This action runs on a single record — select exactly one row.'],
457+
])('through a real runner, %s: refused before the param dialog, with no tab and no request', async (_label, rows, refusal) => {
458+
const openSpy = vi.spyOn(window, 'open');
459+
const { handler, fetch } = makeHandler();
460+
const runner = new ActionRunner({ selectedRecords: rows });
461+
const toastSpy = vi.fn();
462+
const dialog = vi.fn(async () => ({ campaign: 'cmp_webinar' }));
463+
runner.setToastHandler(toastSpy);
464+
runner.setParamCollectionHandler(dialog);
465+
runner.registerHandler('script', handler);
466+
467+
const result = await runner.execute({ ...launch(), opensInNewTab: true });
468+
469+
expect(result).toEqual({ success: false, error: refusal });
470+
expect(dialog).not.toHaveBeenCalled();
471+
expect(fetch).not.toHaveBeenCalled();
472+
expect(openSpy).not.toHaveBeenCalled();
473+
expect(toastSpy).toHaveBeenCalledWith(refusal, expect.objectContaining({ type: 'error' }));
474+
});
475+
476+
it('through a real runner, 1 row: the param dialog opens and the request carries that row', async () => {
477+
const { handler, fetch } = makeHandler();
478+
const runner = new ActionRunner({ selectedRecords: [{ id: 'lead_1' }] });
479+
const dialog = vi.fn(async () => ({ campaign: 'cmp_webinar' }));
480+
runner.setToastHandler(vi.fn());
481+
runner.setParamCollectionHandler(dialog);
482+
runner.registerHandler('script', handler);
483+
484+
const result = await runner.execute(launch());
485+
486+
expect(result.success).toBe(true);
487+
expect(dialog).toHaveBeenCalledTimes(1);
488+
expect(fetch).toHaveBeenCalledTimes(1);
489+
expect(JSON.parse((fetch.mock.calls[0] as unknown as [string, { body: string }])[1].body)).toEqual({
490+
recordId: 'lead_1',
491+
params: { campaign: 'cmp_webinar' },
492+
});
493+
});
494+
});

‎packages/app-shell/src/utils/consoleServerAction.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ export function createConsoleServerActionHandler(opts: ConsoleServerActionOption
175175
const resolveRecordId = opts.resolveRecordId ?? resolveServerActionRecordId;
176176
const t = opts.t ?? defaultTranslate;
177177

178-
return async (action: ActionDef, context?: ActionContext) => {
178+
const handler: ServerActionHandler = async (action: ActionDef, context?: ActionContext) => {
179179
// ── Zero-roundtrip fast path ────────────────────────────────────────
180180
// `newTabUrl` names a GET endpoint that performs ALL auth/authz itself
181181
// (e.g. /sso-open re-runs every check the POST half would have done),
@@ -272,4 +272,11 @@ export function createConsoleServerActionHandler(opts: ConsoleServerActionOption
272272
return { success: false, error: (error as Error).message };
273273
}
274274
};
275+
// Core's early record-id refusal (objectui#13384), forwarded: the runner
276+
// asks the handler it dispatches to — this wrapper, not core's handler
277+
// inside it — before it shows a confirmation or a param dialog. Without the
278+
// forward a single-record action launched with 0 or several rows selected
279+
// ran its whole dialog and was refused only after Confirm.
280+
handler.refuseBeforeInput = dispatch.refuseBeforeInput;
281+
return handler;
275282
}

‎packages/app-shell/src/views/ObjectView.bulkWiredHeaderDuplicate-12462.test.tsx‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import * as React from 'react';
2929
import { describe, it, expect, vi, afterEach } from 'vitest';
3030
import { render, cleanup, screen, fireEvent, waitFor, act, within } from '@testing-library/react';
3131
import { MemoryRouter, Routes, Route } from 'react-router-dom';
32+
import { toast } from 'sonner';
3233
import { createI18n, I18nProvider } from '@object-ui/i18n';
3334
import { NAV_RUN_ACTION_PARAM } from '@object-ui/layout';
3435
// Module scope, per AGENTS.md's test-discipline rule: the param dialog reaches
@@ -80,6 +81,7 @@ vi.mock('./metadata-admin/useMetadata', async (importOriginal) => ({
8081

8182
import { ObjectView } from './ObjectView';
8283
import { ExpressionProvider } from '../providers/ExpressionProvider';
84+
import { ConsoleToaster } from '../chrome/ConsoleToaster';
8385

8486
/** HotCRM's `CreateCampaignAction`, the keys this chain reads: record-scoped. */
8587
const CREATE_CAMPAIGN = {
@@ -138,6 +140,7 @@ const OBJECTS = [
138140
];
139141

140142
afterEach(() => {
143+
act(() => { toast.dismiss(); });
141144
cleanup();
142145
vi.unstubAllGlobals();
143146
window.history.replaceState(null, '', '/');
@@ -157,6 +160,7 @@ function mountLeads(viewName: keyof typeof LIST_VIEWS) {
157160
} as never;
158161
return render(
159162
<I18nProvider instance={i18n}>
163+
<ConsoleToaster />
160164
<ExpressionProvider user={{ id: 'u1', name: 'Sales Manager' }}>
161165
<MemoryRouter initialEntries={[`/apps/crm/crm_lead/view/${viewName}`]}>
162166
<Routes>
@@ -252,6 +256,14 @@ describe('objectui#12462 — a bulk-wired, record-scoped list_toolbar action lea
252256
});
253257
});
254258

259+
/**
260+
* What an ARMED link shows. `create_campaign` is record-scoped and the link
261+
* runs it as the page mounts, with no row selected, so the run is refused for
262+
* its row count before its param dialog opens (objectui#13384). This toast is
263+
* the run's observable: the link armed and the action ran.
264+
*/
265+
const ZERO_ROW_REFUSAL = 'This action runs on a single record — select a row first.';
266+
255267
describe('objectui#12462 — the deep link arms only what the header draws', () => {
256268
const linkTo = (viewName: string) =>
257269
window.history.replaceState(null, '', `/apps/crm/crm_lead/view/${viewName}?${NAV_RUN_ACTION_PARAM}=create_campaign`);
@@ -268,14 +280,18 @@ describe('objectui#12462 — the deep link arms only what the header draws', ()
268280
await rowBoxes();
269281

270282
expect(screen.queryByRole('dialog')).toBeNull();
283+
expect(screen.queryByText(ZERO_ROW_REFUSAL)).toBeNull();
271284
expect(linkStillInUrl()).toBe('create_campaign');
272285
});
273286

274-
it('CONTROL — on a view that does not wire it, the same link arms: the param dialog opens and the link is consumed', async () => {
287+
it('CONTROL — on a view that does not wire it, the same link arms: the action runs and the link is consumed', async () => {
275288
linkTo('my_leads');
276289
mountLeads('my_leads');
277290

278-
expect(await screen.findByRole('dialog', undefined, { timeout: 5000 })).toBeInTheDocument();
291+
// It ran: with no row selected, the record-scoped action is refused before
292+
// its param dialog (objectui#13384), so no dialog opens.
293+
expect(await screen.findByText(ZERO_ROW_REFUSAL, undefined, { timeout: 5000 })).toBeInTheDocument();
294+
expect(screen.queryByRole('dialog')).toBeNull();
279295
await waitFor(() => expect(linkStillInUrl()).toBeNull(), { timeout: 5000 });
280296
});
281297
});

‎packages/app-shell/src/views/ObjectView.toolbarScriptSelection-12331.test.tsx‎

Lines changed: 28 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@
3434
* comes after a picker was used. It refuses and reports exactly as the plain
3535
* fixture does.
3636
*
37+
* objectui#13384 moved the refusal in front of the dialog: a launch the
38+
* dispatch would refuse for its row count is refused before the param dialog
39+
* opens (the runner asks the console handler's forwarded
40+
* `refuseBeforeInput`), so the 0- and 2-row cases below assert that no dialog
41+
* opened, beside the toast and the absent request. One row still opens it.
42+
*
3743
* "Record-scoped" is a declaration, not a guess: an action is single-record
3844
* when its `locations` include a record placement (`isRecordScopedAction`). An
3945
* action declared at `list_toolbar` alone is object-level, so zero rows
@@ -214,22 +220,31 @@ async function launchFromHeader(): Promise<void> {
214220
await act(async () => { fireEvent.click(within(dialog).getByRole('button', { name: 'Confirm' })); });
215221
}
216222

223+
/**
224+
* Click the HEADER toolbar's "Add to Campaign" for a launch that is refused for
225+
* its row count (objectui#13384): the refusal shows, and no dialog opened.
226+
*/
227+
async function launchRefusedFromHeader(refusal: string): Promise<void> {
228+
const toolbars = await screen.findAllByRole('toolbar', undefined, { timeout: 5000 });
229+
fireEvent.click(await within(toolbars[0]).findByRole('button', { name: /Add to Campaign/ }, { timeout: 5000 }));
230+
expect(await screen.findByText(refusal, undefined, { timeout: 5000 })).toBeInTheDocument();
231+
expect(screen.queryByRole('dialog')).toBeNull();
232+
}
233+
217234
describe('objectui#12331 — a record-scoped script action at list_toolbar, with a param', () => {
218-
it('0 rows: the refusal shows, and no request is sent', async () => {
235+
it('0 rows: the refusal shows before any dialog, and no request is sent', async () => {
219236
mountLeads(RECORD_SCOPED);
220237
await tickRows(0);
221-
await launchFromHeader();
238+
await launchRefusedFromHeader(ZERO_ROW_REFUSAL);
222239

223-
expect(await screen.findByText(ZERO_ROW_REFUSAL, undefined, { timeout: 5000 })).toBeInTheDocument();
224240
expect(actionCalls()).toHaveLength(0);
225241
});
226242

227-
it('2 rows: the refusal shows, and no request is sent', async () => {
243+
it('2 rows: the refusal shows before any dialog, and no request is sent', async () => {
228244
mountLeads(RECORD_SCOPED);
229245
await tickRows(2);
230-
await launchFromHeader();
246+
await launchRefusedFromHeader(MULTI_ROW_REFUSAL);
231247

232-
expect(await screen.findByText(MULTI_ROW_REFUSAL, undefined, { timeout: 5000 })).toBeInTheDocument();
233248
expect(actionCalls()).toHaveLength(0);
234249
});
235250

@@ -254,12 +269,11 @@ describe('objectui#12331 — a record-scoped script action at list_toolbar, with
254269
});
255270

256271
describe('objectui#12331 — the refusal follows the `locations` declaration', () => {
257-
it('declared at list_toolbar alone, 2 rows: one dispatch cannot name two records, so it refuses', async () => {
272+
it('declared at list_toolbar alone, 2 rows: one dispatch cannot name two records, so it refuses before any dialog', async () => {
258273
mountLeads(TOOLBAR_ONLY);
259274
await tickRows(2);
260-
await launchFromHeader();
275+
await launchRefusedFromHeader(MULTI_ROW_REFUSAL);
261276

262-
expect(await screen.findByText(MULTI_ROW_REFUSAL, undefined, { timeout: 5000 })).toBeInTheDocument();
263277
expect(actionCalls()).toHaveLength(0);
264278
});
265279

@@ -387,21 +401,20 @@ async function launchHotcrmFromHeader(): Promise<void> {
387401
}
388402

389403
describe('objectui#12331 — HotCRM\'s declaration: list_item placement, a field-backed record-picker param', () => {
390-
it('0 rows: the refusal shows, and no request is sent', async () => {
404+
it('0 rows: the refusal shows before any dialog, and no request is sent', async () => {
391405
mountHotcrmLeads();
392406
await tickRows(0);
393-
await launchHotcrmFromHeader();
407+
// `list_item` also draws the action on every row; the header's toolbar is the first.
408+
await launchRefusedFromHeader(ZERO_ROW_REFUSAL);
394409

395-
expect(await screen.findByText(ZERO_ROW_REFUSAL, undefined, { timeout: 5000 })).toBeInTheDocument();
396410
expect(actionCalls()).toHaveLength(0);
397411
});
398412

399-
it('2 rows: the refusal shows, and no request is sent', async () => {
413+
it('2 rows: the refusal shows before any dialog, and no request is sent', async () => {
400414
mountHotcrmLeads();
401415
await tickRows(2);
402-
await launchHotcrmFromHeader();
416+
await launchRefusedFromHeader(MULTI_ROW_REFUSAL);
403417

404-
expect(await screen.findByText(MULTI_ROW_REFUSAL, undefined, { timeout: 5000 })).toBeInTheDocument();
405418
expect(actionCalls()).toHaveLength(0);
406419
});
407420

‎packages/core/src/actions/ActionRunner.ts‎

Lines changed: 56 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -530,11 +530,26 @@ export interface ActionDef {
530530
* handler — a different calling convention entirely (`(ctx) => unknown`, with
531531
* validated params and a trusted engine facade on `ctx`) and a different
532532
* execution site.
533+
*
534+
* `refuseBeforeInput` is optional. When the handler the runner will dispatch
535+
* to carries it, the runner asks it BEFORE the confirmation and the param
536+
* dialog (objectui#13384), with the same context the dispatch will get. An
537+
* answer refuses the run there: its `error` is toasted, translated through
538+
* {@link ActionRunner.setTranslator}'s translator when it names an `errorKey`,
539+
* and nothing is dispatched. `undefined` lets the run go on as before. The
540+
* server-action handler uses it for its row-count refusal, so a single-record
541+
* action launched with 0 or several rows selected never opens a dialog only
542+
* to refuse after Confirm.
533543
*/
534-
export type ActionRunnerHandler = (
544+
export type ActionRunnerHandler = ((
535545
action: ActionDef,
536546
context: ActionContext
537-
) => Promise<ActionResult> | ActionResult;
547+
) => Promise<ActionResult> | ActionResult) & {
548+
refuseBeforeInput?: (
549+
action: ActionDef,
550+
context: ActionContext,
551+
) => { error: string; errorKey?: string } | undefined;
552+
};
538553

539554
/**
540555
* Confirmation handler — replaces window.confirm.
@@ -605,6 +620,10 @@ export type ToastHandler = (message: string, options?: {
605620
* - `undo` — the label the runner hands the toast handler for an undoable
606621
* success toast's Undo affordance (objectui#10969).
607622
*
623+
* The translator is also asked for one text this table does not hold: a
624+
* handler's early refusal that names an `errorKey` (`ActionRunnerHandler`'s
625+
* `refuseBeforeInput`, objectui#13384). Its `error` is the English source.
626+
*
608627
* An author's `outcomeMessages` / `successMessage` / `errorMessage` and an
609628
* action's own error are never in this table: the host localizes authored copy
610629
* before dispatch, and the runner only fills in their holes (`{{ }}` or the
@@ -629,7 +648,7 @@ const RUNNER_TEXT = {
629648
},
630649
} as const;
631650

632-
type RunnerText = (typeof RUNNER_TEXT)[keyof typeof RUNNER_TEXT];
651+
type RunnerText = { readonly key: string; readonly defaultValue: string };
633652

634653
/**
635654
* Modal handler — consumers provide to render modal dialogs.
@@ -1314,7 +1333,9 @@ export class ActionRunner {
13141333
* reached the runner, and the Undo label of an undoable success toast. An
13151334
* author's `outcomeMessages` / `successMessage` / `errorMessage` and an
13161335
* action's own error never go through this translator: the host localizes
1317-
* authored copy before dispatch. With no translator the text stays English.
1336+
* authored copy before dispatch. The one handler text it does translate is
1337+
* an early refusal that names its key (`ActionRunnerHandler`'s
1338+
* `refuseBeforeInput`). With no translator the text stays English.
13181339
*/
13191340
setTranslator(translate: (key: string, options: { defaultValue: string }) => string): void {
13201341
this.translate = translate;
@@ -1481,6 +1502,19 @@ export class ActionRunner {
14811502
}
14821503
}
14831504

1505+
// The handler's early refusal (objectui#13384), asked before the
1506+
// confirmation and the param dialog below. A run the handler would
1507+
// refuse for its context — a single-record action launched with 0 or
1508+
// several rows selected — is refused here, with the toast and the
1509+
// post-execution the dispatch-time refusal gets, and before the user
1510+
// has typed anything or anything is sent.
1511+
const refusal = this.refusalBeforeInput(action, actionType);
1512+
if (refusal !== undefined) {
1513+
const refused: ActionResult = { success: false, error: refusal };
1514+
await this.handlePostExecution(action, refused);
1515+
return refused;
1516+
}
1517+
14841518
// Confirmation. One spelling: `confirmText` — the only one the
14851519
// translation bundle can address (`…._actions.{name}.confirmText`). The
14861520
// structured `confirm.message` read that used to OUTRANK it is retired
@@ -1692,7 +1726,24 @@ export class ActionRunner {
16921726
}
16931727

16941728
/**
1695-
* One entry of `RUNNER_TEXT`, in the installed translator's language. An
1729+
* The early refusal of the handler {@link dispatchCollected} would route
1730+
* this action to, in the translator's language when it names a key —
1731+
* `undefined` when there is none. An update-operation action never reaches
1732+
* a registered handler, so it is never asked.
1733+
*/
1734+
private refusalBeforeInput(action: ActionDef, actionType: string): string | undefined {
1735+
if (isUpdateOperationAction(action)) return undefined;
1736+
const handler = actionType ? this.handlers.get(actionType) : undefined;
1737+
const refusal = handler?.refuseBeforeInput?.(action, this.context);
1738+
if (!refusal?.error) return undefined;
1739+
return refusal.errorKey
1740+
? this.runnerText({ key: refusal.errorKey, defaultValue: refusal.error })
1741+
: refusal.error;
1742+
}
1743+
1744+
/**
1745+
* One entry of `RUNNER_TEXT` (or a handler's keyed early refusal), in the
1746+
* installed translator's language. An
16961747
* empty answer from the translator falls back to the English source rather
16971748
* than raising an empty toast or an empty label.
16981749
*/

0 commit comments

Comments
 (0)