Container
On this page
Container renders a sortable region, owns its direct Items, and exposes the
core Container object through bind:container.
<script lang="ts">
import { Container, Item } from "@snap-engine/snapsort/svelte";
</script>
<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
type ContainerProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> & {
children?: Snippet;
config?: ContainerConfig;
itemId: string;
container?: SnapSortContainer | null;
locked?: boolean;
selected?: boolean;
className?: string;
metadata?: ItemMetadata;
}; children
Type: Snippet · Default: no content
The markup rendered inside the Container’s managed div. Put the
application-owned keyed Item/Container/Ghost loop and any fixed content in
this snippet.
<Container itemId="tasks-root">
{#each tasks as task (task.id)}
<Item itemId={task.id}>{task.title}</Item>
{/each}
</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.
bind:container
Type: SnapSortContainer | null
Returns the component-owned core Container. The value is unavailable before
mount and becomes null on unmount. Passing an existing Container through
this binding does not adopt it; the Svelte component creates its own object.
<script lang="ts">
import type { Container as SnapSortContainer } from "@snap-engine/snapsort";
let container = $state<SnapSortContainer | null>(null);
</script>
<Container itemId="tasks-root" bind:container />
<button onclick={() => container?.removeItem("task-1")}>Remove task</button> class, className, style, and HTML attributes
Type: standard Svelte HTMLAttributes<HTMLDivElement>
The component renders a div. Native class and the className alias are
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"
class:compact={compact}
className="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. Svelte 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 Svelte component creates
the core object. Treat it as construction-time component configuration; later
changes to config.name are not synchronized by the Svelte wrapper.
<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.
<script lang="ts">
import { defaultAnimations } from "@snap-engine/snapsort";
</script>
<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 Svelte 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) => {
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) => {
board = reduceRenderTree(board, event);
}; onItemSwap
onItemSwap?: (event: ItemSwapEvent) => void; Root callback for one atomic pairwise exchange in swap mode. It is required on a Svelte swap root.
const onItemSwap = (event: ItemSwapEvent) => {
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) => {
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) => {
board = reduceRenderTree(board, event);
}; onGhostRemove
onGhostRemove?: (event: GhostRemoveEvent) => void; Root callback when a rendered ghost becomes absent.
const onGhostRemove = (event: GhostRemoveEvent) => {
board = reduceRenderTree(board, event);
}; Core Container Object
Capture the object with bind:container. 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 Svelte 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 Svelte 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. The Svelte root component calls it automatically after mount.
customRoot.takeRootSnapshot(); Inherited SnapEngine DOM, animation, scheduling, and destruction APIs are documented in Objects.
Appendix
Direct children and RenderTree entries
Svelte owns the rendered collection. Fixed markup can sit before or after the
keyed sortable loop and is never registered as an Item. Within the loop, render
ghost entries as Ghost, entries with a childTree as nested Container, and
ordinary leaves as Item. A nested Container is already an Item and must not
be wrapped in another Item.
<script lang="ts">
import {
createRenderEntry,
createRenderTree,
reduceRenderTree,
type ContainerCallbacks,
type GhostLifecycleEvent,
type ItemMoveEvent,
} from "@snap-engine/snapsort";
import { Container, Ghost, Item } from "@snap-engine/snapsort/svelte";
type BoardValue =
| { kind: "column"; title: string }
| { kind: "task"; label: string };
let board = $state.raw(
createRenderTree<BoardValue>([
createRenderEntry(
{ kind: "column", title: "To do" },
"todo",
createRenderTree([
createRenderEntry({ kind: "task", label: "Sketch" }, "task-1"),
]),
),
]),
);
function applyTreeEvent(event: ItemMoveEvent | GhostLifecycleEvent) {
board = reduceRenderTree(board, event);
}
const callbacks = {
onItemMove: applyTreeEvent,
onGhostInsert: applyTreeEvent,
onGhostMove: applyTreeEvent,
onGhostRemove: applyTreeEvent,
} satisfies ContainerCallbacks;
</script>
<Container itemId="project-board-root" config={{ callbacks }}>
<header>Project board</header>
{#each board.entries as entry (entry.itemId)}
{#if entry.isGhost}
<Ghost ghost={entry.ghost} />
{:else if entry.childTree}
<Container itemId={entry.itemId}>
<!-- Render entry.childTree.entries with the same three branches. -->
</Container>
{:else}
<Item itemId={entry.itemId}>{entry.value.label}</Item>
{/if}
{/each}
<footer>Board controls</footer>
</Container> Item IDs are unique across one RenderTree root, including the root Container, nested Containers, ordinary Items, and live ghosts. Independent roots may reuse IDs. Keep the root mounted for the lifetime of its RenderTree state.
Application-owned item lifetime
Application Add and Delete actions edit framework state directly. These are application functions, not SnapSort helpers:
function addTaskToTodo(id: string, label: string) {
board = addTaskEntry(board, "todo", { id, label });
}
function deleteTasksFromTodo(itemIds: readonly string[]) {
board = removeTaskEntries(board, "todo", new Set(itemIds));
} Svelte reconciliation mounts or unmounts the corresponding Items. Framework
mounting does not emit onItemInsert or onItemRemove. Calling the core removeItem(id) is the opposite synchronization direction: configure root onItemRemove, apply it synchronously, and do not expect onItemRemove for
the source half of a move.
If animation.move is configured, accepted programmatic moves/removals commit
in the coordinated animation transaction. Further commands for that Item
return false while it is pending, and no drag can start in that root until
all pending programmatic mutations commit. Conversely, programmatic
move/removal commands return false while the root has a drag session.
Drag visuals and ghost presentation
DragSession.dragVisual ("item", "preview", or "none") controls what
follows the pointer independently from placement feedback. Configure it while
the session is pending, normally in onDragStart.
Insertion targeting owns a canonical zero-thickness gap and frozen neighbor
geometry. InsertionMarkerState.isCurrentPlacement reports whether committing
that candidate preserves the dragged run’s current placement. Rendering
options affect paint only:
{#if ghost.type === "insertion-marker"}
<Ghost ghost={ghost} insertionMarker={markerOptions} />
{:else}
<Ghost {ghost} />
{/if} const rect = insertionMarkerRect(marker, markerOptions); Use getItemHitbox only when hover/swap targeting itself needs different
geometry. See Drags and Ghosts for the
full ghost lifecycle and insertion-marker model.