Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) đź§ 

feat: add offline workflow editor

Emre Sokullu309340c181d8
diff --git a/test/workflow-editor.mjs b/test/workflow-editor.mjs
new file mode 100644
index 000000000..0d5c21141
--- /dev/null
+++ b/test/workflow-editor.mjs
@@ -0,0 +1,207 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { chromium, firefox } from 'playwright';
+import { fileURLToPath } from 'node:url';
+import { importPortableWorkflowDefinition as importChromeWorkflow } from '../src/chrome/src/agent/workflows.js';
+import { importPortableWorkflowDefinition as importFirefoxWorkflow } from '../src/firefox/src/agent/workflows.js';
+
+const pageURL = new URL('../web/workflow-editor/index.html', import.meta.url).href;
+const scriptPath = fileURLToPath(new URL('../web/workflow-editor/workflow-editor.js', import.meta.url));
+const fixture = {
+ schema: 'webbrain-workflow/1', name: 'Example workflow', id: 'workflow_1',
+ createdAt: 1790572374560, source: { version: '1', extra: null },
+ parameters: [{ id: 'email', label: 'Email', required: true, sensitive: false, type: 'text' }],
+ steps: [
+ { id: 'step_1', tool: 'set_field', args: { text: { $workflowParam: 'email' }, clear: true }, target: { name: 'Email' } },
+ { id: 'step_2', tool: 'click_ax', args: {}, target: { name: 'Save' } }
+ ],
+ extra: JSON.parse('{"__proto__":{"safe":true},"nested":[null,false,12.5,"<img src=x onerror=alert(1)>"]}')
+};
+const val = (page, path) => page.getByRole('textbox', { name: `Value ${JSON.stringify(path)}`, exact: true });
+async function edit(locator, value) { await locator.fill(value); await locator.dispatchEvent('change'); }
+
+for (const [name, browserType] of Object.entries({ chromium, firefox })) {
+ async function withEditor(run) {
+ const browser = await browserType.launch();
+ try {
+ const page = await browser.newPage({ offline: true });
+ const errors = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await page.goto(pageURL);
+ await page.getByRole('button', { name: 'Start a new workflow' }).waitFor();
+ await run(page);
+ assert.deepEqual(errors, []);
+ } finally { await browser.close(); }
+ }
+
+ test(`${name}: marking a save complete preserves active edits and focus`, () => withEditor(async page => {
+ await page.evaluate(value => editor.load(value), fixture);
+ const nameInput = val(page, ['name']);
+ await nameInput.fill('Typing while an earlier save finishes');
+ const before = await nameInput.evaluate(input => ({ start: input.selectionStart, end: input.selectionEnd }));
+ await page.evaluate(() => editor.markSaved());
+ assert.equal(await nameInput.inputValue(), 'Typing while an earlier save finishes');
+ assert.equal(await nameInput.evaluate(input => input.getRootNode().activeElement === input), true);
+ assert.deepEqual(await nameInput.evaluate(input => ({ start: input.selectionStart, end: input.selectionEnd })), before);
+ assert.equal(await page.evaluate(() => editor.isDirty()), true);
+ assert.equal(await page.evaluate(() => editor.getValue().name), fixture.name);
+ await nameInput.press('Tab');
+ assert.equal(await page.evaluate(() => editor.getValue().name), 'Typing while an earlier save finishes');
+ assert.equal(await page.evaluate(() => editor.isDirty()), true);
+ await page.evaluate(() => editor.markSaved());
+ assert.equal(await page.evaluate(() => editor.isDirty()), false);
+ await page.getByRole('button', { name: 'JSON source', exact: true }).click();
+ const source = page.getByRole('textbox', { name: 'Workflow JSON source' });
+ await source.fill('{unfinished');
+ await page.evaluate(() => editor.markSaved());
+ assert.equal(await source.inputValue(), '{unfinished');
+ assert.equal(await page.evaluate(() => editor.isDirty()), true);
+ }));
+
+ test(`${name}: actions immediately after a key rename use the new path`, () => withEditor(async page => {
+ await page.evaluate(value => editor.load(value), { ...fixture, note: 'keep', settings: { child: 'remove', list: ['a', 'b'] } });
+ await page.getByLabel('Field name ["note"]', { exact: true }).fill('renamedNote');
+ await page.getByRole('button', { name: 'Remove ["note"]', exact: true }).click();
+ assert.equal(await page.evaluate(() => Object.hasOwn(editor.getValue(), 'renamedNote')), false);
+ await page.getByRole('button', { name: 'Undo', exact: true }).click();
+ assert.equal(await page.evaluate(() => editor.getValue().renamedNote), 'keep');
+ await page.getByRole('button', { name: 'Undo', exact: true }).click();
+ assert.equal(await page.evaluate(() => editor.getValue().note), 'keep');
+ await page.getByLabel('Field name ["settings"]', { exact: true }).fill('options');
+ await page.getByRole('button', { name: 'Remove ["settings","child"]', exact: true }).click();
+ assert.deepEqual(await page.evaluate(() => editor.getValue().options), { list: ['a', 'b'] });
+ await page.getByLabel('Field name ["options"]', { exact: true }).fill('config');
+ await page.getByRole('button', { name: 'Move down ["options","list",0]', exact: true }).click();
+ assert.deepEqual(await page.evaluate(() => editor.getValue().config.list), ['b', 'a']);
+ await page.getByLabel('Field name ["config"]', { exact: true }).fill('finalConfig');
+ const list = page.locator('[data-path=\'["config","list"]\']');
+ await list.getByRole('button', { name: '+ Add item', exact: true }).click();
+ assert.deepEqual(await page.evaluate(() => editor.getValue().finalConfig.list), ['b', 'a', '']);
+ }));
+
+ test(`${name}: new workflows expose a starting scope and can be imported`, () => withEditor(async page => {
+ await page.getByRole('button', { name: 'Start a new workflow' }).click();
+ assert.deepEqual(await page.evaluate(() => editor.getValue().start), { origin: '', pathFamily: '/' });
+ assert.ok((await page.evaluate(() => editor.validate())).some(issue => issue.includes('start.origin')));
+ await edit(val(page, ['start', 'origin']), 'https://example.com/path');
+ assert.ok((await page.evaluate(() => editor.validate())).some(issue => issue.includes('start.origin')));
+ await edit(val(page, ['start', 'origin']), 'https://example.com');
+ await edit(val(page, ['start', 'pathFamily']), 'missing-leading-slash');
+ assert.ok((await page.evaluate(() => editor.validate())).some(issue => issue.includes('start.pathFamily')));
+ await edit(val(page, ['start', 'pathFamily']), '/');
+ assert.deepEqual(await page.evaluate(() => editor.validate()), []);
+ await page.getByRole('button', { name: '+ Add', exact: true }).last().click();
+ assert.deepEqual(await page.evaluate(() => editor.getValue().steps[0].scope), { origin: 'https://example.com', pathFamily: '/' });
+ await edit(val(page, ['steps', 0, 'target', 'name']), 'Continue');
+ const output = JSON.parse(await page.evaluate(() => editor.toJSON()));
+ const imported = (name === 'chromium' ? importChromeWorkflow : importFirefoxWorkflow)(output);
+ assert.equal(imported.reason, '');
+ assert.equal(imported.workflow.steps.length, 1);
+ }));
+
+ test(`${name}: offline file import, editing, preservation, export, embedding`, async () => {
+ const browser = await browserType.launch();
+ try {
+ const context = await browser.newContext({ offline: true, acceptDownloads: true });
+ const page = await context.newPage();
+ const errors = [], network = [];
+ page.on('pageerror', error => errors.push(error.message));
+ page.on('request', request => { if (/^https?:/.test(request.url())) network.push(request.url()); });
+ await page.goto(pageURL);
+ await page.getByLabel('Open workflow file').setInputFiles({ name: 'example.webbrain-workflow.json', mimeType: 'application/json', buffer: Buffer.from(JSON.stringify(fixture)) });
+ await page.getByRole('heading', { name: 'Workflow details', exact: true }).waitFor();
+ assert.deepEqual(JSON.parse(await page.evaluate(() => JSON.stringify(editor.getValue()))), fixture);
+ assert.equal(await page.locator('img').count(), 0);
+ await val(page, ['name']).fill('Renamed workflow');
+ await page.getByRole('button', { name: 'Parameter 1: Email', exact: true }).click();
+ await page.getByRole('heading', { name: 'Parameter 1', exact: true }).waitFor();
+ assert.equal(await page.evaluate(() => editor.getValue().name), 'Renamed workflow');
+ await edit(val(page, ['parameters', 0, 'id']), 'address');
+ assert.equal(await page.evaluate(() => editor.getValue().steps[0].args.text.$workflowParam), 'address');
+ await page.getByRole('button', { name: 'Undo', exact: true }).click();
+ assert.equal(await page.evaluate(() => editor.getValue().steps[0].args.text.$workflowParam), 'email');
+ await page.getByRole('button', { name: 'Redo', exact: true }).click();
+ await page.getByRole('button', { name: 'Step 2: Save', exact: true }).click();
+ await page.getByRole('button', { name: 'Move up', exact: true }).click();
+ assert.deepEqual(await page.evaluate(() => editor.getValue().steps.map(s => s.id)), ['step_2', 'step_1']);
+ await page.getByRole('button', { name: 'Duplicate', exact: true }).click();
+ assert.equal(new Set(await page.evaluate(() => editor.getValue().steps.map(s => s.id))).size, 3);
+ await page.getByRole('button', { name: 'Remove', exact: true }).click();
+ // Drag reordering works as well as the keyboard-accessible move buttons.
+ await page.getByRole('button', { name: 'Step 1: Save', exact: true }).dragTo(page.getByRole('button', { name: 'Step 2: Email', exact: true }));
+ assert.deepEqual(await page.evaluate(() => editor.getValue().steps.map(s => s.id)), ['step_1', 'step_2']);
+ await page.getByRole('button', { name: 'Workflow details', exact: true }).click();
+ await page.getByLabel('New field name at []', { exact: true }).fill('newField');
+ await page.getByRole('button', { name: '+ Add field', exact: true }).last().click();
+ await edit(val(page, ['newField']), 'New value');
+ await edit(page.getByLabel('Field name ["newField"]', { exact: true }), 'renamedField');
+ assert.equal(await page.evaluate(() => editor.getValue().renamedField), 'New value');
+ await page.getByRole('button', { name: 'Remove ["renamedField"]', exact: true }).click();
+ await page.getByRole('button', { name: 'JSON source', exact: true }).click();
+ const raw = page.getByRole('textbox', { name: 'Workflow JSON source' });
+ await raw.fill('{bad json');
+ assert.equal(await page.getByRole('button', { name: 'Download JSON' }).isDisabled(), true);
+ await page.getByRole('button', { name: 'Apply JSON' }).click();
+ assert.equal(await raw.inputValue(), '{bad json');
+ assert.equal(await page.evaluate(() => editor.getValue().name), 'Renamed workflow');
+ await page.getByRole('button', { name: 'Discard JSON edits' }).click();
+ const next = JSON.parse(await page.evaluate(() => JSON.stringify(editor.getValue()))); next.extra.raw = 'preserved';
+ await raw.fill(JSON.stringify(next)); await page.getByRole('button', { name: 'Apply JSON' }).click();
+ const downloadPromise = page.waitForEvent('download');
+ await page.getByRole('button', { name: 'Download JSON' }).click();
+ const download = await downloadPromise;
+ const stream = await download.createReadStream(); const chunks = [];
+ for await (const chunk of stream) chunks.push(chunk);
+ const exported = JSON.parse(Buffer.concat(chunks).toString());
+ assert.deepEqual(exported, next);
+ assert.deepEqual(exported.extra.__proto__, { safe: true });
+ assert.equal(download.suggestedFilename(), 'example.webbrain-workflow.json');
+ assert.equal(await page.evaluate(() => editor.isDirty()), false);
+ assert.equal(await page.evaluate(() => ({}).safe), undefined);
+ // A focused field is included by the keyboard download shortcut.
+ await page.getByRole('button', { name: 'Workflow details', exact: true }).click();
+ await val(page, ['name']).fill('Keyboard save');
+ assert.equal(await page.evaluate(() => editor.isDirty()), true);
+ const keyboardDownload = page.waitForEvent('download');
+ await val(page, ['name']).press('Control+s');
+ const keyStream = await (await keyboardDownload).createReadStream(); const keyChunks = [];
+ for await (const chunk of keyStream) keyChunks.push(chunk);
+ assert.equal(JSON.parse(Buffer.concat(keyChunks).toString()).name, 'Keyboard save');
+ await page.setViewportSize({ width: 390, height: 844 });
+ await page.getByRole('button', { name: 'Workflow details', exact: true }).click();
+ assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
+ assert.deepEqual(network, []); assert.deepEqual(errors, []);
+
+ // File drop and malformed imports leave the current document intact.
+ await page.evaluate(text => {
+ const transfer = new DataTransfer(); transfer.items.add(new File([text], 'dropped.json', { type: 'application/json' }));
+ document.querySelector('#editor').shadowRoot.querySelector('.app').dispatchEvent(new DragEvent('drop', { bubbles: true, dataTransfer: transfer }));
+ }, JSON.stringify(fixture));
+ await page.getByRole('textbox', { name: 'Value ["name"]', exact: true }).filter({ visible: true }).waitFor();
+ await page.waitForFunction(() => editor.filename === 'dropped.json');
+ assert.equal(await page.evaluate(() => editor.getValue().name), fixture.name);
+ await page.getByLabel('Open workflow file').setInputFiles({ name: 'invalid.json', mimeType: 'application/json', buffer: Buffer.from('[]') });
+ await page.getByRole('status').filter({ hasText: 'Could not open file' }).waitFor();
+ assert.equal(await page.evaluate(() => editor.getValue().name), fixture.name);
+
+ // Two independent instances, public API copies, events, and teardown.
+ const embedded = await context.newPage();
+ await embedded.setContent('<div id="one"></div><div id="two"></div>');
+ await embedded.addScriptTag({ path: scriptPath });
+ const result = await embedded.evaluate(fixture => {
+ const one = WorkflowEditor.mount('#one', { value: fixture });
+ const two = WorkflowEditor.mount('#two', { value: fixture });
+ const external = one.getValue(); external.name = 'external';
+ const original = one.getValue().name;
+ let changes = 0; document.querySelector('#one').addEventListener('workflowchange', () => changes++);
+ const input = document.querySelector('#one').shadowRoot.querySelector('[aria-label=\'Value ["name"]\']');
+ input.value = 'embedded change'; input.dispatchEvent(new Event('change'));
+ const second = two.getValue().name;
+ const edited = one.getValue().name;
+ one.destroy();
+ return { original, second, edited, changes, empty: document.querySelector('#one').shadowRoot.childElementCount === 0 };
+ }, fixture);
+ assert.deepEqual(result, { original: fixture.name, second: fixture.name, edited: 'embedded change', changes: 1, empty: true });
+ } finally { await browser.close(); }
+ });
+}
diff --git a/web/vercel.json b/web/vercel.json
index 19a4a222d..485ea676b 100644
--- a/web/vercel.json
+++ b/web/vercel.json
@@ -1,5 +1,7 @@
{
"rewrites": [
+ { "source": "/workflow-editor", "destination": "/workflow-editor/index.html" },
+ { "source": "/workflow-editor/", "destination": "/workflow-editor/index.html" },
{ "source": "/privacy", "destination": "/privacy.html" },
{ "source": "/subscribe", "destination": "/subscribe/index.html" },
{ "source": "/subscribe/", "destination": "/subscribe/index.html" },
diff --git a/web/workflow-editor/README.md b/web/workflow-editor/README.md
new file mode 100644
index 000000000..f3680200e
--- /dev/null
+++ b/web/workflow-editor/README.md
@@ -0,0 +1,76 @@
+# Workflow editor
+
+Open `index.html` directly in a browser. Keep `workflow-editor.js` beside it.
+The page works from `file://` without a server or internet connection. On the
+website it is available at `/workflow-editor/`.
+
+Drop a JSON file onto the editor, use **Open JSON**, or start a new workflow.
+For a new workflow, fill in `start.origin` (for example, `https://example.com`)
+and `start.pathFamily` (for example, `/` or `/join`) before adding steps. New
+steps inherit this starting scope; adjust their scope when they run on another page.
+Select a step or parameter to edit its fields. Field names, values, and JSON
+types are editable, including nested objects and arrays. Drag steps or parameters
+to reorder them, or use the move buttons. **JSON source** supports bulk edits;
+apply or discard those edits before switching views or downloading.
+
+Renaming a unique parameter's `id` in the field editor updates matching
+`$workflowParam` references throughout the document. Raw JSON edits and field-key
+renames are literal changes. Removing a referenced parameter surfaces a warning.
+Unknown fields are retained; timestamps and recorded statistics are not silently
+rewritten. Basic checks are advisory, not a guarantee that a workflow will run.
+
+**Download JSON** exports a new file. Nothing is uploaded or automatically saved
+in browser storage. Download your work before closing the page. Undo/redo keeps
+up to 100 document changes in memory. File opening starts a new history.
+
+## Embed in another page
+
+Copy only `workflow-editor.js`. It includes the interface and all styles, isolated
+inside a shadow root so host-page styles do not affect the editor.
+
+```html
+<div id="workflow"></div>
+<script src="./workflow-editor.js"></script>
+<script>
+ const editor = WorkflowEditor.mount('#workflow', {
+ value: {
+ schema: 'webbrain-workflow/1',
+ name: 'My workflow',
+ parameters: [],
+ steps: []
+ },
+ filename: 'my-workflow.webbrain-workflow.json',
+ onChange(value, editor) {
+ // Receives an independent copy after visual edits, undo/redo, or Apply JSON.
+ console.log(value);
+ }
+ });
+</script>
+```
+
+Omit `value` for the file-drop welcome screen. Mount into an empty element without
+an existing shadow root. Multiple editors are independent. No build step, global
+CSS, framework, external fonts, network calls, or dependencies are required.
+Hosts with a strict Content Security Policy must allow the script and its embedded
+style element. The editor never executes imported workflows or renders their HTML.
+
+### Instance API
+
+| Method | Behavior |
+| --- | --- |
+| `load(objectOrJsonString, filename?)` | Replace the document, reset history, and mark it clean. Throws on invalid JSON or a non-object root. Programmatic loads do not prompt or emit change events. |
+| `getValue()` | Return an independent copy of the document, or `null` when empty. |
+| `toJSON(space = 2)` | Serialize committed data. Throws while raw JSON edits are pending. |
+| `validate()` | Return an array of basic workflow warning messages. |
+| `isDirty()` | Whether the document differs from the loaded/downloaded version or has pending raw edits. |
+| `markSaved()` | Mark committed data as saved by the host application. Pending field or raw JSON edits remain intact and dirty; focus is preserved. |
+| `download()` | Download the current JSON using the editable filename. |
+| `undo()` / `redo()` | Navigate document history. |
+| `destroy()` | Remove the interface; discard the host element before mounting again. |
+
+The mount element also dispatches a bubbling `workflowchange` event with
+`event.detail.value`. Returned values and change payloads are copies, so host
+code cannot accidentally mutate editor state. Embedding hosts own their save and
+navigation lifecycle; the standalone page adds a warning when leaving with edits.
+
+Run browser regression tests with `node --test test/workflow-editor.mjs`.
diff --git a/web/workflow-editor/index.html b/web/workflow-editor/index.html
new file mode 100644
index 000000000..fe0eabd04
--- /dev/null
+++ b/web/workflow-editor/index.html
@@ -0,0 +1,30 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="description" content="Edit workflow JSON files locally. No uploads, account, or connection required.">
+ <title>Workflow editor — WebBrain</title>
+ <style>
+ body { margin: 0; background: #f3f5f8; }
+ #editor { min-height: 100vh; }
+ </style>
+</head>
+<body>
+ <main id="editor"></main>
+ <script>
+ // Resolve both the clean hosted route and a directly opened local HTML file.
+ const base = new URL(location.href);
+ if (!base.pathname.endsWith('/') && !base.pathname.endsWith('.html')) base.pathname += '/';
+ const script = document.createElement('script');
+ script.src = new URL('workflow-editor.js', base).href;
+ script.onload = () => {
+ window.editor = WorkflowEditor.mount('#editor');
+ window.addEventListener('beforeunload', (event) => {
+ if (editor.isDirty()) { event.preventDefault(); event.returnValue = ''; }
+ });
+ };
+ document.head.append(script);
+ </script>
+</body>
+</html>
diff --git a/web/workflow-editor/workflow-editor.js b/web/workflow-editor/workflow-editor.js
new file mode 100644
index 000000000..e938b3635
--- /dev/null
+++ b/web/workflow-editor/workflow-editor.js
@@ -0,0 +1,480 @@
+/* WebBrain Workflow Editor. Dependency-free classic script; no network or storage access. */
+(function (global) {
+ 'use strict';
+
+ const copy = value => JSON.parse(JSON.stringify(value));
+ const own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
+ const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
+ const typeOf = value => value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;
+ const defaults = { string: '', number: 0, boolean: false, null: null, object: {}, array: [] };
+ const at = (value, path) => path.reduce((node, key) => node[key], value);
+ const put = (value, key, next) => Object.defineProperty(value, key, { value: next, writable: true, enumerable: true, configurable: true });
+ const freshId = (prefix, items) => {
+ let n = 1;
+ while (items.some(item => item?.id === `${prefix}_${n}`)) n++;
+ return `${prefix}_${n}`;
+ };
+ function parse(value) {
+ const result = typeof value === 'string' ? JSON.parse(value) : copy(value);
+ if (!object(result)) throw Error('The workflow must be a JSON object at the top level.');
+ return result;
+ }
+ function references(value, visit) {
+ if (!value || typeof value !== 'object') return;
+ if (own(value, '$workflowParam')) visit(value);
+ Object.values(value).forEach(child => references(child, visit));
+ }
+ function warnings(value) {
+ const issues = [];
+ if (value.schema !== 'webbrain-workflow/1') issues.push('Expected schema “webbrain-workflow/1”.');
+ if (typeof value.name !== 'string' || !value.name.trim()) issues.push('Give this workflow a name.');
+ try {
+ const origin = new URL(value.start?.origin);
+ if (!['http:', 'https:'].includes(origin.protocol) || origin.origin !== value.start.origin) throw Error();
+ } catch {
+ issues.push('Set start.origin to an HTTP or HTTPS origin, such as https://example.com.');
+ }
+ if (typeof value.start?.pathFamily !== 'string' || !value.start.pathFamily.startsWith('/')) {
+ issues.push('Set start.pathFamily to a path beginning with /, such as / or /join.');
+ }
+ for (const key of ['steps', 'parameters']) {
+ if (!Array.isArray(value[key])) { issues.push(`${key} should be an array.`); continue; }
+ const ids = new Set();
+ value[key].forEach((item, i) => {
+ if (!object(item)) { issues.push(`${key}[${i}] should be an object.`); return; }
+ if (typeof item.id !== 'string' || !item.id.trim()) issues.push(`${key}[${i}] needs an id.`);
+ else if (ids.has(item.id)) issues.push(`Duplicate ${key} id: ${item.id}`);
+ ids.add(item.id);
+ if (key === 'steps' && (typeof item.tool !== 'string' || !item.tool.trim())) issues.push(`Step ${i + 1} needs a tool.`);
+ });
+ }
+ const ids = new Set((Array.isArray(value.parameters) ? value.parameters : []).map(item => item?.id));
+ references(value, ref => { if (!ids.has(ref.$workflowParam)) issues.push(`Unknown parameter reference: ${String(ref.$workflowParam)}`); });
+ return [...new Set(issues)];
+ }
+
+ const CSS = `
+ :host{display:block;color:#203047;font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color-scheme:light}
+ *{box-sizing:border-box}button,input,select,textarea{font:inherit}button{cursor:pointer;background:#fff;border:1px solid #ccd5e0;border-radius:6px;padding:7px 12px;color:#203047;line-height:1.4}
+ button:hover{background:#edf3fc;border-color:#95afd3}button:disabled{opacity:.42;cursor:default}button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible,summary:focus-visible{outline:2px solid #2463cb;outline-offset:3px}
+ .primary{background:#245dc1;color:white;border-color:#245dc1}.primary:hover{background:#1c4b9e;color:white}.danger{color:#a33333}.small{padding:4px 8px;font-size:12px}
+ .app{max-width:1520px;margin:0 auto;padding:28px 32px;min-height:100vh}.top,.toolbar,.row,.panel-head,.section-head{display:flex;align-items:center;gap:10px}.top{justify-content:space-between;margin-bottom:25px;flex-wrap:wrap}
+ .brand{display:flex;align-items:center;gap:12px}.mark{display:grid;place-items:center;background:#245dc1;color:white;width:37px;height:37px;border-radius:9px;font-size:23px;font-weight:600}.brand p,.brand h1{margin:0}.brand h1{font-size:21px;font-weight:650;letter-spacing:-.5px}.brand p{color:#65748a;font-size:12px}.offline{color:#426450;font-size:12px;white-space:nowrap}.offline::before{content:'â—Ź';color:#43845a;margin-right:6px}
+ .toolbar{flex-wrap:wrap}.workspace{display:grid;grid-template-columns:290px minmax(0,1fr);border:1px solid #d6dde7;border-radius:10px;overflow:hidden;background:white;min-height:650px}.sidebar{background:#f8fafd;border-right:1px solid #d6dde7;padding:20px 12px;min-width:0}.file{padding:0 10px 16px;border-bottom:1px solid #e0e6ee;margin-bottom:12px}.file strong{font-size:17px;display:block;overflow-wrap:anywhere}.muted{color:#69788e}.file small{display:block;overflow-wrap:anywhere}.nav{display:block;text-align:left;width:100%;border-color:transparent;background:transparent;margin:3px 0;padding:9px 10px}.nav.active{background:#e8f0fe;border-color:#c8d9f6;color:#194fa9}.nav strong{font-weight:550}.nav small{display:block;color:#718096;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.step{display:grid;grid-template-columns:25px minmax(0,1fr);align-items:center;gap:7px}.step .number{font-size:12px;color:#718096}.section-head{padding:17px 10px 6px;justify-content:space-between}.section-head h3{font-size:12px;font-weight:650;margin:0;color:#65748a}.steps{max-height:640px;overflow:auto}.nav[draggable=true]{cursor:grab}.nav.drop-target{border:2px dashed #245dc1}.editor{min-width:0;padding:26px 30px}.panel-head{justify-content:space-between;align-items:flex-start;border-bottom:1px solid #e2e7ee;padding-bottom:20px;margin-bottom:22px;flex-wrap:wrap}.panel-head h2{font-size:23px;letter-spacing:-.5px;margin:0 0 4px;overflow-wrap:anywhere}.panel-head p{margin:0;color:#69788e;font-size:13px}.fields{min-width:0}.field{margin:0 0 12px;padding:12px;border:1px solid #e0e6ee;border-radius:7px;background:white}.field-top{display:flex;align-items:center;gap:7px;margin-bottom:9px}.field-top input{font-weight:550;flex:1;min-width:0}.field-top select{width:100px;font-size:12px}.field-top button{padding:4px 8px}.field-value{width:100%;resize:vertical;min-height:37px}.field input,.field select,.field textarea,.add-row input,.add-row select,.filename{border:1px solid #ccd5e0;border-radius:4px;background:#fff;color:#203047;padding:6px 8px}.field textarea{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:13px;line-height:1.6}.nested{border-left:2px solid #e4ebf5;padding-left:13px;margin-top:12px}.nested .field{padding:9px}.field summary{cursor:pointer;color:#63758d;font-size:12px}.add-row{display:flex;flex-wrap:wrap;gap:7px;margin:12px 0}.add-row input{min-width:100px;flex:1}.add-row select{width:105px}.check{display:flex;gap:9px;align-items:center}.check input{width:17px;height:17px}.null{color:#78869a;font-family:monospace}.empty{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:540px;text-align:center;border:1px dashed #b6c6dc;border-radius:10px;background:#fff;padding:40px 20px}.empty h2{font-size:29px;letter-spacing:-.8px;font-weight:600;margin:18px 0 6px}.empty p{color:#69788e;max-width:400px;margin:0 0 24px}.empty .symbol{font:40px ui-monospace,monospace;color:#245dc1}.empty .row{justify-content:center;flex-wrap:wrap}.hint{font-size:12px;color:#78869a;margin-top:20px}.status{min-height:30px;padding-top:12px;font-size:12px;color:#65748a}.status.error{color:#a33333}.checks{margin-top:22px;padding:12px 14px;background:#f7f9fc;border-radius:6px;color:#65748a;font-size:12px}.checks summary{cursor:pointer}.checks ul{padding-left:20px}.checks li{overflow-wrap:anywhere}.raw{width:100%;min-height:470px;resize:vertical;border:1px solid #ccd5e0;border-radius:6px;padding:16px;font:13px/1.65 ui-monospace,SFMono-Regular,Consolas,monospace;tab-size:2;color:#203047;background:#fbfcfe}.raw-actions{margin-top:12px}.dragging .empty,.dragging .workspace{outline:3px dashed #245dc1;outline-offset:3px}.footer{display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-top:14px;color:#78869a;font-size:12px}.filename{max-width:230px;font-size:12px}.array-index{font-size:12px;color:#718096;flex:1}.quiet{background:transparent;border-color:transparent}.badge{font-size:11px;color:#65748a}.empty-list{padding:10px;color:#78869a;font-size:12px}
+ @media(min-width:1050px){.fields.root-fields{display:grid;grid-template-columns:1fr 1fr;gap:0 14px;align-items:start}.root-fields>.field.complex,.root-fields>.add-row{grid-column:1/-1}}
+ @media(max-width:760px){.app{padding:16px 12px}.top{gap:16px}.workspace{grid-template-columns:1fr}.sidebar{border-right:0;border-bottom:1px solid #d6dde7;padding:12px;max-height:300px;overflow:auto}.steps{max-height:none}.editor{padding:20px 14px}.empty{min-height:430px}.toolbar{gap:6px}.toolbar button{padding:7px 9px}.field{padding:9px}.nested{padding-left:7px}.field-top{flex-wrap:wrap}.field-top input{width:90px}.brand h1{font-size:19px}}
+ `;
+
+ class Editor {
+ constructor(target, options = {}) {
+ this.host = typeof target === 'string' ? document.querySelector(target) : target;
+ if (!this.host) throw Error('WorkflowEditor: mount target not found.');
+ if (this.host.shadowRoot) throw Error('WorkflowEditor: target already has a shadow root.');
+ this.options = options;
+ this.root = this.host.attachShadow({ mode: 'open' });
+ this.value = null;
+ this.history = [];
+ this.future = [];
+ this.selection = { kind: 'overview' };
+ this.filename = 'untitled.webbrain-workflow.json';
+ this.saved = 'null';
+ this.rawDraft = null;
+ this.closed = new Set();
+ this.destroyed = false;
+ // Let blur/change and the following click finish before replacing controls.
+ // This also preserves keyboard focus when tabbing between edited fields.
+ this.flushRender = () => {
+ if (this.needsRender && !this.pointerActive && !this.deferRender) this.render();
+ };
+ this.releasePointer = () => { this.pointerActive = false; this.flushRender(); };
+ this.pointerUp = () => setTimeout(this.releasePointer, 0);
+ this.root.addEventListener('pointerdown', () => { this.pointerActive = true; }, true);
+ document.addEventListener('click', this.releasePointer);
+ document.addEventListener('pointerup', this.pointerUp);
+ document.addEventListener('pointercancel', this.releasePointer);
+ this.root.addEventListener('change', () => {
+ this.pendingField = null;
+ this.deferRender = true;
+ setTimeout(() => { this.deferRender = false; this.flushRender(); }, 0);
+ }, true);
+ this.root.addEventListener('input', event => {
+ if (event.target.closest('[data-path]')) this.pendingField = event.target;
+ });
+ this.root.addEventListener('dragover', event => {
+ if (Array.from(event.dataTransfer?.types || []).includes('Files')) { event.preventDefault(); this.app.classList.add('dragging'); }
+ });
+ this.root.addEventListener('dragleave', event => { if (!this.host.contains(event.relatedTarget)) this.app.classList.remove('dragging'); });
+ this.root.addEventListener('drop', event => {
+ event.preventDefault(); this.app.classList.remove('dragging');
+ if (event.dataTransfer?.files.length) this.readFile(event.dataTransfer.files[0]);
+ });
+ this.root.addEventListener('keydown', event => {
+ if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') { event.preventDefault(); this.download(); }
+ });
+ if (options.value !== undefined) this.load(options.value, options.filename);
+ else this.render();
+ }
+ el(tag, attrs = {}, children = []) {
+ const element = document.createElement(tag);
+ for (const [key, value] of Object.entries(attrs)) {
+ if (key.startsWith('on')) element.addEventListener(key.slice(2), value);
+ else if (key === 'class') element.className = value;
+ else if (key === 'text') element.textContent = value;
+ else element.setAttribute(key, value);
+ }
+ element.append(...children);
+ return element;
+ }
+ button(text, action, className = '', disabled = false) {
+ const button = this.el('button', { type: 'button', text, class: className, onclick: action });
+ button.disabled = disabled;
+ return button;
+ }
+ message(text, error = false) {
+ this.notice = { text, error };
+ if (this.status) { this.status.textContent = text; this.status.classList.toggle('error', error); }
+ }
+ attempt(action) { try { action(); } catch (error) { this.render(); this.message(error.message, true); } }
+ notify() {
+ const value = this.getValue();
+ this.host.dispatchEvent(new CustomEvent('workflowchange', { detail: { value }, bubbles: true }));
+ if (typeof this.options.onChange === 'function') this.options.onChange(this.getValue(), this);
+ }
+ load(value, filename = 'workflow.webbrain-workflow.json') {
+ const next = parse(value);
+ this.value = next;
+ this.notice = null;
+ this.filename = String(filename || 'workflow.webbrain-workflow.json');
+ this.saved = JSON.stringify(next);
+ this.history = []; this.future = []; this.rawDraft = null; this.closed.clear();
+ this.selection = { kind: 'overview' };
+ this.render();
+ return this;
+ }
+ getValue() { return copy(this.value); }
+ toJSON(space = 2) {
+ if (this.rawDraft !== null) throw Error('Apply or discard your JSON edits before exporting.');
+ return JSON.stringify(this.value, null, space) + '\n';
+ }
+ isDirty() { return !!this.pendingField || this.rawDraft !== null || JSON.stringify(this.value) !== this.saved; }
+ validate() { return this.value ? warnings(this.value) : []; }
+ markSaved() {
+ this.saved = JSON.stringify(this.value);
+ // A host may finish saving while the user is typing their next edit.
+ // Do not rebuild controls: that can discard or commit the pending text.
+ this.message(this.isDirty() ? 'Unsaved changes remain' : 'Saved');
+ }
+ destroy() {
+ this.destroyed = true;
+ document.removeEventListener('click', this.releasePointer);
+ document.removeEventListener('pointerup', this.pointerUp);
+ document.removeEventListener('pointercancel', this.releasePointer);
+ this.root.replaceChildren();
+ }
+ commit(change) {
+ const next = copy(this.value);
+ change(next);
+ if (JSON.stringify(next) === JSON.stringify(this.value)) return;
+ this.history.push(copy(this.value)); if (this.history.length > 100) this.history.shift();
+ this.future = []; this.value = next; this.rawDraft = null;
+ this.notice = null;
+ this.render(); this.notify();
+ }
+ undo() {
+ if (!this.history.length || this.rawDraft !== null) return;
+ this.future.push(this.value); this.value = this.history.pop(); this.render(); this.notify();
+ }
+ redo() {
+ if (!this.future.length || this.rawDraft !== null) return;
+ this.history.push(this.value); this.value = this.future.pop(); this.render(); this.notify();
+ }
+ select(kind, index) {
+ if (this.rawDraft !== null) { this.message('Apply or discard your JSON edits first.', true); return; }
+ this.selection = { kind, index }; this.render();
+ }
+ confirmReplace() { return !this.isDirty() || global.confirm('Replace this workflow? Download it first to keep your changes.'); }
+ async readFile(file) {
+ try {
+ const value = parse(await file.text());
+ if (this.destroyed || !this.confirmReplace()) return;
+ this.load(value, file.name); this.message(`Opened ${file.name}. The file stays on your device.`);
+ } catch (error) { if (!this.destroyed) this.message(`Could not open file: ${error.message}`, true); }
+ }
+ newWorkflow() {
+ if (!this.confirmReplace()) return;
+ this.load({ schema: 'webbrain-workflow/1', id: `workflow_${Date.now()}`, name: 'Untitled workflow', start: { origin: '', pathFamily: '/' }, parameters: [], steps: [] }, 'untitled.webbrain-workflow.json');
+ this.saved = 'null'; this.render();
+ }
+ download() {
+ if (!this.value) return;
+ // Keyboard save must include the text still focused in the form.
+ if (this.pendingField?.isConnected) this.pendingField.dispatchEvent(new Event('change', { bubbles: true }));
+ this.attempt(() => {
+ const blob = new Blob([this.toJSON()], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const link = this.el('a', { href: url, download: this.filename.endsWith('.json') ? this.filename : `${this.filename}.json` });
+ this.root.append(link); link.click(); link.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+ this.saved = JSON.stringify(this.value); this.render(); this.message('Download created. Your original file is unchanged.');
+ });
+ }
+ set(path, value) {
+ this.attempt(() => this.commit(next => {
+ if (path.length === 3 && path[0] === 'parameters' && path[2] === 'id') {
+ const old = at(next, path);
+ if (typeof value !== 'string' || !value.trim()) throw Error('Parameter ids must be non-empty text.');
+ if (next.parameters.some((item, i) => i !== path[1] && item?.id === value)) throw Error('That parameter id already exists.');
+ if (typeof old === 'string' && old && !next.parameters.some((item, i) => i !== path[1] && item?.id === old)) {
+ references(next, ref => { if (ref.$workflowParam === old) ref.$workflowParam = value; });
+ }
+ }
+ put(at(next, path.slice(0, -1)), path.at(-1), value);
+ }));
+ }
+ move(path, from, to) {
+ this.commit(next => { const items = at(next, path); items.splice(to, 0, items.splice(from, 1)[0]); });
+ }
+ addItem(kind) {
+ this.commit(next => {
+ const items = next[kind];
+ items.push(kind === 'steps'
+ ? { id: freshId('step', items), tool: 'click_ax', args: {}, target: { role: 'button', name: '' }, scope: copy(object(next.start) ? next.start : { origin: '', pathFamily: '/' }), expected: { kind: 'tool_success' } }
+ : { id: freshId('parameter', items), label: 'New parameter', type: 'text', required: false, sensitive: false });
+ this.selection = { kind, index: items.length - 1 };
+ });
+ }
+ render() {
+ if (this.destroyed) return;
+ if (this.pointerActive || this.deferRender) { this.needsRender = true; return; }
+ this.needsRender = false;
+ this.pendingField = null;
+ this.renderPaths = new Set();
+ const focused = this.root.activeElement;
+ const focusLabel = focused?.matches('input,textarea,select') ? focused.getAttribute('aria-label') : null;
+ const selection = focused?.selectionStart == null ? null : [focused.selectionStart, focused.selectionEnd];
+ this.root.replaceChildren(this.el('style', { text: CSS }));
+ this.app = this.el('div', { class: 'app' }); this.root.append(this.app);
+ this.fileInput = this.el('input', { type: 'file', accept: '.json,application/json', hidden: '', 'aria-label': 'Open workflow file', onchange: event => { if (event.target.files[0]) this.readFile(event.target.files[0]); } });
+ this.app.append(this.fileInput);
+ const toolbar = this.el('div', { class: 'toolbar' }, [
+ this.button('New', () => this.newWorkflow()), this.button('Open JSON', () => this.fileInput.click()),
+ this.button('Undo', () => this.undo(), '', !this.history.length || this.rawDraft !== null),
+ this.button('Redo', () => this.redo(), '', !this.future.length || this.rawDraft !== null),
+ this.button('Download JSON', () => this.download(), 'primary', !this.value || this.rawDraft !== null)
+ ]);
+ this.app.append(this.el('header', { class: 'top' }, [
+ this.el('div', { class: 'brand' }, [this.el('span', { class: 'mark', text: '≡', 'aria-hidden': 'true' }), this.el('div', {}, [this.el('h1', { text: 'Workflow editor' }), this.el('p', { text: 'WebBrain / local workspace' })])]), toolbar
+ ]));
+ if (!this.value) {
+ this.app.append(this.el('section', { class: 'empty' }, [
+ this.el('div', { class: 'symbol', text: '{ }', 'aria-hidden': 'true' }), this.el('h2', { text: 'A workspace for your workflows.' }),
+ this.el('p', { text: 'Drop a workflow JSON file here. Rename steps, adjust parameters, and edit every field in one place.' }),
+ this.el('div', { class: 'row' }, [this.button('Choose a JSON file', () => this.fileInput.click(), 'primary'), this.button('Start a new workflow', () => this.newWorkflow())]),
+ this.el('span', { class: 'hint', text: 'No uploads. No account. No connection required.' })
+ ]));
+ } else {
+ const workspace = this.el('div', { class: 'workspace' });
+ workspace.append(this.sidebar());
+ this.panel = this.el('section', { class: 'editor', 'aria-label': 'Workflow fields' }); workspace.append(this.panel);
+ this.app.append(workspace); this.renderPanel();
+ }
+ this.status = this.el('div', { class: `status ${this.notice?.error ? 'error' : ''}`, role: 'status', 'aria-live': 'polite', text: this.notice?.text ?? (this.value ? (this.isDirty() ? 'Changes not downloaded' : 'Ready to edit') : 'Open a file or start from scratch.') });
+ this.app.append(this.status);
+ const footer = this.el('footer', { class: 'footer' }, [this.el('span', { class: 'offline', text: 'Offline · files stay on your device' })]);
+ if (this.value) {
+ const filename = this.el('input', { class: 'filename', value: this.filename, 'aria-label': 'Download filename', onchange: event => { this.filename = event.target.value.trim() || 'workflow.json'; } });
+ footer.append(this.el('label', {}, ['Download as ', filename]));
+ } else footer.append(this.el('span', { text: 'Edit locally. Download when you’re ready.' }));
+ this.app.append(footer);
+ if (focusLabel) {
+ const replacement = Array.from(this.root.querySelectorAll('[aria-label]')).find(node => node.getAttribute('aria-label') === focusLabel);
+ if (replacement) {
+ replacement.focus({ preventScroll: true });
+ if (selection && replacement.setSelectionRange) replacement.setSelectionRange(...selection);
+ }
+ }
+ }
+ sidebar() {
+ const sidebar = this.el('nav', { class: 'sidebar', 'aria-label': 'Workflow navigation' });
+ sidebar.append(this.el('div', { class: 'file' }, [this.el('strong', { text: typeof this.value.name === 'string' ? this.value.name : 'Untitled workflow' }), this.el('small', { class: 'muted', text: `${Array.isArray(this.value.steps) ? this.value.steps.length : 0} steps` })]));
+ for (const [kind, label] of [['overview', 'Workflow details'], ['json', 'JSON source']]) {
+ sidebar.append(this.button(label, () => this.select(kind), `nav ${this.selection.kind === kind ? 'active' : ''}`));
+ }
+ for (const kind of ['parameters', 'steps']) {
+ if (!Array.isArray(this.value[kind])) continue;
+ sidebar.append(this.el('div', { class: 'section-head' }, [this.el('h3', { text: `${kind === 'steps' ? 'Steps' : 'Parameters'} (${this.value[kind].length})` }), this.button('+ Add', () => this.addItem(kind), 'small', this.rawDraft !== null)]));
+ const list = this.el('div', { class: 'steps' });
+ if (!this.value[kind].length) list.append(this.el('div', { class: 'empty-list', text: `No ${kind} yet.` }));
+ this.value[kind].forEach((item, index) => {
+ const title = kind === 'steps' ? (item?.name || item?.target?.name || item?.tool || 'Step') : (item?.label || item?.id || 'Parameter');
+ const button = this.button('', () => this.select(kind, index), `nav step ${this.selection.kind === kind && this.selection.index === index ? 'active' : ''}`);
+ button.setAttribute('aria-label', `${kind === 'steps' ? 'Step' : 'Parameter'} ${index + 1}: ${String(title)}`);
+ button.append(this.el('span', { class: 'number', text: String(index + 1).padStart(2, '0') }), this.el('span', {}, [this.el('strong', { text: String(title) }), this.el('small', { text: String(kind === 'steps' ? (item?.tool || '') : (item?.id || '')) })]));
+ button.draggable = this.rawDraft === null;
+ button.addEventListener('dragstart', event => { this.drag = { kind, index }; event.dataTransfer.setData('text/plain', String(index)); event.dataTransfer.effectAllowed = 'move'; });
+ button.addEventListener('dragend', () => { this.drag = null; this.root.querySelectorAll('.drop-target').forEach(node => node.classList.remove('drop-target')); });
+ button.addEventListener('dragover', event => { if (this.drag?.kind === kind) { event.preventDefault(); button.classList.add('drop-target'); } });
+ button.addEventListener('dragleave', () => button.classList.remove('drop-target'));
+ button.addEventListener('drop', event => {
+ if (this.drag?.kind !== kind) return;
+ event.preventDefault(); event.stopPropagation(); const from = this.drag.index; this.drag = null;
+ this.selection = { kind, index }; this.move([kind], from, index);
+ });
+ list.append(button);
+ });
+ sidebar.append(list);
+ }
+ return sidebar;
+ }
+ renderPanel() {
+ let { kind, index } = this.selection;
+ if (!['overview', 'json'].includes(kind) && (!Array.isArray(this.value[kind]) || index >= this.value[kind].length)) {
+ this.selection = { kind: 'overview' }; kind = 'overview';
+ }
+ const title = kind === 'overview' ? 'Workflow details' : kind === 'json' ? 'JSON source' : `${kind === 'steps' ? 'Step' : 'Parameter'} ${index + 1}`;
+ const subtitle = kind === 'overview' ? 'Name, starting page, and file metadata.' : kind === 'json' ? 'Edit the full document. Apply changes to return to the visual editor.' : kind === 'steps' ? 'Edit any field. Drag steps in the list to reorder them.' : 'Renaming an id also updates its parameter references.';
+ const heading = this.el('div', { class: 'panel-head' }, [this.el('div', {}, [this.el('h2', { text: title }), this.el('p', { text: subtitle })])]);
+ this.panel.append(heading);
+ if (kind === 'json') {
+ const raw = this.el('textarea', { class: 'raw', 'aria-label': 'Workflow JSON source', spellcheck: 'false' });
+ raw.value = this.rawDraft ?? this.toJSON();
+ raw.addEventListener('input', () => {
+ this.rawDraft = raw.value;
+ this.root.querySelectorAll('.toolbar button').forEach(button => { if (['Undo', 'Redo', 'Download JSON'].includes(button.textContent)) button.disabled = true; });
+ this.root.querySelectorAll('.section-head button').forEach(button => { button.disabled = true; });
+ this.root.querySelectorAll('[draggable]').forEach(button => { button.draggable = false; });
+ this.message('JSON edits pending. Apply changes or discard them.');
+ });
+ this.panel.append(raw, this.el('div', { class: 'row raw-actions' }, [
+ this.button('Apply JSON', () => this.attempt(() => {
+ const next = parse(raw.value);
+ this.rawDraft = null;
+ this.commit(value => { Object.keys(value).forEach(key => delete value[key]); Object.entries(next).forEach(([key, item]) => put(value, key, item)); });
+ this.render(); this.message('JSON changes applied.');
+ }), 'primary'),
+ this.button('Discard JSON edits', () => { this.rawDraft = null; this.render(); })
+ ]));
+ } else {
+ let path = [];
+ if (kind !== 'overview') {
+ path = [kind, index];
+ heading.append(this.el('div', { class: 'row' }, [
+ this.button('↑', () => { this.selection.index--; this.move([kind], index, index - 1); }, '', index === 0),
+ this.button('↓', () => { this.selection.index++; this.move([kind], index, index + 1); }, '', index === this.value[kind].length - 1),
+ this.button('Duplicate', () => this.commit(next => { const item = copy(next[kind][index]); if (object(item)) item.id = freshId(kind === 'steps' ? 'step' : 'parameter', next[kind]); next[kind].splice(index + 1, 0, item); this.selection.index++; })),
+ this.button('Remove', () => this.commit(next => { next[kind].splice(index, 1); this.selection = { kind: 'overview' }; }), 'danger')
+ ]));
+ heading.querySelectorAll('button').forEach(button => { if (button.textContent === '↑') button.setAttribute('aria-label', 'Move up'); if (button.textContent === '↓') button.setAttribute('aria-label', 'Move down'); });
+ }
+ const value = at(this.value, path);
+ if (value !== null && typeof value === 'object') this.panel.append(this.fields(value, path, true));
+ else this.panel.append(this.field(value, path));
+ }
+ const issues = this.validate();
+ this.panel.append(this.el('details', { class: 'checks' }, [
+ this.el('summary', { text: issues.length ? `${issues.length} workflow check${issues.length === 1 ? '' : 's'} to review` : 'Basic checks passed' }),
+ this.el('p', { text: 'Checks cover the starting scope, names, ids, and parameter references. They do not test whether a workflow will run. All fields are preserved when exporting.' }),
+ this.el('ul', {}, issues.map(text => this.el('li', { text })))
+ ]));
+ }
+ trackPath(path) {
+ this.renderPaths.add(path);
+ return path;
+ }
+ rename(path, nextName) {
+ const previous = path.slice(), key = previous.at(-1);
+ if (nextName === key) return;
+ this.commit(next => {
+ const target = at(next, previous.slice(0, -1));
+ if (own(target, nextName)) throw Error('A field with that name already exists.');
+ const entries = Object.entries(target);
+ Object.keys(target).forEach(name => delete target[name]);
+ entries.forEach(([name, item]) => put(target, name === key ? nextName : name, item));
+ // During a blur-to-click transition, existing controls are still live.
+ // Rebase their paths before the following action or nested action runs.
+ for (const current of this.renderPaths) {
+ if (current.length >= previous.length && previous.every((part, index) => current[index] === part)) {
+ current[previous.length - 1] = nextName;
+ }
+ }
+ });
+ }
+ fields(value, path, root = false) {
+ this.trackPath(path);
+ const container = this.el('div', { class: `fields ${root ? 'root-fields' : ''}` });
+ Object.keys(value).forEach(key => {
+ if (!path.length && ['steps', 'parameters'].includes(key) && Array.isArray(value[key])) return;
+ container.append(this.field(value[key], [...path, Array.isArray(value) ? Number(key) : key]));
+ });
+ const keyInput = this.el('input', { placeholder: 'New field name', 'aria-label': `New field name at ${JSON.stringify(path)}` });
+ const type = this.el('select', { 'aria-label': `New field type at ${JSON.stringify(path)}` }, Object.keys(defaults).map(name => this.el('option', { value: name, text: name })));
+ const add = this.el('form', { class: 'add-row', onsubmit: event => {
+ event.preventDefault();
+ this.attempt(() => this.commit(next => {
+ const parent = at(next, path);
+ if (Array.isArray(parent)) parent.push(copy(defaults[type.value]));
+ else {
+ if (!keyInput.value.trim()) throw Error('Enter a field name.');
+ if (own(parent, keyInput.value)) throw Error('A field with that name already exists.');
+ put(parent, keyInput.value, copy(defaults[type.value]));
+ }
+ }));
+ } });
+ if (!Array.isArray(value)) add.append(keyInput);
+ add.append(type, this.el('button', {
+ type: 'submit', text: Array.isArray(value) ? '+ Add item' : '+ Add field',
+ onclick: event => {
+ // Submit before the document click listener flushes a pending redraw.
+ // Otherwise Firefox can lose the default submission with the old form.
+ event.preventDefault(); add.requestSubmit();
+ }
+ }));
+ container.append(add); return container;
+ }
+ field(value, path) {
+ this.trackPath(path);
+ const key = path.at(-1), parentPath = this.trackPath(path.slice(0, -1)), parent = at(this.value, parentPath);
+ const array = Array.isArray(parent), type = typeOf(value), address = JSON.stringify(path);
+ const field = this.el('div', { class: `field ${['object', 'array'].includes(type) ? 'complex' : ''}`, 'data-path': address });
+ const top = this.el('div', { class: 'field-top' });
+ if (array) top.append(this.el('span', { class: 'array-index', text: `Item ${Number(key) + 1}` }));
+ else {
+ const name = this.el('input', { value: key, 'aria-label': `Field name ${address}`, onchange: event => this.attempt(() => this.rename(path, event.target.value)) }); top.append(name);
+ }
+ const select = this.el('select', { 'aria-label': `Type ${address}`, onchange: event => {
+ const nextType = event.target.value;
+ if ((type === 'object' || type === 'array') && Object.keys(value).length && !global.confirm('Changing this type replaces its nested fields. Continue?')) { event.target.value = type; return; }
+ this.set(path, copy(defaults[nextType]));
+ } }, Object.keys(defaults).map(name => this.el('option', { value: name, text: name })));
+ select.value = type; top.append(select);
+ if (array) {
+ const up = this.button('↑', () => this.move(parentPath, key, key - 1), 'small', key === 0); up.setAttribute('aria-label', `Move up ${address}`);
+ const down = this.button('↓', () => this.move(parentPath, key, key + 1), 'small', key === parent.length - 1); down.setAttribute('aria-label', `Move down ${address}`); top.append(up, down);
+ }
+ const remove = this.button('Ă—', () => this.commit(next => { const target = at(next, parentPath); const currentKey = path.at(-1); if (array) target.splice(currentKey, 1); else delete target[currentKey]; }), 'quiet danger');
+ remove.setAttribute('aria-label', `Remove ${address}`); top.append(remove); field.append(top);
+ if (type === 'object' || type === 'array') {
+ const details = this.el('details', {}, [this.el('summary', { text: `${Object.keys(value).length} ${type === 'array' ? 'items' : 'fields'}` }), this.el('div', { class: 'nested' }, [this.fields(value, path)])]);
+ details.open = !this.closed.has(address);
+ details.addEventListener('toggle', () => { if (!details.isConnected) return; if (details.open) this.closed.delete(address); else this.closed.add(address); });
+ field.append(details);
+ } else if (type === 'boolean') {
+ const checkbox = this.el('input', { type: 'checkbox', 'aria-label': `Value ${address}`, onchange: event => this.set(path, event.target.checked) }); checkbox.checked = value;
+ field.append(this.el('label', { class: 'check' }, [checkbox, String(value)]));
+ } else if (type === 'null') field.append(this.el('span', { class: 'null', text: 'null' }));
+ else {
+ const input = this.el(type === 'string' ? 'textarea' : 'input', { class: 'field-value', 'aria-label': `Value ${address}`, spellcheck: 'false' });
+ if (type === 'string') input.rows = Math.min(6, Math.max(1, String(value).split('\n').length, Math.ceil(String(value).length / 85)));
+ else { input.type = 'number'; input.step = 'any'; }
+ input.value = value;
+ input.addEventListener('change', () => {
+ if (type === 'number' && (!input.value.trim() || !Number.isFinite(Number(input.value)))) { input.value = value; this.message('Enter a finite number.', true); return; }
+ this.set(path, type === 'number' ? Number(input.value) : input.value);
+ });
+ field.append(input);
+ }
+ return field;
+ }
+ }
+ global.WorkflowEditor = Object.freeze({ mount: (target, options) => new Editor(target, options), version: '1.0.0' });
+})(globalThis);