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.
262 lines
9.9 KiB
TypeScript
262 lines
9.9 KiB
TypeScript
// 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";
|
|
}
|