Skip to content

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

TypeScript

fix(gestures): a selection a claimed lift's own handlers make stays (#9848)

Christopher Chedeau7b87c5c1dd75
diff --git a/.changeset/gestures-kept-lift-selection.md b/.changeset/gestures-kept-lift-selection.md
new file mode 100644
index 0000000000..3ab939e6ca
--- /dev/null
+++ b/.changeset/gestures-kept-lift-selection.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A text selection that an action's own handlers make when a claimed mouse or pen press lifts on it now stays. Before, the drag's selection hold put the press's selection back over it. When the handlers change nothing, the press's selection still comes back, as before.
+
+@vjeux
diff --git a/packages/core/src/AlertDialog/AlertDialog.test.tsx b/packages/core/src/AlertDialog/AlertDialog.test.tsx
index 5d7b4d007a..fdf99ec2a5 100644
--- a/packages/core/src/AlertDialog/AlertDialog.test.tsx
+++ b/packages/core/src/AlertDialog/AlertDialog.test.tsx
@@ -551,13 +551,14 @@ describe('AlertDialog action tracking', () => {
type: 'pointerdown' | 'pointermove' | 'pointerup',
target: Element,
point: {x: number; y: number},
+ pointerType: 'mouse' | 'pen' = 'mouse',
): void {
touchClock += 16;
const event = new PointerEvent(type, {
bubbles: true,
cancelable: true,
- pointerId: 1,
- pointerType: 'mouse',
+ pointerId: pointerType === 'pen' ? 41 : 1,
+ pointerType,
isPrimary: true,
button: 0,
buttons: type === 'pointerup' ? 0 : 1,
@@ -627,6 +628,49 @@ describe('AlertDialog action tracking', () => {
}
});
+ it("keeps the selection that the action's own click makes when a pen press lifts on it (spec:AST-094 FR41)", async () => {
+ stubAlertDialogMedia({
+ smallScreen: true,
+ coarsePointer: true,
+ noHover: true,
+ });
+ const page = document.createElement('p');
+ page.textContent = 'Text the page selected';
+ const made = document.createElement('p');
+ made.textContent = 'Text the action selects';
+ document.body.append(page, made);
+ const selectText = (element: Element) => {
+ const range = document.createRange();
+ range.selectNodeContents(element);
+ const selection = getSelection();
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+ };
+ render(
+ <AlertDialog
+ isOpen
+ onOpenChange={() => {}}
+ title="Delete item?"
+ description="This cannot be undone."
+ actionLabel="Delete"
+ onAction={() => selectText(made)}
+ />,
+ );
+ const action = screen.getByRole('button', {name: 'Delete'});
+ place(action, 16, 100);
+ place(screen.getByRole('button', {name: 'Cancel'}), 16, 140);
+ selectText(page);
+ mouse('pointerdown', action, {x: 60, y: 116}, 'pen');
+ mouse('pointerup', action, {x: 60, y: 116}, 'pen');
+ await Promise.resolve();
+ // The press's own mouseup would put the press's selection back.
+ document.dispatchEvent(new Event('selectionchange'));
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(String(getSelection())).toBe('Text the action selects');
+ page.remove();
+ made.remove();
+ });
+
it('leaves a mouse press to the native button under the touch presentation: one slid from the action to Cancel runs nothing (family:action-groups FR1)', () => {
const {onOpenChange, onAction, cancel, action} = renderOpen();
mouse('pointerdown', action, {x: 60, y: 116});
diff --git a/packages/core/src/gestures/GestureHost.ts b/packages/core/src/gestures/GestureHost.ts
index 712119d4d5..a6f9aa0389 100644
--- a/packages/core/src/gestures/GestureHost.ts
+++ b/packages/core/src/gestures/GestureHost.ts
@@ -179,6 +179,7 @@ import {
import {subscribeInput} from '../utils/inputStream';
import {isPrimaryClick} from '../utils/primaryClick';
import {
+ type DragSelectionHold,
type DragSelectionReleaseOptions,
lockDragSelection,
locksSelectionFor,
@@ -710,10 +711,7 @@ export class GestureHost {
(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 claimHolds = new Map<number, DragSelectionHold>();
private readonly presentedHitTesting: 'auto' | 'always' | 'never';
/**
* Contacts sent to what is drawn instead of what the engine hit, by host
@@ -3747,10 +3745,13 @@ export class GestureHost {
}
this.pointerIds.delete(event.pointerId);
this.pointerKinds.delete(event.pointerId);
+ const hold = this.claimHolds.get(id);
this.unlockSelection(id);
const dispositions = this.arena.ended([
{id, x: event.clientX, y: event.clientY, time: eventTime(event)},
]);
+ // A selection the lift's own handlers made stays, as a click's does.
+ hold?.keepLiftSelection();
// A retargeted tap's own click arms the click guard for the engine's.
const landed = this.retargeted.get(id);
this.retargeted.delete(id);
diff --git a/packages/core/src/utils/selectionLock.test.ts b/packages/core/src/utils/selectionLock.test.ts
index 766b3b5fb1..0f2e2d84d7 100644
--- a/packages/core/src/utils/selectionLock.test.ts
+++ b/packages/core/src/utils/selectionLock.test.ts
@@ -189,6 +189,63 @@ describe('lockDragSelection (spec:AST-094 FR41)', () => {
expect(refuses(field)).toBe(false);
release({isCancel: true});
});
+
+ it("keeps a selection that the lift's own handlers made after the release", async () => {
+ const get = mount(
+ '<p id="text">Text the page selected</p><p id="made">Text a handler selects</p><div id="pan">Pan</div>',
+ );
+ const selection = select(get('text'));
+ const release = lockDragSelection(
+ [get('pan')],
+ window,
+ selectionRangesOf(window),
+ );
+ release();
+ // The lifted action's own click selects other text.
+ select(get('made'));
+ release.keepLiftSelection();
+ document.dispatchEvent(new Event('selectionchange'));
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(selection.toString()).toBe('Text a handler selects');
+ });
+
+ it("keeps a selection that the lift's handlers make in a microtask queued before the keep, as a click's render does", async () => {
+ const get = mount(
+ '<p id="text">Text the page selected</p><p id="made">Text a layout effect selects</p><div id="pan">Pan</div>',
+ );
+ const selection = select(get('text'));
+ const release = lockDragSelection(
+ [get('pan')],
+ window,
+ selectionRangesOf(window),
+ );
+ release();
+ // The click queued its render, whose layout effect selects other text.
+ queueMicrotask(() => select(get('made')));
+ release.keepLiftSelection();
+ await new Promise(resolve => setTimeout(resolve, 0));
+ document.dispatchEvent(new Event('selectionchange'));
+ expect(selection.toString()).toBe('Text a layout effect selects');
+ });
+
+ it("puts the press's selection back when the lift's handlers changed nothing", async () => {
+ const get = mount(
+ '<p id="text">Text the page selected</p><div id="pan">Pan</div>',
+ );
+ const selection = select(get('text'));
+ const release = lockDragSelection(
+ [get('pan')],
+ window,
+ selectionRangesOf(window),
+ );
+ release();
+ release.keepLiftSelection();
+ // The press's own mouseup collapses the selection after the handlers ran.
+ selection.collapseToStart();
+ document.dispatchEvent(new Event('selectionchange'));
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(selection.toString()).toBe('Text the page selected');
+ });
});
describe('startsOnSelectableText (spec:AST-094 FR41)', () => {
diff --git a/packages/core/src/utils/selectionLock.ts b/packages/core/src/utils/selectionLock.ts
index 57b783055e..180334113d 100644
--- a/packages/core/src/utils/selectionLock.ts
+++ b/packages/core/src/utils/selectionLock.ts
@@ -116,6 +116,16 @@ export interface DragSelectionReleaseOptions {
isCancel?: boolean;
}
+/** A drag's selection hold: call it to release the hold. */
+export interface DragSelectionHold {
+ (options?: DragSelectionReleaseOptions): void;
+ /**
+ * Called after the lift's own handlers ran. A selection they made since
+ * the release stays: the hold then puts it back, not the press's.
+ */
+ keepLiftSelection(): void;
+}
+
/**
* 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
@@ -140,9 +150,13 @@ export function lockDragSelection(
view: Window | null | undefined,
kept: ReadonlyArray<AbstractRange>,
onReleased?: () => void,
-): (options?: DragSelectionReleaseOptions) => void {
+): DragSelectionHold {
const doc = view?.document ?? null;
- const roots = shadowRootsOfRanges(kept);
+ let keptRanges = kept;
+ let roots = shadowRootsOfRanges(keptRanges);
+ // The selection when the lift released the hold, until the lift's
+ // handlers ran.
+ let atLift: ReadonlyArray<AbstractRange> | null = null;
const restore = () => {
const selection = view?.getSelection();
// The focused field keeps its own selection (a drag never starts in one).
@@ -150,7 +164,7 @@ export function lockDragSelection(
return;
}
const held = heldRanges(selection, roots);
- if (kept.length === 0) {
+ if (keptRanges.length === 0) {
if (held.some(range => !range.collapsed)) {
selection.removeAllRanges();
}
@@ -158,10 +172,10 @@ export function lockDragSelection(
}
// A render can remove what the kept selection held: then there is
// nothing to put back.
- if (sameRanges(held, kept) || !kept.every(isValidRange)) {
+ if (sameRanges(held, keptRanges) || !keptRanges.every(isValidRange)) {
return;
}
- selectRanges(selection, kept);
+ selectRanges(selection, keptRanges);
};
restore();
const set = new Set(elements);
@@ -201,9 +215,10 @@ export function lockDragSelection(
onReleased?.();
}
};
- return ({isCancel = false}: DragSelectionReleaseOptions = {}) => {
+ const release = (({isCancel = false}: DragSelectionReleaseOptions = {}) => {
if (stage === 'held') {
stage = 'lifted';
+ atLift = selectionRangesOf(view);
for (const element of set) {
element.removeEventListener('selectstart', refuse);
}
@@ -218,7 +233,26 @@ export function lockDragSelection(
} else if (stage === 'lifted' && isCancel) {
releaseDocument();
}
+ }) as DragSelectionHold;
+ release.keepLiftSelection = () => {
+ if (stage !== 'lifted' || atLift == null) {
+ return;
+ }
+ const before = atLift;
+ atLift = null;
+ const keepIfChanged = () => {
+ const now = selectionRangesOf(view);
+ if (stage !== 'done' && !sameRanges(now, before)) {
+ keptRanges = now;
+ roots = shadowRootsOfRanges(now);
+ }
+ };
+ keepIfChanged();
+ // A click's state update renders in a microtask, and its layout effect
+ // may select then. That still runs before the press's own mouseup.
+ queueMicrotask(keepIfChanged);
};
+ return release;
}
/**