A platform for community discussion. Free, open, simple.
DEV: Add drag-dwell primitives to the UI kit (#42781)
Sérgio Saquetime68edfd9bd1f
diff --git a/docs/developer-guides/docs/03-code-internals/29-drag-and-gesture-primitives.md b/docs/developer-guides/docs/03-code-internals/29-drag-and-gesture-primitives.mdindex 1993132706b..9cbfc9f07c1 100644--- a/docs/developer-guides/docs/03-code-internals/29-drag-and-gesture-primitives.md+++ b/docs/developer-guides/docs/03-code-internals/29-drag-and-gesture-primitives.md@@ -53,6 +53,7 @@ over it.| Upload the files somebody dropped | the upload pipeline, not the modifier above || React to a drag without becoming a drop target | `dDragAndDropMonitor` || Scroll a container while a drag hovers near its edge | `dDragAndDropAutoScroll` |+| Open or reveal something once a drag has hovered it a moment | `dDragDwell` || Render from the in-flight drag | the `dragAndDrop` service || Press, move, and track a value continuously | `dPointerDrag` || Put an accessible handle between two regions | `DResizeSeparator` |@@ -286,16 +287,104 @@ The element only anchors the modifier's lifecycle; a monitor is global.Scrolls a container while a drag hovers near its edge.-| Argument | Type | Purpose |-| --------- | ------------------------------------------------ | ---------------------------------- |-| `types` | `string \| string[]` | Element drag types that engage it. |-| `accepts` | `"files" \| "html" \| "text" \| "urls"` or array | External kinds that engage it. |-| `axis` | `"vertical" \| "horizontal" \| "all"` | Which direction to scroll. |-| `target` | `"element" \| "window"` | Scroll this element or the window. |+| Argument | Type | Purpose |+| --------------- | ------------------------------------------------ | ---------------------------------- |+| `types` | `string \| string[]` | Element drag types that engage it. |+| `externalKinds` | `"files" \| "html" \| "text" \| "urls"` or array | External kinds that engage it. |+| `axis` | `"vertical" \| "horizontal" \| "all"` | Which direction to scroll. |+| `target` | `"element" \| "window"` | Scroll this element or the window. |++Element drags and external drags arrive through different adapters, so an+observer that watches both names both: `types` for the element side,+`externalKinds` for the external side. `accepts` stays a drop-taking word.++# dDragDwell++Fires a callback once a drag has hovered its element for a delay — a folder+opening under a file held over it — without making the element a drop target.+It watches drags the way a monitor does, for both element drags and, when+asked, external ones, and tests its own rectangle against the pointer. It+never joins the drop-target hierarchy: no indicator, no positions, and it+composes freely with a real target on the same element.++| Argument | Type | Purpose |+| --------------- | ----------------------- | --------------------------------------------------------------------------------- |+| `types` | `string \| string[]` | Element drag types to watch. Omit to watch all. |+| `externalKinds` | external kinds or array | External kinds to watch. Omitting it, or naming no kinds, refuses external drags. |+| `delay` | `number` | Milliseconds of hovering before the dwell fires; defaults to 500. |+| `canDwell` | `(feedback) => boolean` | Gates candidacy; shares a drop target's `canDrop` feedback shape. |+| `acceptsSelf` | `boolean` | Whether the element's own drag may dwell. Defaults to `true`. |+| `onDwell` | `(event) => void` | The drag hovered long enough. |+| `onDwellEnd` | `(event) => void` | The candidacy ended; the place to undo what `onDwell` did. |-Element drags and external drags arrive through different adapters, so a surface-that takes both names both: `types` for the element side, `accepts` for the-external side.+```gjs+<div+ {{dDragDwell+ types="card"+ canDwell=this.canDwell+ onDwell=this.open+ onDwellEnd=this.close+ }}+>+```++`onDwellEnd` carries `reason` (`"left"` or `"drag-ended"`), `fired` (whether+`onDwell` ran for this candidacy), and `droppedHere` (whether the drop landed+on a drop target on the element or on one of its descendants — always `false`+when that subtree registers no target at all) — together the undo predicate: close+again when `fired` and not `droppedHere`, and a drop into the element keeps+it open.++The gate runs when a candidacy would start, on every frame while it is+pending, and once more as the dwell fires — but not after: a dwell that opens+a section falsifies its own "only when closed" gate, so after firing only the+rectangle and the `types`/`externalKinds` filters decide when the candidacy+ends. `canDwell` refuses only+on a literal `false`, after `types`/`externalKinds` filtering, exactly like a+target's `canDrop` — the two may share one function.++Adoption stays the co-located target's job: the dwell has no `adopts`, and an+adopted browser drag answers to its adoption's declared type in `types`.++Two limits worth knowing: the rectangle test does not see occlusion — the+dwell answers to the pointer being inside the element's box, not to the box+being visible under the pointer — and an element drag that leaves the window+freezes its last position, so a pending dwell can fire while the pointer is+outside; the drag's eventual end delivers the `onDwellEnd` that undoes it.++## createDragDwell, the engine underneath++The modifier wraps `createDragDwell`, a plain factory re-exported from the+same module, for a consumer driving a dwell directly when it is coordinate-driven+rather than element-bound: one tracker across many discovered elements, or a+sub-rect rule such as a center-third band.++| Option | Type | Purpose |+| ------------- | --------------------- | ----------------------------------------------------------------- |+| `destroyable` | `object` | Bounds the dwell's lifetime; usually the owning component. |+| `delay` | `number` | Milliseconds of hovering before the dwell fires; defaults to 500. |+| `identity` | `(target) => unknown` | Keys candidacy; defaults to the target itself. |+| `onDwell` | `(target) => void` | Fires once, with the latest same-identity target. |++The returned tracker has two members: `update(target)` reports the current+candidate (`null` for none), and `reset()` cancels and clears, ready for the+next drag.++Semantics worth knowing:++- One fire per uninterrupted candidacy. Reporting the same identity again never+ pushes the deadline out and never re-fires an already-fired dwell. A new+ identity restarts the full delay, and `null` clears, so the same identity can+ dwell again after leaving and returning.+- Silence is not `null`. A consumer that stops calling `update` — a monitor+ frame without input, a pointer holding still — leaves the pending dwell+ running. Only an explicit `null` or `reset()` cancels it.+- A drop or teardown ends the drag without a leave, so wire `reset()` into the+ drop and drag-end paths explicitly. The destructor registered on+ `destroyable` covers teardown.+- When the consumer builds a fresh descriptor per report, pass `identity` to+ name the stable part, or every report reads as a new candidate and the dwell+ never fires.# The dragAndDrop service@@ -474,6 +563,11 @@ move within one labeled list while a drag crosses between lists. The keyboardpath should follow the list the user is stepping through rather than silentlycrossing a semantic boundary.+**A dwell only shortcuts a pointer drag.** Whatever `dDragDwell` reveals+must stay reachable without it: the surface keeps its ordinary affordance — a+disclosure control, a keyboard path — and the dwell merely saves the pointer a+detour mid-drag.+# TestingSynthetic mouse events do not drive a native drag; they stall. Use the helpers.@@ -493,6 +587,12 @@ In JavaScript tests, fromEvery synthetic drag event must carry finite `clientX` and `clientY`, which iswhat `centerOf` is for.+A dwell needs no clock control: its delay collapses under test (see+`discourse/lib/later`), so hover with `startDrag` and `dragOver`, then+`await settled()` for the fire. Edges that must land before the collapsed+delay ride synchronous drop-target hierarchy changes via `dragEventNow`, which+is why a dwell test co-locates a drop target on the dwell element.+In system specs, use `SystemHelpers#drag_and_drop`.# dDraggable is deprecateddiff --git a/frontend/discourse/app/lib/-internals/drag-and-drop/drag-dwell.ts b/frontend/discourse/app/lib/-internals/drag-and-drop/drag-dwell.tsnew file mode 100644index 00000000000..20f7c74006a--- /dev/null+++ b/frontend/discourse/app/lib/-internals/drag-and-drop/drag-dwell.ts@@ -0,0 +1,132 @@+import { isDestroying, registerDestructor } from "@ember/destroyable";+import { cancel } from "@ember/runloop";+import discourseLater from "discourse/lib/later";++const EMPTY = Symbol("empty drag dwell");++/** The dwell delay used when the consumer does not pick one. */+const DEFAULT_DELAY = 500;++/** Options for {@link createDragDwell}. */+export interface DragDwellOptions<Target> {+ /**+ * Object whose lifetime bounds the dwell, usually the component or service+ * that owns it. Destruction cancels a pending dwell and prevents later+ * reports from firing.+ */+ destroyable: object;++ /**+ * Milliseconds of uninterrupted same-identity candidacy required before+ * {@link DragDwellOptions.onDwell} fires. Defaults to `500`. The delay is+ * scheduled through `discourseLater`, so it collapses to a short wait under+ * test.+ */+ delay?: number;++ /**+ * Maps a candidate to the key compared with `Object.is`. Defaults to the+ * candidate itself. Called only for non-null candidates; `null` and+ * `undefined` are both valid returned keys. Must be pure.+ */+ identity?: (target: Target) => unknown;++ /**+ * Fires once after an uninterrupted candidacy, with the most recent object+ * reported for that identity. A throw leaves the identity latched, so it+ * cannot fire again until cleared.+ */+ onDwell: (target: Target) => void;+}++/** A live dwell tracker returned by {@link createDragDwell}. */+export interface DragDwell<Target> {+ /**+ * Reports the current candidate, or `null` to clear it. A report with the+ * same identity refreshes only the retained object: it neither pushes the+ * deadline back nor rearms a dwell that already fired. A new identity+ * cancels any pending dwell and starts a fresh delay.+ */+ update(target: Target | null): void;++ /**+ * Cancels any pending dwell and clears its latched identity. Equivalent to+ * `update(null)` and safe to call repeatedly.+ */+ reset(): void;+}++/**+ * Tracks how long one candidate identity remains current during a drag.+ * Consumers can feed it equally from a drop target's enter/leave callbacks or+ * a monitor's per-frame hit-testing. Silence (not calling {@link DragDwell.update})+ * is not `update(null)` and therefore does not interrupt a pending dwell.+ *+ * `Target` must be non-nullish: `null` is reserved as the clear sentinel.+ *+ * Guide to choosing between the drag and gesture primitives:+ * `docs/developer-guides/docs/03-code-internals/29-drag-and-gesture-primitives.md`+ *+ * @see The `dDragDwell` modifier, which packages this for the common case of+ * one element observed through the drag monitors.+ *+ * @param options - The dwell timing, lifetime, identity, and callback.+ * @returns A tracker for reporting and clearing the current candidate.+ */+export default function createDragDwell<Target>(+ options: DragDwellOptions<Target>+): DragDwell<Target> {+ const { delay = DEFAULT_DELAY, destroyable, identity, onDwell } = options;+ let currentKey: unknown | typeof EMPTY = EMPTY;+ let latestTarget: Target | null = null;+ let timer: ReturnType<typeof discourseLater> | null = null;++ function reset() {+ if (currentKey === EMPTY) {+ return;+ }++ cancel(timer ?? undefined);+ timer = null;+ currentKey = EMPTY;+ latestTarget = null;+ }++ function update(target: Target | null) {+ if (target === null) {+ reset();+ return;+ }++ // isDestroying stays true once destruction completes, so this single+ // check also covers a fully destroyed destroyable.+ if (isDestroying(destroyable)) {+ return;+ }++ const key = identity ? identity(target) : target;+ if (Object.is(key, currentKey)) {+ latestTarget = target;+ return;+ }++ cancel(timer ?? undefined);+ currentKey = key;+ latestTarget = target;+ timer = discourseLater(() => {+ // Null the handle first: a reentrant update() or reset() from+ // onDwell must see no pending timer.+ timer = null;+ if (isDestroying(destroyable)) {+ return;+ }++ onDwell(latestTarget as Target);+ // Retain the target: clearing it would corrupt a reentrant re-arm from onDwell.+ }, delay);+ }++ registerDestructor(destroyable, reset);++ return { reset, update };+}diff --git a/frontend/discourse/app/lib/-internals/drag-and-drop/external-vocabulary.ts b/frontend/discourse/app/lib/-internals/drag-and-drop/external-vocabulary.tsindex 48c622e1175..703f6ffe05e 100644--- a/frontend/discourse/app/lib/-internals/drag-and-drop/external-vocabulary.ts+++ b/frontend/discourse/app/lib/-internals/drag-and-drop/external-vocabulary.ts@@ -84,20 +84,21 @@ export function decorateExternalSource(/*** Whether an incoming external drag is one of the named kinds. An empty or- * missing filter matches every external drag.+ * missing filter matches every external drag; callers wanting "no kinds means+ * refuse" guard before calling.*- * @param accepts - The kind filter as the consumer supplied it.+ * @param kinds - The kind filter as the consumer supplied it.* @param source - The raw payload the underlying library reports.*/export function matchesExternalKind(- accepts: ExternalDragKind | ExternalDragKind[] | undefined,+ kinds: ExternalDragKind | ExternalDragKind[] | undefined,source: NativeExternalDragPayload) {- const kinds = makeArray(accepts);- if (kinds.length === 0) {+ const list = makeArray(kinds);+ if (list.length === 0) {return true;}- return kinds.some((kind) => {+ return list.some((kind) => {const predicate = EXTERNAL_KIND_PREDICATES[kind];// Untyped callers can pass an unknown kind; it matches nothing.return predicate ? predicate({ source }) : false;diff --git a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-auto-scroll.ts b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-auto-scroll.tsindex 75e139c1bff..896afe66662 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-auto-scroll.ts+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-auto-scroll.ts@@ -15,6 +15,7 @@ import {} from "discourse/lib/-internals/drag-and-drop/external-vocabulary";import { matchesDragType } from "discourse/lib/-internals/drag-and-drop/vocabulary";import type { Axis } from "discourse/lib/geometry";+import { makeArray } from "discourse/lib/helpers";/** Which direction the container is allowed to scroll while a drag is in flight. */export type AutoScrollAxis = Axis | "all";@@ -38,7 +39,7 @@ interface DDragAndDropAutoScrollSignature {* Also auto-scroll for drags from outside the window, engaging on these* external kinds. Omit it and an external drag scrolls nothing.*/- accepts?: ExternalDragKind | ExternalDragKind[];+ externalKinds?: ExternalDragKind | ExternalDragKind[];/** Defaults to `"vertical"`. */axis?: AutoScrollAxis;@@ -69,8 +70,8 @@ export type DragAndDropAutoScrollArgs =* below wraps it.** @param getArgsRef - Closure returning the latest args. `types`, `axis` and- * `accepts` are re-read on every scroll attempt; `target`, `element` and- * whether `accepts` is set are read once here and need a fresh registration.+ * `externalKinds` are re-read on every scroll attempt; `target`, `element` and+ * whether `externalKinds` is set are read once here and need a fresh registration.* @returns Cleanup; call it once on teardown.*/export function registerDragAndDropAutoScroll(@@ -80,7 +81,7 @@ export function registerDragAndDropAutoScroll(matchesDragType(getArgsRef().types, source);const matchesKind = ({ source }: { source: NativeExternalDragPayload }) =>- matchesExternalKind(getArgsRef().accepts, source);+ matchesExternalKind(getArgsRef().externalKinds, source);const getAllowedAxis = () => getArgsRef().axis ?? "vertical";@@ -97,9 +98,9 @@ export function registerDragAndDropAutoScroll(}),];- // An absent `accepts` would match every external drag, so the external- // registration is made only when the consumer asked for one.- if (args.accepts) {+ // An absent `externalKinds` would match every external drag, so the external+ // registration is made only when the consumer named at least one kind.+ if (makeArray(args.externalKinds).length > 0) {cleanups.push(scrollsWindow? autoScrollWindowForExternal({@@ -137,11 +138,11 @@ export function registerDragAndDropAutoScroll(* ></span>* ```*- * With `accepts`, for payloads dragged in from outside the window too:+ * With `externalKinds`, for payloads dragged in from outside the window too:** ```hbs* <div class="scroll-container"- * {{dDragAndDropAutoScroll types=(array "card") accepts="urls"}}+ * {{dDragAndDropAutoScroll types=(array "card") externalKinds="urls"}}* >* ```*/@@ -151,7 +152,7 @@ export default modifier<DDragAndDropAutoScrollSignature>(// replaces the registration; cheap between drags, and args rarely change.registerDragAndDropAutoScroll(() => ({types: args.types,- accepts: args.accepts,+ externalKinds: args.externalKinds,axis: args.axis,target: args.target,element,diff --git a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-monitor.ts b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-monitor.tsindex 05c08a62b3e..fef34f37deb 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-monitor.ts+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-monitor.ts@@ -89,6 +89,8 @@ export function registerDragAndDropMonitor(** @see The `dragAndDrop` service to read drag state reactively; rendering from* these callbacks duplicates what it keeps.+ * @see `dDragDwell` for the packaged case of acting once a drag has hovered+ * one element for a delay.*/export default modifier<DDragAndDropMonitorSignature>((_element, _positional, args) =>diff --git a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-target.ts b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-target.tsindex 4d939088935..2e043f198b9 100644--- a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-target.ts+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-target.ts@@ -166,6 +166,9 @@ export function registerDragAndDropTarget(* Element drags, and with `adopts` browser-started drags from page content;* see `dDragAndDropExternalTarget` for payloads dragged in from outside the* window.+ *+ * @see `dDragDwell` to act once a drag has hovered this element for a delay;+ * it composes beside this modifier without joining the target hierarchy.*/export default modifier<DDragAndDropTargetSignature>((element, _positional, args) =>diff --git a/frontend/discourse/app/ui-kit/modifiers/d-drag-dwell.ts b/frontend/discourse/app/ui-kit/modifiers/d-drag-dwell.tsnew file mode 100644index 00000000000..07ac9e2d2d3--- /dev/null+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-dwell.ts@@ -0,0 +1,401 @@+import { destroy } from "@ember/destroyable";+import type { ElementDragPayload } from "@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter";+import type { ExternalDragPayload as NativeExternalDragPayload } from "@atlaskit/pragmatic-drag-and-drop/adapter/external-adapter-types";+import { monitorForElements } from "@atlaskit/pragmatic-drag-and-drop/element/adapter";+import { monitorForExternal } from "@atlaskit/pragmatic-drag-and-drop/external/adapter";+import type { CleanupFn } from "@atlaskit/pragmatic-drag-and-drop/types";+import { modifier } from "ember-modifier";+import { consumerMayThrow } from "discourse/lib/-internals/drag-and-drop/consumer-may-throw";+import createDragDwell, {+ type DragDwell,+} from "discourse/lib/-internals/drag-and-drop/drag-dwell";+import type {+ DragInput,+ DragLocation,+} from "discourse/lib/-internals/drag-and-drop/drop-target-kernel";+import {+ decorateExternalSource,+ type ExternalDragKind,+ type ExternalDragPayload,+ matchesExternalKind,+} from "discourse/lib/-internals/drag-and-drop/external-vocabulary";+import {+ matchesDragType,+ type NormalizedDragSource,+ normalizeDragSource,+} from "discourse/lib/-internals/drag-and-drop/vocabulary";+import { makeArray } from "discourse/lib/helpers";++export {+ default as createDragDwell,+ type DragDwell,+ type DragDwellOptions,+} from "discourse/lib/-internals/drag-and-drop/drag-dwell";++/** Which adapter the observed drag arrived through. */+export type DragDwellFamily = "element" | "external";++/** The dragged payload a dwell observes, from either adapter. */+export type DragDwellSource = NormalizedDragSource | ExternalDragPayload;++/**+ * The observed drag: which adapter carried it, discriminating the payload+ * shape. Checking `family` narrows `source`.+ */+type DragDwellObservation =+ | {+ /** The drag came from a registered element source. */+ family: "element";++ /** The dragged payload, normalized. */+ source: NormalizedDragSource;+ }+ | {+ /** The drag came from outside the window. */+ family: "external";++ /** The decorated external payload. */+ source: ExternalDragPayload;+ };++/**+ * What {@link DragDwellArgs.canDwell} receives — structurally what a drop+ * target's `canDrop` receives, so one gating function can serve both.+ */+export type DragDwellFeedback = DragDwellObservation & {+ /** The pointer, with `clientX`/`clientY`. */+ input: DragInput;++ /** The dwell host element. */+ element: HTMLElement;+};++/** What {@link DragDwellArgs.onDwell} receives. */+export type DragDwellEvent = DragDwellObservation & {+ /** The drag's positions: `initial`, `previous`, and `current`. */+ location: DragLocation;++ /** The dwell host element. */+ element: HTMLElement;+};++/** Why a candidacy ended. */+export type DragDwellEndReason = "left" | "drag-ended";++/** What {@link DragDwellArgs.onDwellEnd} receives. */+export type DragDwellEndEvent = DragDwellEvent & {+ /**+ * `"left"` when the drag stopped hovering the element or stopped+ * qualifying; `"drag-ended"` when the drag finished anywhere — dropped,+ * abandoned, or cancelled.+ */+ reason: DragDwellEndReason;++ /** Whether `onDwell` had fired for this candidacy — the undo predicate. */+ fired: boolean;++ /**+ * On `"drag-ended"`: whether the drop landed on a drop target on this+ * element or on one of its descendants. Always `false` for `"left"`, and+ * `false` when the host subtree registers no drop target at all.+ */+ droppedHere: boolean;+};++interface DDragDwellSignature {+ Element: HTMLElement;+ Args: {+ Named: {+ /**+ * Element drag types to watch. Omit to watch every element drag.+ * Re-read on every frame.+ */+ types?: string | string[];++ /**+ * External drag kinds to watch. Omitting it, or naming no kinds,+ * refuses every external drag: the dwell only reacts to drags from+ * outside the window when a consumer asks for them.+ */+ externalKinds?: ExternalDragKind | ExternalDragKind[];++ /**+ * Milliseconds of qualifying hover before `onDwell` fires. Defaults to+ * `500`. Sampled when the first candidacy arms.+ */+ delay?: number;++ /**+ * Whether a drag hovering the element may start or continue a pending+ * candidacy. Same feedback shape as a drop target's `canDrop`, so the+ * two MAY share one function. Only a literal `false` refuses; it runs+ * after `types`/`externalKinds` filtering, and is not consulted again once+ * the dwell has fired.+ */+ canDwell?: (feedback: DragDwellFeedback) => boolean | void;++ /**+ * Whether a drag whose source element is this element, or inside it,+ * may dwell. Defaults to `true`.+ */+ acceptsSelf?: boolean;++ /** The dwell fired: the drag hovered long enough. */+ onDwell: (event: DragDwellEvent) => void;++ /**+ * The candidacy ended — the drag left, stopped qualifying, or+ * finished. The place to undo what `onDwell` did.+ */+ onDwellEnd?: (event: DragDwellEndEvent) => void;+ };+ Positional: [];+ };+}++/**+ * Every named arg of {@link dDragDwell}, for a consumer driving+ * {@link registerDragDwell} imperatively rather than through the modifier.+ */+export type DragDwellArgs = DDragDwellSignature["Args"]["Named"];++function isWithin(input: DragInput, clientRect: DOMRect) {+ return (+ input.clientX >= clientRect.x &&+ input.clientX <= clientRect.x + clientRect.width &&+ input.clientY >= clientRect.y &&+ input.clientY <= clientRect.y + clientRect.height+ );+}++/**+ * Watches drags the way a monitor does and reports dwells on one element.+ *+ * This uses rectangle containment, which does not account for another element+ * occluding the host. An element drag leaving the window can also leave one+ * stale in-rectangle input until the drag ends. Registering the external+ * monitor mounts that adapter page-wide, as the drag-and-drop service does.+ *+ * The delay is sampled when the first candidacy arms. Every other argument is+ * read lazily from monitor or timer callbacks.+ *+ * @param element - The dwell host.+ * @param getArgsRef - Closure returning the latest arguments.+ * @returns Cleanup; call it once on teardown.+ */+export function registerDragDwell(+ element: HTMLElement,+ getArgsRef: () => DragDwellArgs+): CleanupFn {+ const lifetime = {};+ let dwell: DragDwell<DragDwellEvent> | null = null;+ let hovering = false;+ let fired = false;+ let lastEvent: DragDwellEvent | null = null;+ let isDestroying = false;++ const passesGate = (event: DragDwellEvent) => {+ const callback = getArgsRef().canDwell;+ if (!callback) {+ return true;+ }+ const { location, ...observation } = event;+ return consumerMayThrow(+ () =>+ callback({ ...observation, input: location.current.input }) !== false,+ false+ );+ };++ const getDwell = () => {+ if (dwell) {+ return dwell;+ }++ const { delay } = getArgsRef();+ dwell = createDragDwell<DragDwellEvent>({+ destroyable: lifetime,+ delay,+ identity: () => element,+ onDwell: () => {+ if (isDestroying || !hovering || !lastEvent) {+ return;+ }+ const event = lastEvent;+ const gateAllows = passesGate(event);+ // The gate is consumer code and may have torn this registration down.+ if (isDestroying) {+ return;+ }+ if (!gateAllows) {+ dwell?.reset();+ consumerMayThrow(() =>+ getArgsRef().onDwellEnd?.({+ ...event,+ reason: "left",+ fired: false,+ droppedHere: false,+ })+ );+ hovering = false;+ lastEvent = null;+ return;+ }++ fired = true;+ const consumerOnDwell = getArgsRef().onDwell;+ // A throw from a runloop timer would bypass the normal client-error+ // reporting path without this boundary.+ consumerMayThrow(() => consumerOnDwell(event));+ },+ });+ return dwell;+ };++ const reportCandidate = (event: DragDwellEvent, adapterMatches: boolean) => {+ if (isDestroying) {+ return;+ }++ const inRect = isWithin(+ event.location.current.input,+ element.getBoundingClientRect()+ );+ const qualifies = adapterMatches && inRect && (fired || passesGate(event));+ // The gate is consumer code and may have torn this registration down.+ if (isDestroying) {+ return;+ }++ if (!qualifies) {+ if (!hovering) {+ return;+ }++ dwell?.update(null);+ if (lastEvent) {+ consumerMayThrow(() =>+ getArgsRef().onDwellEnd?.({+ ...lastEvent,+ reason: "left",+ fired,+ droppedHere: false,+ })+ );+ }+ hovering = false;+ fired = false;+ lastEvent = null;+ return;+ }++ if (!hovering) {+ hovering = true;+ fired = false;+ }+ lastEvent = event;+ getDwell().update(event);+ };++ const reportDragEnded = (location: DragLocation) => {+ if (isDestroying || !hovering || !lastEvent) {+ return;+ }++ const event = lastEvent;+ const droppedHere = location.current.dropTargets.some((target) =>+ element.contains(target.element)+ );+ // make-adapter.js dispatches source -> drop targets -> monitors, so a+ // target's onDrop is guaranteed to run before this monitor callback.+ consumerMayThrow(() =>+ getArgsRef().onDwellEnd?.({+ ...event,+ location,+ reason: "drag-ended",+ fired,+ droppedHere,+ })+ );+ dwell?.reset();+ hovering = false;+ fired = false;+ lastEvent = null;+ };++ const reportElementCandidate = (+ source: ElementDragPayload,+ location: DragLocation+ ) => {+ const args = getArgsRef();+ const normalizedSource = normalizeDragSource(source);+ const acceptsSelf =+ args.acceptsSelf !== false || !element.contains(normalizedSource.element);+ reportCandidate(+ { family: "element", source: normalizedSource, location, element },+ // Matched on the raw payload: an adopted drag answers to its adoption's+ // declared type there, which normalization strips from `data`.+ matchesDragType(args.types, source) && acceptsSelf+ );+ };++ const reportExternalCandidate = (+ source: NativeExternalDragPayload,+ location: DragLocation+ ) => {+ const { externalKinds } = getArgsRef();+ reportCandidate(+ {+ family: "external",+ source: decorateExternalSource(source),+ location,+ element,+ },+ makeArray(externalKinds).length > 0 &&+ matchesExternalKind(externalKinds, source)+ );+ };++ const cleanupElements = monitorForElements({+ onDragStart: ({ source, location }) =>+ reportElementCandidate(source, location),+ onDrag: ({ source, location }) => reportElementCandidate(source, location),+ onDropTargetChange: ({ source, location }) =>+ reportElementCandidate(source, location),+ onDrop: ({ location }) => reportDragEnded(location),+ });++ const cleanupExternal = monitorForExternal({+ onDragStart: ({ source, location }) =>+ reportExternalCandidate(source, location),+ onDrag: ({ source, location }) => reportExternalCandidate(source, location),+ onDropTargetChange: ({ source, location }) =>+ reportExternalCandidate(source, location),+ onDrop: ({ location }) => reportDragEnded(location),+ });++ return () => {+ isDestroying = true;+ cleanupElements();+ cleanupExternal();+ destroy(lifetime);+ hovering = false;+ fired = false;+ lastEvent = null;+ };+}++/**+ * Fires a callback once a drag has hovered the element for a delay, without+ * making the element a drop target. Every arg is documented on+ * {@link DragDwellArgs}.+ *+ * ```hbs+ * <div {{dDragDwell types="card" onDwell=this.open onDwellEnd=this.close}}>+ * ```+ */+export default modifier<DDragDwellSignature>((element, _positional, args) =>+ // Read args inside the closure: reading them here would track them and+ // re-run the modifier, tearing down a live candidacy.+ registerDragDwell(element, () => args)+);diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-auto-scroll-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-auto-scroll-test.gjsindex d459c3d6e04..1c2d79a3445 100644--- a/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-auto-scroll-test.gjs+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-auto-scroll-test.gjs@@ -1,3 +1,4 @@+import { array } from "@ember/helper";import { find, render } from "@ember/test-helpers";import { module, test } from "qunit";import { setupRenderingTest } from "discourse/tests/helpers/component-test";@@ -34,14 +35,14 @@ module(id="scroller"style="height: 100px; overflow-y: auto"{{dDragAndDropExternalTarget accepts="text"}}- {{dDragAndDropAutoScroll accepts=@accepts}}+ {{dDragAndDropAutoScroll externalKinds=@externalKinds}}><div style="height: 600px">tall</div></div></template>;test("external auto-scroll moves the container for a drag from outside the window", async function (assert) {- await render(<template><scroller @accepts="text" /></template>);+ await render(<template><scroller @externalKinds="text" /></template>);await hoverNearBottomEdge("#scroller", textTransfer());@@ -62,6 +63,20 @@ module("a container that named no external kinds is not scrolled by one");});++ test("external auto-scroll treats an empty kind list as staying off", async function (assert) {+ await render(+ <template><scroller @externalKinds={{(array)}} /></template>+ );++ await hoverNearBottomEdge("#scroller", textTransfer());++ assert.strictEqual(+ find("#scroller").scrollTop,+ 0,+ "an empty kind list opts nothing in"+ );+ });});});diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-dwell-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-dwell-test.gjsnew file mode 100644index 00000000000..82a8667dd84--- /dev/null+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-dwell-test.gjs@@ -0,0 +1,964 @@+import { tracked } from "@glimmer/tracking";+import { array } from "@ember/helper";+import {+ render,+ resetOnerror,+ settled,+ setupOnerror,+} from "@ember/test-helpers";+import { setupRenderingTest } from "ember-qunit";+import { module, test } from "qunit";+import {+ centerOf,+ dragEvent,+ dragEventNow,+ dragOver,+ resetDragAndDropForTesting,+ startDrag,+ textTransfer,+} from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";+import dDragAndDropSource from "discourse/ui-kit/modifiers/d-drag-and-drop-source";+import dDragAndDropTarget from "discourse/ui-kit/modifiers/d-drag-and-drop-target";+import dDragDwell, {+ registerDragDwell,+} from "discourse/ui-kit/modifiers/d-drag-dwell";++/* The dwell delay collapses to a 10ms runloop timer under test, which is+ SHORTER than one ~16ms animation frame. Sequences that must run before a+ pending dwell fires therefore use dragEventNow edges in one task — the+ library reports drop-target hierarchy changes synchronously — and every+ element-drag fixture co-locates a drop target on the dwell element so those+ edges exist. `await settled()` resolves the collapsed timer for fire paths. */++const CHIP = "[data-test-chip]";+const DWELL = "[data-test-dwell]";+const INNER = "[data-test-inner]";+const OUTSIDE = "[data-test-outside]";++module("Integration | ui-kit | Modifier | dDragDwell", function (hooks) {+ setupRenderingTest(hooks);++ hooks.afterEach(function () {+ resetDragAndDropForTesting();+ });++ test("dDragDwell fires once the drag has hovered the element", async function (assert) {+ const dwells = [];+ const onDwell = (event) => dwells.push(event);++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropTarget accepts="card" indicator=false}}+ {{dDragDwell types="card" onDwell=onDwell}}+ >folder</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(CHIP, { dataTransfer });+ await dragOver(DWELL, { dataTransfer });+ await settled();+ assert.strictEqual(dwells.length, 1, "fires once the delay elapses");++ const event = dwells[0];+ assert.strictEqual(event.family, "element", "family discriminant");+ assert.strictEqual(event.source.type, "card", "normalized source");+ assert.strictEqual(+ event.element,+ document.querySelector(DWELL),+ "the dwell host element"+ );+ assert.true(+ Number.isFinite(event.location.current.input.clientX),+ "location carries the pointer"+ );+ });++ test("dDragDwell fires once per candidacy while frames keep coming", async function (assert) {+ const dwells = [];+ const onDwell = (event) => dwells.push(event);++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropTarget accepts="card" indicator=false}}+ {{dDragDwell types="card" onDwell=onDwell}}+ >folder</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(CHIP, { dataTransfer });+ await dragOver(DWELL, { dataTransfer });+ await settled();+ assert.strictEqual(dwells.length, 1, "fired once");++ const point = centerOf(DWELL);+ for (let i = 0; i < 6; i += 1) {+ await dragEvent(DWELL, "dragover", {+ dataTransfer,+ clientX: point.clientX + i,+ clientY: point.clientY,+ });+ }+ await settled();+ assert.strictEqual(+ dwells.length,+ 1,+ "continued in-rect frames never re-fire"+ );+ });++ test("dDragDwell leaving before the delay cancels the pending dwell", async function (assert) {+ const dwells = [];+ const ends = [];+ const onDwell = (event) => dwells.push(event);+ const onDwellEnd = (event) => ends.push(event);++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropTarget accepts="card" indicator=false}}+ {{dDragDwell types="card" onDwell=onDwell onDwellEnd=onDwellEnd}}+ >folder</div>+ <div+ data-test-outside+ style="display: block; height: 60px; margin-top: 30px;"+ {{dDragAndDropTarget accepts="card" indicator=false}}+ >outside</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(CHIP, { dataTransfer });++ // Both edges land synchronously in one task, before the collapsed 10ms+ // timer can possibly run.+ dragEventNow(DWELL, "dragenter", { dataTransfer, ...centerOf(DWELL) });+ dragEventNow(OUTSIDE, "dragenter", { dataTransfer, ...centerOf(OUTSIDE) });++ await settled();+ assert.strictEqual(dwells.length, 0, "the cancelled dwell never fires");+ assert.strictEqual(ends.length, 1, "one candidacy ended");+ assert.strictEqual(ends[0].reason, "left", "by leaving");+ assert.false(ends[0].fired, "before firing");+ assert.false(ends[0].droppedHere, "droppedHere is false for a leave");+ });++ test("dDragDwell leaving after the fire reports fired for the undo", async function (assert) {+ const dwells = [];+ const ends = [];+ const onDwell = (event) => dwells.push(event);+ const onDwellEnd = (event) => ends.push(event);++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropTarget accepts="card" indicator=false}}+ {{dDragDwell types="card" onDwell=onDwell onDwellEnd=onDwellEnd}}+ >folder</div>+ <div+ data-test-outside+ style="display: block; height: 60px; margin-top: 30px;"+ {{dDragAndDropTarget accepts="card" indicator=false}}+ >outside</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(CHIP, { dataTransfer });+ await dragOver(DWELL, { dataTransfer });+ await settled();+ assert.strictEqual(dwells.length, 1, "fired");++ await dragEvent(OUTSIDE, "dragenter", {+ dataTransfer,+ ...centerOf(OUTSIDE),+ });+ await settled();+ assert.strictEqual(ends.length, 1, "the candidacy ended");+ assert.strictEqual(ends[0].reason, "left", "by leaving");+ assert.true(ends[0].fired, "after having fired");+ });++ test("dDragDwell reports the drop-target onDrop before onDwellEnd, with droppedHere", async function (assert) {+ const order = [];+ const onTargetDrop = () => order.push("target-drop");+ const onDwell = () => order.push("dwell");+ const onDwellEnd = (event) =>+ order.push(`end:${event.reason}:${event.fired}:${event.droppedHere}`);++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropTarget+ accepts="card"+ indicator=false+ onDrop=onTargetDrop+ }}+ {{dDragDwell types="card" onDwell=onDwell onDwellEnd=onDwellEnd}}+ >folder</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(CHIP, { dataTransfer });+ await dragOver(DWELL, { dataTransfer });+ await settled();++ await dragEvent(DWELL, "drop", { dataTransfer, ...centerOf(DWELL) });+ await dragEvent(CHIP, "dragend", { dataTransfer, ...centerOf(DWELL) });+ await settled();++ assert.deepEqual(+ order,+ ["dwell", "target-drop", "end:drag-ended:true:true"],+ "the target's onDrop ran before the dwell's end callback, which saw the drop land here"+ );+ });++ test("dDragDwell reports the terminal location on drag-ended", async function (assert) {+ const ends = [];+ const onDwell = () => {};+ const onDwellEnd = (event) => ends.push(event);++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropTarget accepts="card" indicator=false}}+ {{dDragDwell types="card" onDwell=onDwell onDwellEnd=onDwellEnd}}+ >folder</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(CHIP, { dataTransfer });+ await dragOver(DWELL, { dataTransfer });+ await settled();++ const point = centerOf(DWELL);+ const dropPoint = {+ clientX: point.clientX + 17,+ clientY: point.clientY + 5,+ };+ await dragEvent(DWELL, "drop", { dataTransfer, ...dropPoint });+ await settled();++ assert.strictEqual(ends.length, 1, "the drop ended the candidacy");+ assert.strictEqual(+ ends[0].location.current.input.clientX,+ dropPoint.clientX,+ "the end event carries the drop's own position, not the last hover frame"+ );+ });++ test("dDragDwell reports an abandoned drag as drag-ended without droppedHere", async function (assert) {+ const ends = [];+ const onDwell = () => {};+ const onDwellEnd = (event) => ends.push(event);++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropTarget accepts="card" indicator=false}}+ {{dDragDwell types="card" onDwell=onDwell onDwellEnd=onDwellEnd}}+ >folder</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(CHIP, { dataTransfer });+ await dragOver(DWELL, { dataTransfer });+ await settled();++ // A dragend with no drop is the abandon/cancel path; the library empties+ // the targets and still reports the drag's end.+ await dragEvent(CHIP, "dragend", { dataTransfer, ...centerOf(DWELL) });+ await settled();++ assert.strictEqual(ends.length, 1, "the candidacy ended");+ assert.strictEqual(ends[0].reason, "drag-ended", "with the drag");+ assert.true(ends[0].fired, "after having fired");+ assert.false(ends[0].droppedHere, "nothing landed here");+ });++ test("dDragDwell never arms when canDwell refuses", async function (assert) {+ const dwells = [];+ const ends = [];+ const onDwell = (event) => dwells.push(event);+ const onDwellEnd = (event) => ends.push(event);+ const refuse = () => false;++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropTarget accepts="card" indicator=false}}+ {{dDragDwell+ types="card"+ canDwell=refuse+ onDwell=onDwell+ onDwellEnd=onDwellEnd+ }}+ >folder</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(CHIP, { dataTransfer });+ await dragOver(DWELL, { dataTransfer });+ await settled();++ assert.strictEqual(dwells.length, 0, "a refused dwell never fires");+ assert.strictEqual(ends.length, 0, "and no candidacy ever ended");+ });++ test("dDragDwell treats a throwing canDwell as a refusal", async function (assert) {+ const caught = [];+ setupOnerror((error) => caught.push(error));++ try {+ const dwells = [];+ const onDwell = (event) => dwells.push(event);+ const gate = () => {+ throw new Error("gate failure");+ };++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropTarget accepts="card" indicator=false}}+ {{dDragDwell types="card" canDwell=gate onDwell=onDwell}}+ >folder</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(CHIP, { dataTransfer });+ await dragOver(DWELL, { dataTransfer });+ await settled();++ assert.strictEqual(dwells.length, 0, "a throwing gate refuses");+ assert.true(caught.length >= 1, "the throw surfaced through onerror");+ } finally {+ resetOnerror();+ }+ });++ test("dDragDwell contains a throwing onDwell and still reports the end", async function (assert) {+ const caught = [];+ setupOnerror((error) => caught.push(error));++ try {+ const ends = [];+ const onDwell = () => {+ throw new Error("dwell failure");+ };+ const onDwellEnd = (event) => ends.push(event);++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropTarget accepts="card" indicator=false}}+ {{dDragDwell types="card" onDwell=onDwell onDwellEnd=onDwellEnd}}+ >folder</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(CHIP, { dataTransfer });+ await dragOver(DWELL, { dataTransfer });+ await settled();+ assert.true(caught.length >= 1, "the throw surfaced through onerror");++ await dragEvent(CHIP, "dragend", { dataTransfer, ...centerOf(DWELL) });+ await settled();+ assert.strictEqual(ends.length, 1, "the candidacy still ended");+ assert.true(ends[0].fired, "with fired set before the throw");+ } finally {+ resetOnerror();+ }+ });++ test("dDragDwell ignores a candidacy whose gate tears the registration down", async function (assert) {+ const caught = [];+ setupOnerror((error) => caught.push(error));++ try {+ const dwells = [];+ const ends = [];+ let cleanup;+ const gate = () => {+ cleanup();+ return true;+ };++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ >folder</div>+ </template>+ );++ cleanup = registerDragDwell(document.querySelector(DWELL), () => ({+ types: "card",+ canDwell: gate,+ onDwell: (event) => dwells.push(event),+ onDwellEnd: (event) => ends.push(event),+ }));++ const dataTransfer = new DataTransfer();+ const point = centerOf(DWELL);+ await startDrag(CHIP, { dataTransfer });+ await dragEvent(DWELL, "dragenter", { dataTransfer, ...point });+ for (let i = 0; i < 4; i += 1) {+ await dragEvent(DWELL, "dragover", { dataTransfer, ...point });+ }+ await settled();++ assert.deepEqual(+ caught,+ [],+ "the synchronous teardown surfaced no error"+ );+ assert.strictEqual(dwells.length, 0, "nothing fires after the teardown");+ assert.strictEqual(ends.length, 0, "and nothing reports into it");+ } finally {+ resetOnerror();+ }+ });++ test("dDragDwell clears a pending dwell when canDwell stops qualifying", async function (assert) {+ const dwells = [];+ const ends = [];+ const onDwell = (event) => dwells.push(event);+ const onDwellEnd = (event) => ends.push(event);+ let allowed = true;+ const gate = () => allowed;++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropTarget accepts="card" indicator=false}}+ {{dDragDwell+ types="card"+ canDwell=gate+ onDwell=onDwell+ onDwellEnd=onDwellEnd+ }}+ >+ <div+ data-test-inner+ style="display: block; height: 20px;"+ {{dDragAndDropTarget accepts="card" indicator=false}}+ >inner</div>+ </div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(CHIP, { dataTransfer });++ // Arm and re-evaluate synchronously in one task: the inner target changes+ // the hierarchy while the pointer stays inside the dwell rect.+ dragEventNow(DWELL, "dragenter", { dataTransfer, ...centerOf(DWELL) });+ allowed = false;+ dragEventNow(INNER, "dragenter", { dataTransfer, ...centerOf(INNER) });++ await settled();+ assert.strictEqual(dwells.length, 0, "the cleared dwell never fires");+ assert.strictEqual(ends.length, 1, "one candidacy ended");+ assert.strictEqual(ends[0].reason, "left", "reported as a leave");+ assert.false(ends[0].fired, "before firing");+ });++ test("dDragDwell re-validates canDwell at fire time", async function (assert) {+ const dwells = [];+ const ends = [];+ const onDwell = (event) => dwells.push(event);+ const onDwellEnd = (event) => ends.push(event);+ let allowed = true;+ const gate = () => allowed;++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropTarget accepts="card" indicator=false}}+ {{dDragDwell+ types="card"+ canDwell=gate+ onDwell=onDwell+ onDwellEnd=onDwellEnd+ }}+ >folder</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(CHIP, { dataTransfer });++ dragEventNow(DWELL, "dragenter", { dataTransfer, ...centerOf(DWELL) });+ allowed = false;++ // Either a pending pointer frame or the timer re-checks the gate. Both+ // paths must report exactly one end.+ await settled();+ assert.strictEqual(dwells.length, 0, "the vetoed dwell never fires");+ assert.strictEqual(ends.length, 1, "the vetoed candidacy reports its end");+ assert.strictEqual(ends[0]?.reason, "left", "as a leave");+ assert.false(ends[0]?.fired, "before ever firing");++ await dragEvent(CHIP, "dragend", { dataTransfer, ...centerOf(DWELL) });+ await settled();+ assert.strictEqual(dwells.length, 0, "still nothing after the drag ends");+ assert.strictEqual(+ ends.length,+ 1,+ "and no second end for the dead candidacy"+ );+ });++ test("dDragDwell ignores element drags outside its types", async function (assert) {+ const dwells = [];+ const ends = [];+ const onDwell = (event) => dwells.push(event);+ const onDwellEnd = (event) => ends.push(event);++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="other"}}>chip</div>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropTarget accepts="other" indicator=false}}+ {{dDragDwell types="card" onDwell=onDwell onDwellEnd=onDwellEnd}}+ >folder</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(CHIP, { dataTransfer });+ await dragOver(DWELL, { dataTransfer });+ await settled();++ assert.strictEqual(dwells.length, 0, "a filtered drag never dwells");+ assert.strictEqual(ends.length, 0, "and never ends a candidacy");+ });++ test("dDragDwell matches an adopted drag by its adoption's declared type", async function (assert) {+ const dwells = [];+ const onDwell = (event) => dwells.push(event);+ const WEB_LINK = {+ type: "web-link",+ match: ({ element }) => Boolean(element.closest("a[href]")),+ };++ await render(+ <template>+ <a data-test-anchor href="https://example.com/adopted">a link</a>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropTarget adopts=WEB_LINK indicator=false}}+ {{dDragDwell types="web-link" onDwell=onDwell}}+ >folder</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ dataTransfer.setData("text/uri-list", "https://example.com/adopted");+ await dragEvent("[data-test-anchor]", "dragstart", {+ dataTransfer,+ ...centerOf("[data-test-anchor]"),+ });+ await dragOver(DWELL, { dataTransfer });+ await settled();++ assert.strictEqual(+ dwells.length,+ 1,+ "an explicit types filter matches the adoption's declared type"+ );+ assert.strictEqual(+ dwells[0]?.source.type,+ "web-link",+ "the source reports the adoption's type"+ );+ });++ test("dDragDwell refuses external drags unless externalKinds opts in", async function (assert) {+ const dwells = [];+ const onDwell = (event) => dwells.push(event);++ await render(+ <template>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragDwell types="card" onDwell=onDwell}}+ >folder</div>+ </template>+ );++ const dataTransfer = textTransfer();+ const point = centerOf(DWELL);+ await dragEvent(DWELL, "dragenter", { dataTransfer, ...point });+ for (let i = 0; i < 4; i += 1) {+ await dragEvent(DWELL, "dragover", { dataTransfer, ...point });+ }+ await settled();++ assert.strictEqual(dwells.length, 0, "no externalKinds, no external dwell");+ });++ test("dDragDwell treats an empty externalKinds list as refusing external drags", async function (assert) {+ const dwells = [];+ const onDwell = (event) => dwells.push(event);++ await render(+ <template>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragDwell externalKinds=(array) onDwell=onDwell}}+ >folder</div>+ </template>+ );++ const dataTransfer = textTransfer();+ const point = centerOf(DWELL);+ await dragEvent(DWELL, "dragenter", { dataTransfer, ...point });+ for (let i = 0; i < 4; i += 1) {+ await dragEvent(DWELL, "dragover", { dataTransfer, ...point });+ }+ await settled();++ assert.strictEqual(dwells.length, 0, "an empty kind list opts nothing in");+ });++ test("dDragDwell dwells on an external drag and ends with its drop", async function (assert) {+ const dwells = [];+ const ends = [];+ const onDwell = (event) => dwells.push(event);+ const onDwellEnd = (event) => ends.push(event);++ await render(+ <template>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragDwell+ externalKinds="text"+ onDwell=onDwell+ onDwellEnd=onDwellEnd+ }}+ >folder</div>+ </template>+ );++ const dataTransfer = textTransfer();+ const point = centerOf(DWELL);+ await dragEvent(DWELL, "dragenter", { dataTransfer, ...point });+ for (let i = 0; i < 4; i += 1) {+ await dragEvent(DWELL, "dragover", { dataTransfer, ...point });+ }+ await settled();++ assert.strictEqual(dwells.length, 1, "the external drag dwelled");+ assert.strictEqual(dwells[0].family, "external", "family discriminant");+ assert.true(dwells[0].source.containsText(), "the decorated payload");++ await dragEvent(DWELL, "drop", { dataTransfer, ...point });+ await settled();+ assert.strictEqual(ends.length, 1, "the drop ended the candidacy");+ assert.strictEqual(ends[0].reason, "drag-ended", "with the drag");+ assert.true(ends[0].fired, "after having fired");+ });++ test("dDragDwell tears down silently mid-drag", async function (assert) {+ const dwells = [];+ const ends = [];+ const onDwell = (event) => dwells.push(event);+ const onDwellEnd = (event) => ends.push(event);++ class State {+ @tracked show = true;+ }+ const state = new State();++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ {{#if state.show}}+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropTarget accepts="card" indicator=false}}+ {{dDragDwell types="card" onDwell=onDwell onDwellEnd=onDwellEnd}}+ >folder</div>+ {{/if}}+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(CHIP, { dataTransfer });+ await dragOver(DWELL, { dataTransfer });+ await settled();+ assert.strictEqual(dwells.length, 1, "fired");++ state.show = false;+ await settled();+ assert.strictEqual(+ ends.length,+ 0,+ "teardown mid-drag reports nothing into the dying surface"+ );+ });++ test("dDragDwell reports droppedHere false when the host is not a drop target", async function (assert) {+ const dwells = [];+ const ends = [];+ const onDwell = (event) => dwells.push(event);+ const onDwellEnd = (event) => ends.push(event);++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragDwell types="card" onDwell=onDwell onDwellEnd=onDwellEnd}}+ >folder</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ const point = centerOf(DWELL);+ await startDrag(CHIP, { dataTransfer });+ await dragEvent(DWELL, "dragenter", { dataTransfer, ...point });+ for (let i = 0; i < 4; i += 1) {+ await dragEvent(DWELL, "dragover", { dataTransfer, ...point });+ }+ await settled();+ assert.strictEqual(dwells.length, 1, "the dwell fired without a target");++ await dragEvent(CHIP, "dragend", { dataTransfer, ...point });+ await settled();+ assert.strictEqual(ends.length, 1, "the drag end reported");+ assert.strictEqual(ends[0].reason, "drag-ended", "as drag-ended");+ assert.true(ends[0].fired, "after the fire");+ assert.false(+ ends[0].droppedHere,+ "a host that is no drop target never reports droppedHere"+ );+ });++ test("dDragDwell ignores a drop caught by a target outside the host", async function (assert) {+ const dwells = [];+ const ends = [];+ const onDwell = (event) => dwells.push(event);+ const onDwellEnd = (event) => ends.push(event);++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ <div+ data-test-outside+ style="display: block; padding: 12px;"+ {{dDragAndDropTarget accepts="card" indicator=false}}+ >+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragDwell types="card" onDwell=onDwell onDwellEnd=onDwellEnd}}+ >folder</div>+ </div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ const point = centerOf(DWELL);+ await startDrag(CHIP, { dataTransfer });+ await dragEvent(DWELL, "dragenter", { dataTransfer, ...point });+ for (let i = 0; i < 4; i += 1) {+ await dragEvent(DWELL, "dragover", { dataTransfer, ...point });+ }+ await settled();+ assert.strictEqual(dwells.length, 1, "the dwell fired");++ // The pointer is inside the host, but the catching target is an ancestor,+ // not the host or a descendant.+ await dragEvent(DWELL, "drop", { dataTransfer, ...point });+ await settled();+ assert.strictEqual(ends.length, 1, "the drop ended the candidacy");+ assert.false(+ ends[0].droppedHere,+ "a target outside the host never counts as droppedHere"+ );+ });++ test("dDragDwell refuses the element's own drag when acceptsSelf is false", async function (assert) {+ const dwells = [];+ const onDwell = (event) => dwells.push(event);++ await render(+ <template>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropSource type="card"}}+ {{dDragAndDropTarget+ accepts="card"+ acceptsSelf=false+ indicator=false+ }}+ {{dDragDwell types="card" acceptsSelf=false onDwell=onDwell}}+ >row</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(DWELL, { dataTransfer });+ await dragOver(DWELL, { dataTransfer });+ await settled();++ assert.strictEqual(dwells.length, 0, "its own drag never dwells");+ });++ test("dDragDwell lets the element's own drag dwell by default", async function (assert) {+ const dwells = [];+ const onDwell = (event) => dwells.push(event);++ await render(+ <template>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropSource type="card"}}+ {{dDragAndDropTarget accepts="card" indicator=false}}+ {{dDragDwell types="card" onDwell=onDwell}}+ >row</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(DWELL, { dataTransfer });+ await dragOver(DWELL, { dataTransfer });+ await settled();++ assert.strictEqual(+ dwells.length,+ 1,+ "by default the element's own drag may dwell"+ );+ });++ test("dDragDwell arms from the drag's own start inside the host", async function (assert) {+ const dwells = [];+ const onDwell = (event) => dwells.push(event);++ await render(+ <template>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropSource type="card"}}+ {{dDragAndDropTarget accepts="card" indicator=false}}+ {{dDragDwell types="card" onDwell=onDwell}}+ >row</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(DWELL, { dataTransfer });+ await settled();++ assert.strictEqual(+ dwells.length,+ 1,+ "the initial observation armed the dwell without a later frame"+ );+ });++ test("dDragDwell hands canDwell the shared drop-gate feedback shape", async function (assert) {+ const feedbacks = [];+ const gate = (feedback) => {+ feedbacks.push(feedback);+ return true;+ };+ const onDwell = () => {};++ await render(+ <template>+ <div data-test-chip {{dDragAndDropSource type="card"}}>chip</div>+ <div+ data-test-dwell+ style="display: block; height: 60px;"+ {{dDragAndDropTarget accepts="card" canDrop=gate indicator=false}}+ {{dDragDwell types="card" canDwell=gate onDwell=onDwell}}+ >folder</div>+ </template>+ );++ const dataTransfer = new DataTransfer();+ await startDrag(CHIP, { dataTransfer });+ await dragOver(DWELL, { dataTransfer });+ await settled();++ const dwellFeedback = feedbacks.find((f) => f.family === "element");+ assert.notStrictEqual(+ dwellFeedback,+ undefined,+ "the dwell consulted the shared gate"+ );+ assert.strictEqual(dwellFeedback.source.type, "card", "with the source");+ assert.true(+ Number.isFinite(dwellFeedback.input.clientX),+ "the pointer input"+ );+ assert.strictEqual(+ dwellFeedback.element,+ document.querySelector(DWELL),+ "and the host element"+ );+ });+});diff --git a/frontend/discourse/tests/unit/lib/-internals/drag-and-drop/drag-dwell-test.ts b/frontend/discourse/tests/unit/lib/-internals/drag-and-drop/drag-dwell-test.tsnew file mode 100644index 00000000000..d92586c6f1d--- /dev/null+++ b/frontend/discourse/tests/unit/lib/-internals/drag-and-drop/drag-dwell-test.ts@@ -0,0 +1,517 @@+import { destroy } from "@ember/destroyable";+import { resetOnerror, settled, setupOnerror } from "@ember/test-helpers";+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import sinon from "sinon";+import { createDragDwell } from "discourse/ui-kit/modifiers/d-drag-dwell";++/* Under test, discourseLater collapses every delay to a 10ms runloop timer+ (app/lib/later.ts), so `await settled()` resolves a pending dwell and the+ configured delay value itself is unobservable. The fake-clock tests below+ tick around that collapsed 10ms deadline and stay fully synchronous: a+ restored fake clock orphans any still-pending backburner timer, so each of+ them must end with the dwell fired or reset. */++module("Unit | Lib | drag-dwell", function (hooks) {+ setupTest(hooks);++ let parent: object;++ hooks.beforeEach(function () {+ parent = {};+ });++ hooks.afterEach(function () {+ // Quiesces any timer a failing test left behind, via the registered+ // destructor, before the test-isolation validator looks for one.+ destroy(parent);+ });++ test("fires with the target once the delay elapses, never synchronously", async function (assert) {+ const seen: string[] = [];+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ onDwell: (target: string) => seen.push(target),+ });++ dwell.update("candidate");+ assert.deepEqual(seen, [], "nothing fires synchronously");++ await settled();+ assert.deepEqual(seen, ["candidate"], "fires once the delay elapses");+ });++ test("omitting delay uses the built-in default", function (assert) {+ const clock = sinon.useFakeTimers({+ now: Date.now(),+ shouldAdvanceTime: false,+ });++ try {+ const seen: string[] = [];+ const dwell = createDragDwell({+ destroyable: parent,+ onDwell: (target: string) => seen.push(target),+ });++ dwell.update("candidate");+ clock.tick(5);+ // An unapplied default would pass `undefined` to the scheduler, which+ // skips the numeric test-time collapse and misses the 10ms deadline.+ assert.deepEqual(seen, [], "not fired before the collapsed deadline");++ clock.tick(6);+ assert.deepEqual(seen, ["candidate"], "fired at the collapsed deadline");+ } finally {+ clock.restore();+ }+ });++ test("does not re-fire while the same identity continues uninterrupted", async function (assert) {+ const seen: string[] = [];+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ onDwell: (target: string) => seen.push(target),+ });++ dwell.update("candidate");+ await settled();+ assert.deepEqual(seen, ["candidate"], "fired once");++ dwell.update("candidate");+ dwell.update("candidate");+ await settled();+ assert.deepEqual(+ seen,+ ["candidate"],+ "continued same-identity reports never re-fire"+ );+ });++ test("a same-identity report does not push the deadline back", function (assert) {+ const clock = sinon.useFakeTimers({+ now: Date.now(),+ shouldAdvanceTime: false,+ });++ try {+ const seen: string[] = [];+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ onDwell: (target: string) => seen.push(target),+ });++ dwell.update("candidate");+ clock.tick(6);+ dwell.update("candidate");+ clock.tick(6);++ // 12ms is past the collapsed 10ms deadline; an implementation that+ // restarted the timer on the second report would need 16ms.+ assert.deepEqual(seen, ["candidate"], "the original deadline held");+ } finally {+ clock.restore();+ }+ });++ test("an identity change cancels the pending dwell and arms a full fresh delay", function (assert) {+ const clock = sinon.useFakeTimers({+ now: Date.now(),+ shouldAdvanceTime: false,+ });++ try {+ const seen: object[] = [];+ const first = { label: "same shape" };+ const second = { label: "same shape" };+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ onDwell: (target: object) => seen.push(target),+ });++ dwell.update(first);+ clock.tick(6);+ // Structurally equal but a different reference: a NEW identity under+ // the default identity function.+ dwell.update(second);+ clock.tick(6);+ assert.deepEqual(+ seen,+ [],+ "12ms in, the restarted deadline has not elapsed"+ );++ clock.tick(5);+ assert.strictEqual(seen.length, 1, "fires once the fresh delay elapses");+ assert.strictEqual(seen[0], second, "fires with the new target only");+ } finally {+ clock.restore();+ }+ });++ test("a null report cancels the pending dwell, and repeated nulls are no-ops", async function (assert) {+ const seen: string[] = [];+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ onDwell: (target: string) => seen.push(target),+ });++ dwell.update(null);+ dwell.update(null);++ dwell.update("candidate");+ await settled();+ assert.deepEqual(+ seen,+ ["candidate"],+ "idle nulls leave the dwell able to arm and fire"+ );++ dwell.update(null);+ dwell.update("candidate");+ dwell.update(null);+ await settled();+ assert.deepEqual(seen, ["candidate"], "the cancelled dwell never fires");+ });++ test("the same identity can dwell again after reset()", async function (assert) {+ const seen: string[] = [];+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ onDwell: (target: string) => seen.push(target),+ });++ dwell.update("candidate");+ await settled();++ dwell.reset();+ dwell.update("candidate");+ await settled();+ assert.deepEqual(+ seen,+ ["candidate", "candidate"],+ "reset() clears the latched identity"+ );+ });++ test("the same identity can dwell again after leaving via null and returning", async function (assert) {+ const seen: string[] = [];+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ onDwell: (target: string) => seen.push(target),+ });++ dwell.update("candidate");+ await settled();++ dwell.update(null);+ dwell.update("candidate");+ await settled();+ assert.deepEqual(+ seen,+ ["candidate", "candidate"],+ "a null report clears the latched identity"+ );+ });++ test("reset() is idempotent and leaves the dwell usable", async function (assert) {+ const seen: string[] = [];+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ onDwell: (target: string) => seen.push(target),+ });++ dwell.reset();+ dwell.reset();++ dwell.update("candidate");+ dwell.reset();+ dwell.reset();+ await settled();+ assert.deepEqual(seen, [], "the cancelled dwell never fires");++ dwell.update("candidate");+ await settled();+ assert.deepEqual(seen, ["candidate"], "still usable after resets");+ });++ test("destroying the destroyable cancels the pending dwell and disables firing", async function (assert) {+ const seen: string[] = [];+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ onDwell: (target: string) => seen.push(target),+ });++ dwell.update("candidate");+ destroy(parent);+ await settled();+ assert.deepEqual(seen, [], "the armed dwell never fires after destroy");++ dwell.update("candidate");+ await settled();+ assert.deepEqual(seen, [], "a report after destroy cannot fire either");+ });++ test("a report after destroy arms no timer at all", async function (assert) {+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ onDwell: () => {},+ });++ destroy(parent);+ await settled();++ const clock = sinon.useFakeTimers({+ now: Date.now(),+ shouldAdvanceTime: false,+ });+ try {+ dwell.update("candidate");+ assert.strictEqual(+ clock.countTimers(),+ 0,+ "no timer is scheduled once the destroyable is gone"+ );+ // Drains the orphan a failing run leaves behind, so only the assertion+ // above reports.+ clock.tick(20);+ } finally {+ clock.restore();+ }+ });++ test("fires with the latest same-identity object, not the arming one", async function (assert) {+ const seen: { id: number; tag: string }[] = [];+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ identity: (target: { id: number; tag: string }) => target.id,+ onDwell: (target: { id: number; tag: string }) => seen.push(target),+ });++ dwell.update({ id: 1, tag: "armed" });+ dwell.update({ id: 1, tag: "fresh" });+ await settled();++ assert.strictEqual(seen.length, 1, "fires once");+ assert.strictEqual(seen[0]?.tag, "fresh", "with the latest object");+ });++ test("a custom identity dedups fresh per-report objects onto one dwell", function (assert) {+ const clock = sinon.useFakeTimers({+ now: Date.now(),+ shouldAdvanceTime: false,+ });++ try {+ const element = { name: "shared element" };+ const seen: { element: object }[] = [];+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ identity: (target: { element: object }) => target.element,+ onDwell: (target: { element: object }) => seen.push(target),+ });++ dwell.update({ element });+ clock.tick(6);+ dwell.update({ element });+ clock.tick(6);++ // Past the collapsed 10ms deadline: fresh wrapper objects sharing one+ // identity kept the original timer rather than restarting it.+ assert.strictEqual(seen.length, 1, "fires exactly once");+ assert.strictEqual(seen[0]?.element, element, "for the shared identity");+ } finally {+ clock.restore();+ }+ });++ test("the default identity is the target reference itself", function (assert) {+ const clock = sinon.useFakeTimers({+ now: Date.now(),+ shouldAdvanceTime: false,+ });++ try {+ const target = { label: "candidate" };+ const seen: object[] = [];+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ onDwell: (reported: object) => seen.push(reported),+ });++ dwell.update(target);+ clock.tick(6);+ dwell.update(target);+ clock.tick(6);++ // Past the collapsed 10ms deadline: the repeated reference kept the+ // original timer, so reference equality is the key.+ assert.deepEqual(seen, [target], "one identity, one fire");+ } finally {+ clock.restore();+ }+ });++ test("onDwell may reset and re-arm the same identity reentrantly", async function (assert) {+ const seen: string[] = [];+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ onDwell: (target: string) => {+ seen.push(target);+ if (seen.length === 1) {+ dwell.reset();+ dwell.update(target);+ }+ },+ });++ dwell.update("candidate");+ await settled();+ assert.deepEqual(+ seen,+ ["candidate", "candidate"],+ "the reentrant re-arm fired a second dwell"+ );+ });++ test("a throwing onDwell leaves the identity latched until reset", async function (assert) {+ const caught: unknown[] = [];+ setupOnerror((error: unknown) => caught.push(error));++ try {+ const seen: string[] = [];+ let throwOnce = true;+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ onDwell: (target: string) => {+ if (throwOnce) {+ throwOnce = false;+ throw new Error("consumer failure");+ }+ seen.push(target);+ },+ });++ dwell.update("candidate");+ await settled();+ assert.strictEqual(caught.length, 1, "the throw surfaced via onerror");++ dwell.update("candidate");+ await settled();+ assert.deepEqual(seen, [], "the latched identity did not re-fire");++ dwell.reset();+ dwell.update("candidate");+ await settled();+ assert.deepEqual(seen, ["candidate"], "reset() unlatches it");+ } finally {+ resetOnerror();+ }+ });++ test("an identity function returning NaN is a stable key", function (assert) {+ const clock = sinon.useFakeTimers({+ now: Date.now(),+ shouldAdvanceTime: false,+ });++ try {+ const seen: object[] = [];+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ identity: () => NaN,+ onDwell: (target: object) => seen.push(target),+ });++ dwell.update({ frame: 1 });+ clock.tick(6);+ dwell.update({ frame: 2 });+ clock.tick(6);++ // 12ms is past the collapsed 10ms deadline; a comparison for which NaN+ // is not equal to itself would have restarted the timer and need 16ms.+ assert.strictEqual(+ seen.length,+ 1,+ "NaN compares equal to itself as a key"+ );+ } finally {+ clock.restore();+ }+ });++ test("an identity function returning null is a real key, and null reports never reach it", async function (assert) {+ const seen: object[] = [];+ const identityArgs: object[] = [];+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ identity: (target: object) => {+ identityArgs.push(target);+ return null;+ },+ onDwell: (target: object) => seen.push(target),+ });++ dwell.update({ frame: 1 });+ dwell.update({ frame: 2 });+ dwell.update(null);+ await settled();++ assert.deepEqual(seen, [], "the null report cancelled the dwell");+ assert.strictEqual(+ identityArgs.length,+ 2,+ "identity saw only the non-null reports"+ );++ dwell.update({ frame: 3 });+ await settled();+ assert.strictEqual(seen.length, 1, "the null key re-arms after clearing");+ });++ test("an identity function returning undefined is a real key, not a fallback", function (assert) {+ const clock = sinon.useFakeTimers({+ now: Date.now(),+ shouldAdvanceTime: false,+ });++ try {+ const seen: object[] = [];+ const dwell = createDragDwell({+ destroyable: parent,+ delay: 300,+ identity: () => undefined,+ onDwell: (target: object) => seen.push(target),+ });++ dwell.update({ frame: 1 });+ clock.tick(6);+ dwell.update({ frame: 2 });+ clock.tick(6);++ // An implementation that fell back to the fresh target object whenever+ // identity returned undefined would have restarted the timer at 6ms and+ // still be pending here at 12ms.+ assert.strictEqual(seen.length, 1, "the undefined key held the dwell");+ } finally {+ clock.restore();+ }+ });+});diff --git a/frontend/discourse/type-tests/ui-kit/create-drag-dwell-test.ts b/frontend/discourse/type-tests/ui-kit/create-drag-dwell-test.tsnew file mode 100644index 00000000000..847a40dafa5--- /dev/null+++ b/frontend/discourse/type-tests/ui-kit/create-drag-dwell-test.ts@@ -0,0 +1,82 @@+import { expectTypeOf } from "expect-type";+import {+ createDragDwell,+ type DragDwell,+ type DragDwellOptions,+} from "discourse/ui-kit/modifiers/d-drag-dwell";++const destroyable = {};++/* Positive: Target infers from onDwell's parameter without an explicit type+ argument. */+const inferred = createDragDwell({+ destroyable,+ delay: 300,+ onDwell: (target: HTMLElement) => target.focus(),+});+expectTypeOf(inferred).toEqualTypeOf<DragDwell<HTMLElement>>();+expectTypeOf(inferred).not.toBeAny();+expectTypeOf(inferred.update).parameter(0).toEqualTypeOf<HTMLElement | null>();+expectTypeOf(inferred.reset).toEqualTypeOf<() => void>();++/* Positive: identity's parameter matches Target and its return is an+ unconstrained key. */+const keyed = createDragDwell({+ destroyable,+ delay: 300,+ identity: (target: { element: HTMLElement }) => target.element,+ onDwell: (target: { element: HTMLElement }) => target.element.focus(),+});+expectTypeOf(keyed).toEqualTypeOf<DragDwell<{ element: HTMLElement }>>();++/* Positive: identity may return null/undefined as a legitimate key. */+createDragDwell({+ destroyable,+ delay: 300,+ identity: (): undefined => undefined,+ onDwell: (target: object) => target,+});+createDragDwell({+ destroyable,+ delay: 300,+ identity: (): null => null,+ onDwell: (target: object) => target,+});++expectTypeOf<DragDwellOptions<string>["identity"]>().toEqualTypeOf<+ ((target: string) => unknown) | undefined+>();++/* Positive: delay is optional and defaults. */+expectTypeOf(+ createDragDwell({ destroyable, onDwell: (target: string) => target })+).toEqualTypeOf<DragDwell<string>>();++/* Negatives. The repo tsconfig is not strict, so only arity, missing+ required properties, excess properties, and wrong primitives reliably+ error — nullability-based negatives would not fire. */++// @ts-expect-error — onDwell is required+createDragDwell({ destroyable, delay: 300 });++// @ts-expect-error — destroyable is required+createDragDwell({ delay: 300, onDwell: (target: string) => target });++createDragDwell({+ destroyable,+ delay: 300,+ onDwell: (target: string) => target,+ // @ts-expect-error — unknown options are rejected+ eagerness: "high",+});++// @ts-expect-error — delay is a number of milliseconds+createDragDwell({ destroyable, delay: "300", onDwell: (t: string) => t });++const stringDwell = createDragDwell({+ destroyable,+ delay: 300,+ onDwell: (target: string) => target,+});+// @ts-expect-error — update only accepts the inferred Target or null+stringDwell.update(42);diff --git a/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-external-errors-test.gts b/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-external-errors-test.gtsindex 571fbb3d3ed..53bf0f45776 100644--- a/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-external-errors-test.gts+++ b/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-external-errors-test.gts@@ -25,7 +25,7 @@ const Negatives = <template><div {{dDragAndDropAutoScroll target="document"}}></div>{{! @glint-expect-error - auto-scroll filters external drags by kind }}- <div {{dDragAndDropAutoScroll accepts="images"}}></div>+ <div {{dDragAndDropAutoScroll externalKinds="images"}}></div>{{! @glint-expect-error - the element and external targets report different payloads }}<li {{dDragAndDropTarget accepts="link" onDrop=onExternalDrop}}></li>diff --git a/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-external-test.gts b/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-external-test.gtsindex 75f00a79927..f224edbf3a9 100644--- a/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-external-test.gts+++ b/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-external-test.gts@@ -49,7 +49,7 @@ const Positives = <template>{{! External auto-scroll is a separate opt-in keyed by kind, not drag type }}<div- {{dDragAndDropAutoScroll types="card" accepts=(array "urls" "files")}}+ {{dDragAndDropAutoScroll types="card" externalKinds=(array "urls" "files")}}></div></template>;diff --git a/frontend/discourse/type-tests/ui-kit/d-drag-dwell-errors-test.gts b/frontend/discourse/type-tests/ui-kit/d-drag-dwell-errors-test.gtsnew file mode 100644index 00000000000..0a302bf7efe--- /dev/null+++ b/frontend/discourse/type-tests/ui-kit/d-drag-dwell-errors-test.gts@@ -0,0 +1,26 @@+// Every invocation below MUST fail to compile. Negatives are quarantined+// here so a @glint-expect-error cannot mask a broken positive declaration.+import dDragDwell, {+ type DragDwellEvent,+} from "discourse/ui-kit/modifiers/d-drag-dwell";++declare function open(event: DragDwellEvent): void;++const Negatives = <template>+ {{! @glint-expect-error - onDwell is required }}+ <div {{dDragDwell types="card"}}></div>++ {{! @glint-expect-error - delay is a number of milliseconds }}+ <div {{dDragDwell types="card" delay="500" onDwell=open}}></div>++ {{! @glint-expect-error - externalKinds is the closed external-kind vocabulary }}+ <div {{dDragDwell externalKinds="images" onDwell=open}}></div>++ {{! @glint-expect-error - unknown args are rejected }}+ <div {{dDragDwell types="card" eagerness="high" onDwell=open}}></div>++ {{! @glint-expect-error - position is drop-target vocabulary, not dwell }}+ <div {{dDragDwell types="card" position="inside" onDwell=open}}></div>+</template>;++export default Negatives;diff --git a/frontend/discourse/type-tests/ui-kit/d-drag-dwell-test.gts b/frontend/discourse/type-tests/ui-kit/d-drag-dwell-test.gtsnew file mode 100644index 00000000000..d87611d0f1e--- /dev/null+++ b/frontend/discourse/type-tests/ui-kit/d-drag-dwell-test.gts@@ -0,0 +1,73 @@+// Keep this file free of @glint-expect-error directives so broken positive+// invocations cannot be masked by a negative assertion.+import { array } from "@ember/helper";+import { expectTypeOf } from "expect-type";+import type { ExternalDragPayload } from "discourse/lib/-internals/drag-and-drop/external-vocabulary";+import type { NormalizedDragSource } from "discourse/lib/-internals/drag-and-drop/vocabulary";+import dDragDwell, {+ type DragDwellEndEvent,+ type DragDwellEvent,+ type DragDwellFeedback,+ type DragDwellSource,+} from "discourse/ui-kit/modifiers/d-drag-dwell";++declare function open(event: DragDwellEvent): void;+declare function close(event: DragDwellEndEvent): void;+declare function gate(feedback: DragDwellFeedback): boolean;++/* The end event refines the dwell event: same payload plus the outcome. */+expectTypeOf<DragDwellEndEvent>().toExtend<DragDwellEvent>();+expectTypeOf<DragDwellEndEvent["reason"]>().toEqualTypeOf<+ "left" | "drag-ended"+>();++/* The exported source alias is exactly what every event's `source` can be. */+expectTypeOf<DragDwellEvent["source"]>().toEqualTypeOf<DragDwellSource>();++/* `family` discriminates: checking it narrows `source` to that family's+ payload, on the event, the feedback, and the end event alike. */+declare const event: DragDwellEvent;+if (event.family === "external") {+ expectTypeOf(event.source).toEqualTypeOf<ExternalDragPayload>();+} else {+ expectTypeOf(event.source).toEqualTypeOf<NormalizedDragSource>();+}++declare const feedback: DragDwellFeedback;+if (feedback.family === "element") {+ expectTypeOf(feedback.source).toEqualTypeOf<NormalizedDragSource>();+}++declare const end: DragDwellEndEvent;+if (end.family === "external") {+ expectTypeOf(end.source).toEqualTypeOf<ExternalDragPayload>();+}++const Positives = <template>+ {{! Minimal: one drag family and the dwell callback. }}+ <div {{dDragDwell types="card" onDwell=open}}></div>++ {{! Maximal: every named arg. }}+ <div+ {{dDragDwell+ types="card"+ externalKinds="text"+ delay=700+ canDwell=gate+ acceptsSelf=false+ onDwell=open+ onDwellEnd=close+ }}+ ></div>++ {{! Arrays for both filters. }}+ <div+ {{dDragDwell+ types=(array "card" "row")+ externalKinds=(array "text" "urls")+ onDwell=open+ }}+ ></div>+</template>;++export default Positives;diff --git a/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/drag-and-drop/reacting/dwell.gjs b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/drag-and-drop/reacting/dwell.gjsnew file mode 100644index 00000000000..a06c63fabb9--- /dev/null+++ b/plugins/styleguide/assets/javascripts/discourse/components/examples/molecules/drag-and-drop/reacting/dwell.gjs@@ -0,0 +1,113 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import DButton from "discourse/ui-kit/d-button";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";+import dDragAndDropSource from "discourse/ui-kit/modifiers/d-drag-and-drop-source";+import dDragAndDropTarget from "discourse/ui-kit/modifiers/d-drag-and-drop-target";+import dDragDwell from "discourse/ui-kit/modifiers/d-drag-dwell";+import { i18n } from "discourse-i18n";++const ROWS = [1, 2, 3];++// A plain counter rather than `guidFor`: `@ember/object/internals` is not+// resolvable from a plugin bundle.+let dwellExampleId = 0;++export default class DwellExample extends Component {+ @tracked expanded = false;+ @tracked filedCount = 0;++ folderId = `styleguide-dwell-folder-${(dwellExampleId += 1)}`;++ @action+ canDwell() {+ return !this.expanded;+ }++ @action+ openFolder() {+ this.expanded = true;+ }++ @action+ maybeCloseFolder(event) {+ // Dropping into the folder keeps it open; any other end undoes the reveal.+ if (event.fired && !event.droppedHere) {+ this.expanded = false;+ }+ }++ @action+ fileChip() {+ this.filedCount += 1;+ }++ @action+ toggleFolder() {+ this.expanded = !this.expanded;+ }++ <template>+ <div class="styleguide-drag-and-drop">+ <div+ class="styleguide-drag-and-drop__chip"+ {{dDragAndDropSource type="card"}}+ >{{i18n "styleguide.sections.drag_and_drop.drag_me"}}</div>++ <div+ class={{dConcatClass+ "styleguide-drag-and-drop__folder"+ (if this.expanded "--open")+ }}+ {{dDragAndDropTarget+ accepts="card"+ position="inside"+ onDrop=this.fileChip+ }}+ {{dDragDwell+ types="card"+ canDwell=this.canDwell+ onDwell=this.openFolder+ onDwellEnd=this.maybeCloseFolder+ }}+ >+ <DButton+ @action={{this.toggleFolder}}+ @translatedLabel={{if+ this.expanded+ (i18n "styleguide.sections.drag_and_drop.dwell_collapse")+ (i18n "styleguide.sections.drag_and_drop.dwell_expand")+ }}+ class="styleguide-drag-and-drop__folder-toggle"+ aria-expanded={{if this.expanded "true" "false"}}+ aria-controls={{if this.expanded this.folderId}}+ />++ {{#if this.expanded}}+ <div+ id={{this.folderId}}+ class="styleguide-drag-and-drop__folder-rows"+ >+ {{#each ROWS as |row|}}+ <div class="styleguide-drag-and-drop__folder-row">+ {{i18n "styleguide.sections.drag_and_drop.row" number=row}}+ </div>+ {{/each}}+ </div>+ {{/if}}++ {{! A drop can file the chip while the folder is collapsed. The count+ stays outside the reveal so that drop is visible at once. }}+ {{#if this.filedCount}}+ <div class="styleguide-drag-and-drop__folder-row">+ {{i18n+ "styleguide.sections.drag_and_drop.dwell_filed"+ count=this.filedCount+ }}+ </div>+ {{/if}}+ </div>+ </div>+ </template>+}diff --git a/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/drag-and-drop.gjs b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/drag-and-drop.gjsindex e9e46f5b710..8a14249b90b 100644--- a/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/drag-and-drop.gjs+++ b/plugins/styleguide/assets/javascripts/discourse/components/sections/molecules/drag-and-drop.gjs@@ -20,6 +20,8 @@ import ExternalAxisExample from "../../examples/molecules/drag-and-drop/outside/import externalaxisSource from "../../examples/molecules/drag-and-drop/outside/external-axis?source=file";import AutoScrollExample from "../../examples/molecules/drag-and-drop/reacting/auto-scroll";import autoscrollSource from "../../examples/molecules/drag-and-drop/reacting/auto-scroll?source=file";+import DwellExample from "../../examples/molecules/drag-and-drop/reacting/dwell";+import dwellSource from "../../examples/molecules/drag-and-drop/reacting/dwell?source=file";import MonitorExample from "../../examples/molecules/drag-and-drop/reacting/monitor";import monitorSource from "../../examples/molecules/drag-and-drop/reacting/monitor?source=file";import ServiceExample from "../../examples/molecules/drag-and-drop/reacting/service";@@ -309,6 +311,19 @@ export default class DragAndDrop extends Component {><AutoScrollExample /></Example>++ <Example+ @title={{i18n "styleguide.sections.drag_and_drop.dwell_title"}}+ @kind="modifier"+ @description={{i18n+ "styleguide.sections.drag_and_drop.dwell_description"+ }}+ @tryThis={{i18n "styleguide.sections.drag_and_drop.dwell_try_this"}}+ @note={{i18n "styleguide.sections.drag_and_drop.dwell_note"}}+ @code={{dwellSource}}+ >+ <DwellExample />+ </Example></Group><Group @id="resize" as |Example|>diff --git a/plugins/styleguide/assets/stylesheets/styleguide.scss b/plugins/styleguide/assets/stylesheets/styleguide.scssindex 585337d11c7..96fb5e934d2 100644--- a/plugins/styleguide/assets/stylesheets/styleguide.scss+++ b/plugins/styleguide/assets/stylesheets/styleguide.scss@@ -555,6 +555,34 @@background: var(--token-color-surface-hovered);}+ &__folder {+ display: flex;+ flex-direction: column;+ gap: var(--space-2);+ padding: var(--space-3);+ border: 1px dashed var(--primary-medium);++ &.--open {+ border-style: solid;+ background: var(--tertiary-very-low);+ }+ }++ &__folder-toggle {+ align-self: flex-start;+ }++ &__folder-rows {+ display: flex;+ flex-direction: column;+ gap: var(--space-1);+ }++ &__folder-row {+ padding: var(--space-2) var(--space-3);+ background: var(--token-color-surface-hovered);+ }+&__panes {display: flex;align-items: stretch;diff --git a/plugins/styleguide/config/locales/client.en.yml b/plugins/styleguide/config/locales/client.en.ymlindex 987be76b48d..d7e4fc523f2 100644--- a/plugins/styleguide/config/locales/client.en.yml+++ b/plugins/styleguide/config/locales/client.en.yml@@ -169,6 +169,15 @@ en:auto_scroll_title: "Scrolling while dragging"auto_scroll_description: "`dDragAndDropAutoScroll` scrolls a container while a drag hovers near its edge, so a row below the fold stays reachable."auto_scroll_try_this: "Drag the chip to the bottom edge of the list and hold it there."+ dwell_title: "Dwelling to reveal"+ dwell_description: "`dDragDwell` fires a callback once a drag has hovered its element for a delay, without making the element a drop target."+ dwell_try_this: "Drag the chip over the collapsed folder and hold it there until it opens, then drop it inside. Or drag away and watch it close again."+ dwell_note: "The dwell fires once per hover and opens the folder. Dropping the chip inside keeps it open; dragging away or letting the drag end closes a folder the dwell opened."+ dwell_filed:+ one: "Filed %{count} chip"+ other: "Filed %{count} chips"+ dwell_expand: "Show rows"+ dwell_collapse: "Hide rows"row: "Row %{number}"separator_title: "Resizing between regions"separator_description: "`DResizeSeparator` is the component to reach for first. It wraps the `dResizeEdge` modifier and adds the separator contract: the role, one tab stop, and live announced values."diff --git a/plugins/styleguide/spec/system/smoke_test_spec.rb b/plugins/styleguide/spec/system/smoke_test_spec.rbindex 6c98122c3c5..b520a7166a9 100644--- a/plugins/styleguide/spec/system/smoke_test_spec.rb+++ b/plugins/styleguide/spec/system/smoke_test_spec.rb@@ -145,14 +145,14 @@ RSpec.describe "Styleguide Smoke Test" do"sources" => ".styleguide-drag-and-drop__grip","targets" => ".styleguide-drag-and-drop__zone.--inner","outside" => ".styleguide-drag-and-drop__zone",- "reacting" => ".styleguide-drag-and-drop__panel",+ "reacting" => %w[.styleguide-drag-and-drop__panel .styleguide-drag-and-drop__folder],"resize" => ".styleguide-drag-and-drop__resizable","gestures" => ".styleguide-drag-and-drop__knob",- }.each do |group, selector|+ }.each do |group, selectors|visit "/styleguide/molecules/drag-and-drop?group=#{group}"expect(page).to have_css("[data-test-styleguide-group='#{group}']")- expect(page).to have_css(selector)+ Array(selectors).each { |selector| expect(page).to have_css(selector) }endend@@ -163,6 +163,25 @@ RSpec.describe "Styleguide Smoke Test" doexpect(page).to have_css(".styleguide-example__kind", count: 3)end+ it "renders the dwell example collapsed and open" do+ visit "/styleguide/molecules/drag-and-drop?group=reacting"++ expect(page).to have_css(".styleguide-drag-and-drop__folder")+ expect(page).to have_no_css(".styleguide-drag-and-drop__folder.--open")+ if ENV["TAKE_SCREENSHOTS"] == "1"+ page.scroll_to(find(".styleguide-drag-and-drop__folder"), align: :center)+ end+ screenshot_marker(label: "styleguide-drag-and-drop-dwell")++ find(".styleguide-drag-and-drop__folder-toggle").click+ expect(page).to have_css(".styleguide-drag-and-drop__folder.--open")+ expect(page).to have_css(".styleguide-drag-and-drop__folder-row", count: 3)+ if ENV["TAKE_SCREENSHOTS"] == "1"+ page.scroll_to(find(".styleguide-drag-and-drop__folder"), align: :center)+ end+ screenshot_marker(label: "styleguide-drag-and-drop-dwell-open")+ end+it "renders the index page correctly on a site with no default color schemes" doSiteSetting.default_theme_id = Fabricate(:theme).idvisit "/styleguide"