Files
stack/packages/webui/src/public/workflows.js
T

761 lines
57 KiB
JavaScript

// Starter packs SP6 (#1873, design section 8): the owner's workflow list and editor on an
// organization's page. GET /api/orgs/<id>/workflows reads the org's and each code project's workflows
// with the file revision; a save is POST .../workflows/<name> {revision, workflow, project?} and a delete
// DELETE .../workflows/<name> {revision, project?} (workflow.set.console). The bus checks the shape; this
// page marks a step role that resolves to no org definition or role template (and is not `human`) as
// naming no current role. Every organization-supplied string goes through esc.
(() => {
'use strict';
const esc = x => String(x ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const base = org => `/api/orgs/${encodeURIComponent(org)}`;
const STATES = [['todo', 'To do'], ['in-progress', 'In progress'], ['in-review', 'Review'], ['blocked', 'Blocked'], ['done', 'Done']];
const STATE_LABEL = Object.fromEntries(STATES);
// The writer's workflow name rule (organization.mjs PLAN_NAME); a name it would refuse is refused here first.
const NAME = /^[a-z][a-z0-9-]{0,63}$/;
const NAME_RULE = 'A workflow name is 1 to 64 lowercase letters, digits or dashes, starting with a letter.';
const MISSING = 'names no current role';
const states = new Map();
const guidance = {
'revision-conflict': 'The organization changed since this page read it. Reload the page before saving.',
'organization-busy': 'The organization is busy with another write. Try again shortly.',
'invalid-request': 'The bus refused the workflow. Check each step has a title, a state and one to eight distinct roles.',
'project-not-found': 'That project is not in the organization file.',
'credential-leak': 'The workflow carries a value the credential store holds.',
'read-only': 'This Console was started without send. Workflows can be read, not changed.',
'owner-only': 'Only the owner can read and change workflows.',
'sign-in-required': 'Sign in again to read workflows.',
'cross-origin': 'The request did not come from this Console.',
'not-configured': 'This Console cannot read the organization file.',
'org-unavailable': 'The organization file could not be read.',
'no-bus-host': 'The organization bus is not running.',
};
async function call(url, method, body) {
const r = await fetch(url, method === 'GET' ? { cache: 'no-store' } : { method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
let value = null;
try { value = await r.json(); } catch { value = null; }
// The refusal code rides on the error, so a caller with its own words for one (the graph editor) can use them.
if (!r.ok) throw Object.assign(Error(guidance[value?.error] ?? `The bus refused: ${value?.error ?? 'outcome unknown'}.`), { code: value?.error ?? null });
return value;
}
const plain = v => v !== null && typeof v === 'object' && !Array.isArray(v);
async function read(org, s) {
const value = await call(`${base(org)}/workflows`, 'GET');
if (!plain(value) || !plain(value.workflows) || !plain(value.projects) || !plain(value.roles) || typeof value.revision !== 'string') throw Error('The workflow read returned an unexpected answer.');
s.data = value;
s.known = new Set([...(value.roles.definitions || []), ...(value.roles.templates || []), 'human']);
}
// E2E6 P1-1: a poll reloads the data but keeps the page's own state: an open editor and its draft,
// a pending delete confirmation and the last receipt.
async function load(org) {
const prev = states.get(org);
const s = { data: null, known: new Set(), error: null, editing: prev?.editing ?? null, confirm: prev?.confirm ?? null, status: prev?.status ?? '' };
try { await read(org, s); } catch (error) {
// Review P3: a failed poll while an editor is open keeps the last good read, so the fresh section
// still carries its data-live-key and graftLive puts the held section, editor and focus back.
if (prev?.editing && prev.data) Object.assign(s, { data: prev.data, known: prev.known });
else s.error = error.message;
}
states.set(org, s);
}
const scopes = s => [['', 'Organization', s.data.workflows], ...Object.keys(s.data.projects).sort().map(p => [p, `Project ${p}`, s.data.projects[p]])];
const roleChip = (s, role) => s.known.has(role)
? `<code>${esc(role)}</code>`
: `<code>${esc(role)}</code> <span class="wf-missing" data-wf-missing>${MISSING}</span>`;
function stepItem(s, step) {
const roles = Array.isArray(step?.roles) ? step.roles : [];
return `<li data-wf-step><span>${esc(step?.title)}</span> <span class="muted">${esc(STATE_LABEL[step?.state] ?? step?.state)}</span> <span class="wf-roles">${roles.map(r => roleChip(s, r)).join(', ')}</span></li>`;
}
function workflowItem(org, s, scope, name, w) {
const steps = Array.isArray(w?.steps) ? w.steps : [];
const confirm = s.confirm && s.confirm.scope === scope && s.confirm.name === name;
const actions = !s.data.writable ? '' : confirm
? `<p>Delete this workflow? <button class="btn" type="button" data-wf-delete-yes data-focus-key="${esc(`wf-yes:${scope}:${name}`)}">Delete</button> <button class="btn" type="button" data-wf-delete-no data-focus-key="${esc(`wf-no:${scope}:${name}`)}">Keep</button></p>`
: `<p><button class="btn" type="button" data-wf-edit data-focus-key="${esc(`wf-edit:${scope}:${name}`)}">Edit</button> <button class="btn" type="button" data-wf-delete data-focus-key="${esc(`wf-delete:${scope}:${name}`)}">Delete</button></p>`;
return `<li class="wf-item" data-wf="${esc(name)}" data-wf-scope="${esc(scope)}"><strong data-wf-title>${esc(w?.title || name)}</strong> <span class="muted"><code>${esc(name)}</code></span>
${w?.description ? `<p>${esc(w.description)}</p>` : ''}<ol class="wf-steps">${steps.map(st => stepItem(s, st)).join('')}</ol>${actions}</li>`;
}
function stepRow(s, step, i) {
const roles = step.roles.split(',').map(r => r.trim()).filter(Boolean);
const missing = roles.filter(r => !s.known.has(r));
return `<fieldset class="wf-step" data-wf-edit-step="${i}"><legend>Step ${i + 1}</legend>
<label>Title<input name="title" maxlength="120" value="${esc(step.title)}" autocomplete="off"></label>
<label>State<select name="state">${STATES.map(([v, l]) => `<option value="${v}"${step.state === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label>
<label>Roles, separated by commas<input name="roles" value="${esc(step.roles)}" autocomplete="off"></label>
<p class="wf-note" data-wf-step-missing>${missing.length ? `${missing.map(r => `<code>${esc(r)}</code>`).join(', ')} ${MISSING}` : ''}</p>
<button class="btn" type="button" data-wf-step-remove>Remove step</button></fieldset>`;
}
function editor(s) {
const e = s.editing;
if (!e) return '';
const scopeField = e.isNew
? `<label>Where<select name="scope">${scopes(s).map(([v, l]) => `<option value="${esc(v)}"${e.scope === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label><label>Name<input name="name" maxlength="64" value="${esc(e.name)}" autocomplete="off" placeholder="lowercase letters, digits, dashes"></label>`
: `<p>${e.scope ? `Project ${esc(e.scope)}` : 'Organization'}, <code>${esc(e.name)}</code></p>`;
return `<form class="wf-editor" data-wf-editor data-live-hold><h4>${e.isNew ? 'New workflow' : 'Edit workflow'}</h4>${scopeField}
<label>Title<input name="title" maxlength="120" value="${esc(e.draft.title)}" autocomplete="off"></label>
<label>Description<textarea name="description" maxlength="1000" rows="2">${esc(e.draft.description)}</textarea></label>
${e.draft.steps.map((st, i) => stepRow(s, st, i)).join('')}
<p><button class="btn" type="button" data-wf-step-add>Add step</button> <button class="btn" type="submit">Save workflow</button> <button class="btn" type="button" data-wf-cancel>Cancel</button></p>
<p class="note">Roles name an organization role, a role template, or <code>human</code>.</p></form>`;
}
function section(org) {
const s = states.get(org);
if (!s || s.error) return `<section class="panel" data-workflows data-workflows-org="${esc(org)}"><h3>Workflows</h3><p>${esc(s?.error ?? 'Workflows could not be read.')}</p></section>`;
const lists = scopes(s).map(([scope, label, flows]) => {
const names = Object.keys(flows || {}).sort();
return `<div class="wf-scope" data-wf-scope-list="${esc(scope)}"><h4>${esc(label)}</h4>${names.length ? `<ul class="wf-list">${names.map(n => workflowItem(org, s, scope, n, flows[n])).join('')}</ul>` : '<p class="note">No workflows.</p>'}</div>`;
}).join('');
const add = s.data.writable ? (s.editing ? '' : `<p><button class="btn" type="button" data-wf-new data-focus-key="${esc(`wf-new:${org}`)}">New workflow</button></p>`) : '<p class="note">Only the owner, on a Console started with send, can change workflows.</p>';
return `<section class="panel" data-workflows data-workflows-org="${esc(org)}" data-live-key="${esc(`workflows:${org}`)}"><h3>Workflows</h3><p>A workflow lists the steps a task goes through, the state each step puts it in and the roles that do it.</p>${lists}${add}${editor(s)}<p role="status" data-workflows-status>${esc(s.status)}</p></section>`;
}
function redraw(org) {
const el = [...document.querySelectorAll('[data-workflows-org]')].find(n => n.dataset.workflowsOrg === org);
if (el) el.outerHTML = section(org);
}
// The editor's current values back into the draft, so adding or removing a step keeps what was typed.
function capture(root, s) {
const form = root.querySelector('[data-wf-editor]');
if (!form || !s.editing) return;
const e = s.editing;
if (e.isNew) { e.scope = form.elements.scope?.value ?? e.scope; e.name = form.elements.name?.value ?? e.name; }
e.draft.title = form.querySelector(':scope > label > input[name="title"]').value;
e.draft.description = form.elements.description.value;
e.draft.steps = [...form.querySelectorAll('[data-wf-edit-step]')].map(f => ({ title: f.querySelector('[name="title"]').value, state: f.querySelector('[name="state"]').value, roles: f.querySelector('[name="roles"]').value }));
}
const flowsIn = (s, scope) => scope ? s.data.projects[scope] : s.data.workflows;
const target = (s, scope) => scope ? { project: scope } : {};
// SP10: the one check, body and write both editors use, the organization page's form and the graph.
// A step is {title, state, roles: [names]}. The order of the checks is the form's: the name, a name the
// scope already holds, a role that names no current role, then the shape the bus checks (organization-config
// checkWorkflows: 1 to 20 steps, each with a title and 1 to 8 distinct roles), named here before the bus
// refuses it in general words.
const rolesIn = text => String(text ?? '').split(',').map(r => r.trim()).filter(Boolean);
function stepRefusal(st, n) {
if (!String(st.title ?? '').trim()) return `Step ${n} needs a title.`;
if (!st.roles.length) return `Step ${n} needs at least one role.`;
if (st.roles.length > 8) return `Step ${n} names ${st.roles.length} roles. A step takes at most eight.`;
if (new Set(st.roles).size !== st.roles.length) return `Step ${n} names the same role twice.`;
return '';
}
function refusal(s, { isNew, scope, name, steps }) {
if (!NAME.test(name)) return NAME_RULE;
// A save is a set: a new workflow under a name the scope already holds would replace it without a word.
if (isNew && Object.hasOwn(flowsIn(s, scope) ?? {}, name)) return `A workflow named ${name} already exists here. Edit it instead.`;
// E2E6 P2-1: a step role that names no current role is named before the bus refuses it generically.
const unknown = steps.flatMap((st, i) => st.roles.filter(r => !s.known.has(r)).map(r => [i + 1, r]));
if (unknown.length) return `${unknown.map(([i, r]) => `Step ${i}: ${r}`).join('; ')} ${unknown.length === 1 ? 'names' : 'name'} no current role. Use an organization role, a role template or human.`;
if (!steps.length) return 'A workflow needs at least one step.';
if (steps.length > 20) return 'A workflow has at most 20 steps.';
for (const [i, st] of steps.entries()) { const why = stepRefusal(st, i + 1); if (why) return why; }
return '';
}
const shape = ({ title = '', description = '', steps }) => ({
...(title.trim() ? { title: title.trim() } : {}),
...(description.trim() ? { description: description.trim() } : {}),
steps: steps.map(st => ({ title: st.title.trim(), state: st.state, roles: [...st.roles] })),
});
const flowUrl = (org, name) => `${base(org)}/workflows/${encodeURIComponent(name)}`;
// The revision is the one the editor opened on: a change made since then is a revision-conflict, not overwritten.
const saveFlow = (org, s, { scope, name, revision, workflow }) => call(flowUrl(org, name), 'POST', { revision, workflow, ...target(s, scope) });
const removeFlow = (org, s, { scope, name, revision }) => call(flowUrl(org, name), 'DELETE', { revision, ...target(s, scope) });
async function reload(org, s, status) {
try { await read(org, s); s.status = status; } catch (error) { s.status = `${status} ${error.message}`; }
}
document.addEventListener('click', async ev => {
const button = ev.target.closest('[data-wf-new],[data-wf-edit],[data-wf-cancel],[data-wf-step-add],[data-wf-step-remove],[data-wf-delete],[data-wf-delete-yes],[data-wf-delete-no]');
if (!button) return;
const root = button.closest('[data-workflows-org]'), org = root?.dataset.workflowsOrg, s = states.get(org);
if (!s?.data) return;
const item = button.closest('[data-wf]'), scope = item?.dataset.wfScope ?? '', name = item?.dataset.wf;
if (button.hasAttribute('data-wf-new')) {
s.editing = { isNew: true, revision: s.data.revision, scope: '', name: '', draft: { title: '', description: '', steps: [{ title: '', state: 'todo', roles: '' }] } };
} else if (button.hasAttribute('data-wf-edit')) {
const w = flowsIn(s, scope)?.[name];
s.editing = { isNew: false, revision: s.data.revision, scope, name, draft: { title: w?.title ?? '', description: w?.description ?? '', steps: (w?.steps ?? []).map(st => ({ title: st.title ?? '', state: st.state ?? 'todo', roles: (st.roles ?? []).join(', ') })) } };
} else if (button.hasAttribute('data-wf-cancel')) {
s.editing = null;
} else if (button.hasAttribute('data-wf-step-add')) {
capture(root, s); s.editing.draft.steps.push({ title: '', state: 'todo', roles: '' });
} else if (button.hasAttribute('data-wf-step-remove')) {
capture(root, s); s.editing.draft.steps.splice(Number(button.closest('[data-wf-edit-step]').dataset.wfEditStep), 1);
} else if (button.hasAttribute('data-wf-delete')) {
s.confirm = { scope, name };
} else if (button.hasAttribute('data-wf-delete-no')) {
s.confirm = null;
} else if (button.hasAttribute('data-wf-delete-yes')) {
button.disabled = true;
try {
await removeFlow(org, s, { scope, name, revision: s.data.revision });
s.confirm = null;
await reload(org, s, `Deleted ${name}.`);
} catch (error) { s.status = error.message; }
}
redraw(org);
});
// Every keystroke goes back into the draft, so any repaint draws what was typed.
document.addEventListener('input', ev => {
const form = ev.target.closest('[data-wf-editor]'), root = form?.closest('[data-workflows-org]');
if (form && root) { const st = states.get(root.dataset.workflowsOrg); if (st?.editing) capture(root, st); }
const field = ev.target.closest('[data-wf-edit-step] [name="roles"]');
if (!field) return;
const s = states.get(field.closest('[data-workflows-org]')?.dataset.workflowsOrg);
if (!s) return;
const missing = field.value.split(',').map(r => r.trim()).filter(r => r && !s.known.has(r));
// textContent and created nodes only: a typed name never becomes markup.
const note = field.closest('[data-wf-edit-step]').querySelector('[data-wf-step-missing]');
note.textContent = missing.length ? `${missing.join(', ')} ${MISSING}` : '';
});
document.addEventListener('submit', async ev => {
if (!ev.target.matches('[data-wf-editor]')) return;
ev.preventDefault();
const root = ev.target.closest('[data-workflows-org]'), org = root?.dataset.workflowsOrg, s = states.get(org);
if (!s?.editing) return;
capture(root, s);
const e = s.editing;
const draft = { ...e.draft, steps: e.draft.steps.map(st => ({ ...st, roles: rolesIn(st.roles) })) };
const why = refusal(s, { isNew: e.isNew, scope: e.scope, name: e.name, steps: draft.steps });
if (why) { s.status = why; redraw(org); return; }
const workflow = shape(draft);
const button = ev.target.querySelector('button[type="submit"]');
button.disabled = true;
try {
await saveFlow(org, s, { scope: e.scope, name: e.name, revision: e.revision ?? s.data.revision, workflow });
s.editing = null;
await reload(org, s, `Saved ${e.name}.`);
} catch (error) { s.status = error.message; }
redraw(org);
});
// ---------- SP9 (#1873): the read-only view ----------
// #/orgs/<id>/workflows lists the organization's workflows; #/orgs/<id>/workflows/<name>[?project=<p>]
// draws one as an inline-SVG graph. The data is the same read as the editor above: each step's title,
// state and roles, in file order. A workflow has no edges or branches in the file, so a step hands on to
// the next one. Nothing else is drawn: no gate, no inputs and no running mark, because no read gives them.
const WS = () => window.MosaicWorkspace;
const orgHash = org => `#/orgs/${encodeURIComponent(org)}`;
const flowHref = (org, scope, name, step) => {
const q = new URLSearchParams();
if (scope) q.set('project', scope);
if (step) q.set('step', String(step));
return `${orgHash(org)}/workflows/${encodeURIComponent(name)}${q.size ? `?${q}` : ''}`;
};
const stepsOf = w => (Array.isArray(w?.steps) ? w.steps.filter(st => st && typeof st === 'object') : []);
const rolesOf = st => (Array.isArray(st?.roles) ? st.roles.filter(r => typeof r === 'string') : []);
const count = n => `${n} step${n === 1 ? '' : 's'}`;
const stateLabel = st => STATE_LABEL[st?.state] ?? String(st?.state ?? '');
const scopeLabel = scope => (scope ? `Project ${scope}` : 'Organization');
// Each scope that holds a workflow, the organization first. Names are own keys only.
const listed = s => scopes(s).map(([scope, label, flows]) => [scope, label, Object.keys(plain(flows) ? flows : {}).sort().map(n => [n, flows[n]])]);
const total = s => listed(s).reduce((n, [, , rows]) => n + rows.length, 0);
// The organization's bus state from the membership list, and for one that is down the workspace read's
// reason in the Inbox's words (orgsOf + unreadNote, the data-ws-unread note).
async function orgOf(org) {
const list = await window.MosaicWorkspaceData.organizations().catch(() => null);
const row = Array.isArray(list) ? list.find(o => o?.id === org && !o.invalid) : null;
if (!row) return { row: null, list: Array.isArray(list) };
let unread = '';
if (!row.busHealthy) {
const body = await window.MosaicWorkspaceData.workspace({ org, sections: 'projects' }).catch(() => null);
const o = body ? WS().orgsOf({ orgs: (Array.isArray(body.orgs) ? body.orgs : []).filter(r => r?.org === org) }) : null;
unread = o?.unread.length ? WS().unreadNote(o, [], 'workflows')
: `<p class="note ws-unread-note" data-ws-unread>Not read: ${esc(row.label || org)} ${row.busStopped ? 'bus stopped' : 'bus not answering'}. No reason was read.</p>`;
}
return { row, unread, stopped: !row.busHealthy && row.busStopped === true, label: row.label || org };
}
const head = (title, sub) => `<div class="ws-vh"><h1 tabindex="-1">${title}</h1><p class="sub">${sub}</p></div>`;
const applyLink = (org, s) => (s?.data?.writable
? `<p><a class="ws-btn" href="${esc(`${orgHash(org)}/organization`)}" data-wfg-apply data-focus-key="wfg-apply">Apply a pack</a></p>`
: '<p class="note">A starter pack brings workflows. Only the owner, on a Console started with send, can apply one.</p>');
const none = (org, s, label) => `<p class="note" data-wfg-none>No workflows in ${esc(label)} yet.</p>${applyLink(org, s)}`;
// Layout: left to right on a wide screen, top to bottom on a narrow one. The graph scrolls inside its
// own frame when it is wider than the frame; the page never does.
const NARROW = '(max-width: 700px)';
const narrow = () => window.matchMedia(NARROW).matches;
// SP10 (sp9 follow-up): box text is fitted by its measured width in the font it is drawn in, not by a
// character count, so a line ends inside its box with an ellipsis and a short name shows whole. The clip
// path stays as a backstop. Without a canvas the old per-character estimate is used.
let ctx;
function measure(text, font, per) {
if (ctx === undefined) { try { ctx = document.createElement('canvas').getContext('2d'); } catch { ctx = null; } }
if (!ctx) return text.length * per;
ctx.font = font;
return ctx.measureText(text).width;
}
const token = (name, fallback) => getComputedStyle(document.documentElement).getPropertyValue(name).trim() || fallback;
const fonts = () => ({
title: [`600 15px ${token('--font', 'sans-serif')}`, 8.6],
roles: [`13px ${token('--mono', 'monospace')}`, 7.9],
miss: [`12px ${token('--font', 'sans-serif')}`, 6.8],
});
function fit(text, [font, per], max) {
if (measure(text, font, per) <= max) return text;
let lo = 0, hi = text.length;
while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (measure(`${text.slice(0, mid)}…`, font, per) <= max) lo = mid; else hi = mid - 1; }
return `${text.slice(0, lo)}…`;
}
// Up to two lines broken at spaces; the second ends in … when the title is longer.
function wrap(text, f, max) {
const words = String(text ?? '').split(/\s+/).filter(Boolean), lines = [''];
let over = false;
for (const w of words) {
const cur = lines[lines.length - 1], next = cur ? `${cur} ${w}` : w;
if (!cur || measure(next, f[0], f[1]) <= max) lines[lines.length - 1] = next;
else if (lines.length < 2) lines.push(w);
else { lines[1] = `${lines[1]} ${w}`; over = true; }
}
if (measure(lines[0], f[0], f[1]) > max) return [fit(lines[0], f, max)];
if (lines[1] && (over || measure(lines[1], f[0], f[1]) > max)) lines[1] = fit(lines[1], f, max);
return lines;
}
function graph(org, s, scope, name, steps, sel) {
const vertical = narrow(), f = fonts();
const W = vertical ? 300 : 188, GAP = vertical ? 32 : 36, PAD = 14;
// Text runs from x+12 and ends 12px before the box edge; 2px more absorbs a font that loads after the measure.
const room = W - 26;
// One role a line, at most three lines: with four or more, two roles and "+N more". Every role is in the label and the detail panel.
const roleLines = st => { const r = rolesOf(st); return !r.length ? [] : r.length <= 3 ? r : [...r.slice(0, 2), `+${r.length - 2} more`]; };
// A role that names no current role: "No current role:" and then each such role on its own line, at most
// two lines, so the whole name shows (a name longer than the box ends in …).
const missing = st => rolesOf(st).filter(r => !s.known.has(r));
const missLines = st => { const m = missing(st); return m.length <= 2 ? m : [m[0], `+${m.length - 1} more`]; };
const titleEnd = st => 46 + (wrap(st.title, f.title, room).length - 1) * 19;
const rolesY = st => titleEnd(st) + 24;
const missY = st => rolesY(st) + (Math.max(roleLines(st).length, 1) - 1) * 17 + 18;
// Each box is as tall as the tallest step needs: meta, one or two title lines, its role lines, and the missing-role lines if any.
const bottom = st => (missing(st).length ? missY(st) + missLines(st).length * 15 : missY(st) - 18);
const H = Math.max(...steps.map(st => bottom(st) + 16));
const pos = i => (vertical ? [PAD, PAD + i * (H + GAP)] : [PAD + i * (W + GAP), PAD]);
const width = vertical ? W + 2 * PAD : PAD * 2 + steps.length * W + (steps.length - 1) * GAP;
const height = vertical ? PAD * 2 + steps.length * H + (steps.length - 1) * GAP : H + 2 * PAD;
const edges = steps.slice(1).map((_, i) => {
const [x, y] = pos(i), [x2, y2] = pos(i + 1);
const d = vertical ? `M${x + W / 2} ${y + H} V${y2 - 3}` : `M${x + W} ${y + H / 2} H${x2 - 3}`;
return `<path class="wfg-edge" d="${d}" data-wfg-edge="${i + 1}-${i + 2}" marker-end="url(#wfg-arrow)"/>`;
}).join('');
const nodes = steps.map((st, i) => {
const [x, y] = pos(i), n = i + 1, roles = rolesOf(st), miss = missing(st);
const lines = wrap(st.title, f.title, room), on = sel === n;
const label = `Step ${n} of ${steps.length}: ${st.title ?? ''}. ${stateLabel(st)}. Roles ${roles.join(', ')}${miss.length ? `; ${miss.join(', ')} ${MISSING}` : ''}.`;
const rl = roleLines(st), more = roles.length > 3;
const roleText = rl.length
? rl.map((r, j) => `<tspan x="${x + 12}" dy="${j ? 17 : 0}"${more && j === rl.length - 1 ? ' data-wfg-more' : ''}>${esc(more && j === rl.length - 1 ? r : fit(r, f.roles, room))}</tspan>`).join('')
: '<tspan class="wfg-none">No roles recorded</tspan>';
const missText = miss.length
? `<text class="wfg-miss" data-wfg-missing x="${x + 12}" y="${y + missY(st)}"><tspan x="${x + 12}" dy="0">No current role:</tspan>${missLines(st).map((r, j) => `<tspan x="${x + 12}" dy="15"${miss.length > 2 && j === 1 ? ' data-wfg-more' : ''}>${esc(miss.length > 2 && j === 1 ? r : fit(r, f.miss, room))}</tspan>`).join('')}</text>`
: '';
return `<a class="wfg-node${on ? ' is-sel' : ''}" href="${esc(flowHref(org, scope, name, n))}" data-wfg-step="${n}" data-focus-key="${esc(`wfg-step:${n}`)}" aria-label="${esc(label)}"${on ? ' aria-current="step"' : ''}>
<title>${esc(`${st.title ?? ''}${roles.length ? ` (${roles.join(', ')})` : ''}`)}</title><rect x="${x}" y="${y}" width="${W}" height="${H}" rx="10"/>
<clipPath id="wfg-clip-${n}"><rect x="${x + 2}" y="${y}" width="${W - 10}" height="${H}"/></clipPath>
<g clip-path="url(#wfg-clip-${n})">
<text class="wfg-meta" x="${x + 12}" y="${y + 22}">${esc(fit(`Step ${n} · ${stateLabel(st)}`, f.miss, room))}</text>
<text class="wfg-title" data-wfg-title x="${x + 12}" y="${y + 46}">${lines.map((l, j) => `<tspan x="${x + 12}" dy="${j ? 19 : 0}">${esc(l)}${j < lines.length - 1 ? ' ' : ''}</tspan>`).join('')}</text>
<text class="wfg-roles" data-wfg-roles x="${x + 12}" y="${y + rolesY(st)}">${roleText}</text>
${missText}</g></a>`;
}).join('');
return `<svg class="wfg-graph${vertical ? ' is-vertical' : ''}" data-wfg-graph role="group" aria-label="${esc(`${count(steps.length)}, in order`)}" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
<defs><marker id="wfg-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto"><path class="wfg-arrow" d="M0 0L10 5L0 10z"/></marker></defs>${edges}${nodes}</svg>`;
}
// ---------- SP10 (#1873): editing a workflow in its graph ----------
// A change is held in the page, not written, until Save: the graph draws the pending workflow, the bar says
// Unsaved, and Save sends one POST with the revision the page read (saveFlow, the form's write). A refusal is
// shown in words and the pending change kept. The poll redraws from the pending workflow, never over it.
// When the file changes while a change is pending: if this workflow is as the page read it, the new revision
// is taken (a workflow write sets only this workflow, so nothing else is overwritten); if this workflow
// changed, the bar says so and offers Discard. Drafts live per organization until saved or discarded, and
// the organization-switch and restart guards ask before dropping one (hasDraft).
const drafts = new Map(), notes = new Map(), newForms = new Map();
const dkey = (org, scope, name) => JSON.stringify([org, scope, name]);
const norm = w => ({
title: typeof w?.title === 'string' ? w.title : '', description: typeof w?.description === 'string' ? w.description : '',
steps: stepsOf(w).map(st => ({ title: String(st.title ?? ''), state: st.state, roles: rolesOf(st) })),
});
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const changed = d => d.isNew || !same(d.flow, d.base);
const editDirty = e => !!e && !same({ title: e.title, state: e.state, roles: e.roles }, e.orig);
const READ_ONLY = 'Only the owner, on a Console started with send, can change workflows.';
// The graph's own words for a refusal where the form's would mislead: the change is kept, not lost.
const kept = {
'revision-conflict': 'Not saved: the organization file changed since this page read it. Your change is kept. Discard to load the current version.',
'organization-busy': 'Not saved: the organization is busy with another write. Your change is kept. Try Save again shortly.',
'no-bus-host': 'Not saved: the organization bus is not running. Your change is kept. Save again once it runs.',
'invalid-request': 'Not saved: the bus refused the workflow. Check each step has a title, a state and one to eight distinct roles. Your change is kept.',
};
const say = text => { const live = document.getElementById('announce'); if (live) { live.textContent = ''; live.textContent = text; } };
// A pending change measured against the fresh read; drops one with nothing left to keep.
function settle(org, s, scope, name, fresh) {
const key = dkey(org, scope, name), d = drafts.get(key);
if (!d) return null;
if (d.busy) return d;
const now = fresh ? norm(fresh) : null;
if (d.isNew) { d.stale = !!fresh; if (!fresh) d.revision = s.data.revision; }
else if (now && same(now, d.base)) { d.revision = s.data.revision; d.stale = false; }
else if (now && !changed(d)) {
Object.assign(d, { base: now, flow: structuredClone(now), revision: s.data.revision, stale: false });
if (d.edit?.mode === 'edit' && d.edit.i >= now.steps.length) d.edit = null;
} else d.stale = true;
if (!changed(d) && !d.edit && !d.confirm && !d.status) { drafts.delete(key); return null; }
return d;
}
function draftFor(org, s, scope, name) {
const key = dkey(org, scope, name);
if (drafts.has(key)) return drafts.get(key);
const fresh = flowsIn(s, scope)?.[name];
if (!fresh) return null;
const base = norm(fresh), d = { isNew: false, base, flow: structuredClone(base), revision: s.data.revision, edit: null, confirm: false, status: '', busy: false, stale: false };
drafts.set(key, d);
notes.delete(key);
return d;
}
// The role picker: human, the organization's roles, the role templates, and first any role the step names
// that resolves to none of those (checked and marked, so leaving it in is a choice the save check names).
function rolePick(s, chosen, prefix) {
const defs = [...(s.data.roles.definitions || [])].sort(), tpl = [...(s.data.roles.templates || [])].filter(r => !defs.includes(r)).sort();
const odd = chosen.filter(r => !s.known.has(r));
const box = (r, mark = '') => `<label class="wfg-pick"><input type="checkbox" name="role" value="${esc(r)}"${chosen.includes(r) ? ' checked' : ''} data-focus-key="${esc(`${prefix}:role:${r}`)}"> <code>${esc(r)}</code>${mark}</label>`;
const group = (title, list, mark) => (list.length ? `<p class="wfg-pick-h">${title}</p>${list.map(r => box(r, mark)).join('')}` : '');
return `<fieldset class="wfg-roles-pick" data-wfg-roles-pick><legend>Roles, one to eight</legend>
${group('Named in this step', odd, ` <span class="wf-missing" data-wfg-pick-missing>${MISSING}</span>`)}${box('human', ' <span class="muted">a person</span>')}
${group('This organization\'s roles', defs.filter(r => r !== 'human'), '')}${group('Role templates', tpl.filter(r => r !== 'human'), '')}</fieldset>`;
}
const stateSelect = (value, key) => `<label>State<select name="state" data-focus-key="${esc(key)}">${STATES.map(([v, l]) => `<option value="${v}"${value === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label>`;
function stepForm(org, s, scope, name, d) {
const e = d.edit, n = e.i + 1;
return `<form class="wfg-form" data-wfg-form data-live-key="${esc(`wfg-form:${org}:${scope}:${name}:${e.mode}:${e.i}`)}" data-live-hold novalidate>
<h2 data-wfg-form-title>${e.mode === 'add' ? `New step ${n}` : `Edit step ${n}`}</h2>
<label>Title<input name="title" maxlength="120" value="${esc(e.title)}" autocomplete="off" data-focus-key="wfg-f-title"></label>
${stateSelect(e.state, 'wfg-f-state')}${rolePick(s, e.roles, 'wfg-f')}
<p class="wfg-why" data-wfg-why>${esc(e.why ?? '')}</p>
<p class="wfg-form-acts"><button type="submit" class="ws-btn primary" data-wfg-apply data-focus-key="wfg-f-apply">${e.mode === 'add' ? 'Add step' : 'Apply'}</button> <button type="button" class="ws-btn" data-wfg-cancel data-focus-key="wfg-f-cancel">Cancel</button></p>
<p class="note">Apply changes the graph on this page. Save writes it to the organization file.</p></form>`;
}
function bar(org, s, scope, name, d) {
if (!s.data.writable) return `<p class="note wfg-ro" data-wfg-readonly>${READ_ONLY}</p>`;
const dirty = !!d && changed(d), busy = d?.busy ? ' disabled' : '';
const status = d?.status || notes.get(dkey(org, scope, name)) || '';
const stale = d?.stale ? `<p class="wfg-stale" data-wfg-stale>${d.isNew ? `A workflow named ${esc(name)} now exists here. Save will be refused. Discard to drop this one.` : 'The organization file changed this workflow since the page read it. Save will be refused. Discard to load the current version.'}</p>` : '';
const acts = d?.confirm
? `<span class="wfg-confirm" data-wfg-confirm>Delete ${esc(name)} from the organization file? <button type="button" class="ws-btn danger" data-wfg-delete-yes data-focus-key="wfg-delete-yes"${busy}>Delete workflow</button> <button type="button" class="ws-btn" data-wfg-delete-no data-focus-key="wfg-delete-no"${busy}>Keep</button></span>`
: `${dirty ? `<button type="button" class="ws-btn" data-wfg-discard data-focus-key="wfg-discard"${busy}>Discard</button> <button type="button" class="ws-btn primary" data-wfg-save data-focus-key="wfg-save"${busy}>${d.busy ? 'Saving…' : 'Save'}</button>` : ''}${d?.isNew ? '' : ` <button type="button" class="ws-btn danger" data-wfg-delete data-focus-key="wfg-delete"${busy}>Delete workflow</button>`}`;
return `<div class="wfg-bar${dirty ? ' is-dirty' : ''}" data-wfg-bar>${dirty ? `<span class="wfg-badge" data-wfg-unsaved>Unsaved${d.isNew ? ', not in the file yet' : ''}</span>` : ''}<span class="wfg-acts">${acts}</span>
${status ? `<p class="wfg-status" data-wfg-status>${esc(status)}</p>` : ''}${stale}</div>`;
}
const stepRef = (org, scope, name, steps, n) => `<a href="${esc(flowHref(org, scope, name, n))}" data-wfg-go="${n}">Step ${n}, ${esc(steps[n - 1].title)}</a>`;
function actions(steps, sel, d) {
const busy = d?.busy ? ' disabled' : '';
if (!sel) return `<p class="wfg-step-acts" data-wfg-actions><button type="button" class="ws-btn" data-wfg-add data-focus-key="wfg-add"${busy}>Add a step at the end</button></p>`;
const dis = c => (c || d?.busy ? ' disabled' : '');
return `<p class="wfg-step-acts" data-wfg-actions><button type="button" class="ws-btn" data-wfg-edit data-focus-key="wfg-edit"${busy}>Edit step</button>
<button type="button" class="ws-btn" data-wfg-add data-focus-key="wfg-add"${dis(steps.length >= 20)}>Add a step after</button>
<button type="button" class="ws-btn" data-wfg-up data-focus-key="wfg-up"${dis(sel === 1)}>Move earlier</button>
<button type="button" class="ws-btn" data-wfg-down data-focus-key="wfg-down"${dis(sel === steps.length)}>Move later</button>
<button type="button" class="ws-btn danger" data-wfg-remove data-focus-key="wfg-remove"${dis(steps.length === 1)}>Remove step</button></p>`;
}
function detail(org, s, scope, name, steps, sel, d) {
const writable = !!s.data.writable;
if (writable && d?.edit) return `<section class="panel wfg-detail" data-wfg-detail>${stepForm(org, s, scope, name, d)}</section>`;
if (!sel) return `<section class="panel wfg-detail" data-wfg-detail><h2>Step details</h2><p class="note">Select a step to see its roles, the state it puts a task in and the step it hands on to.</p>${writable ? actions(steps, 0, d) : ''}</section>`;
const st = steps[sel - 1], roles = rolesOf(st);
const roleList = roles.map(r => r === 'human' ? '<code>human</code> (a person)' : s.known.has(r) ? `<code>${esc(r)}</code>` : `<code>${esc(r)}</code> <span class="wf-missing" data-wfg-missing>${MISSING}</span>`).join(', ');
return `<section class="panel wfg-detail" data-wfg-detail><h2 data-wfg-detail-title>${esc(st.title)}</h2><dl class="wfg-dl">
<dt>Position</dt><dd data-wfg-field="position">Step ${sel} of ${steps.length}</dd>
<dt>Roles</dt><dd data-wfg-field="roles">${roleList || '<span class="muted">None recorded</span>'}</dd>
<dt>Puts the task in</dt><dd data-wfg-field="state">${esc(stateLabel(st))}</dd>
<dt>Comes after</dt><dd data-wfg-field="after">${sel > 1 ? stepRef(org, scope, name, steps, sel - 1) : 'Nothing: this is the first step'}</dd>
<dt>Hands on to</dt><dd data-wfg-field="next">${sel < steps.length ? stepRef(org, scope, name, steps, sel + 1) : 'Nothing: this is the last step'}</dd>
</dl>${writable ? actions(steps, sel, d) : ''}<p class="note">The workflow file records no gate or inputs for a step, and no read says which step a task is on now.</p></section>`;
}
function graphBody(org, s, name, q) {
const scope = q.get('project') || '';
if (scope && !Object.hasOwn(s.data.projects, scope)) return { title: esc(name), sub: '', body: `<p class="note" data-wfg-unknown>No code project named ${esc(scope)} in the organization file.</p>` };
const flows = flowsIn(s, scope), fresh = plain(flows) && Object.hasOwn(flows, name) ? flows[name] : null;
const d = s.data.writable ? settle(org, s, scope, name, fresh) : null;
const note = notes.get(dkey(org, scope, name));
if (!fresh && !d) return { title: esc(name), sub: '', body: `${note ? `<p class="wfg-status" data-wfg-status>${esc(note)}</p>` : ''}<p class="note" data-wfg-unknown>No workflow named ${esc(name)} in ${scope ? `project ${esc(scope)}` : 'the organization'}.</p>` };
const w = d ? d.flow : norm(fresh), steps = w.steps;
const raw = Number(q.get('step')), sel = Number.isInteger(raw) && raw >= 1 && raw <= steps.length ? raw : 0;
const sub = `${esc(scopeLabel(scope))}, <code>${esc(name)}</code>, ${count(steps.length)}.${w.description ? ` ${esc(w.description)}` : ''}`;
const body = steps.length
? `${bar(org, s, scope, name, d)}<div class="wfg-frame" data-wfg-frame>${graph(org, s, scope, name, steps, sel)}</div>${detail(org, s, scope, name, steps, sel, d)}`
: `${bar(org, s, scope, name, d)}<p class="note">This workflow has no steps.</p>`;
return { title: esc(w.title || name), sub, body };
}
// The list page's New workflow form: where, a name, and the first step. Create opens it in the graph, unsaved.
function newForm(org, s) {
const f = newForms.get(org);
if (!f) return `<p class="wfg-new"><button type="button" class="ws-btn" data-wfg-new data-focus-key="wfg-new">New workflow</button></p>`;
return `<form class="wfg-form wfg-newform panel" data-wfg-form data-wfg-newform data-live-key="${esc(`wfg-new:${org}`)}" data-live-hold novalidate>
<h2>New workflow</h2>
<label>Where<select name="scope" data-focus-key="wfg-n-scope">${scopes(s).map(([v, l]) => `<option value="${esc(v)}"${f.scope === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label>
<label>Name<input name="name" maxlength="64" value="${esc(f.name)}" autocomplete="off" placeholder="lowercase letters, digits, dashes" data-focus-key="wfg-n-name"></label>
<p class="note">${NAME_RULE}</p>
<h3>First step</h3>
<label>Title<input name="title" maxlength="120" value="${esc(f.title)}" autocomplete="off" data-focus-key="wfg-n-title"></label>
${stateSelect(f.state, 'wfg-n-state')}${rolePick(s, f.roles, 'wfg-n')}
<p class="wfg-why" data-wfg-why>${esc(f.why ?? '')}</p>
<p class="wfg-form-acts"><button type="submit" class="ws-btn primary" data-wfg-create data-focus-key="wfg-n-create">Create</button> <button type="button" class="ws-btn" data-wfg-new-cancel data-focus-key="wfg-n-cancel">Cancel</button></p>
<p class="note">Create opens it in its graph. It is written to the organization file when you save it there.</p></form>`;
}
// The rows each scope lists: the file's workflows, and any new one not saved yet.
function rowsWithDrafts(org, s) {
return listed(s).map(([scope, label, rows]) => {
const names = new Set(rows.map(([n]) => n));
const fresh = [...drafts.entries()].map(([k, d]) => [JSON.parse(k), d]).filter(([[o, sc, n], d]) => o === org && sc === scope && d.isNew && !names.has(n)).map(([[, , n], d]) => [n, d.flow]);
return [scope, label, [...rows, ...fresh].sort(([p], [q]) => (p < q ? -1 : p > q ? 1 : 0))];
});
}
function listBody(org, s, label) {
const writable = !!s.data.writable, rows = writable ? rowsWithDrafts(org, s) : listed(s);
const top = `${notes.has(dkey(org, '', '')) ? `<p class="wfg-status" data-wfg-status>${esc(notes.get(dkey(org, '', '')))}</p>` : ''}${writable ? newForm(org, s) : `<p class="note wfg-ro" data-wfg-readonly>${READ_ONLY}</p>`}`;
if (!rows.some(([, , r]) => r.length)) return `${top}${none(org, s, label)}`;
return top + rows.filter(([scope, , r]) => !scope || r.length).map(([scope, label2, r]) => `<section class="wfg-scope" data-wfg-scope-list="${esc(scope)}"><h2>${esc(label2)}</h2>${r.length ? `<ul class="wfg-list">${r.map(([name, w]) => {
const steps = stepsOf(w), d = drafts.get(dkey(org, scope, name)), pending = d && changed(d);
return `<li class="wfg-item" data-wfg-item="${esc(name)}" data-wfg-scope="${esc(scope)}"><div class="wfg-item-h"><a href="${esc(flowHref(org, scope, name))}" data-wfg-open data-focus-key="${esc(`wfg-open:${scope}:${name}`)}">${esc(w?.title || name)}</a>${w?.title ? ` <code>${esc(name)}</code>` : ''} <span class="muted">${count(steps.length)}</span>${pending ? ` <span class="wfg-badge" data-wfg-unsaved>Unsaved${d.isNew ? ', not in the file yet' : ''}</span>` : ''}</div>
${w?.description ? `<p class="wfg-desc">${esc(w.description)}</p>` : ''}<ol class="wfg-chain" data-wfg-chain aria-label="Steps in order">${steps.map(st => `<li>${esc(st.title)}</li>`).join('')}</ol></li>`;
}).join('')}</ul>` : '<p class="note">None at the organization level.</p>'}</section>`).join('');
}
// The page for #/orgs/<org>/workflows (name null) or #/orgs/<org>/workflows/<name>. page() reads; compose()
// draws from what was read, so an edit on the page redraws at once (paint) without waiting for a read.
const shown = { org: null, name: null, info: null };
function compose(org, name, q, info) {
const attr = name === null ? 'data-wfg-list' : 'data-wfg-page';
const wrapIt = (title, sub, body) => `<article class="ws wfg" ${attr} data-wfg-org="${esc(org)}"${name === null ? '' : ` data-wfg-name="${esc(name)}"`}>${head(title, sub)}${info.unread}${body}</article>`;
// Review P3: a change held for this organization that the page cannot draw now is said to be kept.
const held = [...drafts].filter(([k, d]) => JSON.parse(k)[0] === org && (changed(d) || editDirty(d.edit))).map(([k]) => JSON.parse(k)[2]);
const keptNote = held.length ? `<p class="note" data-wfg-held>Unsaved change to ${held.map(n => esc(n)).join(', ')} is kept on this page. It comes back when the workflows can be read.</p>` : '';
// E2E6 P2-8: a stopped bus is not read; the note above says why.
if (info.stopped) return wrapIt(name === null ? 'Workflows' : esc(name), `Workflows in ${esc(info.label)}.`, keptNote);
const s = states.get(org);
if (!s?.data) return wrapIt(name === null ? 'Workflows' : esc(name), `Workflows in ${esc(info.label)}.`, `<p class="note" data-wfg-error>${esc(s?.error ?? 'Workflows could not be read.')}</p>${keptNote}`);
if (name === null) return wrapIt('Workflows', `The steps a task goes through in ${esc(info.label)}, in order, with the roles that do each.${s.data.writable ? ' Open one to change it.' : ''}`, listBody(org, s, info.label));
const g = graphBody(org, s, name, q);
return wrapIt(g.title, g.sub, g.body);
}
async function page(org, name, q) {
const info = await orgOf(org);
if (!info.row) return `<article class="ws wfg" ${name === null ? 'data-wfg-list' : 'data-wfg-page'} data-wfg-org="${esc(org)}">${head('Organization unavailable', info.list ? 'This organization is not on your list.' : 'The organization list could not be read.')}</article>`;
if (!info.stopped) await load(org);
Object.assign(shown, { org, name, info });
return compose(org, name, q, info);
}
const query = () => new URLSearchParams(location.hash.split('?')[1] || '');
// Redraw the open workflow page from the page's state, then put focus on `focus` (a data-focus-key).
function paint(focus) {
const el = document.querySelector('#bus-view [data-wfg-list], #bus-view [data-wfg-page]');
if (!el || !shown.info || el.dataset.wfgOrg !== shown.org || (el.dataset.wfgName ?? null) !== shown.name) return;
el.outerHTML = compose(shown.org, shown.name, query(), shown.info);
const el2 = focus && document.querySelector(`#bus-view [data-focus-key="${CSS.escape(focus)}"]`);
if (!el2) return;
el2.focus();
// A text field takes focus with the caret after its text, ready to change it.
if (el2.matches('input:not([type=checkbox])')) el2.setSelectionRange(el2.value.length, el2.value.length);
}
// The open graph page: its organization, scope, name, read and pending change.
function here(el) {
const root = el.closest('[data-wfg-page]');
if (!root || root.dataset.wfgOrg !== shown.org) return null;
const org = shown.org, name = shown.name, scope = query().get('project') || '', s = states.get(org);
if (!s?.data?.writable) return null;
return { org, name, scope, s, key: dkey(org, scope, name) };
}
const selected = () => { const n = Number(query().get('step')); return Number.isInteger(n) && n > 0 ? n : 0; };
const select = step => WS()?.setQuery?.({ step: step || null }, false);
function openForm(d, mode, i, st) {
const roles = st ? [...st.roles] : [];
d.edit = { mode, i, title: st?.title ?? '', state: st?.state ?? 'todo', roles, why: '', orig: { title: st?.title ?? '', state: st?.state ?? 'todo', roles: [...roles] } };
}
function readForm(form, into) {
into.title = form.elements.title.value;
into.state = form.elements.state.value;
into.roles = [...form.querySelectorAll('input[name="role"]:checked')].map(i => i.value);
if (form.elements.scope) into.scope = form.elements.scope.value;
if (form.elements.name) into.name = form.elements.name.value.trim();
}
function why(form, into, text) {
into.why = text;
// Direct text: the form may be the held node a repaint grafted back.
const p = form.querySelector('[data-wfg-why]');
if (p) p.textContent = text;
say(text);
}
document.addEventListener('click', async ev => {
const btn = ev.target.closest('[data-wfg-new],[data-wfg-new-cancel],[data-wfg-edit],[data-wfg-add],[data-wfg-up],[data-wfg-down],[data-wfg-remove],[data-wfg-cancel],[data-wfg-discard],[data-wfg-save],[data-wfg-delete],[data-wfg-delete-no],[data-wfg-delete-yes]');
if (!btn || btn.disabled) return;
if (btn.matches('[data-wfg-new],[data-wfg-new-cancel]')) {
const org = btn.closest('[data-wfg-list]')?.dataset.wfgOrg;
if (!org || org !== shown.org) return;
if (btn.hasAttribute('data-wfg-new')) { newForms.set(org, { scope: '', name: '', title: '', state: 'todo', roles: [], why: '' }); notes.delete(dkey(org, '', '')); paint('wfg-n-name'); }
else { newForms.delete(org); paint('wfg-new'); }
return;
}
const at = here(btn);
if (!at) return;
const { org, name, scope, s, key } = at;
const sel = selected();
if (btn.hasAttribute('data-wfg-discard')) {
const d = drafts.get(key);
drafts.delete(key);
if (d?.isNew) { location.hash = `${orgHash(org)}/workflows`; return; }
say(`Discarded the change to ${name}.`);
return paint('wfg-delete');
}
if (btn.hasAttribute('data-wfg-save')) return save(at, btn);
if (btn.matches('[data-wfg-delete-yes]')) return remove(at);
const d = draftFor(org, s, scope, name) ?? drafts.get(key);
if (!d) return;
d.status = '';
const steps = d.flow.steps;
if (btn.hasAttribute('data-wfg-edit') && steps[sel - 1]) { openForm(d, 'edit', sel - 1, steps[sel - 1]); return paint('wfg-f-title'); }
if (btn.hasAttribute('data-wfg-add')) { openForm(d, 'add', sel ? sel : steps.length, null); return paint('wfg-f-title'); }
if (btn.hasAttribute('data-wfg-cancel')) { const back = d.edit?.mode === 'edit' ? d.edit.i + 1 : sel; d.edit = null; select(back); return paint(back ? `wfg-step:${back}` : 'wfg-add'); }
if (btn.matches('[data-wfg-up],[data-wfg-down]') && steps[sel - 1]) {
const to = btn.hasAttribute('data-wfg-up') ? sel - 1 : sel + 1;
if (to < 1 || to > steps.length) return;
[steps[sel - 1], steps[to - 1]] = [steps[to - 1], steps[sel - 1]];
select(to);
say(`Moved step ${sel} to position ${to}.`);
const key2 = btn.hasAttribute('data-wfg-up') ? (to > 1 ? 'wfg-up' : 'wfg-down') : (to < steps.length ? 'wfg-down' : 'wfg-up');
return paint(key2);
}
if (btn.hasAttribute('data-wfg-remove') && steps[sel - 1] && steps.length > 1) {
const [gone] = steps.splice(sel - 1, 1);
const next = Math.min(sel, steps.length);
select(next);
say(`Removed step ${sel}, ${gone.title}.`);
return paint(`wfg-step:${next}`);
}
if (btn.hasAttribute('data-wfg-delete')) { d.confirm = true; return paint('wfg-delete-no'); }
if (btn.hasAttribute('data-wfg-delete-no')) { d.confirm = false; return paint('wfg-delete'); }
});
async function save({ org, name, scope, s, key }) {
const d = drafts.get(key);
if (!d || d.busy) return;
// Review P2: the open step form's edits are not in the workflow yet; saving now would drop them unsaid.
const refused = (editDirty(d.edit) ? `Not saved: step ${d.edit.i + 1} has edits not applied. Apply or cancel the step first.` : '')
|| refusal(s, { isNew: d.isNew, scope, name, steps: d.flow.steps });
if (refused) { d.status = refused; say(refused); return paint('wfg-save'); }
d.busy = true; d.status = 'Saving…'; paint();
try {
await saveFlow(org, s, { scope, name, revision: d.revision, workflow: shape(d.flow) });
drafts.delete(key);
notes.set(key, `Saved ${name}.`);
try { await read(org, states.get(org) ?? s); } catch { /* the next poll reads it */ }
say(`Saved ${name}.`);
paint(selected() ? `wfg-step:${selected()}` : 'wfg-delete');
} catch (error) {
d.busy = false;
d.status = kept[error.code] ?? `Not saved: ${error.message} Your change is kept.`;
say(d.status);
paint('wfg-save');
}
}
async function remove({ org, name, scope, s, key }) {
const d = drafts.get(key);
if (!d || d.busy) return;
d.busy = true; paint();
try {
// The revision of the workflow the page shows (settle moves it on only while this workflow is unchanged):
// a change made to it since is refused, not deleted over.
await removeFlow(org, s, { scope, name, revision: d.revision });
drafts.delete(key);
notes.set(dkey(org, '', ''), `Deleted ${name}.`);
say(`Deleted ${name}.`);
try { await read(org, s); } catch { /* the next poll reads it */ }
location.hash = `${orgHash(org)}/workflows`;
} catch (error) {
d.busy = false; d.confirm = false;
// Recheck B: Discard shows only with a pending change; without one the next read draws the current version.
d.status = error.code === 'revision-conflict' ? `Not deleted: the organization file changed this workflow since the page read it. ${changed(d) ? 'Discard to load the current version.' : 'The page shows the current version at its next read.'}` : `Not deleted: ${error.message}`;
say(d.status);
paint('wfg-delete');
}
}
// Every change in a form goes into the page's state at once, so any repaint draws what was entered.
document.addEventListener('input', ev => {
const form = ev.target.closest('[data-wfg-form]');
if (!form) return;
if (form.matches('[data-wfg-newform]')) { const f = newForms.get(shown.org); if (f) readForm(form, f); return; }
const at = here(form), d = at && drafts.get(at.key);
if (d?.edit) readForm(form, d.edit);
});
document.addEventListener('submit', ev => {
const form = ev.target.closest?.('[data-wfg-form]');
if (!form) return;
ev.preventDefault();
if (form.matches('[data-wfg-newform]')) {
const org = shown.org, s = states.get(org), f = newForms.get(org);
if (!f || !s?.data?.writable) return;
readForm(form, f);
const step = { title: f.title, state: f.state, roles: f.roles };
const refused = refusal(s, { isNew: true, scope: f.scope, name: f.name, steps: [step] })
|| (drafts.get(dkey(org, f.scope, f.name))?.isNew ? `A new workflow named ${f.name} is already open here, not saved yet.` : '');
if (refused) return why(form, f, refused);
drafts.set(dkey(org, f.scope, f.name), { isNew: true, base: null, flow: { title: '', description: '', steps: [{ ...step, title: step.title.trim() }] }, revision: s.data.revision, edit: null, confirm: false, status: '', busy: false, stale: false });
newForms.delete(org);
notes.delete(dkey(org, f.scope, f.name));
location.hash = flowHref(org, f.scope, f.name, 1);
return;
}
const at = here(form), d = at && drafts.get(at.key);
if (!d?.edit) return;
readForm(form, d.edit);
const e = d.edit, st = { title: e.title.trim(), state: e.state, roles: e.roles };
const refused = stepRefusal(st, e.i + 1);
if (refused) return why(form, e, refused);
if (e.mode === 'add') d.flow.steps.splice(e.i, 0, st); else d.flow.steps[e.i] = st;
d.edit = null; d.status = '';
select(e.i + 1);
say(`${e.mode === 'add' ? 'Added' : 'Changed'} step ${e.i + 1}. Not saved yet.`);
paint('wfg-save');
});
// Escape in a step form is Cancel.
document.addEventListener('keydown', ev => {
if (ev.key !== 'Escape') return;
const form = ev.target.closest?.('[data-wfg-form]:not([data-wfg-newform])');
form?.querySelector('[data-wfg-cancel]')?.click();
});
// The organization-switch and restart guards (display.js, console-restart.js) ask before these are lost.
function hasDraft() {
return [...drafts.values()].some(d => changed(d) || editDirty(d.edit))
|| [...newForms.values()].some(f => f.name || f.title.trim() || f.roles.length);
}
function forget() { drafts.clear(); newForms.clear(); }
// The organization page's card: each workflow as a link to its graph, from the page's one workflow read.
function card(org, { stopped = false, label = org } = {}) {
const all = `<a href="${esc(`${orgHash(org)}/workflows`)}" data-wfg-all data-focus-key="wfg-all">All workflows</a>`;
const h = note => `<div class="ws-sec-h"><h2>Workflows</h2>${note ? `<span class="note">${note}</span>` : ''}${all}</div>`;
if (stopped) return `<div class="wfg-card" data-wfg-card data-bus-stopped>${h('')}<p class="ws-panel tight note">Not read: the bus is stopped.</p></div>`;
const s = states.get(org);
if (!s?.data) return `<div class="wfg-card" data-wfg-card>${h('')}<p class="ws-panel tight note" data-wfg-error>${esc(s?.error ?? 'Workflows could not be read.')}</p></div>`;
const rows = listed(s).flatMap(([scope, , list]) => list.map(([name, w]) => [scope, name, w]));
if (!rows.length) return `<div class="wfg-card" data-wfg-card>${h('none')}<div class="ws-panel tight">${none(org, s, label)}</div></div>`;
return `<div class="wfg-card" data-wfg-card>${h(String(rows.length))}<ul class="ws-panel tight wfg-cardlist">${rows.map(([scope, name, w]) => `<li><a href="${esc(flowHref(org, scope, name))}" data-wfg-card-item data-focus-key="${esc(`wfg-card:${scope}:${name}`)}"><strong>${esc(w?.title || name)}</strong> <span class="muted">${count(stepsOf(w).length)}${scope ? `, project ${esc(scope)}` : ''}</span></a></li>`).join('')}</ul></div>`;
}
// A step box or a step link in the details selects that step in the address (setQuery repaints).
document.addEventListener('click', ev => {
const link = ev.target.closest('[data-wfg-step],[data-wfg-go]');
if (link && WS()?.setQuery && ev.button === 0 && !ev.metaKey && !ev.ctrlKey && !ev.shiftKey && !ev.altKey) {
ev.preventDefault();
WS().setQuery({ step: link.dataset.wfgStep ?? link.dataset.wfgGo });
return;
}
// Apply a pack: the pack picker on the organization page, scrolled into view.
const apply = ev.target.closest('[data-wfg-apply]');
if (!apply || ev.button !== 0 || ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return;
const show = () => { const p = document.querySelector('[data-packs]'); if (!p) return false; p.scrollIntoView({ block: 'start' }); return true; };
if (location.hash === apply.getAttribute('href') && show()) { ev.preventDefault(); return; }
const until = Date.now() + 8000;
const wait = () => { if (location.hash === apply.getAttribute('href') && document.querySelector('[data-org-dashboard] [data-packs]')) setTimeout(show, 0); else if (Date.now() < until) setTimeout(wait, 60); };
setTimeout(wait, 60);
});
// Crossing the narrow breakpoint redraws the graph in the other direction.
window.matchMedia(NARROW).addEventListener('change', () => {
if (document.querySelector('[data-wfg-graph]')) document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
});
window.MosaicWorkflows = { load, section, page, card, hasDraft, forget };
})();