Skip to content

Commit ad50d61

Browse files
fix(record-page): Esc in the side preview ends an inline edit and keeps the preview open (#36551)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi92ncfFpPUpTD8314otX5oaG)_ Fixes #36472 Clause-②: no Metadata-protocol: none repo:objectstack#2 · os-steve · session_01ADHkmRB34k9WUWeGpRnVNm #36547 merged; main merged at 49024f4, both hunks kept ## 维护者速读 - 用户看到的变化:在列表右侧的记录预览里点进编辑后按 Esc,只退出编辑、预览留着;再按一次 Esc 才关预览。整页不变。 - 为什么做:记录页专题的子单,预览里按 Esc 会把整个预览连同编辑一起关掉,和整页不一致。 - 出错会怎样:编辑时按 Esc 的结果和整页一样,改了的内容直接放弃、不保存、不提示;不对可以直接撤回这个改动。 - 要你做什么:无。 ## What changes The card's rulings, verbatim: 「预览里处于编辑状态时,Esc 先退出编辑,预览留着;不在编辑状态时 Esc 才关闭预览。」 and 「编辑里已经改了内容时按 Esc:和整页里的做法保持一致」. **Changed content + Esc = discard directly (直接放弃), the same as the full page.** On the full page Esc runs the session's `cancel`, which is `InlineEditContext`'s `teardown`: the draft is cleared, nothing is written, no prompt. The preview now does exactly that and stays open. Mechanism, confirmed in code and by ablation (both halves of the dispatch's hypothesis hold): 1. The drawer's Radix dialog layer hears Esc on the document in the capture phase. At the stack's root it dismisses the whole preview, before the session's window listener ever runs. 2. The session would stand down anyway: its "a layer is open over me" check matched any open `role=dialog`, and the drawer is one. The fix, one half per component: - **`NavigationOverlay` (`@object-ui/components`)**: the drawer holds itself open on Esc while it draws an element marked `data-owns-pane-escape` (`escapeOwnedByPaneSession`, beside the existing `data-owns-escape` region rule). Its layer only hears the key when nothing is stacked over it, so a popover or menu over the record still closes first. - **`InlineEditSaveBar` (`@object-ui/plugin-detail`)**: the bar carries that marker while the record is being edited. A dialog that holds the session no longer counts as a layer over it (`escapeOwnedByLayerOver`). Inside a pane, `defaultPrevented` is not read as "someone else handled it", because the pane marks every key it holds itself open on. Whether a layer was over the session is also read when the key is pressed (window capture phase), so a layer that has already closed by the time the key bubbles still owns it. The full-page path is unchanged: no dialog holds the bar, so every check reads as before. **Scope after #36547 (landed).** This card keeps the whole-record edit session in the preview, whichever path enters it. With #36547 on `main`, the card's original repro path (click a value in the preview) opens that PR's per-field in-place editor, whose Esc belongs to its own Radix layer; it was re-measured in the browser on the merged head (see Verification). The whole-record session can still open in a pane (an authored page's double-click, a page with no record-context writer), and this fix covers it. The two changes do not interfere: the `field` face draws no bar, so it carries no pane marker, and its effect returns before any listener is installed. The click-to-edit gesture itself is unchanged (「不改「点一下进入编辑」本身的做法。」). ### Read first (by risk) 1. `ui/packages/plugin-detail/src/InlineEditSaveBar.tsx`: the keyboard effect (`onKeyDownCapture` / `onKeyDown`), `escapeOwnedByLayerOver`, `paneHolding`. 2. `ui/packages/components/src/custom/navigation-overlay.tsx`: `handleDrawerEscape` and `escapeOwnedByPaneSession`. ## Tests New top-level describe in the existing harness file `InlineEditSaveBar.test.tsx`: "Esc inside the record's side preview (objectstack#36472)". It drives the real `NavigationOverlay` and its Radix sheet. 8 cases: no change (first Esc ends the edit, preview open; second Esc closes it) · changed field (discard, no write, preview open) · the modal preview with no list behind it · a level below the root (Esc ends the edit, does not go back; the next Esc goes back) · a real Radix Popover over the record (Esc closes only the popover) · a layer that closes during the capture phase still owns the key · CONTROL not editing (Esc closes the preview) · full page unchanged (a field that handled the key keeps the session). No existing test was changed. ## Verification Two minutes: open the CRM example's Accounts list, hover a name and click its side-panel icon, click the Annual Revenue value, type a number, press Esc. The edit ends, the old value is shown, and the preview stays open. Press Esc again and the preview closes. **Changed content + Esc in the preview: discarded directly, no prompt (直接放弃), the same as the full page** (full page measured below: Esc with a change keeps the page open, ends the edit, opens no dialog and writes nothing). <details><summary>Browser, whole-record session in the preview (fix vs origin/main source), CRM example, 1440 wide, Chromium</summary> Driven with Playwright against this branch's Console (vite, `src`) and a `--fresh` CRM backend. The session was entered through the click-a-value path as it was before #36547. The "before" leg served the two changed files at `origin/main` f3a8a13 (working tree only, restored after, blob == HEAD). | Step | origin/main (before) | this PR (after) | |---|---|---| | Account Initech: edit, no change, Esc | preview CLOSED | edit ends, preview open | | ... Esc again | n/a | preview closes | | Edit, type 777 into Annual Revenue, Esc | preview CLOSED, input lost | edit ends, preview open, shows 2,500,000.00, stored value unchanged (2500000) | | Edit, open the Industry select, Esc | select closes, edit stays | select closes, edit and preview stay; next Esc ends the edit, preview stays | | Full page, type 888, Esc | stays on the page, edit ends, no dialog, nothing written | same (unchanged) | Lead (CRM example `crm_lead`, Marie Curie, Lead Score / Lead Source), after: Esc ends the edit and the preview stays; the next Esc closes it. With a change: discarded, stored 0, shown 0, preview open. Select open: only the select closes. Full page: same as the account. One "after" re-run in between was void: vite had not reloaded `navigation-overlay.tsx` after the before-leg restore. I restarted vite, confirmed the served source, and re-ran; the table shows the valid runs. </details> <details><summary>Browser, the card's repro on the merged head 49024f4 (#36547 on main)</summary> Click a value in the preview: #36547's per-field editor opens (one floating layer, no save bar). Account Initech / Annual Revenue and lead Marie Curie / Lead Score, each: - no change, Esc: the editor closes, the preview stays open; Esc again: the preview closes; - type 777, Esc: the editor closes, nothing written (stored 2500000 / 0 unchanged), the old value shown, the preview stays open. </details> **HotCRM 「线索」 preview: NOT MEASURED.** The HotCRM repository is not in this container. The CRM example's lead object was measured in its place, above. <details><summary>Tests and gates (head 49024f4, after merging main at 87c7bba, under the verify lock)</summary> - Dependency closures rebuilt after the merge (`packages/spec` moved): `pnpm --filter '@object-ui/plugin-detail^...' --filter '@objectstack/example-crm^...' build` exit 0. - `pnpm --dir ui exec vitest run packages/plugin-detail/src/__tests__/InlineEditSaveBar.test.tsx`: Test Files 1 passed, Tests 19 passed. - `pnpm --dir ui exec vitest run packages/plugin-detail/ packages/components/`: Test Files 918 passed, 2 skipped; Tests 8792 passed, 42 skipped. - `pnpm --filter @object-ui/plugin-detail type-check` exit 0; `pnpm --filter @object-ui/components type-check` exit 0. - `node scripts/pm/overlap-check.mjs`: VERDICT clean exit 0. - Derived gates (`dispatch-gates.mjs --commands`): 38 derived, 38 run, all exit 0; `--ran` reconciliation: 0 NOT-MEASURED, 0 UNRUN. `pnpm --dir ui exec vitest run scripts/`: Test Files 172 passed, 2 skipped. An earlier attempt at that one was killed by the OOM killer while the browser stack shared the box; it was re-run. - `pnpm --dir ui run check:new-line-citations`: 0 new citations. </details> <details><summary>Ablation (head 264d9cb, `scripts/ablation-replace.mjs`, fix committed, src is vitest-aliased)</summary> Drawer hold removed: 6 failed, 13 passed. The holding dialog counted as a layer: 5 failed. `defaultPrevented` trusted in a pane: 5 failed. No press-time read: 1 failed (the capture-phase case). Every leg restored blob == HEAD with `git diff HEAD` empty. The first try of the drawer leg was a no-op the tool refused (its replacement text was already in the file); it was redone with a distinct marker. </details> ## Acceptance notes - With no edit session at the drawer's root, Esc pressed inside a plain text field closes the preview (the drawer applies its field-owns-Esc rule only below the root). The card says Esc closes the preview when not editing; this is noted, not filed. - `ui/AGENTS.md` #2: no `content/docs/frontend/` page describes the drawer's Esc, so there is no docs page to update. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmRB34k9WUWeGpRnVNm <!-- signed: repo:objectstack#2 · os-steve · session_01ADHkmRB34k9WUWeGpRnVNm --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c5f8588 commit ad50d61

4 files changed

Lines changed: 278 additions & 18 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@object-ui/components': patch
3+
'@object-ui/plugin-detail': patch
4+
---
5+
6+
fix(record-page): Esc in the side preview ends an inline edit and keeps the preview open
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
In a record's side preview (the drawer beside a list, or a record page's drawer), a field clicked into edit no longer loses the whole preview to Esc:
12+
13+
- **While a field is being edited**, Esc ends the edit and the preview stays open. It does what Esc does on the record's full page: the typed change is discarded without a prompt and nothing is written. The next Esc closes the preview (or, a level down, goes back one level), as before.
14+
- **A popover, select or menu open over the record** still takes Esc first and closes alone; the edit and the preview stay.
15+
- **The full record page is unchanged.**
16+
17+
For hosts of `NavigationOverlay` (`@object-ui/components`): a drawer now holds itself open on Esc while it draws an element marked `data-owns-pane-escape`, which `InlineEditSaveBar` (`@object-ui/plugin-detail`) carries while the record is being edited.

‎ui/packages/components/src/custom/navigation-overlay.tsx‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,17 @@ function escapeOwnedByRegion(target: EventTarget | null, pane?: Element | null):
369369
return !!region && (!pane || pane.contains(region));
370370
}
371371

372+
/**
373+
* Whether the pane draws a part of the record that owns EVERY `Esc` the pane
374+
* hears while it is drawn, wherever the key is pressed
375+
* (`[data-owns-pane-escape]`: the record's inline edit session, whose Esc
376+
* ends the edit — objectstack#36472). The pane then holds itself open and
377+
* leaves the key to it; once the edit ends, the next `Esc` is the pane's.
378+
*/
379+
function escapeOwnedByPaneSession(pane?: Element | null): boolean {
380+
return !!pane?.querySelector('[data-owns-pane-escape]');
381+
}
382+
372383
/**
373384
* Pane resize state — drag handle on the left edge, value persisted to
374385
* localStorage so the same user gets a consistent width across sessions /
@@ -558,9 +569,15 @@ export const NavigationOverlay: React.FC<NavigationOverlayProps> = ({
558569
// A region inside the record that owns its `Esc` (`[data-owns-escape]`: the
559570
// record's comment panel, objectstack#36075) gets the key at every level,
560571
// the root too: the drawer holds itself open and leaves the region to act.
572+
//
573+
// An edit session drawn in the record (`[data-owns-pane-escape]`,
574+
// objectstack#36472) gets every key the drawer hears, the root's too: the
575+
// first `Esc` ends the edit and the drawer stays; the next one is the
576+
// drawer's again. The drawer's layer only hears the key with nothing open
577+
// over it, so a popover or menu over the record still closes first.
561578
const handleDrawerEscape = (e: KeyboardEvent) => {
562579
if (e.defaultPrevented) return;
563-
if (escapeOwnedByRegion(e.target, sheetRef.current)) {
580+
if (escapeOwnedByRegion(e.target, sheetRef.current) || escapeOwnedByPaneSession(sheetRef.current)) {
564581
e.preventDefault();
565582
return;
566583
}
@@ -678,7 +695,9 @@ export const NavigationOverlay: React.FC<NavigationOverlayProps> = ({
678695
// back one level. Only the root's `Esc` closes. objectstack#28156 — a
679696
// field's `Esc` stays the field's ({@link escapeOwnedByTarget}).
680697
// objectstack#36075 — at every level, a region's `Esc` stays the
681-
// region's ({@link escapeOwnedByRegion}).
698+
// region's ({@link escapeOwnedByRegion}). objectstack#36472 — while
699+
// the record is being edited, `Esc` ends the edit
700+
// ({@link escapeOwnedByPaneSession}).
682701
onEscapeKeyDown={handleDrawerEscape}
683702
ref={sheetRef}
684703
className={cn(

‎ui/packages/plugin-detail/src/InlineEditSaveBar.tsx‎

Lines changed: 60 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,11 @@
2323
* (objectstack#35995): see `handleSave`.
2424
*
2525
* While the session is active the bar also owns the record-level keyboard
26-
* shortcuts (objectui#2572): **Esc** cancels (when no popover/dialog is open)
27-
* and **Cmd/Ctrl+Enter** saves — both respecting `saving`/`locked`.
26+
* shortcuts (objectui#2572): **Esc** cancels (when no popover/dialog is open
27+
* over the session) and **Cmd/Ctrl+Enter** saves — both respecting
28+
* `saving`/`locked`. In a record pane (the side preview's drawer) the session
29+
* owns the pane's Esc too (objectstack#36472): the first Esc ends the edit and
30+
* the pane stays open, as the full page does.
2831
*
2932
* The bar renders nothing unless the record is actively being edited.
3033
*
@@ -335,6 +338,26 @@ export async function updateVia(
335338
}
336339
}
337340

341+
/**
342+
* Whether an `Esc` belongs to a layer over the edit session: open floating
343+
* content (a lookup or select popover, a menu, a tooltip), an alert, or an
344+
* open dialog the session is not inside (the conflict or fill-in dialog, a
345+
* confirm). The dialog that holds the session — a record pane's drawer — is
346+
* not one (objectstack#36472).
347+
*/
348+
function escapeOwnedByLayerOver(bar: Element | null): boolean {
349+
const doc = bar?.ownerDocument ?? document;
350+
if (doc.querySelector('[data-radix-popper-content-wrapper], [role="alertdialog"][data-state="open"]')) return true;
351+
return Array.from(doc.querySelectorAll('[role="dialog"][data-state="open"]')).some(
352+
(dialog) => !bar || !dialog.contains(bar),
353+
);
354+
}
355+
356+
/** Whether the session is drawn inside a pane's dialog (the side preview's drawer). */
357+
function paneHolding(bar: Element | null): boolean {
358+
return !!bar?.closest('[role="dialog"]');
359+
}
360+
338361
export const InlineEditSaveBar: React.FC<InlineEditSaveBarProps> = ({
339362
dataSource,
340363
objectName,
@@ -652,17 +675,30 @@ export const InlineEditSaveBar: React.FC<InlineEditSaveBarProps> = ({
652675

653676
// Record-level keyboard shortcuts for the shared edit session
654677
// (objectui#2572 item 5): Cmd/Ctrl+Enter commits the draft, Esc cancels.
655-
// Installed only while editing. Esc defers to any open Radix layer
656-
// (popover / select / dropdown / dialog) — those own Escape for "close the
657-
// layer", so the session only cancels when nothing is stacked on top.
658-
// Both respect the in-flight `saving` state; save also respects `locked`
659-
// and stands down while the conflict dialog drives the session.
678+
// Installed only while editing. Esc defers to any open Radix layer over the
679+
// session (popover / select / dropdown / dialog) — those own Escape for
680+
// "close the layer", so the session only cancels when nothing is stacked on
681+
// top. Both respect the in-flight `saving` state; save also respects
682+
// `locked` and stands down while the conflict dialog drives the session.
683+
//
684+
// objectstack#36472 — in a record pane (the side preview's drawer) the
685+
// dialog that HOLDS the session is not a layer over it. The drawer holds
686+
// itself open while the bar is drawn (`data-owns-pane-escape` below), and
687+
// marks the key handled to do so, so inside a pane `defaultPrevented` says
688+
// nothing; whether a layer was stacked over the session is read when the
689+
// key is pressed — on the window in the capture phase, before any layer
690+
// closes on it — instead.
660691
const saving = !!inline?.saving;
661692
const cancel = inline?.cancel;
662693
const conflictOpen = !!conflict;
694+
const barRef = React.useRef<HTMLDivElement | null>(null);
663695
React.useEffect(() => {
664696
// The `field` face's editor owns its keys (objectstack#36475).
665697
if (!editing || face === 'field') return;
698+
let layeredPress: KeyboardEvent | null = null;
699+
const onKeyDownCapture = (e: KeyboardEvent) => {
700+
layeredPress = e.key === 'Escape' && escapeOwnedByLayerOver(barRef.current) ? e : null;
701+
};
666702
const onKeyDown = (e: KeyboardEvent) => {
667703
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
668704
if (saving || locked || conflictOpen) return;
@@ -671,22 +707,25 @@ export const InlineEditSaveBar: React.FC<InlineEditSaveBarProps> = ({
671707
return;
672708
}
673709
if (e.key === 'Escape') {
674-
if (e.defaultPrevented || saving || conflictOpen) return;
710+
const layered = layeredPress === e;
711+
layeredPress = null;
712+
if (saving || conflictOpen) return;
713+
// On the full page a key already handled is not the session's; in a
714+
// pane the pane marks every key it holds itself open on.
715+
if (e.defaultPrevented && !paneHolding(barRef.current)) return;
675716
// An open floating layer (lookup/select popover, dropdown, dialog)
676717
// owns this Esc — let it close instead of tearing down the draft.
677-
if (
678-
document.querySelector(
679-
'[data-radix-popper-content-wrapper], [role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"]',
680-
)
681-
) {
682-
return;
683-
}
718+
if (layered || escapeOwnedByLayerOver(barRef.current)) return;
684719
e.preventDefault();
685720
cancel?.();
686721
}
687722
};
723+
window.addEventListener('keydown', onKeyDownCapture, true);
688724
window.addEventListener('keydown', onKeyDown);
689-
return () => window.removeEventListener('keydown', onKeyDown);
725+
return () => {
726+
window.removeEventListener('keydown', onKeyDownCapture, true);
727+
window.removeEventListener('keydown', onKeyDown);
728+
};
690729
}, [editing, saving, locked, conflictOpen, handleSave, cancel, face]);
691730

692731
React.useEffect(() => {
@@ -805,8 +844,13 @@ export const InlineEditSaveBar: React.FC<InlineEditSaveBarProps> = ({
805844
'sticky bottom-0 z-30 mt-4 flex flex-wrap items-center justify-end gap-2 rounded-md border bg-background/95 px-3 py-2 shadow-sm backdrop-blur supports-[backdrop-filter]:bg-background/80',
806845
className,
807846
)}
847+
ref={barRef}
808848
role="region"
809849
aria-label={t('detail.editFieldsInline')}
850+
// objectstack#36472: while the edit session is drawn, a record pane
851+
// round it (the side preview's drawer) leaves every Esc to it — the
852+
// first Esc ends the edit, the next one closes the pane.
853+
data-owns-pane-escape=""
810854
// objectui#12248: this bar sticks to the bottom edge with Save at its
811855
// right end, which is where a host's floating launcher sits (the
812856
// console assistant's button covered Save at 1440 wide). The marker

‎ui/packages/plugin-detail/src/__tests__/InlineEditSaveBar.test.tsx‎

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@
66
* LICENSE file in the root directory of this source tree.
77
*/
88

9+
import * as React from 'react';
910
import { describe, it, expect, vi } from 'vitest';
1011
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
1112
import { InlineEditProvider, useInlineEdit } from '@object-ui/react';
13+
import { NavigationOverlay, Popover, PopoverTrigger, PopoverContent } from '@object-ui/components';
1214
import { InlineEditSaveBar } from '../InlineEditSaveBar';
1315

1416
/**
@@ -290,3 +292,181 @@ describe('InlineEditSaveBar — the record changed elsewhere during the edit (ob
290292
expect(notice()).toBeNull();
291293
});
292294
});
295+
296+
/**
297+
* objectstack#36472 — the record's side preview (the drawer `NavigationOverlay`
298+
* draws) holds an edit session the same way the full page does: the first Esc
299+
* ends the edit and the preview stays open; the next Esc closes the preview. A
300+
* layer over the record (a lookup or select popover) still closes first. Driven
301+
* through the real drawer and its Radix sheet: what is measured is who answers
302+
* the key.
303+
*/
304+
describe('InlineEditSaveBar — Esc inside the record\'s side preview (objectstack#36472)', () => {
305+
/** The preview, opened on one record; ✕/Esc closes it for real. */
306+
function Preview({
307+
update = vi.fn(),
308+
onBack,
309+
overList = true,
310+
children,
311+
}: {
312+
update?: ReturnType<typeof vi.fn>;
313+
onBack?: () => void;
314+
overList?: boolean;
315+
children?: React.ReactNode;
316+
}) {
317+
const [open, setOpen] = React.useState(true);
318+
return (
319+
<NavigationOverlay
320+
isOpen={open}
321+
isOverlay
322+
selectedRecord={{ id: 'p1' }}
323+
mode="drawer"
324+
close={() => setOpen(false)}
325+
setIsOpen={setOpen}
326+
onBack={onBack}
327+
title="Project"
328+
width="460px"
329+
mainContent={overList ? <div>list</div> : undefined}
330+
>
331+
{() => (
332+
<InlineEditProvider canEdit>
333+
<Harness />
334+
<input aria-label="status-field" />
335+
{children}
336+
<InlineEditSaveBar dataSource={{ update }} objectName="proj" recordId="p1" data={{ updated_at: 'v1' }} refresh={vi.fn()} />
337+
</InlineEditProvider>
338+
)}
339+
</NavigationOverlay>
340+
);
341+
}
342+
343+
const pane = () => document.querySelector('[data-record-drawer-card]');
344+
const field = () => screen.getByLabelText('status-field');
345+
const editing = () => screen.queryByRole('button', { name: 'Save' }) !== null;
346+
const escape = (target: Element) => fireEvent.keyDown(target, { key: 'Escape', code: 'Escape', bubbles: true });
347+
348+
it('no change: the first Esc ends the edit and the preview stays; the next Esc closes the preview', () => {
349+
const update = vi.fn();
350+
render(<Preview update={update} />);
351+
fireEvent.click(screen.getByText('edit-enter'));
352+
expect(editing()).toBe(true);
353+
expect(pane()?.contains(screen.getByRole('button', { name: 'Save' }))).toBe(true);
354+
355+
escape(field());
356+
expect(editing()).toBe(false);
357+
expect(pane()).not.toBeNull();
358+
359+
escape(field());
360+
expect(pane()).toBeNull();
361+
expect(update).not.toHaveBeenCalled();
362+
});
363+
364+
it('a changed field: Esc discards the draft with no write, as on the full page, and the preview stays', () => {
365+
const update = vi.fn();
366+
render(<Preview update={update} />);
367+
stageTwoFields();
368+
// Pressed on the drawer itself, not in a field: the session still owns it.
369+
escape(pane()!);
370+
expect(editing()).toBe(false);
371+
expect(update).not.toHaveBeenCalled();
372+
expect(pane()).not.toBeNull();
373+
// The draft is gone: entering again starts clean, and Save writes nothing changed.
374+
fireEvent.click(screen.getByText('edit-enter'));
375+
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
376+
expect(update).not.toHaveBeenCalledWith('proj', 'p1', expect.objectContaining({ status: 'active' }), expect.anything());
377+
});
378+
379+
it('the modal preview with no list behind it behaves the same', () => {
380+
render(<Preview overList={false} />);
381+
fireEvent.click(screen.getByText('edit-enter'));
382+
escape(field());
383+
expect(editing()).toBe(false);
384+
expect(pane()).not.toBeNull();
385+
escape(field());
386+
expect(pane()).toBeNull();
387+
});
388+
389+
it('a level below the preview\'s root: Esc ends the edit and does not go back; the next Esc goes back', () => {
390+
const onBack = vi.fn();
391+
render(<Preview onBack={onBack} />);
392+
fireEvent.click(screen.getByText('edit-enter'));
393+
escape(pane()!);
394+
expect(editing()).toBe(false);
395+
expect(onBack).not.toHaveBeenCalled();
396+
escape(pane()!);
397+
expect(onBack).toHaveBeenCalledTimes(1);
398+
});
399+
400+
it('a popover open over the record closes on Esc alone: the edit and the preview stay', () => {
401+
render(
402+
<Preview>
403+
<Popover defaultOpen>
404+
<PopoverTrigger>lookup</PopoverTrigger>
405+
<PopoverContent>
406+
<input aria-label="lookup-search" />
407+
</PopoverContent>
408+
</Popover>
409+
</Preview>,
410+
);
411+
fireEvent.click(screen.getByText('edit-enter'));
412+
const search = screen.getByLabelText('lookup-search');
413+
expect(pane()?.contains(search)).toBe(false); // portaled over the preview
414+
415+
escape(search);
416+
expect(screen.queryByLabelText('lookup-search')).toBeNull();
417+
expect(editing()).toBe(true);
418+
expect(pane()).not.toBeNull();
419+
420+
escape(field());
421+
expect(editing()).toBe(false);
422+
expect(pane()).not.toBeNull();
423+
});
424+
425+
it('a layer open when Esc was pressed owns it, even when it is gone by the time the session hears the key', () => {
426+
render(<Preview />);
427+
fireEvent.click(screen.getByText('edit-enter'));
428+
// A floating layer that closes on the key before it bubbles: its node is
429+
// removed in the capture phase, as a layer whose close the browser flushes
430+
// between listeners is.
431+
const popper = document.createElement('div');
432+
popper.setAttribute('data-radix-popper-content-wrapper', '');
433+
document.body.appendChild(popper);
434+
const closeOnEsc = (e: KeyboardEvent) => {
435+
if (e.key !== 'Escape') return;
436+
e.preventDefault();
437+
popper.remove();
438+
};
439+
document.addEventListener('keydown', closeOnEsc, true);
440+
try {
441+
escape(field());
442+
expect(document.body.contains(popper)).toBe(false);
443+
expect(editing()).toBe(true);
444+
expect(pane()).not.toBeNull();
445+
} finally {
446+
document.removeEventListener('keydown', closeOnEsc, true);
447+
}
448+
escape(field());
449+
expect(editing()).toBe(false);
450+
});
451+
452+
it('CONTROL: not editing, Esc closes the preview as before', () => {
453+
render(<Preview />);
454+
escape(field());
455+
expect(pane()).toBeNull();
456+
});
457+
458+
it('the full page is unchanged: a key a field already handled is not the session\'s', () => {
459+
render(
460+
<InlineEditProvider canEdit>
461+
<Harness />
462+
<input aria-label="own-esc" onKeyDown={(e) => e.key === 'Escape' && e.preventDefault()} />
463+
<InlineEditSaveBar dataSource={{ update: vi.fn() }} objectName="proj" recordId="p1" data={{}} refresh={vi.fn()} />
464+
</InlineEditProvider>,
465+
);
466+
fireEvent.click(screen.getByText('edit-enter'));
467+
escape(screen.getByLabelText('own-esc'));
468+
expect(editing()).toBe(true);
469+
escape(document.body);
470+
expect(editing()).toBe(false);
471+
});
472+
});

0 commit comments

Comments
 (0)