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
59 changes: 34 additions & 25 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,8 @@
# structured-context-map-views

Declarative map views of structured-context spaces: the definition format, the rendering library and the navigator app. Review [docs/concepts.md](docs/concepts.md) before new work and use its terms in code, tests, comments and docs.
Declarative map views of structured-context spaces: the definition format, the rendering library and the navigator app.

## Layout

- `packages/map-views`: the published library, `structured-context-map-views`. Its `src/index.ts` is the public surface; add an export only when a host needs it.
- `packages/map-views/src/core`: framework-agnostic. Definitions, parameters, graph helpers and the projections. No React, DOM, Node or runtime structured-context imports (type-only is fine, and `structured-context/types` is browser-safe); `tests/module-boundaries.test.ts` enforces this.
- `packages/map-views/src/layouts`: React components and the SVG edge overlay. Don't import host code from here.
- `packages/map-views/src/viewer`: the page-filling viewer that hosts share. It knows nothing about any one host: anything host-specific (such as card labels) is an option the host passes. Hosts (`src/artifact`, `src/page`) are imported by nothing else.
- `packages/map-views/src/node`: Node-only definition discovery (`loadMapViewDefinitions`), shipped as its own entry point (`structured-context-map-views/node`). Core and layouts must not import it.
- `packages/sctx-map-views`: the structured-context render plugin (format `map-views.html`), bundling the library's page template and `/html` entry. It reads everything through the render callbacks and has no structured-context dependency at runtime: its bundle imports nothing from it, and `test:package` checks that.
- `apps/navigator`: the standalone host (private package: a Vite app plus dev-server middleware calling the structured-context API). It consumes the library like any other host.
- `packages/map-views/map-views/*.json5`: definitions bundled with the library, only for structured-context's bundled schemas (`$id` `sctx-map-view://core/<name>`). `bun run generate:definitions` embeds them as `src/node/bundled-definitions.ts`; a test fails if that is stale. Plugins ship their own; personal ones go in the config root's `.sctx/map-views/` (structured-context's `resourceDir`).
- `packages/map-views/src/core/format/*.ts`: the definition format's JSON Schemas (`as const`), the source of truth. Types derive from them (`FromSchema`); `bun run generate:schemas` writes `schemas/generated/latest/` at the repo root (so the published URLs stay stable), and a test fails if those are stale; `--release` (run when cutting a release) also freezes `schemas/generated/<version>/` if the format changed. `$id`s are the published https URLs (`schema-url.ts`). Use absolute `${SCHEMA_URL}/…` refs: `FromSchema` doesn't resolve relative refs inside referenced schemas.
- `samples/launch-playbook/`: a public sample space. `packages/map-views/tests/fixtures/launch-playbook.json` is captured from it with `bun run capture-fixtures launch-playbook=../../samples/launch-playbook/.sctx.json` in `packages/map-views`.
Before new work, read [docs/concepts.md](docs/concepts.md) for the terms and [docs/architecture.md](docs/architecture.md#modules) for the modules and what each may import. Use the terms in code, tests, comments and docs.

## Checks

Expand All @@ -23,28 +12,48 @@ bun run test:package # packs the library and the plugin, installs each in a
bun run build # the library, then the navigator
```

## Releases
## Principles

- **Simple, not sloppy.** Prefer the smallest design that does the job. Don't add structures, grammars, limits or presets until a concrete need forces them.
- **One word per concept.** A thing has the same name in the definition format, the docs and the code. Add or rename a term in `docs/concepts.md` first, then use it. Don't rename another package's term: use structured-context's own word and type.
- **One home per fact.** Decide which doc owns a fact, state it there once, and link from elsewhere. Docs don't list what the code already lists (layouts, exports, props, files, variables): a list like that goes stale with the next change.
- **Export only what another module imports.** A type used in one place is written inline. A type used in one file isn't exported. Derive types (from the schemas, `Parameters`, `ReturnType`, `Pick`) instead of restating a shape. When two modules need the same shape, they share one type.
- **The public surface is `src/index.ts`, `src/node/index.ts` and `src/node/html.ts`.** Add an export there only when a host needs it, and say which host.
- **Comments say what the code can't.** A reason, a constraint, a trap. Never the signature, the parameter list or the next line.
- **No barrel files.** Modules import each other directly. A small helper joins the file it serves; it gets its own file when it has several users and a concept of its own.
- **Tests assert the behaviour they name.** Derive expected values from the fixture or the code under test. Don't hard-code a list that grows with the code, and don't assert things that only happen to be true.
- **Mark the loose parts.** Where careful review is traded for speed, say so in place with a `PROTOTYPE:` comment giving the shortcut and what a proper treatment needs. `grep -rn PROTOTYPE: packages apps` is the register. Untagged code is at production standard for its scope.
- **Fix the pattern, not the line.** When a review comment names a habit, search for every instance before replying, and check the result before saying it's fixed.
- **No private data.** This repo is public. Fixtures, samples and definitions come from public or synthetic spaces.

Work and open questions are tracked as GitHub issues on this repo.

## Adding a layout

Releases go through the `/release <major|minor|patch>` skill, which runs `bun pm version --no-git-tag-version` in `packages/map-views` (its `preversion` and `version` scripts run the checks and freeze the definition format's schemas in `schemas/generated/<version>/` when the format changed), sets the same version in `packages/sctx-map-views`, then commits, tags and pushes. The tag push runs `.github/workflows/release.yml`, which publishes both packages to npm with provenance. Don't run `generate:schemas --release` by hand.
A layout is a folder in `packages/map-views/src/core/layouts/<name>/` (`schema.ts`, and `projection.ts` only when deciding what is shown takes logic of its own) and a component in `src/components/`. It is registered in two lists: `core/layouts/schemas.ts` (its schema, and a check for any rule the schema can't express) and `LAYOUTS` in `components/MapView.tsx`. The definition format and the `LayoutConfig<'name'>` type follow from the first. It is documented in `docs/layouts.md` only. A projection decides what is shown; positions, sizes and anything a layout library computes belong in the component.

## Ways of working
## Generated files

- `schemas/generated/latest/` comes from the schemas in `core/schema/` and each layout's `schema.ts` (`bun run generate:schemas`). Use absolute `${SCHEMA_URL}/…` refs there: `FromSchema` doesn't resolve relative refs inside referenced schemas. Never edit the frozen `schemas/generated/<version>/` folders or run `generate:schemas --release` by hand.
- `packages/map-views/src/node/bundled-definitions.ts` comes from `packages/map-views/map-views/*.json5` (`bun run generate:definitions`).
- `packages/map-views/tests/fixtures/` is captured from spaces; see its README.

Tests fail when the first two are stale.

## Releases

- **Simple, not sloppy.** Prefer the smallest design that does the job over speculative generality. Untagged code is expected to be at production standard for its scope.
- **Mark the loose parts.** Where careful review is traded for speed, say so in place with a `PROTOTYPE:` comment explaining the shortcut and what a proper treatment needs. `grep -rn PROTOTYPE: src` is the register.
- **Last responsible moment.** Don't add intermediate structures, grammars, limits or presets until a concrete need forces them.
- **No private data.** This repo will be public. Fixtures, samples and definitions must come from public or synthetic spaces.
- Work and open questions are tracked as GitHub issues on this repo.
Releases go through the `/release <major|minor|patch>` skill. Its tag push runs `.github/workflows/release.yml`, which publishes both packages to npm.

## Definition of done

Review and update with any change:

| Change | Check |
|---|---|
| Definition format (`core/format`) | `docs/definitions.md`; regenerated `schemas/generated/`; definitions in `map-views/` |
| Definition format (`core/schema`, `core/layouts/*/schema.ts`) | `docs/definitions.md`, or `docs/layouts.md` for layout settings; regenerated `schemas/generated/latest/`; definitions in `map-views/` |
| New or renamed term | `docs/concepts.md` |
| Exports or component props | `docs/api.md` |
| Module structure, rendering, styling | `docs/architecture.md`, this file |
| Module structure, rendering, styling | `docs/architecture.md` |
| Anything user-visible | `README.md` (kept short; detail goes in `docs/`) |

Docs describe what the code does now. Decision history and plans don't go in docs.
Expand All @@ -53,9 +62,9 @@ Docs describe what the code does now. Decision history and plans don't go in doc

- `bun run dev --port <port>` runs Vite under Bun. That's intentional: structured-context targets Bun or a bundler.
- Spaces come from the structured-context config. A relative `SCTX_CONFIG` inherited from another repo fails here; run with `env -u SCTX_CONFIG` to use the global config, or pass an absolute path.
- In a Chrome tab driven by an agent, the tab is usually hidden (`document.visibilityState === "hidden"`). Hidden tabs run no `ResizeObserver` or `requestAnimationFrame` callbacks, so edge redraws on resize can't be checked there. Taking a screenshot forces a frame, and DOM measurements remain reliable.
- In a Chrome tab driven by an agent, the tab is usually hidden (`document.visibilityState === "hidden"`). Hidden tabs run no `ResizeObserver` or `requestAnimationFrame` callbacks, so connector redraws on resize can't be checked there. Taking a screenshot forces a frame, and DOM measurements remain reliable.
- React-controlled `<select>`s need the native value setter plus a bubbling `change` event when driven from script.
- Check edge alignment by comparing each `svg path`'s endpoint with the centre of its target card.
- Check connector alignment by comparing each `svg path`'s endpoint with the centre of its target card.

## Styling

Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Declarative visualisations of [structured-context](https://github.com/mindsocket/structured-context) spaces.

A **map view** is a short JSON5 definition that projects every space of one schema into a visual form: a tree, nested containers, or an XY plot. The same space can be shown several ways, and readers can switch settings such as orientation or grouping through parameters the definition declares. Definitions are found the way structured-context finds plugin schemas: bundled here, in plugins, or in the `.sctx/map-views/` folder beside your content.
A **map view** is a short JSON5 definition that projects a space into a visual form, such as a tree, nested containers or a network ([layouts](docs/layouts.md)). The same space can be shown several ways, and readers can switch settings such as orientation or grouping through parameters the definition declares. Definitions are found the way structured-context finds plugin schemas: bundled here, in plugins, or in the `.sctx/map-views/` folder beside your content.

```json5
{
Expand All @@ -24,8 +24,9 @@ This repo holds:

Pre-1.0. Docs:

- [Concepts](docs/concepts.md): map views, regions, layouts, occurrences, parameters
- [Concepts](docs/concepts.md): the terms
- [Definitions](docs/definitions.md): writing a map view definition
- [Layouts](docs/layouts.md): the layouts and their settings
- [Architecture](docs/architecture.md): how the library is put together
- [API](docs/api.md): embedding map views in a host

Expand Down
4 changes: 3 additions & 1 deletion apps/navigator/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { useUrlState } from './useUrlState';
type SpaceListItem = { name: string };

export function App() {
const { spaceName, mapViewId, values, setSpaceName, setMapViewId, setValue } = useUrlState();
const { spaceName, mapViewId, focus, values, setSpaceName, setMapViewId, setFocus, setValue } = useUrlState();
const [selectedNode, setSelectedNode] = useState<SpaceNode>();
const [unattachedPanelOpen, setUnattachedPanelOpen] = useState(false);

Expand Down Expand Up @@ -129,6 +129,8 @@ export function App() {
values={values}
annotations={annotations}
onNodeSelect={setSelectedNode}
focus={(focus || undefined) as SpaceNode['id'] | undefined}
onFocusChange={setFocus}
/>
)}
</div>
Expand Down
2 changes: 1 addition & 1 deletion apps/navigator/src/useFetched.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { messageOf } from './api';

type Settled<T> = { key: string; data?: T; error?: string };

export type Fetched<T> = { data?: T; error?: string; loading: boolean };
type Fetched<T> = { data?: T; error?: string; loading: boolean };

/**
* Loads `load(key)` whenever `key` changes; `undefined` means nothing to load. Results are kept with
Expand Down
24 changes: 16 additions & 8 deletions apps/navigator/src/useUrlState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { ParameterValues } from 'structured-context-map-views';
/** A query parameter holding a map view parameter's value is `p.<name>=<JSON>`. */
const VALUE_PREFIX = 'p.';

type UrlState = { spaceName: string; mapViewId: string; values: ParameterValues };
type UrlState = { spaceName: string; mapViewId: string; focus: string; values: ParameterValues };

function readUrl(): UrlState {
const params = new URLSearchParams(window.location.search);
Expand All @@ -17,22 +17,28 @@ function readUrl(): UrlState {
// A hand-edited value that isn't JSON is ignored; the parameter keeps its default.
}
}
return { spaceName: params.get('space') ?? '', mapViewId: params.get('view') ?? '', values };
return {
spaceName: params.get('space') ?? '',
mapViewId: params.get('view') ?? '',
focus: params.get('focus') ?? '',
values,
};
}

function writeUrl({ spaceName, mapViewId, values }: UrlState) {
function writeUrl({ spaceName, mapViewId, focus, values }: UrlState) {
const params = new URLSearchParams();
if (spaceName) params.set('space', spaceName);
if (mapViewId) params.set('view', mapViewId);
if (focus) params.set('focus', focus);
for (const [name, value] of Object.entries(values)) params.set(VALUE_PREFIX + name, JSON.stringify(value));
const search = params.toString();
window.history.replaceState(null, '', search ? `?${search}` : window.location.pathname);
}

/**
* The chosen space, map view and parameter values, mirrored in the query string so a reload (or a
* shared link) restores them. Values are remembered per map view for the session; only the current
* view's values are in the URL. `mapViewId` is '' until the host settles on a map view (see `setMapViewId`).
* Mirrors the reader's choices in the query string, so a reload or a shared link restores them. Parameter
* values are remembered per map view for the session; only the current view's are in the URL. `mapViewId`
* is '' until the host settles on a map view (see `setMapViewId`).
*/
export function useUrlState() {
const [initial] = useState(readUrl);
Expand All @@ -41,19 +47,21 @@ export function useUrlState() {
const [valuesByView, setValuesByView] = useState<Record<string, ParameterValues>>(
initial.mapViewId ? { [initial.mapViewId]: initial.values } : {},
);
const [focus, setFocus] = useState(initial.focus);
const values = valuesByView[mapViewId] ?? {};

useEffect(() => writeUrl({ spaceName, mapViewId, values }), [spaceName, mapViewId, values]);
useEffect(() => writeUrl({ spaceName, mapViewId, focus, values }), [spaceName, mapViewId, focus, values]);

const setSpaceName = useCallback((name: string) => {
setSpaceNameState(name);
setMapViewId('');
setFocus('');
}, []);
const setValue = useCallback(
(name: string, value: unknown) =>
setValuesByView((all) => ({ ...all, [mapViewId]: { ...all[mapViewId], [name]: value } })),
[mapViewId],
);

return { spaceName, mapViewId, values, setSpaceName, setMapViewId, setValue };
return { spaceName, mapViewId, focus, values, setSpaceName, setMapViewId, setFocus, setValue };
}
16 changes: 14 additions & 2 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading