From 779e674e7b31cb11cc546a501109e63b216de73e Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 13:52:38 +0000 Subject: [PATCH 01/15] feat: edges.labels draws each connector's relationship field Tree and XY connectors can show the field the relationship is declared in, so typed relationships read at a glance. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_019XphpcKhuNyHcNArHFELR4 --- docs/definitions.md | 3 +- .../src/core/format/definition-schema.ts | 5 ++ packages/map-views/src/core/tree.ts | 40 +++++++++------ .../map-views/src/layouts/EdgeOverlay.tsx | 50 +++++++++++++------ packages/map-views/src/layouts/TreeLayout.tsx | 6 ++- packages/map-views/src/layouts/XYLayout.tsx | 3 +- .../map-views/tests/definition-types.test.ts | 2 +- packages/map-views/tests/definition.test.ts | 2 +- packages/map-views/tests/tree.test.ts | 5 ++ schemas/generated/latest/definition.json | 12 +++++ 10 files changed, 95 insertions(+), 33 deletions(-) diff --git a/docs/definitions.md b/docs/definitions.md index d851e1a..5a40523 100644 --- a/docs/definitions.md +++ b/docs/definitions.md @@ -48,6 +48,7 @@ A map view definition is a JSON5 file. Its format is a set of JSON Schemas publi | `nodes.validation` | | The lowest severity of validation result drawn on nodes: `off` (the default), `error`, `warning` or `info`. Results come from the host; with none supplied nothing is drawn | | `nodes.validationSources` | | Which results are drawn: any of structured-context's issue kinds, such as `schema`, `hierarchy` or `rule` (default all) | | `edges.show` | | Whether connectors are drawn (default `true`) | +| `edges.labels` | | Whether each connector shows the field the relationship is declared in (default `false`) | ## Layouts @@ -93,7 +94,7 @@ An axis has a `field` (required), a `domain` (`[min, max]`, or `'data'` for the ## Parameters -Any setting marked parameterisable in the schemas (`orientation`, `dag`, `intermediate`, `nodes.style`, `nodes.fields`, `nodes.validation`, `nodes.validationSources`, `edges.show`, a landscape level's `type`, an axis's `field` and `direction`, `types`, `edgeFields`) takes either a fixed value or `{ $param: '' }`. +Any setting marked parameterisable in the schemas (`orientation`, `dag`, `intermediate`, `nodes.style`, `nodes.fields`, `nodes.validation`, `nodes.validationSources`, `edges.show`, `edges.labels`, a landscape level's `type`, an axis's `field` and `direction`, `types`, `edgeFields`) takes either a fixed value or `{ $param: '' }`. Each parameter is a JSON Schema with a `default` and an optional `title`. It can `$ref` a shared setting from `settings.json` (`orientation`, `nodeStyle`, `fieldList`, `validationLevel`, `validationSources`) or a layout's own definitions (e.g. `layouts/tree.json#/$defs/dag`), and narrow it. Relative refs resolve against the format's `latest` folder; full URLs work too. diff --git a/packages/map-views/src/core/format/definition-schema.ts b/packages/map-views/src/core/format/definition-schema.ts index a07a0c9..b7a7b34 100644 --- a/packages/map-views/src/core/format/definition-schema.ts +++ b/packages/map-views/src/core/format/definition-schema.ts @@ -133,6 +133,11 @@ export const definitionSchema = { default: {}, properties: { show: parameterisable({ type: 'boolean' }, true, 'Whether connectors are drawn.'), + labels: parameterisable( + { type: 'boolean' }, + false, + 'Whether each connector is labelled with the field the relationship is declared in.', + ), }, }, }, diff --git a/packages/map-views/src/core/tree.ts b/packages/map-views/src/core/tree.ts index 1a2d2be..cb3f46c 100644 --- a/packages/map-views/src/core/tree.ts +++ b/packages/map-views/src/core/tree.ts @@ -14,6 +14,8 @@ export type TreeOccurrence = { * appears under each of them, but its subtree is only rendered at its first occurrence. */ repeatOf?: string; + /** The field the parent declares this node through (the edge's label); unset for roots. */ + field?: string; }; export type Tree = { @@ -32,7 +34,7 @@ export type Tree = { crossLinks: TreeLink[]; }; -export type TreeLink = { from: string; to: string; kind: 'tree' | 'cross' }; +export type TreeLink = { from: string; to: string; kind: 'tree' | 'cross'; field?: string }; /** * Lay a space out as a tree over its hierarchy. @@ -48,7 +50,7 @@ export function buildTree(graph: SpaceGraph, regionId: string, dag: DagMode = 'r const rootType = hierarchy?.levels[0]?.type; const primary = new Map(); // Parent occurrence → child title, resolved to the child's primary occurrence afterwards. - const pendingCross: { from: string; child: string }[] = []; + const pendingCross: { from: string; child: string; field: string }[] = []; const hierarchyParents = (title: SpaceNode['id']) => parentEdges(graph, title).filter((edge) => isHierarchyEdge(edge, hierarchy)); @@ -57,20 +59,25 @@ export function buildTree(graph: SpaceGraph, regionId: string, dag: DagMode = 'r const nodePath = [...path, node.id]; const key = occurrenceKey(regionId, nodePath); primary.set(node.id, key); - // A child can reference the same parent through more than one field; it occurs once. - const childTitles = new Set( - childEdges(graph, node.id) - .filter((edge) => isHierarchyEdge(edge, hierarchy)) - .map((edge) => edge.child), - ); + // A child can reference the same parent through more than one field; it occurs once, under the first. + const childFields = new Map(); + for (const edge of childEdges(graph, node.id)) { + if (isHierarchyEdge(edge, hierarchy) && !childFields.has(edge.child)) childFields.set(edge.child, edge.field); + } const children: TreeOccurrence[] = []; - for (const title of childTitles) { + for (const [title, field] of childFields) { const child = graph.nodes.get(title)!; const repeatOf = primary.get(title); - if (repeatOf === undefined) children.push(visit(child, nodePath)); + if (repeatOf === undefined) children.push({ ...visit(child, nodePath), field }); else if (dag === 'repeat') - children.push({ key: occurrenceKey(regionId, [...nodePath, title]), node: child, children: [], repeatOf }); - else pendingCross.push({ from: key, child: title }); + children.push({ + key: occurrenceKey(regionId, [...nodePath, title]), + node: child, + children: [], + repeatOf, + field, + }); + else pendingCross.push({ from: key, child: title, field }); } return { key, node, children }; }; @@ -85,7 +92,12 @@ export function buildTree(graph: SpaceGraph, regionId: string, dag: DagMode = 'r if (!primary.has(node.id)) orphans.push(visit(node, [])); } - const crossLinks = pendingCross.map(({ from, child }) => ({ from, to: primary.get(child)!, kind: 'cross' as const })); + const crossLinks = pendingCross.map(({ from, child, field }) => ({ + from, + to: primary.get(child)!, + kind: 'cross' as const, + field, + })); return { roots, orphans, primary, crossLinks }; } @@ -94,7 +106,7 @@ export function treeLinks(tree: Tree): TreeLink[] { const links: TreeLink[] = []; const walk = (occurrence: TreeOccurrence) => { for (const child of occurrence.children) { - links.push({ from: occurrence.key, to: child.key, kind: 'tree' }); + links.push({ from: occurrence.key, to: child.key, kind: 'tree', field: child.field }); walk(child); } }; diff --git a/packages/map-views/src/layouts/EdgeOverlay.tsx b/packages/map-views/src/layouts/EdgeOverlay.tsx index 37c7a05..7045e41 100644 --- a/packages/map-views/src/layouts/EdgeOverlay.tsx +++ b/packages/map-views/src/layouts/EdgeOverlay.tsx @@ -6,7 +6,15 @@ import type { Orientation } from '../core/definition'; * `id` tells apart several links between the same occurrences; straight links between the same * pair are drawn side by side, `lane` apart (0: on the line between centres). */ -export type Link = { from: string; to: string; kind?: 'tree' | 'cross'; id?: string; lane?: number }; +export type Link = { + from: string; + to: string; + kind?: 'tree' | 'cross'; + id?: string; + lane?: number; + /** Text drawn at the middle of the connector. */ + label?: string; +}; type Props = { links: readonly Link[]; @@ -22,7 +30,7 @@ type Props = { routing: Orientation | 'straight'; }; -type Drawn = { key: string; d: string; cross: boolean }; +type Drawn = { key: string; d: string; cross: boolean; label?: string; at: readonly [number, number] }; /** * SVG layer drawing connectors between rendered occurrences. @@ -41,15 +49,12 @@ export function EdgeOverlay({ links, elements, container, routing }: Props) { const measure = () => { const origin = container.getBoundingClientRect(); const paths: Drawn[] = []; - for (const { from, to, kind, id, lane = 0 } of links) { + for (const { from, to, kind, id, lane = 0, label } of links) { const a = elements.get(from)?.getBoundingClientRect(); const b = elements.get(to)?.getBoundingClientRect(); if (!a || !b) continue; - paths.push({ - key: `${from}→${to}${id ?? ''}`, - d: routing === 'straight' ? line(a, b, origin, lane) : connector(a, b, origin, routing), - cross: kind === 'cross', - }); + const [d, at] = routing === 'straight' ? line(a, b, origin, lane) : connector(a, b, origin, routing); + paths.push({ key: `${from}→${to}${id ?? ''}`, d, cross: kind === 'cross', label, at }); } setPaths(paths); }; @@ -75,26 +80,43 @@ export function EdgeOverlay({ links, elements, container, routing }: Props) { strokeDasharray={cross ? '4 3' : undefined} /> ))} + {paths.map(({ key, label, at }) => + label ? ( + + {label} + + ) : null, + )} ); } -/** Cubic curve from the parent's trailing edge to the child's leading edge. */ -function connector(a: DOMRect, b: DOMRect, origin: DOMRect, orientation: Orientation): string { +/** Cubic curve from the parent's trailing edge to the child's leading edge, and its midpoint. */ +function connector(a: DOMRect, b: DOMRect, origin: DOMRect, orientation: Orientation): [string, [number, number]] { if (orientation === 'vertical') { const x1 = a.left + a.width / 2 - origin.left; const y1 = a.bottom - origin.top; const x2 = b.left + b.width / 2 - origin.left; const y2 = b.top - origin.top; const my = (y1 + y2) / 2; - return `M${x1},${y1} C${x1},${my} ${x2},${my} ${x2},${y2}`; + return [`M${x1},${y1} C${x1},${my} ${x2},${my} ${x2},${y2}`, [(x1 + x2) / 2, my]]; } const x1 = a.right - origin.left; const y1 = a.top + a.height / 2 - origin.top; const x2 = b.left - origin.left; const y2 = b.top + b.height / 2 - origin.top; const mx = (x1 + x2) / 2; - return `M${x1},${y1} C${mx},${y1} ${mx},${y2} ${x2},${y2}`; + return [`M${x1},${y1} C${mx},${y1} ${mx},${y2} ${x2},${y2}`, [mx, (y1 + y2) / 2]]; } /** Pixels between parallel straight links. */ @@ -105,7 +127,7 @@ const LANE_GAP = 6; * overlay to hide the ends. The shift is relative to a fixed orientation of the pair, so links in * opposite directions between the same nodes still separate. */ -function line(a: DOMRect, b: DOMRect, origin: DOMRect, lane: number): string { +function line(a: DOMRect, b: DOMRect, origin: DOMRect, lane: number): [string, [number, number]] { const x1 = a.left + a.width / 2 - origin.left; const y1 = a.top + a.height / 2 - origin.top; const x2 = b.left + b.width / 2 - origin.left; @@ -114,5 +136,5 @@ function line(a: DOMRect, b: DOMRect, origin: DOMRect, lane: number): string { const length = Math.hypot(x2 - x1, y2 - y1) || 1; const dx = (-(y2 - y1) / length) * lane * LANE_GAP * flip; const dy = ((x2 - x1) / length) * lane * LANE_GAP * flip; - return `M${x1 + dx},${y1 + dy} L${x2 + dx},${y2 + dy}`; + return [`M${x1 + dx},${y1 + dy} L${x2 + dx},${y2 + dy}`, [(x1 + x2) / 2 + dx, (y1 + y2) / 2 + dy]]; } diff --git a/packages/map-views/src/layouts/TreeLayout.tsx b/packages/map-views/src/layouts/TreeLayout.tsx index 7e69e2b..6eec3a7 100644 --- a/packages/map-views/src/layouts/TreeLayout.tsx +++ b/packages/map-views/src/layouts/TreeLayout.tsx @@ -20,7 +20,11 @@ export type LayoutProps = { export function TreeLayout({ graph, region, instanceId, onNodeSelect }: LayoutProps) { const { orientation, dag } = region.layout; const tree = useMemo(() => buildTree(graph, region.id, dag), [graph, region.id, dag]); - const links = useMemo(() => (region.edges.show ? treeLinks(tree) : []), [tree, region.edges.show]); + const { show, labels } = region.edges; + const links = useMemo( + () => (show ? treeLinks(tree).map(({ field, ...link }) => ({ ...link, label: labels ? field : undefined })) : []), + [tree, show, labels], + ); const [container, setContainer] = useState(null); // Filled by ref callbacks during commit, read by the overlay's layout effect afterwards. diff --git a/packages/map-views/src/layouts/XYLayout.tsx b/packages/map-views/src/layouts/XYLayout.tsx index bdae60d..d8cfe49 100644 --- a/packages/map-views/src/layouts/XYLayout.tsx +++ b/packages/map-views/src/layouts/XYLayout.tsx @@ -24,9 +24,10 @@ export function XYLayout({ graph, region, instanceId, onNodeSelect }: LayoutProp id: field, lane, kind: hierarchy ? ('tree' as const) : ('cross' as const), + label: region.edges.labels ? field : undefined, })) : [], - [plot, region.edges.show], + [plot, region.edges.show, region.edges.labels], ); const shape = region.nodes.style === 'shape'; diff --git a/packages/map-views/tests/definition-types.test.ts b/packages/map-views/tests/definition-types.test.ts index 1ddfe90..2e21fa7 100644 --- a/packages/map-views/tests/definition-types.test.ts +++ b/packages/map-views/tests/definition-types.test.ts @@ -8,7 +8,7 @@ const region: Region = { id: 'main', layout: { type: 'tree', orientation: 'horizontal', dag: 'cross-edge' }, nodes: { style: 'shape', fields: ['status'], validation: 'warning', validationSources: ['schema', 'rule'] }, - edges: { show: false }, + edges: { show: false, labels: false }, }; // @ts-expect-error resolved regions have no parameter bindings diff --git a/packages/map-views/tests/definition.test.ts b/packages/map-views/tests/definition.test.ts index 6bb3ff7..7db65cd 100644 --- a/packages/map-views/tests/definition.test.ts +++ b/packages/map-views/tests/definition.test.ts @@ -43,7 +43,7 @@ describe('parseMapViewDefinition', () => { validation: 'off', validationSources: [...VALIDATION_ISSUE_KINDS], }, - edges: { show: true }, + edges: { show: true, labels: false }, }, ]); }); diff --git a/packages/map-views/tests/tree.test.ts b/packages/map-views/tests/tree.test.ts index 4371f32..1f740d4 100644 --- a/packages/map-views/tests/tree.test.ts +++ b/packages/map-views/tests/tree.test.ts @@ -35,6 +35,11 @@ describe('sample tree', () => { expect(all.some((o) => o.node.resolvedType === 'Outcomes')).toBe(false); }); + test('every link carries the field the parent declares the child through', () => { + const links = treeLinks(tree); + expect(links.every((link) => typeof link.field === 'string' && link.field.length > 0)).toBe(true); + }); + test('links pair each rendered child with its parent occurrence', () => { const links = treeLinks(tree); expect(links.length).toBe(all.length - tree.roots.length - tree.orphans.length); diff --git a/schemas/generated/latest/definition.json b/schemas/generated/latest/definition.json index 0872929..59f07a5 100644 --- a/schemas/generated/latest/definition.json +++ b/schemas/generated/latest/definition.json @@ -205,6 +205,18 @@ "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json#/$defs/paramRef" } ] + }, + "labels": { + "description": "Whether each connector is labelled with the field the relationship is declared in.", + "default": false, + "anyOf": [ + { + "type": "boolean" + }, + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json#/$defs/paramRef" + } + ] } } } From ffe519867147d200b33f773859684f0c3fd0a727 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 14:01:59 +0000 Subject: [PATCH 02/15] feat: compass layout shows a focus node's neighbours by role Adds the compass layout with a bundled knowledge wiki neighbourhood view. Selecting a neighbour moves the focus; hosts can set it with focus. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_019XphpcKhuNyHcNArHFELR4 --- docs/api.md | 2 +- docs/architecture.md | 5 +- docs/concepts.md | 5 ++ docs/definitions.md | 14 +++- .../knowledge-wiki-neighbourhood.json5 | 18 ++++ packages/map-views/src/core/compass.ts | 71 ++++++++++++++++ packages/map-views/src/core/definition.ts | 3 + .../src/core/format/compass-layout.ts | 24 ++++++ .../src/core/format/definition-schema.ts | 1 + packages/map-views/src/core/format/index.ts | 11 ++- packages/map-views/src/core/lanes.ts | 13 +++ packages/map-views/src/core/xy.ts | 15 +--- .../map-views/src/layouts/CompassLayout.tsx | 83 +++++++++++++++++++ packages/map-views/src/layouts/MapView.tsx | 18 +++- .../map-views/src/node/bundled-definitions.ts | 1 + packages/map-views/tests/compass.test.ts | 67 +++++++++++++++ .../map-views/tests/load-definitions.test.ts | 8 +- schemas/generated/latest/definition.json | 3 + schemas/generated/latest/layouts/compass.json | 64 ++++++++++++++ 19 files changed, 403 insertions(+), 23 deletions(-) create mode 100644 packages/map-views/map-views/knowledge-wiki-neighbourhood.json5 create mode 100644 packages/map-views/src/core/compass.ts create mode 100644 packages/map-views/src/core/format/compass-layout.ts create mode 100644 packages/map-views/src/core/lanes.ts create mode 100644 packages/map-views/src/layouts/CompassLayout.tsx create mode 100644 packages/map-views/tests/compass.test.ts create mode 100644 schemas/generated/latest/layouts/compass.json diff --git a/docs/api.md b/docs/api.md index 06ed5a0..0bdd8c1 100644 --- a/docs/api.md +++ b/docs/api.md @@ -19,7 +19,7 @@ import 'structured-context-map-views/styles.css'; open(node)} /> ``` -`graph` is a structured-context `SpaceGraph` (see [Data](#data)); `values` and the controls' `onChange` belong to the host. Pass `annotations` to show validation results (see [Validation results](#validation-results)). +`graph` is a structured-context `SpaceGraph` (see [Data](#data)); `values` and the controls' `onChange` belong to the host. Pass `annotations` to show validation results (see [Validation results](#validation-results)). `focus` and `onFocusChange` set and follow the node a [compass](definitions.md#compass) layout centres on. A host that lays out the controls itself builds them from `useParameterControls` and `ParameterInput`. diff --git a/docs/architecture.md b/docs/architecture.md index d2c019e..a15b529 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -6,7 +6,7 @@ A space graph and a definition go in; a DOM layout with an SVG overlay comes out flowchart LR space[structured-context space] -->|host assembles| graph[SpaceGraph] def[definition .json5] -->|parseMapViewDefinition| mvd[MapViewDefinition] - graph --> proj[projection
tree · landscape · xy] + graph --> proj[projection
tree · landscape · xy · compass] mvd --> proj proj --> dom[layout component
DOM + SVG overlay] ``` @@ -15,7 +15,7 @@ flowchart LR | Module | Holds | May import | |---|---|---| -| `packages/map-views/src/core` | Definition parsing and validation, parameter resolution, graph helpers, and the projections (`buildTree`, `buildLandscape`, `buildXYPlot`) | Types from structured-context only. No React, DOM or Node | +| `packages/map-views/src/core` | Definition parsing and validation, parameter resolution, graph helpers, and the projections (`buildTree`, `buildLandscape`, `buildXYPlot`, `buildCompass`) | Types from structured-context only. No React, DOM or Node | | `packages/map-views/src/layouts` | `MapView`, the layout components, `NodeCard`, `EdgeOverlay`, the parameter controls (`useParameterControls`, the typed inputs and the default `ParameterControls` layout), styles | core, React | | `packages/map-views/src/viewer` | `Viewer`, the page-filling UI that hosts share. What is specific to a host comes in as an option | core, layouts, React, `structured-context/browser` | | `packages/map-views/src/node` | `loadMapViewDefinitions`: finding definitions in the library (embedded at build time from `packages/map-views/map-views/`), plugins and config folders; `exportSnapshot` and the `export` bin, which snapshot a space for browser-only hosts; `fillPage`, which writes snapshots into the self-contained page. `fillPage` and `readDefinitionFolders` are also the `/html` entry, which imports nothing from structured-context's API | core, Node, structured-context | @@ -37,6 +37,7 @@ Each layout has a pure projection in core that turns the graph and the region's - **Tree**: walks the hierarchy from the root type. A node with several parents is repeated (subtree once) or placed once with cross-links. Cycles end in a repeat. - **Landscape**: walks the grouping levels, joining node levels by edges in either direction, through `via` chains or by field values. - **XY**: normalises two numeric fields to percentages within each axis's domain and lists the nodes it can't place. +- **Compass**: places the focus's neighbours by the role of the field joining them. Occurrence keys are paths (region, ancestors, node), so a node appearing several times gets distinct keys. diff --git a/docs/concepts.md b/docs/concepts.md index 8d88ae8..1565d19 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -21,6 +21,7 @@ The arrangement a region uses, chosen from a fixed catalogue: - **tree**: a tree over the schema's hierarchy. - **landscape**: nested containers following an authored grouping. - **xy**: nodes positioned by two numeric fields. +- **compass**: one node with its neighbours placed around it by role. Each layout carries its own opinions (spacing, card sizes, colours). Definitions choose and configure a layout; they don't compose one. @@ -35,6 +36,10 @@ The two ways a tree shows a node with several parents: - **repeat**: the node appears under each parent, and its subtree is shown once. - **cross-edge**: the node appears under its first parent, with extra connectors from the others. +## Focus + +The node a compass layout centres on. Hosts can set it; otherwise the reader's picks move it. + ## Grouping level One step of a landscape's grouping: a node type, or a field whose values become containers. Levels can follow edges in either direction, and a `via` chain can skip types between two levels. diff --git a/docs/definitions.md b/docs/definitions.md index 5a40523..1b295c5 100644 --- a/docs/definitions.md +++ b/docs/definitions.md @@ -92,9 +92,21 @@ Nodes positioned on two axes by numeric fields. Plotted nodes without a usable v An axis has a `field` (required), a `domain` (`[min, max]`, or `'data'` for the smallest and largest plotted values; default `'data'`), a `direction` (`ascending`, the default, or `descending`) and a `label` (defaults to the field name). +### compass + +One focus node with its neighbours around it. Selecting a neighbour makes it the focus; selecting the focus is a normal node selection. A node is placed by the first role that matches, in the order `left`, `right`, `above`, `below`, then `around` for the rest. + +| Setting | Meaning | +|---|---| +| `above` | Fields through which the focus has a parent. Empty: every field | +| `below` | Fields through which the focus has a child. Empty: every field | +| `left`, `right` | Fields, in either direction. Empty: none | + +The focus is the host's to set (`focus` on `MapView`); by default it is the first hierarchy root, else the first node. + ## Parameters -Any setting marked parameterisable in the schemas (`orientation`, `dag`, `intermediate`, `nodes.style`, `nodes.fields`, `nodes.validation`, `nodes.validationSources`, `edges.show`, `edges.labels`, a landscape level's `type`, an axis's `field` and `direction`, `types`, `edgeFields`) takes either a fixed value or `{ $param: '' }`. +Any setting marked parameterisable in the schemas (`orientation`, `dag`, `intermediate`, `nodes.style`, `nodes.fields`, `nodes.validation`, `nodes.validationSources`, `edges.show`, `edges.labels`, a landscape level's `type`, an axis's `field` and `direction`, `types`, `edgeFields`, a compass's role fields) takes either a fixed value or `{ $param: '' }`. Each parameter is a JSON Schema with a `default` and an optional `title`. It can `$ref` a shared setting from `settings.json` (`orientation`, `nodeStyle`, `fieldList`, `validationLevel`, `validationSources`) or a layout's own definitions (e.g. `layouts/tree.json#/$defs/dag`), and narrow it. Relative refs resolve against the format's `latest` folder; full URLs work too. diff --git a/packages/map-views/map-views/knowledge-wiki-neighbourhood.json5 b/packages/map-views/map-views/knowledge-wiki-neighbourhood.json5 new file mode 100644 index 0000000..2a60307 --- /dev/null +++ b/packages/map-views/map-views/knowledge-wiki-neighbourhood.json5 @@ -0,0 +1,18 @@ +// A knowledge wiki page with the sources and concepts it connects to, around it. +{ + $schema: 'https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json', + $id: 'sctx-map-view://core/knowledge-wiki-neighbourhood', + title: 'Neighbourhood', + schema: 'sctx://core/knowledge_wiki', + parameters: { + labels: { type: 'boolean', title: 'Relationship labels', default: true }, + }, + regions: [ + { + id: 'main', + layout: { type: 'compass' }, + nodes: { style: 'card', fields: ['summary'] }, + edges: { show: true, labels: { $param: 'labels' } }, + }, + ], +} diff --git a/packages/map-views/src/core/compass.ts b/packages/map-views/src/core/compass.ts new file mode 100644 index 0000000..496e5ca --- /dev/null +++ b/packages/map-views/src/core/compass.ts @@ -0,0 +1,71 @@ +import type { SpaceGraph, SpaceNode } from 'structured-context/api'; +import type { CompassLayoutConfig } from './definition'; +import { childEdges, parentEdges } from './graph'; +import { assignLanes } from './lanes'; +import { occurrenceKey } from './occurrence'; + +export type CompassRole = 'left' | 'right' | 'above' | 'below' | 'around'; + +/** A neighbour of the focus, placed once however many fields join them. */ +export type CompassNeighbour = { key: string; node: SpaceNode }; + +/** An edge between the focus and a neighbour, in the edge's own direction. `lane` as in `XYLink`. */ +export type CompassLink = { from: string; to: string; field: string; lane: number }; + +export type Compass = { + /** `undefined` when the graph has no nodes. */ + focus: { key: string; node: SpaceNode } | undefined; + roles: Record; + links: CompassLink[]; +}; + +const ORDER: readonly CompassRole[] = ['left', 'right', 'above', 'below', 'around']; + +/** + * The focus and its neighbours placed by role. Without a usable `focusId`, the focus is the + * first hierarchy root, else the first node. + */ +export function buildCompass( + graph: SpaceGraph, + regionId: string, + layout: CompassLayoutConfig, + focusId?: SpaceNode['id'], +): Compass { + const roles: Compass['roles'] = { left: [], right: [], above: [], below: [], around: [] }; + const node = (focusId && graph.nodes.get(focusId)) || graph.hierarchyRoots[0] || graph.nodes.values().next().value; + if (!node) return { focus: undefined, roles, links: [] }; + const focus = { key: occurrenceKey(regionId, [node.id]), node }; + + const roleOf = (direction: 'parent' | 'child', field: string): CompassRole => { + const listed = (fields: readonly string[]) => fields.includes(field); + const open = (fields: readonly string[]) => fields.length === 0 || listed(fields); + if (listed(layout.left)) return 'left'; + if (listed(layout.right)) return 'right'; + if (direction === 'parent' && open(layout.above)) return 'above'; + if (direction === 'child' && open(layout.below)) return 'below'; + return 'around'; + }; + + const best = new Map(); + const links: CompassLink[] = []; + const neighbour = (id: SpaceNode['id'], direction: 'parent' | 'child', field: string) => { + if (id === node.id || !graph.nodes.has(id)) return; + const role = roleOf(direction, field); + const current = best.get(id); + if (!current || ORDER.indexOf(role) < ORDER.indexOf(current)) best.set(id, role); + const key = occurrenceKey(regionId, [node.id, id]); + links.push( + direction === 'parent' + ? { from: key, to: focus.key, field, lane: 0 } + : { from: focus.key, to: key, field, lane: 0 }, + ); + }; + for (const edge of parentEdges(graph, node.id)) neighbour(edge.parent, 'parent', edge.field); + for (const edge of childEdges(graph, node.id)) neighbour(edge.child, 'child', edge.field); + + for (const [id, role] of best) { + roles[role].push({ key: occurrenceKey(regionId, [node.id, id]), node: graph.nodes.get(id)! }); + } + assignLanes(links); + return { focus, roles, links }; +} diff --git a/packages/map-views/src/core/definition.ts b/packages/map-views/src/core/definition.ts index 70ca949..ba1eb59 100644 --- a/packages/map-views/src/core/definition.ts +++ b/packages/map-views/src/core/definition.ts @@ -2,6 +2,7 @@ import Ajv2020, { type AnySchemaObject, type ErrorObject } from 'ajv/dist/2020'; import type { FromSchema } from 'json-schema-to-ts'; import JSON5 from 'json5'; import { + type compassLayoutSchema, definitionSchema, type landscapeLayoutSchema, MAP_VIEW_SCHEMAS, @@ -19,6 +20,7 @@ type References = { typeof treeLayoutSchema, typeof landscapeLayoutSchema, typeof xyLayoutSchema, + typeof compassLayoutSchema, typeof definitionSchema, ]; // Grouping levels dispatch with if/then/else (see the landscape layout schema). @@ -47,6 +49,7 @@ export type LayoutConfig = Region['layout']; export type TreeLayoutConfig = Extract; export type LandscapeLayoutConfig = Extract; export type XYLayoutConfig = Extract; +export type CompassLayoutConfig = Extract; export type AxisConfig = XYLayoutConfig['x']; export type GroupLevel = LandscapeLayoutConfig['group'][number]; export type IntermediateDisplay = Extract['intermediate']; diff --git a/packages/map-views/src/core/format/compass-layout.ts b/packages/map-views/src/core/format/compass-layout.ts new file mode 100644 index 0000000..8d3277e --- /dev/null +++ b/packages/map-views/src/core/format/compass-layout.ts @@ -0,0 +1,24 @@ +import { parameterisable } from './param-ref'; +import { SCHEMA_URL } from './schema-url'; + +const roleFields = (description: string) => + parameterisable({ $ref: `${SCHEMA_URL}/settings.json#/$defs/fieldList` }, [], description); + +/** Settings of the compass layout: the neighbourhood of one node, placed by role. */ +export const compassLayoutSchema = { + $schema: 'https://json-schema.org/draft/2020-12/schema', + $id: `${SCHEMA_URL}/layouts/compass.json`, + title: 'Compass layout', + description: + 'The neighbourhood of one focus node, with related nodes placed around it by role. Each role lists the fields that put a node there. A node is placed by the first role that matches, in the order left, right, above, below, around.', + type: 'object', + required: ['type'], + additionalProperties: false, + properties: { + type: { const: 'compass' }, + above: roleFields('Fields through which the focus has a parent, shown above it. Empty: every field.'), + below: roleFields('Fields through which the focus has a child, shown below it. Empty: every field.'), + left: roleFields('Fields, in either direction, shown to the left. Empty: none.'), + right: roleFields('Fields, in either direction, shown to the right. Empty: none.'), + }, +} as const; diff --git a/packages/map-views/src/core/format/definition-schema.ts b/packages/map-views/src/core/format/definition-schema.ts index b7a7b34..cea8bb7 100644 --- a/packages/map-views/src/core/format/definition-schema.ts +++ b/packages/map-views/src/core/format/definition-schema.ts @@ -98,6 +98,7 @@ export const definitionSchema = { { $ref: `${SCHEMA_URL}/layouts/tree.json` }, { $ref: `${SCHEMA_URL}/layouts/landscape.json` }, { $ref: `${SCHEMA_URL}/layouts/xy.json` }, + { $ref: `${SCHEMA_URL}/layouts/compass.json` }, ], }, nodes: { diff --git a/packages/map-views/src/core/format/index.ts b/packages/map-views/src/core/format/index.ts index 5596020..cc6307d 100644 --- a/packages/map-views/src/core/format/index.ts +++ b/packages/map-views/src/core/format/index.ts @@ -1,3 +1,4 @@ +import { compassLayoutSchema } from './compass-layout'; import { definitionSchema } from './definition-schema'; import { landscapeLayoutSchema } from './landscape-layout'; import { settingsSchema } from './settings'; @@ -5,7 +6,14 @@ import { treeLayoutSchema } from './tree-layout'; import { xyLayoutSchema } from './xy-layout'; export { PARAM_REF } from './param-ref'; -export { definitionSchema, landscapeLayoutSchema, settingsSchema, treeLayoutSchema, xyLayoutSchema }; +export { + compassLayoutSchema, + definitionSchema, + landscapeLayoutSchema, + settingsSchema, + treeLayoutSchema, + xyLayoutSchema, +}; /** The bundled schemas describing the map view definition format. */ export const MAP_VIEW_SCHEMAS = [ @@ -14,4 +22,5 @@ export const MAP_VIEW_SCHEMAS = [ treeLayoutSchema, landscapeLayoutSchema, xyLayoutSchema, + compassLayoutSchema, ] as const; diff --git a/packages/map-views/src/core/lanes.ts b/packages/map-views/src/core/lanes.ts new file mode 100644 index 0000000..1c2512a --- /dev/null +++ b/packages/map-views/src/core/lanes.ts @@ -0,0 +1,13 @@ +/** Spread links joining the same pair of nodes (in either direction) into lanes around 0. */ +export function assignLanes(links: { from: string; to: string; lane: number }[]) { + const byPair = new Map(); + for (const link of links) { + const pair = [link.from, link.to].sort().join('\n'); + byPair.set(pair, [...(byPair.get(pair) ?? []), link]); + } + for (const group of byPair.values()) { + group.forEach((link, i) => { + link.lane = i - (group.length - 1) / 2; + }); + } +} diff --git a/packages/map-views/src/core/xy.ts b/packages/map-views/src/core/xy.ts index 413226c..32993e0 100644 --- a/packages/map-views/src/core/xy.ts +++ b/packages/map-views/src/core/xy.ts @@ -1,6 +1,7 @@ import type { SpaceGraph, SpaceNode } from 'structured-context/api'; import type { AxisConfig, XYLayoutConfig } from './definition'; import { edgesWithin, isHierarchyEdge } from './graph'; +import { assignLanes } from './lanes'; import { occurrenceKey } from './occurrence'; /** A plotted node. `x` and `y` run from 0 to 1 across the plot, left to right and bottom to top. */ @@ -95,17 +96,3 @@ function position(node: SpaceNode, axis: AxisConfig, [min, max]: readonly [numbe const t = (value - min) / (max - min); return axis.direction === 'descending' ? 1 - t : t; } - -/** Spread links joining the same pair of nodes (in either direction) into lanes around 0. */ -function assignLanes(links: XYLink[]) { - const byPair = new Map(); - for (const link of links) { - const pair = [link.from, link.to].sort().join('\n'); - byPair.set(pair, [...(byPair.get(pair) ?? []), link]); - } - for (const group of byPair.values()) { - group.forEach((link, i) => { - link.lane = i - (group.length - 1) / 2; - }); - } -} diff --git a/packages/map-views/src/layouts/CompassLayout.tsx b/packages/map-views/src/layouts/CompassLayout.tsx new file mode 100644 index 0000000..34ce984 --- /dev/null +++ b/packages/map-views/src/layouts/CompassLayout.tsx @@ -0,0 +1,83 @@ +import { useCallback, useMemo, useRef, useState } from 'react'; +import type { SpaceNode } from 'structured-context/api'; +import { buildCompass, type CompassNeighbour } from '../core/compass'; +import type { CompassLayoutConfig } from '../core/definition'; +import { EdgeOverlay } from './EdgeOverlay'; +import { NodeCard } from './NodeCard'; +import type { LayoutProps } from './TreeLayout'; + +type Props = LayoutProps & { + /** The focus node; the layout keeps its own once the reader picks another. */ + focus?: SpaceNode['id']; + onFocusChange?: (id: SpaceNode['id']) => void; +}; + +/** + * One node with its neighbours around it. Selecting a neighbour moves the focus to it; selecting + * the focus is a regular node selection. + */ +export function CompassLayout({ graph, region, instanceId, onNodeSelect, focus, onFocusChange }: Props) { + const [picked, setPicked] = useState<{ from: SpaceNode['id'] | undefined; id: SpaceNode['id'] }>(); + // A focus the host sets later wins over the reader's earlier pick. + const focusId = picked && picked.from === focus ? picked.id : focus; + const compass = useMemo( + () => buildCompass(graph, region.id, region.layout, focusId), + [graph, region.id, region.layout, focusId], + ); + const { labels, show } = region.edges; + const links = useMemo( + () => + show ? compass.links.map((link) => ({ ...link, id: link.field, label: labels ? link.field : undefined })) : [], + [compass, show, labels], + ); + + const [container, setContainer] = useState(null); + const elements = useRef(new Map()).current; + const register = useCallback( + (key: string) => (el: HTMLElement | null) => { + if (el) elements.set(key, el); + else elements.delete(key); + }, + [elements], + ); + + if (!compass.focus) return null; + const current = compass.focus.node; + const select = (node: SpaceNode) => { + if (node.id === current.id) return onNodeSelect?.(node); + setPicked({ from: focus, id: node.id }); + onFocusChange?.(node.id); + }; + const cell = (item: { key: string; node: SpaceNode }) => ( +
+ +
+ ); + const group = (items: CompassNeighbour[], className: string) => + items.length > 0 && ( +
{items.map(cell)}
+ ); + const { above, below, left, right, around } = compass.roles; + + return ( +
+ {group(above, '')} +
+ {group(left, 'mv:flex-col')} + {cell(compass.focus)} + {group(right, 'mv:flex-col')} +
+ {group(below, '')} + {group(around, 'mv:opacity-80')} + +
+ ); +} diff --git a/packages/map-views/src/layouts/MapView.tsx b/packages/map-views/src/layouts/MapView.tsx index 358cd85..c2dc34d 100644 --- a/packages/map-views/src/layouts/MapView.tsx +++ b/packages/map-views/src/layouts/MapView.tsx @@ -3,6 +3,7 @@ import type { SpaceGraph, SpaceNode } from 'structured-context/api'; import { type AnnotationIndex, filterAnnotations } from '../core/annotations'; import { type MapViewDefinition, type ParameterValues, type Region, resolveRegions } from '../core/definition'; import { AnnotationsContext } from './annotations-context'; +import { CompassLayout } from './CompassLayout'; import { LandscapeLayout } from './LandscapeLayout'; import { type LayoutProps, TreeLayout } from './TreeLayout'; import { XYLayout } from './XYLayout'; @@ -18,12 +19,15 @@ type Props = { */ annotations?: AnnotationIndex; onNodeSelect?: (node: SpaceNode) => void; + /** The node a compass layout centres on (see {@link CompassLayout}). */ + focus?: SpaceNode['id']; + onFocusChange?: (id: SpaceNode['id']) => void; }; const EMPTY: AnnotationIndex = new Map(); /** Renders a map view definition against a space. Sizes to its container and scrolls within it. */ -export function MapView({ definition, graph, values, annotations, onNodeSelect }: Props) { +export function MapView({ definition, graph, values, annotations, onNodeSelect, focus, onFocusChange }: Props) { const instanceId = useId(); const regions = useMemo(() => resolveRegions(definition, values), [definition, values]); // PROTOTYPE: only the first region is rendered. Arranging several regions is undesigned (#8). @@ -37,12 +41,18 @@ export function MapView({ definition, graph, values, annotations, onNodeSelect } return ( -
{layoutFor(region, props)}
+
+ {layoutFor(region, props, { focus, onFocusChange })} +
); } -function layoutFor(region: Region, props: Omit) { +function layoutFor( + region: Region, + props: Omit, + compass: Pick, +) { const { layout } = region; switch (layout.type) { case 'tree': @@ -51,5 +61,7 @@ function layoutFor(region: Region, props: Omit) { return ; case 'xy': return ; + case 'compass': + return ; } } diff --git a/packages/map-views/src/node/bundled-definitions.ts b/packages/map-views/src/node/bundled-definitions.ts index 58da761..276b19e 100644 --- a/packages/map-views/src/node/bundled-definitions.ts +++ b/packages/map-views/src/node/bundled-definitions.ts @@ -1,4 +1,5 @@ // Generated by scripts/generate-definitions.ts from map-views/*.json5. Do not edit. export const BUNDLED_DEFINITIONS: Record = { + "knowledge-wiki-neighbourhood.json5": "// A knowledge wiki page with the sources and concepts it connects to, around it.\n{\n $schema: 'https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json',\n $id: 'sctx-map-view://core/knowledge-wiki-neighbourhood',\n title: 'Neighbourhood',\n schema: 'sctx://core/knowledge_wiki',\n parameters: {\n labels: { type: 'boolean', title: 'Relationship labels', default: true },\n },\n regions: [\n {\n id: 'main',\n layout: { type: 'compass' },\n nodes: { style: 'card', fields: ['summary'] },\n edges: { show: true, labels: { $param: 'labels' } },\n },\n ],\n}\n", "strategy-tree.json5": "// Strategy stack as a tree: vision → mission → goals → opportunities → solutions → experiments.\n{\n $schema: 'https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json',\n $id: 'sctx-map-view://core/strategy-tree',\n title: 'Strategy tree',\n schema: 'sctx://core/strategy_general',\n parameters: {\n orientation: { $ref: 'settings.json#/$defs/orientation', default: 'vertical' },\n nodeStyle: { $ref: 'settings.json#/$defs/nodeStyle', default: 'card' },\n validation: { $ref: 'settings.json#/$defs/validationLevel', default: 'off' },\n cardFields: {\n title: 'Card fields',\n type: 'array',\n items: { enum: ['status', 'priority', 'summary'] },\n default: ['status'],\n },\n },\n regions: [\n {\n id: 'main',\n layout: { type: 'tree', orientation: { $param: 'orientation' } },\n nodes: { style: { $param: 'nodeStyle' }, fields: { $param: 'cardFields' }, validation: { $param: 'validation' } },\n edges: { show: true },\n },\n ],\n}\n", }; diff --git a/packages/map-views/tests/compass.test.ts b/packages/map-views/tests/compass.test.ts new file mode 100644 index 0000000..59ac6ed --- /dev/null +++ b/packages/map-views/tests/compass.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, test } from 'bun:test'; +import { buildSpaceGraph } from 'structured-context/api'; +import { buildCompass } from '../src/core/compass'; +import type { CompassLayoutConfig } from '../src/core/definition'; +import { makeParentRef, makeSpaceNode } from './builders'; + +const rel = (id: string, field: string) => makeParentRef(id, { kind: 'relationship', field }); +// A synthesis cites two sources and a concept; a second synthesis cites the first source. +const graph = buildSpaceGraph( + [ + makeSpaceNode('s1', 'source'), + makeSpaceNode('s2', 'source'), + makeSpaceNode('c1', 'concept'), + makeSpaceNode('x1', 'synthesis', {}, undefined, [ + rel('s1', 'sources'), + rel('s2', 'sources'), + rel('c1', 'concepts'), + ]), + makeSpaceNode('x2', 'synthesis', {}, undefined, [rel('s1', 'sources')]), + ], + undefined, +); +const layout = (overrides: Partial = {}): CompassLayoutConfig => ({ + type: 'compass', + above: [], + below: [], + left: [], + right: [], + ...overrides, +}); +const ids = (items: { node: { id: string } }[]) => items.map((i) => i.node.id); + +describe('compass', () => { + test('puts parents above and children below by default', () => { + const compass = buildCompass(graph, 'main', layout(), 's1' as never); + expect(ids(compass.roles.above)).toEqual([]); + expect(ids(compass.roles.below)).toEqual(['x1', 'x2']); + const x1 = buildCompass(graph, 'main', layout(), 'x1' as never); + expect(ids(x1.roles.above)).toEqual(['s1', 's2', 'c1']); + }); + + test('a listed field moves its neighbours to that role, before above and below', () => { + const compass = buildCompass(graph, 'main', layout({ left: ['concepts'] }), 'x1' as never); + expect(ids(compass.roles.left)).toEqual(['c1']); + expect(ids(compass.roles.above)).toEqual(['s1', 's2']); + }); + + test('edges outside the listed above and below fields go around', () => { + const compass = buildCompass(graph, 'main', layout({ above: ['sources'] }), 'x1' as never); + expect(ids(compass.roles.around)).toEqual(['c1']); + }); + + test('links keep the edge direction and carry the field', () => { + const { focus, links } = buildCompass(graph, 'main', layout(), 'x1' as never); + expect(links).toHaveLength(3); + expect(links.every((l) => l.to === focus!.key)).toBe(true); + expect(links.map((l) => l.field).sort()).toEqual(['concepts', 'sources', 'sources']); + }); + + test('an unknown focus falls back to the first node', () => { + expect(buildCompass(graph, 'main', layout(), 'nope' as never).focus?.node.id).toBe('s1' as never); + }); + + test('an empty graph has no focus', () => { + expect(buildCompass(buildSpaceGraph([], undefined), 'main', layout()).focus).toBeUndefined(); + }); +}); diff --git a/packages/map-views/tests/load-definitions.test.ts b/packages/map-views/tests/load-definitions.test.ts index b4f93e0..e1e7830 100644 --- a/packages/map-views/tests/load-definitions.test.ts +++ b/packages/map-views/tests/load-definitions.test.ts @@ -28,6 +28,7 @@ describe('loadMapViewDefinitions', () => { write('config/.sctx/plugins/sctx-declared/views/b.json5', definition('sctx-map-view://declared/b')); write('config/.sctx/map-views/c.json5', definition('sctx-map-view://c')); expect(ids(noSpaces)).toEqual([ + 'sctx-map-view://core/knowledge-wiki-neighbourhood', 'sctx-map-view://core/strategy-tree', 'sctx-map-view://conventional/a', 'sctx-map-view://declared/b', @@ -48,7 +49,12 @@ describe('loadMapViewDefinitions', () => { }, ], }; - expect(ids(config)).toEqual(['sctx-map-view://core/strategy-tree', 'sctx-map-view://named/a', 'sctx-map-view://b']); + expect(ids(config)).toEqual([ + 'sctx-map-view://core/knowledge-wiki-neighbourhood', + 'sctx-map-view://core/strategy-tree', + 'sctx-map-view://named/a', + 'sctx-map-view://b', + ]); }); test.each([ diff --git a/schemas/generated/latest/definition.json b/schemas/generated/latest/definition.json index 59f07a5..b46555c 100644 --- a/schemas/generated/latest/definition.json +++ b/schemas/generated/latest/definition.json @@ -122,6 +122,9 @@ }, { "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/layouts/xy.json" + }, + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/layouts/compass.json" } ] }, diff --git a/schemas/generated/latest/layouts/compass.json b/schemas/generated/latest/layouts/compass.json new file mode 100644 index 0000000..43e6af9 --- /dev/null +++ b/schemas/generated/latest/layouts/compass.json @@ -0,0 +1,64 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/layouts/compass.json", + "title": "Compass layout", + "description": "The neighbourhood of one focus node, with related nodes placed around it by role. Each role lists the fields that put a node there. A node is placed by the first role that matches, in the order left, right, above, below, around.", + "type": "object", + "required": [ + "type" + ], + "additionalProperties": false, + "properties": { + "type": { + "const": "compass" + }, + "above": { + "description": "Fields through which the focus has a parent, shown above it. Empty: every field.", + "default": [], + "anyOf": [ + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/settings.json#/$defs/fieldList" + }, + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json#/$defs/paramRef" + } + ] + }, + "below": { + "description": "Fields through which the focus has a child, shown below it. Empty: every field.", + "default": [], + "anyOf": [ + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/settings.json#/$defs/fieldList" + }, + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json#/$defs/paramRef" + } + ] + }, + "left": { + "description": "Fields, in either direction, shown to the left. Empty: none.", + "default": [], + "anyOf": [ + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/settings.json#/$defs/fieldList" + }, + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json#/$defs/paramRef" + } + ] + }, + "right": { + "description": "Fields, in either direction, shown to the right. Empty: none.", + "default": [], + "anyOf": [ + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/settings.json#/$defs/fieldList" + }, + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json#/$defs/paramRef" + } + ] + } + } +} From 121bd026110361dbf3cd1bcc96e4bcd39ef636a3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 14:17:29 +0000 Subject: [PATCH 03/15] feat: graph layout and map views that suit any schema Adds the graph layout (d3-force) and makes a definition's schema optional; without one it applies to every schema. Bundles graph, neighbourhood and tree views for any schema. Renames compass to neighbourhood. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_019XphpcKhuNyHcNArHFELR4 --- AGENTS.md | 2 +- bun.lock | 16 +++- docs/api.md | 2 +- docs/architecture.md | 7 +- docs/concepts.md | 5 +- docs/definitions.md | 16 +++- packages/map-views/map-views/graph.json5 | 19 +++++ ...eighbourhood.json5 => neighbourhood.json5} | 10 +-- packages/map-views/map-views/tree.json5 | 19 +++++ packages/map-views/package.json | 2 + packages/map-views/src/core/definition.ts | 19 +++-- packages/map-views/src/core/force.ts | 76 +++++++++++++++++++ .../src/core/format/definition-schema.ts | 8 +- .../map-views/src/core/format/graph-layout.ts | 21 +++++ packages/map-views/src/core/format/index.ts | 9 ++- ...pass-layout.ts => neighbourhood-layout.ts} | 10 +-- .../src/core/{compass.ts => neighbourhood.ts} | 30 ++++---- .../map-views/src/layouts/GraphLayout.tsx | 62 +++++++++++++++ packages/map-views/src/layouts/MapView.tsx | 13 ++-- ...passLayout.tsx => NeighbourhoodLayout.tsx} | 28 +++---- packages/map-views/src/layouts/TreeLayout.tsx | 2 + .../map-views/src/node/bundled-definitions.ts | 4 +- packages/map-views/tests/definition.test.ts | 16 +++- packages/map-views/tests/force.test.ts | 35 +++++++++ .../map-views/tests/load-definitions.test.ts | 16 ++-- ...{compass.test.ts => neighbourhood.test.ts} | 34 ++++----- packages/map-views/tests/snapshot.test.ts | 2 +- packages/map-views/vite.config.ts | 1 + packages/sctx-map-views/tests/render.test.ts | 5 +- schemas/generated/latest/definition.json | 8 +- schemas/generated/latest/layouts/graph.json | 28 +++++++ .../{compass.json => neighbourhood.json} | 6 +- 32 files changed, 426 insertions(+), 105 deletions(-) create mode 100644 packages/map-views/map-views/graph.json5 rename packages/map-views/map-views/{knowledge-wiki-neighbourhood.json5 => neighbourhood.json5} (56%) create mode 100644 packages/map-views/map-views/tree.json5 create mode 100644 packages/map-views/src/core/force.ts create mode 100644 packages/map-views/src/core/format/graph-layout.ts rename packages/map-views/src/core/format/{compass-layout.ts => neighbourhood-layout.ts} (80%) rename packages/map-views/src/core/{compass.ts => neighbourhood.ts} (74%) create mode 100644 packages/map-views/src/layouts/GraphLayout.tsx rename packages/map-views/src/layouts/{CompassLayout.tsx => NeighbourhoodLayout.tsx} (74%) create mode 100644 packages/map-views/tests/force.test.ts rename packages/map-views/tests/{compass.test.ts => neighbourhood.test.ts} (55%) create mode 100644 schemas/generated/latest/layouts/graph.json rename schemas/generated/latest/layouts/{compass.json => neighbourhood.json} (94%) diff --git a/AGENTS.md b/AGENTS.md index 375917c..6e4b136 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,7 @@ Declarative map views of structured-context spaces: the definition format, the r - `packages/map-views/src/node`: Node-only definition discovery (`loadMapViewDefinitions`), shipped as its own entry point (`structured-context-map-views/node`). Core and layouts must not import it. - `packages/sctx-map-views`: the structured-context render plugin (format `map-views.html`), bundling the library's page template and `/html` entry. It reads everything through the render callbacks and has no structured-context dependency at runtime: its bundle imports nothing from it, and `test:package` checks that. - `apps/navigator`: the standalone host (private package: a Vite app plus dev-server middleware calling the structured-context API). It consumes the library like any other host. -- `packages/map-views/map-views/*.json5`: definitions bundled with the library, only for structured-context's bundled schemas (`$id` `sctx-map-view://core/`). `bun run generate:definitions` embeds them as `src/node/bundled-definitions.ts`; a test fails if that is stale. Plugins ship their own; personal ones go in the config root's `.sctx/map-views/` (structured-context's `resourceDir`). +- `packages/map-views/map-views/*.json5`: definitions bundled with the library (`$id` `sctx-map-view://core/`): ones that suit any schema (no `schema`), and ones for structured-context's bundled schemas. `bun run generate:definitions` embeds them as `src/node/bundled-definitions.ts`; a test fails if that is stale. Plugins ship their own; personal ones go in the config root's `.sctx/map-views/` (structured-context's `resourceDir`). - `packages/map-views/src/core/format/*.ts`: the definition format's JSON Schemas (`as const`), the source of truth. Types derive from them (`FromSchema`); `bun run generate:schemas` writes `schemas/generated/latest/` at the repo root (so the published URLs stay stable), and a test fails if those are stale; `--release` (run when cutting a release) also freezes `schemas/generated//` if the format changed. `$id`s are the published https URLs (`schema-url.ts`). Use absolute `${SCHEMA_URL}/…` refs: `FromSchema` doesn't resolve relative refs inside referenced schemas. - `samples/launch-playbook/`: a public sample space. `packages/map-views/tests/fixtures/launch-playbook.json` is captured from it with `bun run capture-fixtures launch-playbook=../../samples/launch-playbook/.sctx.json` in `packages/map-views`. diff --git a/bun.lock b/bun.lock index c247963..c4a4305 100644 --- a/bun.lock +++ b/bun.lock @@ -32,18 +32,20 @@ }, "packages/map-views": { "name": "structured-context-map-views", - "version": "0.6.1", + "version": "0.6.2", "bin": { "structured-context-map-views": "dist/cli.js", }, "dependencies": { "ajv": "^8.20.0", "commander": "^15.0.0", + "d3-force": "^3.0.1", "json-schema-to-ts": "^3.1.1", "json5": "^2.2.3", }, "devDependencies": { "@tailwindcss/cli": "^4.3.3", + "@types/d3-force": "^3.0.10", "@types/node": "^22.20.5", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", @@ -62,7 +64,7 @@ }, "packages/sctx-map-views": { "name": "sctx-map-views", - "version": "0.6.1", + "version": "0.6.2", "devDependencies": { "structured-context": "^0.24.0", "structured-context-map-views": "workspace:*", @@ -202,6 +204,8 @@ "@types/bun": ["@types/bun@1.4.2", "", { "dependencies": { "bun-types": "1.4.2" } }, "sha512-GimotNn7+ZV0uVArItBbriZsR1oNf0+WTzPkdcFrzShI7k2norL0uzEaJT8T33dWr7O/c9ZDuAFQrctKCi72oQ=="], + "@types/d3-force": ["@types/d3-force@3.0.10", "", {}, "sha512-ZYeSaCF3p73RdOKcjj+swRlZfnYpK1EbaDiYICEEp5Q6sUiqFaFQ9qgoshp5CzIyyb/yD09kD9o2zEltCexlgw=="], + "@types/debug": ["@types/debug@4.1.13", "", { "dependencies": { "@types/ms": "*" } }, "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw=="], "@types/mdast": ["@types/mdast@4.0.4", "", { "dependencies": { "@types/unist": "*" } }, "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA=="], @@ -278,6 +282,14 @@ "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + "d3-dispatch": ["d3-dispatch@3.0.2", "", {}, "sha512-sAzH4Y4nsLo8eSqw5jKiZt+LU2wZmL/qS+OkxQGjhwazB/D7TY34R/QK1eshfGr7cZEKymKZ/Haem7m+lu98Sg=="], + + "d3-force": ["d3-force@3.0.1", "", { "dependencies": { "d3-dispatch": "1 - 3", "d3-quadtree": "1 - 3", "d3-timer": "1 - 3" } }, "sha512-kAaaHLFebBYwgi5cYBXAI8vKrQFMCD2MEswj2QuPKKbdU1wYLc8WXtS7O8F/b6POCIe3gJjY6hkDstHi1yMETQ=="], + + "d3-quadtree": ["d3-quadtree@3.0.2", "", {}, "sha512-9Lu9mqJKRbIk0d6mKDjpvPURaPdwHVK5CYbcdd0/4vBgz4ldz/7TIOse3kNERsByGNfld58KEco507AztJWyTQ=="], + + "d3-timer": ["d3-timer@3.0.2", "", {}, "sha512-1Il1aliroVSErrv5aulRBxAY+7+DnaoLIWGd1C6SsBTWDeobWiP/V69vwb8vT6abR1kKwaNe1196pmaQ1fK90A=="], + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], "decode-named-character-reference": ["decode-named-character-reference@1.3.0", "", { "dependencies": { "character-entities": "^2.0.0" } }, "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q=="], diff --git a/docs/api.md b/docs/api.md index 0bdd8c1..9d33d96 100644 --- a/docs/api.md +++ b/docs/api.md @@ -19,7 +19,7 @@ import 'structured-context-map-views/styles.css'; open(node)} /> ``` -`graph` is a structured-context `SpaceGraph` (see [Data](#data)); `values` and the controls' `onChange` belong to the host. Pass `annotations` to show validation results (see [Validation results](#validation-results)). `focus` and `onFocusChange` set and follow the node a [compass](definitions.md#compass) layout centres on. +`graph` is a structured-context `SpaceGraph` (see [Data](#data)); `values` and the controls' `onChange` belong to the host. Pass `annotations` to show validation results (see [Validation results](#validation-results)). `focus` and `onFocusChange` set and follow the node a [neighbourhood](definitions.md#neighbourhood) layout centres on. A host that lays out the controls itself builds them from `useParameterControls` and `ParameterInput`. diff --git a/docs/architecture.md b/docs/architecture.md index a15b529..962e66a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -6,7 +6,7 @@ A space graph and a definition go in; a DOM layout with an SVG overlay comes out flowchart LR space[structured-context space] -->|host assembles| graph[SpaceGraph] def[definition .json5] -->|parseMapViewDefinition| mvd[MapViewDefinition] - graph --> proj[projection
tree · landscape · xy · compass] + graph --> proj[projection
tree · landscape · xy · neighbourhood · graph] mvd --> proj proj --> dom[layout component
DOM + SVG overlay] ``` @@ -15,7 +15,7 @@ flowchart LR | Module | Holds | May import | |---|---|---| -| `packages/map-views/src/core` | Definition parsing and validation, parameter resolution, graph helpers, and the projections (`buildTree`, `buildLandscape`, `buildXYPlot`, `buildCompass`) | Types from structured-context only. No React, DOM or Node | +| `packages/map-views/src/core` | Definition parsing and validation, parameter resolution, graph helpers, and the projections (`buildTree`, `buildLandscape`, `buildXYPlot`, `buildNeighbourhood`, `buildForceGraph`) | Types from structured-context only. No React, DOM or Node | | `packages/map-views/src/layouts` | `MapView`, the layout components, `NodeCard`, `EdgeOverlay`, the parameter controls (`useParameterControls`, the typed inputs and the default `ParameterControls` layout), styles | core, React | | `packages/map-views/src/viewer` | `Viewer`, the page-filling UI that hosts share. What is specific to a host comes in as an option | core, layouts, React, `structured-context/browser` | | `packages/map-views/src/node` | `loadMapViewDefinitions`: finding definitions in the library (embedded at build time from `packages/map-views/map-views/`), plugins and config folders; `exportSnapshot` and the `export` bin, which snapshot a space for browser-only hosts; `fillPage`, which writes snapshots into the self-contained page. `fillPage` and `readDefinitionFolders` are also the `/html` entry, which imports nothing from structured-context's API | core, Node, structured-context | @@ -37,7 +37,8 @@ Each layout has a pure projection in core that turns the graph and the region's - **Tree**: walks the hierarchy from the root type. A node with several parents is repeated (subtree once) or placed once with cross-links. Cycles end in a repeat. - **Landscape**: walks the grouping levels, joining node levels by edges in either direction, through `via` chains or by field values. - **XY**: normalises two numeric fields to percentages within each axis's domain and lists the nodes it can't place. -- **Compass**: places the focus's neighbours by the role of the field joining them. +- **Neighbourhood**: places the focus's neighbours by the role of the field joining them. +- **Graph**: positions every node with a force simulation (`d3-force`), seeded so the same graph gives the same positions. Occurrence keys are paths (region, ancestors, node), so a node appearing several times gets distinct keys. diff --git a/docs/concepts.md b/docs/concepts.md index 1565d19..cc91113 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -21,7 +21,8 @@ The arrangement a region uses, chosen from a fixed catalogue: - **tree**: a tree over the schema's hierarchy. - **landscape**: nested containers following an authored grouping. - **xy**: nodes positioned by two numeric fields. -- **compass**: one node with its neighbours placed around it by role. +- **neighbourhood**: one node with its neighbours placed around it by role. +- **graph**: every node and edge as a network. Each layout carries its own opinions (spacing, card sizes, colours). Definitions choose and configure a layout; they don't compose one. @@ -38,7 +39,7 @@ The two ways a tree shows a node with several parents: ## Focus -The node a compass layout centres on. Hosts can set it; otherwise the reader's picks move it. +The node a neighbourhood layout centres on. Hosts can set it; otherwise the reader's picks move it. ## Grouping level diff --git a/docs/definitions.md b/docs/definitions.md index 1b295c5..07578f7 100644 --- a/docs/definitions.md +++ b/docs/definitions.md @@ -30,7 +30,7 @@ A map view definition is a JSON5 file. Its format is a set of JSON Schemas publi | Field | Required | Meaning | |---|---|---| | `$id` | yes | Identifier, namespaced by where the definition is found (below) | -| `schema` | yes | `$id` of the structured-context schema whose spaces this map view applies to | +| `schema` | | `$id` of the structured-context schema whose spaces this map view applies to. Omitted: every schema | | `regions` | yes | Parts of the map view (at least one; only the first is rendered) | | `title` | | Display name. Defaults to the last segment of the `$id` | | `description` | | | @@ -92,7 +92,15 @@ Nodes positioned on two axes by numeric fields. Plotted nodes without a usable v An axis has a `field` (required), a `domain` (`[min, max]`, or `'data'` for the smallest and largest plotted values; default `'data'`), a `direction` (`ascending`, the default, or `descending`) and a `label` (defaults to the field name). -### compass +### graph + +Every node and edge as a network: connected nodes sit close together. It needs no hierarchy, so it suits any schema. + +| Setting | Values | Default | +|---|---|---| +| `edgeFields` | Fields whose edges are drawn and pull nodes together | all edges | + +### neighbourhood One focus node with its neighbours around it. Selecting a neighbour makes it the focus; selecting the focus is a normal node selection. A node is placed by the first role that matches, in the order `left`, `right`, `above`, `below`, then `around` for the rest. @@ -106,7 +114,7 @@ The focus is the host's to set (`focus` on `MapView`); by default it is the firs ## Parameters -Any setting marked parameterisable in the schemas (`orientation`, `dag`, `intermediate`, `nodes.style`, `nodes.fields`, `nodes.validation`, `nodes.validationSources`, `edges.show`, `edges.labels`, a landscape level's `type`, an axis's `field` and `direction`, `types`, `edgeFields`, a compass's role fields) takes either a fixed value or `{ $param: '' }`. +Any setting marked parameterisable in the schemas (`orientation`, `dag`, `intermediate`, `nodes.style`, `nodes.fields`, `nodes.validation`, `nodes.validationSources`, `edges.show`, `edges.labels`, a landscape level's `type`, an axis's `field` and `direction`, `types`, `edgeFields`, a neighbourhood's role fields) takes either a fixed value or `{ $param: '' }`. Each parameter is a JSON Schema with a `default` and an optional `title`. It can `$ref` a shared setting from `settings.json` (`orientation`, `nodeStyle`, `fieldList`, `validationLevel`, `validationSources`) or a layout's own definitions (e.g. `layouts/tree.json#/$defs/dag`), and narrow it. Relative refs resolve against the format's `latest` folder; full URLs work too. @@ -135,7 +143,7 @@ Definitions are found the way structured-context finds plugin schemas, and each | Where | `$id` | |---|---| -| Bundled with this library (`map-views/`), for structured-context's bundled schemas | `sctx-map-view://core/` | +| Bundled with this library (`map-views/`): views that suit any schema, and views for structured-context's bundled schemas | `sctx-map-view://core/` | | A plugin: the folder named by `"sctx": { "map-views": "…" }` in its `package.json`, else its `map-views/` folder | `sctx-map-view:///` (the plugin's name without `sctx-`) | | The `.sctx/map-views/` folder of a structured-context config root, or `map-views/` beside the global config ([resources folder](https://github.com/mindsocket/structured-context/blob/main/docs/config.md#resources-folder)), including configs pulled in by `includeSpacesFrom` | `sctx-map-view://` | diff --git a/packages/map-views/map-views/graph.json5 b/packages/map-views/map-views/graph.json5 new file mode 100644 index 0000000..03c1b7a --- /dev/null +++ b/packages/map-views/map-views/graph.json5 @@ -0,0 +1,19 @@ +// Every node and edge as a network. Any schema. +{ + $schema: 'https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json', + $id: 'sctx-map-view://core/graph', + title: 'Graph', + parameters: { + nodeStyle: { $ref: 'settings.json#/$defs/nodeStyle', default: 'shape' }, + labels: { type: 'boolean', title: 'Relationship labels', default: false }, + validation: { $ref: 'settings.json#/$defs/validationLevel', default: 'off' }, + }, + regions: [ + { + id: 'main', + layout: { type: 'graph' }, + nodes: { style: { $param: 'nodeStyle' }, validation: { $param: 'validation' } }, + edges: { show: true, labels: { $param: 'labels' } }, + }, + ], +} diff --git a/packages/map-views/map-views/knowledge-wiki-neighbourhood.json5 b/packages/map-views/map-views/neighbourhood.json5 similarity index 56% rename from packages/map-views/map-views/knowledge-wiki-neighbourhood.json5 rename to packages/map-views/map-views/neighbourhood.json5 index 2a60307..fe138fd 100644 --- a/packages/map-views/map-views/knowledge-wiki-neighbourhood.json5 +++ b/packages/map-views/map-views/neighbourhood.json5 @@ -1,17 +1,17 @@ -// A knowledge wiki page with the sources and concepts it connects to, around it. +// One node with the nodes it is related to around it. Any schema. { $schema: 'https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json', - $id: 'sctx-map-view://core/knowledge-wiki-neighbourhood', + $id: 'sctx-map-view://core/neighbourhood', title: 'Neighbourhood', - schema: 'sctx://core/knowledge_wiki', parameters: { labels: { type: 'boolean', title: 'Relationship labels', default: true }, + validation: { $ref: 'settings.json#/$defs/validationLevel', default: 'off' }, }, regions: [ { id: 'main', - layout: { type: 'compass' }, - nodes: { style: 'card', fields: ['summary'] }, + layout: { type: 'neighbourhood' }, + nodes: { validation: { $param: 'validation' } }, edges: { show: true, labels: { $param: 'labels' } }, }, ], diff --git a/packages/map-views/map-views/tree.json5 b/packages/map-views/map-views/tree.json5 new file mode 100644 index 0000000..706e2b0 --- /dev/null +++ b/packages/map-views/map-views/tree.json5 @@ -0,0 +1,19 @@ +// The hierarchy as a tree. Any schema that has one. +{ + $schema: 'https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json', + $id: 'sctx-map-view://core/tree', + title: 'Tree', + parameters: { + orientation: { $ref: 'settings.json#/$defs/orientation', default: 'vertical' }, + nodeStyle: { $ref: 'settings.json#/$defs/nodeStyle', default: 'card' }, + validation: { $ref: 'settings.json#/$defs/validationLevel', default: 'off' }, + }, + regions: [ + { + id: 'main', + layout: { type: 'tree', orientation: { $param: 'orientation' } }, + nodes: { style: { $param: 'nodeStyle' }, validation: { $param: 'validation' } }, + edges: { show: true }, + }, + ], +} diff --git a/packages/map-views/package.json b/packages/map-views/package.json index 086b372..d93c82b 100644 --- a/packages/map-views/package.json +++ b/packages/map-views/package.json @@ -66,11 +66,13 @@ "dependencies": { "ajv": "^8.20.0", "commander": "^15.0.0", + "d3-force": "^3.0.1", "json-schema-to-ts": "^3.1.1", "json5": "^2.2.3" }, "devDependencies": { "@tailwindcss/cli": "^4.3.3", + "@types/d3-force": "^3.0.10", "@types/node": "^22.20.5", "@types/react": "^19.3.0", "@types/react-dom": "^19.3.0", diff --git a/packages/map-views/src/core/definition.ts b/packages/map-views/src/core/definition.ts index ba1eb59..ea21db0 100644 --- a/packages/map-views/src/core/definition.ts +++ b/packages/map-views/src/core/definition.ts @@ -2,10 +2,11 @@ import Ajv2020, { type AnySchemaObject, type ErrorObject } from 'ajv/dist/2020'; import type { FromSchema } from 'json-schema-to-ts'; import JSON5 from 'json5'; import { - type compassLayoutSchema, definitionSchema, + type graphLayoutSchema, type landscapeLayoutSchema, MAP_VIEW_SCHEMAS, + type neighbourhoodLayoutSchema, type settingsSchema, type treeLayoutSchema, type xyLayoutSchema, @@ -20,7 +21,8 @@ type References = { typeof treeLayoutSchema, typeof landscapeLayoutSchema, typeof xyLayoutSchema, - typeof compassLayoutSchema, + typeof neighbourhoodLayoutSchema, + typeof graphLayoutSchema, typeof definitionSchema, ]; // Grouping levels dispatch with if/then/else (see the landscape layout schema). @@ -49,7 +51,8 @@ export type LayoutConfig = Region['layout']; export type TreeLayoutConfig = Extract; export type LandscapeLayoutConfig = Extract; export type XYLayoutConfig = Extract; -export type CompassLayoutConfig = Extract; +export type NeighbourhoodLayoutConfig = Extract; +export type GraphLayoutConfig = Extract; export type AxisConfig = XYLayoutConfig['x']; export type GroupLevel = LandscapeLayoutConfig['group'][number]; export type IntermediateDisplay = Extract['intermediate']; @@ -69,8 +72,8 @@ export type MapViewDefinition = { id: string; title: string; description?: string; - /** `$id` of the schema whose spaces this map view applies to. */ - schema: string; + /** `$id` of the schema whose spaces this map view applies to; unset: every schema. */ + schema?: string; parameters: Parameter[]; /** The definition as authored. */ source: AuthoredDefinition; @@ -173,7 +176,7 @@ export function parseMapViewDefinition(name: string, text: string): MapViewDefin id: source.$id, title: source.title ?? source.$id.slice(source.$id.lastIndexOf('/') + 1), ...(source.description !== undefined && { description: source.description }), - schema: source.schema, + ...(source.schema !== undefined && { schema: source.schema }), parameters, source, }; @@ -228,12 +231,12 @@ export function viewValidationLevel( return resolveRegions(definition, values)[0]?.nodes.validation ?? 'off'; } -/** Map view definitions that apply to a space with the given schema. */ +/** Map view definitions that apply to a space with the given schema, including those for every schema. */ export function mapViewsForSchema( definitions: readonly MapViewDefinition[], schemaId: string | undefined, ): MapViewDefinition[] { - return schemaId === undefined ? [] : definitions.filter((d) => d.schema === schemaId); + return definitions.filter((d) => d.schema === undefined || d.schema === schemaId); } /** Resolve `$ref`s relative to the format schemas, so parameters can write `settings.json#/$defs/orientation`. */ diff --git a/packages/map-views/src/core/force.ts b/packages/map-views/src/core/force.ts new file mode 100644 index 0000000..34bfd71 --- /dev/null +++ b/packages/map-views/src/core/force.ts @@ -0,0 +1,76 @@ +import { forceCollide, forceLink, forceManyBody, forceSimulation, forceX, forceY } from 'd3-force'; +import type { SpaceGraph, SpaceNode } from 'structured-context/api'; +import type { GraphLayoutConfig } from './definition'; +import { edgesWithin } from './graph'; +import { assignLanes } from './lanes'; +import { occurrenceKey } from './occurrence'; + +/** A positioned node; `x` and `y` are pixels from the top left of the plot. */ +export type ForcePoint = { key: string; node: SpaceNode; x: number; y: number }; + +/** An edge between positioned nodes. `lane` as in `XYLink`. */ +export type ForceLink = { from: string; to: string; field: string; lane: number }; + +export type ForceGraph = { points: ForcePoint[]; links: ForceLink[]; width: number; height: number }; + +const TICKS = 300; +const PADDING = 24; + +/** + * Position every node with a force simulation: edges pull their ends together, nodes push apart + * and keep `nodeSize` pixels of room. The result is the same for the same graph. + */ +export function buildForceGraph( + graph: SpaceGraph, + regionId: string, + layout: GraphLayoutConfig, + nodeSize: number, +): ForceGraph { + const nodes = [...graph.nodes.values()].map((node) => ({ node, x: 0, y: 0 })); + const byId = new Map(nodes.map((n) => [n.node.id, n])); + const fields = new Set(layout.edgeFields); + const edges = edgesWithin(graph).filter((e) => e.parent !== e.child && (fields.size === 0 || fields.has(e.field))); + + // A fixed random source keeps positions stable between renders. + let seed = 1; + const random = () => { + seed = (seed * 1664525 + 1013904223) % 4294967296; + return seed / 4294967296; + }; + + const simulation = forceSimulation(nodes) + .randomSource(random) + .force( + 'link', + forceLink<(typeof nodes)[number], { source: string; target: string }>( + edges.map((e) => ({ source: e.parent, target: e.child })), + ) + .id((n) => n.node.id) + .distance(nodeSize * 1.5), + ) + .force('charge', forceManyBody().strength(-nodeSize * 2)) + .force('collide', forceCollide(nodeSize / 2)) + // Keeps unconnected nodes and separate clusters from drifting apart. + .force('x', forceX().strength(0.05)) + .force('y', forceY().strength(0.05)) + .stop(); + simulation.tick(TICKS); + + const minX = Math.min(...nodes.map((n) => n.x), 0); + const minY = Math.min(...nodes.map((n) => n.y), 0); + const maxX = Math.max(...nodes.map((n) => n.x), 0); + const maxY = Math.max(...nodes.map((n) => n.y), 0); + const key = (id: SpaceNode['id']) => occurrenceKey(regionId, [id]); + + const links = edges + .filter((e) => byId.has(e.parent) && byId.has(e.child)) + .map((e) => ({ from: key(e.parent), to: key(e.child), field: e.field, lane: 0 })); + assignLanes(links); + + return { + points: nodes.map((n) => ({ key: key(n.node.id), node: n.node, x: n.x - minX + PADDING, y: n.y - minY + PADDING })), + links, + width: maxX - minX + 2 * PADDING, + height: maxY - minY + 2 * PADDING, + }; +} diff --git a/packages/map-views/src/core/format/definition-schema.ts b/packages/map-views/src/core/format/definition-schema.ts index cea8bb7..1fac012 100644 --- a/packages/map-views/src/core/format/definition-schema.ts +++ b/packages/map-views/src/core/format/definition-schema.ts @@ -15,7 +15,7 @@ export const definitionSchema = { description: 'Declares how spaces of one schema are projected into a map view: shared parameters, and the regions the map view is composed of.', type: 'object', - required: ['$id', 'schema', 'regions'], + required: ['$id', 'regions'], additionalProperties: false, properties: { $schema: { type: 'string' }, @@ -30,7 +30,8 @@ export const definitionSchema = { schema: { type: 'string', minLength: 1, - description: '`$id` of the structured-context schema whose spaces this map view applies to.', + description: + '`$id` of the structured-context schema whose spaces this map view applies to. Omitted: it applies to every schema.', }, parameters: { type: 'object', @@ -98,7 +99,8 @@ export const definitionSchema = { { $ref: `${SCHEMA_URL}/layouts/tree.json` }, { $ref: `${SCHEMA_URL}/layouts/landscape.json` }, { $ref: `${SCHEMA_URL}/layouts/xy.json` }, - { $ref: `${SCHEMA_URL}/layouts/compass.json` }, + { $ref: `${SCHEMA_URL}/layouts/neighbourhood.json` }, + { $ref: `${SCHEMA_URL}/layouts/graph.json` }, ], }, nodes: { diff --git a/packages/map-views/src/core/format/graph-layout.ts b/packages/map-views/src/core/format/graph-layout.ts new file mode 100644 index 0000000..0bc114f --- /dev/null +++ b/packages/map-views/src/core/format/graph-layout.ts @@ -0,0 +1,21 @@ +import { parameterisable } from './param-ref'; +import { SCHEMA_URL } from './schema-url'; + +/** Settings of the graph layout: every node and edge, positioned by a force simulation. */ +export const graphLayoutSchema = { + $schema: 'https://json-schema.org/draft/2020-12/schema', + $id: `${SCHEMA_URL}/layouts/graph.json`, + title: 'Graph layout', + description: 'Nodes and edges as a network: connected nodes sit close together. Works with any schema.', + type: 'object', + required: ['type'], + additionalProperties: false, + properties: { + type: { const: 'graph' }, + edgeFields: parameterisable( + { $ref: `${SCHEMA_URL}/settings.json#/$defs/fieldList` }, + [], + 'Fields whose edges are drawn and pull nodes together. Empty: all edges.', + ), + }, +} as const; diff --git a/packages/map-views/src/core/format/index.ts b/packages/map-views/src/core/format/index.ts index cc6307d..ebf07a3 100644 --- a/packages/map-views/src/core/format/index.ts +++ b/packages/map-views/src/core/format/index.ts @@ -1,15 +1,17 @@ -import { compassLayoutSchema } from './compass-layout'; import { definitionSchema } from './definition-schema'; +import { graphLayoutSchema } from './graph-layout'; import { landscapeLayoutSchema } from './landscape-layout'; +import { neighbourhoodLayoutSchema } from './neighbourhood-layout'; import { settingsSchema } from './settings'; import { treeLayoutSchema } from './tree-layout'; import { xyLayoutSchema } from './xy-layout'; export { PARAM_REF } from './param-ref'; export { - compassLayoutSchema, definitionSchema, + graphLayoutSchema, landscapeLayoutSchema, + neighbourhoodLayoutSchema, settingsSchema, treeLayoutSchema, xyLayoutSchema, @@ -22,5 +24,6 @@ export const MAP_VIEW_SCHEMAS = [ treeLayoutSchema, landscapeLayoutSchema, xyLayoutSchema, - compassLayoutSchema, + neighbourhoodLayoutSchema, + graphLayoutSchema, ] as const; diff --git a/packages/map-views/src/core/format/compass-layout.ts b/packages/map-views/src/core/format/neighbourhood-layout.ts similarity index 80% rename from packages/map-views/src/core/format/compass-layout.ts rename to packages/map-views/src/core/format/neighbourhood-layout.ts index 8d3277e..9958c84 100644 --- a/packages/map-views/src/core/format/compass-layout.ts +++ b/packages/map-views/src/core/format/neighbourhood-layout.ts @@ -4,18 +4,18 @@ import { SCHEMA_URL } from './schema-url'; const roleFields = (description: string) => parameterisable({ $ref: `${SCHEMA_URL}/settings.json#/$defs/fieldList` }, [], description); -/** Settings of the compass layout: the neighbourhood of one node, placed by role. */ -export const compassLayoutSchema = { +/** Settings of the neighbourhood layout: the neighbourhood of one node, placed by role. */ +export const neighbourhoodLayoutSchema = { $schema: 'https://json-schema.org/draft/2020-12/schema', - $id: `${SCHEMA_URL}/layouts/compass.json`, - title: 'Compass layout', + $id: `${SCHEMA_URL}/layouts/neighbourhood.json`, + title: 'Neighbourhood layout', description: 'The neighbourhood of one focus node, with related nodes placed around it by role. Each role lists the fields that put a node there. A node is placed by the first role that matches, in the order left, right, above, below, around.', type: 'object', required: ['type'], additionalProperties: false, properties: { - type: { const: 'compass' }, + type: { const: 'neighbourhood' }, above: roleFields('Fields through which the focus has a parent, shown above it. Empty: every field.'), below: roleFields('Fields through which the focus has a child, shown below it. Empty: every field.'), left: roleFields('Fields, in either direction, shown to the left. Empty: none.'), diff --git a/packages/map-views/src/core/compass.ts b/packages/map-views/src/core/neighbourhood.ts similarity index 74% rename from packages/map-views/src/core/compass.ts rename to packages/map-views/src/core/neighbourhood.ts index 496e5ca..bc6d55d 100644 --- a/packages/map-views/src/core/compass.ts +++ b/packages/map-views/src/core/neighbourhood.ts @@ -1,42 +1,42 @@ import type { SpaceGraph, SpaceNode } from 'structured-context/api'; -import type { CompassLayoutConfig } from './definition'; +import type { NeighbourhoodLayoutConfig } from './definition'; import { childEdges, parentEdges } from './graph'; import { assignLanes } from './lanes'; import { occurrenceKey } from './occurrence'; -export type CompassRole = 'left' | 'right' | 'above' | 'below' | 'around'; +export type NeighbourhoodRole = 'left' | 'right' | 'above' | 'below' | 'around'; /** A neighbour of the focus, placed once however many fields join them. */ -export type CompassNeighbour = { key: string; node: SpaceNode }; +export type Neighbour = { key: string; node: SpaceNode }; /** An edge between the focus and a neighbour, in the edge's own direction. `lane` as in `XYLink`. */ -export type CompassLink = { from: string; to: string; field: string; lane: number }; +export type NeighbourhoodLink = { from: string; to: string; field: string; lane: number }; -export type Compass = { +export type Neighbourhood = { /** `undefined` when the graph has no nodes. */ focus: { key: string; node: SpaceNode } | undefined; - roles: Record; - links: CompassLink[]; + roles: Record; + links: NeighbourhoodLink[]; }; -const ORDER: readonly CompassRole[] = ['left', 'right', 'above', 'below', 'around']; +const ORDER: readonly NeighbourhoodRole[] = ['left', 'right', 'above', 'below', 'around']; /** * The focus and its neighbours placed by role. Without a usable `focusId`, the focus is the * first hierarchy root, else the first node. */ -export function buildCompass( +export function buildNeighbourhood( graph: SpaceGraph, regionId: string, - layout: CompassLayoutConfig, + layout: NeighbourhoodLayoutConfig, focusId?: SpaceNode['id'], -): Compass { - const roles: Compass['roles'] = { left: [], right: [], above: [], below: [], around: [] }; +): Neighbourhood { + const roles: Neighbourhood['roles'] = { left: [], right: [], above: [], below: [], around: [] }; const node = (focusId && graph.nodes.get(focusId)) || graph.hierarchyRoots[0] || graph.nodes.values().next().value; if (!node) return { focus: undefined, roles, links: [] }; const focus = { key: occurrenceKey(regionId, [node.id]), node }; - const roleOf = (direction: 'parent' | 'child', field: string): CompassRole => { + const roleOf = (direction: 'parent' | 'child', field: string): NeighbourhoodRole => { const listed = (fields: readonly string[]) => fields.includes(field); const open = (fields: readonly string[]) => fields.length === 0 || listed(fields); if (listed(layout.left)) return 'left'; @@ -46,8 +46,8 @@ export function buildCompass( return 'around'; }; - const best = new Map(); - const links: CompassLink[] = []; + const best = new Map(); + const links: NeighbourhoodLink[] = []; const neighbour = (id: SpaceNode['id'], direction: 'parent' | 'child', field: string) => { if (id === node.id || !graph.nodes.has(id)) return; const role = roleOf(direction, field); diff --git a/packages/map-views/src/layouts/GraphLayout.tsx b/packages/map-views/src/layouts/GraphLayout.tsx new file mode 100644 index 0000000..7fbfddc --- /dev/null +++ b/packages/map-views/src/layouts/GraphLayout.tsx @@ -0,0 +1,62 @@ +import { useCallback, useMemo, useRef, useState } from 'react'; +import type { GraphLayoutConfig } from '../core/definition'; +import { buildForceGraph } from '../core/force'; +import { EdgeOverlay } from './EdgeOverlay'; +import { NodeCard } from './NodeCard'; +import type { LayoutProps } from './TreeLayout'; + +// Room each node needs: a card is about this wide, a shape is a marker with a label. +const CARD_SIZE = 220; +const SHAPE_SIZE = 90; + +/** Nodes positioned by a force simulation, with straight connectors. */ +export function GraphLayout({ graph, region, instanceId, onNodeSelect }: LayoutProps) { + const shape = region.nodes.style === 'shape'; + const plot = useMemo( + () => buildForceGraph(graph, region.id, region.layout, shape ? SHAPE_SIZE : CARD_SIZE), + [graph, region.id, region.layout, shape], + ); + const { show, labels } = region.edges; + const links = useMemo( + () => (show ? plot.links.map((link) => ({ ...link, id: link.field, label: labels ? link.field : undefined })) : []), + [plot, show, labels], + ); + + const [container, setContainer] = useState(null); + const elements = useRef(new Map()).current; + const register = useCallback( + (key: string) => (el: HTMLElement | null) => { + if (el) elements.set(key, el); + else elements.delete(key); + }, + [elements], + ); + + return ( +
+ {/* Before the nodes, so the opaque nodes cover the ends of the lines. */} + + {plot.points.map((point) => ( +
+
+ +
+ {shape && ( + + {point.node.title} + + )} +
+ ))} +
+ ); +} diff --git a/packages/map-views/src/layouts/MapView.tsx b/packages/map-views/src/layouts/MapView.tsx index c2dc34d..a6e42d0 100644 --- a/packages/map-views/src/layouts/MapView.tsx +++ b/packages/map-views/src/layouts/MapView.tsx @@ -3,8 +3,9 @@ import type { SpaceGraph, SpaceNode } from 'structured-context/api'; import { type AnnotationIndex, filterAnnotations } from '../core/annotations'; import { type MapViewDefinition, type ParameterValues, type Region, resolveRegions } from '../core/definition'; import { AnnotationsContext } from './annotations-context'; -import { CompassLayout } from './CompassLayout'; +import { GraphLayout } from './GraphLayout'; import { LandscapeLayout } from './LandscapeLayout'; +import { NeighbourhoodLayout } from './NeighbourhoodLayout'; import { type LayoutProps, TreeLayout } from './TreeLayout'; import { XYLayout } from './XYLayout'; @@ -19,7 +20,7 @@ type Props = { */ annotations?: AnnotationIndex; onNodeSelect?: (node: SpaceNode) => void; - /** The node a compass layout centres on (see {@link CompassLayout}). */ + /** The node a neighbourhood layout centres on (see {@link NeighbourhoodLayout}). */ focus?: SpaceNode['id']; onFocusChange?: (id: SpaceNode['id']) => void; }; @@ -51,7 +52,7 @@ export function MapView({ definition, graph, values, annotations, onNodeSelect, function layoutFor( region: Region, props: Omit, - compass: Pick, + neighbourhood: Pick, ) { const { layout } = region; switch (layout.type) { @@ -61,7 +62,9 @@ function layoutFor( return ; case 'xy': return ; - case 'compass': - return ; + case 'graph': + return ; + case 'neighbourhood': + return ; } } diff --git a/packages/map-views/src/layouts/CompassLayout.tsx b/packages/map-views/src/layouts/NeighbourhoodLayout.tsx similarity index 74% rename from packages/map-views/src/layouts/CompassLayout.tsx rename to packages/map-views/src/layouts/NeighbourhoodLayout.tsx index 34ce984..9daadb5 100644 --- a/packages/map-views/src/layouts/CompassLayout.tsx +++ b/packages/map-views/src/layouts/NeighbourhoodLayout.tsx @@ -1,12 +1,12 @@ import { useCallback, useMemo, useRef, useState } from 'react'; import type { SpaceNode } from 'structured-context/api'; -import { buildCompass, type CompassNeighbour } from '../core/compass'; -import type { CompassLayoutConfig } from '../core/definition'; +import type { NeighbourhoodLayoutConfig } from '../core/definition'; +import { buildNeighbourhood, type Neighbour } from '../core/neighbourhood'; import { EdgeOverlay } from './EdgeOverlay'; import { NodeCard } from './NodeCard'; import type { LayoutProps } from './TreeLayout'; -type Props = LayoutProps & { +type Props = LayoutProps & { /** The focus node; the layout keeps its own once the reader picks another. */ focus?: SpaceNode['id']; onFocusChange?: (id: SpaceNode['id']) => void; @@ -16,19 +16,21 @@ type Props = LayoutProps & { * One node with its neighbours around it. Selecting a neighbour moves the focus to it; selecting * the focus is a regular node selection. */ -export function CompassLayout({ graph, region, instanceId, onNodeSelect, focus, onFocusChange }: Props) { +export function NeighbourhoodLayout({ graph, region, instanceId, onNodeSelect, focus, onFocusChange }: Props) { const [picked, setPicked] = useState<{ from: SpaceNode['id'] | undefined; id: SpaceNode['id'] }>(); // A focus the host sets later wins over the reader's earlier pick. const focusId = picked && picked.from === focus ? picked.id : focus; - const compass = useMemo( - () => buildCompass(graph, region.id, region.layout, focusId), + const neighbourhood = useMemo( + () => buildNeighbourhood(graph, region.id, region.layout, focusId), [graph, region.id, region.layout, focusId], ); const { labels, show } = region.edges; const links = useMemo( () => - show ? compass.links.map((link) => ({ ...link, id: link.field, label: labels ? link.field : undefined })) : [], - [compass, show, labels], + show + ? neighbourhood.links.map((link) => ({ ...link, id: link.field, label: labels ? link.field : undefined })) + : [], + [neighbourhood, show, labels], ); const [container, setContainer] = useState(null); @@ -41,8 +43,8 @@ export function CompassLayout({ graph, region, instanceId, onNodeSelect, focus, [elements], ); - if (!compass.focus) return null; - const current = compass.focus.node; + if (!neighbourhood.focus) return null; + const current = neighbourhood.focus.node; const select = (node: SpaceNode) => { if (node.id === current.id) return onNodeSelect?.(node); setPicked({ from: focus, id: node.id }); @@ -58,11 +60,11 @@ export function CompassLayout({ graph, region, instanceId, onNodeSelect, focus, ); - const group = (items: CompassNeighbour[], className: string) => + const group = (items: Neighbour[], className: string) => items.length > 0 && (
{items.map(cell)}
); - const { above, below, left, right, around } = compass.roles; + const { above, below, left, right, around } = neighbourhood.roles; return (
{group(left, 'mv:flex-col')} - {cell(compass.focus)} + {cell(neighbourhood.focus)} {group(right, 'mv:flex-col')}
{group(below, '')} diff --git a/packages/map-views/src/layouts/TreeLayout.tsx b/packages/map-views/src/layouts/TreeLayout.tsx index 6eec3a7..d70d08c 100644 --- a/packages/map-views/src/layouts/TreeLayout.tsx +++ b/packages/map-views/src/layouts/TreeLayout.tsx @@ -58,6 +58,8 @@ export function TreeLayout({ graph, region, instanceId, onNodeSelect }: LayoutPr ); + if (!graph.hierarchy) return

This schema has no hierarchy to draw as a tree.

; + return (
{[...tree.roots, ...tree.orphans].map(branch)} diff --git a/packages/map-views/src/node/bundled-definitions.ts b/packages/map-views/src/node/bundled-definitions.ts index 276b19e..d786cf8 100644 --- a/packages/map-views/src/node/bundled-definitions.ts +++ b/packages/map-views/src/node/bundled-definitions.ts @@ -1,5 +1,7 @@ // Generated by scripts/generate-definitions.ts from map-views/*.json5. Do not edit. export const BUNDLED_DEFINITIONS: Record = { - "knowledge-wiki-neighbourhood.json5": "// A knowledge wiki page with the sources and concepts it connects to, around it.\n{\n $schema: 'https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json',\n $id: 'sctx-map-view://core/knowledge-wiki-neighbourhood',\n title: 'Neighbourhood',\n schema: 'sctx://core/knowledge_wiki',\n parameters: {\n labels: { type: 'boolean', title: 'Relationship labels', default: true },\n },\n regions: [\n {\n id: 'main',\n layout: { type: 'compass' },\n nodes: { style: 'card', fields: ['summary'] },\n edges: { show: true, labels: { $param: 'labels' } },\n },\n ],\n}\n", + "graph.json5": "// Every node and edge as a network. Any schema.\n{\n $schema: 'https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json',\n $id: 'sctx-map-view://core/graph',\n title: 'Graph',\n parameters: {\n nodeStyle: { $ref: 'settings.json#/$defs/nodeStyle', default: 'shape' },\n labels: { type: 'boolean', title: 'Relationship labels', default: false },\n validation: { $ref: 'settings.json#/$defs/validationLevel', default: 'off' },\n },\n regions: [\n {\n id: 'main',\n layout: { type: 'graph' },\n nodes: { style: { $param: 'nodeStyle' }, validation: { $param: 'validation' } },\n edges: { show: true, labels: { $param: 'labels' } },\n },\n ],\n}\n", + "neighbourhood.json5": "// One node with the nodes it is related to around it. Any schema.\n{\n $schema: 'https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json',\n $id: 'sctx-map-view://core/neighbourhood',\n title: 'Neighbourhood',\n parameters: {\n labels: { type: 'boolean', title: 'Relationship labels', default: true },\n validation: { $ref: 'settings.json#/$defs/validationLevel', default: 'off' },\n },\n regions: [\n {\n id: 'main',\n layout: { type: 'neighbourhood' },\n nodes: { validation: { $param: 'validation' } },\n edges: { show: true, labels: { $param: 'labels' } },\n },\n ],\n}\n", "strategy-tree.json5": "// Strategy stack as a tree: vision → mission → goals → opportunities → solutions → experiments.\n{\n $schema: 'https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json',\n $id: 'sctx-map-view://core/strategy-tree',\n title: 'Strategy tree',\n schema: 'sctx://core/strategy_general',\n parameters: {\n orientation: { $ref: 'settings.json#/$defs/orientation', default: 'vertical' },\n nodeStyle: { $ref: 'settings.json#/$defs/nodeStyle', default: 'card' },\n validation: { $ref: 'settings.json#/$defs/validationLevel', default: 'off' },\n cardFields: {\n title: 'Card fields',\n type: 'array',\n items: { enum: ['status', 'priority', 'summary'] },\n default: ['status'],\n },\n },\n regions: [\n {\n id: 'main',\n layout: { type: 'tree', orientation: { $param: 'orientation' } },\n nodes: { style: { $param: 'nodeStyle' }, fields: { $param: 'cardFields' }, validation: { $param: 'validation' } },\n edges: { show: true },\n },\n ],\n}\n", + "tree.json5": "// The hierarchy as a tree. Any schema that has one.\n{\n $schema: 'https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json',\n $id: 'sctx-map-view://core/tree',\n title: 'Tree',\n parameters: {\n orientation: { $ref: 'settings.json#/$defs/orientation', default: 'vertical' },\n nodeStyle: { $ref: 'settings.json#/$defs/nodeStyle', default: 'card' },\n validation: { $ref: 'settings.json#/$defs/validationLevel', default: 'off' },\n },\n regions: [\n {\n id: 'main',\n layout: { type: 'tree', orientation: { $param: 'orientation' } },\n nodes: { style: { $param: 'nodeStyle' }, validation: { $param: 'validation' } },\n edges: { show: true },\n },\n ],\n}\n", }; diff --git a/packages/map-views/tests/definition.test.ts b/packages/map-views/tests/definition.test.ts index 7db65cd..9ec3582 100644 --- a/packages/map-views/tests/definition.test.ts +++ b/packages/map-views/tests/definition.test.ts @@ -112,7 +112,7 @@ describe('parseMapViewDefinition', () => { test.each([ ['{', /invalid JSON5/], - [`{ $id: 'sctx-map-view://t', regions: [] }`, /must have required property 'schema'/], + [`{ $id: 'sctx-map-view://t' }`, /must have required property 'regions'/], [`{ schema: 'x', regions: [{ id: 'a', layout: { type: 'tree' } }] }`, /must have required property '\$id'/], [`{ $id: 'map/t', schema: 'x', regions: [{ id: 'a', layout: { type: 'tree' } }] }`, /\$id must match pattern/], [ @@ -187,3 +187,17 @@ describe('parseMapViewDefinition', () => { expect(JSON.parse(JSON.stringify(def))).toEqual(def); }); }); + +describe('mapViewsForSchema', () => { + const def = (id: string, schema?: string) => + parseMapViewDefinition( + id, + `{ $id: 'sctx-map-view://${id}', ${schema ? `schema: '${schema}', ` : ''}regions: [{ id: 'a', layout: { type: 'tree' } }] }`, + ); + const definitions = [def('a', 'x'), def('b', 'y'), def('any')]; + + test('includes definitions without a schema, for every schema', () => { + expect(mapViewsForSchema(definitions, 'x').map((d) => d.title)).toEqual(['a', 'any']); + expect(mapViewsForSchema(definitions, undefined).map((d) => d.title)).toEqual(['any']); + }); +}); diff --git a/packages/map-views/tests/force.test.ts b/packages/map-views/tests/force.test.ts new file mode 100644 index 0000000..79a4cb4 --- /dev/null +++ b/packages/map-views/tests/force.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, test } from 'bun:test'; +import type { GraphLayoutConfig } from '../src/core/definition'; +import { buildForceGraph } from '../src/core/force'; +import { fixtureGraph } from './fixture-graph'; +import sample from './fixtures/launch-playbook.json'; + +const graph = fixtureGraph(sample); +const layout = (edgeFields: string[] = []): GraphLayoutConfig => ({ type: 'graph', edgeFields }); + +describe('force graph', () => { + const result = buildForceGraph(graph, 'main', layout(), 200); + + test('places every node once, inside the plot', () => { + expect(result.points).toHaveLength(graph.nodes.size); + expect(result.points.every((p) => p.x >= 0 && p.x <= result.width && p.y >= 0 && p.y <= result.height)).toBe(true); + }); + + test('gives the same positions for the same graph', () => { + expect(buildForceGraph(graph, 'main', layout(), 200)).toEqual(result); + }); + + test('draws only the listed fields', () => { + const fields = new Set(result.links.map((l) => l.field)); + expect(fields.size).toBeGreaterThan(1); + const [only] = [...fields]; + expect(new Set(buildForceGraph(graph, 'main', layout([only!]), 200).links.map((l) => l.field))).toEqual( + new Set([only!]), + ); + }); + + test('an empty graph has an empty plot', () => { + const empty = buildForceGraph({ ...graph, nodes: new Map() }, 'main', layout(), 200); + expect(empty.points).toEqual([]); + }); +}); diff --git a/packages/map-views/tests/load-definitions.test.ts b/packages/map-views/tests/load-definitions.test.ts index e1e7830..81005cf 100644 --- a/packages/map-views/tests/load-definitions.test.ts +++ b/packages/map-views/tests/load-definitions.test.ts @@ -17,6 +17,12 @@ function write(path: string, text: string) { } const definition = (id: string) => `{ $id: '${id}', schema: 'sctx://x', regions: [{ id: 'main', layout: { type: 'tree' } }] }`; +const BUNDLED = [ + 'sctx-map-view://core/graph', + 'sctx-map-view://core/neighbourhood', + 'sctx-map-view://core/strategy-tree', + 'sctx-map-view://core/tree', +]; const noSpaces: Config = { spaces: [] }; const ids = (config: Config, configDir = join(root, 'config')) => loadMapViewDefinitions(config, { configDir }).map((d) => d.id); @@ -28,8 +34,7 @@ describe('loadMapViewDefinitions', () => { write('config/.sctx/plugins/sctx-declared/views/b.json5', definition('sctx-map-view://declared/b')); write('config/.sctx/map-views/c.json5', definition('sctx-map-view://c')); expect(ids(noSpaces)).toEqual([ - 'sctx-map-view://core/knowledge-wiki-neighbourhood', - 'sctx-map-view://core/strategy-tree', + ...BUNDLED, 'sctx-map-view://conventional/a', 'sctx-map-view://declared/b', 'sctx-map-view://c', @@ -49,12 +54,7 @@ describe('loadMapViewDefinitions', () => { }, ], }; - expect(ids(config)).toEqual([ - 'sctx-map-view://core/knowledge-wiki-neighbourhood', - 'sctx-map-view://core/strategy-tree', - 'sctx-map-view://named/a', - 'sctx-map-view://b', - ]); + expect(ids(config)).toEqual([...BUNDLED, 'sctx-map-view://named/a', 'sctx-map-view://b']); }); test.each([ diff --git a/packages/map-views/tests/compass.test.ts b/packages/map-views/tests/neighbourhood.test.ts similarity index 55% rename from packages/map-views/tests/compass.test.ts rename to packages/map-views/tests/neighbourhood.test.ts index 59ac6ed..0f30e2d 100644 --- a/packages/map-views/tests/compass.test.ts +++ b/packages/map-views/tests/neighbourhood.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from 'bun:test'; import { buildSpaceGraph } from 'structured-context/api'; -import { buildCompass } from '../src/core/compass'; -import type { CompassLayoutConfig } from '../src/core/definition'; +import type { NeighbourhoodLayoutConfig } from '../src/core/definition'; +import { buildNeighbourhood } from '../src/core/neighbourhood'; import { makeParentRef, makeSpaceNode } from './builders'; const rel = (id: string, field: string) => makeParentRef(id, { kind: 'relationship', field }); @@ -20,8 +20,8 @@ const graph = buildSpaceGraph( ], undefined, ); -const layout = (overrides: Partial = {}): CompassLayoutConfig => ({ - type: 'compass', +const layout = (overrides: Partial = {}): NeighbourhoodLayoutConfig => ({ + type: 'neighbourhood', above: [], below: [], left: [], @@ -30,38 +30,38 @@ const layout = (overrides: Partial = {}): CompassLayoutConf }); const ids = (items: { node: { id: string } }[]) => items.map((i) => i.node.id); -describe('compass', () => { +describe('neighbourhood', () => { test('puts parents above and children below by default', () => { - const compass = buildCompass(graph, 'main', layout(), 's1' as never); - expect(ids(compass.roles.above)).toEqual([]); - expect(ids(compass.roles.below)).toEqual(['x1', 'x2']); - const x1 = buildCompass(graph, 'main', layout(), 'x1' as never); + const neighbourhood = buildNeighbourhood(graph, 'main', layout(), 's1' as never); + expect(ids(neighbourhood.roles.above)).toEqual([]); + expect(ids(neighbourhood.roles.below)).toEqual(['x1', 'x2']); + const x1 = buildNeighbourhood(graph, 'main', layout(), 'x1' as never); expect(ids(x1.roles.above)).toEqual(['s1', 's2', 'c1']); }); test('a listed field moves its neighbours to that role, before above and below', () => { - const compass = buildCompass(graph, 'main', layout({ left: ['concepts'] }), 'x1' as never); - expect(ids(compass.roles.left)).toEqual(['c1']); - expect(ids(compass.roles.above)).toEqual(['s1', 's2']); + const neighbourhood = buildNeighbourhood(graph, 'main', layout({ left: ['concepts'] }), 'x1' as never); + expect(ids(neighbourhood.roles.left)).toEqual(['c1']); + expect(ids(neighbourhood.roles.above)).toEqual(['s1', 's2']); }); test('edges outside the listed above and below fields go around', () => { - const compass = buildCompass(graph, 'main', layout({ above: ['sources'] }), 'x1' as never); - expect(ids(compass.roles.around)).toEqual(['c1']); + const neighbourhood = buildNeighbourhood(graph, 'main', layout({ above: ['sources'] }), 'x1' as never); + expect(ids(neighbourhood.roles.around)).toEqual(['c1']); }); test('links keep the edge direction and carry the field', () => { - const { focus, links } = buildCompass(graph, 'main', layout(), 'x1' as never); + const { focus, links } = buildNeighbourhood(graph, 'main', layout(), 'x1' as never); expect(links).toHaveLength(3); expect(links.every((l) => l.to === focus!.key)).toBe(true); expect(links.map((l) => l.field).sort()).toEqual(['concepts', 'sources', 'sources']); }); test('an unknown focus falls back to the first node', () => { - expect(buildCompass(graph, 'main', layout(), 'nope' as never).focus?.node.id).toBe('s1' as never); + expect(buildNeighbourhood(graph, 'main', layout(), 'nope' as never).focus?.node.id).toBe('s1' as never); }); test('an empty graph has no focus', () => { - expect(buildCompass(buildSpaceGraph([], undefined), 'main', layout()).focus).toBeUndefined(); + expect(buildNeighbourhood(buildSpaceGraph([], undefined), 'main', layout()).focus).toBeUndefined(); }); }); diff --git a/packages/map-views/tests/snapshot.test.ts b/packages/map-views/tests/snapshot.test.ts index 994f278..a404944 100644 --- a/packages/map-views/tests/snapshot.test.ts +++ b/packages/map-views/tests/snapshot.test.ts @@ -12,7 +12,7 @@ describe('exportSnapshot', () => { expect(result.space).toBe('launch-playbook'); expect(result.graph.formatVersion).toBe(1); expect(result.validation).toHaveProperty('issues'); - expect(result.definitions.every((d) => d.schema === result.schemaId)).toBe(true); + expect(result.definitions.every((d) => d.schema === undefined || d.schema === result.schemaId)).toBe(true); expect(JSON.parse(JSON.stringify(result))).toEqual(result); }); diff --git a/packages/map-views/vite.config.ts b/packages/map-views/vite.config.ts index 7a7515d..950a087 100644 --- a/packages/map-views/vite.config.ts +++ b/packages/map-views/vite.config.ts @@ -30,6 +30,7 @@ export default defineConfig({ /^react(\/|$)/, /^react-dom(\/|$)/, /^ajv(\/|$)/, + /^d3-/, 'json5', 'commander', /^structured-context(\/|$)/, diff --git a/packages/sctx-map-views/tests/render.test.ts b/packages/sctx-map-views/tests/render.test.ts index dc0b8c3..82a0771 100644 --- a/packages/sctx-map-views/tests/render.test.ts +++ b/packages/sctx-map-views/tests/render.test.ts @@ -47,7 +47,10 @@ describe('map-views.html', () => { const page = await render(context().context); const [snapshot] = snapshotsOf(page); expect(snapshot!.space).toBe('demo'); - expect(snapshot!.definitions.map((d) => d.id)).toEqual(['sctx-map-view://mine']); + const ids = snapshot!.definitions.map((d) => d.id); + expect(ids).toContain('sctx-map-view://mine'); + expect(ids).toContain('sctx-map-view://core/graph'); + expect(ids).not.toContain('sctx-map-view://core/strategy-tree'); }); test('passes validation options from -d', async () => { diff --git a/schemas/generated/latest/definition.json b/schemas/generated/latest/definition.json index b46555c..b11f29c 100644 --- a/schemas/generated/latest/definition.json +++ b/schemas/generated/latest/definition.json @@ -6,7 +6,6 @@ "type": "object", "required": [ "$id", - "schema", "regions" ], "additionalProperties": false, @@ -30,7 +29,7 @@ "schema": { "type": "string", "minLength": 1, - "description": "`$id` of the structured-context schema whose spaces this map view applies to." + "description": "`$id` of the structured-context schema whose spaces this map view applies to. Omitted: it applies to every schema." }, "parameters": { "type": "object", @@ -124,7 +123,10 @@ "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/layouts/xy.json" }, { - "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/layouts/compass.json" + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/layouts/neighbourhood.json" + }, + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/layouts/graph.json" } ] }, diff --git a/schemas/generated/latest/layouts/graph.json b/schemas/generated/latest/layouts/graph.json new file mode 100644 index 0000000..358704f --- /dev/null +++ b/schemas/generated/latest/layouts/graph.json @@ -0,0 +1,28 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/layouts/graph.json", + "title": "Graph layout", + "description": "Nodes and edges as a network: connected nodes sit close together. Works with any schema.", + "type": "object", + "required": [ + "type" + ], + "additionalProperties": false, + "properties": { + "type": { + "const": "graph" + }, + "edgeFields": { + "description": "Fields whose edges are drawn and pull nodes together. Empty: all edges.", + "default": [], + "anyOf": [ + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/settings.json#/$defs/fieldList" + }, + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json#/$defs/paramRef" + } + ] + } + } +} diff --git a/schemas/generated/latest/layouts/compass.json b/schemas/generated/latest/layouts/neighbourhood.json similarity index 94% rename from schemas/generated/latest/layouts/compass.json rename to schemas/generated/latest/layouts/neighbourhood.json index 43e6af9..fbce846 100644 --- a/schemas/generated/latest/layouts/compass.json +++ b/schemas/generated/latest/layouts/neighbourhood.json @@ -1,7 +1,7 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/layouts/compass.json", - "title": "Compass layout", + "$id": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/layouts/neighbourhood.json", + "title": "Neighbourhood layout", "description": "The neighbourhood of one focus node, with related nodes placed around it by role. Each role lists the fields that put a node there. A node is placed by the first role that matches, in the order left, right, above, below, around.", "type": "object", "required": [ @@ -10,7 +10,7 @@ "additionalProperties": false, "properties": { "type": { - "const": "compass" + "const": "neighbourhood" }, "above": { "description": "Fields through which the focus has a parent, shown above it. Empty: every field.", From 53a2b7f9cce530a896a6996fd71f6880f1c60755 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 14:27:57 +0000 Subject: [PATCH 04/15] feat(navigator): keep the neighbourhood focus in the query string Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_019XphpcKhuNyHcNArHFELR4 --- apps/navigator/src/App.tsx | 4 +++- apps/navigator/src/useUrlState.ts | 20 ++++++++++++++------ docs/architecture.md | 2 +- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/apps/navigator/src/App.tsx b/apps/navigator/src/App.tsx index 6088495..764e3e3 100644 --- a/apps/navigator/src/App.tsx +++ b/apps/navigator/src/App.tsx @@ -18,7 +18,7 @@ import { useUrlState } from './useUrlState'; type SpaceListItem = { name: string }; export function App() { - const { spaceName, mapViewId, values, setSpaceName, setMapViewId, setValue } = useUrlState(); + const { spaceName, mapViewId, focus, values, setSpaceName, setMapViewId, setFocus, setValue } = useUrlState(); const [selectedNode, setSelectedNode] = useState(); const [unattachedPanelOpen, setUnattachedPanelOpen] = useState(false); @@ -129,6 +129,8 @@ export function App() { values={values} annotations={annotations} onNodeSelect={setSelectedNode} + focus={(focus || undefined) as SpaceNode['id'] | undefined} + onFocusChange={setFocus} /> )}
diff --git a/apps/navigator/src/useUrlState.ts b/apps/navigator/src/useUrlState.ts index e118222..e7c8ac2 100644 --- a/apps/navigator/src/useUrlState.ts +++ b/apps/navigator/src/useUrlState.ts @@ -4,7 +4,7 @@ import type { ParameterValues } from 'structured-context-map-views'; /** A query parameter holding a map view parameter's value is `p.=`. */ const VALUE_PREFIX = 'p.'; -type UrlState = { spaceName: string; mapViewId: string; values: ParameterValues }; +type UrlState = { spaceName: string; mapViewId: string; focus: string; values: ParameterValues }; function readUrl(): UrlState { const params = new URLSearchParams(window.location.search); @@ -17,20 +17,26 @@ function readUrl(): UrlState { // A hand-edited value that isn't JSON is ignored; the parameter keeps its default. } } - return { spaceName: params.get('space') ?? '', mapViewId: params.get('view') ?? '', values }; + return { + spaceName: params.get('space') ?? '', + mapViewId: params.get('view') ?? '', + focus: params.get('focus') ?? '', + values, + }; } -function writeUrl({ spaceName, mapViewId, values }: UrlState) { +function writeUrl({ spaceName, mapViewId, focus, values }: UrlState) { const params = new URLSearchParams(); if (spaceName) params.set('space', spaceName); if (mapViewId) params.set('view', mapViewId); + if (focus) params.set('focus', focus); for (const [name, value] of Object.entries(values)) params.set(VALUE_PREFIX + name, JSON.stringify(value)); const search = params.toString(); window.history.replaceState(null, '', search ? `?${search}` : window.location.pathname); } /** - * The chosen space, map view and parameter values, mirrored in the query string so a reload (or a + * The chosen space, map view, focus node and parameter values, mirrored in the query string so a reload (or a * shared link) restores them. Values are remembered per map view for the session; only the current * view's values are in the URL. `mapViewId` is '' until the host settles on a map view (see `setMapViewId`). */ @@ -41,13 +47,15 @@ export function useUrlState() { const [valuesByView, setValuesByView] = useState>( initial.mapViewId ? { [initial.mapViewId]: initial.values } : {}, ); + const [focus, setFocus] = useState(initial.focus); const values = valuesByView[mapViewId] ?? {}; - useEffect(() => writeUrl({ spaceName, mapViewId, values }), [spaceName, mapViewId, values]); + useEffect(() => writeUrl({ spaceName, mapViewId, focus, values }), [spaceName, mapViewId, focus, values]); const setSpaceName = useCallback((name: string) => { setSpaceNameState(name); setMapViewId(''); + setFocus(''); }, []); const setValue = useCallback( (name: string, value: unknown) => @@ -55,5 +63,5 @@ export function useUrlState() { [mapViewId], ); - return { spaceName, mapViewId, values, setSpaceName, setMapViewId, setValue }; + return { spaceName, mapViewId, focus, values, setSpaceName, setMapViewId, setFocus, setValue }; } diff --git a/docs/architecture.md b/docs/architecture.md index 962e66a..dbb8163 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -58,7 +58,7 @@ Hosts theme map views through nine variables: `--mv-color-surface`, `--mv-color- ## Hosts -- **Navigator** (`apps/navigator`): dev-server middleware serves spaces (from the structured-context config), the definitions `loadMapViewDefinitions` finds, and, when a map view asks for them, validation results (`validateSpace`, expression rules only), as JSON. The chosen space, map view and parameter values live in the query string, so a reload restores them. Selecting a node opens a side panel with its fields, content and validation results. +- **Navigator** (`apps/navigator`): dev-server middleware serves spaces (from the structured-context config), the definitions `loadMapViewDefinitions` finds, and, when a map view asks for them, validation results (`validateSpace`, expression rules only), as JSON. The chosen space, map view, focus node and parameter values live in the query string, so a reload restores them. Selecting a node opens a side panel with its fields, content and validation results. - **Claude artifact** (`packages/map-views/src/artifact`, shipped as `dist/artifact.js` with its page `dist/artifact.html`): a host with no server. The publishing agent runs the `export` command and writes each space to the artifact's database (`spaces/`: `schemaId`, and `graph`, `validation` and `definitions` as JSON strings). The page lists that collection and shows it in the `Viewer`. It declares only the `db` capability and shows a message when the database is unavailable, empty or slow (10 s). Claude's artifact viewer allows scripts only from a few CDNs and blocks external stylesheets, so `scripts/build-artifact-page.ts` writes a page that carries the CSS inline and loads `dist/artifact.js` (pinned to this package's version) and its dependencies from jsDelivr through an import map; `react` and `react-dom` are pinned to one version so the page runs one React. The host names cards `[] · <view>` through the `Viewer`'s `cardLabel` option, where the index is the node's position in the stored graph's `nodes` array, because the artifact viewer's comment mode reads a comment's location from it (cut at about 45 characters, too short for a node id), so a comment tells an agent which node it concerns. Refreshing the data is writing the documents again; the page doesn't change. - **Self-contained page** (`packages/map-views/src/page`): a host that needs no server or network. The build inlines it, React and the CSS into the template `dist/page.html`, and `fillPage` writes snapshots into it. The `sctx-map-views` plugin bundles that template. - **Obsidian plugin** ([obsidian-structured-context](https://github.com/mindsocket/obsidian-structured-context)): renders map views in a pane, builds the data in-process, opens the source note on selection and keeps parameter values in the view state. From 084f436134667ddb0dc48e569e07eeeab5d883af Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Mon, 16 Nov 2026 05:38:33 +0000 Subject: [PATCH 05/15] Address review: shared layout helpers, layout registry, docs/layouts.md, trimmed docs and tests Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019XphpcKhuNyHcNArHFELR4 --- AGENTS.md | 2 +- README.md | 1 + apps/navigator/src/useUrlState.ts | 6 +- docs/api.md | 2 +- docs/architecture.md | 14 ++--- docs/concepts.md | 14 +---- docs/definitions.md | 62 +----------------- docs/layouts.md | 63 +++++++++++++++++++ packages/map-views/src/core/snapshot.ts | 5 +- .../map-views/src/layouts/GraphLayout.tsx | 20 ++---- .../map-views/src/layouts/LandscapeLayout.tsx | 2 +- packages/map-views/src/layouts/MapView.tsx | 53 ++++++++-------- .../src/layouts/NeighbourhoodLayout.tsx | 38 ++++------- packages/map-views/src/layouts/TreeLayout.tsx | 32 ++-------- packages/map-views/src/layouts/XYLayout.tsx | 30 +++------ packages/map-views/src/layouts/layout.ts | 38 +++++++++++ packages/map-views/src/viewer/Viewer.tsx | 5 +- .../map-views/tests/load-definitions.test.ts | 12 ++-- packages/map-views/tests/snapshot.test.ts | 2 +- packages/sctx-map-views/tests/render.test.ts | 5 +- 20 files changed, 180 insertions(+), 226 deletions(-) create mode 100644 docs/layouts.md create mode 100644 packages/map-views/src/layouts/layout.ts diff --git a/AGENTS.md b/AGENTS.md index 6e4b136..41970ee 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -41,7 +41,7 @@ Review and update with any change: | Change | Check | |---|---| -| Definition format (`core/format`) | `docs/definitions.md`; regenerated `schemas/generated/`; definitions in `map-views/` | +| Definition format (`core/format`) | `docs/definitions.md`, `docs/layouts.md` for layout settings; regenerated `schemas/generated/`; definitions in `map-views/` | | New or renamed term | `docs/concepts.md` | | Exports or component props | `docs/api.md` | | Module structure, rendering, styling | `docs/architecture.md`, this file | diff --git a/README.md b/README.md index d0fb314..b1c532f 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,7 @@ Pre-1.0. Docs: - [Concepts](docs/concepts.md): map views, regions, layouts, occurrences, parameters - [Definitions](docs/definitions.md): writing a map view definition +- [Layouts](docs/layouts.md): the layouts and their settings - [Architecture](docs/architecture.md): how the library is put together - [API](docs/api.md): embedding map views in a host diff --git a/apps/navigator/src/useUrlState.ts b/apps/navigator/src/useUrlState.ts index e7c8ac2..07ba57a 100644 --- a/apps/navigator/src/useUrlState.ts +++ b/apps/navigator/src/useUrlState.ts @@ -36,9 +36,9 @@ function writeUrl({ spaceName, mapViewId, focus, values }: UrlState) { } /** - * The chosen space, map view, focus node and parameter values, mirrored in the query string so a reload (or a - * shared link) restores them. Values are remembered per map view for the session; only the current - * view's values are in the URL. `mapViewId` is '' until the host settles on a map view (see `setMapViewId`). + * Mirrors the reader's choices in the query string, so a reload or a shared link restores them. Parameter + * values are remembered per map view for the session; only the current view's are in the URL. `mapViewId` + * is '' until the host settles on a map view (see `setMapViewId`). */ export function useUrlState() { const [initial] = useState(readUrl); diff --git a/docs/api.md b/docs/api.md index 9d33d96..36cda46 100644 --- a/docs/api.md +++ b/docs/api.md @@ -19,7 +19,7 @@ import 'structured-context-map-views/styles.css'; <MapView definition={definition} graph={graph} values={values} onNodeSelect={(node) => open(node)} /> ``` -`graph` is a structured-context `SpaceGraph` (see [Data](#data)); `values` and the controls' `onChange` belong to the host. Pass `annotations` to show validation results (see [Validation results](#validation-results)). `focus` and `onFocusChange` set and follow the node a [neighbourhood](definitions.md#neighbourhood) layout centres on. +`graph` is a structured-context `SpaceGraph` (see [Data](#data)); `values` and the controls' `onChange` belong to the host. Pass `annotations` to show validation results (see [Validation results](#validation-results)). `focus` and `onFocusChange` set and follow the node that layouts centring on one node show. A host that lays out the controls itself builds them from `useParameterControls` and `ParameterInput`. diff --git a/docs/architecture.md b/docs/architecture.md index dbb8163..b28173a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -6,7 +6,7 @@ A space graph and a definition go in; a DOM layout with an SVG overlay comes out flowchart LR space[structured-context space] -->|host assembles| graph[SpaceGraph] def[definition .json5] -->|parseMapViewDefinition| mvd[MapViewDefinition] - graph --> proj[projection<br>tree · landscape · xy · neighbourhood · graph] + graph --> proj[projection] mvd --> proj proj --> dom[layout component<br>DOM + SVG overlay] ``` @@ -15,7 +15,7 @@ flowchart LR | Module | Holds | May import | |---|---|---| -| `packages/map-views/src/core` | Definition parsing and validation, parameter resolution, graph helpers, and the projections (`buildTree`, `buildLandscape`, `buildXYPlot`, `buildNeighbourhood`, `buildForceGraph`) | Types from structured-context only. No React, DOM or Node | +| `packages/map-views/src/core` | Definition parsing and validation, parameter resolution, graph helpers, and the projections | Types from structured-context only. No React, DOM or Node | | `packages/map-views/src/layouts` | `MapView`, the layout components, `NodeCard`, `EdgeOverlay`, the parameter controls (`useParameterControls`, the typed inputs and the default `ParameterControls` layout), styles | core, React | | `packages/map-views/src/viewer` | `Viewer`, the page-filling UI that hosts share. What is specific to a host comes in as an option | core, layouts, React, `structured-context/browser` | | `packages/map-views/src/node` | `loadMapViewDefinitions`: finding definitions in the library (embedded at build time from `packages/map-views/map-views/`), plugins and config folders; `exportSnapshot` and the `export` bin, which snapshot a space for browser-only hosts; `fillPage`, which writes snapshots into the self-contained page. `fillPage` and `readDefinitionFolders` are also the `/html` entry, which imports nothing from structured-context's API | core, Node, structured-context | @@ -32,13 +32,7 @@ Hosts can also pass validation results as an `AnnotationIndex` (`core/annotation ## Projections -Each layout has a pure projection in core that turns the graph and the region's resolved settings into occurrences and links: - -- **Tree**: walks the hierarchy from the root type. A node with several parents is repeated (subtree once) or placed once with cross-links. Cycles end in a repeat. -- **Landscape**: walks the grouping levels, joining node levels by edges in either direction, through `via` chains or by field values. -- **XY**: normalises two numeric fields to percentages within each axis's domain and lists the nodes it can't place. -- **Neighbourhood**: places the focus's neighbours by the role of the field joining them. -- **Graph**: positions every node with a force simulation (`d3-force`), seeded so the same graph gives the same positions. +Each layout has a pure projection in core that turns the graph and the region's resolved settings into occurrences and links, ready for a layout component to draw. [Layouts](layouts.md) describes each one. Occurrence keys are paths (region, ancestors, node), so a node appearing several times gets distinct keys. @@ -58,7 +52,7 @@ Hosts theme map views through nine variables: `--mv-color-surface`, `--mv-color- ## Hosts -- **Navigator** (`apps/navigator`): dev-server middleware serves spaces (from the structured-context config), the definitions `loadMapViewDefinitions` finds, and, when a map view asks for them, validation results (`validateSpace`, expression rules only), as JSON. The chosen space, map view, focus node and parameter values live in the query string, so a reload restores them. Selecting a node opens a side panel with its fields, content and validation results. +- **Navigator** (`apps/navigator`): dev-server middleware serves spaces (from the structured-context config), the definitions `loadMapViewDefinitions` finds, and, when a map view asks for them, validation results (`validateSpace`, expression rules only), as JSON. What the reader chose lives in the query string, so a reload restores it. Selecting a node opens a side panel with its fields, content and validation results. - **Claude artifact** (`packages/map-views/src/artifact`, shipped as `dist/artifact.js` with its page `dist/artifact.html`): a host with no server. The publishing agent runs the `export` command and writes each space to the artifact's database (`spaces/<space>`: `schemaId`, and `graph`, `validation` and `definitions` as JSON strings). The page lists that collection and shows it in the `Viewer`. It declares only the `db` capability and shows a message when the database is unavailable, empty or slow (10 s). Claude's artifact viewer allows scripts only from a few CDNs and blocks external stylesheets, so `scripts/build-artifact-page.ts` writes a page that carries the CSS inline and loads `dist/artifact.js` (pinned to this package's version) and its dependencies from jsDelivr through an import map; `react` and `react-dom` are pinned to one version so the page runs one React. The host names cards `[<index>] <title> · <view>` through the `Viewer`'s `cardLabel` option, where the index is the node's position in the stored graph's `nodes` array, because the artifact viewer's comment mode reads a comment's location from it (cut at about 45 characters, too short for a node id), so a comment tells an agent which node it concerns. Refreshing the data is writing the documents again; the page doesn't change. - **Self-contained page** (`packages/map-views/src/page`): a host that needs no server or network. The build inlines it, React and the CSS into the template `dist/page.html`, and `fillPage` writes snapshots into it. The `sctx-map-views` plugin bundles that template. - **Obsidian plugin** ([obsidian-structured-context](https://github.com/mindsocket/obsidian-structured-context)): renders map views in a pane, builds the data in-process, opens the source note on selection and keeps parameter values in the view state. diff --git a/docs/concepts.md b/docs/concepts.md index cc91113..7d059e6 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -8,7 +8,7 @@ A declarative way to visualise spaces of one schema, and the rendering it produc ## Definition -The JSON5 file that declares a map view: the schema it applies to, its parameters and its regions. A definition applies to every space whose schema `$id` equals its `schema`. Its own `$id` (`sctx-map-view://…`) identifies it, namespaced by where it's found: bundled, a plugin, or a config folder. See [Definitions](definitions.md). +The JSON5 file that declares a map view: the schema it applies to, its parameters and its regions. A definition applies to every space whose schema `$id` equals its `schema`, or to every space when it names none. Its own `$id` (`sctx-map-view://…`) identifies it, namespaced by where it's found: bundled, a plugin, or a config folder. See [Definitions](definitions.md). ## Region @@ -16,15 +16,7 @@ A part of a map view with its own node selection, layout, node style and edge se ## Layout -The arrangement a region uses, chosen from a fixed catalogue: - -- **tree**: a tree over the schema's hierarchy. -- **landscape**: nested containers following an authored grouping. -- **xy**: nodes positioned by two numeric fields. -- **neighbourhood**: one node with its neighbours placed around it by role. -- **graph**: every node and edge as a network. - -Each layout carries its own opinions (spacing, card sizes, colours). Definitions choose and configure a layout; they don't compose one. +The arrangement a region uses, chosen from a fixed catalogue ([Layouts](layouts.md)). Each layout carries its own opinions (spacing, card sizes, colours). Definitions choose and configure a layout; they don't compose one. ## Occurrence @@ -39,7 +31,7 @@ The two ways a tree shows a node with several parents: ## Focus -The node a neighbourhood layout centres on. Hosts can set it; otherwise the reader's picks move it. +The node a layout centres on. Hosts can set it; otherwise the reader's picks move it. ## Grouping level diff --git a/docs/definitions.md b/docs/definitions.md index 07578f7..1e8c1dc 100644 --- a/docs/definitions.md +++ b/docs/definitions.md @@ -52,69 +52,11 @@ A map view definition is a JSON5 file. Its format is a set of JSON Schemas publi ## Layouts -### tree - -A tree over the schema's hierarchy: nodes of the root type at the top, children through hierarchy edges. Relationship edges don't shape the tree. - -| Setting | Values | Default | -|---|---|---| -| `orientation` | `vertical`, `horizontal` | `vertical` | -| `dag` | `repeat`, `cross-edge` | `repeat` | - -### landscape - -Nested containers. `group` lists grouping levels, outermost first. The last level is drawn as nodes and the others as containers. - -| Setting | Values | Default | -|---|---|---| -| `orientation` | `horizontal` (top-level containers as columns), `vertical` (as rows) | `horizontal` | -| `group` | Grouping levels (below) | required | - -A grouping level is one of: - -- `{ type: 'Activities' }`: a level of nodes of one type. Adjacent node levels are joined by any edge between their types, in either direction, so `Outcomes` can group `Activities` even when the edge is declared from `Activities`. - - `edge: { field: 'phase' }` restricts the join to edges from that field. - - `via: ['Capabilities']` joins through a chain of edges across the listed types, in order. - - `intermediate`: how the skipped nodes of a `via` chain are shown. `hidden` (default) or `breadcrumb` (listed on each node reached through them). -- `{ field: 'status' }`: containers labelled by the values of a field on the next node level. A node with several values appears under each. - -A node that occurs in several containers is repeated in each. Nodes of a grouped type that no container reaches are shown as ungrouped, not dropped. - -### xy - -Nodes positioned on two axes by numeric fields. Plotted nodes without a usable value on both axes, or outside a fixed domain, are listed beside the plot. - -| Setting | Values | Default | -|---|---|---| -| `x`, `y` | Axis (below) | required | -| `types` | Node types to plot | every type with a value on either axis | -| `edgeFields` | Fields whose edges are drawn between plotted nodes | all edges | - -An axis has a `field` (required), a `domain` (`[min, max]`, or `'data'` for the smallest and largest plotted values; default `'data'`), a `direction` (`ascending`, the default, or `descending`) and a `label` (defaults to the field name). - -### graph - -Every node and edge as a network: connected nodes sit close together. It needs no hierarchy, so it suits any schema. - -| Setting | Values | Default | -|---|---|---| -| `edgeFields` | Fields whose edges are drawn and pull nodes together | all edges | - -### neighbourhood - -One focus node with its neighbours around it. Selecting a neighbour makes it the focus; selecting the focus is a normal node selection. A node is placed by the first role that matches, in the order `left`, `right`, `above`, `below`, then `around` for the rest. - -| Setting | Meaning | -|---|---| -| `above` | Fields through which the focus has a parent. Empty: every field | -| `below` | Fields through which the focus has a child. Empty: every field | -| `left`, `right` | Fields, in either direction. Empty: none | - -The focus is the host's to set (`focus` on `MapView`); by default it is the first hierarchy root, else the first node. +A region's `layout` is chosen by `type`. Each layout, with its settings, is in [Layouts](layouts.md). ## Parameters -Any setting marked parameterisable in the schemas (`orientation`, `dag`, `intermediate`, `nodes.style`, `nodes.fields`, `nodes.validation`, `nodes.validationSources`, `edges.show`, `edges.labels`, a landscape level's `type`, an axis's `field` and `direction`, `types`, `edgeFields`, a neighbourhood's role fields) takes either a fixed value or `{ $param: '<name>' }`. +Any setting the schemas mark parameterisable takes either a fixed value or `{ $param: '<name>' }`. Each parameter is a JSON Schema with a `default` and an optional `title`. It can `$ref` a shared setting from `settings.json` (`orientation`, `nodeStyle`, `fieldList`, `validationLevel`, `validationSources`) or a layout's own definitions (e.g. `layouts/tree.json#/$defs/dag`), and narrow it. Relative refs resolve against the format's `latest` folder; full URLs work too. diff --git a/docs/layouts.md b/docs/layouts.md new file mode 100644 index 0000000..aaa729b --- /dev/null +++ b/docs/layouts.md @@ -0,0 +1,63 @@ +# Layouts + +A layout arranges a region's nodes. A region chooses one with `layout.type` and configures it with the settings below (see [Definitions](definitions.md)). + +## tree + +A tree over the schema's hierarchy: nodes of the root type at the top, children through hierarchy edges. Relationship edges don't shape the tree. + +| Setting | Values | Default | +|---|---|---| +| `orientation` | `vertical`, `horizontal` | `vertical` | +| `dag` | `repeat`, `cross-edge` | `repeat` | + +## landscape + +Nested containers. `group` lists grouping levels, outermost first. The last level is drawn as nodes and the others as containers. + +| Setting | Values | Default | +|---|---|---| +| `orientation` | `horizontal` (top-level containers as columns), `vertical` (as rows) | `horizontal` | +| `group` | Grouping levels (below) | required | + +A grouping level is one of: + +- `{ type: 'Activities' }`: a level of nodes of one type. Adjacent node levels are joined by any edge between their types, in either direction, so `Outcomes` can group `Activities` even when the edge is declared from `Activities`. + - `edge: { field: 'phase' }` restricts the join to edges from that field. + - `via: ['Capabilities']` joins through a chain of edges across the listed types, in order. + - `intermediate`: how the skipped nodes of a `via` chain are shown. `hidden` (default) or `breadcrumb` (listed on each node reached through them). +- `{ field: 'status' }`: containers labelled by the values of a field on the next node level. A node with several values appears under each. + +A node that occurs in several containers is repeated in each. Nodes of a grouped type that no container reaches are shown as ungrouped, not dropped. + +## xy + +Nodes positioned on two axes by numeric fields. Plotted nodes without a usable value on both axes, or outside a fixed domain, are listed beside the plot. + +| Setting | Values | Default | +|---|---|---| +| `x`, `y` | Axis (below) | required | +| `types` | Node types to plot | every type with a value on either axis | +| `edgeFields` | Fields whose edges are drawn between plotted nodes | all edges | + +An axis has a `field` (required), a `domain` (`[min, max]`, or `'data'` for the smallest and largest plotted values; default `'data'`), a `direction` (`ascending`, the default, or `descending`) and a `label` (defaults to the field name). + +## graph + +Every node and edge as a network: connected nodes sit close together. It needs no hierarchy, so it suits any schema. + +| Setting | Values | Default | +|---|---|---| +| `edgeFields` | Fields whose edges are drawn and pull nodes together | all edges | + +## neighbourhood + +One focus node with its neighbours around it. Selecting a neighbour makes it the focus; selecting the focus is a normal node selection. A node is placed by the first role that matches, in the order `left`, `right`, `above`, `below`, then `around` for the rest. + +| Setting | Meaning | +|---|---| +| `above` | Fields through which the focus has a parent. Empty: every field | +| `below` | Fields through which the focus has a child. Empty: every field | +| `left`, `right` | Fields, in either direction. Empty: none | + +The focus is the host's to set (`focus` on `MapView`); by default it is the first hierarchy root, else the first node. diff --git a/packages/map-views/src/core/snapshot.ts b/packages/map-views/src/core/snapshot.ts index 10790cb..e4eb4b5 100644 --- a/packages/map-views/src/core/snapshot.ts +++ b/packages/map-views/src/core/snapshot.ts @@ -2,10 +2,7 @@ import type { spaceGraphFrom } from 'structured-context/browser'; import type { ValidationInput } from './annotations'; import type { MapViewDefinition } from './definition'; -/** - * Everything a host without filesystem access needs to render a space: its graph, the validation - * results that attach to nodes, and the map view definitions that apply to its schema. Plain JSON. - */ +/** What a host without filesystem access needs to render a space. Plain JSON. */ export type SpaceSnapshot = { space: string; schemaId: string | undefined; diff --git a/packages/map-views/src/layouts/GraphLayout.tsx b/packages/map-views/src/layouts/GraphLayout.tsx index 7fbfddc..bb7f104 100644 --- a/packages/map-views/src/layouts/GraphLayout.tsx +++ b/packages/map-views/src/layouts/GraphLayout.tsx @@ -1,9 +1,9 @@ -import { useCallback, useMemo, useRef, useState } from 'react'; +import { useMemo } from 'react'; import type { GraphLayoutConfig } from '../core/definition'; import { buildForceGraph } from '../core/force'; import { EdgeOverlay } from './EdgeOverlay'; +import { type LayoutProps, overlayLinks, useOccurrenceElements } from './layout'; import { NodeCard } from './NodeCard'; -import type { LayoutProps } from './TreeLayout'; // Room each node needs: a card is about this wide, a shape is a marker with a label. const CARD_SIZE = 220; @@ -16,21 +16,9 @@ export function GraphLayout({ graph, region, instanceId, onNodeSelect }: LayoutP () => buildForceGraph(graph, region.id, region.layout, shape ? SHAPE_SIZE : CARD_SIZE), [graph, region.id, region.layout, shape], ); - const { show, labels } = region.edges; - const links = useMemo( - () => (show ? plot.links.map((link) => ({ ...link, id: link.field, label: labels ? link.field : undefined })) : []), - [plot, show, labels], - ); + const links = useMemo(() => overlayLinks(plot.links, region.edges), [plot, region.edges]); - const [container, setContainer] = useState<HTMLDivElement | null>(null); - const elements = useRef(new Map<string, HTMLElement>()).current; - const register = useCallback( - (key: string) => (el: HTMLElement | null) => { - if (el) elements.set(key, el); - else elements.delete(key); - }, - [elements], - ); + const { container, setContainer, elements, register } = useOccurrenceElements(); return ( <div diff --git a/packages/map-views/src/layouts/LandscapeLayout.tsx b/packages/map-views/src/layouts/LandscapeLayout.tsx index 7566ea1..0d49750 100644 --- a/packages/map-views/src/layouts/LandscapeLayout.tsx +++ b/packages/map-views/src/layouts/LandscapeLayout.tsx @@ -2,8 +2,8 @@ import { useMemo } from 'react'; import type { SpaceNode } from 'structured-context/api'; import type { LandscapeLayoutConfig, Orientation } from '../core/definition'; import { buildLandscape, type LandscapeOccurrence } from '../core/landscape'; +import type { LayoutProps } from './layout'; import { NodeCard } from './NodeCard'; -import type { LayoutProps } from './TreeLayout'; /** * Nested containers following the layout's grouping levels; the last level is drawn as nodes. diff --git a/packages/map-views/src/layouts/MapView.tsx b/packages/map-views/src/layouts/MapView.tsx index a6e42d0..09e8bff 100644 --- a/packages/map-views/src/layouts/MapView.tsx +++ b/packages/map-views/src/layouts/MapView.tsx @@ -1,12 +1,13 @@ -import { useId, useMemo } from 'react'; +import { type ComponentType, useId, useMemo } from 'react'; import type { SpaceGraph, SpaceNode } from 'structured-context/api'; import { type AnnotationIndex, filterAnnotations } from '../core/annotations'; -import { type MapViewDefinition, type ParameterValues, type Region, resolveRegions } from '../core/definition'; +import { type LayoutConfig, type MapViewDefinition, type ParameterValues, resolveRegions } from '../core/definition'; import { AnnotationsContext } from './annotations-context'; import { GraphLayout } from './GraphLayout'; import { LandscapeLayout } from './LandscapeLayout'; +import type { LayoutProps } from './layout'; import { NeighbourhoodLayout } from './NeighbourhoodLayout'; -import { type LayoutProps, TreeLayout } from './TreeLayout'; +import { TreeLayout } from './TreeLayout'; import { XYLayout } from './XYLayout'; type Props = { @@ -20,20 +21,29 @@ type Props = { */ annotations?: AnnotationIndex; onNodeSelect?: (node: SpaceNode) => void; - /** The node a neighbourhood layout centres on (see {@link NeighbourhoodLayout}). */ - focus?: SpaceNode['id']; - onFocusChange?: (id: SpaceNode['id']) => void; + focus?: LayoutProps['focus']; + onFocusChange?: LayoutProps['onFocusChange']; }; const EMPTY: AnnotationIndex = new Map(); +const LAYOUTS: { [T in LayoutConfig['type']]: ComponentType<LayoutProps<Extract<LayoutConfig, { type: T }>>> } = { + tree: TreeLayout, + landscape: LandscapeLayout, + xy: XYLayout, + neighbourhood: NeighbourhoodLayout, + graph: GraphLayout, +}; + /** Renders a map view definition against a space. Sizes to its container and scrolls within it. */ export function MapView({ definition, graph, values, annotations, onNodeSelect, focus, onFocusChange }: Props) { const instanceId = useId(); const regions = useMemo(() => resolveRegions(definition, values), [definition, values]); // PROTOTYPE: only the first region is rendered. Arranging several regions is undesigned (#8). const region = regions[0]!; - const props = { graph, instanceId, onNodeSelect }; + // TypeScript can't relate the region's layout type to the component it indexes. + const Layout = LAYOUTS[region.layout.type] as ComponentType<LayoutProps>; + const { validation, validationSources } = region.nodes; const visibleAnnotations = useMemo( () => (annotations ? filterAnnotations(annotations, validation, validationSources) : EMPTY), @@ -43,28 +53,15 @@ export function MapView({ definition, graph, values, annotations, onNodeSelect, return ( <AnnotationsContext.Provider value={visibleAnnotations}> <div className="mv:h-full mv:w-full mv:overflow-auto mv:bg-surface mv:text-ink"> - {layoutFor(region, props, { focus, onFocusChange })} + <Layout + graph={graph} + region={region} + instanceId={instanceId} + onNodeSelect={onNodeSelect} + focus={focus} + onFocusChange={onFocusChange} + /> </div> </AnnotationsContext.Provider> ); } - -function layoutFor( - region: Region, - props: Omit<LayoutProps, 'region'>, - neighbourhood: Pick<Props, 'focus' | 'onFocusChange'>, -) { - const { layout } = region; - switch (layout.type) { - case 'tree': - return <TreeLayout {...props} region={{ ...region, layout }} />; - case 'landscape': - return <LandscapeLayout {...props} region={{ ...region, layout }} />; - case 'xy': - return <XYLayout {...props} region={{ ...region, layout }} />; - case 'graph': - return <GraphLayout {...props} region={{ ...region, layout }} />; - case 'neighbourhood': - return <NeighbourhoodLayout {...props} {...neighbourhood} region={{ ...region, layout }} />; - } -} diff --git a/packages/map-views/src/layouts/NeighbourhoodLayout.tsx b/packages/map-views/src/layouts/NeighbourhoodLayout.tsx index 9daadb5..2e541b4 100644 --- a/packages/map-views/src/layouts/NeighbourhoodLayout.tsx +++ b/packages/map-views/src/layouts/NeighbourhoodLayout.tsx @@ -1,22 +1,23 @@ -import { useCallback, useMemo, useRef, useState } from 'react'; +import { useMemo, useState } from 'react'; import type { SpaceNode } from 'structured-context/api'; import type { NeighbourhoodLayoutConfig } from '../core/definition'; import { buildNeighbourhood, type Neighbour } from '../core/neighbourhood'; import { EdgeOverlay } from './EdgeOverlay'; +import { type LayoutProps, overlayLinks, useOccurrenceElements } from './layout'; import { NodeCard } from './NodeCard'; -import type { LayoutProps } from './TreeLayout'; - -type Props = LayoutProps<NeighbourhoodLayoutConfig> & { - /** The focus node; the layout keeps its own once the reader picks another. */ - focus?: SpaceNode['id']; - onFocusChange?: (id: SpaceNode['id']) => void; -}; /** * One node with its neighbours around it. Selecting a neighbour moves the focus to it; selecting * the focus is a regular node selection. */ -export function NeighbourhoodLayout({ graph, region, instanceId, onNodeSelect, focus, onFocusChange }: Props) { +export function NeighbourhoodLayout({ + graph, + region, + instanceId, + onNodeSelect, + focus, + onFocusChange, +}: LayoutProps<NeighbourhoodLayoutConfig>) { const [picked, setPicked] = useState<{ from: SpaceNode['id'] | undefined; id: SpaceNode['id'] }>(); // A focus the host sets later wins over the reader's earlier pick. const focusId = picked && picked.from === focus ? picked.id : focus; @@ -24,24 +25,9 @@ export function NeighbourhoodLayout({ graph, region, instanceId, onNodeSelect, f () => buildNeighbourhood(graph, region.id, region.layout, focusId), [graph, region.id, region.layout, focusId], ); - const { labels, show } = region.edges; - const links = useMemo( - () => - show - ? neighbourhood.links.map((link) => ({ ...link, id: link.field, label: labels ? link.field : undefined })) - : [], - [neighbourhood, show, labels], - ); + const links = useMemo(() => overlayLinks(neighbourhood.links, region.edges), [neighbourhood, region.edges]); - const [container, setContainer] = useState<HTMLDivElement | null>(null); - const elements = useRef(new Map<string, HTMLElement>()).current; - const register = useCallback( - (key: string) => (el: HTMLElement | null) => { - if (el) elements.set(key, el); - else elements.delete(key); - }, - [elements], - ); + const { container, setContainer, elements, register } = useOccurrenceElements(); if (!neighbourhood.focus) return null; const current = neighbourhood.focus.node; diff --git a/packages/map-views/src/layouts/TreeLayout.tsx b/packages/map-views/src/layouts/TreeLayout.tsx index d70d08c..d21fe5b 100644 --- a/packages/map-views/src/layouts/TreeLayout.tsx +++ b/packages/map-views/src/layouts/TreeLayout.tsx @@ -1,41 +1,19 @@ -import { useCallback, useMemo, useRef, useState } from 'react'; -import type { SpaceGraph, SpaceNode } from 'structured-context/api'; -import type { LayoutConfig, Orientation, Region, TreeLayoutConfig } from '../core/definition'; +import { useMemo } from 'react'; +import type { Orientation, TreeLayoutConfig } from '../core/definition'; import { buildTree, type TreeOccurrence, treeLinks } from '../core/tree'; import { EdgeOverlay } from './EdgeOverlay'; +import { type LayoutProps, overlayLinks, useOccurrenceElements } from './layout'; import { NodeCard } from './NodeCard'; -export type LayoutProps<L extends LayoutConfig = LayoutConfig> = { - graph: SpaceGraph; - /** The region with parameter values applied, narrowed to the layout's own settings. */ - region: Region & { layout: L }; - /** Scopes occurrence ids when several map views render in one document. */ - instanceId: string; - onNodeSelect?: (node: SpaceNode) => void; -}; - /** * Tree over the schema's hierarchy. Flexbox does the branching; the SVG overlay draws connectors. */ export function TreeLayout({ graph, region, instanceId, onNodeSelect }: LayoutProps<TreeLayoutConfig>) { const { orientation, dag } = region.layout; const tree = useMemo(() => buildTree(graph, region.id, dag), [graph, region.id, dag]); - const { show, labels } = region.edges; - const links = useMemo( - () => (show ? treeLinks(tree).map(({ field, ...link }) => ({ ...link, label: labels ? field : undefined })) : []), - [tree, show, labels], - ); + const links = useMemo(() => overlayLinks(treeLinks(tree), region.edges), [tree, region.edges]); - const [container, setContainer] = useState<HTMLDivElement | null>(null); - // Filled by ref callbacks during commit, read by the overlay's layout effect afterwards. - const elements = useRef(new Map<string, HTMLElement>()).current; - const register = useCallback( - (key: string) => (el: HTMLElement | null) => { - if (el) elements.set(key, el); - else elements.delete(key); - }, - [elements], - ); + const { container, setContainer, elements, register } = useOccurrenceElements(); const branch = (occurrence: TreeOccurrence) => ( <li diff --git a/packages/map-views/src/layouts/XYLayout.tsx b/packages/map-views/src/layouts/XYLayout.tsx index d8cfe49..616b1c5 100644 --- a/packages/map-views/src/layouts/XYLayout.tsx +++ b/packages/map-views/src/layouts/XYLayout.tsx @@ -1,9 +1,9 @@ -import { useCallback, useMemo, useRef, useState } from 'react'; +import { useMemo } from 'react'; import type { AxisConfig, XYLayoutConfig } from '../core/definition'; import { buildXYPlot } from '../core/xy'; import { EdgeOverlay } from './EdgeOverlay'; +import { type LayoutProps, overlayLinks, useOccurrenceElements } from './layout'; import { NodeCard } from './NodeCard'; -import type { LayoutProps } from './TreeLayout'; /** * Nodes positioned by two numeric fields, with straight connectors between them. Positions are @@ -17,29 +17,15 @@ export function XYLayout({ graph, region, instanceId, onNodeSelect }: LayoutProp // Relationship edges (flows, pipelines) are dashed, to tell them from the value chain. const links = useMemo( () => - region.edges.show - ? plot.links.map(({ from, to, field, hierarchy, lane }) => ({ - from, - to, - id: field, - lane, - kind: hierarchy ? ('tree' as const) : ('cross' as const), - label: region.edges.labels ? field : undefined, - })) - : [], - [plot, region.edges.show, region.edges.labels], + overlayLinks( + plot.links.map((link) => ({ ...link, kind: link.hierarchy ? ('tree' as const) : ('cross' as const) })), + region.edges, + ), + [plot, region.edges], ); const shape = region.nodes.style === 'shape'; - const [container, setContainer] = useState<HTMLDivElement | null>(null); - const elements = useRef(new Map<string, HTMLElement>()).current; - const register = useCallback( - (key: string) => (el: HTMLElement | null) => { - if (el) elements.set(key, el); - else elements.delete(key); - }, - [elements], - ); + const { container, setContainer, elements, register } = useOccurrenceElements(); return ( <div className="mv:box-border mv:flex mv:h-full mv:min-h-[28rem] mv:min-w-[36rem] mv:flex-col mv:gap-4 mv:p-4"> diff --git a/packages/map-views/src/layouts/layout.ts b/packages/map-views/src/layouts/layout.ts new file mode 100644 index 0000000..9e2d97d --- /dev/null +++ b/packages/map-views/src/layouts/layout.ts @@ -0,0 +1,38 @@ +import { useCallback, useRef, useState } from 'react'; +import type { SpaceGraph, SpaceNode } from 'structured-context/api'; +import type { EdgesConfig, LayoutConfig, Region } from '../core/definition'; +import type { Link } from './EdgeOverlay'; + +export type LayoutProps<L extends LayoutConfig = LayoutConfig> = { + graph: SpaceGraph; + /** The region with parameter values applied, narrowed to the layout's own settings. */ + region: Region & { layout: L }; + /** Scopes occurrence ids when several map views render in one document. */ + instanceId: string; + onNodeSelect?: (node: SpaceNode) => void; + /** The node a layout that centres on one node shows; the layout keeps its own once the reader picks another. */ + focus?: SpaceNode['id']; + onFocusChange?: (id: SpaceNode['id']) => void; +}; + +/** Connects a layout's occurrences to its `EdgeOverlay`: `register` fills `elements` during commit, ahead of the overlay's layout effect. */ +export function useOccurrenceElements() { + const [container, setContainer] = useState<HTMLDivElement | null>(null); + const elements = useRef(new Map<string, HTMLElement>()).current; + const register = useCallback( + (key: string) => (el: HTMLElement | null) => { + if (el) elements.set(key, el); + else elements.delete(key); + }, + [elements], + ); + return { container, setContainer, elements, register }; +} + +/** A layout's links as the overlay draws them, following the region's `edges` settings. */ +export function overlayLinks<L extends Omit<Link, 'id' | 'label'> & { field?: string }>( + links: readonly L[], + { show, labels }: EdgesConfig, +): Link[] { + return show ? links.map(({ field, ...link }) => ({ ...link, id: field, label: labels ? field : undefined })) : []; +} diff --git a/packages/map-views/src/viewer/Viewer.tsx b/packages/map-views/src/viewer/Viewer.tsx index f4c1dce..c5b0d13 100644 --- a/packages/map-views/src/viewer/Viewer.tsx +++ b/packages/map-views/src/viewer/Viewer.tsx @@ -7,9 +7,8 @@ import { MapView } from '../layouts/MapView'; import { ParameterControls } from '../layouts/ParameterControls'; /** - * A page-filling viewer for one or more space snapshots: a space and map view switcher, the parameter - * controls, the map view, and a side panel with the selected node's fields and validation results. Hosts - * supply the snapshots and anything specific to where the page is shown. See docs/architecture.md. + * A page-filling viewer for one or more space snapshots. Hosts supply the snapshots and anything + * specific to where the page is shown. See docs/architecture.md. */ export type ViewerProps = { diff --git a/packages/map-views/tests/load-definitions.test.ts b/packages/map-views/tests/load-definitions.test.ts index 81005cf..655af37 100644 --- a/packages/map-views/tests/load-definitions.test.ts +++ b/packages/map-views/tests/load-definitions.test.ts @@ -17,13 +17,9 @@ function write(path: string, text: string) { } const definition = (id: string) => `{ $id: '${id}', schema: 'sctx://x', regions: [{ id: 'main', layout: { type: 'tree' } }] }`; -const BUNDLED = [ - 'sctx-map-view://core/graph', - 'sctx-map-view://core/neighbourhood', - 'sctx-map-view://core/strategy-tree', - 'sctx-map-view://core/tree', -]; const noSpaces: Config = { spaces: [] }; +// A config folder with nothing in it, so only the library's definitions are found. +const bundled = () => loadMapViewDefinitions(noSpaces, { configDir: join(root, 'empty') }).map((d) => d.id); const ids = (config: Config, configDir = join(root, 'config')) => loadMapViewDefinitions(config, { configDir }).map((d) => d.id); @@ -34,7 +30,7 @@ describe('loadMapViewDefinitions', () => { write('config/.sctx/plugins/sctx-declared/views/b.json5', definition('sctx-map-view://declared/b')); write('config/.sctx/map-views/c.json5', definition('sctx-map-view://c')); expect(ids(noSpaces)).toEqual([ - ...BUNDLED, + ...bundled(), 'sctx-map-view://conventional/a', 'sctx-map-view://declared/b', 'sctx-map-view://c', @@ -54,7 +50,7 @@ describe('loadMapViewDefinitions', () => { }, ], }; - expect(ids(config)).toEqual([...BUNDLED, 'sctx-map-view://named/a', 'sctx-map-view://b']); + expect(ids(config)).toEqual([...bundled(), 'sctx-map-view://named/a', 'sctx-map-view://b']); }); test.each([ diff --git a/packages/map-views/tests/snapshot.test.ts b/packages/map-views/tests/snapshot.test.ts index a404944..7a99fc9 100644 --- a/packages/map-views/tests/snapshot.test.ts +++ b/packages/map-views/tests/snapshot.test.ts @@ -10,7 +10,7 @@ describe('exportSnapshot', () => { const config = loadConfig({ startDir: sample }); const result = await exportSnapshot('launch-playbook', config, sample); expect(result.space).toBe('launch-playbook'); - expect(result.graph.formatVersion).toBe(1); + expect(result.graph.nodes.length).toBeGreaterThan(0); expect(result.validation).toHaveProperty('issues'); expect(result.definitions.every((d) => d.schema === undefined || d.schema === result.schemaId)).toBe(true); expect(JSON.parse(JSON.stringify(result))).toEqual(result); diff --git a/packages/sctx-map-views/tests/render.test.ts b/packages/sctx-map-views/tests/render.test.ts index 82a0771..573b4fc 100644 --- a/packages/sctx-map-views/tests/render.test.ts +++ b/packages/sctx-map-views/tests/render.test.ts @@ -47,10 +47,7 @@ describe('map-views.html', () => { const page = await render(context().context); const [snapshot] = snapshotsOf(page); expect(snapshot!.space).toBe('demo'); - const ids = snapshot!.definitions.map((d) => d.id); - expect(ids).toContain('sctx-map-view://mine'); - expect(ids).toContain('sctx-map-view://core/graph'); - expect(ids).not.toContain('sctx-map-view://core/strategy-tree'); + expect(snapshot!.definitions.map((d) => d.id)).toContain('sctx-map-view://mine'); }); test('passes validation options from -d', async () => { From 588d49a37f5d18f667078dcc6d593c193027ba14 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Mon, 16 Nov 2026 05:48:34 +0000 Subject: [PATCH 06/15] Organise core by layout: layouts/<name>/{schema,projection}.ts, schema/ for the shared format, no barrel Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019XphpcKhuNyHcNArHFELR4 --- AGENTS.md | 4 +-- docs/architecture.md | 2 +- .../map-views/scripts/generate-schemas.ts | 6 ++-- packages/map-views/src/core/definition.ts | 30 +++++++++++-------- packages/map-views/src/core/format/index.ts | 29 ------------------ .../{force.ts => layouts/graph/projection.ts} | 8 ++--- .../graph/schema.ts} | 4 +-- .../landscape/projection.ts} | 6 ++-- .../landscape/schema.ts} | 4 +-- .../map-views/src/core/{ => layouts}/lanes.ts | 0 .../neighbourhood/projection.ts} | 8 ++--- .../neighbourhood/schema.ts} | 4 +-- .../{tree.ts => layouts/tree/projection.ts} | 6 ++-- .../tree-layout.ts => layouts/tree/schema.ts} | 4 +-- .../core/{xy.ts => layouts/xy/projection.ts} | 8 ++--- .../xy-layout.ts => layouts/xy/schema.ts} | 4 +-- .../{format => schema}/definition-schema.ts | 0 .../src/core/{format => schema}/param-ref.ts | 0 .../src/core/{format => schema}/schema-url.ts | 0 .../src/core/{format => schema}/settings.ts | 0 packages/map-views/src/index.ts | 2 +- .../map-views/src/layouts/GraphLayout.tsx | 2 +- .../map-views/src/layouts/LandscapeLayout.tsx | 2 +- .../src/layouts/NeighbourhoodLayout.tsx | 2 +- packages/map-views/src/layouts/TreeLayout.tsx | 2 +- packages/map-views/src/layouts/XYLayout.tsx | 2 +- packages/map-views/tests/definition.test.ts | 2 +- packages/map-views/tests/force.test.ts | 2 +- packages/map-views/tests/landscape.test.ts | 2 +- .../map-views/tests/neighbourhood.test.ts | 2 +- packages/map-views/tests/tree.test.ts | 2 +- packages/map-views/tests/xy.test.ts | 2 +- 32 files changed, 64 insertions(+), 87 deletions(-) delete mode 100644 packages/map-views/src/core/format/index.ts rename packages/map-views/src/core/{force.ts => layouts/graph/projection.ts} (93%) rename packages/map-views/src/core/{format/graph-layout.ts => layouts/graph/schema.ts} (86%) rename packages/map-views/src/core/{landscape.ts => layouts/landscape/projection.ts} (97%) rename packages/map-views/src/core/{format/landscape-layout.ts => layouts/landscape/schema.ts} (96%) rename packages/map-views/src/core/{ => layouts}/lanes.ts (100%) rename packages/map-views/src/core/{neighbourhood.ts => layouts/neighbourhood/projection.ts} (93%) rename packages/map-views/src/core/{format/neighbourhood-layout.ts => layouts/neighbourhood/schema.ts} (91%) rename packages/map-views/src/core/{tree.ts => layouts/tree/projection.ts} (96%) rename packages/map-views/src/core/{format/tree-layout.ts => layouts/tree/schema.ts} (90%) rename packages/map-views/src/core/{xy.ts => layouts/xy/projection.ts} (94%) rename packages/map-views/src/core/{format/xy-layout.ts => layouts/xy/schema.ts} (94%) rename packages/map-views/src/core/{format => schema}/definition-schema.ts (100%) rename packages/map-views/src/core/{format => schema}/param-ref.ts (100%) rename packages/map-views/src/core/{format => schema}/schema-url.ts (100%) rename packages/map-views/src/core/{format => schema}/settings.ts (100%) diff --git a/AGENTS.md b/AGENTS.md index 41970ee..ad21aca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,7 +12,7 @@ Declarative map views of structured-context spaces: the definition format, the r - `packages/sctx-map-views`: the structured-context render plugin (format `map-views.html`), bundling the library's page template and `/html` entry. It reads everything through the render callbacks and has no structured-context dependency at runtime: its bundle imports nothing from it, and `test:package` checks that. - `apps/navigator`: the standalone host (private package: a Vite app plus dev-server middleware calling the structured-context API). It consumes the library like any other host. - `packages/map-views/map-views/*.json5`: definitions bundled with the library (`$id` `sctx-map-view://core/<name>`): ones that suit any schema (no `schema`), and ones for structured-context's bundled schemas. `bun run generate:definitions` embeds them as `src/node/bundled-definitions.ts`; a test fails if that is stale. Plugins ship their own; personal ones go in the config root's `.sctx/map-views/` (structured-context's `resourceDir`). -- `packages/map-views/src/core/format/*.ts`: the definition format's JSON Schemas (`as const`), the source of truth. Types derive from them (`FromSchema`); `bun run generate:schemas` writes `schemas/generated/latest/` at the repo root (so the published URLs stay stable), and a test fails if those are stale; `--release` (run when cutting a release) also freezes `schemas/generated/<version>/` if the format changed. `$id`s are the published https URLs (`schema-url.ts`). Use absolute `${SCHEMA_URL}/…` refs: `FromSchema` doesn't resolve relative refs inside referenced schemas. +- `packages/map-views/src/core/schema/` and each layout's `schema.ts` in `src/core/layouts/<name>/`: the definition format's JSON Schemas (`as const`), the source of truth. Types derive from them (`FromSchema`); `bun run generate:schemas` writes `schemas/generated/latest/` at the repo root (so the published URLs stay stable), and a test fails if those are stale; `--release` (run when cutting a release) also freezes `schemas/generated/<version>/` if the format changed. `$id`s are the published https URLs (`schema-url.ts`). Use absolute `${SCHEMA_URL}/…` refs: `FromSchema` doesn't resolve relative refs inside referenced schemas. - `samples/launch-playbook/`: a public sample space. `packages/map-views/tests/fixtures/launch-playbook.json` is captured from it with `bun run capture-fixtures launch-playbook=../../samples/launch-playbook/.sctx.json` in `packages/map-views`. ## Checks @@ -41,7 +41,7 @@ Review and update with any change: | Change | Check | |---|---| -| Definition format (`core/format`) | `docs/definitions.md`, `docs/layouts.md` for layout settings; regenerated `schemas/generated/`; definitions in `map-views/` | +| Definition format (`core/schema`, `core/layouts/*/schema.ts`) | `docs/definitions.md`, `docs/layouts.md` for layout settings; regenerated `schemas/generated/`; definitions in `map-views/` | | New or renamed term | `docs/concepts.md` | | Exports or component props | `docs/api.md` | | Module structure, rendering, styling | `docs/architecture.md`, this file | diff --git a/docs/architecture.md b/docs/architecture.md index b28173a..fd78110 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -32,7 +32,7 @@ Hosts can also pass validation results as an `AnnotationIndex` (`core/annotation ## Projections -Each layout has a pure projection in core that turns the graph and the region's resolved settings into occurrences and links, ready for a layout component to draw. [Layouts](layouts.md) describes each one. +Each layout has a folder in `core/layouts/` holding its settings schema and a pure projection. The projection turns the graph and the region's resolved settings into occurrences and links, ready for a layout component to draw. [Layouts](layouts.md) describes each one. Occurrence keys are paths (region, ancestors, node), so a node appearing several times gets distinct keys. diff --git a/packages/map-views/scripts/generate-schemas.ts b/packages/map-views/scripts/generate-schemas.ts index 2631f2c..2f43220 100644 --- a/packages/map-views/scripts/generate-schemas.ts +++ b/packages/map-views/scripts/generate-schemas.ts @@ -1,6 +1,6 @@ /** * Write the map view definition schemas as JSON, for `$schema` references and editors. - * The TypeScript sources in src/core/format are the source of truth. + * The TypeScript sources under src/core (schema/ and each layout's schema.ts) are the source of truth. * * bun run generate:schemas writes generated/latest/ * bun run generate:schemas --release also freezes generated/<version>/ when the format changed @@ -11,8 +11,8 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import pkg from '../package.json'; -import { MAP_VIEW_SCHEMAS } from '../src/core/format'; -import { SCHEMA_BASE_URL, SCHEMA_URL } from '../src/core/format/schema-url'; +import { MAP_VIEW_SCHEMAS } from '../src/core/definition'; +import { SCHEMA_BASE_URL, SCHEMA_URL } from '../src/core/schema/schema-url'; export const GENERATED_DIR = join(import.meta.dir, '../../../schemas/generated'); const VERSION_FOLDER = /^\d+\.\d+\.\d+$/; diff --git a/packages/map-views/src/core/definition.ts b/packages/map-views/src/core/definition.ts index ea21db0..0600477 100644 --- a/packages/map-views/src/core/definition.ts +++ b/packages/map-views/src/core/definition.ts @@ -1,19 +1,25 @@ import Ajv2020, { type AnySchemaObject, type ErrorObject } from 'ajv/dist/2020'; import type { FromSchema } from 'json-schema-to-ts'; import JSON5 from 'json5'; -import { +import { graphLayoutSchema } from './layouts/graph/schema'; +import { landscapeLayoutSchema } from './layouts/landscape/schema'; +import { neighbourhoodLayoutSchema } from './layouts/neighbourhood/schema'; +import { treeLayoutSchema } from './layouts/tree/schema'; +import { xyLayoutSchema } from './layouts/xy/schema'; +import { definitionSchema } from './schema/definition-schema'; +import { SCHEMA_URL } from './schema/schema-url'; +import { settingsSchema } from './schema/settings'; + +/** The bundled schemas describing the map view definition format. */ +export const MAP_VIEW_SCHEMAS = [ definitionSchema, - type graphLayoutSchema, - type landscapeLayoutSchema, - MAP_VIEW_SCHEMAS, - type neighbourhoodLayoutSchema, - type settingsSchema, - type treeLayoutSchema, - type xyLayoutSchema, -} from './format'; -import { SCHEMA_URL } from './format/schema-url'; - -export { MAP_VIEW_SCHEMAS }; + settingsSchema, + treeLayoutSchema, + landscapeLayoutSchema, + xyLayoutSchema, + neighbourhoodLayoutSchema, + graphLayoutSchema, +] as const; type References = { references: [ diff --git a/packages/map-views/src/core/format/index.ts b/packages/map-views/src/core/format/index.ts deleted file mode 100644 index ebf07a3..0000000 --- a/packages/map-views/src/core/format/index.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { definitionSchema } from './definition-schema'; -import { graphLayoutSchema } from './graph-layout'; -import { landscapeLayoutSchema } from './landscape-layout'; -import { neighbourhoodLayoutSchema } from './neighbourhood-layout'; -import { settingsSchema } from './settings'; -import { treeLayoutSchema } from './tree-layout'; -import { xyLayoutSchema } from './xy-layout'; - -export { PARAM_REF } from './param-ref'; -export { - definitionSchema, - graphLayoutSchema, - landscapeLayoutSchema, - neighbourhoodLayoutSchema, - settingsSchema, - treeLayoutSchema, - xyLayoutSchema, -}; - -/** The bundled schemas describing the map view definition format. */ -export const MAP_VIEW_SCHEMAS = [ - definitionSchema, - settingsSchema, - treeLayoutSchema, - landscapeLayoutSchema, - xyLayoutSchema, - neighbourhoodLayoutSchema, - graphLayoutSchema, -] as const; diff --git a/packages/map-views/src/core/force.ts b/packages/map-views/src/core/layouts/graph/projection.ts similarity index 93% rename from packages/map-views/src/core/force.ts rename to packages/map-views/src/core/layouts/graph/projection.ts index 34bfd71..62cd80d 100644 --- a/packages/map-views/src/core/force.ts +++ b/packages/map-views/src/core/layouts/graph/projection.ts @@ -1,9 +1,9 @@ import { forceCollide, forceLink, forceManyBody, forceSimulation, forceX, forceY } from 'd3-force'; import type { SpaceGraph, SpaceNode } from 'structured-context/api'; -import type { GraphLayoutConfig } from './definition'; -import { edgesWithin } from './graph'; -import { assignLanes } from './lanes'; -import { occurrenceKey } from './occurrence'; +import type { GraphLayoutConfig } from '../../definition'; +import { edgesWithin } from '../../graph'; +import { occurrenceKey } from '../../occurrence'; +import { assignLanes } from '../lanes'; /** A positioned node; `x` and `y` are pixels from the top left of the plot. */ export type ForcePoint = { key: string; node: SpaceNode; x: number; y: number }; diff --git a/packages/map-views/src/core/format/graph-layout.ts b/packages/map-views/src/core/layouts/graph/schema.ts similarity index 86% rename from packages/map-views/src/core/format/graph-layout.ts rename to packages/map-views/src/core/layouts/graph/schema.ts index 0bc114f..6581e04 100644 --- a/packages/map-views/src/core/format/graph-layout.ts +++ b/packages/map-views/src/core/layouts/graph/schema.ts @@ -1,5 +1,5 @@ -import { parameterisable } from './param-ref'; -import { SCHEMA_URL } from './schema-url'; +import { parameterisable } from '../../schema/param-ref'; +import { SCHEMA_URL } from '../../schema/schema-url'; /** Settings of the graph layout: every node and edge, positioned by a force simulation. */ export const graphLayoutSchema = { diff --git a/packages/map-views/src/core/landscape.ts b/packages/map-views/src/core/layouts/landscape/projection.ts similarity index 97% rename from packages/map-views/src/core/landscape.ts rename to packages/map-views/src/core/layouts/landscape/projection.ts index 4f5ca0f..b09e98d 100644 --- a/packages/map-views/src/core/landscape.ts +++ b/packages/map-views/src/core/layouts/landscape/projection.ts @@ -1,7 +1,7 @@ import type { SpaceGraph, SpaceNode } from 'structured-context/api'; -import type { GroupLevel, LandscapeLayoutConfig } from './definition'; -import { childEdges, parentEdges } from './graph'; -import { occurrenceKey, type PathSegment } from './occurrence'; +import type { GroupLevel, LandscapeLayoutConfig } from '../../definition'; +import { childEdges, parentEdges } from '../../graph'; +import { occurrenceKey, type PathSegment } from '../../occurrence'; /** One rendered container or node in a landscape. */ export type LandscapeOccurrence = { diff --git a/packages/map-views/src/core/format/landscape-layout.ts b/packages/map-views/src/core/layouts/landscape/schema.ts similarity index 96% rename from packages/map-views/src/core/format/landscape-layout.ts rename to packages/map-views/src/core/layouts/landscape/schema.ts index d1ff449..f5e3954 100644 --- a/packages/map-views/src/core/format/landscape-layout.ts +++ b/packages/map-views/src/core/layouts/landscape/schema.ts @@ -1,5 +1,5 @@ -import { PARAM_REF, parameterisable } from './param-ref'; -import { SCHEMA_URL } from './schema-url'; +import { PARAM_REF, parameterisable } from '../../schema/param-ref'; +import { SCHEMA_URL } from '../../schema/schema-url'; /** Settings of the landscape layout: nested containers following an authored grouping. */ export const landscapeLayoutSchema = { diff --git a/packages/map-views/src/core/lanes.ts b/packages/map-views/src/core/layouts/lanes.ts similarity index 100% rename from packages/map-views/src/core/lanes.ts rename to packages/map-views/src/core/layouts/lanes.ts diff --git a/packages/map-views/src/core/neighbourhood.ts b/packages/map-views/src/core/layouts/neighbourhood/projection.ts similarity index 93% rename from packages/map-views/src/core/neighbourhood.ts rename to packages/map-views/src/core/layouts/neighbourhood/projection.ts index bc6d55d..9b08eaa 100644 --- a/packages/map-views/src/core/neighbourhood.ts +++ b/packages/map-views/src/core/layouts/neighbourhood/projection.ts @@ -1,8 +1,8 @@ import type { SpaceGraph, SpaceNode } from 'structured-context/api'; -import type { NeighbourhoodLayoutConfig } from './definition'; -import { childEdges, parentEdges } from './graph'; -import { assignLanes } from './lanes'; -import { occurrenceKey } from './occurrence'; +import type { NeighbourhoodLayoutConfig } from '../../definition'; +import { childEdges, parentEdges } from '../../graph'; +import { occurrenceKey } from '../../occurrence'; +import { assignLanes } from '../lanes'; export type NeighbourhoodRole = 'left' | 'right' | 'above' | 'below' | 'around'; diff --git a/packages/map-views/src/core/format/neighbourhood-layout.ts b/packages/map-views/src/core/layouts/neighbourhood/schema.ts similarity index 91% rename from packages/map-views/src/core/format/neighbourhood-layout.ts rename to packages/map-views/src/core/layouts/neighbourhood/schema.ts index 9958c84..09fad5e 100644 --- a/packages/map-views/src/core/format/neighbourhood-layout.ts +++ b/packages/map-views/src/core/layouts/neighbourhood/schema.ts @@ -1,5 +1,5 @@ -import { parameterisable } from './param-ref'; -import { SCHEMA_URL } from './schema-url'; +import { parameterisable } from '../../schema/param-ref'; +import { SCHEMA_URL } from '../../schema/schema-url'; const roleFields = (description: string) => parameterisable({ $ref: `${SCHEMA_URL}/settings.json#/$defs/fieldList` }, [], description); diff --git a/packages/map-views/src/core/tree.ts b/packages/map-views/src/core/layouts/tree/projection.ts similarity index 96% rename from packages/map-views/src/core/tree.ts rename to packages/map-views/src/core/layouts/tree/projection.ts index cb3f46c..4114e73 100644 --- a/packages/map-views/src/core/tree.ts +++ b/packages/map-views/src/core/layouts/tree/projection.ts @@ -1,7 +1,7 @@ import type { SpaceGraph, SpaceNode } from 'structured-context/api'; -import type { DagMode } from './definition'; -import { childEdges, isHierarchyEdge, parentEdges } from './graph'; -import { occurrenceKey } from './occurrence'; +import type { DagMode } from '../../definition'; +import { childEdges, isHierarchyEdge, parentEdges } from '../../graph'; +import { occurrenceKey } from '../../occurrence'; /** One rendered appearance of a node in a tree. */ export type TreeOccurrence = { diff --git a/packages/map-views/src/core/format/tree-layout.ts b/packages/map-views/src/core/layouts/tree/schema.ts similarity index 90% rename from packages/map-views/src/core/format/tree-layout.ts rename to packages/map-views/src/core/layouts/tree/schema.ts index 017a1c9..30bdbcf 100644 --- a/packages/map-views/src/core/format/tree-layout.ts +++ b/packages/map-views/src/core/layouts/tree/schema.ts @@ -1,5 +1,5 @@ -import { parameterisable } from './param-ref'; -import { SCHEMA_URL } from './schema-url'; +import { parameterisable } from '../../schema/param-ref'; +import { SCHEMA_URL } from '../../schema/schema-url'; /** Settings of the tree layout: a tree over the schema's hierarchy. */ export const treeLayoutSchema = { diff --git a/packages/map-views/src/core/xy.ts b/packages/map-views/src/core/layouts/xy/projection.ts similarity index 94% rename from packages/map-views/src/core/xy.ts rename to packages/map-views/src/core/layouts/xy/projection.ts index 32993e0..a08013c 100644 --- a/packages/map-views/src/core/xy.ts +++ b/packages/map-views/src/core/layouts/xy/projection.ts @@ -1,8 +1,8 @@ import type { SpaceGraph, SpaceNode } from 'structured-context/api'; -import type { AxisConfig, XYLayoutConfig } from './definition'; -import { edgesWithin, isHierarchyEdge } from './graph'; -import { assignLanes } from './lanes'; -import { occurrenceKey } from './occurrence'; +import type { AxisConfig, XYLayoutConfig } from '../../definition'; +import { edgesWithin, isHierarchyEdge } from '../../graph'; +import { occurrenceKey } from '../../occurrence'; +import { assignLanes } from '../lanes'; /** A plotted node. `x` and `y` run from 0 to 1 across the plot, left to right and bottom to top. */ export type XYPoint = { key: string; node: SpaceNode; x: number; y: number }; diff --git a/packages/map-views/src/core/format/xy-layout.ts b/packages/map-views/src/core/layouts/xy/schema.ts similarity index 94% rename from packages/map-views/src/core/format/xy-layout.ts rename to packages/map-views/src/core/layouts/xy/schema.ts index 4c81274..e6b0f09 100644 --- a/packages/map-views/src/core/format/xy-layout.ts +++ b/packages/map-views/src/core/layouts/xy/schema.ts @@ -1,5 +1,5 @@ -import { PARAM_REF, parameterisable } from './param-ref'; -import { SCHEMA_URL } from './schema-url'; +import { PARAM_REF, parameterisable } from '../../schema/param-ref'; +import { SCHEMA_URL } from '../../schema/schema-url'; /** Settings of the XY layout: nodes positioned by two numeric fields. */ export const xyLayoutSchema = { diff --git a/packages/map-views/src/core/format/definition-schema.ts b/packages/map-views/src/core/schema/definition-schema.ts similarity index 100% rename from packages/map-views/src/core/format/definition-schema.ts rename to packages/map-views/src/core/schema/definition-schema.ts diff --git a/packages/map-views/src/core/format/param-ref.ts b/packages/map-views/src/core/schema/param-ref.ts similarity index 100% rename from packages/map-views/src/core/format/param-ref.ts rename to packages/map-views/src/core/schema/param-ref.ts diff --git a/packages/map-views/src/core/format/schema-url.ts b/packages/map-views/src/core/schema/schema-url.ts similarity index 100% rename from packages/map-views/src/core/format/schema-url.ts rename to packages/map-views/src/core/schema/schema-url.ts diff --git a/packages/map-views/src/core/format/settings.ts b/packages/map-views/src/core/schema/settings.ts similarity index 100% rename from packages/map-views/src/core/format/settings.ts rename to packages/map-views/src/core/schema/settings.ts diff --git a/packages/map-views/src/index.ts b/packages/map-views/src/index.ts index e75a23b..fb8e29a 100644 --- a/packages/map-views/src/index.ts +++ b/packages/map-views/src/index.ts @@ -25,7 +25,7 @@ export { selectionFilter, viewValidationLevel, } from './core/definition'; -export { buildTree, type Tree, type TreeOccurrence } from './core/tree'; +export { buildTree, type Tree, type TreeOccurrence } from './core/layouts/tree/projection'; export { MapView } from './layouts/MapView'; export { ParameterControls } from './layouts/ParameterControls'; export { diff --git a/packages/map-views/src/layouts/GraphLayout.tsx b/packages/map-views/src/layouts/GraphLayout.tsx index bb7f104..b8f267b 100644 --- a/packages/map-views/src/layouts/GraphLayout.tsx +++ b/packages/map-views/src/layouts/GraphLayout.tsx @@ -1,6 +1,6 @@ import { useMemo } from 'react'; import type { GraphLayoutConfig } from '../core/definition'; -import { buildForceGraph } from '../core/force'; +import { buildForceGraph } from '../core/layouts/graph/projection'; import { EdgeOverlay } from './EdgeOverlay'; import { type LayoutProps, overlayLinks, useOccurrenceElements } from './layout'; import { NodeCard } from './NodeCard'; diff --git a/packages/map-views/src/layouts/LandscapeLayout.tsx b/packages/map-views/src/layouts/LandscapeLayout.tsx index 0d49750..d5f0188 100644 --- a/packages/map-views/src/layouts/LandscapeLayout.tsx +++ b/packages/map-views/src/layouts/LandscapeLayout.tsx @@ -1,7 +1,7 @@ import { useMemo } from 'react'; import type { SpaceNode } from 'structured-context/api'; import type { LandscapeLayoutConfig, Orientation } from '../core/definition'; -import { buildLandscape, type LandscapeOccurrence } from '../core/landscape'; +import { buildLandscape, type LandscapeOccurrence } from '../core/layouts/landscape/projection'; import type { LayoutProps } from './layout'; import { NodeCard } from './NodeCard'; diff --git a/packages/map-views/src/layouts/NeighbourhoodLayout.tsx b/packages/map-views/src/layouts/NeighbourhoodLayout.tsx index 2e541b4..51ea63d 100644 --- a/packages/map-views/src/layouts/NeighbourhoodLayout.tsx +++ b/packages/map-views/src/layouts/NeighbourhoodLayout.tsx @@ -1,7 +1,7 @@ import { useMemo, useState } from 'react'; import type { SpaceNode } from 'structured-context/api'; import type { NeighbourhoodLayoutConfig } from '../core/definition'; -import { buildNeighbourhood, type Neighbour } from '../core/neighbourhood'; +import { buildNeighbourhood, type Neighbour } from '../core/layouts/neighbourhood/projection'; import { EdgeOverlay } from './EdgeOverlay'; import { type LayoutProps, overlayLinks, useOccurrenceElements } from './layout'; import { NodeCard } from './NodeCard'; diff --git a/packages/map-views/src/layouts/TreeLayout.tsx b/packages/map-views/src/layouts/TreeLayout.tsx index d21fe5b..af5549a 100644 --- a/packages/map-views/src/layouts/TreeLayout.tsx +++ b/packages/map-views/src/layouts/TreeLayout.tsx @@ -1,6 +1,6 @@ import { useMemo } from 'react'; import type { Orientation, TreeLayoutConfig } from '../core/definition'; -import { buildTree, type TreeOccurrence, treeLinks } from '../core/tree'; +import { buildTree, type TreeOccurrence, treeLinks } from '../core/layouts/tree/projection'; import { EdgeOverlay } from './EdgeOverlay'; import { type LayoutProps, overlayLinks, useOccurrenceElements } from './layout'; import { NodeCard } from './NodeCard'; diff --git a/packages/map-views/src/layouts/XYLayout.tsx b/packages/map-views/src/layouts/XYLayout.tsx index 616b1c5..ea3201a 100644 --- a/packages/map-views/src/layouts/XYLayout.tsx +++ b/packages/map-views/src/layouts/XYLayout.tsx @@ -1,6 +1,6 @@ import { useMemo } from 'react'; import type { AxisConfig, XYLayoutConfig } from '../core/definition'; -import { buildXYPlot } from '../core/xy'; +import { buildXYPlot } from '../core/layouts/xy/projection'; import { EdgeOverlay } from './EdgeOverlay'; import { type LayoutProps, overlayLinks, useOccurrenceElements } from './layout'; import { NodeCard } from './NodeCard'; diff --git a/packages/map-views/tests/definition.test.ts b/packages/map-views/tests/definition.test.ts index 9ec3582..b82d216 100644 --- a/packages/map-views/tests/definition.test.ts +++ b/packages/map-views/tests/definition.test.ts @@ -7,7 +7,7 @@ import { resolveRegions, selectionFilter, } from '../src/core/definition'; -import { SCHEMA_URL } from '../src/core/format/schema-url'; +import { SCHEMA_URL } from '../src/core/schema/schema-url'; const minimal = `{ $id: 'sctx-map-view://t', schema: 'sctx://x', regions: [{ id: 'main', layout: { type: 'tree' } }] }`; diff --git a/packages/map-views/tests/force.test.ts b/packages/map-views/tests/force.test.ts index 79a4cb4..bdc76f2 100644 --- a/packages/map-views/tests/force.test.ts +++ b/packages/map-views/tests/force.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'bun:test'; import type { GraphLayoutConfig } from '../src/core/definition'; -import { buildForceGraph } from '../src/core/force'; +import { buildForceGraph } from '../src/core/layouts/graph/projection'; import { fixtureGraph } from './fixture-graph'; import sample from './fixtures/launch-playbook.json'; diff --git a/packages/map-views/tests/landscape.test.ts b/packages/map-views/tests/landscape.test.ts index 4d0ad71..59febb8 100644 --- a/packages/map-views/tests/landscape.test.ts +++ b/packages/map-views/tests/landscape.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'bun:test'; import type { LandscapeLayoutConfig } from '../src/core/definition'; -import { buildLandscape, type LandscapeOccurrence } from '../src/core/landscape'; +import { buildLandscape, type LandscapeOccurrence } from '../src/core/layouts/landscape/projection'; import { fixtureGraph } from './fixture-graph'; import sample from './fixtures/launch-playbook.json'; diff --git a/packages/map-views/tests/neighbourhood.test.ts b/packages/map-views/tests/neighbourhood.test.ts index 0f30e2d..c5f5433 100644 --- a/packages/map-views/tests/neighbourhood.test.ts +++ b/packages/map-views/tests/neighbourhood.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from 'bun:test'; import { buildSpaceGraph } from 'structured-context/api'; import type { NeighbourhoodLayoutConfig } from '../src/core/definition'; -import { buildNeighbourhood } from '../src/core/neighbourhood'; +import { buildNeighbourhood } from '../src/core/layouts/neighbourhood/projection'; import { makeParentRef, makeSpaceNode } from './builders'; const rel = (id: string, field: string) => makeParentRef(id, { kind: 'relationship', field }); diff --git a/packages/map-views/tests/tree.test.ts b/packages/map-views/tests/tree.test.ts index 1f740d4..d7db9e6 100644 --- a/packages/map-views/tests/tree.test.ts +++ b/packages/map-views/tests/tree.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'bun:test'; import { buildSpaceGraph } from 'structured-context/api'; -import { buildTree, type TreeOccurrence, treeLinks } from '../src/core/tree'; +import { buildTree, type TreeOccurrence, treeLinks } from '../src/core/layouts/tree/projection'; import { makeHierarchy, makeLevel, makeParentRef, makeSpaceNode } from './builders'; import { fixtureGraph } from './fixture-graph'; import sample from './fixtures/launch-playbook.json'; diff --git a/packages/map-views/tests/xy.test.ts b/packages/map-views/tests/xy.test.ts index 1b94a14..bba2029 100644 --- a/packages/map-views/tests/xy.test.ts +++ b/packages/map-views/tests/xy.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from 'bun:test'; import type { XYLayoutConfig } from '../src/core/definition'; -import { buildXYPlot } from '../src/core/xy'; +import { buildXYPlot } from '../src/core/layouts/xy/projection'; import { fixtureGraph } from './fixture-graph'; import teaShop from './fixtures/tea-shop.json'; From 4e16beeb208a87f2bea32edebde591f924d4745f Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Mon, 16 Nov 2026 06:11:26 +0000 Subject: [PATCH 07/15] Fold assignLanes back into core/graph.ts, the shared link helpers Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019XphpcKhuNyHcNArHFELR4 --- packages/map-views/src/core/graph.ts | 14 ++++++++++++++ .../map-views/src/core/layouts/graph/projection.ts | 3 +-- packages/map-views/src/core/layouts/lanes.ts | 13 ------------- .../src/core/layouts/neighbourhood/projection.ts | 3 +-- .../map-views/src/core/layouts/xy/projection.ts | 3 +-- 5 files changed, 17 insertions(+), 19 deletions(-) delete mode 100644 packages/map-views/src/core/layouts/lanes.ts diff --git a/packages/map-views/src/core/graph.ts b/packages/map-views/src/core/graph.ts index bf00d08..c322540 100644 --- a/packages/map-views/src/core/graph.ts +++ b/packages/map-views/src/core/graph.ts @@ -29,3 +29,17 @@ export function edgesWithin(graph: SpaceGraph): Edge[] { export function isHierarchyEdge(edge: Edge, hierarchy: Hierarchy | undefined): boolean { return hierarchy !== undefined && edge.kind === 'hierarchy' && edge.hierarchy === hierarchy.name; } + +/** Spread links joining the same pair of nodes (in either direction) into lanes around 0. */ +export function assignLanes(links: { from: string; to: string; lane: number }[]) { + const byPair = new Map<string, typeof links>(); + for (const link of links) { + const pair = [link.from, link.to].sort().join('\n'); + byPair.set(pair, [...(byPair.get(pair) ?? []), link]); + } + for (const group of byPair.values()) { + group.forEach((link, i) => { + link.lane = i - (group.length - 1) / 2; + }); + } +} diff --git a/packages/map-views/src/core/layouts/graph/projection.ts b/packages/map-views/src/core/layouts/graph/projection.ts index 62cd80d..978332b 100644 --- a/packages/map-views/src/core/layouts/graph/projection.ts +++ b/packages/map-views/src/core/layouts/graph/projection.ts @@ -1,9 +1,8 @@ import { forceCollide, forceLink, forceManyBody, forceSimulation, forceX, forceY } from 'd3-force'; import type { SpaceGraph, SpaceNode } from 'structured-context/api'; import type { GraphLayoutConfig } from '../../definition'; -import { edgesWithin } from '../../graph'; +import { assignLanes, edgesWithin } from '../../graph'; import { occurrenceKey } from '../../occurrence'; -import { assignLanes } from '../lanes'; /** A positioned node; `x` and `y` are pixels from the top left of the plot. */ export type ForcePoint = { key: string; node: SpaceNode; x: number; y: number }; diff --git a/packages/map-views/src/core/layouts/lanes.ts b/packages/map-views/src/core/layouts/lanes.ts deleted file mode 100644 index 1c2512a..0000000 --- a/packages/map-views/src/core/layouts/lanes.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** Spread links joining the same pair of nodes (in either direction) into lanes around 0. */ -export function assignLanes(links: { from: string; to: string; lane: number }[]) { - const byPair = new Map<string, typeof links>(); - for (const link of links) { - const pair = [link.from, link.to].sort().join('\n'); - byPair.set(pair, [...(byPair.get(pair) ?? []), link]); - } - for (const group of byPair.values()) { - group.forEach((link, i) => { - link.lane = i - (group.length - 1) / 2; - }); - } -} diff --git a/packages/map-views/src/core/layouts/neighbourhood/projection.ts b/packages/map-views/src/core/layouts/neighbourhood/projection.ts index 9b08eaa..c396eef 100644 --- a/packages/map-views/src/core/layouts/neighbourhood/projection.ts +++ b/packages/map-views/src/core/layouts/neighbourhood/projection.ts @@ -1,8 +1,7 @@ import type { SpaceGraph, SpaceNode } from 'structured-context/api'; import type { NeighbourhoodLayoutConfig } from '../../definition'; -import { childEdges, parentEdges } from '../../graph'; +import { assignLanes, childEdges, parentEdges } from '../../graph'; import { occurrenceKey } from '../../occurrence'; -import { assignLanes } from '../lanes'; export type NeighbourhoodRole = 'left' | 'right' | 'above' | 'below' | 'around'; diff --git a/packages/map-views/src/core/layouts/xy/projection.ts b/packages/map-views/src/core/layouts/xy/projection.ts index a08013c..2ca9a7e 100644 --- a/packages/map-views/src/core/layouts/xy/projection.ts +++ b/packages/map-views/src/core/layouts/xy/projection.ts @@ -1,8 +1,7 @@ import type { SpaceGraph, SpaceNode } from 'structured-context/api'; import type { AxisConfig, XYLayoutConfig } from '../../definition'; -import { edgesWithin, isHierarchyEdge } from '../../graph'; +import { assignLanes, edgesWithin, isHierarchyEdge } from '../../graph'; import { occurrenceKey } from '../../occurrence'; -import { assignLanes } from '../lanes'; /** A plotted node. `x` and `y` run from 0 to 1 across the plot, left to right and bottom to top. */ export type XYPoint = { key: string; node: SpaceNode; x: number; y: number }; From cd915b8184b02dd2db5a3d81a0a1108b148a78e5 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Mon, 16 Nov 2026 06:19:38 +0000 Subject: [PATCH 08/15] Move the shared layout helpers (graph edges, lanes, occurrence keys) into core/layouts/helpers.ts Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019XphpcKhuNyHcNArHFELR4 --- .../src/core/layouts/graph/projection.ts | 3 +-- .../src/core/{graph.ts => layouts/helpers.ts} | 15 +++++++++++++++ .../src/core/layouts/landscape/projection.ts | 3 +-- .../src/core/layouts/neighbourhood/projection.ts | 3 +-- .../map-views/src/core/layouts/tree/projection.ts | 3 +-- .../map-views/src/core/layouts/xy/projection.ts | 3 +-- packages/map-views/src/core/occurrence.ts | 14 -------------- .../{graph.test.ts => layout-helpers.test.ts} | 2 +- 8 files changed, 21 insertions(+), 25 deletions(-) rename packages/map-views/src/core/{graph.ts => layouts/helpers.ts} (72%) delete mode 100644 packages/map-views/src/core/occurrence.ts rename packages/map-views/tests/{graph.test.ts => layout-helpers.test.ts} (98%) diff --git a/packages/map-views/src/core/layouts/graph/projection.ts b/packages/map-views/src/core/layouts/graph/projection.ts index 978332b..c962cb1 100644 --- a/packages/map-views/src/core/layouts/graph/projection.ts +++ b/packages/map-views/src/core/layouts/graph/projection.ts @@ -1,8 +1,7 @@ import { forceCollide, forceLink, forceManyBody, forceSimulation, forceX, forceY } from 'd3-force'; import type { SpaceGraph, SpaceNode } from 'structured-context/api'; import type { GraphLayoutConfig } from '../../definition'; -import { assignLanes, edgesWithin } from '../../graph'; -import { occurrenceKey } from '../../occurrence'; +import { assignLanes, edgesWithin, occurrenceKey } from '../helpers'; /** A positioned node; `x` and `y` are pixels from the top left of the plot. */ export type ForcePoint = { key: string; node: SpaceNode; x: number; y: number }; diff --git a/packages/map-views/src/core/graph.ts b/packages/map-views/src/core/layouts/helpers.ts similarity index 72% rename from packages/map-views/src/core/graph.ts rename to packages/map-views/src/core/layouts/helpers.ts index c322540..bc935df 100644 --- a/packages/map-views/src/core/graph.ts +++ b/packages/map-views/src/core/layouts/helpers.ts @@ -43,3 +43,18 @@ export function assignLanes(links: { from: string; to: string; lane: number }[]) }); } } + +/** + * One step of an occurrence path: a node title, a `[field, value]` group, or `null` for the + * ungrouped area. Encoded distinctly, so a field group can't collide with a node of the same name. + */ +export type PathSegment = string | readonly [field: string, value: string | null] | null; + +/** + * Path-based key for one occurrence of a node: region, then the steps from the outermost + * container down to the node. Unique within a map view even when a node appears several times. + * Hosts can render several map views at once, so layouts scope keys to the map view instance. + */ +export function occurrenceKey(regionId: string, path: readonly PathSegment[]): string { + return JSON.stringify([regionId, ...path]); +} diff --git a/packages/map-views/src/core/layouts/landscape/projection.ts b/packages/map-views/src/core/layouts/landscape/projection.ts index b09e98d..3e3f12e 100644 --- a/packages/map-views/src/core/layouts/landscape/projection.ts +++ b/packages/map-views/src/core/layouts/landscape/projection.ts @@ -1,7 +1,6 @@ import type { SpaceGraph, SpaceNode } from 'structured-context/api'; import type { GroupLevel, LandscapeLayoutConfig } from '../../definition'; -import { childEdges, parentEdges } from '../../graph'; -import { occurrenceKey, type PathSegment } from '../../occurrence'; +import { childEdges, occurrenceKey, type PathSegment, parentEdges } from '../helpers'; /** One rendered container or node in a landscape. */ export type LandscapeOccurrence = { diff --git a/packages/map-views/src/core/layouts/neighbourhood/projection.ts b/packages/map-views/src/core/layouts/neighbourhood/projection.ts index c396eef..1a3da09 100644 --- a/packages/map-views/src/core/layouts/neighbourhood/projection.ts +++ b/packages/map-views/src/core/layouts/neighbourhood/projection.ts @@ -1,7 +1,6 @@ import type { SpaceGraph, SpaceNode } from 'structured-context/api'; import type { NeighbourhoodLayoutConfig } from '../../definition'; -import { assignLanes, childEdges, parentEdges } from '../../graph'; -import { occurrenceKey } from '../../occurrence'; +import { assignLanes, childEdges, occurrenceKey, parentEdges } from '../helpers'; export type NeighbourhoodRole = 'left' | 'right' | 'above' | 'below' | 'around'; diff --git a/packages/map-views/src/core/layouts/tree/projection.ts b/packages/map-views/src/core/layouts/tree/projection.ts index 4114e73..02df767 100644 --- a/packages/map-views/src/core/layouts/tree/projection.ts +++ b/packages/map-views/src/core/layouts/tree/projection.ts @@ -1,7 +1,6 @@ import type { SpaceGraph, SpaceNode } from 'structured-context/api'; import type { DagMode } from '../../definition'; -import { childEdges, isHierarchyEdge, parentEdges } from '../../graph'; -import { occurrenceKey } from '../../occurrence'; +import { childEdges, isHierarchyEdge, occurrenceKey, parentEdges } from '../helpers'; /** One rendered appearance of a node in a tree. */ export type TreeOccurrence = { diff --git a/packages/map-views/src/core/layouts/xy/projection.ts b/packages/map-views/src/core/layouts/xy/projection.ts index 2ca9a7e..7f809b4 100644 --- a/packages/map-views/src/core/layouts/xy/projection.ts +++ b/packages/map-views/src/core/layouts/xy/projection.ts @@ -1,7 +1,6 @@ import type { SpaceGraph, SpaceNode } from 'structured-context/api'; import type { AxisConfig, XYLayoutConfig } from '../../definition'; -import { assignLanes, edgesWithin, isHierarchyEdge } from '../../graph'; -import { occurrenceKey } from '../../occurrence'; +import { assignLanes, edgesWithin, isHierarchyEdge, occurrenceKey } from '../helpers'; /** A plotted node. `x` and `y` run from 0 to 1 across the plot, left to right and bottom to top. */ export type XYPoint = { key: string; node: SpaceNode; x: number; y: number }; diff --git a/packages/map-views/src/core/occurrence.ts b/packages/map-views/src/core/occurrence.ts deleted file mode 100644 index 990c2bb..0000000 --- a/packages/map-views/src/core/occurrence.ts +++ /dev/null @@ -1,14 +0,0 @@ -/** - * One step of an occurrence path: a node title, a `[field, value]` group, or `null` for the - * ungrouped area. Encoded distinctly, so a field group can't collide with a node of the same name. - */ -export type PathSegment = string | readonly [field: string, value: string | null] | null; - -/** - * Path-based key for one occurrence of a node: region, then the steps from the outermost - * container down to the node. Unique within a map view even when a node appears several times. - * Hosts can render several map views at once, so layouts scope keys to the map view instance. - */ -export function occurrenceKey(regionId: string, path: readonly PathSegment[]): string { - return JSON.stringify([regionId, ...path]); -} diff --git a/packages/map-views/tests/graph.test.ts b/packages/map-views/tests/layout-helpers.test.ts similarity index 98% rename from packages/map-views/tests/graph.test.ts rename to packages/map-views/tests/layout-helpers.test.ts index 111e9e1..2dad65d 100644 --- a/packages/map-views/tests/graph.test.ts +++ b/packages/map-views/tests/layout-helpers.test.ts @@ -1,6 +1,6 @@ import { expect, test } from 'bun:test'; import { buildSpaceGraph, type SpaceNode } from 'structured-context/api'; -import { childEdges, edgesWithin, isHierarchyEdge, parentEdges } from '../src/core/graph'; +import { childEdges, edgesWithin, isHierarchyEdge, parentEdges } from '../src/core/layouts/helpers'; import { fixtureGraph } from './fixture-graph'; import sample from './fixtures/launch-playbook.json'; From fc30b62dbd1a46bda801f335a050cbbbf4903695 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Mon, 16 Nov 2026 06:25:51 +0000 Subject: [PATCH 09/15] Rename core/snapshot.ts to space-snapshot.ts Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019XphpcKhuNyHcNArHFELR4 --- packages/map-views/src/artifact/load.ts | 2 +- packages/map-views/src/artifact/main.tsx | 2 +- packages/map-views/src/core/{snapshot.ts => space-snapshot.ts} | 0 packages/map-views/src/node/page.ts | 2 +- packages/map-views/src/node/snapshot.ts | 2 +- packages/map-views/src/page/main.tsx | 2 +- packages/map-views/src/viewer/Viewer.tsx | 2 +- packages/map-views/tests/page.test.ts | 2 +- 8 files changed, 7 insertions(+), 7 deletions(-) rename packages/map-views/src/core/{snapshot.ts => space-snapshot.ts} (100%) diff --git a/packages/map-views/src/artifact/load.ts b/packages/map-views/src/artifact/load.ts index 5755812..2cc45b6 100644 --- a/packages/map-views/src/artifact/load.ts +++ b/packages/map-views/src/artifact/load.ts @@ -1,4 +1,4 @@ -import type { SpaceSnapshot } from '../core/snapshot'; +import type { SpaceSnapshot } from '../core/space-snapshot'; const SPACES = 'spaces'; const TIMEOUT_MS = 10_000; diff --git a/packages/map-views/src/artifact/main.tsx b/packages/map-views/src/artifact/main.tsx index 30773d3..233f64b 100644 --- a/packages/map-views/src/artifact/main.tsx +++ b/packages/map-views/src/artifact/main.tsx @@ -2,7 +2,7 @@ import { useEffect, useState } from 'react'; import { createRoot } from 'react-dom/client'; import type { SpaceGraph, SpaceNode } from 'structured-context/browser'; import type { MapViewDefinition } from '../core/definition'; -import type { SpaceSnapshot } from '../core/snapshot'; +import type { SpaceSnapshot } from '../core/space-snapshot'; import { Viewer } from '../viewer/Viewer'; import { loadSpaces } from './load'; diff --git a/packages/map-views/src/core/snapshot.ts b/packages/map-views/src/core/space-snapshot.ts similarity index 100% rename from packages/map-views/src/core/snapshot.ts rename to packages/map-views/src/core/space-snapshot.ts diff --git a/packages/map-views/src/node/page.ts b/packages/map-views/src/node/page.ts index af6bb5e..fddef54 100644 --- a/packages/map-views/src/node/page.ts +++ b/packages/map-views/src/node/page.ts @@ -1,4 +1,4 @@ -import type { SpaceSnapshot } from '../core/snapshot'; +import type { SpaceSnapshot } from '../core/space-snapshot'; export const PAGE_SLOTS = { title: '<!--sctx-title-->', snapshots: '<!--sctx-snapshots-->' } as const; diff --git a/packages/map-views/src/node/snapshot.ts b/packages/map-views/src/node/snapshot.ts index 9df64ad..ba5af3f 100644 --- a/packages/map-views/src/node/snapshot.ts +++ b/packages/map-views/src/node/snapshot.ts @@ -6,7 +6,7 @@ import { validateSpace, } from 'structured-context/api'; import { mapViewsForSchema } from '../core/definition'; -import type { SpaceSnapshot } from '../core/snapshot'; +import type { SpaceSnapshot } from '../core/space-snapshot'; import { loadMapViewDefinitions } from './index'; /** The `validateSpace` options `export` passes through unchanged. */ diff --git a/packages/map-views/src/page/main.tsx b/packages/map-views/src/page/main.tsx index 901cc29..078f3c0 100644 --- a/packages/map-views/src/page/main.tsx +++ b/packages/map-views/src/page/main.tsx @@ -1,5 +1,5 @@ import { createRoot } from 'react-dom/client'; -import type { SpaceSnapshot } from '../core/snapshot'; +import type { SpaceSnapshot } from '../core/space-snapshot'; import { Viewer } from '../viewer/Viewer'; /** The host for a self-contained page: shows the snapshots the page carries. */ diff --git a/packages/map-views/src/viewer/Viewer.tsx b/packages/map-views/src/viewer/Viewer.tsx index c5b0d13..7c81e0b 100644 --- a/packages/map-views/src/viewer/Viewer.tsx +++ b/packages/map-views/src/viewer/Viewer.tsx @@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import { type SpaceGraph, type SpaceNode, spaceGraphFrom } from 'structured-context/browser'; import { annotationsFrom } from '../core/annotations'; import type { MapViewDefinition, ParameterValues } from '../core/definition'; -import type { SpaceSnapshot } from '../core/snapshot'; +import type { SpaceSnapshot } from '../core/space-snapshot'; import { MapView } from '../layouts/MapView'; import { ParameterControls } from '../layouts/ParameterControls'; diff --git a/packages/map-views/tests/page.test.ts b/packages/map-views/tests/page.test.ts index adf6fe6..2aaa5be 100644 --- a/packages/map-views/tests/page.test.ts +++ b/packages/map-views/tests/page.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from 'bun:test'; -import type { SpaceSnapshot } from '../src/core/snapshot'; +import type { SpaceSnapshot } from '../src/core/space-snapshot'; import { fillPage, PAGE_SLOTS } from '../src/node/page'; const template = `<title>${PAGE_SLOTS.title}`; From 936e4973cf628a9260a1532055305a75f88423e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 06:37:00 +0000 Subject: [PATCH 10/15] Fix the core row in the architecture module table Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_019XphpcKhuNyHcNArHFELR4 --- docs/architecture.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/architecture.md b/docs/architecture.md index fd78110..ab37a32 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -15,7 +15,7 @@ flowchart LR | Module | Holds | May import | |---|---|---| -| `packages/map-views/src/core` | Definition parsing and validation, parameter resolution, graph helpers, and the projections | Types from structured-context only. No React, DOM or Node | +| `packages/map-views/src/core` | Definition parsing and validation, parameter resolution, validation annotations, and each layout's settings schema and projection (`core/layouts//`) | Types from structured-context only. No React, DOM or Node | | `packages/map-views/src/layouts` | `MapView`, the layout components, `NodeCard`, `EdgeOverlay`, the parameter controls (`useParameterControls`, the typed inputs and the default `ParameterControls` layout), styles | core, React | | `packages/map-views/src/viewer` | `Viewer`, the page-filling UI that hosts share. What is specific to a host comes in as an option | core, layouts, React, `structured-context/browser` | | `packages/map-views/src/node` | `loadMapViewDefinitions`: finding definitions in the library (embedded at build time from `packages/map-views/map-views/`), plugins and config folders; `exportSnapshot` and the `export` bin, which snapshot a space for browser-only hosts; `fillPage`, which writes snapshots into the self-contained page. `fillPage` and `readDefinitionFolders` are also the `/html` entry, which imports nothing from structured-context's API | core, Node, structured-context | From cf8ef1ca482598f3feace83668f5640c73b0dac8 Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Mon, 16 Nov 2026 19:32:10 +1100 Subject: [PATCH 11/15] Tighten names and layering ahead of 1.0; graph layout reads the space graph - Rename src/layouts to src/components, and EdgeOverlay to ConnectorOverlay: an edge is a reference in the space graph, a connector is a drawn line. The projections share one Connector type in place of a link type each. - A projection is optional: a layout has one only when deciding what is shown takes logic of its own. The graph layout has none; its component reads the space graph and runs d3-force itself. - Graph layout: each hierarchy level settles in a band, hierarchy nodes gather in the middle, relationship connectors are dashed, and nodes with no edge shown sit in a grid underneath. - Neighbourhood layout: a hierarchy root shows the other roots of its type, so the reader can move between them. - Stop exporting types that one file uses, and use structured-context's NodeId in place of local aliases. - AGENTS.md: principles for naming, exports, comments and docs, and what adding a layout involves. Docs no longer enumerate what the code lists. --- AGENTS.md | 59 +++--- README.md | 4 +- apps/navigator/src/useFetched.ts | 2 +- docs/api.md | 2 +- docs/architecture.md | 37 ++-- docs/concepts.md | 25 +-- docs/layouts.md | 6 +- packages/map-views/README.md | 2 +- packages/map-views/package.json | 4 +- .../ConnectorOverlay.tsx} | 46 ++--- .../map-views/src/components/GraphLayout.tsx | 170 ++++++++++++++++++ .../LandscapeLayout.tsx | 0 .../src/{layouts => components}/MapView.tsx | 0 .../NeighbourhoodLayout.tsx | 14 +- .../src/{layouts => components}/NodeCard.tsx | 0 .../ParameterControls.tsx | 0 .../ParameterInputs.tsx | 0 .../{layouts => components}/TreeLayout.tsx | 16 +- .../src/{layouts => components}/XYLayout.tsx | 21 +-- .../annotations-context.ts | 0 .../src/{layouts => components}/layout.ts | 15 +- .../src/{layouts => components}/styles.css | 0 .../useParameterControls.ts | 0 packages/map-views/src/core/annotations.ts | 7 +- packages/map-views/src/core/definition.ts | 2 - .../src/core/layouts/graph/projection.ts | 74 -------- .../src/core/layouts/graph/schema.ts | 2 +- .../map-views/src/core/layouts/helpers.ts | 31 ++-- .../src/core/layouts/landscape/projection.ts | 2 +- .../core/layouts/neighbourhood/projection.ts | 39 ++-- .../src/core/layouts/tree/projection.ts | 24 ++- .../src/core/layouts/xy/projection.ts | 39 ++-- .../src/core/schema/definition-schema.ts | 6 +- packages/map-views/src/index.ts | 24 ++- .../map-views/src/layouts/GraphLayout.tsx | 50 ------ packages/map-views/src/node/index.ts | 14 +- packages/map-views/src/viewer/Viewer.tsx | 14 +- packages/map-views/tests/force.test.ts | 35 ---- .../map-views/tests/module-boundaries.test.ts | 12 +- .../map-views/tests/neighbourhood.test.ts | 26 ++- packages/map-views/tests/node-card.test.tsx | 2 +- packages/map-views/tests/tree.test.ts | 26 +-- packages/map-views/tests/xy.test.ts | 12 +- packages/map-views/vite.config.ts | 2 +- schemas/generated/latest/definition.json | 2 +- 45 files changed, 443 insertions(+), 425 deletions(-) rename packages/map-views/src/{layouts/EdgeOverlay.tsx => components/ConnectorOverlay.tsx} (77%) create mode 100644 packages/map-views/src/components/GraphLayout.tsx rename packages/map-views/src/{layouts => components}/LandscapeLayout.tsx (100%) rename packages/map-views/src/{layouts => components}/MapView.tsx (100%) rename packages/map-views/src/{layouts => components}/NeighbourhoodLayout.tsx (86%) rename packages/map-views/src/{layouts => components}/NodeCard.tsx (100%) rename packages/map-views/src/{layouts => components}/ParameterControls.tsx (100%) rename packages/map-views/src/{layouts => components}/ParameterInputs.tsx (100%) rename packages/map-views/src/{layouts => components}/TreeLayout.tsx (82%) rename packages/map-views/src/{layouts => components}/XYLayout.tsx (88%) rename packages/map-views/src/{layouts => components}/annotations-context.ts (100%) rename packages/map-views/src/{layouts => components}/layout.ts (59%) rename packages/map-views/src/{layouts => components}/styles.css (100%) rename packages/map-views/src/{layouts => components}/useParameterControls.ts (100%) delete mode 100644 packages/map-views/src/core/layouts/graph/projection.ts delete mode 100644 packages/map-views/src/layouts/GraphLayout.tsx delete mode 100644 packages/map-views/tests/force.test.ts diff --git a/AGENTS.md b/AGENTS.md index ad21aca..2adcec1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,19 +1,8 @@ # structured-context-map-views -Declarative map views of structured-context spaces: the definition format, the rendering library and the navigator app. Review [docs/concepts.md](docs/concepts.md) before new work and use its terms in code, tests, comments and docs. +Declarative map views of structured-context spaces: the definition format, the rendering library and the navigator app. -## Layout - -- `packages/map-views`: the published library, `structured-context-map-views`. Its `src/index.ts` is the public surface; add an export only when a host needs it. -- `packages/map-views/src/core`: framework-agnostic. Definitions, parameters, graph helpers and the projections. No React, DOM, Node or runtime structured-context imports (type-only is fine, and `structured-context/types` is browser-safe); `tests/module-boundaries.test.ts` enforces this. -- `packages/map-views/src/layouts`: React components and the SVG edge overlay. Don't import host code from here. -- `packages/map-views/src/viewer`: the page-filling viewer that hosts share. It knows nothing about any one host: anything host-specific (such as card labels) is an option the host passes. Hosts (`src/artifact`, `src/page`) are imported by nothing else. -- `packages/map-views/src/node`: Node-only definition discovery (`loadMapViewDefinitions`), shipped as its own entry point (`structured-context-map-views/node`). Core and layouts must not import it. -- `packages/sctx-map-views`: the structured-context render plugin (format `map-views.html`), bundling the library's page template and `/html` entry. It reads everything through the render callbacks and has no structured-context dependency at runtime: its bundle imports nothing from it, and `test:package` checks that. -- `apps/navigator`: the standalone host (private package: a Vite app plus dev-server middleware calling the structured-context API). It consumes the library like any other host. -- `packages/map-views/map-views/*.json5`: definitions bundled with the library (`$id` `sctx-map-view://core/`): ones that suit any schema (no `schema`), and ones for structured-context's bundled schemas. `bun run generate:definitions` embeds them as `src/node/bundled-definitions.ts`; a test fails if that is stale. Plugins ship their own; personal ones go in the config root's `.sctx/map-views/` (structured-context's `resourceDir`). -- `packages/map-views/src/core/schema/` and each layout's `schema.ts` in `src/core/layouts//`: the definition format's JSON Schemas (`as const`), the source of truth. Types derive from them (`FromSchema`); `bun run generate:schemas` writes `schemas/generated/latest/` at the repo root (so the published URLs stay stable), and a test fails if those are stale; `--release` (run when cutting a release) also freezes `schemas/generated//` if the format changed. `$id`s are the published https URLs (`schema-url.ts`). Use absolute `${SCHEMA_URL}/…` refs: `FromSchema` doesn't resolve relative refs inside referenced schemas. -- `samples/launch-playbook/`: a public sample space. `packages/map-views/tests/fixtures/launch-playbook.json` is captured from it with `bun run capture-fixtures launch-playbook=../../samples/launch-playbook/.sctx.json` in `packages/map-views`. +Before new work, read [docs/concepts.md](docs/concepts.md) for the terms and [docs/architecture.md](docs/architecture.md#modules) for the modules and what each may import. Use the terms in code, tests, comments and docs. ## Checks @@ -23,17 +12,37 @@ bun run test:package # packs the library and the plugin, installs each in a bun run build # the library, then the navigator ``` -## Releases +## Principles + +- **Simple, not sloppy.** Prefer the smallest design that does the job. Don't add structures, grammars, limits or presets until a concrete need forces them. +- **One word per concept.** A thing has the same name in the definition format, the docs and the code. Add or rename a term in `docs/concepts.md` first, then use it. Don't rename another package's term: use structured-context's own word and type. +- **One home per fact.** Decide which doc owns a fact, state it there once, and link from elsewhere. Docs don't list what the code already lists (layouts, exports, props, files, variables): a list like that goes stale with the next change. +- **Export only what another module imports.** A type used in one place is written inline. A type used in one file isn't exported. Derive types (from the schemas, `Parameters`, `ReturnType`, `Pick`) instead of restating a shape. When two modules need the same shape, they share one type. +- **The public surface is `src/index.ts`, `src/node/index.ts` and `src/node/html.ts`.** Add an export there only when a host needs it, and say which host. +- **Comments say what the code can't.** A reason, a constraint, a trap. Never the signature, the parameter list or the next line. +- **No barrel files.** Modules import each other directly. A small helper joins the file it serves; it gets its own file when it has several users and a concept of its own. +- **Tests assert the behaviour they name.** Derive expected values from the fixture or the code under test. Don't hard-code a list that grows with the code, and don't assert things that only happen to be true. +- **Mark the loose parts.** Where careful review is traded for speed, say so in place with a `PROTOTYPE:` comment giving the shortcut and what a proper treatment needs. `grep -rn PROTOTYPE: packages apps` is the register. Untagged code is at production standard for its scope. +- **Fix the pattern, not the line.** When a review comment names a habit, search for every instance before replying, and check the result before saying it's fixed. +- **No private data.** This repo is public. Fixtures, samples and definitions come from public or synthetic spaces. + +Work and open questions are tracked as GitHub issues on this repo. + +## Adding a layout -Releases go through the `/release ` skill, which runs `bun pm version --no-git-tag-version` in `packages/map-views` (its `preversion` and `version` scripts run the checks and freeze the definition format's schemas in `schemas/generated//` when the format changed), sets the same version in `packages/sctx-map-views`, then commits, tags and pushes. The tag push runs `.github/workflows/release.yml`, which publishes both packages to npm with provenance. Don't run `generate:schemas --release` by hand. +A layout is a folder in `packages/map-views/src/core/layouts//` (`schema.ts`, and `projection.ts` only when deciding what is shown takes logic of its own) and a component in `src/components/`. It is registered in `core/definition.ts` (the schema list and the settings type), `core/schema/definition-schema.ts` (the `layout` branch) and `components/MapView.tsx`. It is documented in `docs/layouts.md` only. A projection decides what is shown; positions, sizes and anything a layout library computes belong in the component. -## Ways of working +## Generated files + +- `schemas/generated/latest/` comes from the schemas in `core/schema/` and each layout's `schema.ts` (`bun run generate:schemas`). Use absolute `${SCHEMA_URL}/…` refs there: `FromSchema` doesn't resolve relative refs inside referenced schemas. Never edit the frozen `schemas/generated//` folders or run `generate:schemas --release` by hand. +- `packages/map-views/src/node/bundled-definitions.ts` comes from `packages/map-views/map-views/*.json5` (`bun run generate:definitions`). +- `packages/map-views/tests/fixtures/` is captured from spaces; see its README. + +Tests fail when the first two are stale. + +## Releases -- **Simple, not sloppy.** Prefer the smallest design that does the job over speculative generality. Untagged code is expected to be at production standard for its scope. -- **Mark the loose parts.** Where careful review is traded for speed, say so in place with a `PROTOTYPE:` comment explaining the shortcut and what a proper treatment needs. `grep -rn PROTOTYPE: src` is the register. -- **Last responsible moment.** Don't add intermediate structures, grammars, limits or presets until a concrete need forces them. -- **No private data.** This repo will be public. Fixtures, samples and definitions must come from public or synthetic spaces. -- Work and open questions are tracked as GitHub issues on this repo. +Releases go through the `/release ` skill. Its tag push runs `.github/workflows/release.yml`, which publishes both packages to npm. ## Definition of done @@ -41,10 +50,10 @@ Review and update with any change: | Change | Check | |---|---| -| Definition format (`core/schema`, `core/layouts/*/schema.ts`) | `docs/definitions.md`, `docs/layouts.md` for layout settings; regenerated `schemas/generated/`; definitions in `map-views/` | +| Definition format (`core/schema`, `core/layouts/*/schema.ts`) | `docs/definitions.md`, or `docs/layouts.md` for layout settings; regenerated `schemas/generated/latest/`; definitions in `map-views/` | | New or renamed term | `docs/concepts.md` | | Exports or component props | `docs/api.md` | -| Module structure, rendering, styling | `docs/architecture.md`, this file | +| Module structure, rendering, styling | `docs/architecture.md` | | Anything user-visible | `README.md` (kept short; detail goes in `docs/`) | Docs describe what the code does now. Decision history and plans don't go in docs. @@ -53,9 +62,9 @@ Docs describe what the code does now. Decision history and plans don't go in doc - `bun run dev --port ` runs Vite under Bun. That's intentional: structured-context targets Bun or a bundler. - Spaces come from the structured-context config. A relative `SCTX_CONFIG` inherited from another repo fails here; run with `env -u SCTX_CONFIG` to use the global config, or pass an absolute path. -- In a Chrome tab driven by an agent, the tab is usually hidden (`document.visibilityState === "hidden"`). Hidden tabs run no `ResizeObserver` or `requestAnimationFrame` callbacks, so edge redraws on resize can't be checked there. Taking a screenshot forces a frame, and DOM measurements remain reliable. +- In a Chrome tab driven by an agent, the tab is usually hidden (`document.visibilityState === "hidden"`). Hidden tabs run no `ResizeObserver` or `requestAnimationFrame` callbacks, so connector redraws on resize can't be checked there. Taking a screenshot forces a frame, and DOM measurements remain reliable. - React-controlled `