Skip to content

Commit db1a05c

Browse files
fix(components): page header actions show an in-flight state while their click runs (#34956)
🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufzgwLiKcfujYUug7sPs Fixes #34933 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:记录页头部动作按钮在点击后、结果或对话框到来前,显示「进行中」:按钮标为不可用(`aria-disabled`)但仍可获得焦点、`aria-busy`、图标换成转圈,再点无效;手机底部动作栏同样处理,`⋯` 菜单项用原生禁用。确认对话框关闭后焦点回到按钮(第 1 轮,L1 S1)。 - 为什么改:Convert Lead 这类慢动作(流程要先走网络再开向导)点击后按钮毫无反应,用户会重复点击(hotcrm 实测)。 - 风险与回滚:只改 `containers.tsx` 一个渲染器;点击返回 promise 才进入忙碌态,同步点击(如 Edit)不受影响。回滚即 revert 本 PR。 - 先看:`ui/packages/components/src/renderers/layout/containers.tsx` 的 `runHeaderAction`(忙碌态与 settle);同文件 `dispatchHeaderAction` 现在返回 `execute` 的 promise;测试 `page-header-actions.test.tsx` 末尾的新 describe。 - 两分钟验证:`pnpm --dir ui exec vitest run packages/components/src/__tests__/page-header-actions.test.tsx`,预期 50 passed,其中 in-flight 一组 7 条。 - 需要你做的:无,席位落地。 ## What changes `PageHeaderActions` (the one resolver behind `page:header`'s row, the phone bottom-bar face and the shared print-chrome row) now tracks which header actions have a click in flight. - `dispatchHeaderAction` returns the runner's `execute` promise instead of discarding it (both the record and the no-record branch). - `runHeaderAction(action, key)` calls the host `onClick` or the dispatch. When the outcome is thenable, the action is pending until that promise settles, fulfilled or rejected. A ref keyed by action is the double-click guard; state draws the face. - While pending, the inline button (row and bar face) stays focusable: it carries `aria-disabled="true"`, `aria-busy="true"` and `cursor-progress opacity-50`, and a `Loader2` spinner (the components package's existing spinner icon) replaces its icon. It is not natively `disabled`, so a dialog's return-focus call (app-shell's `useActionDialogReturnFocus`, `opener.focus()` on close) lands on it while the action is still running (round 1, L1 S1). The ref guard holds the second click. The `⋯` overflow item keeps Radix `disabled`, because its `onSelect` keeps the menu open and could be re-selected, and the menu does not take focus back. - The declared `disabled`, the inline-edit lock and the disabled-reason tooltip are unchanged: `disabledReasonFor` still reads only the declared verdict, so a pending button shows no "not available" reason. - A host `onClick` that rejects is now reported with `console.error` naming the action. It used to surface as an unhandled rejection from `void action.onClick()`. - No new UI strings. ### Premise, measured by code read on 8e49847 - Runner path: `useAction().execute` (ActionProvider) awaits `runner.execute` and catches, so it always resolves, never rejects. For `type: 'flow'` (Convert Lead in `examples/app-crm`), the host's flow handler (RecordDetailView's `flowHandler` and `useConsoleActionRuntime`'s `flowDispatch`) awaits `launchConsoleFlow`, which is the network launch, then calls `setScreenFlow` and returns. So the promise settles when the screen dialog opens, or on failure, as the card asks. - Runner-owned dialogs behave differently: the confirm dialog (`confirmText`), the param dialog and `type: 'modal'` (`useActionModal` resolves on close). Their promise spans the dialog. The button stays busy behind the modal overlay and returns to normal when the dialog closes. Nothing here never settles. - Host `onClick` actions: a sync one (Edit) returns no promise and is never busy. An async one (Delete awaits its confirm) is busy until it settles. ## Tests New top-level describe `PageHeaderRenderer — in-flight header action (objectstack#34933)` in the shared harness `page-header-actions.test.tsx`: - busy from the click until the launch resolves; extra clicks do not dispatch again; a click after settle dispatches again - normal after the launch rejects - a host `onClick` that rejects: busy, second click ignored, normal after reject, failure reported - a host `onClick` returning nothing is never busy - the phone bar face: busy, second click ignored, normal after resolve - round 1: the click guard holds a second and third click on the busy, still-focusable (`aria-disabled`) button - round 1: a `confirmText` header action confirmed from the keyboard with a real `AlertDialog` returns focus to its trigger while the run is pending, and keeps it after it settles ## Acceptance notes - Round 1: the ref guard is now the only click guard on the inline face and is pinned (a second `fireEvent.click` on the busy, `aria-disabled` button calls the flow once). Ablating it reds 4 / 50 (it was green in round 0, when native `disabled` swallowed the click). - Round 1 (L1 S1): a confirmText header action confirmed from the keyboard now returns focus to its trigger while the run is still pending, and keeps it after it settles (jsdom pin with a real `AlertDialog`; the host models app-shell's `useActionDialogReturnFocus`, since components cannot import app-shell). Restoring native `disabled` reds that pin at the `activeElement` assertion (body instead of the button). Radix's own `onCloseAutoFocus` focuses only a `Dialog.Trigger`, which the console's `ActionConfirmDialog` does not have. A live browser Convert Lead click is still not taken. - No live CRM probe was run (throttled-network Convert Lead); the evidence is code read plus the pins. - `ui/AGENTS.md` #2 (docs-driven) was not applied: no README or docs page describes header action button states today. ## Verification All on head 76c0928 unless noted (the merge of origin/main fff0ad0 touches no file in this diff; the harness was re-run on the merged head). <details><summary>Component tests</summary> - `pnpm --dir ui exec vitest run --maxWorkers=2` on 8 page-header files (actions, phone-bar, disabledReason x2, actions-shared, pressed, danger, more-actions-i18n): Test Files 8 passed, Tests 87 passed (on fe9aaee) - merged head 76c0928: page-header-actions + phone-bar: Test Files 2 passed, Tests 59 passed - `pnpm --filter @object-ui/components type-check` (`tsc --noEmit && tsc -p tsconfig.test.json`): exit 0 - eslint on the two touched files: 0 errors (pre-existing `no-explicit-any` warnings only) </details> <details><summary>Ablations (scripts/ablation-replace.mjs, restored blob == HEAD, git diff HEAD empty)</summary> - delete `pendingActionKeysRef.current.delete(key);` (settle leg): 4 failed / 44 passed, all four in-flight pins red - round 0: inline `const disabled = isActionDisabled(action) || pending;` to drop `|| pending`: 4 failed / 44 passed - round 0: guard made dead: 48 passed - round 1 (head f950825, 8 page-header files: 89 passed): guard made dead: 4 failed / 46 passed (incl. the second-click pin); native `disabled` restored (`isActionDisabled(action) || pending`): 6 failed / 44 passed (incl. the focus pin). Report 6959971728. </details> <details><summary>Derived gates (dispatch-gates --commands, 38 families)</summary> - `dispatch-gates --ran`: 38 derived, 38 run, 0 NOT-MEASURED, 0 UNRUN - 37 exit 0 on fe9aaee's tree. `check:test-source-alias` was red on the first pass: the new harness import reached the components barrel's dynamic `import()`. Fixed by importing `page-header-phone-context` directly, then re-run with exit 0. - `pnpm --dir ui exec vitest run scripts/` was OOM-killed on the first pass. Re-run with `--maxWorkers=2`: Test Files 171 passed / 2 skipped, Tests 5077 passed - `check:new-line-citations`: 0 new citations - `overlap-check`: clean exit 0, 0 PR heads </details> <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzgwLiKcfujYUug7sPs --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 421f180 commit db1a05c

3 files changed

Lines changed: 287 additions & 23 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/components': patch
3+
---
4+
5+
fix(components): a record header action shows that its click is in flight
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A click on a slow header action, such as a flow-backed Convert Lead whose screen dialog waits on a network launch, used to leave the button live and unchanged until the dialog or result arrived, so users clicked again. While the click's promise is pending, the button is now disabled and `aria-busy`, a spinner replaces its icon, and further clicks do nothing. It returns to normal when the promise settles, on success or failure. The same applies to the phone bottom-bar face and to `⋯` overflow items, which share the renderer. A click that returns no promise is never busy. A host `onClick` that rejects is now reported with `console.error` naming the action, where it used to surface as an unhandled rejection.

‎ui/packages/components/src/__tests__/page-header-actions.test.tsx‎

Lines changed: 228 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
*/
88

99
import { describe, it, expect, vi } from 'vitest';
10-
import { useEffect } from 'react';
11-
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
10+
import { useEffect, useMemo, useState } from 'react';
11+
import { render, screen, fireEvent, waitFor, act, within } from '@testing-library/react';
1212
import { ComponentRegistry } from '@object-ui/core';
1313
import type {
1414
ActionContext,
@@ -23,6 +23,15 @@ import {
2323
useInlineEdit,
2424
PredicateScopeProvider,
2525
} from '@object-ui/react';
26+
import { PageHeaderPhoneContext, type PageHeaderPhoneFace } from '../renderers/layout/page-header-phone-context';
27+
import {
28+
AlertDialog,
29+
AlertDialogAction,
30+
AlertDialogCancel,
31+
AlertDialogContent,
32+
AlertDialogDescription,
33+
AlertDialogTitle,
34+
} from '../ui/alert-dialog';
2635

2736
function PageHeader({ schema }: { schema: any }) {
2837
const Component = ComponentRegistry.get('page:header');
@@ -883,3 +892,220 @@ describe('PageHeaderRenderer — #2358 action visibility traps', () => {
883892
});
884893
});
885894
});
895+
896+
describe('PageHeaderRenderer — in-flight header action (objectstack#34933)', () => {
897+
function deferred<T>() {
898+
let resolve!: (v: T) => void;
899+
let reject!: (e: unknown) => void;
900+
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
901+
return { promise, resolve, reject };
902+
}
903+
const convert = { name: 'convert', locations: ['record_header'], label: 'Convert Lead', type: 'flow', icon: 'ArrowRightCircle' };
904+
const record = { id: 'lead-1', name: 'Mira Costa' };
905+
906+
function renderWithFlow(flow: (action: ActionDef, ctx: ActionContext) => Promise<ActionResult>) {
907+
render(
908+
<ActionProvider handlers={{ flow }}>
909+
<RecordContextProvider objectName="lead" recordId="lead-1" data={record} objectSchema={{ name: 'lead', label: 'Lead' }}>
910+
<PageHeader schema={{ type: 'page:header', title: 'Lead', actions: [convert] }} />
911+
</RecordContextProvider>
912+
</ActionProvider>,
913+
);
914+
}
915+
916+
// A busy inline button stays focusable: `aria-disabled`, never native
917+
// `disabled`, so a dialog its click opened can return focus to it.
918+
const expectBusy = (button: HTMLElement) => {
919+
expect((button as HTMLButtonElement).disabled).toBe(false);
920+
expect(button.getAttribute('aria-disabled')).toBe('true');
921+
expect(button.getAttribute('aria-busy')).toBe('true');
922+
expect(button.querySelector('[data-header-action-pending]')).not.toBeNull();
923+
};
924+
const expectIdle = (button: HTMLElement) => {
925+
expect((button as HTMLButtonElement).disabled).toBe(false);
926+
expect(button.hasAttribute('aria-disabled')).toBe(false);
927+
expect(button.hasAttribute('aria-busy')).toBe(false);
928+
expect(button.querySelector('[data-header-action-pending]')).toBeNull();
929+
};
930+
931+
it('is busy from the click until the launch resolves, and a second click does not dispatch again', async () => {
932+
const launch = deferred<ActionResult>();
933+
const flow = vi.fn<(action: ActionDef, ctx: ActionContext) => Promise<ActionResult>>(() => launch.promise);
934+
renderWithFlow(flow);
935+
const button = screen.getByRole('button', { name: /Convert Lead/i });
936+
expectIdle(button);
937+
938+
fireEvent.click(button);
939+
await waitFor(() => expect(flow).toHaveBeenCalledTimes(1));
940+
expectBusy(button);
941+
942+
fireEvent.click(button);
943+
fireEvent.click(button);
944+
await act(async () => { await Promise.resolve(); });
945+
expect(flow).toHaveBeenCalledTimes(1);
946+
947+
await act(async () => { launch.resolve({ success: true }); await launch.promise; });
948+
await waitFor(() => expectIdle(button));
949+
950+
fireEvent.click(button);
951+
await waitFor(() => expect(flow).toHaveBeenCalledTimes(2));
952+
});
953+
954+
it('returns to normal when the launch fails', async () => {
955+
const launch = deferred<ActionResult>();
956+
const flow = vi.fn<(action: ActionDef, ctx: ActionContext) => Promise<ActionResult>>(() => launch.promise);
957+
renderWithFlow(flow);
958+
const button = screen.getByRole('button', { name: /Convert Lead/i });
959+
fireEvent.click(button);
960+
await waitFor(() => expectBusy(button));
961+
await act(async () => { launch.reject(new Error('flow launch failed')); await launch.promise.catch(() => undefined); });
962+
await waitFor(() => expectIdle(button));
963+
});
964+
965+
it('a host action whose click rejects returns to normal and the failure is reported', async () => {
966+
const run = deferred<void>();
967+
const onClick = vi.fn(() => run.promise);
968+
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
969+
try {
970+
renderHeader(
971+
{ type: 'page:header', title: 'Lead' },
972+
{ record, headerSystemActions: [{ name: 'sys_delete_34933', label: 'Remove', onClick }] },
973+
);
974+
const button = await screen.findByRole('button', { name: /Remove/i });
975+
fireEvent.click(button);
976+
expectBusy(button);
977+
fireEvent.click(button);
978+
expect(onClick).toHaveBeenCalledTimes(1);
979+
const failure = new Error('delete refused');
980+
await act(async () => { run.reject(failure); await run.promise.catch(() => undefined); });
981+
await waitFor(() => expectIdle(button));
982+
expect(error).toHaveBeenCalledWith(expect.stringContaining('sys_delete_34933'), failure);
983+
} finally {
984+
error.mockRestore();
985+
}
986+
});
987+
988+
it('a host action whose click returns nothing is never busy', async () => {
989+
const onClick = vi.fn(() => undefined);
990+
renderHeader(
991+
{ type: 'page:header', title: 'Lead' },
992+
{ record, headerSystemActions: [{ name: 'sys_edit_34933', label: 'Edit', onClick }] },
993+
);
994+
const button = await screen.findByRole('button', { name: /^Edit$/i });
995+
fireEvent.click(button);
996+
expectIdle(button);
997+
fireEvent.click(button);
998+
expect(onClick).toHaveBeenCalledTimes(2);
999+
});
1000+
1001+
it('the phone bar face is busy the same way and returns to normal on settle', async () => {
1002+
const launch = deferred<ActionResult>();
1003+
const flow = vi.fn<(action: ActionDef, ctx: ActionContext) => Promise<ActionResult>>(() => launch.promise);
1004+
function PhoneHost() {
1005+
const [bar, setBar] = useState<HTMLDivElement | null>(null);
1006+
const face = useMemo<PageHeaderPhoneFace>(() => ({ actionBar: bar }), [bar]);
1007+
return (
1008+
<ActionProvider handlers={{ flow }}>
1009+
<RecordContextProvider objectName="lead" recordId="lead-1" data={record} objectSchema={{ name: 'lead', label: 'Lead' }}>
1010+
<PageHeaderPhoneContext.Provider value={face}>
1011+
<PageHeader schema={{ type: 'page:header', title: 'Lead', actions: [convert] }} />
1012+
</PageHeaderPhoneContext.Provider>
1013+
</RecordContextProvider>
1014+
<div ref={setBar} data-testid="bar" />
1015+
</ActionProvider>
1016+
);
1017+
}
1018+
render(<PhoneHost />);
1019+
await waitFor(() => expect(screen.getByTestId('bar').querySelector('[data-page-header-actions-face="bar"]')).not.toBeNull());
1020+
const button = within(screen.getByTestId('bar')).getByRole('button', { name: /Convert Lead/i });
1021+
fireEvent.click(button);
1022+
await waitFor(() => expectBusy(button));
1023+
fireEvent.click(button);
1024+
await act(async () => { await Promise.resolve(); });
1025+
expect(flow).toHaveBeenCalledTimes(1);
1026+
await act(async () => { launch.resolve({ success: true }); await launch.promise; });
1027+
await waitFor(() => expectIdle(button));
1028+
});
1029+
it('the click guard holds a second click on the busy, still-focusable button', async () => {
1030+
const launch = deferred<ActionResult>();
1031+
const flow = vi.fn<(action: ActionDef, ctx: ActionContext) => Promise<ActionResult>>(() => launch.promise);
1032+
renderWithFlow(flow);
1033+
const button = screen.getByRole('button', { name: /Convert Lead/i });
1034+
fireEvent.click(button);
1035+
await waitFor(() => expectBusy(button));
1036+
// Not natively disabled, so the click is dispatched: only the guard stops it.
1037+
fireEvent.click(button);
1038+
fireEvent.click(button);
1039+
await act(async () => { await Promise.resolve(); });
1040+
expect(flow).toHaveBeenCalledTimes(1);
1041+
await act(async () => { launch.resolve({ success: true }); await launch.promise; });
1042+
await waitFor(() => expectIdle(button));
1043+
});
1044+
1045+
it('a confirmText action confirmed from the keyboard hands focus back to its trigger, busy until the run settles', async () => {
1046+
const run = deferred<ActionResult>();
1047+
const api = vi.fn<(action: ActionDef, ctx: ActionContext) => Promise<ActionResult>>(() => run.promise);
1048+
// The console's confirm dialog opens with no Radix Trigger, so Radix's own
1049+
// return-to-trigger does nothing; it returns focus to the control focused
1050+
// at open, as app-shell's `useActionDialogReturnFocus` does. This host
1051+
// does the same: focus() on a natively disabled opener is a no-op.
1052+
function ConfirmHost() {
1053+
const [ask, setAsk] = useState<{ message: string; answer: (ok: boolean) => void } | null>(null);
1054+
const [opener, setOpener] = useState<HTMLElement | null>(null);
1055+
const onConfirm = (message: string) => new Promise<boolean>((resolve) => {
1056+
setOpener(document.activeElement as HTMLElement | null);
1057+
setAsk({ message, answer: resolve });
1058+
});
1059+
const answer = (ok: boolean) => { ask?.answer(ok); setAsk(null); };
1060+
return (
1061+
<ActionProvider handlers={{ api }} onConfirm={onConfirm}>
1062+
<RecordContextProvider objectName="lead" recordId="lead-1" data={record} objectSchema={{ name: 'lead', label: 'Lead' }}>
1063+
<PageHeader
1064+
schema={{
1065+
type: 'page:header',
1066+
title: 'Lead',
1067+
actions: [{ name: 'qualify', type: 'api', target: '/api/v1/qualify', confirmText: 'Qualify this lead?', locations: ['record_header'], label: 'Qualify' }],
1068+
}}
1069+
/>
1070+
</RecordContextProvider>
1071+
<AlertDialog open={ask !== null} onOpenChange={(open) => { if (!open) answer(false); }}>
1072+
<AlertDialogContent
1073+
onCloseAutoFocus={(event) => {
1074+
if (!opener) return;
1075+
event.preventDefault();
1076+
opener.focus();
1077+
}}
1078+
>
1079+
<AlertDialogTitle>Confirm</AlertDialogTitle>
1080+
<AlertDialogDescription>{ask?.message}</AlertDialogDescription>
1081+
<AlertDialogCancel>Cancel</AlertDialogCancel>
1082+
<AlertDialogAction onClick={() => answer(true)}>Confirm</AlertDialogAction>
1083+
</AlertDialogContent>
1084+
</AlertDialog>
1085+
</ActionProvider>
1086+
);
1087+
}
1088+
render(<ConfirmHost />);
1089+
const trigger = screen.getByRole('button', { name: /Qualify/i });
1090+
// Keyboard activation: the trigger holds focus and Enter clicks it.
1091+
trigger.focus();
1092+
expect(document.activeElement).toBe(trigger);
1093+
fireEvent.click(trigger);
1094+
const dialog = await screen.findByRole('alertdialog');
1095+
// Busy is read off `aria-busy` alone here, so this case judges focus only.
1096+
expect(trigger.getAttribute('aria-busy')).toBe('true');
1097+
const confirm = within(dialog).getByRole('button', { name: 'Confirm' });
1098+
await waitFor(() => expect(dialog.contains(document.activeElement)).toBe(true));
1099+
confirm.focus();
1100+
fireEvent.click(confirm);
1101+
await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull());
1102+
await waitFor(() => expect(api).toHaveBeenCalledTimes(1));
1103+
// The run is still in flight: busy, and focus is back on the trigger.
1104+
expect(trigger.getAttribute('aria-busy')).toBe('true');
1105+
await waitFor(() => expect(document.activeElement).toBe(trigger));
1106+
await act(async () => { run.resolve({ success: true }); await run.promise; });
1107+
await waitFor(() => expect(trigger.hasAttribute('aria-busy')).toBe(false));
1108+
expect(document.activeElement).toBe(trigger);
1109+
});
1110+
1111+
});

0 commit comments

Comments
 (0)