An open source design system that's fully customizable and agent ready
TypeScript
fix(core): a swizzled copy shares the package's per-page touch state (#10599)
Cindy Zhang92784f658939
diff --git a/.changeset/core-shared-gesture-host.md b/.changeset/core-shared-gesture-host.mdnew file mode 100644index 0000000000..e3aa33f5b2--- /dev/null+++ b/.changeset/core-shared-gesture-host.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A swizzled component that carries Core's touch code, such as a swizzled `Switch` or `Slider`, now joins the package's gesture host, window input listeners, click guard, layer input holds and moving-element hit testing for the page instead of keeping a second set, so the copy and package components do not both claim the same touches. No API changes.++@cixzhangdiff --git a/packages/core/src/Layer/inputHold.ts b/packages/core/src/Layer/inputHold.tsindex acb6c25131..4b5015271d 100644--- a/packages/core/src/Layer/inputHold.ts+++ b/packages/core/src/Layer/inputHold.ts@@ -28,6 +28,7 @@ import {type MousePoint,} from '../utils/inputStream';import {isDocument, isElement, isHTMLElement, isNode} from '../utils/nodeType';+import {realmValue, sharedKey} from '../utils/sharedRealm';/*** What a hold does. `'viewport'` and `'layer'` add one shield over the whole@@ -84,10 +85,17 @@ interface PressHold {holds: (pointerId: number) => boolean;}-const held = new WeakMap<Element, HeldLayer>();-const heldDocuments = new WeakMap<Document, HeldDocument>();-const pressHolds = new WeakMap<Document, PressHold>();-const liveShields = new WeakSet<Node>();+// Registered, so the gesture host sees the layer holds of a swizzled copy as+// it does the package's.+const {held, heldDocuments, pressHolds, liveShields} = realmValue(+ sharedKey('layer/input-hold', 1),+ () => ({+ held: new WeakMap<Element, HeldLayer>(),+ heldDocuments: new WeakMap<Document, HeldDocument>(),+ pressHolds: new WeakMap<Document, PressHold>(),+ liveShields: new WeakSet<Node>(),+ }),+);/** Whether the shared input stream last delivered a mouse's pointer event. */function isMouseLast(doc: Document | null): boolean {diff --git a/packages/core/src/gestures/__tests__/sharedTouchState.test.ts b/packages/core/src/gestures/__tests__/sharedTouchState.test.tsnew file mode 100644index 0000000000..2d60691ddd--- /dev/null+++ b/packages/core/src/gestures/__tests__/sharedTouchState.test.ts@@ -0,0 +1,94 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * A swizzled copy carries its own copy of Core's touch modules. The+ * package's and the copy's code must still share one gesture host, one set of+ * window input listeners and one click guard per page, so a copied component+ * and a package component do not each claim the same touches.+ */++import {describe, expect, it, vi} from 'vitest';++describe('the gesture host a swizzled copy shares', () => {+ it('gives two copies of the gesture modules one host per document', async () => {+ const pkg = await import('../GestureHost');+ vi.resetModules();+ const copy = await import('../GestureHost');+ expect(copy).not.toBe(pkg);+ expect(copy.getGestureHost(document)).toBe(pkg.getGestureHost(document));+ });+});++describe('the window input state a swizzled copy shares', () => {+ it('gives two copies of the input stream one window listener per event type', async () => {+ const pkg = await import('../../utils/inputStream');+ vi.resetModules();+ const copy = await import('../../utils/inputStream');+ expect(copy).not.toBe(pkg);+ const added = vi.spyOn(window, 'addEventListener');+ const heard: string[] = [];+ const stopPkg = pkg.subscribeInput(+ window,+ 'keyup',+ () => void heard.push('pkg'),+ );+ const stopCopy = copy.subscribeInput(+ window,+ 'keyup',+ () => void heard.push('copy'),+ );+ window.dispatchEvent(new KeyboardEvent('keyup'));+ expect(heard).toEqual(['pkg', 'copy']);+ expect(added.mock.calls.filter(([type]) => type === 'keyup')).toHaveLength(+ 1,+ );+ stopPkg();+ stopCopy();+ added.mockRestore();+ });++ it('gives two copies of the click guard one guard per document', async () => {+ const pkg = await import('../../utils/clickGuard');+ vi.resetModules();+ const copy = await import('../../utils/clickGuard');+ expect(copy).not.toBe(pkg);+ pkg.armClickGuard(document);+ expect(copy.isClickGuardArmed(document)).toBe(true);+ copy.disarmClickGuard(document);+ expect(pkg.isClickGuardArmed(document)).toBe(false);+ });+});++describe('the state the shared gesture host reads', () => {+ it("lets a copy's layer holds reach the package's host", async () => {+ const pkg = await import('../../Layer/inputHold');+ vi.resetModules();+ const copy = await import('../../Layer/inputHold');+ expect(copy).not.toBe(pkg);+ const layer = document.createElement('div');+ const inside = document.createElement('span');+ layer.append(inside);+ document.body.append(layer);+ const release = copy.holdInput(layer, {+ until: new Promise(() => {}),+ scope: 'viewport',+ });+ expect(pkg.isInHeldLayer(inside)).toBe(true);+ release();+ layer.remove();+ });++ it("lets the package's host hit-test an element a copy moves", async () => {+ const pkg = await import('../../motion/presentation');+ vi.resetModules();+ const copy = await import('../../motion/presentation');+ expect(copy).not.toBe(pkg);+ const element = document.createElement('div');+ const stop = copy.registerPresentedOffset(element, {+ offset: () => ({x: 0, y: 0}),+ resolve: () => {},+ });+ expect(pkg.presentedElements()).toContain(element);+ stop();+ });+});diff --git a/packages/core/src/gestures/hostRegistry.ts b/packages/core/src/gestures/hostRegistry.tsindex 3c30fa9584..a14399f351 100644--- a/packages/core/src/gestures/hostRegistry.ts+++ b/packages/core/src/gestures/hostRegistry.ts@@ -4,7 +4,7 @@* @file hostRegistry.ts* @input Documents, and the gesture host created for each* @output Exports gestureHosts: each document's gesture host, once something- * has asked getGestureHost for it+ * has asked getGestureHost for it, shared by every copy of Core* @position Shared by GestureHost.ts, which creates and records the hosts, and* code that only asks a host that already exists (pageHold.ts), which then* imports nothing of the host itself.@@ -13,6 +13,14 @@*/import type {GestureHost} from './GestureHost';+import {realmValue, sharedKey} from '../utils/sharedRealm';-/** Each document's gesture host, recorded when getGestureHost creates it. */-export const gestureHosts = new WeakMap<Document, GestureHost>();+/**+ * Each document's gesture host, recorded when getGestureHost creates it. The+ * map is registered, so a swizzled copy's gesture code joins the package's+ * host instead of starting a second one.+ */+export const gestureHosts = realmValue(+ sharedKey('gestures/host', 1),+ () => new WeakMap<Document, GestureHost>(),+);diff --git a/packages/core/src/motion/presentation.ts b/packages/core/src/motion/presentation.tsindex 8edca42f5f..de40e9a446 100644--- a/packages/core/src/motion/presentation.ts+++ b/packages/core/src/motion/presentation.ts@@ -36,6 +36,7 @@import {parentAcrossShadow} from '../utils/flatTree';import {isElement} from '../utils/nodeType';+import {realmValue, sharedKey} from '../utils/sharedRealm';/** How far an element is drawn from where the engine hit-tests it, CSS px. */export interface PresentedOffset {@@ -60,16 +61,21 @@ export interface PresentedSource {const ZERO: PresentedOffset = {x: 0, y: 0};-const sources = new Map<Element, PresentedSource>();-const watchers = new Set<() => void>();-// Inside batchPresented, a change waits for the batch's end.-let batchDepth = 0;-let isChanged = false;+// Registered, so the gesture host hit-tests elements a swizzled copy moves+// as it does the package's.+const presented = realmValue(sharedKey('motion/presentation', 1), () => ({+ sources: new Map<Element, PresentedSource>(),+ watchers: new Set<() => void>(),+ // Inside batchPresented, a change waits for the batch's end.+ batchDepth: 0,+ isChanged: false,+}));+const {sources, watchers} = presented;/** Tell every watcher the reported elements changed; one's throw stops none. */function notifyWatchers(): void {- if (batchDepth > 0) {- isChanged = true;+ if (presented.batchDepth > 0) {+ presented.isChanged = true;return;}for (const watcher of [...watchers]) {@@ -89,13 +95,13 @@ function notifyWatchers(): void {* moves of one layout change cost one notice.*/export function batchPresented(apply: () => void): void {- batchDepth += 1;+ presented.batchDepth += 1;try {apply();} finally {- batchDepth -= 1;- if (batchDepth === 0 && isChanged) {- isChanged = false;+ presented.batchDepth -= 1;+ if (presented.batchDepth === 0 && presented.isChanged) {+ presented.isChanged = false;notifyWatchers();}}diff --git a/packages/core/src/utils/clickGuard.ts b/packages/core/src/utils/clickGuard.tsindex 5ba2e68db8..88f12cf7a2 100644--- a/packages/core/src/utils/clickGuard.ts+++ b/packages/core/src/utils/clickGuard.ts@@ -41,6 +41,7 @@import {isHapticSwitch} from '../privateAttributes/hapticSwitch.stylex';import {subscribeInput} from './inputStream';+import {realmValue, sharedKey} from './sharedRealm';/*** How long after a release the browser's click is still swallowed, in ms.@@ -77,10 +78,17 @@ interface Guard {timer: ReturnType<typeof setTimeout> | null;}-const guards = new Map<Document, Guard>();-/** The click listeners that stay, by window: the menu press model's. */-const stayingClickListeners = new WeakMap<Window, () => void>();-let unguardedDepth = 0;+/**+ * The click guard's state, registered, so a swizzled copy guards the same+ * clicks as the package.+ */+const guardState = realmValue(sharedKey('click-guard', 1), () => ({+ guards: new Map<Document, Guard>(),+ /** The click listeners that stay, by window: the menu press model's. */+ stayingClickListeners: new WeakMap<Window, () => void>(),+ unguardedDepth: 0,+}));+const {guards, stayingClickListeners} = guardState;/** Listen for the next click on `view`'s capture phase; returns the stop. */function listenForClicks(view: Window): () => void {@@ -183,11 +191,11 @@ export function isClickGuardArmed(doc: Document): boolean {* retargeted click).*/export function withoutClickGuard<T>(dispatch: () => T): T {- unguardedDepth++;+ guardState.unguardedDepth++;try {return dispatch();} finally {- unguardedDepth--;+ guardState.unguardedDepth--;}}@@ -215,7 +223,7 @@ function swallowLateMouse(event: MouseEvent): void {}function isExempt(event: MouseEvent): boolean {- if (event.detail === 0 || unguardedDepth > 0) {+ if (event.detail === 0 || guardState.unguardedDepth > 0) {return true;}return isHapticSwitch(event.target);diff --git a/packages/core/src/utils/inputStream.ts b/packages/core/src/utils/inputStream.tsindex e3232168f4..0d311f4a0d 100644--- a/packages/core/src/utils/inputStream.ts+++ b/packages/core/src/utils/inputStream.ts@@ -15,6 +15,8 @@* SYNC: When modified, update inputStream.test.ts.*/+import {realmValue, sharedKey} from './sharedRealm';+// The window's capture phase runs before document listeners, so an app's// `stopPropagation` there does not hide input from press feedback or the// gesture host. A claiming recognizer still needs the touch to reach its@@ -67,14 +69,20 @@ export interface InputSubscriptionOptions {/** The events a window's capture phase sees: its own, and the document's. */export type InputEventMap = WindowEventMap & DocumentEventMap;-const streams = new WeakMap<Window, Map<string, Channel>>();-/** The type of the latest pointer event each window's stream delivered. */-const lastPointerTypes = new WeakMap<Window, string>();-/** Where the latest mouse pointer event each window's stream delivered was. */-const lastMousePoints = new WeakMap<Window, MousePoint>();--/** Each window's finger and pen presses that are down, by pointer id. */-const downPresses = new WeakMap<Window, Map<number, MousePoint>>();+/**+ * Registered, so a swizzled copy's subscribers join the package's window+ * listeners.+ */+const inputState = realmValue(sharedKey('input-stream', 1), () => ({+ streams: new WeakMap<Window, Map<string, Channel>>(),+ /** The type of the latest pointer event each window's stream delivered. */+ lastPointerTypes: new WeakMap<Window, string>(),+ /** Where the latest mouse pointer event each window's stream delivered was. */+ lastMousePoints: new WeakMap<Window, MousePoint>(),+ /** Each window's finger and pen presses that are down, by pointer id. */+ downPresses: new WeakMap<Window, Map<number, MousePoint>>(),+}));+const {streams, lastPointerTypes, lastMousePoints, downPresses} = inputState;const NO_PRESSES: ReadonlyMap<number, MousePoint> = new Map();/** A point in the viewport, in CSS pixels. */