Repository Public
1"use client";2import { useCallback, useReducer } from "react";3import { allBlocks, stableStringify, type Block, type LeafBlock, type Sheet } from "@/schema";45/**6 * Document state of the editor: the working copy plus an undo/redo history of whole documents (they are small7 * JSON values; 100 steps cost little). Edits made in quick succession on the same field coalesce into one step.8 */9interface State { doc: Sheet; past: Sheet[]; future: Sheet[]; lastKey: string | null; lastAt: number }10type Action =11 | { type: "commit"; doc: Sheet; key?: string }12 | { type: "replace"; doc: Sheet } // from the server (AI edit, revert, reload): becomes a new undoable step13 | { type: "reset"; doc: Sheet }14 | { type: "undo" } | { type: "redo" };1516const LIMIT = 100;17function reducer(s: State, a: Action): State {18 switch (a.type) {19 case "commit": {20 if (stableStringify(a.doc) === stableStringify(s.doc)) return s;21 const now = Date.now();22 const coalesce = a.key !== undefined && a.key === s.lastKey && now - s.lastAt < 1200;23 return { doc: a.doc, past: coalesce ? s.past : [...s.past, s.doc].slice(-LIMIT), future: [], lastKey: a.key ?? null, lastAt: now };24 }25 case "replace": return stableStringify(a.doc) === stableStringify(s.doc) ? s : { doc: a.doc, past: [...s.past, s.doc].slice(-LIMIT), future: [], lastKey: null, lastAt: 0 };26 case "reset": return { doc: a.doc, past: [], future: [], lastKey: null, lastAt: 0 };27 case "undo": return s.past.length ? { doc: s.past[s.past.length - 1], past: s.past.slice(0, -1), future: [s.doc, ...s.future], lastKey: null, lastAt: 0 } : s;28 case "redo": return s.future.length ? { doc: s.future[0], past: [...s.past, s.doc], future: s.future.slice(1), lastKey: null, lastAt: 0 } : s;29 }30}3132export function useDocState(initial: Sheet) {33 const [s, dispatch] = useReducer(reducer, { doc: initial, past: [], future: [], lastKey: null, lastAt: 0 });34 return {35 doc: s.doc, canUndo: s.past.length > 0, canRedo: s.future.length > 0,36 commit: useCallback((doc: Sheet, key?: string) => dispatch({ type: "commit", doc, key }), []),37 replace: useCallback((doc: Sheet) => dispatch({ type: "replace", doc }), []),38 reset: useCallback((doc: Sheet) => dispatch({ type: "reset", doc }), []),39 undo: useCallback(() => dispatch({ type: "undo" }), []),40 redo: useCallback(() => dispatch({ type: "redo" }), []),41 };42}4344// ── Pure document operations (top-level blocks and tab children) ────────────────────────────────────4546export const replaceBlock = (doc: Sheet, id: string, next: Block | LeafBlock): Sheet => ({47 ...doc,48 blocks: doc.blocks.map((b) => (b.id === id ? (next as Block) : b.type === "tabs" ? { ...b, tabs: b.tabs.map((t) => ({ ...t, blocks: t.blocks.map((c) => (c.id === id ? (next as LeafBlock) : c)) })) } : b)),49});5051/**52 * Removes blocks at any depth. A removed tab group takes its children with it; a tab never ends up empty (its last53 * child stays). Claims that pointed at a removed block keep their text and lose the link.54 */55export const removeBlocks = (doc: Sheet, ids: string[]): Sheet => {56 const wanted = new Set(ids.filter((id) => !allBlocks(doc).find((b) => b.id === id)?.locked));57 const blocks = doc.blocks.filter((b) => !wanted.has(b.id)).map((b) => (b.type !== "tabs" ? b : { ...b, tabs: b.tabs.map((t) => { const kept = t.blocks.filter((c) => !wanted.has(c.id)); return { ...t, blocks: kept.length ? kept : t.blocks.slice(0, 1) }; }) }));58 const left = new Set(allBlocks({ ...doc, blocks }).map((b) => b.id));59 return { ...doc, blocks, claims: doc.claims.map((c) => (c.blockId && !left.has(c.blockId) ? { ...c, blockId: undefined } : c)) };60};6162export const insertAfter = (doc: Sheet, afterId: string | null, block: Block): Sheet => {63 const i = afterId ? doc.blocks.findIndex((b) => b.id === afterId) : -1;64 const blocks = [...doc.blocks];65 blocks.splice(afterId && i >= 0 ? i + 1 : afterId === null ? blocks.length : blocks.length, 0, block);66 return { ...doc, blocks };67};6869export const moveBlock = (doc: Sheet, id: string, toIndex: number): Sheet => {70 const from = doc.blocks.findIndex((b) => b.id === id);71 if (from < 0 || doc.blocks[from].locked) return doc;72 const blocks = [...doc.blocks];73 const [b] = blocks.splice(from, 1);74 blocks.splice(Math.max(0, Math.min(blocks.length, toIndex)), 0, b);75 return { ...doc, blocks };76};77