# Tree View editing and drag and drop

> Inline rename with F2, pointer and keyboard moves before, after or into an item, moves between trees of one drag group, and the moveTreeItems helper for application-owned data.

Canonical: https://salmonui.dev/docs/navigation/tree-view-drag-drop

The tree reports edits and moves; it never changes `data`. The application
applies them, which keeps one source of truth and works with any store.
`TreeView` and `moveTreeItems` come from `@salmonui/navigation/tree-view`, styled
by `@salmonui/navigation/tree-view/styles.css` (see
[Tree View](https://salmonui.dev/docs/navigation/tree-view)); the rename field and the drag code
are lazy chunks of the same subpath.

### Live demo: Tree View drag and drop

Live demo: https://salmonui.dev/demos/navigation/tree-view-drag-drop

Two task trees in one drag group with pointer moves before, after or into an item, Alt+arrow keyboard moves and F2 rename, applied to application data with moveTreeItems.

`Demo.tsx`:

```tsx
'use client';
import { useState } from 'react';
import { moveTreeItems, TreeView, type TreeViewKey, type TreeViewMoveEvent } from '@salmonui/navigation/tree-view';

interface Task {
  id: string;
  name: string;
  children?: Task[];
}

const options = {
  getItemId: (t: Task) => t.id,
  getChildren: (t: Task) => t.children,
  withChildren: (t: Task, children: readonly Task[]) => ({ ...t, children: [...children] }),
};

const rename = (list: readonly Task[], id: TreeViewKey, name: string): Task[] =>
  list.map((t) => (t.id === id ? { ...t, name } : t.children ? { ...t, children: rename(t.children, id, name) } : t));

// `expanded` is reactive (applied when the array identity changes): keep one array.
const EXPANDED = ['launch'];
const listStyle = { border: '1px solid var(--salmon-border-subtle)', borderRadius: 'var(--salmon-radius-lg)' } as const;

export default function TreeViewDragDropDemo() {
  const [todo, setTodo] = useState<Task[]>([
    { id: 'launch', name: 'Launch', children: [{ id: 'copy', name: 'Write copy' }, { id: 'assets', name: 'Export assets' }] },
    { id: 'qa', name: 'QA pass' },
    { id: 'ship', name: 'Ship it' },
  ]);
  const [done, setDone] = useState<Task[]>([{ id: 'plan', name: 'Plan' }]);
  const [last, setLast] = useState('nothing yet');

  const into = (setTarget: typeof setTodo, setSource: typeof setTodo) => (e: TreeViewMoveEvent<Task>) => {
    setLast(`${e.ids.join(', ')} ${e.position} ${e.targetId}${e.sourceTreeId ? ' (from the other list)' : ''} by ${e.source}`);
    if (e.sourceTreeId) setSource((d) => moveTreeItems(d, { ids: e.ids, targetId: '', position: 'after' }, options));
    setTarget((d) => moveTreeItems(d, { ...e, items: e.items }, options));
  };

  const common = {
    getItemId: options.getItemId,
    getItemLabel: (t: Task) => t.name,
    getChildren: options.getChildren,
    draggable: true,
    dragGroup: 'tasks',
    renamable: true,
    selection: 'multiple' as const,
    height: 220,
  };
  return (
    <div style={{ display: 'grid', gap: 12 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))', gap: 16, maxWidth: 640 }}>
        <div style={{ display: 'grid', gap: 8 }}>
          <strong id="todo-label">To do</strong>
          <TreeView
            {...common}
            id="todo"
            aria-labelledby="todo-label"
            data={todo}
            expanded={EXPANDED}
            onMove={into(setTodo, setDone)}
            onRename={(e) => setTodo((d) => rename(d, e.id, e.label))}
            style={listStyle}
          />
        </div>
        <div style={{ display: 'grid', gap: 8 }}>
          <strong id="done-label">Done</strong>
          <TreeView {...common} id="done" aria-labelledby="done-label" data={done} onMove={into(setDone, setTodo)} onRename={(e) => setDone((d) => rename(d, e.id, e.label))} style={listStyle} />
        </div>
      </div>
      <p style={{ margin: 0 }}>
        Last move: <output>{last}</output>
      </p>
    </div>
  );
}
```

## Rename

`renamable`: F2 on the focused item or
`api.startRename(id)` opens an inline text field (a lazy chunk, loaded on
first use). Enter or leaving the field commits, Escape cancels; focus returns
to the item. `onBeforeRename({ id, item, label, previousLabel })` is
cancellable and `onRename` reports the new label:

```tsx
<TreeView renamable onRename={(e) => setData((d) => renameItem(d, e.id, e.label))} /* ... */ />
```

An empty or unchanged label is not reported. The draft lives in the field,
never in React state.

## Drag and drop

`draggable` loads the pointer drag
chunk. Dragging an item (or the selection, when the item is selected) shows
an indicator: the top quarter of a target row drops `before` it, the bottom
quarter `after` it, the middle `into` it. A drop onto the dragged item or
its own subtree is refused, the list scrolls near its edges, and Escape
cancels. `onBeforeMove({ ids, items, targetId, position, sourceTreeId })`
is cancellable; `onMove` reports the move.

From the keyboard (with `draggable`): Alt+ArrowUp / Alt+ArrowDown move the
focused item before its previous or after its next sibling, Alt+ArrowRight
moves it into the previous sibling, Alt+ArrowLeft out of its parent. Each
move is announced in a live region (`moved` text).

`moveTreeItems(data, event, { getItemId, getChildren, withChildren })`
applies a move to nested data and keeps the identity of every unchanged
subtree:

```tsx
import { moveTreeItems } from '@salmonui/navigation/tree-view';

const options = { getItemId: (f) => f.id, getChildren: (f) => f.children, withChildren: (f, children) => ({ ...f, children }) };
<TreeView draggable onMove={(e) => setData((d) => moveTreeItems(d, e, options))} /* ... */ />
```

For flat data, update the moved items' parent id instead.

## Between trees

Trees with the same `dragGroup` exchange items: the target tree
reports `onMove` with `sourceTreeId` (the source tree's `id`) and `items`
taken from the source. Remove the items from the source data and insert
them in the target data (`moveTreeItems` accepts `items` for the insert).

## Design notes

- **Drop targets**: dropping onto arbitrary elements needs a
  cross-component drag protocol, and constraining the drag to an area is a
  niche case. Drops land on tree items only, inside the tree or another tree
  of the same `dragGroup`. Use the native drag and drop API on your own
  elements for other targets.
- **No item add, remove, move, update or refresh methods**: the
  data belongs to the application, and editing it is the fast path, because
  items keep their state by stable id and the tree re-flattens incrementally
  once per `data` identity. Make the matching immutable update of `data`
  (`moveTreeItems` for moves); no refresh is needed.
- **No data-changed events**: the tree never writes to `data`, so
  such events would have nothing to report. React to changes in `onMove`,
  `onRename`, `onCheckedChange` and `onExpandedChange`, and run code after
  new data arrives in an effect on `data`.

## Server rendering

Renaming and dragging only start from user input after hydration, so they
add nothing to the server markup; the tree renders its first window on the
server as described on the [Tree View](https://salmonui.dev/docs/navigation/tree-view#server-rendering)
page.

## API reference

`renamable`, `onBeforeRename`, `onRename`, `draggable`, `dragGroup`,
`onBeforeMove`, `onMove`, `TreeViewApi.startRename` and `moveTreeItems` are
in the [`@salmonui/navigation/tree-view` reference](https://salmonui.dev/docs/reference/navigation/tree-view).
