Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ 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 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 term per concept.** A thing has the same name in the definition format, the docs, comments and code. Add, rename or refine terms in `docs/concepts.md`, or 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'`).
- **A setting lives at the narrowest scope where it can differ and still make sense.** Per region: how that region presents its nodes (`nodes.style`, `nodes.validation`). Never in a definition: data the host supplies (such as validation results), where a definition only chooses how to show it.
- **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.
Expand Down Expand Up @@ -57,7 +58,6 @@ Review and update with any change:
| 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/`) |
| New or changed tests | Each one proves a behaviour no other test proves; remove the ones a change makes redundant |

Docs describe what the code does now. Decision history, plans and how things used to work don't go in docs: git history records changes, and release notes record the breaking ones.

Expand All @@ -71,4 +71,4 @@ Docs describe what the code does now. Decision history, plans and how things use

## Styling

Utilities are Tailwind with the `mv` prefix and no preflight. They are deliberately unlayered, because host CSS outside a cascade layer beats anything inside one. Avoid native elements that hosts style globally (e.g. `<button>`; cards are `div role="button"`). Hosts theme through the `--mv-color-*` variables.
Utilities are Tailwind with the `mv` prefix and no preflight, and deliberately unlayered. Avoid native elements that hosts style globally (e.g. `<button>`; cards are `div role="button"`). Hosts theme through the `--mv-color-*` variables.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Pre-1.0. Docs:
bun install
bun run dev # the navigator, reading spaces from your structured-context config
bun test && bun run typecheck && bun run lint
bun run test:package # packs the library and checks it installs and typechecks in an empty project
bun run test:package # packs the library and the plugin, installs each in an empty project, typechecks a consumer and renders a page
```

Licence: MIT.
2 changes: 1 addition & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import 'structured-context-map-views/styles.css';
<MapView definition={definition} graph={graph} values={values} onNodeSelect={(node) => open(node)} />
```

`graph` is a structured-context `SpaceGraph` (see [Data](#data)); `values` and the controls' `onChange` belong to the host. Pass `annotations` to show validation results (see [Validation results](#validation-results)). `focus` and `onFocusChange` set and follow the node that layouts centring on one node show.
`graph` is a structured-context `SpaceGraph` (see [Data](#data)); `values` and the controls' `onChange` belong to the host. Pass `annotations` to show validation results (see [Validation results](#validation-results)). `focus` and `onFocusChange` set and follow the [focus](concepts.md#focus), for layouts arranged around one node.

A host that lays out the controls itself builds them from `useParameterControls` and `ParameterInput`.

Expand Down
2 changes: 1 addition & 1 deletion docs/concepts.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ The JSON5 file that declares a map view: the schema it applies to, its parameter

## Region

A part of a map view with its own node selection, layout, node style and edge setting. A definition holds a list of regions; only the first is rendered for now.
A part of a map view with its own node selection, layout, node style and edge setting. A definition holds a list of regions; only the first is rendered.

## Layout

Expand Down
8 changes: 1 addition & 7 deletions docs/definitions.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ A region's `layout` is chosen by `type`. Each layout, with its settings, is in [

Any setting the schemas mark parameterisable takes either a fixed value or `{ $param: '<name>' }`.

Each parameter is a JSON Schema with a `default` and an optional `title`. It can `$ref` a shared setting from `settings.json` (`orientation`, `nodeStyle`, `fieldList`, `validationLevel`, `validationSources`) or a layout's own definitions (e.g. `layouts/tree.json#/$defs/dag`), and narrow it. Relative refs resolve against the format's `latest` folder; full URLs work too.
Each parameter is a JSON Schema with a `default` and an optional `title`. It can `$ref` a shared setting from `settings.json` or a layout's own definitions (e.g. `layouts/tree.json#/$defs/dag`), and narrow it. Relative refs resolve against the format's `latest` folder; full URLs work too.

```json5
parameters: {
Expand All @@ -73,10 +73,6 @@ parameters: {

Writing a fixed value instead of a binding forces the setting and offers no control: `validation: 'warning'` always shows warnings and errors, `validation: 'off'` never shows results.

### Where a setting belongs

A setting lives at the narrowest scope where it can differ and still make sense. Per region: how that region presents its nodes (`nodes.style`, `nodes.validation`). Never in a definition: data the host supplies (such as validation results), where a definition only chooses how to show it.

A definition is rejected when a parameter's default doesn't match its schema, when a binding names an undeclared parameter, or when a value the parameter allows isn't valid for a setting it's bound to.

## Where definitions are found
Expand All @@ -90,5 +86,3 @@ Definitions are found the way structured-context finds plugin schemas, and each
| The `.sctx/map-views/` folder of a structured-context config root, or `map-views/` beside the global config ([resources folder](https://github.com/mindsocket/structured-context/blob/main/docs/config.md#resources-folder)), including configs pulled in by `includeSpacesFrom` | `sctx-map-view://<name>` |

Plugins are those in a config root's `.sctx/plugins/`, plus those a space or the config names (in `plugins`, or as the prefix of `schema`). Two definitions with the same `$id` are an error: to change a definition, write another with its own `$id`.

A host lists the definitions whose `schema` matches the space's schema `$id` (`mapViewsForSchema`).
2 changes: 1 addition & 1 deletion packages/map-views/src/components/layout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export type LayoutProps<L extends LayoutConfig = LayoutConfig> = {
/** Scopes occurrence keys when several map views render in one document. */
instanceId: string;
onNodeSelect?: (node: SpaceNode) => void;
/** The node a layout that centres on one node shows; the layout keeps its own once the reader picks another. */
/** The focus, for layouts arranged around one node; the layout keeps its own once the reader picks another. */
focus?: SpaceNode['id'];
onFocusChange?: (id: SpaceNode['id']) => void;
};
Expand Down
12 changes: 3 additions & 9 deletions packages/map-views/src/node/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/// <reference types="node" />
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { type Config, PLUGIN_PREFIX, resolveConfigPath, resolvePluginDir, resourceDir } from 'structured-context/api';
import type { MapViewDefinition } from '../core/definition';
Expand All @@ -14,14 +14,8 @@ const DEFINITIONS_DIR = 'map-views';
const CONFIG_PLUGINS_DIR = 'plugins';

/**
* Every map view definition available with `config`, from:
* - this package's embedded definitions (`sctx-map-view://core/<name>`);
* - each plugin found from a config folder or named by a space (`sctx-map-view://<plugin>/<name>`): the
* folder named by `"sctx": { "map-views": "…" }` in its package.json, else its `map-views/` folder;
* - the `map-views` resources folder of each config root (`sctx-map-view://<name>`).
*
* Each definition's `$id` must be in the namespace of where it was found, and ids must be unique.
* Throws on the first invalid definition.
* Every map view definition available with `config`, found as docs/definitions.md describes.
* Throws on the first invalid definition, including one outside its namespace or with a duplicate `$id`.
*
* `configDir` is the root of the main config file; it defaults to where structured-context finds it.
*/
Expand Down
4 changes: 0 additions & 4 deletions packages/map-views/tests/annotations.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,6 @@ describe('annotationsFrom', () => {
[undefined, 'parse', 'y.md', undefined],
]);
});

test('accepts no issues', () => {
expect(annotationsFrom({ issues: [] }, graph)).toEqual({ annotations: new Map(), unattached: [] });
});
});

describe('filterAnnotations', () => {
Expand Down
13 changes: 0 additions & 13 deletions packages/map-views/tests/definition.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,6 @@ describe('parseMapViewDefinition', () => {

test.each([
['{', /invalid JSON5/],
[`{ $id: 'sctx-map-view://t' }`, /must have required property 'regions'/],
[`{ schema: 'x', regions: [{ id: 'a', layout: { type: 'tree' } }] }`, /must have required property '\$id'/],
[`{ $id: 'map/t', schema: 'x', regions: [{ id: 'a', layout: { type: 'tree' } }] }`, /\$id must match pattern/],
[
`{ $id: 'sctx-map-view://t', schema: 'x', regions: [{ id: 'a', layout: { type: 'grid' } }] }`,
/layout has unknown type "grid"/,
Expand Down Expand Up @@ -168,16 +165,6 @@ describe('parseMapViewDefinition', () => {
expect(selectionFilter(filtered)).toBe('my-view');
});

test('matches definitions to a schema', () => {
const def = parseMapViewDefinition(
't',
`{ $id: 'sctx-map-view://t', schema: 'sctx://x', regions: [{ id: 'main', layout: { type: 'tree' } }] }`,
);
expect(mapViewsForSchema([def], 'sctx://x')).toEqual([def]);
expect(mapViewsForSchema([def], 'sctx://y')).toEqual([]);
expect(mapViewsForSchema([def], undefined)).toEqual([]);
});

test('parsed definitions survive a JSON round trip', () => {
const def = parseMapViewDefinition('t', withParameters);
expect(JSON.parse(JSON.stringify(def))).toEqual(def);
Expand Down
11 changes: 6 additions & 5 deletions packages/map-views/tests/landscape.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { fixtureGraph } from './fixture-graph';
import sample from './fixtures/launch-playbook.json';

const graph = fixtureGraph(sample);
const count = (type: string) => [...graph.nodes.values()].filter((n) => n.resolvedType === type).length;
/** A plain landscape: its containers are the one cell of its one strip. */
function plainLandscape(...args: Parameters<typeof buildLandscape>) {
const { dimension, strips } = buildLandscape(...args);
Expand All @@ -28,16 +29,16 @@ describe('sample landscape', () => {
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);
expect(byPhase.groups).toHaveLength(count('Phases'));
const activities = byPhase.groups.flatMap((g) => g.children);
expect(activities.every((o) => o.item.kind === 'node' && o.item.node.resolvedType === 'Activities')).toBe(true);
expect(activities).toHaveLength(12);
expect(activities).toHaveLength(count('Activities'));
});

test('field levels split the next node level by value', () => {
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);
expect(byStatus.groups.flatMap((g) => g.children)).toHaveLength(count('Applications'));
});

test('via chains join through the skipped type and record the skipped nodes', () => {
Expand All @@ -56,7 +57,7 @@ describe('sample landscape', () => {
// Without the chain, Activities and Applications share no edge.
const direct = plainLandscape(graph, 'main', layout([level('Activities'), level('Applications')]));
expect(direct.groups.flatMap((g) => g.children)).toEqual([]);
expect(direct.ungrouped).toHaveLength(8);
expect(direct.ungrouped).toHaveLength(count('Applications'));
});

test('edge.field restricts which edges join two levels', () => {
Expand All @@ -71,7 +72,7 @@ describe('sample landscape', () => {
'main',
layout([level('Phases'), { ...level('Activities'), edge: { field: 'phase' } }]),
);
expect(phase.groups.flatMap((g) => g.children)).toHaveLength(12);
expect(phase.groups.flatMap((g) => g.children)).toHaveLength(count('Activities'));
});

test('field-group keys cannot collide with node titles', () => {
Expand Down
9 changes: 4 additions & 5 deletions packages/map-views/tests/snapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,10 @@ describe('exportSnapshot', () => {
});

test('passes validation options to validateSpace', async () => {
// The sample has no rule issues to filter, so an invalid filter is what shows the option arrives.
const config = loadConfig({ startDir: sample });
const all = await exportSnapshot('launch-playbook', config, sample);
const none = await exportSnapshot('launch-playbook', config, sample, { ruleFilter: ['id=no-such-rule'] });
const rules = (snapshot: typeof all) => snapshot.validation.issues.filter((issue) => issue.kind === 'rule');
expect(rules(none)).toEqual([]);
expect(rules(all).length).toBeGreaterThanOrEqual(rules(none).length);
await expect(exportSnapshot('launch-playbook', config, sample, { ruleFilter: ['nonsense'] })).rejects.toThrow(
/Invalid rule filter/,
);
});
});
8 changes: 5 additions & 3 deletions packages/map-views/tests/tree.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ function occurrences(roots: TreeOccurrence[]): TreeOccurrence[] {
}

describe('sample tree', () => {
const tree = buildTree(fixtureGraph(sample), 'main');
const graph = fixtureGraph(sample);
const tree = buildTree(graph, 'main');
const all = occurrences([...tree.roots, ...tree.orphans]);

test('roots are the Phases', () => {
expect(tree.roots.map((o) => o.node.resolvedType)).toEqual(['Phases', 'Phases', 'Phases', 'Phases']);
const phases = [...graph.nodes.values()].filter((n) => n.resolvedType === 'Phases');
expect(tree.roots.map((o) => o.node.id)).toEqual(phases.map((n) => n.id));
});

test('occurrence keys are unique even though nodes repeat', () => {
Expand Down Expand Up @@ -49,7 +51,7 @@ describe('sample tree', () => {
});

test('cross-edge mode replaces repeats with cross-edge connectors to the primary occurrence', () => {
const cross = buildTree(fixtureGraph(sample), 'main', 'cross-edge');
const cross = buildTree(graph, 'main', 'cross-edge');
const crossAll = occurrences([...cross.roots, ...cross.orphans]);
const repeats = all.filter((o) => o.repeatOf !== undefined);
expect(crossAll.some((o) => o.repeatOf !== undefined)).toBe(false);
Expand Down
4 changes: 3 additions & 1 deletion packages/map-views/tests/xy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ describe('tea-shop XY plot', () => {
const kettle = plot.points.find((p) => p.node.title === 'Kettle')!;
expect(kettle.x).toBeCloseTo(0.35);
expect(kettle.y).toBeCloseTo(0.43);
expect(plot.points).toHaveLength(14);
expect(plot.points).toHaveLength(
[...graph.nodes.values()].filter((n) => layout().types.includes(n.resolvedType)).length,
);
expect(plot.unplaced).toEqual([]);
});

Expand Down
2 changes: 1 addition & 1 deletion packages/map-views/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { defineConfig } from 'vite';

/**
* Library build, so hosts consume plain ES modules and declarations instead of compiling this
* package's TypeScript and JSX themselves. Entry points: the package root, `/node`, the `export` bin and the Claude artifact host.
* package's TypeScript and JSX themselves.
*/
export default defineConfig({
plugins: [react()],
Expand Down
Loading