Documentation
Guides

Drag and drop

Move items with the pointer or the keyboard, draw the drop indicator, restrict what moves and where, and announce each step to screen readers.

Drag and drop is a feature: dragAndDrop(), from @fragiola/tree-react/drag-and-drop (@fragiola/tree-vue/drag-and-drop, @fragiola/tree-angular/drag-and-drop). With it, a row dragged with the mouse, a finger or a pen moves its item (and the rest of the selection, when it is selected) with one item.move. The package brings the gesture (Pointer Events, a movement threshold, auto-expanding folders, auto-scroll), the drop evaluation and the keyboard drag; the indicator's look and the announcements are yours. A tree without it never drags, and does not ship its code. Three more features extend it, each from its own entry: dragGroup() (between trees), foreignDrop() (files and links from outside) and dropOutside() (rows dropped on your own targets).

import { createTreeModel, Tree } from "@fragiola/tree-react";
import { DropIndicator, dragAndDrop } from "@fragiola/tree-react/drag-and-drop";

// the toggle and a grip come before the label: the drop line starts after them
const features = [dragAndDrop({ indicatorInset: 30 })] as const;
const model = createTreeModel<Types, typeof features>(json, { features });

dragAndDrop(options) takes dragThreshold (px a press moves before it is a drag, default 4), autoExpandDelay (ms a hovered collapsed parent waits before it expands, default 800), indentation (px of one level, default 16), indicatorInset (px a drop line starts past its level, default 0) and autoScroll ({ threshold, speed }). The features are the model's, fixed when it is created (Features).

The drop indicator

Render DropIndicator (from the feature's entry) inside the root. It exists only while there is a drop target, and is absolutely positioned in the root: a zero-height line for before and after, the row's box for inside. Draw it with data-drop-position:

<Tree.Root model={model} aria-label="Project files">
    <Tree.Items<Types>>{(item) => <FileItem item={item} />}</Tree.Items>
    <DropIndicator className="drop-indicator" />
</Tree.Root>
.drop-indicator[data-drop-position="before"],
.drop-indicator[data-drop-position="after"] {
    border-top: 2px solid #2563eb;
    margin-top: -1px;
}
.drop-indicator[data-drop-position="inside"] {
    border: 2px solid #2563eb;
    border-radius: 4px;
}

The rows carry the drag too: data-dragging on the dragged items, data-drop-target and data-drop-position on the item the target is relative to, and data-dragging on the root.

Drag and drop
Gallery

How a target is chosen

Over a row, the top third drops before it, the bottom third after it, and the middle third inside it, for a row that takes children; a row that takes none splits in halves. At the end of a sublist, the pointer's inline position picks the level, in steps of the root's indentation (default 16 pixels). A collapsed parent hovered for autoExpandDelay milliseconds (default 800) expands, and the nearest scroll container scrolls near its edges.

A press becomes a drag after it moves dragThreshold pixels (default 4), so a click still selects. A press on a button, a link, an input, the toggle or an element with data-tree-no-drag (your check control) never starts one.

Restricting moves

The rules are the commands': the engine asks model.can("item.move", …) for every target, and a refused target never shows. Set the permission flags in the document, per item or as defaults:

const json: TreeJson<Types> = {
    version: 1,
    settings: { movable: true, droppable: true },
    rootItemIds: ["src", "vendor", "license"],
    items: {
        src: { kind: "folder", label: "src", childItemIds: [] },
        vendor: { kind: "folder", label: "vendor", droppable: false, childItemIds: [] },
        license: { kind: "file", label: "LICENSE", movable: false },
    },
};

A disabled item is neither moved nor dropped into, and an item never goes inside itself. For rules of your own (nothing into the archive), write a middleware: a drag's hover asks it too, as a dry run.

import { veto } from "@fragiola/tree-react";

model.use((ctx, next) =>
    ctx.command === "item.move" && ctx.payload.to.parentItemId === "archive"
        ? veto("The archive is read-only.")
        : next(),
);

Turn dragging off for the whole tree with settings.movable: false. See Middleware and permissions.

The keyboard drag

Ctrl/Cmd + Shift + D ("start-drag") picks up the selection, or the focused item. ArrowDown and ArrowUp step through the targets the model accepts, Enter drops and Escape cancels. Start one from code with engine.run("start-keyboard-drag", { itemIds }), from a "Move" menu item for example:

function MoveButton({ itemId }: { itemId: string }) {
    const { engine } = useTree<Types>();
    return (
        <button type="button" onClick={() => engine.run("start-keyboard-drag", { itemIds: [itemId] })}>
            Move
        </button>
    );
}

Announcing the drag

announce returns the live region's text for each event: drag-start, drag-over (with the target, or null when there is no valid one), drop and drag-cancel (and drop-outside, foreign-drag-over and foreign-drop, below). Render Tree.LiveRegion, visually hidden:

import type { AnnounceEvent, DropTarget, TreeModel } from "@fragiola/tree-react";

function announcer(model: TreeModel<Types>) {
    const label = (itemId: string | null) =>
        itemId === null ? "the tree" : (model.get("item-by", { id: itemId })?.label ?? itemId);
    const where = (target: DropTarget) =>
        target.position === "inside" ? `into ${label(target.itemId)}` : `${target.position} ${label(target.itemId)}`;
    return (event: AnnounceEvent): string | undefined => {
        switch (event.type) {
            case "drag-start":
                // a keyboard drag's start comes with its first target, in one message
                return event.target
                    ? `Picked up ${event.itemIds.map(label).join(", ")}. Drop ${where(event.target)}.`
                    : `Picked up ${event.itemIds.map(label).join(", ")}.`;
            case "drag-over":
                return event.target ? `Drop ${where(event.target)}.` : "No place to drop here.";
            case "drop":
                return `Moved ${event.itemIds.map(label).join(", ")} ${where(event.target)}.`;
            case "drag-cancel":
                return "Cancelled.";
            default:
                return undefined;
        }
    };
}

A keyboard drag starts next to the dragged item and announces its start and its first target in one drag-start event (target), so a screen reader reads both; the next drag-over comes with the first arrow key.

Reacting to a drop

A drop is one item.move command, with meta.source set to "drag" (or "keyboard-drag"): listen to the model to save it or send it to a server.

model.subscribe((event) => {
    if (event.command === "item.move" && event.before !== event.after) {
        void saveOrder(model.get("tree-json"));
    }
});

A drag's auto-expansion runs item.expand as a transient step; undo can merge it into the drop (Undo and redo).

Between trees

The trees in the same document whose models have the same dragGroup({ name }) share their drags: a row dragged out of one tree drops into another, with the pointer or the keyboard. It needs dragAndDrop() (a missing one fails at createTreeModel), from @fragiola/tree-react/drag-group (and the Vue and Angular entries). The tree under the pointer finds its own target (the same thirds and inline offset), draws its own DropIndicator, expands a hovered folder and scrolls near its edges, virtualized or not; the source keeps the pointer capture, the keys and the announcements. The receiving tree carries data-dragging and data-dragging-from-other-tree while the drag is under way. A tree without it keeps its drags. The group is the model's: every tree on screen of a model joins it.

import { DropIndicator, dragAndDrop } from "@fragiola/tree-react/drag-and-drop";
import { dragGroup } from "@fragiola/tree-react/drag-group";

const features = [dragAndDrop(), dragGroup({ name: "lists" })] as const;
const available = createTreeModel<Types, typeof features>(left, { features });
const selected = createTreeModel<Types, typeof features>(right, { features });

<Tree.Root model={available} aria-label="Available">
    <Tree.Items>{(item) => <Item item={item} />}</Tree.Items>
    <DropIndicator />
</Tree.Root>
<Tree.Root model={selected} aria-label="Selected">
    <Tree.Items>{(item) => <Item item={item} />}</Tree.Items>
    <DropIndicator />
</Tree.Root>
Two trees
Gallery

Over one model (two views of the same tree), a drop is one item.move, as inside a tree. Over two models it is a transfer: the target model runs one batch of item.add (each dragged item and its descendants, ids kept, expanded as they were) and the source model runs item.remove, each through its own middleware. A target shows only when the target model accepts the batch (model.can): a veto, a non-droppable parent, data its schema refuses or an id it already has hides it. Atomicity across the two models is yours: an undo stack that spans them records both commands (Undo and redo).

The transfer option of dragGroup({ name, transfer }) (the receiving model's, else the source's) replaces the default: copy instead of move, convert kinds, refuse. It is asked first with dryRun: true for each target (return false to hide it, true to show it, nothing for the default answer), then at the drop (return true once your commands ran, false when nothing happened, nothing for the default transfer). commands holds the default transfer's commands, to map:

// a copy, kept in the source: each added id gets a suffix, and so does a parent an item names
const transfer: TransferHandler = ({ commands, to, dryRun }) => {
    const added = new Set(
        commands.flatMap((entry) =>
            entry.command === "item.add" && entry.payload.item.id ? [entry.payload.item.id] : [],
        ),
    );
    const copy = (id: string) => (added.has(id) ? `${id}-copy` : id);
    const copied = commands.map((entry) => {
        if (entry.command === "item.expand")
            return { ...entry, payload: { itemId: copy(entry.payload.itemId) } };
        if (entry.command !== "item.add") return entry;
        const { item, to: place } = entry.payload;
        return {
            ...entry,
            payload: {
                item: { ...item, id: item.id && copy(item.id) },
                to: { ...place, parentItemId: place.parentItemId && copy(place.parentItemId) },
            },
        };
    });
    // the same commands answer the dry run and run at the drop
    return dryRun
        ? to.model.can("batch", { commands: copied })
        : to.model.run("batch", { commands: copied }).ok;
};

modifiers carries the drop's Alt, Ctrl, Meta and Shift keys: copy on Alt (Option) and return nothing otherwise, for example, which keeps the default move.

The keyboard drag steps through the group's trees in document order: Down past the last place of one tree reaches the first of the next, and the focus stays in the source tree. drag-over and drop carry targetTree (the other tree's root and model) when the target is in another tree, so the announcement can name it:

const announce = (event: AnnounceEvent) => {
    if (event.type !== "drag-over" || !event.target) return undefined;
    const list = event.targetTree?.root.getAttribute("aria-label") ?? "this list";
    return `Drop in ${list}.`;
};

Foreign content

Files from the desktop, links and text dragged from another window come with native HTML5 drag events, the one case the package listens to them. Install foreignDrop({ accept, onDrop }), from @fragiola/tree-react/foreign-drop (and the Vue and Angular entries): the tree then evaluates the target under the pointer as for its own drags (the same thirds and inline offset), draws DropIndicator (that entry exports it too) and data-drop-target, expands a hovered folder and scrolls near its edges, virtualized or not. The root carries data-dragging meanwhile. It works with or without dragAndDrop(): a tree can take files without dragging its own items. It takes the same autoExpandDelay, indentation, indicatorInset and autoScroll options (dragAndDrop()'s win when both are installed).

Before the drop a browser shows only the drag's types ("Files", "text/uri-list", "text/plain"), so accept decides from types and the target to; it is asked once per target. A disabled or non-droppable folder never takes a drop. At the drop, onDrop gets the dataTransfer and reads it: the package reads no file and makes no network call, so adding items, uploading or rejecting is your commands.

import { createTreeModel, Tree } from "@fragiola/tree-react";
import { DropIndicator, foreignDrop } from "@fragiola/tree-react/foreign-drop";

const files = foreignDrop<Types>({
    accept: ({ types }) => types.includes("Files"),
    onDrop: ({ dataTransfer, to: { parentItemId, index }, model }) => {
        [...dataTransfer.files].forEach((file, i) => {
            model.run("item.add", {
                item: { kind: "file", label: file.name, data: { size: file.size } },
                to: { parentItemId, index: index + i },
            });
        });
    },
});
const features = [files] as const;
const model = createTreeModel<Types, typeof features>(json, { features });

<Tree.Root model={model} aria-label="Project files">
    <Tree.Items>{(item) => <Item item={item} />}</Tree.Items>
    <DropIndicator />
</Tree.Root>;
File drop
Gallery

to is a DropTarget: its parentItemId and index are an item.add's placement. announce gets foreign-drag-over (the types and the target, null where nothing is taken) when the target changes (and a null target when the drag leaves), and foreign-drop after onDrop. With foreignDrop() the root is a drop zone: the browser never opens a file dropped on it, and shows no drop where nothing is taken. A tree without it forwards no native drag, and the browser keeps its own behaviour for them (opening a dropped file).

Text or a link selected in a row and dragged natively comes back as foreign content too: an accept that takes text/plain or text/uri-list takes it.

Dropping outside

A pointer drag of the tree's rows released outside every tree (outside every tree of its drag group, or outside its own tree without one) is cancelled, unless the model has dropOutside({ onDrop }), from @fragiola/tree-react/drop-outside (and the Vue and Angular entries); it needs dragAndDrop(). Its onDrop gets the dragged itemIds, the model, the client point, the modifier keys and the element under the pointer, and returns true when it took the items (announced as drop-outside) or false (a drag-cancel). Your own targets are what it looks for: a trash zone, a panel, a @fragiola/dnd droppable.

import { dragAndDrop } from "@fragiola/tree-react/drag-and-drop";
import { dropOutside } from "@fragiola/tree-react/drop-outside";

const trash = dropOutside<Types>({
    onDrop: ({ itemIds, element, model }) =>
        element?.closest("[data-trash]") != null &&
        model.run("item.remove", { itemIds: [...itemIds] }).ok,
});
const features = [dragAndDrop(), trash] as const;

The drag keeps the pointer capture on its row, so your targets get no pointer events of their own while it is under way. engine.get("drop-outside-element") is the element under the pointer while the drag is outside every tree (null otherwise), and engine.subscribe tells when it changes: a target highlights when it contains it.

const tree = useTreeRef<Types, typeof features>();
const engine = tree.current?.engine;
const overTrash = useSyncExternalStore(
    useCallback((onChange: () => void) => engine?.subscribe(onChange) ?? (() => {}), [engine]),
    () => engine?.get("drop-outside-element")?.closest("[data-trash]") != null,
    () => false,
);

A keyboard drag stays in the trees of its group: it has no place outside them.

What it does not do

No native outbound drag: a row cannot be dragged to the desktop or into another window (the drag uses Pointer Events), and trees in two documents (an iframe, a popup) never share a drag. See Known limitations.