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>
This commit is contained in:
378
apps/web/lib/workspace/analysisStore.tsx
Normal file
378
apps/web/lib/workspace/analysisStore.tsx
Normal file
@@ -0,0 +1,378 @@
|
||||
// Client-side store holding the analyzer outputs (taxonomy, glossary terms,
|
||||
// requirements, findings, last-run metadata). Sidebar reads from here for
|
||||
// counts/timestamps; panes read for full content. Refetches on demand.
|
||||
|
||||
"use client";
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { SectionPaneId } from "./openPanesStore";
|
||||
|
||||
export type ClientTermStatus = "accepted" | "suggested" | "deprecated";
|
||||
|
||||
export interface ClientTerm {
|
||||
id: string;
|
||||
parentId: string | null;
|
||||
label: string;
|
||||
definition: string | null;
|
||||
synonyms: string[];
|
||||
linkedBlockId: string | null;
|
||||
/// Review state: "accepted" surfaces normally, "suggested" / "deprecated"
|
||||
/// are pending the user's keep/discard decision.
|
||||
status: ClientTermStatus;
|
||||
pinned: boolean;
|
||||
/// True when the user authored / edited the definition by hand. Future
|
||||
/// Analyze runs skip this term's definition while the flag is on.
|
||||
definitionPinned: boolean;
|
||||
}
|
||||
|
||||
export type ReviewStatus = "accepted" | "suggested" | "deprecated";
|
||||
|
||||
export interface ClientRequirement {
|
||||
id: string;
|
||||
tag: string;
|
||||
text: string;
|
||||
tracedToIds: string[];
|
||||
unsupported: boolean;
|
||||
/// Term this requirement is conceptually about, if any. Powers the back-link
|
||||
/// from a requirement row → TermDetail.
|
||||
linkedTermId: string | null;
|
||||
status: ReviewStatus;
|
||||
pinned: boolean;
|
||||
}
|
||||
|
||||
export interface ClientFinding {
|
||||
id: string;
|
||||
kind: "assumption" | "risk" | "inconsistency";
|
||||
text: string;
|
||||
linkedElementIds: string[];
|
||||
confidence: number;
|
||||
severity: string | null;
|
||||
validationCode: string | null;
|
||||
/// "suggested" | "accepted" | "deprecated" | "dismissed" | "resolved" |
|
||||
/// (legacy) "open". Visible-only set is fetched from the API; dismissed and
|
||||
/// resolved are filtered server-side.
|
||||
status: string;
|
||||
pinned: boolean;
|
||||
}
|
||||
|
||||
export interface ClientRun {
|
||||
status: "running" | "succeeded" | "failed";
|
||||
startedAt: string;
|
||||
finishedAt: string | null;
|
||||
errorMessage: string | null;
|
||||
}
|
||||
|
||||
// All sections map 1:1 to server sections after T3 (taxonomy + glossary
|
||||
// collapsed into "concepts"). Legacy values "taxonomy" / "glossary" still
|
||||
// work because the server normalizes them.
|
||||
export type AnalyzeSection = SectionPaneId | "all" | "taxonomy" | "glossary";
|
||||
|
||||
interface AnalysisStoreValue {
|
||||
terms: ClientTerm[];
|
||||
requirements: ClientRequirement[];
|
||||
findings: ClientFinding[];
|
||||
runs: Partial<Record<string, ClientRun>>;
|
||||
inFlight: Set<AnalyzeSection>;
|
||||
refresh(): Promise<void>;
|
||||
analyze(section: AnalyzeSection): Promise<void>;
|
||||
/** Lookup helper used by TermDetail. */
|
||||
getTerm(termId: string): ClientTerm | null;
|
||||
/** Apply a user decision to a pending term. Optimistically updates local
|
||||
* state; on server error refreshes to recover. */
|
||||
decideTerm(termId: string, decision: "keep" | "discard"): Promise<void>;
|
||||
/** Set a term's definition by user action. Empty string clears it AND
|
||||
* clears the pin (future Analyze fills it again from prose). */
|
||||
setTermDefinition(termId: string, definition: string | null): Promise<void>;
|
||||
decideRequirement(reqId: string, decision: "keep" | "discard"): Promise<void>;
|
||||
/** Findings support an extra "resolve" decision (semantically distinct from
|
||||
* "dismissed" — same effect on visibility, but signals "I fixed it"). */
|
||||
decideFinding(findingId: string, decision: "keep" | "discard" | "resolve" | "restore"): Promise<void>;
|
||||
}
|
||||
|
||||
const Ctx = createContext<AnalysisStoreValue | null>(null);
|
||||
|
||||
interface ProviderProps {
|
||||
projectId: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function AnalysisStoreProvider({ projectId, children }: ProviderProps) {
|
||||
const [terms, setTerms] = useState<ClientTerm[]>([]);
|
||||
const [requirements, setRequirements] = useState<ClientRequirement[]>([]);
|
||||
const [findings, setFindings] = useState<ClientFinding[]>([]);
|
||||
const [runs, setRuns] = useState<Partial<Record<string, ClientRun>>>({});
|
||||
const [inFlight, setInFlight] = useState<Set<AnalyzeSection>>(new Set());
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const [t, r, f, runsRes] = await Promise.all([
|
||||
fetch(`/api/projects/${encodeURIComponent(projectId)}/taxonomy`).then(x => (x.ok ? x.json() : { terms: [] })),
|
||||
fetch(`/api/projects/${encodeURIComponent(projectId)}/requirements`).then(x => (x.ok ? x.json() : { requirements: [] })),
|
||||
fetch(`/api/projects/${encodeURIComponent(projectId)}/findings?include=all`).then(x => (x.ok ? x.json() : { findings: [] })),
|
||||
fetch(`/api/projects/${encodeURIComponent(projectId)}/runs`).then(x => (x.ok ? x.json() : { runs: {} })),
|
||||
]);
|
||||
setTerms((t.terms as ClientTerm[]) ?? []);
|
||||
setRequirements((r.requirements as ClientRequirement[]) ?? []);
|
||||
setFindings((f.findings as ClientFinding[]) ?? []);
|
||||
setRuns((runsRes.runs as Partial<Record<string, ClientRun>>) ?? {});
|
||||
} catch (err) {
|
||||
console.error("[analysisStore] refresh failed:", err);
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
const analyze = useCallback(
|
||||
async (section: AnalyzeSection) => {
|
||||
setInFlight(prev => {
|
||||
const next = new Set(prev);
|
||||
next.add(section);
|
||||
return next;
|
||||
});
|
||||
try {
|
||||
const url =
|
||||
`/api/projects/${encodeURIComponent(projectId)}/analyze` +
|
||||
(section === "all" ? "" : `?section=${section}`);
|
||||
const res = await fetch(url, { method: "POST" });
|
||||
if (!res.ok) {
|
||||
const body = await res.text();
|
||||
console.error("[analyze] HTTP", res.status, body.slice(0, 200));
|
||||
}
|
||||
await refresh();
|
||||
} catch (err) {
|
||||
console.error("[analyze] failed:", err);
|
||||
} finally {
|
||||
setInFlight(prev => {
|
||||
const next = new Set(prev);
|
||||
next.delete(section);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
},
|
||||
[projectId, refresh]
|
||||
);
|
||||
|
||||
const getTerm = useCallback(
|
||||
(termId: string): ClientTerm | null => terms.find(t => t.id === termId) ?? null,
|
||||
[terms]
|
||||
);
|
||||
|
||||
const decideRequirement = useCallback(
|
||||
async (reqId: string, decision: "keep" | "discard") => {
|
||||
setRequirements(prev => {
|
||||
if (decision === "discard") return prev.filter(r => r.id !== reqId);
|
||||
return prev.map(r =>
|
||||
r.id === reqId
|
||||
? {
|
||||
...r,
|
||||
status: "accepted" as ReviewStatus,
|
||||
pinned: r.status === "deprecated" ? true : r.pinned,
|
||||
}
|
||||
: r
|
||||
);
|
||||
});
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/api/projects/${encodeURIComponent(projectId)}/requirements/${encodeURIComponent(reqId)}/decision`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ decision }),
|
||||
}
|
||||
);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
} catch (err) {
|
||||
console.error("[analysisStore] decideRequirement failed:", err);
|
||||
await refresh();
|
||||
}
|
||||
},
|
||||
[projectId, refresh]
|
||||
);
|
||||
|
||||
const decideFinding = useCallback(
|
||||
async (findingId: string, decision: "keep" | "discard" | "resolve" | "restore") => {
|
||||
// Optimistic update by terminal status:
|
||||
// keep / restore → "accepted" (visible in Kept list)
|
||||
// discard → "dismissed" (visible in Discarded drawer)
|
||||
// resolve → "resolved" (visible in Discarded drawer)
|
||||
const nextStatus =
|
||||
decision === "keep" || decision === "restore"
|
||||
? "accepted"
|
||||
: decision === "discard"
|
||||
? "dismissed"
|
||||
: "resolved";
|
||||
setFindings(prev =>
|
||||
prev.map(f =>
|
||||
f.id === findingId
|
||||
? {
|
||||
...f,
|
||||
status: nextStatus,
|
||||
pinned:
|
||||
decision === "keep" && f.status === "deprecated" ? true : f.pinned,
|
||||
}
|
||||
: f
|
||||
)
|
||||
);
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/api/projects/${encodeURIComponent(projectId)}/findings/${encodeURIComponent(findingId)}/decision`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ decision }),
|
||||
}
|
||||
);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
} catch (err) {
|
||||
console.error("[analysisStore] decideFinding failed:", err);
|
||||
await refresh();
|
||||
}
|
||||
},
|
||||
[projectId, refresh]
|
||||
);
|
||||
|
||||
const setTermDefinition = useCallback(
|
||||
async (termId: string, definition: string | null) => {
|
||||
const trimmed = (definition ?? "").trim();
|
||||
// Optimistic update: pin when non-empty, clear pin when empty.
|
||||
setTerms(prev =>
|
||||
prev.map(t =>
|
||||
t.id === termId
|
||||
? {
|
||||
...t,
|
||||
definition: trimmed.length > 0 ? trimmed : null,
|
||||
definitionPinned: trimmed.length > 0,
|
||||
}
|
||||
: t
|
||||
)
|
||||
);
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/api/projects/${encodeURIComponent(projectId)}/terms/${encodeURIComponent(termId)}/definition`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ definition: trimmed.length > 0 ? trimmed : null }),
|
||||
}
|
||||
);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
} catch (err) {
|
||||
console.error("[analysisStore] setTermDefinition failed:", err);
|
||||
await refresh();
|
||||
}
|
||||
},
|
||||
[projectId, refresh]
|
||||
);
|
||||
|
||||
const decideTerm = useCallback(
|
||||
async (termId: string, decision: "keep" | "discard") => {
|
||||
// Optimistic update: keep → accepted (+ pinned if previously deprecated);
|
||||
// discard → drop from local state.
|
||||
setTerms(prev => {
|
||||
if (decision === "discard") return prev.filter(t => t.id !== termId);
|
||||
return prev.map(t =>
|
||||
t.id === termId
|
||||
? {
|
||||
...t,
|
||||
status: "accepted" as ClientTermStatus,
|
||||
pinned: t.status === "deprecated" ? true : t.pinned,
|
||||
}
|
||||
: t
|
||||
);
|
||||
});
|
||||
try {
|
||||
const res = await fetch(
|
||||
`/api/projects/${encodeURIComponent(projectId)}/terms/${encodeURIComponent(termId)}/decision`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ decision }),
|
||||
}
|
||||
);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
} catch (err) {
|
||||
console.error("[analysisStore] decideTerm failed:", err);
|
||||
await refresh();
|
||||
}
|
||||
},
|
||||
[projectId, refresh]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
// First-load auto-analyze: if the project has a non-empty document but
|
||||
// nothing has been analyzed yet (no runs of any kind), kick off a full
|
||||
// Analyze in the background so the editor lands populated. Matches the
|
||||
// seed-finalize UX for the demo project and any imported docs.
|
||||
const bootstrappedRef = useRef(false);
|
||||
useEffect(() => {
|
||||
if (bootstrappedRef.current) return;
|
||||
if (Object.keys(runs).length > 0) return;
|
||||
if (terms.length > 0 || requirements.length > 0 || findings.length > 0) return;
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/projects/${encodeURIComponent(projectId)}/document`);
|
||||
if (!res.ok) return;
|
||||
const body = (await res.json()) as { doc?: unknown };
|
||||
const hasDoc = !!body.doc;
|
||||
if (!hasDoc || cancelled || bootstrappedRef.current) return;
|
||||
bootstrappedRef.current = true;
|
||||
void analyze("all");
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [projectId, runs, terms.length, requirements.length, findings.length, analyze]);
|
||||
|
||||
// Poll while any AnalysisRun is still "running" (e.g. the seed-finalize
|
||||
// background pipeline). Stop polling once everything has settled.
|
||||
useEffect(() => {
|
||||
const anyRunning = Object.values(runs).some(r => r?.status === "running");
|
||||
if (!anyRunning) return;
|
||||
const handle = setInterval(() => void refresh(), 3000);
|
||||
return () => clearInterval(handle);
|
||||
}, [runs, refresh]);
|
||||
|
||||
const value = useMemo<AnalysisStoreValue>(
|
||||
() => ({
|
||||
terms,
|
||||
requirements,
|
||||
findings,
|
||||
runs,
|
||||
inFlight,
|
||||
refresh,
|
||||
analyze,
|
||||
getTerm,
|
||||
decideTerm,
|
||||
decideRequirement,
|
||||
decideFinding,
|
||||
setTermDefinition,
|
||||
}),
|
||||
[
|
||||
terms,
|
||||
requirements,
|
||||
findings,
|
||||
runs,
|
||||
inFlight,
|
||||
refresh,
|
||||
analyze,
|
||||
getTerm,
|
||||
decideTerm,
|
||||
decideRequirement,
|
||||
decideFinding,
|
||||
setTermDefinition,
|
||||
]
|
||||
);
|
||||
|
||||
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
|
||||
}
|
||||
|
||||
export function useAnalysis(): AnalysisStoreValue {
|
||||
const ctx = useContext(Ctx);
|
||||
if (!ctx) throw new Error("useAnalysis must be inside <AnalysisStoreProvider>");
|
||||
return ctx;
|
||||
}
|
||||
236
apps/web/lib/workspace/openPanesStore.tsx
Normal file
236
apps/web/lib/workspace/openPanesStore.tsx
Normal file
@@ -0,0 +1,236 @@
|
||||
// Column-stack workspace store (Finder-style miller columns).
|
||||
//
|
||||
// State is a single ordered list `columns: Column[]` rendered left-to-right
|
||||
// in the main workspace. The first column is always a top-level section
|
||||
// (Concepts / Model / Requirements / Assumptions / Risks / Inconsistencies);
|
||||
// subsequent columns are entity details that drill down from the previous
|
||||
// column's selection.
|
||||
//
|
||||
// Invariants:
|
||||
// - Only one top-level section is open at a time. Clicking a different
|
||||
// section in the LeftSidebar replaces the entire stack.
|
||||
// - Pushing a child at parentIndex truncates everything to its right first.
|
||||
// - Resizing a column persists per (kind, id) so the user's chosen widths
|
||||
// stick across pushes.
|
||||
//
|
||||
// localStorage persistence keeps just the open section + per-column widths.
|
||||
// Detail children are deliberately ephemeral — they don't survive a reload.
|
||||
|
||||
"use client";
|
||||
|
||||
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
|
||||
|
||||
export type SectionPaneId =
|
||||
| "concepts"
|
||||
| "model"
|
||||
| "requirements"
|
||||
| "assumptions"
|
||||
| "risks"
|
||||
| "inconsistencies";
|
||||
|
||||
export const SECTION_TITLES: Record<SectionPaneId, string> = {
|
||||
concepts: "Concepts",
|
||||
model: "Model",
|
||||
requirements: "Requirements",
|
||||
assumptions: "Assumptions",
|
||||
risks: "Risks",
|
||||
inconsistencies: "Inconsistencies",
|
||||
};
|
||||
|
||||
export type Column =
|
||||
| { kind: "section"; id: SectionPaneId }
|
||||
| { kind: "term"; id: string }
|
||||
| { kind: "block"; id: string }
|
||||
| { kind: "association"; id: string }
|
||||
| { kind: "constraint"; id: string }
|
||||
| { kind: "requirement"; id: string }
|
||||
| { kind: "finding"; id: string };
|
||||
|
||||
export function columnKey(c: Column): string {
|
||||
return `${c.kind}:${c.id}`;
|
||||
}
|
||||
|
||||
export const PANE_MIN_WIDTH = 240;
|
||||
export const PANE_MAX_WIDTH = 720;
|
||||
export const PANE_DEFAULT_WIDTH = 340;
|
||||
|
||||
interface OpenPanesValue {
|
||||
/** Ordered chain of columns rendered in the main workspace. */
|
||||
columns: Column[];
|
||||
/** True when the first column is this section (the chain is rooted here). */
|
||||
isSectionOpen(id: SectionPaneId): boolean;
|
||||
/** Sidebar click: open this section as the chain root, or close everything
|
||||
* if it's already the active root. */
|
||||
toggleSection(id: SectionPaneId): void;
|
||||
/** Force-open a section (no-op if already root). */
|
||||
openSection(id: SectionPaneId): void;
|
||||
/** Truncate everything past `parentIndex`, then push `child`. If the same
|
||||
* child already sits at parentIndex+1, this is a no-op (clicking the
|
||||
* active item shouldn't flicker). */
|
||||
pushFrom(parentIndex: number, child: Column): void;
|
||||
/** Drop columns from `index` onward. */
|
||||
closeFrom(index: number): void;
|
||||
/** Replace the entire stack (used for cross-section jumps, e.g. a chip
|
||||
* click that wants to land in Concepts → term). */
|
||||
setStack(columns: Column[]): void;
|
||||
/** Per-column width, keyed by columnKey. */
|
||||
widthFor(c: Column): number;
|
||||
setWidth(c: Column, width: number): void;
|
||||
}
|
||||
|
||||
const Ctx = createContext<OpenPanesValue | null>(null);
|
||||
|
||||
interface PersistShape {
|
||||
rootSection?: SectionPaneId | null;
|
||||
widths?: Record<string, number>;
|
||||
/** Legacy field from the pre-stack store. Hydrated and discarded. */
|
||||
open?: string[];
|
||||
}
|
||||
|
||||
interface ProviderProps {
|
||||
projectId: string;
|
||||
initial?: SectionPaneId | null;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function OpenPanesProvider({ projectId, initial = null, children }: ProviderProps) {
|
||||
const storageKey = `socrata.workspace.${projectId}`;
|
||||
const [columns, setColumns] = useState<Column[]>(initial ? [{ kind: "section", id: initial }] : []);
|
||||
const [widths, setWidths] = useState<Record<string, number>>({});
|
||||
const [hydrated, setHydrated] = useState(false);
|
||||
|
||||
// Hydrate from localStorage on mount.
|
||||
useEffect(() => {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(storageKey);
|
||||
if (raw) {
|
||||
const parsed = JSON.parse(raw) as PersistShape | string[];
|
||||
let nextRoot: SectionPaneId | null = null;
|
||||
const cleanedWidths: Record<string, number> = {};
|
||||
|
||||
if (Array.isArray(parsed)) {
|
||||
// Very old format: array of section ids. Take the first valid one.
|
||||
for (const id of parsed.map(migrateLegacyId).filter(isSectionPaneId)) {
|
||||
nextRoot = id;
|
||||
break;
|
||||
}
|
||||
} else if (parsed && typeof parsed === "object") {
|
||||
if (parsed.rootSection && isSectionPaneId(parsed.rootSection)) {
|
||||
nextRoot = parsed.rootSection;
|
||||
} else if (Array.isArray(parsed.open)) {
|
||||
// Pre-stack store kept multiple sections open; pick the first valid one.
|
||||
for (const id of parsed.open.map(migrateLegacyId).filter(isSectionPaneId)) {
|
||||
nextRoot = id;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (parsed.widths && typeof parsed.widths === "object") {
|
||||
for (const [k, v] of Object.entries(parsed.widths)) {
|
||||
if (typeof v === "number" && Number.isFinite(v)) cleanedWidths[k] = clamp(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (nextRoot) setColumns([{ kind: "section", id: nextRoot }]);
|
||||
setWidths(cleanedWidths);
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
setHydrated(true);
|
||||
}, [storageKey]);
|
||||
|
||||
// Persist root section + widths (NOT child columns — those are ephemeral).
|
||||
useEffect(() => {
|
||||
if (!hydrated) return;
|
||||
try {
|
||||
const root = columns[0]?.kind === "section" ? columns[0].id : null;
|
||||
const payload: PersistShape = { rootSection: root, widths };
|
||||
window.localStorage.setItem(storageKey, JSON.stringify(payload));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}, [columns, widths, storageKey, hydrated]);
|
||||
|
||||
const isSectionOpen = useCallback(
|
||||
(id: SectionPaneId) => columns[0]?.kind === "section" && columns[0].id === id,
|
||||
[columns]
|
||||
);
|
||||
|
||||
const toggleSection = useCallback((id: SectionPaneId) => {
|
||||
setColumns(cur => {
|
||||
if (cur[0]?.kind === "section" && cur[0].id === id) return [];
|
||||
return [{ kind: "section", id }];
|
||||
});
|
||||
}, []);
|
||||
|
||||
const openSection = useCallback((id: SectionPaneId) => {
|
||||
setColumns(cur => {
|
||||
if (cur[0]?.kind === "section" && cur[0].id === id) return cur;
|
||||
return [{ kind: "section", id }];
|
||||
});
|
||||
}, []);
|
||||
|
||||
const pushFrom = useCallback((parentIndex: number, child: Column) => {
|
||||
setColumns(cur => {
|
||||
const head = cur.slice(0, parentIndex + 1);
|
||||
const existing = cur[parentIndex + 1];
|
||||
// Same child already there → keep it (no flicker, preserves any state).
|
||||
if (existing && existing.kind === child.kind && existing.id === child.id) {
|
||||
return cur.slice(0, parentIndex + 2);
|
||||
}
|
||||
return [...head, child];
|
||||
});
|
||||
}, []);
|
||||
|
||||
const closeFrom = useCallback((index: number) => {
|
||||
setColumns(cur => cur.slice(0, Math.max(0, index)));
|
||||
}, []);
|
||||
|
||||
const setStack = useCallback((next: Column[]) => {
|
||||
setColumns(next);
|
||||
}, []);
|
||||
|
||||
const widthFor = useCallback(
|
||||
(c: Column) => widths[columnKey(c)] ?? PANE_DEFAULT_WIDTH,
|
||||
[widths]
|
||||
);
|
||||
const setWidth = useCallback((c: Column, width: number) => {
|
||||
setWidths(prev => ({ ...prev, [columnKey(c)]: clamp(width) }));
|
||||
}, []);
|
||||
|
||||
const value = useMemo<OpenPanesValue>(
|
||||
() => ({
|
||||
columns,
|
||||
isSectionOpen,
|
||||
toggleSection,
|
||||
openSection,
|
||||
pushFrom,
|
||||
closeFrom,
|
||||
setStack,
|
||||
widthFor,
|
||||
setWidth,
|
||||
}),
|
||||
[columns, isSectionOpen, toggleSection, openSection, pushFrom, closeFrom, setStack, widthFor, setWidth]
|
||||
);
|
||||
|
||||
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
|
||||
}
|
||||
|
||||
export function useOpenPanes(): OpenPanesValue {
|
||||
const ctx = useContext(Ctx);
|
||||
if (!ctx) throw new Error("useOpenPanes must be inside <OpenPanesProvider>");
|
||||
return ctx;
|
||||
}
|
||||
|
||||
function isSectionPaneId(x: unknown): x is SectionPaneId {
|
||||
return typeof x === "string" && x in SECTION_TITLES;
|
||||
}
|
||||
|
||||
function migrateLegacyId(id: string): string {
|
||||
if (id === "taxonomy" || id === "glossary") return "concepts";
|
||||
return id;
|
||||
}
|
||||
|
||||
function clamp(w: number): number {
|
||||
return Math.max(PANE_MIN_WIDTH, Math.min(PANE_MAX_WIDTH, Math.round(w)));
|
||||
}
|
||||
3
apps/web/lib/workspace/types.ts
Normal file
3
apps/web/lib/workspace/types.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
// Small shared types used across editor surfaces.
|
||||
|
||||
export type Density = "comfortable" | "compact";
|
||||
Reference in New Issue
Block a user