From 30dd436729e0a8c6fdc45f9b6bfe06dcdda28c40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ola=20Gr=C3=B8ttvik?= Date: Fri, 30 Oct 2026 08:45:01 +0000 Subject: [PATCH 1/6] Add bust-editor npm package with register map tree and schema forms --- .github/workflows/editor_ui.yml | 68 ++++ editor-ui/.gitignore | 2 + editor-ui/.npmrc | 1 + editor-ui/README.md | 38 ++ editor-ui/package-lock.json | 146 ++++++++ editor-ui/package.json | 37 ++ editor-ui/src/editor.ts | 626 ++++++++++++++++++++++++++++++++ editor-ui/src/index.ts | 15 + editor-ui/src/operations.ts | 65 ++++ editor-ui/src/protocol.ts | 104 ++++++ editor-ui/src/schema.ts | 79 ++++ editor-ui/src/style.css | 386 ++++++++++++++++++++ editor-ui/tests/editor.test.mjs | 169 +++++++++ editor-ui/tsconfig.json | 16 + 14 files changed, 1752 insertions(+) create mode 100644 .github/workflows/editor_ui.yml create mode 100644 editor-ui/.gitignore create mode 100644 editor-ui/.npmrc create mode 100644 editor-ui/README.md create mode 100644 editor-ui/package-lock.json create mode 100644 editor-ui/package.json create mode 100644 editor-ui/src/editor.ts create mode 100644 editor-ui/src/index.ts create mode 100644 editor-ui/src/operations.ts create mode 100644 editor-ui/src/protocol.ts create mode 100644 editor-ui/src/schema.ts create mode 100644 editor-ui/src/style.css create mode 100644 editor-ui/tests/editor.test.mjs create mode 100644 editor-ui/tsconfig.json diff --git a/.github/workflows/editor_ui.yml b/.github/workflows/editor_ui.yml new file mode 100644 index 0000000..2a8931a --- /dev/null +++ b/.github/workflows/editor_ui.yml @@ -0,0 +1,68 @@ +name: Editor UI + +on: + push: + branches: [ "master" ] + tags: [ "editor-ui-v*" ] + pull_request: + branches: [ "**" ] + +permissions: + contents: read + +concurrency: + group: editor-ui-${{ github.ref }} + cancel-in-progress: true + +defaults: + run: + working-directory: editor-ui + +jobs: + test: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + # The tests run the editor against bust's bridge over stdio. + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.13" + - run: pip install -e .. + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 22 + cache: npm + cache-dependency-path: editor-ui/package-lock.json + - run: npm ci + - run: npm test + env: + PYTHON: python + - run: npm pack --dry-run + + # Pushing a tag editor-ui-vX.Y.Z publishes that version to npm, with npm + # trusted publishing, so no token is stored here. The package must exist on + # npm with this workflow set as its trusted publisher. + publish: + needs: test + if: startsWith(github.ref, 'refs/tags/editor-ui-v') + runs-on: ubuntu-24.04 + environment: npm + permissions: + contents: read + id-token: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + registry-url: https://registry.npmjs.org + - name: Check that the tag matches the package version + run: | + version="$(node -p 'require("./package.json").version')" + if [ "editor-ui-v$version" != "$GITHUB_REF_NAME" ]; then + echo "::error::Tag $GITHUB_REF_NAME does not match version $version in editor-ui/package.json" + exit 1 + fi + - run: npm ci + - run: npm run build + - run: npm publish --provenance --access public diff --git a/editor-ui/.gitignore b/editor-ui/.gitignore new file mode 100644 index 0000000..b947077 --- /dev/null +++ b/editor-ui/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +dist/ diff --git a/editor-ui/.npmrc b/editor-ui/.npmrc new file mode 100644 index 0000000..b6f27f1 --- /dev/null +++ b/editor-ui/.npmrc @@ -0,0 +1 @@ +engine-strict=true diff --git a/editor-ui/README.md b/editor-ui/README.md new file mode 100644 index 0000000..5e22595 --- /dev/null +++ b/editor-ui/README.md @@ -0,0 +1,38 @@ +# bust-editor + +The register map editor of [bust](https://github.com/logvik-org/bust), for the web. It shows a register map as a tree of the bus, the module, its registers and their fields, with a form for the one selected, built from bust's JSON Schema. [cloudbust](https://cloudbust.netlify.app) runs it with bust in the browser. + +The editor never changes a register map itself. Every change goes to bust as JSON Patch operations, and bust either makes it or rejects it with its problems, which the editor shows next to the values they are about. So the editor only ever holds register maps bust accepts. + +## Use + +```ts +import { BustBridge, RegisterMapEditor } from "bust-editor"; +import "bust-editor/style.css"; + +const bridge = new BustBridge(transport); +const editor = new RegisterMapEditor(container, bridge, { + onChange: (state) => console.log(state.text), +}); +await editor.open(registerMapText); +``` + +`transport` takes one JSON-RPC 2.0 request as a string and resolves to bust's response. bust answers these in `bust.editing.bridge`: call `EditorBridge().handle(request)` in Python (Pyodide in a browser), or run `python -m bust.editing.bridge` and exchange one message per line over stdin and stdout. The methods are listed in [bridge.py](../bust/editing/bridge.py). + +The look follows bust's documentation, in light and dark. Set the `--bust-*` variables named at the top of `style.css` to theme it. + +## Develop + +Node.js 22.12 or newer, and a Python with bust installed for the tests: + +```sh +pip install -e .. +npm ci +PYTHON=python npm test +``` + +`npm test` builds `dist/` and runs the editor in happy-dom against a bust bridge process. + +## Release + +Set `version` in `package.json` and push a tag `editor-ui-vX.Y.Z`. The Editor UI workflow tests the package and publishes it to npm with trusted publishing. diff --git a/editor-ui/package-lock.json b/editor-ui/package-lock.json new file mode 100644 index 0000000..815a482 --- /dev/null +++ b/editor-ui/package-lock.json @@ -0,0 +1,146 @@ +{ + "name": "bust-editor", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "bust-editor", + "version": "0.1.0", + "license": "Apache-2.0", + "devDependencies": { + "@types/node": "22.20.5", + "happy-dom": "21.0.3", + "typescript": "5.9.3" + }, + "engines": { + "node": ">=22.12" + } + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/whatwg-mimetype": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz", + "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/buffer-image-size": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz", + "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/happy-dom": { + "version": "21.0.3", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-21.0.3.tgz", + "integrity": "sha512-PesNgu5BnIEmAwzKGewB3K1ORFeznFZJ4JrRz89ea1wkHnxskdpzX9sN/+zb4KO6k8oSMhyJSj/cwXAFrYBBNA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": ">=20.0.0", + "@types/whatwg-mimetype": "^3.0.2", + "@types/ws": "^8.18.1", + "buffer-image-size": "^0.6.4", + "entities": "^7.0.1", + "whatwg-mimetype": "^3.0.0", + "ws": "^8.21.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/whatwg-mimetype": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz", + "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/editor-ui/package.json b/editor-ui/package.json new file mode 100644 index 0000000..67926c6 --- /dev/null +++ b/editor-ui/package.json @@ -0,0 +1,37 @@ +{ + "name": "bust-editor", + "version": "0.1.0", + "description": "Register map editor for bust, the VHDL register file generator", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/logvik-org/bust.git", + "directory": "editor-ui" + }, + "type": "module", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./style.css": "./dist/style.css" + }, + "files": [ + "dist" + ], + "sideEffects": [ + "*.css" + ], + "engines": { + "node": ">=22.12" + }, + "scripts": { + "build": "tsc && cp src/style.css dist/", + "test": "npm run build && node --test tests/*.test.mjs" + }, + "devDependencies": { + "@types/node": "22.20.5", + "happy-dom": "21.0.3", + "typescript": "5.9.3" + } +} diff --git a/editor-ui/src/editor.ts b/editor-ui/src/editor.ts new file mode 100644 index 0000000..39693e8 --- /dev/null +++ b/editor-ui/src/editor.ts @@ -0,0 +1,626 @@ +import { + ACCESS_KEYS, + ADVANCED_KEYS, + definitionOf, + inputKindOf, + labelOf, + parseNumber, + placeholderOf, + type NodeKind, +} from "./schema.js"; +import { insertAt, move, removeAt, setFieldType, setKey, setRegisterType, uniqueName } from "./operations.js"; +import type { + AcceptedState, + BustBridge, + EditorState, + JsonObject, + JsonSchema, + JsonValue, + Operation, + Problem, + ValuePath, +} from "./protocol.js"; + +export type EditorOptions = { + // Called with every register map bust accepts, after each change. + onChange?: (state: AcceptedState) => void; +}; + +type TreeNode = { kind: NodeKind; path: ValuePath; label: string; meta: string; children: TreeNode[] }; + +const REGISTERS: ValuePath = ["module", "register"]; + +let nextEditorId = 0; + +function element( + tag: K, + attributes: Record = {}, + ...children: (Node | string)[] +): HTMLElementTagNameMap[K] { + const created = document.createElement(tag); + for (const [name, value] of Object.entries(attributes)) { + created.setAttribute(name, value); + } + created.append(...children); + return created; +} + +function samePath(a: ValuePath, b: ValuePath): boolean { + return a.length === b.length && a.every((token, index) => token === b[index]); +} + +function startsWith(path: ValuePath, prefix: ValuePath): boolean { + return prefix.length <= path.length && prefix.every((token, index) => token === path[index]); +} + +function valueAt(data: JsonValue, path: ValuePath): JsonValue | undefined { + let current: JsonValue | undefined = data; + for (const token of path) { + if (current === null || typeof current !== "object") { + return undefined; + } + current = (current as Record)[token as string]; + } + return current; +} + +function hex(value: number, digits: number): string { + return "0x" + value.toString(16).toUpperCase().padStart(digits, "0"); +} + +function bits(low: number, high: number): string { + return low === high ? `[${low}]` : `[${high}:${low}]`; +} + +// A tree of the bus, the module, its registers and their fields, next to a +// form for the one selected. Every change goes to bust as JSON Patch, and the +// editor shows only register maps bust accepts. A change bust rejects leaves +// the form as typed, with bust's problems next to the values they are about. +export class RegisterMapEditor { + private schema?: JsonSchema; + private accepted?: AcceptedState; + private problems: Problem[] = []; + private selected: ValuePath = ["module"]; + private queue: Promise = Promise.resolve(); + private readonly id = `bust-editor-${nextEditorId++}`; + private readonly toolbar = element("div", { class: "bust-editor-toolbar", role: "toolbar", "aria-label": "Register map" }); + private readonly tree = element("nav", { class: "bust-editor-tree", "aria-label": "Registers" }); + private readonly form = element("form", { class: "bust-editor-form" }); + private readonly messages = element("div", { class: "bust-editor-messages", role: "status", "aria-live": "polite" }); + + constructor( + container: HTMLElement, + private readonly bridge: BustBridge, + private readonly options: EditorOptions = {}, + ) { + container.classList.add("bust-editor"); + container.replaceChildren( + this.toolbar, + element("div", { class: "bust-editor-body" }, this.tree, element("div", { class: "bust-editor-detail" }, this.messages, this.form)), + ); + this.form.addEventListener("submit", (event) => event.preventDefault()); + container.addEventListener("keydown", (event) => this.onKey(event)); + } + + get state(): AcceptedState | undefined { + return this.accepted; + } + + // Starts editing the register map in `text`. If bust rejects it, the + // editor keeps what it had and the state lists bust's problems. + open(text: string): Promise { + return this.run(async () => { + this.selected = ["module"]; + return this.bridge.call("open", { text }); + }); + } + + create(bus: JsonObject, module: JsonObject): Promise { + return this.run(async () => { + this.selected = ["module"]; + return this.bridge.call("new", { bus, module }); + }); + } + + apply(operations: Operation[], select?: ValuePath): Promise { + return this.run(async () => { + const state = await this.bridge.call("apply", { operations }); + if (state.accepted && select) { + this.selected = select; + } + return state; + }); + } + + // Resolves when every change made so far has come back from bust. + async idle(): Promise { + await this.queue; + } + + undo(): Promise { + return this.run(() => this.bridge.call("undo", {})); + } + + redo(): Promise { + return this.run(() => this.bridge.call("redo", {})); + } + + // One request at a time, so that quick changes reach bust in order. + private run(request: () => Promise): Promise { + const result = this.queue.then(async () => { + this.schema ??= await this.bridge.call("schema", {}); + const state = await request(); + this.show(state); + return state; + }); + this.queue = result.catch(() => undefined); + return result; + } + + private show(state: EditorState): void { + if (!state.accepted) { + this.problems = state.problems; + this.renderMessages(); + this.renderTree(); + this.markProblemsInForm(); + return; + } + this.accepted = state; + this.problems = []; + if (valueAt(state.data, this.selected) === undefined) { + this.selected = this.nearestExisting(this.selected); + } + this.render(); + this.options.onChange?.(state); + } + + private nearestExisting(path: ValuePath): ValuePath { + const data = this.accepted!.data; + const parent = path.slice(0, -1); + const index = path[path.length - 1]; + if (typeof index === "number" && index > 0 && valueAt(data, [...parent, index - 1]) !== undefined) { + return [...parent, index - 1]; + } + return parent.length > 1 ? this.nearestExisting(parent.slice(0, -1)) : ["module"]; + } + + private render(): void { + this.renderToolbar(); + this.renderTree(); + this.renderForm(); + this.renderMessages(); + } + + private renderToolbar(): void { + const state = this.accepted!; + const kind = this.selectedKind(); + const index = this.selected[this.selected.length - 1]; + const siblings = kind === "register" || kind === "field" ? (valueAt(state.data, this.selected.slice(0, -1)) as JsonValue[]) : []; + const button = (label: string, enabled: boolean, action: () => void, shortcut?: string) => { + const created = element("button", { type: "button" }, label); + created.disabled = !enabled; + if (shortcut) { + created.setAttribute("aria-keyshortcuts", shortcut); + } + created.addEventListener("click", action); + return created; + }; + this.toolbar.replaceChildren( + element( + "div", + { class: "bust-editor-group" }, + button("Undo", state.canUndo, () => this.undo(), "Control+Z"), + button("Redo", state.canRedo, () => this.redo(), "Control+Shift+Z"), + ), + element( + "div", + { class: "bust-editor-group" }, + button("Add register", true, () => this.addRegister()), + button("Add field", kind === "register" || kind === "field", () => this.addField()), + ), + element( + "div", + { class: "bust-editor-group" }, + button("Move up", typeof index === "number" && index > 0, () => this.moveSelected(-1)), + button("Move down", typeof index === "number" && index < siblings.length - 1, () => this.moveSelected(1)), + button("Remove", kind === "register" || kind === "field", () => this.removeSelected()), + ), + ); + } + + private selectedKind(): NodeKind { + return this.kindOf(this.selected); + } + + private kindOf(path: ValuePath): NodeKind { + if (path[0] === "bus") { + return "bus"; + } + return (["module", "module", "register", "register", "field"] as NodeKind[])[path.length - 1] ?? "field"; + } + + private nodes(): TreeNode[] { + const { data, layout } = this.accepted!; + const bus = data.bus as JsonObject; + const module = data.module as JsonObject; + const registers = module.register as JsonObject[]; + const digits = Math.ceil(Number(bus.addr_width) / 4) || 4; + return [ + { kind: "bus", path: ["bus"], label: "Bus", meta: String(bus.type), children: [] }, + { + kind: "module", + path: ["module"], + label: String(module.name), + meta: "module", + children: registers.map((register, index) => { + const placed = layout[String(register.name)]; + const fields = (register.fields as JsonObject[] | undefined) ?? []; + return { + kind: "register", + path: [...REGISTERS, index], + label: String(register.name), + meta: placed ? hex(placed.address, digits) : "", + children: fields.map((field, fieldIndex) => { + const span = placed?.fields[String(field.name)]; + return { + kind: "field", + path: [...REGISTERS, index, "fields", fieldIndex], + label: String(field.name), + meta: span ? bits(span[0], span[1]) : "", + children: [], + }; + }), + }; + }), + }, + ]; + } + + // The node a problem belongs to: the deepest one whose path leads to it. + private ownerOf(problem: Problem, nodes: TreeNode[]): ValuePath | undefined { + for (const node of nodes) { + if (startsWith(problem.path, node.path)) { + return this.ownerOf(problem, node.children) ?? node.path; + } + } + return undefined; + } + + private renderTree(): void { + if (!this.accepted) { + return; + } + const nodes = this.nodes(); + const owners = this.problems.map((problem) => this.ownerOf(problem, nodes)).filter((path) => path !== undefined); + const item = (node: TreeNode): HTMLLIElement => { + const button = element( + "button", + { type: "button", class: `bust-editor-node bust-editor-${node.kind}` }, + element("span", { class: "bust-editor-meta" }, node.meta), + element("span", { class: "bust-editor-name" }, node.label), + ); + if (samePath(node.path, this.selected)) { + button.setAttribute("aria-current", "true"); + } + if (owners.some((owner) => samePath(owner, node.path))) { + button.classList.add("bust-editor-invalid"); + } + button.addEventListener("click", () => this.select(node.path)); + const created = element("li", {}, button); + if (node.children.length > 0) { + created.append(element("ul", {}, ...node.children.map(item))); + } + return created; + }; + this.tree.replaceChildren(element("ul", {}, ...nodes.map(item))); + } + + private select(path: ValuePath): void { + this.selected = path; + this.problems = []; + this.render(); + this.form.querySelector("input, select, textarea")?.focus(); + } + + private renderMessages(): void { + const items: HTMLElement[] = []; + if (this.problems.length > 0) { + items.push( + element("p", { class: "bust-editor-rejected" }, "bust did not make this change:"), + element( + "ul", + { class: "bust-editor-problems" }, + ...this.problems.map((problem) => + element("li", {}, problem.location ? `${problem.location}: ${problem.message}` : problem.message), + ), + ), + ); + } + const warnings = this.accepted?.warnings ?? []; + if (warnings.length > 0) { + items.push(element("ul", { class: "bust-editor-warnings" }, ...warnings.map((warning) => element("li", {}, `Ignored: ${warning}`)))); + } + this.messages.replaceChildren(...items); + } + + private renderForm(): void { + const kind = this.selectedKind(); + const object = valueAt(this.accepted!.data, this.selected) as JsonObject; + const definition = definitionOf(this.schema!, kind); + const keys = Object.keys(definition.properties ?? {}).filter((key) => this.isShown(kind, key, object)); + const rows = (wanted: string[]) => + wanted.map((key) => this.row(kind, object, key, definition.properties![key], definition.required ?? [])); + const children: Node[] = [this.heading(kind, object), ...rows(keys.filter((key) => !ADVANCED_KEYS.has(key)))]; + const advanced = keys.filter((key) => ADVANCED_KEYS.has(key)); + if (advanced.length > 0) { + const details = element("details", {}, element("summary", {}, "More access options"), ...rows(advanced)); + details.open = advanced.some((key) => key in object); + children.push(details); + } + if (kind === "register" && Array.isArray(object.fields)) { + children.push(this.bitMap(object)); + } + if (kind === "field") { + children.push(this.enumTable(object)); + } + this.form.replaceChildren(...children); + } + + private heading(kind: NodeKind, object: JsonObject): HTMLElement { + const title = kind === "bus" ? "Bus" : `${labelOf(kind)} ${String(object.name)}`; + const heading = element("div", { class: "bust-editor-heading" }, element("h3", {}, title)); + const placed = kind === "register" ? this.accepted!.layout[String(object.name)] : undefined; + if (placed) { + const bus = this.accepted!.data.bus as JsonObject; + const digits = Math.ceil(Number(bus.addr_width) / 4) || 4; + heading.append(element("p", {}, `At ${hex(placed.address, digits)}, ${placed.width} bits wide`)); + } + return heading; + } + + // Keys that do not apply to the object's type stay out of the form. + private isShown(kind: NodeKind, key: string, object: JsonObject): boolean { + if (["register", "fields", "enums", "$schema"].includes(key)) { + return false; + } + if (key === "width" && (kind === "register" || kind === "field")) { + return object.type === "vector" || "width" in object; + } + if (kind === "register" && object.type === "fields") { + return !(ACCESS_KEYS.has(key) || key === "reset") || key in object; + } + return true; + } + + private row(kind: NodeKind, object: JsonObject, key: string, property: JsonSchema, required: string[]): HTMLElement { + const inputId = `${this.id}-${key}`; + const input = this.input(key, property, object[key], required.includes(key), inputId); + const commit = () => { + const value = this.readInput(input, key, property, required.includes(key)); + this.apply(this.operationsFor(kind, object, key, value)); + }; + input.addEventListener("change", commit); + const row = element("div", { class: "bust-editor-row", "data-key": key }); + const label = element("label", { for: inputId }, labelOf(key)); + if (input instanceof HTMLInputElement && input.type === "checkbox") { + row.classList.add("bust-editor-check"); + row.append(input, label); + } else { + row.append(label, input); + } + if (property.description) { + const help = element("p", { class: "bust-editor-help", id: `${inputId}-help` }, property.description); + input.setAttribute("aria-describedby", help.id); + row.append(help); + } + return row; + } + + private operationsFor(kind: NodeKind, object: JsonObject, key: string, value: JsonValue | undefined): Operation[] { + if (key === "type" && kind === "register") { + return setRegisterType(object, this.selected, value as string | undefined); + } + if (key === "type" && kind === "field") { + return setFieldType(object, this.selected, value as string | undefined); + } + return setKey(object, this.selected, key, value); + } + + private input( + key: string, + property: JsonSchema, + value: JsonValue | undefined, + isRequired: boolean, + id: string, + ): HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement { + switch (inputKindOf(key, property)) { + case "choice": { + const select = element("select", { id }); + if (!isRequired || value === undefined) { + const fallback = property.default === undefined ? "Not set" : `Default (${String(property.default)})`; + select.append(element("option", { value: "" }, fallback)); + } + select.append(...property.enum!.map((choice) => element("option", { value: choice }, choice))); + select.value = value === undefined ? "" : String(value).toLowerCase(); + return select; + } + case "either": { + const select = element( + "select", + { id }, + element("option", { value: "" }, placeholderOf(property) || "Not set"), + element("option", { value: "true" }, "Yes"), + element("option", { value: "false" }, "No"), + ); + select.value = value === undefined || value === null ? "" : String(value); + return select; + } + case "flag": { + const checkbox = element("input", { id, type: "checkbox" }); + checkbox.checked = value === true; + return checkbox; + } + case "longtext": { + const textarea = element("textarea", { id, rows: "3" }); + textarea.value = value === undefined ? "" : String(value); + return textarea; + } + default: { + const text = element("input", { id, type: "text", spellcheck: "false", autocomplete: "off" }); + text.value = value === undefined || value === null ? "" : String(value); + text.placeholder = placeholderOf(property); + return text; + } + } + } + + private readInput( + input: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement, + key: string, + property: JsonSchema, + isRequired: boolean, + ): JsonValue | undefined { + switch (inputKindOf(key, property)) { + case "flag": + return (input as HTMLInputElement).checked ? true : undefined; + case "either": + return input.value === "" ? undefined : input.value === "true"; + case "number": + return parseNumber(input.value) ?? (isRequired ? "" : undefined); + default: + return input.value === "" && !isRequired ? undefined : input.value; + } + } + + // Shows each problem under the input of the value it is about, when that + // value is in the form. + private markProblemsInForm(): void { + for (const row of this.form.querySelectorAll(".bust-editor-row")) { + row.classList.remove("bust-editor-invalid"); + row.querySelector(".bust-editor-problem")?.remove(); + const path = [...this.selected, row.dataset.key!]; + const problems = this.problems.filter((problem) => startsWith(problem.path, path)); + if (problems.length > 0) { + row.classList.add("bust-editor-invalid"); + row.append(element("p", { class: "bust-editor-problem" }, problems.map((problem) => problem.message).join(" "))); + } + } + } + + // The register's bits from the highest down, each field where bust put it. + private bitMap(register: JsonObject): HTMLElement { + const placed = this.accepted!.layout[String(register.name)]; + const width = Math.max(placed?.width ?? 0, Number((this.accepted!.data.bus as JsonObject).data_width) || 0); + const map = element("div", { class: "bust-editor-bits", role: "group", "aria-label": "Fields by bit" }); + map.style.setProperty("--bust-editor-bit-count", String(width)); + const fields = (register.fields as JsonObject[]).map((field, index) => ({ field, index, span: placed?.fields[String(field.name)] })); + for (const { field, index, span } of fields) { + if (!span) { + continue; + } + const cell = element( + "button", + { type: "button", title: `${String(field.name)} ${bits(span[0], span[1])}` }, + element("span", {}, String(field.name)), + element("small", {}, bits(span[0], span[1])), + ); + cell.style.gridColumn = `${width - span[1]} / ${width - span[0] + 1}`; + cell.addEventListener("click", () => this.select([...this.selected, "fields", index])); + map.append(cell); + } + return element("div", { class: "bust-editor-row" }, element("span", { class: "bust-editor-label" }, "Fields"), map); + } + + private enumTable(field: JsonObject): HTMLElement { + const enums = (field.enums as JsonObject[] | undefined) ?? []; + const listPath = [...this.selected, "enums"]; + const cell = (index: number, key: "name" | "value") => { + const input = element("input", { type: "text", spellcheck: "false", "aria-label": `${labelOf(key)} ${index + 1}` }); + input.value = String(enums[index][key]); + input.addEventListener("change", () => { + const value = key === "value" ? (parseNumber(input.value) ?? "") : input.value; + this.apply(setKey(enums[index], [...listPath, index], key, value)); + }); + return element("td", {}, input); + }; + const remove = (index: number) => { + const button = element("button", { type: "button", "aria-label": `Remove value ${index + 1}` }, "Remove"); + button.addEventListener("click", () => + this.apply(enums.length === 1 ? setKey(field, this.selected, "enums", undefined) : removeAt(listPath, index)), + ); + return element("td", {}, button); + }; + const add = element("button", { type: "button" }, "Add value"); + add.addEventListener("click", () => { + const name = uniqueName("VALUE", enums.map((value) => String(value.name))); + const values = enums.map((value) => Number(parseNumber(String(value.value)))).filter(Number.isFinite); + const value = { name, value: values.length > 0 ? Math.max(...values) + 1 : 0 }; + this.apply(enums.length === 0 ? setKey(field, this.selected, "enums", [value]) : insertAt(listPath, enums.length, value)); + }); + const table = element( + "table", + { class: "bust-editor-enums" }, + element("thead", {}, element("tr", {}, element("th", {}, "Name"), element("th", {}, "Value"), element("th", {}))), + element("tbody", {}, ...enums.map((_, index) => element("tr", {}, cell(index, "name"), cell(index, "value"), remove(index)))), + ); + return element( + "div", + { class: "bust-editor-row", "data-key": "enums" }, + element("span", { class: "bust-editor-label" }, "Named values"), + ...(enums.length > 0 ? [table] : []), + add, + ); + } + + private addRegister(): Promise { + const registers = (this.accepted!.data.module as JsonObject).register as JsonObject[]; + const kind = this.selectedKind(); + const index = kind === "register" || kind === "field" ? (this.selected[2] as number) + 1 : registers.length; + const register: JsonObject = { name: uniqueName("reg", registers.map((other) => String(other.name))) }; + // Without an address of its own, a register put before one with an + // address could take that address. + if (registers[index] && "address" in registers[index]) { + register.address = "0x" + this.accepted!.nextAddress.toString(16).toUpperCase(); + } + return this.apply(insertAt(REGISTERS, index, register), [...REGISTERS, index]); + } + + private addField(): Promise { + const registerPath = this.selected.slice(0, 3); + const register = valueAt(this.accepted!.data, registerPath) as JsonObject; + const fields = (register.fields as JsonObject[] | undefined) ?? []; + const name = uniqueName("field", fields.map((field) => String(field.name))); + if (fields.length === 0) { + const operations = setRegisterType(register, registerPath, "fields"); + return this.apply(operations, [...registerPath, "fields", 0]); + } + const index = this.selectedKind() === "field" ? (this.selected[4] as number) + 1 : fields.length; + return this.apply(insertAt([...registerPath, "fields"], index, { name, type: "bit" }), [...registerPath, "fields", index]); + } + + private moveSelected(step: number): Promise { + const listPath = this.selected.slice(0, -1); + const from = this.selected[this.selected.length - 1] as number; + const list = valueAt(this.accepted!.data, listPath) as JsonValue[]; + return this.apply(move(listPath, list, from, from + step), [...listPath, from + step]); + } + + private removeSelected(): Promise { + const listPath = this.selected.slice(0, -1); + const index = this.selected[this.selected.length - 1] as number; + return this.apply(removeAt(listPath, index)); + } + + private onKey(event: KeyboardEvent): void { + const target = event.target as HTMLElement; + if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "z" || target.matches("input, textarea")) { + return; + } + event.preventDefault(); + if (event.shiftKey) { + this.redo(); + } else { + this.undo(); + } + } +} diff --git a/editor-ui/src/index.ts b/editor-ui/src/index.ts new file mode 100644 index 0000000..f1de215 --- /dev/null +++ b/editor-ui/src/index.ts @@ -0,0 +1,15 @@ +export { RegisterMapEditor, type EditorOptions } from "./editor.js"; +export { + BustBridge, + pointer, + type AcceptedState, + type EditorState, + type JsonObject, + type JsonValue, + type Operation, + type Problem, + type RegisterLayout, + type RejectedState, + type Transport, + type ValuePath, +} from "./protocol.js"; diff --git a/editor-ui/src/operations.ts b/editor-ui/src/operations.ts new file mode 100644 index 0000000..cb18749 --- /dev/null +++ b/editor-ui/src/operations.ts @@ -0,0 +1,65 @@ +import { pointer, type JsonObject, type JsonValue, type Operation, type ValuePath } from "./protocol.js"; + +// The operations that set `key` of the object at `path` to `value`, or take +// the key out when `value` is undefined. +export function setKey(object: JsonObject, path: ValuePath, key: string, value: JsonValue | undefined): Operation[] { + const target = pointer([...path, key]); + const isPresent = key in object; + if (value === undefined) { + return isPresent ? [{ op: "remove", path: target }] : []; + } + return [{ op: isPresent ? "replace" : "add", path: target, value }]; +} + +// Changing a register's type also adds or takes out the keys only some types +// have, so that the change does not leave a register bust rejects. +export function setRegisterType( + register: JsonObject, + path: ValuePath, + type: string | undefined, +): Operation[] { + const operations = setKey(register, path, "type", type); + if (type === "fields" && !("fields" in register)) { + operations.push(...setKey(register, path, "fields", [{ name: "field0", type: "bit" }])); + for (const key of ["reset", "width"]) { + operations.push(...setKey(register, path, key, undefined)); + } + } + if (type !== "fields") { + operations.push(...setKey(register, path, "fields", undefined)); + } + if (type !== "vector") { + operations.push(...setKey(register, path, "width", undefined)); + } + return operations; +} + +// A field's type picks between bit and vector, and only a vector has a width. +export function setFieldType(field: JsonObject, path: ValuePath, type: string | undefined): Operation[] { + const operations = setKey(field, path, "type", type); + if (type !== "vector") { + operations.push(...setKey(field, path, "width", undefined)); + } + return operations; +} + +export function insertAt(listPath: ValuePath, index: number, value: JsonValue): Operation[] { + return [{ op: "add", path: pointer([...listPath, index]), value }]; +} + +export function removeAt(listPath: ValuePath, index: number): Operation[] { + return [{ op: "remove", path: pointer([...listPath, index]) }]; +} + +export function move(listPath: ValuePath, list: JsonValue[], from: number, to: number): Operation[] { + return [...removeAt(listPath, from), ...insertAt(listPath, to, list[from])]; +} + +export function uniqueName(prefix: string, taken: Iterable): string { + const names = new Set(taken); + for (let number = 0; ; number++) { + if (!names.has(`${prefix}${number}`)) { + return `${prefix}${number}`; + } + } +} diff --git a/editor-ui/src/protocol.ts b/editor-ui/src/protocol.ts new file mode 100644 index 0000000..66d494d --- /dev/null +++ b/editor-ui/src/protocol.ts @@ -0,0 +1,104 @@ +// The JSON-RPC 2.0 messages between the editor and bust, as +// bust/editing/bridge.py answers them. + +export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; +export type JsonObject = { [key: string]: JsonValue }; + +// Keys and list indexes from the top of the register map down to one value. +export type ValuePath = (string | number)[]; + +export type Operation = + | { op: "add"; path: string; value: JsonValue } + | { op: "replace"; path: string; value: JsonValue } + | { op: "remove"; path: string }; + +export type Problem = { + path: ValuePath; + location: string; + message: string; + line: number | null; +}; + +export type RegisterLayout = { + address: number; + width: number; + // The lowest and highest bit of each field, by name. + fields: Record; +}; + +export type AcceptedState = { + accepted: true; + data: JsonObject; + text: string; + warnings: string[]; + // Where bust places each register, by name. + layout: Record; + // The address bust gives a register added without one. + nextAddress: number; + canUndo: boolean; + canRedo: boolean; +}; + +export type RejectedState = { + accepted: false; + problems: Problem[]; +}; + +export type EditorState = AcceptedState | RejectedState; + +export type JsonSchema = { + type?: string | string[]; + enum?: string[]; + anyOf?: JsonSchema[]; + default?: JsonValue; + description?: string; + required?: string[]; + properties?: Record; + items?: JsonSchema; + $ref?: string; + $defs?: Record; +}; + +export type BridgeMethods = { + schema: { params: Record; result: JsonSchema }; + open: { params: { text: string }; result: EditorState }; + new: { params: { bus: JsonObject; module: JsonObject }; result: EditorState }; + apply: { params: { operations: Operation[] }; result: EditorState }; + undo: { params: Record; result: EditorState }; + redo: { params: Record; result: EditorState }; +}; + +export type BridgeMethod = keyof BridgeMethods; + +// Carries one JSON-RPC request to bust and brings back its response: a +// Pyodide worker in cloudbust, a bust process over stdio on the desktop. +export type Transport = (request: string) => Promise; + +type Response = { + id: number; + result?: unknown; + error?: { code: number; message: string }; +}; + +export class BustBridge { + private nextId = 0; + + constructor(private readonly transport: Transport) {} + + async call( + method: M, + params: BridgeMethods[M]["params"], + ): Promise { + const request = { jsonrpc: "2.0", id: this.nextId++, method, params }; + const response: Response = JSON.parse(await this.transport(JSON.stringify(request))); + if (response.error) { + throw new Error(response.error.message); + } + return response.result as BridgeMethods[M]["result"]; + } +} + +// RFC 6901: ~ and / in a key are escaped. +export function pointer(path: ValuePath): string { + return path.map((token) => "/" + String(token).replace(/~/g, "~0").replace(/\//g, "~1")).join(""); +} diff --git a/editor-ui/src/schema.ts b/editor-ui/src/schema.ts new file mode 100644 index 0000000..1d54253 --- /dev/null +++ b/editor-ui/src/schema.ts @@ -0,0 +1,79 @@ +import type { JsonSchema, JsonValue } from "./protocol.js"; + +export type NodeKind = "bus" | "module" | "register" | "field"; + +// How a key is edited, worked out from its schema. +export type InputKind = "choice" | "flag" | "either" | "number" | "text" | "longtext" | "list"; + +const LABELS: Record = { + addr_width: "Address width", + data_width: "Data width", + byte_addressable: "Byte addressable", + sw: "Software access", + hw: "Hardware access", + onread: "On read", + onwrite: "On write", + singlepulse: "Single pulse", + we: "Write enable (we)", + wel: "Write enable, active low (wel)", + hwset: "Hardware set (hwset)", + hwclr: "Hardware clear (hwclr)", + swmod: "Software modified strobe (swmod)", + swacc: "Software access strobe (swacc)", + reset: "Reset value", +}; + +// Access keys that most registers leave at their defaults, so the form puts +// them out of the way. +export const ADVANCED_KEYS = new Set(["onread", "onwrite", "singlepulse", "we", "wel", "hwset", "hwclr", "swmod", "swacc"]); + +export const ACCESS_KEYS = new Set(["sw", "hw", ...ADVANCED_KEYS]); + +export function labelOf(key: string): string { + return LABELS[key] ?? key.charAt(0).toUpperCase() + key.slice(1).replace(/_/g, " "); +} + +export function definitionOf(schema: JsonSchema, kind: NodeKind): JsonSchema { + const definition = schema.$defs?.[kind]; + if (!definition) { + throw new Error(`The schema has no definition of a ${kind}`); + } + return definition; +} + +export function inputKindOf(key: string, property: JsonSchema): InputKind { + if (property.enum) { + return "choice"; + } + if (property.anyOf) { + return "number"; + } + const types = Array.isArray(property.type) ? property.type : [property.type]; + if (types.includes("array")) { + return "list"; + } + if (types.includes("boolean")) { + // Without a default, leaving the key out means something of its own. + return property.default === undefined ? "either" : "flag"; + } + return key === "description" ? "longtext" : "text"; +} + +// The text an input shows for a value that is not set. +export function placeholderOf(property: JsonSchema): string { + if (property.default !== undefined && property.default !== "" && property.default !== false) { + return `Default: ${String(property.default)}`; + } + const match = property.description?.match(/Default: ([^.]+)\./); + return match ? `Default: ${match[1]}` : ""; +} + +// A number as the user typed it: decimal digits become a JSON number, any +// other form (0x1c, 0b101) stays a string, as bust reads both. +export function parseNumber(text: string): JsonValue | undefined { + const trimmed = text.trim(); + if (trimmed === "") { + return undefined; + } + return /^[0-9]+$/.test(trimmed) ? Number(trimmed) : trimmed; +} diff --git a/editor-ui/src/style.css b/editor-ui/src/style.css new file mode 100644 index 0000000..ad1ebfd --- /dev/null +++ b/editor-ui/src/style.css @@ -0,0 +1,386 @@ +/* The bust documentation palette: logvik paper, ink and teal. A host page can + set the --bust-* variables to theme the editor. */ +.bust-editor { + --bust-editor-paper: var(--bust-paper, #f2eee3); + --bust-editor-raised: var(--bust-raised, #e9e3d3); + --bust-editor-hover: var(--bust-hover, #e3ddcb); + --bust-editor-border: var(--bust-border, #d3cbb4); + --bust-editor-ink: var(--bust-ink, #1c2118); + --bust-editor-muted: var(--bust-muted, #686b61); + --bust-editor-teal: var(--bust-teal, #2c6e6a); + --bust-editor-on-teal: var(--bust-on-teal, #f2eee3); + --bust-editor-error: var(--bust-error, #b3261e); + --bust-editor-warning: var(--bust-warning, #8d6e00); + --bust-editor-mono: var(--bust-mono, ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace); + + display: flex; + flex-direction: column; + gap: 0.75rem; + min-height: 0; + color: var(--bust-editor-ink); + background: var(--bust-editor-paper); + font-size: 0.95rem; +} + +@media (prefers-color-scheme: dark) { + .bust-editor { + --bust-editor-paper: var(--bust-paper, #1f1e1d); + --bust-editor-raised: var(--bust-raised, #2a2725); + --bust-editor-hover: var(--bust-hover, #2f2c2a); + --bust-editor-border: var(--bust-border, #3a3633); + --bust-editor-ink: var(--bust-ink, #ece8df); + --bust-editor-muted: var(--bust-muted, #9a948a); + --bust-editor-teal: var(--bust-teal, #5fa8a0); + --bust-editor-on-teal: var(--bust-on-teal, #1f1e1d); + --bust-editor-error: var(--bust-error, #f2867c); + --bust-editor-warning: var(--bust-warning, #d9b44a); + } +} + +.bust-editor button, +.bust-editor input, +.bust-editor select, +.bust-editor textarea { + font: inherit; + color: inherit; +} + +.bust-editor :focus-visible { + outline: 2px solid var(--bust-editor-teal); + outline-offset: 1px; +} + +.bust-editor-toolbar { + display: flex; + flex-wrap: wrap; + gap: 0.5rem 1rem; +} + +.bust-editor-group { + display: flex; + gap: 0.25rem; +} + +.bust-editor-toolbar button, +.bust-editor-form button, +.bust-editor-enums button { + padding: 0.3rem 0.7rem; + background: var(--bust-editor-raised); + border: 1px solid var(--bust-editor-border); + border-radius: 4px; + cursor: pointer; +} + +.bust-editor-toolbar button:hover:not(:disabled), +.bust-editor-form button:hover { + background: var(--bust-editor-hover); +} + +.bust-editor-toolbar button:disabled { + opacity: 0.45; + cursor: default; +} + +.bust-editor-body { + display: grid; + grid-template-columns: minmax(13rem, 1fr) 2.5fr; + gap: 1rem; + min-height: 0; +} + +@media (max-width: 44rem) { + .bust-editor-body { + grid-template-columns: 1fr; + } +} + +.bust-editor-tree { + overflow: auto; + max-height: 70vh; + padding: 0.4rem; + background: var(--bust-editor-raised); + border: 1px solid var(--bust-editor-border); + border-radius: 6px; +} + +.bust-editor-tree ul { + margin: 0; + padding: 0; + list-style: none; +} + +.bust-editor-tree ul ul { + margin-left: 0.9rem; + padding-left: 0.4rem; + border-left: 1px solid var(--bust-editor-border); +} + +.bust-editor-node { + display: flex; + align-items: baseline; + gap: 0.6rem; + width: 100%; + padding: 0.2rem 0.45rem; + text-align: left; + background: none; + border: none; + border-radius: 4px; + cursor: pointer; +} + +.bust-editor-node:hover { + background: var(--bust-editor-hover); +} + +.bust-editor-node[aria-current="true"] { + color: var(--bust-editor-on-teal); + background: var(--bust-editor-teal); +} + +.bust-editor-node[aria-current="true"] .bust-editor-meta { + color: inherit; + opacity: 0.85; +} + +.bust-editor-meta { + flex: none; + min-width: 3.2rem; + font-family: var(--bust-editor-mono); + font-size: 0.8rem; + color: var(--bust-editor-muted); +} + +.bust-editor-name { + overflow-wrap: anywhere; +} + +.bust-editor-module .bust-editor-name { + font-weight: 600; +} + +.bust-editor-node.bust-editor-invalid .bust-editor-name::after { + content: " \25CF"; + color: var(--bust-editor-error); +} + +.bust-editor-detail { + min-width: 0; +} + +.bust-editor-heading { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0 1rem; + margin-bottom: 0.5rem; + border-bottom: 2px solid var(--bust-editor-teal); +} + +.bust-editor-heading h3 { + margin: 0 0 0.25rem; + font-size: 1.15rem; +} + +.bust-editor-heading p { + margin: 0; + font-family: var(--bust-editor-mono); + font-size: 0.85rem; + color: var(--bust-editor-muted); +} + +.bust-editor-row { + display: grid; + grid-template-columns: 11rem 1fr; + align-items: center; + gap: 0.15rem 0.75rem; + padding: 0.4rem 0; +} + +.bust-editor-row > label, +.bust-editor-label { + font-weight: 500; +} + +.bust-editor-row > :not(label, .bust-editor-label, input[type="checkbox"]) { + grid-column: 2; +} + +.bust-editor-check { + grid-template-columns: 11rem auto 1fr; +} + +.bust-editor-check input { + justify-self: start; + width: 1.1rem; + height: 1.1rem; + accent-color: var(--bust-editor-teal); +} + +.bust-editor-check label { + grid-row: 1; + grid-column: 1; +} + +@media (max-width: 30rem) { + .bust-editor-row { + grid-template-columns: 1fr; + } + .bust-editor-row > * { + grid-column: 1 !important; + } +} + +.bust-editor-row input[type="text"], +.bust-editor-row select, +.bust-editor-row textarea { + box-sizing: border-box; + width: 100%; + max-width: 28rem; + padding: 0.3rem 0.45rem; + background: var(--bust-editor-paper); + border: 1px solid var(--bust-editor-border); + border-radius: 4px; +} + +.bust-editor-row input[type="text"] { + font-family: var(--bust-editor-mono); + font-size: 0.9rem; +} + +.bust-editor-row textarea { + max-width: none; + resize: vertical; +} + +.bust-editor-help { + margin: 0; + font-size: 0.8rem; + color: var(--bust-editor-muted); +} + +.bust-editor-row.bust-editor-invalid :is(input, select, textarea) { + border-color: var(--bust-editor-error); + box-shadow: 0 0 0 1px var(--bust-editor-error); +} + +.bust-editor-problem { + margin: 0; + font-size: 0.85rem; + color: var(--bust-editor-error); +} + +.bust-editor-form details { + margin: 0.5rem 0; + padding: 0.25rem 0.75rem; + border: 1px solid var(--bust-editor-border); + border-radius: 6px; +} + +.bust-editor-form summary { + padding: 0.25rem 0; + cursor: pointer; + color: var(--bust-editor-teal); +} + +.bust-editor-messages:empty { + display: none; +} + +.bust-editor-messages { + margin-bottom: 0.5rem; +} + +.bust-editor-rejected { + margin: 0; + font-weight: 600; + color: var(--bust-editor-error); +} + +.bust-editor-problems, +.bust-editor-warnings { + margin: 0.25rem 0; + padding-left: 1.2rem; + font-family: var(--bust-editor-mono); + font-size: 0.85rem; +} + +.bust-editor-problems { + color: var(--bust-editor-error); +} + +.bust-editor-warnings { + color: var(--bust-editor-warning); +} + +/* One column per bit, the highest on the left, as in bust's documentation. */ +.bust-editor-bits { + display: grid; + grid-template-columns: repeat(var(--bust-editor-bit-count), minmax(0, 1fr)); + gap: 2px; + padding: 2px; + background: repeating-linear-gradient( + 90deg, + var(--bust-editor-raised) 0 calc(100% / var(--bust-editor-bit-count) - 2px), + var(--bust-editor-border) 0 calc(100% / var(--bust-editor-bit-count)) + ); + border: 1px solid var(--bust-editor-border); + border-radius: 4px; +} + +.bust-editor-bits button { + grid-row: 1; + display: flex; + flex-direction: column; + align-items: center; + min-width: 0; + padding: 0.2rem 0.1rem; + overflow: hidden; + color: var(--bust-editor-on-teal); + background: var(--bust-editor-teal); + border: none; + border-radius: 3px; + cursor: pointer; +} + +.bust-editor-bits span, +.bust-editor-bits small { + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 0.75rem; +} + +.bust-editor-bits small { + font-family: var(--bust-editor-mono); + font-size: 0.7rem; + opacity: 0.85; +} + +.bust-editor-enums { + border-collapse: collapse; +} + +.bust-editor-enums th { + font-weight: 500; + text-align: left; + color: var(--bust-editor-muted); +} + +.bust-editor-enums td { + padding: 0.15rem 0.5rem 0.15rem 0; +} + +.bust-editor-enums input { + box-sizing: border-box; + width: 100%; + padding: 0.25rem 0.4rem; + font-family: var(--bust-editor-mono); + background: var(--bust-editor-paper); + border: 1px solid var(--bust-editor-border); + border-radius: 4px; +} + +.bust-editor-row > button { + justify-self: start; +} diff --git a/editor-ui/tests/editor.test.mjs b/editor-ui/tests/editor.test.mjs new file mode 100644 index 0000000..9d7320a --- /dev/null +++ b/editor-ui/tests/editor.test.mjs @@ -0,0 +1,169 @@ +// The editor against bust itself: a bust bridge process over stdio, as an +// editor on the desktop runs it. Set PYTHON to a Python that has bust. +import { after, before, beforeEach, describe, test } from "node:test"; +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { createInterface } from "node:readline"; +import { Window } from "happy-dom"; +import { BustBridge, RegisterMapEditor } from "../dist/index.js"; + +const window = new Window(); +for (const name of ["document", "Node", "HTMLElement", "HTMLInputElement", "Event", "KeyboardEvent"]) { + globalThis[name] = window[name]; +} + +const example = readFileSync(new URL("../../example/example_axi.json", import.meta.url), "utf8"); + +function startBust() { + const child = spawn(process.env.PYTHON ?? "python3", ["-m", "bust.editing.bridge"], { + cwd: new URL("../..", import.meta.url), + stdio: ["pipe", "pipe", "inherit"], + }); + const waiting = new Map(); + createInterface({ input: child.stdout }).on("line", (line) => { + const { id } = JSON.parse(line); + waiting.get(id)(line); + waiting.delete(id); + }); + const transport = (request) => + new Promise((resolve) => { + waiting.set(JSON.parse(request).id, resolve); + child.stdin.write(request + "\n"); + }); + return { child, transport }; +} + +function button(container, name) { + return [...container.querySelectorAll("button")].find((candidate) => candidate.textContent === name); +} + +function treeNode(container, name) { + return [...container.querySelectorAll(".bust-editor-node")].find( + (node) => node.querySelector(".bust-editor-name").textContent === name, + ); +} + +function treeNames(container) { + return [...container.querySelectorAll(".bust-editor-node .bust-editor-name")].map((name) => name.textContent); +} + +function change(input, value) { + if (input.type === "checkbox") { + input.checked = value; + } else { + input.value = value; + } + input.dispatchEvent(new Event("change")); +} + +describe("RegisterMapEditor", () => { + let bust; + let container; + let editor; + let changes; + + before(() => { + bust = startBust(); + }); + + after(() => bust.child.kill()); + + beforeEach(async () => { + container = document.createElement("div"); + changes = []; + editor = new RegisterMapEditor(container, new BustBridge(bust.transport), { + onChange: (state) => changes.push(state), + }); + await editor.open(example); + }); + + test("lists the registers with the addresses bust gives them", () => { + const names = treeNames(container); + assert.deepEqual(names.slice(0, 4), ["Bus", "example_axi", "reg0", "reg1"]); + assert.equal(treeNode(container, "reg1").querySelector(".bust-editor-meta").textContent, "0x00000004"); + assert.ok(names.includes("field3")); + }); + + test("a change in the form goes to bust and comes back as text", async () => { + treeNode(container, "reg1").click(); + await editor.idle(); + const sw = container.querySelector("[data-key='sw'] select"); + change(sw, "ro"); + await editor.idle(); + assert.equal(editor.state.data.module.register[1].sw, "ro"); + assert.match(changes.at(-1).text, /"sw": "ro"/); + assert.equal(button(container, "Undo").disabled, false); + }); + + test("a change bust rejects stays in the form with bust's problem", async () => { + treeNode(container, "reg1").click(); + const name = container.querySelector("[data-key='name'] input"); + change(name, "reg0"); + await editor.idle(); + assert.equal(editor.state.data.module.register[1].name, "reg1"); + assert.equal(name.value, "reg0"); + assert.ok(container.querySelector(".bust-editor-rejected")); + }); + + test("problems with a path show next to their input", async () => { + treeNode(container, "reg1").click(); + const address = container.querySelector("[data-key='address'] input"); + change(address, "zz"); + await editor.idle(); + const row = container.querySelector("[data-key='address']"); + assert.ok(row.classList.contains("bust-editor-invalid")); + assert.ok(row.querySelector(".bust-editor-problem").textContent.length > 0); + }); + + test("adding a register puts it after the selected one", async () => { + treeNode(container, "reg1").click(); + await editor.idle(); + button(container, "Add register").click(); + await editor.idle(); + const names = editor.state.data.module.register.map((register) => register.name); + assert.deepEqual(names.slice(0, 3), ["reg0", "reg1", "reg12"]); + assert.equal(container.querySelector("[aria-current='true'] .bust-editor-name").textContent, "reg12"); + }); + + test("adding a field turns a register into a fields register", async () => { + treeNode(container, "reg0").click(); + await editor.idle(); + button(container, "Add field").click(); + await editor.idle(); + const register = editor.state.data.module.register[0]; + assert.equal(register.type, "fields"); + assert.deepEqual(register.fields, [{ name: "field0", type: "bit" }]); + assert.equal(container.querySelector("[aria-current='true'] .bust-editor-name").textContent, "field0"); + }); + + test("moving and removing a register, then undoing", async () => { + treeNode(container, "reg1").click(); + await editor.idle(); + button(container, "Move up").click(); + await editor.idle(); + assert.deepEqual( + editor.state.data.module.register.slice(0, 2).map((register) => register.name), + ["reg1", "reg0"], + ); + button(container, "Remove").click(); + await editor.idle(); + assert.equal(editor.state.data.module.register[0].name, "reg0"); + button(container, "Undo").click(); + await editor.idle(); + button(container, "Undo").click(); + await editor.idle(); + assert.equal(editor.state.text, example); + }); + + test("the register's fields show by bit", async () => { + treeNode(container, "reg7").click(); + await editor.idle(); + const cells = [...container.querySelectorAll(".bust-editor-bits button")]; + assert.deepEqual( + cells.map((cell) => cell.title), + ["field0 [0]", "field1 [4:1]", "field2 [5]", "field3 [20:6]"], + ); + assert.equal(cells[1].style.gridColumn, "28 / 32"); + }); +}); diff --git a/editor-ui/tsconfig.json b/editor-ui/tsconfig.json new file mode 100644 index 0000000..0328651 --- /dev/null +++ b/editor-ui/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "types": [], + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "declaration": true, + "outDir": "dist", + "rootDir": "src" + }, + "include": ["src"] +} From efbb47b6ea0306d5d7dbba03d6fdb286d2ebcd0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ola=20Gr=C3=B8ttvik?= Date: Fri, 30 Oct 2026 08:59:40 +0000 Subject: [PATCH 2/6] Show bust's unplaced problems at the edited value in bust-editor --- editor-ui/src/editor.ts | 11 ++++++++++- editor-ui/src/style.css | 6 +++--- editor-ui/tests/editor.test.mjs | 2 ++ 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/editor-ui/src/editor.ts b/editor-ui/src/editor.ts index 39693e8..74bb639 100644 --- a/editor-ui/src/editor.ts +++ b/editor-ui/src/editor.ts @@ -81,6 +81,9 @@ export class RegisterMapEditor { private accepted?: AcceptedState; private problems: Problem[] = []; private selected: ValuePath = ["module"]; + // The key of the selected object the last change from the form set. A + // problem bust gives without a place is shown there. + private editedKey?: string; private queue: Promise = Promise.resolve(); private readonly id = `bust-editor-${nextEditorId++}`; private readonly toolbar = element("div", { class: "bust-editor-toolbar", role: "toolbar", "aria-label": "Register map" }); @@ -167,6 +170,7 @@ export class RegisterMapEditor { } this.accepted = state; this.problems = []; + this.editedKey = undefined; if (valueAt(state.data, this.selected) === undefined) { this.selected = this.nearestExisting(this.selected); } @@ -318,6 +322,7 @@ export class RegisterMapEditor { private select(path: ValuePath): void { this.selected = path; this.problems = []; + this.editedKey = undefined; this.render(); this.form.querySelector("input, select, textarea")?.focus(); } @@ -396,6 +401,7 @@ export class RegisterMapEditor { const inputId = `${this.id}-${key}`; const input = this.input(key, property, object[key], required.includes(key), inputId); const commit = () => { + this.editedKey = key; const value = this.readInput(input, key, property, required.includes(key)); this.apply(this.operationsFor(kind, object, key, value)); }; @@ -499,7 +505,10 @@ export class RegisterMapEditor { row.classList.remove("bust-editor-invalid"); row.querySelector(".bust-editor-problem")?.remove(); const path = [...this.selected, row.dataset.key!]; - const problems = this.problems.filter((problem) => startsWith(problem.path, path)); + const problems = this.problems.filter( + (problem) => + startsWith(problem.path, path) || (problem.path.length === 0 && row.dataset.key === this.editedKey), + ); if (problems.length > 0) { row.classList.add("bust-editor-invalid"); row.append(element("p", { class: "bust-editor-problem" }, problems.map((problem) => problem.message).join(" "))); diff --git a/editor-ui/src/style.css b/editor-ui/src/style.css index ad1ebfd..2b4559b 100644 --- a/editor-ui/src/style.css +++ b/editor-ui/src/style.css @@ -83,7 +83,7 @@ .bust-editor-body { display: grid; - grid-template-columns: minmax(13rem, 1fr) 2.5fr; + grid-template-columns: minmax(12rem, 1fr) minmax(0, 2.5fr); gap: 1rem; min-height: 0; } @@ -190,7 +190,7 @@ .bust-editor-row { display: grid; - grid-template-columns: 11rem 1fr; + grid-template-columns: 8.5rem minmax(0, 1fr); align-items: center; gap: 0.15rem 0.75rem; padding: 0.4rem 0; @@ -206,7 +206,7 @@ } .bust-editor-check { - grid-template-columns: 11rem auto 1fr; + grid-template-columns: 8.5rem auto 1fr; } .bust-editor-check input { diff --git a/editor-ui/tests/editor.test.mjs b/editor-ui/tests/editor.test.mjs index 9d7320a..0f94dde 100644 --- a/editor-ui/tests/editor.test.mjs +++ b/editor-ui/tests/editor.test.mjs @@ -104,6 +104,8 @@ describe("RegisterMapEditor", () => { assert.equal(editor.state.data.module.register[1].name, "reg1"); assert.equal(name.value, "reg0"); assert.ok(container.querySelector(".bust-editor-rejected")); + // bust names no place for this problem, so it shows at the edited value. + assert.ok(container.querySelector("[data-key='name']").classList.contains("bust-editor-invalid")); }); test("problems with a path show next to their input", async () => { From 37f516a782a577c4b4a658e7579dde2d121c855b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ola=20Gr=C3=B8ttvik?= Date: Fri, 30 Oct 2026 09:01:33 +0000 Subject: [PATCH 3/6] Widen the bust-editor bit map and mark the selected node on hover --- editor-ui/src/editor.ts | 10 ++++++++-- editor-ui/src/style.css | 14 ++++++++------ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/editor-ui/src/editor.ts b/editor-ui/src/editor.ts index 74bb639..b2a7b09 100644 --- a/editor-ui/src/editor.ts +++ b/editor-ui/src/editor.ts @@ -378,7 +378,8 @@ export class RegisterMapEditor { if (placed) { const bus = this.accepted!.data.bus as JsonObject; const digits = Math.ceil(Number(bus.addr_width) / 4) || 4; - heading.append(element("p", {}, `At ${hex(placed.address, digits)}, ${placed.width} bits wide`)); + const width = placed.width === 1 ? "1 bit" : `${placed.width} bits`; + heading.append(element("p", {}, `At ${hex(placed.address, digits)}, ${width} wide`)); } return heading; } @@ -537,7 +538,12 @@ export class RegisterMapEditor { cell.addEventListener("click", () => this.select([...this.selected, "fields", index])); map.append(cell); } - return element("div", { class: "bust-editor-row" }, element("span", { class: "bust-editor-label" }, "Fields"), map); + return element( + "div", + { class: "bust-editor-row bust-editor-wide" }, + element("span", { class: "bust-editor-label" }, `Fields, bit ${width - 1} down to 0`), + map, + ); } private enumTable(field: JsonObject): HTMLElement { diff --git a/editor-ui/src/style.css b/editor-ui/src/style.css index 2b4559b..8102922 100644 --- a/editor-ui/src/style.css +++ b/editor-ui/src/style.css @@ -132,7 +132,8 @@ background: var(--bust-editor-hover); } -.bust-editor-node[aria-current="true"] { +.bust-editor-node[aria-current="true"], +.bust-editor-node[aria-current="true"]:hover { color: var(--bust-editor-on-teal); background: var(--bust-editor-teal); } @@ -205,6 +206,10 @@ grid-column: 2; } +.bust-editor-wide > * { + grid-column: 1 / -1 !important; +} + .bust-editor-check { grid-template-columns: 8.5rem auto 1fr; } @@ -318,17 +323,14 @@ grid-template-columns: repeat(var(--bust-editor-bit-count), minmax(0, 1fr)); gap: 2px; padding: 2px; - background: repeating-linear-gradient( - 90deg, - var(--bust-editor-raised) 0 calc(100% / var(--bust-editor-bit-count) - 2px), - var(--bust-editor-border) 0 calc(100% / var(--bust-editor-bit-count)) - ); + background: var(--bust-editor-raised); border: 1px solid var(--bust-editor-border); border-radius: 4px; } .bust-editor-bits button { grid-row: 1; + min-height: 2.6rem; display: flex; flex-direction: column; align-items: center; From 3cf906856a9dd6a22e37bfd533a6069614a53b5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ola=20Gr=C3=B8ttvik?= Date: Fri, 30 Oct 2026 09:34:13 +0000 Subject: [PATCH 4/6] Rebuild bust-editor around register and field tables, menus and dialogs --- editor-ui/src/diagram.ts | 40 ++ editor-ui/src/dom.ts | 20 + editor-ui/src/editor.ts | 1043 +++++++++++++++++++---------------- editor-ui/src/form.ts | 317 +++++++++++ editor-ui/src/index.ts | 2 + editor-ui/src/menu.ts | 102 ++++ editor-ui/src/operations.ts | 52 ++ editor-ui/src/protocol.ts | 26 +- editor-ui/src/style.css | 598 ++++++++++++++------ 9 files changed, 1546 insertions(+), 654 deletions(-) create mode 100644 editor-ui/src/diagram.ts create mode 100644 editor-ui/src/dom.ts create mode 100644 editor-ui/src/form.ts create mode 100644 editor-ui/src/menu.ts diff --git a/editor-ui/src/diagram.ts b/editor-ui/src/diagram.ts new file mode 100644 index 0000000..61e46e6 --- /dev/null +++ b/editor-ui/src/diagram.ts @@ -0,0 +1,40 @@ +import { element } from "./dom.js"; +import type { BitSegment } from "./protocol.js"; + +// A register's bits from the highest down, drawn as bust's documentation +// draws them: a box per field with its name, its bit numbers above and its +// reset value below. Unused bits are a dashed box. +export function bitDiagram( + segments: BitSegment[], + selectedName: string | undefined, + onSelect?: (name: string) => void, +): HTMLElement { + const width = segments.reduce((highest, segment) => Math.max(highest, segment.high + 1), 0); + const diagram = element("div", { class: "bust-editor-diagram", role: "group", "aria-label": "Bits" }); + diagram.style.setProperty("--bust-editor-bit-count", String(width)); + for (const segment of segments) { + const column = `${width - segment.high} / ${width - segment.low + 1}`; + const numbers = + segment.high === segment.low + ? [element("span", {}, String(segment.high))] + : [element("span", {}, String(segment.high)), element("span", {}, String(segment.low))]; + const label = element("span", { class: "bust-editor-diagram-bits" }, ...numbers); + const box = segment.isUnused || !onSelect + ? element("span", { class: "bust-editor-diagram-box" }, element("span", {}, segment.isUnused ? "" : segment.name)) + : element("button", { type: "button", class: "bust-editor-diagram-box", title: segment.name }, element("span", {}, segment.name)); + if (box instanceof HTMLButtonElement) { + box.addEventListener("click", () => onSelect!(segment.name)); + if (segment.name === selectedName) { + box.setAttribute("aria-current", "true"); + } + } + const reset = element("span", { class: "bust-editor-diagram-reset" }, segment.reset); + const cell = element("div", { class: "bust-editor-diagram-segment" }, label, box, reset); + if (segment.isUnused) { + cell.classList.add("bust-editor-unused"); + } + cell.style.gridColumn = column; + diagram.append(cell); + } + return diagram; +} diff --git a/editor-ui/src/dom.ts b/editor-ui/src/dom.ts new file mode 100644 index 0000000..8a294f4 --- /dev/null +++ b/editor-ui/src/dom.ts @@ -0,0 +1,20 @@ +export function element( + tag: K, + attributes: Record = {}, + ...children: (Node | string)[] +): HTMLElementTagNameMap[K] { + const created = document.createElement(tag); + for (const [name, value] of Object.entries(attributes)) { + created.setAttribute(name, value); + } + created.append(...children); + return created; +} + +export function hex(value: number, digits: number): string { + return "0x" + value.toString(16).toUpperCase().padStart(digits, "0"); +} + +export function bitRange(low: number, high: number): string { + return low === high ? `[${low}]` : `[${high}:${low}]`; +} diff --git a/editor-ui/src/editor.ts b/editor-ui/src/editor.ts index b2a7b09..d56487a 100644 --- a/editor-ui/src/editor.ts +++ b/editor-ui/src/editor.ts @@ -1,14 +1,8 @@ -import { - ACCESS_KEYS, - ADVANCED_KEYS, - definitionOf, - inputKindOf, - labelOf, - parseNumber, - placeholderOf, - type NodeKind, -} from "./schema.js"; -import { insertAt, move, removeAt, setFieldType, setKey, setRegisterType, uniqueName } from "./operations.js"; +import { bitDiagram } from "./diagram.js"; +import { bitRange, element, hex } from "./dom.js"; +import { FormDialog, type Draft, type FormSection } from "./form.js"; +import { PopupMenu, type MenuItem } from "./menu.js"; +import { editOperations, insertAt, move, newObject, removeAt, setRegisterType, uniqueName } from "./operations.js"; import type { AcceptedState, BustBridge, @@ -20,76 +14,49 @@ import type { Problem, ValuePath, } from "./protocol.js"; +import { definitionOf, labelOf, placeholderOf, type NodeKind } from "./schema.js"; export type EditorOptions = { // Called with every register map bust accepts, after each change. onChange?: (state: AcceptedState) => void; }; -type TreeNode = { kind: NodeKind; path: ValuePath; label: string; meta: string; children: TreeNode[] }; - const REGISTERS: ValuePath = ["module", "register"]; -let nextEditorId = 0; - -function element( - tag: K, - attributes: Record = {}, - ...children: (Node | string)[] -): HTMLElementTagNameMap[K] { - const created = document.createElement(tag); - for (const [name, value] of Object.entries(attributes)) { - created.setAttribute(name, value); - } - created.append(...children); - return created; -} - -function samePath(a: ValuePath, b: ValuePath): boolean { - return a.length === b.length && a.every((token, index) => token === b[index]); -} - -function startsWith(path: ValuePath, prefix: ValuePath): boolean { - return prefix.length <= path.length && prefix.every((token, index) => token === path[index]); -} - -function valueAt(data: JsonValue, path: ValuePath): JsonValue | undefined { - let current: JsonValue | undefined = data; - for (const token of path) { - if (current === null || typeof current !== "object") { - return undefined; - } - current = (current as Record)[token as string]; - } - return current; -} +// What the keys pane shows: the selected register, or one of its fields. +type Subject = "register" | "field"; -function hex(value: number, digits: number): string { - return "0x" + value.toString(16).toUpperCase().padStart(digits, "0"); -} - -function bits(low: number, high: number): string { - return low === high ? `[${low}]` : `[${high}:${low}]`; -} +const SHORTCUTS = { + edit: "Enter", + addRegister: "A", + addField: "F", + remove: "Del", + module: "M", + menu: "Shift+F10", +}; -// A tree of the bus, the module, its registers and their fields, next to a -// form for the one selected. Every change goes to bust as JSON Patch, and the -// editor shows only register maps bust accepts. A change bust rejects leaves -// the form as typed, with bust's problems next to the values they are about. +// The register map as bust's console editor shows it: the registers, the +// fields of the selected one with its bit diagram, and the keys of the +// register or field in focus. Changes are made in dialogs and from pop-up +// menus on each register and field, and every one goes to bust as JSON +// Patch. A change bust rejects keeps its dialog open with bust's problems +// next to the values they are about, so the editor only holds register maps +// bust accepts. export class RegisterMapEditor { private schema?: JsonSchema; private accepted?: AcceptedState; - private problems: Problem[] = []; - private selected: ValuePath = ["module"]; - // The key of the selected object the last change from the form set. A - // problem bust gives without a place is shown there. - private editedKey?: string; + private registerIndex = 0; + private fieldIndex = 0; + private subject: Subject = "register"; private queue: Promise = Promise.resolve(); - private readonly id = `bust-editor-${nextEditorId++}`; private readonly toolbar = element("div", { class: "bust-editor-toolbar", role: "toolbar", "aria-label": "Register map" }); - private readonly tree = element("nav", { class: "bust-editor-tree", "aria-label": "Registers" }); - private readonly form = element("form", { class: "bust-editor-form" }); + private readonly summary = element("div", { class: "bust-editor-summary" }); private readonly messages = element("div", { class: "bust-editor-messages", role: "status", "aria-live": "polite" }); + private readonly registersPane = element("section", { class: "bust-editor-pane bust-editor-registers" }); + private readonly detailPane = element("section", { class: "bust-editor-pane bust-editor-detail" }); + private readonly keysPane = element("section", { class: "bust-editor-pane bust-editor-keys" }); + private readonly menu: PopupMenu; + private readonly dialog: FormDialog; constructor( container: HTMLElement, @@ -99,9 +66,17 @@ export class RegisterMapEditor { container.classList.add("bust-editor"); container.replaceChildren( this.toolbar, - element("div", { class: "bust-editor-body" }, this.tree, element("div", { class: "bust-editor-detail" }, this.messages, this.form)), + this.summary, + this.messages, + element( + "div", + { class: "bust-editor-body" }, + element("div", { class: "bust-editor-main" }, this.registersPane, this.detailPane), + this.keysPane, + ), ); - this.form.addEventListener("submit", (event) => event.preventDefault()); + this.menu = new PopupMenu(container); + this.dialog = new FormDialog(container); container.addEventListener("keydown", (event) => this.onKey(event)); } @@ -112,32 +87,15 @@ export class RegisterMapEditor { // Starts editing the register map in `text`. If bust rejects it, the // editor keeps what it had and the state lists bust's problems. open(text: string): Promise { - return this.run(async () => { - this.selected = ["module"]; - return this.bridge.call("open", { text }); - }); + return this.run(() => this.bridge.call("open", { text }), () => this.reset()); } create(bus: JsonObject, module: JsonObject): Promise { - return this.run(async () => { - this.selected = ["module"]; - return this.bridge.call("new", { bus, module }); - }); - } - - apply(operations: Operation[], select?: ValuePath): Promise { - return this.run(async () => { - const state = await this.bridge.call("apply", { operations }); - if (state.accepted && select) { - this.selected = select; - } - return state; - }); + return this.run(() => this.bridge.call("new", { bus, module }), () => this.reset()); } - // Resolves when every change made so far has come back from bust. - async idle(): Promise { - await this.queue; + apply(operations: Operation[], onAccepted?: () => void): Promise { + return this.run(() => this.bridge.call("apply", { operations }), onAccepted); } undo(): Promise { @@ -148,494 +106,605 @@ export class RegisterMapEditor { return this.run(() => this.bridge.call("redo", {})); } + // Resolves when every change made so far has come back from bust. + async idle(): Promise { + await this.queue; + } + // One request at a time, so that quick changes reach bust in order. - private run(request: () => Promise): Promise { + private run(request: () => Promise, onAccepted?: () => void): Promise { const result = this.queue.then(async () => { this.schema ??= await this.bridge.call("schema", {}); const state = await request(); - this.show(state); + if (state.accepted) { + this.accepted = state; + onAccepted?.(); + this.render(); + this.showProblems([]); + this.options.onChange?.(state); + } else { + this.showProblems(state.problems); + } return state; }); this.queue = result.catch(() => undefined); return result; } - private show(state: EditorState): void { - if (!state.accepted) { - this.problems = state.problems; - this.renderMessages(); - this.renderTree(); - this.markProblemsInForm(); - return; + // Makes a change from a dialog: problems keep the dialog open. + private async applyFromDialog(operations: Operation[], onAccepted?: () => void): Promise { + if (operations.length === 0) { + return undefined; } - this.accepted = state; - this.problems = []; - this.editedKey = undefined; - if (valueAt(state.data, this.selected) === undefined) { - this.selected = this.nearestExisting(this.selected); + const state = await this.apply(operations, onAccepted); + if (state.accepted) { + return undefined; } - this.render(); - this.options.onChange?.(state); + this.showProblems([]); + return state.problems; } - private nearestExisting(path: ValuePath): ValuePath { - const data = this.accepted!.data; - const parent = path.slice(0, -1); - const index = path[path.length - 1]; - if (typeof index === "number" && index > 0 && valueAt(data, [...parent, index - 1]) !== undefined) { - return [...parent, index - 1]; - } - return parent.length > 1 ? this.nearestExisting(parent.slice(0, -1)) : ["module"]; + // The register map as bust read it. + + private get data(): JsonObject { + return this.accepted!.data; + } + + private get registers(): JsonObject[] { + return (this.data.module as JsonObject).register as JsonObject[]; + } + + private get register(): JsonObject | undefined { + return this.registers[this.registerIndex]; + } + + private get fields(): JsonObject[] { + return (this.register?.fields as JsonObject[] | undefined) ?? []; + } + + private get addressDigits(): number { + return Math.ceil(Number((this.data.bus as JsonObject).addr_width) / 4) || 4; } + private registerPath(index = this.registerIndex): ValuePath { + return [...REGISTERS, index]; + } + + private fieldPath(index = this.fieldIndex): ValuePath { + return [...this.registerPath(), "fields", index]; + } + + // Showing it. + private render(): void { + this.registerIndex = Math.min(this.registerIndex, Math.max(this.registers.length - 1, 0)); + this.fieldIndex = Math.min(this.fieldIndex, Math.max(this.fields.length - 1, 0)); + if (this.fields.length === 0) { + this.subject = "register"; + } this.renderToolbar(); - this.renderTree(); - this.renderForm(); - this.renderMessages(); + this.renderSummary(); + this.renderRegisters(); + this.renderDetail(); + this.renderKeys(); + } + + private button(label: string, action: () => void, options: { shortcut?: string; isEnabled?: boolean; className?: string } = {}): HTMLButtonElement { + const created = element("button", { type: "button" }, label); + created.disabled = options.isEnabled === false; + if (options.shortcut) { + created.title = `${label} (${options.shortcut})`; + } + if (options.className) { + created.className = options.className; + } + created.addEventListener("click", action); + return created; } private renderToolbar(): void { const state = this.accepted!; - const kind = this.selectedKind(); - const index = this.selected[this.selected.length - 1]; - const siblings = kind === "register" || kind === "field" ? (valueAt(state.data, this.selected.slice(0, -1)) as JsonValue[]) : []; - const button = (label: string, enabled: boolean, action: () => void, shortcut?: string) => { - const created = element("button", { type: "button" }, label); - created.disabled = !enabled; - if (shortcut) { - created.setAttribute("aria-keyshortcuts", shortcut); - } - created.addEventListener("click", action); - return created; - }; this.toolbar.replaceChildren( element( "div", { class: "bust-editor-group" }, - button("Undo", state.canUndo, () => this.undo(), "Control+Z"), - button("Redo", state.canRedo, () => this.redo(), "Control+Shift+Z"), + this.button("Undo", () => this.undo(), { isEnabled: state.canUndo, shortcut: "Ctrl+Z" }), + this.button("Redo", () => this.redo(), { isEnabled: state.canRedo, shortcut: "Ctrl+Shift+Z" }), ), element( "div", { class: "bust-editor-group" }, - button("Add register", true, () => this.addRegister()), - button("Add field", kind === "register" || kind === "field", () => this.addField()), - ), - element( - "div", - { class: "bust-editor-group" }, - button("Move up", typeof index === "number" && index > 0, () => this.moveSelected(-1)), - button("Move down", typeof index === "number" && index < siblings.length - 1, () => this.moveSelected(1)), - button("Remove", kind === "register" || kind === "field", () => this.removeSelected()), + this.button("Add register", () => this.addRegister(this.registers.length), { shortcut: SHORTCUTS.addRegister }), + this.button("Module and bus", () => this.editModule(), { shortcut: SHORTCUTS.module }), ), + element("p", { class: "bust-editor-hint" }, "Right-click a register or field, or press ", element("kbd", {}, "Shift+F10"), ", for its menu."), ); } - private selectedKind(): NodeKind { - return this.kindOf(this.selected); - } - - private kindOf(path: ValuePath): NodeKind { - if (path[0] === "bus") { - return "bus"; - } - return (["module", "module", "register", "register", "field"] as NodeKind[])[path.length - 1] ?? "field"; - } - - private nodes(): TreeNode[] { - const { data, layout } = this.accepted!; - const bus = data.bus as JsonObject; - const module = data.module as JsonObject; - const registers = module.register as JsonObject[]; - const digits = Math.ceil(Number(bus.addr_width) / 4) || 4; - return [ - { kind: "bus", path: ["bus"], label: "Bus", meta: String(bus.type), children: [] }, - { - kind: "module", - path: ["module"], - label: String(module.name), - meta: "module", - children: registers.map((register, index) => { - const placed = layout[String(register.name)]; - const fields = (register.fields as JsonObject[] | undefined) ?? []; - return { - kind: "register", - path: [...REGISTERS, index], - label: String(register.name), - meta: placed ? hex(placed.address, digits) : "", - children: fields.map((field, fieldIndex) => { - const span = placed?.fields[String(field.name)]; - return { - kind: "field", - path: [...REGISTERS, index, "fields", fieldIndex], - label: String(field.name), - meta: span ? bits(span[0], span[1]) : "", - children: [], - }; - }), - }; - }), - }, - ]; + private renderSummary(): void { + const module = this.data.module as JsonObject; + const bus = this.data.bus as JsonObject; + const facts = [`${String(bus.type)} bus`, `${String(bus.addr_width)}-bit addresses`, `${String(bus.data_width)}-bit data`]; + if (module.version) { + facts.push(`version ${String(module.version)}`); + } + const name = this.button(String(module.name), () => this.editModule(), { className: "bust-editor-module-name" }); + name.title = "Module and bus"; + this.summary.replaceChildren(name, element("span", {}, facts.join(" · "))); + if (module.description) { + this.summary.append(element("p", {}, String(module.description))); + } } - // The node a problem belongs to: the deepest one whose path leads to it. - private ownerOf(problem: Problem, nodes: TreeNode[]): ValuePath | undefined { - for (const node of nodes) { - if (startsWith(problem.path, node.path)) { - return this.ownerOf(problem, node.children) ?? node.path; - } - } - return undefined; + private renderRegisters(): void { + const { layout } = this.accepted!; + const rows = this.registers.map((register, index) => { + const placed = layout[String(register.name)]; + return this.tableRow( + [ + placed ? hex(placed.address, this.addressDigits) : "", + String(register.name), + placed?.type ?? String(register.type ?? ""), + placed ? String(placed.width) : "", + placed?.access ?? "", + placed?.reset ?? "", + String(register.description ?? ""), + ], + index === this.registerIndex, + () => this.selectRegister(index), + () => this.editRegister(), + (x, y, anchor) => this.registerMenu(x, y, anchor), + ); + }); + const empty = element("p", { class: "bust-editor-empty" }, "No registers yet. ", this.button("Add register", () => this.addRegister(0))); + this.registersPane.replaceChildren( + element("h3", {}, "Registers"), + rows.length > 0 ? this.table(["Address", "Name", "Type", "Width", "SW/HW", "Reset", "Description"], rows, "Registers") : empty, + ); } - private renderTree(): void { - if (!this.accepted) { + private renderDetail(): void { + const register = this.register; + if (!register) { + this.detailPane.replaceChildren(); return; } - const nodes = this.nodes(); - const owners = this.problems.map((problem) => this.ownerOf(problem, nodes)).filter((path) => path !== undefined); - const item = (node: TreeNode): HTMLLIElement => { - const button = element( - "button", - { type: "button", class: `bust-editor-node bust-editor-${node.kind}` }, - element("span", { class: "bust-editor-meta" }, node.meta), - element("span", { class: "bust-editor-name" }, node.label), - ); - if (samePath(node.path, this.selected)) { - button.setAttribute("aria-current", "true"); - } - if (owners.some((owner) => samePath(owner, node.path))) { - button.classList.add("bust-editor-invalid"); - } - button.addEventListener("click", () => this.select(node.path)); - const created = element("li", {}, button); - if (node.children.length > 0) { - created.append(element("ul", {}, ...node.children.map(item))); - } - return created; - }; - this.tree.replaceChildren(element("ul", {}, ...nodes.map(item))); + const placed = this.accepted!.layout[String(register.name)]; + const heading = element( + "div", + { class: "bust-editor-pane-head" }, + element("h3", {}, `Fields of ${String(register.name)}`), + this.button("Add field", () => this.addField(this.fields.length), { shortcut: SHORTCUTS.addField }), + ); + const children: Node[] = [heading]; + if (placed) { + const selected = this.subject === "field" ? String(this.fields[this.fieldIndex]?.name) : undefined; + const onSelect = register.type === "fields" ? (name: string) => this.selectField(this.fields.findIndex((field) => field.name === name)) : undefined; + children.push(bitDiagram(placed.segments, selected, onSelect)); + } + if (this.fields.length > 0) { + const rows = this.fields.map((field, index) => { + const fieldLayout = placed?.fields[String(field.name)]; + return this.tableRow( + [ + fieldLayout ? bitRange(fieldLayout.low, fieldLayout.high) : "", + String(field.name), + String(field.type), + fieldLayout?.access ?? "", + fieldLayout?.reset ?? "", + String(field.description ?? ""), + ], + this.subject === "field" && index === this.fieldIndex, + () => this.selectField(index), + () => this.editField(), + (x, y, anchor) => this.fieldMenu(x, y, anchor), + ); + }); + children.push(this.table(["Bits", "Name", "Type", "SW/HW", "Reset", "Description"], rows, `Fields of ${String(register.name)}`)); + } else { + children.push(element("p", { class: "bust-editor-empty" }, "A register of type fields holds named fields. Add one to turn this register into one.")); + } + this.detailPane.replaceChildren(...children); } - private select(path: ValuePath): void { - this.selected = path; - this.problems = []; - this.editedKey = undefined; - this.render(); - this.form.querySelector("input, select, textarea")?.focus(); - } - - private renderMessages(): void { - const items: HTMLElement[] = []; - if (this.problems.length > 0) { - items.push( - element("p", { class: "bust-editor-rejected" }, "bust did not make this change:"), - element( - "ul", - { class: "bust-editor-problems" }, - ...this.problems.map((problem) => - element("li", {}, problem.location ? `${problem.location}: ${problem.message}` : problem.message), - ), - ), - ); - } - const warnings = this.accepted?.warnings ?? []; - if (warnings.length > 0) { - items.push(element("ul", { class: "bust-editor-warnings" }, ...warnings.map((warning) => element("li", {}, `Ignored: ${warning}`)))); + private table(headings: string[], rows: HTMLTableRowElement[], label: string): HTMLElement { + return element( + "div", + { class: "bust-editor-table-wrap" }, + element( + "table", + { class: "bust-editor-table", "aria-label": label }, + element("thead", {}, element("tr", {}, ...headings.map((heading) => element("th", {}, heading)), element("th", { class: "bust-editor-actions" }, element("span", { class: "bust-editor-hidden" }, "Actions")))), + element("tbody", {}, ...rows), + ), + ); + } + + private tableRow( + cells: string[], + isSelected: boolean, + select: () => void, + edit: () => void, + openMenu: (x: number, y: number, anchor?: HTMLElement) => void, + ): HTMLTableRowElement { + const more = element("button", { type: "button", class: "bust-editor-more", "aria-label": "Actions", "aria-haspopup": "menu" }, "⋯"); + more.addEventListener("click", (event) => { + event.stopPropagation(); + select(); + const box = more.getBoundingClientRect(); + openMenu(box.left, box.bottom + 2, more); + }); + const row = element( + "tr", + { tabindex: isSelected ? "0" : "-1" }, + ...cells.map((cell, index) => element("td", index === 1 ? { class: "bust-editor-name" } : {}, cell)), + element("td", { class: "bust-editor-actions" }, more), + ); + if (isSelected) { + row.setAttribute("aria-selected", "true"); } - this.messages.replaceChildren(...items); + row.addEventListener("click", select); + row.addEventListener("dblclick", edit); + row.addEventListener("contextmenu", (event) => { + event.preventDefault(); + select(); + openMenu(event.clientX, event.clientY); + }); + return row; } - private renderForm(): void { - const kind = this.selectedKind(); - const object = valueAt(this.accepted!.data, this.selected) as JsonObject; + // The keys of the register or field in focus, with the values bust uses + // for those the file leaves out. A click on one changes it. + private renderKeys(): void { + const kind: NodeKind = this.subject; + const object = kind === "field" ? this.fields[this.fieldIndex] : this.register; + if (!object) { + this.keysPane.replaceChildren(element("h3", {}, "Keys"), element("p", { class: "bust-editor-empty" }, "Add a register to see its keys.")); + return; + } const definition = definitionOf(this.schema!, kind); - const keys = Object.keys(definition.properties ?? {}).filter((key) => this.isShown(kind, key, object)); - const rows = (wanted: string[]) => - wanted.map((key) => this.row(kind, object, key, definition.properties![key], definition.required ?? [])); - const children: Node[] = [this.heading(kind, object), ...rows(keys.filter((key) => !ADVANCED_KEYS.has(key)))]; - const advanced = keys.filter((key) => ADVANCED_KEYS.has(key)); - if (advanced.length > 0) { - const details = element("details", {}, element("summary", {}, "More access options"), ...rows(advanced)); - details.open = advanced.some((key) => key in object); - children.push(details); + const owner = kind === "field" ? `Field ${String(object.name)} of ${String(this.register!.name)}` : `Register ${String(object.name)}`; + const list = element("dl", { class: "bust-editor-key-list" }); + for (const [key, property] of Object.entries(definition.properties ?? {})) { + if (["fields", "$schema"].includes(key)) { + continue; + } + const value = this.shownValue(kind, object, key, property); + const button = this.button(labelOf(key), () => (kind === "field" ? this.editField(key) : this.editRegister(key))); + button.title = property.description ?? ""; + const valueElement = element("dd", {}, value.text); + if (!value.isSet) { + valueElement.classList.add("bust-editor-unset"); + } + list.append(element("div", {}, element("dt", {}, button), valueElement)); } - if (kind === "register" && Array.isArray(object.fields)) { - children.push(this.bitMap(object)); + const edit = this.button("Edit", () => (kind === "field" ? this.editField() : this.editRegister()), { shortcut: SHORTCUTS.edit }); + this.keysPane.replaceChildren(element("div", { class: "bust-editor-pane-head" }, element("h3", {}, owner), edit), list); + } + + private shownValue(kind: NodeKind, object: JsonObject, key: string, property: JsonSchema): { text: string; isSet: boolean } { + const value = object[key]; + if (key === "enums") { + const entries = Array.isArray(value) ? (value as JsonObject[]) : []; + const text = entries.map((entry) => `${String(entry.name)} = ${String(entry.value)}`).join(", "); + return { text: text || "none", isSet: entries.length > 0 }; } - if (kind === "field") { - children.push(this.enumTable(object)); + if (value !== undefined && value !== null) { + return { text: String(value), isSet: true }; } - this.form.replaceChildren(...children); + const placed = this.accepted!.layout[String(this.register!.name)]; + const known: Record = { + address: placed ? hex(placed.address, this.addressDigits) : undefined, + width: placed && kind === "register" ? String(placed.width) : undefined, + position: kind === "field" ? String(placed?.fields[String(object.name)]?.low ?? "") : undefined, + }; + const fallback = known[key] ?? (property.default !== undefined ? String(property.default) : placeholderOf(property).replace(/^Default: /, "")); + return { text: fallback ? `${fallback} (not set)` : "not set", isSet: false }; } - private heading(kind: NodeKind, object: JsonObject): HTMLElement { - const title = kind === "bus" ? "Bus" : `${labelOf(kind)} ${String(object.name)}`; - const heading = element("div", { class: "bust-editor-heading" }, element("h3", {}, title)); - const placed = kind === "register" ? this.accepted!.layout[String(object.name)] : undefined; - if (placed) { - const bus = this.accepted!.data.bus as JsonObject; - const digits = Math.ceil(Number(bus.addr_width) / 4) || 4; - const width = placed.width === 1 ? "1 bit" : `${placed.width} bits`; - heading.append(element("p", {}, `At ${hex(placed.address, digits)}, ${width} wide`)); + private showProblems(problems: Problem[]): void { + if (problems.length === 0) { + this.messages.replaceChildren(...this.warningItems()); + return; } - return heading; + this.messages.replaceChildren( + element("p", { class: "bust-editor-rejected" }, "bust did not make this change:"), + element( + "ul", + { class: "bust-editor-problems" }, + ...problems.map((problem) => element("li", {}, problem.location ? `${problem.location}: ${problem.message}` : problem.message)), + ), + ...this.warningItems(), + ); + } + + private warningItems(): HTMLElement[] { + const warnings = this.accepted?.warnings ?? []; + return warnings.length === 0 + ? [] + : [element("ul", { class: "bust-editor-warnings" }, ...warnings.map((warning) => element("li", {}, `Ignored: ${warning}`)))]; } - // Keys that do not apply to the object's type stay out of the form. - private isShown(kind: NodeKind, key: string, object: JsonObject): boolean { - if (["register", "fields", "enums", "$schema"].includes(key)) { - return false; + // Selection. + + private reset(): void { + this.registerIndex = 0; + this.fieldIndex = 0; + this.subject = "register"; + } + + private selectRegister(index: number): void { + const isNew = index !== this.registerIndex; + this.registerIndex = index; + this.subject = "register"; + if (isNew) { + this.fieldIndex = 0; } - if (key === "width" && (kind === "register" || kind === "field")) { - return object.type === "vector" || "width" in object; + if (this.accepted) { + this.render(); + this.focusSelectedRow(this.registersPane); } - if (kind === "register" && object.type === "fields") { - return !(ACCESS_KEYS.has(key) || key === "reset") || key in object; + } + + private selectField(index: number): void { + if (index < 0) { + return; } - return true; + this.fieldIndex = index; + this.subject = "field"; + this.render(); + this.focusSelectedRow(this.detailPane); } - private row(kind: NodeKind, object: JsonObject, key: string, property: JsonSchema, required: string[]): HTMLElement { - const inputId = `${this.id}-${key}`; - const input = this.input(key, property, object[key], required.includes(key), inputId); - const commit = () => { - this.editedKey = key; - const value = this.readInput(input, key, property, required.includes(key)); - this.apply(this.operationsFor(kind, object, key, value)); - }; - input.addEventListener("change", commit); - const row = element("div", { class: "bust-editor-row", "data-key": key }); - const label = element("label", { for: inputId }, labelOf(key)); - if (input instanceof HTMLInputElement && input.type === "checkbox") { - row.classList.add("bust-editor-check"); - row.append(input, label); - } else { - row.append(label, input); + private focusSelectedRow(pane: HTMLElement): void { + pane.querySelector("tr[aria-selected='true']")?.focus({ preventScroll: false }); + } + + // Menus. + + private registerMenu(x: number, y: number, anchor?: HTMLElement): void { + const index = this.registerIndex; + const items: MenuItem[] = [ + { label: "Edit register…", shortcut: SHORTCUTS.edit, action: () => this.editRegister() }, + { label: "Add field…", shortcut: SHORTCUTS.addField, action: () => this.addField(this.fields.length) }, + "separator", + { label: "Insert register above…", action: () => this.addRegister(index) }, + { label: "Insert register below…", shortcut: SHORTCUTS.addRegister, action: () => this.addRegister(index + 1) }, + { label: "Duplicate", action: () => this.duplicate(REGISTERS, this.registers, index, "register") }, + "separator", + { label: "Move up", isDisabled: index === 0, action: () => this.moveSelected(REGISTERS, this.registers, index, -1, "register") }, + { label: "Move down", isDisabled: index >= this.registers.length - 1, action: () => this.moveSelected(REGISTERS, this.registers, index, 1, "register") }, + "separator", + { label: "Remove register", shortcut: SHORTCUTS.remove, isDangerous: true, action: () => this.apply(removeAt(REGISTERS, index)) }, + ]; + this.menu.openAt(x, y, `Register ${String(this.register!.name)}`, items, anchor ?? this.focusTarget()); + } + + private fieldMenu(x: number, y: number, anchor?: HTMLElement): void { + const index = this.fieldIndex; + const listPath = [...this.registerPath(), "fields"]; + const items: MenuItem[] = [ + { label: "Edit field…", shortcut: SHORTCUTS.edit, action: () => this.editField() }, + { label: "Named values…", action: () => this.editField("enums") }, + "separator", + { label: "Insert field above…", action: () => this.addField(index) }, + { label: "Insert field below…", shortcut: SHORTCUTS.addField, action: () => this.addField(index + 1) }, + { label: "Duplicate", action: () => this.duplicate(listPath, this.fields, index, "field") }, + "separator", + { label: "Move up", isDisabled: index === 0, action: () => this.moveSelected(listPath, this.fields, index, -1, "field") }, + { label: "Move down", isDisabled: index >= this.fields.length - 1, action: () => this.moveSelected(listPath, this.fields, index, 1, "field") }, + "separator", + { label: "Remove field", shortcut: SHORTCUTS.remove, isDangerous: true, action: () => this.apply(removeAt(listPath, index)) }, + ]; + this.menu.openAt(x, y, `Field ${String(this.fields[index].name)}`, items, anchor ?? this.focusTarget()); + } + + private focusTarget(): HTMLElement | undefined { + const pane = this.subject === "field" ? this.detailPane : this.registersPane; + return pane.querySelector("tr[aria-selected='true']") ?? undefined; + } + + private openMenuForSelection(): void { + const row = this.focusTarget(); + if (!row) { + return; } - if (property.description) { - const help = element("p", { class: "bust-editor-help", id: `${inputId}-help` }, property.description); - input.setAttribute("aria-describedby", help.id); - row.append(help); + const box = row.getBoundingClientRect(); + if (this.subject === "field") { + this.fieldMenu(box.left + 24, box.bottom, row); + } else { + this.registerMenu(box.left + 24, box.bottom, row); } - return row; } - private operationsFor(kind: NodeKind, object: JsonObject, key: string, value: JsonValue | undefined): Operation[] { - if (key === "type" && kind === "register") { - return setRegisterType(object, this.selected, value as string | undefined); - } - if (key === "type" && kind === "field") { - return setFieldType(object, this.selected, value as string | undefined); - } - return setKey(object, this.selected, key, value); - } - - private input( - key: string, - property: JsonSchema, - value: JsonValue | undefined, - isRequired: boolean, - id: string, - ): HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement { - switch (inputKindOf(key, property)) { - case "choice": { - const select = element("select", { id }); - if (!isRequired || value === undefined) { - const fallback = property.default === undefined ? "Not set" : `Default (${String(property.default)})`; - select.append(element("option", { value: "" }, fallback)); - } - select.append(...property.enum!.map((choice) => element("option", { value: choice }, choice))); - select.value = value === undefined ? "" : String(value).toLowerCase(); - return select; - } - case "either": { - const select = element( - "select", - { id }, - element("option", { value: "" }, placeholderOf(property) || "Not set"), - element("option", { value: "true" }, "Yes"), - element("option", { value: "false" }, "No"), - ); - select.value = value === undefined || value === null ? "" : String(value); - return select; - } - case "flag": { - const checkbox = element("input", { id, type: "checkbox" }); - checkbox.checked = value === true; - return checkbox; - } - case "longtext": { - const textarea = element("textarea", { id, rows: "3" }); - textarea.value = value === undefined ? "" : String(value); - return textarea; - } - default: { - const text = element("input", { id, type: "text", spellcheck: "false", autocomplete: "off" }); - text.value = value === undefined || value === null ? "" : String(value); - text.placeholder = placeholderOf(property); - return text; - } + // Dialogs. + + private section(kind: NodeKind, values: JsonObject, path: ValuePath, heading?: string): FormSection { + return { kind, heading, definition: definitionOf(this.schema!, kind), values, path }; + } + + private formKeys(kind: NodeKind): string[] { + return Object.keys(definitionOf(this.schema!, kind).properties ?? {}).filter((key) => !["register", "fields", "$schema"].includes(key)); + } + + private editModule(): void { + const bus = this.data.bus as JsonObject; + const module = this.data.module as JsonObject; + this.dialog.open({ + title: "Module and bus", + submitLabel: "Save", + sections: [this.section("module", module, ["module"], "Module"), this.section("bus", bus, ["bus"], "Bus")], + submit: ([moduleDraft, busDraft]) => + this.applyFromDialog([ + ...editOperations("module", module, ["module"], moduleDraft, this.formKeys("module")), + ...editOperations("bus", bus, ["bus"], busDraft, this.formKeys("bus")), + ]), + }); + } + + private editRegister(focusKey?: string): void { + const register = this.register; + if (!register) { + return; } + const path = this.registerPath(); + this.dialog.open({ + title: `Register ${String(register.name)}`, + submitLabel: "Save", + focusKey, + sections: [this.section("register", register, path)], + submit: ([draft]) => this.applyFromDialog(editOperations("register", register, path, draft, this.formKeys("register"))), + }); } - private readInput( - input: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement, - key: string, - property: JsonSchema, - isRequired: boolean, - ): JsonValue | undefined { - switch (inputKindOf(key, property)) { - case "flag": - return (input as HTMLInputElement).checked ? true : undefined; - case "either": - return input.value === "" ? undefined : input.value === "true"; - case "number": - return parseNumber(input.value) ?? (isRequired ? "" : undefined); - default: - return input.value === "" && !isRequired ? undefined : input.value; - } - } - - // Shows each problem under the input of the value it is about, when that - // value is in the form. - private markProblemsInForm(): void { - for (const row of this.form.querySelectorAll(".bust-editor-row")) { - row.classList.remove("bust-editor-invalid"); - row.querySelector(".bust-editor-problem")?.remove(); - const path = [...this.selected, row.dataset.key!]; - const problems = this.problems.filter( - (problem) => - startsWith(problem.path, path) || (problem.path.length === 0 && row.dataset.key === this.editedKey), - ); - if (problems.length > 0) { - row.classList.add("bust-editor-invalid"); - row.append(element("p", { class: "bust-editor-problem" }, problems.map((problem) => problem.message).join(" "))); - } + private editField(focusKey?: string): void { + const field = this.fields[this.fieldIndex]; + if (!field) { + return; } + const path = this.fieldPath(); + this.dialog.open({ + title: `Field ${String(field.name)} of ${String(this.register!.name)}`, + submitLabel: "Save", + focusKey, + sections: [this.section("field", field, path)], + submit: ([draft]) => this.applyFromDialog(editOperations("field", field, path, draft, this.formKeys("field"))), + }); } - // The register's bits from the highest down, each field where bust put it. - private bitMap(register: JsonObject): HTMLElement { - const placed = this.accepted!.layout[String(register.name)]; - const width = Math.max(placed?.width ?? 0, Number((this.accepted!.data.bus as JsonObject).data_width) || 0); - const map = element("div", { class: "bust-editor-bits", role: "group", "aria-label": "Fields by bit" }); - map.style.setProperty("--bust-editor-bit-count", String(width)); - const fields = (register.fields as JsonObject[]).map((field, index) => ({ field, index, span: placed?.fields[String(field.name)] })); - for (const { field, index, span } of fields) { - if (!span) { - continue; - } - const cell = element( - "button", - { type: "button", title: `${String(field.name)} ${bits(span[0], span[1])}` }, - element("span", {}, String(field.name)), - element("small", {}, bits(span[0], span[1])), - ); - cell.style.gridColumn = `${width - span[1]} / ${width - span[0] + 1}`; - cell.addEventListener("click", () => this.select([...this.selected, "fields", index])); - map.append(cell); + private addRegister(index: number): void { + const values: JsonObject = { name: uniqueName("reg", this.registers.map((register) => String(register.name))) }; + const address = this.addressBefore(index); + if (address) { + values.address = address; } - return element( - "div", - { class: "bust-editor-row bust-editor-wide" }, - element("span", { class: "bust-editor-label" }, `Fields, bit ${width - 1} down to 0`), - map, - ); + this.dialog.open({ + title: "Add register", + submitLabel: "Add", + sections: [this.section("register", values, this.registerPath(index))], + submit: ([draft]) => + this.applyFromDialog(insertAt(REGISTERS, index, newObject("register", draft)), () => this.selectRegister(index)), + }); } - private enumTable(field: JsonObject): HTMLElement { - const enums = (field.enums as JsonObject[] | undefined) ?? []; - const listPath = [...this.selected, "enums"]; - const cell = (index: number, key: "name" | "value") => { - const input = element("input", { type: "text", spellcheck: "false", "aria-label": `${labelOf(key)} ${index + 1}` }); - input.value = String(enums[index][key]); - input.addEventListener("change", () => { - const value = key === "value" ? (parseNumber(input.value) ?? "") : input.value; - this.apply(setKey(enums[index], [...listPath, index], key, value)); - }); - return element("td", {}, input); - }; - const remove = (index: number) => { - const button = element("button", { type: "button", "aria-label": `Remove value ${index + 1}` }, "Remove"); - button.addEventListener("click", () => - this.apply(enums.length === 1 ? setKey(field, this.selected, "enums", undefined) : removeAt(listPath, index)), - ); - return element("td", {}, button); - }; - const add = element("button", { type: "button" }, "Add value"); - add.addEventListener("click", () => { - const name = uniqueName("VALUE", enums.map((value) => String(value.name))); - const values = enums.map((value) => Number(parseNumber(String(value.value)))).filter(Number.isFinite); - const value = { name, value: values.length > 0 ? Math.max(...values) + 1 : 0 }; - this.apply(enums.length === 0 ? setKey(field, this.selected, "enums", [value]) : insertAt(listPath, enums.length, value)); + // Without an address of its own, a register put before one with an + // address could take that address. + private addressBefore(index: number): string | undefined { + const next = this.registers[index]; + return next && "address" in next ? "0x" + this.accepted!.nextAddress.toString(16).toUpperCase() : undefined; + } + + private addField(index: number): void { + const register = this.register; + if (!register) { + return; + } + const values: JsonObject = { name: uniqueName("field", this.fields.map((field) => String(field.name))), type: "bit" }; + const registerPath = this.registerPath(); + const listPath = [...registerPath, "fields"]; + this.dialog.open({ + title: `Add field to ${String(register.name)}`, + submitLabel: "Add", + sections: [this.section("field", values, [...listPath, index])], + submit: ([draft]) => this.applyFromDialog(this.addFieldOperations(register, index, draft), () => this.selectField(index)), }); - const table = element( - "table", - { class: "bust-editor-enums" }, - element("thead", {}, element("tr", {}, element("th", {}, "Name"), element("th", {}, "Value"), element("th", {}))), - element("tbody", {}, ...enums.map((_, index) => element("tr", {}, cell(index, "name"), cell(index, "value"), remove(index)))), - ); - return element( - "div", - { class: "bust-editor-row", "data-key": "enums" }, - element("span", { class: "bust-editor-label" }, "Named values"), - ...(enums.length > 0 ? [table] : []), - add, - ); } - private addRegister(): Promise { - const registers = (this.accepted!.data.module as JsonObject).register as JsonObject[]; - const kind = this.selectedKind(); - const index = kind === "register" || kind === "field" ? (this.selected[2] as number) + 1 : registers.length; - const register: JsonObject = { name: uniqueName("reg", registers.map((other) => String(other.name))) }; - // Without an address of its own, a register put before one with an - // address could take that address. - if (registers[index] && "address" in registers[index]) { - register.address = "0x" + this.accepted!.nextAddress.toString(16).toUpperCase(); + // The first field makes the register a fields register, which leaves no + // place for the keys only a register of bits has. + private addFieldOperations(register: JsonObject, index: number, draft: Draft): Operation[] { + const registerPath = this.registerPath(); + const field = newObject("field", draft); + if (this.fields.length > 0) { + return insertAt([...registerPath, "fields"], index, field); } - return this.apply(insertAt(REGISTERS, index, register), [...REGISTERS, index]); + return setRegisterType(register, registerPath, "fields").map((operation) => + operation.op === "add" && operation.path.endsWith("/fields") ? { ...operation, value: [field] } : operation, + ); } - private addField(): Promise { - const registerPath = this.selected.slice(0, 3); - const register = valueAt(this.accepted!.data, registerPath) as JsonObject; - const fields = (register.fields as JsonObject[] | undefined) ?? []; - const name = uniqueName("field", fields.map((field) => String(field.name))); - if (fields.length === 0) { - const operations = setRegisterType(register, registerPath, "fields"); - return this.apply(operations, [...registerPath, "fields", 0]); + private duplicate(listPath: ValuePath, list: JsonObject[], index: number, kind: "register" | "field"): Promise { + const copy: JsonObject = structuredClone(list[index]); + copy.name = uniqueName(`${String(copy.name)}_copy`, list.map((item) => String(item.name))); + if (kind === "register") { + delete copy.address; + const address = this.addressBefore(index + 1); + if (address) { + copy.address = address; + } + } else { + delete copy.position; } - const index = this.selectedKind() === "field" ? (this.selected[4] as number) + 1 : fields.length; - return this.apply(insertAt([...registerPath, "fields"], index, { name, type: "bit" }), [...registerPath, "fields", index]); + const select = () => (kind === "register" ? this.selectRegister(index + 1) : this.selectField(index + 1)); + return this.apply(insertAt(listPath, index + 1, copy), select); } - private moveSelected(step: number): Promise { - const listPath = this.selected.slice(0, -1); - const from = this.selected[this.selected.length - 1] as number; - const list = valueAt(this.accepted!.data, listPath) as JsonValue[]; - return this.apply(move(listPath, list, from, from + step), [...listPath, from + step]); + private moveSelected(listPath: ValuePath, list: JsonValue[], index: number, step: number, kind: "register" | "field"): Promise { + const select = () => (kind === "register" ? this.selectRegister(index + step) : this.selectField(index + step)); + return this.apply(move(listPath, list, index, index + step), select); } - private removeSelected(): Promise { - const listPath = this.selected.slice(0, -1); - const index = this.selected[this.selected.length - 1] as number; - return this.apply(removeAt(listPath, index)); + private removeSelected(): void { + if (this.subject === "field" && this.fields.length > 0) { + this.apply(removeAt([...this.registerPath(), "fields"], this.fieldIndex)); + } else if (this.register) { + this.apply(removeAt(REGISTERS, this.registerIndex)); + } } + // Keys, as in the console editor. + private onKey(event: KeyboardEvent): void { const target = event.target as HTMLElement; - if (!(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "z" || target.matches("input, textarea")) { + if (!this.accepted || this.dialog.isOpen || this.menu.isOpen || target.matches("input, textarea, select")) { return; } - event.preventDefault(); - if (event.shiftKey) { - this.redo(); - } else { - this.undo(); + const key = event.key; + if ((event.ctrlKey || event.metaKey) && key.toLowerCase() === "z") { + event.preventDefault(); + if (event.shiftKey) { + this.redo(); + } else { + this.undo(); + } + return; + } + if (event.ctrlKey || event.metaKey || event.altKey) { + return; + } + const isRow = target.matches("tr"); + const actions: Record void> = { + a: () => this.addRegister(this.register ? this.registerIndex + 1 : 0), + f: () => this.addField(this.subject === "field" ? this.fieldIndex + 1 : this.fields.length), + m: () => this.editModule(), + Delete: () => this.removeSelected(), + ContextMenu: () => this.openMenuForSelection(), + }; + if (isRow) { + Object.assign(actions, { + Enter: () => (this.subject === "field" ? this.editField() : this.editRegister()), + ArrowDown: () => this.step(1), + ArrowUp: () => this.step(-1), + }); + } + const action = key === "F10" && event.shiftKey ? actions.ContextMenu : actions[key.length === 1 ? key.toLowerCase() : key]; + if (action) { + event.preventDefault(); + action(); + } + } + + private step(change: number): void { + if (this.subject === "field") { + const index = this.fieldIndex + change; + if (index >= 0 && index < this.fields.length) { + this.selectField(index); + } + return; + } + const index = this.registerIndex + change; + if (index >= 0 && index < this.registers.length) { + this.selectRegister(index); } } } diff --git a/editor-ui/src/form.ts b/editor-ui/src/form.ts new file mode 100644 index 0000000..6361e28 --- /dev/null +++ b/editor-ui/src/form.ts @@ -0,0 +1,317 @@ +import { element } from "./dom.js"; +import type { JsonObject, JsonSchema, JsonValue, Problem, ValuePath } from "./protocol.js"; +import { ACCESS_KEYS, ADVANCED_KEYS, inputKindOf, labelOf, parseNumber, placeholderOf, type NodeKind } from "./schema.js"; + +type Input = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement; + +// The values a section of the form holds, by key. An undefined value means +// the key is left out of the register map. +export type Draft = Record; + +export type FormSection = { + kind: NodeKind; + heading?: string; + definition: JsonSchema; + values: JsonObject; + // Where the object sits in the register map, to place bust's problems. + path: ValuePath; +}; + +export type FormRequest = { + title: string; + submitLabel: string; + sections: FormSection[]; + focusKey?: string; + // Makes the change. Problems keep the dialog open and show next to the + // values they are about. + submit: (drafts: Draft[]) => Promise; +}; + +type Row = { key: string; property: JsonSchema; isRequired: boolean; element: HTMLElement; read: () => JsonValue | undefined }; + +let nextFormId = 0; + +// Keys that do not apply to an object's type stay out of the form. +export function isShown(kind: NodeKind, key: string, values: Draft): boolean { + if (["register", "fields", "$schema"].includes(key)) { + return false; + } + if (key === "enums") { + return kind === "field"; + } + if (key === "width" && (kind === "register" || kind === "field")) { + return values.type === "vector"; + } + if (kind === "register" && values.type === "fields") { + return !(ACCESS_KEYS.has(key) || key === "reset") || values[key] !== undefined; + } + return true; +} + +// A dialog with a form built from bust's JSON Schema, one section per object. +export class FormDialog { + private readonly dialog = element("dialog", { class: "bust-editor-dialog" }); + private sectionRows: Row[][] = []; + private request?: FormRequest; + + constructor(host: HTMLElement) { + host.append(this.dialog); + this.dialog.addEventListener("cancel", (event) => { + event.preventDefault(); + this.close(); + }); + } + + get isOpen(): boolean { + return this.dialog.open; + } + + open(request: FormRequest): void { + this.request = request; + const id = `bust-editor-form-${nextFormId++}`; + const form = element("form", { method: "dialog", "aria-labelledby": `${id}-title` }); + form.addEventListener("submit", (event) => { + event.preventDefault(); + this.submit(); + }); + const cancel = element("button", { type: "button" }, "Cancel"); + cancel.addEventListener("click", () => this.close()); + this.sectionRows = request.sections.map((section) => this.rows(section, id)); + form.append( + element("h2", { id: `${id}-title` }, request.title), + element("div", { class: "bust-editor-dialog-problems", role: "alert" }), + ...request.sections.flatMap((section, index) => this.sectionElements(section, this.sectionRows[index])), + element( + "div", + { class: "bust-editor-dialog-buttons" }, + element("button", { type: "submit", class: "bust-editor-primary" }, request.submitLabel), + cancel, + ), + ); + this.dialog.replaceChildren(form); + this.updateVisibility(); + if (typeof this.dialog.showModal === "function") { + this.dialog.showModal(); + } else { + this.dialog.setAttribute("open", ""); + } + const focused = this.sectionRows.flat().find((row) => row.key === request.focusKey) ?? this.sectionRows.flat()[0]; + focused?.element.querySelector("input, select, textarea")?.focus(); + } + + close(): void { + if (typeof this.dialog.close === "function") { + this.dialog.close(); + } + this.dialog.removeAttribute("open"); + this.request = undefined; + } + + private sectionElements(section: FormSection, rows: Row[]): Node[] { + const plain = rows.filter((row) => !ADVANCED_KEYS.has(row.key)).map((row) => row.element); + const advanced = rows.filter((row) => ADVANCED_KEYS.has(row.key)); + const nodes: Node[] = section.heading ? [element("h3", {}, section.heading), ...plain] : plain; + if (advanced.length > 0) { + const details = element("details", {}, element("summary", {}, "More access options"), ...advanced.map((row) => row.element)); + details.open = advanced.some((row) => section.values[row.key] !== undefined); + nodes.push(details); + } + return nodes; + } + + private rows(section: FormSection, formId: string): Row[] { + const required = section.definition.required ?? []; + return Object.entries(section.definition.properties!) + .filter(([key]) => !["register", "fields", "$schema"].includes(key) && (key !== "enums" || section.kind === "field")) + .map(([key, property]) => this.row(section, key, property, required.includes(key), `${formId}-${section.kind}-${key}`)); + } + + private row(section: FormSection, key: string, property: JsonSchema, isRequired: boolean, id: string): Row { + const value = section.values[key]; + if (key === "enums") { + return this.enumRow(value as JsonObject[] | undefined, property, id); + } + const input = inputFor(key, property, value, isRequired, id); + const label = element("label", { for: id }, labelOf(key)); + const rowElement = element("div", { class: "bust-editor-row", "data-key": key }); + if (input instanceof HTMLInputElement && input.type === "checkbox") { + rowElement.classList.add("bust-editor-check"); + rowElement.append(input, label); + } else { + rowElement.append(label, input); + } + if (property.description) { + const help = element("p", { class: "bust-editor-help", id: `${id}-help` }, property.description); + input.setAttribute("aria-describedby", help.id); + rowElement.append(help); + } + if (key === "type") { + input.addEventListener("change", () => this.updateVisibility()); + } + return { key, property, isRequired, element: rowElement, read: () => readInput(input, key, property, isRequired) }; + } + + // The named values of a field: a small table of names and numbers. + private enumRow(values: JsonObject[] | undefined, property: JsonSchema, id: string): Row { + const body = element("tbody"); + const addRow = (name: string, value: string) => { + const index = body.children.length + 1; + const nameInput = element("input", { type: "text", spellcheck: "false", autocomplete: "off", "aria-label": `Name of value ${index}` }); + const valueInput = element("input", { type: "text", spellcheck: "false", autocomplete: "off", "aria-label": `Value ${index}` }); + nameInput.value = name; + valueInput.value = value; + const remove = element("button", { type: "button", "aria-label": `Remove value ${index}` }, "Remove"); + const row = element("tr", {}, element("td", {}, nameInput), element("td", {}, valueInput), element("td", {}, remove)); + remove.addEventListener("click", () => row.remove()); + body.append(row); + return nameInput; + }; + for (const value of values ?? []) { + addRow(String(value.name), String(value.value)); + } + const add = element("button", { type: "button" }, "Add value"); + add.addEventListener("click", () => { + const numbers = [...body.querySelectorAll("td:nth-child(2) input")].map((input) => Number(parseNumber(input.value))); + const next = numbers.filter(Number.isFinite).reduce((highest, number) => Math.max(highest, number + 1), 0); + addRow(`VALUE${body.children.length}`, String(next)).focus(); + }); + const table = element( + "table", + { class: "bust-editor-enums", id }, + element("thead", {}, element("tr", {}, element("th", {}, "Name"), element("th", {}, "Value"), element("th", {}))), + body, + ); + const rowElement = element( + "div", + { class: "bust-editor-row bust-editor-wide", "data-key": "enums" }, + element("span", { class: "bust-editor-label" }, "Named values"), + element("p", { class: "bust-editor-help" }, property.description ?? ""), + table, + add, + ); + const read = (): JsonValue | undefined => { + const rows = [...body.querySelectorAll("tr")].map((row) => { + const [name, value] = row.querySelectorAll("input"); + return { name: name.value, value: parseNumber(value.value) ?? "" }; + }); + return rows.length > 0 ? rows : undefined; + }; + return { key: "enums", property, isRequired: false, element: rowElement, read }; + } + + private drafts(): Draft[] { + return this.sectionRows.map((rows) => + Object.fromEntries(rows.filter((row) => !row.element.hidden).map((row) => [row.key, row.read()])), + ); + } + + private updateVisibility(): void { + this.request?.sections.forEach((section, index) => { + const rows = this.sectionRows[index]; + const values: Draft = { ...section.values, ...Object.fromEntries(rows.map((row) => [row.key, row.read()])) }; + for (const row of rows) { + row.element.hidden = !isShown(section.kind, row.key, values); + } + }); + } + + private async submit(): Promise { + const request = this.request; + if (!request) { + return; + } + const problems = await request.submit(this.drafts()); + if (problems === undefined) { + this.close(); + return; + } + this.showProblems(request, problems); + } + + // Each problem goes under the value it is about. The ones bust gives + // without a place, or for a value not in the form, go at the top. + private showProblems(request: FormRequest, problems: Problem[]): void { + const unplaced: Problem[] = []; + for (const row of this.sectionRows.flat()) { + row.element.classList.remove("bust-editor-invalid"); + row.element.querySelector(".bust-editor-problem")?.remove(); + } + for (const problem of problems) { + const row = request.sections + .flatMap((section, index) => this.sectionRows[index].map((candidate) => ({ section, candidate }))) + .find(({ section, candidate }) => startsWith(problem.path, [...section.path, candidate.key]))?.candidate; + if (!row || row.element.hidden) { + unplaced.push(problem); + continue; + } + row.element.classList.add("bust-editor-invalid"); + row.element.append(element("p", { class: "bust-editor-problem" }, problem.message)); + } + const top = this.dialog.querySelector(".bust-editor-dialog-problems")!; + top.replaceChildren( + ...(unplaced.length > 0 + ? [element("ul", {}, ...unplaced.map((problem) => element("li", {}, problem.message)))] + : []), + ); + this.dialog.querySelector(".bust-editor-invalid input, .bust-editor-invalid select")?.focus(); + } +} + +export function startsWith(path: ValuePath, prefix: ValuePath): boolean { + return prefix.length <= path.length && prefix.every((token, index) => token === path[index]); +} + +function inputFor(key: string, property: JsonSchema, value: JsonValue | undefined, isRequired: boolean, id: string): Input { + switch (inputKindOf(key, property)) { + case "choice": { + const select = element("select", { id }); + if (!isRequired || value === undefined) { + const fallback = property.default === undefined ? "Not set" : `Default (${String(property.default)})`; + select.append(element("option", { value: "" }, fallback)); + } + select.append(...property.enum!.map((choice) => element("option", { value: choice }, choice))); + select.value = value === undefined ? "" : String(value).toLowerCase(); + return select; + } + case "either": { + const select = element( + "select", + { id }, + element("option", { value: "" }, placeholderOf(property) || "Not set"), + element("option", { value: "true" }, "Yes"), + element("option", { value: "false" }, "No"), + ); + select.value = value === undefined || value === null ? "" : String(value); + return select; + } + case "flag": { + const checkbox = element("input", { id, type: "checkbox" }); + checkbox.checked = value === true; + return checkbox; + } + case "longtext": { + const textarea = element("textarea", { id, rows: "3" }); + textarea.value = value === undefined ? "" : String(value); + return textarea; + } + default: { + const text = element("input", { id, type: "text", spellcheck: "false", autocomplete: "off" }); + text.value = value === undefined || value === null ? "" : String(value); + text.placeholder = placeholderOf(property); + return text; + } + } +} + +function readInput(input: Input, key: string, property: JsonSchema, isRequired: boolean): JsonValue | undefined { + switch (inputKindOf(key, property)) { + case "flag": + return (input as HTMLInputElement).checked ? true : undefined; + case "either": + return input.value === "" ? undefined : input.value === "true"; + case "number": + return parseNumber(input.value) ?? (isRequired ? "" : undefined); + default: + return input.value === "" && !isRequired ? undefined : input.value; + } +} diff --git a/editor-ui/src/index.ts b/editor-ui/src/index.ts index f1de215..b5fd3f8 100644 --- a/editor-ui/src/index.ts +++ b/editor-ui/src/index.ts @@ -8,6 +8,8 @@ export { type JsonValue, type Operation, type Problem, + type BitSegment, + type FieldLayout, type RegisterLayout, type RejectedState, type Transport, diff --git a/editor-ui/src/menu.ts b/editor-ui/src/menu.ts new file mode 100644 index 0000000..1126b5a --- /dev/null +++ b/editor-ui/src/menu.ts @@ -0,0 +1,102 @@ +import { element } from "./dom.js"; + +export type MenuItem = + | { + label: string; + action: () => void; + // The key that does the same outside the menu, shown beside the label. + shortcut?: string; + isDisabled?: boolean; + isDangerous?: boolean; + } + | "separator"; + +// A pop-up menu of actions, at a point or under a button. Arrow keys move, +// Enter picks, Escape or a click elsewhere closes it and gives focus back. +export class PopupMenu { + private readonly list = element("ul", { class: "bust-editor-menu", role: "menu" }); + private returnFocus?: HTMLElement; + + constructor(private readonly host: HTMLElement) { + this.list.hidden = true; + host.append(this.list); + this.list.addEventListener("keydown", (event) => this.onKey(event)); + document.addEventListener("pointerdown", (event) => { + if (!this.list.hidden && !this.list.contains(event.target as Node)) { + this.close(false); + } + }); + } + + get isOpen(): boolean { + return !this.list.hidden; + } + + openAt(x: number, y: number, title: string, items: MenuItem[], returnFocus?: HTMLElement): void { + this.returnFocus = returnFocus ?? (document.activeElement as HTMLElement | undefined); + this.list.setAttribute("aria-label", title); + this.list.replaceChildren(element("li", { class: "bust-editor-menu-title", role: "presentation" }, title), ...items.map((item) => this.item(item))); + this.list.hidden = false; + const hostBox = this.host.getBoundingClientRect(); + const menuBox = this.list.getBoundingClientRect(); + // Keeps the menu inside the window. + const left = Math.min(x, window.innerWidth - menuBox.width - 8) - hostBox.left; + const top = (y + menuBox.height > window.innerHeight - 8 ? y - menuBox.height : y) - hostBox.top; + this.list.style.left = `${Math.max(left, 0)}px`; + this.list.style.top = `${Math.max(top, 0)}px`; + this.focusable()[0]?.focus(); + } + + openBelow(anchor: HTMLElement, title: string, items: MenuItem[]): void { + const box = anchor.getBoundingClientRect(); + this.openAt(box.left, box.bottom + 2, title, items, anchor); + } + + close(shouldRestoreFocus = true): void { + if (this.list.hidden) { + return; + } + this.list.hidden = true; + if (shouldRestoreFocus) { + this.returnFocus?.focus(); + } + } + + private item(item: MenuItem): HTMLLIElement { + if (item === "separator") { + return element("li", { class: "bust-editor-menu-separator", role: "separator" }); + } + const button = element( + "button", + { type: "button", role: "menuitem", tabindex: "-1" }, + element("span", {}, item.label), + element("kbd", {}, item.shortcut ?? ""), + ); + button.disabled = item.isDisabled ?? false; + if (item.isDangerous) { + button.classList.add("bust-editor-danger"); + } + button.addEventListener("click", () => { + this.close(); + item.action(); + }); + return element("li", { role: "none" }, button); + } + + private focusable(): HTMLButtonElement[] { + return [...this.list.querySelectorAll("button:not(:disabled)")]; + } + + private onKey(event: KeyboardEvent): void { + const items = this.focusable(); + const index = items.indexOf(document.activeElement as HTMLButtonElement); + const moves: Record = { ArrowDown: index + 1, ArrowUp: index - 1, Home: 0, End: items.length - 1 }; + if (event.key in moves) { + event.preventDefault(); + items[(moves[event.key] + items.length) % items.length]?.focus(); + } else if (event.key === "Escape" || event.key === "Tab") { + event.preventDefault(); + this.close(); + } + } +} diff --git a/editor-ui/src/operations.ts b/editor-ui/src/operations.ts index cb18749..d8ea9e0 100644 --- a/editor-ui/src/operations.ts +++ b/editor-ui/src/operations.ts @@ -63,3 +63,55 @@ export function uniqueName(prefix: string, taken: Iterable): string { } } } + +function isSame(a: JsonValue | undefined, b: JsonValue | undefined): boolean { + return JSON.stringify(a) === JSON.stringify(b); +} + +// The operations that turn `original` into what a form holds. Keys the form +// hides for the object's type are taken out. +export function editOperations( + kind: "bus" | "module" | "register" | "field", + original: JsonObject, + path: ValuePath, + draft: Record, + formKeys: string[], +): Operation[] { + const operations: Operation[] = []; + if ("type" in draft && !isSame(draft.type, original.type)) { + const type = draft.type as string | undefined; + if (kind === "register") { + operations.push(...setRegisterType(original, path, type)); + } else if (kind === "field") { + operations.push(...setFieldType(original, path, type)); + } else { + operations.push(...setKey(original, path, "type", type)); + } + } + const touched = new Set(operations.map((operation) => operation.path)); + for (const key of formKeys) { + const target = pointer([...path, key]); + if (key === "type" || touched.has(target)) { + continue; + } + const value = key in draft ? draft[key] : undefined; + if (!isSame(value, original[key])) { + operations.push(...setKey(original, path, key, value)); + } + } + return operations; +} + +// A new register or field from what a form holds. +export function newObject(kind: "register" | "field", draft: Record): JsonObject { + const created: JsonObject = {}; + for (const [key, value] of Object.entries(draft)) { + if (value !== undefined) { + created[key] = value; + } + } + if (kind === "register" && created.type === "fields") { + created.fields = [{ name: "field0", type: "bit" }]; + } + return created; +} diff --git a/editor-ui/src/protocol.ts b/editor-ui/src/protocol.ts index 66d494d..01bccbc 100644 --- a/editor-ui/src/protocol.ts +++ b/editor-ui/src/protocol.ts @@ -19,11 +19,33 @@ export type Problem = { line: number | null; }; +// A run of bits in a register, from the highest down, as bust's documentation +// draws it: a field, the whole register, or bits no field uses. +export type BitSegment = { + name: string; + high: number; + low: number; + reset: string; + isUnused: boolean; +}; + +export type FieldLayout = { + low: number; + high: number; + // Software and hardware access with defaults filled in, such as "RW/R". + access: string; + reset: string; +}; + +// A register as bust reads it, with the defaults filled in. export type RegisterLayout = { address: number; width: number; - // The lowest and highest bit of each field, by name. - fields: Record; + type: string; + access: string; + reset: string; + segments: BitSegment[]; + fields: Record; }; export type AcceptedState = { diff --git a/editor-ui/src/style.css b/editor-ui/src/style.css index 8102922..abc33ea 100644 --- a/editor-ui/src/style.css +++ b/editor-ui/src/style.css @@ -13,12 +13,12 @@ --bust-editor-warning: var(--bust-warning, #8d6e00); --bust-editor-mono: var(--bust-mono, ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace); + position: relative; display: flex; flex-direction: column; gap: 0.75rem; min-height: 0; color: var(--bust-editor-ink); - background: var(--bust-editor-paper); font-size: 0.95rem; } @@ -37,6 +37,10 @@ } } +.bust-editor [hidden] { + display: none !important; +} + .bust-editor button, .bust-editor input, .bust-editor select, @@ -50,9 +54,41 @@ outline-offset: 1px; } +.bust-editor button { + padding: 0.25rem 0.7rem; + background: var(--bust-editor-raised); + border: 1px solid var(--bust-editor-border); + border-radius: 4px; + cursor: pointer; +} + +.bust-editor button:hover:not(:disabled) { + background: var(--bust-editor-hover); +} + +.bust-editor button:disabled { + opacity: 0.45; + cursor: default; +} + +.bust-editor kbd { + font-family: var(--bust-editor-mono); + font-size: 0.8em; +} + +.bust-editor h3 { + margin: 0; + font-size: 0.8rem; + font-weight: 700; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--bust-editor-muted); +} + .bust-editor-toolbar { display: flex; flex-wrap: wrap; + align-items: center; gap: 0.5rem 1rem; } @@ -61,140 +97,454 @@ gap: 0.25rem; } -.bust-editor-toolbar button, -.bust-editor-form button, -.bust-editor-enums button { - padding: 0.3rem 0.7rem; - background: var(--bust-editor-raised); - border: 1px solid var(--bust-editor-border); - border-radius: 4px; - cursor: pointer; +.bust-editor-hint { + margin: 0 0 0 auto; + font-size: 0.8rem; + color: var(--bust-editor-muted); } -.bust-editor-toolbar button:hover:not(:disabled), -.bust-editor-form button:hover { - background: var(--bust-editor-hover); +.bust-editor-summary { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0.25rem 0.75rem; + font-family: var(--bust-editor-mono); + font-size: 0.85rem; + color: var(--bust-editor-muted); } -.bust-editor-toolbar button:disabled { - opacity: 0.45; - cursor: default; +.bust-editor-summary p { + flex-basis: 100%; + margin: 0; + font-family: initial; + font-family: inherit; +} + +.bust-editor .bust-editor-module-name { + padding: 0; + font-family: inherit; + font-size: 1.1rem; + font-weight: 700; + color: var(--bust-editor-ink); + background: none; + border: none; + border-bottom: 2px solid var(--bust-editor-teal); + border-radius: 0; +} + +.bust-editor .bust-editor-module-name:hover:not(:disabled) { + color: var(--bust-editor-teal); + background: none; +} + +.bust-editor-messages:empty { + display: none; +} + +.bust-editor-rejected { + margin: 0; + font-weight: 600; + color: var(--bust-editor-error); +} + +.bust-editor-problems, +.bust-editor-warnings { + margin: 0.25rem 0; + padding-left: 1.2rem; + font-family: var(--bust-editor-mono); + font-size: 0.85rem; +} + +.bust-editor-problems { + color: var(--bust-editor-error); +} + +.bust-editor-warnings { + color: var(--bust-editor-warning); } +/* The registers and the fields of one on the left, the keys on the right, as + in the console editor. */ .bust-editor-body { display: grid; - grid-template-columns: minmax(12rem, 1fr) minmax(0, 2.5fr); - gap: 1rem; - min-height: 0; + grid-template-columns: minmax(0, 3fr) minmax(14rem, 1.3fr); + gap: 0.75rem; + align-items: start; } -@media (max-width: 44rem) { +@media (max-width: 52rem) { .bust-editor-body { - grid-template-columns: 1fr; + grid-template-columns: minmax(0, 1fr); } } -.bust-editor-tree { - overflow: auto; - max-height: 70vh; - padding: 0.4rem; - background: var(--bust-editor-raised); +.bust-editor-main { + display: flex; + flex-direction: column; + gap: 0.75rem; + min-width: 0; +} + +.bust-editor-pane { + display: flex; + flex-direction: column; + gap: 0.5rem; + min-width: 0; + padding: 0.6rem; border: 1px solid var(--bust-editor-border); border-radius: 6px; } -.bust-editor-tree ul { - margin: 0; - padding: 0; - list-style: none; +.bust-editor-pane:empty { + display: none; } -.bust-editor-tree ul ul { - margin-left: 0.9rem; - padding-left: 0.4rem; - border-left: 1px solid var(--bust-editor-border); +.bust-editor-pane:focus-within { + border-color: var(--bust-editor-teal); +} + +.bust-editor-pane:focus-within > h3, +.bust-editor-pane:focus-within > .bust-editor-pane-head h3 { + color: var(--bust-editor-teal); } -.bust-editor-node { +.bust-editor-pane-head { display: flex; - align-items: baseline; - gap: 0.6rem; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 0.5rem; +} + +.bust-editor-empty { + margin: 0; + color: var(--bust-editor-muted); +} + +.bust-editor-table-wrap { + max-height: 22rem; + overflow: auto; +} + +.bust-editor-registers .bust-editor-table-wrap { + max-height: 26rem; +} + +.bust-editor-table { width: 100%; - padding: 0.2rem 0.45rem; + border-collapse: collapse; + font-size: 0.875rem; +} + +.bust-editor-table th { + position: sticky; + top: 0; + padding: 0.25rem 0.5rem; + font-size: 0.75rem; + font-weight: 600; text-align: left; - background: none; - border: none; - border-radius: 4px; - cursor: pointer; + color: var(--bust-editor-muted); + background: var(--bust-editor-paper); + border-bottom: 1px solid var(--bust-editor-border); +} + +.bust-editor-table td { + padding: 0.25rem 0.5rem; + white-space: nowrap; + border-bottom: 1px solid color-mix(in srgb, var(--bust-editor-border) 50%, transparent); +} + +.bust-editor-table td:not(.bust-editor-name, :last-child, :nth-last-child(2)) { + font-family: var(--bust-editor-mono); + font-size: 0.8rem; +} + +.bust-editor-table td:nth-last-child(2) { + max-width: 16rem; + overflow: hidden; + text-overflow: ellipsis; + color: var(--bust-editor-muted); } -.bust-editor-node:hover { +.bust-editor-table .bust-editor-name { + font-weight: 600; +} + +.bust-editor-table tbody tr { + cursor: default; +} + +.bust-editor-table tbody tr:hover { background: var(--bust-editor-hover); } -.bust-editor-node[aria-current="true"], -.bust-editor-node[aria-current="true"]:hover { +.bust-editor-table tbody tr[aria-selected="true"] { + background: color-mix(in srgb, var(--bust-editor-teal) 16%, transparent); + box-shadow: inset 3px 0 0 var(--bust-editor-teal); +} + +.bust-editor-table tbody tr:focus-visible { + outline-offset: -2px; +} + +.bust-editor-actions { + width: 1px; + text-align: right; +} + +.bust-editor .bust-editor-more { + padding: 0 0.45rem; + line-height: 1.3; + background: none; + border-color: transparent; +} + +.bust-editor tr:hover .bust-editor-more, +.bust-editor tr[aria-selected="true"] .bust-editor-more { + border-color: var(--bust-editor-border); +} + +.bust-editor-hidden { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); +} + +/* One column per bit, the highest on the left, as in bust's documentation. */ +.bust-editor-diagram { + display: grid; + grid-template-columns: repeat(var(--bust-editor-bit-count), minmax(0, 1fr)); + overflow-x: auto; + font-family: var(--bust-editor-mono); + font-size: 0.7rem; +} + +.bust-editor-diagram-segment { + display: grid; + grid-template-rows: auto 2.4rem auto; + min-width: 0; + text-align: center; +} + +.bust-editor-diagram-bits { + display: flex; + justify-content: space-between; + padding: 0 0.15rem; + color: var(--bust-editor-muted); +} + +.bust-editor-diagram-bits:has(span:only-child) { + justify-content: center; +} + +.bust-editor .bust-editor-diagram-box { + display: flex; + align-items: center; + justify-content: center; + min-width: 0; + margin: 0; + padding: 0 0.15rem; + overflow: hidden; + font-family: var(--bust-editor-mono); + font-size: 0.75rem; + background: var(--bust-editor-paper); + border: 1px solid var(--bust-editor-ink); + border-left-width: 0; + border-radius: 0; +} + +.bust-editor-diagram-segment:first-child .bust-editor-diagram-box { + border-left-width: 1px; +} + +.bust-editor-diagram-box span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.bust-editor .bust-editor-diagram-box[aria-current="true"] { color: var(--bust-editor-on-teal); background: var(--bust-editor-teal); } -.bust-editor-node[aria-current="true"] .bust-editor-meta { - color: inherit; - opacity: 0.85; +.bust-editor-unused .bust-editor-diagram-box { + background: repeating-linear-gradient( + -45deg, + transparent 0 4px, + color-mix(in srgb, var(--bust-editor-muted) 25%, transparent) 4px 5px + ); +} + +.bust-editor-diagram-reset { + overflow: hidden; + text-overflow: ellipsis; + color: var(--bust-editor-muted); +} + +.bust-editor-key-list { + margin: 0; +} + +.bust-editor-key-list div { + display: grid; + grid-template-columns: 9.5rem minmax(0, 1fr); + gap: 0.5rem; + align-items: baseline; + border-bottom: 1px solid color-mix(in srgb, var(--bust-editor-border) 50%, transparent); +} + +.bust-editor-key-list dt { + margin: 0; +} + +.bust-editor-key-list dt button { + width: 100%; + padding: 0.2rem 0; + text-align: left; + background: none; + border: none; } -.bust-editor-meta { - flex: none; - min-width: 3.2rem; +.bust-editor-key-list dt button:hover:not(:disabled) { + color: var(--bust-editor-teal); + background: none; + text-decoration: underline; +} + +.bust-editor-key-list dd { + margin: 0; + overflow-wrap: anywhere; font-family: var(--bust-editor-mono); font-size: 0.8rem; +} + +.bust-editor-unset { color: var(--bust-editor-muted); } -.bust-editor-name { - overflow-wrap: anywhere; +/* The pop-up menu of a register or field. */ +.bust-editor-menu { + position: absolute; + z-index: 20; + min-width: 15rem; + margin: 0; + padding: 0.3rem; + list-style: none; + background: var(--bust-editor-paper); + border: 1px solid var(--bust-editor-border); + border-top: 3px solid var(--bust-editor-teal); + border-radius: 6px; + box-shadow: 0 8px 24px rgb(0 0 0 / 0.18); } -.bust-editor-module .bust-editor-name { - font-weight: 600; +.bust-editor-menu-title { + padding: 0.2rem 0.6rem 0.35rem; + font-family: var(--bust-editor-mono); + font-size: 0.75rem; + color: var(--bust-editor-muted); +} + +.bust-editor-menu-separator { + height: 1px; + margin: 0.25rem 0; + background: var(--bust-editor-border); +} + +.bust-editor .bust-editor-menu button { + display: flex; + justify-content: space-between; + gap: 1.5rem; + width: 100%; + padding: 0.3rem 0.6rem; + text-align: left; + background: none; + border: none; +} + +.bust-editor .bust-editor-menu button:hover:not(:disabled), +.bust-editor .bust-editor-menu button:focus { + color: var(--bust-editor-on-teal); + background: var(--bust-editor-teal); + outline: none; +} + +.bust-editor-menu kbd { + color: inherit; + opacity: 0.7; } -.bust-editor-node.bust-editor-invalid .bust-editor-name::after { - content: " \25CF"; +.bust-editor .bust-editor-danger { color: var(--bust-editor-error); } -.bust-editor-detail { - min-width: 0; +/* The dialogs that add and change registers, fields and the module. */ +.bust-editor-dialog { + width: min(40rem, calc(100vw - 2rem)); + max-height: calc(100vh - 2rem); + padding: 0; + color: var(--bust-editor-ink); + background: var(--bust-editor-paper); + border: 1px solid var(--bust-editor-border); + border-top: 4px solid var(--bust-editor-teal); + border-radius: 8px; } -.bust-editor-heading { - display: flex; - flex-wrap: wrap; - align-items: baseline; - gap: 0 1rem; - margin-bottom: 0.5rem; - border-bottom: 2px solid var(--bust-editor-teal); +.bust-editor-dialog::backdrop { + background: rgb(0 0 0 / 0.4); } -.bust-editor-heading h3 { - margin: 0 0 0.25rem; +.bust-editor-dialog form { + padding: 1rem 1.25rem; +} + +.bust-editor-dialog h2 { + margin: 0 0 0.75rem; font-size: 1.15rem; } -.bust-editor-heading p { - margin: 0; - font-family: var(--bust-editor-mono); - font-size: 0.85rem; - color: var(--bust-editor-muted); +.bust-editor-dialog h3 { + margin-top: 0.75rem; +} + +.bust-editor-dialog-problems ul { + margin: 0 0 0.5rem; + padding: 0.5rem 0.75rem 0.5rem 1.75rem; + color: var(--bust-editor-error); + border-left: 3px solid var(--bust-editor-error); +} + +.bust-editor-dialog-buttons { + position: sticky; + bottom: -1rem; + display: flex; + gap: 0.5rem; + justify-content: flex-end; + padding: 0.75rem 0 0; + background: var(--bust-editor-paper); +} + +.bust-editor .bust-editor-primary, +.bust-editor-dialog .bust-editor-primary { + font-weight: 600; + color: var(--bust-editor-on-teal); + background: var(--bust-editor-teal); + border-color: var(--bust-editor-teal); +} + +.bust-editor-dialog .bust-editor-primary:hover:not(:disabled) { + background: var(--bust-editor-teal); + filter: brightness(1.08); } .bust-editor-row { display: grid; - grid-template-columns: 8.5rem minmax(0, 1fr); + grid-template-columns: 9rem minmax(0, 1fr); align-items: center; gap: 0.15rem 0.75rem; - padding: 0.4rem 0; + padding: 0.35rem 0; } .bust-editor-row > label, @@ -211,7 +561,7 @@ } .bust-editor-check { - grid-template-columns: 8.5rem auto 1fr; + grid-template-columns: 9rem auto 1fr; } .bust-editor-check input { @@ -237,29 +587,29 @@ .bust-editor-row input[type="text"], .bust-editor-row select, -.bust-editor-row textarea { +.bust-editor-row textarea, +.bust-editor-enums input { box-sizing: border-box; width: 100%; - max-width: 28rem; padding: 0.3rem 0.45rem; - background: var(--bust-editor-paper); + background: var(--bust-editor-raised); border: 1px solid var(--bust-editor-border); border-radius: 4px; } -.bust-editor-row input[type="text"] { +.bust-editor-row input[type="text"], +.bust-editor-enums input { font-family: var(--bust-editor-mono); font-size: 0.9rem; } .bust-editor-row textarea { - max-width: none; resize: vertical; } .bust-editor-help { margin: 0; - font-size: 0.8rem; + font-size: 0.78rem; color: var(--bust-editor-muted); } @@ -274,91 +624,19 @@ color: var(--bust-editor-error); } -.bust-editor-form details { +.bust-editor-dialog details { margin: 0.5rem 0; padding: 0.25rem 0.75rem; border: 1px solid var(--bust-editor-border); border-radius: 6px; } -.bust-editor-form summary { +.bust-editor-dialog summary { padding: 0.25rem 0; - cursor: pointer; color: var(--bust-editor-teal); -} - -.bust-editor-messages:empty { - display: none; -} - -.bust-editor-messages { - margin-bottom: 0.5rem; -} - -.bust-editor-rejected { - margin: 0; - font-weight: 600; - color: var(--bust-editor-error); -} - -.bust-editor-problems, -.bust-editor-warnings { - margin: 0.25rem 0; - padding-left: 1.2rem; - font-family: var(--bust-editor-mono); - font-size: 0.85rem; -} - -.bust-editor-problems { - color: var(--bust-editor-error); -} - -.bust-editor-warnings { - color: var(--bust-editor-warning); -} - -/* One column per bit, the highest on the left, as in bust's documentation. */ -.bust-editor-bits { - display: grid; - grid-template-columns: repeat(var(--bust-editor-bit-count), minmax(0, 1fr)); - gap: 2px; - padding: 2px; - background: var(--bust-editor-raised); - border: 1px solid var(--bust-editor-border); - border-radius: 4px; -} - -.bust-editor-bits button { - grid-row: 1; - min-height: 2.6rem; - display: flex; - flex-direction: column; - align-items: center; - min-width: 0; - padding: 0.2rem 0.1rem; - overflow: hidden; - color: var(--bust-editor-on-teal); - background: var(--bust-editor-teal); - border: none; - border-radius: 3px; cursor: pointer; } -.bust-editor-bits span, -.bust-editor-bits small { - max-width: 100%; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - font-size: 0.75rem; -} - -.bust-editor-bits small { - font-family: var(--bust-editor-mono); - font-size: 0.7rem; - opacity: 0.85; -} - .bust-editor-enums { border-collapse: collapse; } @@ -373,16 +651,6 @@ padding: 0.15rem 0.5rem 0.15rem 0; } -.bust-editor-enums input { - box-sizing: border-box; - width: 100%; - padding: 0.25rem 0.4rem; - font-family: var(--bust-editor-mono); - background: var(--bust-editor-paper); - border: 1px solid var(--bust-editor-border); - border-radius: 4px; -} - .bust-editor-row > button { justify-self: start; } From 862fa43e85d6d0a089c91b68e26cfe9511b8332c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ola=20Gr=C3=B8ttvik?= Date: Fri, 30 Oct 2026 09:38:19 +0000 Subject: [PATCH 5/6] Select a row on double-click in bust-editor and describe the new layout --- editor-ui/README.md | 2 +- editor-ui/src/editor.ts | 13 ++- editor-ui/src/style.css | 9 +- editor-ui/tests/editor.test.mjs | 156 ++++++++++++++++++-------------- 4 files changed, 104 insertions(+), 76 deletions(-) diff --git a/editor-ui/README.md b/editor-ui/README.md index 5e22595..ba0e470 100644 --- a/editor-ui/README.md +++ b/editor-ui/README.md @@ -1,6 +1,6 @@ # bust-editor -The register map editor of [bust](https://github.com/logvik-org/bust), for the web. It shows a register map as a tree of the bus, the module, its registers and their fields, with a form for the one selected, built from bust's JSON Schema. [cloudbust](https://cloudbust.netlify.app) runs it with bust in the browser. +The register map editor of [bust](https://github.com/logvik-org/bust), for the web. Like bust's console editor, it shows the registers in a table, the fields and bits of the selected register below, and the keys of the one in focus beside them. Right-click or Shift+F10 on a register or field opens a menu of what to do with it, and changes go through dialogs built from bust's JSON Schema. [cloudbust](https://cloudbust.netlify.app) runs it with bust in the browser. The editor never changes a register map itself. Every change goes to bust as JSON Patch operations, and bust either makes it or rejects it with its problems, which the editor shows next to the values they are about. So the editor only ever holds register maps bust accepts. diff --git a/editor-ui/src/editor.ts b/editor-ui/src/editor.ts index d56487a..9eb8bfa 100644 --- a/editor-ui/src/editor.ts +++ b/editor-ui/src/editor.ts @@ -14,7 +14,7 @@ import type { Problem, ValuePath, } from "./protocol.js"; -import { definitionOf, labelOf, placeholderOf, type NodeKind } from "./schema.js"; +import { ADVANCED_KEYS, definitionOf, labelOf, placeholderOf, type NodeKind } from "./schema.js"; export type EditorOptions = { // Called with every register map bust accepts, after each change. @@ -273,7 +273,7 @@ export class RegisterMapEditor { const heading = element( "div", { class: "bust-editor-pane-head" }, - element("h3", {}, `Fields of ${String(register.name)}`), + element("h3", {}, `${register.type === "fields" ? "Fields" : "Bits"} of ${String(register.name)}`), this.button("Add field", () => this.addField(this.fields.length), { shortcut: SHORTCUTS.addField }), ); const children: Node[] = [heading]; @@ -344,7 +344,10 @@ export class RegisterMapEditor { row.setAttribute("aria-selected", "true"); } row.addEventListener("click", select); - row.addEventListener("dblclick", edit); + row.addEventListener("dblclick", () => { + select(); + edit(); + }); row.addEventListener("contextmenu", (event) => { event.preventDefault(); select(); @@ -366,7 +369,9 @@ export class RegisterMapEditor { const owner = kind === "field" ? `Field ${String(object.name)} of ${String(this.register!.name)}` : `Register ${String(object.name)}`; const list = element("dl", { class: "bust-editor-key-list" }); for (const [key, property] of Object.entries(definition.properties ?? {})) { - if (["fields", "$schema"].includes(key)) { + // The rarely used access keys show only when set, as the dialog keeps + // them under "More access options". + if (["fields", "$schema"].includes(key) || (ADVANCED_KEYS.has(key) && object[key] === undefined)) { continue; } const value = this.shownValue(kind, object, key, property); diff --git a/editor-ui/src/style.css b/editor-ui/src/style.css index abc33ea..55ed66b 100644 --- a/editor-ui/src/style.css +++ b/editor-ui/src/style.css @@ -18,6 +18,7 @@ flex-direction: column; gap: 0.75rem; min-height: 0; + container-type: inline-size; color: var(--bust-editor-ink); font-size: 0.95rem; } @@ -172,7 +173,7 @@ align-items: start; } -@media (max-width: 52rem) { +@container (max-width: 52rem) { .bust-editor-body { grid-template-columns: minmax(0, 1fr); } @@ -259,6 +260,12 @@ font-size: 0.8rem; } +@container (max-width: 46rem) { + .bust-editor-table :is(td, th):nth-last-child(2) { + display: none; + } +} + .bust-editor-table td:nth-last-child(2) { max-width: 16rem; overflow: hidden; diff --git a/editor-ui/tests/editor.test.mjs b/editor-ui/tests/editor.test.mjs index 0f94dde..db1a348 100644 --- a/editor-ui/tests/editor.test.mjs +++ b/editor-ui/tests/editor.test.mjs @@ -9,7 +9,7 @@ import { Window } from "happy-dom"; import { BustBridge, RegisterMapEditor } from "../dist/index.js"; const window = new Window(); -for (const name of ["document", "Node", "HTMLElement", "HTMLInputElement", "Event", "KeyboardEvent"]) { +for (const name of ["document", "Node", "HTMLElement", "HTMLInputElement", "HTMLButtonElement", "Event", "KeyboardEvent"]) { globalThis[name] = window[name]; } @@ -38,23 +38,35 @@ function button(container, name) { return [...container.querySelectorAll("button")].find((candidate) => candidate.textContent === name); } -function treeNode(container, name) { - return [...container.querySelectorAll(".bust-editor-node")].find( - (node) => node.querySelector(".bust-editor-name").textContent === name, +function row(container, pane, name) { + return [...container.querySelectorAll(`.bust-editor-${pane} tbody tr`)].find( + (candidate) => candidate.querySelector(".bust-editor-name").textContent === name, ); } -function treeNames(container) { - return [...container.querySelectorAll(".bust-editor-node .bust-editor-name")].map((name) => name.textContent); +function names(container, pane) { + return [...container.querySelectorAll(`.bust-editor-${pane} tbody .bust-editor-name`)].map((cell) => cell.textContent); } -function change(input, value) { - if (input.type === "checkbox") { - input.checked = value; - } else { - input.value = value; - } - input.dispatchEvent(new Event("change")); +function dialog(container) { + return container.querySelector("dialog.bust-editor-dialog"); +} + +function input(container, key) { + return dialog(container).querySelector(`[data-key='${key}'] :is(input, select, textarea)`); +} + +async function submit(container, editor) { + dialog(container).querySelector("form").dispatchEvent(new Event("submit", { cancelable: true })); + await new Promise((resolve) => setTimeout(resolve, 0)); + await editor.idle(); + await new Promise((resolve) => setTimeout(resolve, 0)); +} + +function menuItem(container, label) { + return [...container.querySelectorAll(".bust-editor-menu [role='menuitem']")].find( + (item) => item.firstChild.textContent === label, + ); } describe("RegisterMapEditor", () => { @@ -79,78 +91,70 @@ describe("RegisterMapEditor", () => { }); test("lists the registers with the addresses bust gives them", () => { - const names = treeNames(container); - assert.deepEqual(names.slice(0, 4), ["Bus", "example_axi", "reg0", "reg1"]); - assert.equal(treeNode(container, "reg1").querySelector(".bust-editor-meta").textContent, "0x00000004"); - assert.ok(names.includes("field3")); + assert.deepEqual(names(container, "registers").slice(0, 3), ["reg0", "reg1", "reg2"]); + assert.equal(row(container, "registers", "reg1").firstChild.textContent, "0x00000004"); + assert.equal(row(container, "registers", "reg7").children[4].textContent, "RW/R"); }); - test("a change in the form goes to bust and comes back as text", async () => { - treeNode(container, "reg1").click(); - await editor.idle(); - const sw = container.querySelector("[data-key='sw'] select"); - change(sw, "ro"); - await editor.idle(); + test("a change in a dialog goes to bust and comes back as text", async () => { + row(container, "registers", "reg1").dispatchEvent(new Event("dblclick")); + assert.equal(dialog(container).querySelector("h2").textContent, "Register reg1"); + input(container, "sw").value = "ro"; + await submit(container, editor); + assert.equal(dialog(container).open, false); assert.equal(editor.state.data.module.register[1].sw, "ro"); assert.match(changes.at(-1).text, /"sw": "ro"/); assert.equal(button(container, "Undo").disabled, false); }); - test("a change bust rejects stays in the form with bust's problem", async () => { - treeNode(container, "reg1").click(); - const name = container.querySelector("[data-key='name'] input"); - change(name, "reg0"); - await editor.idle(); + test("a change bust rejects keeps the dialog open with bust's problem", async () => { + row(container, "registers", "reg1").dispatchEvent(new Event("dblclick")); + input(container, "name").value = "reg0"; + await submit(container, editor); + assert.equal(dialog(container).open, true); assert.equal(editor.state.data.module.register[1].name, "reg1"); - assert.equal(name.value, "reg0"); - assert.ok(container.querySelector(".bust-editor-rejected")); - // bust names no place for this problem, so it shows at the edited value. - assert.ok(container.querySelector("[data-key='name']").classList.contains("bust-editor-invalid")); + assert.match(dialog(container).querySelector(".bust-editor-dialog-problems").textContent, /reg0/); }); - test("problems with a path show next to their input", async () => { - treeNode(container, "reg1").click(); - const address = container.querySelector("[data-key='address'] input"); - change(address, "zz"); - await editor.idle(); - const row = container.querySelector("[data-key='address']"); - assert.ok(row.classList.contains("bust-editor-invalid")); - assert.ok(row.querySelector(".bust-editor-problem").textContent.length > 0); + test("problems with a path show next to their value", async () => { + row(container, "registers", "reg1").dispatchEvent(new Event("dblclick")); + input(container, "address").value = "zz"; + await submit(container, editor); + const address = dialog(container).querySelector("[data-key='address']"); + assert.ok(address.classList.contains("bust-editor-invalid")); + assert.ok(address.querySelector(".bust-editor-problem").textContent.length > 0); }); - test("adding a register puts it after the selected one", async () => { - treeNode(container, "reg1").click(); - await editor.idle(); + test("adding a register from the toolbar puts it last and selects it", async () => { button(container, "Add register").click(); - await editor.idle(); - const names = editor.state.data.module.register.map((register) => register.name); - assert.deepEqual(names.slice(0, 3), ["reg0", "reg1", "reg12"]); - assert.equal(container.querySelector("[aria-current='true'] .bust-editor-name").textContent, "reg12"); + assert.equal(input(container, "name").value, "reg12"); + await submit(container, editor); + assert.equal(names(container, "registers").at(-1), "reg12"); + assert.equal(container.querySelector(".bust-editor-registers tr[aria-selected='true'] .bust-editor-name").textContent, "reg12"); }); - test("adding a field turns a register into a fields register", async () => { - treeNode(container, "reg0").click(); - await editor.idle(); + test("the first field turns a register into a fields register", async () => { + row(container, "registers", "reg0").click(); button(container, "Add field").click(); - await editor.idle(); + input(container, "name").value = "enable"; + await submit(container, editor); const register = editor.state.data.module.register[0]; assert.equal(register.type, "fields"); - assert.deepEqual(register.fields, [{ name: "field0", type: "bit" }]); - assert.equal(container.querySelector("[aria-current='true'] .bust-editor-name").textContent, "field0"); + assert.deepEqual(register.fields, [{ name: "enable", type: "bit" }]); + assert.ok(!("reset" in register)); + assert.equal(container.querySelector(".bust-editor-detail tr[aria-selected='true'] .bust-editor-name").textContent, "enable"); }); - test("moving and removing a register, then undoing", async () => { - treeNode(container, "reg1").click(); - await editor.idle(); - button(container, "Move up").click(); + test("a register's pop-up menu moves and removes it, and undo brings it back", async () => { + row(container, "registers", "reg1").dispatchEvent(new window.MouseEvent("contextmenu", { clientX: 10, clientY: 10, cancelable: true })); + assert.equal(container.querySelector(".bust-editor-menu").hidden, false); + menuItem(container, "Move up").click(); await editor.idle(); - assert.deepEqual( - editor.state.data.module.register.slice(0, 2).map((register) => register.name), - ["reg1", "reg0"], - ); - button(container, "Remove").click(); + assert.deepEqual(names(container, "registers").slice(0, 2), ["reg1", "reg0"]); + row(container, "registers", "reg1").querySelector(".bust-editor-more").click(); + menuItem(container, "Remove register").click(); await editor.idle(); - assert.equal(editor.state.data.module.register[0].name, "reg0"); + assert.equal(names(container, "registers")[0], "reg0"); button(container, "Undo").click(); await editor.idle(); button(container, "Undo").click(); @@ -158,14 +162,26 @@ describe("RegisterMapEditor", () => { assert.equal(editor.state.text, example); }); - test("the register's fields show by bit", async () => { - treeNode(container, "reg7").click(); - await editor.idle(); - const cells = [...container.querySelectorAll(".bust-editor-bits button")]; + test("a field's menu edits its named values", async () => { + row(container, "registers", "reg7").click(); + row(container, "detail", "field1").dispatchEvent(new window.MouseEvent("contextmenu", { clientX: 10, clientY: 10, cancelable: true })); + menuItem(container, "Named values…").click(); + button(dialog(container), "Add value").click(); + // bust wants field1's reset, 0xB, to be one of the named values. + dialog(container).querySelector('[aria-label="Value 1"]').value = "11"; + await submit(container, editor); + assert.deepEqual(editor.state.data.module.register[7].fields[1].enums, [{ name: "VALUE0", value: 11 }]); + }); + + test("the register's fields show by bit, as in the documentation", () => { + row(container, "registers", "reg7").click(); + const boxes = [...container.querySelectorAll(".bust-editor-diagram-segment")]; assert.deepEqual( - cells.map((cell) => cell.title), - ["field0 [0]", "field1 [4:1]", "field2 [5]", "field3 [20:6]"], + boxes.map((box) => box.querySelector(".bust-editor-diagram-box").textContent), + ["", "field3", "field2", "field1", "field0"], ); - assert.equal(cells[1].style.gridColumn, "28 / 32"); + assert.equal(boxes[3].style.gridColumn, "28 / 32"); + boxes[3].querySelector("button").click(); + assert.equal(container.querySelector(".bust-editor-keys h3").textContent, "Field field1 of reg7"); }); }); From 2f5006966db2d7c35a8490921d017abe47735151 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ola=20Gr=C3=B8ttvik?= Date: Fri, 30 Oct 2026 14:23:10 +0000 Subject: [PATCH 6/6] Link bust-editor README to cloudbust.org --- editor-ui/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/editor-ui/README.md b/editor-ui/README.md index ba0e470..b70a0c9 100644 --- a/editor-ui/README.md +++ b/editor-ui/README.md @@ -1,6 +1,6 @@ # bust-editor -The register map editor of [bust](https://github.com/logvik-org/bust), for the web. Like bust's console editor, it shows the registers in a table, the fields and bits of the selected register below, and the keys of the one in focus beside them. Right-click or Shift+F10 on a register or field opens a menu of what to do with it, and changes go through dialogs built from bust's JSON Schema. [cloudbust](https://cloudbust.netlify.app) runs it with bust in the browser. +The register map editor of [bust](https://github.com/logvik-org/bust), for the web. Like bust's console editor, it shows the registers in a table, the fields and bits of the selected register below, and the keys of the one in focus beside them. Right-click or Shift+F10 on a register or field opens a menu of what to do with it, and changes go through dialogs built from bust's JSON Schema. [cloudbust](https://cloudbust.org) runs it with bust in the browser. The editor never changes a register map itself. Every change goes to bust as JSON Patch operations, and bust either makes it or rejects it with its problems, which the editor shows next to the values they are about. So the editor only ever holds register maps bust accepts.