An open source design system that's fully customizable and agent ready
TypeScript
fix(Layer): a layer opened by a right click stays open when that press is released (#10128)
Cindy Zhang28401fb14943
diff --git a/.changeset/layer-contextmenu-release.md b/.changeset/layer-contextmenu-release.mdnew file mode 100644index 0000000000..54d3225260--- /dev/null+++ b/.changeset/layer-contextmenu-release.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Layer: a light-dismissible layer that opens from a right click's `contextmenu` event stays open when that same press is released. Before, the release counted as a press outside, so a DropdownMenu opened through `isMenuOpen` from a right click closed at once. A later press outside still dismisses the layer.++@cixzhangdiff --git a/apps/storybook/stories/Layer.stories.tsx b/apps/storybook/stories/Layer.stories.tsxindex 0a8916d402..34da5e196c 100644--- a/apps/storybook/stories/Layer.stories.tsx+++ b/apps/storybook/stories/Layer.stories.tsx@@ -6,6 +6,7 @@ import * as stylex from '@stylexjs/stylex';import {useLayer} from '@astryxdesign/core/Layer';import {LayerProvider} from '@astryxdesign/core/Layer';import {Button} from '@astryxdesign/core/Button';+import {DropdownMenu} from '@astryxdesign/core/DropdownMenu';import {Text} from '@astryxdesign/core/Text';const styles = stylex.create({@@ -22,6 +23,22 @@ const styles = stylex.create({alignItems: 'center',minHeight: 200,},+ contextZone: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: 200,+ height: 96,+ border: '1px dashed var(--color-border-default)',+ borderRadius: 8,+ },+ contextRow: {+ display: 'flex',+ gap: 24,+ alignItems: 'center',+ minHeight: 200,+ paddingInline: 24,+ },});const meta: Meta = {@@ -1585,3 +1602,53 @@ function BrowserHideWakesAFocusLayerDemo() {export const BrowserHideWakesAFocusLayer: Story = {render: () => <BrowserHideWakesAFocusLayerDemo />,};++/**+ * A right click on a zone opens a light-dismissible layer+ * from its `contextmenu` event, and a DropdownMenu through `isMenuOpen`. The+ * release of that same press stays outside both, so the browser's light+ * dismiss reads it as a dismissal unless the layer claims the press.+ */+function ContextMenuPressOpensALayerDemo() {+ const layer = useLayer({mode: 'context', lightDismiss: true});+ const [isMenuOpen, setIsMenuOpen] = useState(false);+ return (+ <div {...stylex.props(styles.contextRow)}>+ <div+ ref={layer.ref}+ data-testid="layer-zone"+ onContextMenu={event => {+ event.preventDefault();+ layer.show();+ }}+ {...stylex.props(styles.contextZone)}>+ <Text type="body">Right-click for a layer</Text>+ </div>+ {layer.render(+ <div {...stylex.props(styles.popoverContent)} data-testid="layer">+ <Text type="body">Opened by a right click.</Text>+ </div>,+ {placement: 'below', alignment: 'center'},+ )}+ <div+ data-testid="menu-zone"+ onContextMenu={event => {+ event.preventDefault();+ setIsMenuOpen(true);+ }}+ {...stylex.props(styles.contextZone)}>+ <Text type="body">Right-click for the menu</Text>+ </div>+ <DropdownMenu+ button={{label: 'Actions'}}+ isMenuOpen={isMenuOpen}+ onOpenChange={setIsMenuOpen}+ items={[{label: 'Rename'}, {label: 'Duplicate'}]}+ />+ </div>+ );+}++export const ContextMenuPressOpensALayer: Story = {+ render: () => <ContextMenuPressOpensALayerDemo />,+};diff --git a/docs/specs/AST-003/spec.md b/docs/specs/AST-003/spec.mdindex 5e9a4d7767..5804fe1e67 100644--- a/docs/specs/AST-003/spec.md+++ b/docs/specs/AST-003/spec.md@@ -242,6 +242,7 @@ Interaction modality continues to follow `architecture:interaction-modality`.| FR1–FR6 | Pure registry/resolver tests plus family interaction tests | active, blocking, passive Tooltip, pinned Tooltip over a Dialog, visual-only, controlled owner | Passive surface wins, a pinned surface lets Escape reach the owner beneath, blocker leaks, or wrong owner closes || FR7–FR10 | Branch resolver tests and real-browser outside interaction | root menu with two submenu levels; parent + child Popover; associated trigger | Outside root leaves submenu open, or child-only outside closes parent || FR11–FR14 | Gesture-counter and browser event-order tests | native light dismiss before/after click; menu button; hover-open; touch; backdrop; swipe | Same gesture reopens any associated trigger or exposed hover reopens panel |+| FR11–FR13 | Gesture-counter tests; real-Chromium context-menu press | layer and DropdownMenu opened from `contextmenu`; release on and off the zone | The release of the press that opened the layer dismisses it, or a later press does not || FR15–FR20 | Chromium/WebKit native host tests | Toast at root; Toast through one/two modals; CommandPalette above modal; ordinary local Popover | Global surface is behind/inert, loses state, or ordinary overlay becomes global || FR21–FR23 | Supported/unsupported browser matrix and public-doc checks | anchor/fixed/custom; auto/manual; explicit controls; absent feature APIs | Docs promise equivalence or reduced fallback is unusable || IR1–IR3 | API/type tests and mutation tests for resolvers/claims | one-at-a-time channel versus branch channel | One topmost query is reused for outside branches or timestamps replace identity |diff --git a/packages/core/src/Layer/__tests__/LayerContextMenuPress.a11y.browser.spec.ts b/packages/core/src/Layer/__tests__/LayerContextMenuPress.a11y.browser.spec.tsnew file mode 100644index 0000000000..15f15febaa--- /dev/null+++ b/packages/core/src/Layer/__tests__/LayerContextMenuPress.a11y.browser.spec.ts@@ -0,0 +1,130 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope core/Layer++/**+ * @file LayerContextMenuPress.a11y.browser.spec.ts+ * @input The `Core/Layer` ContextMenuPressOpensALayer story in a built+ * Storybook, driven by real Chromium and WebKit mouse input.+ * @output Real-engine proof that a light-dismissible layer, and a+ * DropdownMenu opened through `isMenuOpen`, stay open after the release of+ * the right-button press whose `contextmenu` opened them, also when that+ * release lands away from the zone; that the held pointer still+ * highlights the menu's rows; and that a later press outside still+ * dismisses them (spec:AST-003 FR11, FR12, FR13). Only a real engine runs+ * the popover's light dismiss at that release; the unit suite+ * (useLayer.test.tsx) covers the claim on a stub.+ * @position Run with `pnpm test:a11y-contract`.+ */++import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++async function openStory(page: Page): Promise<void> {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-layer--context-menu-press-opens-a-layer&viewMode=story`,+ );+ await expect(page.getByTestId('layer-zone')).toBeVisible();+}++/** A right-button press on `testId`'s center, released at `releaseOffset`. */+async function rightPress(+ page: Page,+ testId: string,+ releaseOffset = {x: 0, y: 0},+): Promise<void> {+ const box = await page.getByTestId(testId).boundingBox();+ if (box == null) {+ throw new Error(`${testId} has no box`);+ }+ const x = box.x + box.width / 2;+ const y = box.y + box.height / 2;+ await page.mouse.move(x, y);+ await page.mouse.down({button: 'right'});+ await page.mouse.move(x + releaseOffset.x, y + releaseOffset.y, {steps: 4});+ await page.mouse.up({button: 'right'});+}++test('a layer opened by a right click stays open after that press’s release', async ({+ page,+}) => {+ await openStory(page);+ await rightPress(page, 'layer-zone');+ await expect(page.getByTestId('layer')).toBeVisible();+ // The layer stays open past the release's own task.+ await page.waitForTimeout(150);+ await expect(page.getByTestId('layer')).toBeVisible();++ // A later press outside is a gesture of its own and dismisses the layer.+ await page.mouse.click(4, 4);+ await expect(page.getByTestId('layer')).toBeHidden();+});++test('the opening press’s release keeps the layer open even away from the zone', async ({+ page,+}) => {+ await openStory(page);+ await rightPress(page, 'layer-zone', {x: 0, y: -60});+ await page.waitForTimeout(150);+ await expect(page.getByTestId('layer')).toBeVisible();+});++test('with the right button still down, moving onto the DropdownMenu highlights the row under the pointer', async ({+ page,+}) => {+ await openStory(page);+ const zone = await page.getByTestId('menu-zone').boundingBox();+ if (zone == null) {+ throw new Error('menu-zone has no box');+ }+ await page.mouse.move(zone.x + zone.width / 2, zone.y + zone.height / 2);+ await page.mouse.down({button: 'right'});+ const menu = page.getByRole('menu');+ await expect(menu).toBeVisible();+ const row = page.getByRole('menuitem', {name: 'Duplicate'});+ const rowBox = await row.boundingBox();+ if (rowBox == null) {+ throw new Error('the row has no box');+ }+ await page.mouse.move(+ rowBox.x + rowBox.width / 2,+ rowBox.y + rowBox.height / 2,+ {steps: 8},+ );+ await expect(row).toBeFocused();++ // Back outside the menu, the release still leaves it open.+ await page.mouse.move(zone.x + zone.width / 2, zone.y + zone.height / 2, {+ steps: 8,+ });+ await page.mouse.up({button: 'right'});+ await page.waitForTimeout(150);+ await expect(menu).toBeVisible();+});++test('a DropdownMenu opened through isMenuOpen from a right click stays open after that press’s release', async ({+ page,+}) => {+ await openStory(page);+ await rightPress(page, 'menu-zone');+ const menu = page.getByRole('menu');+ await expect(menu).toBeVisible();+ await page.waitForTimeout(150);+ await expect(menu).toBeVisible();++ await page.mouse.click(4, 4);+ await expect(menu).toBeHidden();+});diff --git a/packages/core/src/Layer/gestureCounter.test.ts b/packages/core/src/Layer/gestureCounter.test.tsnew file mode 100644index 0000000000..2a1617a1e8--- /dev/null+++ b/packages/core/src/Layer/gestureCounter.test.ts@@ -0,0 +1,172 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file gestureCounter.test.ts+ * @input claimContextMenuPress with a stubbed layer box, stubbed pointer+ * capture, and a layer inside an open shadow root+ * @output The claim compares the pointer with the layer's box read once (no+ * hit test or layout read per move), lets go over the layer, and ends when+ * the layer closes while the button is still down+ * @position Unit test of packages/core/src/Layer/gestureCounter.ts+ */++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {claimContextMenuPress, currentGesture} from './gestureCounter';++/** A pointer event of `type` for `pointerId`, which jsdom's events lack. */+function pointerEvent(+ type: string,+ pointerId: number,+ {button = 0, x = 0, y = 0} = {},+): Event {+ return Object.assign(+ new MouseEvent(type, {+ bubbles: true,+ composed: true,+ button,+ clientX: x,+ clientY: y,+ }),+ {pointerId},+ );+}++describe('claimContextMenuPress', () => {+ let captured: number[];+ let released: number[];+ let isCaptured: boolean;++ beforeEach(() => {+ captured = [];+ released = [];+ isCaptured = false;+ HTMLElement.prototype.setPointerCapture = (pointerId: number) => {+ captured.push(pointerId);+ isCaptured = true;+ };+ HTMLElement.prototype.hasPointerCapture = () => isCaptured;+ HTMLElement.prototype.releasePointerCapture = (pointerId: number) => {+ released.push(pointerId);+ isCaptured = false;+ };+ });++ afterEach(() => {+ document.dispatchEvent(pointerEvent('pointerup', 7));+ document.body.replaceChildren();+ vi.restoreAllMocks();+ delete (HTMLElement.prototype as Partial<HTMLElement>).setPointerCapture;+ delete (HTMLElement.prototype as Partial<HTMLElement>).hasPointerCapture;+ delete (HTMLElement.prototype as Partial<HTMLElement>)+ .releasePointerCapture;+ });++ /** Presses the right button on `zone` and claims the press for `layer`. */+ function openFromRightClick(zone: Element, layer: HTMLElement) {+ // Reading the gesture installs its listeners before the press.+ currentGesture();+ zone.dispatchEvent(pointerEvent('pointerdown', 7, {button: 2}));+ zone.dispatchEvent(+ new MouseEvent('contextmenu', {bubbles: true, composed: true}),+ );+ claimContextMenuPress(layer);+ }++ function stubLayerBox(layer: HTMLElement) {+ return vi.spyOn(layer, 'getBoundingClientRect').mockReturnValue({+ left: 100,+ right: 200,+ top: 100,+ bottom: 200,+ width: 100,+ height: 100,+ x: 100,+ y: 100,+ toJSON() {+ return this;+ },+ });+ }++ it('keeps no pointerup listener at rest, only while a press is down', () => {+ const zone = document.createElement('div');+ document.body.append(zone);+ currentGesture();+ const added = vi.spyOn(window, 'addEventListener');+ const removed = vi.spyOn(window, 'removeEventListener');+ const types = (spy: typeof added | typeof removed) =>+ spy.mock.calls.map(([type]) => type);++ zone.dispatchEvent(pointerEvent('pointerdown', 9));+ expect(types(added)).toContain('pointerup');+ zone.dispatchEvent(pointerEvent('pointerup', 9));+ expect(types(removed)).toContain('pointerup');+ });++ it('lets go over the layer and holds outside it, reading the layer box once', () => {+ const zone = document.createElement('div');+ const layer = document.createElement('div');+ document.body.append(zone, layer);+ const box = stubLayerBox(layer);++ openFromRightClick(zone, layer);+ expect(captured).toEqual([7]);++ layer.dispatchEvent(pointerEvent('pointermove', 7, {x: 150, y: 150}));+ expect(released).toEqual([7]);+ zone.dispatchEvent(pointerEvent('pointermove', 7, {x: 20, y: 20}));+ expect(captured).toEqual([7, 7]);+ layer.dispatchEvent(pointerEvent('pointermove', 7, {x: 120, y: 180}));+ expect(released).toEqual([7, 7]);+ expect(box).toHaveBeenCalledTimes(1);+ });++ it('reads the layer box again after a scroll', () => {+ const zone = document.createElement('div');+ const layer = document.createElement('div');+ document.body.append(zone, layer);+ const box = stubLayerBox(layer);++ openFromRightClick(zone, layer);+ layer.dispatchEvent(pointerEvent('pointermove', 7, {x: 150, y: 150}));+ expect(box).toHaveBeenCalledTimes(1);+ document.dispatchEvent(new Event('scroll'));+ layer.dispatchEvent(pointerEvent('pointermove', 7, {x: 150, y: 150}));+ expect(box).toHaveBeenCalledTimes(2);+ });++ it('works for a layer inside an open shadow root', () => {+ const host = document.createElement('div');+ document.body.append(host);+ const shadow = host.attachShadow({mode: 'open'});+ const zone = document.createElement('div');+ const layer = document.createElement('div');+ shadow.append(zone, layer);+ stubLayerBox(layer);++ openFromRightClick(zone, layer);+ expect(captured).toEqual([7]);+ layer.dispatchEvent(pointerEvent('pointermove', 7, {x: 150, y: 150}));+ expect(released).toEqual([7]);+ });++ it('lets the pointer go when the layer closes while the button is still down', () => {+ const zone = document.createElement('div');+ const layer = document.createElement('div');+ document.body.append(zone, layer);+ stubLayerBox(layer);++ openFromRightClick(zone, layer);+ expect(captured).toEqual([7]);++ // Escape closes the layer before the release.+ layer.dispatchEvent(+ Object.assign(new Event('toggle'), {newState: 'closed'}),+ );+ expect(released).toEqual([7]);++ // The claim has ended: a later move outside captures nothing.+ zone.dispatchEvent(pointerEvent('pointermove', 7, {x: 20, y: 20}));+ expect(captured).toEqual([7]);+ });+});diff --git a/packages/core/src/Layer/gestureCounter.ts b/packages/core/src/Layer/gestureCounter.tsindex 972d444703..5a59516038 100644--- a/packages/core/src/Layer/gestureCounter.ts+++ b/packages/core/src/Layer/gestureCounter.ts@@ -4,8 +4,10 @@/*** @file gestureCounter.ts- * @input Listens for pointerdown, keydown, and click on the document- * @output Exports the current gesture identity and whether its click has run+ * @input Pointer and context-menu events through the shared input stream;+ * keydown and click on the document+ * @output Exports the gesture identity, whether its click has run, and+ * claimContextMenuPress* @position Internal to Layer; used by useLayer to tell a click that belongs* to a dismissing press from a fresh one*@@ -17,14 +19,51 @@* the dismissal", no matter how long the main thread was blocked in between.*/+import {subscribeInput} from '../utils/inputStream';+let gesture = 0;let clickedGesture: number | null = null;+let contextMenuGesture: number | null = null;+let pressPointerId: number | null = null;let isListening = false;function advance() {gesture += 1;}+let unsubscribePress: (() => void) | null = null;++// The page listens for a press's end and its context menu only while a press+// is down, so at rest it keeps no pointerup listener of its own.+function startPress(event: PointerEvent) {+ advance();+ pressPointerId = event.pointerId;+ const view = event.view ?? document.defaultView;+ if (unsubscribePress != null || view == null) {+ return;+ }+ const unsubscribes = [+ subscribeInput(view, 'pointerup', endPress, {first: true}),+ subscribeInput(view, 'pointercancel', endPress, {first: true}),+ subscribeInput(view, 'contextmenu', markContextMenu, {first: true}),+ ];+ unsubscribePress = () => {+ for (const unsubscribe of unsubscribes) {+ unsubscribe();+ }+ };+}++function endPress() {+ pressPointerId = null;+ unsubscribePress?.();+ unsubscribePress = null;+}++function markContextMenu() {+ contextMenuGesture = gesture;+}+function markClicked() {clickedGesture = gesture;}@@ -35,7 +74,10 @@ function listen() {}isListening = true;// Capture phase: the count must advance before any handler reads it.- document.addEventListener('pointerdown', advance, true);+ const view = document.defaultView;+ if (view != null) {+ subscribeInput(view, 'pointerdown', startPress, {first: true});+ }document.addEventListener('keydown', advance, true);// Capture phase observes the click even when a consumer stops propagation.document.addEventListener('click', markClicked, true);@@ -55,3 +97,96 @@ export function currentGestureHasClicked(): boolean {listen();return clickedGesture === gesture;}++/**+ * Keeps the release of the press in flight from dismissing `layer`, when that+ * press opened a context menu (a right click). The browser's light dismiss+ * reads a release outside every open popover as a dismissal, also the release+ * of the press that opened the popover. While the pointer is outside the+ * layer, the layer captures it, so a release there lands on the layer. Over+ * the layer the capture lets go, so hover works and a release there is inside+ * anyway. The claim ends at that press's release, or when the layer closes; a+ * later press dismisses as usual.+ */+export function claimContextMenuPress(layer: HTMLElement): void {+ listen();+ const pointerId = pressPointerId;+ const view = layer.ownerDocument.defaultView;+ if (pointerId === null || contextMenuGesture !== gesture || view == null) {+ return;+ }+ const holdCapture = (isOutside: boolean) => {+ try {+ if (isOutside) {+ layer.setPointerCapture(pointerId);+ } else if (layer.hasPointerCapture(pointerId)) {+ layer.releasePointerCapture(pointerId);+ }+ } catch {+ // The pointer is no longer active (its release did not reach the+ // page), so no release can dismiss the layer.+ }+ };+ holdCapture(true);+ // A move of the pointer reads no layout. The claim reads the layer's box,+ // and the box of each popover open in it (a sub-menu), once. It reads them+ // again only after a scroll, a resize or a toggle in the layer.+ let boxes: DOMRect[] | null = null;+ const readBoxes = (): DOMRect[] => {+ let nested: HTMLElement[] = [];+ try {+ nested = [...layer.querySelectorAll<HTMLElement>(':popover-open')];+ } catch {+ // An engine without `:popover-open` has no nested popover to read.+ }+ return [layer, ...nested].map(el => el.getBoundingClientRect());+ };+ const isOverLayer = (x: number, y: number): boolean => {+ boxes ??= readBoxes();+ return boxes.some(+ box => x >= box.left && x < box.right && y >= box.top && y < box.bottom,+ );+ };+ const invalidate = () => {+ boxes = null;+ };+ const followPointer = (event: PointerEvent) => {+ if (event.pointerId === pointerId) {+ holdCapture(!isOverLayer(event.clientX, event.clientY));+ }+ };+ const unsubscribes: (() => void)[] = [];+ const stop = () => {+ for (const unsubscribe of unsubscribes) {+ unsubscribe();+ }+ unsubscribes.length = 0;+ };+ const endClaim = (event: PointerEvent) => {+ if (event.pointerId === pointerId) {+ stop();+ }+ };+ // A layer that closes while the button is still down lets the pointer go,+ // so the page under it hovers again.+ const onToggle = (event: Event) => {+ if (+ event.target === layer &&+ (event as Event & {newState?: string}).newState === 'closed'+ ) {+ holdCapture(false);+ stop();+ return;+ }+ invalidate();+ };+ layer.addEventListener('toggle', onToggle, true);+ unsubscribes.push(+ subscribeInput(view, 'pointermove', followPointer),+ subscribeInput(view, 'pointerup', endClaim),+ subscribeInput(view, 'pointercancel', endClaim),+ subscribeInput(view, 'scroll', invalidate),+ subscribeInput(view, 'resize', invalidate),+ () => layer.removeEventListener('toggle', onToggle, true),+ );+}diff --git a/packages/core/src/Layer/useLayer.test.tsx b/packages/core/src/Layer/useLayer.test.tsxindex cdb3f64f23..31e65eeced 100644--- a/packages/core/src/Layer/useLayer.test.tsx+++ b/packages/core/src/Layer/useLayer.test.tsx@@ -3048,6 +3048,136 @@ describe('wasJustDismissed (light dismiss vs. the trigger click, #5004)', () =>});});+describe('a light-dismiss layer opened by a context-menu press', () => {+ function ContextOpenedHarness({lightDismiss}: {lightDismiss: boolean}) {+ const layer = useLayerInternal({mode: 'context', lightDismiss});+ return (+ <>+ <div+ data-testid="zone"+ ref={layer.ref}+ onContextMenu={event => {+ event.preventDefault();+ layer.show();+ }}+ />+ {layer.render(<span>Menu</span>, {placement: 'below'})}+ </>+ );+ }++ /** A press of `pointerId` on `target`, which jsdom's events do not carry. */+ function pressDown(target: Element, pointerId: number) {+ fireEvent(+ target,+ Object.assign(new MouseEvent('pointerdown', {bubbles: true, button: 2}), {+ pointerId,+ }),+ );+ }++ let captured: {element: Element; pointerId: number}[] = [];+ beforeEach(() => {+ captured = [];+ HTMLElement.prototype.setPointerCapture = function (pointerId: number) {+ captured.push({element: this, pointerId});+ };+ });+ afterEach(() => {+ // The press ends, so no claim outlives its test.+ fireEvent(+ document,+ Object.assign(new MouseEvent('pointerup', {bubbles: true}), {+ pointerId: 7,+ }),+ );+ delete (HTMLElement.prototype as Partial<HTMLElement>).setPointerCapture;+ });++ it('captures the opening press, so its release lands on the layer and cannot dismiss it', () => {+ const {container, getByTestId} = render(+ <ContextOpenedHarness lightDismiss />,+ );+ const zone = getByTestId('zone');+ pressDown(zone, 7);+ fireEvent.contextMenu(zone);+ expect(captured).toEqual([+ {element: container.querySelector('[popover]'), pointerId: 7},+ ]);+ });++ it('lets the capture go while the pointer is over the layer, and takes it again outside', () => {+ const released: number[] = [];+ HTMLElement.prototype.hasPointerCapture = () => true;+ HTMLElement.prototype.releasePointerCapture = (pointerId: number) => {+ released.push(pointerId);+ };+ const {container, getByTestId} = render(+ <ContextOpenedHarness lightDismiss />,+ );+ const zone = getByTestId('zone');+ pressDown(zone, 7);+ fireEvent.contextMenu(zone);+ const layer = container.querySelector('[popover]') as HTMLElement;+ vi.spyOn(layer, 'getBoundingClientRect').mockReturnValue(+ new DOMRect(100, 100, 100, 100),+ );+ let at = {x: 150, y: 150};+ const move = (pointerId: number) =>+ fireEvent(+ layer,+ Object.assign(+ new MouseEvent('pointermove', {+ bubbles: true,+ clientX: at.x,+ clientY: at.y,+ }),+ {pointerId},+ ),+ );++ move(7);+ expect(released).toEqual([7]);+ at = {x: 20, y: 20};+ move(7);+ expect(captured).toHaveLength(2);+ // Another pointer's move leaves the claim alone.+ move(8);+ expect(captured).toHaveLength(2);++ // The release ends the claim: later moves capture nothing.+ fireEvent(+ zone,+ Object.assign(new MouseEvent('pointerup', {bubbles: true}), {+ pointerId: 7,+ }),+ );+ move(7);+ expect(captured).toHaveLength(2);+ delete (HTMLElement.prototype as Partial<HTMLElement>).hasPointerCapture;+ delete (HTMLElement.prototype as Partial<HTMLElement>)+ .releasePointerCapture;+ });++ it('captures nothing for a context menu from the keyboard, which has no press', () => {+ const {getByTestId} = render(<ContextOpenedHarness lightDismiss />);+ const zone = getByTestId('zone');+ pressDown(zone, 7);+ fireEvent.pointerUp(zone);+ fireEvent.keyDown(zone, {key: 'F10', shiftKey: true});+ fireEvent.contextMenu(zone);+ expect(captured).toEqual([]);+ });++ it('captures nothing for a layer without light dismiss', () => {+ const {getByTestId} = render(<ContextOpenedHarness lightDismiss={false} />);+ const zone = getByTestId('zone');+ pressDown(zone, 7);+ fireEvent.contextMenu(zone);+ expect(captured).toEqual([]);+ });+});+describe('a layer that keeps its anchor clear (spec:AST-059 FR4)', () => {function ClearHarness({placement}: {placement?: LayerPlacement}) {const layer = useLayerInternal({mode: 'context', keepsAnchorClear: true});diff --git a/packages/core/src/Layer/useLayer.tsx b/packages/core/src/Layer/useLayer.tsxindex 89955c554b..40e7f103bd 100644--- a/packages/core/src/Layer/useLayer.tsx+++ b/packages/core/src/Layer/useLayer.tsx@@ -31,7 +31,11 @@ import {createPortal} from 'react-dom';import {LayerContentBoundary} from './layerScopedContext';import {layerClickBoundary} from './layerClickBoundary';import {addAnchorName, readAnchorNames, removeAnchorName} from './anchorName';-import {currentGesture, currentGestureHasClicked} from './gestureCounter';+import {+ claimContextMenuPress,+ currentGesture,+ currentGestureHasClicked,+} from './gestureCounter';import {resolveLayerPortalTarget} from './layerHost';import {layerTextReset} from './layerTextReset.stylex';import {layerStructureReset} from './layerStructureReset.stylex';@@ -1539,6 +1543,9 @@ function useLayerImplementation(closedAnimations !== 'none' &&closedAnimations !== animationNames(popover);closeKeepsShownRef.current = closeTransitionHolds || closeStartsAnimation;+ if (lightDismiss) {+ claimContextMenuPress(popover);+ }if (keepsAnchorClear) {keepAnchorClear(popover, triggerRef.current);}@@ -1550,6 +1557,7 @@ function useLayerImplementation(anchorId,onShow,keepsAnchorClear,+ lightDismiss,requestContextMount,applyDeferredWritingContext,showPopoverElement,