Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(gestures): a mouse or pen drag a gesture claims keeps the page's text selection (spec:AST-094 FR41) (#8665)

Christopher Chedeau5f3198edf50b
diff --git a/.changeset/drag-selection.md b/.changeset/drag-selection.md
new file mode 100644
index 0000000000..ab0a8d0729
--- /dev/null
+++ b/.changeset/drag-selection.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: a mouse or pen drag that a gesture claims takes no new text selection and keeps the page's existing one, from the claim of whichever recognizer makes it (a swipe or a recognizer waiting on another's failure included), and a drag that starts on selectable text is left to the browser, which selects that text. Not exported from the package entry point.
+
+@vjeux
diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md
index 87194f4b4b..5684069e40 100644
--- a/docs/specs/AST-094-touch-presentations/spec.md
+++ b/docs/specs/AST-094-touch-presentations/spec.md
@@ -520,7 +520,10 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and
own record. Keyboard and assistive-technology selection are unchanged. A pen's hold
acts as a finger's; a mouse makes the context request by a right click, not
a long press (FR43), and otherwise keeps its released behavior
- (`spec:AST-017` FR59; DEC-9).
+ (`spec:AST-017` FR59; DEC-9). A mouse or pen drag that a recognizer claims
+ takes no new text selection for that drag and never clears an existing
+ selection; a drag that starts on selectable text is not claimed. An
+ unclaimed mouse drag keeps its released behavior.
Guidance: a caller whose menu element carries text a person may want offers
a Copy action in its menu.
@@ -767,7 +770,7 @@ under a finger, and a mouse follows `module:DropdownMenu/useMenuPress` FR3 and
| FR31–FR33 | Browser tests and storyboards under a finger | a menu, a Popover and a ContextMenu lift: open, close, a pan outside, a tap outside, a pinch over the surface; a mouse | a surface that does not grow from and shrink into its trigger, a pan outside that leaves a menu open, a Popover whose dismissal changed, a pinch blocked other than by the author's `touch-action`, a tap outside that reaches the page, or a changed mouse path fails |
| FR34, FR35 | Browser tests and storyboards under a finger | a sub-menu drilling in and its Back row returning; a tap and a drag during a popover's and a menu's growth; a pinch during growth; a mouse; a tap and a drag during an alert's, a sheet's, and a dialog's entrance; a key and a screen reader during an entrance; a pinch during an alert's and a sheet's entrance; a tap and a scroll on the page beside an entering non-modal sheet, which pass | a drill-in that leaves the parent's rows in place, a change between levels that does not play on its roles, a tap during growth that closes, scrolls or moves focus, a pinch blocked other than by the author's `touch-action`, or a changed mouse path, a held key or assistive-technology activation, a hidden content tree, or a tap or drag during an entrance that closes the presentation, scrolls a held page, moves focus or reaches anything beneath, fails |
| FR36–FR40 | Release tests on synthetic touch streams with explicit timestamps, per use | below and past each commit point; a flick that projects past it; a slow drag past it; a release moving back; Reduce Motion; keyboard and mouse paths | a decision that changes mid-settle, a release moving back that commits, a settle that does not start at the release velocity (a paging release starts its settle per FR6's paging paragraph, DEC-25), or an action with no keyboard or mouse path fails |
-| FR41 | Browser tests with real touch input (`spec:AST-013` FR10) | a tap; a long press on a ContextMenu trigger, a DropdownMenu trigger the caller renders, a row with a context menu, and a slider thumb; a long press on a checkbox row's label and on plain text; a cancelled press; mouse and keyboard selection; a pen long press; a mouse long press, which makes no context request | a tap that selects, a hold with an action that starts a selection or callout, a label or plain text whose long press does not select natively, a suppression that outlives the press, or a change to native selection elsewhere or to mouse, keyboard, or assistive-technology selection fails |
+| FR41 | Browser tests with real touch input (`spec:AST-013` FR10) | a tap; a long press on a ContextMenu trigger, a DropdownMenu trigger the caller renders, a row with a context menu, and a slider thumb; a long press on a checkbox row's label and on plain text; a cancelled press; mouse and keyboard selection; a pen long press; a mouse long press, which makes no context request; a mouse drag a recognizer claims, with and without a page selection; a mouse drag that starts on selectable text | a tap that selects, a hold with an action that starts a selection or callout, a label or plain text whose long press does not select natively, a suppression that outlives the press, a change to native selection elsewhere, to keyboard or assistive-technology selection, or to mouse selection outside a drag a recognizer claims, a claimed drag that takes a new selection or after which an existing one does not survive, or a drag starting on text that does not select text fails |
| FR42 | Default-theme geometry tests under a coarse and a fine pointer, and hit-testing between adjacent targets | every component at phone width with a finger and with a mouse; a dense toolbar; a chip and its remove button; a Switch beside a label link | a default-theme box that grows under touch or at phone width other than with its text, or, where no component or module record sets the hit area, a touch target under 44 px where neighbors allow it or a hit area that overlaps a neighbor's target, fails |
| FR43 | Browser tests with a mouse, a trackpad, a pen, a finger, and the keyboard, and resource counts | a pan by drag and by wheel; a slider's thumb under a wheel and a trackpad scroll; a ctrl-wheel pinch; a long press, a right click, and Shift+F10; a mouse press; a handle drag; a row swipe with a mouse and a trackpad; a component with no gesture | a gesture missing under a mouse or pen, a mouse-drag swipe action, a pen pinch, an edge pan under a mouse, a trackpad, or a pen, a press delay under a fine pointer, a wheel or trackpad scroll that changes a thumb's value or does not reach the scroll under it, an idle listener in a component with no gesture, or added stylesheet bytes, fails |
| FR43 trackpad | Unit tests on timed wheel streams; WebKit browser tests with trackpad streams (Chromium's driver wheels read as a mouse wheel) | a form and a required sheet pulled 30 to 240 px by a finger and by a trackpad; mouse lines, notches, ticks and accelerated deltas over a sheet, a pager and a row; ten swipes each starting mid-momentum, ten whose momentum ends, and a slow drag with 150 ms pauses; a trackpad flick and a slow stopped drag on an info sheet; a fling, a slow 60 px swipe, a 42 px spike and back-to-back swipes on a pager; a row opened and swiped back within one gesture, and a long fast swipe; a pinch ending; a trackpad pan through a window blur and through a hidden page | a trackpad stretch that differs from a finger's for the same travel (120 px gives 54 px on the reference sheet), a mouse wheel that moves a sheet, a pager or a row, splitter counts other than ten, ten and one, momentum that moves a surface, a flick released with no velocity, a pager that travels past one page or pages on a spike, an info sheet a flick leaves open or a slow stopped drag closes, an open row that reveals its other side within one gesture, a trackpad pan a window blur or a hidden page leaves mid-gesture, or a pinch that ends after 100 ms fails |
diff --git a/packages/core/src/gestures/GestureArena.ts b/packages/core/src/gestures/GestureArena.ts
index a3731a5d1b..46d8084fdd 100644
--- a/packages/core/src/gestures/GestureArena.ts
+++ b/packages/core/src/gestures/GestureArena.ts
@@ -90,8 +90,18 @@ export interface ArenaBeganInput extends TouchBeganInput {
export interface GestureArenaOptions {
clock?: GestureClock;
environment?: GestureEnvironment;
- /** Touches a recognizer now owns: cancel the browser's default for them. */
- onClaim?: (touchIds: ReadonlyArray<number>) => void;
+ /**
+ * Touches a recognizer now owns, and the recognizer that claimed them. A
+ * claim comes in any state: a recognizer that waits on another's failure
+ * claims while `possible`, and a swipe claims as `ended`. Each claim is
+ * reported once.
+ */
+ onClaim?: (
+ touchIds: ReadonlyArray<number>,
+ claimer: GestureRecognizer,
+ ) => void;
+ /** Claimed touches given back to the browser (releaseClaim). */
+ onRelease?: (touchIds: ReadonlyArray<number>) => void;
/** A click deferred at touch end resolved: replay it, or drop it. */
onDeferredClick?: (touch: GestureTouch, allowed: boolean) => void;
/**
@@ -100,6 +110,13 @@ export interface GestureArenaOptions {
* listening now (`spec:AST-094` FR24).
*/
onIdle?: () => void;
+ /**
+ * Whether the browser keeps a contact for itself while it is down. Then no
+ * claiming recognizer recognizes with it before its lift. So a mouse or pen
+ * drag that starts on selectable text selects that text. A recognition at
+ * the lift, such as a tap's, is unaffected.
+ */
+ refusesClaim?: (touch: GestureTouch) => boolean;
/** Every recognizer transition, for debugging and tests. */
onTransition?: (
recognizer: GestureRecognizer,
@@ -553,7 +570,8 @@ export class GestureArena {
): void {
if (
!internals(recognizer).shouldBegin() ||
- this.isVetoedByConsumer(recognizer)
+ this.isVetoedByConsumer(recognizer) ||
+ this.isRefusedByBrowser(recognizer)
) {
this.fail(recognizer);
return;
@@ -635,6 +653,23 @@ export class GestureArena {
return winner.canPrevent(other) && other.canBePrevented(winner);
}
+ /**
+ * Whether a recognizer that claims touches would take a contact the
+ * browser keeps while it is down (`refusesClaim`).
+ */
+ private isRefusedByBrowser(recognizer: GestureRecognizer): boolean {
+ const refuses = this.options.refusesClaim;
+ if (refuses == null || !recognizer.claimsTouches) {
+ return false;
+ }
+ return recognizer.trackedTouches.some(
+ touch =>
+ touch.phase !== 'ended' &&
+ touch.phase !== 'cancelled' &&
+ refuses(touch),
+ );
+ }
+
/** UIControl's rule: a control may veto an overlapping ancestor recognizer. */
private isVetoedByConsumer(recognizer: GestureRecognizer): boolean {
for (const id of internals(recognizer).seenTouchIds) {
@@ -674,6 +709,7 @@ export class GestureArena {
recognizer: GestureRecognizer,
keep: ReadonlySet<number> = new Set(),
): void {
+ const released: number[] = [];
for (const touch of recognizer.trackedTouches) {
const record = this.records.get(touch.id);
if (record == null || !record.isClaimed || keep.has(touch.id)) {
@@ -692,8 +728,12 @@ export class GestureArena {
);
if (!isOwned) {
record.isClaimed = false;
+ released.push(touch.id);
}
}
+ if (released.length > 0) {
+ this.options.onRelease?.(released);
+ }
}
private apply(recognizer: GestureRecognizer, next: GestureState): void {
@@ -768,7 +808,7 @@ export class GestureArena {
}
}
if (claimed.length > 0) {
- this.options.onClaim?.(claimed);
+ this.options.onClaim?.(claimed, recognizer);
}
}
diff --git a/packages/core/src/gestures/GestureHost.ts b/packages/core/src/gestures/GestureHost.ts
index 0b7f937278..ec80183bc1 100644
--- a/packages/core/src/gestures/GestureHost.ts
+++ b/packages/core/src/gestures/GestureHost.ts
@@ -177,7 +177,13 @@ import {
} from '../utils/clickGuard';
import {subscribeInput} from '../utils/inputStream';
import {isPrimaryClick} from '../utils/primaryClick';
-import {locksSelectionFor} from '../utils/selectionLock';
+import {
+ type DragSelectionReleaseOptions,
+ lockDragSelection,
+ locksSelectionFor,
+ selectionRangesOf,
+ startsOnSelectableText,
+} from '../utils/selectionLock';
import {isCoarsePointer, watchCoarsePointer} from '../utils/coarsePointer';
import {gestureHosts} from './hostRegistry';
@@ -635,7 +641,35 @@ export class GestureHost {
/** Cancels the scheduled next-frame read (readCallerTouchActionInNextFrame). */
private cancelCallerRead: (() => void) | null = null;
/** The selection lock each contact holds, by host contact id. */
- private readonly lockedBy = new Map<number, () => void>();
+ private readonly lockedBy = new Map<
+ number,
+ (options?: DragSelectionReleaseOptions) => void
+ >();
+ /**
+ * The page's selection when each mouse or pen press began: a drag a
+ * recognizer claims keeps it.
+ */
+ private readonly pressSelections = new Map<
+ number,
+ ReadonlyArray<AbstractRange>
+ >();
+ /**
+ * Mouse and pen contacts that began on selectable text. Once one moves, the
+ * browser keeps the drag for a selection, and no recognizer claims it.
+ */
+ private readonly selectingContacts = new Set<number>();
+ /**
+ * Drag selection holds until their last task ends, a task after their lift
+ * (lockDragSelection); the last detach ends them at once.
+ */
+ private readonly dragHolds = new Set<
+ (options?: DragSelectionReleaseOptions) => void
+ >();
+ /** Each claimed contact's drag hold, until its lift or a give-back. */
+ private readonly claimHolds = new Map<
+ number,
+ (options?: DragSelectionReleaseOptions) => void
+ >();
private readonly presentedHitTesting: 'auto' | 'always' | 'never';
/**
* Contacts sent to what is drawn instead of what the engine hit, by host
@@ -816,6 +850,11 @@ export class GestureHost {
// tap) ends here: an armed press stops listening (FR24).
onIdle: () => this.releaseArmedPress(),
onTransition: options.onTransition,
+ onClaim: (ids, claimer) => this.lockClaimedDrags(ids, claimer),
+ onRelease: ids => this.releaseClaimedDrags(ids),
+ refusesClaim: touch =>
+ this.selectingContacts.has(touch.id) &&
+ (touch.x !== touch.startX || touch.y !== touch.startY),
});
const view = doc.defaultView;
// A test may pass its own read; otherwise the one coarse-pointer gate,
@@ -1779,6 +1818,13 @@ export class GestureHost {
}
this.ownScrollFrames.clear();
this.ownedScrolls.clear();
+ // A drag's hold whose press lifted in this task ends now, not a task
+ // later: nothing is attached to meet its mouseup or click.
+ for (const release of [...this.dragHolds]) {
+ release({isCancel: true});
+ }
+ this.pressSelections.clear();
+ this.selectingContacts.clear();
});
}
@@ -2506,6 +2552,94 @@ export class GestureHost {
}
}
+ /**
+ * Hold the page's selection for a mouse or pen contact that a recognizer
+ * claims. Examples are a pan's drag and a press a group claims at its own
+ * pointerdown. While the contact is down, the claiming recognizers'
+ * elements refuse a new selection. The selection the page had at the press
+ * is put back over anything that replaced it. That includes the press's own
+ * collapse and a selection the drag made before its claim. The claiming
+ * recognizer's element holds from its claim, in any state: a waiting
+ * recognizer claims while possible, and a swipe claims as ended. The
+ * participants that already recognize hold too. A claim given back to the
+ * browser lets its hold go (releaseClaimedDrags). A drag that starts on
+ * selectable text never gets here, because no recognizer claims it
+ * (`selectingContacts`). A tap claims only at its lift, so a click keeps
+ * the selection it made. A finger keeps the touch-down lock alone.
+ */
+ private lockClaimedDrags(
+ ids: ReadonlyArray<number>,
+ claimer: GestureRecognizer,
+ ): void {
+ for (const id of ids) {
+ if (this.claimHolds.has(id)) {
+ continue;
+ }
+ const touch = this.arena.touches.find(each => each.id === id);
+ // A claim made at the contact's own lift (a tap's) holds nothing: the
+ // drag is over, and a click keeps the selection it made. A wheel's
+ // contact keeps the page's selection, as a scroll does.
+ if (
+ touch == null ||
+ touch.pointerType === 'touch' ||
+ touch.scrollType != null ||
+ touch.phase === 'ended' ||
+ touch.phase === 'cancelled'
+ ) {
+ continue;
+ }
+ const elements = new Set<Element>();
+ for (const recognizer of this.arena.participantsOf(id)) {
+ if (
+ (recognizer.state === 'began' || recognizer.state === 'changed') &&
+ (recognizer.view as Node | null)?.nodeType === 1
+ ) {
+ elements.add(recognizer.view as Element);
+ }
+ }
+ if ((claimer.view as Node | null)?.nodeType === 1) {
+ elements.add(claimer.view as Element);
+ }
+ if (elements.size === 0) {
+ continue;
+ }
+ const release = lockDragSelection(
+ elements,
+ this.doc.defaultView,
+ this.pressSelections.get(id) ?? [],
+ () => {
+ this.dragHolds.delete(release);
+ },
+ );
+ this.dragHolds.add(release);
+ // A press lock the contact took at its press stays in `lockedBy`. The
+ // hold sits beside it, and the contact's end releases both.
+ if (!this.lockedBy.has(id)) {
+ this.lockedBy.set(id, release);
+ }
+ this.claimHolds.set(id, release);
+ }
+ }
+
+ /**
+ * Claimed contacts the arena gave back. Their drag holds end at once, so
+ * the browser's drag selects again. A contact's press lock (lockSelection)
+ * is not a drag hold and stays.
+ */
+ private releaseClaimedDrags(ids: ReadonlyArray<number>): void {
+ for (const id of ids) {
+ const release = this.claimHolds.get(id);
+ if (release == null) {
+ continue;
+ }
+ this.claimHolds.delete(id);
+ if (this.lockedBy.get(id) === release) {
+ this.lockedBy.delete(id);
+ }
+ release({isCancel: true});
+ }
+ }
+
/**
* End the trackpad pan a recognizer still drives, when the page loses focus
* or hides, and return its contacts to cancel. The rest of its stream is
@@ -2583,10 +2717,44 @@ export class GestureHost {
);
}
- /** Undo `lockSelection` for a contact that ended; idempotent. */
- private unlockSelection(id: number): void {
- this.lockedBy.get(id)?.();
+ /**
+ * At a mouse or pen press, mark one that lands on selectable text: once it
+ * moves, it is the browser's drag, and selects text.
+ * Text whose hold does something is locked at this press already
+ * (lockSelection), so it is not selectable text.
+ */
+ private noteSelectingPress(
+ id: number,
+ x: number,
+ y: number,
+ target: EventTarget | null,
+ ): void {
+ if (
+ !this.lockedBy.has(id) &&
+ startsOnSelectableText(this.doc, x, y, target)
+ ) {
+ this.selectingContacts.add(id);
+ }
+ }
+
+ /**
+ * Undo a contact's selection locks, its press lock and its drag hold, at
+ * once for a cancel, and forget its press's selection; idempotent. A
+ * drag's hold keeps its last task after a lift (lockDragSelection).
+ */
+ private unlockSelection(id: number, isCancel = false): void {
+ const lock = this.lockedBy.get(id);
+ lock?.({isCancel});
+ // A press lock keeps `lockedBy` when the contact also has a drag hold.
+ // Release the hold too.
+ const hold = this.claimHolds.get(id);
+ if (hold != null && hold !== lock) {
+ hold({isCancel});
+ }
this.lockedBy.delete(id);
+ this.claimHolds.delete(id);
+ this.pressSelections.delete(id);
+ this.selectingContacts.delete(id);
}
// --- Touch events ----------------------------------------------------------
@@ -3349,6 +3517,11 @@ export class GestureHost {
if (target !== landed && target != null) {
this.retargeted.set(id, {x: event.clientX, y: event.clientY, target});
}
+ // Before the arena admits it: a press a group claims at its own
+ // pointerdown keeps the selection the page has now.
+ if (event.pointerType !== 'touch') {
+ this.pressSelections.set(id, selectionRangesOf(this.doc.defaultView));
+ }
this.arena.began([
{
id,
@@ -3373,6 +3546,10 @@ export class GestureHost {
consumerElement,
);
}
+ if (event.pointerType !== 'touch') {
+ // The engine's own hit: the text its caret query and a drag select.
+ this.noteSelectingPress(id, event.clientX, event.clientY, landed);
+ }
};
private readonly onPointerMove = (event: PointerEvent): void => {
@@ -3524,7 +3701,7 @@ export class GestureHost {
const id = this.pointerIds.get(event.pointerId);
if (id != null) {
this.pointerIds.delete(event.pointerId);
- this.unlockSelection(id);
+ this.unlockSelection(id, true);
this.retargeted.delete(id);
this.arena.cancelled([id], eventTime(event));
}
@@ -3765,7 +3942,7 @@ export class GestureHost {
private cancelEverything(time: number): void {
const ids = [...this.pointerIds.values()];
for (const id of ids) {
- this.unlockSelection(id);
+ this.unlockSelection(id, true);
}
for (const identifier of [...this.touchIds.keys()]) {
// The browser may keep the touch alive: its lift must not click.
diff --git a/packages/core/src/gestures/README.md b/packages/core/src/gestures/README.md
index a2429c0c93..638256b47d 100644
--- a/packages/core/src/gestures/README.md
+++ b/packages/core/src/gestures/README.md
@@ -304,9 +304,25 @@ presses nothing.
controller's surfaces (`usePressFeedback` rows), keep the browser's
long-press selection; a tap never selects. A non-text input under the finger inside such an element (a checkbox, a radio, a switch's input) is locked too: WebKit's own stylesheet makes every input selectable, which no ancestor's lock reaches. A text field keeps its selection, since a held finger places its caret. A
finger or a pen takes the lock under any primary pointer, a touchscreen
- laptop and a desktop pen tablet included; a mouse never does, so mouse
- selection is unchanged (`spec:AST-017` FR59); content under a sheet's or a
- pager's pan stays selectable.
+ laptop and a desktop pen tablet included; a mouse never does
+ (`spec:AST-017` FR59).
+
+ A mouse or pen drag that a recognizer claims takes no new text selection
+ and never clears the page's (`spec:AST-094` FR41): from the claim until a
+ task after the lift (the press's own `mouseup` and `click` come in its
+ task), the claiming elements and the document refuse a selection, and the
+ selection the page had when the press began is put back over whatever the
+ press or the drag made of it. The hold starts at the claim of whichever
+ recognizer makes it, whatever its state: a swipe recognizes as `ended`
+ while the button is still down, and a recognizer that waits on another's
+ failure claims while still `possible`. A claim given back to the browser
+ (that waiting recognizer failing or cancelled, with no other owner) lets
+ the hold go, and the drag selects again. A drag that starts on selectable text (a
+ character of text that allows a selection, or a text field) is not
+ claimed: no recognizer recognizes with it while it is down, so it selects
+ text, and content under a sheet's or a pager's pan stays selectable. A
+ press a recognizer claims at its own pointerdown, before it moves, is no
+ drag, and a tap claims only at its lift.
- **Claiming.** When a recognizer recognizes, it owns its touches. Each
element with a recognizer that can claim a moving touch (a pan, a swipe, a
diff --git a/packages/core/src/gestures/__tests__/GestureHost.test.ts b/packages/core/src/gestures/__tests__/GestureHost.test.ts
index d4c8265481..96976a66d6 100644
--- a/packages/core/src/gestures/__tests__/GestureHost.test.ts
+++ b/packages/core/src/gestures/__tests__/GestureHost.test.ts
@@ -23,6 +23,7 @@ import {createPressTracker} from '../PressTracker';
import type {SelectionLock} from '../GestureRecognizer';
import {VelocityTracker} from '../VelocityTracker';
import {ScreenEdgePanGestureRecognizer} from '../ScreenEdgePanGestureRecognizer';
+import {SwipeGestureRecognizer} from '../SwipeGestureRecognizer';
import {lockSelection} from '../../utils/selectionLock';
import {TapGestureRecognizer} from '../TapGestureRecognizer';
import {createNativeScrollProbe} from '../nativeScroll';
@@ -5415,6 +5416,583 @@ describe('every pointer where the primary pointer is fine (spec:AST-094 FR19, FR
});
});
+describe('a mouse or pen drag and the page selection (spec:AST-094 FR41)', () => {
+ function fineHost(): GestureHost {
+ return new GestureHost(document, {
+ clock,
+ isPrimaryPointerCoarse: () => false,
+ });
+ }
+
+ /** Select all of `node`, as the page or a drag would. */
+ function select(node: Node): Selection {
+ const selection = window.getSelection() as Selection;
+ selection.removeAllRanges();
+ const range = document.createRange();
+ range.selectNodeContents(node);
+ selection.addRange(range);
+ return selection;
+ }
+
+ /**
+ * Every point lands on a character of `text`, as an engine's caret query
+ * over text answers (jsdom has none); the returned function undoes it.
+ */
+ function textUnderEveryPoint(text: Text): () => void {
+ Object.defineProperty(document, 'caretRangeFromPoint', {
+ configurable: true,
+ value: () => {
+ const range = document.createRange();
+ range.setStart(text, 1);
+ range.collapse(true);
+ return range;
+ },
+ });
+ const rects = Object.getOwnPropertyDescriptor(
+ Range.prototype,
+ 'getClientRects',
+ );
+ Object.defineProperty(Range.prototype, 'getClientRects', {
+ configurable: true,
+ value: () => [{left: 0, right: 1000, top: 0, bottom: 1000}],
+ });
+ return () => {
+ delete (document as {caretRangeFromPoint?: unknown}).caretRangeFromPoint;
+ if (rects == null) {
+ delete (Range.prototype as {getClientRects?: unknown}).getClientRects;
+ } else {
+ Object.defineProperty(Range.prototype, 'getClientRects', rects);
+ }
+ };
+ }
+
+ /**
+ * A press at the first of `xs` and moves through the rest, 16 ms apart, or
+ * only moves when `isPressed`; returns the last event's time.
+ */
+ function drag(
+ target: EventTarget,
+ pointerType: 'mouse' | 'pen',
+ start: number,
+ xs: ReadonlyArray<number>,
+ isPressed = false,
+ ): number {
+ let time = start;
+ for (const [index, x] of xs.entries()) {
+ time += 16;
+ pointer(
+ index === 0 && !isPressed ? 'pointerdown' : 'pointermove',
+ target,
+ {
+ pointerType,
+ x,
+ y: 10,
+ buttons: 1,
+ time,
+ },
+ );
+ }
+ return time;
+ }
+
+ it('takes no new selection once a mouse or a pen pan claims: a selection its drag started goes, and its element refuses one until the lift', async () => {
+ const {box} = mount('<div id="box">Some text a drag would select</div>');
+ const fine = fineHost();
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ detachers.push(fine.attach(box, pan));
+ const selection = window.getSelection() as Selection;
+ let time = 0;
+ for (const pointerType of ['mouse', 'pen'] as const) {
+ selection.removeAllRanges();
+ time = drag(box, pointerType, time + 1000, [10]);
+ // The drag selects text before the pan claims at 10 px.
+ select(box);
+ time = drag(box, pointerType, time, [30, 50], true);
+ expect(['began', 'changed']).toContain(pan.state);
+ expect(selection.rangeCount).toBe(0);
+ expect(box.style.getPropertyValue('user-select')).toBe('none');
+ const start = new Event('selectstart', {bubbles: true, cancelable: true});
+ box.dispatchEvent(start);
+ expect(start.defaultPrevented).toBe(true);
+ pointer('pointerup', box, {pointerType, x: 50, y: 10, time: time + 16});
+ // The document's hold ends a task after the lift: wait for it, so no
+ // hold outlives the press.
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(box.style.getPropertyValue('user-select')).toBe('');
+ }
+ });
+
+ it('holds the selection for a swipe that claims a mouse or a pen drag: it recognizes as ended while the button is still down', async () => {
+ const {box} = mount('<div id="box">Some text a drag would select</div>');
+ const fine = fineHost();
+ const swipe = new SwipeGestureRecognizer({direction: 'right'});
+ const states: string[] = [];
+ swipe.addTransitionListener((_current, _from, to) => states.push(to));
+ detachers.push(fine.attach(box, swipe));
+ const selection = window.getSelection() as Selection;
+ let time = 0;
+ for (const pointerType of ['mouse', 'pen'] as const) {
+ selection.removeAllRanges();
+ states.length = 0;
+ time = drag(box, pointerType, time + 1000, [10]);
+ // The drag selects text before the swipe recognizes at 50 px.
+ select(box);
+ time = drag(box, pointerType, time, [40, 70, 100], true);
+ expect(states).toContain('ended');
+ expect(selection.rangeCount).toBe(0);
+ expect(box.style.getPropertyValue('user-select')).toBe('none');
+ const start = new Event('selectstart', {bubbles: true, cancelable: true});
+ box.dispatchEvent(start);
+ expect(start.defaultPrevented).toBe(true);
+ pointer('pointerup', box, {pointerType, x: 100, y: 10, time: time + 16});
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(box.style.getPropertyValue('user-select')).toBe('');
+ }
+ });
+
+ it('holds the selection from the claim of a pan that waits on another to fail, and lets it go when that claim is given back', async () => {
+ const {box} = mount('<div id="box">Some text a drag would select</div>');
+ const fine = fineHost();
+ // The pan wants to begin at 10 px. A hold that allows 15 px of movement
+ // is still possible then. So the pan waits on it and claims the drag. The
+ // hold takes no selection lock of its own at the press, because its hold
+ // does nothing to the selection. So only the claim can hold it.
+ const hold = new LongPressGestureRecognizer({
+ name: 'hold',
+ allowableMovement: 15,
+ selectionLock: null,
+ });
+ const pan = new PanGestureRecognizer({
+ direction: 'horizontal',
+ }).requireToFail(hold);
+ detachers.push(fine.attach(box, pan), fine.attach(box, hold));
+ const selection = window.getSelection() as Selection;
+ let time = 0;
+ for (const pointerType of ['mouse', 'pen'] as const) {
+ selection.removeAllRanges();
+ time = drag(box, pointerType, time + 1000, [10]);
+ select(box);
+ // 12 px: the pan claims while it waits, still possible.
+ time = drag(box, pointerType, time, [22], true);
+ expect(pan.state).toBe('possible');
+ expect(selection.rangeCount).toBe(0);
+ expect(box.style.getPropertyValue('user-select')).toBe('none');
+ // 30 px: the hold fails and the pan begins; the hold stays.
+ time = drag(box, pointerType, time, [40], true);
+ expect(['began', 'changed']).toContain(pan.state);
+ expect(box.style.getPropertyValue('user-select')).toBe('none');
+ pointer('pointerup', box, {pointerType, x: 40, y: 10, time: time + 16});
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(box.style.getPropertyValue('user-select')).toBe('');
+ }
+ // A waiting pan disabled mid-drag gives its claim back: the drag is the
+ // browser's again, and selects.
+ time = drag(box, 'mouse', time + 1000, [10]);
+ time = drag(box, 'mouse', time, [22], true);
+ expect(box.style.getPropertyValue('user-select')).toBe('none');
+ pan.setEnabled(false);
+ expect(pan.state).not.toBe('possible');
+ expect(box.style.getPropertyValue('user-select')).toBe('');
+ pointer('pointerup', box, {
+ pointerType: 'mouse',
+ x: 22,
+ y: 10,
+ time: time + 16,
+ });
+ });
+
+ it("never clears the page's existing selection: a claimed drag puts back what its press collapsed, what it selected, and what WebKit extends, through the lift", async () => {
+ const {text, box} = mount(
+ '<p id="text">Text the page selected</p><div id="box">Pan</div>',
+ );
+ const fine = fineHost();
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ detachers.push(fine.attach(box, pan));
+ let time = 0;
+ for (const pointerType of ['mouse', 'pen'] as const) {
+ const selection = select(text);
+ time = drag(box, pointerType, time + 1000, [10]);
+ // The press's own mousedown collapses the page's selection, and the
+ // drag starts its own before the pan claims.
+ selection.collapseToStart();
+ select(box);
+ time = drag(box, pointerType, time, [30, 50], true);
+ expect(['began', 'changed']).toContain(pan.state);
+ expect(selection.toString()).toBe('Text the page selected');
+ // WebKit extends the drag's selection over the page without a
+ // selectstart.
+ select(box);
+ document.dispatchEvent(new Event('selectionchange'));
+ expect(selection.toString()).toBe('Text the page selected');
+ pointer('pointerup', box, {pointerType, x: 50, y: 10, time: time + 16});
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(selection.toString()).toBe('Text the page selected');
+ }
+ });
+
+ it.each([
+ ['in a paragraph', '<p>Card text a drag selects</p>'],
+ ['directly under the root', 'Card text a drag selects'],
+ ])(
+ 'does not claim a mouse drag that starts on text inside an open shadow root (%s): the caret query gets the press target’s open roots, so the browser selects',
+ async (_where, html) => {
+ const {box, card} = mount(
+ '<div id="box"><x-card id="card"></x-card></div>',
+ );
+ const root = card.attachShadow({mode: 'open'});
+ root.innerHTML = html;
+ const text = (root.querySelector('p') ?? root).firstChild as Text;
+ const paragraph = root.querySelector<HTMLElement>('p') ?? card;
+ // As Chromium answers: inside the shadow root only when it is passed.
+ Object.defineProperty(document, 'caretPositionFromPoint', {
+ configurable: true,
+ value: (
+ _x: number,
+ _y: number,
+ options?: {shadowRoots?: ReadonlyArray<ShadowRoot>},
+ ) =>
+ options?.shadowRoots?.includes(root) === true
+ ? {offsetNode: text, offset: 1}
+ : {offsetNode: card, offset: 0},
+ });
+ const rects = Object.getOwnPropertyDescriptor(
+ Range.prototype,
+ 'getClientRects',
+ );
+ Object.defineProperty(Range.prototype, 'getClientRects', {
+ configurable: true,
+ value: () => [{left: 0, right: 1000, top: 0, bottom: 1000}],
+ });
+ try {
+ const fine = fineHost();
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ detachers.push(fine.attach(box, pan));
+ const time = drag(paragraph, 'mouse', 1000, [10, 30, 50, 70]);
+ expect(['began', 'changed']).not.toContain(pan.state);
+ expect(box.style.getPropertyValue('user-select')).toBe('');
+ pointer('pointerup', paragraph, {
+ pointerType: 'mouse',
+ x: 70,
+ y: 10,
+ time: time + 16,
+ });
+ await new Promise(resolve => setTimeout(resolve, 0));
+ } finally {
+ delete (document as {caretPositionFromPoint?: unknown})
+ .caretPositionFromPoint;
+ if (rects == null) {
+ delete (Range.prototype as {getClientRects?: unknown}).getClientRects;
+ } else {
+ Object.defineProperty(Range.prototype, 'getClientRects', rects);
+ }
+ }
+ },
+ );
+
+ it('holds a claimed drag’s selection through the shared window listener: the document gets no selectstart or selectionchange listener of its own (architecture:react-component-runtime INV13)', async () => {
+ const {box} = mount('<div id="box"></div>');
+ const fine = fineHost();
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ detachers.push(fine.attach(box, pan));
+ const added = vi.spyOn(document, 'addEventListener');
+ detachers.push(() => added.mockRestore());
+ const time = drag(box, 'mouse', 1000, [10, 30, 50]);
+ expect(['began', 'changed']).toContain(pan.state);
+ expect(
+ added.mock.calls
+ .map(([type]) => type)
+ .filter(type => type === 'selectstart' || type === 'selectionchange'),
+ ).toEqual([]);
+ // The hold still refuses a selection that starts anywhere on the page.
+ const start = new Event('selectstart', {bubbles: true, cancelable: true});
+ document.body.dispatchEvent(start);
+ expect(start.defaultPrevented).toBe(true);
+ pointer('pointerup', box, {
+ pointerType: 'mouse',
+ x: 50,
+ y: 10,
+ time: time + 16,
+ });
+ await new Promise(resolve => setTimeout(resolve, 0));
+ });
+
+ it('does not claim a mouse or a pen drag that starts on selectable text: the pan fails and the browser selects, while a tap on text still recognizes at the lift', async () => {
+ const {box, label} = mount(
+ '<div id="box">Card text a drag selects</div><div id="label">A label</div>',
+ );
+ const undo = textUnderEveryPoint(box.firstChild as Text);
+ try {
+ const fine = fineHost();
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ const panStates: string[] = [];
+ pan.addTransitionListener((_current, _from, to) => panStates.push(to));
+ const tap = new TapGestureRecognizer();
+ const tapStates: string[] = [];
+ tap.addTransitionListener((_current, _from, to) => tapStates.push(to));
+ detachers.push(fine.attach(box, pan), fine.attach(label, tap));
+ let time = 0;
+ for (const pointerType of ['mouse', 'pen'] as const) {
+ time = drag(box, pointerType, time + 1000, [10, 30, 50, 70]);
+ expect(['began', 'changed']).not.toContain(pan.state);
+ // No hold: the browser's selection runs.
+ expect(box.style.getPropertyValue('user-select')).toBe('');
+ const start = new Event('selectstart', {
+ bubbles: true,
+ cancelable: true,
+ });
+ box.dispatchEvent(start);
+ expect(start.defaultPrevented).toBe(false);
+ pointer('pointerup', box, {pointerType, x: 70, y: 10, time: time + 16});
+ time += 1000;
+ pointer('pointerdown', label, {
+ pointerType,
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time,
+ });
+ pointer('pointerup', label, {
+ pointerType,
+ x: 10,
+ y: 10,
+ time: time + 80,
+ });
+ }
+ expect(panStates).not.toContain('began');
+ expect(tapStates.filter(state => state === 'ended')).toHaveLength(2);
+ } finally {
+ undo();
+ }
+ });
+
+ it("claims a mouse or a pen drag that starts on a native button's label: the engine starts no selection there, so the pan takes it", async () => {
+ const {box, label} = mount(
+ '<div id="box"><button id="label">Next page</button></div>',
+ );
+ const undo = textUnderEveryPoint(label.firstChild as Text);
+ try {
+ const fine = fineHost();
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ detachers.push(fine.attach(box, pan));
+ let time = 0;
+ for (const pointerType of ['mouse', 'pen'] as const) {
+ time = drag(label, pointerType, time + 1000, [10, 30, 50]);
+ expect(['began', 'changed']).toContain(pan.state);
+ pointer('pointerup', label, {
+ pointerType,
+ x: 50,
+ y: 10,
+ time: time + 16,
+ });
+ await new Promise(resolve => setTimeout(resolve, 0));
+ }
+ } finally {
+ undo();
+ }
+ });
+
+ it('claims a mouse drag that starts on a slotted label inside a native button in a shadow tree', async () => {
+ const {box, next} = mount(
+ '<div id="box"><x-next id="next">Next page</x-next></div>',
+ );
+ next.attachShadow({mode: 'open'}).innerHTML =
+ '<button><slot></slot></button>';
+ const undo = textUnderEveryPoint(next.firstChild as Text);
+ try {
+ const fine = fineHost();
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ detachers.push(fine.attach(box, pan));
+ const time = drag(next, 'mouse', 1000, [10, 30, 50]);
+ expect(['began', 'changed']).toContain(pan.state);
+ pointer('pointerup', next, {
+ pointerType: 'mouse',
+ x: 50,
+ y: 10,
+ time: time + 16,
+ });
+ await new Promise(resolve => setTimeout(resolve, 0));
+ } finally {
+ undo();
+ }
+ });
+
+ it("still claims a press a group claims at its own pointerdown on selectable text: it has not moved, so it is no drag, and the page's selection stays; a pen's hold ends a task after its lift, though the row's long press locks too", async () => {
+ const {text, row, group, copy} = mount(
+ '<p id="text">Text the page selected</p><div id="row"><div id="group"><button id="copy">Copy</button></div></div>',
+ );
+ const undo = textUnderEveryPoint(copy.firstChild as Text);
+ try {
+ const fine = fineHost();
+ // The row's context-menu long press brings a selection lock (its hold
+ // opens a menu), which a pen's press takes as well.
+ detachers.push(
+ fine.attach(row, new LongPressGestureRecognizer({name: 'menu'})),
+ );
+ // The action-group adapter's recognizer: a long press with no minimum
+ // duration and no movement limit, which claims at the pointerdown.
+ const press = new LongPressGestureRecognizer({
+ minimumPressDuration: 0,
+ allowableMovement: Number.POSITIVE_INFINITY,
+ });
+ detachers.push(fine.attach(group, press, {actionGroup: true}));
+ let time = 0;
+ for (const pointerType of ['mouse', 'pen'] as const) {
+ const selection = select(text);
+ time += 1000;
+ pointer('pointerdown', copy, {
+ pointerType,
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time,
+ });
+ expect(press.state).toBe('began');
+ expect(selection.toString()).toBe('Text the page selected');
+ pointer('pointerup', copy, {
+ pointerType,
+ x: 10,
+ y: 10,
+ time: time + 80,
+ });
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(selection.toString()).toBe('Text the page selected');
+ // The hold kept the press's own task, then ended: the page selects
+ // again.
+ const later = new Event('selectstart', {
+ bubbles: true,
+ cancelable: true,
+ });
+ text.dispatchEvent(later);
+ expect(later.defaultPrevented).toBe(false);
+ expect(group.style.getPropertyValue('user-select')).toBe('');
+ }
+ } finally {
+ undo();
+ }
+ });
+
+ it("keeps the page's selection for a pen drag a pan claims after the press took the row's press lock: the drag hold sits beside the lock (spec:AST-094 FR41)", async () => {
+ const {text, row, box} = mount(
+ '<p id="text">Text the page selected</p><div id="row"><div id="box"></div></div>',
+ );
+ const fine = fineHost();
+ // The row's context-menu long press brings a selection lock, which a
+ // pen's press takes at its pointerdown.
+ detachers.push(
+ fine.attach(row, new LongPressGestureRecognizer({name: 'menu'})),
+ );
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ detachers.push(fine.attach(box, pan));
+ let time = 0;
+ for (const pointerType of ['pen', 'mouse'] as const) {
+ const selection = select(text);
+ time += 1000;
+ pointer('pointerdown', box, {
+ pointerType,
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time,
+ });
+ // The engine collapses the selection at the press.
+ selection.removeAllRanges();
+ document.dispatchEvent(new Event('selectionchange'));
+ time = drag(box, pointerType, time + 16, [30, 50], true);
+ expect(['began', 'changed']).toContain(pan.state);
+ expect(selection.toString()).toBe('Text the page selected');
+ pointer('pointerup', box, {pointerType, x: 50, y: 10, time: time + 16});
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(selection.toString()).toBe('Text the page selected');
+ expect(row.style.getPropertyValue('user-select')).toBe('');
+ expect(box.style.getPropertyValue('user-select')).toBe('');
+ }
+ });
+
+ it("keeps the page's selection for a pen press a group claims at its own pointerdown before the row's press lock, and ends both at the lift (spec:AST-094 FR41)", async () => {
+ const {text, row, group, copy} = mount(
+ '<p id="text">Text the page selected</p><div id="row"><div id="group"><button id="copy">Copy</button></div></div>',
+ );
+ const fine = fineHost();
+ detachers.push(
+ fine.attach(row, new LongPressGestureRecognizer({name: 'menu'})),
+ );
+ // The action-group adapter's press claims at the pointerdown, before the
+ // row's lock is taken.
+ const press = new LongPressGestureRecognizer({
+ minimumPressDuration: 0,
+ allowableMovement: Number.POSITIVE_INFINITY,
+ });
+ detachers.push(fine.attach(group, press, {actionGroup: true}));
+ const selection = select(text);
+ pointer('pointerdown', copy, {
+ pointerType: 'pen',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 1000,
+ });
+ expect(press.state).toBe('began');
+ // The engine collapses the selection at the press.
+ selection.removeAllRanges();
+ document.dispatchEvent(new Event('selectionchange'));
+ expect(selection.toString()).toBe('Text the page selected');
+ pointer('pointerup', copy, {pointerType: 'pen', x: 10, y: 10, time: 1080});
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(selection.toString()).toBe('Text the page selected');
+ expect(row.style.getPropertyValue('user-select')).toBe('');
+ expect(group.style.getPropertyValue('user-select')).toBe('');
+ const later = new Event('selectstart', {bubbles: true, cancelable: true});
+ text.dispatchEvent(later);
+ expect(later.defaultPrevented).toBe(false);
+ });
+
+ for (const ending of ['pointercancel', 'blur', 'detach'] as const) {
+ it(`ends a claimed drag's document-wide hold at once when it ends in a ${ending}: no mouseup or click follows a cancel`, () => {
+ const {box, outside} = mount(
+ '<p id="outside">Text outside the pan</p><div id="box">Pan</div>',
+ );
+ const fine = fineHost();
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ const detach = fine.attach(box, pan);
+ detachers.push(detach);
+ const time = drag(box, 'mouse', 0, [10, 30, 50]);
+ expect(['began', 'changed']).toContain(pan.state);
+ if (ending === 'pointercancel') {
+ pointer('pointercancel', document.body, {
+ pointerType: 'mouse',
+ x: 50,
+ y: 10,
+ time: time + 16,
+ });
+ } else if (ending === 'blur') {
+ window.dispatchEvent(new Event('blur'));
+ } else {
+ detach();
+ }
+ const later = new Event('selectstart', {bubbles: true, cancelable: true});
+ outside.dispatchEvent(later);
+ expect(later.defaultPrevented).toBe(false);
+ });
+ }
+
+ it("leaves a mouse click's selection alone: a tap claims only at its lift", () => {
+ const {box} = mount('<div id="box">Some selected text</div>');
+ const fine = fineHost();
+ detachers.push(fine.attach(box, new TapGestureRecognizer()));
+ const selection = select(box);
+ pointer('pointerdown', box, {
+ pointerType: 'mouse',
+ x: 10,
+ y: 10,
+ buttons: 1,
+ time: 0,
+ });
+ pointer('pointerup', box, {pointerType: 'mouse', x: 10, y: 10, time: 80});
+ expect(selection.rangeCount).toBe(1);
+ expect(box.style.getPropertyValue('user-select')).toBe('');
+ });
+});
+
describe('nothing left after the last detach (spec:AST-094 FR21, FR24)', () => {
/** Listeners added and not removed since the case began: target and type. */
let open: Map<string, string>;
@@ -5545,6 +6123,9 @@ describe('nothing left after the last detach (spec:AST-094 FR21, FR24)', () => {
'registry',
'pendingCallerReads',
'lockedBy',
+ 'pressSelections',
+ 'selectingContacts',
+ 'dragHolds',
'retargeted',
'touchIds',
'cancelledFingers',
diff --git a/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts b/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts
index 49b2338836..d2d2024dcd 100644
--- a/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts
+++ b/packages/core/src/gestures/__tests__/browser/gestures.interaction.browser.spec.ts
@@ -1999,6 +1999,365 @@ test.describe('where the primary pointer is fine', () => {
).toBeGreaterThan(1);
});
+ /**
+ * A page has text above a card that a pan takes, the card's own text on its
+ * first line only, and text below. The pan's transitions land on
+ * `window.__panStates`. Returns the card's box and its text's.
+ */
+ async function cardPage(page: Page) {
+ await page.goto('about:blank');
+ await page.setContent(
+ '<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><body></body>',
+ );
+ await page.addScriptTag({content: bareBundle});
+ await page.evaluate(() => {
+ const {host, PanGestureRecognizer} = window.__api;
+ document.body.style.font = '16px sans-serif';
+ document.body.innerHTML =
+ '<h1 id="heading">A story heading with words</h1><p>A description with several words in it.</p><div id="card" style="margin-top: 24px; width: 320px; height: 120px; background: #ccd"><span id="cardText">Card text a drag selects</span></div><p>Text below the card, with words.</p>';
+ const pan = new PanGestureRecognizer();
+ const states: string[] = [];
+ (window as unknown as {__panStates: string[]}).__panStates = states;
+ pan.addTransitionListener((_current, _from, to) => states.push(to));
+ host.attach(document.getElementById('card') as HTMLElement, pan);
+ });
+ const card = await page.locator('#card').boundingBox();
+ const text = await page.locator('#cardText').boundingBox();
+ if (card == null || text == null) {
+ throw new Error('no box for #card');
+ }
+ return {card, text};
+ }
+
+ /**
+ * The page's selection once `selectionchange`, dispatched as its own
+ * task, has run: as the next frame paints it.
+ */
+ async function paintedSelection(page: Page): Promise<string> {
+ return page.evaluate(
+ async () =>
+ new Promise<string>(resolve => {
+ requestAnimationFrame(() =>
+ resolve(String(window.getSelection() ?? '').trim()),
+ );
+ }),
+ );
+ }
+
+ test("a mouse drag a pan claimed takes no new selection though it carries over text, and the page's existing selection survives it (spec:AST-094 FR41)", async ({
+ page,
+ }) => {
+ const {card} = await cardPage(page);
+ // From the card's lower half, below its text, past the pan's start and
+ // up over the text above the card.
+ const drag = async () => {
+ const x = card.x + 40;
+ const y = card.y + card.height * 0.75;
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x + 30, y - 10, {steps: 4});
+ await page.mouse.move(x + 60, card.y - 80, {steps: 12});
+ const during = await paintedSelection(page);
+ await page.mouse.up();
+ return {during, after: await paintedSelection(page)};
+ };
+ const fresh = await drag();
+ const kept = await page.evaluate(() => {
+ window
+ .getSelection()
+ ?.selectAllChildren(document.getElementById('heading') as HTMLElement);
+ return String(window.getSelection() ?? '').trim();
+ });
+ expect(kept).toBe('A story heading with words');
+ const overKept = await drag();
+ const states = await page.evaluate(
+ () => (window as unknown as {__panStates: string[]}).__panStates,
+ );
+ expect({
+ fresh,
+ overKept,
+ began: states.filter(state => state === 'began').length,
+ }).toEqual({
+ fresh: {during: '', after: ''},
+ overKept: {during: kept, after: kept},
+ began: 2,
+ });
+ });
+
+ test('a mouse drag that starts on selectable text selects it, and the pan under it never claims the drag (spec:AST-094 FR41)', async ({
+ page,
+ }) => {
+ const {text} = await cardPage(page);
+ const y = text.y + text.height / 2;
+ await page.mouse.move(text.x + 2, y);
+ await page.mouse.down();
+ await page.mouse.move(text.x + text.width * 0.6, y, {steps: 10});
+ await page.mouse.up();
+ const selected = await paintedSelection(page);
+ const states = await page.evaluate(
+ () => (window as unknown as {__panStates: string[]}).__panStates,
+ );
+ expect(selected.length).toBeGreaterThan(3);
+ expect('Card text a drag selects'.includes(selected)).toBe(true);
+ expect(states).not.toContain('began');
+ });
+
+ test("after a pen press a group claims at its own pointerdown, in a row whose long press opens a menu, a mouse drag selects the page's text again (spec:AST-094 FR41)", async ({
+ page,
+ browserName,
+ }) => {
+ test.skip(browserName === 'webkit', 'no pen input in WebKit’s driver');
+ await page.goto('about:blank');
+ await page.setContent(
+ '<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><body></body>',
+ );
+ await page.addScriptTag({content: bareBundle});
+ await page.evaluate(() => {
+ const {host, LongPressGestureRecognizer} = window.__api;
+ document.body.style.font = '16px sans-serif';
+ document.body.innerHTML =
+ '<p id="para">A paragraph a later mouse drag selects.</p><div id="row" style="width: 320px; padding: 12px; background: #ccd"><div id="group"><button id="copy" style="width: 120px; height: 40px">Copy</button></div></div>';
+ // The row's context-menu long press brings a selection lock; the
+ // action group's press claims at its own pointerdown.
+ host.attach(
+ document.getElementById('row') as HTMLElement,
+ new LongPressGestureRecognizer({name: 'menu'}),
+ );
+ host.attach(
+ document.getElementById('group') as HTMLElement,
+ new LongPressGestureRecognizer({
+ minimumPressDuration: 0,
+ allowableMovement: Number.POSITIVE_INFINITY,
+ }),
+ {actionGroup: true},
+ );
+ });
+ const copy = await page.locator('#copy').boundingBox();
+ const para = await page.locator('#para').boundingBox();
+ if (copy == null || para == null) {
+ throw new Error('no box for #copy or #para');
+ }
+ const cdp = await page.context().newCDPSession(page);
+ for (const type of ['mousePressed', 'mouseReleased'] as const) {
+ await cdp.send('Input.dispatchMouseEvent', {
+ type,
+ x: copy.x + 20,
+ y: copy.y + 20,
+ button: 'left',
+ buttons: type === 'mousePressed' ? 1 : 0,
+ clickCount: 1,
+ pointerType: 'pen',
+ });
+ }
+ // A task after the lift, the hold has ended: a real mouse drag over the
+ // paragraph selects it.
+ await page.evaluate(
+ async () =>
+ new Promise<void>(resolve => {
+ setTimeout(resolve, 0);
+ }),
+ );
+ const y = para.y + para.height / 2;
+ await page.mouse.move(para.x + 2, y);
+ await page.mouse.down();
+ await page.mouse.move(para.x + para.width * 0.6, y, {steps: 10});
+ await page.mouse.up();
+ const selected = await paintedSelection(page);
+ expect(selected.length).toBeGreaterThan(3);
+ expect('A paragraph a later mouse drag selects.'.includes(selected)).toBe(
+ true,
+ );
+ });
+
+ test("a mouse drag that starts on a native button's label inside a pan pans: the engine starts no selection there (spec:AST-094 FR41)", async ({
+ page,
+ }) => {
+ await page.goto('about:blank');
+ await page.setContent(
+ '<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><body></body>',
+ );
+ await page.addScriptTag({content: bareBundle});
+ await page.evaluate(() => {
+ const {host, PanGestureRecognizer} = window.__api;
+ document.body.style.font = '16px sans-serif';
+ document.body.innerHTML =
+ '<div id="card" style="width: 320px; height: 120px; padding: 16px; background: #ccd"><button id="next" style="font: inherit; padding: 8px 16px">Next page</button></div>';
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ const states: string[] = [];
+ (window as unknown as {__panStates: string[]}).__panStates = states;
+ pan.addTransitionListener((_current, _from, to) => states.push(to));
+ host.attach(document.getElementById('card') as HTMLElement, pan);
+ });
+ const label = await page.locator('#next').boundingBox();
+ if (label == null) {
+ throw new Error('no box for #next');
+ }
+ const y = label.y + label.height / 2;
+ await page.mouse.move(label.x + label.width / 2, y);
+ await page.mouse.down();
+ await page.mouse.move(label.x + label.width / 2 + 60, y, {steps: 10});
+ await page.mouse.up();
+ const selected = await paintedSelection(page);
+ const states = await page.evaluate(
+ () => (window as unknown as {__panStates: string[]}).__panStates,
+ );
+ expect({began: states.includes('began'), selected}).toEqual({
+ began: true,
+ selected: '',
+ });
+ });
+
+ test('a mouse drag that starts on text inside an open shadow root in a pan selects it, and the pan never begins (spec:AST-094 FR41)', async ({
+ page,
+ }) => {
+ await page.goto('about:blank');
+ await page.setContent(
+ '<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><body></body>',
+ );
+ await page.addScriptTag({content: bareBundle});
+ await page.evaluate(() => {
+ const {host, PanGestureRecognizer} = window.__api;
+ document.body.innerHTML =
+ '<div id="card" style="width: 360px; padding: 16px; background: #ccd"><x-words id="words"></x-words></div>';
+ const words = document.getElementById('words') as HTMLElement;
+ words.attachShadow({mode: 'open'}).innerHTML =
+ '<p style="margin: 0; font: 20px sans-serif">Shadow words to select</p>';
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ const states: string[] = [];
+ (window as unknown as {__panStates: string[]}).__panStates = states;
+ pan.addTransitionListener((_current, _from, to) => states.push(to));
+ host.attach(document.getElementById('card') as HTMLElement, pan);
+ });
+ const words = await page.locator('#words').boundingBox();
+ if (words == null) {
+ throw new Error('no box for #words');
+ }
+ const y = words.y + words.height / 2;
+ await page.mouse.move(words.x + 4, y);
+ await page.mouse.down();
+ await page.mouse.move(words.x + 150, y, {steps: 10});
+ await page.mouse.up();
+ const selected = await paintedSelection(page);
+ const states = await page.evaluate(
+ () => (window as unknown as {__panStates: string[]}).__panStates,
+ );
+ expect({began: states.includes('began'), selected}).toEqual({
+ began: false,
+ selected: expect.stringMatching(/^Shadow/),
+ });
+ });
+
+ test('a selection inside an open shadow root survives a claimed mouse drag on a pan elsewhere (spec:AST-094 FR41)', async ({
+ page,
+ }) => {
+ await page.goto('about:blank');
+ await page.setContent(
+ '<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><body></body>',
+ );
+ await page.addScriptTag({content: bareBundle});
+ await page.evaluate(() => {
+ const {host, PanGestureRecognizer} = window.__api;
+ document.body.innerHTML =
+ '<x-words id="words"></x-words><div id="card" style="width: 320px; height: 120px; margin-top: 24px; background: #ccd"></div>';
+ const words = document.getElementById('words') as HTMLElement;
+ words.attachShadow({mode: 'open'}).innerHTML =
+ '<p style="margin: 0; font: 20px sans-serif">Shadow words to keep</p>';
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ const states: string[] = [];
+ (window as unknown as {__panStates: string[]}).__panStates = states;
+ pan.addTransitionListener((_current, _from, to) => states.push(to));
+ host.attach(document.getElementById('card') as HTMLElement, pan);
+ });
+ const words = await page.locator('#words').boundingBox();
+ const card = await page.locator('#card').boundingBox();
+ if (words == null || card == null) {
+ throw new Error('no box for #words or #card');
+ }
+ const y = words.y + words.height / 2;
+ await page.mouse.move(words.x + 2, y);
+ await page.mouse.down();
+ await page.mouse.move(words.x + 160, y, {steps: 8});
+ await page.mouse.up();
+ const before = await paintedSelection(page);
+ expect(before).toMatch(/^Shadow/);
+ await page.mouse.move(card.x + 40, card.y + 60);
+ await page.mouse.down();
+ await page.mouse.move(card.x + 160, card.y + 60, {steps: 10});
+ await page.mouse.up();
+ const states = await page.evaluate(
+ () => (window as unknown as {__panStates: string[]}).__panStates,
+ );
+ expect({
+ began: states.includes('began'),
+ after: await paintedSelection(page),
+ }).toEqual({began: true, after: before});
+ });
+
+ test("a render that shortens the kept selection's text during a claimed drag throws nothing, and the page selects again after the release (spec:AST-094 FR41)", async ({
+ page,
+ }) => {
+ const errors: string[] = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await page.goto('about:blank');
+ await page.setContent(
+ '<!doctype html><meta name="viewport" content="width=device-width, initial-scale=1"><body></body>',
+ );
+ await page.addScriptTag({content: bareBundle});
+ await page.evaluate(() => {
+ const {host, PanGestureRecognizer} = window.__api;
+ document.body.innerHTML =
+ '<p id="words" style="margin: 0; font: 20px sans-serif">Hello world text</p><div id="card" style="width: 320px; height: 120px; margin: 24px 0; background: #ccd"></div><p id="other" style="margin: 0; font: 20px sans-serif">Other words to select</p>';
+ const words = (document.getElementById('words') as HTMLElement)
+ .firstChild as Text;
+ const pan = new PanGestureRecognizer({direction: 'horizontal'});
+ const states: string[] = [];
+ (window as unknown as {__panStates: string[]}).__panStates = states;
+ pan.addTransitionListener((_current, _from, to) => {
+ states.push(to);
+ // A render during the drag shortens the selected text.
+ if (to === 'changed' && words.data !== 'Hi') {
+ words.data = 'Hi';
+ }
+ });
+ host.attach(document.getElementById('card') as HTMLElement, pan);
+ const range = document.createRange();
+ range.setStart(words, 6);
+ range.setEnd(words, 16);
+ window.getSelection()?.addRange(range);
+ });
+ expect(await paintedSelection(page)).toBe('world text');
+ const card = await page.locator('#card').boundingBox();
+ const other = await page.locator('#other').boundingBox();
+ if (card == null || other == null) {
+ throw new Error('no box for #card or #other');
+ }
+ await page.mouse.move(card.x + 40, card.y + 60);
+ await page.mouse.down();
+ await page.mouse.move(card.x + 160, card.y + 60, {steps: 10});
+ await page.mouse.up();
+ // The hold ends a task after the lift.
+ await page.evaluate(
+ async () => new Promise(resolve => setTimeout(resolve, 50)),
+ );
+ const y = other.y + other.height / 2;
+ await page.mouse.move(other.x + 2, y);
+ await page.mouse.down();
+ await page.mouse.move(other.x + 120, y, {steps: 8});
+ await page.mouse.up();
+ const states = await page.evaluate(
+ () => (window as unknown as {__panStates: string[]}).__panStates,
+ );
+ expect({
+ began: states.includes('began'),
+ errors,
+ selected: await paintedSelection(page),
+ }).toEqual({
+ began: true,
+ errors: [],
+ selected: expect.stringMatching(/^Other/),
+ });
+ });
+
test("the host registers no page touch listener while idle and warns for nothing, though the page attaches recognizers: an element keeps only a claiming recognizer's blocking touchmove; a mouse drag pans (spec:AST-094 FR43, FR24, FR19)", async ({
page,
}) => {
diff --git a/packages/core/src/utils/selectionLock.test.ts b/packages/core/src/utils/selectionLock.test.ts
index 75e5b72928..766b3b5fb1 100644
--- a/packages/core/src/utils/selectionLock.test.ts
+++ b/packages/core/src/utils/selectionLock.test.ts
@@ -12,7 +12,13 @@
*/
import {afterEach, describe, expect, it, vi} from 'vitest';
-import {lockSelection, locksSelectionFor} from './selectionLock';
+import {
+ lockDragSelection,
+ lockSelection,
+ locksSelectionFor,
+ selectionRangesOf,
+ startsOnSelectableText,
+} from './selectionLock';
/** Make `CSS.supports` answer as iOS WebKit does for its touch callout. */
function asIosWebKit(): () => void {
@@ -104,3 +110,146 @@ describe('locksSelectionFor', () => {
matchMedia.mockRestore();
});
});
+
+/** Select all of `node`. */
+function select(node: Node): Selection {
+ const selection = window.getSelection() as Selection;
+ selection.removeAllRanges();
+ const range = document.createRange();
+ range.selectNodeContents(node);
+ selection.addRange(range);
+ return selection;
+}
+
+describe('lockDragSelection (spec:AST-094 FR41)', () => {
+ it('keeps the selection the press began with: what replaces it goes back, a new one is refused on the elements and the document, and the document refuses one until a task after the lift', async () => {
+ const get = mount(
+ '<p id="text">Text the page selected</p><div id="pan">Pan</div>',
+ );
+ const selection = select(get('text'));
+ const kept = selectionRangesOf(window);
+ selection.collapseToStart();
+ const onReleased = vi.fn();
+ const release = lockDragSelection([get('pan')], window, kept, onReleased);
+ expect(selection.toString()).toBe('Text the page selected');
+ expect(refuses(get('pan'))).toBe(true);
+ expect(refuses(get('text'))).toBe(true);
+ select(get('pan'));
+ document.dispatchEvent(new Event('selectionchange'));
+ expect(selection.toString()).toBe('Text the page selected');
+ release();
+ expect(refuses(get('text'))).toBe(true);
+ expect(onReleased).not.toHaveBeenCalled();
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(refuses(get('text'))).toBe(false);
+ expect(refuses(get('pan'))).toBe(false);
+ expect(onReleased).toHaveBeenCalledTimes(1);
+ expect(selection.toString()).toBe('Text the page selected');
+ });
+
+ it('takes away a selection the drag made when the page had none', () => {
+ const get = mount('<div id="pan">Pan text</div>');
+ window.getSelection()?.removeAllRanges();
+ const kept = selectionRangesOf(window);
+ expect(kept).toEqual([]);
+ const selection = select(get('pan'));
+ const release = lockDragSelection([get('pan')], window, kept);
+ expect(selection.rangeCount).toBe(0);
+ release({isCancel: true});
+ });
+
+ it('ends at once at a cancel, and a cancel after a lift ends its last task at once; onReleased runs once', () => {
+ const get = mount('<p id="text">Text</p><div id="pan">Pan</div>');
+ const cancelled = vi.fn();
+ lockDragSelection([get('pan')], window, [], cancelled)({isCancel: true});
+ expect(refuses(get('text'))).toBe(false);
+ expect(cancelled).toHaveBeenCalledTimes(1);
+ const lifted = vi.fn();
+ const release = lockDragSelection([get('pan')], window, [], lifted);
+ release();
+ expect(refuses(get('text'))).toBe(true);
+ release({isCancel: true});
+ expect(refuses(get('text'))).toBe(false);
+ release({isCancel: true});
+ expect(lifted).toHaveBeenCalledTimes(1);
+ });
+
+ it('leaves a focused text field its own selection', () => {
+ const get = mount(
+ '<input id="field" value="typed words"><div id="pan">Pan</div>',
+ );
+ const field = get('field') as HTMLInputElement;
+ field.focus();
+ const text = document.createElement('p');
+ text.textContent = 'Page text';
+ document.body.append(text);
+ const selection = select(text);
+ const release = lockDragSelection([get('pan')], window, []);
+ expect(selection.toString()).toBe('Page text');
+ expect(refuses(field)).toBe(false);
+ release({isCancel: true});
+ });
+});
+
+describe('startsOnSelectableText (spec:AST-094 FR41)', () => {
+ /** The caret query lands at `offset` in `node`, and each character's box is `rect`. */
+ function caretAt(
+ node: Node,
+ offset: number,
+ rect: {left: number; right: number; top: number; bottom: number},
+ ): void {
+ Object.defineProperty(document, 'caretRangeFromPoint', {
+ configurable: true,
+ value: () => {
+ const range = document.createRange();
+ range.setStart(node, offset);
+ range.collapse(true);
+ return range;
+ },
+ });
+ Object.defineProperty(Range.prototype, 'getClientRects', {
+ configurable: true,
+ value: () => [rect],
+ });
+ }
+
+ afterEach(() => {
+ delete (document as {caretRangeFromPoint?: unknown}).caretRangeFromPoint;
+ delete (Range.prototype as {getClientRects?: unknown}).getClientRects;
+ });
+
+ it('answers yes on a character of text, and on a text field', () => {
+ const get = mount('<p id="text">Selectable words</p><input id="field">');
+ caretAt(get('text').firstChild as Text, 3, {
+ left: 0,
+ right: 50,
+ top: 0,
+ bottom: 20,
+ });
+ expect(startsOnSelectableText(document, 10, 10, get('text'))).toBe(true);
+ expect(startsOnSelectableText(document, 400, 400, get('field'))).toBe(true);
+ });
+
+ it('answers no beside text the caret query snaps to, on whitespace, on text that refuses a selection, and where the engine has no caret query', () => {
+ const get = mount('<p id="text">Selectable words</p><p id="blank"> </p>');
+ const text = get('text').firstChild as Text;
+ caretAt(text, 3, {left: 0, right: 50, top: 0, bottom: 20});
+ expect(startsOnSelectableText(document, 200, 10, get('text'))).toBe(false);
+ caretAt(get('blank').firstChild as Text, 1, {
+ left: 0,
+ right: 50,
+ top: 0,
+ bottom: 20,
+ });
+ expect(startsOnSelectableText(document, 10, 10, get('blank'))).toBe(false);
+ caretAt(text, 3, {left: 0, right: 50, top: 0, bottom: 20});
+ vi.spyOn(window, 'getComputedStyle').mockReturnValue({
+ getPropertyValue: (name: string) =>
+ name === 'user-select' ? 'none' : '',
+ } as unknown as CSSStyleDeclaration);
+ expect(startsOnSelectableText(document, 10, 10, get('text'))).toBe(false);
+ vi.restoreAllMocks();
+ delete (document as {caretRangeFromPoint?: unknown}).caretRangeFromPoint;
+ expect(startsOnSelectableText(document, 10, 10, get('text'))).toBe(false);
+ });
+});
diff --git a/packages/core/src/utils/selectionLock.ts b/packages/core/src/utils/selectionLock.ts
index d29b1b04e1..57b783055e 100644
--- a/packages/core/src/utils/selectionLock.ts
+++ b/packages/core/src/utils/selectionLock.ts
@@ -3,11 +3,12 @@
/**
* @file selectionLock.ts
* @input The elements a held touch contact presses, and the touch's target
- * @output lockSelection: no text selection and no touch callout under the
- * held finger until the release runs; and locksSelectionFor: which contacts
- * take it
- * @position Brought by the recognizers whose hold does something. The gesture
- * host calls it and never imports it.
+ * @output lockSelection and locksSelectionFor give a held finger's lock.
+ * lockDragSelection gives a claimed mouse or pen drag's hold, which keeps
+ * the page's selection. startsOnSelectableText and selectionRangesOf are
+ * what a mouse or pen press reads.
+ * @position Recognizers whose hold does something bring lockSelection; the
+ * gesture host imports the drag hold and the press reads.
*
* SYNC: When modified, update GestureHost.ts and utils/pressFeedback.ts; the
* iOS query matches utils/touchPresentation.ts.
@@ -27,7 +28,8 @@
//
// A mouse never takes the lock, so its released behavior stays (AST-017).
-import {containsAlongFlatTree} from './flatTree';
+import {containsAlongFlatTree, parentAcrossShadow} from './flatTree';
+import {subscribeInput} from './inputStream';
import {isIosWebKit} from './touchQueries';
/** What a held finger must not start on a control or a cell. */
@@ -101,6 +103,499 @@ export function lockSelection(
}
};
}
+ return lockStyles(set);
+}
+
+/** How a drag's selection hold ends: at a lift, or at a cancel. */
+export interface DragSelectionReleaseOptions {
+ /**
+ * The press was cancelled (a pointercancel, a blur, a detach), so no
+ * mouseup or click follows: the hold ends at once. Called again after a
+ * lift, it ends the hold's last task at once too.
+ */
+ isCancel?: boolean;
+}
+
+/**
+ * Refuse a new selection while a mouse or pen drag that a recognizer claimed
+ * runs, until the returned function runs. `kept` is the page's selection
+ * when the press began, and it stays. Anything that replaces it while the
+ * drag runs is put back to it. That includes the press's own collapse and a
+ * selection the drag started before its claim. So the drag takes no new
+ * selection and never clears an existing one. `elements` refuse a
+ * selection with inline styles, on every engine. The document refuses one
+ * too, because WebKit extends a drag's selection over text outside the
+ * elements without another `selectstart`. So a `selectstart` anywhere is
+ * refused, and the selection is put back. A `selectstart` does not leave its
+ * shadow tree. So the document refuses only one that starts outside every
+ * shadow tree, and a claiming element inside one refuses its own. The
+ * press's own `mouseup` and `click` come after its `pointerup` in the same
+ * task, and WebKit settles the drag's selection there. So the document's
+ * hold ends a task after a lift. A cancel ends it at once, because nothing
+ * follows a cancel. `onReleased` runs once the document's hold has ended.
+ * The page listeners exist only during a press. Idempotent.
+ */
+export function lockDragSelection(
+ elements: Iterable<Element>,
+ view: Window | null | undefined,
+ kept: ReadonlyArray<AbstractRange>,
+ onReleased?: () => void,
+): (options?: DragSelectionReleaseOptions) => void {
+ const doc = view?.document ?? null;
+ const roots = shadowRootsOfRanges(kept);
+ const restore = () => {
+ const selection = view?.getSelection();
+ // The focused field keeps its own selection (a drag never starts in one).
+ if (selection == null || isTextEntry(deepActiveElement(doc))) {
+ return;
+ }
+ const held = heldRanges(selection, roots);
+ if (kept.length === 0) {
+ if (held.some(range => !range.collapsed)) {
+ selection.removeAllRanges();
+ }
+ return;
+ }
+ // A render can remove what the kept selection held: then there is
+ // nothing to put back.
+ if (sameRanges(held, kept) || !kept.every(isValidRange)) {
+ return;
+ }
+ selectRanges(selection, kept);
+ };
+ restore();
+ const set = new Set(elements);
+ const refuse = (event: Event) => {
+ if (!isTextEntry(event.target)) {
+ event.preventDefault();
+ }
+ };
+ for (const element of set) {
+ element.addEventListener('selectstart', refuse);
+ }
+ const stopDocument =
+ view == null
+ ? []
+ : [
+ subscribeInput(view, 'selectstart', refuse, {cancels: true}),
+ subscribeInput(view, 'selectionchange', restore),
+ ];
+ const unlockStyles = lockStyles(set);
+ let stage: 'held' | 'lifted' | 'done' = 'held';
+ let timer: number | null = null;
+ const releaseDocument = () => {
+ if (stage === 'done') {
+ return;
+ }
+ stage = 'done';
+ if (timer != null) {
+ view?.clearTimeout(timer);
+ timer = null;
+ }
+ try {
+ restore();
+ } finally {
+ for (const stop of stopDocument) {
+ stop();
+ }
+ onReleased?.();
+ }
+ };
+ return ({isCancel = false}: DragSelectionReleaseOptions = {}) => {
+ if (stage === 'held') {
+ stage = 'lifted';
+ for (const element of set) {
+ element.removeEventListener('selectstart', refuse);
+ }
+ unlockStyles();
+ // A lift's own mouseup and click follow in its task and must still
+ // meet the hold; nothing follows a cancel, which ends it at once.
+ if (view == null || isCancel) {
+ releaseDocument();
+ } else {
+ timer = view.setTimeout(releaseDocument, 0);
+ }
+ } else if (stage === 'lifted' && isCancel) {
+ releaseDocument();
+ }
+ };
+}
+
+/**
+ * The page's selection now, its ranges copied; none for a collapsed or empty
+ * one. A drag's hold keeps what this read when the press began.
+ */
+export function selectionRangesOf(
+ view: Window | null | undefined,
+): ReadonlyArray<AbstractRange> {
+ const selection = view?.getSelection();
+ if (selection == null) {
+ return [];
+ }
+ const composed = composedRangesOf(selection, []);
+ if (composed != null) {
+ return composed.filter(range => !range.collapsed).map(liveWhereItCan);
+ }
+ if (selection.isCollapsed) {
+ return [];
+ }
+ const ranges: Range[] = [];
+ for (let index = 0; index < selection.rangeCount; index++) {
+ ranges.push(selection.getRangeAt(index).cloneRange());
+ }
+ return ranges;
+}
+
+/**
+ * Whether a press at (`x`, `y`) lands on text a drag would select. That is a
+ * text field, or a character of non-empty text whose element allows a
+ * selection. A native button's label, slotted or not, is not selectable text,
+ * because the engine starts no selection from a drag inside a button. A point
+ * beside text, which a caret query snaps to the nearest character, lands on
+ * none. Where the engine has no caret query, nothing is selectable text.
+ */
+export function startsOnSelectableText(
+ doc: Document,
+ x: number,
+ y: number,
+ target: EventTarget | null,
+): boolean {
+ if (isTextEntry(target)) {
+ return true;
+ }
+ const caret = caretAt(doc, x, y, [
+ ...ownShadowRoot(target),
+ ...openShadowRootsOf(target),
+ ]);
+ if (caret == null) {
+ return false;
+ }
+ const {node, offset} = caret;
+ if (node.nodeType !== 3 || (node.textContent ?? '').trim() === '') {
+ return false;
+ }
+ // Text directly under a shadow root takes its host's style.
+ const element =
+ node.parentElement ??
+ (node.parentNode?.nodeType === 11
+ ? (node.parentNode as ShadowRoot).host
+ : null);
+ if (element == null || !allowsSelection(element) || isInButton(node)) {
+ return false;
+ }
+ const length = (node.textContent ?? '').length;
+ const range = doc.createRange();
+ if (typeof range.getClientRects !== 'function') {
+ return false;
+ }
+ for (const start of [offset - 1, offset]) {
+ if (start < 0 || start >= length) {
+ continue;
+ }
+ range.setStart(node, start);
+ range.setEnd(node, start + 1);
+ for (const rect of Array.from(range.getClientRects())) {
+ if (
+ x >= rect.left &&
+ x <= rect.right &&
+ y >= rect.top &&
+ y <= rect.bottom
+ ) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+/** Whether `node` is inside a native button, along the flat tree. */
+function isInButton(node: Node): boolean {
+ for (let at: Node | null = node; at != null; at = parentAcrossShadow(at)) {
+ if (at.nodeType === 1 && (at as Element).localName === 'button') {
+ return true;
+ }
+ }
+ return false;
+}
+
+/** The caret position the engine puts at a point, by either query. */
+function caretAt(
+ doc: Document,
+ x: number,
+ y: number,
+ shadowRoots: ReadonlyArray<ShadowRoot>,
+): {node: Node; offset: number} | null {
+ const queries = doc as Document & {
+ caretPositionFromPoint?: (
+ x: number,
+ y: number,
+ options?: {shadowRoots?: ShadowRoot[]},
+ ) => {offsetNode: Node; offset: number} | null;
+ caretRangeFromPoint?: (x: number, y: number) => Range | null;
+ };
+ if (typeof queries.caretPositionFromPoint === 'function') {
+ // Without the roots, a point over shadow text answers at its host.
+ const position =
+ shadowRoots.length > 0
+ ? queries.caretPositionFromPoint(x, y, {
+ shadowRoots: [...shadowRoots],
+ })
+ : queries.caretPositionFromPoint(x, y);
+ return position == null
+ ? null
+ : {node: position.offsetNode, offset: position.offset};
+ }
+ if (typeof queries.caretRangeFromPoint === 'function') {
+ const range = queries.caretRangeFromPoint(x, y);
+ return range == null
+ ? null
+ : {node: range.startContainer, offset: range.startOffset};
+ }
+ return null;
+}
+
+/** Whether an element's text can be selected (`user-select` is not none). */
+function allowsSelection(element: Element): boolean {
+ const style = element.ownerDocument.defaultView?.getComputedStyle(element);
+ if (style == null) {
+ return false;
+ }
+ return (
+ style.getPropertyValue('user-select') !== 'none' &&
+ style.getPropertyValue('-webkit-user-select') !== 'none'
+ );
+}
+
+/**
+ * The ranges `selection` holds, with boundaries inside `shadowRoots` where the
+ * engine reads composed ranges.
+ */
+function heldRanges(
+ selection: Selection,
+ shadowRoots: ReadonlyArray<ShadowRoot>,
+): ReadonlyArray<AbstractRange> {
+ const composed = composedRangesOf(selection, shadowRoots);
+ if (composed != null) {
+ return composed;
+ }
+ const ranges: Range[] = [];
+ for (let index = 0; index < selection.rangeCount; index++) {
+ ranges.push(selection.getRangeAt(index));
+ }
+ return ranges;
+}
+
+/**
+ * A live copy of `range` when both boundaries share a root, so it follows
+ * DOM changes. A range across roots stays static: no live range holds it.
+ */
+function liveWhereItCan(range: StaticRange): AbstractRange {
+ const live = range.startContainer.ownerDocument?.createRange();
+ if (
+ live == null ||
+ range.startContainer.getRootNode() !== range.endContainer.getRootNode()
+ ) {
+ return range;
+ }
+ live.setStart(range.startContainer, range.startOffset);
+ live.setEnd(range.endContainer, range.endOffset);
+ return live;
+}
+
+/** Whether both of `range`'s boundaries still exist in the document. */
+function isValidRange(range: AbstractRange): boolean {
+ return (
+ isValidBoundary(range.startContainer, range.startOffset) &&
+ isValidBoundary(range.endContainer, range.endOffset)
+ );
+}
+
+function isValidBoundary(node: Node, offset: number): boolean {
+ const length =
+ node.nodeType === 3 || node.nodeType === 4 || node.nodeType === 8
+ ? (node as CharacterData).length
+ : node.childNodes.length;
+ return node.isConnected && offset >= 0 && offset <= length;
+}
+
+/** Whether two range lists have the same boundaries, in order. */
+function sameRanges(
+ held: ReadonlyArray<AbstractRange>,
+ kept: ReadonlyArray<AbstractRange>,
+): boolean {
+ return (
+ held.length === kept.length &&
+ kept.every((range, index) => {
+ const other = held[index];
+ return (
+ other.startContainer === range.startContainer &&
+ other.startOffset === range.startOffset &&
+ other.endContainer === range.endContainer &&
+ other.endOffset === range.endOffset
+ );
+ })
+ );
+}
+
+/**
+ * Put `ranges` back as the selection. One range goes through
+ * `setBaseAndExtent`, which also reaches inside a shadow root.
+ */
+function selectRanges(
+ selection: Selection,
+ ranges: ReadonlyArray<AbstractRange>,
+): void {
+ const [only] = ranges;
+ if (ranges.length === 1 && typeof selection.setBaseAndExtent === 'function') {
+ selection.setBaseAndExtent(
+ only.startContainer,
+ only.startOffset,
+ only.endContainer,
+ only.endOffset,
+ );
+ return;
+ }
+ selection.removeAllRanges();
+ for (const range of ranges) {
+ const copy = range.startContainer.ownerDocument?.createRange();
+ if (copy == null) {
+ continue;
+ }
+ copy.setStart(range.startContainer, range.startOffset);
+ copy.setEnd(range.endContainer, range.endOffset);
+ selection.addRange(copy);
+ }
+}
+
+/**
+ * The selection's composed ranges, reaching into each open shadow root a
+ * boundary lands on; null where the engine has no `getComposedRanges`.
+ * Without the roots, a selection inside a shadow root reads as one around
+ * its host.
+ */
+function composedRangesOf(
+ selection: Selection,
+ known: ReadonlyArray<ShadowRoot>,
+): StaticRange[] | null {
+ const query = (
+ selection as Selection & {
+ getComposedRanges?: (options?: {
+ shadowRoots?: ShadowRoot[];
+ }) => StaticRange[];
+ }
+ ).getComposedRanges;
+ if (typeof query !== 'function') {
+ return null;
+ }
+ // Engines take the roots as a dictionary, or, in older releases, as
+ // arguments.
+ const read = (roots: ShadowRoot[]): StaticRange[] | null => {
+ try {
+ return query.call(selection, {shadowRoots: roots});
+ } catch {
+ try {
+ return (query as (...roots: ShadowRoot[]) => StaticRange[]).call(
+ selection,
+ ...roots,
+ );
+ } catch {
+ return null;
+ }
+ }
+ };
+ const roots = [...known];
+ for (;;) {
+ const ranges = read([...roots]);
+ if (ranges == null) {
+ return null;
+ }
+ const found = new Set<ShadowRoot>();
+ for (const range of ranges) {
+ for (const [node, offset] of [
+ [range.startContainer, range.startOffset],
+ [range.endContainer, range.endOffset],
+ ] as const) {
+ for (const child of [
+ node.childNodes[offset],
+ node.childNodes[offset - 1],
+ ]) {
+ const root =
+ child?.nodeType === 1 ? (child as Element).shadowRoot : null;
+ if (root != null && !roots.includes(root)) {
+ found.add(root);
+ }
+ }
+ }
+ }
+ if (found.size === 0) {
+ return ranges;
+ }
+ roots.push(...found);
+ }
+}
+
+/** The open shadow roots on the root chains of `ranges`' boundaries. */
+function shadowRootsOfRanges(
+ ranges: ReadonlyArray<AbstractRange>,
+): ReadonlyArray<ShadowRoot> {
+ const roots = new Set<ShadowRoot>();
+ for (const range of ranges) {
+ for (const root of [
+ ...openShadowRootsOf(range.startContainer),
+ ...openShadowRootsOf(range.endContainer),
+ ]) {
+ roots.add(root);
+ }
+ }
+ return [...roots];
+}
+
+/**
+ * The open shadow root `target` hosts, if any. A press on text directly under
+ * a shadow root targets its host.
+ */
+function ownShadowRoot(target: EventTarget | null): ShadowRoot[] {
+ const root =
+ (target as Node | null)?.nodeType === 1
+ ? (target as Element).shadowRoot
+ : null;
+ return root == null ? [] : [root];
+}
+
+/** The open shadow roots on `target`'s root chain, innermost first. */
+function openShadowRootsOf(target: EventTarget | null): ShadowRoot[] {
+ const roots: ShadowRoot[] = [];
+ let root =
+ target != null && typeof (target as Node).nodeType === 'number'
+ ? (target as Node).getRootNode()
+ : null;
+ while (root != null && root.nodeType === 11) {
+ const host = (root as ShadowRoot).host as Element | undefined;
+ if (host == null) {
+ break;
+ }
+ if ((root as ShadowRoot).mode === 'open') {
+ roots.push(root as ShadowRoot);
+ }
+ root = host.getRootNode();
+ }
+ return roots;
+}
+
+/** The focused element, inside open shadow roots too. */
+function deepActiveElement(doc: Document | null): Element | null {
+ let active = doc?.activeElement ?? null;
+ while (active?.shadowRoot?.activeElement != null) {
+ active = active.shadowRoot.activeElement;
+ }
+ return active;
+}
+
+/**
+ * The selection-lock styles on `set`, refcounted per element; idempotent
+ * release.
+ */
+function lockStyles(set: ReadonlySet<Element>): () => void {
const locked: Element[] = [];
for (const element of set) {
const style = styleOf(element);