Fractal UI Motif Fractal UI Type
On this Page

TreeNode

TreeNode is the recursive data shape used by the immutable moveTreeNode collection helper. It is a TypeScript interface, not a rendered motion primitive.

Overview

Every node needs a stable id. Arbitrary additional data is supported, and children can contain nested TreeNode values at any depth.

Behaviour

moveTreeNode returns a new hierarchy when it can move a node. It does not mutate the input array. Attempts to move a node onto itself or into one of its descendants are rejected and return the original tree.

Usage

TypeScript
import { moveTreeNode, type TreeNode } from "fractalsvelte/motion";

const tree: TreeNode[] = [
	{
		id: "workspace",
		children: [{ id: "inbox" }, { id: "archive" }],
	},
	{ id: "trash" },
];

const nextTree = moveTreeNode(tree, "archive", undefined, 0);
// `archive` is now the first root node; `tree` is unchanged.

Pass undefined as parentId to move an item to the root. Omit index to append it to the selected parent or root collection.

API

TreeNode

FieldTypeRequiredDescription
idstringYesStable node identifier.
childrenTreeNode[]NoOptional nested child nodes.
[key: string]unknownNoAdditional application-specific node data.

moveTreeNode

moveTreeNode(nodes, id, parentId?, index?): TreeNode[]

ParameterTypeDescription
nodesTreeNode[]Source hierarchy. It is never mutated.
idstringIdentifier of the node to move.
parentIdstring \| undefinedDestination parent id. Omit it to insert at the root.
indexnumber \| undefinedDestination index. Omit it to append.

The function returns the resulting TreeNode[]. If id is absent, matches parentId, or would become its own descendant, it returns the original nodes reference unchanged.

Integrations

TreeView uses the same hierarchy model for its reorderable mode. Use moveTreeNode directly when application state needs the same immutable move logic outside a rendered tree.