Skip to content

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

DEV: Add shared drag-and-drop primitives for element and external drags (#42597)

Sérgio Saquetimd5017b21e27f
diff --git a/app/assets/stylesheets/common/ui-kit/_index.scss b/app/assets/stylesheets/common/ui-kit/_index.scss
index 75c6e665b28..408240ad4ba 100644
--- a/app/assets/stylesheets/common/ui-kit/_index.scss
+++ b/app/assets/stylesheets/common/ui-kit/_index.scss
@@ -5,3 +5,4 @@
@import "d-pointer-drag";
@import "d-resize-separator";
+@import "d-drag-and-drop";
diff --git a/app/assets/stylesheets/common/ui-kit/d-drag-and-drop.scss b/app/assets/stylesheets/common/ui-kit/d-drag-and-drop.scss
new file mode 100644
index 00000000000..a0b3fc0f3dc
--- /dev/null
+++ b/app/assets/stylesheets/common/ui-kit/d-drag-and-drop.scss
@@ -0,0 +1,98 @@
+/* Full-strength `--tertiary`, not `--token-color-border-accent`: that tint
+ misses the 3:1 contrast a non-text UI component needs on a light surface. */
+
+:root {
+ --d-drag-indicator-color: var(--tertiary);
+}
+
+@mixin d-drag-line($axis) {
+ content: "";
+ position: absolute;
+ background: var(--d-drag-indicator-color);
+ pointer-events: none;
+
+ @if $axis == horizontal {
+ left: 0;
+ right: 0;
+ height: 2px;
+ } @else {
+ top: 0;
+ bottom: 0;
+ width: 2px;
+ }
+}
+
+@mixin d-drag-outline {
+ outline: 2px solid var(--d-drag-indicator-color);
+ outline-offset: -2px;
+}
+
+[data-drag-source] {
+ &.--dragging {
+ opacity: 0.5;
+ }
+}
+
+/* `:where()` so a target that positions itself keeps its own value; the line's
+ pseudo-element only needs some containing block. */
+
+:where(
+ [data-drop-target].--drag-above,
+ [data-drop-target].--drag-below,
+ [data-drop-target].--drag-left,
+ [data-drop-target].--drag-right,
+ [data-drop-target-external].--drag-above,
+ [data-drop-target-external].--drag-below,
+ [data-drop-target-external].--drag-left,
+ [data-drop-target-external].--drag-right
+) {
+ position: relative;
+}
+
+[data-drop-target],
+[data-drop-target-external] {
+ &.--drag-above {
+ &::before {
+ @include d-drag-line(horizontal);
+ top: -1px;
+ }
+ }
+
+ &.--drag-below {
+ &::after {
+ @include d-drag-line(horizontal);
+ bottom: -1px;
+ }
+ }
+
+ /* `--drag-left` / `--drag-right` name the physical side under the pointer, so
+ the RTL flip must leave them alone. */
+
+ &.--drag-left {
+ &::before {
+ @include d-drag-line(vertical);
+
+ /*! rtl:ignore */
+ left: -1px;
+ }
+ }
+
+ &.--drag-right {
+ &::after {
+ @include d-drag-line(vertical);
+
+ /*! rtl:ignore */
+ right: -1px;
+ }
+ }
+
+ &.--drag-inside {
+ @include d-drag-outline;
+ }
+}
+
+[data-drop-target-external] {
+ &.--drag-over-external {
+ @include d-drag-outline;
+ }
+}
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 7825e34ef06..37f11bc004b 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -437,6 +437,7 @@ en:
broken_transformer_alert: "There was an error. Your site may not work properly."
broken_block_alert: "A block configuration error was detected. Check browser console for details."
broken_block_factory_alert: "A block failed to load. Some UI elements may not display correctly."
+ broken_drag_and_drop_alert: "A drag and drop handler failed. The action may not have completed."
on_before_category_types_change_error: "An error occurred while changing the category types. Check the browser console for more information."
critical_deprecation:
diff --git a/frontend/discourse/app/lib/-internals/drag-and-drop/consumer-may-throw.ts b/frontend/discourse/app/lib/-internals/drag-and-drop/consumer-may-throw.ts
new file mode 100644
index 00000000000..290d2b5dd3d
--- /dev/null
+++ b/frontend/discourse/app/lib/-internals/drag-and-drop/consumer-may-throw.ts
@@ -0,0 +1,33 @@
+import { next } from "@ember/runloop";
+import { isTesting } from "discourse/lib/environment";
+import { reportClientError } from "discourse/lib/report-client-error";
+
+/**
+ * Calls a consumer callback that is allowed to throw, so nothing it throws
+ * reaches the caller.
+ *
+ * The library calls consumer callbacks from inside its event dispatch, with
+ * the end-of-drag cleanup on the next statement unguarded. An exception that
+ * escapes skips that cleanup.
+ *
+ * The error is reported through `reportClientError`. Under test it is also
+ * rethrown asynchronously, so the test it happened in still fails.
+ *
+ * @param run - The consumer callback.
+ * @param fallback - Returned when the callback throws. Give a gate its
+ * conservative answer.
+ */
+export function consumerMayThrow<T>(run: () => T, fallback?: T): T | undefined {
+ try {
+ return run();
+ } catch (error) {
+ reportClientError(error, "broken_drag_and_drop_alert");
+ if (isTesting()) {
+ // Rethrown later so the library's cleanup on the next statement runs.
+ next(() => {
+ throw error;
+ });
+ }
+ return fallback;
+ }
+}
diff --git a/frontend/discourse/app/lib/-internals/drag-and-drop/drop-target-kernel.ts b/frontend/discourse/app/lib/-internals/drag-and-drop/drop-target-kernel.ts
new file mode 100644
index 00000000000..794caed3064
--- /dev/null
+++ b/frontend/discourse/app/lib/-internals/drag-and-drop/drop-target-kernel.ts
@@ -0,0 +1,443 @@
+import type {
+ CleanupFn,
+ DragLocationHistory,
+ Input,
+} from "@atlaskit/pragmatic-drag-and-drop/types";
+import { consumerMayThrow } from "discourse/lib/-internals/drag-and-drop/consumer-may-throw";
+import type { Axis } from "discourse/lib/geometry";
+
+/** The pointer position as the underlying library reports it. */
+export type DragInput = Input;
+
+/** The drag's initial, previous and current locations. */
+export type DragLocation = DragLocationHistory;
+
+/** Where a drop would land relative to its target. */
+export type DropPosition = "before" | "after" | "inside";
+
+/** The cursor feedback the browser shows for a drop. */
+export type DropEffect = "copy" | "link" | "move";
+
+/** How a target decides where a drop would land. */
+export interface DropPositionOptions {
+ /** A fixed position, which wins over midpoint math. */
+ position?: DropPosition;
+
+ /** The axis whose midpoint is measured. Defaults to `"vertical"`. */
+ axis?: Axis;
+}
+
+/** What a synchronous consumer gate is asked about. */
+export interface DropTargetKernelFeedback<Source> {
+ /** The consumer-facing drag source. */
+ source: Source;
+
+ /** The pointer position. */
+ input: Input;
+
+ /** The registered target element. */
+ element: Element;
+}
+
+/** What a consumer lifecycle callback is told. */
+export interface DropTargetKernelEvent<Source> {
+ /** The consumer-facing drag source. */
+ source: Source;
+
+ /** Where the drop would land, or `null` when no position applies. */
+ position: DropPosition | null;
+
+ /** The drag's location history. */
+ location: DragLocationHistory;
+
+ /** The registered target element. */
+ element: Element;
+}
+
+/** Consumer callbacks and display options shared by every drop target. */
+export interface DropTargetKernelArgs<Source> extends DropPositionOptions {
+ /**
+ * Synchronous gate, asked while the drag hovers. Returning `false` takes
+ * this target out of the running, leaving the drop to an ancestor target.
+ * It is not asked again when the drag is released.
+ */
+ canDrop?: (feedback: DropTargetKernelFeedback<Source>) => boolean | void;
+
+ /** Determines the cursor feedback browsers show during the drag. */
+ getDropEffect?: (feedback: DropTargetKernelFeedback<Source>) => DropEffect;
+
+ /** Metadata attached to the drag's record of this target under `.data`. */
+ getData?: () => object;
+
+ /**
+ * Whether the target stays current after the pointer leaves it. It lets go
+ * when its parent changes, another target takes its depth, or the gate
+ * refuses it.
+ */
+ getIsSticky?: () => boolean;
+
+ /** `false` suppresses the target's indicator. Defaults to `true`. */
+ indicator?: boolean;
+
+ /**
+ * Called when this target becomes the deepest accepted target. Usually the
+ * pointer entered it, but it also fires when a nested target covering it
+ * goes away, without the pointer moving.
+ */
+ onDragEnter?: (event: DropTargetKernelEvent<Source>) => void;
+
+ /**
+ * Called repeatedly while this target is the deepest accepted target,
+ * throttled by the underlying library.
+ */
+ onDrag?: (event: DropTargetKernelEvent<Source>) => void;
+
+ /**
+ * Called when this target stops being the deepest accepted target: the
+ * pointer left, a nested target took over, or the gate refused it.
+ * `position` is `null`.
+ *
+ * A drop or teardown ends the drag without a leave, so consumers must also
+ * release their drag-time state when they are destroyed.
+ */
+ onDragLeave?: (event: DropTargetKernelEvent<Source>) => void;
+
+ /** Called when the drag is released on this target. */
+ onDrop?: (event: DropTargetKernelEvent<Source>) => void;
+}
+
+type LibraryFeedbackArgs<Payload> = {
+ input: Input;
+ source: Payload;
+ element: Element;
+};
+
+type LibraryEventArgs<Payload> = {
+ source: Payload;
+ location: DragLocationHistory;
+};
+
+/**
+ * What the kernel hands an adapter's `register` function, shaped so the
+ * library's registrars accept it without a cast.
+ */
+export type DropTargetRegistrationArgs<Payload> = {
+ element: Element;
+ canDrop: (args: LibraryFeedbackArgs<Payload>) => boolean;
+ getData: (
+ args: LibraryFeedbackArgs<Payload>
+ ) => Record<string | symbol, unknown>;
+ getDropEffect: (args: LibraryFeedbackArgs<Payload>) => DropEffect | undefined;
+ getIsSticky: (args: LibraryFeedbackArgs<Payload>) => boolean;
+ onDropTargetChange: (args: LibraryEventArgs<Payload>) => void;
+ onDragEnter: (args: LibraryEventArgs<Payload>) => void;
+ onDrag: (args: LibraryEventArgs<Payload>) => void;
+ onDragLeave: (args: LibraryEventArgs<Payload>) => void;
+ onDrop: (args: LibraryEventArgs<Payload>) => void;
+};
+
+/** Adapter-specific configuration for the shared drop-target state machine. */
+export interface DropTargetKernelConfig<Payload, Source> {
+ /** The element to register as a drop target. */
+ element: Element;
+
+ /** The data attribute stamped for the lifetime of the registration. */
+ attribute: "data-drop-target" | "data-drop-target-external";
+
+ /** Registers the callbacks with the adapter. */
+ register: (args: DropTargetRegistrationArgs<Payload>) => CleanupFn;
+
+ /** Converts the adapter payload to the consumer-facing source. */
+ decorateSource: (payload: Payload) => Source;
+
+ /** Applies adapter-specific filters before the consumer's gate. */
+ accepts: (payload: Payload) => boolean;
+
+ /** Whether this adapter resolves a position for the current arguments. */
+ resolvesPosition?: (args: DropTargetKernelArgs<Source>) => boolean;
+
+ /** The hover class used when this adapter resolves no position. */
+ positionlessClass?: string;
+
+ /** Optional adapter teardown run after the shared cleanup. */
+ onCleanup?: () => void;
+
+ /** Returns the consumer's latest callbacks and display options. */
+ getArgs: () => DropTargetKernelArgs<Source>;
+}
+
+const POSITION_CLASSES = Object.freeze({
+ before: { vertical: "--drag-above", horizontal: "--drag-left" },
+ after: { vertical: "--drag-below", horizontal: "--drag-right" },
+ inside: { vertical: "--drag-inside", horizontal: "--drag-inside" },
+});
+
+/**
+ * Resolves a fixed position, or the side of the element's midpoint the pointer
+ * is on, mapped through the target's writing direction.
+ */
+function resolveDropPosition(
+ element: Element,
+ input: Input,
+ { position, axis = "vertical" }: DropPositionOptions,
+ rtl: boolean
+): DropPosition {
+ if (position) {
+ return position;
+ }
+ const rect = element.getBoundingClientRect();
+ if (axis === "horizontal") {
+ const isPhysicalLeft = input.clientX < rect.left + rect.width / 2;
+ return isPhysicalLeft === rtl ? "after" : "before";
+ }
+ return input.clientY < rect.top + rect.height / 2 ? "before" : "after";
+}
+
+/** Positional feedback that keeps at most one indicator class active. */
+function createPositionIndicator(element: Element, positionlessClass?: string) {
+ let activeClass: string | null = null;
+
+ return {
+ show(position: DropPosition | null, axis: Axis, rtl: boolean) {
+ if (!position) {
+ if (activeClass) {
+ element.classList.remove(activeClass);
+ activeClass = null;
+ }
+ if (positionlessClass) {
+ element.classList.add(positionlessClass);
+ }
+ return;
+ }
+
+ if (positionlessClass) {
+ element.classList.remove(positionlessClass);
+ }
+ const physicalPosition =
+ axis === "horizontal" && rtl && position !== "inside"
+ ? position === "before"
+ ? "after"
+ : "before"
+ : position;
+ const className = POSITION_CLASSES[physicalPosition][axis];
+ if (!className || activeClass === className) {
+ return;
+ }
+ if (activeClass) {
+ element.classList.remove(activeClass);
+ }
+ element.classList.add(className);
+ activeClass = className;
+ },
+ clear() {
+ if (activeClass) {
+ element.classList.remove(activeClass);
+ activeClass = null;
+ }
+ if (positionlessClass) {
+ element.classList.remove(positionlessClass);
+ }
+ },
+ };
+}
+
+function isDeepestTarget(location: DragLocationHistory, element: Element) {
+ return location.current.dropTargets[0]?.element === element;
+}
+
+/**
+ * Pairs consumer-facing enter and leave state. The writing direction is
+ * sampled once per hover and dropped when the hover ends.
+ */
+function createEnterLeavePairing(element: Element) {
+ let entered = false;
+ let rtl: boolean | null = null;
+
+ return {
+ enter() {
+ if (entered) {
+ return false;
+ }
+ entered = true;
+ return true;
+ },
+ isRtl() {
+ return (rtl ??= getComputedStyle(element).direction === "rtl");
+ },
+ leave(fire: () => void) {
+ rtl = null;
+ if (!entered) {
+ return;
+ }
+ entered = false;
+ fire();
+ },
+ reset() {
+ entered = false;
+ rtl = null;
+ },
+ };
+}
+
+/**
+ * Registers the shared drop-target state machine through a concrete adapter.
+ *
+ * @param config - Adapter hooks and the latest consumer arguments.
+ * @returns Cleanup for the adapter registration and its target state.
+ */
+export function registerDropTargetKernel<Payload, Source>({
+ element,
+ attribute,
+ register,
+ decorateSource,
+ accepts,
+ resolvesPosition = () => true,
+ positionlessClass,
+ onCleanup,
+ getArgs,
+}: DropTargetKernelConfig<Payload, Source>): CleanupFn {
+ const pairing = createEnterLeavePairing(element);
+ const indicator = createPositionIndicator(element, positionlessClass);
+
+ const positionFor = (
+ args: DropTargetKernelArgs<Source>,
+ input: Input,
+ rtl: boolean
+ ) =>
+ resolvesPosition(args)
+ ? resolveDropPosition(element, input, args, rtl)
+ : null;
+
+ const passesGate = (source: Payload, input: Input) => {
+ if (!accepts(source)) {
+ return false;
+ }
+ const callback = getArgs().canDrop;
+ if (!callback) {
+ return true;
+ }
+ return consumerMayThrow(
+ () =>
+ callback({ source: decorateSource(source), input, element }) !== false,
+ false
+ );
+ };
+
+ const reportLeave = (source: Payload, location: DragLocationHistory) =>
+ pairing.leave(() =>
+ consumerMayThrow(() =>
+ getArgs().onDragLeave?.({
+ source: decorateSource(source),
+ position: null,
+ location,
+ element,
+ })
+ )
+ );
+
+ const reportActive = (
+ source: Payload,
+ location: DragLocationHistory,
+ reportDrag: boolean
+ ) => {
+ if (!isDeepestTarget(location, element)) {
+ indicator.clear();
+ // The library sends no leave to an ancestor a child took over from, since
+ // the ancestor stays in the hierarchy.
+ reportLeave(source, location);
+ return;
+ }
+
+ const args = getArgs();
+ const entered = pairing.enter();
+ const rtl = pairing.isRtl();
+ const position = positionFor(args, location.current.input, rtl);
+ if (args.indicator === false) {
+ indicator.clear();
+ } else {
+ indicator.show(position, args.axis ?? "vertical", rtl);
+ }
+ // A target can become deepest on a drag update without a library enter, so
+ // the consumer's enter fires from here rather than from the enter hook.
+ if (entered) {
+ consumerMayThrow(() =>
+ args.onDragEnter?.({
+ source: decorateSource(source),
+ position,
+ location,
+ element,
+ })
+ );
+ }
+ if (reportDrag) {
+ consumerMayThrow(() =>
+ args.onDrag?.({
+ source: decorateSource(source),
+ position,
+ location,
+ element,
+ })
+ );
+ }
+ };
+
+ // The stylesheet gates the indicator classes on this attribute; a marker
+ // class would not survive a consumer rebinding `class`.
+ element.setAttribute(attribute, "");
+
+ const cleanup = register({
+ element,
+ canDrop: ({ source, input }) => passesGate(source, input),
+ getData: () =>
+ consumerMayThrow(() => getArgs().getData?.() ?? {}, {}) as Record<
+ string | symbol,
+ unknown
+ >,
+ getDropEffect: ({ source, input }) =>
+ consumerMayThrow(() =>
+ getArgs().getDropEffect?.({
+ source: decorateSource(source),
+ input,
+ element,
+ })
+ ),
+ getIsSticky: () =>
+ consumerMayThrow(() => getArgs().getIsSticky?.() === true, false),
+ onDragEnter: ({ source, location }) =>
+ reportActive(source, location, false),
+ onDropTargetChange: ({ source, location }) =>
+ reportActive(source, location, false),
+ onDrag: ({ source, location }) => reportActive(source, location, true),
+ onDragLeave: ({ source, location }) => {
+ indicator.clear();
+ reportLeave(source, location);
+ },
+ onDrop: ({ source, location }) => {
+ indicator.clear();
+ if (!isDeepestTarget(location, element)) {
+ pairing.reset();
+ return;
+ }
+ // Sampled before the reset clears it, so the drop uses the direction the
+ // hover was measured against.
+ const rtl = pairing.isRtl();
+ pairing.reset();
+ const args = getArgs();
+ consumerMayThrow(() =>
+ args.onDrop?.({
+ source: decorateSource(source),
+ position: positionFor(args, location.current.input, rtl),
+ location,
+ element,
+ })
+ );
+ },
+ });
+
+ return () => {
+ cleanup();
+ indicator.clear();
+ element.removeAttribute(attribute);
+ onCleanup?.();
+ };
+}
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.ts
new file mode 100644
index 00000000000..48c622e1175
--- /dev/null
+++ b/frontend/discourse/app/lib/-internals/drag-and-drop/external-vocabulary.ts
@@ -0,0 +1,105 @@
+import type {
+ ExternalDragPayload as NativeExternalDragPayload,
+ NativeMediaType,
+} from "@atlaskit/pragmatic-drag-and-drop/adapter/external-adapter-types";
+import { containsFiles } from "@atlaskit/pragmatic-drag-and-drop/utils/contains-files";
+import { containsHTML } from "@atlaskit/pragmatic-drag-and-drop/utils/contains-html";
+import { containsText } from "@atlaskit/pragmatic-drag-and-drop/utils/contains-text";
+import { containsURLs } from "@atlaskit/pragmatic-drag-and-drop/utils/contains-ur-ls";
+import { getFiles } from "@atlaskit/pragmatic-drag-and-drop/utils/get-files";
+import { getHTML } from "@atlaskit/pragmatic-drag-and-drop/utils/get-html";
+import { getText } from "@atlaskit/pragmatic-drag-and-drop/utils/get-text";
+import { getURLs } from "@atlaskit/pragmatic-drag-and-drop/utils/get-ur-ls";
+import { makeArray } from "discourse/lib/helpers";
+
+/**
+ * The in-flight external drag, with the read helpers bound to it so consumers
+ * never reach for the underlying library themselves.
+ */
+export interface ExternalDragPayload {
+ /**
+ * Native MIME types declared by the incoming drag (e.g. `"Files"`,
+ * `"text/plain"`, `"text/uri-list"`).
+ */
+ types: NativeMediaType[];
+
+ /**
+ * The `DataTransferItem` list. Empty until the drop, so `getFiles()` returns
+ * files in `onDrop` alone. Use `types` or `containsFiles()` while hovering.
+ */
+ items: DataTransferItem[];
+
+ /**
+ * Reads the string payload for a MIME type. Returns `null` while hovering,
+ * and at the drop when the type is absent.
+ */
+ getStringData: (mediaType: string) => string | null;
+
+ containsFiles: () => boolean;
+ getFiles: () => File[];
+ containsHTML: () => boolean;
+ getHTML: () => string | null;
+ containsText: () => boolean;
+ getText: () => string | null;
+ containsURLs: () => boolean;
+ getURLs: () => string[];
+}
+
+/**
+ * The kinds `accepts` / `acceptsExternal()` understand, each mapped to its
+ * payload predicate.
+ */
+const EXTERNAL_KIND_PREDICATES = Object.freeze({
+ files: containsFiles,
+ html: containsHTML,
+ text: containsText,
+ urls: containsURLs,
+});
+
+/** A kind of external payload, as named by `accepts` / `acceptsExternal()`. */
+export type ExternalDragKind = keyof typeof EXTERNAL_KIND_PREDICATES;
+
+/**
+ * Binds the read helpers to the library's raw external payload.
+ *
+ * @param source - The raw payload the library reports.
+ */
+export function decorateExternalSource(
+ source: NativeExternalDragPayload
+): ExternalDragPayload {
+ return {
+ types: source.types,
+ items: source.items,
+ getStringData: (mediaType) => source.getStringData(mediaType),
+ containsFiles: () => containsFiles({ source }),
+ getFiles: () => getFiles({ source }),
+ containsHTML: () => containsHTML({ source }),
+ getHTML: () => getHTML({ source }),
+ containsText: () => containsText({ source }),
+ getText: () => getText({ source }),
+ containsURLs: () => containsURLs({ source }),
+ getURLs: () => getURLs({ source }),
+ };
+}
+
+/**
+ * Whether an incoming external drag is one of the named kinds. An empty or
+ * missing filter matches every external drag.
+ *
+ * @param accepts - The kind filter as the consumer supplied it.
+ * @param source - The raw payload the underlying library reports.
+ */
+export function matchesExternalKind(
+ accepts: ExternalDragKind | ExternalDragKind[] | undefined,
+ source: NativeExternalDragPayload
+) {
+ const kinds = makeArray(accepts);
+ if (kinds.length === 0) {
+ return true;
+ }
+ return kinds.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/lib/-internals/drag-and-drop/vocabulary.ts b/frontend/discourse/app/lib/-internals/drag-and-drop/vocabulary.ts
new file mode 100644
index 00000000000..12a20d5e7db
--- /dev/null
+++ b/frontend/discourse/app/lib/-internals/drag-and-drop/vocabulary.ts
@@ -0,0 +1,103 @@
+import type { ElementDragPayload } from "@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter";
+import { makeArray } from "discourse/lib/helpers";
+
+/**
+ * Payload key under which a source registered through a drag handle publishes
+ * the element the handle stands for. Targets report that body as
+ * `source.element` and compare it for `acceptsSelf`.
+ */
+export const DRAG_BODY = "discourse:dragBody";
+
+/**
+ * Resolves the body an element drag represents.
+ *
+ * @param source - The payload as the underlying library carries it.
+ */
+export function dragBodyOf(source: ElementDragPayload): HTMLElement {
+ return (
+ (source.data?.[DRAG_BODY] as HTMLElement | undefined) ?? source.element
+ );
+}
+
+/**
+ * The type a drag answers to in an `accepts` / `types` filter.
+ *
+ * @param data - A drag payload's `data`, as the underlying library carries it.
+ */
+export function dragTypeOf(data?: Record<string, unknown>) {
+ return data?.type as string | undefined;
+}
+
+/**
+ * Whether a drag's type is one the consumer asked for.
+ *
+ * @param types - One type, several, or nothing at all to match every drag.
+ * @param source - The dragged source, compared through {@link dragTypeOf}.
+ */
+export function matchesDragType(
+ types: string | string[] | undefined,
+ source: ElementDragPayload
+) {
+ const list = makeArray(types);
+ if (list.length === 0) {
+ return true;
+ }
+ return list.includes(dragTypeOf(source.data) as string);
+}
+
+/**
+ * A drag source as consumers read it: routing keys removed and the dragged
+ * body in place of the handle that carried it.
+ */
+export interface NormalizedDragSource {
+ /** The source's discriminator, or `null` when the drag carries none. */
+ type: string | null;
+
+ /** The payload the source attached to the drag. */
+ data: Record<string, unknown>;
+
+ /** The dragged element: the published body, else the registered element. */
+ element: HTMLElement;
+}
+
+/**
+ * Normalizes a payload stamped by `dDragAndDropSource`.
+ *
+ * Unlike arbitrary element drags, an owned payload always carries a string
+ * discriminator and an HTML body.
+ *
+ * @param source - The owned payload as the underlying library carries it.
+ */
+export function normalizeOwnedDragSource(source: ElementDragPayload): {
+ /** The discriminator stamped by the source. */
+ type: string;
+
+ /** The consumer payload, including its discriminator. */
+ data: Record<string, unknown>;
+
+ /** The dragged body, rather than a handle registered on its behalf. */
+ element: HTMLElement;
+} {
+ const { type, data, element } = normalizeDragSource(source);
+ return { type: type as string, data, element };
+}
+
+/**
+ * Resolves a raw payload into the shape every reader reports.
+ *
+ * @param source - The payload as the underlying library carries it.
+ */
+export function normalizeDragSource(
+ source: ElementDragPayload
+): NormalizedDragSource {
+ const data = { ...(source.data ?? {}) };
+ delete data[DRAG_BODY];
+
+ return {
+ // The library types payload values as `unknown`; owned sources always stamp
+ // a string `type`.
+ type: (data.type ?? null) as string | null,
+ data,
+ element: dragBodyOf(source),
+ };
+}
diff --git a/frontend/discourse/app/lib/geometry.ts b/frontend/discourse/app/lib/geometry.ts
new file mode 100644
index 00000000000..352e0991c15
--- /dev/null
+++ b/frontend/discourse/app/lib/geometry.ts
@@ -0,0 +1,11 @@
+/**
+ * The axis a gesture runs along: a resize, a scroll, or the midpoint a drop
+ * is measured against.
+ */
+export type Axis = "vertical" | "horizontal";
+
+/**
+ * A logical side of a box along an axis, resolved against the writing
+ * direction rather than a physical edge.
+ */
+export type Side = "start" | "end";
diff --git a/frontend/discourse/app/lib/helpers.js b/frontend/discourse/app/lib/helpers.js
deleted file mode 100644
index a80934cd165..00000000000
--- a/frontend/discourse/app/lib/helpers.js
+++ /dev/null
@@ -1,79 +0,0 @@
-import Helper from "@ember/component/helper";
-import { dasherize } from "@ember/string";
-import { trustHTML } from "@ember/template";
-import deprecated from "discourse/lib/deprecated";
-
-export function makeArray(obj) {
- if (obj === null || obj === undefined) {
- return [];
- }
- return Array.isArray(obj) ? obj : [obj];
-}
-
-export function htmlHelper(fn) {
- deprecated(
- `htmlHelper is deprecated. Use a plain function and \`htmlSafe()\` from "@ember/template" instead.`,
- { id: "discourse.html-helper" }
- );
-
- return Helper.helper(function (...args) {
- args =
- args.length > 1 ? args[0].concat({ hash: args[args.length - 1] }) : args;
- return trustHTML(fn.apply(this, args) || "");
- });
-}
-
-const _helpers = {};
-
-export function registerHelper(name, fn) {
- _helpers[name] = Helper.helper(fn);
-}
-
-export function findHelper(name) {
- return _helpers[name] || _helpers[dasherize(name)];
-}
-
-export function registerHelpers(registry) {
- Object.keys(_helpers).forEach((name) => {
- registry.register(`helper:${name}`, _helpers[name], { singleton: false });
- });
-}
-
-let _helperContext;
-export function createHelperContext(ctx) {
- _helperContext = ctx;
-}
-
-// This can be used by a helper to get the SiteSettings. Note you should not
-// be using it outside of helpers (or lib code that helpers use!)
-export function helperContext() {
- return _helperContext;
-}
-
-/**
- * Register a helper for Ember and raw-hbs. This exists for
- * legacy reasons, and should be avoided in new code. Instead, you should
- * do `export default ...` from a `helpers/*.js` file.
- */
-export function registerUnbound(name, fn) {
- deprecated(
- `[registerUnbound ${name}] registerUnbound is deprecated. Instead, you should export a default function from 'discourse/helpers/${name}.js'.`,
- { id: "discourse.register-unbound" }
- );
-
- _helpers[name] = class extends Helper {
- compute(params, args) {
- return fn(...params, args);
- }
- };
-}
-
-/**
- * Register a helper for raw-hbs only
- */
-export function registerRawHelper(name) {
- deprecated(
- `[registerRawHelper ${name}] the raw handlebars system has been removed, so calls to registerRawHelper should be removed.`,
- { id: "discourse.register-raw-helper" }
- );
-}
diff --git a/frontend/discourse/app/lib/helpers.ts b/frontend/discourse/app/lib/helpers.ts
new file mode 100644
index 00000000000..ce5b07d3685
--- /dev/null
+++ b/frontend/discourse/app/lib/helpers.ts
@@ -0,0 +1,121 @@
+import Helper from "@ember/component/helper";
+import type { RegisterOptions } from "@ember/owner";
+import { dasherize } from "@ember/string";
+import { trustHTML } from "@ember/template";
+import deprecated from "discourse/lib/deprecated";
+import type Session from "discourse/models/session";
+import type Site from "discourse/models/site";
+import type TopicTrackingState from "discourse/models/topic-tracking-state";
+import type User from "discourse/models/user";
+import type Capabilities from "discourse/services/capabilities";
+import type KeyValueStore from "discourse/services/key-value-store";
+import type SiteSettings from "discourse/services/site-settings";
+
+/**
+ * Returns a value as an array. Only `null` and `undefined` give an empty
+ * array, so falsy values like `""` and `0` are kept.
+ */
+export function makeArray<T>(obj: T | T[] | null | undefined): T[] {
+ if (obj === null || obj === undefined) {
+ return [];
+ }
+ return Array.isArray(obj) ? obj : [obj];
+}
+
+export function htmlHelper(fn: (...args: unknown[]) => unknown) {
+ deprecated(
+ `htmlHelper is deprecated. Use a plain function and \`htmlSafe()\` from "@ember/template" instead.`,
+ { id: "discourse.html-helper" }
+ );
+
+ return Helper.helper(function (this: unknown, ...args: unknown[]) {
+ args =
+ args.length > 1
+ ? (args[0] as unknown[]).concat({ hash: args[args.length - 1] })
+ : args;
+ return trustHTML((fn.apply(this, args) || "") as string);
+ });
+}
+
+/** The subset of the owner's registry {@link registerHelpers} writes into. */
+export interface HelperRegistry {
+ register(fullName: string, factory: unknown, options?: RegisterOptions): void;
+}
+
+/**
+ * What a legacy helper reads through {@link helperContext}. Such helpers run
+ * without an owner, so they cannot inject any of it themselves.
+ */
+export interface HelperContext {
+ siteSettings: SiteSettings;
+ keyValueStore: KeyValueStore;
+ capabilities: Capabilities;
+ currentUser: User | null;
+ site: Site;
+ session: Session;
+ topicTrackingState: TopicTrackingState;
+ registry: HelperRegistry;
+}
+
+const _helpers: Record<string, unknown> = {};
+
+export function registerHelper(
+ name: string,
+ fn: (...args: unknown[]) => unknown
+) {
+ _helpers[name] = Helper.helper(fn);
+}
+
+export function findHelper(name: string) {
+ return _helpers[name] || _helpers[dasherize(name)];
+}
+
+export function registerHelpers(registry: HelperRegistry) {
+ Object.keys(_helpers).forEach((name) => {
+ registry.register(`helper:${name}`, _helpers[name], { singleton: false });
+ });
+}
+
+let _helperContext: HelperContext;
+export function createHelperContext(ctx: HelperContext) {
+ _helperContext = ctx;
+}
+
+/**
+ * The context a legacy helper reads instead of injecting services. Nothing
+ * outside helpers, and the lib code they call, should use it.
+ */
+export function helperContext() {
+ return _helperContext;
+}
+
+/**
+ * Register a helper for Ember and raw-hbs. This exists for
+ * legacy reasons, and should be avoided in new code. Instead, you should
+ * do `export default ...` from a `helpers/*.js` file.
+ */
+export function registerUnbound(
+ name: string,
+ fn: (...args: unknown[]) => unknown
+) {
+ deprecated(
+ `[registerUnbound ${name}] registerUnbound is deprecated. Instead, you should export a default function from 'discourse/helpers/${name}.js'.`,
+ { id: "discourse.register-unbound" }
+ );
+
+ _helpers[name] = class extends Helper {
+ compute(params: unknown[], args: unknown) {
+ return fn(...params, args);
+ }
+ };
+}
+
+/**
+ * Register a helper for raw-hbs only
+ */
+export function registerRawHelper(name: string) {
+ deprecated(
+ `[registerRawHelper ${name}] the raw handlebars system has been removed, so calls to registerRawHelper should be removed.`,
+ { id: "discourse.register-raw-helper" }
+ );
+}
diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjs
index 92e30e1a221..49cae9fd9c0 100644
--- a/frontend/discourse/app/lib/plugin-api.gjs
+++ b/frontend/discourse/app/lib/plugin-api.gjs
@@ -101,6 +101,7 @@ import { registerTopicFooterDropdown } from "discourse/lib/register-topic-footer
import { replaceTagRenderer } from "discourse/lib/render-tag";
import { addTagsHtmlCallback } from "discourse/lib/render-tags";
import { addFeaturedLinkMetaDecorator } from "discourse/lib/render-topic-featured-link";
+import { reportClientError } from "discourse/lib/report-client-error";
import {
addLogSearchLinkClickedCallbacks,
addSearchResultsCallback,
@@ -195,11 +196,7 @@ function wrapWithErrorHandler(func, messageKey) {
try {
return func.call(this, ...arguments);
} catch (error) {
- document.dispatchEvent(
- new CustomEvent("discourse-error", {
- detail: { messageKey, error },
- })
- );
+ reportClientError(error, messageKey);
if (isTesting()) {
throw error;
}
diff --git a/frontend/discourse/app/lib/report-client-error.ts b/frontend/discourse/app/lib/report-client-error.ts
new file mode 100644
index 00000000000..e2053fdd167
--- /dev/null
+++ b/frontend/discourse/app/lib/report-client-error.ts
@@ -0,0 +1,15 @@
+/**
+ * Reports an error the application caught and chose to survive.
+ * `ClientErrorHandlerService` logs it with the theme or plugin it came from
+ * and shows admins a notice.
+ *
+ * @param error - The error that was caught.
+ * @param messageKey - i18n key for the notice, by convention `broken_*_alert`.
+ */
+export function reportClientError(error: unknown, messageKey: string) {
+ document.dispatchEvent(
+ new CustomEvent("discourse-error", {
+ detail: { messageKey, error },
+ })
+ );
+}
diff --git a/frontend/discourse/app/lib/resize-measurements.ts b/frontend/discourse/app/lib/resize-measurements.ts
index 9c15b8212cf..0d939fbe2ee 100644
--- a/frontend/discourse/app/lib/resize-measurements.ts
+++ b/frontend/discourse/app/lib/resize-measurements.ts
@@ -1,7 +1,8 @@
+import type { Axis } from "discourse/lib/geometry";
import { headerOffset } from "discourse/lib/offset-calculator";
/** The axis a resize runs along. */
-export type ResizeAxis = "vertical" | "horizontal";
+export type ResizeAxis = Axis;
/**
* Floor for a box whose minimum does not resolve to pixels, per axis.
diff --git a/frontend/discourse/app/services/drag-and-drop.ts b/frontend/discourse/app/services/drag-and-drop.ts
new file mode 100644
index 00000000000..82ba839c3b8
--- /dev/null
+++ b/frontend/discourse/app/services/drag-and-drop.ts
@@ -0,0 +1,136 @@
+import { tracked } from "@glimmer/tracking";
+import { isDestroying, registerDestructor } from "@ember/destroyable";
+import Service from "@ember/service";
+import { monitorForElements } from "@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter";
+import { monitorForExternal } from "@atlaskit/pragmatic-drag-and-drop/adapter/monitor-for-external";
+import {
+ decorateExternalSource,
+ type ExternalDragKind,
+ type ExternalDragPayload,
+ matchesExternalKind,
+} from "discourse/lib/-internals/drag-and-drop/external-vocabulary";
+import {
+ dragTypeOf,
+ normalizeDragSource,
+} from "discourse/lib/-internals/drag-and-drop/vocabulary";
+import { makeArray } from "discourse/lib/helpers";
+
+/** The in-flight element drag, as the source described it. */
+export interface DragPayload {
+ /** Discriminator string set by the source. */
+ type: string;
+
+ /** Arbitrary payload the source attached to the drag. */
+ data: Record<string, unknown>;
+
+ /**
+ * The element that originated the drag. `null` only when a caller of
+ * `setCurrentDrag` supplied none; the service's own monitor always does.
+ */
+ element: HTMLElement | null;
+}
+
+/**
+ * Tracks the in-flight element drag and the in-flight external drag, as the
+ * `dDragAndDrop*` modifiers see them, so surfaces can render from drag state.
+ *
+ * @see The `dDragAndDropMonitor` modifier to respond to a drag imperatively.
+ */
+export default class DragAndDropService extends Service {
+ @tracked currentDrag: DragPayload | null = null;
+
+ @tracked currentExternalDrag: ExternalDragPayload | null = null;
+
+ constructor(...args: ConstructorParameters<typeof Service>) {
+ super(...args);
+ // A monitor only subscribes to the drag stream; the element listener is
+ // bound when a draggable registers, so this costs nothing without one.
+ const cleanupElements = monitorForElements({
+ canMonitor: ({ source }) =>
+ !isDestroying(this) && dragTypeOf(source.data) != null,
+ onDragStart: ({ source }) => {
+ if (isDestroying(this)) {
+ return;
+ }
+ const normalized = normalizeDragSource(source);
+ this.setCurrentDrag({
+ // `canMonitor` above only admits sources whose `type` is set, so the
+ // `null` a typeless drag would normalize to cannot reach here.
+ type: normalized.type as string,
+ data: normalized.data,
+ element: normalized.element,
+ });
+ },
+ onDrop: () => {
+ if (isDestroying(this)) {
+ return;
+ }
+ this.clearCurrentDrag();
+ },
+ });
+ const cleanupExternal = monitorForExternal({
+ canMonitor: () => !isDestroying(this),
+ onDragStart: ({ source }) => {
+ if (isDestroying(this)) {
+ return;
+ }
+ this.currentExternalDrag = decorateExternalSource(source);
+ },
+ onDrop: () => {
+ if (isDestroying(this)) {
+ return;
+ }
+ this.currentExternalDrag = null;
+ },
+ });
+ // This runs deferred, so a monitor callback can still fire after
+ // destruction begins. The `isDestroying` guards above cover that gap.
+ registerDestructor(this, () => {
+ cleanupElements();
+ cleanupExternal();
+ });
+ }
+
+ /** Whether an element or external drag is in flight. */
+ get isDragging() {
+ return !!(this.currentDrag || this.currentExternalDrag);
+ }
+
+ /** Stores the in-flight drag's payload. */
+ setCurrentDrag(payload: DragPayload) {
+ this.currentDrag = payload;
+ }
+
+ /** Clears the in-flight drag. */
+ clearCurrentDrag() {
+ this.currentDrag = null;
+ }
+
+ /**
+ * Whether the in-flight drag's `type` is in `accepts`. Unlike a target's
+ * `accepts`, a nullish or empty filter matches nothing: a caller that has not
+ * decided should not light up for every drag.
+ *
+ * @param accepts - One type or several. Nullish or empty matches nothing.
+ */
+ accepts(accepts?: string | string[] | null) {
+ if (!this.currentDrag) {
+ return false;
+ }
+ return makeArray(accepts).includes(this.currentDrag.type);
+ }
+
+ /**
+ * Whether the in-flight external drag carries one of `kinds`. As with
+ * {@link accepts}, a nullish or empty filter matches nothing.
+ *
+ * @param kinds - One kind or several. Nullish or empty matches nothing.
+ */
+ acceptsExternal(kinds?: ExternalDragKind | ExternalDragKind[] | null) {
+ const list = makeArray(kinds);
+ if (!this.currentExternalDrag || list.length === 0) {
+ return false;
+ }
+ return matchesExternalKind(list, this.currentExternalDrag);
+ }
+}
diff --git a/frontend/discourse/app/ui-kit/d-resize-separator.gts b/frontend/discourse/app/ui-kit/d-resize-separator.gts
index b8792656033..a64342abe5f 100644
--- a/frontend/discourse/app/ui-kit/d-resize-separator.gts
+++ b/frontend/discourse/app/ui-kit/d-resize-separator.gts
@@ -5,6 +5,7 @@ import { action } from "@ember/object";
import type Owner from "@ember/owner";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import { modifier } from "ember-modifier";
+import type { Side } from "discourse/lib/geometry";
import {
measuredMax,
measuredMin,
@@ -120,7 +121,7 @@ interface DResizeSeparatorSignature {
* the one that moves: a handle at the top of a bottom-docked box is `"end"`.
* Defaults to `"start"`.
*/
- side?: "start" | "end";
+ side?: Side;
/**
* The box being resized. Given this, the separator measures its own size and
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.ts
new file mode 100644
index 00000000000..3e0d7f51574
--- /dev/null
+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-auto-scroll.ts
@@ -0,0 +1,158 @@
+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 {
+ autoScrollForElements,
+ autoScrollWindowForElements,
+} from "@atlaskit/pragmatic-drag-and-drop-auto-scroll/element";
+import {
+ autoScrollForExternal,
+ autoScrollWindowForExternal,
+} from "@atlaskit/pragmatic-drag-and-drop-auto-scroll/external";
+import { modifier } from "ember-modifier";
+import {
+ type ExternalDragKind,
+ matchesExternalKind,
+} 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";
+
+/** Which direction the container is allowed to scroll while a drag is in flight. */
+export type AutoScrollAxis = Axis | "all";
+
+/** What gets scrolled: the element the modifier sits on, or the window. */
+export type AutoScrollTarget = "element" | "window";
+
+interface DDragAndDropAutoScrollSignature {
+ /** The scroll container, or a sentinel when `target` is `"window"`. */
+ Element: HTMLElement;
+ Args: {
+ Named: {
+ /**
+ * Only drags whose `type` matches engage the auto-scroll. Omit to engage
+ * on any element drag.
+ */
+ types?: string | string[];
+
+ /**
+ * 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[];
+
+ /** Defaults to `"vertical"`. */
+ axis?: AutoScrollAxis;
+
+ /**
+ * `"element"` (default) scrolls the host element; `"window"` scrolls the
+ * window and ignores the element.
+ */
+ target?: AutoScrollTarget;
+ };
+ Positional: [];
+ };
+}
+
+/**
+ * The auto-scroll's named args, for a consumer driving
+ * {@link registerDragAndDropAutoScroll} imperatively rather than through the
+ * modifier.
+ */
+export type DragAndDropAutoScrollArgs =
+ DDragAndDropAutoScrollSignature["Args"]["Named"] & {
+ /** The scroll container. Required when `target` is `"element"`. */
+ element?: HTMLElement;
+ };
+
+/**
+ * Imperative auto-scroll registration; the `dDragAndDropAutoScroll` modifier
+ * 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.
+ * @returns Cleanup; call it once on teardown.
+ */
+export function registerDragAndDropAutoScroll(
+ getArgsRef: () => DragAndDropAutoScrollArgs
+) {
+ const matchesType = ({ source }: { source: ElementDragPayload }) =>
+ matchesDragType(getArgsRef().types, source);
+
+ const matchesKind = ({ source }: { source: NativeExternalDragPayload }) =>
+ matchesExternalKind(getArgsRef().accepts, source);
+
+ const getAllowedAxis = () => getArgsRef().axis ?? "vertical";
+
+ const args = getArgsRef();
+ const scrollsWindow = args.target === "window";
+
+ const cleanups = [
+ scrollsWindow
+ ? autoScrollWindowForElements({ canScroll: matchesType, getAllowedAxis })
+ : autoScrollForElements({
+ element: args.element,
+ canScroll: matchesType,
+ getAllowedAxis,
+ }),
+ ];
+
+ // An absent `accepts` would match every external drag, so the external
+ // registration is made only when the consumer asked for one.
+ if (args.accepts) {
+ cleanups.push(
+ scrollsWindow
+ ? autoScrollWindowForExternal({
+ canScroll: matchesKind,
+ getAllowedAxis,
+ })
+ : autoScrollForExternal({
+ element: args.element,
+ canScroll: matchesKind,
+ getAllowedAxis,
+ })
+ );
+ }
+
+ return () => cleanups.forEach((cleanup) => cleanup());
+}
+
+/**
+ * Enables auto-scroll while a compatible drag is in flight. Every arg is
+ * documented on {@link DragAndDropAutoScrollArgs}.
+ *
+ * On a scroll container:
+ *
+ * ```hbs
+ * <div class="scroll-container"
+ * {{dDragAndDropAutoScroll types=(array "card") axis="vertical"}}
+ * >
+ * ```
+ *
+ * On a sentinel with `target="window"` to scroll the window instead:
+ *
+ * ```hbs
+ * <span class="visually-hidden"
+ * {{dDragAndDropAutoScroll target="window" types=this.acceptedTypes}}
+ * ></span>
+ * ```
+ *
+ * With `accepts`, for payloads dragged in from outside the window too:
+ *
+ * ```hbs
+ * <div class="scroll-container"
+ * {{dDragAndDropAutoScroll types=(array "card") accepts="urls"}}
+ * >
+ * ```
+ */
+export default modifier<DDragAndDropAutoScrollSignature>(
+ (element, _positional, args) =>
+ // Every arg read here is tracked, so a change re-runs the modifier and
+ // replaces the registration; cheap between drags, and args rarely change.
+ registerDragAndDropAutoScroll(() => ({
+ types: args.types,
+ accepts: args.accepts,
+ axis: args.axis,
+ target: args.target,
+ element,
+ }))
+);
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-external-target.ts b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-external-target.ts
new file mode 100644
index 00000000000..33bc58f8cf8
--- /dev/null
+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-external-target.ts
@@ -0,0 +1,124 @@
+import { dropTargetForExternal } from "@atlaskit/pragmatic-drag-and-drop/adapter/drop-target-for-external";
+import type { ExternalDragPayload as NativeExternalDragPayload } from "@atlaskit/pragmatic-drag-and-drop/adapter/external-adapter-types";
+import { modifier } from "ember-modifier";
+import {
+ type DropPosition,
+ type DropTargetKernelArgs,
+ type DropTargetKernelEvent,
+ type DropTargetKernelFeedback,
+ registerDropTargetKernel,
+} 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 type { Axis } from "discourse/lib/geometry";
+
+/** What a synchronous gate (`canDrop`, `getDropEffect`) is asked about. */
+export type ExternalDropTargetFeedback =
+ DropTargetKernelFeedback<ExternalDragPayload>;
+
+/** What a lifecycle callback is told. */
+export type ExternalDropTargetEvent =
+ DropTargetKernelEvent<ExternalDragPayload>;
+
+/**
+ * The external drop target's named args, shared by the
+ * `dDragAndDropExternalTarget` modifier and
+ * {@link registerDragAndDropExternalTarget}.
+ */
+export interface DragAndDropExternalTargetArgs extends DropTargetKernelArgs<ExternalDragPayload> {
+ /**
+ * Filters which external drag kinds engage the target. Omit to accept any
+ * external drag.
+ */
+ accepts?: ExternalDragKind | ExternalDragKind[];
+
+ /** Setting this or `axis` opts the target into resolving a position at all. */
+ position?: DropPosition;
+
+ /**
+ * Without this or `position` the target is one destination, not a slot:
+ * callbacks get `position: null` and the indicator is the single
+ * `--drag-over-external` class.
+ */
+ axis?: Axis;
+}
+
+interface DDragAndDropExternalTargetSignature {
+ /** The element to register as a drop target. */
+ Element: HTMLElement;
+ Args: {
+ Named: DragAndDropExternalTargetArgs;
+ Positional: [];
+ };
+}
+
+/**
+ * Imperative external drop-target registration, wrapped by the
+ * `dDragAndDropExternalTarget` modifier below; the counterpart of
+ * `registerDragAndDropTarget` for drags from outside the window.
+ *
+ * @param element - The element to register as a drop target.
+ * @param getArgsRef - Closure returning the latest args. Adapter callbacks read
+ * it on every invocation, so arg changes apply without re-registering.
+ * @returns Cleanup; call it once on teardown.
+ */
+export function registerDragAndDropExternalTarget(
+ element: Element,
+ getArgsRef: () => DragAndDropExternalTargetArgs
+) {
+ return registerDropTargetKernel({
+ element,
+ attribute: "data-drop-target-external",
+ register: dropTargetForExternal,
+ decorateSource: (source: NativeExternalDragPayload) =>
+ decorateExternalSource(source),
+ accepts: (source) => matchesExternalKind(getArgsRef().accepts, source),
+ resolvesPosition: (args) => !!(args.position || args.axis),
+ positionlessClass: "--drag-over-external",
+ getArgs: getArgsRef,
+ });
+}
+
+/**
+ * Marks an element as a drop target for drags from outside the window: files,
+ * URLs, HTML or text from another application or tab. Every arg is documented
+ * on {@link DragAndDropExternalTargetArgs}, and the payload every callback
+ * receives on {@link ExternalDragPayload}.
+ *
+ * An accepted drop cancels the native event's default without stopping its
+ * propagation, so another `dragover` / `drop` handler still runs and sees
+ * `defaultPrevented`.
+ *
+ * Files:
+ *
+ * ```hbs
+ * <div {{dDragAndDropExternalTarget
+ * accepts="files"
+ * onDrop=this.handleFileDrop
+ * }}>...</div>
+ * ```
+ *
+ * A slot rather than a destination, with `axis` opting into a before/after
+ * position:
+ *
+ * ```hbs
+ * <li {{dDragAndDropExternalTarget
+ * accepts="urls"
+ * axis="vertical"
+ * onDrop=this.insertBeside
+ * }}>...</li>
+ * ```
+ *
+ * An ancestor that should stay lit while a nested target is hovered reads
+ * `@service dragAndDrop` instead of registering a target of its own.
+ */
+export default modifier<DDragAndDropExternalTargetSignature>(
+ (element, _positional, args) =>
+ // Pass `args` unread: reading a property here would track it and re-run
+ // the modifier, re-registering the target on every change.
+ registerDragAndDropExternalTarget(element, () => args)
+);
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.ts
new file mode 100644
index 00000000000..05c08a62b3e
--- /dev/null
+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-monitor.ts
@@ -0,0 +1,103 @@
+import {
+ type ElementEventBasePayload,
+ monitorForElements,
+} from "@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter";
+import { modifier } from "ember-modifier";
+import { consumerMayThrow } from "discourse/lib/-internals/drag-and-drop/consumer-may-throw";
+import {
+ matchesDragType,
+ type NormalizedDragSource,
+ normalizeDragSource,
+} from "discourse/lib/-internals/drag-and-drop/vocabulary";
+
+/**
+ * What a monitor callback is told: the normalized source and the drag's
+ * location history.
+ */
+export type DragMonitorEvent = Omit<ElementEventBasePayload, "source"> & {
+ source: NormalizedDragSource;
+};
+
+interface DDragAndDropMonitorSignature {
+ /**
+ * A monitor is global. The element only anchors the modifier's lifecycle.
+ */
+ Element: HTMLElement;
+ Args: {
+ Named: {
+ /**
+ * Only drags whose `type` matches are observed. Omit to observe any drag.
+ */
+ types?: string | string[];
+
+ /** A drag started. */
+ onDragStart?: (event: DragMonitorEvent) => void;
+
+ /** The drag moved. */
+ onDrag?: (event: DragMonitorEvent) => void;
+
+ /** The drag ended, whether or not it landed on a target. */
+ onDrop?: (event: DragMonitorEvent) => void;
+ };
+ Positional: [];
+ };
+}
+
+/**
+ * The monitor's named args, for a consumer driving
+ * {@link registerDragAndDropMonitor} imperatively rather than through the
+ * modifier.
+ */
+export type DragAndDropMonitorArgs =
+ DDragAndDropMonitorSignature["Args"]["Named"];
+
+/**
+ * Imperative monitor registration; the `dDragAndDropMonitor` modifier below
+ * wraps it.
+ *
+ * @param getArgsRef - Closure returning the latest args. Callbacks read it on
+ * every invocation; `types` is consulted once as a drag starts, so a change
+ * applies from the next drag.
+ * @returns Cleanup; call it once on teardown.
+ */
+export function registerDragAndDropMonitor(
+ getArgsRef: () => DragAndDropMonitorArgs
+) {
+ const normalized = (event: ElementEventBasePayload): DragMonitorEvent => ({
+ ...event,
+ source: normalizeDragSource(event.source),
+ });
+ return monitorForElements({
+ canMonitor: ({ source }) => matchesDragType(getArgsRef().types, source),
+ onDragStart: (event) =>
+ consumerMayThrow(() => getArgsRef().onDragStart?.(normalized(event))),
+ onDrag: (event) =>
+ consumerMayThrow(() => getArgsRef().onDrag?.(normalized(event))),
+ onDrop: (event) =>
+ consumerMayThrow(() => getArgsRef().onDrop?.(normalized(event))),
+ });
+}
+
+/**
+ * Observes the in-flight element drag regardless of drop targets, to react to
+ * its progress without making an element droppable. Every arg is documented on
+ * {@link DragAndDropMonitorArgs}.
+ *
+ * ```hbs
+ * <div {{dDragAndDropMonitor types=this.dragTypes onDrag=this.onDrag}}></div>
+ * ```
+ *
+ * @see The `dragAndDrop` service to read drag state reactively; rendering from
+ * these callbacks duplicates what it keeps.
+ */
+export default modifier<DDragAndDropMonitorSignature>(
+ (_element, _positional, args) =>
+ // Read args inside the closure: reading them here would track them and
+ // re-run the modifier, re-registering the monitor on every change.
+ registerDragAndDropMonitor(() => ({
+ types: args.types,
+ onDragStart: args.onDragStart,
+ onDrag: args.onDrag,
+ onDrop: args.onDrop,
+ }))
+);
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-source.ts b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-source.ts
new file mode 100644
index 00000000000..676db1bab0b
--- /dev/null
+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-source.ts
@@ -0,0 +1,673 @@
+import { registerDestructor } from "@ember/destroyable";
+import type Owner from "@ember/owner";
+import { cancel, next } from "@ember/runloop";
+import { draggable } from "@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter";
+import { pointerOutsideOfPreview } from "@atlaskit/pragmatic-drag-and-drop/utils/pointer-outside-of-preview";
+import { preventUnhandled } from "@atlaskit/pragmatic-drag-and-drop/utils/prevent-unhandled";
+import { setCustomNativeDragPreview } from "@atlaskit/pragmatic-drag-and-drop/utils/set-custom-native-drag-preview";
+import Modifier, { type ArgsFor } from "ember-modifier";
+import { consumerMayThrow } from "discourse/lib/-internals/drag-and-drop/consumer-may-throw";
+import type {
+ DragInput,
+ DragLocation,
+} from "discourse/lib/-internals/drag-and-drop/drop-target-kernel";
+import {
+ DRAG_BODY,
+ normalizeOwnedDragSource,
+} from "discourse/lib/-internals/drag-and-drop/vocabulary";
+
+/**
+ * Renders a drag preview into an isolated, offscreen container the browser
+ * photographs. Return a cleanup function that tears the preview down.
+ */
+export type DragPreviewRenderer = (args: {
+ /** The offscreen container to render into. */
+ container: HTMLElement;
+
+ /** The source element the drag began on. */
+ element: HTMLElement;
+}) => (() => void) | void;
+
+/** The dragged source, as the lifecycle callbacks receive it. */
+export type DragSource = ReturnType<typeof normalizeOwnedDragSource>;
+
+interface DDragAndDropSourceSignature {
+ /** The element to mark draggable. */
+ Element: HTMLElement;
+ Args: {
+ Named: {
+ /**
+ * Discriminator string. Targets filter on this via their `accepts` arg, and
+ * it is stamped onto `source.data.type` for callbacks.
+ *
+ * Reserved: it overwrites any `type` the payload carries. The `dragAndDrop`
+ * service also identifies drags by it, so a source without one is invisible
+ * there.
+ */
+ type: string;
+
+ /**
+ * Static payload the source attaches to the drag, exposed as `source.data`
+ * in target callbacks. A `type` key on it is overwritten; see `type`.
+ */
+ data?: object;
+
+ /**
+ * Alternative to `data` for dynamic payloads. Called once just before
+ * `dragstart`. Its `type` key is overwritten the same way.
+ */
+ getInitialData?: () => object;
+
+ /**
+ * A custom native drag preview. An `Element` is photographed in place: the
+ * source element keeps the grab point as its hotspot, any other element
+ * uses its top-left. Defaults to the source element.
+ *
+ * A render function mounts a fresh preview into an isolated, offscreen
+ * container, so nothing around the source bleeds into the drag image.
+ */
+ dragPreview?: Element | DragPreviewRenderer;
+
+ /**
+ * CSS lengths (e.g. `{x: "1rem", y: "0.5rem"}`) that push the preview clear
+ * of the pointer. Applies only to the render-function `dragPreview`; an
+ * `Element` preview is placed by its own hotspot.
+ */
+ dragPreviewOffset?: { x: string; y: string };
+
+ /**
+ * Which drop operations this drag permits, written onto the native
+ * `dataTransfer` at `dragstart`. Defaults to `"move"`, which also stops the
+ * browser badging the pointer with its copy offer.
+ *
+ * A source whose drop duplicates wants `"copyMove"`: a target's
+ * `getDropEffect` may only return an effect this permits.
+ */
+ effectAllowed?: DataTransfer["effectAllowed"];
+
+ /** Returning `false` blocks the drag from starting. */
+ canDrag?: (feedback: {
+ /**
+ * The source as it stands before the drag begins. `data` is the arg
+ * exactly as passed, before it is merged into the drag payload.
+ */
+ source: { type?: string; data?: object; element: HTMLElement };
+
+ /** Where the pointer is. */
+ input: DragInput;
+ }) => boolean | void;
+
+ /** Fires once the drag is confirmed. */
+ onDragStart?: (event: {
+ /** The dragged source. */
+ source: DragSource;
+
+ /** Where the pointer is. */
+ input: DragInput;
+ }) => void;
+
+ /**
+ * Fires once at the end of every drag, landed or abandoned, and is where
+ * drag-time state gets undone. A source destroyed before the deferred
+ * dispatch fires does not receive it.
+ *
+ * Fires after the whole drop dispatch, target and monitor callbacks
+ * included, so shared dispatch state can be cleared here. Branch on the
+ * outcome with `location.current.dropTargets`.
+ */
+ onDragEnd?: (event: {
+ /** The dragged source. */
+ source: DragSource;
+
+ /** The drag's location history. */
+ location: DragLocation;
+ }) => void;
+
+ /**
+ * Fires only for a drag that ended on at least one drop target, so this is
+ * where the operation is performed. `onDragEnd` fires first, with the same
+ * `source` and `location`.
+ */
+ onDrop?: (event: {
+ /** The dragged source. */
+ source: DragSource;
+
+ /** The drag's location history. */
+ location: DragLocation;
+ }) => void;
+
+ /**
+ * An element inside this one that a drag must start from, so the rest stays
+ * free for selecting text and operating controls. Pass the element itself,
+ * captured with a modifier on the handle, not a selector.
+ *
+ * Changing it re-registers, so a ref that only arrives on a later render
+ * still takes effect. Omit it and the whole element initiates a drag.
+ *
+ * The handle carries `draggable="true"`; this element stays the body: it
+ * gets the state markers, is the target's `source.element`, and is what the
+ * default preview photographs.
+ */
+ dragHandle?: Element;
+
+ /**
+ * When `true`, the draggable registration is detached; a drag already in
+ * flight finishes and reports first. This, not `dragHandle`, is how to stop
+ * an element being dragged: a handle only moves where a drag may begin.
+ *
+ * Style and assert on `data-drag-source`, never on `draggable`: the
+ * attribute sits on whichever element was registered.
+ */
+ disabled?: boolean;
+ };
+ Positional: [];
+ };
+}
+
+/**
+ * What a registration still owes after being detached without cancelling, and
+ * the ways its owner can resume or let go of it.
+ *
+ * A registration waiting for its drag can be reclaimed when the modifier needs
+ * that same element again. Work holding only a scheduled dispatch cannot: its
+ * drag has ended and its registration has already been torn down.
+ */
+export interface DetachedSourceWork {
+ /**
+ * The element the registration was created on: the drag handle when one was
+ * given, the source element otherwise. A replacement registering on the same
+ * element can reclaim this work; one registering elsewhere must leave it
+ * waiting, because the underlying library dispatches an in-flight drag's end
+ * by looking this element up.
+ */
+ registeredElement: HTMLElement;
+
+ /**
+ * Re-adopts a registration still waiting for its drag, or returns `null` when
+ * only a scheduled dispatch remains.
+ */
+ reclaim: () => DragAndDropSourceCleanup | null;
+
+ /** The consumer is going away. Drops everything, dispatch included. */
+ abandon: () => void;
+
+ /**
+ * Whether anything is still owed. Goes false once the dispatch has fired and
+ * no teardown is waiting; a holder has no other way to know when to let go.
+ */
+ outstanding: () => boolean;
+}
+
+/**
+ * Tears a drag source registration down.
+ *
+ * `cancelPending` decides the fate of a drop dispatch already scheduled for the
+ * next task. `true` (the default) drops it: the consumer is going away. `false`
+ * keeps it: the registration is only being replaced and the consumer lives on.
+ *
+ * Returns the work still owed, or `null`. A caller that kept the dispatch must
+ * hold onto it: it is the only way left to reach the registration, and a
+ * reclaimed one is torn down by calling this again.
+ */
+export type DragAndDropSourceCleanup = (options?: {
+ cancelPending?: boolean;
+}) => DetachedSourceWork | null;
+
+/**
+ * The drag source's named args, for a consumer driving
+ * {@link registerDragAndDropSource} imperatively rather than through the
+ * modifier.
+ */
+export type DragAndDropSourceArgs =
+ DDragAndDropSourceSignature["Args"]["Named"];
+
+type RegistrationToken = symbol;
+
+/**
+ * Registered element to its current args. Weak so a removed subtree whose
+ * registration never ends is not kept alive for the life of the tab.
+ */
+let effectDeclarers = new WeakMap<
+ Element,
+ { token: RegistrationToken; getArgsRef: () => DragAndDropSourceArgs }
+>();
+
+/** Which live registrations own each body's source mark. */
+let dragSourceMarks = new WeakMap<Element, Set<RegistrationToken>>();
+
+/**
+ * Registered source count; the shared listener is bound while it is above
+ * zero.
+ */
+let liveSourceCount = 0;
+
+/** Unbinds the shared listener below. Null while no source is registered. */
+let stopDeclaringEffects: (() => void) | null = null;
+
+/**
+ * Writes the starting drag's `effectAllowed`. Left unwritten it means
+ * "anything", which the browser renders as its standing offer to copy.
+ *
+ * A native listener because the library never hands the callbacks the event,
+ * and the browser reads the value once the `dragstart` dispatch has finished.
+ */
+function declareEffectAllowed(event: DragEvent) {
+ const declarer =
+ event.target instanceof Element
+ ? effectDeclarers.get(event.target)
+ : undefined;
+ if (declarer && event.dataTransfer) {
+ event.dataTransfer.effectAllowed =
+ declarer.getArgsRef().effectAllowed ?? "move";
+ }
+}
+
+/**
+ * Registers a source with the shared `dragstart` listener; one listener serves
+ * every source because a long list registers one per row.
+ *
+ * @returns Cleanup, which unbinds the listener once the last source has gone.
+ */
+function declareEffectFor(
+ element: Element,
+ getArgsRef: () => DragAndDropSourceArgs,
+ token: RegistrationToken
+) {
+ if (!effectDeclarers.has(element)) {
+ liveSourceCount += 1;
+ }
+ effectDeclarers.set(element, { token, getArgsRef });
+ if (!stopDeclaringEffects) {
+ window.addEventListener("dragstart", declareEffectAllowed, {
+ capture: true,
+ });
+ stopDeclaringEffects = () =>
+ window.removeEventListener("dragstart", declareEffectAllowed, {
+ capture: true,
+ });
+ }
+
+ return () => {
+ // A repeated or superseded release must not decrement again and unbind the
+ // listener under a source that is still registered.
+ if (effectDeclarers.get(element)?.token !== token) {
+ return;
+ }
+ effectDeclarers.delete(element);
+ liveSourceCount -= 1;
+ if (liveSourceCount === 0) {
+ stopDeclaringEffects?.();
+ stopDeclaringEffects = null;
+ }
+ };
+}
+
+/** Test-only: forget every source and unbind the listener between tests. */
+export function resetDragSourcesForTesting() {
+ effectDeclarers = new WeakMap();
+ dragSourceMarks = new WeakMap();
+ liveSourceCount = 0;
+ stopDeclaringEffects?.();
+ stopDeclaringEffects = null;
+}
+
+/**
+ * Wraps the underlying draggable registration with payload normalisation, the
+ * source's state markers, and the end-of-drag deferral. Exported so a consumer
+ * can register a source imperatively, beside `registerDragAndDropTarget`.
+ *
+ * End-of-drag callbacks are deferred to the next task, after the drop event has
+ * finished propagating: `onDragEnd` for every drag, then `onDrop` for one that
+ * landed on a target.
+ *
+ * One registration per element: the underlying library keys registrations by
+ * element, so a second one must wait for the first's cleanup.
+ *
+ * @param element - The element to mark draggable.
+ * @param getArgsRef - Closure returning the latest args, read on every library
+ * callback, so changes apply without re-registering. `dragHandle` is read once
+ * at registration; change it by re-registering.
+ * @returns Cleanup function; see {@link DragAndDropSourceCleanup}.
+ */
+export function registerDragAndDropSource(
+ element: HTMLElement,
+ getArgsRef: () => DragAndDropSourceArgs
+): DragAndDropSourceCleanup {
+ const token = Symbol("drag-source-registration");
+
+ // Registered on the handle itself, not via the library's own `dragHandle`
+ // option, so `draggable="true"` never lands on the body.
+ const registered = (getArgsRef().dragHandle ?? element) as HTMLElement;
+
+ // An attribute, not a class: the stylesheet gates on it, and a consumer's
+ // dynamic `class` binding would overwrite a class written here.
+ const marks = dragSourceMarks.get(element) ?? new Set();
+ marks.add(token);
+ dragSourceMarks.set(element, marks);
+ element.setAttribute("data-drag-source", "");
+
+ /** The scheduled end-of-drag dispatch, so teardown can cancel it. */
+ let pendingConsumers: Parameters<typeof cancel>[0] | null = null;
+
+ /** Whether a drag from this element is in flight. */
+ let dragging = false;
+
+ /** A teardown waiting for the drag in flight to finish, if there is one. */
+ let teardownWhenIdle: (() => void) | null = null;
+
+ const stopDeclaringEffect = declareEffectFor(registered, getArgsRef, token);
+
+ const cleanup = draggable({
+ element: registered,
+ canDrag: ({ input }) => {
+ const args = getArgsRef();
+ if (!args.canDrag) {
+ return true;
+ }
+ return consumerMayThrow(
+ () =>
+ args.canDrag!({
+ source: { type: args.type, data: args.data, element },
+ input,
+ }) !== false,
+ false
+ );
+ },
+ onGenerateDragPreview: ({ nativeSetDragImage, location }) => {
+ const args = getArgsRef();
+ // Latched here rather than in `onDragStart`, which the library defers by
+ // a frame: a detach landing in that frame must still see the drag.
+ dragging = true;
+
+ // Claims the drag over dead space, so a release there ends it in place.
+ // Never stopped: the utility unbinds itself on drop, dragend and broken drags.
+ preventUnhandled.start();
+
+ if (!nativeSetDragImage) {
+ return;
+ }
+ if (typeof args.dragPreview === "function") {
+ setCustomNativeDragPreview({
+ nativeSetDragImage,
+ getOffset: args.dragPreviewOffset
+ ? pointerOutsideOfPreview(args.dragPreviewOffset)
+ : undefined,
+ render: ({ container }) => {
+ const dispose = consumerMayThrow(() =>
+ (args.dragPreview as DragPreviewRenderer)({ container, element })
+ );
+ return typeof dispose === "function"
+ ? () => consumerMayThrow(dispose)
+ : undefined;
+ },
+ });
+ return;
+ }
+ // With a handle the browser's default preview would be the grip alone, so
+ // the body stands in.
+ const preview =
+ args.dragPreview ?? (registered === element ? null : element);
+ if (preview) {
+ if (preview === element) {
+ const { clientX, clientY } = location.current.input;
+ const { left, top, width, height } = element.getBoundingClientRect();
+ nativeSetDragImage(
+ preview,
+ Math.max(0, Math.min(clientX - left, width)),
+ Math.max(0, Math.min(clientY - top, height))
+ );
+ } else {
+ nativeSetDragImage(preview, 0, 0);
+ }
+ }
+ },
+ getInitialData: () => {
+ const args = getArgsRef();
+ const resolved = consumerMayThrow(
+ () => args.getInitialData?.() ?? args.data ?? {},
+ {}
+ );
+ // Spread first so the payload's own `type` cannot win. `DRAG_BODY` lets a
+ // target resolve the body behind a handle; the vocabulary strips it.
+ return { ...resolved, type: args.type, [DRAG_BODY]: element };
+ },
+ onDragStart: (event) => {
+ const args = getArgsRef();
+ element.classList.add("--dragging");
+ const sourcePayload = normalizeOwnedDragSource(event.source);
+ consumerMayThrow(() =>
+ args.onDragStart?.({
+ source: sourcePayload,
+ input: event.location.current.input,
+ })
+ );
+ },
+ onDrop: (event) => {
+ const args = getArgsRef();
+ dragging = false;
+ element.classList.remove("--dragging");
+
+ // Snapshot before deferring: when the task runs, `getArgsRef()` may
+ // belong to a later render or a new drag.
+ const consumerOnDragEnd = args.onDragEnd;
+ const consumerOnDrop = args.onDrop;
+ const sourcePayload = normalizeOwnedDragSource(event.source);
+ const location = event.location;
+ const landed = location.current.dropTargets.length > 0;
+
+ // One task for both callbacks, so `pendingConsumers` cancels the whole
+ // dispatch and their order is fixed.
+ pendingConsumers = next(() => {
+ pendingConsumers = null;
+ try {
+ // Guarded one at a time so an `onDragEnd` that throws does not cost
+ // the drag its `onDrop`.
+ consumerMayThrow(() =>
+ consumerOnDragEnd?.({ source: sourcePayload, location })
+ );
+ if (landed) {
+ consumerMayThrow(() =>
+ consumerOnDrop?.({ source: sourcePayload, location })
+ );
+ }
+ } finally {
+ // The teardown held back for this drag runs after both callbacks, so
+ // the consumer hears its drag end before the registration goes.
+ const deferred = teardownWhenIdle;
+ teardownWhenIdle = null;
+ deferred?.();
+ }
+ });
+ },
+ });
+
+ const teardown = () => {
+ cleanup();
+ stopDeclaringEffect();
+ if (dragging) {
+ element.classList.remove("--dragging");
+ }
+ const currentMarks = dragSourceMarks.get(element);
+ if (!currentMarks?.delete(token)) {
+ return;
+ }
+ if (currentMarks.size === 0) {
+ dragSourceMarks.delete(element);
+ element.removeAttribute("data-drag-source");
+ }
+ };
+
+ /**
+ * Drops everything this registration is still owed, for a consumer that is
+ * going away: the scheduled dispatch as well as any waiting teardown.
+ */
+ const abandon = () => {
+ if (pendingConsumers) {
+ cancel(pendingConsumers);
+ pendingConsumers = null;
+ }
+ if (teardownWhenIdle) {
+ teardownWhenIdle = null;
+ teardown();
+ }
+ };
+
+ const outstanding = () => Boolean(pendingConsumers || teardownWhenIdle);
+
+ /** Re-adopts this registration while its drag still requires it. */
+ const reclaim = () => {
+ if (!teardownWhenIdle) {
+ return null;
+ }
+ teardownWhenIdle = null;
+ return cleanupRegistration;
+ };
+
+ /** See {@link DragAndDropSourceCleanup}. */
+ const cleanupRegistration: DragAndDropSourceCleanup = ({
+ cancelPending = true,
+ } = {}) => {
+ if (cancelPending) {
+ abandon();
+ teardown();
+ return null;
+ }
+
+ if (dragging) {
+ // Unregistering mid-drag drops the library's end-of-drag dispatch to this
+ // element, so the teardown waits for the drag.
+ teardownWhenIdle = teardown;
+ return { registeredElement: registered, reclaim, abandon, outstanding };
+ }
+
+ teardown();
+ return pendingConsumers
+ ? { registeredElement: registered, reclaim, abandon, outstanding }
+ : null;
+ };
+
+ return cleanupRegistration;
+}
+
+/**
+ * Marks an element as a drag source for the Discourse drag-and-drop vocabulary,
+ * paired with `dDragAndDropTarget`. A thin wrapper around
+ * {@link registerDragAndDropSource}; every arg is documented on
+ * {@link DragAndDropSourceArgs}.
+ *
+ * ```hbs
+ * <li {{dDragAndDropSource
+ * type="sidebar-link"
+ * data=this.link
+ * dragPreview=this.previewEl
+ * canDrag=this.canDrag
+ * onDragStart=this.handleDragStart
+ * onDragEnd=this.clearDragState
+ * onDrop=this.applyDrop
+ * }}>...</li>
+ * ```
+ *
+ * Stamps `data-drag-source` for the registration's lifetime and `--dragging`
+ * while a drag is active; the ui-kit drag-and-drop stylesheet gates its
+ * selectors on the attribute.
+ *
+ * Testing: see the note on `dDragAndDropTarget`; the same helpers drive both
+ * ends of a drag.
+ *
+ * Pointer-only. A native drag has no keyboard equivalent, so a surface built on
+ * this needs a keyboard route to the same operation beside it.
+ *
+ * @see The `dPointerDrag` modifier when there is no drop target and no payload:
+ * a press that changes a value continuously is a different gesture.
+ */
+export default class DDragAndDropSourceModifier extends Modifier<DDragAndDropSourceSignature> {
+ #cleanup: DragAndDropSourceCleanup | null = null;
+
+ /**
+ * Replaced by `modify` before any callback can read it; the empty bag only
+ * covers the window before the first run.
+ */
+ #args = {} as DragAndDropSourceArgs;
+
+ /** The handle the live registration was created with, to detect a change. */
+ #dragHandle: Element | undefined = undefined;
+
+ /**
+ * Registrations replaced while still owing the consumer something. Held here
+ * because a consumer can be destroyed after its registration was replaced but
+ * before the drag it kept has reported. A set: several can be outstanding.
+ */
+ #detached = new Set<DetachedSourceWork>();
+
+ constructor(owner: Owner, args: ArgsFor<DDragAndDropSourceSignature>) {
+ super(owner, args);
+ registerDestructor(this, (instance) => {
+ instance.#detach();
+ instance.#detached.forEach((work) => work.abandon());
+ instance.#detached.clear();
+ });
+ }
+
+ modify(
+ element: HTMLElement,
+ _positional: [],
+ args: DragAndDropSourceArgs = {} as DragAndDropSourceArgs
+ ) {
+ if (args.disabled) {
+ this.#detach({ cancelPending: false });
+ return;
+ }
+
+ this.#args = args;
+
+ if (this.#cleanup && args.dragHandle !== this.#dragHandle) {
+ this.#detach({ cancelPending: false });
+ }
+ this.#dragHandle = args.dragHandle;
+
+ if (!this.#cleanup) {
+ const registering = (args.dragHandle ?? element) as HTMLElement;
+ for (const work of this.#detached) {
+ if (work.registeredElement === registering) {
+ const reclaimed = work.reclaim();
+ if (reclaimed) {
+ this.#detached.delete(work);
+ this.#cleanup = reclaimed;
+ break;
+ }
+ }
+ }
+ this.#pruneDetached();
+ this.#cleanup ??= registerDragAndDropSource(element, () => this.#args);
+ }
+ }
+
+ /**
+ * Unregisters the source.
+ *
+ * @param options - `cancelPending` passes through to the registration's
+ * cleanup. Defaults to `true`, the destructor's case; only a replacement
+ * while the consumer lives on keeps the pending dispatch.
+ */
+ #detach({ cancelPending = true }: { cancelPending?: boolean } = {}) {
+ const work = this.#cleanup?.({ cancelPending }) ?? null;
+ if (work) {
+ this.#detached.add(work);
+ }
+ this.#pruneDetached();
+ this.#cleanup = null;
+ }
+
+ /**
+ * Forgets detached registrations that have finished what they were kept for.
+ * Without a sweep on each detach and re-registration, one would be retained
+ * per drag for as long as this modifier lives.
+ */
+ #pruneDetached() {
+ this.#detached.forEach((work) => {
+ if (!work.outstanding()) {
+ this.#detached.delete(work);
+ }
+ });
+ }
+}
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.ts
new file mode 100644
index 00000000000..dae8415099f
--- /dev/null
+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-target.ts
@@ -0,0 +1,125 @@
+import {
+ dropTargetForElements,
+ type ElementDragPayload,
+} from "@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter";
+import { modifier } from "ember-modifier";
+import {
+ type DropTargetKernelArgs,
+ type DropTargetKernelEvent,
+ type DropTargetKernelFeedback,
+ registerDropTargetKernel,
+} from "discourse/lib/-internals/drag-and-drop/drop-target-kernel";
+import {
+ dragBodyOf,
+ matchesDragType,
+ type NormalizedDragSource,
+ normalizeDragSource,
+} from "discourse/lib/-internals/drag-and-drop/vocabulary";
+
+export {
+ type DropEffect,
+ type DropPosition,
+ type DropPositionOptions,
+} from "discourse/lib/-internals/drag-and-drop/drop-target-kernel";
+
+/** The dragged source, normalized to the shape `dDragAndDropSource` publishes. */
+export type DropTargetSource = NormalizedDragSource;
+
+/** What a synchronous gate (`canDrop`, `getDropEffect`) is asked about. */
+export type DropTargetFeedback = DropTargetKernelFeedback<DropTargetSource>;
+
+/** What a lifecycle callback is told. */
+export type DropTargetEvent = DropTargetKernelEvent<DropTargetSource>;
+
+/**
+ * The drop target's named args, shared by the `dDragAndDropTarget` modifier
+ * and {@link registerDragAndDropTarget}.
+ */
+export interface DragAndDropTargetArgs extends DropTargetKernelArgs<DropTargetSource> {
+ /**
+ * The dragged source's `type` must be in this list for the target to engage.
+ * Omit to accept any source.
+ */
+ accepts?: string | string[];
+
+ /**
+ * `false` refuses a drop whose dragged element is this element. Defaults to
+ * `true`: an element that is both source and target has a meaningful drop
+ * onto itself, so excluding it is opt-in.
+ */
+ acceptsSelf?: boolean;
+}
+
+interface DDragAndDropTargetSignature {
+ /** The element to register as a drop target. */
+ Element: HTMLElement;
+ Args: {
+ Named: DragAndDropTargetArgs;
+ Positional: [];
+ };
+}
+
+/**
+ * Imperative drop-target registration; the `dDragAndDropTarget` modifier
+ * below wraps it.
+ *
+ * @param element - The element to register as a drop target.
+ * @param getArgsRef - Closure returning the latest args. Library callbacks read
+ * it on every invocation, so arg changes apply without re-registering.
+ * @returns Cleanup; call it once on teardown.
+ */
+export function registerDragAndDropTarget(
+ element: Element,
+ getArgsRef: () => DragAndDropTargetArgs
+) {
+ return registerDropTargetKernel({
+ element,
+ attribute: "data-drop-target",
+ register: dropTargetForElements,
+ decorateSource: (source: ElementDragPayload) => normalizeDragSource(source),
+ accepts: (source) => {
+ const args = getArgsRef();
+ if (!matchesDragType(args.accepts, source)) {
+ return false;
+ }
+
+ return args.acceptsSelf !== false || dragBodyOf(source) !== element;
+ },
+ getArgs: getArgsRef,
+ });
+}
+
+/**
+ * Marks an element as a drop target for `dDragAndDropSource` drags. Every arg
+ * is documented on {@link DragAndDropTargetArgs}. The indicator classes are
+ * styled in `app/assets/stylesheets/common/ui-kit/d-drag-and-drop.scss`.
+ *
+ * Position from the pointer against the element's midpoint:
+ *
+ * ```hbs
+ * <li {{dDragAndDropTarget accepts="sidebar-link" onDrop=this.reorder}}>...</li>
+ * ```
+ *
+ * A fixed position:
+ *
+ * ```hbs
+ * <div {{dDragAndDropTarget
+ * accepts="block"
+ * position="inside"
+ * onDrop=this.applyMove
+ * }}></div>
+ * ```
+ *
+ * Testing: use `simulateDrag` from
+ * `discourse/tests/helpers/ui-kit/drag-and-drop-helper` in JS, and
+ * `SystemHelpers#drag_and_drop` in system specs; synthetic mouse drags stall.
+ *
+ * Element drags only; see `dDragAndDropExternalTarget` for payloads dragged in
+ * from outside the window.
+ */
+export default modifier<DDragAndDropTargetSignature>(
+ (element, _positional, args) =>
+ // Pass `args` unread: reading a property here would track it and re-run
+ // the modifier, re-registering the target on every change.
+ registerDragAndDropTarget(element, () => args)
+);
diff --git a/frontend/discourse/app/ui-kit/modifiers/d-resize-edge.ts b/frontend/discourse/app/ui-kit/modifiers/d-resize-edge.ts
index 1d7aefa8048..b42401fc60b 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-resize-edge.ts
+++ b/frontend/discourse/app/ui-kit/modifiers/d-resize-edge.ts
@@ -1,6 +1,8 @@
import { registerDestructor } from "@ember/destroyable";
import type Owner from "@ember/owner";
import Modifier, { type ArgsFor } from "ember-modifier";
+import type { Side } from "discourse/lib/geometry";
+import type { ResizeAxis } from "discourse/lib/resize-measurements";
import {
type DPointerDragArgs,
registerPointerDrag,
@@ -55,7 +57,7 @@ interface DResizeEdgeSignature {
* should carry: that describes the separator itself, which lies across
* the axis it moves along.
*/
- axis?: "horizontal" | "vertical";
+ axis?: ResizeAxis;
/**
* Which edge the resized element is docked against, in logical terms.
@@ -67,7 +69,7 @@ interface DResizeEdgeSignature {
* Changing this or `axis` mid-gesture measures the new orientation against
* an origin captured in the old one, so the result is undefined.
*/
- side?: "start" | "end";
+ side?: Side;
/**
* A class held on `document.body` for the length of a gesture, for a cursor
diff --git a/frontend/discourse/package.json b/frontend/discourse/package.json
index 44eb0ee3a2f..2c0e8fba141 100644
--- a/frontend/discourse/package.json
+++ b/frontend/discourse/package.json
@@ -24,6 +24,8 @@
"start": "./rolldown.mjs"
},
"dependencies": {
+ "@atlaskit/pragmatic-drag-and-drop": "^3.0.0",
+ "@atlaskit/pragmatic-drag-and-drop-auto-scroll": "^3.0.1",
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.10.3",
"@codemirror/lang-javascript": "^6.2.5",
diff --git a/frontend/discourse/tests/helpers/qunit-helpers.js b/frontend/discourse/tests/helpers/qunit-helpers.js
index 212e63f1e44..cccadf50f00 100644
--- a/frontend/discourse/tests/helpers/qunit-helpers.js
+++ b/frontend/discourse/tests/helpers/qunit-helpers.js
@@ -112,8 +112,10 @@ import {
currentSettings,
mergeSettings,
} from "discourse/tests/helpers/site-settings";
+import { resetDragAndDropForTesting } from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";
import { resetHtmlDecorators } from "discourse/ui-kit/d-decorated-html";
import { clearToolbarCallbacks } from "discourse/ui-kit/d-editor";
+import { resetDragSourcesForTesting } from "discourse/ui-kit/modifiers/d-drag-and-drop-source";
import { resetPointerDragForTesting } from "discourse/ui-kit/modifiers/d-pointer-drag";
import I18n from "discourse-i18n";
import { setupDSelectAssertions } from "./d-select-assertions";
@@ -290,6 +292,8 @@ export function testCleanup(container, app) {
_resetOutletLayoutsForTesting();
resetBlockRegistryForTesting();
resetDebugCallbacks();
+ resetDragAndDropForTesting();
+ resetDragSourcesForTesting();
resetPointerDragForTesting();
resetElementClassLeasesForTesting();
clearBacklog();
diff --git a/frontend/discourse/tests/helpers/ui-kit/drag-and-drop-helper.ts b/frontend/discourse/tests/helpers/ui-kit/drag-and-drop-helper.ts
new file mode 100644
index 00000000000..0121e8c5361
--- /dev/null
+++ b/frontend/discourse/tests/helpers/ui-kit/drag-and-drop-helper.ts
@@ -0,0 +1,329 @@
+import { triggerEvent } from "@ember/test-helpers";
+
+/** A point on the viewport, in the shape every drag event has to carry. */
+interface ClientPoint {
+ clientX: number;
+ clientY: number;
+}
+
+/**
+ * The center-point client coordinates of an element.
+ *
+ * Every synthetic drag event must carry finite `clientX` / `clientY`: the
+ * underlying library resolves the pointer with `elementsFromPoint`, which
+ * throws on non-finite values.
+ *
+ * @param selector - CSS selector for the element to measure.
+ * @returns The element's center point.
+ */
+export function centerOf(selector: string): ClientPoint {
+ const rect = (
+ document.querySelector(selector) as Element
+ ).getBoundingClientRect();
+ return {
+ clientX: rect.left + rect.width / 2,
+ clientY: rect.top + rect.height / 2,
+ };
+}
+
+/**
+ * A `DataTransfer` carrying plain text, the way a selection dragged in from
+ * another window arrives.
+ *
+ * @param text - The `text/plain` payload.
+ */
+export function textTransfer(text = "dropped text") {
+ const dataTransfer = new DataTransfer();
+ dataTransfer.setData("text/plain", text);
+ return dataTransfer;
+}
+
+/**
+ * A `DataTransfer` carrying one file, the way a drag from the OS file manager
+ * arrives.
+ *
+ * @param name - The file's name, as `getFiles()` reports it.
+ */
+export function fileTransfer(name = "a.txt") {
+ const dataTransfer = new DataTransfer();
+ dataTransfer.items.add(new File(["payload"], name, { type: "text/plain" }));
+ return dataTransfer;
+}
+
+/**
+ * Throws unless both ends of a drag are registered with the primitives.
+ *
+ * A drag dispatched at an unregistered source or target does nothing, so a
+ * test asserting that nothing happened would pass for the wrong reason and
+ * keep passing after the registration was removed outright.
+ *
+ * @param sourceSelector - CSS selector for the element the drag starts on.
+ * @param targetSelector - CSS selector for the element it is dropped on.
+ */
+function assertDragRegistered(sourceSelector: string, targetSelector: string) {
+ const source = document.querySelector(sourceSelector);
+ const target = document.querySelector(targetSelector);
+
+ if (!source?.hasAttribute("data-drag-source")) {
+ throw new Error(
+ `${sourceSelector} is not a registered drag source, so this drag would do nothing`
+ );
+ }
+ if (!target?.hasAttribute("data-drop-target")) {
+ throw new Error(
+ `${targetSelector} is not a registered drop target, so this drag would do nothing`
+ );
+ }
+}
+
+/**
+ * Throws unless the element is registered as an external drop target; the
+ * external counterpart of {@link assertDragRegistered}.
+ *
+ * @param targetSelector - CSS selector for the element the drag is aimed at.
+ */
+export function assertExternalTargetRegistered(targetSelector: string) {
+ const target = document.querySelector(targetSelector);
+
+ if (!target?.hasAttribute("data-drop-target-external")) {
+ throw new Error(
+ `${targetSelector} is not a registered external drop target, so this drag would do nothing`
+ );
+ }
+}
+
+/**
+ * Dispatches one synthetic drag event, then waits one animation frame.
+ *
+ * The frame wait is the point of this wrapper; every other helper here
+ * dispatches through it. The underlying library runs `onDragStart` in a
+ * `requestAnimationFrame` and throttles `onDrag` to a frame.
+ *
+ * Ember's `settled()` does not pump animation frames, so without the wait
+ * those callbacks have not fired when the caller's next step runs. One frame
+ * is enough: ours is queued after the library's.
+ *
+ * A drop cancels a still-pending `onDrag`, so a frame after every `dragover`
+ * is also what lets `onDrag` be observed. Use {@link dragEventNow} when a test
+ * needs two events in one task, with no frame between them.
+ *
+ * @param target - CSS selector for the event target, or the element itself.
+ * @param type - The drag event type (e.g. `"dragstart"`, `"drop"`).
+ * @param options - Forwarded to `triggerEvent`; must include the shared
+ * `dataTransfer` and finite client coordinates (see {@link centerOf}).
+ */
+export async function dragEvent(
+ target: string | Element,
+ type: string,
+ options?: Record<string, unknown>
+) {
+ await triggerEvent(target as Element, type, options);
+ await new Promise((resolve) => requestAnimationFrame(resolve));
+}
+
+/**
+ * Dispatches one native drag event synchronously, with no frame wait.
+ *
+ * The counterpart of {@link dragEvent} for the timing it hides. The underlying
+ * library reports a hierarchy change synchronously but throttles the drag
+ * update that follows to a frame, and a drop cancels that frame.
+ *
+ * The source likewise defers its consumer callbacks past the drop into the
+ * next runloop task. A test probing either window lands a second event, or a
+ * teardown, in the same task as the first, so nothing here may yield.
+ *
+ * @param target - CSS selector for the event target, or the element itself.
+ * @param type - The drag event type (e.g. `"dragenter"`, `"drop"`).
+ * @param options - The shared `dataTransfer` and finite client coordinates.
+ */
+export function dragEventNow(
+ target: string | Element,
+ type: string,
+ {
+ dataTransfer,
+ clientX,
+ clientY,
+ }: { dataTransfer: DataTransfer } & ClientPoint
+) {
+ const element =
+ typeof target === "string"
+ ? (document.querySelector(target) as Element)
+ : target;
+ element.dispatchEvent(
+ new DragEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ dataTransfer,
+ clientX,
+ clientY,
+ })
+ );
+}
+
+/** How a drag event, or a short run of them, is aimed at one element. */
+interface AimedDragOptions {
+ /** Shared payload every event of one drag must carry. */
+ dataTransfer: DataTransfer;
+
+ /** Coordinates merged over the addressed element's center. */
+ coordinates?: Partial<ClientPoint>;
+}
+
+/**
+ * Begins an element drag on a source and leaves it in flight, without moving
+ * it anywhere.
+ *
+ * `sourceSelector` names the row. A row that scopes its drag to a handle is
+ * registered on the handle, so `dragstart` is dispatched on whichever element
+ * the registration sits on; the coordinates are the row's center either way.
+ *
+ * @param sourceSelector - CSS selector for the source row.
+ * @param options - The shared payload and any coordinate override.
+ */
+export async function startDrag(
+ sourceSelector: string,
+ { dataTransfer, coordinates }: AimedDragOptions
+) {
+ const source = { ...centerOf(sourceSelector), ...coordinates };
+ await dragEvent(registeredElementFor(sourceSelector), "dragstart", {
+ dataTransfer,
+ ...source,
+ });
+}
+
+/**
+ * Brings an in-flight element drag over a target and leaves it hovering,
+ * without dropping, so a caller can assert on state a completed drop would
+ * already have cleared.
+ *
+ * @param targetSelector - CSS selector for the target element.
+ * @param options - The shared payload and any coordinate override.
+ */
+export async function dragOver(
+ targetSelector: string,
+ { dataTransfer, coordinates }: AimedDragOptions
+) {
+ const target = { ...centerOf(targetSelector), ...coordinates };
+ await dragEvent(targetSelector, "dragenter", { dataTransfer, ...target });
+ await dragEvent(targetSelector, "dragover", { dataTransfer, ...target });
+}
+
+/**
+ * Drives a complete element drag from a source to a target: `dragstart`,
+ * `dragenter`, `dragover`, `drop`, `dragend`, each through {@link dragEvent}.
+ *
+ * Coordinates default to each element's center. Override them when the
+ * pointer position matters: a bare center only ever exercises the `after`
+ * branch of a midpoint comparison.
+ *
+ * `sourceSelector` names the row; see {@link startDrag}.
+ *
+ * @param sourceSelector - CSS selector for the source element.
+ * @param targetSelector - CSS selector for the target element.
+ */
+export async function simulateDrag(
+ sourceSelector: string,
+ targetSelector: string,
+ {
+ dataTransfer,
+ sourceCoordinates,
+ targetCoordinates,
+ }: {
+ /** Shared payload every event of one drag must carry. */
+ dataTransfer: DataTransfer;
+
+ /** Coordinates merged over the source element's center. */
+ sourceCoordinates?: Partial<ClientPoint>;
+
+ /** Coordinates merged over the target element's center. */
+ targetCoordinates?: Partial<ClientPoint>;
+ }
+) {
+ assertDragRegistered(sourceSelector, targetSelector);
+ const source = { ...centerOf(sourceSelector), ...sourceCoordinates };
+ const target = { ...centerOf(targetSelector), ...targetCoordinates };
+ await startDrag(sourceSelector, { dataTransfer, coordinates: source });
+ await dragOver(targetSelector, { dataTransfer, coordinates: target });
+ await dragEvent(targetSelector, "drop", { dataTransfer, ...target });
+ await dragEvent(registeredElementFor(sourceSelector), "dragend", {
+ dataTransfer,
+ ...source,
+ });
+}
+
+/**
+ * The element a row's drag registration sits on: the row itself, or its
+ * handle when the row scopes the drag to one.
+ *
+ * The underlying library looks a registration up by the element carrying
+ * `draggable`, so a synthetic `dragstart` aimed anywhere else does nothing.
+ */
+function registeredElementFor(rowSelector: string) {
+ const row = document.querySelector(rowSelector) as Element;
+ if (row.matches('[draggable="true"]')) {
+ return row;
+ }
+ return row.querySelector('[draggable="true"]') ?? row;
+}
+
+/**
+ * Brings an external drag over a target and leaves it hovering there, without
+ * dropping.
+ *
+ * Deliberately no `dragstart`: a drag that began outside the page never fires
+ * one, and its absence is what routes the drag to the external adapter rather
+ * than the element one.
+ *
+ * Stops short of the drop so a caller can assert on state a completed drop
+ * would already have cleared. Use {@link simulateExternalDrag} when the drop
+ * itself is the subject.
+ *
+ * @param targetSelector - CSS selector for the target element.
+ * @param options - The shared payload and any coordinate override.
+ */
+export async function externalDragOver(
+ targetSelector: string,
+ { dataTransfer, coordinates }: AimedDragOptions
+) {
+ assertExternalTargetRegistered(targetSelector);
+ const target = { ...centerOf(targetSelector), ...coordinates };
+ await dragEvent(targetSelector, "dragenter", { dataTransfer, ...target });
+ await dragEvent(targetSelector, "dragover", { dataTransfer, ...target });
+}
+
+/**
+ * Drives a complete external drag onto a target and drops it there; the
+ * external counterpart of {@link simulateDrag}.
+ *
+ * Override the coordinates when the pointer position matters: a bare center
+ * only ever exercises the `after` branch of a midpoint comparison.
+ *
+ * @param targetSelector - CSS selector for the target element.
+ * @param options - The shared payload and any coordinate override.
+ */
+export async function simulateExternalDrag(
+ targetSelector: string,
+ { dataTransfer, coordinates }: AimedDragOptions
+) {
+ const target = { ...centerOf(targetSelector), ...coordinates };
+ await externalDragOver(targetSelector, { dataTransfer, coordinates });
+ await dragEvent(targetSelector, "drop", { dataTransfer, ...target });
+}
+
+/**
+ * Ends any drag the underlying library still considers in flight. A no-op when
+ * nothing is in flight. Call from the global test teardown.
+ *
+ * A drag whose `dragend` / `drop` never reached the library (source torn down
+ * mid-drag, assertion thrown) leaves its global state active, and the next
+ * test's `dragstart` is silently ignored.
+ */
+export function resetDragAndDropForTesting() {
+ // The library listens for `dragend` on `window` (capture) only while a drag
+ // is active, and treats it as a cancel that empties the targets first.
+ const event =
+ typeof DragEvent === "function"
+ ? new DragEvent("dragend", { bubbles: true })
+ : new Event("dragend", { bubbles: true });
+ window.dispatchEvent(event);
+}
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.gjs
new file mode 100644
index 00000000000..d459c3d6e04
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-auto-scroll-test.gjs
@@ -0,0 +1,67 @@
+import { find, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ dragEvent,
+ textTransfer,
+} from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";
+import dDragAndDropAutoScroll from "discourse/ui-kit/modifiers/d-drag-and-drop-auto-scroll";
+import dDragAndDropExternalTarget from "discourse/ui-kit/modifiers/d-drag-and-drop-external-target";
+
+module(
+ "Integration | ui-kit | Modifier | dDragAndDropAutoScroll",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ module("external auto-scroll", function () {
+ /**
+ * Holds a drag near the container's bottom edge across several frames:
+ * auto-scroll runs off its own animation-frame loop and eases in over
+ * time, so a single event moves nothing measurable.
+ */
+ async function hoverNearBottomEdge(selector, dataTransfer) {
+ const { left, bottom, width } = find(selector).getBoundingClientRect();
+ const point = { clientX: left + width / 2, clientY: bottom - 2 };
+
+ await dragEvent(selector, "dragenter", { dataTransfer, ...point });
+ for (let frame = 0; frame < 12; frame++) {
+ await dragEvent(selector, "dragover", { dataTransfer, ...point });
+ }
+ }
+
+ const scroller = <template>
+ <div
+ id="scroller"
+ style="height: 100px; overflow-y: auto"
+ {{dDragAndDropExternalTarget accepts="text"}}
+ {{dDragAndDropAutoScroll accepts=@accepts}}
+ >
+ <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 hoverNearBottomEdge("#scroller", textTransfer());
+
+ assert.true(
+ find("#scroller").scrollTop > 0,
+ "holding a drag against the bottom edge scrolls the container down"
+ );
+ });
+
+ test("external auto-scroll stays off until a consumer asks for it", async function (assert) {
+ await render(<template><scroller /></template>);
+
+ await hoverNearBottomEdge("#scroller", textTransfer());
+
+ assert.strictEqual(
+ find("#scroller").scrollTop,
+ 0,
+ "a container that named no external kinds is not scrolled by one"
+ );
+ });
+ });
+ }
+);
diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-external-target-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-external-target-test.gjs
new file mode 100644
index 00000000000..cc5457db356
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-external-target-test.gjs
@@ -0,0 +1,669 @@
+import { tracked } from "@glimmer/tracking";
+import { find, render, settled, setupOnerror } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ centerOf,
+ dragEvent,
+ externalDragOver,
+ fileTransfer,
+ simulateExternalDrag,
+ textTransfer,
+} from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";
+import dDragAndDropExternalTarget, {
+ registerDragAndDropExternalTarget,
+} from "discourse/ui-kit/modifiers/d-drag-and-drop-external-target";
+
+module(
+ "Integration | ui-kit | Modifier | dDragAndDropExternalTarget",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("registration marker follows the target lifecycle", async function (assert) {
+ const state = new (class {
+ @tracked show = true;
+ })();
+
+ await render(
+ <template>
+ {{#if state.show}}
+ <div
+ id="external-target"
+ {{dDragAndDropExternalTarget accepts="files"}}
+ >external target</div>
+ {{/if}}
+ </template>
+ );
+
+ const target = find("#external-target");
+ assert.true(
+ target.hasAttribute("data-drop-target-external"),
+ "the target is marked while registered"
+ );
+
+ state.show = false;
+ await settled();
+
+ assert.false(
+ target.hasAttribute("data-drop-target-external"),
+ "destroying the target removes its marker"
+ );
+ });
+
+ test("a lit target torn down mid-drag clears its class and mark without a leave", async function (assert) {
+ const leaves = [];
+ const recordLeave = () => leaves.push("leave");
+
+ await render(
+ <template>
+ <div id="ext">ext</div>
+ </template>
+ );
+
+ const cleanup = registerDragAndDropExternalTarget(find("#ext"), () => ({
+ accepts: "text",
+ onDragLeave: recordLeave,
+ }));
+
+ const dataTransfer = textTransfer();
+ await externalDragOver("#ext", { dataTransfer });
+
+ assert
+ .dom("#ext")
+ .hasClass("--drag-over-external", "lit while hovered")
+ .hasAttribute("data-drop-target-external");
+
+ cleanup();
+
+ assert
+ .dom("#ext")
+ .doesNotHaveClass(
+ "--drag-over-external",
+ "the indicator does not outlive the registration"
+ )
+ .doesNotHaveAttribute(
+ "data-drop-target-external",
+ "and neither does the mark"
+ );
+ assert.deepEqual(
+ leaves,
+ [],
+ "a registration that is going away reports no leave to a consumer that is going with it"
+ );
+
+ // The library still has the drag in flight; leaving the window ends it
+ // rather than carrying it into the next test.
+ await dragEvent("#ext", "dragleave", {
+ dataTransfer,
+ ...centerOf("#ext"),
+ });
+ });
+
+ module("external target behaviour", function () {
+ test("hands the consumer a payload it can read without importing the library", async function (assert) {
+ let seen = null;
+ const onDrop = ({ source }) => {
+ seen = {
+ containsFiles: source.containsFiles(),
+ names: source.getFiles().map((file) => file.name),
+ };
+ };
+
+ await render(
+ <template>
+ <div
+ id="ext"
+ {{dDragAndDropExternalTarget accepts="files" onDrop=onDrop}}
+ >ext</div>
+ </template>
+ );
+
+ await simulateExternalDrag("#ext", { dataTransfer: fileTransfer() });
+
+ assert.deepEqual(
+ seen,
+ { containsFiles: true, names: ["a.txt"] },
+ "the decorated source answers about its own payload and returns the files"
+ );
+ });
+
+ test("accepts filters which external kinds engage the target", async function (assert) {
+ const drops = [];
+ const onFilesDrop = () => drops.push("files");
+ const onTextDrop = () => drops.push("text");
+
+ await render(
+ <template>
+ <div
+ id="files-only"
+ {{dDragAndDropExternalTarget accepts="files" onDrop=onFilesDrop}}
+ >files</div>
+ <div
+ id="text-only"
+ {{dDragAndDropExternalTarget accepts="text" onDrop=onTextDrop}}
+ >text</div>
+ </template>
+ );
+
+ await simulateExternalDrag("#files-only", {
+ dataTransfer: textTransfer(),
+ });
+
+ assert.deepEqual(
+ drops,
+ [],
+ "a text drag does not reach a target that only accepts files"
+ );
+
+ await simulateExternalDrag("#text-only", {
+ dataTransfer: textTransfer(),
+ });
+
+ assert.deepEqual(
+ drops,
+ ["text"],
+ "the same drag reaches the target whose kind it matches"
+ );
+ });
+
+ test("a gate that turns false after the last dragover still lands the drop", async function (assert) {
+ let allowed = true;
+ let drops = 0;
+ const canDrop = () => allowed;
+ const onDrop = () => drops++;
+
+ await render(
+ <template>
+ <div
+ id="ext"
+ {{dDragAndDropExternalTarget
+ accepts="files"
+ canDrop=canDrop
+ onDrop=onDrop
+ }}
+ >ext</div>
+ </template>
+ );
+
+ const dataTransfer = fileTransfer();
+ await externalDragOver("#ext", { dataTransfer });
+
+ // Turned off with no dragover left to observe it, so the release still
+ // sees the target the last hover collected.
+ allowed = false;
+ await dragEvent("#ext", "drop", {
+ dataTransfer,
+ ...centerOf("#ext"),
+ });
+
+ assert.strictEqual(
+ drops,
+ 1,
+ "eligibility is sampled while hovering, not re-asked at the release"
+ );
+ });
+
+ test("external drop position drives the same indicator classes the element target uses", async function (assert) {
+ const drops = [];
+ const onDrop = (payload) => drops.push(payload.position);
+
+ await render(
+ <template>
+ <div
+ id="ext"
+ style="height: 100px"
+ {{dDragAndDropExternalTarget
+ accepts="text"
+ axis="vertical"
+ onDrop=onDrop
+ }}
+ >ext</div>
+ </template>
+ );
+
+ const rect = find("#ext").getBoundingClientRect();
+ const dataTransfer = textTransfer();
+
+ await externalDragOver("#ext", {
+ dataTransfer,
+ coordinates: { clientY: rect.top + 5 },
+ });
+
+ assert
+ .dom("#ext")
+ .hasClass("--drag-above", "the indicator marks the upper half")
+ .doesNotHaveClass(
+ "--drag-over-external",
+ "and the positionless hover class is not also applied"
+ );
+
+ const lowerHalf = { clientY: rect.top + rect.height - 5 };
+ await externalDragOver("#ext", {
+ dataTransfer,
+ coordinates: lowerHalf,
+ });
+
+ assert
+ .dom("#ext")
+ .hasClass("--drag-below", "crossing the midpoint swaps the indicator")
+ .doesNotHaveClass(
+ "--drag-above",
+ "rather than accumulating both positions"
+ );
+
+ await dragEvent("#ext", "drop", {
+ dataTransfer,
+ ...centerOf("#ext"),
+ ...lowerHalf,
+ });
+
+ assert.deepEqual(
+ drops,
+ ["after"],
+ "and the drop reports the side the indicator was showing"
+ );
+ });
+
+ test("external drop position honours the horizontal axis", async function (assert) {
+ const drops = [];
+ const onDrop = (payload) => drops.push(payload.position);
+
+ await render(
+ <template>
+ <div
+ id="ext"
+ style="width: 200px"
+ {{dDragAndDropExternalTarget
+ accepts="text"
+ axis="horizontal"
+ onDrop=onDrop
+ }}
+ >ext</div>
+ </template>
+ );
+
+ const rect = find("#ext").getBoundingClientRect();
+ const dataTransfer = textTransfer();
+ const nearLeftEdge = { clientX: rect.left + 5 };
+
+ await externalDragOver("#ext", {
+ dataTransfer,
+ coordinates: nearLeftEdge,
+ });
+
+ assert
+ .dom("#ext")
+ .hasClass("--drag-left", "the indicator names the horizontal side")
+ .doesNotHaveClass(
+ "--drag-above",
+ "and the class comes from the horizontal vocabulary, not the vertical one"
+ );
+
+ await dragEvent("#ext", "drop", {
+ dataTransfer,
+ ...centerOf("#ext"),
+ ...nearLeftEdge,
+ });
+
+ assert.deepEqual(
+ drops,
+ ["before"],
+ "the midpoint is measured along the named axis"
+ );
+ });
+
+ test("external drop position takes a fixed position over the midpoint", async function (assert) {
+ const drops = [];
+ const onDrop = (payload) => drops.push(payload.position);
+
+ await render(
+ <template>
+ <div
+ id="ext"
+ style="height: 100px"
+ {{dDragAndDropExternalTarget
+ accepts="text"
+ position="inside"
+ onDrop=onDrop
+ }}
+ >ext</div>
+ </template>
+ );
+
+ const rect = find("#ext").getBoundingClientRect();
+ const dataTransfer = textTransfer();
+
+ await externalDragOver("#ext", {
+ dataTransfer,
+ coordinates: { clientY: rect.top + 5 },
+ });
+
+ assert
+ .dom("#ext")
+ .hasClass(
+ "--drag-inside",
+ "a fixed position ignores which half the cursor is in"
+ );
+
+ await dragEvent("#ext", "drop", {
+ dataTransfer,
+ clientY: rect.top + 5,
+ clientX: rect.left + 5,
+ });
+
+ assert.deepEqual(drops, ["inside"], "and reports itself on the drop");
+ });
+
+ test("external drop position is null once the drag leaves", async function (assert) {
+ const seen = [];
+ const onDragEnter = (payload) => seen.push(["enter", payload.position]);
+ const onDragLeave = (payload) => seen.push(["leave", payload.position]);
+
+ await render(
+ <template>
+ <div
+ id="ext"
+ style="height: 100px"
+ {{dDragAndDropExternalTarget
+ accepts="text"
+ axis="vertical"
+ onDragEnter=onDragEnter
+ onDragLeave=onDragLeave
+ }}
+ >ext</div>
+ </template>
+ );
+
+ const rect = find("#ext").getBoundingClientRect();
+ const dataTransfer = textTransfer();
+
+ await externalDragOver("#ext", {
+ dataTransfer,
+ coordinates: { clientY: rect.top + 5 },
+ });
+ await dragEvent("#ext", "dragleave", {
+ dataTransfer,
+ ...centerOf("#ext"),
+ });
+
+ assert.deepEqual(
+ seen,
+ [
+ ["enter", "before"],
+ ["leave", null],
+ ],
+ "the position is where a drop would have landed while hovering, and nothing once there is nowhere to land"
+ );
+ assert
+ .dom("#ext")
+ .doesNotHaveClass("--drag-above", "and the indicator is dropped");
+ });
+
+ test("external drop position stays out of the way when neither arg is given", async function (assert) {
+ const drops = [];
+ const onDrop = (payload) => drops.push(payload.position);
+
+ await render(
+ <template>
+ <div
+ id="ext"
+ style="height: 100px"
+ {{dDragAndDropExternalTarget accepts="text" onDrop=onDrop}}
+ >ext</div>
+ </template>
+ );
+
+ const rect = find("#ext").getBoundingClientRect();
+ const dataTransfer = textTransfer();
+
+ await externalDragOver("#ext", {
+ dataTransfer,
+ coordinates: { clientY: rect.top + 5 },
+ });
+
+ assert
+ .dom("#ext")
+ .hasClass(
+ "--drag-over-external",
+ "a target that asked for no position keeps the single hover class"
+ )
+ .doesNotHaveClass(
+ "--drag-above",
+ "rather than being opted into the positional vocabulary"
+ );
+
+ await dragEvent("#ext", "drop", {
+ dataTransfer,
+ clientY: rect.top + 5,
+ clientX: rect.left + 5,
+ });
+
+ assert.deepEqual(
+ drops,
+ [null],
+ "and reports no position, because it was never asked to resolve one"
+ );
+ });
+
+ test("an external target switching between destination and slot mid-hover shows one indicator family", async function (assert) {
+ const state = new (class {
+ @tracked axis = undefined;
+ })();
+
+ await render(
+ <template>
+ <div
+ id="ext"
+ style="height: 100px"
+ {{dDragAndDropExternalTarget accepts="text" axis=state.axis}}
+ >ext</div>
+ </template>
+ );
+
+ const rect = find("#ext").getBoundingClientRect();
+ const dataTransfer = textTransfer();
+ const lowerHalf = {
+ clientX: rect.left + 5,
+ clientY: rect.top + rect.height - 5,
+ };
+
+ await externalDragOver("#ext", {
+ dataTransfer,
+ coordinates: lowerHalf,
+ });
+
+ assert
+ .dom("#ext")
+ .hasClass(
+ "--drag-over-external",
+ "a destination lights its one class"
+ )
+ .doesNotHaveClass("--drag-below");
+
+ state.axis = "vertical";
+ await settled();
+ await dragEvent("#ext", "dragover", { dataTransfer, ...lowerHalf });
+
+ assert
+ .dom("#ext")
+ .hasClass("--drag-below", "a slot lights the positional class")
+ .doesNotHaveClass(
+ "--drag-over-external",
+ "and drops the destination class it had"
+ );
+
+ state.axis = undefined;
+ await settled();
+ await dragEvent("#ext", "dragover", { dataTransfer, ...lowerHalf });
+
+ assert
+ .dom("#ext")
+ .hasClass("--drag-over-external", "back to a destination")
+ .doesNotHaveClass(
+ "--drag-below",
+ "the positional class goes with it"
+ );
+
+ await dragEvent("#ext", "drop", { dataTransfer, ...lowerHalf });
+ });
+ });
+
+ module("an external consumer that throws", function () {
+ const blowUp = () => {
+ throw new Error("external consumer blew up");
+ };
+
+ test("a throwing external getDropEffect is reported and the drop still lands", async function (assert) {
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+
+ const drops = [];
+ const recordDrop = () => drops.push("drop");
+
+ await render(
+ <template>
+ <div
+ id="ext"
+ {{dDragAndDropExternalTarget
+ accepts="text"
+ getDropEffect=blowUp
+ onDrop=recordDrop
+ }}
+ >ext</div>
+ </template>
+ );
+
+ await simulateExternalDrag("#ext", { dataTransfer: textTransfer() });
+
+ assert.deepEqual(
+ drops,
+ ["drop"],
+ "the drop lands without an effect from the consumer"
+ );
+ assert.true(
+ reported.length >= 1,
+ `and the throwing effect gate was raised (${reported.length} seen)`
+ );
+ });
+
+ test("a throwing external onDrag is reported and the drop still lands", async function (assert) {
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+
+ const drops = [];
+ const recordDrop = ({ position }) => drops.push(position);
+
+ await render(
+ <template>
+ <div
+ id="ext"
+ {{dDragAndDropExternalTarget
+ accepts="text"
+ onDrag=blowUp
+ onDrop=recordDrop
+ }}
+ >ext</div>
+ </template>
+ );
+
+ await simulateExternalDrag("#ext", { dataTransfer: textTransfer() });
+
+ assert.deepEqual(drops, [null], "the drop lands");
+ assert.true(
+ reported.length >= 1,
+ `and the throwing drag callback was raised (${reported.length} seen)`
+ );
+ });
+
+ test("a throwing external onDragLeave still clears the indicator and leaves the target usable", async function (assert) {
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+
+ const drops = [];
+ const recordDrop = () => drops.push("drop");
+
+ await render(
+ <template>
+ <div
+ id="ext"
+ {{dDragAndDropExternalTarget
+ accepts="text"
+ onDragLeave=blowUp
+ onDrop=recordDrop
+ }}
+ >ext</div>
+ </template>
+ );
+
+ const dataTransfer = textTransfer();
+ await externalDragOver("#ext", { dataTransfer });
+ assert
+ .dom("#ext")
+ .hasClass("--drag-over-external", "lit while hovered");
+
+ await dragEvent("#ext", "dragleave", {
+ dataTransfer,
+ ...centerOf("#ext"),
+ });
+
+ assert
+ .dom("#ext")
+ .doesNotHaveClass(
+ "--drag-over-external",
+ "the indicator is cleared even though the leave callback threw"
+ );
+ assert.strictEqual(reported.length, 1, "and the throw was raised once");
+
+ await simulateExternalDrag("#ext", { dataTransfer: textTransfer() });
+
+ assert.deepEqual(
+ drops,
+ ["drop"],
+ "and the target still takes a drop afterwards"
+ );
+ });
+
+ test("a throwing external onDragEnter does not cost the target its drop", async function (assert) {
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+
+ const drops = [];
+ const recordDrop = ({ position }) => drops.push(position);
+ const leaves = [];
+ const recordLeave = () => leaves.push("leave");
+
+ await render(
+ <template>
+ <div
+ id="ext"
+ {{dDragAndDropExternalTarget
+ accepts="text"
+ onDragEnter=blowUp
+ onDragLeave=recordLeave
+ onDrop=recordDrop
+ }}
+ >ext</div>
+ </template>
+ );
+
+ await simulateExternalDrag("#ext", { dataTransfer: textTransfer() });
+
+ assert.deepEqual(
+ drops,
+ [null],
+ "the drop still lands (with no position, since the target asked for none)"
+ );
+ assert.deepEqual(
+ leaves,
+ [],
+ "a drop ends the drag without a leave, exactly as when the enter did not throw"
+ );
+ assert.strictEqual(
+ reported.length,
+ 1,
+ "and the throwing enter was raised once"
+ );
+ });
+ });
+ }
+);
diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-monitor-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-monitor-test.gjs
new file mode 100644
index 00000000000..16dd1c497d5
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-monitor-test.gjs
@@ -0,0 +1,120 @@
+import { hash } from "@ember/helper";
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import { simulateDrag } from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";
+import dDragAndDropMonitor from "discourse/ui-kit/modifiers/d-drag-and-drop-monitor";
+import dDragAndDropSource from "discourse/ui-kit/modifiers/d-drag-and-drop-source";
+import dDragAndDropTarget from "discourse/ui-kit/modifiers/d-drag-and-drop-target";
+
+module(
+ "Integration | ui-kit | Modifier | dDragAndDropMonitor",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("observes a matching drag from start to drop", async function (assert) {
+ const events = [];
+
+ const onDragStart = () => events.push("start");
+ const onDrag = () => events.push("drag");
+ const onDrop = () => events.push("drop");
+
+ await render(
+ <template>
+ <div
+ {{dDragAndDropMonitor
+ types="row"
+ onDragStart=onDragStart
+ onDrag=onDrag
+ onDrop=onDrop
+ }}
+ ></div>
+ <div id="src" {{dDragAndDropSource type="row" data=(hash id=1)}}>
+ src
+ </div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ await simulateDrag("#src", "#tgt", { dataTransfer: new DataTransfer() });
+
+ assert.true(events.includes("start"), "onDragStart fired");
+ assert.true(events.includes("drag"), "onDrag fired on move");
+ assert.true(events.includes("drop"), "onDrop fired when the drag ended");
+ });
+
+ test("is type-gated and ignores a non-matching drag", async function (assert) {
+ let fired = false;
+
+ const onDragStart = () => {
+ fired = true;
+ };
+
+ await render(
+ <template>
+ <div
+ {{dDragAndDropMonitor types="card" onDragStart=onDragStart}}
+ ></div>
+ <div id="src" {{dDragAndDropSource type="row" data=(hash id=1)}}>
+ src
+ </div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ await simulateDrag("#src", "#tgt", { dataTransfer: new DataTransfer() });
+
+ assert.false(fired, "a `row` drag does not engage a `card` monitor");
+ });
+
+ test("observes any drag when no types are given", async function (assert) {
+ let started = false;
+
+ const onDragStart = () => {
+ started = true;
+ };
+
+ await render(
+ <template>
+ <div {{dDragAndDropMonitor onDragStart=onDragStart}}></div>
+ <div id="src" {{dDragAndDropSource type="row" data=(hash id=1)}}>
+ src
+ </div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ await simulateDrag("#src", "#tgt", { dataTransfer: new DataTransfer() });
+
+ assert.true(started, "untyped monitor engages on any drag");
+ });
+
+ test("passes the source payload to the callbacks", async function (assert) {
+ let seen = null;
+
+ const onDragStart = ({ source }) => {
+ seen = source.data;
+ };
+
+ await render(
+ <template>
+ <div
+ {{dDragAndDropMonitor types="row" onDragStart=onDragStart}}
+ ></div>
+ <div id="src" {{dDragAndDropSource type="row" data=(hash id=2)}}>
+ src
+ </div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ await simulateDrag("#src", "#tgt", { dataTransfer: new DataTransfer() });
+
+ assert.deepEqual(
+ seen,
+ { type: "row", id: 2 },
+ "the monitor callback receives the source's data"
+ );
+ });
+ }
+);
diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-test.gjs
new file mode 100644
index 00000000000..6a8e349bfee
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-test.gjs
@@ -0,0 +1,3337 @@
+import { tracked } from "@glimmer/tracking";
+import { hash } from "@ember/helper";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import {
+ clearRender,
+ find,
+ render,
+ settled,
+ setupOnerror,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ centerOf,
+ dragEvent,
+ dragEventNow,
+ dragOver,
+ simulateDrag,
+ startDrag,
+} from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";
+import { registerDragAndDropMonitor } from "discourse/ui-kit/modifiers/d-drag-and-drop-monitor";
+import dDragAndDropSource, {
+ registerDragAndDropSource,
+} from "discourse/ui-kit/modifiers/d-drag-and-drop-source";
+import dDragAndDropTarget from "discourse/ui-kit/modifiers/d-drag-and-drop-target";
+
+module("Integration | ui-kit | Modifier | dragAndDrop", function (hooks) {
+ setupRenderingTest(hooks);
+
+ module("marker attribute lifecycle", function () {
+ test("removes every marker when its element is destroyed", async function (assert) {
+ const state = new (class {
+ @tracked show = true;
+ })();
+
+ await render(
+ <template>
+ {{#if state.show}}
+ <div id="source" {{dDragAndDropSource type="row"}}>source</div>
+ <div id="target" {{dDragAndDropTarget accepts="row"}}>target</div>
+ {{/if}}
+ </template>
+ );
+
+ const source = find("#source");
+ const target = find("#target");
+
+ assert.true(
+ source.hasAttribute("data-drag-source"),
+ "the source starts registered"
+ );
+ assert.true(
+ target.hasAttribute("data-drop-target"),
+ "the element target starts registered"
+ );
+ state.show = false;
+ await settled();
+
+ assert.false(
+ source.hasAttribute("data-drag-source"),
+ "destroying the source removes its marker"
+ );
+ assert.false(
+ target.hasAttribute("data-drop-target"),
+ "destroying the element target removes its marker"
+ );
+ });
+
+ test("source marker follows the disabled registration cycle", async function (assert) {
+ const state = new (class {
+ @tracked disabled = false;
+ })();
+
+ await render(
+ <template>
+ <div
+ id="source"
+ {{dDragAndDropSource type="row" disabled=state.disabled}}
+ >source</div>
+ </template>
+ );
+
+ const source = find("#source");
+ assert.true(
+ source.hasAttribute("data-drag-source"),
+ "the enabled source is marked"
+ );
+
+ state.disabled = true;
+ await settled();
+ assert.false(
+ source.hasAttribute("data-drag-source"),
+ "disabling removes the marker from the live element"
+ );
+
+ state.disabled = false;
+ await settled();
+ assert.true(
+ source.hasAttribute("data-drag-source"),
+ "re-enabling restores the marker on the same element"
+ );
+ });
+ });
+
+ test("source + target handshake fires onDrop with source data", async function (assert) {
+ const drops = [];
+ const onDrop = (payload) => drops.push(payload);
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" data=(hash id=1)}}
+ >src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget accepts="row" position="before" onDrop=onDrop}}
+ >tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await simulateDrag("#src", "#tgt", { dataTransfer });
+
+ assert.strictEqual(drops.length, 1, "onDrop fires once");
+ assert.strictEqual(drops[0].position, "before");
+ assert.deepEqual(drops[0].source.data, { type: "row", id: 1 });
+ assert.strictEqual(drops[0].source.type, "row");
+ });
+
+ test("source re-registers when dragHandle arrives after initial registration", async function (assert) {
+ const state = new (class {
+ @tracked showHandle = false;
+ @tracked dragHandle;
+ starts = 0;
+ captureHandle = (element) => (this.dragHandle = element);
+ onDragStart = () => this.starts++;
+ })();
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ dragHandle=state.dragHandle
+ onDragStart=state.onDragStart
+ }}
+ >
+ <span id="body">body</span>
+ {{#if state.showHandle}}
+ <button id="handle" type="button" {{didInsert state.captureHandle}}>
+ handle
+ </button>
+ {{/if}}
+ </div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>target</div>
+ </template>
+ );
+
+ state.showHandle = true;
+ await settled();
+
+ assert.dom("#src").doesNotHaveAttribute("draggable");
+ assert.dom("#handle").hasAttribute("draggable", "true");
+
+ await simulateDrag("#src", "#tgt", {
+ dataTransfer: new DataTransfer(),
+ });
+ assert.strictEqual(
+ state.starts,
+ 1,
+ "after the handle arrives, a drag from it still reaches the source"
+ );
+ });
+
+ test("source re-registers when dragHandle changes identity", async function (assert) {
+ const state = new (class {
+ @tracked showSecondHandle = false;
+ @tracked dragHandle;
+ starts = 0;
+ captureHandle = (element) => (this.dragHandle = element);
+ onDragStart = () => this.starts++;
+ })();
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ dragHandle=state.dragHandle
+ onDragStart=state.onDragStart
+ }}
+ >
+ <button
+ id="first-handle"
+ type="button"
+ {{didInsert state.captureHandle}}
+ >
+ first
+ </button>
+ {{#if state.showSecondHandle}}
+ <button
+ id="second-handle"
+ type="button"
+ {{didInsert state.captureHandle}}
+ >
+ second
+ </button>
+ {{/if}}
+ </div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>target</div>
+ </template>
+ );
+
+ state.showSecondHandle = true;
+ await settled();
+
+ assert.dom("#first-handle").doesNotHaveAttribute("draggable");
+ assert.dom("#second-handle").hasAttribute("draggable", "true");
+
+ await simulateDrag("#src", "#tgt", {
+ dataTransfer: new DataTransfer(),
+ });
+ assert.strictEqual(
+ state.starts,
+ 1,
+ "a drag from the replacement handle reaches the source"
+ );
+ });
+
+ test("source re-registers when dragHandle is removed", async function (assert) {
+ const state = new (class {
+ @tracked dragHandle;
+ @tracked useHandle = true;
+ starts = 0;
+ captureHandle = (element) => (this.dragHandle = element);
+ onDragStart = () => this.starts++;
+ })();
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ dragHandle=(if state.useHandle state.dragHandle)
+ onDragStart=state.onDragStart
+ }}
+ >
+ <span id="body">body</span>
+ <button id="handle" type="button" {{didInsert state.captureHandle}}>
+ handle
+ </button>
+ </div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>target</div>
+ </template>
+ );
+
+ assert.dom("#src").doesNotHaveAttribute("draggable");
+ assert.dom("#handle").hasAttribute("draggable", "true");
+
+ state.useHandle = false;
+ await settled();
+
+ assert.dom("#handle").doesNotHaveAttribute("draggable");
+ assert.dom("#src").hasAttribute("draggable", "true");
+
+ await simulateDrag("#src", "#tgt", {
+ dataTransfer: new DataTransfer(),
+ sourceCoordinates: centerOf("#body"),
+ });
+ assert.strictEqual(
+ state.starts,
+ 1,
+ "after removing the handle, pressing the row body starts a drag"
+ );
+ });
+
+ test("target accepts a self drop by default", async function (assert) {
+ let drops = 0;
+ const onDrop = () => drops++;
+
+ await render(
+ <template>
+ <div
+ id="row"
+ {{dDragAndDropSource type="row"}}
+ {{dDragAndDropTarget accepts="row" onDrop=onDrop}}
+ >row</div>
+ </template>
+ );
+
+ await simulateDrag("#row", "#row", {
+ dataTransfer: new DataTransfer(),
+ });
+
+ assert.strictEqual(drops, 1, "self drops remain enabled when omitted");
+ });
+
+ test("target with acceptsSelf=false rejects its own source element", async function (assert) {
+ let drops = 0;
+ const onDrop = () => drops++;
+
+ await render(
+ <template>
+ <div
+ id="row"
+ {{dDragAndDropSource type="row"}}
+ {{dDragAndDropTarget accepts="row" acceptsSelf=false onDrop=onDrop}}
+ >row</div>
+ </template>
+ );
+
+ await simulateDrag("#row", "#row", {
+ dataTransfer: new DataTransfer(),
+ });
+
+ assert.strictEqual(drops, 0, "the target refuses its own source element");
+ });
+
+ test("a handled row with acceptsSelf=false refuses its own body, and a target reads the row as source.element", async function (assert) {
+ const drops = [];
+ const recordDrop = ({ source }) => drops.push(source.element);
+ const state = new (class {
+ @tracked dragHandle;
+ captureHandle = (element) => (this.dragHandle = element);
+ })();
+
+ await render(
+ <template>
+ <div
+ id="row"
+ {{dDragAndDropSource type="row" dragHandle=state.dragHandle}}
+ {{dDragAndDropTarget
+ accepts="row"
+ acceptsSelf=false
+ onDrop=recordDrop
+ }}
+ >
+ <button id="grip" type="button" {{didInsert state.captureHandle}}>
+ grip
+ </button>
+ </div>
+ <div id="other" {{dDragAndDropTarget accepts="row" onDrop=recordDrop}}>
+ other
+ </div>
+ </template>
+ );
+
+ await simulateDrag("#row", "#row", { dataTransfer: new DataTransfer() });
+ assert.deepEqual(
+ drops,
+ [],
+ "the row refuses a drop of itself even though the grip is what was registered"
+ );
+
+ await simulateDrag("#row", "#other", { dataTransfer: new DataTransfer() });
+ assert.deepEqual(
+ drops,
+ [find("#row")],
+ "another target is handed the row, not the grip"
+ );
+ });
+
+ test("source toggles --dragging during the drag", async function (assert) {
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" data=(hash id=1)}}
+ >src</div>
+ </template>
+ );
+
+ assert
+ .dom("#src")
+ .hasAttribute(
+ "data-drag-source",
+ "",
+ "the style hook is present for the whole registration, not only mid-drag"
+ );
+
+ const dataTransfer = new DataTransfer();
+ await dragEvent("#src", "dragstart", { dataTransfer, ...centerOf("#src") });
+ assert.dom("#src").hasClass("--dragging");
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+ assert.dom("#src").doesNotHaveClass("--dragging");
+ });
+
+ module("source end callbacks", function () {
+ test("abandoned drag defers onDragEnd without onDrop", async function (assert) {
+ const calls = [];
+ let dragEndPayload;
+ const onDragEnd = (payload) => {
+ dragEndPayload = payload;
+ calls.push("onDragEnd");
+ };
+ const onDrop = () => calls.push("onDrop");
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ data=(hash id=1)
+ onDragEnd=onDragEnd
+ onDrop=onDrop
+ }}
+ >src</div>
+ </template>
+ );
+
+ find("#src").addEventListener("dragend", () =>
+ calls.push("native dragend")
+ );
+
+ const dataTransfer = new DataTransfer();
+ await dragEvent("#src", "dragstart", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+ await dragEvent("#src", "dragend", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+
+ assert.deepEqual(
+ {
+ calls,
+ sourceData: dragEndPayload?.source.data ?? null,
+ hasSourceElement: dragEndPayload?.source.element === find("#src"),
+ dropTargetCount:
+ dragEndPayload?.location.current.dropTargets.length ?? null,
+ },
+ {
+ calls: ["native dragend", "onDragEnd"],
+ sourceData: { type: "row", id: 1 },
+ hasSourceElement: true,
+ dropTargetCount: 0,
+ },
+ "an abandoned drag defers onDragEnd with its snapshot and does not fire onDrop"
+ );
+ });
+
+ test("landed drag defers onDragEnd before onDrop with the same payload", async function (assert) {
+ const calls = [];
+ const onDragEnd = (payload) => calls.push({ name: "onDragEnd", payload });
+ const onDrop = (payload) => calls.push({ name: "onDrop", payload });
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ data=(hash id=1)
+ onDragEnd=onDragEnd
+ onDrop=onDrop
+ }}
+ >src</div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>target</div>
+ </template>
+ );
+
+ find("#tgt").addEventListener("drop", () =>
+ calls.push({ name: "native drop" })
+ );
+
+ await simulateDrag("#src", "#tgt", {
+ dataTransfer: new DataTransfer(),
+ });
+
+ const dragEndPayload = calls.find(
+ ({ name }) => name === "onDragEnd"
+ )?.payload;
+ const dropPayload = calls.find(({ name }) => name === "onDrop")?.payload;
+
+ assert.deepEqual(
+ {
+ calls: calls.map(({ name }) => name),
+ sharesSource: dragEndPayload?.source === dropPayload?.source,
+ sharesLocation: dragEndPayload?.location === dropPayload?.location,
+ sourceData: dragEndPayload?.source.data ?? null,
+ },
+ {
+ calls: ["native drop", "onDragEnd", "onDrop"],
+ sharesSource: true,
+ sharesLocation: true,
+ sourceData: { type: "row", id: 1 },
+ },
+ "a landed drag defers onDragEnd before onDrop with the same snapshot"
+ );
+ });
+ });
+
+ test("smart row mode resolves position from cursor midpoint", async function (assert) {
+ const drops = [];
+ const onDrop = (payload) => drops.push(payload);
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" data=(hash id=1)}}
+ >src</div>
+ <div
+ id="tgt"
+ style="height: 100px"
+ {{dDragAndDropTarget accepts="row" onDrop=onDrop}}
+ >tgt</div>
+ </template>
+ );
+
+ const rect = find("#tgt").getBoundingClientRect();
+
+ await simulateDrag("#src", "#tgt", {
+ dataTransfer: new DataTransfer(),
+ targetCoordinates: { clientY: rect.top + 5 },
+ });
+ await simulateDrag("#src", "#tgt", {
+ dataTransfer: new DataTransfer(),
+ targetCoordinates: { clientY: rect.top + rect.height - 5 },
+ });
+
+ assert.deepEqual(
+ drops.map(({ position }) => position),
+ ["before", "after"],
+ "a drop lands before or after the target depending on which side of its midpoint the cursor is"
+ );
+ });
+
+ test("a horizontal target measures the midpoint along x and lights the side class", async function (assert) {
+ const drops = [];
+ const onDrop = (payload) => drops.push(payload.position);
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="col" data=(hash id=1)}}
+ >src</div>
+ <div
+ id="tgt"
+ style="width: 200px; height: 20px"
+ {{dDragAndDropTarget accepts="col" axis="horizontal" onDrop=onDrop}}
+ >tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ const rect = find("#tgt").getBoundingClientRect();
+ // Deep in the vertical lower half, so a target still measuring y reads
+ // "after" and lights `--drag-below` instead.
+ const nearLeftEdge = {
+ clientX: rect.left + 5,
+ clientY: rect.top + rect.height - 2,
+ };
+
+ await dragEvent("#src", "dragstart", { dataTransfer, ...centerOf("#src") });
+ await dragEvent("#tgt", "dragenter", { dataTransfer, ...nearLeftEdge });
+ await dragEvent("#tgt", "dragover", { dataTransfer, ...nearLeftEdge });
+
+ assert
+ .dom("#tgt")
+ .hasClass("--drag-left", "the indicator names the horizontal side");
+ assert.dom("#tgt").doesNotHaveClass("--drag-below");
+
+ await dragEvent("#tgt", "drop", { dataTransfer, ...nearLeftEdge });
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+
+ assert.deepEqual(drops, ["before"], "the midpoint is measured along x");
+ });
+
+ test("a horizontal target in RTL reports the logical side and lights the physical one", async function (assert) {
+ const drops = [];
+ const onDrop = (payload) => drops.push(payload.position);
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="col" data=(hash id=1)}}
+ >src</div>
+ <div
+ id="tgt"
+ style="width: 200px; height: 20px; direction: rtl"
+ {{dDragAndDropTarget accepts="col" axis="horizontal" onDrop=onDrop}}
+ >tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ const rect = find("#tgt").getBoundingClientRect();
+ const nearLeftEdge = {
+ clientX: rect.left + 5,
+ clientY: rect.top + rect.height / 2,
+ };
+
+ await dragEvent("#src", "dragstart", { dataTransfer, ...centerOf("#src") });
+ await dragEvent("#tgt", "dragenter", { dataTransfer, ...nearLeftEdge });
+ await dragEvent("#tgt", "dragover", { dataTransfer, ...nearLeftEdge });
+
+ assert
+ .dom("#tgt")
+ .hasClass("--drag-left", "the line stays on the side under the pointer");
+ assert.dom("#tgt").doesNotHaveClass("--drag-right");
+
+ await dragEvent("#tgt", "drop", { dataTransfer, ...nearLeftEdge });
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+
+ assert.deepEqual(
+ drops,
+ ["after"],
+ "in a right-to-left row the left half comes after the midpoint in reading order"
+ );
+ });
+
+ test("a drop before the first drag frame still resolves the position against the row's direction", async function (assert) {
+ const drops = [];
+ const enters = [];
+ const onDrop = (payload) => drops.push(payload.position);
+ const onDragEnter = () => enters.push("enter");
+
+ await render(
+ <template>
+ <div
+ id="tgt"
+ style="width: 200px; height: 40px; direction: rtl"
+ {{dDragAndDropTarget
+ accepts="col"
+ axis="horizontal"
+ onDrop=onDrop
+ onDragEnter=onDragEnter
+ }}
+ >
+ <div id="src" {{dDragAndDropSource type="col" data=(hash id=1)}}>
+ src
+ </div>
+ </div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ const rect = find("#tgt").getBoundingClientRect();
+ const nearLeftEdge = {
+ clientX: rect.left + 5,
+ clientY: rect.top + rect.height / 2,
+ };
+
+ // The drag starts inside the target, so the target is entered only on the
+ // first drag frame; a drop that lands before that frame skips the enter.
+ await dragEvent("#src", "dragstart", { dataTransfer, ...centerOf("#src") });
+ dragEventNow("#tgt", "dragover", { dataTransfer, ...nearLeftEdge });
+ dragEventNow("#tgt", "drop", { dataTransfer, ...nearLeftEdge });
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+
+ assert.deepEqual(
+ enters,
+ [],
+ "control: the target was never entered before the drop"
+ );
+ assert.deepEqual(
+ drops,
+ ["after"],
+ "the position is read against the row's direction even before the first drag frame"
+ );
+ });
+
+ test("nested targets: the innermost accepting target wins the drop", async function (assert) {
+ const events = [];
+ const hierarchies = [];
+ const onOuterDrop = () => events.push("outer");
+ const onInnerDrop = ({ location }) => {
+ events.push("inner");
+ hierarchies.push(location.current.dropTargets.length);
+ };
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" data=(hash id=1)}}
+ >src</div>
+ <div
+ id="outer"
+ {{dDragAndDropTarget
+ accepts="row"
+ position="inside"
+ onDrop=onOuterDrop
+ }}
+ >
+ outer
+ <div
+ id="inner"
+ {{dDragAndDropTarget
+ accepts="row"
+ position="before"
+ onDrop=onInnerDrop
+ }}
+ >inner</div>
+ </div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await simulateDrag("#src", "#inner", { dataTransfer });
+
+ assert.deepEqual(
+ events,
+ ["inner"],
+ "only the deepest accepted target receives the drop"
+ );
+ assert.deepEqual(
+ hierarchies,
+ [2],
+ "while the ancestor stays in the settled hierarchy the drop reports"
+ );
+ });
+
+ test("target arg changes reach the registered closure", async function (assert) {
+ const state = new (class {
+ @tracked accepted = "row";
+ @tracked dropped = null;
+ handleDrop = (payload) => (this.dropped = payload.source.type);
+ })();
+
+ await render(
+ <template>
+ <div
+ id="src-row"
+ {{dDragAndDropSource type="row" data=(hash id=1)}}
+ >src-row</div>
+ <div
+ id="src-card"
+ {{dDragAndDropSource type="card" data=(hash id=2)}}
+ >src-card</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget accepts=state.accepted onDrop=state.handleDrop}}
+ >tgt</div>
+ </template>
+ );
+
+ let dataTransfer = new DataTransfer();
+ await simulateDrag("#src-row", "#tgt", { dataTransfer });
+ assert.strictEqual(
+ state.dropped,
+ "row",
+ "drops the type currently in `accepts`"
+ );
+
+ state.accepted = "card";
+ state.dropped = null;
+ await settled();
+
+ dataTransfer = new DataTransfer();
+ await simulateDrag("#src-row", "#tgt", { dataTransfer });
+ assert.strictEqual(
+ state.dropped,
+ null,
+ "after arg update, the old accepted type is rejected"
+ );
+
+ dataTransfer = new DataTransfer();
+ await simulateDrag("#src-card", "#tgt", { dataTransfer });
+ assert.strictEqual(
+ state.dropped,
+ "card",
+ "after arg update, the new accepted type fires onDrop"
+ );
+ });
+
+ test("the service tracks the element drag first-hand", async function (assert) {
+ // Looked up before the drag: the service registers its own monitor when it
+ // is first instantiated, so a later lookup would miss this drag.
+ const dnd = this.owner.lookup("service:drag-and-drop");
+
+ await render(
+ <template>
+ <div id="src" {{dDragAndDropSource type="row" data=(hash id=1)}}>
+ src
+ </div>
+ </template>
+ );
+
+ assert.false(dnd.isDragging, "no drag in flight before dragstart");
+
+ const dataTransfer = new DataTransfer();
+ await dragEvent("#src", "dragstart", { dataTransfer, ...centerOf("#src") });
+
+ assert.true(dnd.isDragging, "isDragging is true during the drag");
+ assert.true(dnd.accepts("row"), "accepts the in-flight type");
+ assert.false(dnd.accepts("card"), "rejects a foreign type");
+ assert.strictEqual(dnd.currentDrag.type, "row", "currentDrag carries type");
+ assert.deepEqual(
+ dnd.currentDrag.data,
+ { type: "row", id: 1 },
+ "currentDrag.data carries the source payload"
+ );
+ assert.strictEqual(
+ dnd.currentDrag.element,
+ document.querySelector("#src"),
+ "currentDrag.element is the source element"
+ );
+
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+
+ assert.strictEqual(dnd.currentDrag, null, "cleared once the drag ends");
+ assert.false(dnd.isDragging, "isDragging is false after the drag");
+ });
+
+ test("currentDrag identity is stable within a drag (one object per drag)", async function (assert) {
+ const dnd = this.owner.lookup("service:drag-and-drop");
+
+ await render(
+ <template>
+ <div id="src" {{dDragAndDropSource type="row" data=(hash id=1)}}>
+ src
+ </div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await dragEvent("#src", "dragstart", { dataTransfer, ...centerOf("#src") });
+ const first = dnd.currentDrag;
+ await dragEvent("#src", "dragover", { dataTransfer, ...centerOf("#src") });
+ assert.strictEqual(
+ dnd.currentDrag,
+ first,
+ "the reference is unchanged across drag moves"
+ );
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+ });
+
+ module(
+ "the discriminator is the primitive's, not the payload's",
+ function () {
+ test("a `type` key on the payload does not change what a target accepts", async function (assert) {
+ const drops = [];
+ const onDrop = ({ source }) => drops.push(source.type);
+ const payload = { id: 1, type: "something-else" };
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" data=payload}}
+ >src</div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row" onDrop=onDrop}}>
+ tgt
+ </div>
+ </template>
+ );
+
+ await simulateDrag("#src", "#tgt", {
+ dataTransfer: new DataTransfer(),
+ });
+
+ assert.deepEqual(
+ drops,
+ ["row"],
+ "the declared type wins, so the target still matches and reports it"
+ );
+ });
+ }
+ );
+
+ module("a torn-down source drops its deferred callbacks", function () {
+ test("destroying the modifier before the runloop flushes cancels them", async function (assert) {
+ const calls = [];
+ const state = new (class {
+ @tracked rendered = true;
+ })();
+ const onDragEnd = () => calls.push("dragEnd");
+ const onDrop = () => calls.push("drop");
+
+ await render(
+ <template>
+ {{#if state.rendered}}
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ onDragEnd=onDragEnd
+ onDrop=onDrop
+ }}
+ >src</div>
+ {{/if}}
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+
+ // Torn down in the same task as the drop, before the deferred callbacks flush.
+ dragEventNow("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ state.rendered = false;
+ await settled();
+
+ assert.deepEqual(
+ calls,
+ [],
+ "a destroyed source runs no consumer callback against it"
+ );
+ });
+
+ test("re-registering the modifier before the runloop flushes keeps them", async function (assert) {
+ const calls = [];
+ const state = new (class {
+ @tracked disabled = false;
+ })();
+ const onDragEnd = () => calls.push("dragEnd");
+ const onDrop = () => calls.push("drop");
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ disabled=state.disabled
+ onDragEnd=onDragEnd
+ onDrop=onDrop
+ }}
+ >src</div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+
+ dragEventNow("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ state.disabled = true;
+ await settled();
+
+ assert.deepEqual(
+ calls,
+ ["dragEnd", "drop"],
+ "a source that merely re-registered still reports the drop it was in the middle of"
+ );
+ });
+
+ test("a source disabled mid-drag still reports how that drag ended", async function (assert) {
+ const calls = [];
+ const state = new (class {
+ @tracked disabled = false;
+ })();
+ const onDragEnd = () => calls.push("dragEnd");
+ const onDrop = () => calls.push("drop");
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ disabled=state.disabled
+ onDragEnd=onDragEnd
+ onDrop=onDrop
+ }}
+ >src</div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await dragEvent("#src", "dragstart", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+ await dragEvent("#tgt", "dragenter", {
+ dataTransfer,
+ ...centerOf("#tgt"),
+ });
+
+ state.disabled = true;
+ await settled();
+
+ await dragEvent("#tgt", "dragover", {
+ dataTransfer,
+ ...centerOf("#tgt"),
+ });
+ await dragEvent("#tgt", "drop", {
+ dataTransfer,
+ ...centerOf("#tgt"),
+ });
+
+ assert.deepEqual(
+ calls,
+ ["dragEnd", "drop"],
+ "the consumer is still told how its drag finished, as it is promised for every drag"
+ );
+ });
+
+ test("a source re-enabled mid-drag leaves only one registration behind", async function (assert) {
+ // White-box: a duplicate registration is only visible through the
+ // library's dev-only warning, so that is what is asserted on.
+ const warn = sinon.stub(console, "warn");
+ const state = new (class {
+ @tracked disabled = false;
+ })();
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" disabled=state.disabled}}
+ >src</div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await dragEvent("#src", "dragstart", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+
+ state.disabled = true;
+ await settled();
+ state.disabled = false;
+ await settled();
+
+ const duplicate = warn
+ .getCalls()
+ .some((call) =>
+ String(call.args[0]).includes("already registered a `draggable`")
+ );
+
+ assert.false(
+ duplicate,
+ "the element carries one registration, not two competing for the same drag"
+ );
+ });
+
+ test("a detached registration keeps its scheduled dispatch and reports it outstanding until it fires", async function (assert) {
+ const calls = [];
+ const args = {
+ type: "row",
+ onDragEnd: () => calls.push("dragEnd"),
+ onDrop: () => calls.push("drop"),
+ };
+
+ await render(
+ <template>
+ <div id="src">src</div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ const release = registerDragAndDropSource(find("#src"), () => args);
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+
+ dragEventNow("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+
+ const work = release({ cancelPending: false });
+
+ assert.true(
+ work.outstanding(),
+ "a dispatch is still scheduled, so a holder has to keep it"
+ );
+
+ assert.strictEqual(
+ work.reclaim(),
+ null,
+ "a finished drag leaves nothing to reclaim"
+ );
+ await settled();
+
+ assert.deepEqual(
+ calls,
+ ["dragEnd", "drop"],
+ "being replaced does not cost the consumer the drag it had already completed"
+ );
+ assert.false(
+ work.outstanding(),
+ "and once it has fired the work reports itself finished, so a holder can let go"
+ );
+ });
+
+ test("abandoning a detached source drops the callbacks it still owes", async function (assert) {
+ const calls = [];
+ const args = {
+ type: "row",
+ onDragEnd: () => calls.push("dragEnd"),
+ onDrop: () => calls.push("drop"),
+ };
+
+ await render(
+ <template>
+ <div id="src">src</div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ const release = registerDragAndDropSource(find("#src"), () => args);
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+
+ dragEventNow("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+
+ const work = release({ cancelPending: false });
+ assert.strictEqual(
+ typeof work?.abandon,
+ "function",
+ "keeping the dispatch hands back a way to reach it"
+ );
+
+ work.abandon();
+ await settled();
+
+ assert.deepEqual(
+ calls,
+ [],
+ "a consumer that is gone is not called for the drag it completed"
+ );
+ });
+
+ test("a source disabled and re-enabled mid-drag still reports how that drag ended", async function (assert) {
+ const calls = [];
+ const state = new (class {
+ @tracked disabled = false;
+ })();
+ const onDragEnd = () => calls.push("dragEnd");
+ const onDrop = () => calls.push("drop");
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ disabled=state.disabled
+ onDragEnd=onDragEnd
+ onDrop=onDrop
+ }}
+ >src</div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await dragEvent("#src", "dragstart", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+ await dragEvent("#tgt", "dragenter", {
+ dataTransfer,
+ ...centerOf("#tgt"),
+ });
+
+ state.disabled = true;
+ await settled();
+ state.disabled = false;
+ await settled();
+
+ assert
+ .dom("#src")
+ .hasClass(
+ "--dragging",
+ "the drag in flight keeps its mark across the disable and re-enable"
+ );
+
+ await dragEvent("#tgt", "dragover", {
+ dataTransfer,
+ ...centerOf("#tgt"),
+ });
+ await dragEvent("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+
+ assert.deepEqual(
+ calls,
+ ["dragEnd", "drop"],
+ "replacing the registration mid-drag does not cost the consumer the end of it"
+ );
+ });
+
+ test("a source re-enabled between the drop and its deferred dispatch keeps its registration for the next drag", async function (assert) {
+ const calls = [];
+ const state = new (class {
+ @tracked disabled = false;
+ })();
+ const onDragEnd = () => calls.push("dragEnd");
+ const onDrop = () => calls.push("drop");
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ disabled=state.disabled
+ onDragEnd=onDragEnd
+ onDrop=onDrop
+ }}
+ >src</div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+ state.disabled = true;
+ await settled();
+
+ dragEventNow("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ state.disabled = false;
+ await settled();
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+
+ assert.deepEqual(
+ calls,
+ ["dragEnd", "drop"],
+ "the first drag reports once"
+ );
+ assert
+ .dom("#src")
+ .hasAttribute("data-drag-source", "", "and the row stays registered");
+
+ await simulateDrag("#src", "#tgt", { dataTransfer: new DataTransfer() });
+
+ assert.deepEqual(
+ calls,
+ ["dragEnd", "drop", "dragEnd", "drop"],
+ "so the next drag from the reclaimed registration reports too"
+ );
+ });
+
+ test("a source whose handle changes identity mid-drag still reports how that drag ended", async function (assert) {
+ const calls = [];
+ const state = new (class {
+ @tracked useSecondHandle = false;
+ @tracked dragHandle;
+ captureHandle = (element) => (this.dragHandle = element);
+ onDragEnd = () => calls.push("dragEnd");
+ onDrop = () => calls.push("drop");
+ })();
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ dragHandle=state.dragHandle
+ onDragEnd=state.onDragEnd
+ onDrop=state.onDrop
+ }}
+ >
+ {{#if state.useSecondHandle}}
+ <button
+ id="second-handle"
+ type="button"
+ {{didInsert state.captureHandle}}
+ >second</button>
+ {{else}}
+ <button
+ id="first-handle"
+ type="button"
+ {{didInsert state.captureHandle}}
+ >first</button>
+ {{/if}}
+ </div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await dragEvent("#first-handle", "dragstart", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+ await dragEvent("#tgt", "dragenter", {
+ dataTransfer,
+ ...centerOf("#tgt"),
+ });
+ await dragEvent("#tgt", "dragover", {
+ dataTransfer,
+ ...centerOf("#tgt"),
+ });
+
+ state.useSecondHandle = true;
+ await settled();
+
+ assert
+ .dom("#src")
+ .hasClass("--dragging", "the drag in flight keeps its mark");
+
+ await dragEvent("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ await settled();
+
+ assert.deepEqual(
+ calls,
+ ["dragEnd", "drop"],
+ "the swap does not cost the consumer the end of its drag"
+ );
+ });
+
+ test("a source disabled mid-drag and then destroyed drops its callbacks", async function (assert) {
+ const calls = [];
+ const state = new (class {
+ @tracked disabled = false;
+ @tracked rendered = true;
+ })();
+ const onDragEnd = () => calls.push("dragEnd");
+ const onDrop = () => calls.push("drop");
+
+ await render(
+ <template>
+ {{#if state.rendered}}
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ disabled=state.disabled
+ onDragEnd=onDragEnd
+ onDrop=onDrop
+ }}
+ >src</div>
+ {{/if}}
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+
+ state.disabled = true;
+ await settled();
+
+ // Destroyed in the same task as the drop, before its deferred callbacks flush.
+ dragEventNow("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ state.rendered = false;
+ await settled();
+
+ assert.deepEqual(
+ calls,
+ [],
+ "a destroyed consumer runs no callback for the drag its registration was keeping"
+ );
+ });
+ });
+
+ module("a drag held over nothing", function () {
+ /**
+ * Dispatches a `dragover` and hands the event back so a test can read
+ * `defaultPrevented`, which is what tells the browser the drag was claimed.
+ *
+ * `dataTransfer.dropEffect` is not readable here: a synthetic drag leaves
+ * it at `"none"` however a target sets it.
+ */
+ async function dragOverAndReturnEvent(selector, dataTransfer) {
+ const event = new DragEvent("dragover", {
+ bubbles: true,
+ cancelable: true,
+ dataTransfer,
+ ...centerOf(selector),
+ });
+ find(selector).dispatchEvent(event);
+ await new Promise((resolve) => requestAnimationFrame(resolve));
+ return event;
+ }
+
+ test("a sourced drag claims the space no target wants", async function (assert) {
+ await render(
+ <template>
+ <div id="row" {{dDragAndDropSource type="row"}}>row</div>
+ <div id="nowhere">not a drop target</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await dragEvent("#row", "dragstart", {
+ dataTransfer,
+ ...centerOf("#row"),
+ });
+
+ const event = await dragOverAndReturnEvent("#nowhere", dataTransfer);
+
+ assert.true(
+ event.defaultPrevented,
+ "the drag answers for itself over dead space, so the browser stops offering to copy something it has no way to take"
+ );
+ });
+ });
+
+ module("what a drag permits", function () {
+ /**
+ * A real `DataTransfer` whose `effectAllowed` keeps what is written to it.
+ *
+ * The native setter is a no-op on a constructed `DataTransfer`, so a
+ * synthetic event silently discards every write. An own property shadows
+ * the accessor and leaves the rest of the object real.
+ */
+ function recordingTransfer(effectAllowed = "none") {
+ const dataTransfer = new DataTransfer();
+ Object.defineProperty(dataTransfer, "effectAllowed", {
+ value: effectAllowed,
+ writable: true,
+ configurable: true,
+ });
+ return dataTransfer;
+ }
+
+ test("a sourced drag permits a move, and nothing else", async function (assert) {
+ await render(
+ <template>
+ <div id="row" {{dDragAndDropSource type="row"}}>row</div>
+ </template>
+ );
+
+ const dataTransfer = recordingTransfer();
+ await dragEvent("#row", "dragstart", {
+ dataTransfer,
+ ...centerOf("#row"),
+ });
+
+ assert.strictEqual(
+ dataTransfer.effectAllowed,
+ "move",
+ "the drag says what it permits, so the pointer stops carrying the browser's standing offer to copy"
+ );
+ });
+
+ test("a source can permit a copy as well", async function (assert) {
+ await render(
+ <template>
+ <div
+ id="row"
+ {{dDragAndDropSource type="row" effectAllowed="copyMove"}}
+ >row</div>
+ </template>
+ );
+
+ const dataTransfer = recordingTransfer();
+ await dragEvent("#row", "dragstart", {
+ dataTransfer,
+ ...centerOf("#row"),
+ });
+
+ assert.strictEqual(
+ dataTransfer.effectAllowed,
+ "copyMove",
+ "a source whose drop duplicates rather than relocates keeps the copy available to its targets"
+ );
+ });
+
+ test("the innermost source is the one that answers", async function (assert) {
+ await render(
+ <template>
+ <div id="outer" {{dDragAndDropSource type="outer"}}>
+ <div
+ id="inner"
+ {{dDragAndDropSource type="inner" effectAllowed="copyMove"}}
+ >inner</div>
+ </div>
+ </template>
+ );
+
+ const dataTransfer = recordingTransfer();
+ await dragEvent("#inner", "dragstart", {
+ dataTransfer,
+ ...centerOf("#inner"),
+ });
+
+ assert.strictEqual(
+ dataTransfer.effectAllowed,
+ "copyMove",
+ "a drag begun on a nested source passes through its ancestor on the way out, which must not answer over it"
+ );
+ });
+
+ test("a source still registered keeps answering after a sibling detaches", async function (assert) {
+ const state = new (class {
+ @tracked disabled = false;
+ })();
+
+ await render(
+ <template>
+ <div
+ id="going"
+ {{dDragAndDropSource type="going" disabled=state.disabled}}
+ >going</div>
+ <div id="staying" {{dDragAndDropSource type="staying"}}>staying</div>
+ </template>
+ );
+
+ state.disabled = true;
+ await settled();
+
+ const dataTransfer = recordingTransfer();
+ await dragEvent("#staying", "dragstart", {
+ dataTransfer,
+ ...centerOf("#staying"),
+ });
+
+ assert.strictEqual(
+ dataTransfer.effectAllowed,
+ "move",
+ "one source going away takes only its own share of the shared listener"
+ );
+ });
+
+ test("the last source to go takes the shared listener with it", async function (assert) {
+ // White-box, because the only thing a leak costs is an idle listener and
+ // a map entry per registration, nothing a drag can observe.
+ const state = new (class {
+ @tracked disabled = false;
+ })();
+
+ await render(
+ <template>
+ <div
+ id="row"
+ {{dDragAndDropSource type="row" disabled=state.disabled}}
+ >row</div>
+ </template>
+ );
+
+ const released = sinon.spy(window, "removeEventListener");
+ state.disabled = true;
+ await settled();
+
+ assert.true(
+ released.calledWith("dragstart", sinon.match.func, { capture: true }),
+ "nothing stays bound to a page with no drag sources left on it"
+ );
+ });
+
+ module("registration ownership across a handle change", function () {
+ test("a handle swapped mid-drag leaves the row registered and declaring its effect", async function (assert) {
+ const state = new (class {
+ @tracked useSecondHandle = false;
+ @tracked dragHandle;
+ captureHandle = (element) => (this.dragHandle = element);
+ })();
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" dragHandle=state.dragHandle}}
+ >
+ {{#if state.useSecondHandle}}
+ <button
+ id="second-handle"
+ type="button"
+ {{didInsert state.captureHandle}}
+ >second</button>
+ {{else}}
+ <button
+ id="first-handle"
+ type="button"
+ {{didInsert state.captureHandle}}
+ >first</button>
+ {{/if}}
+ </div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await dragEvent("#first-handle", "dragstart", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+ await dragEvent("#tgt", "dragenter", {
+ dataTransfer,
+ ...centerOf("#tgt"),
+ });
+
+ state.useSecondHandle = true;
+ await settled();
+
+ await dragEvent("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ await dragEvent("#src", "dragend", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+ await settled();
+
+ assert
+ .dom("#src")
+ .hasAttribute(
+ "data-drag-source",
+ "",
+ "the replaced registration's teardown does not strip the mark the live one owns"
+ );
+
+ const second = recordingTransfer();
+ await dragEvent("#second-handle", "dragstart", {
+ dataTransfer: second,
+ ...centerOf("#src"),
+ });
+ assert.strictEqual(
+ second.effectAllowed,
+ "move",
+ "and the live registration still declares what a drag from the new handle permits"
+ );
+ await dragEvent("#src", "dragend", {
+ dataTransfer: second,
+ ...centerOf("#src"),
+ });
+
+ const released = sinon.spy(window, "removeEventListener");
+ await clearRender();
+ assert.true(
+ released.calledWith("dragstart", sinon.match.func, { capture: true }),
+ "destroying the source unbinds the shared listener: the swap left no phantom registration counted"
+ );
+ });
+
+ test("a handle swapped mid-drag and then disabled keeps the row marked until the drag it started ends", async function (assert) {
+ const state = new (class {
+ @tracked useSecondHandle = false;
+ @tracked disabled = false;
+ @tracked dragHandle;
+ captureHandle = (element) => (this.dragHandle = element);
+ })();
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ dragHandle=state.dragHandle
+ disabled=state.disabled
+ }}
+ >
+ {{#if state.useSecondHandle}}
+ <button
+ id="second-handle"
+ type="button"
+ {{didInsert state.captureHandle}}
+ >second</button>
+ {{else}}
+ <button
+ id="first-handle"
+ type="button"
+ {{didInsert state.captureHandle}}
+ >first</button>
+ {{/if}}
+ </div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await dragEvent("#first-handle", "dragstart", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+ await dragEvent("#tgt", "dragenter", {
+ dataTransfer,
+ ...centerOf("#tgt"),
+ });
+
+ state.useSecondHandle = true;
+ await settled();
+ state.disabled = true;
+ await settled();
+
+ assert
+ .dom("#src")
+ .hasAttribute(
+ "data-drag-source",
+ "",
+ "the first handle's drag is still in flight, so the row stays a registered source"
+ );
+ assert
+ .dom("#src")
+ .hasClass(
+ "--dragging",
+ "and disabling the replacement does not strip the mark of the drag it never owned"
+ );
+
+ await dragEvent("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ await dragEvent("#src", "dragend", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+ await settled();
+
+ assert
+ .dom("#src")
+ .doesNotHaveAttribute(
+ "data-drag-source",
+ "once that drag ends nothing is registered any more"
+ );
+ });
+
+ test("a handle cycled away, back and away again mid-drag still reports how that drag ended", async function (assert) {
+ const calls = [];
+ const state = new (class {
+ @tracked dragHandle;
+ handles = {};
+ captureHandle = (element) => {
+ this.handles[element.id] = element;
+ this.dragHandle ??= element;
+ };
+ onDragEnd = () => calls.push("dragEnd");
+ onDrop = () => calls.push("drop");
+ })();
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ dragHandle=state.dragHandle
+ onDragEnd=state.onDragEnd
+ onDrop=state.onDrop
+ }}
+ >
+ <button
+ id="handle-a"
+ type="button"
+ {{didInsert state.captureHandle}}
+ >a</button>
+ <button
+ id="handle-b"
+ type="button"
+ {{didInsert state.captureHandle}}
+ >b</button>
+ </div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ assert
+ .dom("#handle-a")
+ .hasAttribute("draggable", "true", "the drag starts on handle a");
+
+ const dataTransfer = new DataTransfer();
+ await dragEvent("#handle-a", "dragstart", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+ await dragEvent("#tgt", "dragenter", {
+ dataTransfer,
+ ...centerOf("#tgt"),
+ });
+ await dragEvent("#tgt", "dragover", {
+ dataTransfer,
+ ...centerOf("#tgt"),
+ });
+
+ // The drag's end is dispatched to whatever is registered on handle a at
+ // drop time, so a must stay registered through the swap that brings it back.
+ state.dragHandle = state.handles["handle-b"];
+ await settled();
+ state.dragHandle = state.handles["handle-a"];
+ await settled();
+ state.dragHandle = state.handles["handle-b"];
+ await settled();
+
+ assert
+ .dom("#src")
+ .hasClass("--dragging", "the drag in flight keeps its mark");
+
+ await dragEvent("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ await settled();
+
+ assert.deepEqual(
+ calls,
+ ["dragEnd", "drop"],
+ "cycling the handle does not cost the consumer the end of its drag"
+ );
+ });
+
+ test("a handle swapped in the same task as dragstart still reports the drag", async function (assert) {
+ const calls = [];
+ const state = new (class {
+ @tracked dragHandle;
+ handles = {};
+ captureHandle = (element) => {
+ this.handles[element.id] = element;
+ this.dragHandle ??= element;
+ };
+ onDragStart = () => calls.push("start");
+ onDragEnd = () => calls.push("dragEnd");
+ onDrop = () => calls.push("drop");
+ })();
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ dragHandle=state.dragHandle
+ onDragStart=state.onDragStart
+ onDragEnd=state.onDragEnd
+ onDrop=state.onDrop
+ }}
+ >
+ <button
+ id="handle-a"
+ type="button"
+ {{didInsert state.captureHandle}}
+ >a</button>
+ <button
+ id="handle-b"
+ type="button"
+ {{didInsert state.captureHandle}}
+ >b</button>
+ </div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ // The drag-start callback is deferred by a frame; a swap in that window
+ // must still see a drag in flight.
+ const dataTransfer = new DataTransfer();
+ dragEventNow("#handle-a", "dragstart", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+ state.dragHandle = state.handles["handle-b"];
+ await settled();
+
+ await dragEvent("#tgt", "dragenter", {
+ dataTransfer,
+ ...centerOf("#tgt"),
+ });
+ await dragEvent("#tgt", "dragover", {
+ dataTransfer,
+ ...centerOf("#tgt"),
+ });
+ assert
+ .dom("#src")
+ .hasClass("--dragging", "the drag in flight is marked");
+
+ await dragEvent("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ await settled();
+
+ assert.deepEqual(
+ calls,
+ ["start", "dragEnd", "drop"],
+ "the swap does not orphan the drag"
+ );
+ });
+
+ test("a natively draggable child of a source row is not answered", async function (assert) {
+ await render(
+ <template>
+ <div id="row" {{dDragAndDropSource type="row"}}>
+ row
+ <a id="link" href="/somewhere">link</a>
+ </div>
+ </template>
+ );
+
+ const dataTransfer = recordingTransfer();
+ await dragEvent("#link", "dragstart", {
+ dataTransfer,
+ ...centerOf("#link"),
+ });
+
+ assert.strictEqual(
+ dataTransfer.effectAllowed,
+ "none",
+ "a drag the primitive did not start keeps whatever the browser gave it"
+ );
+ });
+ });
+ });
+
+ module("drag previews", function () {
+ test("the default preview of a handled row keeps the grab point", async function (assert) {
+ const state = new (class {
+ @tracked dragHandle;
+ captureHandle = (element) => (this.dragHandle = element);
+ })();
+
+ await render(
+ <template>
+ <div
+ id="src"
+ style="width: 300px; height: 40px; display: flex; justify-content: flex-end"
+ {{dDragAndDropSource type="row" dragHandle=state.dragHandle}}
+ >
+ <button
+ id="grip"
+ type="button"
+ style="width: 30px"
+ {{didInsert state.captureHandle}}
+ >grip</button>
+ </div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ const setDragImage = sinon.spy(dataTransfer, "setDragImage");
+ const rowRect = find("#src").getBoundingClientRect();
+ const grab = centerOf("#grip");
+
+ await dragEvent("#grip", "dragstart", { dataTransfer, ...grab });
+
+ assert.true(setDragImage.calledOnce, "the row stands in for the grip");
+ const [image, x, y] = setDragImage.firstCall.args;
+ assert.strictEqual(image, find("#src"), "the photograph is the row");
+ assert.strictEqual(
+ Math.round(x),
+ Math.round(grab.clientX - rowRect.left),
+ "the hotspot is where the user grabbed, measured from the row's left"
+ );
+ assert.strictEqual(
+ Math.round(y),
+ Math.round(grab.clientY - rowRect.top),
+ "and from its top, so the picture does not jump under the pointer"
+ );
+
+ await dragEvent("#src", "dragend", { dataTransfer, ...grab });
+ });
+
+ test("an Element preview that is not the row is photographed at its own origin", async function (assert) {
+ const state = new (class {
+ @tracked preview;
+ capturePreview = (element) => (this.preview = element);
+ })();
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" dragPreview=state.preview}}
+ >src</div>
+ <div id="ghost" {{didInsert state.capturePreview}}>ghost</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ const setDragImage = sinon.spy(dataTransfer, "setDragImage");
+ await dragEvent("#src", "dragstart", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+
+ assert.true(
+ setDragImage.calledOnceWithExactly(find("#ghost"), 0, 0),
+ "a foreign preview keeps the top-left hotspot"
+ );
+
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+ });
+
+ test("getInitialData supplies the payload and cannot override the type", async function (assert) {
+ const sources = [];
+ const recordDrop = ({ source }) => sources.push(source);
+ const describe = () => ({ id: 7, type: "impostor" });
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" getInitialData=describe}}
+ >src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget accepts="row" onDrop=recordDrop}}
+ >tgt</div>
+ </template>
+ );
+
+ await simulateDrag("#src", "#tgt", { dataTransfer: new DataTransfer() });
+
+ assert.deepEqual(
+ sources.map(({ type, data }) => ({ type, data })),
+ [{ type: "row", data: { id: 7, type: "row" } }],
+ "the payload comes from getInitialData and the primitive's type is stamped over the payload's own"
+ );
+ });
+ });
+
+ module("lifecycle callbacks stay paired", function () {
+ test("an ancestor that never received an enter receives no leave", async function (assert) {
+ const events = [];
+ const onOuterEnter = () => events.push("outer:enter");
+ const onOuterLeave = () => events.push("outer:leave");
+ // The inner target is the positive control: without it a build that fires
+ // no lifecycle callback at all would pass just as well.
+ const onInnerEnter = () => events.push("inner:enter");
+ const onInnerLeave = () => events.push("inner:leave");
+
+ await render(
+ <template>
+ <div id="src" {{dDragAndDropSource type="row"}}>src</div>
+ <div
+ id="outer"
+ style="height: 100px"
+ {{dDragAndDropTarget
+ accepts="row"
+ position="inside"
+ onDragEnter=onOuterEnter
+ onDragLeave=onOuterLeave
+ }}
+ >
+ outer
+ <div
+ id="inner"
+ {{dDragAndDropTarget
+ accepts="row"
+ position="inside"
+ onDragEnter=onInnerEnter
+ onDragLeave=onInnerLeave
+ }}
+ >inner</div>
+ </div>
+ <div id="away" {{dDragAndDropTarget accepts="row"}}>away</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#inner", { dataTransfer });
+ await dragOver("#away", { dataTransfer });
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+
+ assert.deepEqual(
+ events,
+ ["inner:enter", "inner:leave"],
+ "the deepest target is entered and left as a pair, and the ancestor that was never entered is never left"
+ );
+ });
+
+ test("a target that becomes deepest without a fresh enter is entered and left", async function (assert) {
+ const events = [];
+ let drags = 0;
+
+ const onOuterEnter = () => events.push("outer:enter");
+ const onOuterDrag = () => drags++;
+ const onOuterLeave = () => events.push("outer:leave");
+
+ await render(
+ <template>
+ <div id="src" {{dDragAndDropSource type="row"}}>src</div>
+ <div
+ id="outer"
+ style="height: 100px"
+ {{dDragAndDropTarget
+ accepts="row"
+ position="inside"
+ onDragEnter=onOuterEnter
+ onDrag=onOuterDrag
+ onDragLeave=onOuterLeave
+ }}
+ >
+ outer
+ <div
+ id="inner"
+ {{dDragAndDropTarget accepts="row" position="inside"}}
+ >inner</div>
+ </div>
+ <div id="away" {{dDragAndDropTarget accepts="row"}}>away</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ const outerRect = find("#outer").getBoundingClientRect();
+
+ await dragEvent("#src", "dragstart", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+
+ await dragEvent("#inner", "dragenter", {
+ dataTransfer,
+ ...centerOf("#inner"),
+ });
+ await dragEvent("#inner", "dragover", {
+ dataTransfer,
+ ...centerOf("#inner"),
+ });
+
+ await dragEvent("#outer", "dragover", {
+ dataTransfer,
+ clientX: outerRect.left + 5,
+ clientY: outerRect.top + 5,
+ });
+
+ await dragEvent("#away", "dragenter", {
+ dataTransfer,
+ ...centerOf("#away"),
+ });
+ await dragEvent("#away", "dragover", {
+ dataTransfer,
+ ...centerOf("#away"),
+ });
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+
+ assert.true(
+ drags > 0,
+ "the ancestor was told about the drag once it was the deepest target"
+ );
+ assert.deepEqual(
+ events,
+ ["outer:enter", "outer:leave"],
+ "so it is entered when it takes over and left when it gives up, rather than being told only about the middle"
+ );
+ });
+
+ test("an ancestor superseded by a child is left before the drop lands", async function (assert) {
+ const events = [];
+ const onOuterEnter = () => events.push("outer:enter");
+ const onOuterLeave = () => events.push("outer:leave");
+ const onInnerDrop = () => events.push("inner:drop");
+
+ await render(
+ <template>
+ <div id="src" {{dDragAndDropSource type="row"}}>src</div>
+ <div
+ id="outer"
+ style="height: 100px"
+ {{dDragAndDropTarget
+ accepts="row"
+ position="inside"
+ onDragEnter=onOuterEnter
+ onDragLeave=onOuterLeave
+ }}
+ >
+ outer
+ <div
+ id="inner"
+ {{dDragAndDropTarget
+ accepts="row"
+ position="inside"
+ onDrop=onInnerDrop
+ }}
+ >inner</div>
+ </div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ const outerRect = find("#outer").getBoundingClientRect();
+
+ await dragEvent("#src", "dragstart", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+
+ await dragEvent("#outer", "dragenter", {
+ dataTransfer,
+ clientX: outerRect.left + 5,
+ clientY: outerRect.top + 5,
+ });
+ await dragEvent("#outer", "dragover", {
+ dataTransfer,
+ clientX: outerRect.left + 5,
+ clientY: outerRect.top + 5,
+ });
+
+ await dragEvent("#inner", "dragenter", {
+ dataTransfer,
+ ...centerOf("#inner"),
+ });
+ await dragEvent("#inner", "dragover", {
+ dataTransfer,
+ ...centerOf("#inner"),
+ });
+
+ await dragEvent("#inner", "drop", {
+ dataTransfer,
+ ...centerOf("#inner"),
+ });
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+
+ assert.deepEqual(
+ events,
+ ["outer:enter", "outer:leave", "inner:drop"],
+ "the ancestor is left as soon as the child takes over, so a drop never lands with its enter still open"
+ );
+ });
+
+ test("a second drag over the same target is entered again", async function (assert) {
+ const events = [];
+ const onEnter = () => events.push("enter");
+ const onLeave = () => events.push("leave");
+ const onDrop = () => events.push("drop");
+
+ await render(
+ <template>
+ <div id="src" {{dDragAndDropSource type="row"}}>src</div>
+ <div
+ id="target"
+ {{dDragAndDropTarget
+ accepts="row"
+ position="inside"
+ onDragEnter=onEnter
+ onDragLeave=onLeave
+ onDrop=onDrop
+ }}
+ >target</div>
+ <div id="away" {{dDragAndDropTarget accepts="row"}}>away</div>
+ </template>
+ );
+
+ const firstTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer: firstTransfer });
+ await dragOver("#target", { dataTransfer: firstTransfer });
+ await dragEvent("#target", "drop", {
+ dataTransfer: firstTransfer,
+ ...centerOf("#target"),
+ });
+ await dragEvent("#src", "dragend", {
+ dataTransfer: firstTransfer,
+ ...centerOf("#src"),
+ });
+
+ const secondTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer: secondTransfer });
+ await dragOver("#target", { dataTransfer: secondTransfer });
+ await dragOver("#away", { dataTransfer: secondTransfer });
+ await dragEvent("#src", "dragend", {
+ dataTransfer: secondTransfer,
+ ...centerOf("#src"),
+ });
+
+ assert.deepEqual(
+ events,
+ ["enter", "drop", "enter", "leave"],
+ "each drag gets its own enter, and the second one is still paired with a leave"
+ );
+ });
+ });
+
+ /**
+ * The library reports a hierarchy change synchronously but throttles the drag
+ * update that follows to a frame, and a drop cancels that frame. Anything a
+ * target learns only from the drag update is lost to a fast release.
+ */
+ module("a hierarchy change is observed in the same frame", function () {
+ test("an ancestor superseded by a child is left in the same frame, before the drop", async function (assert) {
+ const events = [];
+ const onOuterEnter = () => events.push("outer:enter");
+ const onOuterLeave = () => events.push("outer:leave");
+ const onInnerDrop = () => events.push("inner:drop");
+
+ await render(
+ <template>
+ <div id="src" {{dDragAndDropSource type="row"}}>src</div>
+ <div
+ id="outer"
+ style="height: 100px"
+ {{dDragAndDropTarget
+ accepts="row"
+ position="inside"
+ onDragEnter=onOuterEnter
+ onDragLeave=onOuterLeave
+ }}
+ >
+ outer
+ <div
+ id="inner"
+ {{dDragAndDropTarget
+ accepts="row"
+ position="inside"
+ onDrop=onInnerDrop
+ }}
+ >inner</div>
+ </div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ const outerRect = find("#outer").getBoundingClientRect();
+
+ await dragEvent("#src", "dragstart", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+ await dragEvent("#outer", "dragenter", {
+ dataTransfer,
+ clientX: outerRect.left + 5,
+ clientY: outerRect.top + 5,
+ });
+ await dragEvent("#outer", "dragover", {
+ dataTransfer,
+ clientX: outerRect.left + 5,
+ clientY: outerRect.top + 5,
+ });
+
+ assert
+ .dom("#outer")
+ .hasClass("--drag-inside", "the ancestor is entered and lit");
+
+ dragEventNow("#inner", "dragenter", {
+ dataTransfer,
+ ...centerOf("#inner"),
+ });
+
+ assert.deepEqual(
+ events,
+ ["outer:enter", "outer:leave"],
+ "the ancestor is left the moment the child takes over, without waiting for a frame"
+ );
+ assert
+ .dom("#outer")
+ .doesNotHaveClass(
+ "--drag-inside",
+ "and its indicator goes with the role"
+ );
+
+ dragEventNow("#inner", "drop", { dataTransfer, ...centerOf("#inner") });
+ await settled();
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+
+ assert.deepEqual(
+ events,
+ ["outer:enter", "outer:leave", "inner:drop"],
+ "the drop lands on the child with the ancestor already left"
+ );
+ });
+
+ test("flipping indicator off mid-hover clears the class already shown", async function (assert) {
+ const state = new (class {
+ @tracked indicator = true;
+ })();
+
+ await render(
+ <template>
+ <div id="src" {{dDragAndDropSource type="row"}}>src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget
+ accepts="row"
+ position="before"
+ indicator=state.indicator
+ }}
+ >tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+
+ assert.dom("#tgt").hasClass("--drag-above", "lit while indicating");
+
+ state.indicator = false;
+ await settled();
+ await dragEvent("#tgt", "dragover", {
+ dataTransfer,
+ ...centerOf("#tgt"),
+ });
+
+ assert
+ .dom("#tgt")
+ .doesNotHaveClass(
+ "--drag-above",
+ "turning the indicator off clears what was already painted, not only what comes next"
+ );
+ });
+
+ test("a drop clears the indicator of the target it lands on", async function (assert) {
+ await render(
+ <template>
+ <div id="src" {{dDragAndDropSource type="row"}}>src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget accepts="row" position="before"}}
+ >tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+
+ assert.dom("#tgt").hasClass("--drag-above", "lit while hovered");
+
+ // The drop follows without a frame, so the throttled drag update it would
+ // have cancelled is not what clears the class.
+ dragEventNow("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ await settled();
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+
+ assert
+ .dom("#tgt")
+ .doesNotHaveClass(
+ "--drag-above",
+ "the drop itself clears the indicator of the target it lands on"
+ );
+ });
+ });
+
+ /**
+ * The library runs its end-of-drag cleanup on the statement after it calls a
+ * consumer, unguarded, so an escaping exception skips it and surfaces as an
+ * uncaught error.
+ */
+ module("a consumer that throws cannot break the dispatch", function () {
+ const blowUp = () => {
+ throw new Error("consumer blew up");
+ };
+
+ test("a throwing target onDrop leaves the next drag able to run", async function (assert) {
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+
+ // `setupOnerror` only sees the test-time raise. The production report is a
+ // separate channel and would go unnoticed if it stopped firing.
+ const notices = [];
+ const collect = (event) => notices.push(event.detail.messageKey);
+ document.addEventListener("discourse-error", collect);
+
+ const ends = [];
+ const recordEnd = () => ends.push("end");
+ const laterDrops = [];
+ const recordLaterDrop = () => laterDrops.push("drop");
+ // Looked up before the drag so the service is there to see it.
+ const dnd = this.owner.lookup("service:drag-and-drop");
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" onDragEnd=recordEnd}}
+ >src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget accepts="row" onDrop=blowUp}}
+ >tgt</div>
+ <div id="later-src" {{dDragAndDropSource type="row"}}>later src</div>
+ <div
+ id="later-tgt"
+ {{dDragAndDropTarget accepts="row" onDrop=recordLaterDrop}}
+ >later tgt</div>
+ </template>
+ );
+
+ try {
+ await simulateDrag("#src", "#tgt", {
+ dataTransfer: new DataTransfer(),
+ });
+
+ assert.strictEqual(
+ reported.length,
+ 1,
+ "the error reaches the application rather than escaping as an uncaught one"
+ );
+ assert.deepEqual(
+ notices,
+ ["broken_drag_and_drop_alert"],
+ "and is reported through the channel that reaches admins in production"
+ );
+ assert.deepEqual(
+ ends,
+ ["end"],
+ "the source hears its drag end exactly once"
+ );
+ assert.false(
+ dnd.isDragging,
+ "and the service stops reporting a drag in flight"
+ );
+
+ await simulateDrag("#later-src", "#later-tgt", {
+ dataTransfer: new DataTransfer(),
+ });
+
+ assert.deepEqual(
+ laterDrops,
+ ["drop"],
+ "so a later drag still reaches its own target"
+ );
+ } finally {
+ document.removeEventListener("discourse-error", collect);
+ }
+ });
+
+ test("a throwing monitor onDrop leaves the next drag able to run", async function (assert) {
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+
+ const laterDrops = [];
+ const recordLaterDrop = () => laterDrops.push("drop");
+ const stopMonitoring = registerDragAndDropMonitor(() => ({
+ onDrop: blowUp,
+ }));
+
+ try {
+ await render(
+ <template>
+ <div id="src" {{dDragAndDropSource type="row"}}>src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget accepts="row" onDrop=recordLaterDrop}}
+ >tgt</div>
+ </template>
+ );
+
+ // Abandoned rather than dropped, because that is the path where the
+ // library has no later event to recover on.
+ const abandoned = new DataTransfer();
+ await dragEvent("#src", "dragstart", {
+ dataTransfer: abandoned,
+ ...centerOf("#src"),
+ });
+ await dragEvent("#src", "dragend", {
+ dataTransfer: abandoned,
+ ...centerOf("#src"),
+ });
+
+ await simulateDrag("#src", "#tgt", {
+ dataTransfer: new DataTransfer(),
+ });
+ } finally {
+ stopMonitoring();
+ }
+
+ assert.deepEqual(
+ laterDrops,
+ ["drop"],
+ "a drag abandoned into a throwing monitor does not stop the next one"
+ );
+ assert.strictEqual(
+ reported.length,
+ 2,
+ "and both throws are reported, one per drag the global monitor saw"
+ );
+ });
+
+ test("a throwing onDragEnd does not cost a landed drag its onDrop", async function (assert) {
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+
+ const drops = [];
+ const recordDrop = () => drops.push("drop");
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" onDragEnd=blowUp onDrop=recordDrop}}
+ >src</div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ await simulateDrag("#src", "#tgt", {
+ dataTransfer: new DataTransfer(),
+ });
+
+ assert.deepEqual(
+ drops,
+ ["drop"],
+ "the drag landed, so the operation still runs even though the lifecycle callback threw"
+ );
+ assert.strictEqual(reported.length, 1, "and the throw is still reported");
+ });
+
+ test("a throwing canDrop refuses the drop instead of allowing it", async function (assert) {
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+
+ const notices = [];
+ const collect = (event) => notices.push(event.detail.messageKey);
+ document.addEventListener("discourse-error", collect);
+
+ const drops = [];
+ const recordDrop = () => drops.push("drop");
+
+ await render(
+ <template>
+ <div id="src" {{dDragAndDropSource type="row"}}>src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget
+ accepts="row"
+ canDrop=blowUp
+ onDrop=recordDrop
+ }}
+ >tgt</div>
+ </template>
+ );
+
+ try {
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+
+ assert
+ .dom("#tgt")
+ .doesNotHaveClass(
+ /^--drag-/,
+ "a gate that threw has decided nothing, so the target does not light"
+ );
+
+ await dragEvent("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ await dragEvent("#src", "dragend", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+
+ assert.deepEqual(drops, [], "and the drop is refused");
+ assert.true(
+ reported.length >= 1,
+ `each throw is raised for the test (${reported.length} seen)`
+ );
+ assert.strictEqual(
+ new Set(notices).size,
+ 1,
+ "and every report goes through the drag-and-drop notice"
+ );
+ assert.strictEqual(
+ notices[0],
+ "broken_drag_and_drop_alert",
+ "under its own message key"
+ );
+ } finally {
+ document.removeEventListener("discourse-error", collect);
+ }
+ });
+
+ test("a throwing canDrag refuses to start the drag", async function (assert) {
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+
+ const drops = [];
+ const recordDrop = () => drops.push("drop");
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" canDrag=blowUp}}
+ >src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget accepts="row" onDrop=recordDrop}}
+ >tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+ assert
+ .dom("#src")
+ .doesNotHaveClass(
+ "--dragging",
+ "no drag starts, so the source is never marked as dragging"
+ );
+ await dragEvent("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+
+ assert.deepEqual(drops, [], "and nothing is dropped");
+ assert.true(
+ reported.length >= 1,
+ `and the throwing gate was raised (${reported.length} seen)`
+ );
+ });
+
+ test("a throwing getData is reported and the drag record carries no data", async function (assert) {
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+
+ const targets = [];
+ const recordDrop = ({ location }) =>
+ targets.push(location.current.dropTargets[0].data);
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" onDrop=recordDrop}}
+ >src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget accepts="row" getData=blowUp}}
+ >tgt</div>
+ </template>
+ );
+
+ await simulateDrag("#src", "#tgt", { dataTransfer: new DataTransfer() });
+
+ assert.deepEqual(
+ targets,
+ [{}],
+ "the drop lands with an empty record in place of what the consumer failed to attach"
+ );
+ assert.true(
+ reported.length >= 1,
+ `and the throwing getData was raised (${reported.length} seen)`
+ );
+ });
+
+ test("a throwing getIsSticky is reported and treated as not sticky", async function (assert) {
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+
+ const events = [];
+ const onEnter = () => events.push("enter");
+ const onLeave = () => events.push("leave");
+
+ await render(
+ <template>
+ <div id="src" {{dDragAndDropSource type="row"}}>src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget
+ accepts="row"
+ position="before"
+ getIsSticky=blowUp
+ onDragEnter=onEnter
+ onDragLeave=onLeave
+ }}
+ >tgt</div>
+ <div id="away" style="height: 50px">away</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+ await dragOver("#away", { dataTransfer });
+
+ // Asserted while the drag is still in flight: ending the drag would let
+ // even a sticky target go, and hide the difference.
+ assert.deepEqual(
+ events,
+ ["enter", "leave"],
+ "a gate that threw decided nothing, so the target lets go when the pointer leaves"
+ );
+ assert
+ .dom("#tgt")
+ .doesNotHaveClass("--drag-above", "and stops showing its indicator");
+ assert.true(
+ reported.length >= 1,
+ `and the throwing stickiness gate was raised (${reported.length} seen)`
+ );
+
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+ });
+
+ test("a throwing preview cleanup is reported and leaves no preview container behind", async function (assert) {
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+
+ const notices = [];
+ const collect = (event) => notices.push(event.detail.messageKey);
+ document.addEventListener("discourse-error", collect);
+
+ const drops = [];
+ const recordDrop = () => drops.push("drop");
+ const renderPreview = ({ container }) => {
+ container.dataset.previewMarker = "";
+ container.textContent = "preview";
+ return blowUp;
+ };
+
+ try {
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" dragPreview=renderPreview}}
+ >src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget accepts="row" onDrop=recordDrop}}
+ >tgt</div>
+ </template>
+ );
+
+ await simulateDrag("#src", "#tgt", {
+ dataTransfer: new DataTransfer(),
+ });
+
+ assert.deepEqual(drops, ["drop"], "the drop still lands");
+ assert.deepEqual(
+ notices,
+ ["broken_drag_and_drop_alert"],
+ "the throwing cleanup is reported once, as a consumer error"
+ );
+ assert
+ .dom("[data-preview-marker]", document.body)
+ .doesNotExist("and the offscreen preview container is still removed");
+ } finally {
+ document.removeEventListener("discourse-error", collect);
+ }
+ });
+
+ test("a throwing preview renderer is reported and the drag still starts", async function (assert) {
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+
+ const drops = [];
+ const recordDrop = () => drops.push("drop");
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" dragPreview=blowUp}}
+ >src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget accepts="row" onDrop=recordDrop}}
+ >tgt</div>
+ </template>
+ );
+
+ await simulateDrag("#src", "#tgt", { dataTransfer: new DataTransfer() });
+
+ assert.deepEqual(
+ drops,
+ ["drop"],
+ "the drag runs to a drop without a preview"
+ );
+ assert.true(
+ reported.length >= 1,
+ `and the throwing renderer was raised (${reported.length} seen)`
+ );
+ });
+
+ test("a throwing source onDragStart is reported and the drag still runs to its drop", async function (assert) {
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+
+ const drops = [];
+ const recordDrop = () => drops.push("drop");
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" onDragStart=blowUp}}
+ >src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget accepts="row" onDrop=recordDrop}}
+ >tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ assert
+ .dom("#src")
+ .hasClass("--dragging", "the drag is in flight despite the throw");
+ await dragOver("#tgt", { dataTransfer });
+ await dragEvent("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+
+ assert.deepEqual(
+ drops,
+ ["drop"],
+ "and the target still receives the drop"
+ );
+ assert.true(reported.length >= 1, "the throwing callback was raised");
+ });
+
+ test("a throwing source onDrop still runs the teardown that was waiting on the drag", async function (assert) {
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+ const state = new (class {
+ @tracked disabled = false;
+ })();
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ onDrop=blowUp
+ disabled=state.disabled
+ }}
+ >src</div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+
+ state.disabled = true;
+ await settled();
+ assert.dom("#src").hasAttribute("data-drag-source", "", "waiting");
+
+ await dragEvent("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+ await settled();
+
+ assert
+ .dom("#src")
+ .doesNotHaveAttribute(
+ "data-drag-source",
+ "the consumer's throw does not leave the element registered"
+ );
+ assert.strictEqual(reported.length, 1, "and the throw was raised once");
+ });
+ });
+
+ module("arg changes reach a drag already in flight", function () {
+ test("disabling a source mid-drag still reports to its current callbacks", async function (assert) {
+ const calls = [];
+ const state = new (class {
+ @tracked disabled = false;
+ @tracked onDragEnd = () => calls.push("before");
+ })();
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ disabled=state.disabled
+ onDragEnd=state.onDragEnd
+ }}
+ >src</div>
+ <div id="tgt" {{dDragAndDropTarget accepts="row"}}>tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await dragEvent("#src", "dragstart", {
+ dataTransfer,
+ ...centerOf("#src"),
+ });
+ await dragEvent("#tgt", "dragenter", {
+ dataTransfer,
+ ...centerOf("#tgt"),
+ });
+
+ // One flush for both: the registration detaches with the callback replaced.
+ state.disabled = true;
+ state.onDragEnd = () => calls.push("after");
+ await settled();
+
+ await dragEvent("#tgt", "dragover", {
+ dataTransfer,
+ ...centerOf("#tgt"),
+ });
+ await dragEvent("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+
+ assert.deepEqual(
+ calls,
+ ["after"],
+ "the drag reports to the callback the consumer has now, not the one it had at press"
+ );
+ });
+ });
+
+ module(
+ "the indicator leaves a consumer's positioning alone",
+ function (indicatorHooks) {
+ let consumerSheet;
+
+ indicatorHooks.afterEach(function () {
+ consumerSheet?.remove();
+ consumerSheet = null;
+ });
+
+ test("a positioned drop target keeps its own positioning while showing an indicator", async function (assert) {
+ // At the top of the head, so it loses on source order and can only take
+ // effect by outranking the primitive's default.
+ consumerSheet = document.createElement("style");
+ consumerSheet.textContent = ".positioned { position: absolute; }";
+ document.head.insertBefore(consumerSheet, document.head.firstChild);
+
+ // The stylesheet is the subject, so the mark and the class a lit target
+ // carries are written out rather than reached through a drag.
+ await render(
+ <template>
+ <div
+ id="tgt"
+ class="positioned --drag-above"
+ data-drop-target
+ >tgt</div>
+ </template>
+ );
+
+ assert.strictEqual(
+ getComputedStyle(find("#tgt")).position,
+ "absolute",
+ "the target is still positioned the way its consumer asked"
+ );
+ });
+
+ test("a drop target that positions nothing still gets the containing block the line needs", async function (assert) {
+ await render(
+ <template>
+ <div id="tgt" class="--drag-above" data-drop-target>tgt</div>
+ </template>
+ );
+
+ assert.strictEqual(
+ getComputedStyle(find("#tgt")).position,
+ "relative",
+ "so the line has something to resolve against"
+ );
+ });
+ }
+ );
+
+ module("gates and feedback the consumer supplies", function () {
+ test("canDrag returning false stops the drag before it starts", async function (assert) {
+ const drops = [];
+ const recordDrop = () => drops.push("drop");
+ const refuse = () => false;
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" canDrag=refuse}}
+ >src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget accepts="row" onDrop=recordDrop}}
+ >tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+ assert
+ .dom("#src")
+ .doesNotHaveClass(
+ "--dragging",
+ "the source never enters the drag state"
+ );
+ await dragEvent("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+
+ assert.deepEqual(drops, [], "and nothing is dropped");
+ });
+
+ test("canDrop returning false refuses a drag the type filter would have taken", async function (assert) {
+ const drops = [];
+ const recordDrop = () => drops.push("drop");
+ const refuse = () => false;
+
+ await render(
+ <template>
+ <div id="src" {{dDragAndDropSource type="row"}}>src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget
+ accepts="row"
+ canDrop=refuse
+ onDrop=recordDrop
+ }}
+ >tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+ assert
+ .dom("#tgt")
+ .doesNotHaveClass(
+ /^--drag-/,
+ "no indicator is drawn for a drop that cannot land"
+ );
+ await dragEvent("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+
+ assert.deepEqual(
+ drops,
+ [],
+ "and the identity gate refuses what the type gate allowed"
+ );
+ });
+
+ test("a gate that turns false after the last dragover still lands the drop", async function (assert) {
+ let allow = true;
+ const calls = [];
+ const canDrop = () => allow;
+ const recordTargetDrop = () => calls.push("target onDrop");
+ const recordSourceDrop = () => calls.push("source onDrop");
+ const recordSourceDragEnd = () => calls.push("source onDragEnd");
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ onDrop=recordSourceDrop
+ onDragEnd=recordSourceDragEnd
+ }}
+ >src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget
+ accepts="row"
+ canDrop=canDrop
+ onDrop=recordTargetDrop
+ }}
+ >tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+
+ // Turned off with no dragover left to observe it, so the release still
+ // sees the hierarchy the indicator was drawn from.
+ allow = false;
+
+ await dragEvent("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+
+ assert.deepEqual(
+ calls,
+ ["target onDrop", "source onDragEnd", "source onDrop"],
+ "both ends act on the answer the drag was last given"
+ );
+ });
+
+ test("a gate that turns false before the last dragover refuses the drop", async function (assert) {
+ let allow = true;
+ const calls = [];
+ const canDrop = () => allow;
+ const recordTargetDrop = () => calls.push("target onDrop");
+ const recordSourceDrop = () => calls.push("source onDrop");
+ const recordSourceDragEnd = () => calls.push("source onDragEnd");
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ onDrop=recordSourceDrop
+ onDragEnd=recordSourceDragEnd
+ }}
+ >src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget
+ accepts="row"
+ canDrop=canDrop
+ onDrop=recordTargetDrop
+ }}
+ >tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+
+ allow = false;
+ await dragOver("#tgt", { dataTransfer });
+
+ await dragEvent("#tgt", "drop", { dataTransfer, ...centerOf("#tgt") });
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+
+ assert.deepEqual(
+ calls,
+ ["source onDragEnd"],
+ "a dragover observed the refusal, so the drag ends holding nothing"
+ );
+ });
+
+ test("getDropEffect decides the effect recorded against this target", async function (assert) {
+ const effects = [];
+ const copyEffect = () => "copy";
+ const recordDrop = ({ location }) =>
+ effects.push(location.current.dropTargets[0].dropEffect);
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource
+ type="row"
+ effectAllowed="copyMove"
+ onDrop=recordDrop
+ }}
+ >src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget accepts="row" getDropEffect=copyEffect}}
+ >tgt</div>
+ </template>
+ );
+
+ await simulateDrag("#src", "#tgt", { dataTransfer: new DataTransfer() });
+
+ // Read from the drag's own record rather than the `dataTransfer`, whose
+ // `dropEffect` a synthetic drag reports as `none` however it was set up.
+ assert.deepEqual(
+ effects,
+ ["copy"],
+ "the effect the target asked for is the one the drag carries for it"
+ );
+ });
+
+ test("getData attaches target metadata the drag carries to the source", async function (assert) {
+ const targets = [];
+ const describeTarget = () => ({ slot: "inbox" });
+ const recordDrop = ({ location }) =>
+ targets.push(location.current.dropTargets[0].data);
+
+ await render(
+ <template>
+ <div
+ id="src"
+ {{dDragAndDropSource type="row" onDrop=recordDrop}}
+ >src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget accepts="row" getData=describeTarget}}
+ >tgt</div>
+ </template>
+ );
+
+ await simulateDrag("#src", "#tgt", { dataTransfer: new DataTransfer() });
+
+ assert.deepEqual(
+ targets,
+ [{ slot: "inbox" }],
+ "the source reads what the target attached to its own record of the drag"
+ );
+ });
+
+ test("a sticky target keeps its enter while the pointer is outside it and is left when stickiness ends", async function (assert) {
+ const state = new (class {
+ @tracked sticky = true;
+ })();
+ const isSticky = () => state.sticky;
+ const events = [];
+ const onEnter = () => events.push("enter");
+ const onLeave = () => events.push("leave");
+
+ await render(
+ <template>
+ <div id="src" {{dDragAndDropSource type="row"}}>src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget
+ accepts="row"
+ position="before"
+ getIsSticky=isSticky
+ onDragEnter=onEnter
+ onDragLeave=onLeave
+ }}
+ >tgt</div>
+ <div id="away" style="height: 50px">away</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+ await dragOver("#away", { dataTransfer });
+
+ assert.deepEqual(
+ events,
+ ["enter"],
+ "stickiness keeps the role while the pointer is outside"
+ );
+ assert
+ .dom("#tgt")
+ .hasClass("--drag-above", "and the indicator stays with the role");
+
+ state.sticky = false;
+ await settled();
+ await dragEvent("#away", "dragover", {
+ dataTransfer,
+ ...centerOf("#away"),
+ });
+
+ assert.deepEqual(
+ events,
+ ["enter", "leave"],
+ "once stickiness ends the target is left exactly once"
+ );
+ assert.dom("#tgt").doesNotHaveClass("--drag-above");
+
+ await dragEvent("#src", "dragend", { dataTransfer, ...centerOf("#src") });
+ });
+
+ test("indicator=false drops the marker without dropping the callbacks", async function (assert) {
+ const entered = [];
+ const recordEnter = () => entered.push("enter");
+
+ await render(
+ <template>
+ <div id="src" {{dDragAndDropSource type="row"}}>src</div>
+ <div
+ id="tgt"
+ {{dDragAndDropTarget
+ accepts="row"
+ position="before"
+ indicator=false
+ onDragEnter=recordEnter
+ }}
+ >tgt</div>
+ </template>
+ );
+
+ const dataTransfer = new DataTransfer();
+ await startDrag("#src", { dataTransfer });
+ await dragOver("#tgt", { dataTransfer });
+
+ assert
+ .dom("#tgt")
+ .doesNotHaveClass(
+ "--drag-above",
+ "the consumer draws its own feedback"
+ );
+ assert.deepEqual(
+ entered,
+ ["enter"],
+ "and is still told the drag arrived, so it can draw it"
+ );
+ });
+ });
+});
diff --git a/frontend/discourse/tests/unit/lib/-internals/drag-and-drop/vocabulary-test.js b/frontend/discourse/tests/unit/lib/-internals/drag-and-drop/vocabulary-test.js
new file mode 100644
index 00000000000..7a3661c4641
--- /dev/null
+++ b/frontend/discourse/tests/unit/lib/-internals/drag-and-drop/vocabulary-test.js
@@ -0,0 +1,116 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import { matchesExternalKind } from "discourse/lib/-internals/drag-and-drop/external-vocabulary";
+import { matchesDragType } from "discourse/lib/-internals/drag-and-drop/vocabulary";
+import {
+ fileTransfer,
+ textTransfer,
+} from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";
+
+/**
+ * The raw payload the underlying library hands its external callbacks, built
+ * from a real `DataTransfer` so the kind predicates read the same `types` a
+ * browser would report.
+ */
+function externalPayload(dataTransfer) {
+ return {
+ types: [...dataTransfer.types],
+ items: [...dataTransfer.items],
+ getStringData: (type) => dataTransfer.getData(type),
+ };
+}
+
+function stringTransfer(mimeType, value) {
+ const dataTransfer = new DataTransfer();
+ dataTransfer.setData(mimeType, value);
+ return dataTransfer;
+}
+
+module("Unit | Lib | drag-and-drop vocabulary", function (hooks) {
+ setupTest(hooks);
+
+ module("matchesDragType", function () {
+ const source = (type) => ({ data: { type } });
+
+ test("a single type engages only a drag of that type", function (assert) {
+ assert.true(matchesDragType("row", source("row")), "the same type");
+ assert.false(matchesDragType("row", source("card")), "a different type");
+ assert.false(
+ matchesDragType("row", { data: {} }),
+ "a typeless source matches no filter"
+ );
+ });
+
+ test("a list engages a drag of any type in it", function (assert) {
+ assert.true(
+ matchesDragType(["row", "card"], source("card")),
+ "a list containing the type"
+ );
+ assert.false(
+ matchesDragType(["row", "card"], source("other")),
+ "a list without it"
+ );
+ });
+
+ test("no filter engages every drag", function (assert) {
+ assert.true(matchesDragType(undefined, source("row")), "omitted");
+ assert.true(
+ matchesDragType([], source("row")),
+ "an empty list is the same as no filter"
+ );
+ });
+ });
+
+ module("matchesExternalKind", function () {
+ const files = () => externalPayload(fileTransfer());
+ const text = () => externalPayload(textTransfer());
+ const html = () =>
+ externalPayload(stringTransfer("text/html", "<b>dropped</b>"));
+ const urls = () =>
+ externalPayload(stringTransfer("text/uri-list", "https://example.com"));
+
+ test("each kind engages only the payload that carries it", function (assert) {
+ assert.true(matchesExternalKind("files", files()), "files: a file");
+ assert.false(matchesExternalKind("files", text()), "files: text");
+
+ assert.true(matchesExternalKind("text", text()), "text: text");
+ assert.false(matchesExternalKind("text", files()), "text: a file");
+
+ assert.true(matchesExternalKind("html", html()), "html: html");
+ assert.false(matchesExternalKind("html", text()), "html: text");
+
+ assert.true(matchesExternalKind("urls", urls()), "urls: a url list");
+ assert.false(matchesExternalKind("urls", html()), "urls: html");
+ });
+
+ test("a list engages a payload carrying any kind in it", function (assert) {
+ assert.true(
+ matchesExternalKind(["files", "text"], text()),
+ "a list containing the payload's kind"
+ );
+ assert.false(
+ matchesExternalKind(["files", "html"], text()),
+ "a list without it"
+ );
+ });
+
+ test("no filter engages every external drag", function (assert) {
+ assert.true(matchesExternalKind(undefined, files()), "omitted");
+ assert.true(
+ matchesExternalKind([], text()),
+ "an empty list is the same as no filter"
+ );
+ });
+
+ test("an unknown kind fails closed", function (assert) {
+ assert.false(
+ matchesExternalKind("images", files()),
+ "a kind outside the vocabulary matches nothing rather than everything"
+ );
+ assert.false(
+ matchesExternalKind(["images"], text()),
+ "even inside a list"
+ );
+ });
+ });
+});
diff --git a/frontend/discourse/tests/unit/services/drag-and-drop-test.js b/frontend/discourse/tests/unit/services/drag-and-drop-test.js
new file mode 100644
index 00000000000..4cfad19d4ec
--- /dev/null
+++ b/frontend/discourse/tests/unit/services/drag-and-drop-test.js
@@ -0,0 +1,177 @@
+import { destroy } from "@ember/destroyable";
+import { getOwner } from "@ember/owner";
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import {
+ dragEvent,
+ dragEventNow,
+ textTransfer,
+} from "discourse/tests/helpers/ui-kit/drag-and-drop-helper";
+
+module("Unit | Service | drag-and-drop", function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.dragAndDrop = getOwner(this).lookup("service:drag-and-drop");
+ });
+
+ test("accepts matches a single type or any of a list", function (assert) {
+ this.dragAndDrop.setCurrentDrag({
+ type: "row",
+ data: {},
+ element: null,
+ });
+ assert.true(
+ this.dragAndDrop.accepts("row"),
+ "the in-flight type is accepted"
+ );
+ assert.false(
+ this.dragAndDrop.accepts("card"),
+ "a different type is rejected"
+ );
+ assert.true(
+ this.dragAndDrop.accepts(["card", "row"]),
+ "a list containing the in-flight type is accepted"
+ );
+ assert.false(
+ this.dragAndDrop.accepts(["other"]),
+ "a list without it is rejected"
+ );
+ });
+
+ test("accepts is false when nothing is in flight", function (assert) {
+ assert.false(
+ this.dragAndDrop.accepts("row"),
+ "no drag in flight accepts no single type"
+ );
+ assert.false(
+ this.dragAndDrop.accepts(["a", "b"]),
+ "and accepts no list either"
+ );
+ });
+
+ test("accepts is false when no filter is supplied", function (assert) {
+ this.dragAndDrop.setCurrentDrag({
+ type: "row",
+ data: {},
+ element: null,
+ });
+ assert.false(
+ this.dragAndDrop.accepts(null),
+ "a null filter accepts nothing rather than everything"
+ );
+ assert.false(
+ this.dragAndDrop.accepts(undefined),
+ "an omitted filter accepts nothing either"
+ );
+ assert.false(
+ this.dragAndDrop.accepts([]),
+ "and so does an empty list: the caller has not decided"
+ );
+ });
+
+ test("tracks and filters an external drag", async function (assert) {
+ const dataTransfer = textTransfer("external payload");
+
+ await dragEvent(document.body, "dragenter", {
+ dataTransfer,
+ clientX: 1,
+ clientY: 1,
+ });
+
+ assert.true(this.dragAndDrop.isDragging, "an external drag is in flight");
+ assert.true(
+ this.dragAndDrop.currentExternalDrag.containsText(),
+ "the decorated payload reports its native kind"
+ );
+ assert.strictEqual(
+ this.dragAndDrop.currentExternalDrag.getText(),
+ null,
+ "the hover-time service snapshot does not claim access to string data the browser withholds until drop"
+ );
+ assert.true(
+ this.dragAndDrop.acceptsExternal("text"),
+ "the matching external vocabulary is accepted"
+ );
+ assert.false(
+ this.dragAndDrop.acceptsExternal("files"),
+ "a different external kind is rejected"
+ );
+ assert.true(
+ this.dragAndDrop.acceptsExternal(["files", "text"]),
+ "a list is accepted when any kind in it matches"
+ );
+ assert.false(
+ this.dragAndDrop.acceptsExternal([]),
+ "an empty list matches nothing, unlike a target's empty filter"
+ );
+ assert.false(
+ this.dragAndDrop.acceptsExternal(null),
+ "a null filter matches nothing"
+ );
+ assert.false(
+ this.dragAndDrop.acceptsExternal(undefined),
+ "an omitted filter matches nothing"
+ );
+
+ await dragEvent(document.body, "drop", {
+ dataTransfer,
+ clientX: 1,
+ clientY: 1,
+ });
+
+ assert.strictEqual(
+ this.dragAndDrop.currentExternalDrag,
+ null,
+ "the external payload is cleared after drop"
+ );
+ assert.false(
+ this.dragAndDrop.isDragging,
+ "the drag is no longer in flight"
+ );
+ });
+
+ test("external monitor ignores drag start while service is destroying", function (assert) {
+ const dataTransfer = textTransfer("external payload");
+
+ destroy(this.dragAndDrop);
+ dragEventNow(document.body, "dragenter", {
+ dataTransfer,
+ clientX: 1,
+ clientY: 1,
+ });
+
+ assert.false(
+ Boolean(this.dragAndDrop.currentExternalDrag),
+ "a destroying service does not record a newly-started external drag"
+ );
+ });
+
+ test("external monitor ignores drop after service destruction begins", async function (assert) {
+ const dataTransfer = textTransfer("external payload");
+ await dragEvent(document.body, "dragenter", {
+ dataTransfer,
+ clientX: 1,
+ clientY: 1,
+ });
+ const externalDrag = this.dragAndDrop.currentExternalDrag;
+
+ assert.true(
+ Boolean(externalDrag),
+ "the service records the external drag before destruction"
+ );
+
+ destroy(this.dragAndDrop);
+ dragEventNow(document.body, "drop", {
+ dataTransfer,
+ clientX: 1,
+ clientY: 1,
+ });
+
+ assert.strictEqual(
+ this.dragAndDrop.currentExternalDrag,
+ externalDrag,
+ "a destroying service ignores the in-flight external drag's drop callback"
+ );
+ });
+});
diff --git a/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-errors-test.gts b/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-errors-test.gts
new file mode 100644
index 00000000000..bb15bfa9d7d
--- /dev/null
+++ b/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-errors-test.gts
@@ -0,0 +1,25 @@
+// Every invocation below MUST fail to compile. Negatives are quarantined here
+// so a `@glint-expect-error` cannot mask a broken positive declaration.
+import dDragAndDropSource from "discourse/ui-kit/modifiers/d-drag-and-drop-source";
+import dDragAndDropTarget from "discourse/ui-kit/modifiers/d-drag-and-drop-target";
+
+declare const payload: object;
+
+const Negatives = <template>
+ {{! @glint-expect-error - a selector is not an element; the handle ref must be }}
+ <li {{dDragAndDropSource type="link" dragHandle="#handle"}}></li>
+
+ {{! @glint-expect-error - the discriminator is required }}
+ <li {{dDragAndDropSource data=payload}}></li>
+
+ {{! @glint-expect-error - "moveCopy" is not a permitted effect }}
+ <li {{dDragAndDropSource type="link" effectAllowed="moveCopy"}}></li>
+
+ {{! @glint-expect-error - the axis vocabulary is vertical and horizontal }}
+ <li {{dDragAndDropTarget accepts="link" axis="y"}}></li>
+
+ {{! @glint-expect-error - a drop lands before, after or inside, nowhere else }}
+ <li {{dDragAndDropTarget accepts="link" position="middle"}}></li>
+</template>;
+
+export default Negatives;
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.gts
new file mode 100644
index 00000000000..571fbb3d3ed
--- /dev/null
+++ b/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-external-errors-test.gts
@@ -0,0 +1,37 @@
+// Every invocation below MUST fail to compile. Negatives are quarantined here
+// so a `@glint-expect-error` cannot mask a broken positive declaration.
+import dDragAndDropAutoScroll from "discourse/ui-kit/modifiers/d-drag-and-drop-auto-scroll";
+import dDragAndDropExternalTarget, {
+ ExternalDropTargetEvent,
+} from "discourse/ui-kit/modifiers/d-drag-and-drop-external-target";
+import dDragAndDropTarget, {
+ DropTargetEvent,
+} from "discourse/ui-kit/modifiers/d-drag-and-drop-target";
+
+declare function onExternalDrop(event: ExternalDropTargetEvent): void;
+declare function onElementDrop(event: DropTargetEvent): void;
+
+const Negatives = <template>
+ {{! @glint-expect-error - the external vocabulary is a closed set of kinds }}
+ <div {{dDragAndDropExternalTarget accepts="images"}}></div>
+
+ {{! @glint-expect-error - the external target rejects the same axes }}
+ <div {{dDragAndDropExternalTarget accepts="urls" axis="x"}}></div>
+
+ {{! @glint-expect-error - auto-scroll adds only "all" to the shared axis vocabulary }}
+ <div {{dDragAndDropAutoScroll types="card" axis="both"}}></div>
+
+ {{! @glint-expect-error - auto-scroll moves the host element or the window }}
+ <div {{dDragAndDropAutoScroll target="document"}}></div>
+
+ {{! @glint-expect-error - auto-scroll filters external drags by kind }}
+ <div {{dDragAndDropAutoScroll accepts="images"}}></div>
+
+ {{! @glint-expect-error - the element and external targets report different payloads }}
+ <li {{dDragAndDropTarget accepts="link" onDrop=onExternalDrop}}></li>
+
+ {{! @glint-expect-error - an element handler cannot read the external payload }}
+ <li {{dDragAndDropExternalTarget accepts="files" onDrop=onElementDrop}}></li>
+</template>;
+
+export default Negatives;
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.gts
new file mode 100644
index 00000000000..75f00a79927
--- /dev/null
+++ b/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-external-test.gts
@@ -0,0 +1,56 @@
+// 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 dDragAndDropAutoScroll from "discourse/ui-kit/modifiers/d-drag-and-drop-auto-scroll";
+import dDragAndDropExternalTarget, {
+ ExternalDropTargetEvent,
+} from "discourse/ui-kit/modifiers/d-drag-and-drop-external-target";
+
+declare const noop: () => void;
+declare const acceptedTypes: string[];
+declare function onExternalDrop(event: ExternalDropTargetEvent): void;
+declare function describeTarget(): { slot: string };
+declare function isSticky(): boolean;
+
+const Positives = <template>
+ {{! The external target speaks the kind vocabulary, not drag types }}
+ <div
+ {{dDragAndDropExternalTarget accepts="files" onDrop=onExternalDrop}}
+ ></div>
+
+ {{! Target-side metadata and stickiness are shared with the element target }}
+ <div
+ {{dDragAndDropExternalTarget
+ accepts="files"
+ getData=describeTarget
+ getIsSticky=isSticky
+ }}
+ ></div>
+ <div
+ {{dDragAndDropExternalTarget
+ accepts=(array "files" "urls")
+ indicator=false
+ onDragEnter=noop
+ onDrop=noop
+ }}
+ ></div>
+
+ {{! A positioned external target shares the element target's vocabulary }}
+ <li
+ {{dDragAndDropExternalTarget accepts="urls" axis="vertical" onDrop=noop}}
+ ></li>
+ <li
+ {{dDragAndDropExternalTarget accepts="urls" position="inside" onDrop=noop}}
+ ></li>
+
+ {{! Auto-scroll defaults to the host element, or takes the window }}
+ <div {{dDragAndDropAutoScroll types="card" axis="vertical"}}></div>
+ <span {{dDragAndDropAutoScroll target="window" types=acceptedTypes}}></span>
+
+ {{! External auto-scroll is a separate opt-in keyed by kind, not drag type }}
+ <div
+ {{dDragAndDropAutoScroll types="card" accepts=(array "urls" "files")}}
+ ></div>
+</template>;
+
+export default Positives;
diff --git a/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-test.gts b/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-test.gts
new file mode 100644
index 00000000000..09cb12e09b7
--- /dev/null
+++ b/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-test.gts
@@ -0,0 +1,55 @@
+// Keep this file free of @glint-expect-error directives so broken positive
+// invocations cannot be masked by a negative assertion.
+import { hash } from "@ember/helper";
+import dDragAndDropMonitor from "discourse/ui-kit/modifiers/d-drag-and-drop-monitor";
+import dDragAndDropSource from "discourse/ui-kit/modifiers/d-drag-and-drop-source";
+import dDragAndDropTarget, {
+ DropTargetEvent,
+} from "discourse/ui-kit/modifiers/d-drag-and-drop-target";
+
+declare const noop: () => void;
+declare const handle: HTMLElement;
+declare const payload: object;
+declare const acceptedTypes: string[];
+
+declare function onDropTargetEvent(event: DropTargetEvent): void;
+
+const Positives = <template>
+ {{! A source takes a single type, an arbitrary payload object, and a handle }}
+ <li
+ {{dDragAndDropSource
+ type="sidebar-link"
+ data=payload
+ dragHandle=handle
+ dragPreviewOffset=(hash x="1rem" y="0.5rem")
+ effectAllowed="copyMove"
+ disabled=false
+ onDragStart=noop
+ onDragEnd=noop
+ onDrop=noop
+ }}
+ ></li>
+
+ {{! A target accepts one type or several, and reports a normalised source }}
+ <li
+ {{dDragAndDropTarget accepts="sidebar-link" onDrop=onDropTargetEvent}}
+ ></li>
+ <li
+ {{dDragAndDropTarget
+ accepts=acceptedTypes
+ acceptsSelf=false
+ position="inside"
+ axis="horizontal"
+ indicator=false
+ onDragEnter=onDropTargetEvent
+ onDrag=onDropTargetEvent
+ onDragLeave=onDropTargetEvent
+ onDrop=onDropTargetEvent
+ }}
+ ></li>
+
+ {{! A monitor is global, so any sentinel element carries it }}
+ <div {{dDragAndDropMonitor types=acceptedTypes onDrag=noop}}></div>
+</template>;
+
+export default Positives;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 59979abebee..9c40abcf7fb 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -198,6 +198,12 @@ importers:
frontend/discourse:
dependencies:
+ '@atlaskit/pragmatic-drag-and-drop':
+ specifier: ^3.0.0
+ version: 3.0.0
+ '@atlaskit/pragmatic-drag-and-drop-auto-scroll':
+ specifier: ^3.0.1
+ version: 3.0.1
'@codemirror/autocomplete':
specifier: ^6.20.3
version: 6.20.3
@@ -974,6 +980,12 @@ packages:
'@asamuzakjp/[email protected]':
resolution: {integrity: sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==}
+ '@atlaskit/[email protected]':
+ resolution: {integrity: sha512-JgVNhb3CMkxzAU87k8+9fpWy67kaZkALIDgyqT34rkgpWWYM5nCQpQwDLJBeYzlyt/lvlUyWfyaaSGuDfSbbNA==}
+
+ '@atlaskit/[email protected]':
+ resolution: {integrity: sha512-EEKBELv757wrvhMHBAoFcXjfzGZ4Y2FJ2xnSsWovsOKywkN1Q4IWRH52hQpPmJnATLcmO9viVhoXWSXFBLKSLQ==}
+
resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==}
engines: {node: '>=6.9.0'}
@@ -3551,6 +3563,9 @@ packages:
resolution: {integrity: sha512-yzkH0uog6Vv/vQ9+rhSKxecnqGUZHYncg7qS7voz3Q76+TAi1SGiOKk2mlOvusQnFz9Dc4BC/NMkeXu11YgjJg==}
+ resolution: {integrity: sha512-PJvH288AWQhKs2v9zyfYdPzlPqf5bXbGMmhmUIY9x4dAUGIWgomO771oBQNwJnMQSnUIXhKu6sgzpBRXTlvb8Q==}
+
resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==}
@@ -7012,6 +7027,9 @@ packages:
engines: {node: '>=10'}
hasBin: true
+ resolution: {integrity: sha512-tQkJl2GRWh83ui2DiPTJz9wEiMN20syf+5oKfB03yYP7ioZcJwsIK8FjrtLwH1m7C7e+Tt2yYBlrOpdT+dyeIQ==}
+
resolution: {integrity: sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==}
engines: {node: '>= 0.6'}
@@ -8478,6 +8496,17 @@ snapshots:
'@csstools/css-tokenizer': 3.0.4
lru-cache: 10.4.3
+ '@atlaskit/[email protected]':
+ dependencies:
+ '@atlaskit/pragmatic-drag-and-drop': 3.0.0
+ '@babel/runtime': 7.29.7
+
+ '@atlaskit/[email protected]':
+ dependencies:
+ '@babel/runtime': 7.29.7
+ bind-event-listener: 3.0.0
+ raf-schd: 4.0.3
+
dependencies:
'@babel/helper-validator-identifier': 7.29.7
@@ -11589,6 +11618,8 @@ snapshots:
+
dependencies:
buffer: 5.7.1
@@ -15734,6 +15765,8 @@ snapshots:
node-watch: 0.7.3
tiny-glob: 0.2.9
+
diff --git a/spec/support/system_helpers.rb b/spec/support/system_helpers.rb
index 6512e1ac2ea..fb052365dee 100644
--- a/spec/support/system_helpers.rb
+++ b/spec/support/system_helpers.rb
@@ -422,17 +422,50 @@ module SystemHelpers
page.driver.with_playwright_page { |pw_page| pw_page.touchscreen.tap_point(x, y) }
end
+ # Drives a real native drag through Playwright's CDP drag interception.
+ #
+ # Capybara's own `drag_to` synthesises mouse events, and a native drag driven
+ # that way can fire `dragstart` and then stall with no `dragover`, `drop` or
+ # `dragend`, so the drop silently no-ops.
+ #
+ # `source:` and `target:` are CSS selectors.
+ #
+ # `source_position:` picks the press point, which decides what starts: a press
+ # on a text input starts a text-selection drag that stalls the same way, and a
+ # drag handle only starts a drag when the press lands inside it.
+ #
+ # `target_position:` (`{ x:, y: }` from the target's top-left) picks where the
+ # drop lands; the centre is the ambiguous midpoint of a before/after zone.
+ # `steps:` adds intermediate moves for a drag that needs more to register.
+ #
+ # This does NOT wait for the client to settle: that wait lives in Capybara's
+ # patched node methods, and driving Playwright directly bypasses it. Assert
+ # through a retrying matcher, not a value read once.
+ def drag_and_drop(source:, target:, source_position: nil, target_position: nil, steps: nil)
+ page.driver.with_playwright_page do |pw_page|
+ options = {}
+ options[:sourcePosition] = source_position if source_position
+ options[:targetPosition] = target_position if target_position
+ options[:steps] = steps if steps
+ pw_page.drag_and_drop(source, target, **options)
+ end
+ end
+
# Drives a press-drag-release with the real mouse, for the surfaces built on
# pointer events rather than native drag-and-drop.
#
+ # Not interchangeable with `drag_and_drop`: CDP drag interception suppresses
+ # the ordinary mouse moves a pointer gesture needs, so a pointer-driven
+ # surface sees the press and then nothing, exactly like a dead drag.
+ #
# `from:` is a CSS selector for the element to press. `to:` is an absolute
# viewport point; `by:` is an offset from the press point, for when the distance
# matters more than the destination. Movement is broken into `steps:` so a
# gesture with a movement threshold actually crosses it, and so anything driven
# by intermediate moves sees more than one.
#
- # This bypasses Capybara's client-settle wait, so assert through a retrying
- # matcher rather than a value read once.
+ # Like `drag_and_drop`, this bypasses Capybara's client-settle wait, so assert
+ # through a retrying matcher rather than a value read once.
#
# The mouse moves through absolute viewport coordinates. An element below the
# fold would otherwise be measured where it cannot be pressed, so it is scrolled