Container renders a sortable region, owns its direct Items, and exposes the core Container object through a forwarded React ref.

import { Container, Item } from "@snap-engine/snapsort/react";

<Container itemId="tasks-root">
  <Item itemId="task-1">Write API reference</Item>
</Container>;

For composition and collection workflows, see Container basics and Container Recipes.

Component Properties

interface ContainerProps
  extends Omit<HTMLAttributes<HTMLDivElement>, "children"> {
  children?: ReactNode;
  className?: string;
  config?: ContainerConfig;
  containerObject?: SnapSortContainer | null;
  itemId: string;
  locked?: boolean;
  metadata?: ItemMetadata;
  selected?: boolean;
}

children

Type: ReactNode · Default: no content

The content rendered inside the Container’s managed div. Put the application-owned keyed Item/Container/Ghost loop and any fixed content here.

<Container itemId="tasks-root">
  {tasks.map((task) => (
    <Item key={task.id} itemId={task.id}>
      {task.title}
    </Item>
  ))}
</Container>

The component has no items, entry, before, or after collection props.

config

Type: ContainerConfig · Default: {}

Configures sorting, layout projection, animation, policy, and callbacks. The component synchronizes supported runtime changes to its core object.

<Container itemId="tasks-root" config={{ direction: "row", mode: "insertion" }}>
  {/* Items */}
</Container>

See Configuration and Callbacks.

itemId

Type: string · Required · Construction-only

The stable identity for both root and nested Containers. It must be non-empty, unique within one SnapSort root, and unchanged while mounted. A nested Container uses the same ID as its application render entry.

<Container itemId={column.id}>{column.title}</Container>

Pass identity through this property, not metadata.itemId; the latter is rejected.

locked

Type: boolean · Default: true

Controls whether this Container can itself be dragged as an Item of its parent. It does not disable dragging the Container’s children.

<Container itemId={column.id} locked={false}>
  {/* The whole column can move in its parent. */}
</Container>

selected

Type: boolean · Default: false

Consumer-owned multi-drag selection state for a movable nested Container. It is only meaningful when locked={false}.

<Container
  itemId={column.id}
  locked={false}
  selected={selectedIds.has(column.id)}
>
  {/* Column content */}
</Container>

metadata

Type: ItemMetadata · Default: {}

Application data exposed as containerMetadata when this Container is a destination and as item metadata when the Container is dragged from a parent.

<Container itemId={column.id} metadata={{ kind: "column", accepts: "task" }}>
  {/* Items */}
</Container>

SnapSort reads the object but never mutates it.

containerObject

Type: SnapSortContainer | null · Default: null · Advanced

Adopts an existing nested Container instead of creating one. Root adoption is unsupported because React must own the root adapter. The nested object must use the same Engine, share the surrounding tree’s exact adapter, and have the same itemId. React attaches it to the surrounding Container when needed. The component does not destroy an adopted object.

<Container
  containerObject={existingNestedContainer}
  itemId={existingNestedContainer.itemId}
/>

ref

Type: Ref<SnapSortContainer>

Receives the component-owned or adopted core Container. Supplying a ref does not change ownership.

import { useRef } from "react";
import type { Container as SnapSortContainer } from "@snap-engine/snapsort";

const containerRef = useRef<SnapSortContainer | null>(null);

<Container ref={containerRef} itemId="tasks-root" />;

containerRef.current?.removeItem("task-1");

className, style, and HTML attributes

Type: standard React HTMLAttributes<HTMLDivElement>

The component renders a div. className is merged with snapsort-container and the mode class. Styles, events, ARIA attributes, and data-* attributes are forwarded; direction and mainAxisAlign also contribute inline layout declarations.

<Container
  itemId="tasks-root"
  className={compact ? "task-list compact" : "task-list"}
  style={{ gap: "0.5rem" }}
  aria-label="Tasks"
  data-view="backlog"
/>

Configuration

config accepts the following properties. Defaults shown here are the values resolved by a new component.

mode

Type: "euclidean" | "progressive" | "insertion" | "swap" · Default: "euclidean"

Selects the built-in drop-target and placement behavior. The root’s mode is resolved when a drag starts, so Containers in one tree should use the same mode. React swap roots must provide callbacks.onItemSwap.

<Container itemId="tasks-root" config={{ mode: "swap", callbacks }} />

direction

Type: "column" | "row" · Default: "column"

Sets the main layout direction used by placement prediction and the rendered flex direction.

<Container itemId="toolbar" config={{ direction: "row" }} />

mainAxisAlign

Type: "start" | "center" · Default: "start"

Sets main-axis alignment for virtual placement and maps to the component’s justify-content value.

<Container itemId="empty-state" config={{ mainAxisAlign: "center" }} />

wrap

Type: "auto" | "nowrap" · Default: "auto"

"auto" infers wrapped visual lines from measured layout. "nowrap" treats the Container as one line along its main axis.

<Container itemId="toolbar" config={{ direction: "row", wrap: "nowrap" }} />

stretchItems

Type: boolean · Default: false

Sizes projected entries to the destination’s cross axis, analogous to CSS align-items: stretch.

<Container itemId="cards" config={{ stretchItems: true }} />

name

Type: string · Default: generated container-N

A human-readable diagnostic name assigned when the React component creates the core object. React synchronizes later config.name changes to the live configuration object.

<Container itemId="tasks-root" config={{ name: "Task board" }} />

animation

Type: ContainerAnimations | null · Default: undefined

Enables optional FLIP animation. reorder controls displacement during a drag, drop controls final settling, and move controls programmatic moveItem/removeItem layout changes. Each accepts { duration, timing_function } or null.

import { defaultAnimations } from "@snap-engine/snapsort";

<Container itemId="tasks-root" config={{ animation: defaultAnimations }} />;
const animation = {
  reorder: { duration: 120, timing_function: "ease-out" },
  drop: { duration: 160, timing_function: "ease-in-out" },
  move: null,
};

dropPriority

Type: number · Default: 0

Sets the static destination priority. -1 rejects this Container; finite nonnegative values remain eligible and higher values are considered before lower values. Other negative or nonfinite values are invalid.

<Container itemId="archive" config={{ dropPriority: -1 }} />

callbacks

Type: Readonly<ContainerCallbacks> · Default: {}

Installs structural, lifecycle, policy, geometry, and hover callbacks. Root-dispatched callbacks must be configured on the root; local callbacks are read from the direct destination or Item owner.

<Container itemId="tasks-root" config={{ callbacks }} />

Callbacks

Structural and lifecycle callbacks resolve on the tree root. Policy, geometry, and Item-hover callbacks remain per container. Framework structural callbacks must update React state synchronously; SnapSort does not fall back to Vanilla DOM mutation.

onItemMove

onItemMove?: (event: ItemMoveEvent) => void;

Root callback for one semantic move, including the full selected run and its from/froms and to locations. It is preferred over primitive insertion.

const onItemMove = (event: ItemMoveEvent) => {
  setBoard((board) => reduceRenderTree(board, event));
};

onItemInsert

onItemInsert?: (event: ItemInsertEvent) => void;

Root callback for a primitive insertion and the fallback when onItemMove is absent. Framework mounting does not emit it; application code must resolve the value for a newly introduced ID.

const onItemInsert = (event: ItemInsertEvent) => {
  insertKnownValue(event.itemId, event.container, event.index);
};

onItemRemove

onItemRemove?: (event: ItemRemoveEvent) => void;

Root callback for the imperative removeItem command. Application-state unmounting and the source half of an ordinary move do not emit it.

const onItemRemove = (event: ItemRemoveEvent) => {
  setBoard((board) => reduceRenderTree(board, event));
};

onItemSwap

onItemSwap?: (event: ItemSwapEvent) => void;

Root callback for one atomic pairwise exchange in swap mode. It is required on a React swap root.

const onItemSwap = (event: ItemSwapEvent) => {
  setBoard((board) => reduceRenderTree(board, event));
};

onDragStart

onDragStart?: (event: DragStartEvent) => void | false;

Root callback before drag activation. Return false to veto the gesture, or set pending-session controls such as dragVisual.

const onDragStart = (event: DragStartEvent) => {
  event.session.dragVisual = "preview";
};

onDragEnd

onDragEnd?: (event: DragEndEvent) => void;

Root callback when an activated drag ends, including cancellation or returning to the source. destination is the final resolved location or null.

const onDragEnd = (event: DragEndEvent) => {
  console.log(event.destination);
};

onDropTargetChange

onDropTargetChange?: (event: DropTargetChangeEvent) => void;

Root callback when the prospective direct Container/index changes. It does not fire for presentation-only changes at the same location.

const onDropTargetChange = (event: DropTargetChangeEvent) => {
  activeTarget = event.current;
};

onDragItemEnter

onDragItemEnter?: (event: DragItemHoverEvent) => void;

Local callback on the direct owner when the dragged pointer first matches an Item’s hitbox.

const onDragItemEnter = (event: DragItemHoverEvent) => {
  hoveredId = event.overItemId;
};

onDragItemMove

onDragItemMove?: (event: DragItemHoverEvent) => void;

Local callback on each pointer move while the same Item hitbox remains matched.

const onDragItemMove = (event: DragItemHoverEvent) => {
  hoverPointer = event.pointer;
};

onDragItemLeave

onDragItemLeave?: (event: DragItemHoverEvent) => void;

Local callback when an Item’s hitbox stops matching or the drag ends.

const onDragItemLeave = (event: DragItemHoverEvent) => {
  if (hoveredId === event.overItemId) hoveredId = null;
};

onVisualGeometryInvalidated

onVisualGeometryInvalidated?: (
  event: VisualGeometryInvalidationEvent,
) => void;

Root, frame-coalesced notification that drag, ghost, animation, or settling may have changed rendered Item geometry.

const onVisualGeometryInvalidated = () => connectorLayer.invalidate();

getDropPriority

getDropPriority?: (event: DropPriorityEvent) => number | undefined;

Local destination policy. Return a finite nonnegative priority, -1 to reject, or undefined to keep event.staticPriority.

const getDropPriority = (event: DropPriorityEvent) =>
  event.containerMetadata.disabled ? DROP_REJECT_PRIORITY : undefined;

See Standard Callbacks for reusable policies.

getItemHitbox

getItemHitbox?: (event: ItemHitboxEvent) => ItemHitbox;

Local, synchronous geometry policy for direct-child hover and swap targeting. Return a world-space Rect or Circle (from @snap-engine/core/geometry): { shape: "rect", rect } or { shape: "circle", circle }.

import { rectCenter } from "@snap-engine/core/geometry";

const getItemHitbox = (event: ItemHitboxEvent): ItemHitbox => ({
  shape: "circle",
  circle: { ...rectCenter(event.defaultRect), radius: 24 },
});

onGhostInsert

onGhostInsert?: (event: GhostInsertEvent) => void;

Root callback when a ghost becomes present in framework render state.

const onGhostInsert = (event: GhostInsertEvent) => {
  setBoard((board) => reduceRenderTree(board, event));
};

onGhostMove

onGhostMove?: (event: GhostMoveEvent) => void;

Root callback when an existing ghost changes location or insertion-marker presentation. from and to may be equal for a presentation-only update.

const onGhostMove = (event: GhostMoveEvent) => {
  setBoard((board) => reduceRenderTree(board, event));
};

onGhostRemove

onGhostRemove?: (event: GhostRemoveEvent) => void;

Root callback when a rendered ghost becomes absent.

const onGhostRemove = (event: GhostRemoveEvent) => {
  setBoard((board) => reduceRenderTree(board, event));
};

Core Container Object

Capture the object with a React ref. The examples below use const container = containerRef.current!. A Container is also an Item; the entries below include the relevant inherited Item state as well as Container-specific APIs.

container.itemId

Type: ItemId · Read-only

Returns the stable identity supplied to the component.

console.log(container.itemId);

container.metadata

Type: ItemMetadata · Read/write

Gets or replaces application metadata. Prefer the component property while React owns the object.

container.metadata = { accepts: "task" };

container.locked

Type: boolean · Read/write · Default for Container: true

Controls whether this Container can move as an Item in its parent.

container.locked = false;

container.selected

Type: boolean · Read/write

Gets or sets the consumer-owned selection flag inherited from Item.

container.selected = true;

container.container

Type: Container · Read-only

Returns the direct parent Container for a nested Container. A root has no usable parent-container value.

const parent = nested.container;

container.rootContainer

Type: Container · Read-only for consumers

Returns the independent root that owns this Container’s drag tree.

const root = container.rootContainer;

container.depth

Type: number · Read-only

Returns the object-tree depth; the root is 0.

console.log(container.depth);

container.isGhost

Type: boolean · Read-only

Reports whether this is a transient engine-owned ghost. An application Container component exposes false.

console.log(container.isGhost);

container.dragSession

Type: DragSession | null · Read-only

Returns the active public drag handle on the root Container. Nested Containers always return null.

const draggedIds = container.dragSession?.items.map((item) => item.itemId);

container.adapter

Type: SnapSortAdapter · Read-only · Advanced

Returns the root-scoped renderer adapter. Framework components manage this object; every Container in one tree must share it.

console.log(container.adapter === nested.adapter);

container.name

Type: string · Read-only accessor

Returns the current diagnostic name stored in container.config.name.

console.log(container.name);

container.mode

Type: SortMode · Read/write

Gets or sets the built-in mode.

container.mode = "insertion";

container.direction

Type: "column" | "row" · Read/write

Gets or sets the main layout direction.

container.direction = "row";

container.mainAxisAlign

Type: "start" | "center" · Read/write

Gets or sets virtual main-axis alignment.

container.mainAxisAlign = "center";

container.wrap

Type: "auto" | "nowrap" · Read/write

Gets or sets wrapped-line inference.

container.wrap = "nowrap";

container.stretchItems

Type: boolean · Read/write

Gets or sets cross-axis stretching for projected entries.

container.stretchItems = true;

container.dropPriority

Type: number · Read/write

Gets or sets the static destination priority.

container.dropPriority = DROP_REJECT_PRIORITY;

container.callbacks

Type: Readonly<ContainerCallbacks> · Read/write

Gets or replaces the frozen callback set. Assigning root-dispatched callbacks to a descendant throws.

container.callbacks = { ...container.callbacks, getDropPriority };

container.config

Type: ContainerRuntimeConfig · Read-only reference to live values

Returns the sealed live configuration object. It contains runtime config except callbacks; use container.callbacks for callback replacement. animation and the diagnostic name are accessed through this object.

container.config.animation = defaultAnimations;

container.itemList

Type: Item[] · Read-only snapshot array

Returns direct ordinary Items in DOM order, excluding ghosts.

const ids = container.itemList.map((item) => item.itemId);

container.itemOrderedList

Type: Item[] · Read-only usage

Returns the direct ordered Item list used by SnapSort, including live ghost Items. Do not mutate the returned array.

const renderedOrder = container.itemOrderedList.map((item) => item.itemId);

container.numberOfItems

Type: number · Read-only

Returns the number of direct ordinary Items, excluding ghosts.

console.log(container.numberOfItems);

container.dragSnapshot

Type: ItemSnapshot<Item> | null · Read-only

Returns this Container’s frozen drag-tree snapshot while one exists.

const frozenChildren = container.dragSnapshot?.children;

container.dragPointerPosition

Type: { x: number; y: number } | null · Read-only

Returns the active pointer in world coordinates when this Container is being dragged as an Item and has a drag snapshot.

const pointer = container.dragPointerPosition;

container.dragPositionX

Type: number · Read-only

Returns the projected world-space left edge while this Container is dragged.

const left = container.dragPositionX;

container.dragPositionY

Type: number · Read-only

Returns the projected world-space top edge while this Container is dragged.

const top = container.dragPositionY;

container.getIndexAndContainer()

getIndexAndContainer(): { index: number; container: Container | null }

Returns this Container’s location as an Item in its parent. A root returns { index: -1, container: null }.

const location = container.getIndexAndContainer();

container.attachItem(item)

attachItem(item: Item): void

Advanced direct-object API that attaches an Item at the end and synchronizes the root snapshot. Framework collection rendering normally handles attachment.

container.attachItem(existingItem);

container.moveItem(itemId, targetContainer, index)

moveItem(itemId: ItemId, targetContainer: Container, index: number): boolean

Authoritatively moves an Item within the same root, bypassing drop policy. Returns false when the ID is missing or that Item already has a pending programmatic mutation, or when the root has a drag session. The root onItemMove/onItemInsert callback must update React state synchronously.

const accepted = source.moveItem("task-1", archive, 0);

container.removeItem(itemId)

removeItem(itemId: ItemId): boolean

Requests removal of a direct ordinary Item. Returns false when it is missing or already pending, or when the root has a drag session, and dispatches root onItemRemove when accepted.

const accepted = source.removeItem("task-1");

container.debugAllItems()

debugAllItems(node?: Item): void

Draws debug circles at Item centers, color-coded by parent Container. It uses SnapEngine’s debug renderer.

container.debugAllItems();

container.takeRootSnapshot()

takeRootSnapshot(): void

Advanced adapter hook that reconciles tree state and queues the initial root DOM read. React components manage their own attachment lifecycle; custom adapters call this after mounting a complete tree.

customRoot.takeRootSnapshot();

Inherited SnapEngine DOM, animation, scheduling, and destruction APIs are documented in Objects.

Appendix

Define Render State

RenderTree is an optional application-state shape for flat and nested collections. Every tree owns one keyed sequence of ordinary entries and ghosts. A non-null childTree says that an ordinary entry is a nested sortable Container rather than a leaf Item.

Item IDs must be unique across one RenderTree root, including the root Container, nested Containers, ordinary Items, and live ghosts. Independent roots may reuse IDs. The reducer recognizes the callback’s root structurally and routes nested Containers through their immutable itemId; no framework ref is part of RenderTree state. Keep the root component mounted for the lifetime of that state. If it is destroyed, discard the tree and create a new one for the replacement root.

import { useCallback, useState } from "react";
import {
  createRenderEntry,
  createRenderTree,
  reduceRenderTree,
  type ContainerCallbacks,
  type GhostLifecycleEvent,
  type ItemMoveEvent,
  type RenderTree,
} from "@snap-engine/snapsort";

type BoardValue =
  | { kind: "column"; title: string }
  | { kind: "task"; label: string };

function createInitialBoard(): RenderTree<BoardValue> {
  const tasks = (values: { id: string; label: string }[]) =>
    createRenderTree(
      values.map(({ id, label }) =>
        createRenderEntry<BoardValue>({ kind: "task", label }, id),
      ),
    );

  return createRenderTree([
    createRenderEntry(
      { kind: "column", title: "To do" },
      "todo",
      tasks([
        { id: "task-1", label: "Sketch layout" },
        { id: "task-2", label: "Wire behavior" },
      ]),
    ),
    createRenderEntry({ kind: "column", title: "Done" }, "done", tasks([])),
  ]);
}

The empty Done child tree is intentional. Its Container still mounts and can receive the first task or ghost.

Define Callback Functions

The root owns the structural callbacks. Item and ghost APIs remain explicit; the callbacks may delegate to the same optional reducer.

function useTaskBoardState() {
  const [board, setBoard] = useState(createInitialBoard);

  const onItemMove = useCallback((event: ItemMoveEvent) => {
    setBoard((current) => reduceRenderTree(current, event));
  }, []);

  const onGhostMove = useCallback((event: GhostLifecycleEvent) => {
    setBoard((current) => reduceRenderTree(current, event));
  }, []);

  const callbacks = {
    onItemMove,
    onGhostInsert: onGhostMove,
    onGhostMove,
    onGhostRemove: onGhostMove,
  } satisfies ContainerCallbacks;

  return { board, callbacks };
}

GhostLifecycleEvent is a convenience union for the shared local function; SnapSort still exposes and dispatches onGhostInsert, onGhostMove, and onGhostRemove separately. SnapSort owns the ghosts’ presence, so React must be told when a ghost appears, when the same keyed ghost relocates or changes its insertion-gap presentation, and when it disappears. A presentation-only insertion update carries equal from and to locations.

One onItemMove event, meanwhile, describes the whole semantic transition: its source, destination, and complete selected run. It does not also emit item remove and insert events. Application-created and application-deleted ordinary values do not require callbacks; update React state and let reconciliation mount or unmount the corresponding component.

Render Items and Nested Containers

Rendering has three branches:

  1. Ghost entries render Ghost.
  2. Ordinary entries with childTree render a nested Container.
  3. Other ordinary entries render Item.

Use entry.itemId directly as each React key. SnapSort keeps ordinary Items, nested Containers, and live ghosts unique inside one root, so no second key domain or prefix is needed.

A SnapSort Container is already an Item. Do not wrap the nested Container in another Item.

Ordinary UI nested inside an Item does not need a childTree. Keep it null and render the item’s labels, buttons, handles, or other React children inside Item. Set childTree only when the entry itself renders a SnapSort Container with its own sortable sequence.

import { Container, Ghost, Item } from "@snap-engine/snapsort/react";
import { rejectDrop } from "@snap-engine/snapsort/callbacks";

function ChildContainer({
  entry,
}: {
  entry: Extract<RenderTree<BoardValue>["entries"][number], { isGhost: false }>;
}) {
  if (!entry.childTree || entry.value.kind !== "column") {
    throw new Error("A board column requires a child render tree.");
  }

  return (
    <Container itemId={entry.itemId} metadata={{ columnId: entry.itemId }}>
      <h2>{entry.value.title}</h2>

      {entry.childTree.entries.map((child) =>
        child.isGhost ? (
          <Ghost key={child.itemId} ghost={child.ghost} />
        ) : child.childTree ? (
          <ChildContainer key={child.itemId} entry={child} />
        ) : child.value.kind === "task" ? (
          <Item key={child.itemId} itemId={child.itemId}>
            {child.value.label}
          </Item>
        ) : null,
      )}
    </Container>
  );
}

function TaskBoard() {
  const { board, callbacks } = useTaskBoardState();

  return (
    <Container
      itemId="project-board-root"
      config={{ callbacks: { ...callbacks, getDropPriority: rejectDrop } }}
      locked
    >
      <header>Project board</header>

      {board.entries.map((entry) =>
        entry.isGhost ? (
          <Ghost key={entry.itemId} ghost={entry.ghost} />
        ) : entry.childTree ? (
          <ChildContainer key={entry.itemId} entry={entry} />
        ) : (
          <Item key={entry.itemId} itemId={entry.itemId}>
            Unexpected root item
          </Item>
        ),
      )}

      <footer>Board controls</footer>
    </Container>
  );
}

The root owns structural callbacks; descendants configure only local policy, geometry, or hover behavior. rejectDrop keeps tasks out of the board’s top level while child lists remain eligible. Fixed headers and footers stay outside the keyed loop and never become SnapSort Items.

reduceRenderTree moves an ordinary entry together with its complete childTree, so a draggable nested Container retains its descendants and immutable identity. Applications with a different state model can skip this helper and implement the explicit callbacks directly.

reduceRenderTree accepts ItemMoveEvent, ItemSwapEvent, ItemRemoveEvent, and the three ghost lifecycle events. Those events completely describe the next state of existing application entries. It deliberately does not accept ItemInsertEvent: that event identifies a new core Item and its location but cannot provide the application value to store in RenderEntry<T>. An advanced onItemInsert integration must resolve that value and edit its own state.

Application-owned item lifetime

An Add button or Delete button should edit application state directly. Inside useTaskBoardState, these functions update one nested child tree while preserving its entries:

const addTaskToTodo = useCallback((id: string, label: string) => {
  setBoard((current) => ({
    ...current,
    entries: current.entries.map((entry) =>
      !entry.isGhost && entry.itemId === "todo" && entry.childTree
        ? {
            ...entry,
            childTree: {
              ...entry.childTree,
              entries: [
                ...entry.childTree.entries,
                createRenderEntry<BoardValue>({ kind: "task", label }, id),
              ],
            },
          }
        : entry,
    ),
  }));
}, []);

const deleteTasksFromTodo = useCallback((itemIds: readonly string[]) => {
  const deleted = new Set(itemIds);
  setBoard((current) => ({
    ...current,
    entries: current.entries.map((entry) =>
      !entry.isGhost && entry.itemId === "todo" && entry.childTree
        ? {
            ...entry,
            childTree: {
              ...entry.childTree,
              entries: entry.childTree.entries.filter(
                (child) => child.isGhost || !deleted.has(child.itemId),
              ),
            },
          }
        : entry,
    ),
  }));
}, []);

These are application functions, not SnapSort helpers. React reconciliation mounts or unmounts Item and synchronizes its core registration. A drop-to-trash interface follows the same ownership rule: set session.dropEffect = "none" for the trash target, then delete all event.itemIds from application state only if onDragEnd reports the trash as its final destination. See Give a Drop Application Meaning for a recursive, cancellation-safe recipe.

The imperative command is a separate direction of synchronization. If code calls a core Container’s removeItem(id), SnapSort removes it from the core tree and emits root onItemRemove. Add that callback and reduce it synchronously:

import type {
  Container as SnapSortContainer,
  ItemRemoveEvent,
} from "@snap-engine/snapsort";

const onItemRemove = useCallback((event: ItemRemoveEvent) => {
  setBoard((current) => reduceRenderTree(current, event));
}, []);

const callbacksWithCoreRemove = {
  onItemMove,
  onItemRemove,
  onGhostInsert: onGhostMove,
  onGhostMove,
  onGhostRemove: onGhostMove,
} satisfies ContainerCallbacks;

function removeThroughSnapSort(source: SnapSortContainer, itemId: string) {
  source.removeItem(itemId);
}

Use this imperative path only when SnapSort’s core command is intended to lead the change. Do not call it after already deleting the same entry from React state, and do not expect onItemRemove for the source half of a move.

If the source Container has animation.move, removeItem(id) returns true when the request is accepted, commits onItemRemove in the next coordinated frame, and FLIP-animates the surviving layout. While any animated programmatic move or removal is pending, further move/remove commands for that Item return false, and no drag can start in that root. Conversely, programmatic move/removal commands return false while the root has a drag session. Direct React-state deletion bypasses this animation, and SnapSort does not retain the removed element for an exit effect.

Ghost remains a thin lifecycle view: it binds the engine-owned ghostItem to the rendered element and applies ghost geometry plus the snapsort-ghost class. It does not own or distribute state.

See the Item reference for extracting the item branch into a reusable component.

Drag visuals

DragSession.dragVisual separates pointer representation from placement mode:

const rootCallbacks = {
  ...ghostCallbacks,
  onDragStart(event: DragStartEvent) {
    event.session.dragVisual = "preview";
  },
};

The choices are "item", "preview", and "none". A preview is one root-owned pointer-preview ghost for the complete dragged run; insertion’s destination remains a separate insertion-marker ghost. Both live in their owning tree node’s entries sequence and render through Ghost. Set the property only while the session is pending, normally in onDragStart.

Insertion marker geometry and item hitboxes

SnapSort owns insertion targeting geometry. The insertion-marker state contains a zero-thickness world-space gap, frozen previous and next neighbors for the chosen physical boundary, and isCurrentPlacement. Marker paint is deliberately separate from candidate ranking.

The insertion-specific part of the public state is:

interface InsertionMarkerState {
  readonly type: "insertion-marker";
  readonly location: GhostSlotLocation;
  readonly gap: InsertionGapSegment;
  readonly previous: InsertionMarkerNeighbor | null;
  readonly next: InsertionMarkerNeighbor | null;
  readonly isCurrentPlacement: boolean;
  // Plus the shared GhostState identity and dragged-run fields.
}

Each neighbor contains its exact Item, itemId, frozen metadata, and frozen world-space border rectangle. A nested Container is also an Item, so no separate container-neighbor variant is needed.

The built-in Ghost has an explicit 3px stock presentation. Pass all three marker options when the product needs another rectangle:

import type {
  GhostState,
  InsertionMarkerRectOptions,
} from "@snap-engine/snapsort";
import { Ghost } from "@snap-engine/snapsort/react";

const markerOptions = {
  thickness: 2,
  startInset: 24,
  endInset: 8,
} satisfies InsertionMarkerRectOptions;

function RenderGhost({ ghost }: { ghost: GhostState }) {
  return ghost.type === "insertion-marker" ? (
    <Ghost ghost={ghost} insertionMarker={markerOptions} />
  ) : (
    <Ghost ghost={ghost} />
  );
}

Custom renderers and adapters use the same pure conversion instead of reimplementing coordinate projection:

import { insertionMarkerRect } from "@snap-engine/snapsort";
import type { InsertionMarkerState } from "@snap-engine/snapsort";

function renderMarker(marker: InsertionMarkerState, element: HTMLElement) {
  const rect = insertionMarkerRect(marker, markerOptions);
  element.style.left = `${rect.x}px`;
  element.style.top = `${rect.y}px`;
  element.style.width = `${rect.width}px`;
  element.style.height = `${rect.height}px`;
}

startInset means left for a horizontal line and top for a vertical line; endInset means right or bottom. Insets and thickness alter only rendering. Both insets must be non-negative and their sum must not exceed gap.length. The returned rectangle is relative to ghost.location.container, including its border and scroll offset, and is ready for absolute positioning.

toContainerLocalRect(worldRect, container) exposes the same border-, scroll-, and camera-aware projection for another world-space overlay. Vanilla can keep the stock adapter and choose marker presentation with createVanillaAdapter({ insertionMarker: markerOptions }).

getItemHitbox remains a direct-container geometry callback because its return value intentionally changes hover/swap targeting. It receives the dragged item, candidate overItem, direct owner, pointer, and frozen defaultRect. Return either { shape: "rect", rect } or { shape: "circle", circle }.

  • Configure persistent and ghost structural callbacks once on the root. Their event locations route updates to the source and destination records.
  • Configure onItemSwap on the root of every swap tree.
  • Keep priority, item-hitbox geometry, and hover callbacks on the direct containers whose behavior they customize.

Configure onItemRemove when application code can invoke removeItem(id), and pass it through reduceRenderTree when using RenderTree state. Direct application-state deletion needs no callback. Ordinary moves emit only the root-dispatched onItemMove/onItemInsert event.

Update React state synchronously in every structural callback. The adapter wraps the root command in flushSync, allowing SnapSort to read committed DOM before paint. Do not defer these updates with transitions, timers, animation frames, or promises. Missing callbacks fail clearly instead of mutating framework-rendered DOM.