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..b70a0c9 --- /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. 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. + +## 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/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 new file mode 100644 index 0000000..9eb8bfa --- /dev/null +++ b/editor-ui/src/editor.ts @@ -0,0 +1,715 @@ +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, + EditorState, + JsonObject, + JsonSchema, + JsonValue, + Operation, + Problem, + ValuePath, +} from "./protocol.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. + onChange?: (state: AcceptedState) => void; +}; + +const REGISTERS: ValuePath = ["module", "register"]; + +// What the keys pane shows: the selected register, or one of its fields. +type Subject = "register" | "field"; + +const SHORTCUTS = { + edit: "Enter", + addRegister: "A", + addField: "F", + remove: "Del", + module: "M", + menu: "Shift+F10", +}; + +// 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 registerIndex = 0; + private fieldIndex = 0; + private subject: Subject = "register"; + private queue: Promise = Promise.resolve(); + private readonly toolbar = element("div", { class: "bust-editor-toolbar", role: "toolbar", "aria-label": "Register map" }); + 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, + private readonly bridge: BustBridge, + private readonly options: EditorOptions = {}, + ) { + container.classList.add("bust-editor"); + container.replaceChildren( + this.toolbar, + this.summary, + this.messages, + element( + "div", + { class: "bust-editor-body" }, + element("div", { class: "bust-editor-main" }, this.registersPane, this.detailPane), + this.keysPane, + ), + ); + this.menu = new PopupMenu(container); + this.dialog = new FormDialog(container); + 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(() => this.bridge.call("open", { text }), () => this.reset()); + } + + create(bus: JsonObject, module: JsonObject): Promise { + return this.run(() => this.bridge.call("new", { bus, module }), () => this.reset()); + } + + apply(operations: Operation[], onAccepted?: () => void): Promise { + return this.run(() => this.bridge.call("apply", { operations }), onAccepted); + } + + undo(): Promise { + return this.run(() => this.bridge.call("undo", {})); + } + + redo(): Promise { + 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, onAccepted?: () => void): Promise { + const result = this.queue.then(async () => { + this.schema ??= await this.bridge.call("schema", {}); + const state = await request(); + 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; + } + + // 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; + } + const state = await this.apply(operations, onAccepted); + if (state.accepted) { + return undefined; + } + this.showProblems([]); + return state.problems; + } + + // 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.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!; + this.toolbar.replaceChildren( + element( + "div", + { class: "bust-editor-group" }, + 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" }, + 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 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))); + } + } + + 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 renderDetail(): void { + const register = this.register; + if (!register) { + this.detailPane.replaceChildren(); + return; + } + const placed = this.accepted!.layout[String(register.name)]; + const heading = element( + "div", + { class: "bust-editor-pane-head" }, + 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]; + 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 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"); + } + row.addEventListener("click", select); + row.addEventListener("dblclick", () => { + select(); + edit(); + }); + row.addEventListener("contextmenu", (event) => { + event.preventDefault(); + select(); + openMenu(event.clientX, event.clientY); + }); + return row; + } + + // 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 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 ?? {})) { + // 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); + 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)); + } + 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 (value !== undefined && value !== null) { + return { text: String(value), isSet: true }; + } + 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 showProblems(problems: Problem[]): void { + if (problems.length === 0) { + this.messages.replaceChildren(...this.warningItems()); + return; + } + 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}`)))]; + } + + // 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 (this.accepted) { + this.render(); + this.focusSelectedRow(this.registersPane); + } + } + + private selectField(index: number): void { + if (index < 0) { + return; + } + this.fieldIndex = index; + this.subject = "field"; + this.render(); + this.focusSelectedRow(this.detailPane); + } + + 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; + } + 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); + } + } + + // 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 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"))), + }); + } + + 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; + } + 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)), + }); + } + + // 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)), + }); + } + + // 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 setRegisterType(register, registerPath, "fields").map((operation) => + operation.op === "add" && operation.path.endsWith("/fields") ? { ...operation, value: [field] } : operation, + ); + } + + 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 select = () => (kind === "register" ? this.selectRegister(index + 1) : this.selectField(index + 1)); + return this.apply(insertAt(listPath, index + 1, copy), select); + } + + 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(): 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 (!this.accepted || this.dialog.isOpen || this.menu.isOpen || target.matches("input, textarea, select")) { + return; + } + 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 new file mode 100644 index 0000000..b5fd3f8 --- /dev/null +++ b/editor-ui/src/index.ts @@ -0,0 +1,17 @@ +export { RegisterMapEditor, type EditorOptions } from "./editor.js"; +export { + BustBridge, + pointer, + type AcceptedState, + type EditorState, + type JsonObject, + type JsonValue, + type Operation, + type Problem, + type BitSegment, + type FieldLayout, + type RegisterLayout, + type RejectedState, + type Transport, + type ValuePath, +} from "./protocol.js"; 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 new file mode 100644 index 0000000..d8ea9e0 --- /dev/null +++ b/editor-ui/src/operations.ts @@ -0,0 +1,117 @@ +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}`; + } + } +} + +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 new file mode 100644 index 0000000..01bccbc --- /dev/null +++ b/editor-ui/src/protocol.ts @@ -0,0 +1,126 @@ +// 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; +}; + +// 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; + type: string; + access: string; + reset: string; + segments: BitSegment[]; + 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..55ed66b --- /dev/null +++ b/editor-ui/src/style.css @@ -0,0 +1,663 @@ +/* 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); + + position: relative; + display: flex; + flex-direction: column; + gap: 0.75rem; + min-height: 0; + container-type: inline-size; + color: var(--bust-editor-ink); + 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 [hidden] { + display: none !important; +} + +.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 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; +} + +.bust-editor-group { + display: flex; + gap: 0.25rem; +} + +.bust-editor-hint { + margin: 0 0 0 auto; + font-size: 0.8rem; + color: var(--bust-editor-muted); +} + +.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-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(0, 3fr) minmax(14rem, 1.3fr); + gap: 0.75rem; + align-items: start; +} + +@container (max-width: 52rem) { + .bust-editor-body { + grid-template-columns: minmax(0, 1fr); + } +} + +.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-pane:empty { + display: none; +} + +.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-pane-head { + display: flex; + 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%; + 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; + 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; +} + +@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; + text-overflow: ellipsis; + color: var(--bust-editor-muted); +} + +.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-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-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-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); +} + +/* 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-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 .bust-editor-danger { + color: var(--bust-editor-error); +} + +/* 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-dialog::backdrop { + background: rgb(0 0 0 / 0.4); +} + +.bust-editor-dialog form { + padding: 1rem 1.25rem; +} + +.bust-editor-dialog h2 { + margin: 0 0 0.75rem; + font-size: 1.15rem; +} + +.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: 9rem minmax(0, 1fr); + align-items: center; + gap: 0.15rem 0.75rem; + padding: 0.35rem 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-wide > * { + grid-column: 1 / -1 !important; +} + +.bust-editor-check { + grid-template-columns: 9rem 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, +.bust-editor-enums input { + box-sizing: border-box; + width: 100%; + padding: 0.3rem 0.45rem; + background: var(--bust-editor-raised); + border: 1px solid var(--bust-editor-border); + border-radius: 4px; +} + +.bust-editor-row input[type="text"], +.bust-editor-enums input { + font-family: var(--bust-editor-mono); + font-size: 0.9rem; +} + +.bust-editor-row textarea { + resize: vertical; +} + +.bust-editor-help { + margin: 0; + font-size: 0.78rem; + 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-dialog details { + margin: 0.5rem 0; + padding: 0.25rem 0.75rem; + border: 1px solid var(--bust-editor-border); + border-radius: 6px; +} + +.bust-editor-dialog summary { + padding: 0.25rem 0; + color: var(--bust-editor-teal); + cursor: pointer; +} + +.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-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..db1a348 --- /dev/null +++ b/editor-ui/tests/editor.test.mjs @@ -0,0 +1,187 @@ +// 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", "HTMLButtonElement", "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 row(container, pane, name) { + return [...container.querySelectorAll(`.bust-editor-${pane} tbody tr`)].find( + (candidate) => candidate.querySelector(".bust-editor-name").textContent === name, + ); +} + +function names(container, pane) { + return [...container.querySelectorAll(`.bust-editor-${pane} tbody .bust-editor-name`)].map((cell) => cell.textContent); +} + +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", () => { + 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", () => { + 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 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 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.match(dialog(container).querySelector(".bust-editor-dialog-problems").textContent, /reg0/); + }); + + 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 from the toolbar puts it last and selects it", async () => { + button(container, "Add register").click(); + 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("the first field turns a register into a fields register", async () => { + row(container, "registers", "reg0").click(); + button(container, "Add field").click(); + 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: "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("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(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(names(container, "registers")[0], "reg0"); + button(container, "Undo").click(); + await editor.idle(); + button(container, "Undo").click(); + await editor.idle(); + assert.equal(editor.state.text, example); + }); + + 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( + boxes.map((box) => box.querySelector(".bust-editor-diagram-box").textContent), + ["", "field3", "field2", "field1", "field0"], + ); + 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"); + }); +}); 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"] +}