Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

feat(docs): put the Library first and let a drag file a document

Pouzored49c5396955
diff --git a/frontend/src/documentation/__tests__/DocTree.test.tsx b/frontend/src/documentation/__tests__/DocTree.test.tsx
index 46cbba9..d773938 100644
--- a/frontend/src/documentation/__tests__/DocTree.test.tsx
+++ b/frontend/src/documentation/__tests__/DocTree.test.tsx
@@ -7,10 +7,10 @@
* it is invisible to a test, but the `title` that goes with it is not, and it is
* what makes a genuinely over-long name readable at all.
*/
-import { render, screen } from '@testing-library/react'
+import { fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
-import { DocTreeGroups } from '../components/DocTree'
+import { DocTreeGroups, DocTreeItem, type TreeDnd } from '../components/DocTree'
import type { TreeGroup, TreeLeaf } from '../types'
function leaf(overrides: Partial<TreeLeaf> = {}): TreeLeaf {
@@ -82,3 +82,84 @@ describe('DocTree', () => {
)
})
})
+
+/** A drag needs a dataTransfer; jsdom's synthetic events carry none. */
+function transfer() {
+ return { effectAllowed: '', dropEffect: '', setData: vi.fn(), getData: () => '' }
+}
+
+function dndProps(overrides: Partial<TreeDnd> = {}): TreeDnd {
+ return {
+ draggingId: null,
+ overId: null,
+ canDrop: () => true,
+ onDragStart: vi.fn(),
+ onDragEnd: vi.fn(),
+ onDragOver: vi.fn(),
+ onDrop: vi.fn(),
+ ...overrides,
+ }
+}
+
+function renderItem(leafValue: TreeLeaf, dnd?: TreeDnd, expanded: string[] = []) {
+ return render(
+ <DocTreeItem
+ leaf={leafValue}
+ depth={1}
+ activeId={null}
+ expanded={expanded}
+ starred={new Set()}
+ onSelect={vi.fn()}
+ onToggle={vi.fn()}
+ dnd={dnd}
+ />,
+ )
+}
+
+const page = (overrides: Partial<TreeLeaf> = {}): TreeLeaf =>
+ leaf({ id: 'doc-1', docId: 'doc-1', kind: 'page', label: 'Runbook', ...overrides })
+
+const folder = (overrides: Partial<TreeLeaf> = {}): TreeLeaf =>
+ leaf({ id: 'folder-1', docId: 'folder-1', kind: 'folder', label: 'Runbooks', children: [], ...overrides })
+
+describe('DocTree drag to file', () => {
+ it('makes the icon the handle, not the row', () => {
+ const dnd = dndProps()
+ renderItem(page(), dnd)
+ const handle = screen.getByTestId('drag-doc-1')
+ expect(handle).toHaveAttribute('draggable', 'true')
+ expect(screen.getByRole('button')).not.toHaveAttribute('draggable')
+
+ fireEvent.dragStart(handle, { dataTransfer: transfer() })
+ expect(dnd.onDragStart).toHaveBeenCalledWith(expect.objectContaining({ docId: 'doc-1' }))
+ })
+
+ it('leaves rows undraggable when the tree has no filing wired up', () => {
+ renderItem(page())
+ expect(screen.queryByTestId('drag-doc-1')).not.toBeInTheDocument()
+ })
+
+ it('drops a document into a folder', () => {
+ const dnd = dndProps()
+ renderItem(folder(), dnd)
+ const row = screen.getByRole('button')
+ fireEvent.dragOver(row, { dataTransfer: transfer() })
+ expect(dnd.onDragOver).toHaveBeenCalledWith('folder-1')
+ fireEvent.drop(row, { dataTransfer: transfer() })
+ expect(dnd.onDrop).toHaveBeenCalledWith('folder-1')
+ })
+
+ it('refuses a folder the caller rules out', () => {
+ const dnd = dndProps({ canDrop: () => false })
+ renderItem(folder(), dnd)
+ fireEvent.drop(screen.getByRole('button'), { dataTransfer: transfer() })
+ expect(dnd.onDrop).not.toHaveBeenCalled()
+ })
+
+ it('never treats a page as a drop target', () => {
+ const dnd = dndProps()
+ renderItem(page(), dnd)
+ fireEvent.drop(screen.getByRole('button'), { dataTransfer: transfer() })
+ expect(dnd.onDrop).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/documentation/__tests__/tree.test.ts b/frontend/src/documentation/__tests__/tree.test.ts
index 24fe166..83288b5 100644
--- a/frontend/src/documentation/__tests__/tree.test.ts
+++ b/frontend/src/documentation/__tests__/tree.test.ts
@@ -6,6 +6,7 @@ import {
bucketsFor,
buildDeviceTree,
buildLibraryTree,
+ canMoveInto,
deviceLabel,
docState,
filterGroups,
@@ -382,3 +383,40 @@ describe('filterGroups', () => {
expect(filterGroups(groups, 'zzz')).toEqual([])
})
})
+
+describe('canMoveInto', () => {
+ const root = doc({ id: 'root', kind: 'folder', title: 'Runbooks' })
+ const nested = doc({ id: 'nested', kind: 'folder', title: 'Restores', parent_id: 'root' })
+ const page = doc({ id: 'page', kind: 'page', title: 'Restore the NAS', parent_id: null })
+ const all = [root, nested, page]
+
+ it('files a top-level page under a folder', () => {
+ expect(canMoveInto(all, page, 'root')).toBe(true)
+ })
+
+ it('takes a filed page back out to the root', () => {
+ expect(canMoveInto(all, { ...page, parent_id: 'root' }, null)).toBe(true)
+ })
+
+ it('refuses the parent it already has', () => {
+ expect(canMoveInto(all, { ...page, parent_id: 'root' }, 'root')).toBe(false)
+ expect(canMoveInto(all, page, null)).toBe(false)
+ })
+
+ it('refuses a page as a parent — only folders take children', () => {
+ expect(canMoveInto(all, nested, 'page')).toBe(false)
+ })
+
+ it('refuses a folder into itself or its own subtree', () => {
+ expect(canMoveInto(all, root, 'root')).toBe(false)
+ expect(canMoveInto(all, root, 'nested')).toBe(false)
+ })
+
+ it('refuses a device document, which the Library does not hold', () => {
+ expect(canMoveInto(all, doc({ id: 'dev-doc', kind: 'device' }), 'root')).toBe(false)
+ })
+
+ it('refuses a parent that is not there', () => {
+ expect(canMoveInto(all, page, 'gone')).toBe(false)
+ })
+})
diff --git a/frontend/src/documentation/components/DocTree.tsx b/frontend/src/documentation/components/DocTree.tsx
index 98e17e8..05da537 100644
--- a/frontend/src/documentation/components/DocTree.tsx
+++ b/frontend/src/documentation/components/DocTree.tsx
@@ -37,6 +37,24 @@ export function DocStateDot({ state }: { state: DocState }) {
)
}
+/**
+ * Filing by drag, wired by the view that owns the documents.
+ *
+ * Only the Library passes this — the Devices tree is a pivot, so its rows have
+ * no parentage to change. `null` as a target means the Library root.
+ */
+export interface TreeDnd {
+ /** The document being dragged, or null when nothing is. */
+ draggingId: string | null
+ /** The folder currently under the pointer, highlighted as the landing spot. */
+ overId: string | null
+ canDrop: (targetId: string | null) => boolean
+ onDragStart: (leaf: TreeLeaf) => void
+ onDragEnd: () => void
+ onDragOver: (targetId: string | null) => void
+ onDrop: (targetId: string | null) => void
+}
+
interface ItemProps {
leaf: TreeLeaf
depth: number
@@ -45,13 +63,20 @@ interface ItemProps {
starred: Set<string>
onSelect: (leaf: TreeLeaf) => void
onToggle: (key: string) => void
+ dnd?: TreeDnd
}
-export function DocTreeItem({ leaf, depth, activeId, expanded, starred, onSelect, onToggle }: ItemProps) {
+export function DocTreeItem({ leaf, depth, activeId, expanded, starred, onSelect, onToggle, dnd }: ItemProps) {
const isFolder = leaf.kind === 'folder'
const isOpen = expanded.includes(leaf.id)
const active = activeId !== null && leaf.docId === activeId
const Icon = isFolder ? (isOpen ? FolderOpen : Folder) : leaf.docId ? FileText : File
+ // The icon is the handle, not the row: a row-wide drag would fight the click
+ // that opens a document and the double-click that opens a folder.
+ const dragHandle = Boolean(dnd && leaf.docId)
+ const dragging = dnd?.draggingId !== null && dnd?.draggingId === leaf.docId
+ const dropTarget = Boolean(dnd && isFolder && dnd.canDrop(leaf.id))
+ const over = dropTarget && dnd?.overId === leaf.id
return (
<>
@@ -59,6 +84,25 @@ export function DocTreeItem({ leaf, depth, activeId, expanded, starred, onSelect
type="button"
onClick={() => (isFolder ? onToggle(leaf.id) : onSelect(leaf))}
onDoubleClick={() => isFolder && onSelect(leaf)}
+ onDragOver={
+ dropTarget
+ ? (event) => {
+ event.preventDefault()
+ event.dataTransfer.dropEffect = 'move'
+ dnd?.onDragOver(leaf.id)
+ }
+ : undefined
+ }
+ onDragLeave={dropTarget ? () => dnd?.onDragOver(null) : undefined}
+ onDrop={
+ dropTarget
+ ? (event) => {
+ event.preventDefault()
+ event.stopPropagation()
+ dnd?.onDrop(leaf.id)
+ }
+ : undefined
+ }
aria-current={active ? 'page' : undefined}
aria-expanded={isFolder ? isOpen : undefined}
style={{ paddingLeft: 8 + depth * 12 }}
@@ -66,6 +110,8 @@ export function DocTreeItem({ leaf, depth, activeId, expanded, starred, onSelect
'flex w-full cursor-pointer items-center gap-1.5 rounded py-1 pr-2 text-left text-xs',
active ? 'bg-primary/15 text-foreground' : 'text-muted-foreground hover:bg-muted/60 hover:text-foreground',
!leaf.docId && !isFolder && 'italic',
+ dragging && 'opacity-50',
+ over && 'bg-primary/20 text-foreground ring-1 ring-inset ring-primary/60',
)}
>
{isFolder ? (
@@ -73,7 +119,25 @@ export function DocTreeItem({ leaf, depth, activeId, expanded, starred, onSelect
) : (
<span className="w-3 shrink-0" />
)}
- <Icon size={13} className="shrink-0 opacity-70" />
+ <span
+ draggable={dragHandle || undefined}
+ data-testid={dragHandle ? `drag-${leaf.id}` : undefined}
+ aria-label={dragHandle ? `Drag ${leaf.label}` : undefined}
+ title={dragHandle ? 'Drag to file this elsewhere' : undefined}
+ onDragStart={
+ dragHandle
+ ? (event) => {
+ event.dataTransfer.effectAllowed = 'move'
+ event.dataTransfer.setData('text/plain', leaf.docId ?? '')
+ dnd?.onDragStart(leaf)
+ }
+ : undefined
+ }
+ onDragEnd={dragHandle ? () => dnd?.onDragEnd() : undefined}
+ className={cn('shrink-0', dragHandle && 'cursor-grab active:cursor-grabbing')}
+ >
+ <Icon size={13} className="opacity-70" />
+ </span>
{/* `truncate` hides overflow at the content edge, and this box shrink-wraps
to the text — so its edge is the advance width, which italic glyphs
lean past. An undocumented device is italic, and lost the tail of its
@@ -101,6 +165,7 @@ export function DocTreeItem({ leaf, depth, activeId, expanded, starred, onSelect
starred={starred}
onSelect={onSelect}
onToggle={onToggle}
+ dnd={dnd}
/>
))}
</>
diff --git a/frontend/src/documentation/components/DocumentationView.tsx b/frontend/src/documentation/components/DocumentationView.tsx
index 9615440..b81f079 100644
--- a/frontend/src/documentation/components/DocumentationView.tsx
+++ b/frontend/src/documentation/components/DocumentationView.tsx
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import { BookOpen, FilePlus, FolderPlus, Search, X } from 'lucide-react'
+import { BookOpen, ChevronDown, ChevronRight, FilePlus, FolderPlus, Search, X } from 'lucide-react'
import { toast } from 'sonner'
import { scanApi } from '@/api/client'
@@ -11,10 +11,17 @@ import type { InventoryEntry } from '@/types'
import { cn } from '@/lib/utils'
import { isOverdue } from '../frontmatter'
import { driftedIds, useDocsStore } from '../store'
-import { buildDeviceTree, buildLibraryTree, deviceLabel, filterGroups, filterTree } from '../tree'
+import {
+ buildDeviceTree,
+ buildLibraryTree,
+ canMoveInto,
+ deviceLabel,
+ filterGroups,
+ filterTree,
+} from '../tree'
import { GROUP_BY_LABELS, type GroupBy, type TreeLeaf } from '../types'
import { DocEditor } from './DocEditor'
-import { DocTreeGroups, DocTreeItem } from './DocTree'
+import { DocTreeGroups, DocTreeItem, type TreeDnd } from './DocTree'
import { DocViewer } from './DocViewer'
import { MigrateNotesBanner } from './MigrateNotesBanner'
import { NewDocMenu } from './NewDocMenu'
@@ -49,6 +56,7 @@ export function DocumentationView() {
acceptPendingDraft,
discardPendingDraft,
create,
+ move,
remove,
toggleStar,
markReviewed,
@@ -60,6 +68,7 @@ export function DocumentationView() {
setGroupBy,
expanded,
toggleExpanded,
+ setExpanded,
treeWidth,
setTreeWidth,
filter,
@@ -144,6 +153,64 @@ export function DocumentationView() {
[create, devices, dirty, open],
)
+ // Filing by drag. The confirmation is the point — a document that moves
+ // because a pointer slipped is worse than one nobody filed.
+ const [draggingId, setDraggingId] = useState<string | null>(null)
+ const [overId, setOverId] = useState<string | null>(null)
+ const [rootOver, setRootOver] = useState(false)
+
+ const dragged = useMemo(
+ () => (draggingId ? (docs.find((d) => d.id === draggingId) ?? null) : null),
+ [docs, draggingId],
+ )
+
+ const allowDrop = useCallback(
+ (targetId: string | null) => (dragged ? canMoveInto(docs, dragged, targetId) : false),
+ [docs, dragged],
+ )
+
+ const handleDrop = useCallback(
+ async (targetId: string | null) => {
+ const doc = dragged
+ setDraggingId(null)
+ setOverId(null)
+ setRootOver(false)
+ if (!doc || !canMoveInto(docs, doc, targetId)) return
+ const target = targetId ? docs.find((d) => d.id === targetId) : null
+ if (targetId && !target) return
+ const question = target
+ ? `Move \u201c${doc.title}\u201d into \u201c${target.title}\u201d?`
+ : `Move \u201c${doc.title}\u201d out to the top of the Library?`
+ if (!window.confirm(question)) return
+ try {
+ await move(doc.id, targetId)
+ // Land somewhere the user can see: a closed folder would swallow it.
+ if (targetId && !expanded.includes(targetId)) setExpanded([...expanded, targetId])
+ toast.success(target ? `Moved into \u201c${target.title}\u201d` : 'Moved to the top of the Library')
+ } catch {
+ toast.error('Could not move that document')
+ }
+ },
+ [docs, dragged, expanded, move, setExpanded],
+ )
+
+ const dnd: TreeDnd = useMemo(
+ () => ({
+ draggingId,
+ overId,
+ canDrop: allowDrop,
+ onDragStart: (leaf) => setDraggingId(leaf.docId ?? null),
+ onDragEnd: () => {
+ setDraggingId(null)
+ setOverId(null)
+ setRootOver(false)
+ },
+ onDragOver: setOverId,
+ onDrop: (targetId) => void handleDrop(targetId),
+ }),
+ [allowDrop, draggingId, handleDrop, overId],
+ )
+
const handleSave = useCallback(async () => {
if (await save()) toast.success('Saved')
}, [save])
@@ -248,7 +315,84 @@ export function DocumentationView() {
</div>
<div className="min-h-0 flex-1 overflow-y-auto py-1">
- <p className="px-2 pb-1 pt-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/50">
+ <div className="flex items-center gap-0.5 px-2 pb-1 pt-1">
+ <button
+ type="button"
+ onClick={() => setLibraryOpen((value) => !value)}
+ aria-expanded={libraryOpen}
+ className="flex flex-1 cursor-pointer items-center gap-1 text-left text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/50"
+ >
+ {libraryOpen ? <ChevronDown size={10} /> : <ChevronRight size={10} />}
+ Library
+ </button>
+ <NewDocMenu
+ placement="down"
+ onCreate={async (input) => {
+ const doc = await create(input)
+ if (doc) await open(doc.id)
+ }}
+ trigger={
+ <Button size="icon-xs" variant="ghost" aria-label="New document" title="New document">
+ <FilePlus />
+ </Button>
+ }
+ />
+ <Button
+ size="icon-xs"
+ variant="ghost"
+ aria-label="New folder"
+ title="New folder"
+ onClick={async () => {
+ const title = window.prompt('Folder name')
+ if (title?.trim()) await create({ title: title.trim(), kind: 'folder' })
+ }}
+ >
+ <FolderPlus />
+ </Button>
+ </div>
+
+ {/* Dropping on the empty space around the Library files a document at
+ its top level — the only way back out of a folder. */}
+ <div
+ onDragOver={(event) => {
+ if (!allowDrop(null)) return
+ event.preventDefault()
+ event.dataTransfer.dropEffect = 'move'
+ setRootOver(true)
+ }}
+ onDragLeave={() => setRootOver(false)}
+ onDrop={(event) => {
+ if (!allowDrop(null)) return
+ event.preventDefault()
+ void handleDrop(null)
+ }}
+ className={cn(
+ 'min-h-6 rounded',
+ rootOver && 'bg-primary/10 ring-1 ring-inset ring-primary/40',
+ )}
+ >
+ {libraryOpen &&
+ libraryItems.map((leaf) => (
+ <DocTreeItem
+ key={leaf.id}
+ leaf={leaf}
+ depth={1}
+ activeId={openDoc?.id ?? null}
+ expanded={expanded}
+ starred={starred}
+ onSelect={(item) => void handleSelect(item)}
+ onToggle={toggleExpanded}
+ dnd={dnd}
+ />
+ ))}
+ {libraryOpen && libraryItems.length === 0 && (
+ <p className="px-3 py-1 text-xs text-muted-foreground/60">
+ Nothing here yet — runbooks and overviews live in the Library.
+ </p>
+ )}
+ </div>
+
+ <p className="mt-3 px-2 pb-1 pt-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/50">
Devices
</p>
<DocTreeGroups
@@ -259,67 +403,18 @@ export function DocumentationView() {
onSelect={(leaf) => void handleSelect(leaf)}
onToggle={toggleExpanded}
/>
-
- <button
- type="button"
- onClick={() => setLibraryOpen((value) => !value)}
- aria-expanded={libraryOpen}
- className="mt-3 flex w-full cursor-pointer items-center px-2 pb-1 pt-1 text-left text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/50"
- >
- Library
- </button>
- {libraryOpen &&
- libraryItems.map((leaf) => (
- <DocTreeItem
- key={leaf.id}
- leaf={leaf}
- depth={1}
- activeId={openDoc?.id ?? null}
- expanded={expanded}
- starred={starred}
- onSelect={(item) => void handleSelect(item)}
- onToggle={toggleExpanded}
- />
- ))}
- {libraryOpen && libraryItems.length === 0 && (
- <p className="px-3 py-1 text-xs text-muted-foreground/60">
- Nothing here yet — runbooks and overviews live in the Library.
- </p>
- )}
</div>
- <div className="flex items-center gap-1 border-t border-border px-2 py-1.5">
- <NewDocMenu
- onCreate={async (input) => {
- const doc = await create(input)
- if (doc) await open(doc.id)
- }}
- trigger={
- <Button size="xs" variant="ghost" className="cursor-pointer gap-1">
- <FilePlus size={12} /> New
- </Button>
- }
- />
- <Button
- size="xs"
- variant="ghost"
- className="cursor-pointer gap-1"
- onClick={async () => {
- const title = window.prompt('Folder name')
- if (title?.trim()) await create({ title: title.trim(), kind: 'folder' })
- }}
- >
- <FolderPlus size={12} /> Folder
- </Button>
- {coverage && (
+ {coverage && (
+ <div className="flex items-center border-t border-border px-2 py-1.5">
<span
className="ml-auto text-[10px] tabular-nums text-muted-foreground/70"
title={`${coverage.documented} of ${coverage.devices} devices documented · ${coverage.header_only} still only the generated header`}
>
{coverage.documented}/{coverage.devices}
</span>
- )}
- </div>
+ </div>
+ )}
</aside>
<div
diff --git a/frontend/src/documentation/components/NewDocMenu.tsx b/frontend/src/documentation/components/NewDocMenu.tsx
index 29811d9..a99aed0 100644
--- a/frontend/src/documentation/components/NewDocMenu.tsx
+++ b/frontend/src/documentation/components/NewDocMenu.tsx
@@ -1,9 +1,13 @@
import { useEffect, useRef, useState, type ReactNode } from 'react'
+import { cn } from '@/lib/utils'
+
import { DOC_TEMPLATES } from '../types'
interface Props {
trigger: ReactNode
+ /** Which way the popover opens. The menu sits at the top of the pane now. */
+ placement?: 'up' | 'down'
parentId?: string | null
onCreate: (input: { title: string; templateId: string; parentId?: string | null }) => void | Promise<void>
}
@@ -15,7 +19,7 @@ interface Props {
* handful of primitives and this needs no focus trapping beyond closing on an
* outside click or Escape.
*/
-export function NewDocMenu({ trigger, parentId, onCreate }: Props) {
+export function NewDocMenu({ trigger, placement = 'up', parentId, onCreate }: Props) {
const [open, setOpen] = useState(false)
const root = useRef<HTMLDivElement>(null)
@@ -39,7 +43,12 @@ export function NewDocMenu({ trigger, parentId, onCreate }: Props) {
<div ref={root} className="relative">
<div onClick={() => setOpen((value) => !value)}>{trigger}</div>
{open && (
- <div className="absolute bottom-full left-0 z-30 mb-1 w-64 overflow-hidden rounded-lg border border-border bg-popover shadow-lg">
+ <div
+ className={cn(
+ 'absolute z-30 w-64 overflow-hidden rounded-lg border border-border bg-popover shadow-lg',
+ placement === 'up' ? 'bottom-full left-0 mb-1' : 'right-0 top-full mt-1',
+ )}
+ >
{DOC_TEMPLATES.map((template) => (
<button
key={template.id}
diff --git a/frontend/src/documentation/store.ts b/frontend/src/documentation/store.ts
index 477efc6..7b3bba7 100644
--- a/frontend/src/documentation/store.ts
+++ b/frontend/src/documentation/store.ts
@@ -2,6 +2,7 @@ import { create } from 'zustand'
import { documentsApi } from '@/api/client'
import { isOverdue } from './frontmatter'
+import { isDescendant } from './tree'
import type {
Doc,
DocCoverage,
@@ -20,6 +21,10 @@ import type {
* The draft is cleared the moment the save lands.
*/
+// The tree owns the parentage walk; the store re-exports it because callers of
+// `remove` and `move` reach for it from here.
+export { isDescendant }
+
const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
const UI_KEY = 'homelable_docs_ui'
@@ -302,7 +307,10 @@ export const useDocsStore = create<DocsState>()((set, get) => ({
move: async (id, parentId) => {
const { data } = await documentsApi.update(id, { parent_id: parentId })
- set((state) => ({ docs: state.docs.map((d) => (d.id === id ? { ...d, ...data } : d)) }))
+ set((state) => ({
+ docs: state.docs.map((d) => (d.id === id ? { ...d, ...data } : d)),
+ openDoc: state.openDoc?.id === id ? { ...state.openDoc, ...data } : state.openDoc,
+ }))
},
toggleStar: async (id) => {
@@ -442,19 +450,6 @@ export const useDocsStore = create<DocsState>()((set, get) => ({
setFilter: (filter) => set({ filter }),
}))
-/** Whether `doc` sits anywhere under `ancestorId`. */
-export function isDescendant(all: DocumentSummary[], doc: DocumentSummary, ancestorId: string): boolean {
- const byId = new Map(all.map((d) => [d.id, d]))
- const seen = new Set<string>()
- let cursor = doc.parent_id ?? null
- while (cursor && !seen.has(cursor)) {
- if (cursor === ancestorId) return true
- seen.add(cursor)
- cursor = byId.get(cursor)?.parent_id ?? null
- }
- return false
-}
-
/** Document ids the server flagged as drifted. Used for the tree badge. */
export function driftedIds(docs: DocumentSummary[]): Set<string> {
return new Set(docs.filter((doc) => doc.drifted).map((doc) => doc.id))
diff --git a/frontend/src/documentation/tree.ts b/frontend/src/documentation/tree.ts
index 75ea16f..cc03f9a 100644
--- a/frontend/src/documentation/tree.ts
+++ b/frontend/src/documentation/tree.ts
@@ -327,3 +327,40 @@ export function filterGroups(groups: TreeGroup[], query: string): TreeGroup[] {
}))
.filter((group) => group.items.length > 0)
}
+
+/** Whether `doc` sits anywhere under `ancestorId`. */
+export function isDescendant(
+ all: DocumentSummary[],
+ doc: DocumentSummary,
+ ancestorId: string,
+): boolean {
+ const byId = new Map(all.map((d) => [d.id, d]))
+ const seen = new Set<string>()
+ let cursor = doc.parent_id ?? null
+ while (cursor && !seen.has(cursor)) {
+ if (cursor === ancestorId) return true
+ seen.add(cursor)
+ cursor = byId.get(cursor)?.parent_id ?? null
+ }
+ return false
+}
+
+/**
+ * Whether `doc` can be filed under `targetId` — `null` being the Library root.
+ *
+ * The server enforces the same four rules; deciding them here too is what lets
+ * a drag refuse the drop instead of asking, moving, and then failing.
+ */
+export function canMoveInto(
+ docs: DocumentSummary[],
+ doc: DocumentSummary,
+ targetId: string | null,
+): boolean {
+ if (doc.kind !== 'page' && doc.kind !== 'folder') return false
+ if ((doc.parent_id ?? null) === targetId) return false
+ if (targetId === null) return true
+ if (targetId === doc.id) return false
+ const target = docs.find((d) => d.id === targetId)
+ if (!target || target.kind !== 'folder') return false
+ return !isDescendant(docs, target, doc.id)
+}