A platform for community discussion. Free, open, simple.
DEV: Add shared two-dimensional resize handles (#42603)
Sérgio Saquetim00e1bcc7c5f8
diff --git a/frontend/discourse/app/ui-kit/d-resize-handles.gts b/frontend/discourse/app/ui-kit/d-resize-handles.gtsnew file mode 100644index 00000000000..179b7f3ecad--- /dev/null+++ b/frontend/discourse/app/ui-kit/d-resize-handles.gts@@ -0,0 +1,576 @@+import Component from "@glimmer/component";+import { DEBUG } from "@glimmer/env";+import { assert } from "@ember/debug";+import { registerDestructor } from "@ember/destroyable";+import { fn } from "@ember/helper";+import { action } from "@ember/object";+import type Owner from "@ember/owner";+import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";+import { isTrustedHTML, type TrustedHTML } from "@ember/template";+import dPointerDrag, {+ type DPointerDragInfo,+} from "discourse/ui-kit/modifiers/d-pointer-drag";++/** One of the eight compass directions of the built-in box resize. */+export type BoxDirection = "n" | "ne" | "e" | "se" | "s" | "sw" | "w" | "nw";++/**+ * The eight compass handles of a box resize, in clockwise order. The common+ * case (resizing a rectangle's edges + corners) — generated from `@handleClass`+ * so consumers don't repeat the list. Each handle's `payload` is its direction.+ */+export const BOX_DIRECTIONS: BoxDirection[] = [+ "n",+ "ne",+ "e",+ "se",+ "s",+ "sw",+ "w",+ "nw",+];++/**+ * One handle to render. The escape hatch from the built-in box: supply these+ * when the handles are not a rectangle's edges and corners.+ */+export interface DResizeHandleDescriptor<Payload extends string | number> {+ /**+ * What makes this handle itself. It must be unique among its siblings and+ * stable across recomputes, so that a list changing under a held pointer+ * destroys the handle that really went rather than the last one.+ *+ * Not derived from `payload`, which says what a handle means rather than which+ * one it is. Several handles can legitimately mean the same thing.+ */+ key: string;++ /** What the handle means. Handed back to every callback, and may repeat. */+ payload: Payload;++ /** Positions and styles the handle. */+ class?: string;++ /**+ * Inline positioning. Wrap the string in `trustHTML` before passing it here.+ * Only the caller knows whether the values it interpolated are safe, so this+ * component will not make that call for it.+ */+ style?: TrustedHTML;+}++/** What one gesture carries for as long as it runs. */+interface Gesture<Payload, Session> {+ payload: Payload;+ /** The element pressed, so its teardown can close this gesture. */+ handle: HTMLElement;+ /** The last report, so teardown can close the gesture at its last position. */+ event: PointerEvent;+ info: DPointerDragInfo;+ measured: Element | null;+ measuredRect: DOMRect | null;+ session: Session;+}++/**+ * The pointer geometry of a move, reported to every callback. Deliberately raw:+ * the consumer decides what a pixel delta means in its own units.+ *+ * Everything here is a snapshot of the moment it was handed over, EXCEPT+ * `session`, which is the one thing that lives for the gesture.+ */+export interface DResizeHandleDragInfo<+ Payload extends string | number,+ Session extends object = object,+> {+ /** The handle being dragged — the same value the callback's first argument carries. */+ readonly payload: Payload;++ /** The pointer event that produced this report. */+ readonly event: PointerEvent;++ /** Where the press landed, in client coordinates. */+ readonly origin: Readonly<{ x: number; y: number }>;++ /** Where the pointer is now, in client coordinates. */+ readonly current: Readonly<{ x: number; y: number }>;++ /** How far the pointer has travelled since the press. */+ readonly delta: Readonly<{ x: number; y: number }>;++ /**+ * Whether `@onResize` has fired at least once for THIS gesture. It tells a+ * resize apart from a click that landed on a handle. Commit on `@onResizeEnd`+ * only when it is set, or a bare click records a no-op change.+ */+ readonly moved: boolean;++ /**+ * Scratch for the length of one gesture, and the same object throughout it.+ *+ * Write the press-time snapshot here in `@onResizeStart` and read it back on+ * every later report. It lives here rather than on the consumer so that each+ * gesture starts with a fresh one.+ */+ readonly session: Session;++ /**+ * The element named by `@measure`, or `null` when none was named. Handed back+ * so a consumer that also needs the element itself (to paint a preview on it,+ * say) does not resolve it a second time.+ */+ readonly measured: Element | null;++ /**+ * The bounds of the element named by `@measure`, or `null` when none was+ * named. Viewport-relative, with transforms applied, so a consumer working in+ * unscaled units divides by the scale factor and subtracts `left` and `top`.+ *+ * A LIVE reading, re-read on scroll and viewport resize, so it stays correct+ * when the box moves under a held pointer. It is NOT re-read when the element+ * changes size, or on a layout shift or transform. Those raise no event.+ */+ readonly measuredRect: DOMRect | null;+}++/**+ * The box whose bounds a gesture reports: the element itself, or a function+ * receiving the pressed handle and returning it.+ */+type MeasureTarget =+ | Element+ | ((handle: HTMLElement) => Element | null | undefined);++interface DResizeHandlesSignature<+ Payload extends string | number,+ Session extends object = object,+> {+ Args: {+ /**+ * BEM block for the built-in 8-direction box. Each handle is classed+ * `<handleClass> --<dir>`. Ignored when `@handles` is supplied.+ */+ handleClass?: string;++ /**+ * A subset of the eight compass directions to render for the built-in box+ * (e.g. only the edges and corners that can actually move). Defaults to all+ * eight; ignored when `@handles` is supplied.+ */+ directions?: BoxDirection[];++ /**+ * Explicit handle descriptors. The escape hatch for anything that is not a+ * box — N column-gutter handles at computed offsets, say. Takes precedence+ * over `@handleClass`.+ */+ handles?: DResizeHandleDescriptor<Payload>[];++ /**+ * The gesture began. Snapshot the press-time state onto `dragInfo.session`+ * here. Return `false` to veto it.+ *+ * The callbacks sit in `NoInfer` positions so that `@handles` alone decides+ * the payload type. Without it a handler taking a number would infer+ * `Payload` as `number` on the built-in box, hiding a real mismatch.+ */+ onResizeStart?: (+ payload: NoInfer<Payload>,+ dragInfo: DResizeHandleDragInfo<NoInfer<Payload>, Session>+ ) => boolean | void;++ /** Fired on every move. Compute and preview here. */+ onResize?: (+ payload: NoInfer<Payload>,+ dragInfo: DResizeHandleDragInfo<NoInfer<Payload>, Session>+ ) => void;++ /**+ * Fired once on release, and on teardown for a gesture still held. Commit+ * here, guarded on `dragInfo.moved`.+ */+ onResizeEnd?: (+ payload: NoInfer<Payload>,+ dragInfo: DResizeHandleDragInfo<NoInfer<Payload>, Session>+ ) => void;++ /**+ * Fired when the gesture is cancelled rather than released, teardown with a+ * gesture still held included. Mutually exclusive with `@cancelCommits`,+ * which routes cancels to `@onResizeEnd` and so leaves this one unreachable.+ */+ onResizeCancel?: (+ payload: NoInfer<Payload>,+ dragInfo: DResizeHandleDragInfo<NoInfer<Payload>, Session>+ ) => void;++ /** A class toggled on the active handle while it is being dragged. */+ draggingClass?: string;++ /**+ * Pixels of travel before `@onResize` starts firing, to absorb the jitter of+ * a click that was never meant to be a drag.+ */+ threshold?: number;++ /**+ * Whether a gesture cut short — `pointercancel`, a lost capture, or another+ * registration claiming the pointer — reports through `@onResizeEnd` rather+ * than `@onResizeCancel`, leaving the latter unreachable.+ *+ * A consumer that commits the terminal event's position must NOT set this: a+ * cancel carries no position the user chose, so the commit would write a+ * coordinate the pointer was never at.+ */+ cancelCommits?: boolean;++ /**+ * The box being resized, so it and its bounds ride along on every report.+ * Either the element, or a function receiving the pressed handle and+ * returning it. See `measuredRect` for what is and is not re-read.+ */+ measure?: MeasureTarget;++ /**+ * Whether an accepted press stops propagating. Defaults to `false`, because+ * document-level listeners need to see `pointerdown`. Set it when the handles+ * sit inside another gesture that would otherwise steal the pointer.+ */+ stopPropagation?: boolean;+ };+}++/**+ * Renders a set of drag handles and drives each through the pointer-drag+ * lifecycle, owning what every consumer would otherwise repeat: the handle loop,+ * the per-handle pointer wiring, and one gesture's state for as long as it runs.+ *+ * It reports pointer geometry rather than a size. The consumer does the math in+ * its own units, paints its own preview, and commits on `@onResizeEnd`.+ *+ * Every gesture ends with exactly one terminal callback, whether it ends on+ * release, on its handle being removed, or on the component being destroyed.+ * Each gesture carries a `session` for press-time state.+ *+ * ONE gesture at a time. A press arriving while another is held is refused, so+ * two handles on one box can never fight over the same geometry. Two separate+ * boxes still drag at once, because each renders its own handles.+ *+ * The common case, a box's 8 edge and corner handles, is built in through+ * `@handleClass`. Anything else passes explicit `@handles` descriptors.+ *+ * @example+ * Box (edges + corners) from a BEM block:+ * ```gjs+ * <DResizeHandles @handleClass="my-block__handle" @onResize={{this.onResize}} />+ * ```+ *+ * @example+ * Escape hatch — explicit descriptors:+ * ```gjs+ * <DResizeHandles @handles={{this.columnHandles}} @onResize={{this.onResize}} />+ * ```+ *+ * `role="separator"` is wrong here and must not be used: a box resized from its+ * corners has no single value to report.+ *+ * Deliberately POINTER-ONLY. The handles are `aria-hidden` and out of the tab+ * order: eight tab stops per box would be hostile, and no ARIA role describes a+ * corner drag. Put keyboard resizing on the resized object itself.+ *+ * @see The `DResizeSeparator` component for a ONE-axis resize between two regions, which is+ * operable by keyboard and announced.+ * @see The `dOnResize` modifier to merely OBSERVE a size change. It is not a gesture.+ */+export default class DResizeHandles<+ Payload extends string | number = BoxDirection,+ Session extends object = object,+> extends Component<DResizeHandlesSignature<Payload, Session>> {+ /** The gesture in flight, or `null` when nothing is held. */+ #gesture: Gesture<Payload, Session> | null = null;++ /**+ * Re-measures the live gesture's box.+ *+ * Bound to scroll and resize for the gesture's length because the bounds are+ * viewport-relative: the box can move under a held pointer without changing+ * size, and stale bounds put the pointer in the wrong place.+ */+ #onReflow = () => {+ if (this.#gesture) {+ this.#gesture.measuredRect =+ this.#gesture.measured?.getBoundingClientRect() ?? null;+ }+ };++ #watchingReflow = false;++ constructor(+ owner: Owner,+ args: DResizeHandlesSignature<Payload, Session>["Args"]+ ) {+ super(owner, args);+ registerDestructor(this, () => this.#closeGesture());+ }++ /**+ * The resolved handle descriptors: explicit `@handles` when named, otherwise+ * the built-in box from `@handleClass`.+ *+ * The branch tests whether `@handles` was NAMED, not whether it holds+ * anything, because naming it is what `Payload` is inferred from. Falling+ * through to the box would hand compass strings to differently-typed callbacks.+ */+ get handles() {+ const source =+ "handles" in this.args ? (this.args.handles ?? []) : this.#boxHandles();++ if (DEBUG) {+ const seen = new Set<string>();+ for (const handle of source) {+ assert(+ "DResizeHandles: wrap a descriptor's `style` in `trustHTML` before passing it",+ handle.style == null || isTrustedHTML(handle.style)+ );+ // Glimmer reports neither a missing nor a duplicate key. It derives a+ // positional one, which is what keying exists to avoid.+ assert(+ "DResizeHandles: every handle descriptor needs a unique `key`",+ handle.key != null+ );+ assert(+ `DResizeHandles: two handles share the key \`${handle.key}\``,+ !seen.has(handle.key)+ );+ seen.add(handle.key);+ }+ }++ return source;+ }++ @action+ onHandleDown(payload: Payload, event: PointerEvent, info: DPointerDragInfo) {+ // Returning false vetoes the press, so only one gesture runs at a time.+ if (this.#gesture) {+ return false;+ }++ const handle = event.currentTarget as HTMLElement;+ const measured = this.#measureTarget(handle);+ const gesture: Gesture<Payload, Session> = {+ payload,+ handle,+ event,+ info,+ measured,+ measuredRect: measured?.getBoundingClientRect() ?? null,+ session: {} as Session,+ };+ this.#gesture = gesture;+ this.#watchReflow();++ let started;+ try {+ started = this.args.onResizeStart?.(+ payload,+ this.#dragInfo(gesture, event, info)+ );+ } catch (error) {+ this.#reset();+ throw error;+ }++ // The press was vetoed, so no terminal callback will arrive to clear it.+ if (started === false) {+ this.#reset();+ }++ return started;+ }++ @action+ onHandleMove(event: PointerEvent, info: DPointerDragInfo) {+ const gesture = this.#gesture;+ if (!gesture) {+ return;+ }+ // Build the report first. `onResize?.()` skips its arguments when there is+ // no handler, and the gesture's snapshot has to update either way.+ const dragInfo = this.#dragInfo(gesture, event, info);+ this.args.onResize?.(gesture.payload, dragInfo);+ }++ @action+ onHandleUp(event: PointerEvent, info: DPointerDragInfo) {+ const gesture = this.#gesture;+ if (!gesture) {+ return;+ }+ const dragInfo = this.#dragInfo(gesture, event, info);+ // Released in a `finally` so a throwing consumer cannot strand the gesture+ // and leave the reflow listeners attached.+ try {+ this.args.onResizeEnd?.(gesture.payload, dragInfo);+ } finally {+ this.#reset();+ }+ }++ @action+ onHandleCancel(event: PointerEvent, info: DPointerDragInfo) {+ const gesture = this.#gesture;+ if (!gesture) {+ return;+ }+ const dragInfo = this.#dragInfo(gesture, event, info);+ try {+ this.args.onResizeCancel?.(gesture.payload, dragInfo);+ } finally {+ this.#reset();+ }+ }++ /**+ * Closes the gesture when the handle holding it is destroyed. That happens+ * when `@handles` or `@directions` drops a handle while the pointer is down.+ *+ * The engine reports nothing when its element goes. Without this, the consumer+ * would never get to close what it opened at the press.+ *+ * @param element - The handle being torn down.+ */+ @action+ onHandleTeardown(element: Element) {+ if (this.#gesture?.handle === element) {+ this.#closeGesture();+ }+ }++ /**+ * Ends a gesture that is still held. Runs both when a single handle is+ * destroyed and when the whole component is.+ */+ #closeGesture() {+ const gesture = this.#gesture;+ if (!gesture) {+ return;+ }+ // Clear it first. At teardown the handle and the component both close the+ // gesture, and whichever runs second has to do nothing.+ this.#reset();++ const dragInfo = {+ ...gesture.info,+ payload: gesture.payload,+ event: gesture.event,+ session: gesture.session,+ measured: gesture.measured,+ measuredRect: gesture.measuredRect,+ };+ try {+ if (this.args.cancelCommits) {+ this.args.onResizeEnd?.(gesture.payload, dragInfo);+ } else {+ this.args.onResizeCancel?.(gesture.payload, dragInfo);+ }+ } catch (error) {+ // Swallowed only here. A throw from a destructor aborts the teardown+ // flush and takes every sibling's cleanup with it.+ // eslint-disable-next-line no-console+ console.error(error);+ }+ }++ #boxHandles(): DResizeHandleDescriptor<Payload>[] {+ const handleClass = this.args.handleClass;+ if (!handleClass) {+ return [];+ }+ const directions = this.args.directions ?? BOX_DIRECTIONS;+ return directions.map((dir) => ({+ // A direction appears once in a box, so it is the handle's identity too.+ key: dir,+ // The cast is safe. Only `@handles` pins `Payload` to something else, and+ // supplying it makes this branch unreachable. TypeScript cannot see that.+ payload: dir as Payload,+ class: `${handleClass} --${dir}`,+ }));+ }++ #dragInfo(+ gesture: Gesture<Payload, Session>,+ event: PointerEvent,+ info: DPointerDragInfo+ ): DResizeHandleDragInfo<Payload, Session> {+ gesture.event = event;+ gesture.info = info;++ return {+ payload: gesture.payload,+ event,+ origin: info.origin,+ current: info.current,+ delta: info.delta,+ moved: info.moved,+ session: gesture.session,+ measured: gesture.measured,+ measuredRect: gesture.measuredRect,+ };+ }++ #reset() {+ this.#gesture = null;+ this.#unwatchReflow();+ }++ #measureTarget(handle: HTMLElement): Element | null {+ const target = this.args.measure;+ return (typeof target === "function" ? target(handle) : target) ?? null;+ }++ #watchReflow() {+ // Skip the listeners when nothing is measured, which is the common case.+ // Otherwise a document-wide scroll listener fires on every scroll for nothing.+ if (this.#watchingReflow || !this.#gesture?.measured) {+ return;+ }+ this.#watchingReflow = true;+ window.addEventListener("scroll", this.#onReflow, true);+ window.addEventListener("resize", this.#onReflow);+ }++ #unwatchReflow() {+ if (!this.#watchingReflow) {+ return;+ }+ this.#watchingReflow = false;+ window.removeEventListener("scroll", this.#onReflow, true);+ window.removeEventListener("resize", this.#onReflow);+ }++ <template>+ {{! Keyed by identity so that removing a handle destroys the right one. With+ positional keys the last handle goes instead. That strands its gesture, and+ leaves the handles after the gap bound to descriptors nobody pressed. }}+ {{#each this.handles key="key" as |handle|}}+ <span+ class={{handle.class}}+ style={{handle.style}}+ data-resize-handle={{handle.payload}}+ aria-hidden="true"+ {{willDestroy this.onHandleTeardown}}+ {{dPointerDrag+ onDragStart=(fn this.onHandleDown handle.payload)+ onDrag=this.onHandleMove+ onDragEnd=this.onHandleUp+ onDragCancel=this.onHandleCancel+ draggingClass=@draggingClass+ threshold=@threshold+ stopPropagation=@stopPropagation+ cancelCommits=@cancelCommits+ }}+ ></span>+ {{/each}}+ </template>+}diff --git a/frontend/discourse/app/ui-kit/d-resize-separator.gts b/frontend/discourse/app/ui-kit/d-resize-separator.gtsindex e0f5ec1171c..a7cdc9d5d3b 100644--- a/frontend/discourse/app/ui-kit/d-resize-separator.gts+++ b/frontend/discourse/app/ui-kit/d-resize-separator.gts@@ -242,6 +242,8 @@ interface DResizeSeparatorSignature {** @see {@link dResizeEdge}, the modifier underneath. Use it directly only when the* element and its separator semantics are already yours to own.+ * @see The `DResizeHandles` component for a TWO-dimensional box resize, where the separator role+ * does not apply.* @see The `dOnResize` modifier to merely OBSERVE a size change. It is not a gesture.*/export default class DResizeSeparator extends Component<DResizeSeparatorSignature> {diff --git a/frontend/discourse/app/ui-kit/modifiers/d-on-resize.ts b/frontend/discourse/app/ui-kit/modifiers/d-on-resize.tsindex 9b38eed7f69..0c71a21d284 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-on-resize.ts+++ b/frontend/discourse/app/ui-kit/modifiers/d-on-resize.ts@@ -22,6 +22,9 @@ interface DOnResizeSignature {/*** Calls `callback` with the observed `ResizeObserverEntry`s whenever the element* resizes, throttled through the runloop. Cleans up the observer on teardown.+ *+ * @see The `DResizeSeparator` / `dResizeEdge` / `DResizeHandles` primitives to let a user+ * PERFORM a resize. The similar names are the trap; this one only watches.*/export default class DOnResize extends Modifier<DOnResizeSignature> {#resizeObserver?: ResizeObserver;diff --git a/frontend/discourse/app/ui-kit/modifiers/d-pointer-drag.ts b/frontend/discourse/app/ui-kit/modifiers/d-pointer-drag.tsindex 6c498711b71..5a78090f68b 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-pointer-drag.ts+++ b/frontend/discourse/app/ui-kit/modifiers/d-pointer-drag.ts@@ -20,39 +20,69 @@ export type TouchActionToken =*/const DEFAULT_TOUCH_ACTION: TouchActionToken = "none";+/** A point in client coordinates. */+type Point = Readonly<{ x: number; y: number }>;++/**+ * Where the gesture is, reported alongside every callback's event.+ *+ * A snapshot, not a live view. A fresh one is built per dispatch, so a consumer+ * that stores it keeps the numbers it was given.+ */+export interface DPointerDragInfo {+ /** Where the press landed. */+ readonly origin: Point;++ /** Where the pointer is now. */+ readonly current: Point;++ /** How far the pointer has travelled since the press. */+ readonly delta: Point;++ /**+ * Whether `onDrag` has fired at least once for THIS gesture. It separates a+ * drag from a click that landed on the handle.+ *+ * This is not the same as passing `threshold`. With no threshold a gesture can+ * report from the press onwards, but it may still have reported nothing.+ */+ readonly moved: boolean;+}+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.+ * Return `false` to ABORT the gesture, for example when an anchor cannot+ * be resolved. Any other return starts it. An exception here is rethrown+ * after the pointer capture is released, and no gesture starts.*/- onDragStart?: (event: PointerEvent) => boolean | void;+ onDragStart?: (+ event: PointerEvent,+ info: DPointerDragInfo+ ) => 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;+ onDrag?: (event: PointerEvent, info: DPointerDragInfo) => 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.+ * released. Fires for any release on this element, including one that never+ * reached `threshold` and saw no `onDrag`. Use `info.moved` to tell them apart.*/- onDragEnd?: (event: PointerEvent) => void;+ onDragEnd?: (event: PointerEvent, info: DPointerDragInfo) => 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;+ onDragCancel?: (event: PointerEvent, info: DPointerDragInfo) => void;/*** A class toggled on the element for the gesture's duration. A single@@ -213,6 +243,9 @@ export function registerPointerDrag(// the rest of the gesture: returning inside the threshold must not start// suppressing movement again mid-drag.let engaged = false;+ // Separate from `engaged`, which is already true at the press when no+ // threshold is set.+ let moved = 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.@@ -222,6 +255,13 @@ export function registerPointerDrag(// inside `onDragStart`, and the rest of that dispatch still runs.let tornDown = false;+ const dragInfo = (event: PointerEvent): DPointerDragInfo => ({+ origin: { x: originX, y: originY },+ current: { x: event.clientX, y: event.clientY },+ delta: { x: event.clientX - originX, y: event.clientY - originY },+ moved,+ });+const finish = () => {const finishedPointer = pointerId;const classToRemove = appliedClass;@@ -231,6 +271,7 @@ export function registerPointerDrag(// `pointerId` set would keep the gesture in flight forever.pointerId = null;engaged = false;+ moved = false;appliedClass = null;bodyClassLease = null;@@ -263,11 +304,12 @@ export function registerPointerDrag(* @param event - The event ending the gesture.*/const cancelGesture = (args: DPointerDragArgs, event: PointerEvent) => {+ const info = dragInfo(event);try {if (args.cancelCommits) {- args.onDragEnd?.(event);+ args.onDragEnd?.(event, info);} else {- args.onDragCancel?.(event);+ args.onDragCancel?.(event, info);}} finally {finish();@@ -335,10 +377,14 @@ export function registerPointerDrag(};const args = getArgsRef();- // The caller captures its origin state here and may veto by returning false.+ // Before the dispatch below, which reports them.+ originX = event.clientX;+ originY = event.clientY;+ moved = false;+let vetoed;try {- vetoed = args.onDragStart?.(event) === false;+ vetoed = args.onDragStart?.(event, dragInfo(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.@@ -354,8 +400,6 @@ export function registerPointerDrag(}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@@ -413,7 +457,9 @@ export function registerPointerDrag(}engaged = true;}- args.onDrag?.(event);+ // Latched before the dispatch, so this report already counts as movement.+ moved = true;+ args.onDrag?.(event, dragInfo(event));};const onPointerUp = (event: PointerEvent) => {@@ -425,7 +471,7 @@ export function registerPointerDrag(// throwing callback cannot leave the gesture active and reject every later// press.try {- getArgsRef().onDragEnd?.(event);+ getArgsRef().onDragEnd?.(event, dragInfo(event));} finally {finish();}diff --git a/frontend/discourse/app/ui-kit/modifiers/d-resize-edge.ts b/frontend/discourse/app/ui-kit/modifiers/d-resize-edge.tsindex 18f1fdd8190..9dcac79fbc9 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-resize-edge.ts+++ b/frontend/discourse/app/ui-kit/modifiers/d-resize-edge.ts@@ -173,6 +173,8 @@ interface DResizeEdgeSignature {* @see The `DResizeSeparator` component, which wraps this and supplies the whole block of* separator markup above. Prefer it; reach for this modifier directly only when* the element and its semantics are already yours to own.+ * @see The `DResizeHandles` component for a TWO-dimensional box resize. The separator role does+ * not apply there — a 2D resize has no single `aria-valuenow` to report.* @see The `dOnResize` modifier to merely OBSERVE a size change. It is not a gesture.*/export default class DResizeEdgeModifier extends Modifier<DResizeEdgeSignature> {diff --git a/frontend/discourse/tests/integration/ui-kit/d-resize-handles-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-resize-handles-test.gjsnew file mode 100644index 00000000000..e26c0d4503b--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/d-resize-handles-test.gjs@@ -0,0 +1,1472 @@+import { tracked } from "@glimmer/tracking";+import { trustHTML } from "@ember/template";+import {+ clearRender,+ find,+ render,+ resetOnerror,+ settled,+ setupOnerror,+ triggerEvent,+} from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import { stubPointerCapture } from "discourse/tests/helpers/ui-kit/pointer-gesture-helper";+import DResizeHandles from "discourse/ui-kit/d-resize-handles";++module("Integration | ui-kit | DResizeHandles", function (hooks) {+ setupRenderingTest(hooks);++ test("renders a handle per descriptor and passes its class through", async function (assert) {+ const handles = [+ { payload: "e", key: "e", class: "handle-e" },+ { payload: "s", key: "s", class: "handle-s" },+ ];++ await render(<template><DResizeHandles @handles={{handles}} /></template>);++ assert+ .dom("[data-resize-handle]")+ .exists({ count: 2 }, "renders one handle per descriptor");+ assert.dom(".handle-e").exists("forwards the descriptor's class");+ assert+ .dom("[data-resize-handle='e']")+ .exists("tags each handle with its payload");+ });++ test("@handleClass renders the 8-direction box with standalone modifiers", async function (assert) {+ await render(+ <template><DResizeHandles @handleClass="my-block__handle" /></template>+ );++ assert+ .dom("[data-resize-handle]")+ .exists({ count: 8 }, "renders the eight compass handles");+ assert+ .dom("[data-resize-handle='ne']")+ .hasClass("my-block__handle", "applies the base class")+ .hasClass("--ne", "applies the standalone direction modifier")+ .doesNotHaveClass(+ "my-block__handle--ne",+ "does not generate a suffixed BEM modifier"+ );+ assert+ .dom("[data-resize-handle='w']")+ .hasClass("--w", "each direction gets its standalone modifier");+ });++ test("naming @handles opts out of the box even when it resolves to nothing", async function (assert) {+ // `Payload` is inferred from `@handles`, so a consumer whose descriptors are+ // momentarily undefined has callbacks typed for its own payload. Falling+ // back to the box here would hand those callbacks compass strings instead,+ // type-checked and wrong.+ const noHandles = undefined;++ await render(+ <template>+ <DResizeHandles+ @handleClass="my-block__handle"+ @handles={{noHandles}}+ />+ </template>+ );++ assert+ .dom("[data-resize-handle]")+ .doesNotExist("renders no handles rather than eight compass ones");+ });++ test("@directions renders exactly the subset it names", async function (assert) {+ const directions = ["n", "se"];++ await render(+ <template>+ <DResizeHandles+ @handleClass="my-block__handle"+ @directions={{directions}}+ />+ </template>+ );++ assert+ .dom("[data-resize-handle]")+ .exists({ count: 2 }, "renders only the named directions");+ assert.dom("[data-resize-handle='n']").exists("renders the north handle");+ assert+ .dom("[data-resize-handle='se']")+ .exists("renders the south-east handle");+ assert+ .dom("[data-resize-handle='e']")+ .doesNotExist("and none of the six it did not name");+ });++ test("@draggingClass marks the handle being dragged, and only it", async function (assert) {+ await render(+ <template>+ <DResizeHandles+ @handleClass="my-block__handle"+ @draggingClass="--dragging"+ />+ </template>+ );++ const east = stubPointerCapture("[data-resize-handle='e']").element;+ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ assert+ .dom("[data-resize-handle='e']")+ .hasClass("--dragging", "the pressed handle carries the class");+ assert+ .dom("[data-resize-handle='w']")+ .doesNotHaveClass("--dragging", "its siblings do not");++ await triggerEvent(east, "pointerup", {+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ assert+ .dom("[data-resize-handle='e']")+ .doesNotHaveClass("--dragging", "and it is dropped on release");+ });++ test("a descriptor's trusted style is applied without a dynamic-style warning", async function (assert) {+ const warn = sinon.stub(console, "warn");+ const handles = [+ {+ payload: "gutter",+ key: "gutter",+ class: "handle-gutter",+ style: trustHTML("grid-column: 3"),+ },+ ];++ await render(<template><DResizeHandles @handles={{handles}} /></template>);++ assert+ .dom(".handle-gutter")+ .hasAttribute("style", "grid-column: 3", "the style reaches the element");+ // The component passes the trusted value straight through. If it re-wrapped+ // or stringified it, the style would still land and only this would catch it.+ assert.false(+ warn.getCalls().some((call) => String(call.args[0]).includes("style")),+ "and does so without tripping the dynamic-style warning"+ );+ });++ test("a descriptor's plain style string is refused rather than trusted", async function (assert) {+ const consoleError = sinon.stub(console, "error");+ const handles = [+ {+ payload: "gutter",+ key: "gutter",+ class: "handle-gutter",+ style: "grid-column: 3",+ },+ ];+ let errors = 0;++ // Only the caller knows whether it interpolated anything unsafe, so the+ // component will not trust the string on its behalf.+ setupOnerror((error) => {+ assert.true(+ error.message.includes("trustHTML"),+ "the assertion names the call the consumer has to make"+ );+ errors++;+ });++ await render(<template><DResizeHandles @handles={{handles}} /></template>);++ assert.strictEqual(errors, 1, "the untrusted style is reported once");++ resetOnerror();+ consoleError.restore();+ });++ test("a descriptor with no key is refused rather than keyed by position", async function (assert) {+ const consoleError = sinon.stub(console, "error");+ const handles = [{ payload: "gutter", class: "handle-gutter" }];+ let errors = 0;++ // Glimmer would fall back to position here, which is the bug keys exist to+ // remove, and it would do it without saying anything.+ setupOnerror((error) => {+ assert.true(+ error.message.includes("every handle descriptor needs"),+ "the assertion names what is missing"+ );+ errors++;+ });++ await render(<template><DResizeHandles @handles={{handles}} /></template>);++ assert.strictEqual(errors, 1, "the missing key is reported once");++ resetOnerror();+ consoleError.restore();+ });++ test("@measure reports the resized box's bounds, not the handle's", async function (assert) {+ let reported = null;+ const onResizeStart = (payload, info) => (reported = info.measuredRect);+ const findBox = (handle) =>+ handle.closest(".fixture")?.querySelector(".box");++ await render(+ <template>+ <div class="fixture">+ <div class="box" style="width: 220px; height: 90px"></div>+ <DResizeHandles+ @handleClass="my-block__handle"+ @measure={{findBox}}+ @onResizeStart={{onResizeStart}}+ />+ </div>+ </template>+ );++ const east = stubPointerCapture("[data-resize-handle='e']").element;+ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ const box = find(".box").getBoundingClientRect();+ assert.strictEqual(+ reported?.width,+ box.width,+ "reports the measured box's width"+ );+ assert.strictEqual(+ reported?.height,+ box.height,+ "and its height, which a 6px handle's own bounds could never give"+ );+ });++ test("@measure is absent by default rather than reporting something arbitrary", async function (assert) {+ let reported = "untouched";+ const onResizeStart = (payload, info) => (reported = info.measuredRect);++ await render(+ <template>+ <DResizeHandles+ @handleClass="my-block__handle"+ @onResizeStart={{onResizeStart}}+ />+ </template>+ );++ const east = stubPointerCapture("[data-resize-handle='e']").element;+ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ assert.strictEqual(reported, null, "nothing to measure, nothing reported");+ });++ test("@measure accepts the element itself, not only a function", async function (assert) {+ let reported = null;+ const onResizeStart = (payload, info) => (reported = info.measuredRect);+ const body = document.body;++ await render(+ <template>+ <DResizeHandles+ @handleClass="my-block__handle"+ @measure={{body}}+ @onResizeStart={{onResizeStart}}+ />+ </template>+ );++ const east = stubPointerCapture("[data-resize-handle='e']").element;+ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ assert.strictEqual(+ reported?.width,+ document.body.getBoundingClientRect().width,+ "an element target is measured directly"+ );+ });++ test("@measure hands back the element alongside its bounds", async function (assert) {+ let reported = null;+ const onResizeStart = (payload, info) => (reported = info.measured);+ const findBox = (handle) =>+ handle.closest(".fixture")?.querySelector(".box");++ await render(+ <template>+ <div class="fixture">+ <div class="box" style="width: 220px; height: 90px"></div>+ <DResizeHandles+ @handleClass="my-block__handle"+ @measure={{findBox}}+ @onResizeStart={{onResizeStart}}+ />+ </div>+ </template>+ );++ const east = stubPointerCapture("[data-resize-handle='e']").element;+ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ assert.strictEqual(+ reported,+ find(".box"),+ "so a consumer painting a preview on it need not resolve it again"+ );+ });++ test("@measure re-reads the box when it moves under a held gesture", async function (assert) {+ const rects = [];+ const onResize = (payload, info) => rects.push(info.measuredRect);+ const findBox = (handle) =>+ handle.closest(".fixture")?.querySelector(".box");++ await render(+ <template>+ <div class="fixture">+ <div class="box" style="width: 220px; height: 90px"></div>+ <DResizeHandles+ @handleClass="my-block__handle"+ @measure={{findBox}}+ @onResize={{onResize}}+ />+ </div>+ </template>+ );++ const east = stubPointerCapture("[data-resize-handle='e']").element;+ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(east, "pointermove", {+ pointerId: 1,+ clientX: 10,+ clientY: 0,+ });+ const before = rects.at(-1).left;++ // The box moves without changing size, as a scroll would move it. Bounds+ // frozen at press-time would land the pointer in the wrong place for the+ // rest of the gesture.+ find(".box").style.marginLeft = "40px";+ window.dispatchEvent(new Event("scroll"));+ await settled();++ // Read rather than computed: the test container is scaled, so the viewport+ // delta is not the margin that produced it.+ const moved = find(".box").getBoundingClientRect().left;+ assert.notStrictEqual(moved, before, "control: the box really did move");++ await triggerEvent(east, "pointermove", {+ pointerId: 1,+ clientX: 20,+ clientY: 0,+ });++ assert.strictEqual(+ rects.at(-1).left,+ moved,+ "the reported bounds follow the box"+ );+ });++ test("the reflow listeners are released when the gesture ends", async function (assert) {+ const findBox = (handle) =>+ handle.closest(".fixture")?.querySelector(".box");++ await render(+ <template>+ <div class="fixture">+ <div class="box" style="width: 220px; height: 90px"></div>+ <DResizeHandles+ @handleClass="my-block__handle"+ @measure={{findBox}}+ />+ </div>+ </template>+ );++ const east = stubPointerCapture("[data-resize-handle='e']").element;+ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ // Spied only from here, so the release's own detach is the one observed.+ const removeSpy = sinon.spy(window, "removeEventListener");+ await triggerEvent(east, "pointerup", {+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ assert.true(+ removeSpy+ .getCalls()+ .some((call) => call.args[0] === "scroll" && call.args[2] === true),+ "the capture-phase scroll listener does not outlive the gesture"+ );+ });++ test("a refused press releases what it reserved", async function (assert) {+ const onResizeStart = () => false;+ const findBox = (handle) =>+ handle.closest(".fixture")?.querySelector(".box");++ await render(+ <template>+ <div class="fixture">+ <div class="box" style="width: 220px; height: 90px"></div>+ <DResizeHandles+ @handleClass="my-block__handle"+ @measure={{findBox}}+ @onResizeStart={{onResizeStart}}+ />+ </div>+ </template>+ );++ const east = stubPointerCapture("[data-resize-handle='e']").element;+ const removeSpy = sinon.spy(window, "removeEventListener");+ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ // A vetoed press starts no gesture, so no terminal callback will ever+ // arrive to clean up after it. Observed through the listeners rather than+ // the gesture map, because a later press on the same pointer id would+ // overwrite a stranded entry and hide the leak.+ assert.true(+ removeSpy+ .getCalls()+ .some((call) => call.args[0] === "scroll" && call.args[2] === true),+ "the refused press leaves no listener behind"+ );+ });++ test("a throwing commit callback still releases the gesture", async function (assert) {+ const onResizeEnd = () => {+ throw new Error("consumer failure");+ };+ const findBox = (handle) =>+ handle.closest(".fixture")?.querySelector(".box");++ await render(+ <template>+ <div class="fixture">+ <div class="box" style="width: 220px; height: 90px"></div>+ <DResizeHandles+ @handleClass="my-block__handle"+ @measure={{findBox}}+ @onResizeEnd={{onResizeEnd}}+ />+ </div>+ </template>+ );++ const east = stubPointerCapture("[data-resize-handle='e']").element;+ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ const removeSpy = sinon.spy(window, "removeEventListener");+ // The throw is the consumer's bug and is rethrown, so it surfaces as an+ // uncaught error rather than a rejected promise. Swallowed here so the+ // assertion below is about cleanup rather than about the throw.+ const priorOnError = window.onerror;+ window.onerror = (...args) =>+ args[4]?.message === "consumer failure" || priorOnError?.(...args);+ try {+ await triggerEvent(east, "pointerup", {+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ } finally {+ window.onerror = priorOnError;+ }++ assert.true(+ removeSpy+ .getCalls()+ .some((call) => call.args[0] === "scroll" && call.args[2] === true),+ "a consumer that throws cannot strand the gesture's listeners"+ );+ });++ test("a second press is refused while a gesture is held", async function (assert) {+ const handles = [+ { payload: "nw", key: "nw", class: "handle-nw" },+ { payload: "se", key: "se", class: "handle-se" },+ ];+ const events = [];+ const onResizeStart = (payload) => events.push(`start:${payload}`);+ const onResize = (payload, info) =>+ events.push(`resize:${payload}:${info.delta.x}`);+ const onResizeEnd = (payload) => events.push(`end:${payload}`);++ await render(+ <template>+ <DResizeHandles+ @handles={{handles}}+ @onResizeStart={{onResizeStart}}+ @onResize={{onResize}}+ @onResizeEnd={{onResizeEnd}}+ />+ </template>+ );++ stubPointerCapture(".handle-nw");+ stubPointerCapture(".handle-se");++ await triggerEvent(".handle-nw", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 100,+ clientY: 100,+ });+ // A second finger on another handle of the same box. One gesture at a time,+ // so this press never starts.+ await triggerEvent(".handle-se", "pointerdown", {+ button: 0,+ pointerId: 2,+ clientX: 400,+ clientY: 400,+ });+ await triggerEvent(".handle-se", "pointermove", {+ pointerId: 2,+ clientX: 430,+ clientY: 430,+ });+ await triggerEvent(".handle-nw", "pointermove", {+ pointerId: 1,+ clientX: 120,+ clientY: 100,+ });+ await triggerEvent(".handle-nw", "pointerup", {+ pointerId: 1,+ clientX: 120,+ clientY: 100,+ });++ assert.deepEqual(+ events,+ ["start:nw", "resize:nw:20", "end:nw"],+ "the refused press reports nothing and the held gesture is untouched"+ );+ });++ test("@onResizeCancel fires when the gesture is cancelled rather than released", async function (assert) {+ const events = [];+ const onResizeEnd = (payload) => events.push(`end:${payload}`);+ const onResizeCancel = (payload) => events.push(`cancel:${payload}`);++ await render(+ <template>+ <DResizeHandles+ @handleClass="my-block__handle"+ @onResizeEnd={{onResizeEnd}}+ @onResizeCancel={{onResizeCancel}}+ />+ </template>+ );++ const east = stubPointerCapture("[data-resize-handle='e']").element;+ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(east, "pointercancel", {+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ assert.deepEqual(+ events,+ ["cancel:e"],+ "a cancel reaches the cancel callback and not the end callback"+ );+ });++ test("handles are hidden from assistive technology", async function (assert) {+ await render(+ <template><DResizeHandles @handleClass="my-block__handle" /></template>+ );++ // They are pointer affordances with no accessible name and no tab stop, so+ // exposing them would announce eight nameless nodes per box. Keyboard+ // operation is the consumer's job, on the resized object itself.+ assert+ .dom("[data-resize-handle='ne']")+ .hasAttribute("aria-hidden", "true", "each handle is hidden from AT");+ });++ test("explicit @handles take precedence over @handleClass", async function (assert) {+ const handles = [+ { payload: "only", key: "only", class: "explicit-handle" },+ ];++ await render(+ <template>+ <DResizeHandles @handleClass="my-block__handle" @handles={{handles}} />+ </template>+ );++ assert+ .dom("[data-resize-handle]")+ .exists({ count: 1 }, "the escape hatch wins over the box default");+ assert.dom(".explicit-handle").exists();+ });++ test("dispatches start / resize / end with the payload and the pointer delta", async function (assert) {+ const handles = [{ payload: "e", key: "e", class: "handle-e" }];+ const events = [];+ const onResizeStart = (payload) => events.push(`start:${payload}`);+ const onResize = (payload, info) =>+ events.push(`resize:${payload}:${info.delta.x},${info.delta.y}`);+ const onResizeEnd = (payload) => events.push(`end:${payload}`);++ await render(+ <template>+ <DResizeHandles+ @handles={{handles}}+ @onResizeStart={{onResizeStart}}+ @onResize={{onResize}}+ @onResizeEnd={{onResizeEnd}}+ />+ </template>+ );++ stubPointerCapture(".handle-e");+ await triggerEvent(".handle-e", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 100,+ clientY: 50,+ });+ await triggerEvent(".handle-e", "pointermove", {+ pointerId: 1,+ clientX: 130,+ clientY: 60,+ });+ await triggerEvent(".handle-e", "pointerup", {+ pointerId: 1,+ clientX: 130,+ clientY: 60,+ });++ assert.deepEqual(+ events,+ ["start:e", "resize:e:30,10", "end:e"],+ "reports the handle payload and the origin→current delta"+ );+ });++ test("a vetoed press starts no gesture and does not spoil the next one", async function (assert) {+ const handles = [{ payload: "e", key: "e", class: "handle-e" }];+ const events = [];+ const state = { veto: true };+ const onResizeStart = () => (state.veto ? false : undefined);+ const onResize = (payload, info) =>+ events.push(`resize:${payload}:${info.delta.x}`);+ const onResizeEnd = (payload) => events.push(`end:${payload}`);++ await render(+ <template>+ <DResizeHandles+ @handles={{handles}}+ @onResizeStart={{onResizeStart}}+ @onResize={{onResize}}+ @onResizeEnd={{onResizeEnd}}+ />+ </template>+ );++ stubPointerCapture(".handle-e");+ await triggerEvent(".handle-e", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 100,+ clientY: 50,+ });+ await triggerEvent(".handle-e", "pointermove", {+ pointerId: 1,+ clientX: 130,+ clientY: 50,+ });+ await triggerEvent(".handle-e", "pointerup", {+ pointerId: 1,+ clientX: 130,+ clientY: 50,+ });++ assert.deepEqual(+ events,+ [],+ "returning false from the start callback refuses the drag outright"+ );++ // The same pointer presses again, elsewhere, and is accepted this time.+ // Each press records where it began under the pointer's own id, so this+ // measures from 200 rather than carrying anything over from the press that+ // was refused.+ state.veto = false;+ await triggerEvent(".handle-e", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 200,+ clientY: 50,+ });+ await triggerEvent(".handle-e", "pointermove", {+ pointerId: 1,+ clientX: 230,+ clientY: 50,+ });+ await triggerEvent(".handle-e", "pointerup", {+ pointerId: 1,+ clientX: 230,+ clientY: 50,+ });++ assert.deepEqual(+ events,+ ["resize:e:30", "end:e"],+ "the accepted press measures from where it began"+ );+ });++ test("replacing a held descriptor ends its gesture rather than rebinding it", async function (assert) {+ const state = new (class {+ @tracked+ handles = [{ payload: "first", key: "first", class: "handle-x" }];+ })();+ const events = [];+ const onResize = (payload) => events.push(`resize:${payload}`);+ const onResizeCancel = (payload) => events.push(`cancel:${payload}`);++ await render(+ <template>+ <DResizeHandles+ @handles={{state.handles}}+ @onResize={{onResize}}+ @onResizeCancel={{onResizeCancel}}+ />+ </template>+ );++ stubPointerCapture(".handle-x");+ await triggerEvent(".handle-x", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 100,+ clientY: 50,+ });+ await triggerEvent(".handle-x", "pointermove", {+ pointerId: 1,+ clientX: 120,+ clientY: 50,+ });++ state.handles = [{ payload: "second", key: "second", class: "handle-x" }];+ await settled();++ await triggerEvent(".handle-x", "pointermove", {+ pointerId: 1,+ clientX: 140,+ clientY: 50,+ });++ // The handle the user grabbed is gone, so the gesture ends on the payload it+ // started with. Reporting the descriptor that replaced it would commit+ // something the user never touched.+ assert.deepEqual(+ events,+ ["resize:first", "cancel:first"],+ "the gesture ends rather than retargeting the replacement"+ );++ await triggerEvent(".handle-x", "pointerup", {+ pointerId: 1,+ clientX: 140,+ clientY: 50,+ });++ assert.deepEqual(+ events,+ ["resize:first", "cancel:first"],+ "and the release of a gesture already ended reports nothing further"+ );+ });++ test("removing the held handle ends its gesture and leaves its neighbours in place", async function (assert) {+ const state = new (class {+ @tracked+ handles = [+ { payload: "a", key: "a", class: "handle-a" },+ { payload: "b", key: "b", class: "handle-b" },+ { payload: "c", key: "c", class: "handle-c" },+ ];+ })();+ const events = [];+ const onResize = (payload) => events.push(`resize:${payload}`);+ const onResizeCancel = (payload) => events.push(`cancel:${payload}`);++ await render(+ <template>+ <DResizeHandles+ @handles={{state.handles}}+ @onResize={{onResize}}+ @onResizeCancel={{onResizeCancel}}+ />+ </template>+ );++ const cBefore = find(".handle-c");+ stubPointerCapture(".handle-b");+ await triggerEvent(".handle-b", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 100,+ clientY: 50,+ });+ await triggerEvent(".handle-b", "pointermove", {+ pointerId: 1,+ clientX: 120,+ clientY: 50,+ });++ state.handles = [+ { payload: "a", key: "a", class: "handle-a" },+ { payload: "c", key: "c", class: "handle-c" },+ ];+ await settled();++ assert.deepEqual(+ events,+ ["resize:b", "cancel:b"],+ "the gesture on the removed handle is closed exactly once"+ );+ assert+ .dom(".handle-b")+ .doesNotExist("the removed descriptor's handle is gone");+ // With positional keys the LAST handle goes instead. That destroys `c` and+ // leaves `b` bound to whatever moved into its slot.+ assert.strictEqual(+ find(".handle-c"),+ cBefore,+ "a handle that was not removed keeps its element"+ );+ });++ test("@directions shrinking mid-gesture ends the gesture on the handle it removed", async function (assert) {+ const state = new (class {+ @tracked directions = ["n", "e", "s"];+ })();+ const events = [];+ const onResize = (payload) => events.push(`resize:${payload}`);+ const onResizeCancel = (payload) => events.push(`cancel:${payload}`);++ await render(+ <template>+ <DResizeHandles+ @handleClass="my-block__handle"+ @directions={{state.directions}}+ @onResize={{onResize}}+ @onResizeCancel={{onResizeCancel}}+ />+ </template>+ );++ stubPointerCapture("[data-resize-handle='e']");+ await triggerEvent("[data-resize-handle='e']", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 100,+ clientY: 50,+ });+ await triggerEvent("[data-resize-handle='e']", "pointermove", {+ pointerId: 1,+ clientX: 120,+ clientY: 50,+ });++ state.directions = ["n", "s"];+ await settled();++ assert.deepEqual(+ events,+ ["resize:e", "cancel:e"],+ "the built-in box closes the gesture on the direction it dropped"+ );+ });++ test("@cancelCommits routes a removed handle's gesture to the commit callback", async function (assert) {+ const state = new (class {+ @tracked+ handles = [+ { payload: "a", key: "a", class: "handle-a" },+ { payload: "b", key: "b", class: "handle-b" },+ ];+ })();+ const ends = [];+ const cancels = [];+ const onResizeEnd = (payload, info) =>+ ends.push(`${payload}:moved=${info.moved}`);+ const onResizeCancel = (payload) => cancels.push(payload);++ await render(+ <template>+ <DResizeHandles+ @handles={{state.handles}}+ @cancelCommits={{true}}+ @onResizeEnd={{onResizeEnd}}+ @onResizeCancel={{onResizeCancel}}+ />+ </template>+ );++ stubPointerCapture(".handle-b");+ await triggerEvent(".handle-b", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 100,+ clientY: 50,+ });+ await triggerEvent(".handle-b", "pointermove", {+ pointerId: 1,+ clientX: 130,+ clientY: 50,+ });++ state.handles = [{ payload: "a", key: "a", class: "handle-a" }];+ await settled();++ // `moved` has to survive. A handle destroyed before the first move must not+ // look like a resize worth committing.+ assert.deepEqual(ends, ["b:moved=true"], "the commit callback gets it");+ assert.deepEqual(cancels, [], "and the cancel callback stays unreachable");+ });++ test("a recompute that changes nothing leaves a live gesture alone", async function (assert) {+ const state = new (class {+ @tracked seed = 0;++ // A getter over tracked state returns fresh objects on every read. Keys+ // based on object identity would rebuild every handle here and cancel the+ // gesture, which is worse than the bug this fixes. The seed rides along in+ // the class so the test can prove the recompute really happened.+ get handles() {+ return [+ { payload: "a", key: "a", class: `handle-a seed-${this.seed}` },+ { payload: "b", key: "b", class: `handle-b seed-${this.seed}` },+ ];+ }+ })();+ const events = [];+ const onResize = (payload) => events.push(`resize:${payload}`);+ const onResizeCancel = (payload) => events.push(`cancel:${payload}`);+ const onResizeEnd = (payload) => events.push(`end:${payload}`);++ await render(+ <template>+ <DResizeHandles+ @handles={{state.handles}}+ @onResize={{onResize}}+ @onResizeCancel={{onResizeCancel}}+ @onResizeEnd={{onResizeEnd}}+ />+ </template>+ );++ const bBefore = find(".handle-b");+ stubPointerCapture(".handle-b");+ await triggerEvent(".handle-b", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 100,+ clientY: 50,+ });++ state.seed = 1;+ await settled();++ // Without this the test would pass by never re-rendering at all.+ assert+ .dom(".handle-b")+ .hasClass("seed-1", "control: the descriptors really were rebuilt");++ await triggerEvent(".handle-b", "pointermove", {+ pointerId: 1,+ clientX: 120,+ clientY: 50,+ });+ await triggerEvent(".handle-b", "pointerup", {+ pointerId: 1,+ clientX: 120,+ clientY: 50,+ });++ assert.strictEqual(+ find(".handle-b"),+ bBefore,+ "the handle keeps its element across the recompute"+ );+ assert.deepEqual(+ events,+ ["resize:b", "end:b"],+ "and the gesture runs to its own release, uninterrupted"+ );+ });++ test("handles sharing a payload are told apart", async function (assert) {+ const state = new (class {+ @tracked+ handles = [+ { payload: 0, key: "run-a", class: "handle-run-a" },+ { payload: 0, key: "run-b", class: "handle-run-b" },+ { payload: 1, key: "other", class: "handle-other" },+ ];+ })();+ const events = [];+ const onResizeCancel = (payload) => events.push(`cancel:${payload}`);++ await render(+ <template>+ <DResizeHandles+ @handles={{state.handles}}+ @onResizeCancel={{onResizeCancel}}+ />+ </template>+ );++ assert+ .dom("[data-resize-handle]")+ .exists({ count: 3 }, "a repeated payload is not a duplicate key");++ const runABefore = find(".handle-run-a");+ stubPointerCapture(".handle-run-b");+ await triggerEvent(".handle-run-b", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 100,+ clientY: 50,+ });++ // One run of a gridline disappears while another run of the same line is+ // being dragged. Both carry the same payload, so the key has to tell them+ // apart.+ state.handles = [+ { payload: 0, key: "run-a", class: "handle-run-a" },+ { payload: 1, key: "other", class: "handle-other" },+ ];+ await settled();++ assert.deepEqual(+ events,+ ["cancel:0"],+ "only the removed run's gesture is closed"+ );+ assert.strictEqual(+ find(".handle-run-a"),+ runABefore,+ "the surviving run of the same payload keeps its element"+ );+ });++ test("removing an earlier twin leaves a gesture on the later one alone", async function (assert) {+ const state = new (class {+ @tracked+ handles = [+ { payload: 0, key: "run-a", class: "handle-run-a" },+ { payload: 0, key: "run-b", class: "handle-run-b" },+ ];+ })();+ const events = [];+ const onResizeCancel = (payload) => events.push(`cancel:${payload}`);++ await render(+ <template>+ <DResizeHandles+ @handles={{state.handles}}+ @onResizeCancel={{onResizeCancel}}+ />+ </template>+ );++ const runBBefore = find(".handle-run-b");+ stubPointerCapture(".handle-run-b");+ await triggerEvent(".handle-run-b", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 100,+ clientY: 50,+ });++ // The dragged run survives and the one before it goes. Anything positional+ // would shift here and cancel a live gesture; the key does not move.+ state.handles = [{ payload: 0, key: "run-b", class: "handle-run-b" }];+ await settled();++ assert.deepEqual(events, [], "the surviving run keeps its gesture");+ assert.strictEqual(+ find(".handle-run-b"),+ runBBefore,+ "and its element is not rebuilt"+ );+ });++ test("removing a measured handle mid-gesture releases the reflow listeners", async function (assert) {+ const state = new (class {+ @tracked+ handles = [+ { payload: "a", key: "a", class: "handle-a" },+ { payload: "b", key: "b", class: "handle-b" },+ ];+ })();+ const findBox = (handle) =>+ handle.closest(".fixture")?.querySelector(".box");++ await render(+ <template>+ <div class="fixture">+ <div class="box" style="width: 220px; height: 90px"></div>+ <DResizeHandles @handles={{state.handles}} @measure={{findBox}} />+ </div>+ </template>+ );++ stubPointerCapture(".handle-b");+ await triggerEvent(".handle-b", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 100,+ clientY: 50,+ });++ const removeSpy = sinon.spy(window, "removeEventListener");+ state.handles = [{ payload: "a", key: "a", class: "handle-a" }];+ await settled();++ // A stranded gesture used to leave this document-wide scroll listener+ // attached for the rest of the component's life.+ assert.true(+ removeSpy+ .getCalls()+ .some((call) => call.args[0] === "scroll" && call.args[2] === true),+ "the destroyed handle takes its listeners with it"+ );+ });++ test("@stopPropagation keeps the press from reaching an ancestor", async function (assert) {+ const handles = [{ payload: "e", key: "e", class: "handle-e" }];+ const ancestorPresses = [];++ await render(+ <template>+ <div class="ancestor">+ <DResizeHandles @handles={{handles}} @stopPropagation={{true}} />+ </div>+ </template>+ );++ find(".ancestor").addEventListener("pointerdown", () =>+ ancestorPresses.push("ancestor")+ );+ stubPointerCapture(".handle-e");+ await triggerEvent(".handle-e", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ assert.deepEqual(+ ancestorPresses,+ [],+ "an isolated handle does not let an enclosing gesture claim the pointer"+ );+ });++ test("a press reaches an ancestor by default", async function (assert) {+ const handles = [{ payload: "e", key: "e", class: "handle-e" }];+ const ancestorPresses = [];++ await render(+ <template>+ <div class="ancestor">+ <DResizeHandles @handles={{handles}} />+ </div>+ </template>+ );++ find(".ancestor").addEventListener("pointerdown", (event) =>+ ancestorPresses.push(event.defaultPrevented ? "accepted" : "ancestor")+ );+ stubPointerCapture(".handle-e");+ await triggerEvent(".handle-e", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ // Read through `defaultPrevented`, which only an accepted press sets. A press+ // that started no gesture bubbles too, so the ancestor seeing it proves+ // nothing on its own.+ assert.deepEqual(+ ancestorPresses,+ ["accepted"],+ "suppression stays opt-in, so document-level listeners still see a press that did start a gesture"+ );+ });++ test("@threshold suppresses jitter before the first resize", async function (assert) {+ const handles = [{ payload: "e", key: "e", class: "handle-e" }];+ const events = [];+ const onResize = (payload, info) => events.push(`resize:${info.delta.x}`);+ const onResizeEnd = () => events.push("end");++ await render(+ <template>+ <DResizeHandles+ @handles={{handles}}+ @threshold={{10}}+ @onResize={{onResize}}+ @onResizeEnd={{onResizeEnd}}+ />+ </template>+ );++ stubPointerCapture(".handle-e");+ await triggerEvent(".handle-e", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(".handle-e", "pointermove", {+ pointerId: 1,+ clientX: 4,+ clientY: 0,+ });++ assert.deepEqual(+ events,+ [],+ "movement inside the threshold reports nothing"+ );++ await triggerEvent(".handle-e", "pointermove", {+ pointerId: 1,+ clientX: 12,+ clientY: 0,+ });+ await triggerEvent(".handle-e", "pointerup", {+ pointerId: 1,+ clientX: 12,+ clientY: 0,+ });++ assert.deepEqual(+ events,+ ["resize:12", "end"],+ "past the threshold the full delta from the press origin is reported"+ );+ });++ test("a gesture still held at teardown is cancelled once", async function (assert) {+ const handles = [{ payload: "e", key: "e", class: "handle-e" }];+ const events = [];+ const onResizeCancel = (payload) => events.push(`cancel:${payload}`);+ const onResizeEnd = (payload) => events.push(`end:${payload}`);++ await render(+ <template>+ <DResizeHandles+ @handles={{handles}}+ @onResizeCancel={{onResizeCancel}}+ @onResizeEnd={{onResizeEnd}}+ />+ </template>+ );++ stubPointerCapture(".handle-e");+ await triggerEvent(".handle-e", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(".handle-e", "pointermove", {+ pointerId: 1,+ clientX: 30,+ clientY: 0,+ });++ await clearRender();++ // The engine reports nothing when the element goes, so whatever the consumer+ // opened at the press would stay open with no callback left to close it.+ assert.deepEqual(+ events,+ ["cancel:e"],+ "the held gesture is cancelled exactly once on the way out"+ );+ });++ test("a gesture that already ended is not cancelled again at teardown", async function (assert) {+ const handles = [{ payload: "e", key: "e", class: "handle-e" }];+ const events = [];+ const onResizeCancel = (payload) => events.push(`cancel:${payload}`);+ const onResizeEnd = (payload) => events.push(`end:${payload}`);++ await render(+ <template>+ <DResizeHandles+ @handles={{handles}}+ @onResizeCancel={{onResizeCancel}}+ @onResizeEnd={{onResizeEnd}}+ />+ </template>+ );++ stubPointerCapture(".handle-e");+ await triggerEvent(".handle-e", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(".handle-e", "pointerup", {+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ assert.deepEqual(events, ["end:e"], "the release reported once");++ await clearRender();++ assert.deepEqual(+ events,+ ["end:e"],+ "and teardown has nothing left to close"+ );+ });++ test("@cancelCommits routes a gesture held at teardown to the commit callback", async function (assert) {+ const handles = [{ payload: "e", key: "e", class: "handle-e" }];+ const events = [];+ const onResizeCancel = (payload) => events.push(`cancel:${payload}`);+ const onResizeEnd = (payload) => events.push(`end:${payload}`);++ await render(+ <template>+ <DResizeHandles+ @handles={{handles}}+ @cancelCommits={{true}}+ @onResizeCancel={{onResizeCancel}}+ @onResizeEnd={{onResizeEnd}}+ />+ </template>+ );++ stubPointerCapture(".handle-e");+ await triggerEvent(".handle-e", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(".handle-e", "pointermove", {+ pointerId: 1,+ clientX: 30,+ clientY: 0,+ });++ await clearRender();++ // Teardown is an end the pointer was never released for, so it reports the+ // way every other such end does rather than inventing a third route.+ assert.deepEqual(+ events,+ ["end:e"],+ "the held gesture commits instead of cancelling"+ );+ });++ test("a throwing consumer cannot abort the teardown of its siblings", async function (assert) {+ const handles = [{ payload: "e", key: "e", class: "handle-e" }];+ const onResizeCancel = () => {+ throw new Error("consumer blew up on teardown");+ };+ const errors = sinon.stub(console, "error");++ await render(+ <template>+ <DResizeHandles+ @handles={{handles}}+ @onResizeCancel={{onResizeCancel}}+ />+ </template>+ );++ stubPointerCapture(".handle-e");+ await triggerEvent(".handle-e", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ // A destructor throws into the flush tearing down every sibling component,+ // and would take their cleanup with it.+ await clearRender();++ assert.true(+ errors.calledOnce,+ "the consumer's exception is reported rather than escaping the flush"+ );+ });+});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.gjsindex 5d5858fe244..ade075be533 100644--- 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@@ -46,6 +46,126 @@ function caughtError(callback) {module("Integration | ui-kit | d-pointer-drag", function (hooks) {setupRenderingTest(hooks);+ test("reports the gesture geometry alongside every event", async function (assert) {+ const seen = [];+ const record = (phase) => (event, info) =>+ seen.push(+ `${phase}:origin=${info.origin.x},${info.origin.y}` ++ ` current=${info.current.x},${info.current.y}` ++ ` delta=${info.delta.x},${info.delta.y}` ++ ` moved=${info.moved}`+ );++ await render(+ <template>+ <div+ class="dpd-target"+ {{dPointerDrag+ onDragStart=(record "start")+ onDrag=(record "drag")+ onDragEnd=(record "end")+ }}+ ></div>+ </template>+ );++ stubPointerCapture(".dpd-target");+ await triggerEvent(".dpd-target", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 10,+ clientY: 20,+ });+ await triggerEvent(".dpd-target", "pointermove", {+ pointerId: 1,+ clientX: 40,+ clientY: 25,+ });+ await triggerEvent(".dpd-target", "pointerup", {+ pointerId: 1,+ clientX: 40,+ clientY: 25,+ });++ assert.deepEqual(+ seen,+ [+ "start:origin=10,20 current=10,20 delta=0,0 moved=false",+ "drag:origin=10,20 current=40,25 delta=30,5 moved=true",+ "end:origin=10,20 current=40,25 delta=30,5 moved=true",+ ],+ "the origin is the press, the delta is measured from it, and moved latches on the first report"+ );+ });++ test("a release that never moved says so, so a click is not a drag", async function (assert) {+ const ends = [];+ const onDragEnd = (event, info) => ends.push(info.moved);++ await render(+ <template>+ <div class="dpd-target" {{dPointerDrag onDragEnd=onDragEnd}}></div>+ </template>+ );++ stubPointerCapture(".dpd-target");+ await triggerEvent(".dpd-target", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 5,+ clientY: 5,+ });+ await triggerEvent(".dpd-target", "pointerup", {+ pointerId: 1,+ clientX: 5,+ clientY: 5,+ });++ // A commit guarded on this is the difference between a resize and a click+ // writing an entry into whatever history the commit feeds.+ assert.deepEqual(ends, [false], "a press and release reports no movement");+ });++ test("each report is its own snapshot, not a view that keeps changing", async function (assert) {+ const stashed = [];+ const onDrag = (event, info) => stashed.push(info);++ await render(+ <template>+ <div class="dpd-target" {{dPointerDrag onDrag=onDrag}}></div>+ </template>+ );++ stubPointerCapture(".dpd-target");+ await triggerEvent(".dpd-target", "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(".dpd-target", "pointermove", {+ pointerId: 1,+ clientX: 10,+ clientY: 0,+ });+ await triggerEvent(".dpd-target", "pointermove", {+ pointerId: 1,+ clientX: 90,+ clientY: 0,+ });++ assert.deepEqual(+ [stashed[0].delta.x, stashed[1].delta.x],+ [10, 90],+ "a report kept by the consumer still holds the numbers it was handed"+ );+ assert.notStrictEqual(+ stashed[0],+ stashed[1],+ "and each report is a distinct object rather than one mutated in place"+ );+ });+test("dispatches start → drag → end and toggles the dragging class", async function (assert) {const calls = [];const onDragStart = () => calls.push("start");diff --git a/frontend/discourse/type-tests/ui-kit/d-resize-handles-args-errors-test.gts b/frontend/discourse/type-tests/ui-kit/d-resize-handles-args-errors-test.gtsnew file mode 100644index 00000000000..f34d3a7d46e--- /dev/null+++ b/frontend/discourse/type-tests/ui-kit/d-resize-handles-args-errors-test.gts@@ -0,0 +1,22 @@+/** Verifies that unknown component arguments are rejected. Keep ONE error source inside each guarded element: a+ * directive suppresses every error in the element it guards, so a second+ * mistake added alongside this one would be absorbed silently.+ */+import DResizeHandles from "discourse/ui-kit/d-resize-handles";++declare const noop: () => void;+declare const untrustedStyleHandles: {+ key: string;+ payload: number;+ style?: string;+}[];++const Negative = <template>+ {{! @glint-expect-error - an unknown arg is not silently ignored }}+ <DResizeHandles @handleClass="my-block__handle" @onResizeFinished={{noop}} />++ {{! @glint-expect-error - a plain string style has to be trusted by its caller }}+ <DResizeHandles @handles={{untrustedStyleHandles}} />+</template>;++export default Negative;diff --git a/frontend/discourse/type-tests/ui-kit/d-resize-handles-box-errors-test.gts b/frontend/discourse/type-tests/ui-kit/d-resize-handles-box-errors-test.gtsnew file mode 100644index 00000000000..b957348e44d--- /dev/null+++ b/frontend/discourse/type-tests/ui-kit/d-resize-handles-box-errors-test.gts@@ -0,0 +1,14 @@+/** Verifies that built-in handles always report compass directions. Keep ONE error source inside each guarded element: a+ * directive suppresses every error in the element it guards, so a second+ * mistake added alongside this one would be absorbed silently.+ */+import DResizeHandles from "discourse/ui-kit/d-resize-handles";++declare function onColumnResize(column: number): void;++const Negative = <template>+ {{! @glint-expect-error - the built-in box hands back compass directions, and the handler must not be allowed to decide the payload type for it }}+ <DResizeHandles @handleClass="handle" @onResize={{onColumnResize}} />+</template>;++export default Negative;diff --git a/frontend/discourse/type-tests/ui-kit/d-resize-handles-payload-errors-test.gts b/frontend/discourse/type-tests/ui-kit/d-resize-handles-payload-errors-test.gtsnew file mode 100644index 00000000000..0f1efe1a8ef--- /dev/null+++ b/frontend/discourse/type-tests/ui-kit/d-resize-handles-payload-errors-test.gts@@ -0,0 +1,15 @@+/** Verifies that explicit handle descriptors determine the callback payload. Keep ONE error source inside each guarded element: a+ * directive suppresses every error in the element it guards, so a second+ * mistake added alongside this one would be absorbed silently.+ */+import DResizeHandles from "discourse/ui-kit/d-resize-handles";++declare const columnHandles: { key: string; payload: number }[];+declare function onDirectionResize(direction: string): void;++const Negative = <template>+ {{! @glint-expect-error - the descriptors pin the payload type, so a handler taking something else is rejected }}+ <DResizeHandles @handles={{columnHandles}} @onResize={{onDirectionResize}} />+</template>;++export default Negative;diff --git a/frontend/discourse/type-tests/ui-kit/d-resize-handles-test.gts b/frontend/discourse/type-tests/ui-kit/d-resize-handles-test.gtsnew file mode 100644index 00000000000..60655a8861d--- /dev/null+++ b/frontend/discourse/type-tests/ui-kit/d-resize-handles-test.gts@@ -0,0 +1,95 @@+/**+ * Positive template invocations for DResizeHandles. This file intentionally has+ * no Glint error directives, so a broken public signature cannot be suppressed.+ */+import { array } from "@ember/helper";+import type { TrustedHTML } from "@ember/template";+import DResizeHandles, {+ BOX_DIRECTIONS,+ type BoxDirection,+ type DResizeHandleDragInfo,+} from "discourse/ui-kit/d-resize-handles";++declare const columnHandles: {+ key: string;+ payload: number;+ class?: string;+ style?: TrustedHTML;+}[];+declare const box: Element;+declare function onColumnResize(column: number): void;+declare function onCompassResize(direction: BoxDirection): void;+declare function measureFrom(handle: HTMLElement): Element | null;+declare function veto(direction: BoxDirection): boolean;++/**+ * Reads every field of the report, so the shape of the public callback payload+ * is checked rather than merely its first argument.+ */+function onReport(+ direction: BoxDirection,+ dragInfo: DResizeHandleDragInfo<BoxDirection>+): void {+ const payload: BoxDirection = dragInfo.payload;+ const event: PointerEvent = dragInfo.event;+ const origin: { x: number; y: number } = dragInfo.origin;+ const current: { x: number; y: number } = dragInfo.current;+ const delta: { x: number; y: number } = dragInfo.delta;+ const moved: boolean = dragInfo.moved;+ const session: object = dragInfo.session;+ const measured: Element | null = dragInfo.measured;+ const measuredRect: DOMRect | null = dragInfo.measuredRect;+ void [+ direction,+ payload,+ event,+ origin,+ current,+ delta,+ moved,+ session,+ measured,+ measuredRect,+ ];+}++const Positives = <template>+ {{! The built-in box hands a compass direction to the handler }}+ <DResizeHandles @handleClass="my-block__handle" @threshold={{4}} />+ <DResizeHandles+ @handleClass="my-block__handle"+ @onResize={{onCompassResize}}+ />+ <DResizeHandles+ @handleClass="my-block__handle"+ @directions={{array "n" "s"}}+ @stopPropagation={{true}}+ />++ {{! Explicit descriptors carry the payload type through to the callbacks }}+ <DResizeHandles @handles={{columnHandles}} @onResize={{onColumnResize}} />++ {{! The whole report shape, and the terminal and veto callbacks }}+ <DResizeHandles+ @handleClass="my-block__handle"+ @directions={{BOX_DIRECTIONS}}+ @onResizeStart={{veto}}+ @onResize={{onReport}}+ @onResizeEnd={{onReport}}+ @onResizeCancel={{onReport}}+ @draggingClass="is-dragging"+ />++ {{! cancelCommits belongs with a consumer that handles only the one terminal }}+ <DResizeHandles+ @handleClass="my-block__handle"+ @onResizeEnd={{onReport}}+ @cancelCommits={{true}}+ />++ {{! Both forms of the measure target }}+ <DResizeHandles @handleClass="my-block__handle" @measure={{box}} />+ <DResizeHandles @handleClass="my-block__handle" @measure={{measureFrom}} />+</template>;++export default Positives;diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/sticky-note.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/sticky-note.gjsindex 746abda7ebf..33aa632e276 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/sticky-note.gjs+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/sticky-note.gjs@@ -8,9 +8,11 @@ import { modifier } from "ember-modifier";import DTooltip from "discourse/float-kit/components/d-tooltip";import { eq } from "discourse/truth-helpers";import DCookText from "discourse/ui-kit/d-cook-text";+import DResizeHandles from "discourse/ui-kit/d-resize-handles";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dIcon from "discourse/ui-kit/helpers/d-icon";import dAutoFocus from "discourse/ui-kit/modifiers/d-auto-focus";+import dPointerDrag from "discourse/ui-kit/modifiers/d-pointer-drag";import { i18n } from "discourse-i18n";import CanvasHoverToolbar from "./hover-toolbar";import { DRAG_LENIENCE_PX } from "./rete-editor";@@ -51,16 +53,42 @@ export default class StickyNote extends Component {stickyNoteElement = null;colorOptions = COLORS;resizeEdges = RESIZE_EDGES;-+ dragLeniencePx = DRAG_LENIENCE_PX;handleDocumentClick = (event) => {if (!this.stickyNoteElement?.contains(event.target)) {this.closeColorPicker();}};+ #dragOrigin = { x: 0, y: 0 };+ #dragZoom = null;+ #noteDragOpen = false;++ /** How much of the move has already been handed to co-selected notes. */+ #appliedDx = 0;+ #appliedDy = 0;++ /**+ * How many gestures and edits are inside the open mutation. Counted rather+ * than flagged because a resize can begin while an edit is already open. The+ * first of the two to finish must not close a capture the other is still+ * writing into.+ */+ #openGestures = 0;++ /**+ * Whether editing holds one of those. Kept apart from `isEditing` because+ * reading a tracked field before writing it in the same computation is a+ * backtracking error, and blur can arrive mid-render.+ */+ #editingOpen = false;+willDestroy() {super.willDestroy(...arguments);this.closeColorPicker();+ // A note drag and an open edit report nothing on teardown. Left open, they+ // make the next undo jump further back than the user ever went.+ this.#abandonMutation();}get style() {@@ -98,119 +126,221 @@ export default class StickyNote extends Component {document.removeEventListener("click", this.handleDocumentClick);}- #startDrag(event, { onMove, onEnd }) {- event.stopPropagation();- event.preventDefault();- const zoom = this.args.zoom ?? 1;- const startX = event.clientX;- const startY = event.clientY;- let withinLenience = true;-- const moveHandler = (e) => {- if (withinLenience) {- if (- Math.hypot(e.clientX - startX, e.clientY - startY) < DRAG_LENIENCE_PX- ) {- return;- }- withinLenience = false;- }- const dx = (e.clientX - startX) / zoom;- const dy = (e.clientY - startY) / zoom;- onMove(dx, dy);- };+ /**+ * Converts a pointer delta from screen pixels into canvas units.+ *+ * @param {{x: number, y: number}} delta - The pointer delta in screen pixels.+ * @param {number} [zoom] - The zoom snapshotted when the gesture began. Reading+ * it live would re-divide the whole accumulated delta by the new factor and+ * make the note jump, since the delta is measured from the original press.+ * @returns {{dx: number, dy: number}} The same delta in canvas units.+ */+ #inCanvasUnits(delta, zoom) {+ const factor = zoom ?? this.args.zoom ?? 1;+ return { dx: delta.x / factor, dy: delta.y / factor };+ }- const upHandler = () => {- document.removeEventListener("pointermove", moveHandler);- document.removeEventListener("pointerup", upHandler);- onEnd?.();- };+ /**+ * Emits the box this gesture's edge implies, working in edge space.+ *+ * Each boundary moves from where it sat at this gesture's own press, and the+ * three it does not own are read live. That way dragging one edge and then the+ * opposite one composes. Deriving a width from a press-time snapshot instead+ * would make the second drag overwrite the first.+ *+ * @param {string} edge - The compass edge being dragged.+ * @param {object} dragInfo - The gesture report, carrying the pointer delta+ * and the box and zoom this gesture snapshotted at its own press.+ */+ #applyEdgeResize(edge, dragInfo) {+ const { origin, zoom } = dragInfo.session;+ const { dx, dy } = this.#inCanvasUnits(dragInfo.delta, zoom);++ const live = { ...this.args.note.position, ...this.args.note.size };+ let left = live.x;+ let right = live.x + live.width;+ let top = live.y;+ let bottom = live.y + live.height;++ if (edge.includes("e")) {+ right = Math.max(left + MIN_WIDTH, origin.x + origin.width + dx);+ }+ if (edge.includes("w")) {+ left = Math.min(right - MIN_WIDTH, origin.x + dx);+ }+ if (edge.includes("s")) {+ bottom = Math.max(top + MIN_HEIGHT, origin.y + origin.height + dy);+ }+ if (edge.includes("n")) {+ top = Math.min(bottom - MIN_HEIGHT, origin.y + dy);+ }++ this.args.onResize?.({ width: right - left, height: bottom - top });+ // A trailing edge cannot move the origin, and emitting it unchanged would+ // rebuild the whole note list for nothing.+ if (edge.includes("w") || edge.includes("n")) {+ this.args.onMove?.({ x: left, y: top });+ }+ }++ #applyNoteDrag(info) {+ const { dx, dy } = this.#inCanvasUnits(info.delta, this.#dragZoom);++ this.args.onMove?.({+ x: this.#dragOrigin.x + dx,+ y: this.#dragOrigin.y + dy,+ });- document.addEventListener("pointermove", moveHandler);- document.addEventListener("pointerup", upHandler);+ // Any co-selected notes move by the increment since the last report, not by+ // the total, because they are translated relative to wherever they now sit.+ const incrementalDx = dx - this.#appliedDx;+ const incrementalDy = dy - this.#appliedDy;+ if (incrementalDx !== 0 || incrementalDy !== 0) {+ this.args.onTranslateSelected?.(incrementalDx, incrementalDy);+ }+ this.#appliedDx = dx;+ this.#appliedDy = dy;+ }++ #openMutation() {+ this.#openGestures += 1;+ if (this.#openGestures === 1) {+ this.args.onBeforeMutation?.();+ }+ }++ #closeMutation() {+ if (this.#openGestures === 0) {+ return;+ }+ this.#openGestures -= 1;+ if (this.#openGestures === 0) {+ this.args.onAfterMutation?.();+ }+ }++ #closeNoteDrag() {+ if (this.#noteDragOpen) {+ this.#closeMutation();+ }+ this.#noteDragOpen = false;+ this.#dragZoom = null;+ }++ #closeEdgeResize(dragInfo) {+ if (dragInfo.session.opened) {+ dragInfo.session.opened = false;+ this.#closeMutation();+ }+ }++ #abandonMutation() {+ if (this.#openGestures === 0) {+ return;+ }+ this.#openGestures = 0;+ this.args.onAfterMutation?.();}@action- handlePointerDown(event) {+ onNoteDragStart(event) {+ // The handles carry `stopPropagation`, but one already holding a gesture+ // refuses a second contact *before* stopping it, so that press arrives here.if (- event.target.closest(".workflow-sticky-note__edge") ||event.target.closest(".workflow-canvas-toolbar") ||- event.target.tagName === "TEXTAREA"+ event.target.closest(".workflow-sticky-note__edge")) {- return;+ return false;}this.args.onSelect?.();- this.args.onBeforeMutation?.();-- const { x, y } = this.args.note.position;- let prevDx = 0;- let prevDy = 0;- this.#startDrag(event, {- onMove: (dx, dy) => {- this.args.onMove?.({ x: x + dx, y: y + dy });- const incrementalDx = dx - prevDx;- const incrementalDy = dy - prevDy;- if (incrementalDx !== 0 || incrementalDy !== 0) {- this.args.onTranslateSelected?.(incrementalDx, incrementalDy);- }- prevDx = dx;- prevDy = dy;- },- onEnd: () => this.args.onAfterMutation?.(),- });+ // The mutation waits for the first real move. A press that only selects would+ // otherwise bracket an undo entry whose before and after are identical.+ this.#dragZoom = this.args.zoom ?? 1;+ this.#dragOrigin = { ...this.args.note.position };+ this.#appliedDx = 0;+ this.#appliedDy = 0;+ this.#noteDragOpen = false;}@action- handleResizePointerDown(event) {- const edge = event.target.dataset.edge;- if (!edge) {- return;+ onNoteDrag(event, info) {+ if (!this.#noteDragOpen) {+ this.#noteDragOpen = true;+ this.#openMutation();}+ this.#applyNoteDrag(info);+ }- this.args.onBeforeMutation?.();-- const { width, height } = this.args.note.size;- const { x, y } = this.args.note.position;- const resizeN = edge.includes("n");- const resizeS = edge.includes("s");- const resizeW = edge.includes("w");- const resizeE = edge.includes("e");-- this.#startDrag(event, {- onMove: (dx, dy) => {- let newW = width;- let newH = height;- let newX = x;- let newY = y;-- if (resizeE) {- newW = Math.max(MIN_WIDTH, width + dx);- }- if (resizeS) {- newH = Math.max(MIN_HEIGHT, height + dy);- }- if (resizeW) {- newW = Math.max(MIN_WIDTH, width - dx);- newX = x + width - newW;- }- if (resizeN) {- newH = Math.max(MIN_HEIGHT, height - dy);- newY = y + height - newH;- }-- this.args.onResize?.({ width: newW, height: newH });- this.args.onMove?.({ x: newX, y: newY });- },- onEnd: () => this.args.onAfterMutation?.(),- });+ @action+ onNoteDragEnd(event, info) {+ // Closed in a `finally`. A consumer that throws on the commit would otherwise+ // leave the counter above zero and unbracket every later gesture.+ try {+ if (info.moved) {+ this.#applyNoteDrag(info);+ }+ } finally {+ this.#closeNoteDrag();+ }+ }++ @action+ onNoteDragCancel() {+ // Deliberately no geometry, unlike the release handler. A cancel carries no+ // position the user chose, and the last move already applied the note's box.+ this.#closeNoteDrag();+ }++ @action+ onEdgeResizeStart(edge, dragInfo) {+ dragInfo.session.origin = {+ ...this.args.note.position,+ ...this.args.note.size,+ };+ dragInfo.session.zoom = this.args.zoom ?? 1;+ }++ @action+ onEdgeResize(edge, dragInfo) {+ if (!dragInfo.session.opened) {+ dragInfo.session.opened = true;+ this.#openMutation();+ }+ this.#applyEdgeResize(edge, dragInfo);+ }++ @action+ onEdgeResizeEnd(edge, dragInfo) {+ // The release can carry a newer position than the last move, so the box is+ // recomputed. Closed in a `finally`, as on the note drag's release.+ try {+ if (dragInfo.moved) {+ this.#applyEdgeResize(edge, dragInfo);+ }+ } finally {+ this.#closeEdgeResize(dragInfo);+ }+ }++ @action+ onEdgeResizeCancel(edge, dragInfo) {+ // No geometry, for the reason given on `onNoteDragCancel`.+ this.#closeEdgeResize(dragInfo);}@actionstartEditing(event) {event.stopPropagation();- this.args.onBeforeMutation?.();+ if (this.#editingOpen) {+ return;+ }+ // Same counter the gestures use. A press does not move focus off the+ // textarea, so a resize begun mid-edit nests inside it instead of closing it.+ this.#editingOpen = true;this.isEditing = true;+ // Flags set first, so a throwing hook still leaves the note editable.+ this.#openMutation();}@action@@ -220,8 +350,12 @@ export default class StickyNote extends Component {@actionstopEditing() {+ if (!this.#editingOpen) {+ return;+ }+ this.#editingOpen = false;this.isEditing = false;- this.args.onAfterMutation?.();+ this.#closeMutation();}@action@@ -260,7 +394,15 @@ export default class StickyNote extends Component {}}style={{this.style}}{{registerStickyNoteElement this}}- {{on "pointerdown" this.handlePointerDown}}+ {{dPointerDrag+ onDragStart=this.onNoteDragStart+ onDrag=this.onNoteDrag+ onDragEnd=this.onNoteDragEnd+ onDragCancel=this.onNoteDragCancel+ threshold=this.dragLeniencePx+ stopPropagation=true+ touchAction="pinch-zoom"+ }}{{on "dblclick" this.startEditing}}><CanvasHoverToolbar>@@ -342,16 +484,17 @@ export default class StickyNote extends Component {{{/if}}</div>- <div- class="workflow-sticky-note__edges"- {{on "pointerdown" this.handleResizePointerDown}}- >- {{#each this.resizeEdges as |edge|}}- <div- class="workflow-sticky-note__edge --{{edge}}"- data-edge={{edge}}- />- {{/each}}+ <div class="workflow-sticky-note__edges">+ <DResizeHandles+ @handleClass="workflow-sticky-note__edge"+ @directions={{this.resizeEdges}}+ @threshold={{this.dragLeniencePx}}+ @stopPropagation={{true}}+ @onResizeStart={{this.onEdgeResizeStart}}+ @onResize={{this.onEdgeResize}}+ @onResizeEnd={{this.onEdgeResizeEnd}}+ @onResizeCancel={{this.onEdgeResizeCancel}}+ /></div></div></template>diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/canvas/sticky-note-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/canvas/sticky-note-test.gjsindex 86aeadeed9e..58a88fa42ec 100644--- a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/canvas/sticky-note-test.gjs+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/canvas/sticky-note-test.gjs@@ -1,14 +1,28 @@-import { find, render, settled } from "@ember/test-helpers";+import { tracked } from "@glimmer/tracking";+import { clearRender, render, triggerEvent } from "@ember/test-helpers";import { module, test } from "qunit";import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import { stubPointerCapture } from "discourse/tests/helpers/ui-kit/pointer-gesture-helper";import StickyNote from "discourse/plugins/discourse-workflows/admin/components/workflows/canvas/sticky-note";-function pointerEvent(type, options = {}) {- return new PointerEvent(type, {- bubbles: true,- cancelable: true,- ...options,- });+/**+ * The element a synthetic press can actually reach, ready to receive one.+ *+ * @param {string} selector - The element that will receive the press.+ * @returns {HTMLElement} That element.+ */+function pressable(selector) {+ return stubPointerCapture(selector).element;+}++function noteFixture(overrides = {}) {+ return {+ position: { x: 10, y: 20 },+ size: { width: 200, height: 150 },+ color: "yellow",+ text: "",+ ...overrides,+ };}module(@@ -19,12 +33,7 @@ module(test("dragging only starts once the pointer passes the lenience radius", async function (assert) {const moves = [];const afterMutations = [];- const note = {- position: { x: 10, y: 20 },- size: { width: 200, height: 150 },- color: "yellow",- text: "",- };+ const note = noteFixture();const onMove = (position) => moves.push(position);const onAfterMutation = () => afterMutations.push(true);@@ -39,33 +48,42 @@ module(</template>);- const element = find(".workflow-sticky-note");- element.dispatchEvent(- pointerEvent("pointerdown", { clientX: 100, clientY: 100 })- );+ const element = pressable(".workflow-sticky-note");+ await triggerEvent(element, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 100,+ clientY: 100,+ });- document.dispatchEvent(- pointerEvent("pointermove", { clientX: 102, clientY: 101 })- );+ await triggerEvent(element, "pointermove", {+ pointerId: 1,+ clientX: 102,+ clientY: 101,+ });assert.deepEqual(moves,[],"sub-lenience movement does not move the note");- document.dispatchEvent(- pointerEvent("pointermove", { clientX: 110, clientY: 100 })- );+ await triggerEvent(element, "pointermove", {+ pointerId: 1,+ clientX: 110,+ clientY: 100,+ });assert.deepEqual(moves,[{ x: 20, y: 20 }],"past the lenience the note follows the full pointer delta");- document.dispatchEvent(- pointerEvent("pointerup", { clientX: 110, clientY: 100 })- );- await settled();+ await triggerEvent(element, "pointerup", {+ pointerId: 1,+ clientX: 110,+ clientY: 100,+ });+assert.strictEqual(afterMutations.length,1,@@ -75,12 +93,407 @@ module(test("a click with pointer jitter never moves the note", async function (assert) {const moves = [];- const note = {- position: { x: 0, y: 0 },- size: { width: 200, height: 150 },- color: "yellow",- text: "",+ const note = noteFixture({ position: { x: 0, y: 0 } });+ const onMove = (position) => moves.push(position);++ await render(+ <template>+ <StickyNote @note={{note}} @zoom={{1}} @onMove={{onMove}} />+ </template>+ );++ const element = pressable(".workflow-sticky-note");+ await triggerEvent(element, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 50,+ clientY: 50,+ });+ await triggerEvent(element, "pointermove", {+ pointerId: 1,+ clientX: 52,+ clientY: 49,+ });+ await triggerEvent(element, "pointerup", {+ pointerId: 1,+ clientX: 52,+ clientY: 49,+ });++ assert.deepEqual(moves, [], "the note position never changed");+ });++ test("the pointer delta is divided by the canvas zoom", async function (assert) {+ const moves = [];+ const note = noteFixture({ position: { x: 0, y: 0 } });+ const onMove = (position) => moves.push(position);++ await render(+ <template>+ <StickyNote @note={{note}} @zoom={{2}} @onMove={{onMove}} />+ </template>+ );++ const element = pressable(".workflow-sticky-note");+ await triggerEvent(element, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(element, "pointermove", {+ pointerId: 1,+ clientX: 40,+ clientY: 20,+ });++ assert.deepEqual(+ moves,+ [{ x: 20, y: 10 }],+ "at 2x zoom the note travels half the pointer distance"+ );+ });++ test("pressing a resize edge resizes without moving the note", async function (assert) {+ const moves = [];+ const resizes = [];+ const note = noteFixture({ position: { x: 10, y: 20 } });+ const onMove = (position) => moves.push(position);+ const onResize = (size) => resizes.push(size);++ await render(+ <template>+ <StickyNote+ @note={{note}}+ @zoom={{1}}+ @onMove={{onMove}}+ @onResize={{onResize}}+ />+ </template>+ );++ pressable(".workflow-sticky-note");+ const edge = pressable("[data-resize-handle='e']");+ await triggerEvent(edge, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(edge, "pointermove", {+ pointerId: 1,+ clientX: 30,+ clientY: 0,+ });++ assert.deepEqual(+ resizes,+ [{ width: 230, height: 150 }],+ "the east edge grows the width by the pointer delta"+ );+ assert.deepEqual(+ moves,+ [],+ "a trailing edge cannot move the origin, so nothing is emitted for it"+ );+ });++ test("a cancelled note drag still closes the mutation it opened", async function (assert) {+ const afterMutations = [];+ const moves = [];+ const translates = [];+ const note = noteFixture();+ const onAfterMutation = () => afterMutations.push(true);+ const onMove = (position) => moves.push(position);+ const onTranslateSelected = (dx, dy) => translates.push([dx, dy]);++ await render(+ <template>+ <StickyNote+ @note={{note}}+ @zoom={{1}}+ @onAfterMutation={{onAfterMutation}}+ @onMove={{onMove}}+ @onTranslateSelected={{onTranslateSelected}}+ />+ </template>+ );++ const element = pressable(".workflow-sticky-note");+ await triggerEvent(element, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 100,+ clientY: 100,+ });+ await triggerEvent(element, "pointermove", {+ pointerId: 1,+ clientX: 120,+ clientY: 100,+ });+ // The OS taking the pointer away. The undo-mutation pair opened at the+ // press must still close, or the canvas is left holding an open mutation.+ await triggerEvent(element, "pointercancel", {+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ assert.strictEqual(+ afterMutations.length,+ 1,+ "the interruption closes the mutation the press opened"+ );+ // A cancel is not a release: its coordinates describe no pointer position+ // the user chose. The last move already committed where the note was+ // dragged to, so the interruption must add nothing of its own.+ assert.deepEqual(+ moves,+ [{ x: 30, y: 20 }],+ "the interrupted note keeps where it was dragged to"+ );+ assert.deepEqual(+ translates,+ [[20, 0]],+ "and co-selected notes are not dragged along by the cancel"+ );+ });++ test("a cancelled edge resize still closes the mutation it opened", async function (assert) {+ const afterMutations = [];+ const resizes = [];+ const note = noteFixture();+ const onAfterMutation = () => afterMutations.push(true);+ const onResize = (size) => resizes.push(size);++ await render(+ <template>+ <StickyNote+ @note={{note}}+ @zoom={{1}}+ @onAfterMutation={{onAfterMutation}}+ @onResize={{onResize}}+ />+ </template>+ );++ pressable(".workflow-sticky-note");+ const edge = pressable("[data-resize-handle='e']");+ await triggerEvent(edge, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(edge, "pointermove", {+ pointerId: 1,+ clientX: 30,+ clientY: 0,+ });+ await triggerEvent(edge, "pointercancel", {+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ assert.strictEqual(+ afterMutations.length,+ 1,+ "the interruption closes the mutation the press opened"+ );+ assert.deepEqual(+ resizes,+ [{ width: 230, height: 150 }],+ "the interrupted box keeps the size it was dragged to"+ );+ });++ test("a second edge press leaves the gesture already held alone", async function (assert) {+ const resizes = [];+ const note = noteFixture();+ const onResize = (size) => {+ resizes.push(size);+ // Committed the way the canvas does. If the gesture used the note's+ // current size as its base instead of the press-time size, the numbers+ // below would change.+ note.size = { ...size };+ };++ await render(+ <template>+ <StickyNote @note={{note}} @zoom={{1}} @onResize={{onResize}} />+ </template>+ );++ pressable(".workflow-sticky-note");+ const east = pressable("[data-resize-handle='e']");+ const south = pressable("[data-resize-handle='s']");++ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(east, "pointermove", {+ pointerId: 1,+ clientX: 50,+ clientY: 0,+ });++ // A second finger lands on another edge while the first still holds the+ // note. One gesture at a time, so it never starts.+ await triggerEvent(south, "pointerdown", {+ button: 0,+ pointerId: 2,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(south, "pointermove", {+ pointerId: 2,+ clientX: 0,+ clientY: 40,+ });++ await triggerEvent(east, "pointermove", {+ pointerId: 1,+ clientX: 60,+ clientY: 0,+ });++ assert.deepEqual(+ resizes,+ [+ { width: 250, height: 150 },+ { width: 260, height: 150 },+ ],+ "the refused press resizes nothing and the held gesture keeps its origin"+ );+ });++ test("opposite edges of one axis compose instead of overwriting", async function (assert) {+ const moves = [];+ const resizes = [];+ const note = noteFixture();+ const onMove = (position) => {+ moves.push(position);+ note.position = { ...position };+ };+ const onResize = (size) => {+ resizes.push(size);+ note.size = { ...size };+ };++ await render(+ <template>+ <StickyNote+ @note={{note}}+ @zoom={{1}}+ @onMove={{onMove}}+ @onResize={{onResize}}+ />+ </template>+ );++ pressable(".workflow-sticky-note");+ const west = pressable("[data-resize-handle='w']");+ const east = pressable("[data-resize-handle='e']");++ // Each handle owns one boundary and reads the other three live. Drag one+ // edge, then the other. The second drag has to move its own boundary and+ // keep the first's.+ await triggerEvent(west, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(west, "pointermove", {+ pointerId: 1,+ clientX: -30,+ clientY: 0,+ });+ await triggerEvent(west, "pointerup", {+ pointerId: 1,+ clientX: -30,+ clientY: 0,+ });++ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 2,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(east, "pointermove", {+ pointerId: 2,+ clientX: 50,+ clientY: 0,+ });+ await triggerEvent(east, "pointerup", {+ pointerId: 2,+ clientX: 50,+ clientY: 0,+ });++ assert.deepEqual(+ resizes.at(-1),+ { width: 280, height: 150 },+ "the box spans both boundaries, not just the last one dragged"+ );+ assert.deepEqual(+ moves.at(-1),+ { x: -20, y: 20 },+ "and the west edge still carries the origin with it"+ );+ });++ test("a release past the last move commits where the pointer was let go", async function (assert) {+ const resizes = [];+ const note = noteFixture();+ const onResize = (size) => {+ resizes.push(size);+ note.size = { ...size };};++ await render(+ <template>+ <StickyNote @note={{note}} @zoom={{1}} @onResize={{onResize}} />+ </template>+ );++ pressable(".workflow-sticky-note");+ const east = pressable("[data-resize-handle='e']");++ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(east, "pointermove", {+ pointerId: 1,+ clientX: 50,+ clientY: 0,+ });+ // The browser can coalesce moves, so the release may carry a newer+ // position than the last move ever reported.+ await triggerEvent(east, "pointerup", {+ pointerId: 1,+ clientX: 80,+ clientY: 0,+ });++ assert.deepEqual(+ resizes.at(-1),+ { width: 280, height: 150 },+ "the committed box is the one the pointer was released at"+ );+ });++ test("a released note drag commits where the pointer was let go", async function (assert) {+ const moves = [];+ const note = noteFixture();const onMove = (position) => moves.push(position);await render(@@ -89,19 +502,618 @@ module(</template>);- const element = find(".workflow-sticky-note");- element.dispatchEvent(- pointerEvent("pointerdown", { clientX: 50, clientY: 50 })+ const element = pressable(".workflow-sticky-note");+ await triggerEvent(element, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(element, "pointermove", {+ pointerId: 1,+ clientX: 40,+ clientY: 0,+ });+ await triggerEvent(element, "pointerup", {+ pointerId: 1,+ clientX: 70,+ clientY: 0,+ });++ assert.deepEqual(+ moves.at(-1),+ { x: 80, y: 20 },+ "the committed position is the one the pointer was released at"+ );+ });++ test("a click on a resize edge resizes nothing", async function (assert) {+ const resizes = [];+ const note = noteFixture();+ const onResize = (size) => resizes.push(size);++ await render(+ <template>+ <StickyNote @note={{note}} @zoom={{1}} @onResize={{onResize}} />+ </template>+ );++ pressable(".workflow-sticky-note");+ const east = pressable("[data-resize-handle='e']");++ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(east, "pointerup", {+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ assert.deepEqual(+ resizes,+ [],+ "a press that never moved commits no box of its own");- document.dispatchEvent(- pointerEvent("pointermove", { clientX: 52, clientY: 49 })+ });++ test("co-selected notes are translated by the increment, not the total", async function (assert) {+ const translates = [];+ // The note the user grabbed is replaced on every move, the way the canvas+ // replaces it, so a stale read of the previous object would show up here.+ const state = new (class {+ @tracked note = noteFixture();+ })();+ const onMove = (position) => {+ state.note = { ...state.note, position: { ...position } };+ };+ const onTranslateSelected = (dx, dy) => translates.push([dx, dy]);++ await render(+ <template>+ <StickyNote+ @note={{state.note}}+ @zoom={{1}}+ @onMove={{onMove}}+ @onTranslateSelected={{onTranslateSelected}}+ />+ </template>);- document.dispatchEvent(- pointerEvent("pointerup", { clientX: 52, clientY: 49 })++ const element = pressable(".workflow-sticky-note");+ await triggerEvent(element, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(element, "pointermove", {+ pointerId: 1,+ clientX: 40,+ clientY: 0,+ });+ await triggerEvent(element, "pointermove", {+ pointerId: 1,+ clientX: 70,+ clientY: 0,+ });++ // The others are translated relative to wherever they now sit, so each+ // report must carry only what changed since the previous one. Handing+ // over the running total instead makes them accelerate away.+ assert.deepEqual(+ translates,+ [+ [40, 0],+ [30, 0],+ ],+ "each report carries the step, not the distance from the press");- await settled();+ });- assert.deepEqual(moves, [], "the note position never changed");+ test("a second contact on a held handle does not drag the note", async function (assert) {+ const moves = [];+ const note = noteFixture();+ const onMove = (position) => moves.push(position);++ await render(+ <template>+ <StickyNote @note={{note}} @zoom={{1}} @onMove={{onMove}} />+ </template>+ );++ pressable(".workflow-sticky-note");+ const east = pressable("[data-resize-handle='e']");++ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ // The handle is already holding a gesture, so it refuses this press. A+ // refused press is not stopped from propagating, so it reaches the note+ // behind the handle, which must not treat it as the start of a note drag.+ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 2,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(east, "pointermove", {+ pointerId: 2,+ clientX: 60,+ clientY: 0,+ });++ assert.deepEqual(moves, [], "the note stayed where it was");+ });++ test("a click that never moved brackets no mutation at all", async function (assert) {+ const beforeMutations = [];+ const afterMutations = [];+ const note = noteFixture();+ const onBeforeMutation = () => beforeMutations.push(true);+ const onAfterMutation = () => afterMutations.push(true);++ await render(+ <template>+ <StickyNote+ @note={{note}}+ @zoom={{1}}+ @onBeforeMutation={{onBeforeMutation}}+ @onAfterMutation={{onAfterMutation}}+ />+ </template>+ );++ const element = pressable(".workflow-sticky-note");+ const edge = pressable("[data-resize-handle='e']");++ // Selecting a note, and a press on the narrow resize strip that never+ // became a drag. Bracketing these captures an undo entry whose before and+ // after are identical, and the history is short enough that a handful of+ // them push the user's real last edit out of reach.+ await triggerEvent(element, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(element, "pointerup", {+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(edge, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(edge, "pointerup", {+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });++ assert.deepEqual(beforeMutations, [], "neither click opened a mutation");+ assert.deepEqual(afterMutations, [], "so neither closed one");++ // The positive control: without it, the two assertions above would hold+ // just as well if the mutation wiring had been removed entirely.+ await triggerEvent(element, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(element, "pointermove", {+ pointerId: 1,+ clientX: 60,+ clientY: 0,+ });+ await triggerEvent(element, "pointerup", {+ pointerId: 1,+ clientX: 60,+ clientY: 0,+ });++ assert.deepEqual(+ beforeMutations,+ [true],+ "a gesture that really moved opens exactly one"+ );+ assert.deepEqual(afterMutations, [true], "and closes exactly one");+ });++ test("a leading edge stops shrinking at the minimum and stops moving with it", async function (assert) {+ const moves = [];+ const resizes = [];+ const note = noteFixture({ position: { x: 100, y: 100 } });+ const onMove = (position) => moves.push(position);+ const onResize = (size) => resizes.push(size);++ await render(+ <template>+ <StickyNote+ @note={{note}}+ @zoom={{1}}+ @onMove={{onMove}}+ @onResize={{onResize}}+ />+ </template>+ );++ const edge = pressable("[data-resize-handle='w']");+ await triggerEvent(edge, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ // 500px past the west edge is far beyond the 140px minimum width.+ await triggerEvent(edge, "pointermove", {+ pointerId: 1,+ clientX: 500,+ clientY: 0,+ });++ assert.deepEqual(+ resizes,+ [{ width: 140, height: 150 }],+ "the width clamps at the minimum"+ );+ assert.deepEqual(+ moves,+ [{ x: 160, y: 100 }],+ "the origin only advances by the width the note actually lost"+ );+ });++ test("teardown mid-gesture closes the mutation the press opened", async function (assert) {+ const beforeMutations = [];+ const afterMutations = [];+ const note = noteFixture();+ const onBeforeMutation = () => beforeMutations.push(true);+ const onAfterMutation = () => afterMutations.push(true);++ await render(+ <template>+ <StickyNote+ @note={{note}}+ @zoom={{1}}+ @onBeforeMutation={{onBeforeMutation}}+ @onAfterMutation={{onAfterMutation}}+ />+ </template>+ );++ const element = pressable(".workflow-sticky-note");+ await triggerEvent(element, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(element, "pointermove", {+ pointerId: 1,+ clientX: 60,+ clientY: 0,+ });++ // The positive control: without it, an assertion that the end fired once+ // could not tell a closed mutation from one that never opened.+ assert.deepEqual(beforeMutations, [true], "the drag opened a mutation");+ assert.deepEqual(afterMutations, [], "and has not closed it yet");++ // The gesture is still held. The drag engine deliberately reports nothing+ // when the element is destroyed, so the consumer has to close its own.+ await clearRender();++ assert.deepEqual(+ afterMutations,+ [true],+ "teardown closes it rather than stranding the undo capture it opened"+ );+ });++ test("teardown after a released gesture does not close it twice", async function (assert) {+ const afterMutations = [];+ const note = noteFixture();+ const onAfterMutation = () => afterMutations.push(true);++ await render(+ <template>+ <StickyNote+ @note={{note}}+ @zoom={{1}}+ @onAfterMutation={{onAfterMutation}}+ />+ </template>+ );++ const element = pressable(".workflow-sticky-note");+ await triggerEvent(element, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(element, "pointermove", {+ pointerId: 1,+ clientX: 60,+ clientY: 0,+ });+ await triggerEvent(element, "pointerup", {+ pointerId: 1,+ clientX: 60,+ clientY: 0,+ });+ assert.deepEqual(afterMutations, [true], "the release closed it");++ await clearRender();++ assert.deepEqual(+ afterMutations,+ [true],+ "teardown has nothing left to close"+ );+ });++ test("a commit callback that throws still closes the mutation it opened", async function (assert) {+ const beforeMutations = [];+ const afterMutations = [];+ const note = noteFixture();+ const onBeforeMutation = () => beforeMutations.push(true);+ const onAfterMutation = () => afterMutations.push(true);+ // Throws only on the release, so the gesture opens and runs normally and+ // only the terminal geometry blows up.+ let reports = 0;+ const onResize = (size) => {+ reports += 1;+ if (reports > 1) {+ throw new Error("consumer blew up committing the size");+ }+ note.size = { ...size };+ };++ await render(+ <template>+ <StickyNote+ @note={{note}}+ @zoom={{1}}+ @onResize={{onResize}}+ @onBeforeMutation={{onBeforeMutation}}+ @onAfterMutation={{onAfterMutation}}+ />+ </template>+ );++ pressable(".workflow-sticky-note");+ const east = pressable("[data-resize-handle='e']");++ await triggerEvent(east, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(east, "pointermove", {+ pointerId: 1,+ clientX: 40,+ clientY: 0,+ });++ assert.deepEqual(beforeMutations, [true], "the drag opened a mutation");++ // The throw is the consumer's bug and is rethrown, so it surfaces as an+ // uncaught error rather than a rejected promise. Swallowed here so the+ // assertion below is about the bracket rather than about the throw.+ const priorOnError = window.onerror;+ window.onerror = (...args) =>+ args[4]?.message === "consumer blew up committing the size" ||+ priorOnError?.(...args);+ try {+ await triggerEvent(east, "pointerup", {+ pointerId: 1,+ clientX: 40,+ clientY: 0,+ });+ } finally {+ window.onerror = priorOnError;+ }++ // Left open, the counter never returns to zero and every later gesture on+ // this note silently stops bracketing its undo entry.+ assert.strictEqual(+ afterMutations.length,+ 1,+ "the mutation closes exactly once even though the commit threw"+ );+ });++ test("a resize during an edit does not close the edit's mutation", async function (assert) {+ const beforeMutations = [];+ const afterMutations = [];+ const note = noteFixture();+ const onBeforeMutation = () => beforeMutations.push(true);+ const onAfterMutation = () => afterMutations.push(true);++ await render(+ <template>+ <StickyNote+ @note={{note}}+ @zoom={{1}}+ @onBeforeMutation={{onBeforeMutation}}+ @onAfterMutation={{onAfterMutation}}+ />+ </template>+ );++ await triggerEvent(".workflow-sticky-note", "dblclick");+ assert.deepEqual(beforeMutations, [true], "editing opened one mutation");++ // The press does not move focus, because the gesture cancels it, so the+ // note is still being edited while the resize runs. Both write to the same+ // pair of hooks, so the resize must nest inside the edit rather than open+ // and close a bracket of its own.+ const edge = pressable("[data-resize-handle='e']");+ await triggerEvent(edge, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(edge, "pointermove", {+ pointerId: 1,+ clientX: 30,+ clientY: 0,+ });+ await triggerEvent(edge, "pointerup", {+ pointerId: 1,+ clientX: 30,+ clientY: 0,+ });++ assert.deepEqual(+ beforeMutations,+ [true],+ "the resize did not open a second one"+ );+ assert.deepEqual(+ afterMutations,+ [],+ "and its release did not close the one the edit is still holding"+ );+ });++ test("a throwing mutation hook still leaves the note editable", async function (assert) {+ const afterMutations = [];+ const note = noteFixture();+ const onBeforeMutation = () => {+ throw new Error("owner failure");+ };+ const onAfterMutation = () => afterMutations.push(true);++ await render(+ <template>+ <StickyNote+ @note={{note}}+ @zoom={{1}}+ @onBeforeMutation={{onBeforeMutation}}+ @onAfterMutation={{onAfterMutation}}+ />+ </template>+ );++ // The hook belongs to the owner and can fail. If the throw were to leave+ // the note flagged as holding an edit it never entered, no textarea would+ // render, so no blur could ever release it and the note could never be+ // edited again.+ const priorOnError = window.onerror;+ // Only the throw under test. Anything else still reaches the harness,+ // which would otherwise go quiet for the whole interaction.+ window.onerror = (...args) =>+ args[4]?.message === "owner failure" || priorOnError?.(...args);+ try {+ await triggerEvent(".workflow-sticky-note", "dblclick");+ } finally {+ window.onerror = priorOnError;+ }++ assert+ .dom(".workflow-sticky-note__textarea")+ .exists("the note entered editing despite the hook throwing");++ // And what the failed hook opened is still releasable. Without this, a+ // note left flagged as editing but not as holding a mutation would pass+ // the assertion above while pinning the count for every later gesture.+ await triggerEvent(".workflow-sticky-note__textarea", "blur");++ assert.deepEqual(+ afterMutations,+ [true],+ "blur releases the mutation the failed hook opened"+ );+ });++ test("teardown mid-edit closes the mutation editing opened", async function (assert) {+ const beforeMutations = [];+ const afterMutations = [];+ const note = noteFixture();+ const onBeforeMutation = () => beforeMutations.push(true);+ const onAfterMutation = () => afterMutations.push(true);++ await render(+ <template>+ <StickyNote+ @note={{note}}+ @zoom={{1}}+ @onBeforeMutation={{onBeforeMutation}}+ @onAfterMutation={{onAfterMutation}}+ />+ </template>+ );++ // Editing opens a capture on the same wire a gesture does. Removing a+ // focused textarea does not reliably fire blur, so teardown has to close+ // it for the same reason teardown mid-gesture does.+ await triggerEvent(".workflow-sticky-note", "dblclick");++ assert.deepEqual(beforeMutations, [true], "editing opened a mutation");+ assert.deepEqual(afterMutations, [], "and has not closed it yet");++ await clearRender();++ assert.deepEqual(+ afterMutations,+ [true],+ "teardown closes it rather than stranding the undo capture"+ );+ });++ test("pressing the hover toolbar does not drag the note", async function (assert) {+ const moves = [];+ const beforeMutations = [];+ const note = noteFixture({ position: { x: 0, y: 0 } });+ const onMove = (position) => moves.push(position);+ const onBeforeMutation = () => beforeMutations.push(true);++ await render(+ <template>+ <StickyNote+ @note={{note}}+ @zoom={{1}}+ @onMove={{onMove}}+ @onBeforeMutation={{onBeforeMutation}}+ />+ </template>+ );++ pressable(".workflow-sticky-note");+ const toolbar = pressable(".workflow-canvas-toolbar");+ await triggerEvent(toolbar, "pointerdown", {+ button: 0,+ pointerId: 1,+ clientX: 0,+ clientY: 0,+ });+ await triggerEvent(toolbar, "pointermove", {+ pointerId: 1,+ clientX: 60,+ clientY: 60,+ });++ assert.deepEqual(moves, [], "the note never moved");+ assert.deepEqual(+ beforeMutations,+ [],+ "a vetoed press does not open a mutation either"+ );});});