Files
Socrates/apps/web/components/text-canvas/ChipView.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

203 lines
7.6 KiB
TypeScript

// React NodeView for the chip TipTap node.
//
// M5: chips look up their displayed label from the SysMLModel via refId.
// Click a chip → opens an inline rename popover that emits an update-block
// op via useApply(). Renaming here updates every other chip with the same
// refId AND the diagram block label.
"use client";
import { NodeViewWrapper } from "@tiptap/react";
import type { NodeViewProps } from "@tiptap/react";
import { useEffect, useRef, useState } from "react";
import type { ChipKind } from "../../lib/fixtures/aristotle";
import type { MarkupStyle } from "./Chip";
import { useChipFocus } from "./FocusContext";
import { useModelStore } from "../../lib/sync/ModelStore";
import { useAnalysis } from "../../lib/workspace/analysisStore";
import { useOpenPanes } from "../../lib/workspace/openPanesStore";
import { updateBlock, updateRequirement, updateAssociation } from "../../lib/sync/ops";
const KIND_LABEL: Record<ChipKind, string> = {
block: "block",
property: "property",
association: "assoc",
requirement: "req",
};
function kindGlyph(kind: ChipKind): string {
switch (kind) {
case "block": return "▢";
case "property": return "·";
case "association": return "→";
case "requirement": return "§";
}
}
export function ChipView({ node, selected, editor }: NodeViewProps) {
const kind = (node.attrs.kind as ChipKind) ?? "block";
const refId = (node.attrs.refId as string | null) ?? null;
const fallbackLabel = (node.attrs.label as string) ?? "untitled";
const markupStyle =
((editor.storage as unknown as Record<string, unknown>).markupStyle as MarkupStyle | undefined) ?? "color";
const { focusBlockId, setFocusBlockId } = useChipFocus();
const { model, apply } = useModelStore();
const { getTerm } = useAnalysis();
const { setStack } = useOpenPanes();
// Resolve the live label from the model, falling back to the node's stored
// label (e.g. for chips created via slash-menu before they're bound).
const liveLabel = useMemo_label(model, kind, refId) ?? fallbackLabel;
const isFocused = (refId !== null && refId === focusBlockId) || selected;
const [isEditing, setIsEditing] = useState(false);
const [draft, setDraft] = useState(liveLabel);
const inputRef = useRef<HTMLInputElement | null>(null);
useEffect(() => {
if (isEditing) {
setDraft(liveLabel);
// Allow the input to mount before focusing.
requestAnimationFrame(() => {
inputRef.current?.focus();
inputRef.current?.select();
});
}
}, [isEditing, liveLabel]);
function commitRename() {
setIsEditing(false);
const next = draft.trim();
if (!next || next === liveLabel || !refId) return;
if (kind === "block") {
apply([updateBlock(refId, { label: next })]);
} else if (kind === "requirement") {
apply([updateRequirement(refId, { tag: next })]);
} else if (kind === "association") {
apply([updateAssociation(refId, { label: next })]);
}
// property and (potential future) constraint chips: rename in the
// model is more involved (need parent block id resolution); skip for M5.
}
const cls = `chip chip-${kind} chip-style-${markupStyle}${isFocused ? " chip-focus" : ""}${isEditing ? " chip-editing" : ""}`;
const handlers = refId
? {
onMouseEnter: () => setFocusBlockId(refId),
onMouseLeave: () => !isEditing && setFocusBlockId(null),
onDoubleClick: (e: React.MouseEvent) => {
e.preventDefault();
if (refId) setIsEditing(true);
},
onClick: () => {
// Single-click signals local diagram focus AND, if the chip refers
// to a term, opens that term as a Concepts → term column chain so
// the user lands in a coherent place.
setFocusBlockId(refId);
if (kind === "block" && getTerm(refId)) {
setStack([
{ kind: "section", id: "concepts" },
{ kind: "term", id: refId },
]);
}
},
}
: {};
// Inline rename input — replaces the label visual, preserves the chip frame
if (isEditing && refId) {
return (
<NodeViewWrapper as="span" className={cls} contentEditable={false} draggable={false}>
{markupStyle === "bracket" && <span className="chip-bracket">[</span>}
{markupStyle === "bracket" && <span className="chip-kind">{KIND_LABEL[kind]}:</span>}
{markupStyle !== "bracket" && <span className="chip-glyph">{kindGlyph(kind)}</span>}
<input
ref={inputRef}
className="chip-rename"
value={draft}
onChange={e => setDraft(e.target.value)}
onBlur={commitRename}
onKeyDown={e => {
if (e.key === "Enter") {
e.preventDefault();
(e.target as HTMLInputElement).blur();
} else if (e.key === "Escape") {
setDraft(liveLabel);
setIsEditing(false);
}
}}
size={Math.max(draft.length, 6)}
/>
{markupStyle === "bracket" && <span className="chip-bracket">]</span>}
</NodeViewWrapper>
);
}
if (markupStyle === "bracket") {
return (
<NodeViewWrapper as="span" className={cls} contentEditable={false} draggable={false} {...handlers} title={refId ? "double-click to rename" : undefined}>
<span className="chip-bracket">[</span>
<span className="chip-kind">{KIND_LABEL[kind]}:</span>
<span className="chip-label">{liveLabel}</span>
<span className="chip-bracket">]</span>
</NodeViewWrapper>
);
}
if (markupStyle === "underline") {
return (
<NodeViewWrapper as="span" className={cls} contentEditable={false} draggable={false} {...handlers} title={refId ? "double-click to rename" : undefined}>
<span className="chip-glyph">{kindGlyph(kind)}</span>
<span className="chip-label">{liveLabel}</span>
</NodeViewWrapper>
);
}
return (
<NodeViewWrapper as="span" className={cls} contentEditable={false} draggable={false} {...handlers} title={refId ? "double-click to rename" : undefined}>
<span className="chip-glyph">{kindGlyph(kind)}</span>
<span className="chip-label">{liveLabel}</span>
</NodeViewWrapper>
);
}
/**
* Look up the live label for a chip from the model. Inline-imported and
* collocated to keep the resolution rules near the consumer.
*
* For block / requirement / association / constraint chips we resolve by
* matching `refId` against the corresponding element. Property chips use a
* composite refId ("blockId.propertyId") — handled with a `.` split.
*/
function useMemo_label(model: ReturnType<typeof useModelStore>["model"], kind: ChipKind, refId: string | null): string | null {
if (!refId) return null;
if (kind === "block") {
return model.blocks.find(b => b.id === refId)?.label ?? null;
}
if (kind === "requirement") {
return model.requirements.find(r => r.id === refId || r.tag === refId)?.tag ?? null;
}
if (kind === "association") {
return model.associations.find(a => a.id === refId)?.label ?? null;
}
if (kind === "property") {
const dot = refId.indexOf(".");
if (dot < 0) {
// Bare property name from the fixture; do a flat search.
for (const b of model.blocks) {
const p = b.properties.find(p => p.name === refId || p.id === refId);
if (p) return p.name;
}
return null;
}
const blockId = refId.slice(0, dot);
const propId = refId.slice(dot + 1);
const b = model.blocks.find(x => x.id === blockId);
return b?.properties.find(p => p.id === propId || p.name === propId)?.name ?? null;
}
return null;
}