Skip to content

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

DEV: Adopt browser-started element drags (#42594)

Sérgio Saquetim5ee8e2494e39
diff --git a/frontend/discourse/app/lib/-internals/drag-and-drop/native-drag-adoption.ts b/frontend/discourse/app/lib/-internals/drag-and-drop/native-drag-adoption.ts
new file mode 100644
index 00000000000..6c596c70281
--- /dev/null
+++ b/frontend/discourse/app/lib/-internals/drag-and-drop/native-drag-adoption.ts
@@ -0,0 +1,293 @@
+import { cancel, next } from "@ember/runloop";
+import { draggable } from "@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter";
+import { consumerMayThrow } from "discourse/lib/-internals/drag-and-drop/consumer-may-throw";
+import {
+ decorateExternalSource,
+ type ExternalDragPayload,
+} from "discourse/lib/-internals/drag-and-drop/external-vocabulary";
+import {
+ ADOPTED_AS,
+ ADOPTED_DRAG_TYPE,
+ DRAG_BODY,
+} from "discourse/lib/-internals/drag-and-drop/vocabulary";
+import { makeArray } from "discourse/lib/helpers";
+
+/** The one arg an adoption candidate is read for. */
+export interface AdoptionCandidateArgs {
+ adopts?: NativeDragAdoption | NativeDragAdoption[];
+}
+
+/**
+ * Whether a drag was started by the browser and claimed by an adoption.
+ *
+ * @param data - The drag payload's `data`, as the underlying library carries it.
+ */
+export function isAdoptedDrag(data: Record<string, unknown> | undefined) {
+ return data?.type === ADOPTED_DRAG_TYPE;
+}
+
+/**
+ * Whether one of the supplied adoptions is the one that claimed this drag.
+ *
+ * @param data - The drag payload's `data`, as the underlying library carries it.
+ * @param adopts - The target's `adopts` arg.
+ */
+export function offersAdoptionFor(
+ data: Record<string, unknown> | undefined,
+ adopts: NativeDragAdoption | NativeDragAdoption[] | undefined
+) {
+ return makeArray(adopts).some(
+ (adoption) => adoption.type === data?.[ADOPTED_AS]
+ );
+}
+
+/** What an adoption gate is asked about, and handed if it accepts. */
+export interface NativeDragAdoptionFeedback {
+ /** The element the browser chose to drag. */
+ element: HTMLElement;
+
+ /**
+ * The incoming payload, already snapshotted. It is not the live
+ * `DataTransfer`. Those handles go inert when the `dragstart` dispatch ends,
+ * so a later read comes back empty.
+ */
+ source: ExternalDragPayload;
+}
+
+/**
+ * Opt-in description of a browser-started drag a target is willing to adopt.
+ *
+ * The gate is a predicate rather than a list of payload kinds, because the
+ * kinds are too coarse. Accepting `"text"` catches a URL published only as
+ * text, but it catches a dragged text selection too.
+ */
+export interface NativeDragAdoption {
+ /**
+ * Names this kind of adopted drag. `adopts` is matched against it, a target
+ * reports it as `source.type`, and a monitor or auto-scroll filters on it.
+ */
+ type: string;
+
+ /** Whether this drag should be adopted. Throwing is reported as a refusal. */
+ match: (feedback: NativeDragAdoptionFeedback) => boolean;
+
+ /**
+ * Payload for `source.data`. Reserved routing keys are stamped over it.
+ * Throwing is reported and yields no payload.
+ */
+ getData?: (feedback: NativeDragAdoptionFeedback) => object;
+}
+
+/**
+ * Live targets that might adopt, held so the listener below can ask them.
+ *
+ * Every target joins, not only those with `adopts`. Reading the arg during
+ * registration would track it and re-register the target on unrelated changes.
+ * A DOM listener has no tracking frame open, so reading it there is free.
+ */
+const adoptionCandidates = new Set<() => AdoptionCandidateArgs>();
+
+let stopListeningForAdoption: (() => void) | null = null;
+
+/** The one adoption a drag can have in flight, and how to undo it. */
+let liveAdoption: { release: () => void } | null = null;
+
+/**
+ * Whether this drag started from a text selection, which must never be adopted.
+ *
+ * A selection drag can target a text node, which the `HTMLElement` check
+ * already excludes, but some browsers report the nearest element instead. So
+ * editable ancestry, text controls and the document selection are all asked.
+ */
+function isTextSelectionDrag(target: HTMLElement) {
+ if (target.closest("[contenteditable]:not([contenteditable='false'])")) {
+ return true;
+ }
+ // A text control keeps its selection out of the document's, so the check
+ // below cannot see it. Ask the control itself, and refuse when it will not
+ // answer: some control types report null offsets rather than a range.
+ if (
+ (target instanceof HTMLInputElement ||
+ target instanceof HTMLTextAreaElement) &&
+ (target.selectionStart === null ||
+ target.selectionStart !== target.selectionEnd)
+ ) {
+ return true;
+ }
+ const selection = window.getSelection();
+ return Boolean(
+ selection &&
+ !selection.isCollapsed &&
+ selection.rangeCount > 0 &&
+ selection.containsNode(target, true)
+ );
+}
+
+/**
+ * Reads and copies the payload while it is still available.
+ *
+ * String data is readable during `dragstart`. By `dragover` the store is
+ * protected and item handles cannot be held safely. So the snapshot keeps
+ * strings and types, and exposes an empty `items` rather than dead handles.
+ */
+function snapshotPayload(dataTransfer: DataTransfer): ExternalDragPayload {
+ const types = Array.from(dataTransfer.types);
+ const strings = new Map<string, string>();
+ for (const type of types) {
+ if (type !== "Files") {
+ strings.set(type, dataTransfer.getData(type));
+ }
+ }
+
+ return decorateExternalSource({
+ types,
+ items: [],
+ getStringData: (mediaType: string) => strings.get(mediaType) ?? null,
+ } as Parameters<typeof decorateExternalSource>[0]);
+}
+
+/** The adoptions live targets currently offer, in registration order. */
+function offeredAdoptions() {
+ const offered: NativeDragAdoption[] = [];
+ for (const getArgs of adoptionCandidates) {
+ offered.push(...makeArray(getArgs().adopts));
+ }
+ return offered;
+}
+
+/**
+ * Hands a browser-started drag to the element-drag adapter so ordinary targets
+ * receive it.
+ *
+ * The adapter dispatches only for registered elements, and looks one up while
+ * `dragstart` bubbles. A capture-phase listener on `window` registers in time
+ * for that drag, so adopted content shares the registered sources' dispatch.
+ */
+function adoptNativeDrag(event: DragEvent) {
+ const target = event.target;
+ if (!(target instanceof HTMLElement) || !event.dataTransfer) {
+ return;
+ }
+
+ // Already registered for element-drag dispatch. Registering over it would
+ // replace the real source's entry, and releasing ours would delete theirs.
+ if (target.closest("[data-drag-source]")) {
+ return;
+ }
+
+ // Someone else's explicitly draggable element. Cleanup removes that attribute
+ // unconditionally, so adopting it would strip one we did not add.
+ if (target.hasAttribute("draggable")) {
+ return;
+ }
+
+ if (isTextSelectionDrag(target)) {
+ return;
+ }
+
+ const source = snapshotPayload(event.dataTransfer);
+ if (source.containsFiles()) {
+ return;
+ }
+
+ const feedback = { element: target, source };
+ const adoption = offeredAdoptions().find((candidate) =>
+ // A throw must not stop the candidates after it from being asked.
+ consumerMayThrow(() => candidate.match(feedback), false)
+ );
+
+ if (!adoption) {
+ return;
+ }
+
+ liveAdoption?.release();
+
+ let started = false;
+ let released = false;
+
+ const cleanup = draggable({
+ element: target,
+ getInitialData: () => ({
+ // Copied inside the guard, so a payload that throws while it is read is
+ // caught like one that throws while it is built.
+ ...consumerMayThrow(() => ({ ...adoption.getData?.(feedback) }), {}),
+ // Last, so consumer data cannot overwrite the routing values and disguise
+ // an adopted drag as a registered source, or name a different element as
+ // the one being dragged.
+ type: ADOPTED_DRAG_TYPE,
+ [ADOPTED_AS]: adoption.type,
+ [DRAG_BODY]: target,
+ native: source,
+ }),
+ // Fires synchronously during the originating dispatch. The drag-start
+ // callback runs later, too late to tell a live drag from one that never was.
+ onGenerateDragPreview: () => {
+ started = true;
+ },
+ onDrop: () => release(),
+ });
+
+ const release = () => {
+ if (released) {
+ return;
+ }
+ released = true;
+ cancel(neverStarted);
+ if (liveAdoption?.release === release) {
+ liveAdoption = null;
+ }
+ // A registered source may have claimed this element since adoption. Cleanup
+ // deletes registrations by element, so running ours would tear theirs down.
+ if (!target.hasAttribute("data-drag-source")) {
+ cleanup();
+ }
+ };
+
+ // A drag cancelled before it starts fires no event that would release this
+ // registration. A run-loop task waits for every listener, a microtask would not.
+ const neverStarted = next(() => {
+ if (!started) {
+ release();
+ }
+ });
+
+ liveAdoption = { release };
+}
+
+/** Test-only: releases adoption state and its global listener between tests. */
+export function resetDragAdoptionForTesting() {
+ liveAdoption?.release();
+ liveAdoption = null;
+ adoptionCandidates.clear();
+ stopListeningForAdoption?.();
+ stopListeningForAdoption = null;
+}
+
+/**
+ * Adds a target to the adoption candidates, starting the shared listener.
+ *
+ * @param getArgsRef - Closure returning the target's latest args.
+ * @returns Cleanup; call it once on teardown.
+ */
+export function watchForAdoptableDrags(
+ getArgsRef: () => AdoptionCandidateArgs
+) {
+ adoptionCandidates.add(getArgsRef);
+ if (!stopListeningForAdoption) {
+ window.addEventListener("dragstart", adoptNativeDrag, { capture: true });
+ stopListeningForAdoption = () =>
+ window.removeEventListener("dragstart", adoptNativeDrag, {
+ capture: true,
+ });
+ }
+
+ return () => {
+ adoptionCandidates.delete(getArgsRef);
+ // An adoption already in flight belongs to its drag and must keep the
+ // adapter registration until that drag ends.
+ if (adoptionCandidates.size === 0) {
+ stopListeningForAdoption?.();
+ stopListeningForAdoption = null;
+ }
+ };
+}
diff --git a/frontend/discourse/app/lib/-internals/drag-and-drop/vocabulary.ts b/frontend/discourse/app/lib/-internals/drag-and-drop/vocabulary.ts
index 12a20d5e7db..60b38654145 100644
--- a/frontend/discourse/app/lib/-internals/drag-and-drop/vocabulary.ts
+++ b/frontend/discourse/app/lib/-internals/drag-and-drop/vocabulary.ts
@@ -1,4 +1,5 @@
import type { ElementDragPayload } from "@atlaskit/pragmatic-drag-and-drop/adapter/element-adapter";
+import type { ExternalDragPayload } from "discourse/lib/-internals/drag-and-drop/external-vocabulary";
import { makeArray } from "discourse/lib/helpers";
/**
@@ -19,12 +20,30 @@ export function dragBodyOf(source: ElementDragPayload): HTMLElement {
);
}
+/**
+ * The routing type carried by a browser-started drag after adoption.
+ *
+ * Namespaced because it shares the same field as consumer-defined types. It
+ * must remain a string because the drag library's routing data crosses the same
+ * public surface as ordinary source data.
+ */
+export const ADOPTED_DRAG_TYPE = "discourse:adopted-native-drag";
+
+/** Where an adoption's consumer-facing type travels beside the routing type. */
+export const ADOPTED_AS = "adoptedAs";
+
/**
* The type a drag answers to in an `accepts` / `types` filter.
*
+ * For an adopted drag this is the adoption's declared type, not the internal
+ * routing type, so consumers filter on their own vocabulary either way.
+ *
* @param data - A drag payload's `data`, as the underlying library carries it.
*/
export function dragTypeOf(data?: Record<string, unknown>) {
+ if (data?.type === ADOPTED_DRAG_TYPE) {
+ return data[ADOPTED_AS] as string | undefined;
+ }
return data?.type as string | undefined;
}
@@ -46,18 +65,25 @@ export function matchesDragType(
}
/**
- * A drag source as consumers read it: routing keys removed and the dragged
- * body in place of the handle that carried it.
+ * A drag source as consumers read it: routing keys removed, the type resolved
+ * through the adoption, 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. */
+ /** The payload the source or adoption attached to the drag. */
data: Record<string, unknown>;
/** The dragged element: the published body, else the registered element. */
element: HTMLElement;
+
+ /**
+ * The snapshotted native payload for an adopted drag. Absent for registered
+ * element sources.
+ */
+ native?: ExternalDragPayload;
}
/**
@@ -90,14 +116,19 @@ export function normalizeOwnedDragSource(source: ElementDragPayload): {
export function normalizeDragSource(
source: ElementDragPayload
): NormalizedDragSource {
- const data = { ...(source.data ?? {}) };
- delete data[DRAG_BODY];
+ const { [DRAG_BODY]: body, ...data } = source.data ?? {};
+ const adopted = data.type === ADOPTED_DRAG_TYPE;
+ // The reserved keys route an adopted drag. A consumer iterating `data` must
+ // not meet them.
+ const { [ADOPTED_AS]: adoptedAs, native, ...consumerData } = data;
+ delete consumerData.type;
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),
+ // a string `type` and the adoption its sentinel.
+ type: (adopted ? adoptedAs : (data.type ?? null)) as string | null,
+ data: adopted ? consumerData : data,
+ element: (body as HTMLElement | undefined) ?? source.element,
+ ...(adopted ? { native: native as ExternalDragPayload } : {}),
};
}
diff --git a/frontend/discourse/app/services/drag-and-drop.ts b/frontend/discourse/app/services/drag-and-drop.ts
index 82ba839c3b8..b438a607ddb 100644
--- a/frontend/discourse/app/services/drag-and-drop.ts
+++ b/frontend/discourse/app/services/drag-and-drop.ts
@@ -17,10 +17,10 @@ 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. */
+ /** Discriminator string set by the source or the adoption that claimed it. */
type: string;
- /** Arbitrary payload the source attached to the drag. */
+ /** Arbitrary payload the source or adoption attached to the drag. */
data: Record<string, unknown>;
/**
@@ -28,6 +28,12 @@ export interface DragPayload {
* `setCurrentDrag` supplied none; the service's own monitor always does.
*/
element: HTMLElement | null;
+
+ /**
+ * The snapshotted native payload for a browser-started drag adopted from page
+ * content. Absent for registered element sources.
+ */
+ native?: ExternalDragPayload;
}
/**
@@ -59,6 +65,7 @@ export default class DragAndDropService extends Service {
type: normalized.type as string,
data: normalized.data,
element: normalized.element,
+ ...(normalized.native ? { native: normalized.native } : {}),
});
},
onDrop: () => {
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
index 3e0d7f51574..75e139c1bff 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-auto-scroll.ts
+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-auto-scroll.ts
@@ -28,8 +28,9 @@ interface DDragAndDropAutoScrollSignature {
Args: {
Named: {
/**
- * Only drags whose `type` matches engage the auto-scroll. Omit to engage
- * on any element drag.
+ * Only drags whose `type` matches engage the auto-scroll; an adopted drag
+ * answers to the adoption's declared type. Omit to engage on any element
+ * drag.
*/
types?: string | string[];
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
index dae8415099f..4d939088935 100644
--- a/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-target.ts
+++ b/frontend/discourse/app/ui-kit/modifiers/d-drag-and-drop-target.ts
@@ -9,6 +9,12 @@ import {
type DropTargetKernelFeedback,
registerDropTargetKernel,
} from "discourse/lib/-internals/drag-and-drop/drop-target-kernel";
+import {
+ isAdoptedDrag,
+ type NativeDragAdoption,
+ offersAdoptionFor,
+ watchForAdoptableDrags,
+} from "discourse/lib/-internals/drag-and-drop/native-drag-adoption";
import {
dragBodyOf,
matchesDragType,
@@ -16,13 +22,22 @@ import {
normalizeDragSource,
} from "discourse/lib/-internals/drag-and-drop/vocabulary";
+export type {
+ NativeDragAdoption,
+ NativeDragAdoptionFeedback,
+} from "discourse/lib/-internals/drag-and-drop/native-drag-adoption";
+
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. */
+/**
+ * The dragged source, normalized to the shape `dDragAndDropSource` publishes.
+ * An adopted drag also carries `native`, with the same reader API as an
+ * external target's payload; its `items` is always empty.
+ */
export type DropTargetSource = NormalizedDragSource;
/** What a synchronous gate (`canDrop`, `getDropEffect`) is asked about. */
@@ -38,10 +53,30 @@ export type DropTargetEvent = DropTargetKernelEvent<DropTargetSource>;
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.
+ * Omit to accept any registered source, unless `adopts` is set; then omission
+ * accepts only the adopted drags named there.
*/
accepts?: string | string[];
+ /**
+ * Also accept browser-started drags from page content that no
+ * `dDragAndDropSource` registered, such as native links or images.
+ * Independent of `accepts`, since such content carries no source type;
+ * adopted payloads arrive on `source.native`.
+ *
+ * Adoption is resolved once for the page, not per target. At `dragstart` the
+ * first live adoption whose predicate matches names the drag, and every
+ * target listing that name accepts it.
+ *
+ * So two adoptions sharing a name must share a predicate. Declare one as a
+ * module constant and offer it from each target.
+ *
+ * Covers only what the browser started on this page. Pair it with
+ * `dDragAndDropExternalTarget` on the same element to take the same content
+ * dragged in from outside the window.
+ */
+ adopts?: NativeDragAdoption | NativeDragAdoption[];
+
/**
* `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
@@ -72,6 +107,8 @@ export function registerDragAndDropTarget(
element: Element,
getArgsRef: () => DragAndDropTargetArgs
) {
+ const stopWatchingForAdoption = watchForAdoptableDrags(getArgsRef);
+
return registerDropTargetKernel({
element,
attribute: "data-drop-target",
@@ -79,12 +116,24 @@ export function registerDragAndDropTarget(
decorateSource: (source: ElementDragPayload) => normalizeDragSource(source),
accepts: (source) => {
const args = getArgsRef();
- if (!matchesDragType(args.accepts, source)) {
+ // Computed above every branch, so a filter added later cannot return
+ // without applying it.
+ const acceptsSelf =
+ args.acceptsSelf !== false || dragBodyOf(source) !== element;
+
+ if (isAdoptedDrag(source.data)) {
+ return offersAdoptionFor(source.data, args.adopts) && acceptsSelf;
+ }
+ // A target offering adoption named exactly what it wants through
+ // `adopts`; treating an omitted source filter as "everything" would also
+ // hand it every registered source on the page.
+ if (!args.accepts && args.adopts) {
return false;
}
- return args.acceptsSelf !== false || dragBodyOf(source) !== element;
+ return matchesDragType(args.accepts, source) && acceptsSelf;
},
+ onCleanup: stopWatchingForAdoption,
getArgs: getArgsRef,
});
}
@@ -114,8 +163,9 @@ export function registerDragAndDropTarget(
* `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.
+ * Element drags, and with `adopts` browser-started drags from page content;
+ * see `dDragAndDropExternalTarget` for payloads dragged in from outside the
+ * window.
*/
export default modifier<DDragAndDropTargetSignature>(
(element, _positional, args) =>
diff --git a/frontend/discourse/tests/helpers/qunit-helpers.js b/frontend/discourse/tests/helpers/qunit-helpers.js
index cccadf50f00..8b2b113268e 100644
--- a/frontend/discourse/tests/helpers/qunit-helpers.js
+++ b/frontend/discourse/tests/helpers/qunit-helpers.js
@@ -40,6 +40,7 @@ import { resetCustomUserNavMessagesDropdownRows } from "discourse/controllers/us
import { clearHTMLCache } from "discourse/helpers/custom-html";
import { resetUsernameDecorators } from "discourse/helpers/decorate-username-selector";
import { resetBeforeAuthCompleteCallbacks } from "discourse/instance-initializers/auth-complete";
+import { resetDragAdoptionForTesting } from "discourse/lib/-internals/drag-and-drop/native-drag-adoption";
import { resetAdminPluginConfigNav } from "discourse/lib/admin-plugin-config-nav";
import { clearPluginHeaderActionComponents } from "discourse/lib/admin-plugin-header-actions";
import { resetAdditionalReportModes } from "discourse/lib/admin-report-additional-modes";
@@ -293,6 +294,9 @@ export function testCleanup(container, app) {
resetBlockRegistryForTesting();
resetDebugCallbacks();
resetDragAndDropForTesting();
+ // Run after the drag reset so any active drag releases its own adoption. This
+ // only has to force-release a registration for a drag that never started.
+ resetDragAdoptionForTesting();
resetDragSourcesForTesting();
resetPointerDragForTesting();
resetElementClassLeasesForTesting();
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
index 0121e8c5361..c262c0762b4 100644
--- a/frontend/discourse/tests/helpers/ui-kit/drag-and-drop-helper.ts
+++ b/frontend/discourse/tests/helpers/ui-kit/drag-and-drop-helper.ts
@@ -266,6 +266,52 @@ function registeredElementFor(rowSelector: string) {
return row.querySelector('[draggable="true"]') ?? row;
}
+/**
+ * Drives a browser-started drag from page content no source registered.
+ *
+ * The event sequence matches an element drag. The guards prove the source is
+ * unsourced and the destination is an element target, so this cannot quietly
+ * exercise the registered-source or external path instead.
+ *
+ * @param sourceSelector - CSS selector for the unregistered element to drag.
+ * @param targetSelector - CSS selector for the target element.
+ */
+export async function simulateUnsourcedDrag(
+ sourceSelector: string,
+ targetSelector: string,
+ {
+ dataTransfer,
+ sourceCoordinates,
+ targetCoordinates,
+ }: {
+ dataTransfer: DataTransfer;
+ sourceCoordinates?: Partial<ClientPoint>;
+ targetCoordinates?: Partial<ClientPoint>;
+ }
+) {
+ const sourceElement = document.querySelector(sourceSelector);
+ if (sourceElement?.closest("[data-drag-source]")) {
+ throw new Error(
+ `${sourceSelector} is inside a registered drag source, so this would exercise the sourced path instead of adoption`
+ );
+ }
+
+ const targetElement = document.querySelector(targetSelector);
+ if (!targetElement?.hasAttribute("data-drop-target")) {
+ throw new Error(
+ `${targetSelector} is not a registered element drop target, so this drag would do nothing`
+ );
+ }
+
+ const source = { ...centerOf(sourceSelector), ...sourceCoordinates };
+ const target = { ...centerOf(targetSelector), ...targetCoordinates };
+ await dragEvent(sourceSelector, "dragstart", { dataTransfer, ...source });
+ await dragEvent(targetSelector, "dragenter", { dataTransfer, ...target });
+ await dragEvent(targetSelector, "dragover", { dataTransfer, ...target });
+ await dragEvent(targetSelector, "drop", { dataTransfer, ...target });
+ await dragEvent(sourceSelector, "dragend", { dataTransfer, ...source });
+}
+
/**
* Brings an external drag over a target and leaves it hovering there, without
* dropping.
diff --git a/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-adoption-test.gjs b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-adoption-test.gjs
new file mode 100644
index 00000000000..3760a276acc
--- /dev/null
+++ b/frontend/discourse/tests/integration/ui-kit/modifiers/d-drag-and-drop-adoption-test.gjs
@@ -0,0 +1,960 @@
+import { hash } from "@ember/helper";
+import { find, render, setupOnerror } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import {
+ centerOf,
+ dragEvent,
+ fileTransfer,
+ simulateDrag,
+ simulateUnsourcedDrag,
+ 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 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 | dDragAndDropAdoption",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ const WEB_LINK = {
+ type: "web-link",
+ match: ({ element }) => Boolean(element.closest("a[href]")),
+ };
+
+ /**
+ * Claims anything, so a test can prove a guard refuses a drag before any
+ * predicate is consulted.
+ */
+ const ANY_CONTENT = {
+ type: "any-content",
+ match: () => true,
+ };
+
+ function linkTransfer() {
+ const dataTransfer = new DataTransfer();
+ dataTransfer.setData("text/uri-list", "https://example.com/adopted");
+ dataTransfer.setData("text/plain", "https://example.com/adopted");
+ return dataTransfer;
+ }
+
+ module("adopting an unsourced drag", function () {
+ test("delivers a browser-started link through the ordinary target", async function (assert) {
+ let seen = null;
+ const onDrop = ({ source }) => {
+ seen = { type: source.type, urls: source.native.getURLs() };
+ };
+
+ await render(
+ <template>
+ <a id="anchor" href="https://example.com/adopted">a link</a>
+ <div
+ id="zone"
+ {{dDragAndDropTarget adopts=WEB_LINK onDrop=onDrop}}
+ >zone</div>
+ </template>
+ );
+
+ await simulateUnsourcedDrag("#anchor", "#zone", {
+ dataTransfer: linkTransfer(),
+ });
+
+ assert.deepEqual(
+ seen,
+ { type: "web-link", urls: ["https://example.com/adopted"] },
+ "the target reports the adoption's type and the snapshotted native payload"
+ );
+ });
+
+ test("the service reports the adoption without routing keys", async function (assert) {
+ // A target strips the adoption's routing keys before a consumer sees
+ // them; the service must expose the same shape.
+ const dragAndDrop = this.owner.lookup("service:drag-and-drop");
+
+ await render(
+ <template>
+ <a id="anchor" href="https://example.com/adopted">a link</a>
+ <div id="zone" {{dDragAndDropTarget adopts=WEB_LINK}}>zone</div>
+ </template>
+ );
+
+ const dataTransfer = linkTransfer();
+ await dragEvent("#anchor", "dragstart", {
+ dataTransfer,
+ ...centerOf("#anchor"),
+ });
+
+ assert.strictEqual(
+ dragAndDrop.currentDrag.type,
+ "web-link",
+ "currentDrag.type is the adoption's own type"
+ );
+ assert.deepEqual(
+ dragAndDrop.currentDrag.data,
+ {},
+ "routing keys never reach currentDrag.data"
+ );
+ assert.deepEqual(
+ dragAndDrop.currentDrag.native.getURLs(),
+ ["https://example.com/adopted"],
+ "the native payload sits beside consumer data"
+ );
+
+ await dragEvent("#anchor", "dragend", {
+ dataTransfer,
+ ...centerOf("#anchor"),
+ });
+
+ assert.strictEqual(
+ dragAndDrop.currentDrag,
+ null,
+ "the service clears the adopted drag when it ends"
+ );
+ });
+
+ test("an adoption's payload cannot disguise it as a registered source", async function (assert) {
+ const spoofing = {
+ type: "web-link",
+ match: () => true,
+ getData: () => ({ id: 7, type: "spoofed", adoptedAs: "spoofed" }),
+ };
+ let seen = null;
+ const onDrop = ({ source }) => {
+ seen = { type: source.type, data: source.data };
+ };
+
+ await render(
+ <template>
+ <a id="anchor" href="https://example.com/adopted">a link</a>
+ <div
+ id="zone"
+ {{dDragAndDropTarget adopts=spoofing onDrop=onDrop}}
+ >zone</div>
+ </template>
+ );
+
+ await simulateUnsourcedDrag("#anchor", "#zone", {
+ dataTransfer: linkTransfer(),
+ });
+
+ assert.deepEqual(
+ seen,
+ { type: "web-link", data: { id: 7 } },
+ "the declared type survives and the routing keys reach no consumer"
+ );
+ });
+
+ test("an adoption cannot pass off another element as the dragged one", async function (assert) {
+ const spoofing = {
+ type: "web-link",
+ match: () => true,
+ // The key a handle uses to publish the row it drags on behalf of.
+ getData: () => ({ "discourse:dragBody": find("#decoy") }),
+ };
+ let seen = null;
+ const onDrop = ({ source }) => {
+ seen = source.element.id;
+ };
+
+ await render(
+ <template>
+ <a id="anchor" href="https://example.com/adopted">a link</a>
+ <div id="decoy">decoy</div>
+ <div
+ id="zone"
+ {{dDragAndDropTarget adopts=spoofing onDrop=onDrop}}
+ >zone</div>
+ </template>
+ );
+
+ await simulateUnsourcedDrag("#anchor", "#zone", {
+ dataTransfer: linkTransfer(),
+ });
+
+ assert.strictEqual(
+ seen,
+ "anchor",
+ "a target reports the element the browser dragged, not one the payload named"
+ );
+ });
+
+ test("nested targets sharing one adoption deliver to the deepest", async function (assert) {
+ const drops = [];
+ const onOuter = () => drops.push("outer");
+ const onInner = () => drops.push("inner");
+
+ await render(
+ <template>
+ <a id="anchor" href="https://example.com/adopted">a link</a>
+ <div
+ id="outer"
+ {{dDragAndDropTarget adopts=WEB_LINK onDrop=onOuter}}
+ >
+ <div
+ id="inner"
+ {{dDragAndDropTarget adopts=WEB_LINK onDrop=onInner}}
+ >inner</div>
+ </div>
+ </template>
+ );
+
+ await simulateUnsourcedDrag("#anchor", "#inner", {
+ dataTransfer: linkTransfer(),
+ });
+
+ assert.deepEqual(
+ drops,
+ ["inner"],
+ "one adoption shared by a zone and its sections lands once, deepest first"
+ );
+ });
+
+ test("an adopted drag onto its own element lands by default", async function (assert) {
+ const drops = [];
+ const onDrop = () => drops.push("dropped");
+
+ await render(
+ <template>
+ <a
+ id="anchor"
+ href="https://example.com/adopted"
+ {{dDragAndDropTarget adopts=WEB_LINK onDrop=onDrop}}
+ >a link</a>
+ </template>
+ );
+
+ await simulateUnsourcedDrag("#anchor", "#anchor", {
+ dataTransfer: linkTransfer(),
+ });
+
+ assert.deepEqual(
+ drops,
+ ["dropped"],
+ "content that is both adoptable and a target accepts its own drag"
+ );
+ });
+
+ test("an adopted drag onto its own element is refused when acceptsSelf is false", async function (assert) {
+ const drops = [];
+ const onDrop = () => drops.push("dropped");
+
+ await render(
+ <template>
+ <a
+ id="anchor"
+ href="https://example.com/adopted"
+ {{dDragAndDropTarget
+ acceptsSelf=false
+ adopts=WEB_LINK
+ onDrop=onDrop
+ }}
+ >a link</a>
+ </template>
+ );
+
+ await simulateUnsourcedDrag("#anchor", "#anchor", {
+ dataTransfer: linkTransfer(),
+ });
+
+ assert.deepEqual(
+ drops,
+ [],
+ "acceptsSelf governs an adopted drag as it does a registered one"
+ );
+ });
+ });
+
+ module("what adoption refuses", function () {
+ test("a target that did not name it refuses an adopted drag", async function (assert) {
+ const drops = [];
+ const onAdopting = () => drops.push("adopting");
+ const onPlain = () => drops.push("plain");
+
+ await render(
+ <template>
+ <a id="anchor" href="https://example.com/adopted">a link</a>
+ <div
+ id="adopting"
+ {{dDragAndDropTarget adopts=WEB_LINK onDrop=onAdopting}}
+ >adopting</div>
+ <div id="plain" {{dDragAndDropTarget onDrop=onPlain}}>plain</div>
+ </template>
+ );
+
+ await simulateUnsourcedDrag("#anchor", "#plain", {
+ dataTransfer: linkTransfer(),
+ });
+
+ assert.deepEqual(
+ drops,
+ [],
+ "an omitted accepts filter does not admit a drag another target's adoption named"
+ );
+
+ await simulateUnsourcedDrag("#anchor", "#adopting", {
+ dataTransfer: linkTransfer(),
+ });
+
+ assert.deepEqual(
+ drops,
+ ["adopting"],
+ "while the target that named it receives the drop"
+ );
+ });
+
+ test("a target that only adopts refuses a registered source", async function (assert) {
+ const drops = [];
+ const onDrop = () => drops.push("dropped");
+
+ await render(
+ <template>
+ <div id="row" {{dDragAndDropSource type="row"}}>a row</div>
+ <div
+ id="zone"
+ {{dDragAndDropTarget adopts=WEB_LINK onDrop=onDrop}}
+ >zone</div>
+ </template>
+ );
+
+ await simulateDrag("#row", "#zone", {
+ dataTransfer: new DataTransfer(),
+ });
+
+ assert.deepEqual(
+ drops,
+ [],
+ "an omitted accepts filter beside adopts takes no source on the page"
+ );
+ });
+
+ test("a registered source is not adopted from under itself", async function (assert) {
+ const drops = [];
+ const onDrop = ({ source }) => drops.push(source.type);
+
+ await render(
+ <template>
+ <div id="row" {{dDragAndDropSource type="row" data=(hash id=1)}}>
+ <a id="inner" href="https://example.com/adopted">a link</a>
+ </div>
+ <div
+ id="zone"
+ {{dDragAndDropTarget accepts="row" adopts=WEB_LINK onDrop=onDrop}}
+ >zone</div>
+ </template>
+ );
+
+ await simulateDrag("#row", "#zone", { dataTransfer: linkTransfer() });
+
+ assert.deepEqual(
+ drops,
+ ["row"],
+ "the registered source retains its own type and lifecycle"
+ );
+ });
+
+ test("a dragged text selection is not adopted", async function (assert) {
+ const drops = [];
+ const onDrop = () => drops.push("dropped");
+
+ await render(
+ <template>
+ {{! A selected URL can produce a dragstart whose payload looks
+ exactly like a dragged link. }}
+ <a id="inner" href="https://example.com/adopted">a link</a>
+ <div
+ id="zone"
+ {{dDragAndDropTarget adopts=WEB_LINK onDrop=onDrop}}
+ >zone</div>
+ </template>
+ );
+
+ const range = document.createRange();
+ range.selectNodeContents(find("#inner"));
+ window.getSelection().removeAllRanges();
+ window.getSelection().addRange(range);
+
+ await simulateUnsourcedDrag("#inner", "#zone", {
+ dataTransfer: linkTransfer(),
+ });
+
+ window.getSelection().removeAllRanges();
+
+ assert.deepEqual(
+ drops,
+ [],
+ "editing text is not repurposed as a drag, however link-shaped its payload"
+ );
+ });
+
+ test("a selection dragged out of a text control is not adopted", async function (assert) {
+ const drops = [];
+ const onDrop = () => drops.push("dropped");
+
+ await render(
+ <template>
+ {{! A text control keeps its selection to itself, so the document
+ selection stays collapsed while this one is held. }}
+ <textarea id="notes">hello world</textarea>
+ <div
+ id="zone"
+ {{dDragAndDropTarget adopts=ANY_CONTENT onDrop=onDrop}}
+ >zone</div>
+ </template>
+ );
+
+ find("#notes").setSelectionRange(0, 5);
+
+ await simulateUnsourcedDrag("#notes", "#zone", {
+ dataTransfer: textTransfer("hello"),
+ });
+
+ assert.deepEqual(
+ drops,
+ [],
+ "text dragged out of a text control is a selection, whatever its payload looks like"
+ );
+ });
+
+ test("a selection dragged out of a text input is not adopted", async function (assert) {
+ const drops = [];
+ const onDrop = () => drops.push("dropped");
+
+ await render(
+ <template>
+ <input id="query" type="text" value="hello world" />
+ <div
+ id="zone"
+ {{dDragAndDropTarget adopts=ANY_CONTENT onDrop=onDrop}}
+ >zone</div>
+ </template>
+ );
+
+ find("#query").setSelectionRange(0, 5);
+
+ await simulateUnsourcedDrag("#query", "#zone", {
+ dataTransfer: textTransfer("hello"),
+ });
+
+ assert.deepEqual(
+ drops,
+ [],
+ "a single-line control holds a selection the same way a multi-line one does"
+ );
+ });
+
+ test("a text control that hides its selection offsets is not adopted", async function (assert) {
+ const drops = [];
+ const onDrop = () => drops.push("dropped");
+
+ await render(
+ <template>
+ {{! Some control types report null offsets rather than a range, so
+ whether a selection is held cannot be read back from them. }}
+ <input id="address" type="email" value="[email protected]" />
+ <div
+ id="zone"
+ {{dDragAndDropTarget adopts=ANY_CONTENT onDrop=onDrop}}
+ >zone</div>
+ </template>
+ );
+
+ await simulateUnsourcedDrag("#address", "#zone", {
+ dataTransfer: textTransfer("[email protected]"),
+ });
+
+ assert.deepEqual(
+ drops,
+ [],
+ "a control that cannot answer is refused rather than adopted"
+ );
+ });
+
+ test("a text control holding no selection is still adoptable", async function (assert) {
+ const drops = [];
+ const onDrop = () => drops.push("dropped");
+
+ await render(
+ <template>
+ <textarea id="notes">hello world</textarea>
+ <div
+ id="zone"
+ {{dDragAndDropTarget adopts=ANY_CONTENT onDrop=onDrop}}
+ >zone</div>
+ </template>
+ );
+
+ await simulateUnsourcedDrag("#notes", "#zone", {
+ dataTransfer: textTransfer("hello"),
+ });
+
+ assert.deepEqual(
+ drops,
+ ["dropped"],
+ "the selection is what is refused, not the control it was held in"
+ );
+ });
+
+ test("a file drag is not adopted", async function (assert) {
+ const drops = [];
+ const onDrop = () => drops.push("dropped");
+
+ await render(
+ <template>
+ <a id="anchor" href="https://example.com/adopted">a link</a>
+ <div
+ id="zone"
+ {{dDragAndDropTarget adopts=ANY_CONTENT onDrop=onDrop}}
+ >zone</div>
+ </template>
+ );
+
+ await simulateUnsourcedDrag("#anchor", "#zone", {
+ dataTransfer: fileTransfer(),
+ });
+
+ assert.deepEqual(
+ drops,
+ [],
+ "files reach an external target, not this one"
+ );
+ assert.false(
+ find("#anchor").hasAttribute("draggable"),
+ "and nothing is registered on the element it started from"
+ );
+ });
+
+ test("content that declares its own draggable is not adopted", async function (assert) {
+ const drops = [];
+ const onDrop = () => drops.push("dropped");
+
+ await render(
+ <template>
+ <div id="widget" draggable="true">a widget</div>
+ <div
+ id="zone"
+ {{dDragAndDropTarget adopts=ANY_CONTENT onDrop=onDrop}}
+ >zone</div>
+ </template>
+ );
+
+ await simulateUnsourcedDrag("#widget", "#zone", {
+ dataTransfer: textTransfer(),
+ });
+
+ assert.deepEqual(
+ drops,
+ [],
+ "an element somebody else made draggable keeps its own drag"
+ );
+ assert.strictEqual(
+ find("#widget").getAttribute("draggable"),
+ "true",
+ "and the attribute adoption would have removed is left alone"
+ );
+ });
+ });
+
+ module("resolving which adoption claims a drag", function () {
+ const BOOKMARK = { type: "bookmark", match: () => true };
+ const ATTACHMENT = { type: "attachment", match: () => true };
+
+ test("the first live target to match names the drag", async function (assert) {
+ const drops = [];
+ const onFirst = () => drops.push("first");
+ const onSecond = () => drops.push("second");
+
+ await render(
+ <template>
+ <a id="anchor" href="https://example.com/adopted">a link</a>
+ <div
+ id="first"
+ {{dDragAndDropTarget adopts=BOOKMARK onDrop=onFirst}}
+ >first</div>
+ <div
+ id="second"
+ {{dDragAndDropTarget adopts=ATTACHMENT onDrop=onSecond}}
+ >second</div>
+ </template>
+ );
+
+ await simulateUnsourcedDrag("#anchor", "#second", {
+ dataTransfer: linkTransfer(),
+ });
+
+ assert.deepEqual(
+ drops,
+ [],
+ "a later target does not receive a drag the first one already named"
+ );
+
+ await simulateUnsourcedDrag("#anchor", "#first", {
+ dataTransfer: linkTransfer(),
+ });
+
+ assert.deepEqual(
+ drops,
+ ["first"],
+ "adoption is resolved once for the page, in target registration order"
+ );
+ });
+
+ test("a drag the browser refuses releases its adoption", async function (assert) {
+ const drops = [];
+ const onDrop = () => drops.push("dropped");
+
+ await render(
+ <template>
+ <a id="anchor" href="https://example.com/adopted">a link</a>
+ <a id="other" href="https://example.com/other">another link</a>
+ <div
+ id="zone"
+ {{dDragAndDropTarget adopts=WEB_LINK onDrop=onDrop}}
+ >zone</div>
+ </template>
+ );
+
+ // Runs after adoption's window listener and before the drag
+ // library's, so the drag it just registered for never begins.
+ const refuse = (event) => event.preventDefault();
+ document.addEventListener("dragstart", refuse, { capture: true });
+ try {
+ await dragEvent("#anchor", "dragstart", {
+ dataTransfer: linkTransfer(),
+ ...centerOf("#anchor"),
+ });
+ } finally {
+ document.removeEventListener("dragstart", refuse, { capture: true });
+ }
+
+ assert.false(
+ find("#anchor").hasAttribute("draggable"),
+ "a drag that never began leaves no registration behind"
+ );
+
+ await simulateUnsourcedDrag("#other", "#zone", {
+ dataTransfer: linkTransfer(),
+ });
+
+ assert.deepEqual(
+ drops,
+ ["dropped"],
+ "and the next drag is adopted normally"
+ );
+ });
+ });
+
+ module("a consumer that throws", function () {
+ const blowUp = () => {
+ throw new Error("consumer blew up");
+ };
+
+ test("a throwing adoption predicate is reported and leaves later ones to decide", async function (assert) {
+ const broken = { type: "broken", match: blowUp };
+ 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 drops = [];
+ const onDrop = ({ source }) => drops.push(source.type);
+
+ await render(
+ <template>
+ <a id="anchor" href="https://example.com/adopted">a link</a>
+ <div id="broken" {{dDragAndDropTarget adopts=broken}}>broken</div>
+ <div
+ id="zone"
+ {{dDragAndDropTarget adopts=WEB_LINK onDrop=onDrop}}
+ >zone</div>
+ </template>
+ );
+
+ try {
+ await simulateUnsourcedDrag("#anchor", "#zone", {
+ dataTransfer: linkTransfer(),
+ });
+
+ assert.strictEqual(
+ reported.length,
+ 1,
+ "the failure reaches the application rather than vanishing"
+ );
+ assert.deepEqual(
+ notices,
+ ["broken_drag_and_drop_alert"],
+ "through the channel that reaches admins in production"
+ );
+ assert.deepEqual(
+ drops,
+ ["web-link"],
+ "and a later adoption still gets to claim the drag"
+ );
+ } finally {
+ document.removeEventListener("discourse-error", collect);
+ }
+ });
+
+ test("a throwing adoption getData is reported and the drag still lands", async function (assert) {
+ const clumsy = { type: "web-link", match: () => true, getData: blowUp };
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+
+ const notices = [];
+ const collect = (event) => notices.push(event.detail.messageKey);
+ document.addEventListener("discourse-error", collect);
+
+ let seen = null;
+ const onDrop = ({ source }) => {
+ seen = { type: source.type, data: source.data };
+ };
+
+ await render(
+ <template>
+ <a id="anchor" href="https://example.com/adopted">a link</a>
+ <div
+ id="zone"
+ {{dDragAndDropTarget adopts=clumsy onDrop=onDrop}}
+ >zone</div>
+ </template>
+ );
+
+ try {
+ await simulateUnsourcedDrag("#anchor", "#zone", {
+ dataTransfer: linkTransfer(),
+ });
+
+ assert.strictEqual(
+ reported.length,
+ 1,
+ "the failure reaches the application rather than vanishing"
+ );
+ assert.deepEqual(
+ notices,
+ ["broken_drag_and_drop_alert"],
+ "through the channel that reaches admins in production"
+ );
+ assert.deepEqual(
+ seen,
+ { type: "web-link", data: {} },
+ "and the drag lands carrying no consumer data, rather than not at all"
+ );
+ } finally {
+ document.removeEventListener("discourse-error", collect);
+ }
+ });
+ });
+
+ module("a consumer whose payload throws while it is read", function () {
+ test("an adoption payload that throws while being read is reported", async function (assert) {
+ const clumsy = {
+ type: "web-link",
+ match: () => true,
+ // Throws while the payload is copied, not while it is built.
+ getData: () => ({
+ get id() {
+ throw new Error("consumer blew up");
+ },
+ }),
+ };
+ const reported = [];
+ setupOnerror((error) => reported.push(error));
+
+ const notices = [];
+ const collect = (event) => notices.push(event.detail.messageKey);
+ document.addEventListener("discourse-error", collect);
+
+ let seen = null;
+ const onDrop = ({ source }) => {
+ seen = { type: source.type, data: source.data };
+ };
+
+ await render(
+ <template>
+ <a id="anchor" href="https://example.com/adopted">a link</a>
+ <div
+ id="zone"
+ {{dDragAndDropTarget adopts=clumsy onDrop=onDrop}}
+ >zone</div>
+ </template>
+ );
+
+ try {
+ await simulateUnsourcedDrag("#anchor", "#zone", {
+ dataTransfer: linkTransfer(),
+ });
+
+ assert.strictEqual(
+ reported.length,
+ 1,
+ "reading the payload is inside the boundary, not outside it"
+ );
+ assert.deepEqual(
+ notices,
+ ["broken_drag_and_drop_alert"],
+ "through the channel that reaches admins in production"
+ );
+ assert.deepEqual(
+ seen,
+ { type: "web-link", data: {} },
+ "and the drag lands carrying no consumer data"
+ );
+ } finally {
+ document.removeEventListener("discourse-error", collect);
+ }
+ });
+ });
+
+ module("native browser behavior", function () {
+ /**
+ * Dispatches dragover and returns the event so the test can observe
+ * whether the page claimed 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;
+ }
+
+ /**
+ * A real `DataTransfer` whose `effectAllowed` retains synthetic writes.
+ * The native setter ignores them outside a browser-driven drag data store.
+ */
+ function recordingTransfer(effectAllowed) {
+ const dataTransfer = new DataTransfer();
+ Object.defineProperty(dataTransfer, "effectAllowed", {
+ value: effectAllowed,
+ });
+ return dataTransfer;
+ }
+
+ test("dead space remains available to the browser", async function (assert) {
+ const dataTransfer = linkTransfer();
+
+ await render(
+ <template>
+ <a id="anchor" href="https://example.com/adopted">a link</a>
+ <div id="zone" {{dDragAndDropTarget adopts=WEB_LINK}}>zone</div>
+ <div id="nowhere">not a drop target</div>
+ </template>
+ );
+
+ await dragEvent("#anchor", "dragstart", {
+ dataTransfer,
+ ...centerOf("#anchor"),
+ });
+
+ const event = await dragOverAndReturnEvent("#nowhere", dataTransfer);
+
+ assert.false(
+ event.defaultPrevented,
+ "an adopted payload can still be dropped somewhere the app does not own"
+ );
+ });
+
+ test("the browser's allowed effects remain unchanged", async function (assert) {
+ const dataTransfer = recordingTransfer("all");
+ dataTransfer.setData("text/uri-list", "https://example.com/adopted");
+
+ await render(
+ <template>
+ <a id="anchor" href="https://example.com/adopted">a link</a>
+ <div id="zone" {{dDragAndDropTarget adopts=WEB_LINK}}>zone</div>
+ </template>
+ );
+
+ await dragEvent("#anchor", "dragstart", {
+ dataTransfer,
+ ...centerOf("#anchor"),
+ });
+
+ assert.strictEqual(
+ dataTransfer.effectAllowed,
+ "all",
+ "adoption does not narrow what the browser permits"
+ );
+ });
+ });
+
+ module("auto-scroll", function () {
+ /**
+ * Holds a drag near the container's bottom edge across several frames.
+ * Auto-scroll eases in over time, so a single event moves nothing.
+ */
+ async function hoverNearBottomEdge(sourceSelector, dataTransfer) {
+ await dragEvent(sourceSelector, "dragstart", {
+ dataTransfer,
+ ...centerOf(sourceSelector),
+ });
+
+ const { left, bottom, width } =
+ find("#scroller").getBoundingClientRect();
+ const point = { clientX: left + width / 2, clientY: bottom - 2 };
+
+ await dragEvent("#scroller", "dragenter", { dataTransfer, ...point });
+ for (let frame = 0; frame < 12; frame++) {
+ await dragEvent("#scroller", "dragover", { dataTransfer, ...point });
+ }
+ }
+
+ const scroller = <template>
+ <a id="anchor" href="https://example.com/adopted">a link</a>
+ <div id="row" {{dDragAndDropSource type="row"}}>a registered row</div>
+ <div
+ id="scroller"
+ style="height: 100px; overflow-y: auto"
+ {{dDragAndDropTarget adopts=WEB_LINK}}
+ {{dDragAndDropAutoScroll types=@types}}
+ >
+ <div style="height: 600px">tall</div>
+ </div>
+ </template>;
+
+ test("engages for the adoption's declared type", async function (assert) {
+ await render(<template><scroller @types="web-link" /></template>);
+
+ await hoverNearBottomEdge("#anchor", linkTransfer());
+
+ assert.true(
+ find("#scroller").scrollTop > 0,
+ "consumers filter an adopted drag using the type they declared"
+ );
+ });
+
+ test("ignores an adopted drag of another type", async function (assert) {
+ await render(<template><scroller @types="card" /></template>);
+
+ await hoverNearBottomEdge("#anchor", linkTransfer());
+
+ assert.strictEqual(
+ find("#scroller").scrollTop,
+ 0,
+ "adoption is not a license to match every browser-started drag"
+ );
+ });
+
+ test("an adoption type does not match a registered source", async function (assert) {
+ await render(<template><scroller @types="web-link" /></template>);
+
+ await hoverNearBottomEdge("#row", linkTransfer());
+
+ assert.strictEqual(
+ find("#scroller").scrollTop,
+ 0,
+ "a registered source retains its own type for auto-scroll"
+ );
+ });
+ });
+ }
+);
diff --git a/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-adoption-errors-test.gts b/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-adoption-errors-test.gts
new file mode 100644
index 00000000000..d0b440a922f
--- /dev/null
+++ b/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-adoption-errors-test.gts
@@ -0,0 +1,20 @@
+// Negative type assertions for native drag adoption: every invocation below
+// must fail. They are quarantined because an expected Glint error suppresses
+// reporting elsewhere in its file.
+import { hash } from "@ember/helper";
+import dDragAndDropTarget from "discourse/ui-kit/modifiers/d-drag-and-drop-target";
+
+declare const noop: () => void;
+
+const Negatives = <template>
+ {{! @glint-expect-error - adoption requires a predicate, not an external kind }}
+ <div {{dDragAndDropTarget adopts="urls"}}></div>
+
+ {{! @glint-expect-error - an adoption needs a consumer-facing type }}
+ <div {{dDragAndDropTarget adopts=(hash match=noop)}}></div>
+
+ {{! @glint-expect-error - the adoption predicate must return a decision }}
+ <div {{dDragAndDropTarget adopts=(hash type="web-link" match=noop)}}></div>
+</template>;
+
+export default Negatives;
diff --git a/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-adoption-test.gts b/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-adoption-test.gts
new file mode 100644
index 00000000000..8b68de97f66
--- /dev/null
+++ b/frontend/discourse/type-tests/ui-kit/d-drag-and-drop-adoption-test.gts
@@ -0,0 +1,38 @@
+// Positive template invocations for native drag adoption, asserting the target
+// and auto-scroll Signatures resolve together. Keep this file free of Glint
+// directives: one expected error would suppress unrelated declaration failures.
+import { hash } from "@ember/helper";
+import dDragAndDropAutoScroll from "discourse/ui-kit/modifiers/d-drag-and-drop-auto-scroll";
+import dDragAndDropTarget, {
+ type NativeDragAdoptionFeedback,
+} from "discourse/ui-kit/modifiers/d-drag-and-drop-target";
+
+declare const noop: () => void;
+declare function matchesLink(feedback: NativeDragAdoptionFeedback): boolean;
+declare function linkData(
+ feedback: NativeDragAdoptionFeedback
+): Record<string, unknown>;
+
+const Positives = <template>
+ {{! An element target can adopt browser-started page content by predicate }}
+ <div
+ {{dDragAndDropTarget
+ adopts=(hash type="web-link" match=matchesLink getData=linkData)
+ onDrop=noop
+ }}
+ ></div>
+
+ {{! Registered and adopted source vocabularies can coexist on one target }}
+ <div
+ {{dDragAndDropTarget
+ accepts="card"
+ adopts=(hash type="web-link" match=matchesLink)
+ onDrop=noop
+ }}
+ ></div>
+
+ {{! Auto-scroll sees the adoption's declared type like any element drag }}
+ <div {{dDragAndDropAutoScroll types="web-link"}}></div>
+</template>;
+
+export default Positives;