Files
stack/packages/webui/src/public/workflows.js
T
jason.woltje a88302d6eb feat(webui): triage drawer, the instance owner opens Triage from the top bar and reads its state, health and transcript, and sends a message when the route allows it; nobody else gets the entry, the markup or a request (#1873, lane triage-drawer)
The drawer reads GET /api/triage only while open. A poll keeps the draft and the reader's scroll place.
Every field is set as text. Cards show the command with no Run button, and the dropped count.
The send box shows only when config triageSend and the read's send are both true. It names each
answer in plain words, never resends, and keeps the draft after a refusal.
Workflows: Save with only the state changed in an add form says the step is not added yet and keeps
the form. The step picker no longer offers the system-only triage template.
2026-11-16 14:36:07 -06:00

830 lines
62 KiB
JavaScript

// Starter packs SP6 (#1873, design section 8): an organization's workflows. 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.
// SP17: the graph page is the one editor. The organization page's old form editor is gone; its card links to
// each workflow and each step, and a step's panel is its edit form with Save.
(() => {
'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);
// #1873: the templates no organization may hold (organization vocabulary SYSTEM_ONLY). The read may still
// list them; a step role never resolves to one and the picker never offers one.
const SYSTEM_ONLY = ['triage'];
const offered = list => (list || []).filter(r => !SYSTEM_ONLY.includes(r));
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 || []), ...offered(value.roles.templates), 'human']);
}
// SP17: a write in flight holds the poll. Each organization counts its writes (epoch moves when one starts
// and when it ends); a read that began before a write ended, or answers while one is in flight, is dropped
// and the page keeps what it has, which the write's answer brings up to date (written()).
const writes = new Map();
const writeState = org => { if (!writes.has(org)) writes.set(org, { epoch: 0, inflight: 0 }); return writes.get(org); };
async function writing(org, fn) {
const w = writeState(org);
w.epoch++; w.inflight++;
try { return await fn(); } finally { w.inflight--; w.epoch++; }
}
async function load(org) {
const prev = states.get(org), w = writeState(org), began = w.epoch;
const s = { data: null, known: new Set(), error: null };
const raced = () => !!prev?.data && (w.inflight > 0 || w.epoch !== began);
try { await read(org, s); if (raced()) return; } catch (error) {
if (raced()) return;
// Review P3: a failed poll while a change to this organization's workflows is held keeps the last good
// read, so the page still draws the change and its form, and graftLive puts the held form and focus back.
// SP17: the failure is still said; the page draws the last read under that line.
if (prev?.data && held(org).length) Object.assign(s, { data: prev.data, known: prev.known, readError: error.message });
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 flowsIn = (s, scope) => scope ? s.data.projects[scope] : s.data.workflows;
const target = (s, scope) => scope ? { project: scope } : {};
// SP10: the save check. A step is {title, state, roles: [names]}. The order of the checks: 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.
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) });
// ---------- 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 pending = d => !!d && (changed(d) || editDirty(d.edit));
// The steps as the graph draws them: the pending workflow with the open step's edit as typed.
const preview = d => {
const e = d?.edit;
if (!d) return null;
if (e?.mode !== 'edit' || !d.flow.steps[e.i] || !editDirty(e)) return d.flow.steps;
return d.flow.steps.map((st, j) => (j === e.i ? { title: e.title.trim() || st.title, state: e.state, roles: [...e.roles] } : st));
};
// The names of this organization's workflows with a change held on the page.
const heldKeys = org => [...drafts].filter(([k, d]) => JSON.parse(k)[0] === org && pending(d)).map(([k]) => JSON.parse(k).slice(1));
const held = org => heldKeys(org).map(([, name]) => name);
// The organization card's word for a held change (a bus stop or restart keeps it): each held workflow
// links back to its page, where the change is as typed.
const heldCardNote = org => {
const keys = heldKeys(org);
if (!keys.length) return '';
return `<p class="ws-panel tight note" data-wfg-held>Unsaved change kept on this page: ${keys.map(([scope, name]) => `<a href="${esc(flowHref(org, scope, name))}" data-wfg-held-link data-focus-key="${esc(`wfg-held:${scope}:${name}`)}">${esc(name)}${scope ? ` (project ${esc(scope)})` : ''}</a>`).join(', ')}.</p>`;
};
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) && !(d.edit?.mode === 'edit' && editDirty(d.edit) && !same(now.steps[d.edit.i], d.base.steps[d.edit.i]))) {
// Only other parts changed: take them. A typed step whose step changed elsewhere is stale below instead.
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.edit.mode === 'edit' && !editDirty(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, off = false) {
const defs = [...(s.data.roles.definitions || [])].sort(), tpl = offered(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${off ? ' disabled' : ''}><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, off = false) => `<label>State<select name="state" data-focus-key="${esc(key)}"${off ? ' disabled' : ''}>${STATES.map(([v, l]) => `<option value="${v}"${value === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label>`;
// A new step's form: Add step puts it in the graph on this page, unsaved.
function addForm(org, s, scope, name, d) {
const e = d.edit, n = e.i + 1;
return `<form class="wfg-form" data-wfg-form data-wfg-add-form data-live-key="${esc(`wfg-form:${org}:${scope}:${name}:add:${e.i}`)}" data-live-hold novalidate>
<h2 data-wfg-form-title>New 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-add-step data-focus-key="wfg-f-add">Add step</button> <button type="button" class="ws-btn" data-wfg-cancel data-focus-key="wfg-f-cancel">Cancel</button></p>
<p class="note">Add step puts it in the graph on this page. Save writes the workflow to the organization file.</p></form>`;
}
// SP17: the Save inside a panel form. It saves the whole workflow, the open step's edit with it.
// The line that says what Save did or why it did not: next to Save, wherever Save is. A refused delete
// (d.atBar) is said in the bar, next to Delete workflow.
const statusOf = (org, scope, name, d) => d?.status || notes.get(dkey(org, scope, name)) || '';
const formStatus = (org, scope, name, d) => (d?.atBar ? '' : statusOf(org, scope, name, d));
const statusLine = text => (text ? `<p class="wfg-status" data-wfg-status>${esc(text)}</p>` : '');
const saveButton = d => {
const busy = !!d?.busy, on = pending(d) && !busy;
return `<button type="button" class="ws-btn primary" data-wfg-save data-focus-key="wfg-save"${on ? '' : ' disabled'}>${busy ? 'Saving…' : 'Save'}</button>`;
};
// SP17: a selected step's panel is its edit form. It shows the step as the page holds it, or the edit typed
// into it, and holds its node across a repaint only once it differs from the step (data-live-hold).
function editForm(org, s, scope, name, steps, sel, d) {
const i = sel - 1, st = steps[i], e = d?.edit?.mode === 'edit' && d.edit.i === i ? d.edit : null;
const v = e ?? { title: st.title, state: st.state, roles: rolesOf(st), why: '' }, dirty = editDirty(e), off = !!d?.busy;
return `<form class="wfg-form wfg-stepform" data-wfg-form data-wfg-step-form="${i}" data-live-key="${esc(`wfg-form:${org}:${scope}:${name}:edit:${i}`)}"${dirty ? ' data-live-hold' : ''} novalidate aria-label="${esc(`Step ${sel}`)}">
<label>Title<input name="title" maxlength="120" value="${esc(v.title)}" autocomplete="off" data-focus-key="wfg-f-title"${off ? ' disabled' : ''}></label>
${stateSelect(v.state, 'wfg-f-state', off)}${rolePick(s, v.roles, 'wfg-f', off)}
<p class="wfg-why" data-wfg-why>${esc(v.why ?? '')}</p>
<p class="wfg-form-acts">${saveButton(d)} <button type="button" class="ws-btn" data-wfg-cancel data-focus-key="wfg-f-cancel"${dirty ? '' : ' hidden'}>Reset step</button></p>${statusLine(formStatus(org, scope, name, d))}</form>`;
}
// SP17: with no step selected, the panel edits the workflow's title and description, which the old
// organization-page form did. Each change goes into the pending workflow at once.
function metaForm(org, s, scope, name, d, w) {
return `<form class="wfg-form wfg-metaform" data-wfg-form data-wfg-meta-form data-live-key="${esc(`wfg-meta:${org}:${scope}:${name}`)}"${pending(d) ? ' data-live-hold' : ''} novalidate aria-label="Workflow">
<label>Title<input name="title" maxlength="120" value="${esc(w.title)}" autocomplete="off" data-focus-key="wfg-m-title"${d?.busy ? ' disabled' : ''}></label>
<label>Description<textarea name="description" maxlength="1000" rows="2" data-focus-key="wfg-m-desc"${d?.busy ? ' disabled' : ''}>${esc(w.description)}</textarea></label>
<p class="wfg-form-acts">${saveButton(d)}</p>${statusLine(formStatus(org, scope, name, d))}</form>`;
}
// `inPanel`: the panel shows a form with its own Save, so the bar does not repeat it.
function bar(org, s, scope, name, d, inPanel) {
if (!s.data.writable) return `<p class="note wfg-ro" data-wfg-readonly>${READ_ONLY}</p>`;
const dirty = pending(d), busy = d?.busy ? ' disabled' : '';
// With a panel form, the status sits with that form's Save instead.
const status = inPanel ? (d?.atBar ? d.status : '') : statusOf(org, scope, name, d);
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>${inPanel ? '' : ` <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>
${statusLine(status)}${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-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, w) {
const writable = !!s.data.writable;
if (writable && d?.edit?.mode === 'add') return `<section class="panel wfg-detail" data-wfg-detail>${addForm(org, s, scope, name, d)}</section>`;
if (!sel) {
return writable
? `<section class="panel wfg-detail" data-wfg-detail><h2>This workflow</h2>${metaForm(org, s, scope, name, d, w)}<p class="note">Select a step in the graph to change it.</p>${actions(steps, 0, d)}</section>`
: `<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></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(', ');
const fields = writable ? '' : `
<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>`;
return `<section class="panel wfg-detail" data-wfg-detail><h2 data-wfg-detail-title>${esc(st.title)}</h2>${writable ? editForm(org, s, scope, name, steps, sel, d) : ''}<dl class="wfg-dl">
<dt>Position</dt><dd data-wfg-field="position">Step ${sel} of ${steps.length}</dd>${fields}
<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;
if (d && !d.busy) park(d, sel - 1);
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, !!s.data.writable && d?.edit?.mode !== 'add')}<div class="wfg-frame" data-wfg-frame>${graph(org, s, scope, name, d ? preview(d) : steps, sel)}</div>${detail(org, s, scope, name, steps, sel, d, w)}`
: `${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 names = held(org), s = states.get(org);
const keptNote = !names.length ? '' : s?.readError && s.data
? `<p class="note" data-wfg-error>The last workflows read failed: ${esc(s.readError.replace(/\.$/, ''))}. The page shows the read before it.</p><p class="note" data-wfg-held>Unsaved change to ${names.map(n => esc(n)).join(', ')} is kept on this page.</p>`
: `<p class="note" data-wfg-held>Unsaved change to ${names.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);
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}`);
const lastRead = s.readError ? 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.' : ''}`, lastRead + listBody(org, s, info.label));
const g = graphBody(org, s, name, q);
return wrapIt(g.title, g.sub, lastRead + 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);
}
// SP17: the selected step's form, its edit (made at the first change) and its message line.
const stepFormEl = () => document.querySelector('#bus-view [data-wfg-page] [data-wfg-step-form]');
// The open step edit carried into the pending workflow: '' when there was nothing to carry or it went in,
// or the reason it cannot (the edit is kept and the form says why).
function carry(d) {
const e = d?.edit;
if (!e || e.mode !== 'edit') return '';
if (!editDirty(e)) { d.edit = null; return ''; }
const st = { title: e.title.trim(), state: e.state, roles: [...e.roles] };
const refused = stepRefusal(st, e.i + 1);
if (refused) { const form = stepFormEl(); if (form) why(form, e, refused); else { e.why = refused; say(refused); } return refused; }
d.flow.steps[e.i] = st; d.edit = null;
return '';
}
// SP17 review: an open edit of a step other than the one shown (a card step link, the address or Back opened
// another step) goes into the pending workflow as typed, never dropped. A step the save check refuses is then
// named by Save, which checks every step.
function park(d, i) {
const e = d?.edit;
if (!e || e.mode !== 'edit' || e.i === i) return;
if (editDirty(e) && d.flow.steps[e.i]) d.flow.steps[e.i] = { title: e.title.trim(), state: e.state, roles: [...e.roles] };
d.edit = null;
}
// SP17 review: while a Save or delete is in flight the form's fields take no typing, so nothing typed then is
// dropped when the answer redraws the form. Drawn off when busy; a held form (data-live-hold) is set here.
const lockForms = off => document.querySelectorAll('#bus-view [data-wfg-page] :is([data-wfg-step-form],[data-wfg-meta-form])').forEach(f =>
f.querySelectorAll('input[name="title"],textarea,select,[data-wfg-roles-pick]').forEach(c => { c.disabled = off; }));
const toAddTitle = () => document.querySelector('#bus-view [data-wfg-page] [data-wfg-add-form] input[name="title"]')?.focus();
// Put focus back in the step form's title after a refusal (the form may be a held node).
const toTitle = () => { const f = stepFormEl()?.elements.title; if (f) { f.focus(); f.setSelectionRange(f.value.length, f.value.length); } };
document.addEventListener('click', async ev => {
const btn = ev.target.closest('[data-wfg-new],[data-wfg-new-cancel],[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);
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 = ''; d.atBar = false;
const steps = d.flow.steps;
if (btn.hasAttribute('data-wfg-cancel')) {
// The new step's Cancel goes back to the step it was opened from; the step form's Reset puts the step back.
if (d.edit?.mode === 'edit') { d.edit = null; say(`Step ${sel} is back as the page holds it.`); return paint('wfg-f-title'); }
d.edit = null; select(sel); return paint(sel ? 'wfg-f-title' : 'wfg-add');
}
// Moving, adding or removing a step takes the open step's edit with it first.
if (carry(d)) return toTitle();
if (btn.hasAttribute('data-wfg-add')) { openForm(d, 'add', sel ? sel : steps.length, null); return paint('wfg-f-title'); }
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'); }
});
// SP17: the page's read brought up to date from a write's answer: the workflow as sent (or gone) and the
// revision the write answered. Without a revision in the answer the page reads the file again.
async function written(org, s, scope, name, workflow, answer) {
const now = states.get(org) ?? s, flows = now.data ? flowsIn(now, scope) : null;
if (plain(flows) && typeof answer?.revision === 'string' && /^[0-9a-f]{64}$/.test(answer.revision)) {
if (workflow) flows[name] = workflow; else delete flows[name];
now.data.revision = answer.revision;
return;
}
try { await read(org, now); } catch { /* the next poll reads it */ }
}
async function save({ org, name, scope, s, key }) {
const d = drafts.get(key);
if (!d || d.busy) return;
// SP17 review: a new step typed in the add form is not saved over or dropped: Save says so and keeps the
// form. So is one in which only the state was changed. An add form left as it opened is closed and the
// rest is saved.
if (d.edit?.mode === 'add') {
if (d.edit.title.trim() || d.edit.roles.length || editDirty(d.edit)) {
d.atBar = false; d.status = `Not saved: new step ${d.edit.i + 1} is not added yet. Press Add step, or Cancel to drop it.`;
say(d.status); paint(); return toAddTitle();
}
d.edit = null;
}
// SP17: the open step's edit goes in with the save; one the save check refuses stays in its form.
const unfit = carry(d);
d.atBar = false;
if (unfit) { d.status = `Not saved: ${unfit}`; say(d.status); paint(); return toTitle(); }
const refused = refusal(s, { isNew: d.isNew, scope, name, steps: d.flow.steps });
if (refused) { d.status = refused; say(refused); return paint('wfg-save'); }
if (!changed(d)) return paint();
d.busy = true; d.status = 'Saving…'; paint(); lockForms(true);
try {
const workflow = shape(d.flow);
await writing(org, async () => written(org, s, scope, name, workflow, await saveFlow(org, s, { scope, name, revision: d.revision, workflow })));
drafts.delete(key);
notes.set(key, `Saved ${name}.`);
say(`Saved ${name}.`);
// Focus stays in the form it was saved from, so the line saying Saved stays in view (at 390 a jump to the
// graph node put it below the fold).
paint(selected() ? 'wfg-f-title' : 'wfg-m-title');
} catch (error) {
d.busy = false;
d.status = kept[error.code] ?? `Not saved: ${error.message} Your change is kept.`;
say(d.status);
paint('wfg-save'); lockForms(false);
}
}
async function remove({ org, name, scope, s, key }) {
const d = drafts.get(key);
if (!d || d.busy) return;
d.busy = true; paint(); lockForms(true);
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 writing(org, async () => written(org, s, scope, name, null, await removeFlow(org, s, { scope, name, revision: d.revision })));
drafts.delete(key);
notes.set(dkey(org, '', ''), `Deleted ${name}.`);
say(`Deleted ${name}.`);
location.hash = `${orgHash(org)}/workflows`;
} catch (error) {
d.busy = false; d.confirm = false; d.atBar = true;
// 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'); lockForms(false);
}
}
// SP17: after a change in a panel form, the bar and the form's own buttons follow it without redrawing the
// form, so the caret stays where it is.
function follow(at, d, form) {
const old = document.querySelector('#bus-view [data-wfg-page] [data-wfg-bar]');
if (old) old.outerHTML = bar(at.org, at.s, at.scope, at.name, d, true);
const save = form.querySelector('[data-wfg-save]');
if (save) save.disabled = !pending(d) || !!d.busy;
form.querySelector('[data-wfg-cancel]')?.toggleAttribute('hidden', !editDirty(d.edit));
form.toggleAttribute('data-live-hold', form.matches('[data-wfg-step-form]') ? editDirty(d.edit) : pending(d));
// A status from before this change no longer applies.
const text = formStatus(at.org, at.scope, at.name, d), line = form.querySelector('[data-wfg-status]');
if (line && !text) line.remove(); else if (line) line.textContent = text;
// The graph draws the step as typed, so the box shows the change before Save.
const frame = document.querySelector('#bus-view [data-wfg-page] [data-wfg-frame]');
if (frame && form.matches('[data-wfg-step-form]')) frame.innerHTML = graph(at.org, at.s, at.scope, at.name, preview(d), Number(form.dataset.wfgStepForm) + 1);
}
// 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);
if (!at) return;
if (form.matches('[data-wfg-add-form]')) { const d = drafts.get(at.key); if (d?.edit) readForm(form, d.edit); return; }
const d = draftFor(at.org, at.s, at.scope, at.name) ?? drafts.get(at.key);
if (!d || d.busy) return;
d.status = ''; d.atBar = false;
if (form.matches('[data-wfg-meta-form]')) {
d.flow.title = form.elements.title.value;
d.flow.description = form.elements.description.value;
return follow(at, d, form);
}
const i = Number(form.dataset.wfgStepForm);
if (!(d.edit?.mode === 'edit' && d.edit.i === i)) { if (!d.flow.steps[i]) return; park(d, i); openForm(d, 'edit', i, d.flow.steps[i]); }
readForm(form, d.edit);
follow(at, d, form);
});
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);
if (!at) return;
// Enter in the step or workflow form is its Save.
if (!form.matches('[data-wfg-add-form]')) { if (!form.querySelector('[data-wfg-save]')?.disabled) save(at); return; }
const d = 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);
d.flow.steps.splice(e.i, 0, st);
d.edit = null; d.status = '';
select(e.i + 1);
say(`Added step ${e.i + 1}. Not saved yet.`);
paint('wfg-save');
});
// Escape in a step form is its Cancel or Reset.
document.addEventListener('keydown', ev => {
if (ev.key !== 'Escape') return;
const form = ev.target.closest?.('[data-wfg-add-form],[data-wfg-step-form]');
const b = form?.querySelector('[data-wfg-cancel]');
if (b && !b.hidden) b.click();
});
// The organization-switch and restart guards (display.js, console-restart.js) ask before these are lost.
function hasDraft() {
return [...drafts.values()].some(pending)
|| [...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, and under it each step as a link to
// that step's form (SP17), 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>`;
const heldNote = heldCardNote(org);
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>${heldNote}</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>${heldNote}</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>${heldNote}</div>`;
const stepLinks = (scope, name, w) => {
const steps = stepsOf(w);
if (!steps.length) return '';
return `<ol class="wfg-card-steps" aria-label="${esc(`Steps of ${w?.title || name}`)}">${steps.map((st, i) => `<li><a href="${esc(flowHref(org, scope, name, i + 1))}" data-wfg-card-step="${i + 1}" data-focus-key="${esc(`wfg-card:${scope}:${name}:${i + 1}`)}" aria-label="${esc(`Change step ${i + 1}, ${st.title ?? ''}`)}">${esc(st.title)}</a></li>`).join('')}</ol>`;
};
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>${stepLinks(scope, name, w)}</li>`).join('')}</ul>${heldNote}</div>`;
}
// SP17: a step link on the card lands in that step's title field, ready to type (bus.js asks landed() after
// the page it opens is drawn, in place of focusing the heading).
let landing = null;
function landed() {
const want = landing;
landing = null;
if (!want || location.hash !== want) return false;
const form = stepFormEl(), f = form?.elements.title;
if (!f) return false;
// The title and the Save under it both in view (at 390 Save was below the fold), the title winning on a short screen.
f.focus({ preventScroll: true });
form.querySelector('[data-wfg-save]')?.scrollIntoView({ block: 'nearest' });
f.scrollIntoView({ block: 'nearest' });
f.setSelectionRange(f.value.length, f.value.length);
say(`Step ${Number(form.dataset.wfgStepForm) + 1}, ${f.value}. Change it and press Save.`);
return true;
}
document.addEventListener('click', ev => {
if (ev.button !== 0 || ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return;
const cardStep = ev.target.closest('[data-wfg-card-step]');
if (cardStep) { landing = cardStep.getAttribute('href'); return; }
// A step box or a step link in the details selects that step in the address (setQuery repaints). The open
// step's edit goes into the pending workflow first; one the save check refuses keeps the step selected.
const link = ev.target.closest('[data-wfg-step],[data-wfg-go]');
if (link && WS()?.setQuery) {
ev.preventDefault();
const at = here(link), d = at && drafts.get(at.key);
if (d && carry(d)) return toTitle();
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('a[data-wfg-apply]');
if (!apply) 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'));
});
// section(): the organization page's old form editor is gone (SP17); workspace.js still asks for it.
const section = () => '';
window.MosaicWorkflows = { load, section, page, card, hasDraft, forget, landed };
})();