Files
Socrates/apps/web/components/text-canvas/TextCanvas.tsx
dtoro b55425cc68 Pivot to text-first column-stack workspace + merge-with-review across AI artifacts
Workspace
- Pivot from "set of open panes" to a Finder-style miller column stack:
  TopBar / LeftSidebar / [section → entity → entity ...] / pinned text editor.
  openPanesStore is now an ordered Column[] with pushFrom / closeFrom /
  setStack; only one top-level section is rooted at a time.
- New entity column panes: Term, Block, Association, Constraint,
  Requirement, Finding. Click-through navigation truncates deeper
  columns automatically.
- LeftSidebar surfaces a pending-count chip per section (single-glance
  navigation cue) and spins its analyze ↻ via SVG Spinner whenever the
  LLM is working — including server-initiated runs caught by the runs
  poll, not just user-triggered ones.

Analyze pipeline + persistence
- Unified `concepts` pass (taxonomy + glossary in one LLM call) replaces
  the two-pass setup. Server still accepts ?section=taxonomy|glossary
  and normalizes them for back-compat.
- model / requirements / detection (assumptions, risks, inconsistencies)
  + cross-layer validation rules (X1–X4: stale term link, unlinked
  formalism, undefined linked term, prose-only term).
- Persistence: NarrativeDocument, ModelSnapshot, ChangelogEntry,
  TaxonomyTerm, RequirementEntry, Finding, AnalysisRun. Re-runs MERGE
  instead of replace: gentle update on existing items, suggested on new,
  deprecated on missing — same idiom for every artifact kind. User pins
  preserve "kept" decisions across re-analyses.
- Migrations: pivot_text_first, add_requirement_linked_term,
  term_review_state, review_state_for_reqs_and_findings,
  add_term_definition_pinned.

Concept ↔ ontology integration
- linkedTermId on Block / Association / Constraint / Requirement.
  PromoteToolbar lets the user formalize a concept inline: + Block /
  + Association / + Constraint / + Requirement, all routed through
  applyOps so undo/redo and SSE work for free.
- decideElement op for in-canvas keep/discard on review-pending model
  elements.

User-authored definitions
- TermColumn definition is click-to-edit. Save (Cmd-Enter / blur),
  Cancel (Esc), Reset to AI suggestion when pinned.
- definitionPinned flag on TaxonomyTerm: future Analyze runs leave the
  user's text alone. setTermDefinition repo function + POST
  /api/projects/[id]/terms/[termId]/definition endpoint.
- mergeTaxonomySuggestion + applyGlossaryDefinitions both pin-aware.

UX/UI
- StatusChip: single component for all state idioms (suggested,
  deprecated, accepted, dismissed, resolved, severity, validation code,
  confidence, warn). Replaces 5+ ad-hoc badge classes.
- PaneControls (PaneViewTabs + PaneFilterChip): separates view-mode
  toggles from filter chips so toggling Pending no longer flips you off
  the current view.
- PaneEmpty: unified empty-state with title + hint + action.
- PaneDrawer: collapsible groups for Pending / Discarded review; cards
  group as Kept (top) → Pending (bottom drawer) → Discarded (Findings
  only, hidden when empty). Restore action recovers dismissed/resolved
  findings.
- ConceptCard unifies Tree and A–Z views in Concepts; only Tree parents
  carry the chevron (no empty placeholder offset).
- Type + spacing tokens (--text-xs..xl, --space-1..6, --lh-tight/ui/
  prose, --radius-*) replace every ad-hoc value.
- Buttons standardized to body sans 500 (was a mishmash of mono / display).
- Card shells unified across Concepts / Requirements / Findings.

Cleanup
- Removed: LeftRail, FindingsPanel, IssuesPanel, SocratesDock,
  ProposalCard, SlashMenu, SlashExtension, slashSuggestion,
  CanvasHeader, TaxonomyPane, GlossaryPane, TermDetail (popover; now
  TermColumn).
- Section ids in openPanesStore: dropped taxonomy/glossary, added
  concepts. localStorage migration runs on hydrate.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 00:12:06 +02:00

137 lines
4.5 KiB
TypeScript

// TipTap-backed narrative editor.
//
// After the pivot the text editor is the canonical surface. It loads its doc
// from /api/projects/[id]/document and saves on a 600ms debounce. Chips remain
// the rendered primitive but are no longer inserted via slash menu — the
// ChipSuggestionDecorator (added separately) suggests chip-ifying terms that
// match the project's taxonomy.
"use client";
import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import { useEffect, useMemo, useRef, useState } from "react";
import { ChipNode } from "./ChipNode";
import { ChipFocusContext } from "./FocusContext";
import { fixtureToDoc } from "./fixtureToDoc";
import { ChipSuggestionExtension } from "./ChipSuggestionExtension";
import type { FixtureData } from "../../lib/fixtures/aristotle";
import type { MarkupStyle } from "./Chip";
import { useAnalysis } from "../../lib/workspace/analysisStore";
export type Density = "comfortable" | "compact";
interface TextCanvasProps {
data: FixtureData;
projectId: string;
density?: Density;
markupStyle?: MarkupStyle;
}
export function TextCanvas({ data, projectId, density = "comfortable", markupStyle = "color" }: TextCanvasProps) {
const padY = density === "compact" ? 10 : 18;
const padX = density === "compact" ? 22 : 36;
const [focusBlockId, setFocusBlockId] = useState<string | null>(null);
const [initialDoc, setInitialDoc] = useState<unknown | null>(null);
const [loaded, setLoaded] = useState(false);
const focusValue = useMemo(() => ({ focusBlockId, setFocusBlockId }), [focusBlockId, setFocusBlockId]);
const { terms } = useAnalysis();
// Load the saved doc once on mount; fall back to the fixture if there is none.
useEffect(() => {
let cancelled = false;
(async () => {
try {
const res = await fetch(`/api/projects/${encodeURIComponent(projectId)}/document`);
if (!res.ok) throw new Error(`load doc: ${res.status}`);
const body = (await res.json()) as { doc: unknown };
if (cancelled) return;
setInitialDoc(body.doc ?? fixtureToDoc(data));
} catch {
if (!cancelled) setInitialDoc(fixtureToDoc(data));
} finally {
if (!cancelled) setLoaded(true);
}
})();
return () => {
cancelled = true;
};
}, [projectId, data]);
const editor = useEditor(
{
immediatelyRender: false,
extensions: [
StarterKit.configure({
heading: { levels: [1, 2] },
codeBlock: false,
blockquote: false,
horizontalRule: false,
bulletList: false,
orderedList: false,
listItem: false,
strike: false,
code: false,
link: false,
}),
ChipNode,
ChipSuggestionExtension,
],
content: initialDoc ?? null,
editorProps: {
attributes: {
class: "text-canvas tiptap",
style: `padding: ${padY}px ${padX}px;`,
},
},
},
[initialDoc]
);
// Push markup style + terms into the editor storage so node-views read them.
useEffect(() => {
if (!editor) return;
const storage = editor.storage as unknown as Record<string, unknown>;
storage.markupStyle = markupStyle;
storage.terms = terms;
editor.view.dispatch(editor.state.tr.setMeta("force-update", true));
}, [editor, markupStyle, terms]);
// Debounced save on document change.
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
if (!editor) return;
const onUpdate = () => {
if (saveTimer.current) clearTimeout(saveTimer.current);
saveTimer.current = setTimeout(() => {
const doc = editor.getJSON();
void fetch(`/api/projects/${encodeURIComponent(projectId)}/document`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ doc }),
}).catch(err => console.error("[TextCanvas] save failed:", err));
}, 600);
};
editor.on("update", onUpdate);
return () => {
editor.off("update", onUpdate);
if (saveTimer.current) clearTimeout(saveTimer.current);
};
}, [editor, projectId]);
if (!loaded || !editor) {
return (
<div className="text-canvas" style={{ padding: `${padY}px ${padX}px` }}>
<div style={{ color: "var(--muted)", fontFamily: "var(--font-mono)", fontSize: 12 }}>loading editor</div>
</div>
);
}
return (
<ChipFocusContext.Provider value={focusValue}>
<EditorContent editor={editor} />
</ChipFocusContext.Provider>
);
}