From 14507098858f1aec089d5255206849e1581d4a40 Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Tue, 17 Nov 2026 13:56:41 +1100 Subject: [PATCH 1/2] Add a synthetic software delivery lifecycle fixture, loaded from JSONL in tests --- packages/map-views/tests/fixture-graph.ts | 22 +++++++++- packages/map-views/tests/fixtures/README.md | 1 + .../map-views/tests/fixtures/sdlc/nodes.jsonl | 40 +++++++++++++++++ .../map-views/tests/fixtures/sdlc/schema.json | 43 +++++++++++++++++++ 4 files changed, 105 insertions(+), 1 deletion(-) create mode 100644 packages/map-views/tests/fixtures/sdlc/nodes.jsonl create mode 100644 packages/map-views/tests/fixtures/sdlc/schema.json diff --git a/packages/map-views/tests/fixture-graph.ts b/packages/map-views/tests/fixture-graph.ts index 9788f6a..9f67ed5 100644 --- a/packages/map-views/tests/fixture-graph.ts +++ b/packages/map-views/tests/fixture-graph.ts @@ -1,6 +1,26 @@ -import type { SpaceGraph } from 'structured-context/api'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { createSpaceContext, exportSpaceGraph, type SpaceGraph, type SpaceNode } from 'structured-context/api'; import { spaceGraphFrom } from 'structured-context/browser'; /** Rebuild a captured fixture's graph, as a browser host does with a server's response. */ export const fixtureGraph = (fixture: unknown): SpaceGraph => spaceGraphFrom((fixture as { graph: Parameters[0] }).graph); + +/** + * Build a graph from a fixture folder holding `schema.json` and `nodes.jsonl`: parsed nodes, one per + * line, as `sctx dump ` prints them (resolved fields included). Nodes keep the file's order. + */ +export function jsonlFixtureGraph(dir: string): SpaceGraph { + const path = (file: string) => join(import.meta.dir, 'fixtures', dir, file); + const nodes = readFileSync(path('nodes.jsonl'), 'utf8') + .split('\n') + .filter((line) => line.trim() !== '') + .map((line) => JSON.parse(line) as SpaceNode); + const { metadata } = createSpaceContext( + dir, + { spaces: [{ name: dir, path: path('.'), schema: path('schema.json') }] }, + { configDir: path('.') }, + ).schema; + return spaceGraphFrom(exportSpaceGraph(nodes, metadata)); +} diff --git a/packages/map-views/tests/fixtures/README.md b/packages/map-views/tests/fixtures/README.md index e887682..8f5ebd9 100644 --- a/packages/map-views/tests/fixtures/README.md +++ b/packages/map-views/tests/fixtures/README.md @@ -4,3 +4,4 @@ Spaces captured in the shape a host's server sends them (`schemaId` plus structu - `launch-playbook.json`: captured from [`samples/launch-playbook`](../../../../samples/launch-playbook), an invented open-source launch playbook. - `tea-shop.json`: the tea shop, the standard introductory example in [Online Wardley Maps](https://onlinewardleymaps.com/), parsed by the structured-context Wardley mapping plugin. +- `sdlc/`: an invented software delivery lifecycle space, as a folder of `schema.json` and `nodes.jsonl` (parsed nodes, one per line, as `sctx dump` prints them; line order is the space order). Made by writing the notes as markdown and running `sctx dump | jq -c '.nodes[]'`, then ordering the lines. Loaded by `jsonlFixtureGraph` in `tests/fixture-graph.ts`. diff --git a/packages/map-views/tests/fixtures/sdlc/nodes.jsonl b/packages/map-views/tests/fixtures/sdlc/nodes.jsonl new file mode 100644 index 0000000..9f52120 --- /dev/null +++ b/packages/map-views/tests/fixtures/sdlc/nodes.jsonl @@ -0,0 +1,40 @@ +{"id":"Discover.md","title":"Discover","schemaData":{"title":"Discover","type":"Stage","order":1,"content":"Discover."},"linkTargets":["Discover"],"type":"Stage","source":{"file":"Discover.md","line":1},"contentLinks":[],"content":"Discover.","resolvedType":"Stage","resolvedParents":[],"resolvedLinks":[]} +{"id":"Specify.md","title":"Specify","schemaData":{"title":"Specify","type":"Stage","order":2,"content":"Specify."},"linkTargets":["Specify"],"type":"Stage","source":{"file":"Specify.md","line":1},"contentLinks":[],"content":"Specify.","resolvedType":"Stage","resolvedParents":[],"resolvedLinks":[]} +{"id":"Build.md","title":"Build","schemaData":{"title":"Build","type":"Stage","order":3,"content":"Build."},"linkTargets":["Build"],"type":"Stage","source":{"file":"Build.md","line":1},"contentLinks":[],"content":"Build.","resolvedType":"Stage","resolvedParents":[],"resolvedLinks":[]} +{"id":"Review.md","title":"Review","schemaData":{"title":"Review","type":"Stage","order":4,"content":"Review."},"linkTargets":["Review"],"type":"Stage","source":{"file":"Review.md","line":1},"contentLinks":[],"content":"Review.","resolvedType":"Stage","resolvedParents":[],"resolvedLinks":[]} +{"id":"Release.md","title":"Release","schemaData":{"title":"Release","type":"Stage","order":5,"content":"Release."},"linkTargets":["Release"],"type":"Stage","source":{"file":"Release.md","line":1},"contentLinks":[],"content":"Release.","resolvedType":"Stage","resolvedParents":[],"resolvedLinks":[]} +{"id":"Operate.md","title":"Operate","schemaData":{"title":"Operate","type":"Stage","order":6,"content":"Operate."},"linkTargets":["Operate"],"type":"Stage","source":{"file":"Operate.md","line":1},"contentLinks":[],"content":"Operate.","resolvedType":"Stage","resolvedParents":[],"resolvedLinks":[]} +{"id":"Retire.md","title":"Retire","schemaData":{"title":"Retire","type":"Stage","order":7,"content":"Retire."},"linkTargets":["Retire"],"type":"Stage","source":{"file":"Retire.md","line":1},"contentLinks":[],"content":"Retire.","resolvedType":"Stage","resolvedParents":[],"resolvedLinks":[]} +{"id":"Product Manager.md","title":"Product Manager","schemaData":{"title":"Product Manager","type":"Actor","content":"Product Manager."},"linkTargets":["Product Manager"],"type":"Actor","source":{"file":"Product Manager.md","line":1},"contentLinks":[],"content":"Product Manager.","resolvedType":"Actor","resolvedParents":[{"id":"Draft the spec.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Collect usage feedback.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Interview users.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Announce the release.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Check against the spec.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Size the opportunity.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false}],"resolvedLinks":[]} +{"id":"Engineer.md","title":"Engineer","schemaData":{"title":"Engineer","type":"Actor","content":"Engineer."},"linkTargets":["Engineer"],"type":"Actor","source":{"file":"Engineer.md","line":1},"contentLinks":[],"content":"Engineer.","resolvedType":"Actor","resolvedParents":[{"id":"Challenge the spec.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Approve the change.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Write the code.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Fix failing checks.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Roll out behind a flag.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Merge to main.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Break work into tasks.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Triage an incident.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false}],"resolvedLinks":[]} +{"id":"Coding Agent.md","title":"Coding Agent","schemaData":{"title":"Coding Agent","type":"Actor","content":"Coding Agent."},"linkTargets":["Coding Agent"],"type":"Actor","source":{"file":"Coding Agent.md","line":1},"contentLinks":[],"content":"Coding Agent.","resolvedType":"Actor","resolvedParents":[{"id":"Keep the glossary current.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Fix failing checks.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Propose a fix for an alert.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Write tests.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Generate a first draft.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false}],"resolvedLinks":[]} +{"id":"Review Agent.md","title":"Review Agent","schemaData":{"title":"Review Agent","type":"Actor","content":"Review Agent."},"linkTargets":["Review Agent"],"type":"Actor","source":{"file":"Review Agent.md","line":1},"contentLinks":[],"content":"Review Agent.","resolvedType":"Actor","resolvedParents":[{"id":"Challenge the spec.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Review the diff.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false}],"resolvedLinks":[]} +{"id":"SRE.md","title":"SRE","schemaData":{"title":"SRE","type":"Actor","content":"SRE."},"linkTargets":["SRE"],"type":"Actor","source":{"file":"SRE.md","line":1},"contentLinks":[],"content":"SRE.","resolvedType":"Actor","resolvedParents":[{"id":"Watch the dashboards.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Triage an incident.md","field":"actors","fieldOn":"parent","kind":"relationship","selfRef":false}],"resolvedLinks":[]} +{"id":"Issue Tracker.md","title":"Issue Tracker","schemaData":{"title":"Issue Tracker","type":"Tool","content":"Issue Tracker."},"linkTargets":["Issue Tracker"],"type":"Tool","source":{"file":"Issue Tracker.md","line":1},"contentLinks":[],"content":"Issue Tracker.","resolvedType":"Tool","resolvedParents":[{"id":"Collect usage feedback.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Interview users.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Break work into tasks.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Triage an incident.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false}],"resolvedLinks":[]} +{"id":"Spec Template.md","title":"Spec Template","schemaData":{"title":"Spec Template","type":"Tool","content":"Spec Template."},"linkTargets":["Spec Template"],"type":"Tool","source":{"file":"Spec Template.md","line":1},"contentLinks":[],"content":"Spec Template.","resolvedType":"Tool","resolvedParents":[{"id":"Draft the spec.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Challenge the spec.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Check against the spec.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false}],"resolvedLinks":[]} +{"id":"CI Pipeline.md","title":"CI Pipeline","schemaData":{"title":"CI Pipeline","type":"Tool","content":"CI Pipeline."},"linkTargets":["CI Pipeline"],"type":"Tool","source":{"file":"CI Pipeline.md","line":1},"contentLinks":[],"content":"CI Pipeline.","resolvedType":"Tool","resolvedParents":[{"id":"Write the code.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Fix failing checks.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Write tests.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Merge to main.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Tidy stale branches.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false}],"resolvedLinks":[]} +{"id":"Agent Sandbox.md","title":"Agent Sandbox","schemaData":{"title":"Agent Sandbox","type":"Tool","content":"Agent Sandbox."},"linkTargets":["Agent Sandbox"],"type":"Tool","source":{"file":"Agent Sandbox.md","line":1},"contentLinks":[],"content":"Agent Sandbox.","resolvedType":"Tool","resolvedParents":[{"id":"Write tests.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Generate a first draft.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false}],"resolvedLinks":[]} +{"id":"Feature Flags.md","title":"Feature Flags","schemaData":{"title":"Feature Flags","type":"Tool","content":"Feature Flags."},"linkTargets":["Feature Flags"],"type":"Tool","source":{"file":"Feature Flags.md","line":1},"contentLinks":[],"content":"Feature Flags.","resolvedType":"Tool","resolvedParents":[{"id":"Roll out behind a flag.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false}],"resolvedLinks":[]} +{"id":"Alerting.md","title":"Alerting","schemaData":{"title":"Alerting","type":"Tool","content":"Alerting."},"linkTargets":["Alerting"],"type":"Tool","source":{"file":"Alerting.md","line":1},"contentLinks":[],"content":"Alerting.","resolvedType":"Tool","resolvedParents":[{"id":"Propose a fix for an alert.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Watch the dashboards.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false},{"id":"Triage an incident.md","field":"tools","fieldOn":"parent","kind":"relationship","selfRef":false}],"resolvedLinks":[]} +{"id":"Interview users.md","title":"Interview users","schemaData":{"title":"Interview users","type":"Step","stage":"[[Discover]]","actors":["[[Product Manager]]"],"tools":["[[Issue Tracker]]"],"content":"Interview users."},"linkTargets":["Interview users"],"type":"Step","source":{"file":"Interview users.md","line":1},"contentLinks":[],"content":"Interview users.","resolvedType":"Step","resolvedParents":[{"id":"Discover.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Size the opportunity.md","title":"Size the opportunity","schemaData":{"title":"Size the opportunity","type":"Step","stage":"[[Discover]]","actors":["[[Product Manager]]"],"content":"Size the opportunity."},"linkTargets":["Size the opportunity"],"type":"Step","source":{"file":"Size the opportunity.md","line":1},"contentLinks":[],"content":"Size the opportunity.","resolvedType":"Step","resolvedParents":[{"id":"Discover.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Draft the spec.md","title":"Draft the spec","schemaData":{"title":"Draft the spec","type":"Step","stage":"[[Specify]]","actors":["[[Product Manager]]"],"tools":["[[Spec Template]]"],"content":"Draft the spec."},"linkTargets":["Draft the spec"],"type":"Step","source":{"file":"Draft the spec.md","line":1},"contentLinks":[],"content":"Draft the spec.","resolvedType":"Step","resolvedParents":[{"id":"Specify.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Challenge the spec.md","title":"Challenge the spec","schemaData":{"title":"Challenge the spec","type":"Step","stage":"[[Specify]]","actors":["[[Engineer]]","[[Review Agent]]"],"tools":["[[Spec Template]]"],"content":"Challenge the spec."},"linkTargets":["Challenge the spec"],"type":"Step","source":{"file":"Challenge the spec.md","line":1},"contentLinks":[],"content":"Challenge the spec.","resolvedType":"Step","resolvedParents":[{"id":"Specify.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Break work into tasks.md","title":"Break work into tasks","schemaData":{"title":"Break work into tasks","type":"Step","stage":"[[Specify]]","actors":["[[Engineer]]"],"tools":["[[Issue Tracker]]"],"content":"Break work into tasks."},"linkTargets":["Break work into tasks"],"type":"Step","source":{"file":"Break work into tasks.md","line":1},"contentLinks":[],"content":"Break work into tasks.","resolvedType":"Step","resolvedParents":[{"id":"Specify.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Write the code.md","title":"Write the code","schemaData":{"title":"Write the code","type":"Step","stage":"[[Build]]","actors":["[[Engineer]]"],"tools":["[[CI Pipeline]]"],"content":"Write the code."},"linkTargets":["Write the code"],"type":"Step","source":{"file":"Write the code.md","line":1},"contentLinks":[],"content":"Write the code.","resolvedType":"Step","resolvedParents":[{"id":"Build.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Generate a first draft.md","title":"Generate a first draft","schemaData":{"title":"Generate a first draft","type":"Step","stage":"[[Build]]","actors":["[[Coding Agent]]"],"tools":["[[Agent Sandbox]]"],"content":"Generate a first draft."},"linkTargets":["Generate a first draft"],"type":"Step","source":{"file":"Generate a first draft.md","line":1},"contentLinks":[],"content":"Generate a first draft.","resolvedType":"Step","resolvedParents":[{"id":"Build.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Write tests.md","title":"Write tests","schemaData":{"title":"Write tests","type":"Step","stage":"[[Build]]","actors":["[[Coding Agent]]"],"tools":["[[Agent Sandbox]]","[[CI Pipeline]]"],"content":"Write tests."},"linkTargets":["Write tests"],"type":"Step","source":{"file":"Write tests.md","line":1},"contentLinks":[],"content":"Write tests.","resolvedType":"Step","resolvedParents":[{"id":"Build.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Fix failing checks.md","title":"Fix failing checks","schemaData":{"title":"Fix failing checks","type":"Step","stage":"[[Build]]","actors":["[[Coding Agent]]","[[Engineer]]"],"tools":["[[CI Pipeline]]"],"content":"Fix failing checks."},"linkTargets":["Fix failing checks"],"type":"Step","source":{"file":"Fix failing checks.md","line":1},"contentLinks":[],"content":"Fix failing checks.","resolvedType":"Step","resolvedParents":[{"id":"Build.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Review the diff.md","title":"Review the diff","schemaData":{"title":"Review the diff","type":"Step","stage":"[[Review]]","actors":["[[Review Agent]]"],"content":"Review the diff."},"linkTargets":["Review the diff"],"type":"Step","source":{"file":"Review the diff.md","line":1},"contentLinks":[],"content":"Review the diff.","resolvedType":"Step","resolvedParents":[{"id":"Review.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Approve the change.md","title":"Approve the change","schemaData":{"title":"Approve the change","type":"Step","stage":"[[Review]]","actors":["[[Engineer]]"],"content":"Approve the change."},"linkTargets":["Approve the change"],"type":"Step","source":{"file":"Approve the change.md","line":1},"contentLinks":[],"content":"Approve the change.","resolvedType":"Step","resolvedParents":[{"id":"Review.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Check against the spec.md","title":"Check against the spec","schemaData":{"title":"Check against the spec","type":"Step","stage":"[[Review]]","actors":["[[Product Manager]]"],"tools":["[[Spec Template]]"],"content":"Check against the spec."},"linkTargets":["Check against the spec"],"type":"Step","source":{"file":"Check against the spec.md","line":1},"contentLinks":[],"content":"Check against the spec.","resolvedType":"Step","resolvedParents":[{"id":"Review.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Merge to main.md","title":"Merge to main","schemaData":{"title":"Merge to main","type":"Step","stage":"[[Release]]","actors":["[[Engineer]]"],"tools":["[[CI Pipeline]]"],"content":"Merge to main."},"linkTargets":["Merge to main"],"type":"Step","source":{"file":"Merge to main.md","line":1},"contentLinks":[],"content":"Merge to main.","resolvedType":"Step","resolvedParents":[{"id":"Release.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Roll out behind a flag.md","title":"Roll out behind a flag","schemaData":{"title":"Roll out behind a flag","type":"Step","stage":"[[Release]]","actors":["[[Engineer]]"],"tools":["[[Feature Flags]]"],"content":"Roll out behind a flag."},"linkTargets":["Roll out behind a flag"],"type":"Step","source":{"file":"Roll out behind a flag.md","line":1},"contentLinks":[],"content":"Roll out behind a flag.","resolvedType":"Step","resolvedParents":[{"id":"Release.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Announce the release.md","title":"Announce the release","schemaData":{"title":"Announce the release","type":"Step","stage":"[[Release]]","actors":["[[Product Manager]]"],"content":"Announce the release."},"linkTargets":["Announce the release"],"type":"Step","source":{"file":"Announce the release.md","line":1},"contentLinks":[],"content":"Announce the release.","resolvedType":"Step","resolvedParents":[{"id":"Release.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Watch the dashboards.md","title":"Watch the dashboards","schemaData":{"title":"Watch the dashboards","type":"Step","stage":"[[Operate]]","actors":["[[SRE]]"],"tools":["[[Alerting]]"],"content":"Watch the dashboards."},"linkTargets":["Watch the dashboards"],"type":"Step","source":{"file":"Watch the dashboards.md","line":1},"contentLinks":[],"content":"Watch the dashboards.","resolvedType":"Step","resolvedParents":[{"id":"Operate.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Triage an incident.md","title":"Triage an incident","schemaData":{"title":"Triage an incident","type":"Step","stage":"[[Operate]]","actors":["[[SRE]]","[[Engineer]]"],"tools":["[[Alerting]]","[[Issue Tracker]]"],"content":"Triage an incident."},"linkTargets":["Triage an incident"],"type":"Step","source":{"file":"Triage an incident.md","line":1},"contentLinks":[],"content":"Triage an incident.","resolvedType":"Step","resolvedParents":[{"id":"Operate.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Propose a fix for an alert.md","title":"Propose a fix for an alert","schemaData":{"title":"Propose a fix for an alert","type":"Step","stage":"[[Operate]]","actors":["[[Coding Agent]]"],"tools":["[[Alerting]]"],"content":"Propose a fix for an alert."},"linkTargets":["Propose a fix for an alert"],"type":"Step","source":{"file":"Propose a fix for an alert.md","line":1},"contentLinks":[],"content":"Propose a fix for an alert.","resolvedType":"Step","resolvedParents":[{"id":"Operate.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Collect usage feedback.md","title":"Collect usage feedback","schemaData":{"title":"Collect usage feedback","type":"Step","stage":"[[Operate]]","actors":["[[Product Manager]]"],"tools":["[[Issue Tracker]]"],"content":"Collect usage feedback."},"linkTargets":["Collect usage feedback"],"type":"Step","source":{"file":"Collect usage feedback.md","line":1},"contentLinks":[],"content":"Collect usage feedback.","resolvedType":"Step","resolvedParents":[{"id":"Operate.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Keep the glossary current.md","title":"Keep the glossary current","schemaData":{"title":"Keep the glossary current","type":"Step","actors":["[[Coding Agent]]"],"content":"Keep the glossary current."},"linkTargets":["Keep the glossary current"],"type":"Step","source":{"file":"Keep the glossary current.md","line":1},"contentLinks":[],"content":"Keep the glossary current.","resolvedType":"Step","resolvedParents":[],"resolvedLinks":[]} +{"id":"Hold a retrospective.md","title":"Hold a retrospective","schemaData":{"title":"Hold a retrospective","type":"Step","stage":"[[Review]]","content":"Hold a retrospective."},"linkTargets":["Hold a retrospective"],"type":"Step","source":{"file":"Hold a retrospective.md","line":1},"contentLinks":[],"content":"Hold a retrospective.","resolvedType":"Step","resolvedParents":[{"id":"Review.md","field":"stage","fieldOn":"child","kind":"hierarchy","hierarchy":"schema","selfRef":false}],"resolvedLinks":[]} +{"id":"Tidy stale branches.md","title":"Tidy stale branches","schemaData":{"title":"Tidy stale branches","type":"Step","tools":["[[CI Pipeline]]"],"content":"Tidy stale branches."},"linkTargets":["Tidy stale branches"],"type":"Step","source":{"file":"Tidy stale branches.md","line":1},"contentLinks":[],"content":"Tidy stale branches.","resolvedType":"Step","resolvedParents":[],"resolvedLinks":[]} diff --git a/packages/map-views/tests/fixtures/sdlc/schema.json b/packages/map-views/tests/fixtures/sdlc/schema.json new file mode 100644 index 0000000..b2c9a93 --- /dev/null +++ b/packages/map-views/tests/fixtures/sdlc/schema.json @@ -0,0 +1,43 @@ +{ + "$schema": "https://raw.githubusercontent.com/mindsocket/structured-context/main/schemas/generated/latest/_structured_context_schema_meta.json", + "$id": "sctx://sdlc", + "title": "Software delivery lifecycle", + "description": "Synthetic schema: the stages of delivering software, the actors (people and agents) in them, the steps they take and the tools the steps use.", + "$metadata": { + "hierarchy": { + "levels": ["Stage", { "type": "Step", "field": "stage" }] + }, + "relationships": [ + { "parent": "Step", "type": "Actor", "field": "actors", "fieldOn": "parent", "multiple": true }, + { "parent": "Step", "type": "Tool", "field": "tools", "fieldOn": "parent", "multiple": true } + ] + }, + "oneOf": [ + { + "type": "object", + "properties": { "type": { "const": "Stage" }, "title": { "type": "string" }, "order": { "type": "integer" } }, + "required": ["type", "title"] + }, + { + "type": "object", + "properties": { + "type": { "const": "Step" }, + "title": { "type": "string" }, + "stage": { "type": "string" }, + "actors": { "type": "array", "items": { "type": "string" } }, + "tools": { "type": "array", "items": { "type": "string" } } + }, + "required": ["type", "title"] + }, + { + "type": "object", + "properties": { "type": { "const": "Actor" }, "title": { "type": "string" } }, + "required": ["type", "title"] + }, + { + "type": "object", + "properties": { "type": { "const": "Tool" }, "title": { "type": "string" } }, + "required": ["type", "title"] + } + ] +} From dd16ffd39b207adc36ef1109b4756bc915242ed8 Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Wed, 18 Nov 2026 13:38:43 +1100 Subject: [PATCH 2/2] Landscape: strips, divided into cells by dimensions A landscape is one or more strips laid out one after the other. Each strip has its own grouping levels (`group`) and nests them as before. A dimension divides strips into cells, one per group: a group for every node of a type, or for every value of a field. The layout's `dimension` divides every strip alike, so strips line up; a strip's own `dimension` divides that strip further. A strip's first level is joined to a dimension's node the way a level is joined to the level above, so `via` and `edge` apply there. `showUngrouped` (default true) draws, or hides, the nodes of a strip that no cell or container reached. `orientation` decides which way the layout dimension runs; the direction is chosen in one place in the component. `buildLandscape` returns one shape, `{ dimension?, strips }`. A plain landscape is one strip with one cell and no dimension, and renders as nested containers with no grid. The synthetic AI-assisted delivery fixture exercises dimensions, a swimlane and strips joined through `via`. --- AGENTS.md | 7 +- docs/concepts.md | 2 +- docs/layouts.md | 28 +- .../src/components/LandscapeLayout.tsx | 202 ++++++++++-- .../map-views/src/core/layouts/helpers.ts | 7 +- .../src/core/layouts/landscape/projection.ts | 209 +++++++++--- .../src/core/layouts/landscape/schema.ts | 160 ++++++--- packages/map-views/tests/definition.test.ts | 8 +- .../map-views/tests/landscape-strips.test.ts | 312 ++++++++++++++++++ packages/map-views/tests/landscape.test.ts | 54 +-- .../generated/latest/layouts/landscape.json | 270 +++++++++++---- 11 files changed, 1022 insertions(+), 237 deletions(-) create mode 100644 packages/map-views/tests/landscape-strips.test.ts diff --git a/AGENTS.md b/AGENTS.md index 8f850d1..57a86cd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,7 +2,7 @@ Declarative map views of structured-context spaces: the definition format, the rendering library and the navigator app. -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. +Before new work, read [docs/concepts.md](docs/concepts.md) for the terms (and the layout's section of [docs/layouts.md](docs/layouts.md) when working on one layout) and [docs/architecture.md](docs/architecture.md#modules) for the modules and what each may import. ## Checks @@ -15,8 +15,9 @@ bun run build # the library, then the navigator ## 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 term per concept.** A thing has the same name in the definition format, the docs, comments and code. Add, rename or refine common terms (when they're unclear or new requirements go beyond existing definitions) in `docs/concepts.md`, and do the same in `docs/layouts.md` for a term only one layout uses. 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. +- **A setting's type says how many behaviours it has.** A boolean for on or off, when no third option is expected. An enum when there are two or more behaviours, each value naming one (`dag: 'repeat' | 'cross-edge'`). - **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. @@ -51,7 +52,7 @@ Review and update with any change: | Change | Check | |---|---| | 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` | +| New or renamed term | `docs/concepts.md`; and `docs/layouts.md` for a term of one layout | | Exports or component props | `docs/api.md` | | Module structure, rendering, styling | `docs/architecture.md` | | Anything user-visible | `README.md` (kept short; detail goes in `docs/`) | diff --git a/docs/concepts.md b/docs/concepts.md index 73caa3e..a124ada 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -16,7 +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. Each layout carries its own opinions (spacing, card sizes, colours). Definitions choose and configure a layout; they don't compose one. [Layouts](layouts.md) describes each one, with the terms that belong to it alone. +The arrangement a region uses, chosen from a fixed catalogue. Each layout carries its own opinions (spacing, card sizes, colours). Definitions choose and configure a layout; they don't compose one. [Layouts](layouts.md) describes each one. ## Projection diff --git a/docs/layouts.md b/docs/layouts.md index b79b691..104fb49 100644 --- a/docs/layouts.md +++ b/docs/layouts.md @@ -15,14 +15,25 @@ A tree over the schema's hierarchy: nodes of the root type at the top, children ## landscape -Nested containers. `group` lists grouping levels, outermost first. The last level is drawn as nodes and the others as containers. +Strips of nested containers. A **strip** is a list of grouping levels, outermost first: the last level is drawn as nodes and the others as containers. A plain landscape is one strip. Several strips are drawn one after the other, each with its own levels. + +A **dimension** divides strips into **cells**, one for each of its groups. The layout's dimension divides every strip alike, so the strips line up; a strip's own dimension divides that strip further. With both, a strip has a cell for every pair of groups. + +| Setting | Values | Default | +|---|---|---| +| `orientation` | `horizontal`: top-level containers, or the layout dimension's groups, side by side, and strips stacked. `vertical`: the reverse | `horizontal` | +| `dimension` | A dimension (below) dividing every strip | none | +| `strips` | One or more strips | required | + +A strip has: | Setting | Values | Default | |---|---|---| -| `orientation` | `horizontal` (top-level containers as columns), `vertical` (as rows) | `horizontal` | -| `group` | Grouping levels (below) | required | +| `group` | Grouping levels, outermost first | required | +| `dimension` | A dimension dividing this strip | none | +| `showUngrouped` | `true` draws the strip's ungrouped nodes in a box of their own, `false` leaves them out | `true` | -A grouping level is one of: +A 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. @@ -30,7 +41,14 @@ A grouping level is one of: - `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. +A dimension is one of: + +- `{ type: 'Stages' }`: a group for every node of the type, in space order, so a cell exists even when it holds nothing. `edge: { field: 'stage' }` restricts the join to edges from that field, and takes the place of the first level's own `edge`. +- `{ field: 'stage' }`: a group for every value the strip's first node level has in that field. A value no node has is not a group. + +A strip's first level is joined to a dimension's nodes the way a level is joined to the node level above, so `via` applies there: a strip of `{ type: 'Capabilities', via: ['Activities'] }` under a `Stages` dimension holds each stage's capabilities once, beside a strip of its activities. Under two dimensions, a node must be joined to both. + +A node that occurs in several containers or cells is repeated in each. Nodes of a strip's levels that no container or cell reaches are ungrouped. Each strip is named by its first level. ## xy diff --git a/packages/map-views/src/components/LandscapeLayout.tsx b/packages/map-views/src/components/LandscapeLayout.tsx index 82963a3..1567ab2 100644 --- a/packages/map-views/src/components/LandscapeLayout.tsx +++ b/packages/map-views/src/components/LandscapeLayout.tsx @@ -1,22 +1,24 @@ import { useMemo } from 'react'; import type { SpaceNode } from 'structured-context/api'; import type { LayoutConfig, Orientation } from '../core/definition'; -import { buildLandscape, type LandscapeOccurrence } from '../core/layouts/landscape/projection'; +import { buildLandscape, type LandscapeGroup, type LandscapeOccurrence } from '../core/layouts/landscape/projection'; import type { LayoutProps } from './layout'; import { NodeCard } from './NodeCard'; +type Level = LayoutConfig<'landscape'>['strips'][number]['group'][number]; + /** - * Nested containers following the layout's grouping levels; the last level is drawn as nodes. - * Flexbox does the nesting and wrapping. Containment shows the grouping edges, so no connectors - * are drawn. PROTOTYPE: `edges.show` has no effect here; other edges aren't drawn yet. + * Strips of nested containers following each strip's grouping levels; the last level is drawn as + * nodes. Flexbox does the nesting and wrapping, and CSS grid lays out strips divided into cells. + * Containment shows the grouping edges, so no connectors are drawn. PROTOTYPE: `edges.show` has no + * effect here; other edges aren't drawn yet. */ export function LandscapeLayout({ graph, region, instanceId, onNodeSelect }: LayoutProps>) { const { layout } = region; const landscape = useMemo(() => buildLandscape(graph, region.id, layout), [graph, region.id, layout]); - const last = layout.group.length - 1; - const breadcrumb = (occurrence: LandscapeOccurrence) => { - const level = layout.group[occurrence.level]; + const breadcrumb = (occurrence: LandscapeOccurrence, levels: readonly Level[]) => { + const level = levels[occurrence.level]; if (!level || !('type' in level) || level.intermediate !== 'breadcrumb') return null; const steps = occurrence.via.filter((step) => step.nodes.length > 0); if (steps.length === 0) return null; @@ -27,60 +29,202 @@ export function LandscapeLayout({ graph, region, instanceId, onNodeSelect }: Lay ); }; - const render = (occurrence: LandscapeOccurrence, direction: Orientation): React.ReactNode => { + /** The label of a container or a dimension's group: its node, or its field value. */ + const heading = (occurrence: LandscapeGroup | LandscapeOccurrence, levels: readonly Level[] = []) => + occurrence.item.kind === 'node' ? ( + + {'level' in occurrence && breadcrumb(occurrence, levels)} + + ) : ( + + {occurrence.item.field}: {occurrence.item.value === null ? '(none)' : displayValue(occurrence.item.value)} + + ); + + const render = ( + occurrence: LandscapeOccurrence, + direction: Orientation, + levels: readonly Level[], + ): React.ReactNode => { const repeat = occurrence.repeatOf !== undefined; const marker = { 'data-occurrence': `${instanceId}${occurrence.key}` }; + // A level is drawn as nodes when it is the strip's last. + const isLeaf = (level: number) => level === levels.length - 1; - if (occurrence.item.kind === 'node' && occurrence.level === last) { + if (occurrence.item.kind === 'node' && isLeaf(occurrence.level)) { return (
  • - {breadcrumb(occurrence)} + {breadcrumb(occurrence, levels)}
  • ); } // Containers alternate direction with depth; a container of nodes wraps them. const inner: Orientation = direction === 'horizontal' ? 'vertical' : 'horizontal'; - const holdsNodes = occurrence.level + 1 === last; + const holdsNodes = isLeaf(occurrence.level + 1); return (
  • - {occurrence.item.kind === 'node' ? ( - - {breadcrumb(occurrence)} - - ) : ( - - {occurrence.item.field}: {occurrence.item.value === null ? '(none)' : displayValue(occurrence.item.value)} - - )} + {heading(occurrence, levels)} - {occurrence.children.map((child) => render(child, inner))} + {occurrence.children.map((child) => render(child, inner, levels))}
  • ); }; const top = layout.orientation; + const ungroupedClass = 'mv:flex mv:flex-col mv:gap-2 mv:rounded-lg mv:border mv:border-dashed mv:border-edge mv:p-2'; + const ungroupedItems = (ungrouped: LandscapeOccurrence[], levels: readonly Level[]) => ( + <> + Ungrouped + {ungrouped.map((o) => render(o, top, levels))} + + ); + + const [only] = landscape.strips; + // One strip with no dimension of either kind is plain nested containers, with no grid. + const plain = only && landscape.strips.length === 1 && !landscape.dimension && !only.dimension; + if (!plain) { + const anyOwn = landscape.strips.some((strip) => strip.dimension); + // A strip takes a position for each group of its own dimension (one without), and one for its ungrouped nodes. + const sizes = landscape.strips.map( + (strip) => (strip.dimension?.length ?? 1) + (strip.ungrouped.length > 0 ? 1 : 0), + ); + const starts = sizes.map( + (_, s) => 1 + (landscape.dimension ? 1 : 0) + sizes.slice(0, s).reduce((a, b) => a + b, 0), + ); + const place = gridPlacement(top, { + lead: anyOwn ? 2 : 1, + dimensionSize: landscape.dimension?.length ?? 1, + leadStrips: landscape.dimension ? 1 : 0, + strips: sizes.reduce((a, b) => a + b, 0), + }); + return ( +
    +
    + {landscape.dimension?.map((group, i) => ( +
    + {heading(group)} +
    + ))} + {landscape.strips.map((strip, s) => { + const levels = layout.strips[s]!.group; + const start = starts[s]!; + return ( + // biome-ignore lint/suspicious/noArrayIndexKey: strips are positional, fixed by the definition. +
    +
    + {levelLabel(levels[0]!)} +
    + {strip.dimension?.map((group, j) => ( +
    + {heading(group)} +
    + ))} + {strip.cells.map((cell) => ( +
    + {cell.children.map((child) => render(child, top, levels))} +
    + ))} + {strip.ungrouped.length > 0 && ( +
    + {ungroupedItems(strip.ungrouped, levels)} +
    + )} +
    + ); + })} +
    +
    + ); + } + + const levels = layout.strips[0]!.group; return (
    - - {landscape.groups.map((group) => render(group, top))} - {landscape.ungrouped.length > 0 && ( -
  • - Ungrouped - {landscape.ungrouped.map((o) => render(o, top))} -
  • - )} + + {only.cells[0]!.children.map((group) => render(group, top, levels))} + {only.ungrouped.length > 0 &&
  • {ungroupedItems(only.ungrouped, levels)}
  • }
    ); } +const levelLabel = (level: Level) => ('type' in level ? level.type : level.field); + +/** + * Where the grid's labels, headings and cells go. The only place that decides which way the layout + * dimension runs: with `horizontal` its groups sit side by side, like top-level containers elsewhere + * in this layout, and strips stack; with `vertical` its groups stack and strips sit side by side. + * Along the layout dimension's axis, the leading positions hold the strip names and, if any strip + * has its own dimension, that dimension's headings. Along the strips' axis, the first holds the + * layout dimension's headings. + * PROTOTYPE: track sizes are fixed guesses, headings scroll away with the grid, and a grid has no + * connectors or highlights. + */ +function gridPlacement( + orientation: Orientation, + shape: { lead: number; dimensionSize: number; leadStrips: number; strips: number }, +) { + const dimensionAcross = orientation === 'horizontal'; + /** A start line, and how many lines it spans. */ + const lines = (start: number, span = 1) => (span === 1 ? start : `${start} / span ${span}`); + /** `onDimension` runs along the layout dimension's axis, `onStrips` along the strips'. */ + const at = (onDimension: number, onStrips: number, dimensionSpan = 1, stripsSpan = 1) => + dimensionAcross + ? { gridColumn: lines(onDimension, dimensionSpan), gridRow: lines(onStrips, stripsSpan) } + : { gridColumn: lines(onStrips, stripsSpan), gridRow: lines(onDimension, dimensionSpan) }; + const groupsStart = shape.lead + 1; + return { + // Only the columns are given tracks; the rows size to their content. + container: { + gridTemplateColumns: dimensionAcross + ? `${'max-content '.repeat(shape.lead)}repeat(${shape.dimensionSize}, minmax(9rem, 1fr))` + : `${'max-content '.repeat(shape.leadStrips)}repeat(${shape.strips}, minmax(9rem, 1fr))`, + }, + heading: (index: number) => at(groupsStart + index, 1), + name: (start: number, span: number) => at(1, start, 1, span), + stripHeading: (line: number) => at(2, line), + cell: (index: number, line: number) => at(groupsStart + index, line), + ungrouped: (line: number) => at(groupsStart, line, shape.dimensionSize), + }; +} + function Items({ direction, children }: { direction: Orientation | 'wrap'; children: React.ReactNode }) { const layout = { horizontal: 'mv:flex-row mv:items-start mv:gap-3', diff --git a/packages/map-views/src/core/layouts/helpers.ts b/packages/map-views/src/core/layouts/helpers.ts index 84a177e..2496550 100644 --- a/packages/map-views/src/core/layouts/helpers.ts +++ b/packages/map-views/src/core/layouts/helpers.ts @@ -52,10 +52,11 @@ export function assignLanes(connectors: Connector[]) { } /** - * 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. + * One step of an occurrence path: a node title, a `[field, value]` group, `null` for the ungrouped + * area, or a number for a part of the layout picked by position. Each kind encodes differently in + * JSON, so none can collide with another. */ -export type PathSegment = string | readonly [field: string, value: string | null] | null; +export type PathSegment = string | readonly [field: string, value: string | null] | null | number; /** * Path-based key for one occurrence of a node: region, then the steps from the outermost diff --git a/packages/map-views/src/core/layouts/landscape/projection.ts b/packages/map-views/src/core/layouts/landscape/projection.ts index ae240b8..678b2e9 100644 --- a/packages/map-views/src/core/layouts/landscape/projection.ts +++ b/packages/map-views/src/core/layouts/landscape/projection.ts @@ -6,9 +6,9 @@ import { childEdges, occurrenceKey, type PathSegment, parentEdges } from '../hel export type LandscapeOccurrence = { /** Path-based key, unique within the map view (see {@link occurrenceKey}). */ key: string; - /** Index of the grouping level this occurrence belongs to. */ + /** Index of the grouping level this occurrence belongs to, within its strip. */ level: number; - /** A node, or a field value shared by the nodes inside (`null`: the field is empty). */ + /** A node, or a field value common to the nodes inside (`null`: the field is empty). */ item: { kind: 'node'; node: SpaceNode } | { kind: 'value'; field: string; value: string | null }; /** Nodes on the `via` chain that joined this node to the node level above, one entry per skipped type. */ via: ViaStep[]; @@ -19,61 +19,104 @@ export type LandscapeOccurrence = { type ViaStep = { type: string; nodes: SpaceNode[] }; -export type Landscape = { - groups: LandscapeOccurrence[]; +/** A group of a dimension: a node of the dimension's type, or a value of its field. It holds nothing itself. */ +export type LandscapeGroup = Pick; + +type LandscapeStrip = { + /** The strip's own dimension, dividing it further. */ + dimension?: LandscapeGroup[]; /** - * Nodes of a grouped level that no container above reaches (e.g. an Activity with no - * Outcome when grouping by Outcomes), each with its own contents. + * A cell for every group of the layout's dimension paired with every group of the strip's own, the + * layout's varying slowest. A strip with no dimension has one cell. + */ + cells: LandscapeCell[]; + /** + * Nodes of the strip's levels that no cell or container reached (e.g. an Activity with no + * Outcome when grouping by Outcomes), each with its own contents. Empty when the strip hides them. */ ungrouped: LandscapeOccurrence[]; }; +/** What the strip's grouping levels place among the nodes that belong to one group of each dimension. */ +type LandscapeCell = { + /** Path-based key of the strip and its group or pair of groups. */ + key: string; + /** Indexes of its groups in the layout's dimension and in the strip's own; 0 where there is none. */ + at: [layout: number, strip: number]; + children: LandscapeOccurrence[]; +}; + +/** + * The layout as strips divided into cells. A dimension's groups are worked out once, so every cell + * exists, empty or not. Which axis a dimension runs along is the component's choice. A plain + * landscape is one strip with one cell and no dimension: the cell holds its top-level containers. + */ +export type Landscape = { + /** The layout's dimension: its groups divide every strip alike, so the strips line up. */ + dimension?: LandscapeGroup[]; + /** The strips, in order. */ + strips: LandscapeStrip[]; +}; + type Candidate = { node: SpaceNode; via: ViaStep[] }; -type FieldFilter = { field: string; value: string | null }; +type ValueFilter = { field: string; value: string | null }; +type NodeFilter = { node: SpaceNode; edge?: string }; +/** Keeps the nodes with a field value, or the nodes joined to a node (across edges from `edge`, if set). */ +type Filter = ValueFilter | NodeFilter; /** - * Lay a space out as nested containers following the layout's grouping levels. + * Lay a space out as strips of nested containers following each strip's grouping levels. * * Adjacent node levels are joined by any edge between their types, in either direction, or only * edges from `edge.field`. A `via` chain joins them through the skipped types. A field level * splits the next node level by that field's values. A node reached from several containers * appears in each, in full: the levels are finite, so repeating contents can't recurse. + * + * A dimension divides a strip into cells. A strip's first level is joined to a dimension's node the + * way a level is joined to the node level above, so `via` applies there too. */ export function buildLandscape(graph: SpaceGraph, regionId: string, layout: LayoutConfig<'landscape'>): Landscape { - const levels = layout.group; const order = new Map([...graph.nodes.keys()].map((title, i) => [title, i])); + // The first occurrence of each node, across strips, for marking repeats. const first = new Map(); - const occurrenceFor = (candidate: Candidate, levelIdx: number, path: readonly PathSegment[]): LandscapeOccurrence => { + const occurrenceFor = ( + strip: StripContext, + candidate: Candidate, + levelIdx: number, + path: readonly PathSegment[], + ): LandscapeOccurrence => { const { node } = candidate; const nodePath = [...path, node.id]; const key = occurrenceKey(regionId, nodePath); const repeatOf = first.get(node.id); if (repeatOf === undefined) first.set(node.id, key); + strip.placed.add(node.id); return { key, level: levelIdx, item: { kind: 'node', node }, via: candidate.via, ...(repeatOf !== undefined && { repeatOf }), - children: place(levelIdx + 1, node, [], nodePath), + children: place(strip, levelIdx + 1, node, [], nodePath), }; }; - /** Occurrences for level `levelIdx` inside `anchor`, the nearest enclosing node. */ + /** Occurrences for level `levelIdx` of a strip inside `anchor`, the nearest enclosing node. */ const place = ( + strip: StripContext, levelIdx: number, anchor: SpaceNode | undefined, - filters: readonly FieldFilter[], + filters: readonly Filter[], path: readonly PathSegment[], ): LandscapeOccurrence[] => { - const level = levels[levelIdx]; + const level = strip.levels[levelIdx]; if (level === undefined) return []; if (isTypeLevel(level)) { - return candidates(level, anchor, filters).map((c) => occurrenceFor(c, levelIdx, path)); + return candidates(level, anchor, filters).map((c) => occurrenceFor(strip, c, levelIdx, path)); } - const nodeLevel = levels.slice(levelIdx).find(isTypeLevel)!; + const nodeLevel = strip.levels.slice(levelIdx).find(isTypeLevel)!; const values = distinctValues( candidates(nodeLevel, anchor, filters).map((c) => c.node), level.field, @@ -85,22 +128,32 @@ export function buildLandscape(graph: SpaceGraph, regionId: string, layout: Layo level: levelIdx, item: { kind: 'value', field: level.field, value }, via: [], - children: place(levelIdx + 1, anchor, [...filters, { field: level.field, value }], valuePath), + children: place(strip, levelIdx + 1, anchor, [...filters, { field: level.field, value }], valuePath), }; }); }; - /** Nodes of a type level joined to `anchor` (all of the type at the top) and matching the filters. */ - const candidates = ( - level: TypeLevel, - anchor: SpaceNode | undefined, - filters: readonly FieldFilter[], - ): Candidate[] => { - const reached: Candidate[] = - anchor === undefined - ? ofType(level.type).map((node) => ({ node, via: [] })) - : walkChain(anchor, level.via ?? [], level.type, level.edge?.field); - return reached.filter(({ node }) => filters.every((f) => hasValue(node, f))); + /** + * Nodes of a type level joined to `anchor` and matching the filters. With no anchor they are all + * of the type at the top, or, under dimension nodes, those joined to every one of them. + */ + const candidates = (level: TypeLevel, anchor: SpaceNode | undefined, filters: readonly Filter[]): Candidate[] => { + const nodeFilters = filters.filter((f): f is NodeFilter => 'node' in f); + let reached: Candidate[]; + if (anchor !== undefined) { + reached = walkChain(anchor, level.via ?? [], level.type, level.edge?.field); + } else if (nodeFilters.length === 0) { + reached = ofType(level.type).map((node) => ({ node, via: [] })); + } else { + // PROTOTYPE: a dimension's `edge` applies to the last hop of a `via` chain, like a level's own, + // and the skipped nodes shown for `intermediate: breadcrumb` come from the layout dimension only. + const [head, ...rest] = nodeFilters.map((f) => + walkChain(f.node, level.via ?? [], level.type, f.edge ?? level.edge?.field), + ); + reached = head!.filter((c) => rest.every((others) => others.some((o) => o.node.id === c.node.id))); + } + const values = filters.filter((f): f is ValueFilter => 'field' in f); + return reached.filter(({ node }) => values.every((f) => valuesOf(node, f.field).includes(f.value))); }; const ofType = (type: string) => [...graph.nodes.values()].filter((node) => node.resolvedType === type); @@ -146,22 +199,98 @@ export function buildLandscape(graph: SpaceGraph, regionId: string, layout: Layo return [...byTitle.values()].sort((a, b) => order.get(a.node.id)! - order.get(b.node.id)!); }; - const groups = place(0, undefined, [], []); - - // Nodes of an inner level that no container reached get their own contents, like tree orphans. - const ungrouped: LandscapeOccurrence[] = []; - levels.forEach((level, levelIdx) => { - if (levelIdx === 0 || !isTypeLevel(level)) return; - for (const node of ofType(level.type)) { - if (!first.has(node.id)) ungrouped.push(occurrenceFor({ node, via: [] }, levelIdx, [null])); + /** + * A dimension's groups, worked out once. A type dimension lists every node of its type, so it can + * show a group that holds nothing. A field dimension takes the values the nodes of `drawn` (the + * types of the first node level of each strip it divides) have, so a value no node has is not a group. + * A node with no value, or joined to no node of the dimension, is in none of its groups; it + * is shown as ungrouped, the same for both kinds. + * PROTOTYPE: groups come in space order. A field's declared domain, or an `order` field, would give + * the order authors expect and let a field dimension show empty groups too. + */ + const dimensionGroups = ( + dimension: Dimension, + drawn: readonly string[], + prefix: readonly PathSegment[], + ): { group: LandscapeGroup; filter: Filter; segment: PathSegment }[] => { + if ('type' in dimension) { + return ofType(dimension.type).map((node) => ({ + group: { key: occurrenceKey(regionId, [...prefix, node.id]), item: { kind: 'node', node } }, + filter: { node, edge: dimension.edge?.field }, + segment: node.id, + })); } + const { field } = dimension; + const nodes = drawn.flatMap(ofType); + return distinctValues(nodes, field) + .filter((v) => v !== null) + .map((value) => ({ + group: { key: occurrenceKey(regionId, [...prefix, [field, value]]), item: { kind: 'value', field, value } }, + filter: { field, value }, + segment: [field, value], + })); + }; + + const firstNodeType = (strip: Strip) => strip.group.find(isTypeLevel)!.type; + + /** Nodes of the strip's levels that no container or cell reached get their own contents, like tree orphans. */ + const orphans = (strip: StripContext, hasDimension: boolean, path: readonly PathSegment[]) => { + const ungrouped: LandscapeOccurrence[] = []; + strip.levels.forEach((level, levelIdx) => { + // The first level has no container above it unless a dimension divides the strip. + if ((levelIdx === 0 && !hasDimension) || !isTypeLevel(level)) return; + for (const node of ofType(level.type)) { + if (!strip.placed.has(node.id)) { + ungrouped.push(occurrenceFor(strip, { node, via: [] }, levelIdx, [...path, null])); + } + } + }); + return ungrouped; + }; + + const layoutGroups = layout.dimension + ? dimensionGroups(layout.dimension, [...new Set(layout.strips.map(firstNodeType))], []) + : undefined; + const strips = layout.strips.map((strip, s): LandscapeStrip => { + const context: StripContext = { levels: strip.group, placed: new Set() }; + // Keys name the strip only where several could share a path; a lone strip keeps the shorter key. + const stripPath: PathSegment[] = layout.strips.length > 1 ? [s] : []; + const own = strip.dimension ? dimensionGroups(strip.dimension, [firstNodeType(strip)], stripPath) : undefined; + const cells = (layoutGroups ?? [undefined]).flatMap((a, i) => + (own ?? [undefined]).map((b, j): LandscapeCell => { + const along = [a, b].filter((d) => d !== undefined); + const path = [...stripPath, ...along.map((d) => d.segment)]; + return { + key: occurrenceKey(regionId, path), + at: [i, j], + children: place( + context, + 0, + undefined, + along.map((d) => d.filter), + path, + ), + }; + }), + ); + return { + ...(own && { dimension: own.map((d) => d.group) }), + cells, + ungrouped: strip.showUngrouped + ? orphans(context, layoutGroups !== undefined || own !== undefined, stripPath) + : [], + }; }); - return { groups, ungrouped }; + return { ...(layoutGroups && { dimension: layoutGroups.map((d) => d.group) }), strips }; } -type GroupLevel = LayoutConfig<'landscape'>['group'][number]; +/** A strip being placed: its levels, and the nodes it has drawn so far. */ +type StripContext = { levels: readonly GroupLevel[]; placed: Set }; +type Strip = LayoutConfig<'landscape'>['strips'][number]; +type GroupLevel = Strip['group'][number]; type TypeLevel = Extract; +type Dimension = NonNullable['dimension']>; function isTypeLevel(level: GroupLevel): level is TypeLevel { return 'type' in level; @@ -180,7 +309,3 @@ function distinctValues(nodes: SpaceNode[], field: string): (string | null)[] { const present = [...values].filter((v): v is string => v !== null); return values.has(null) ? [...present, null] : present; } - -function hasValue(node: SpaceNode, { field, value }: FieldFilter): boolean { - return valuesOf(node, field).includes(value); -} diff --git a/packages/map-views/src/core/layouts/landscape/schema.ts b/packages/map-views/src/core/layouts/landscape/schema.ts index 586e690..0630388 100644 --- a/packages/map-views/src/core/layouts/landscape/schema.ts +++ b/packages/map-views/src/core/layouts/landscape/schema.ts @@ -2,71 +2,133 @@ import type { AuthoredLayout } from '../../definition'; 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. */ +/** A dimension: groups that are the same wherever the dimension is used. Dispatches on `field`, like a grouping level. */ +const dimensionSchema = { + type: 'object', + if: { type: 'object', required: ['field'] }, + // biome-ignore lint/suspicious/noThenProperty: JSON Schema's `then` keyword. + then: { + type: 'object', + description: + "Groups labelled by the values of a field of the strip's first node level. A value no node has is not a group.", + required: ['field'], + additionalProperties: false, + properties: { field: { type: 'string', minLength: 1 } }, + }, + else: { + type: 'object', + description: 'A group for every node of one type.', + required: ['type'], + additionalProperties: false, + properties: { + type: { + description: 'Node type of the groups.', + anyOf: [{ type: 'string', minLength: 1 }, { $ref: PARAM_REF }], + }, + edge: { + type: 'object', + description: + "Which edges join a group's node to the strip's first node level, or to its last `via` type. By default, any edge between the two types, in either direction.", + required: ['field'], + additionalProperties: false, + properties: { field: { type: 'string', minLength: 1 } }, + }, + }, + }, +} as const; + +/** Settings of the landscape layout: strips of nested containers, optionally divided into cells by dimensions. */ export const landscapeLayoutSchema = { $schema: 'https://json-schema.org/draft/2020-12/schema', $id: `${SCHEMA_URL}/layouts/landscape.json`, title: 'Landscape layout', description: - 'Nested containers: each grouping level becomes containers inside the level above, and the last level is drawn as nodes.', + "Strips, one after the other. Each strip nests its grouping levels, and its last level is drawn as nodes. A dimension divides a strip into cells: the layout's dimension divides every strip alike, so they line up, and a strip's own dimension divides that strip further.", type: 'object', - required: ['type', 'group'], + required: ['type', 'strips'], additionalProperties: false, properties: { type: { const: 'landscape' }, orientation: parameterisable( { $ref: `${SCHEMA_URL}/settings.json#/$defs/orientation` }, 'horizontal', - 'horizontal: top-level containers side by side, as columns. vertical: stacked, as rows.', + "horizontal: top-level containers, or the layout dimension's groups, side by side, as columns, and strips stacked. vertical: the reverse.", ), - group: { + dimension: { + ...dimensionSchema, + description: + 'Divides every strip. Its groups are worked out once, so every strip has the same groups in the same order, and a cell exists even when it is empty.', + }, + strips: { type: 'array', minItems: 1, - description: - 'Grouping levels, outermost first. The last level is drawn as nodes; the others as containers. Adjacent node levels are joined by any edge between their types, in either direction.', - // Dispatch on `field`, so errors come from the kind of level written, not both. + description: 'The strips, in order along the axis the layout dimension does not run along.', items: { type: 'object', - if: { type: 'object', required: ['field'] }, - // biome-ignore lint/suspicious/noThenProperty: JSON Schema's `then` keyword. - then: { - type: 'object', - description: - "Containers labelled by the values of a field of the next node level's nodes. A node with several values appears under each.", - required: ['field'], - additionalProperties: false, - properties: { field: { type: 'string', minLength: 1 } }, - }, - else: { - type: 'object', - description: 'A level of nodes of one type.', - required: ['type'], - additionalProperties: false, - properties: { - type: { - description: 'Node type at this level.', - anyOf: [{ type: 'string', minLength: 1 }, { $ref: PARAM_REF }], - }, - edge: { + required: ['group'], + additionalProperties: false, + properties: { + dimension: { + ...dimensionSchema, + description: + "Divides this strip further, along the strip's own axis. Without a layout dimension, a strip with its own dimension is a swimlane.", + }, + showUngrouped: parameterisable( + { type: 'boolean' }, + true, + "Whether to draw the nodes of the strip's levels that no cell or container reached.", + ), + group: { + type: 'array', + minItems: 1, + description: + 'Grouping levels, outermost first. The last level is drawn as nodes; the others as containers. Adjacent node levels are joined by any edge between their types, in either direction. In a strip with a dimension, the first level is joined to each dimension node the same way, so `edge` and `via` apply there.', + // Dispatch on `field`, so errors come from the kind of level written, not both. + items: { type: 'object', - description: - 'Which edges join this level to the node level above (or to the last `via` type). By default, any edge between the two types.', - required: ['field'], - additionalProperties: false, - properties: { field: { type: 'string', minLength: 1 } }, - }, - via: { - type: 'array', - minItems: 1, - description: - 'Types skipped between the node level above and this one, in order. Nodes are joined through a chain of edges across them. Ignored on the first level, which has no level above.', - items: { type: 'string', minLength: 1 }, + if: { type: 'object', required: ['field'] }, + // biome-ignore lint/suspicious/noThenProperty: JSON Schema's `then` keyword. + then: { + type: 'object', + description: + "Containers labelled by the values of a field of the next node level's nodes. A node with several values appears under each.", + required: ['field'], + additionalProperties: false, + properties: { field: { type: 'string', minLength: 1 } }, + }, + else: { + type: 'object', + description: 'A level of nodes of one type.', + required: ['type'], + additionalProperties: false, + properties: { + type: { + description: 'Node type at this level.', + anyOf: [{ type: 'string', minLength: 1 }, { $ref: PARAM_REF }], + }, + edge: { + type: 'object', + description: + 'Which edges join this level to the node level above (or to the last `via` type). By default, any edge between the two types.', + required: ['field'], + additionalProperties: false, + properties: { field: { type: 'string', minLength: 1 } }, + }, + via: { + type: 'array', + minItems: 1, + description: + "Types skipped between the node level above (or the dimension's node) and this one, in order. Nodes are joined through a chain of edges across them. Ignored on the first level of a strip with no dimension.", + items: { type: 'string', minLength: 1 }, + }, + intermediate: parameterisable( + { $ref: `${SCHEMA_URL}/layouts/landscape.json#/$defs/intermediate` }, + 'hidden', + 'How the skipped nodes of a `via` chain are shown.', + ), + }, + }, }, - intermediate: parameterisable( - { $ref: `${SCHEMA_URL}/layouts/landscape.json#/$defs/intermediate` }, - 'hidden', - 'How the skipped nodes of a `via` chain are shown.', - ), }, }, }, @@ -82,6 +144,8 @@ export const landscapeLayoutSchema = { } as const; export function checkLandscapeLayout(layout: AuthoredLayout<'landscape'>) { - // A field level labels the nodes of a later level, so a node level must come last. - if (!('type' in layout.group.at(-1)!)) return 'the last grouping level must be a node type, not a field'; + // A field level labels the nodes of a later level, so a node level must come last in each strip. + if (layout.strips.some((strip) => !('type' in strip.group.at(-1)!))) { + return 'the last grouping level of a strip must be a node type, not a field'; + } } diff --git a/packages/map-views/tests/definition.test.ts b/packages/map-views/tests/definition.test.ts index b82d216..dc9bea6 100644 --- a/packages/map-views/tests/definition.test.ts +++ b/packages/map-views/tests/definition.test.ts @@ -120,8 +120,8 @@ describe('parseMapViewDefinition', () => { /layout has unknown type "grid"/, ], [ - `{ $id: 'sctx-map-view://t', schema: 'x', regions: [{ id: 'a', layout: { type: 'landscape', group: [{ type: 'A' }, { field: 's' }] } }] }`, - /the last grouping level must be a node type/, + `{ $id: 'sctx-map-view://t', schema: 'x', regions: [{ id: 'a', layout: { type: 'landscape', strips: [{ group: [{ type: 'A' }] }, { group: [{ type: 'B' }, { field: 's' }] }] } }] }`, + /the last grouping level of a strip must be a node type/, ], [ `{ $id: 'sctx-map-view://t', schema: 'x', parameters: { g: { enum: ['A', 'B'], default: 'A' } }, regions: [{ id: 'a', layout: { type: 'tree', orientation: { $param: 'g' } } }] }`, @@ -155,10 +155,6 @@ describe('parseMapViewDefinition', () => { `{ $id: 'sctx-map-view://t', schema: 'x', regions: [{ id: 'a', layout: { type: 'xy', x: { field: 'e', domain: [1, 0] }, y: { field: 'v' } } }] }`, /x domain must be \[min, max\] with min < max/, ], - [ - `{ $id: 'sctx-map-view://t', schema: 'x', regions: [{ id: 'a', layout: { type: 'xy', x: { field: 'e' } } }] }`, - /must have required property 'y'/, - ], ])('rejects %s', (source, message) => { expect(() => parseMapViewDefinition('t', source)).toThrow(message); }); diff --git a/packages/map-views/tests/landscape-strips.test.ts b/packages/map-views/tests/landscape-strips.test.ts new file mode 100644 index 0000000..361ebba --- /dev/null +++ b/packages/map-views/tests/landscape-strips.test.ts @@ -0,0 +1,312 @@ +import { describe, expect, test } from 'bun:test'; +import { createElement } from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import type { SpaceNode } from 'structured-context/api'; +import { MapView } from '../src/components/MapView'; +import { type LayoutConfig, parseMapViewDefinition } from '../src/core/definition'; +import { + buildLandscape, + type LandscapeGroup, + type LandscapeOccurrence, +} from '../src/core/layouts/landscape/projection'; +import { jsonlFixtureGraph } from './fixture-graph'; + +const graph = jsonlFixtureGraph('sdlc'); +const nodesOf = (type: string) => [...graph.nodes.values()].filter((n) => n.resolvedType === type); +const stages = nodesOf('Stage'); +const actors = nodesOf('Actor'); +const tools = nodesOf('Tool'); +const steps = nodesOf('Step'); + +/** The titles a node's wikilink field names. */ +const linked = (node: SpaceNode, field: string): string[] => { + const raw = node.schemaData[field]; + return (Array.isArray(raw) ? raw : raw === undefined ? [] : [raw]).map((v) => String(v).replace(/^\[\[|\]\]$/g, '')); +}; +const stageOf = (step: SpaceNode) => linked(step, 'stage')[0]; +const actorsOf = (step: SpaceNode) => linked(step, 'actors'); +/** The titles the given steps name in a field, in the space's order of `all`. */ +const reached = (of: SpaceNode[], field: string, all: SpaceNode[]) => { + const names = new Set(of.flatMap((s) => linked(s, field))); + return all.filter((n) => names.has(n.title)).map((n) => n.title); +}; + +type Config = LayoutConfig<'landscape'>; +const level = (type: string, extra: object = {}) => ({ type, intermediate: 'hidden' as const, ...extra }); +const step = level('Step'); +const strip = (group: Config['strips'][number]['group'], dimension?: Config['dimension'], showUngrouped = true) => ({ + group, + showUngrouped, + ...(dimension && { dimension }), +}); +const layout = (strips: Config['strips'], dimension?: Config['dimension']): Config => ({ + type: 'landscape', + orientation: 'horizontal', + strips, + ...(dimension && { dimension }), +}); + +const title = (o: Pick) => + o.item.kind === 'node' ? o.item.node.title : String(o.item.value); +const cellTitles = (cell: { children: LandscapeOccurrence[] }) => cell.children.map(title); +const unplaced = steps.filter((s) => stageOf(s) === undefined || actorsOf(s).length === 0); +const build = (config: Config) => buildLandscape(graph, 'main', config); + +describe('one strip with a layout dimension', () => { + const grid = build(layout([strip([step])], { type: 'Stage' })); + const [only] = grid.strips; + + test('the strip has a cell for every group, and the steps that belong to it', () => { + expect(grid.dimension!.map(title)).toEqual(stages.map((n) => n.title)); + expect(only!.dimension).toBeUndefined(); + expect(only!.cells.map((c) => c.at)).toEqual(stages.map((_, i) => [i, 0])); + for (const cell of only!.cells) { + const stage = title(grid.dimension![cell.at[0]]!); + expect(cellTitles(cell)).toEqual(steps.filter((s) => stageOf(s) === stage).map((s) => s.title)); + } + }); + + test('a group with nothing in it still has its cell, and steps with no stage are ungrouped', () => { + expect(only!.cells.some((c) => c.children.length === 0)).toBe(true); + expect(only!.ungrouped.map(title)).toEqual(steps.filter((s) => stageOf(s) === undefined).map((s) => s.title)); + }); + + test('a strip with only its own dimension holds the same cells, the other way round', () => { + const transposed = build(layout([strip([step], { type: 'Stage' })])); + expect(transposed.dimension).toBeUndefined(); + expect(transposed.strips[0]!.dimension!.map(title)).toEqual(grid.dimension!.map(title)); + expect(transposed.strips[0]!.cells.map((c) => c.at)).toEqual(stages.map((_, j) => [0, j])); + expect(transposed.strips[0]!.cells.map(cellTitles)).toEqual(only!.cells.map(cellTitles)); + }); +}); + +describe('a layout dimension and a strip dimension (swimlane)', () => { + const grid = build(layout([strip([step], { type: 'Actor', edge: { field: 'actors' } })], { type: 'Stage' })); + const [only] = grid.strips; + const own = only!.dimension as LandscapeGroup[]; + + test('the cells are the cross product, the layout dimension varying slowest', () => { + expect(own.map(title)).toEqual(actors.map((n) => n.title)); + expect(only!.cells.map((c) => c.at)).toEqual(stages.flatMap((_, i) => actors.map((_, j) => [i, j]))); + expect(new Set(only!.cells.map((c) => c.key)).size).toBe(only!.cells.length); + }); + + test('a cell holds the steps in its stage with its actor; empty cells and empty stages are present', () => { + for (const cell of only!.cells) { + const stage = title(grid.dimension![cell.at[0]]!); + const actor = title(own[cell.at[1]]!); + expect(cellTitles(cell)).toEqual( + steps.filter((s) => stageOf(s) === stage && actorsOf(s).includes(actor)).map((s) => s.title), + ); + } + const emptyStage = stages.find((s) => !steps.some((x) => stageOf(x) === s.title))!; + const index = grid.dimension!.findIndex((g) => title(g) === emptyStage.title); + expect(only!.cells.filter((c) => c.at[0] === index).every((c) => c.children.length === 0)).toBe(true); + }); + + test('a step with several actors repeats in each of their cells, in full', () => { + const several = steps.find((s) => stageOf(s) !== undefined && actorsOf(s).length > 1)!; + const placed = only!.cells.flatMap((c) => c.children).filter((o) => title(o) === several.title); + expect(placed).toHaveLength(actorsOf(several).length); + expect(placed.slice(1).every((o) => o.repeatOf === placed[0]!.key)).toBe(true); + }); + + test('steps missing either dimension are ungrouped; field dimensions agree with type dimensions', () => { + expect(only!.ungrouped.map(title)).toEqual(unplaced.map((s) => s.title)); + const byField = build(layout([strip([step], { field: 'actors' })], { field: 'stage' })); + expect(byField.strips[0]!.ungrouped.map(title)).toEqual(only!.ungrouped.map(title)); + expect(new Set(byField.strips[0]!.cells.flatMap(cellTitles))).toEqual(new Set(only!.cells.flatMap(cellTitles))); + }); + + test('a value no step has is not a field group, unlike a node of a type dimension', () => { + const byField = build(layout([strip([step], { field: 'actors' })], { field: 'stage' })); + const emptyStage = stages.find((s) => !steps.some((x) => stageOf(x) === s.title))!; + expect(byField.dimension!.map(title)).not.toContain(`[[${emptyStage.title}]]`); + }); + + test('an `edge` that is not the join leaves every cell empty', () => { + const none = build(layout([strip([step], { type: 'Actor', edge: { field: 'tools' } })], { type: 'Stage' })); + expect(none.strips[0]!.cells.every((c) => c.children.length === 0)).toBe(true); + }); + + test('a cell holds several grouping levels', () => { + const nested = build(layout([strip([step, level('Tool')], { type: 'Actor' })], { type: 'Stage' })); + const occurrences = nested.strips[0]!.cells.flatMap((c) => c.children); + expect(occurrences.length).toBeGreaterThan(0); + for (const o of occurrences) { + const node = (o.item as { node: SpaceNode }).node; + expect(o.children.map(title).sort()).toEqual(linked(node, 'tools').sort()); + } + }); +}); + +describe('a strip joined through `via` (blueprint)', () => { + const config = layout([strip([step]), strip([level('Tool', { via: ['Step'] })])], { type: 'Stage' }); + const grid = build(config); + const [stepStrip, toolStrip] = grid.strips; + + test('every strip has the layout dimension’s groups, so the strips line up', () => { + expect(stepStrip!.cells.map((c) => c.at)).toEqual(toolStrip!.cells.map((c) => c.at)); + expect(toolStrip!.cells).toHaveLength(stages.length); + }); + + test('a stage holds each tool its steps reach once, however many steps reach it', () => { + for (const cell of toolStrip!.cells) { + const stage = title(grid.dimension![cell.at[0]]!); + const inStage = steps.filter((s) => stageOf(s) === stage); + expect(cell.children.map(title)).toEqual(reached(inStage, 'tools', tools)); + } + }); + + test('a tool reached from several stages repeats in full, and keys are unique across strips', () => { + const byTitle = Map.groupBy( + toolStrip!.cells.flatMap((c) => c.children), + title, + ); + const several = [...byTitle.values()].find((list) => list.length > 1)!; + expect(several[0]!.repeatOf).toBeUndefined(); + expect(several.slice(1).every((o) => o.repeatOf === several[0]!.key)).toBe(true); + const keys = grid.strips.flatMap((s) => s.cells.flatMap((c) => [c.key, ...c.children.map((o) => o.key)])); + expect(new Set(keys).size).toBe(keys.length); + }); + + test('a strip joined through `via` lists the nodes no stage reached', () => { + const reachedTools = new Set(steps.filter((s) => stageOf(s)).flatMap((s) => linked(s, 'tools'))); + expect(toolStrip!.ungrouped.map(title)).toEqual( + tools.filter((t) => !reachedTools.has(t.title)).map((t) => t.title), + ); + }); +}); + +describe('a swimlane strip beside a strip joined through `via` (hybrid)', () => { + const grid = build( + layout([strip([step], { type: 'Actor', edge: { field: 'actors' } }), strip([level('Tool', { via: ['Step'] })])], { + type: 'Stage', + }), + ); + + test('the first strip is the grid of both dimensions; the other has one cell per stage', () => { + expect(grid.strips[0]!.cells).toHaveLength(stages.length * actors.length); + expect(grid.strips[1]!.cells.map((c) => c.at)).toEqual(stages.map((_, i) => [i, 0])); + }); + + test('a stage’s tools come from all its steps, not only those placed under an actor', () => { + for (const cell of grid.strips[1]!.cells) { + const stage = title(grid.dimension![cell.at[0]]!); + expect(cell.children.map(title)).toEqual( + reached( + steps.filter((s) => stageOf(s) === stage), + 'tools', + tools, + ), + ); + } + }); +}); + +describe('strips with their own dimensions and no layout dimension', () => { + const grid = build(layout([strip([step], { type: 'Stage' }), strip([step], { type: 'Actor' })])); + + test('each strip is divided by its own dimension alone', () => { + expect(grid.strips[0]!.cells).toHaveLength(stages.length); + expect(grid.strips[1]!.cells).toHaveLength(actors.length); + }); + + test('a step appears in both strips, a repeat in the second, with unique keys', () => { + const inFirst = grid.strips[0]!.cells.flatMap(cellTitles); + const second = grid.strips[1]!.cells.flatMap((c) => c.children); + const both = second.filter((o) => inFirst.includes(title(o))); + expect(both.length).toBeGreaterThan(0); + expect(both.every((o) => o.repeatOf !== undefined)).toBe(true); + const keys = grid.strips.flatMap((s) => s.cells.flatMap((c) => [c.key, ...c.children.map((o) => o.key)])); + expect(new Set(keys).size).toBe(keys.length); + }); +}); + +describe('hiding ungrouped nodes', () => { + const config = layout([strip([step], undefined, false), strip([level('Tool', { via: ['Step'] })])], { + type: 'Stage', + }); + const grid = build(config); + + test('a hidden strip has no ungrouped nodes, and the nodes it would list are not drawn', () => { + const shown = build(layout([strip([step]), strip([level('Tool', { via: ['Step'] })])], { type: 'Stage' })); + expect(shown.strips[0]!.ungrouped.length).toBeGreaterThan(0); + expect(grid.strips[0]!.ungrouped).toEqual([]); + const drawn = new Set(grid.strips[0]!.cells.flatMap(cellTitles)); + for (const orphan of shown.strips[0]!.ungrouped) expect(drawn.has(title(orphan))).toBe(false); + }); + + test('the cells and the other strips are unaffected', () => { + const shown = build(layout([strip([step]), strip([level('Tool', { via: ['Step'] })])], { type: 'Stage' })); + expect(grid.strips[0]!.cells.map(cellTitles)).toEqual(shown.strips[0]!.cells.map(cellTitles)); + expect(grid.strips[1]).toEqual(shown.strips[1]); + }); + + test('a hidden strip draws no ungrouped box, and the others still do', () => { + const html = (body: string) => + renderToStaticMarkup( + createElement(MapView, { + definition: parseMapViewDefinition( + 't', + `{ $id: 'sctx-map-view://t', regions: [{ id: 'main', layout: { type: 'landscape', ${body} } }] }`, + ), + graph, + values: {}, + }), + ); + const both = (show: boolean) => + `strips: [{ showUngrouped: ${show}, dimension: { type: 'Stage' }, group: [{ type: 'Step' }] }, { dimension: { type: 'Actor' }, group: [{ type: 'Step' }] }]`; + expect([...html(both(true)).matchAll(/data-ungrouped/g)]).toHaveLength(2); + expect([...html(both(false)).matchAll(/data-ungrouped/g)]).toHaveLength(1); + }); +}); + +describe('without dimensions', () => { + test('several strips without dimensions are a grid with one cell each', () => { + const grid = build(layout([strip([step]), strip([level('Tool')])])); + expect(grid.strips.map((s) => s.cells.length)).toEqual([1, 1]); + expect(grid.strips[0]!.cells[0]!.children).toHaveLength(steps.length); + }); +}); + +describe('rendering', () => { + const html = (orientation: string, body: string) => + renderToStaticMarkup( + createElement(MapView, { + definition: parseMapViewDefinition( + 't', + `{ $id: 'sctx-map-view://t', regions: [{ id: 'main', layout: { type: 'landscape', orientation: '${orientation}', ${body} } }] }`, + ), + graph, + values: {}, + }), + ); + const blueprint = + "dimension: { type: 'Stage' }, strips: [{ group: [{ type: 'Step' }] }, { group: [{ type: 'Tool', via: ['Step'] }] }]"; + const hybrid = + "dimension: { type: 'Stage' }, strips: [{ dimension: { type: 'Actor' }, group: [{ type: 'Step' }] }, { group: [{ type: 'Tool', via: ['Step'] }] }]"; + + test('every strip has a cell for each of its groups', () => { + const page = html('horizontal', blueprint); + expect([...page.matchAll(/data-strip-cell="0"/g)]).toHaveLength(stages.length); + expect([...page.matchAll(/data-strip-cell="1"/g)]).toHaveLength(stages.length); + const swimlane = html('horizontal', hybrid); + expect([...swimlane.matchAll(/data-strip-cell="0"/g)]).toHaveLength(stages.length * actors.length); + expect([...swimlane.matchAll(/data-dimension="strip"/g)]).toHaveLength(actors.length); + }); + + test('a plain nested landscape draws no grid', () => { + expect(html('horizontal', "strips: [{ group: [{ type: 'Stage' }, { type: 'Step' }] }]")).not.toContain('data-grid'); + }); + + test('orientation moves the layout dimension’s headings to the other axis, in one place', () => { + const across = html('horizontal', hybrid).match(/data-dimension="layout"[^>]*style="([^"]*)"/)![1]!; + const down = html('vertical', hybrid).match(/data-dimension="layout"[^>]*style="([^"]*)"/)![1]!; + expect(across).toContain('grid-row:1'); + expect(down).toContain('grid-column:1'); + const name = (orientation: string) => html(orientation, hybrid).match(/data-strip-name[^>]*style="([^"]*)"/)![1]!; + expect(name('horizontal')).toMatch(/grid-column:1;/); + expect(name('vertical')).toMatch(/grid-row:1$/); + }); +}); diff --git a/packages/map-views/tests/landscape.test.ts b/packages/map-views/tests/landscape.test.ts index 953d19e..d64391c 100644 --- a/packages/map-views/tests/landscape.test.ts +++ b/packages/map-views/tests/landscape.test.ts @@ -5,10 +5,17 @@ import { fixtureGraph } from './fixture-graph'; import sample from './fixtures/launch-playbook.json'; const graph = fixtureGraph(sample); -const layout = (group: LayoutConfig<'landscape'>['group']): LayoutConfig<'landscape'> => ({ +/** A plain landscape: its containers are the one cell of its one strip. */ +function plainLandscape(...args: Parameters) { + const { dimension, strips } = buildLandscape(...args); + expect(dimension).toBeUndefined(); + expect(strips).toHaveLength(1); + return { groups: strips[0]!.cells[0]!.children, ungrouped: strips[0]!.ungrouped }; +} +const layout = (group: LayoutConfig<'landscape'>['strips'][number]['group']): LayoutConfig<'landscape'> => ({ type: 'landscape', orientation: 'horizontal', - group, + strips: [{ group, showUngrouped: true }], }); const level = (type: string) => ({ type, intermediate: 'hidden' as const }); @@ -18,7 +25,7 @@ function all(occurrences: LandscapeOccurrence[]): LandscapeOccurrence[] { const title = (o: LandscapeOccurrence) => (o.item.kind === 'node' ? o.item.node.title : o.item.value); describe('sample landscape', () => { - const byPhase = buildLandscape(graph, 'main', layout([level('Phases'), level('Activities'), level('Capabilities')])); + const byPhase = plainLandscape(graph, 'main', layout([level('Phases'), level('Activities'), level('Capabilities')])); test('top-level containers are the Phases, holding their Activities', () => { expect(byPhase.groups.map(title)).toHaveLength(4); @@ -27,43 +34,14 @@ describe('sample landscape', () => { expect(activities).toHaveLength(12); }); - test('nodes no container reaches are ungrouped, not dropped', () => { - // Some Capabilities are only sub-capabilities, with no Activity of their own. - const ungrouped = byPhase.ungrouped.map((o) => o.item.kind === 'node' && o.item.node); - expect(ungrouped.length).toBeGreaterThan(0); - expect(ungrouped.every((n) => n && n.resolvedType === 'Capabilities')).toBe(true); - const placed = new Set(all([...byPhase.groups, ...byPhase.ungrouped]).map(title)); - const capabilities = [...graph.nodes.values()].filter((n) => n.resolvedType === 'Capabilities'); - expect(capabilities.every((n) => placed.has(n.title))).toBe(true); - }); - - test('a node in several containers repeats in full, with unique keys', () => { - const occurrences = all(byPhase.groups); - expect(new Set(occurrences.map((o) => o.key)).size).toBe(occurrences.length); - const web = occurrences.filter((o) => title(o) === 'Project Website'); - expect(web.length).toBeGreaterThan(1); - expect(web[0]!.repeatOf).toBeUndefined(); - expect(web.slice(1).every((o) => o.repeatOf === web[0]!.key)).toBe(true); - }); - - test('grouping follows edges against their direction (Outcomes over Activities)', () => { - const byOutcome = buildLandscape(graph, 'main', layout([level('Outcomes'), level('Activities')])); - expect(byOutcome.groups).toHaveLength(3); - const placements = byOutcome.groups.flatMap((g) => g.children); - // 12 Activity → Outcome links in the fixture, one placement each. - expect(placements).toHaveLength(12); - const activityTitles = new Set(placements.map(title)); - expect(activityTitles.size + byOutcome.ungrouped.length).toBe(12); - }); - test('field levels split the next node level by value', () => { - const byStatus = buildLandscape(graph, 'main', layout([{ field: 'status' }, level('Applications')])); + const byStatus = plainLandscape(graph, 'main', layout([{ field: 'status' }, level('Applications')])); expect(byStatus.groups.map(title).sort()).toEqual(['identified', 'stub']); expect(byStatus.groups.flatMap((g) => g.children)).toHaveLength(8); }); test('via chains join through the skipped type and record the skipped nodes', () => { - const chained = buildLandscape( + const chained = plainLandscape( graph, 'main', layout([level('Activities'), { type: 'Applications', via: ['Capabilities'], intermediate: 'breadcrumb' }]), @@ -76,19 +54,19 @@ describe('sample landscape', () => { expect(app.via[0]!.nodes.length).toBeGreaterThan(0); } // Without the chain, Activities and Applications share no edge. - const direct = buildLandscape(graph, 'main', layout([level('Activities'), level('Applications')])); + const direct = plainLandscape(graph, 'main', layout([level('Activities'), level('Applications')])); expect(direct.groups.flatMap((g) => g.children)).toEqual([]); expect(direct.ungrouped).toHaveLength(8); }); test('edge.field restricts which edges join two levels', () => { - const none = buildLandscape( + const none = plainLandscape( graph, 'main', layout([level('Phases'), { ...level('Activities'), edge: { field: 'outcomes' } }]), ); expect(none.groups.flatMap((g) => g.children)).toEqual([]); - const phase = buildLandscape( + const phase = plainLandscape( graph, 'main', layout([level('Phases'), { ...level('Activities'), edge: { field: 'phase' } }]), @@ -98,7 +76,7 @@ describe('sample landscape', () => { test('field-group keys cannot collide with node titles', () => { const occurrences = all( - buildLandscape(graph, 'main', layout([level('Activities'), { field: 'status' }, level('Capabilities')])).groups, + plainLandscape(graph, 'main', layout([level('Activities'), { field: 'status' }, level('Capabilities')])).groups, ); expect(new Set(occurrences.map((o) => o.key)).size).toBe(occurrences.length); }); diff --git a/schemas/generated/latest/layouts/landscape.json b/schemas/generated/latest/layouts/landscape.json index 9ff3fef..3ead195 100644 --- a/schemas/generated/latest/layouts/landscape.json +++ b/schemas/generated/latest/layouts/landscape.json @@ -2,11 +2,11 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/layouts/landscape.json", "title": "Landscape layout", - "description": "Nested containers: each grouping level becomes containers inside the level above, and the last level is drawn as nodes.", + "description": "Strips, one after the other. Each strip nests its grouping levels, and its last level is drawn as nodes. A dimension divides a strip into cells: the layout's dimension divides every strip alike, so they line up, and a strip's own dimension divides that strip further.", "type": "object", "required": [ "type", - "group" + "strips" ], "additionalProperties": false, "properties": { @@ -14,7 +14,7 @@ "const": "landscape" }, "orientation": { - "description": "horizontal: top-level containers side by side, as columns. vertical: stacked, as rows.", + "description": "horizontal: top-level containers, or the layout dimension's groups, side by side, as columns, and strips stacked. vertical: the reverse.", "default": "horizontal", "anyOf": [ { @@ -25,55 +25,88 @@ } ] }, - "group": { + "dimension": { + "type": "object", + "if": { + "type": "object", + "required": [ + "field" + ] + }, + "then": { + "type": "object", + "description": "Groups labelled by the values of a field of the strip's first node level. A value no node has is not a group.", + "required": [ + "field" + ], + "additionalProperties": false, + "properties": { + "field": { + "type": "string", + "minLength": 1 + } + } + }, + "else": { + "type": "object", + "description": "A group for every node of one type.", + "required": [ + "type" + ], + "additionalProperties": false, + "properties": { + "type": { + "description": "Node type of the groups.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json#/$defs/paramRef" + } + ] + }, + "edge": { + "type": "object", + "description": "Which edges join a group's node to the strip's first node level, or to its last `via` type. By default, any edge between the two types, in either direction.", + "required": [ + "field" + ], + "additionalProperties": false, + "properties": { + "field": { + "type": "string", + "minLength": 1 + } + } + } + } + }, + "description": "Divides every strip. Its groups are worked out once, so every strip has the same groups in the same order, and a cell exists even when it is empty." + }, + "strips": { "type": "array", "minItems": 1, - "description": "Grouping levels, outermost first. The last level is drawn as nodes; the others as containers. Adjacent node levels are joined by any edge between their types, in either direction.", + "description": "The strips, in order along the axis the layout dimension does not run along.", "items": { "type": "object", - "if": { - "type": "object", - "required": [ - "field" - ] - }, - "then": { - "type": "object", - "description": "Containers labelled by the values of a field of the next node level's nodes. A node with several values appears under each.", - "required": [ - "field" - ], - "additionalProperties": false, - "properties": { - "field": { - "type": "string", - "minLength": 1 - } - } - }, - "else": { - "type": "object", - "description": "A level of nodes of one type.", - "required": [ - "type" - ], - "additionalProperties": false, - "properties": { - "type": { - "description": "Node type at this level.", - "anyOf": [ - { - "type": "string", - "minLength": 1 - }, - { - "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json#/$defs/paramRef" - } + "required": [ + "group" + ], + "additionalProperties": false, + "properties": { + "dimension": { + "type": "object", + "if": { + "type": "object", + "required": [ + "field" ] }, - "edge": { + "then": { "type": "object", - "description": "Which edges join this level to the node level above (or to the last `via` type). By default, any edge between the two types.", + "description": "Groups labelled by the values of a field of the strip's first node level. A value no node has is not a group.", "required": [ "field" ], @@ -85,26 +118,139 @@ } } }, - "via": { - "type": "array", - "minItems": 1, - "description": "Types skipped between the node level above and this one, in order. Nodes are joined through a chain of edges across them. Ignored on the first level, which has no level above.", - "items": { - "type": "string", - "minLength": 1 + "else": { + "type": "object", + "description": "A group for every node of one type.", + "required": [ + "type" + ], + "additionalProperties": false, + "properties": { + "type": { + "description": "Node type of the groups.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json#/$defs/paramRef" + } + ] + }, + "edge": { + "type": "object", + "description": "Which edges join a group's node to the strip's first node level, or to its last `via` type. By default, any edge between the two types, in either direction.", + "required": [ + "field" + ], + "additionalProperties": false, + "properties": { + "field": { + "type": "string", + "minLength": 1 + } + } + } } }, - "intermediate": { - "description": "How the skipped nodes of a `via` chain are shown.", - "default": "hidden", - "anyOf": [ - { - "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/layouts/landscape.json#/$defs/intermediate" - }, - { - "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json#/$defs/paramRef" + "description": "Divides this strip further, along the strip's own axis. Without a layout dimension, a strip with its own dimension is a swimlane." + }, + "showUngrouped": { + "description": "Whether to draw the nodes of the strip's levels that no cell or container reached.", + "default": true, + "anyOf": [ + { + "type": "boolean" + }, + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json#/$defs/paramRef" + } + ] + }, + "group": { + "type": "array", + "minItems": 1, + "description": "Grouping levels, outermost first. The last level is drawn as nodes; the others as containers. Adjacent node levels are joined by any edge between their types, in either direction. In a strip with a dimension, the first level is joined to each dimension node the same way, so `edge` and `via` apply there.", + "items": { + "type": "object", + "if": { + "type": "object", + "required": [ + "field" + ] + }, + "then": { + "type": "object", + "description": "Containers labelled by the values of a field of the next node level's nodes. A node with several values appears under each.", + "required": [ + "field" + ], + "additionalProperties": false, + "properties": { + "field": { + "type": "string", + "minLength": 1 + } } - ] + }, + "else": { + "type": "object", + "description": "A level of nodes of one type.", + "required": [ + "type" + ], + "additionalProperties": false, + "properties": { + "type": { + "description": "Node type at this level.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json#/$defs/paramRef" + } + ] + }, + "edge": { + "type": "object", + "description": "Which edges join this level to the node level above (or to the last `via` type). By default, any edge between the two types.", + "required": [ + "field" + ], + "additionalProperties": false, + "properties": { + "field": { + "type": "string", + "minLength": 1 + } + } + }, + "via": { + "type": "array", + "minItems": 1, + "description": "Types skipped between the node level above (or the dimension's node) and this one, in order. Nodes are joined through a chain of edges across them. Ignored on the first level of a strip with no dimension.", + "items": { + "type": "string", + "minLength": 1 + } + }, + "intermediate": { + "description": "How the skipped nodes of a `via` chain are shown.", + "default": "hidden", + "anyOf": [ + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/layouts/landscape.json#/$defs/intermediate" + }, + { + "$ref": "https://raw.githubusercontent.com/mindsocket/structured-context-map-views/main/schemas/generated/latest/definition.json#/$defs/paramRef" + } + ] + } + } + } } } }