MVP M5 (in-memory): bidirectional sync via ModelOp + applyOps + ModelStore

Both canvases now share a canonical SysMLModel through React context.
Renames in the diagram inspector ripple to every chip in the narrative
referencing the same refId, and double-clicking a chip emits an update op
that re-renders the diagram block. Validation re-runs on every successful
apply. State is in-memory; M5.9 adds Postgres persistence.

apps/web/lib/sync (new)
- ops.ts: ModelOp alphabet (18 op kinds across block / property /
  association / constraint / requirement / relation, add/update/remove for
  each). tempId() helper + per-kind constructors.
- applyOps.ts: pure (model, ops) → { model, idMapping, errors, applied }
  reducer. Atomic per batch. Cascades on remove-block (drops incident
  associations + constraint applies-to + requirement satisfiers). tempId
  resolution rewrites to canonical ids on duplicate-id collision.
- ModelStore.tsx: React provider exposing { model, apply, issues,
  issuesByElement }. Validation memoized on every model change.

Editor refactor
- EditorShell wraps in ModelStoreProvider. Initial model derived from
  fixture (+ optional ?break= corruptions). Validation now lives in the
  store, not duplicated here.
- LeftRail consumes useModel(): Model section lists real blocks +
  constraints (sorted by kind), Requirements section lists real
  requirements with traced/untraced status from r.relations.

Diagram refactor (the tricky piece)
- React Flow now owns ephemeral state via useNodesState / useEdgesState.
  Positions, drag-in-progress, selection are all RF-internal.
- Model → RF: a useEffect runs on model change, applies targeted setNodes
  updates only for elements whose semantic data (label, kind, properties)
  changed. Object identity preserved for unchanged nodes — fixes the
  "re-render storm on drag" + RF measurement-cache loss.
- RF → Model: onNodesChange / onEdgesChange / onConnect / onDrop emit
  ops via useApply(). Constraint-applies edges decompose into
  updateConstraint ops. deleteKeyCode={[Backspace, Delete]}.
- onNodesChange now handles type:'remove' too (was missing — that's why
  selecting a block + Del removed only the edges, leaving the block).

Chip refactor
- ChipView resolves displayed label from useModel() via refId lookup
  (block / requirement / association / property). Double-click chip →
  inline rename input → emit update-{block,requirement,association} op.
  All other chips with the same refId update on the next render.
- Slash-menu inserted chips have refId=null and skip the rename
  affordance (until M6 wires real model element resolution).

Removed obsolete components/diagram-canvas/fixtureToFlow.ts; replaced
with modelToFlow.ts. Bumped CSS for the chip-rename input.
This commit is contained in:
2026-04-29 00:42:18 +02:00
parent 2052a280b1
commit 384cbb4ae9
12 changed files with 1375 additions and 229 deletions

View File

@@ -0,0 +1,83 @@
// React provider exposing the canonical SysMLModel + applyOps.
// Used by both canvases (and the rail) so they stay in sync.
"use client";
import { createContext, useCallback, useContext, useMemo, useState } from "react";
import { applyOps, type ApplyResult } from "./applyOps";
import { validate, type ValidationIssue } from "../sysml/validate";
import type { SysMLModel } from "../sysml/model";
import type { ModelOp } from "./ops";
export interface ModelStoreValue {
model: SysMLModel;
apply: (ops: ModelOp[]) => ApplyResult;
/** Validation issues, recomputed on each successful apply. */
issues: ValidationIssue[];
issuesByElement: Map<string, ValidationIssue[]>;
}
const ModelStoreContext = createContext<ModelStoreValue | null>(null);
interface ModelStoreProviderProps {
initialModel: SysMLModel;
children: React.ReactNode;
}
export function ModelStoreProvider({ initialModel, children }: ModelStoreProviderProps) {
const [model, setModel] = useState<SysMLModel>(initialModel);
const apply = useCallback((ops: ModelOp[]): ApplyResult => {
let result: ApplyResult = { model, idMapping: {}, errors: [], applied: false };
setModel(current => {
result = applyOps(current, ops);
return result.applied ? result.model : current;
});
return result;
}, [model]);
const { issues, issuesByElement } = useMemo(() => {
const issues = validate(model);
const issuesByElement = new Map<string, ValidationIssue[]>();
for (const i of issues) {
const k = anchorKey(i.anchor);
if (!k) continue;
const prev = issuesByElement.get(k) ?? [];
prev.push(i);
issuesByElement.set(k, prev);
}
return { issues, issuesByElement };
}, [model]);
const value: ModelStoreValue = useMemo(
() => ({ model, apply, issues, issuesByElement }),
[model, apply, issues, issuesByElement]
);
return <ModelStoreContext.Provider value={value}>{children}</ModelStoreContext.Provider>;
}
export function useModelStore(): ModelStoreValue {
const ctx = useContext(ModelStoreContext);
if (!ctx) throw new Error("useModelStore must be used inside ModelStoreProvider");
return ctx;
}
export function useModel(): SysMLModel {
return useModelStore().model;
}
export function useApply(): (ops: ModelOp[]) => ApplyResult {
return useModelStore().apply;
}
function anchorKey(anchor: ValidationIssue["anchor"]): string | null {
switch (anchor.kind) {
case "block": return anchor.id;
case "association": return `assoc:${anchor.id}`;
case "constraint": return `constraint:${anchor.id}`;
case "requirement": return `req:${anchor.id}`;
case "property": return anchor.blockId;
case "model": return null;
}
}

View File

@@ -0,0 +1,261 @@
// The single chokepoint for SysMLModel mutations.
//
// Pure: (model, ops) → { model, idMapping, errors }. No DB / network here.
// M5 in-memory: tempIds are used as canonical ids when free, otherwise
// rewritten with a `_n` suffix. The DB layer (later) will replace this with
// server-issued ids.
//
// applyOps is atomic per-batch: if any op fails validation, the entire
// batch is rejected and the original model is returned unchanged. This is
// the contract docs/sync.md §4 specifies.
import type { SysMLModel, Block, Association, Constraint, Requirement } from "../sysml/model";
import type { ModelOp } from "./ops";
export interface ApplyResult {
model: SysMLModel;
/** Map of any tempId → assigned canonical id. */
idMapping: Record<string, string>;
errors: ApplyError[];
/** True iff the batch landed without errors. */
applied: boolean;
}
export interface ApplyError {
opIndex: number;
code: "DUPLICATE_ID" | "MISSING_ELEMENT" | "INVALID_PATCH";
message: string;
}
export function applyOps(model: SysMLModel, ops: ModelOp[]): ApplyResult {
const idMapping: Record<string, string> = {};
const errors: ApplyError[] = [];
// Fail-fast working copy. We mutate this; if errors accumulate we throw it
// away and return the original.
let next = cloneModel(model);
for (let i = 0; i < ops.length; i++) {
const op = ops[i]!;
try {
next = applyOne(next, op, idMapping);
} catch (err) {
errors.push({ opIndex: i, code: classifyError(err), message: (err as Error).message });
}
}
if (errors.length > 0) {
return { model, idMapping: {}, errors, applied: false };
}
return { model: next, idMapping, errors: [], applied: true };
}
// ─── Per-op application ──────────────────────────────────────────────────
function applyOne(model: SysMLModel, op: ModelOp, idMapping: Record<string, string>): SysMLModel {
switch (op.kind) {
case "add-block": {
const id = resolveAddId(op.block.id, op.tempId, idMapping, model.blocks.map(b => b.id));
const block: Block = { ...op.block, id };
return { ...model, blocks: [...model.blocks, block] };
}
case "update-block": {
const realId = idMapping[op.blockId] ?? op.blockId;
assertExists(model.blocks, realId, "block");
return {
...model,
blocks: model.blocks.map(b => (b.id === realId ? { ...b, ...op.patch } : b)),
};
}
case "remove-block": {
const realId = idMapping[op.blockId] ?? op.blockId;
assertExists(model.blocks, realId, "block");
// Cascade: drop incident associations + requirement satisfiers + constraint applies-to
return {
...model,
blocks: model.blocks.filter(b => b.id !== realId),
associations: model.associations.filter(a => a.fromBlockId !== realId && a.toBlockId !== realId),
constraints: model.constraints.map(c => ({ ...c, appliesTo: c.appliesTo.filter(id => id !== realId) })),
requirements: model.requirements.map(r => ({
...r,
relations: r.relations.filter(rel => rel.kind !== "satisfy" || rel.blockId !== realId),
})),
};
}
case "add-property": {
const blockId = idMapping[op.blockId] ?? op.blockId;
const block = model.blocks.find(b => b.id === blockId);
if (!block) throw missing("block", blockId);
const propId = resolveAddId(op.property.id, op.tempId, idMapping, block.properties.map(p => p.id));
return {
...model,
blocks: model.blocks.map(b =>
b.id === blockId ? { ...b, properties: [...b.properties, { ...op.property, id: propId }] } : b
),
};
}
case "update-property": {
const blockId = idMapping[op.blockId] ?? op.blockId;
return {
...model,
blocks: model.blocks.map(b =>
b.id === blockId
? { ...b, properties: b.properties.map(p => (p.id === op.propertyId ? { ...p, ...op.patch } : p)) }
: b
),
};
}
case "remove-property": {
const blockId = idMapping[op.blockId] ?? op.blockId;
return {
...model,
blocks: model.blocks.map(b =>
b.id === blockId ? { ...b, properties: b.properties.filter(p => p.id !== op.propertyId) } : b
),
};
}
case "add-association": {
const id = resolveAddId(op.association.id, op.tempId, idMapping, model.associations.map(a => a.id));
const association: Association = {
...op.association,
id,
fromBlockId: idMapping[op.association.fromBlockId] ?? op.association.fromBlockId,
toBlockId: idMapping[op.association.toBlockId] ?? op.association.toBlockId,
};
return { ...model, associations: [...model.associations, association] };
}
case "update-association": {
const realId = idMapping[op.associationId] ?? op.associationId;
assertExists(model.associations, realId, "association");
return {
...model,
associations: model.associations.map(a => (a.id === realId ? { ...a, ...op.patch } : a)),
};
}
case "remove-association": {
const realId = idMapping[op.associationId] ?? op.associationId;
assertExists(model.associations, realId, "association");
return { ...model, associations: model.associations.filter(a => a.id !== realId) };
}
case "add-constraint": {
const id = resolveAddId(op.constraint.id, op.tempId, idMapping, model.constraints.map(c => c.id));
const constraint: Constraint = {
...op.constraint,
id,
appliesTo: op.constraint.appliesTo.map(b => idMapping[b] ?? b),
};
return { ...model, constraints: [...model.constraints, constraint] };
}
case "update-constraint": {
const realId = idMapping[op.constraintId] ?? op.constraintId;
assertExists(model.constraints, realId, "constraint");
return {
...model,
constraints: model.constraints.map(c => (c.id === realId ? { ...c, ...op.patch } : c)),
};
}
case "remove-constraint": {
const realId = idMapping[op.constraintId] ?? op.constraintId;
assertExists(model.constraints, realId, "constraint");
return { ...model, constraints: model.constraints.filter(c => c.id !== realId) };
}
case "add-requirement": {
const id = resolveAddId(op.requirement.id, op.tempId, idMapping, model.requirements.map(r => r.id));
const requirement: Requirement = { ...op.requirement, id };
return { ...model, requirements: [...model.requirements, requirement] };
}
case "update-requirement": {
const realId = idMapping[op.requirementId] ?? op.requirementId;
assertExists(model.requirements, realId, "requirement");
return {
...model,
requirements: model.requirements.map(r => (r.id === realId ? { ...r, ...op.patch } : r)),
};
}
case "remove-requirement": {
const realId = idMapping[op.requirementId] ?? op.requirementId;
assertExists(model.requirements, realId, "requirement");
return { ...model, requirements: model.requirements.filter(r => r.id !== realId) };
}
case "add-relation": {
const realId = idMapping[op.requirementId] ?? op.requirementId;
assertExists(model.requirements, realId, "requirement");
return {
...model,
requirements: model.requirements.map(r =>
r.id === realId ? { ...r, relations: [...r.relations, op.relation] } : r
),
};
}
case "remove-relation": {
const realId = idMapping[op.requirementId] ?? op.requirementId;
assertExists(model.requirements, realId, "requirement");
return {
...model,
requirements: model.requirements.map(r =>
r.id === realId
? { ...r, relations: r.relations.filter((_, idx) => idx !== op.relationIndex) }
: r
),
};
}
}
}
// ─── Helpers ─────────────────────────────────────────────────────────────
function cloneModel(model: SysMLModel): SysMLModel {
// Shallow-clone collections; nested objects are immutable per our op contract.
return {
systemOfInterestId: model.systemOfInterestId,
blocks: model.blocks.map(b => ({ ...b, properties: [...b.properties], stereotypes: [...b.stereotypes] })),
associations: model.associations.map(a => ({ ...a })),
constraints: model.constraints.map(c => ({ ...c, appliesTo: [...c.appliesTo] })),
requirements: model.requirements.map(r => ({ ...r, relations: [...r.relations] })),
};
}
/**
* Decide what id to use for a newly-added element.
* - If the requested id is unused, it sticks. (Most common path.)
* - Otherwise, append `_2`, `_3`, … until free, and record the mapping from
* the requested id to the assigned id so subsequent ops in the same batch
* can reference the new element by its tempId.
*/
function resolveAddId(
desiredId: string,
tempId: string | undefined,
idMapping: Record<string, string>,
existing: string[]
): string {
const taken = new Set(existing);
if (!taken.has(desiredId)) {
if (tempId) idMapping[tempId] = desiredId;
return desiredId;
}
let suffix = 2;
while (taken.has(`${desiredId}_${suffix}`)) suffix++;
const final = `${desiredId}_${suffix}`;
if (tempId) idMapping[tempId] = final;
idMapping[desiredId] = final;
return final;
}
function assertExists<T extends { id: string }>(items: T[], id: string, what: string): void {
if (!items.find(i => i.id === id)) throw missing(what, id);
}
function missing(what: string, id: string): Error {
return new Error(`${what} "${id}" not found`);
}
function classifyError(err: unknown): ApplyError["code"] {
const msg = (err as Error).message ?? "";
if (msg.includes("not found")) return "MISSING_ELEMENT";
if (msg.includes("duplicate")) return "DUPLICATE_ID";
return "INVALID_PATCH";
}

235
apps/web/lib/sync/ops.ts Normal file
View File

@@ -0,0 +1,235 @@
// The canonical ModelOp alphabet — every mutation to a SysMLModel is
// expressible as one or more of these. See docs/sync.md §3 for the design.
//
// `tempId` lets clients optimistically create elements with a client-generated
// id; applyOps may rewrite to a canonical id and return the mapping. (M5
// in-memory: tempId IS the canonical id; the rewrite seam is here for the
// later DB / SSE iteration.)
import type {
Block,
BlockKind,
Association,
AssociationKind,
Constraint,
Property,
PropertyType,
Multiplicity,
Requirement,
RequirementRelation,
} from "../sysml/model";
// ─── Block ops ───────────────────────────────────────────────────────────
export interface AddBlockOp {
kind: "add-block";
block: Block;
tempId?: string;
}
export interface UpdateBlockOp {
kind: "update-block";
blockId: string;
patch: Partial<Pick<Block, "label" | "kind" | "stereotypes" | "description">>;
}
export interface RemoveBlockOp {
kind: "remove-block";
blockId: string;
}
// ─── Property ops ────────────────────────────────────────────────────────
export interface AddPropertyOp {
kind: "add-property";
blockId: string;
property: Property;
tempId?: string;
}
export interface UpdatePropertyOp {
kind: "update-property";
blockId: string;
propertyId: string;
patch: Partial<Pick<Property, "name" | "type" | "multiplicity" | "description">>;
}
export interface RemovePropertyOp {
kind: "remove-property";
blockId: string;
propertyId: string;
}
// ─── Association ops ─────────────────────────────────────────────────────
export interface AddAssociationOp {
kind: "add-association";
association: Association;
tempId?: string;
}
export interface UpdateAssociationOp {
kind: "update-association";
associationId: string;
patch: Partial<Pick<Association, "fromBlockId" | "toBlockId" | "label" | "kind" | "multiplicity">>;
}
export interface RemoveAssociationOp {
kind: "remove-association";
associationId: string;
}
// ─── Constraint ops ──────────────────────────────────────────────────────
export interface AddConstraintOp {
kind: "add-constraint";
constraint: Constraint;
tempId?: string;
}
export interface UpdateConstraintOp {
kind: "update-constraint";
constraintId: string;
patch: Partial<Pick<Constraint, "label" | "expression" | "appliesTo">>;
}
export interface RemoveConstraintOp {
kind: "remove-constraint";
constraintId: string;
}
// ─── Requirement ops ─────────────────────────────────────────────────────
export interface AddRequirementOp {
kind: "add-requirement";
requirement: Requirement;
tempId?: string;
}
export interface UpdateRequirementOp {
kind: "update-requirement";
requirementId: string;
patch: Partial<Pick<Requirement, "tag" | "text">>;
}
export interface RemoveRequirementOp {
kind: "remove-requirement";
requirementId: string;
}
export interface AddRelationOp {
kind: "add-relation";
requirementId: string;
relation: RequirementRelation;
}
export interface RemoveRelationOp {
kind: "remove-relation";
requirementId: string;
relationIndex: number;
}
// ─── Union ───────────────────────────────────────────────────────────────
export type ModelOp =
| AddBlockOp
| UpdateBlockOp
| RemoveBlockOp
| AddPropertyOp
| UpdatePropertyOp
| RemovePropertyOp
| AddAssociationOp
| UpdateAssociationOp
| RemoveAssociationOp
| AddConstraintOp
| UpdateConstraintOp
| RemoveConstraintOp
| AddRequirementOp
| UpdateRequirementOp
| RemoveRequirementOp
| AddRelationOp
| RemoveRelationOp;
// ─── Op constructors (call sites stay readable) ─────────────────────────
export function addBlock(block: Block, tempId?: string): AddBlockOp {
return { kind: "add-block", block, tempId };
}
export function updateBlock(blockId: string, patch: UpdateBlockOp["patch"]): UpdateBlockOp {
return { kind: "update-block", blockId, patch };
}
export function removeBlock(blockId: string): RemoveBlockOp {
return { kind: "remove-block", blockId };
}
export function addProperty(blockId: string, property: Property, tempId?: string): AddPropertyOp {
return { kind: "add-property", blockId, property, tempId };
}
export function updateProperty(blockId: string, propertyId: string, patch: UpdatePropertyOp["patch"]): UpdatePropertyOp {
return { kind: "update-property", blockId, propertyId, patch };
}
export function removeProperty(blockId: string, propertyId: string): RemovePropertyOp {
return { kind: "remove-property", blockId, propertyId };
}
export function addAssociation(association: Association, tempId?: string): AddAssociationOp {
return { kind: "add-association", association, tempId };
}
export function updateAssociation(associationId: string, patch: UpdateAssociationOp["patch"]): UpdateAssociationOp {
return { kind: "update-association", associationId, patch };
}
export function removeAssociation(associationId: string): RemoveAssociationOp {
return { kind: "remove-association", associationId };
}
export function addConstraint(constraint: Constraint, tempId?: string): AddConstraintOp {
return { kind: "add-constraint", constraint, tempId };
}
export function updateConstraint(constraintId: string, patch: UpdateConstraintOp["patch"]): UpdateConstraintOp {
return { kind: "update-constraint", constraintId, patch };
}
export function removeConstraint(constraintId: string): RemoveConstraintOp {
return { kind: "remove-constraint", constraintId };
}
export function addRequirement(requirement: Requirement, tempId?: string): AddRequirementOp {
return { kind: "add-requirement", requirement, tempId };
}
export function updateRequirement(requirementId: string, patch: UpdateRequirementOp["patch"]): UpdateRequirementOp {
return { kind: "update-requirement", requirementId, patch };
}
export function removeRequirement(requirementId: string): RemoveRequirementOp {
return { kind: "remove-requirement", requirementId };
}
export function addRelation(requirementId: string, relation: RequirementRelation): AddRelationOp {
return { kind: "add-relation", requirementId, relation };
}
export function removeRelation(requirementId: string, relationIndex: number): RemoveRelationOp {
return { kind: "remove-relation", requirementId, relationIndex };
}
// ─── Helpers ─────────────────────────────────────────────────────────────
let counter = 0;
/** Generate a temp id. Distinct prefix so applyOps can recognize them. */
export function tempId(prefix = "tmp"): string {
counter++;
return `${prefix}_${Date.now().toString(36)}_${counter}`;
}
/** Quick property factory used by clients producing add-property ops. */
export function newProperty(name: string, type: PropertyType = { kind: "string" }, multiplicity: Multiplicity = "0..1"): Property {
return { id: tempId("p"), name, type, multiplicity };
}