Skip to content

A platform for community discussion. Free, open, simple.

DEV: Add a shared pointer drag primitive (#42590)

Sérgio Saquetimc12d8168353d
diff --git a/app/assets/stylesheets/common.scss b/app/assets/stylesheets/common.scss
index 38ff1630673..2817087e2cf 100644
--- a/app/assets/stylesheets/common.scss
+++ b/app/assets/stylesheets/common.scss
@@ -9,6 +9,7 @@
@import "common/form-kit/_index";
@import "common/float-kit/_index";
@import "common/select-kit/_index";
+@import "common/ui-kit/_index";
@import "common/components/_index";
@import "common/modal/_index";
@import "common/input_tip";
diff --git a/app/assets/stylesheets/common/topic-timeline.scss b/app/assets/stylesheets/common/topic-timeline.scss
index bea82d2b327..dd807743499 100644
--- a/app/assets/stylesheets/common/topic-timeline.scss
+++ b/app/assets/stylesheets/common/topic-timeline.scss
@@ -244,6 +244,13 @@
position: relative;
max-width: 100%;
transform: translateZ(0);
+
+ // The padding is a sibling of the scroller, so the drag state is read from
+ // the parent the two share. Easing during a drag leaves the timeline
+ // trailing the pointer for the length of the transition.
+ &.--dragging .timeline-padding {
+ transition: none;
+ }
}
.timeline-padding {
@@ -255,14 +262,6 @@
// the scrollarea's vertical track and thus it
// enables taps on the track to work
margin-left: -1em;
-
- .widget-dragging & {
- transition: none;
- }
-
- .dragging & {
- transition: none;
- }
}
.timeline-handle {
diff --git a/app/assets/stylesheets/common/ui-kit/_index.scss b/app/assets/stylesheets/common/ui-kit/_index.scss
new file mode 100644
index 00000000000..d24aba62645
--- /dev/null
+++ b/app/assets/stylesheets/common/ui-kit/_index.scss
@@ -0,0 +1,6 @@
+/* Styles owned by ui-kit primitives, mirroring `frontend/discourse/app/ui-kit/`
+ the way `form-kit`, `float-kit` and `select-kit` mirror theirs. Component
+ stylesheets not yet moved out of `common/components/` still live there; new
+ ui-kit styles belong here. */
+
+@import "d-pointer-drag";
diff --git a/app/assets/stylesheets/common/ui-kit/d-pointer-drag.scss b/app/assets/stylesheets/common/ui-kit/d-pointer-drag.scss
new file mode 100644
index 00000000000..bcf62f74100
--- /dev/null
+++ b/app/assets/stylesheets/common/ui-kit/d-pointer-drag.scss
@@ -0,0 +1,27 @@
+/* `touch-action` for elements carrying the press-drag-transform gesture. The
+ modifier reflects its `touchAction` arg to `data-pointer-drag`, because the
+ declaration has to be in effect before a touch begins and consumers bind
+ `style` themselves.
+
+ `none` suits a small handle. Anything large enough that a user might start a
+ scroll or a pinch-zoom on it wants a value that leaves those gestures alone. */
+
+[data-pointer-drag="none"] {
+ touch-action: none;
+}
+
+[data-pointer-drag="pan-x"] {
+ touch-action: pan-x pinch-zoom;
+}
+
+[data-pointer-drag="pan-y"] {
+ touch-action: pan-y pinch-zoom;
+}
+
+[data-pointer-drag="manipulation"] {
+ touch-action: manipulation;
+}
+
+[data-pointer-drag="pinch-zoom"] {
+ touch-action: pinch-zoom;
+}
diff --git a/frontend/discourse/app/components/topic-timeline/container.gjs b/frontend/discourse/app/components/topic-timeline/container.gjs
index bbc86d57fe2..e9f2d66c997 100644
--- a/frontend/discourse/app/components/topic-timeline/container.gjs
+++ b/frontend/discourse/app/components/topic-timeline/container.gjs
@@ -21,6 +21,7 @@ import { and, not, or } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
import dAgeWithTooltip from "discourse/ui-kit/helpers/d-age-with-tooltip";
import dCategoryLink from "discourse/ui-kit/helpers/d-category-link";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dDiscourseTags from "discourse/ui-kit/helpers/d-discourse-tags";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
@@ -370,7 +371,9 @@ export default class TopicTimelineScrollArea extends Component {
updatePercentage(e) {
e.preventDefault();
- const currentCursorY = e.pageY || e.touches[0].pageY;
+ // Both a pointer drag and a click on the timeline track land here, and both
+ // carry `pageY` directly.
+ const currentCursorY = e.pageY;
const desiredScrollerCentre = currentCursorY - this.dragOffset;
@@ -390,7 +393,7 @@ export default class TopicTimelineScrollArea extends Component {
@bind
didStartDrag(event) {
- const y = event.pageY || event.touches[0].pageY;
+ const y = event.pageY;
const scrollerCentre =
domUtils.offset(this.scrollerElement).top +
@@ -603,7 +606,10 @@ export default class TopicTimelineScrollArea extends Component {
</div>
<div
- class="timeline-scrollarea"
+ class={{dConcatClass
+ "timeline-scrollarea"
+ (if this.dragging "--dragging")
+ }}
style={{this.timelineScrollareaStyle}}
{{didInsert this.registerScrollarea}}
>
diff --git a/frontend/discourse/app/components/topic-timeline/scroller.gjs b/frontend/discourse/app/components/topic-timeline/scroller.gjs
index 509c454c6df..fccfa77e9b0 100644
--- a/frontend/discourse/app/components/topic-timeline/scroller.gjs
+++ b/frontend/discourse/app/components/topic-timeline/scroller.gjs
@@ -5,7 +5,7 @@ import {
timelineDate,
} from "discourse/components/topic-timeline/container";
import { and, not } from "discourse/truth-helpers";
-import dDraggable from "discourse/ui-kit/modifiers/d-draggable";
+import dPointerDrag from "discourse/ui-kit/modifiers/d-pointer-drag";
import { i18n } from "discourse-i18n";
import BackButton from "./back-button";
@@ -25,10 +25,14 @@ export default class TopicTimelineScroller extends Component {
<template>
<div
- {{dDraggable
- didStartDrag=@didStartDrag
- didEndDrag=@didEndDrag
- dragMove=@dragMove
+ {{! Position is committed continuously as the pointer moves, so discarding
+ on cancel would snap the topic back to where the drag began. }}
+ {{dPointerDrag
+ onDragStart=@didStartDrag
+ onDrag=@dragMove
+ onDragEnd=@didEndDrag
+ cancelCommits=true
+ bodyClass="dragging"
}}
style={{this.style}}
class="timeline-scroller"
diff --git a/frontend/discourse/app/lib/element-class-lease.ts b/frontend/discourse/app/lib/element-class-lease.ts
new file mode 100644
index 00000000000..3d24efe6470
--- /dev/null
+++ b/frontend/discourse/app/lib/element-class-lease.ts
@@ -0,0 +1,107 @@
+/** Bookkeeping for one class token on one element. */
+interface LeaseState {
+ holders: number;
+
+ /**
+ * False when the class was already on the element before the first lease, so
+ * an owner outside this registry does not lose its class when ours ends.
+ */
+ removeOnRelease: boolean;
+}
+
+/** Module-global, so leases coordinate across every caller on the page. */
+let leases = new WeakMap<Element, Map<string, LeaseState>>();
+
+/**
+ * Drops all lease bookkeeping. For tests only: `document.body` outlives every
+ * test, so one unreleased lease pins `holders` above zero and sends every later
+ * lease on that token down the increment path for the rest of the run.
+ */
+export function resetElementClassLeasesForTesting() {
+ leases = new WeakMap();
+}
+
+/**
+ * Holds one class on an element until every cooperating owner releases it.
+ * A class that predates the first lease is preserved after the final release.
+ *
+ * Distinct from `discourse/services/element-classes`, which arbitrates the same
+ * DOM property for the `body-class`/`html-class`/`element-class` helpers: that
+ * service needs an owner, and removes a class regardless of who put it there.
+ * Reach for it from a component or helper, and for a lease from plain functions
+ * and from code that must not clobber a class it did not add. The two
+ * registries do not see each other, so never split one token across both.
+ */
+export default class ElementClassLease {
+ #className: string;
+ #element: Element;
+ #released = false;
+
+ /**
+ * Takes a lease, adding the class if this is the first holder.
+ *
+ * @param className - A single class token.
+ * @throws A `DOMException` if the DOM rejects `className` (whitespace or
+ * empty). It throws before any bookkeeping is recorded, so construct inside
+ * a `try` when the token is not a literal.
+ */
+ constructor(element: Element, className: string) {
+ this.#element = element;
+ this.#className = className;
+
+ const held = leases.get(element)?.get(className);
+ if (held) {
+ // Re-asserted rather than assumed from the count, so a class removed by
+ // anything outside this registry comes back for the next holder.
+ element.classList.add(className);
+ held.holders += 1;
+ return;
+ }
+
+ const removeOnRelease = !element.classList.contains(className);
+ if (removeOnRelease) {
+ // Before the registry is touched, so a token the DOM rejects leaves no
+ // entry behind to be released later.
+ element.classList.add(className);
+ }
+
+ let elementLeases = leases.get(element);
+ if (!elementLeases) {
+ elementLeases = new Map();
+ leases.set(element, elementLeases);
+ }
+ elementLeases.set(className, { holders: 1, removeOnRelease });
+ }
+
+ /**
+ * Gives up this lease, removing the class once the last holder has released
+ * and the class did not predate the first lease. Idempotent, so a caller may
+ * release from both a normal path and a teardown path without tracking which
+ * ran.
+ */
+ release(): void {
+ if (this.#released) {
+ return;
+ }
+ this.#released = true;
+
+ const elementLeases = leases.get(this.#element);
+ const state = elementLeases?.get(this.#className);
+ if (!elementLeases || !state) {
+ return;
+ }
+
+ state.holders -= 1;
+ if (state.holders > 0) {
+ return;
+ }
+
+ elementLeases.delete(this.#className);
+ if (elementLeases.size === 0) {
+ leases.delete(this.#element);
+ }
+ if (state.removeOnRelease) {
+ this.#element.classList.remove(this.#className);
+ }
+ }
+}
diff --git a/frontend/discourse/app/static/dev-tools/toolbar.gjs b/frontend/discourse/app/static/dev-tools/toolbar.gjs
index 9fe9f49e618..5cff14b26fc 100644
--- a/frontend/discourse/app/static/dev-tools/toolbar.gjs
+++ b/frontend/discourse/app/static/dev-tools/toolbar.gjs
@@ -5,8 +5,8 @@ import { action } from "@ember/object";
import { trustHTML } from "@ember/template";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dIcon from "discourse/ui-kit/helpers/d-icon";
-import dDraggable from "discourse/ui-kit/modifiers/d-draggable";
import dOnResize from "discourse/ui-kit/modifiers/d-on-resize";
+import dPointerDrag from "discourse/ui-kit/modifiers/d-pointer-drag";
import I18n, { i18n } from "discourse-i18n";
import BlockDebugButton from "./block-debug/button";
import PluginOutletDebugButton from "./plugin-outlet-debug/button";
@@ -15,10 +15,18 @@ import UpcomingChangesDebugButton from "./upcoming-changes-debug/button";
import VerboseLocalizationButton from "./verbose-localization/button";
export default class Toolbar extends Component {
- @tracked activeDragOffset;
+ @tracked activeDragOffset = null;
@tracked ownSize = 0;
@tracked top = 250;
+ /**
+ * Not the offset's truthiness: a grab exactly at the top edge gives 0, which
+ * would read as "not dragging" for the whole gesture.
+ */
+ get dragging() {
+ return this.activeDragOffset !== null;
+ }
+
get style() {
const clampedTop = Math.max(this.top, 0);
return trustHTML(`top: min(100dvh - ${this.ownSize}px, ${clampedTop}px);`);
@@ -35,7 +43,7 @@ export default class Toolbar extends Component {
const realTop = event.target
.closest(".dev-tools-toolbar")
.getBoundingClientRect().top;
- const dragStartedAtY = event.pageY || event.touches[0].pageY;
+ const dragStartedAtY = event.pageY;
this.activeDragOffset = dragStartedAtY - realTop;
}
@@ -46,7 +54,7 @@ export default class Toolbar extends Component {
@action
dragMove(event) {
- const dragY = event.pageY || event.touches[0].pageY;
+ const dragY = event.pageY;
this.top = dragY - this.activeDragOffset;
}
@@ -57,10 +65,7 @@ export default class Toolbar extends Component {
<template>
<div
- class={{dConcatClass
- "dev-tools-toolbar"
- (if this.activeDragOffset "--dragging")
- }}
+ class={{dConcatClass "dev-tools-toolbar" (if this.dragging "--dragging")}}
style={{this.style}}
{{dOnResize this.onResize}}
>
@@ -68,13 +73,17 @@ export default class Toolbar extends Component {
type="button"
title={{i18n "dev_tools.drag_to_move"}}
class="gripper"
- {{dDraggable
- didStartDrag=this.didStartDrag
- didEndDrag=this.didEndDrag
- dragMove=this.dragMove
+ {{! An interrupted drag leaves the toolbar where it was dragged to,
+ rather than snapping back to where the grab started. }}
+ {{dPointerDrag
+ onDragStart=this.didStartDrag
+ onDrag=this.dragMove
+ onDragEnd=this.didEndDrag
+ cancelCommits=true
+ bodyClass="dragging"
}}
>
- {{dIcon "grip-lines"}}
+ {{dIcon "grip-vertical"}}
</button>
<PluginOutletDebugButton />
<BlockDebugButton />
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-draggable.js b/frontend/discourse/app/ui-kit/modifiers/d-draggable.js
index c89ac7ffb86..ab1f04a2aff 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-draggable.js
+++ b/frontend/discourse/app/ui-kit/modifiers/d-draggable.js
@@ -1,10 +1,12 @@
import { registerDestructor } from "@ember/destroyable";
import Modifier from "ember-modifier";
import { bind } from "discourse/lib/decorators";
+import ElementClassLease from "discourse/lib/element-class-lease";
export default class DDraggableModifier extends Modifier {
hasStarted = false;
element;
+ #bodyClassLease;
constructor(owner, args) {
super(owner, args);
@@ -40,7 +42,7 @@ export default class DDraggableModifier extends Modifier {
document.addEventListener("touchmove", this.drag, { passive: false });
document.addEventListener("mousemove", this.drag, { passive: false });
document.addEventListener("dragover", this.drag, { passive: false });
- document.body.classList.add("dragging");
+ this.#bodyClassLease = new ElementClassLease(document.body, "dragging");
// On leaving click, stop moving.
document.addEventListener("touchend", this.didEndDrag, {
@@ -71,7 +73,8 @@ export default class DDraggableModifier extends Modifier {
document.removeEventListener("mousemove", this.drag);
document.removeEventListener("dragover", this.drag);
- document.body.classList.remove("dragging");
+ this.#bodyClassLease?.release();
+ this.#bodyClassLease = null;
this.hasStarted = false;
}
}
@@ -86,6 +89,7 @@ export default class DDraggableModifier extends Modifier {
document.removeEventListener("mousemove", this.drag);
document.removeEventListener("touchmove", this.drag);
document.removeEventListener("dragover", this.drag);
- document.body.classList.remove("dragging");
+ this.#bodyClassLease?.release();
+ this.#bodyClassLease = null;
}
}
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-pointer-drag.ts b/frontend/discourse/app/ui-kit/modifiers/d-pointer-drag.ts
new file mode 100644
index 00000000000..6c498711b71
--- /dev/null
+++ b/frontend/discourse/app/ui-kit/modifiers/d-pointer-drag.ts
@@ -0,0 +1,548 @@
+import { registerDestructor } from "@ember/destroyable";
+import type Owner from "@ember/owner";
+import Modifier, { type ArgsFor } from "ember-modifier";
+import ElementClassLease from "discourse/lib/element-class-lease";
+
+/**
+ * The `touch-action` tokens `d-pointer-drag.scss` has a rule for. A token
+ * without one leaves the element at `auto`, so the two must move together.
+ */
+export type TouchActionToken =
+ | "none"
+ | "pan-x"
+ | "pan-y"
+ | "pinch-zoom"
+ | "manipulation";
+
+/**
+ * Suppressing every browser touch gesture suits a small handle, which is what
+ * most consumers of this are.
+ */
+const DEFAULT_TOUCH_ACTION: TouchActionToken = "none";
+
+interface DPointerDragSignature {
+ /** The element the gesture is bound to. */
+ Element: HTMLElement;
+ Args: {
+ Named: {
+ /**
+ * Capture origin state here. Return `false` to ABORT the gesture (e.g. an
+ * anchor isn't resolvable); any other return starts it. An exception thrown
+ * here is rethrown, having released the pointer capture and started no
+ * gesture.
+ */
+ onDragStart?: (event: PointerEvent) => boolean | void;
+
+ /**
+ * Compute and preview the new value. Only fires during an active gesture,
+ * and only once `threshold` has been exceeded.
+ */
+ onDrag?: (event: PointerEvent) => void;
+
+ /**
+ * Compute and commit the new value. Runs BEFORE the pointer capture is
+ * released. Fires for any release on this element, including one that
+ * never reached `threshold` and so saw no `onDrag` at all — read the
+ * pointer position rather than assuming movement happened.
+ */
+ onDragEnd?: (event: PointerEvent) => void;
+
+ /**
+ * Release any preview without committing. Neither this nor `onDragEnd`
+ * runs when the element is destroyed mid-gesture; see the modifier's own
+ * docs for what to do with state that outlives the handle.
+ */
+ onDragCancel?: (event: PointerEvent) => void;
+
+ /**
+ * A class toggled on the element for the gesture's duration. A single
+ * token: a value with whitespace in it is rejected by the DOM, which costs
+ * the drag its styling but leaves the gesture working.
+ */
+ draggingClass?: string;
+
+ /**
+ * A class held on `document.body` for the gesture's duration, for a cursor
+ * that has to survive the pointer leaving the handle. Whether that happens
+ * by itself is engine-dependent, so the rule cannot be left to the element.
+ * It reaches only what inherits `cursor`, so anything declaring its own
+ * still wins over it, and a gesture that must hold the cursor everywhere
+ * wants an overlay instead. Held by count, so two gestures asking for the
+ * same class both keep it until the last one ends.
+ *
+ * Reach for a class on a shared ancestor, not this, when the target is
+ * simply outside the dragged element's subtree — a sibling is still
+ * reachable from the parent the two have in common.
+ */
+ bodyClass?: string;
+
+ /**
+ * Pixels of travel, measured as a straight line from the press origin, that
+ * `onDrag` waits for before it starts firing. Reaching the distance is
+ * enough; it does not have to be exceeded. Suppresses the jitter of a click
+ * that was never meant to be a drag. Defaults to `0`. Read live until the
+ * distance is reached; only the latch is permanent, so raising it after
+ * movement has engaged will not re-suppress a gesture already under way.
+ */
+ threshold?: number;
+
+ /**
+ * Whether an accepted press also stops propagating. Defaults to `false`:
+ * document-level listeners (click-outside dismissal, card and menu closers)
+ * depend on seeing `pointerdown`, so suppression is opt-in for the handles
+ * that genuinely need to isolate themselves.
+ */
+ stopPropagation?: boolean;
+
+ /**
+ * Whether a gesture that ends without the pointer being released on this
+ * element — `pointercancel`, or the capture being taken away — commits via
+ * `onDragEnd` instead of discarding via `onDragCancel`. Defaults to
+ * `false`. A splitter wants `true`: an OS-interrupted resize should keep
+ * the size the user dragged to.
+ */
+ cancelCommits?: boolean;
+
+ /**
+ * Which browser touch gestures the element gives up, reflected as
+ * `data-pointer-drag` and mapped by
+ * `app/assets/stylesheets/common/ui-kit/d-pointer-drag.scss`. Defaults to
+ * `"none"`, which suits a small handle. Anything large enough that a user
+ * might start a scroll or a pinch-zoom on it wants `"pan-x"`, `"pan-y"`,
+ * `"pinch-zoom"` or `"manipulation"` instead.
+ *
+ * The union is closed against that stylesheet, so widen it only alongside
+ * a rule there: `touch-action` is not inherited, and a token with no rule
+ * behind it leaves the element at `auto`, where the browser claims the
+ * touch as a scroll and the gesture dies through `pointercancel`.
+ */
+ touchAction?: TouchActionToken;
+ };
+ Positional: [];
+ };
+}
+
+/**
+ * The gesture's named args, for a consumer driving {@link registerPointerDrag}
+ * imperatively rather than through the modifier.
+ */
+export type DPointerDragArgs = DPointerDragSignature["Args"]["Named"];
+
+/**
+ * The gesture holding each active pointer, keyed by `pointerId`, so a
+ * registration that loses a contested pointer can be told to stand down.
+ *
+ * Keyed per pointer rather than kept as a single current owner, because two
+ * gestures driven by two different pointers are both legitimately live.
+ *
+ * A pointer ID is a number, so this cannot be a `WeakMap`, and each entry holds
+ * its element: an entry left behind holds a detached element alive, and a
+ * later press reusing that ID would call into a registration that no longer
+ * exists. Removing an entry the moment its gesture ends is therefore load-bearing
+ * rather than housekeeping.
+ *
+ * The element is held beside the supersede callback so a claim rejected in the
+ * same dispatch — a veto, a throw — can hand the pending capture it displaced
+ * back to the entry's owner rather than releasing it into nothing.
+ */
+const pointerOwners = new Map<
+ number,
+ { element: HTMLElement; supersede: (event: PointerEvent) => void }
+>();
+
+/**
+ * Drops all pointer-ownership bookkeeping. For tests only: a consumer of
+ * {@link registerPointerDrag} that never invokes its cleanup would otherwise
+ * leave an entry behind that releases the next gesture to reuse that pointer ID.
+ */
+export function resetPointerDragForTesting() {
+ pointerOwners.clear();
+}
+
+/**
+ * Reflects the wanted `touch-action` onto the element for the stylesheet to
+ * pick up. Separate from the gesture registration because the declaration has to
+ * be in place before a touch begins, so it is refreshed whenever the args
+ * change rather than frozen when the gesture was installed.
+ *
+ * @param element - The element carrying the gesture.
+ * @param touchAction - A token the stylesheet maps; see its docs.
+ */
+function syncTouchAction(element: HTMLElement, touchAction?: TouchActionToken) {
+ element.setAttribute(
+ "data-pointer-drag",
+ touchAction ?? DEFAULT_TOUCH_ACTION
+ );
+}
+
+/**
+ * Wires the "press-drag-transform" pointer lifecycle to an element: the gesture
+ * class where the user presses, drags, and a value changes continuously with the
+ * pointer (resize handles, sliders, splitters, knobs). Used by the
+ * default-exported modifier below, and exported so a consumer can install the
+ * gesture imperatively when a template modifier does not fit.
+ *
+ * This is not a transfer operation: there is no drop target or payload. The
+ * `onDrag*` callback names describe this gesture's lifecycle (start, move, end,
+ * cancel).
+ *
+ * Unified Pointer Events with `setPointerCapture` cover mouse, touch and pen
+ * without per-input branching. Only the primary button starts a gesture, and
+ * every subsequent event must carry the same `pointerId`, so a second finger
+ * landing on the element cannot drive or end a gesture the first one owns.
+ *
+ * The lifecycle is owned here; everything domain-specific (what origin to
+ * capture, how to compute the next value, how to preview it, what to commit)
+ * stays in the caller's handlers.
+ *
+ * @param element - The element the gesture is bound to.
+ * @param getArgsRef - Closure returning the latest args, read on every event so
+ * arg changes take effect without re-registering.
+ * @returns Cleanup function. Releases an in-flight capture, so a gesture
+ * interrupted by teardown does not strand the pointer. Caller invokes it once
+ * on teardown.
+ */
+export function registerPointerDrag(
+ element: HTMLElement,
+ getArgsRef: () => DPointerDragArgs
+) {
+ let pointerId: number | null = null;
+ let originX = 0;
+ let originY = 0;
+ // Latches true once the pointer has reached `threshold`, and stays true for
+ // the rest of the gesture: returning inside the threshold must not start
+ // suppressing movement again mid-drag.
+ let engaged = false;
+ // The class actually added at the start of this gesture. `draggingClass` can
+ // change between gestures, so the value really on the element is snapshotted
+ // rather than re-read when it is time to remove it.
+ let appliedClass: string | null = null;
+ let bodyClassLease: ElementClassLease | null = null;
+ // Set by the cleanup below. A consumer can destroy its own registration from
+ // inside `onDragStart`, and the rest of that dispatch still runs.
+ let tornDown = false;
+
+ const finish = () => {
+ const finishedPointer = pointerId;
+ const classToRemove = appliedClass;
+ const finishedBodyClassLease = bodyClassLease;
+
+ // Reset before touching the DOM: either call below can throw, and leaving
+ // `pointerId` set would keep the gesture in flight forever.
+ pointerId = null;
+ engaged = false;
+ appliedClass = null;
+ bodyClassLease = null;
+
+ if (finishedPointer !== null) {
+ // Only while the claim is still ours: a later claimant owns the entry from
+ // the moment it supersedes us, and must not have it deleted underneath it.
+ if (pointerOwners.get(finishedPointer)?.supersede === onSuperseded) {
+ pointerOwners.delete(finishedPointer);
+ }
+ try {
+ element.releasePointerCapture(finishedPointer);
+ } catch {
+ // Already released if the element was removed mid-gesture.
+ }
+ }
+ if (classToRemove) {
+ // Unguarded: `appliedClass` is only ever set to a token `classList.add`
+ // already accepted, and `remove` rejects exactly what `add` rejects.
+ element.classList.remove(classToRemove);
+ }
+ finishedBodyClassLease?.release();
+ };
+
+ /**
+ * Ends the gesture the way the caller asked cancellation to behave. Shared by
+ * `pointercancel` and by losing the capture, which are the same situation: the
+ * gesture is over without the pointer having been released on this element.
+ *
+ * @param args - The current args.
+ * @param event - The event ending the gesture.
+ */
+ const cancelGesture = (args: DPointerDragArgs, event: PointerEvent) => {
+ try {
+ if (args.cancelCommits) {
+ args.onDragEnd?.(event);
+ } else {
+ args.onDragCancel?.(event);
+ }
+ } finally {
+ finish();
+ }
+ };
+
+ /**
+ * Ends this gesture because another registration has claimed the pointer it
+ * was holding. Routed through `cancelGesture` so `cancelCommits` decides how
+ * it reports, like any other end that is not a release on this element.
+ *
+ * Doubles as this registration's identity in `pointerOwners`: one stable
+ * function per registration, so an entry can only be removed by its owner.
+ *
+ * @param event - The press that claimed the pointer away.
+ */
+ const onSuperseded = (event: PointerEvent) => {
+ cancelGesture(getArgsRef(), event);
+ };
+
+ const onPointerDown = (event: PointerEvent) => {
+ // Never take over a gesture already in flight: doing so would overwrite the
+ // tracked pointer and strand the first one's capture.
+ if (event.button !== 0 || pointerId !== null) {
+ return;
+ }
+ // Capture first, before telling anyone a gesture started. Capture is what
+ // routes the rest of the gesture back to this element, so without it a
+ // pointer leaving the element would never deliver its release and the
+ // in-flight guard would then reject every later press. Abort rather than
+ // begin a gesture that cannot finish.
+ try {
+ element.setPointerCapture(event.pointerId);
+ } catch {
+ return;
+ }
+
+ const releaseCapture = () => {
+ try {
+ element.releasePointerCapture(event.pointerId);
+ } catch {
+ // Already gone if the element was detached in between.
+ }
+ };
+
+ // For a claim rejected during its own dispatch. The `setPointerCapture`
+ // above displaced any earlier claimant's pending capture, so a plain
+ // release here would clear the override entirely and leave that claimant's
+ // live gesture uncaptured — latched until some later press happens to
+ // supersede it, which a touch pointer's unreused ID never does. Handing the
+ // capture back is the only exit that keeps the one-terminal-callback
+ // guarantee; releasing is only right when there was no one to displace.
+ const restoreDisplacedCapture = () => {
+ const prior = pointerOwners.get(event.pointerId);
+ if (!prior) {
+ releaseCapture();
+ return;
+ }
+ try {
+ prior.element.setPointerCapture(event.pointerId);
+ } catch {
+ // The prior claimant's element is gone; nothing to hand back.
+ releaseCapture();
+ }
+ };
+
+ const args = getArgsRef();
+ // The caller captures its origin state here and may veto by returning false.
+ let vetoed;
+ try {
+ vetoed = args.onDragStart?.(event) === false;
+ } catch (error) {
+ // Rethrown, because a throwing consumer is the consumer's bug. The capture
+ // still has to go back: nothing else would release it.
+ restoreDisplacedCapture();
+ throw error;
+ }
+ // A registration torn down by its own `onDragStart` has already had its
+ // listeners removed, so nothing is left to end a gesture installed now — and
+ // claiming the pointer would leave an entry no one can remove.
+ if (vetoed || tornDown) {
+ restoreDisplacedCapture();
+ return;
+ }
+
+ pointerId = event.pointerId;
+ originX = event.clientX;
+ originY = event.clientY;
+ engaged = !(args.threshold > 0);
+
+ // A press bubbles, so an ancestor registration starts its own gesture from
+ // the same event. Capture requested during `pointerdown` is only pending
+ // until the dispatch ends and the last request wins, so the earlier claimant
+ // keeps none of it and receives no terminal event at all — its in-flight
+ // guard would then reject every later press. Tracked here rather than read
+ // back through `hasPointerCapture`, which cannot tell a lost claim apart from
+ // a pointer that was never real.
+ const superseded = pointerOwners.get(event.pointerId);
+ pointerOwners.set(event.pointerId, { element, supersede: onSuperseded });
+
+ if (args.draggingClass) {
+ try {
+ element.classList.add(args.draggingClass);
+ // Only once it is really on the element, so `finish` never tries to
+ // remove a token the DOM rejected.
+ appliedClass = args.draggingClass;
+ } catch {
+ // A whitespace token is a caller mistake: it costs the drag its styling
+ // but must not abort the gesture.
+ }
+ }
+ if (args.bodyClass) {
+ try {
+ bodyClassLease = new ElementClassLease(document.body, args.bodyClass);
+ } catch {
+ // Same as above: a rejected token costs the page-level styling only.
+ }
+ }
+
+ // Only an accepted press is suppressed. A secondary button, a press during
+ // an active gesture, or a vetoed one must reach whatever else was listening.
+ event.preventDefault();
+ if (args.stopPropagation) {
+ event.stopPropagation();
+ }
+
+ // Last, so this gesture is fully established before control passes to another
+ // consumer's callback, which is free to throw.
+ superseded?.supersede(event);
+ };
+
+ const onPointerMove = (event: PointerEvent) => {
+ if (pointerId === null || event.pointerId !== pointerId) {
+ return;
+ }
+ const args = getArgsRef();
+ if (!engaged) {
+ const threshold = args.threshold ?? 0;
+ if (
+ Math.hypot(event.clientX - originX, event.clientY - originY) < threshold
+ ) {
+ return;
+ }
+ engaged = true;
+ }
+ args.onDrag?.(event);
+ };
+
+ const onPointerUp = (event: PointerEvent) => {
+ if (pointerId === null || event.pointerId !== pointerId) {
+ return;
+ }
+ // Commit before releasing capture, so the caller sees a consistent gesture
+ // state while it reads the final value. Finalised in a `finally` so a
+ // throwing callback cannot leave the gesture active and reject every later
+ // press.
+ try {
+ getArgsRef().onDragEnd?.(event);
+ } finally {
+ finish();
+ }
+ };
+
+ const onPointerCancel = (event: PointerEvent) => {
+ if (pointerId === null || event.pointerId !== pointerId) {
+ return;
+ }
+ cancelGesture(getArgsRef(), event);
+ };
+
+ const onLostPointerCapture = (event: PointerEvent) => {
+ if (pointerId === null || event.pointerId !== pointerId) {
+ return;
+ }
+ // Once capture is gone, a pointer no longer over this element delivers its
+ // release somewhere else, so this is the last event to arrive and a gesture
+ // not ended here stays in flight forever. A normal release fires this too,
+ // but after `pointerup` cleared the state, so the guard above no-ops it.
+ cancelGesture(getArgsRef(), event);
+ };
+
+ // `touch-action` has to be in effect before the gesture starts, or the browser
+ // has already claimed the touch as a scroll. Expressed as an attribute the
+ // stylesheet maps, rather than an inline style, because consumers bind `style`
+ // and would clobber it. Refreshed by `syncTouchAction` so a consumer that
+ // changes orientation between gestures is not stuck with the first value.
+ syncTouchAction(element, getArgsRef().touchAction);
+
+ element.addEventListener("pointerdown", onPointerDown);
+ element.addEventListener("pointermove", onPointerMove);
+ element.addEventListener("pointerup", onPointerUp);
+ element.addEventListener("pointercancel", onPointerCancel);
+ element.addEventListener("lostpointercapture", onLostPointerCapture);
+
+ return () => {
+ tornDown = true;
+ finish();
+ element.removeEventListener("pointerdown", onPointerDown);
+ element.removeEventListener("pointermove", onPointerMove);
+ element.removeEventListener("pointerup", onPointerUp);
+ element.removeEventListener("pointercancel", onPointerCancel);
+ element.removeEventListener("lostpointercapture", onLostPointerCapture);
+ element.removeAttribute("data-pointer-drag");
+ };
+}
+
+/**
+ * Binds the press-drag-transform gesture to an element. Thin Ember-modifier
+ * wrapper around {@link registerPointerDrag}. Every arg is optional and
+ * documented on {@link DPointerDragArgs}.
+ *
+ * @example
+ * ```gjs
+ * <span {{dPointerDrag
+ * onDragStart=this.onDragStart
+ * onDrag=this.onDrag
+ * onDragEnd=this.onDragEnd
+ * onDragCancel=this.onDragCancel
+ * draggingClass="--dragging"
+ * }} />
+ * ```
+ *
+ * A press never moves focus. Cancelling `pointerdown` suppresses the compatibility
+ * `mousedown` that focus rides on, and that suppression is kept: a handle usually
+ * sits beside the thing it resizes or reorders, so taking focus on press would pull
+ * the caret out of whatever the user was working in. Give the handle its own tab
+ * stop when it has a keyboard path worth reaching — that is how it stays operable,
+ * not by claiming focus from a gesture assistive technology cannot perform.
+ *
+ * That cancellation reaches further than focus: an accepted press produces no
+ * `mousedown` or `mouseup`, so a document-level listener on either never sees it.
+ * Build dismiss-on-outside-press on `pointerdown`, which still bubbles unless
+ * `stopPropagation` is set.
+ *
+ * A single element supports one registration. Two would each claim the same
+ * pointer capture and the same attribute, and tearing either down would strand
+ * the other's gesture.
+ *
+ * Nesting one registration inside another is supported, but only one of them can
+ * hold a given press: the ancestor sees it too, and whichever claims the pointer
+ * last keeps it. The other is ended immediately through `onDragCancel` (or
+ * `onDragEnd` under `cancelCommits`) with the same press as its event, so a
+ * contested press still leaves each consumer with one terminal callback for the
+ * `onDragStart` it received. Pass `stopPropagation` on the inner registration when
+ * the press should not reach the ancestor at all.
+ *
+ * The one end that reports nothing is teardown: destroying the element mid-gesture
+ * releases the capture and drops the classes but fires no terminal callback, since
+ * one would run against a consumer already being torn down. Release gesture state
+ * that outlives the handle from the consumer's own destructor instead.
+ */
+export default class DPointerDragModifier extends Modifier<DPointerDragSignature> {
+ #args: DPointerDragArgs | null = null;
+ #cleanup: (() => void) | null = null;
+
+ constructor(owner: Owner, args: ArgsFor<DPointerDragSignature>) {
+ super(owner, args);
+ registerDestructor(this, (instance) => instance.#teardown());
+ }
+
+ modify(element: HTMLElement, _positional: [], named: DPointerDragArgs) {
+ // Refreshed every run so arg changes are picked up; the gesture itself is
+ // installed once and reads these live.
+ this.#args = named;
+
+ this.#cleanup ??= registerPointerDrag(element, () => this.#args);
+
+ // Re-reflected here rather than only at registration: the declaration has to
+ // be in place before a touch begins, so a consumer that changes it between
+ // gestures needs the next one to see the new value.
+ syncTouchAction(element, named.touchAction);
+ }
+
+ #teardown() {
+ this.#cleanup?.();
+ this.#cleanup = null;
+ }
+}
diff --git a/frontend/discourse/tests/helpers/qunit-helpers.js b/frontend/discourse/tests/helpers/qunit-helpers.js
index 07b9520aec5..c4b18f09e07 100644
--- a/frontend/discourse/tests/helpers/qunit-helpers.js
+++ b/frontend/discourse/tests/helpers/qunit-helpers.js
@@ -49,6 +49,7 @@ import deprecated, { clearBacklog } from "discourse/lib/deprecated";
import { clearDesktopNotificationHandlers } from "discourse/lib/desktop-notifications";
import { visible as isVisible } from "discourse/lib/dom-utils";
import { clearRegisteredEditCategoryTabs } from "discourse/lib/edit-category-tabs";
+import { resetElementClassLeasesForTesting } from "discourse/lib/element-class-lease";
import { getOwnerWithFallback } from "discourse/lib/get-owner";
import { restoreBaseUri } from "discourse/lib/get-url";
import { cleanUpHashtagTypeClasses } from "discourse/lib/hashtag-type-registry";
@@ -113,6 +114,7 @@ import {
} from "discourse/tests/helpers/site-settings";
import { resetHtmlDecorators } from "discourse/ui-kit/d-decorated-html";
import { clearToolbarCallbacks } from "discourse/ui-kit/d-editor";
+import { resetPointerDragForTesting } from "discourse/ui-kit/modifiers/d-pointer-drag";
import I18n from "discourse-i18n";
import { setupDSelectAssertions } from "./d-select-assertions";
import { setupFormKitAssertions } from "./form-kit-assertions";
@@ -288,6 +290,8 @@ export function testCleanup(container, app) {
_resetOutletLayoutsForTesting();
resetBlockRegistryForTesting();
resetDebugCallbacks();
+ resetPointerDragForTesting();
+ resetElementClassLeasesForTesting();
clearBacklog();
}
diff --git a/frontend/discourse/tests/helpers/ui-kit/pointer-gesture-helper.ts b/frontend/discourse/tests/helpers/ui-kit/pointer-gesture-helper.ts
new file mode 100644
index 00000000000..dddd9fd6a7a
--- /dev/null
+++ b/frontend/discourse/tests/helpers/ui-kit/pointer-gesture-helper.ts
@@ -0,0 +1,78 @@
+import { find } from "@ember/test-helpers";
+
+/**
+ * Makes an element accept pointer capture for a pointer that was never real.
+ *
+ * The gesture engine captures the pointer before telling anyone a drag started, and
+ * aborts if that fails — deliberately, since a gesture that cannot receive its own
+ * release would strand itself. A browser rejects `setPointerCapture` for a synthetic
+ * pointer ID, so without this every synthetic drag stops at the press, silently and
+ * with nothing to indicate why.
+ *
+ * `captured` and `released` are exposed for the tests that assert the capture itself
+ * was taken and given back; most callers only need the side effect.
+ *
+ * @param target - The element that will receive the press, or a selector for it.
+ * @returns The element, the pointer IDs it currently holds, and those it has given
+ * back in order.
+ */
+export function stubPointerCapture(target: string | HTMLElement) {
+ // `find` is typed as possibly missing the element; a test naming one that is
+ // not rendered is a test bug, and failing on the next line says so directly.
+ const element = (
+ typeof target === "string" ? find(target) : target
+ ) as HTMLElement;
+ const captured = new Set<number>();
+ const released: number[] = [];
+
+ element.setPointerCapture = (pointerId) => captured.add(pointerId);
+ element.hasPointerCapture = (pointerId) => captured.has(pointerId);
+ element.releasePointerCapture = (pointerId) => {
+ captured.delete(pointerId);
+ released.push(pointerId);
+ };
+
+ return { element, captured, released };
+}
+
+/**
+ * Like {@link stubPointerCapture}, but models the browser's one pending
+ * capture override per pointer across a set of elements.
+ *
+ * The per-element stub gives each element an independent record, so it cannot
+ * express displacement: in a real browser a second element's
+ * `setPointerCapture` during the same dispatch replaces the first's pending
+ * override, and a release by the displacing element clears the override
+ * entirely. Tests about contested claims on one bubbling press need exactly
+ * that shape — who ends up owning the pointer is the assertion.
+ *
+ * @param targets - The elements contending for capture, or selectors for them.
+ * @returns Per-element records in input order, and `ownerOf` to ask which
+ * element currently holds a pointer's capture.
+ */
+export function stubSharedPointerCapture(targets: (string | HTMLElement)[]) {
+ const owners = new Map<number, HTMLElement>();
+ const stubs = targets.map((target) => {
+ const element = (
+ typeof target === "string" ? find(target) : target
+ ) as HTMLElement;
+ const released: number[] = [];
+ element.setPointerCapture = (pointerId) => owners.set(pointerId, element);
+ element.hasPointerCapture = (pointerId) =>
+ owners.get(pointerId) === element;
+ element.releasePointerCapture = (pointerId) => {
+ // A release only clears the override the caller holds, as in the spec: a
+ // displaced claimant releasing changes nothing.
+ if (owners.get(pointerId) === element) {
+ owners.delete(pointerId);
+ }
+ released.push(pointerId);
+ };
+ return { element, released };
+ });
+
+ return {
+ stubs,
+ ownerOf: (pointerId: number) => owners.get(pointerId) ?? null,
+ };
+}
diff --git a/frontend/discourse/tests/integration/components/dev-tools-toolbar-test.gjs b/frontend/discourse/tests/integration/components/dev-tools-toolbar-test.gjs
new file mode 100644
index 00000000000..82426f22cae
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/dev-tools-toolbar-test.gjs
@@ -0,0 +1,185 @@
+import { find, render, triggerEvent } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import Toolbar from "discourse/static/dev-tools/toolbar";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import { stubPointerCapture } from "discourse/tests/helpers/ui-kit/pointer-gesture-helper";
+
+/**
+ * The toolbar positions itself with `top: min(100dvh - <own height>px, <top>px)`,
+ * so the tracked value is read back out of the declaration rather than guessed at.
+ *
+ * @returns {number} The pixel value the toolbar last wrote for its own top.
+ */
+function declaredTop() {
+ const style = find(".dev-tools-toolbar").getAttribute("style");
+ return parseFloat(style.match(/,\s*(-?[\d.]+)px\)/)[1]);
+}
+
+module("Integration | Component | DevTools | Toolbar", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("dragging the gripper moves the toolbar by the pointer's travel", async function (assert) {
+ await render(<template><Toolbar /></template>);
+
+ const gripper = find(".dev-tools-toolbar .gripper");
+ stubPointerCapture(gripper);
+ // Where the toolbar actually sits, so the grab offset can be asserted rather
+ // than cancelled out by comparing two dragged positions.
+ const realTop = find(".dev-tools-toolbar").getBoundingClientRect().top;
+
+ await triggerEvent(gripper, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientX: 10,
+ clientY: 300,
+ pageX: 10,
+ pageY: 300,
+ });
+ await triggerEvent(gripper, "pointermove", {
+ pointerId: 1,
+ clientX: 10,
+ clientY: 340,
+ pageX: 10,
+ pageY: 340,
+ });
+ const settled = declaredTop();
+
+ assert.strictEqual(
+ settled,
+ realTop + 40,
+ "the toolbar keeps the offset it was grabbed at, so it follows the pointer from where the user picked it up rather than jumping its edge to the cursor"
+ );
+
+ await triggerEvent(gripper, "pointermove", {
+ pointerId: 1,
+ clientX: 10,
+ clientY: 380,
+ pageX: 10,
+ pageY: 380,
+ });
+
+ assert.strictEqual(
+ declaredTop() - settled,
+ 40,
+ "further travel moves the toolbar one pixel per pixel"
+ );
+
+ await triggerEvent(gripper, "pointerup", {
+ pointerId: 1,
+ clientX: 10,
+ clientY: 340,
+ pageX: 10,
+ pageY: 340,
+ });
+ assert
+ .dom(".dev-tools-toolbar")
+ .doesNotHaveClass(
+ "--dragging",
+ "releasing the pointer ends the drag session"
+ );
+ });
+
+ test("the gripper is marked as dragging only while the pointer is down", async function (assert) {
+ await render(<template><Toolbar /></template>);
+
+ const gripper = find(".dev-tools-toolbar .gripper");
+ stubPointerCapture(gripper);
+
+ assert
+ .dom(".dev-tools-toolbar")
+ .doesNotHaveClass("--dragging", "idle to begin with");
+
+ await triggerEvent(gripper, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientX: 10,
+ clientY: 300,
+ pageX: 10,
+ pageY: 300,
+ });
+
+ assert
+ .dom(".dev-tools-toolbar")
+ .hasClass("--dragging", "a press opens a drag session");
+ assert
+ .dom(document.body)
+ .hasClass("dragging", "and marks the page so the cursor holds");
+
+ await triggerEvent(gripper, "pointerup", {
+ pointerId: 1,
+ clientX: 10,
+ clientY: 300,
+ pageX: 10,
+ pageY: 300,
+ });
+
+ assert
+ .dom(document.body)
+ .doesNotHaveClass("dragging", "the page mark is given back on release");
+ });
+
+ test("grabbing the toolbar at its exact top edge still opens a drag session", async function (assert) {
+ await render(<template><Toolbar /></template>);
+
+ const gripper = find(".dev-tools-toolbar .gripper");
+ stubPointerCapture(gripper);
+ // A press here yields a grab offset of exactly 0, which is the value a
+ // truthiness check on the offset silently reads as "not dragging".
+ const realTop = find(".dev-tools-toolbar").getBoundingClientRect().top;
+
+ await triggerEvent(gripper, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientX: 10,
+ clientY: realTop,
+ pageX: 10,
+ pageY: realTop,
+ });
+
+ assert
+ .dom(".dev-tools-toolbar")
+ .hasClass("--dragging", "a zero grab offset is still a live drag");
+
+ await triggerEvent(gripper, "pointerup", {
+ pointerId: 1,
+ clientX: 10,
+ clientY: realTop,
+ pageX: 10,
+ pageY: realTop,
+ });
+
+ assert
+ .dom(".dev-tools-toolbar")
+ .doesNotHaveClass("--dragging", "and it still closes on release");
+ });
+
+ test("a cancelled gesture closes the drag session too", async function (assert) {
+ await render(<template><Toolbar /></template>);
+
+ const gripper = find(".dev-tools-toolbar .gripper");
+ stubPointerCapture(gripper);
+
+ await triggerEvent(gripper, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientX: 10,
+ clientY: 300,
+ pageX: 10,
+ pageY: 300,
+ });
+ await triggerEvent(gripper, "pointercancel", { pointerId: 1 });
+
+ assert
+ .dom(".dev-tools-toolbar")
+ .doesNotHaveClass(
+ "--dragging",
+ "an interrupted gesture does not leave the toolbar stuck dragging"
+ );
+ assert
+ .dom(document.body)
+ .doesNotHaveClass(
+ "dragging",
+ "the cancelled gesture releases the page mark"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-pointer-drag-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-pointer-drag-test.gjs
new file mode 100644
index 00000000000..5d5858fe244
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-pointer-drag-test.gjs
@@ -0,0 +1,1615 @@
+import { tracked } from "@glimmer/tracking";
+import {
+ clearRender,
+ find,
+ render,
+ settled,
+ triggerEvent,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ stubPointerCapture,
+ stubSharedPointerCapture,
+} from "discourse/tests/helpers/ui-kit/pointer-gesture-helper";
+import dDraggable from "discourse/ui-kit/modifiers/d-draggable";
+import dPointerDrag, * as dPointerDragModule from "discourse/ui-kit/modifiers/d-pointer-drag";
+
+function installEventListenerSpy(element) {
+ const added = [];
+ const listeners = new Map();
+ const removed = [];
+ const addEventListener = element.addEventListener.bind(element);
+ const removeEventListener = element.removeEventListener.bind(element);
+
+ element.addEventListener = (type, listener, options) => {
+ added.push(type);
+ listeners.set(type, listener);
+ addEventListener(type, listener, options);
+ };
+ element.removeEventListener = (type, listener, options) => {
+ removed.push(type);
+ removeEventListener(type, listener, options);
+ };
+
+ return { added, listeners, removed };
+}
+
+function caughtError(callback) {
+ try {
+ callback();
+ } catch (error) {
+ return error;
+ }
+}
+
+module("Integration | ui-kit | d-pointer-drag", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("dispatches start → drag → end and toggles the dragging class", async function (assert) {
+ const calls = [];
+ const onDragStart = () => calls.push("start");
+ const onDrag = (event) => calls.push(`drag:${event.clientX}`);
+ const onDragEnd = () => calls.push("end");
+
+ await render(
+ <template>
+ <div
+ class="dpd-target"
+ {{dPointerDrag
+ onDragStart=onDragStart
+ onDrag=onDrag
+ onDragEnd=onDragEnd
+ draggingClass="--dragging"
+ }}
+ ></div>
+ </template>
+ );
+
+ await triggerEvent(".dpd-target", "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientX: 0,
+ clientY: 0,
+ });
+ assert
+ .dom(".dpd-target")
+ .hasClass("--dragging", "adds the dragging class on a started press");
+
+ await triggerEvent(".dpd-target", "pointermove", {
+ pointerId: 1,
+ clientX: 12,
+ clientY: 0,
+ });
+ await triggerEvent(".dpd-target", "pointerup", {
+ pointerId: 1,
+ clientX: 12,
+ clientY: 0,
+ });
+
+ assert.deepEqual(
+ calls,
+ ["start", "drag:12", "end"],
+ "fires the lifecycle in order"
+ );
+ assert
+ .dom(".dpd-target")
+ .doesNotHaveClass("--dragging", "removes the dragging class on release");
+ });
+
+ test("ignores non-primary buttons", async function (assert) {
+ const calls = [];
+ const onDragStart = () => calls.push("start");
+
+ await render(
+ <template>
+ <div class="dpd-target" {{dPointerDrag onDragStart=onDragStart}}></div>
+ </template>
+ );
+
+ await triggerEvent(".dpd-target", "pointerdown", {
+ button: 2,
+ pointerId: 1,
+ });
+ assert.deepEqual(
+ calls,
+ [],
+ "a secondary-button press does not start a drag"
+ );
+ });
+
+ test("a second pointer cannot take over a gesture already in flight", async function (assert) {
+ const calls = [];
+ const onDragStart = (event) => calls.push(`start:${event.pointerId}`);
+ const onDrag = (event) => calls.push(`drag:${event.pointerId}`);
+ const onDragEnd = (event) => calls.push(`end:${event.pointerId}`);
+
+ await render(
+ <template>
+ <div
+ class="dpd-target"
+ {{dPointerDrag
+ onDragStart=onDragStart
+ onDrag=onDrag
+ onDragEnd=onDragEnd
+ }}
+ ></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ const capture = stubPointerCapture(target);
+ const prevented = [];
+ const record = (event) => prevented.push(event.defaultPrevented);
+ document.addEventListener("pointerdown", record);
+
+ try {
+ await triggerEvent(target, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientX: 0,
+ clientY: 0,
+ });
+ await triggerEvent(target, "pointerdown", {
+ button: 0,
+ pointerId: 2,
+ clientX: 50,
+ clientY: 50,
+ });
+ await triggerEvent(target, "pointermove", {
+ pointerId: 2,
+ clientX: 60,
+ clientY: 60,
+ });
+ await triggerEvent(target, "pointerup", { pointerId: 2 });
+
+ await triggerEvent(target, "pointermove", {
+ pointerId: 1,
+ clientX: 10,
+ clientY: 0,
+ });
+ await triggerEvent(target, "pointerup", { pointerId: 1 });
+ } finally {
+ document.removeEventListener("pointerdown", record);
+ }
+
+ assert.deepEqual(
+ calls,
+ ["start:1", "drag:1", "end:1"],
+ "the second pointer neither starts, drives nor ends the gesture the first one owns"
+ );
+ assert.deepEqual(
+ prevented,
+ [true, false],
+ "the rejected second press is left for whatever else was listening"
+ );
+ assert.deepEqual(
+ capture.released,
+ [1],
+ "the interloper never captured, so only the owning pointer is released"
+ );
+ });
+
+ test("onDragStart can veto the drag", async function (assert) {
+ const calls = [];
+ const onDragStart = () => {
+ calls.push("start");
+ return false;
+ };
+ const onDrag = () => calls.push("drag");
+
+ await render(
+ <template>
+ <div
+ class="dpd-target"
+ {{dPointerDrag onDragStart=onDragStart onDrag=onDrag}}
+ ></div>
+ </template>
+ );
+
+ await triggerEvent(".dpd-target", "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientX: 0,
+ });
+ await triggerEvent(".dpd-target", "pointermove", {
+ pointerId: 1,
+ clientX: 5,
+ });
+
+ assert.deepEqual(
+ calls,
+ ["start"],
+ "a false return from onDragStart aborts the drag; no drag fires"
+ );
+ });
+
+ module("press suppression", function (suppressionHooks) {
+ // Focus is deliberately not asserted here: `triggerEvent` dispatches an
+ // untrusted event, no compatibility `mousedown` follows it, and so focus stays
+ // put however the modifier behaves. Assert what the modifier owns, which is
+ // whether it cancels the press; focus itself needs a system spec.
+ let prevented;
+ let record;
+
+ suppressionHooks.beforeEach(function () {
+ prevented = [];
+ record = (event) => prevented.push(event.defaultPrevented);
+ document.addEventListener("pointerdown", record);
+ });
+
+ suppressionHooks.afterEach(function () {
+ document.removeEventListener("pointerdown", record);
+ });
+
+ test("an accepted press is cancelled", async function (assert) {
+ const onDragStart = () => {};
+
+ await render(
+ <template>
+ <button
+ type="button"
+ class="dpd-target"
+ {{dPointerDrag onDragStart=onDragStart}}
+ ></button>
+ </template>
+ );
+ stubPointerCapture(".dpd-target");
+
+ await triggerEvent(".dpd-target", "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ });
+
+ assert.deepEqual(
+ prevented,
+ [true],
+ "cancelling the press is what stops the compatibility mousedown, and with it the focus that would pull the caret out of whatever the user was working in"
+ );
+ });
+
+ test("a press that starts no gesture is left for other listeners", async function (assert) {
+ const vetoed = () => false;
+
+ await render(
+ <template>
+ <button
+ type="button"
+ class="dpd-secondary"
+ {{dPointerDrag onDragStart=vetoed}}
+ ></button>
+ <button
+ type="button"
+ class="dpd-vetoed"
+ {{dPointerDrag onDragStart=vetoed}}
+ ></button>
+ </template>
+ );
+ stubPointerCapture(".dpd-secondary");
+ stubPointerCapture(".dpd-vetoed");
+
+ await triggerEvent(".dpd-secondary", "pointerdown", {
+ button: 2,
+ pointerId: 1,
+ });
+ await triggerEvent(".dpd-vetoed", "pointerdown", {
+ button: 0,
+ pointerId: 2,
+ });
+
+ assert.deepEqual(
+ prevented,
+ [false, false],
+ "a secondary-button press and a vetoed one both reach document-level listeners"
+ );
+ });
+ });
+
+ module("configurable pointer lifecycle", function () {
+ test("exports registerPointerDrag for lifecycle reuse", function (assert) {
+ assert.strictEqual(
+ typeof dPointerDragModule.registerPointerDrag,
+ "function",
+ "consumers can share the pointer lifecycle without installing the modifier"
+ );
+ });
+
+ test("a pointer capture failure does not block a later press", async function (assert) {
+ const starts = [];
+ const onDragStart = (event) => starts.push(event.pointerId);
+
+ await render(
+ <template>
+ <div
+ class="dpd-target"
+ {{dPointerDrag onDragStart=onDragStart}}
+ ></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ target.setPointerCapture = (pointerId) => {
+ // Force the failure: a browser may treat a synthetic pointer ID as an
+ // active mouse, so relying on an ambient NotFoundError is unstable.
+ if (pointerId === 1) {
+ throw new DOMException("No active pointer", "NotFoundError");
+ }
+ };
+
+ await triggerEvent(target, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ });
+ await triggerEvent(target, "pointerdown", {
+ button: 0,
+ pointerId: 2,
+ });
+
+ assert.deepEqual(
+ starts,
+ [2],
+ "only the later press starts after pointer capture fails"
+ );
+ });
+
+ test("a throwing onDragStart releases capture, rethrows, and permits a later press", function (assert) {
+ const target = document.createElement("div");
+ const capture = stubPointerCapture(target);
+ const events = installEventListenerSpy(target);
+ const starts = [];
+ const error = new Error("consumer start failed");
+ const cleanup = dPointerDragModule.registerPointerDrag(target, () => ({
+ onDragStart(event) {
+ starts.push(event.pointerId);
+ if (event.pointerId === 1) {
+ throw error;
+ }
+ },
+ }));
+
+ assert.throws(
+ () =>
+ events.listeners.get("pointerdown")(
+ new PointerEvent("pointerdown", { button: 0, pointerId: 1 })
+ ),
+ error,
+ "the consumer error is rethrown"
+ );
+ assert.false(
+ capture.captured.has(1),
+ "a throwing start does not strand its pointer capture"
+ );
+
+ events.listeners.get("pointerdown")(
+ new PointerEvent("pointerdown", { button: 0, pointerId: 2 })
+ );
+
+ assert.deepEqual(
+ starts,
+ [1, 2],
+ "a later press can start after the throwing callback"
+ );
+
+ cleanup();
+ });
+
+ test("threshold suppresses movement until the distance is reached, then stays engaged", async function (assert) {
+ const moves = [];
+ const onDrag = (event) => moves.push(event.clientX);
+
+ await render(
+ <template>
+ <div
+ class="dpd-target"
+ {{dPointerDrag threshold=5 onDrag=onDrag}}
+ ></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ stubPointerCapture(target);
+
+ await triggerEvent(target, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientX: 0,
+ clientY: 0,
+ });
+ await triggerEvent(target, "pointermove", {
+ pointerId: 1,
+ clientX: 4,
+ clientY: 0,
+ });
+ // Exactly the threshold. Reaching the distance is enough, so this must
+ // engage; sampling only 4 and 6 would leave `<=` passing just as well.
+ await triggerEvent(target, "pointermove", {
+ pointerId: 1,
+ clientX: 5,
+ clientY: 0,
+ });
+ await triggerEvent(target, "pointermove", {
+ pointerId: 1,
+ clientX: 6,
+ clientY: 0,
+ });
+ await triggerEvent(target, "pointermove", {
+ pointerId: 1,
+ clientX: 2,
+ clientY: 0,
+ });
+
+ assert.deepEqual(
+ moves,
+ [5, 6, 2],
+ "a below-threshold move is suppressed, a move exactly at the threshold engages, and later moves remain engaged"
+ );
+ });
+
+ test("a press released below the threshold still ends the gesture", async function (assert) {
+ const calls = [];
+ const onDragStart = () => calls.push("start");
+ const onDrag = (event) => calls.push(`drag:${event.clientX}`);
+ const onDragEnd = (event) => calls.push(`end:${event.clientX}`);
+
+ await render(
+ <template>
+ <div
+ class="dpd-target"
+ {{dPointerDrag
+ threshold=5
+ onDragStart=onDragStart
+ onDrag=onDrag
+ onDragEnd=onDragEnd
+ }}
+ ></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ stubPointerCapture(target);
+
+ await triggerEvent(target, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ clientX: 0,
+ clientY: 0,
+ });
+ await triggerEvent(target, "pointermove", {
+ pointerId: 1,
+ clientX: 2,
+ clientY: 0,
+ });
+ await triggerEvent(target, "pointerup", {
+ pointerId: 1,
+ clientX: 2,
+ clientY: 0,
+ });
+
+ assert.deepEqual(
+ calls,
+ ["start", "end:2"],
+ "the threshold gates onDrag only: a click on a thresholded handle still commits, so a consumer must read the position rather than assume movement"
+ );
+ });
+
+ test("stopPropagation defaults off and can be enabled", async function (assert) {
+ const ancestorEvents = [];
+ const prevented = [];
+
+ await render(
+ <template>
+ <div class="dpd-ancestor">
+ <div class="dpd-default" {{dPointerDrag}}></div>
+ <div
+ class="dpd-stopped"
+ {{dPointerDrag stopPropagation=true}}
+ ></div>
+ </div>
+ </template>
+ );
+
+ const ancestor = find(".dpd-ancestor");
+ const defaultTarget = find(".dpd-default");
+ const stoppedTarget = find(".dpd-stopped");
+ stubPointerCapture(defaultTarget);
+ stubPointerCapture(stoppedTarget);
+ ancestor.addEventListener("pointerdown", (event) => {
+ ancestorEvents.push(event.target.className);
+ });
+ defaultTarget.addEventListener("pointerdown", (event) => {
+ prevented.push(event.defaultPrevented);
+ });
+ stoppedTarget.addEventListener("pointerdown", (event) => {
+ prevented.push(event.defaultPrevented);
+ });
+
+ await triggerEvent(defaultTarget, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ });
+ await triggerEvent(stoppedTarget, "pointerdown", {
+ button: 0,
+ pointerId: 2,
+ });
+
+ assert.deepEqual(
+ ancestorEvents,
+ ["dpd-default"],
+ "the default press bubbles while the opted-in press does not"
+ );
+ assert.deepEqual(
+ prevented,
+ [true, true],
+ "both propagation modes still prevent the browser default"
+ );
+ });
+
+ test("cancelCommits chooses whether cancellation commits", async function (assert) {
+ const calls = [];
+ const cancelOnCancel = (event) =>
+ calls.push(`cancel:cancel:${event.pointerId}`);
+ const cancelOnEnd = (event) =>
+ calls.push(`end:cancel:${event.pointerId}`);
+ const commitOnCancel = (event) =>
+ calls.push(`cancel:commit:${event.pointerId}`);
+ const commitOnEnd = (event) =>
+ calls.push(`end:commit:${event.pointerId}`);
+
+ await render(
+ <template>
+ <div
+ class="dpd-cancel"
+ {{dPointerDrag onDragEnd=cancelOnEnd onDragCancel=cancelOnCancel}}
+ ></div>
+ <div
+ class="dpd-commit"
+ {{dPointerDrag
+ cancelCommits=true
+ onDragEnd=commitOnEnd
+ onDragCancel=commitOnCancel
+ }}
+ ></div>
+ </template>
+ );
+
+ const cancelTarget = find(".dpd-cancel");
+ const commitTarget = find(".dpd-commit");
+ stubPointerCapture(cancelTarget);
+ stubPointerCapture(commitTarget);
+
+ await triggerEvent(cancelTarget, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ });
+ await triggerEvent(cancelTarget, "pointercancel", { pointerId: 1 });
+ await triggerEvent(commitTarget, "pointerdown", {
+ button: 0,
+ pointerId: 2,
+ });
+ await triggerEvent(commitTarget, "pointercancel", { pointerId: 2 });
+
+ assert.deepEqual(
+ calls,
+ ["cancel:cancel:1", "end:commit:2"],
+ "cancellation only commits when requested"
+ );
+ });
+
+ test("lost pointer capture discards and permits a later press by default", async function (assert) {
+ const calls = [];
+ const onDragStart = (event) => calls.push(`start:${event.pointerId}`);
+ const onDragEnd = (event) => calls.push(`end:${event.pointerId}`);
+ const onDragCancel = (event) => calls.push(`cancel:${event.pointerId}`);
+
+ await render(
+ <template>
+ <div
+ class="dpd-target"
+ {{dPointerDrag
+ onDragStart=onDragStart
+ onDragEnd=onDragEnd
+ onDragCancel=onDragCancel
+ }}
+ ></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ stubPointerCapture(target);
+ await triggerEvent(target, "pointerdown", { button: 0, pointerId: 1 });
+ await triggerEvent(target, "lostpointercapture", { pointerId: 1 });
+ await triggerEvent(target, "pointerdown", { button: 0, pointerId: 2 });
+ await triggerEvent(target, "pointerup", { pointerId: 2 });
+
+ assert.deepEqual(
+ calls,
+ ["start:1", "cancel:1", "start:2", "end:2"],
+ "capture loss discards the active drag and clears the gesture latch"
+ );
+ });
+
+ test("lost pointer capture commits and permits a later press when configured", async function (assert) {
+ const calls = [];
+ const onDragStart = (event) => calls.push(`start:${event.pointerId}`);
+ const onDragEnd = (event) => calls.push(`end:${event.pointerId}`);
+ const onDragCancel = (event) => calls.push(`cancel:${event.pointerId}`);
+
+ await render(
+ <template>
+ <div
+ class="dpd-target"
+ {{dPointerDrag
+ cancelCommits=true
+ onDragStart=onDragStart
+ onDragEnd=onDragEnd
+ onDragCancel=onDragCancel
+ }}
+ ></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ stubPointerCapture(target);
+ await triggerEvent(target, "pointerdown", { button: 0, pointerId: 1 });
+ await triggerEvent(target, "lostpointercapture", { pointerId: 1 });
+ await triggerEvent(target, "pointerdown", { button: 0, pointerId: 2 });
+ await triggerEvent(target, "pointerup", { pointerId: 2 });
+
+ assert.deepEqual(
+ calls,
+ ["start:1", "end:1", "start:2", "end:2"],
+ "capture loss commits the active drag and clears the gesture latch"
+ );
+ });
+
+ test("lost pointer capture ignores other pointers and is harmless after release", async function (assert) {
+ const calls = [];
+ const onDragStart = (event) => calls.push(`start:${event.pointerId}`);
+ const onDragEnd = (event) => calls.push(`end:${event.pointerId}`);
+ const onDragCancel = (event) => calls.push(`cancel:${event.pointerId}`);
+
+ await render(
+ <template>
+ <div
+ class="dpd-target"
+ {{dPointerDrag
+ onDragStart=onDragStart
+ onDragEnd=onDragEnd
+ onDragCancel=onDragCancel
+ }}
+ ></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ stubPointerCapture(target);
+ await triggerEvent(target, "pointerdown", { button: 0, pointerId: 7 });
+ await triggerEvent(target, "lostpointercapture", { pointerId: 99 });
+ await triggerEvent(target, "pointerup", { pointerId: 7 });
+ await triggerEvent(target, "lostpointercapture", { pointerId: 7 });
+ await triggerEvent(target, "pointerdown", { button: 0, pointerId: 8 });
+ await triggerEvent(target, "lostpointercapture", { pointerId: 8 });
+
+ assert.deepEqual(
+ calls,
+ ["start:7", "end:7", "start:8", "cancel:8"],
+ "only active capture loss terminates a gesture"
+ );
+ });
+
+ test("teardown removes the lostpointercapture listener", function (assert) {
+ const target = document.createElement("div");
+ const events = installEventListenerSpy(target);
+ const cleanup = dPointerDragModule.registerPointerDrag(
+ target,
+ () => ({})
+ );
+
+ assert.true(
+ events.added.includes("lostpointercapture"),
+ "capture loss is observed while the gesture is registered"
+ );
+
+ cleanup();
+
+ assert.true(
+ events.removed.includes("lostpointercapture"),
+ "teardown removes the capture-loss listener"
+ );
+ });
+
+ test("an invalid draggingClass degrades safely through gesture and teardown", function (assert) {
+ const target = document.createElement("div");
+ const capture = stubPointerCapture(target);
+ const events = installEventListenerSpy(target);
+ const starts = [];
+ const ends = [];
+ const cleanup = dPointerDragModule.registerPointerDrag(target, () => ({
+ draggingClass: "is-dragging active",
+ onDragStart: (event) => starts.push(event.pointerId),
+ onDragEnd: (event) => ends.push(event.pointerId),
+ }));
+
+ const firstStartError = caughtError(() =>
+ events.listeners.get("pointerdown")(
+ new PointerEvent("pointerdown", { button: 0, pointerId: 1 })
+ )
+ );
+ assert.false(
+ Boolean(firstStartError),
+ "an invalid dragging class does not abort gesture start"
+ );
+
+ const firstEndError = caughtError(() =>
+ events.listeners.get("pointerup")(
+ new PointerEvent("pointerup", { pointerId: 1 })
+ )
+ );
+ assert.false(
+ Boolean(firstEndError),
+ "an invalid dragging class does not abort gesture finish"
+ );
+
+ events.listeners.get("pointerdown")(
+ new PointerEvent("pointerdown", { button: 0, pointerId: 2 })
+ );
+ events.listeners.get("pointerup")(
+ new PointerEvent("pointerup", { pointerId: 2 })
+ );
+
+ assert.deepEqual(
+ starts,
+ [1, 2],
+ "an invalid dragging class does not leave gesture state latched"
+ );
+ assert.deepEqual(
+ ends,
+ [1, 2],
+ "both gestures remain functional with an invalid dragging class"
+ );
+ assert.deepEqual(
+ [...capture.released],
+ [1, 2],
+ "both gestures release pointer capture"
+ );
+
+ const cleanupError = caughtError(cleanup);
+ assert.false(
+ Boolean(cleanupError),
+ "an invalid dragging class does not abort teardown"
+ );
+ assert.strictEqual(
+ target.getAttribute("data-pointer-drag"),
+ null,
+ "teardown still removes the pointer-drag attribute"
+ );
+ assert.deepEqual(
+ events.removed,
+ [
+ "pointerdown",
+ "pointermove",
+ "pointerup",
+ "pointercancel",
+ "lostpointercapture",
+ ],
+ "teardown still removes every pointer listener"
+ );
+ });
+
+ test("ignores pointermove from a different pointer", async function (assert) {
+ const moves = [];
+ const onDrag = (event) => moves.push(event.pointerId);
+
+ await render(
+ <template>
+ <div class="dpd-target" {{dPointerDrag onDrag=onDrag}}></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ stubPointerCapture(target);
+ await triggerEvent(target, "pointerdown", {
+ button: 0,
+ pointerId: 7,
+ });
+ await triggerEvent(target, "pointermove", { pointerId: 99 });
+ await triggerEvent(target, "pointermove", { pointerId: 7 });
+
+ assert.deepEqual(moves, [7], "only the active pointer can move the drag");
+ });
+
+ test("ignores pointerup from a different pointer", async function (assert) {
+ const ends = [];
+ const onDragEnd = (event) => ends.push(event.pointerId);
+
+ await render(
+ <template>
+ <div class="dpd-target" {{dPointerDrag onDragEnd=onDragEnd}}></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ stubPointerCapture(target);
+ await triggerEvent(target, "pointerdown", {
+ button: 0,
+ pointerId: 7,
+ });
+ await triggerEvent(target, "pointerup", { pointerId: 99 });
+ await triggerEvent(target, "pointerup", { pointerId: 7 });
+
+ assert.deepEqual(ends, [7], "only the active pointer can end the drag");
+ });
+
+ test("ignores pointercancel from a different pointer", async function (assert) {
+ const cancellations = [];
+ const onDragCancel = (event) => cancellations.push(event.pointerId);
+
+ await render(
+ <template>
+ <div
+ class="dpd-target"
+ {{dPointerDrag onDragCancel=onDragCancel}}
+ ></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ stubPointerCapture(target);
+ await triggerEvent(target, "pointerdown", {
+ button: 0,
+ pointerId: 7,
+ });
+ await triggerEvent(target, "pointercancel", { pointerId: 99 });
+ await triggerEvent(target, "pointercancel", { pointerId: 7 });
+
+ assert.deepEqual(
+ cancellations,
+ [7],
+ "only the active pointer can cancel the drag"
+ );
+ });
+
+ test("teardown during a gesture releases pointer capture", async function (assert) {
+ await render(
+ <template>
+ <div class="dpd-target" {{dPointerDrag}}></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ const capture = stubPointerCapture(target);
+ await triggerEvent(target, "pointerdown", {
+ button: 0,
+ pointerId: 17,
+ });
+
+ await clearRender();
+
+ assert.deepEqual(
+ capture.released,
+ [17],
+ "teardown releases the active pointer"
+ );
+ });
+
+ test("touchAction is reflected to an attribute and removed on teardown", async function (assert) {
+ await render(
+ <template>
+ <div class="dpd-default" {{dPointerDrag}}></div>
+ <div class="dpd-custom" {{dPointerDrag touchAction="pan-y"}}></div>
+ </template>
+ );
+
+ const defaultTarget = find(".dpd-default");
+ const customTarget = find(".dpd-custom");
+
+ assert
+ .dom(defaultTarget)
+ .hasAttribute(
+ "data-pointer-drag",
+ "none",
+ "the default opts out of browser touch gestures"
+ );
+ assert
+ .dom(customTarget)
+ .hasAttribute(
+ "data-pointer-drag",
+ "pan-y",
+ "a custom touch-action value is reflected"
+ );
+
+ await clearRender();
+
+ assert.strictEqual(
+ defaultTarget.getAttribute("data-pointer-drag"),
+ null,
+ "the default attribute is removed"
+ );
+ assert.strictEqual(
+ customTarget.getAttribute("data-pointer-drag"),
+ null,
+ "the custom attribute is removed"
+ );
+ });
+
+ test("touchAction is re-reflected when the consumer changes it", async function (assert) {
+ const state = new (class {
+ @tracked touchAction = "pan-y";
+ })();
+
+ await render(
+ <template>
+ <div
+ class="dpd-target"
+ {{dPointerDrag touchAction=state.touchAction}}
+ ></div>
+ </template>
+ );
+
+ assert
+ .dom(".dpd-target")
+ .hasAttribute(
+ "data-pointer-drag",
+ "pan-y",
+ "the initial value is reflected"
+ );
+
+ state.touchAction = "pan-x";
+ await settled();
+
+ // The declaration has to be in place before a touch begins, so a value
+ // changed between gestures has to reach the attribute without the modifier
+ // being torn down and rebuilt.
+ assert
+ .dom(".dpd-target")
+ .hasAttribute(
+ "data-pointer-drag",
+ "pan-x",
+ "a later value replaces it without a re-render of the element"
+ );
+ });
+ });
+
+ module("nested registrations claiming one pointer", function () {
+ function recorder(calls) {
+ return {
+ onDragStart: () => calls.push("start"),
+ onDragEnd: () => calls.push("end"),
+ onDragCancel: () => calls.push("cancel"),
+ };
+ }
+
+ test("an ancestor claiming the same press releases the descendant's gesture", async function (assert) {
+ const inner = [];
+ const outer = [];
+ const innerHandlers = recorder(inner);
+ const outerHandlers = recorder(outer);
+
+ await render(
+ <template>
+ <div
+ class="dpd-outer"
+ {{dPointerDrag
+ onDragStart=outerHandlers.onDragStart
+ onDragEnd=outerHandlers.onDragEnd
+ onDragCancel=outerHandlers.onDragCancel
+ }}
+ >
+ <div
+ class="dpd-inner"
+ {{dPointerDrag
+ onDragStart=innerHandlers.onDragStart
+ onDragEnd=innerHandlers.onDragEnd
+ onDragCancel=innerHandlers.onDragCancel
+ }}
+ ></div>
+ </div>
+ </template>
+ );
+
+ const outerTarget = find(".dpd-outer");
+ const innerTarget = find(".dpd-inner");
+ stubPointerCapture(outerTarget);
+ stubPointerCapture(innerTarget);
+
+ await triggerEvent(innerTarget, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ });
+
+ assert.deepEqual(
+ inner,
+ ["start", "cancel"],
+ "the descendant is told its gesture ended when the ancestor takes the pointer"
+ );
+ assert.deepEqual(
+ outer,
+ ["start"],
+ "the ancestor's gesture is the live one"
+ );
+
+ // The release goes to whichever element holds the capture, which is the
+ // ancestor — so the descendant sees nothing, exactly as in a real browser
+ // once the pointer has left it.
+ await triggerEvent(outerTarget, "pointerup", { pointerId: 1 });
+
+ await triggerEvent(innerTarget, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ });
+
+ assert.deepEqual(
+ inner,
+ ["start", "cancel", "start", "cancel"],
+ "a later press still starts a gesture on the descendant"
+ );
+ assert.deepEqual(
+ outer,
+ ["start", "end", "start"],
+ "every started gesture reaches exactly one terminal callback"
+ );
+ });
+
+ test("an ancestor that vetoes the press leaves the descendant's capture in place", async function (assert) {
+ const inner = [];
+ const innerHandlers = recorder(inner);
+ const veto = () => false;
+
+ await render(
+ <template>
+ <div class="dpd-outer" {{dPointerDrag onDragStart=veto}}>
+ <div
+ class="dpd-inner"
+ {{dPointerDrag
+ onDragStart=innerHandlers.onDragStart
+ onDragEnd=innerHandlers.onDragEnd
+ onDragCancel=innerHandlers.onDragCancel
+ }}
+ ></div>
+ </div>
+ </template>
+ );
+
+ const innerTarget = find(".dpd-inner");
+ // The shared stub, because the subject is exactly the displacement: the
+ // ancestor's claim replaces the descendant's pending capture before the
+ // veto is known.
+ const { ownerOf } = stubSharedPointerCapture([".dpd-outer", innerTarget]);
+
+ await triggerEvent(innerTarget, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ });
+
+ assert.deepEqual(
+ inner,
+ ["start"],
+ "the descendant's gesture is the live one"
+ );
+ assert.strictEqual(
+ ownerOf(1),
+ innerTarget,
+ "the capture the veto displaced is handed back to the claimant"
+ );
+
+ await triggerEvent(innerTarget, "pointerup", { pointerId: 1 });
+
+ assert.deepEqual(
+ inner,
+ ["start", "end"],
+ "the gesture still reaches its one terminal callback"
+ );
+ });
+
+ test("a superseded gesture honours cancelCommits", async function (assert) {
+ const inner = [];
+ const innerHandlers = recorder(inner);
+
+ await render(
+ <template>
+ <div class="dpd-outer" {{dPointerDrag}}>
+ <div
+ class="dpd-inner"
+ {{dPointerDrag
+ onDragStart=innerHandlers.onDragStart
+ onDragEnd=innerHandlers.onDragEnd
+ onDragCancel=innerHandlers.onDragCancel
+ cancelCommits=true
+ }}
+ ></div>
+ </div>
+ </template>
+ );
+
+ stubPointerCapture(find(".dpd-outer"));
+ const innerTarget = find(".dpd-inner");
+ stubPointerCapture(innerTarget);
+
+ await triggerEvent(innerTarget, "pointerdown", {
+ button: 0,
+ pointerId: 3,
+ });
+
+ assert.deepEqual(
+ inner,
+ ["start", "end"],
+ "a consumer that commits on cancellation commits here too"
+ );
+ });
+
+ test("a descendant that stops propagation keeps the pointer", async function (assert) {
+ const inner = [];
+ const outer = [];
+ const innerHandlers = recorder(inner);
+ const outerHandlers = recorder(outer);
+
+ await render(
+ <template>
+ <div
+ class="dpd-outer"
+ {{dPointerDrag
+ onDragStart=outerHandlers.onDragStart
+ onDragEnd=outerHandlers.onDragEnd
+ onDragCancel=outerHandlers.onDragCancel
+ }}
+ >
+ <div
+ class="dpd-inner"
+ {{dPointerDrag
+ onDragStart=innerHandlers.onDragStart
+ onDragEnd=innerHandlers.onDragEnd
+ onDragCancel=innerHandlers.onDragCancel
+ stopPropagation=true
+ }}
+ ></div>
+ </div>
+ </template>
+ );
+
+ stubPointerCapture(find(".dpd-outer"));
+ const innerTarget = find(".dpd-inner");
+ stubPointerCapture(innerTarget);
+
+ await triggerEvent(innerTarget, "pointerdown", {
+ button: 0,
+ pointerId: 4,
+ });
+ await triggerEvent(innerTarget, "pointerup", { pointerId: 4 });
+
+ assert.deepEqual(
+ inner,
+ ["start", "end"],
+ "the isolated gesture runs to completion uninterrupted"
+ );
+ assert.deepEqual(outer, [], "the ancestor never sees the press");
+ });
+
+ test("gestures on distinct pointers do not supersede each other", async function (assert) {
+ const first = [];
+ const second = [];
+ const firstHandlers = recorder(first);
+ const secondHandlers = recorder(second);
+
+ await render(
+ <template>
+ <div
+ class="dpd-first"
+ {{dPointerDrag
+ onDragStart=firstHandlers.onDragStart
+ onDragEnd=firstHandlers.onDragEnd
+ onDragCancel=firstHandlers.onDragCancel
+ }}
+ ></div>
+ <div
+ class="dpd-second"
+ {{dPointerDrag
+ onDragStart=secondHandlers.onDragStart
+ onDragEnd=secondHandlers.onDragEnd
+ onDragCancel=secondHandlers.onDragCancel
+ }}
+ ></div>
+ </template>
+ );
+
+ const firstTarget = find(".dpd-first");
+ const secondTarget = find(".dpd-second");
+ stubPointerCapture(firstTarget);
+ stubPointerCapture(secondTarget);
+
+ await triggerEvent(firstTarget, "pointerdown", {
+ button: 0,
+ pointerId: 5,
+ });
+ await triggerEvent(secondTarget, "pointerdown", {
+ button: 0,
+ pointerId: 6,
+ });
+ await triggerEvent(firstTarget, "pointerup", { pointerId: 5 });
+ await triggerEvent(secondTarget, "pointerup", { pointerId: 6 });
+
+ assert.deepEqual(
+ first,
+ ["start", "end"],
+ "a second pointer elsewhere leaves the first gesture alone"
+ );
+ assert.deepEqual(
+ second,
+ ["start", "end"],
+ "ownership is tracked per pointer, not globally"
+ );
+ });
+
+ test("three levels each release the level below them", async function (assert) {
+ const inner = [];
+ const middle = [];
+ const outer = [];
+ const innerHandlers = recorder(inner);
+ const middleHandlers = recorder(middle);
+ const outerHandlers = recorder(outer);
+
+ await render(
+ <template>
+ <div
+ class="dpd-outer"
+ {{dPointerDrag
+ onDragStart=outerHandlers.onDragStart
+ onDragEnd=outerHandlers.onDragEnd
+ onDragCancel=outerHandlers.onDragCancel
+ }}
+ >
+ <div
+ class="dpd-middle"
+ {{dPointerDrag
+ onDragStart=middleHandlers.onDragStart
+ onDragEnd=middleHandlers.onDragEnd
+ onDragCancel=middleHandlers.onDragCancel
+ }}
+ >
+ <div
+ class="dpd-inner"
+ {{dPointerDrag
+ onDragStart=innerHandlers.onDragStart
+ onDragEnd=innerHandlers.onDragEnd
+ onDragCancel=innerHandlers.onDragCancel
+ }}
+ ></div>
+ </div>
+ </div>
+ </template>
+ );
+
+ for (const selector of [".dpd-outer", ".dpd-middle", ".dpd-inner"]) {
+ stubPointerCapture(find(selector));
+ }
+
+ await triggerEvent(find(".dpd-inner"), "pointerdown", {
+ button: 0,
+ pointerId: 11,
+ });
+
+ // The middle releasing the inner must not drop the middle's own fresh
+ // claim, or the outer would find no owner to release and the middle would
+ // stay latched with nothing left to end it.
+ assert.deepEqual(inner, ["start", "cancel"], "the innermost is released");
+ assert.deepEqual(
+ middle,
+ ["start", "cancel"],
+ "the middle is released too"
+ );
+ assert.deepEqual(
+ outer,
+ ["start"],
+ "only the outermost keeps the pointer"
+ );
+
+ await triggerEvent(find(".dpd-outer"), "pointerup", { pointerId: 11 });
+ await triggerEvent(find(".dpd-middle"), "pointerdown", {
+ button: 0,
+ pointerId: 11,
+ });
+
+ assert.deepEqual(
+ middle,
+ ["start", "cancel", "start", "cancel"],
+ "a level released mid-dispatch can start a later gesture"
+ );
+ });
+
+ test("a registration torn down during onDragStart claims no pointer", function (assert) {
+ const target = document.createElement("div");
+ stubPointerCapture(target);
+ const events = installEventListenerSpy(target);
+ const calls = [];
+ let cleanup;
+
+ cleanup = dPointerDragModule.registerPointerDrag(target, () => ({
+ onDragStart: () => {
+ calls.push("start");
+ // A consumer destroying its own registration from inside the callback
+ // that started it: every listener is gone by the time this returns.
+ cleanup();
+ },
+ onDragCancel: () => calls.push("cancel"),
+ }));
+
+ events.listeners.get("pointerdown")(
+ new PointerEvent("pointerdown", { button: 0, pointerId: 21 })
+ );
+
+ const later = document.createElement("div");
+ stubPointerCapture(later);
+ const laterEvents = installEventListenerSpy(later);
+ const laterCleanup = dPointerDragModule.registerPointerDrag(
+ later,
+ () => ({})
+ );
+ laterEvents.listeners.get("pointerdown")(
+ new PointerEvent("pointerdown", { button: 0, pointerId: 21 })
+ );
+
+ assert.deepEqual(
+ calls,
+ ["start"],
+ "reusing the pointer never reaches into the destroyed registration"
+ );
+
+ laterCleanup();
+ });
+
+ test("teardown mid-gesture gives up the pointer", function (assert) {
+ const target = document.createElement("div");
+ stubPointerCapture(target);
+ const events = installEventListenerSpy(target);
+ const calls = [];
+
+ const cleanup = dPointerDragModule.registerPointerDrag(target, () => ({
+ onDragStart: () => calls.push("start"),
+ onDragCancel: () => calls.push("cancel"),
+ }));
+
+ events.listeners.get("pointerdown")(
+ new PointerEvent("pointerdown", { button: 0, pointerId: 22 })
+ );
+ cleanup();
+
+ const later = document.createElement("div");
+ stubPointerCapture(later);
+ const laterEvents = installEventListenerSpy(later);
+ const laterCleanup = dPointerDragModule.registerPointerDrag(
+ later,
+ () => ({})
+ );
+ laterEvents.listeners.get("pointerdown")(
+ new PointerEvent("pointerdown", { button: 0, pointerId: 22 })
+ );
+
+ assert.deepEqual(
+ calls,
+ ["start"],
+ "a torn-down registration is not asked to release a pointer it no longer holds"
+ );
+
+ laterCleanup();
+ });
+ });
+
+ module("bodyClass", function () {
+ test("marks the document body for the gesture's duration", async function (assert) {
+ await render(
+ <template>
+ <div class="dpd-target" {{dPointerDrag bodyClass="dragging"}}></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ stubPointerCapture(target);
+
+ await triggerEvent(target, "pointerdown", { button: 0, pointerId: 1 });
+ assert
+ .dom(document.body)
+ .hasClass("dragging", "the body is marked while the gesture runs");
+
+ await triggerEvent(target, "pointerup", { pointerId: 1 });
+ assert
+ .dom(document.body)
+ .doesNotHaveClass("dragging", "and unmarked on release");
+ });
+
+ test("unmarks the body when the gesture is cancelled", async function (assert) {
+ await render(
+ <template>
+ <div class="dpd-target" {{dPointerDrag bodyClass="dragging"}}></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ stubPointerCapture(target);
+
+ await triggerEvent(target, "pointerdown", { button: 0, pointerId: 1 });
+ assert.dom(document.body).hasClass("dragging", "the gesture marked it");
+
+ await triggerEvent(target, "pointercancel", { pointerId: 1 });
+ assert
+ .dom(document.body)
+ .doesNotHaveClass(
+ "dragging",
+ "a cancelled gesture cleans up after itself"
+ );
+ });
+
+ test("unmarks the body when torn down mid-gesture", async function (assert) {
+ await render(
+ <template>
+ <div class="dpd-target" {{dPointerDrag bodyClass="dragging"}}></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ stubPointerCapture(target);
+ await triggerEvent(target, "pointerdown", { button: 0, pointerId: 1 });
+ assert.dom(document.body).hasClass("dragging", "the gesture marked it");
+
+ await clearRender();
+ assert
+ .dom(document.body)
+ .doesNotHaveClass("dragging", "teardown does not strand the mark");
+ });
+
+ test("a second gesture keeps the mark until it ends too", async function (assert) {
+ await render(
+ <template>
+ <div class="dpd-first" {{dPointerDrag bodyClass="dragging"}}></div>
+ <div class="dpd-second" {{dPointerDrag bodyClass="dragging"}}></div>
+ </template>
+ );
+
+ const first = find(".dpd-first");
+ const second = find(".dpd-second");
+ stubPointerCapture(first);
+ stubPointerCapture(second);
+
+ await triggerEvent(first, "pointerdown", { button: 0, pointerId: 1 });
+ await triggerEvent(second, "pointerdown", { button: 0, pointerId: 2 });
+ await triggerEvent(first, "pointerup", { pointerId: 1 });
+
+ assert
+ .dom(document.body)
+ .hasClass(
+ "dragging",
+ "one gesture ending does not unmark the body while another is live"
+ );
+
+ await triggerEvent(second, "pointerup", { pointerId: 2 });
+
+ assert
+ .dom(document.body)
+ .doesNotHaveClass("dragging", "the last one out clears the mark");
+ });
+
+ test("a legacy drag keeps the body class after a pointer drag ends", async function (assert) {
+ const noop = () => {};
+ await render(
+ <template>
+ <div class="dpd-target" {{dPointerDrag bodyClass="dragging"}}></div>
+ <div class="legacy-target" {{dDraggable didEndDrag=noop}}></div>
+ </template>
+ );
+
+ const pointerTarget = find(".dpd-target");
+ stubPointerCapture(pointerTarget);
+
+ await triggerEvent(".legacy-target", "mousedown");
+ await triggerEvent(pointerTarget, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ });
+ await triggerEvent(pointerTarget, "pointerup", { pointerId: 1 });
+
+ assert
+ .dom(document.body)
+ .hasClass("dragging", "the legacy gesture still owns the body class");
+
+ await triggerEvent(document, "mouseup");
+ assert
+ .dom(document.body)
+ .doesNotHaveClass(
+ "dragging",
+ "the last gesture releases the body class"
+ );
+ });
+
+ test("a pointer drag keeps the body class after a legacy drag ends", async function (assert) {
+ const noop = () => {};
+ await render(
+ <template>
+ <div class="dpd-target" {{dPointerDrag bodyClass="dragging"}}></div>
+ <div class="legacy-target" {{dDraggable didEndDrag=noop}}></div>
+ </template>
+ );
+
+ const pointerTarget = find(".dpd-target");
+ stubPointerCapture(pointerTarget);
+
+ await triggerEvent(pointerTarget, "pointerdown", {
+ button: 0,
+ pointerId: 1,
+ });
+ await triggerEvent(".legacy-target", "mousedown");
+ await triggerEvent(document, "mouseup");
+
+ assert
+ .dom(document.body)
+ .hasClass("dragging", "the pointer gesture still owns the body class");
+
+ await triggerEvent(pointerTarget, "pointerup", { pointerId: 1 });
+ assert
+ .dom(document.body)
+ .doesNotHaveClass(
+ "dragging",
+ "the last gesture releases the body class"
+ );
+ });
+
+ test("preserves a body class that predates the gesture", async function (assert) {
+ document.body.classList.add("dragging");
+ await render(
+ <template>
+ <div class="dpd-target" {{dPointerDrag bodyClass="dragging"}}></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ stubPointerCapture(target);
+
+ await triggerEvent(target, "pointerdown", { button: 0, pointerId: 1 });
+ await triggerEvent(target, "pointerup", { pointerId: 1 });
+
+ assert
+ .dom(document.body)
+ .hasClass(
+ "dragging",
+ "the gesture leaves the pre-existing class alone"
+ );
+
+ document.body.classList.remove("dragging");
+ });
+
+ test("an invalid bodyClass costs the page styling but not the gesture", async function (assert) {
+ const calls = [];
+ const onDragStart = () => calls.push("start");
+ const onDragEnd = () => calls.push("end");
+
+ await render(
+ <template>
+ <div
+ class="dpd-target"
+ {{dPointerDrag
+ bodyClass="is dragging"
+ onDragStart=onDragStart
+ onDragEnd=onDragEnd
+ }}
+ ></div>
+ </template>
+ );
+
+ const target = find(".dpd-target");
+ stubPointerCapture(target);
+
+ await triggerEvent(target, "pointerdown", { button: 0, pointerId: 1 });
+ assert
+ .dom(document.body)
+ .doesNotHaveClass(
+ "is",
+ "a whitespace token is rejected whole, not split into parts"
+ );
+
+ await triggerEvent(target, "pointerup", { pointerId: 1 });
+
+ assert.deepEqual(
+ calls,
+ ["start", "end"],
+ "a token the DOM refuses costs the page-level styling only; the gesture runs to completion"
+ );
+ });
+ });
+});
diff --git a/frontend/discourse/type-tests/ui-kit/d-pointer-drag-errors-test.gts b/frontend/discourse/type-tests/ui-kit/d-pointer-drag-errors-test.gts
new file mode 100644
index 00000000000..9808cd2c658
--- /dev/null
+++ b/frontend/discourse/type-tests/ui-kit/d-pointer-drag-errors-test.gts
@@ -0,0 +1,25 @@
+import dPointerDrag from "discourse/ui-kit/modifiers/d-pointer-drag";
+
+declare function onGesture(event: PointerEvent): void;
+
+const Test = <template>
+ {{! @glint-expect-error - threshold is a pixel count, not a string }}
+ <span {{dPointerDrag threshold="4"}}></span>
+
+ {{! @glint-expect-error - touchAction is closed against the stylesheet, and "auto" has no rule }}
+ <span {{dPointerDrag touchAction="auto"}}></span>
+
+ {{! @glint-expect-error - a typo'd token would silently leave touch-action at auto }}
+ <span {{dPointerDrag touchAction="pan-Y"}}></span>
+
+ {{! @glint-expect-error - stopPropagation is a flag, not a string }}
+ <span {{dPointerDrag stopPropagation="true"}}></span>
+
+ {{! @glint-expect-error - onDrag receives the event; it cannot take extra arguments }}
+ <span {{dPointerDrag onDrag=onGesture extra=1}}></span>
+
+ {{! @glint-expect-error - the gesture takes no positional arguments }}
+ <span {{dPointerDrag onGesture}}></span>
+</template>;
+
+export default Test;
diff --git a/frontend/discourse/type-tests/ui-kit/d-pointer-drag-test.gts b/frontend/discourse/type-tests/ui-kit/d-pointer-drag-test.gts
new file mode 100644
index 00000000000..9a37c623685
--- /dev/null
+++ b/frontend/discourse/type-tests/ui-kit/d-pointer-drag-test.gts
@@ -0,0 +1,49 @@
+// Keep this file free of @glint-expect-error directives so broken positive
+// invocations cannot be masked by a negative assertion.
+import dPointerDrag, {
+ type DPointerDragArgs,
+ registerPointerDrag,
+ type TouchActionToken,
+} from "discourse/ui-kit/modifiers/d-pointer-drag";
+
+declare const noop: () => void;
+declare function onGesture(event: PointerEvent): void;
+declare function vetoGesture(event: PointerEvent): boolean;
+
+const Test = <template>
+ <span
+ {{dPointerDrag
+ onDragStart=vetoGesture
+ onDrag=onGesture
+ onDragEnd=onGesture
+ onDragCancel=onGesture
+ draggingClass="--dragging"
+ bodyClass="d-resizing-ew"
+ threshold=4
+ stopPropagation=true
+ cancelCommits=true
+ touchAction="pan-y"
+ }}
+ ></span>
+
+ <span {{dPointerDrag onDragStart=noop}}></span>
+</template>;
+
+/**
+ * The imperative entry point is exported public API too, so it is checked here
+ * rather than only through the modifier. Never invoked.
+ */
+export function checkImperativeSurface(handle: HTMLElement) {
+ const touchAction: TouchActionToken = "manipulation";
+ const args: DPointerDragArgs = {
+ onDragStart: vetoGesture,
+ onDrag: onGesture,
+ threshold: 4,
+ touchAction,
+ };
+
+ const cleanup: () => void = registerPointerDrag(handle, () => args);
+ cleanup();
+}
+
+export default Test;
diff --git a/spec/support/system_helpers.rb b/spec/support/system_helpers.rb
index eff5b94c5e1..6512e1ac2ea 100644
--- a/spec/support/system_helpers.rb
+++ b/spec/support/system_helpers.rb
@@ -422,6 +422,67 @@ module SystemHelpers
page.driver.with_playwright_page { |pw_page| pw_page.touchscreen.tap_point(x, y) }
end
+ # Drives a press-drag-release with the real mouse, for the surfaces built on
+ # pointer events rather than native drag-and-drop.
+ #
+ # `from:` is a CSS selector for the element to press. `to:` is an absolute
+ # viewport point; `by:` is an offset from the press point, for when the distance
+ # matters more than the destination. Movement is broken into `steps:` so a
+ # gesture with a movement threshold actually crosses it, and so anything driven
+ # by intermediate moves sees more than one.
+ #
+ # This bypasses Capybara's client-settle wait, so assert through a retrying
+ # matcher rather than a value read once.
+ #
+ # The mouse moves through absolute viewport coordinates. An element below the
+ # fold would otherwise be measured where it cannot be pressed, so it is scrolled
+ # into view first and measured after.
+ #
+ # Pass a block to assert on the page while the gesture is still open: it runs
+ # after the pointer has moved and before the release, so anything a drag holds
+ # for its own duration is still there to be seen. Without one, asserting only
+ # that such a mark is absent afterwards would pass just as well against a drag
+ # that never started.
+ def drag_with_pointer(from:, to: nil, by: nil, steps: 10)
+ raise ArgumentError, "pass exactly one of to: or by:" if to.nil? == by.nil?
+
+ page.driver.with_playwright_page do |pw_page|
+ # Waited for rather than queried once: `query_selector` returns nil without
+ # waiting, so a not-yet-rendered element would fail as a `NoMethodError` on
+ # nil, naming neither the selector nor the timing.
+ # Capybara's budget, not Playwright's 30s default: the driver is registered
+ # without `default_timeout`, so a missing handle would otherwise stall the
+ # example for half a minute before failing.
+ node =
+ pw_page.wait_for_selector(
+ from,
+ state: "visible",
+ timeout: Capybara.default_max_wait_time * 1000,
+ )
+ node.scroll_into_view_if_needed
+ box = node.bounding_box
+ start_x = box["x"] + box["width"] / 2
+ start_y = box["y"] + box["height"] / 2
+ end_x = to ? to[:x] : start_x + by.fetch(:x, 0)
+ end_y = to ? to[:y] : start_y + by.fetch(:y, 0)
+
+ pw_page.mouse.move(start_x, start_y)
+ pw_page.mouse.down
+ # Stepped rather than a single jump: a gesture with a threshold needs to be
+ # seen crossing it, not teleported past it.
+ pw_page.mouse.move(end_x, end_y, steps: steps)
+ end
+
+ begin
+ # Outside the driver block, so Capybara's own matchers work normally in it.
+ yield if block_given?
+ ensure
+ # Released even when an in-gesture assertion fails, so the example does not
+ # run its remaining hooks with the button still held.
+ page.driver.with_playwright_page { |pw_page| pw_page.mouse.up }
+ end
+ end
+
def html_translation_to_text(html_translation)
Nokogiri.HTML5(html_translation).at("body").inner_text
end
diff --git a/spec/system/page_objects/components/topic_timeline.rb b/spec/system/page_objects/components/topic_timeline.rb
new file mode 100644
index 00000000000..3773b905840
--- /dev/null
+++ b/spec/system/page_objects/components/topic_timeline.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Components
+ class TopicTimeline < PageObjects::Components::Base
+ SCROLLER_SELECTOR = ".timeline-scroller"
+ SCROLLAREA_SELECTOR = ".timeline-scrollarea"
+
+ def has_scroller?
+ has_css?(SCROLLER_SELECTOR)
+ end
+
+ # The timeline's own readout of where the reader is. Distinct from the
+ # stream having loaded a post: a cloaked post keeps its `#post_N` id, so
+ # `has_post_number?` is satisfied by a placeholder the reader never reached.
+ def has_position?(current, total)
+ has_css?("#{SCROLLER_SELECTOR} .timeline-replies", exact_text: "#{current} / #{total}")
+ end
+
+ def drag_to_bottom
+ drag_with_pointer(from: SCROLLER_SELECTOR, to: { x: 20, y: scrollarea_bottom })
+ end
+
+ def drag_by(y:, &block)
+ drag_with_pointer(from: SCROLLER_SELECTOR, by: { y: y }, &block)
+ end
+
+ def has_dragging_page?
+ has_css?("body.dragging")
+ end
+
+ def has_no_dragging_page?
+ has_no_css?("body.dragging")
+ end
+
+ def has_dragging_scrollarea?
+ has_css?("#{SCROLLAREA_SELECTOR}.--dragging")
+ end
+
+ def has_no_dragging_scrollarea?
+ has_no_css?("#{SCROLLAREA_SELECTOR}.--dragging")
+ end
+
+ private
+
+ def scrollarea_bottom
+ page.evaluate_script(<<~JS)
+ (() => {
+ const area = document.querySelector("#{SCROLLAREA_SELECTOR}");
+ const box = area.getBoundingClientRect();
+ // Just inside the track, so the press lands on the scrollarea rather
+ // than whatever sits immediately below it.
+ return box.bottom - 4;
+ })()
+ JS
+ end
+ end
+ end
+end
diff --git a/spec/system/page_objects/pages/topic.rb b/spec/system/page_objects/pages/topic.rb
index 2d117776bd1..24a65de332b 100644
--- a/spec/system/page_objects/pages/topic.rb
+++ b/spec/system/page_objects/pages/topic.rb
@@ -7,6 +7,7 @@ module PageObjects
@composer_component = PageObjects::Components::Composer.new
@fast_edit_component = PageObjects::Components::FastEditor.new
@topic_map_component = PageObjects::Components::TopicMap.new
+ @topic_timeline_component = PageObjects::Components::TopicTimeline.new
@private_message_map_component = PageObjects::Components::PrivateMessageMap.new
end
@@ -15,6 +16,10 @@ module PageObjects
self
end
+ def timeline
+ @topic_timeline_component
+ end
+
def open_new_topic
visit "/new-topic"
self
diff --git a/spec/system/topic_timeline_drag_spec.rb b/spec/system/topic_timeline_drag_spec.rb
new file mode 100644
index 00000000000..21d927fbd41
--- /dev/null
+++ b/spec/system/topic_timeline_drag_spec.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+describe "Topic timeline scroller drag" do
+ fab!(:current_user, :user)
+ fab!(:topic)
+ fab!(:post_1) { Fabricate(:post, topic: topic) }
+ # More replies than `TopicView::CHUNK_SIZE`, so a late post is only in the DOM
+ # once the drag has actually moved the stream on.
+ fab!(:replies) { 30.times.map { Fabricate(:post, topic: topic) } }
+
+ let(:topic_page) { PageObjects::Pages::Topic.new }
+
+ before { sign_in(current_user) }
+
+ it "lets the user scroll the topic by dragging down the timeline" do
+ topic_page.visit_topic(topic)
+
+ expect(topic_page).to have_post_number(1)
+ expect(topic_page.timeline).to have_scroller
+
+ # The pointer path is only exercised for real in a browser, where pointer
+ # capture actually routes the drag back to the scroller. A synthetic dispatch
+ # picks its own event target and so cannot tell a live drag from a dead one.
+ topic_page.timeline.drag_to_bottom
+
+ # A later chunk had to load for this to be in the DOM at all.
+ expect(topic_page).to have_post_number(25)
+ # And the reader travelled with it. Asserted separately because the two can
+ # come apart: a cloaked post keeps its `#post_N` id, so the assertion above
+ # proves the stream advanced without saying where the reader ended up, and
+ # the readout is computed from the drag rather than from what loaded.
+ expect(topic_page.timeline).to have_position(31, 31)
+ end
+
+ it "clears the user's drag state when the pointer is released" do
+ topic_page.visit_topic(topic)
+
+ expect(topic_page).to have_post_number(1)
+ expect(topic_page.timeline).to have_scroller
+
+ topic_page
+ .timeline
+ .drag_by(y: 120) do
+ # Asserted mid-gesture, because the absence afterwards is also what a drag
+ # that never started would produce.
+ expect(topic_page.timeline).to have_dragging_page
+ expect(topic_page.timeline).to have_dragging_scrollarea
+ end
+
+ expect(topic_page.timeline).to have_no_dragging_page
+ expect(topic_page.timeline).to have_no_dragging_scrollarea
+ end
+end