diff --git a/packages/webui/src/public/bus.js b/packages/webui/src/public/bus.js index 9b50d15d8..b546af884 100644 --- a/packages/webui/src/public/bus.js +++ b/packages/webui/src/public/bus.js @@ -1949,6 +1949,8 @@ if (k) restore(k); // Message on the Board (row 95) lands in the form it opened, addressed to the role. else if (focusSend && $('send-body')) { $('send-body').focus(); announce(`Message to ${draft.to}`); } + // SP17: a step link on an organization's Workflows card lands in that step's title field. + else if (navigated && window.MosaicWorkflows?.landed?.()) { /* landed() focused the field and said so */ } else if (navigated && h1) { const target=settingsFocusDisclosure&&path.startsWith('/settings/') ? $('settings-disclosure') : path.startsWith('/settings/') ? ($('settings-page-title')||h1) : h1; settingsFocusDisclosure=false; target.focus(); announce(target.textContent); } focusSend = false; window.MosaicWorkspace?.afterPaint?.(); diff --git a/packages/webui/src/public/packs.css b/packages/webui/src/public/packs.css index bc8894180..92d57fbd2 100644 --- a/packages/webui/src/public/packs.css +++ b/packages/webui/src/public/packs.css @@ -1,22 +1,19 @@ [data-packs],[data-workflows]{margin-top:16px} -:is(.pack-list,.pack-hires,.wf-list){list-style:none;margin:8px 0;padding:0} -:is(.pack-row,.pack-hire,.wf-item){border-top:1px solid var(--border);padding:12px 0;overflow-wrap:anywhere} +.pack-list,.pack-hires{list-style:none;margin:8px 0;padding:0} +.pack-row,.pack-hire{border-top:1px solid var(--border);padding:12px 0;overflow-wrap:anywhere} .pack-preview{border:1px solid var(--border);border-radius:var(--r);padding:12px;margin:12px 0;overflow-wrap:anywhere} .pack-preview .ws-tbl{overflow-x:auto} /* E2E6 P2-3: the preview's overflow-wrap:anywhere let the table squeeze words ("Workfl ow"). Cells wrap at word breaks; only a path, which has none, may break anywhere. */ .pack-preview .ws-tbl :is(td,th){overflow-wrap:normal;word-break:normal} .pack-preview .ws-tbl td code{overflow-wrap:anywhere} -.pack-nohire,.wf-missing,.wf-note{color:var(--danger)} +.pack-nohire,.wf-missing{color:var(--danger)} .wf-missing{font-size:.9em} -.wf-steps{margin:6px 0;padding-left:22px}.wf-steps li{margin:4px 0} -.wf-editor{display:grid;gap:12px;margin:12px 0} -.wf-step{border:1px solid var(--border);border-radius:var(--r);padding:12px;display:grid;gap:10px;min-width:0} -:is(.wf-editor,[data-packs]) label{display:flex;flex-direction:column;gap:6px;min-width:0} -:is(.wf-editor,[data-packs]) :is(select,input,textarea){width:100%;box-sizing:border-box;min-height:44px;padding:8px 12px;border:1px solid var(--border);border-radius:var(--r);background:var(--canvas);color:var(--text);font:inherit} -:is([data-packs],[data-workflows]) .btn{min-height:44px;margin:4px 8px 4px 0} -:is([data-packs],[data-workflows]) :is(button,select,input,textarea):focus-visible{outline:2px solid var(--focus);outline-offset:2px} -:is([data-packs],[data-workflows]) [role=status]{overflow-wrap:anywhere} +[data-packs] label{display:flex;flex-direction:column;gap:6px;min-width:0} +[data-packs] :is(select,input,textarea){width:100%;box-sizing:border-box;min-height:44px;padding:8px 12px;border:1px solid var(--border);border-radius:var(--r);background:var(--canvas);color:var(--text);font:inherit} +[data-packs] .btn{min-height:44px;margin:4px 8px 4px 0} +[data-packs] :is(button,select,input,textarea):focus-visible{outline:2px solid var(--focus);outline-offset:2px} +[data-packs] [role=status]{overflow-wrap:anywhere} .pack-applied{border-left:3px solid var(--border);padding:4px 0 4px 12px;margin:8px 0} .pack-applied p{margin:0 0 6px} .pack-open{list-style:none;margin:6px 0 8px;padding:0} diff --git a/packages/webui/src/public/workflows.css b/packages/webui/src/public/workflows.css index 44fa603dc..f3ec8867b 100644 --- a/packages/webui/src/public/workflows.css +++ b/packages/webui/src/public/workflows.css @@ -52,14 +52,23 @@ .wfg-cardlist a{display:block;padding:8px 0;color:var(--text);text-decoration:none;overflow-wrap:anywhere} .wfg-cardlist a:hover strong{text-decoration:underline} .wfg-cardlist strong{color:var(--action,var(--accent))} +/* SP17: each step of a workflow as a link to its form, under the workflow's link. */ +.wfg-cardlist .wfg-card-steps{list-style:none;display:flex;flex-wrap:wrap;gap:2px 0;margin:-4px 0 0;padding:0 0 8px;font-size:13px} +.wfg-cardlist .wfg-card-steps li{display:inline-flex;align-items:center;border:0} +.wfg-cardlist .wfg-card-steps li+li::before{content:"\2192";color:var(--muted);padding:0 6px} +.wfg-cardlist .wfg-card-steps a{display:inline-block;padding:4px 0;color:var(--action,var(--accent));text-decoration:underline;text-decoration-color:color-mix(in srgb,currentColor 40%,transparent);text-underline-offset:2px} +.wfg-cardlist .wfg-card-steps a:hover{text-decoration-color:currentColor} .wfg-card [data-wfg-none]{margin:0 0 8px} .wfg-card p:last-child{margin-bottom:0} -/* SP10 (#1873): editing a workflow in its graph. The bar above the graph holds Unsaved, Discard, Save and - Delete workflow; the step panel holds the step actions and the step form; the list page holds New workflow. */ +/* SP10 (#1873): editing a workflow in its graph. The bar above the graph holds Unsaved, Discard and Delete + workflow; the step panel holds the step's form with Save (SP17) and the step actions; the list page holds + New workflow. */ html[data-organizations] :is(.wfg-bar,.wfg-step-acts,.wfg-form,.wfg-new) .ws-btn{min-height:32px} html[data-organizations] :is(.wfg-bar,.wfg-form) .ws-btn.primary{background:var(--action);color:var(--onAction);border-color:var(--action)} html[data-organizations] :is(.wfg-bar,.wfg-form) .ws-btn.primary:hover:not(:disabled){background:color-mix(in srgb,var(--action) 88%,var(--strong))} +/* SP17 shots: a Save with nothing to save reads as off, not as the action colour. */ +html[data-organizations] :is(.wfg-bar,.wfg-form) .ws-btn.primary:disabled{background:var(--raised);color:var(--muted);border-color:var(--line)} html[data-organizations] :is(.wfg-bar,.wfg-step-acts) .ws-btn.danger{color:var(--danger)} html[data-organizations] :is(.wfg-bar,.wfg-step-acts,.wfg-form,.wfg-new) .ws-btn:focus-visible{outline:2px solid var(--focus);outline-offset:2px} .wfg-bar{display:flex;flex-wrap:wrap;align-items:center;gap:8px 12px;margin:0 0 10px} @@ -75,6 +84,11 @@ html[data-organizations] :is(.wfg-bar,.wfg-step-acts,.wfg-form,.wfg-new) .ws-btn .wfg-form h2{margin:0} .wfg-form h3{font-size:14px;margin:6px 0 0} .wfg-form>label,.wfg-form label:has(>select){display:grid;gap:4px;font-size:13px;color:var(--muted)} +.wfg-form [hidden]{display:none!important} +.wfg-form textarea{font:14px/1.4 var(--font);color:var(--text);background:var(--canvas);border:1px solid var(--line);border-radius:6px;padding:6px 8px;min-width:0;max-width:100%;resize:vertical} +.wfg-form>label:has(>textarea){display:grid;gap:4px;font-size:13px;color:var(--muted)} +.wfg-form textarea:focus-visible{outline:2px solid var(--focus);outline-offset:1px} +.wfg-stepform,.wfg-metaform{margin:0 0 14px} .wfg-form input:not([type=checkbox]),.wfg-form select{font:14px/1.4 var(--font);color:var(--text);background:var(--canvas);border:1px solid var(--line);border-radius:6px;padding:6px 8px;min-width:0;max-width:100%} .wfg-form :is(input,select):focus-visible{outline:2px solid var(--focus);outline-offset:1px} .wfg-form .note{margin:0} diff --git a/packages/webui/src/public/workflows.js b/packages/webui/src/public/workflows.js index d9fb0e295..2447e3240 100644 --- a/packages/webui/src/public/workflows.js +++ b/packages/webui/src/public/workflows.js @@ -1,9 +1,11 @@ -// Starter packs SP6 (#1873, design section 8): the owner's workflow list and editor on an -// organization's page. GET /api/orgs//workflows reads the org's and each code project's workflows -// with the file revision; a save is POST .../workflows/ {revision, workflow, project?} and a delete -// DELETE .../workflows/ {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. +// Starter packs SP6 (#1873, design section 8): an organization's workflows. GET /api/orgs//workflows reads +// the org's and each code project's workflows with the file revision; a save is POST .../workflows/ +// {revision, workflow, project?} and a delete DELETE .../workflows/ {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 => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); @@ -44,91 +46,37 @@ 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. + // 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); - 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 }); + 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 roleChip = (s, role) => s.known.has(role) - ? `${esc(role)}` - : `${esc(role)} ${MISSING}`; - function stepItem(s, step) { - const roles = Array.isArray(step?.roles) ? step.roles : []; - return `
  • ${esc(step?.title)} ${esc(STATE_LABEL[step?.state] ?? step?.state)} ${roles.map(r => roleChip(s, r)).join(', ')}
  • `; - } - 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 - ? `

    Delete this workflow?

    ` - : `

    `; - return `
  • ${esc(w?.title || name)} ${esc(name)} - ${w?.description ? `

    ${esc(w.description)}

    ` : ''}
      ${steps.map(st => stepItem(s, st)).join('')}
    ${actions}
  • `; - } - 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 `
    Step ${i + 1} - - - -

    ${missing.length ? `${missing.map(r => `${esc(r)}`).join(', ')} ${MISSING}` : ''}

    -
    `; - } - function editor(s) { - const e = s.editing; - if (!e) return ''; - const scopeField = e.isNew - ? `` - : `

    ${e.scope ? `Project ${esc(e.scope)}` : 'Organization'}, ${esc(e.name)}

    `; - return `

    ${e.isNew ? 'New workflow' : 'Edit workflow'}

    ${scopeField} - - - ${e.draft.steps.map((st, i) => stepRow(s, st, i)).join('')} -

    -

    Roles name an organization role, a role template, or human.

    `; - } - function section(org) { - const s = states.get(org); - if (!s || s.error) return `

    Workflows

    ${esc(s?.error ?? 'Workflows could not be read.')}

    `; - const lists = scopes(s).map(([scope, label, flows]) => { - const names = Object.keys(flows || {}).sort(); - return `

    ${esc(label)}

    ${names.length ? `
      ${names.map(n => workflowItem(org, s, scope, n, flows[n])).join('')}
    ` : '

    No workflows.

    '}
    `; - }).join(''); - const add = s.data.writable ? (s.editing ? '' : `

    `) : '

    Only the owner, on a Console started with send, can change workflows.

    '; - return `

    Workflows

    A workflow lists the steps a task goes through, the state each step puts it in and the roles that do it.

    ${lists}${add}${editor(s)}

    ${esc(s.status)}

    `; - } - 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); + // 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.`; @@ -157,74 +105,6 @@ // 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//workflows lists the organization's workflows; #/orgs//workflows/[?project=

    ] // draws one as an inline-SVG graph. The data is the same read as the editor above: each step's title, @@ -373,6 +253,24 @@ 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 `

    Unsaved change kept on this page: ${keys.map(([scope, name]) => `${esc(name)}${scope ? ` (project ${esc(scope)})` : ''}`).join(', ')}.

    `; + }; 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 = { @@ -391,11 +289,12 @@ 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)) { + 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.confirm && !d.status) { drafts.delete(key); return null; } + 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) { @@ -410,58 +309,94 @@ } // 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) { + function rolePick(s, chosen, prefix, off = false) { 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 = '') => ``; const group = (title, list, mark) => (list.length ? `

    ${title}

    ${list.map(r => box(r, mark)).join('')}` : ''); - return `
    Roles, one to eight + return `
    Roles, one to eight ${group('Named in this step', odd, ` ${MISSING}`)}${box('human', ' a person')} ${group('This organization\'s roles', defs.filter(r => r !== 'human'), '')}${group('Role templates', tpl.filter(r => r !== 'human'), '')}
    `; } - const stateSelect = (value, key) => ``; - function stepForm(org, s, scope, name, d) { + const stateSelect = (value, key, off = false) => ``; + // 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 `
    -

    ${e.mode === 'add' ? `New step ${n}` : `Edit step ${n}`}

    + return ` +

    New step ${n}

    ${stateSelect(e.state, 'wfg-f-state')}${rolePick(s, e.roles, 'wfg-f')}

    ${esc(e.why ?? '')}

    -

    -

    Apply changes the graph on this page. Save writes it to the organization file.

    `; +

    +

    Add step puts it in the graph on this page. Save writes the workflow to the organization file.

    `; } - function bar(org, s, scope, name, d) { + // 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 ? `

    ${esc(text)}

    ` : ''); + const saveButton = d => { + const busy = !!d?.busy, on = pending(d) && !busy; + return ``; + }; + // 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 `
    + + ${stateSelect(v.state, 'wfg-f-state', off)}${rolePick(s, v.roles, 'wfg-f', off)} +

    ${esc(v.why ?? '')}

    +

    ${saveButton(d)}

    ${statusLine(formStatus(org, scope, name, d))}
    `; + } + // 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 `
    + + +

    ${saveButton(d)}

    ${statusLine(formStatus(org, scope, name, d))}
    `; + } + // `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 `

    ${READ_ONLY}

    `; - const dirty = !!d && changed(d), busy = d?.busy ? ' disabled' : ''; - const status = d?.status || notes.get(dkey(org, scope, name)) || ''; + 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 ? `

    ${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.'}

    ` : ''; const acts = d?.confirm ? `Delete ${esc(name)} from the organization file? ` - : `${dirty ? ` ` : ''}${d?.isNew ? '' : ` `}`; + : `${dirty ? `${inPanel ? '' : ` `}` : ''}${d?.isNew ? '' : ` `}`; return `
    ${dirty ? `Unsaved${d.isNew ? ', not in the file yet' : ''}` : ''}${acts} - ${status ? `

    ${esc(status)}

    ` : ''}${stale}
    `; + ${statusLine(status)}${stale}`; } const stepRef = (org, scope, name, steps, n) => `Step ${n}, ${esc(steps[n - 1].title)}`; function actions(steps, sel, d) { const busy = d?.busy ? ' disabled' : ''; if (!sel) return `

    `; const dis = c => (c || d?.busy ? ' disabled' : ''); - return `

    - + return `

    `; } - function detail(org, s, scope, name, steps, sel, d) { + function detail(org, s, scope, name, steps, sel, d, w) { const writable = !!s.data.writable; - if (writable && d?.edit) return `
    ${stepForm(org, s, scope, name, d)}
    `; - if (!sel) return `

    Step details

    Select a step to see its roles, the state it puts a task in and the step it hands on to.

    ${writable ? actions(steps, 0, d) : ''}
    `; + if (writable && d?.edit?.mode === 'add') return `
    ${addForm(org, s, scope, name, d)}
    `; + if (!sel) { + return writable + ? `

    This workflow

    ${metaForm(org, s, scope, name, d, w)}

    Select a step in the graph to change it.

    ${actions(steps, 0, d)}
    ` + : `

    Step details

    Select a step to see its roles, the state it puts a task in and the step it hands on to.

    `; + } const st = steps[sel - 1], roles = rolesOf(st); const roleList = roles.map(r => r === 'human' ? 'human (a person)' : s.known.has(r) ? `${esc(r)}` : `${esc(r)} ${MISSING}`).join(', '); - return `

    ${esc(st.title)}

    -
    Position
    Step ${sel} of ${steps.length}
    + const fields = writable ? '' : `
    Roles
    ${roleList || 'None recorded'}
    -
    Puts the task in
    ${esc(stateLabel(st))}
    +
    Puts the task in
    ${esc(stateLabel(st))}
    `; + return `

    ${esc(st.title)}

    ${writable ? editForm(org, s, scope, name, steps, sel, d) : ''}
    +
    Position
    Step ${sel} of ${steps.length}
    ${fields}
    Comes after
    ${sel > 1 ? stepRef(org, scope, name, steps, sel - 1) : 'Nothing: this is the first step'}
    Hands on to
    ${sel < steps.length ? stepRef(org, scope, name, steps, sel + 1) : 'Nothing: this is the last step'}
    ${writable ? actions(steps, sel, d) : ''}

    The workflow file records no gate or inputs for a step, and no read says which step a task is on now.

    `; @@ -475,9 +410,10 @@ if (!fresh && !d) return { title: esc(name), sub: '', body: `${note ? `

    ${esc(note)}

    ` : ''}

    No workflow named ${esc(name)} in ${scope ? `project ${esc(scope)}` : 'the organization'}.

    ` }; 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))}, ${esc(name)}, ${count(steps.length)}.${w.description ? ` ${esc(w.description)}` : ''}`; const body = steps.length - ? `${bar(org, s, scope, name, d)}
    ${graph(org, s, scope, name, steps, sel)}
    ${detail(org, s, scope, name, steps, sel, d)}` + ? `${bar(org, s, scope, name, d, !!s.data.writable && d?.edit?.mode !== 'add')}
    ${graph(org, s, scope, name, d ? preview(d) : steps, sel)}
    ${detail(org, s, scope, name, steps, sel, d, w)}` : `${bar(org, s, scope, name, d)}

    This workflow has no steps.

    `; return { title: esc(w.title || name), sub, body }; } @@ -524,15 +460,17 @@ const attr = name === null ? 'data-wfg-list' : 'data-wfg-page'; const wrapIt = (title, sub, body) => `
    ${head(title, sub)}${info.unread}${body}
    `; // 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 ? `

    Unsaved change to ${held.map(n => esc(n)).join(', ')} is kept on this page. It comes back when the workflows can be read.

    ` : ''; + const names = held(org), s = states.get(org); + const keptNote = !names.length ? '' : s?.readError && s.data + ? `

    The last workflows read failed: ${esc(s.readError.replace(/\.$/, ''))}. The page shows the read before it.

    Unsaved change to ${names.map(n => esc(n)).join(', ')} is kept on this page.

    ` + : `

    Unsaved change to ${names.map(n => esc(n)).join(', ')} is kept on this page. It comes back when the workflows can be read.

    `; // 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)}.`, `

    ${esc(s?.error ?? 'Workflows could not be read.')}

    ${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 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, g.body); + return wrapIt(g.title, g.sub, lastRead + g.body); } async function page(org, name, q) { const info = await orgOf(org); @@ -582,8 +520,39 @@ 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-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]'); + 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; @@ -603,15 +572,20 @@ say(`Discarded the change to ${name}.`); return paint('wfg-delete'); } - if (btn.hasAttribute('data-wfg-save')) return save(at, btn); + 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.status = ''; d.atBar = false; 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-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.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; @@ -631,56 +605,109 @@ 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; - // 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 }); + // SP17 review: a new step typed in the add form is not saved over or dropped: Save says so and keeps the + // form. An add form with nothing typed in it is closed and the rest is saved. + if (d.edit?.mode === 'add') { + if (d.edit.title.trim() || d.edit.roles.length) { + 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'); } - d.busy = true; d.status = 'Saving…'; paint(); + if (!changed(d)) return paint(); + d.busy = true; d.status = 'Saving…'; paint(); lockForms(true); try { - await saveFlow(org, s, { scope, name, revision: d.revision, workflow: shape(d.flow) }); + 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}.`); - try { await read(org, states.get(org) ?? s); } catch { /* the next poll reads it */ } say(`Saved ${name}.`); - paint(selected() ? `wfg-step:${selected()}` : 'wfg-delete'); + // 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'); + 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(); + 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 removeFlow(org, s, { scope, name, revision: d.revision }); + 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}.`); - try { await read(org, s); } catch { /* the next poll reads it */ } location.hash = `${orgHash(org)}/workflows`; } catch (error) { - d.busy = false; d.confirm = false; + 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'); + 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), d = at && drafts.get(at.key); - if (d?.edit) readForm(form, d.edit); + 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]'); @@ -700,52 +727,87 @@ location.hash = flowHref(org, f.scope, f.name, 1); return; } - const at = here(form), d = at && drafts.get(at.key); + 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); - if (e.mode === 'add') d.flow.steps.splice(e.i, 0, st); else d.flow.steps[e.i] = st; + d.flow.steps.splice(e.i, 0, st); d.edit = null; d.status = ''; select(e.i + 1); - say(`${e.mode === 'add' ? 'Added' : 'Changed'} step ${e.i + 1}. Not saved yet.`); + say(`Added step ${e.i + 1}. Not saved yet.`); paint('wfg-save'); }); - // Escape in a step form is Cancel. + // 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-form]:not([data-wfg-newform])'); - form?.querySelector('[data-wfg-cancel]')?.click(); + 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(d => changed(d) || editDirty(d.edit)) + 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, from the page's one workflow read. + // 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 = `All workflows`; const h = note => `

    Workflows

    ${note ? `${note}` : ''}${all}
    `; - if (stopped) return `
    ${h('')}

    Not read: the bus is stopped.

    `; + const heldNote = heldCardNote(org); + if (stopped) return `
    ${h('')}

    Not read: the bus is stopped.

    ${heldNote}
    `; const s = states.get(org); - if (!s?.data) return `
    ${h('')}

    ${esc(s?.error ?? 'Workflows could not be read.')}

    `; + if (!s?.data) return `
    ${h('')}

    ${esc(s?.error ?? 'Workflows could not be read.')}

    ${heldNote}
    `; const rows = listed(s).flatMap(([scope, , list]) => list.map(([name, w]) => [scope, name, w])); - if (!rows.length) return `
    ${h('none')}
    ${none(org, s, label)}
    `; - return `
    ${h(String(rows.length))}
    `; + if (!rows.length) return `
    ${h('none')}
    ${none(org, s, label)}
    ${heldNote}
    `; + const stepLinks = (scope, name, w) => { + const steps = stepsOf(w); + if (!steps.length) return ''; + return `
      ${steps.map((st, i) => `
    1. ${esc(st.title)}
    2. `).join('')}
    `; + }; + return `
    ${h(String(rows.length))}${heldNote}
    `; + } + // 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; } - // A step box or a step link in the details selects that step in the address (setQuery repaints). 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.button === 0 && !ev.metaKey && !ev.ctrlKey && !ev.shiftKey && !ev.altKey) { + 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('[data-wfg-apply]'); - if (!apply || ev.button !== 0 || ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return; + 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; @@ -756,5 +818,7 @@ 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 }; + // 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 }; })(); diff --git a/packages/webui/tests/org-live-edit-browser.test.mjs b/packages/webui/tests/org-live-edit-browser.test.mjs index 5287a60e7..eb9728467 100644 --- a/packages/webui/tests/org-live-edit-browser.test.mjs +++ b/packages/webui/tests/org-live-edit-browser.test.mjs @@ -1,6 +1,7 @@ // E2E6 P1-1, P2-2 (#1873): an editor in use on an organization's page survives the page's refresh. The -// workflow editor's node, typed draft and focus, the autonomy form's unsaved choice and a pack's picked -// project are kept when the page reads every section again. An apply refreshes the other sections. +// autonomy form's unsaved choice and a pack's picked project are kept when the page reads every section +// again. An apply refreshes the other sections. SP17: the workflow editor is the graph page's step form +// now (the organization page's old form is gone); its node, typed step and focus survive the poll there. import test from 'node:test'; import assert from 'node:assert/strict'; import { startServer } from '../src/serve.mjs'; @@ -54,9 +55,9 @@ async function fixture(t) { await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/acme/organization`); // poll: wait for the page's own 10-second poll. Otherwise send the event a write on the page sends, // which repaints /organization the same way. - const refresh = async ({ poll = false } = {}) => { + const refresh = async ({ poll = false, event = 'mosaic-org-changed' } = {}) => { const n = counts.workflows; - if (!poll) await b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-org-changed',{detail:{org:'acme'}}));true`); + if (!poll) await b.evaluate(`document.dispatchEvent(new CustomEvent(${JSON.stringify(event)},{detail:{org:'acme'}}));true`); for (let i = 0; i < 500 && counts.workflows === n; i++) await new Promise(r => setTimeout(r, 30)); assert.ok(counts.workflows > n, 'the refresh read the workflows again'); await b.evaluate(`new Promise(r=>setTimeout(()=>r(true),200))`); @@ -64,29 +65,39 @@ async function fixture(t) { return { b, counts, ctl, refresh }; } -test('E2E6 P1-1: an open workflow editor keeps its node, draft and focus across a refresh', { timeout: 60000 }, async t => { - const { b, refresh } = await fixture(t); - await waitFor(b, `document.querySelector('[data-wf="intake"] [data-wf-edit]')`, 'workflow list'); - await b.evaluate(`document.querySelector('[data-wf="intake"] [data-wf-edit]').click();true`); - await waitFor(b, `document.querySelector('[data-wf-editor]')`, 'editor'); - await b.evaluate(`{const f=document.querySelector('[data-wf-editor]');window.__editor=f;const i=f.querySelector('input[name=title]');i.value='Intake, revised';i.focus();i.setSelectionRange(3,3);f.querySelector('[data-wf-edit-step="0"] [name=roles]').value='human, coder'}true`); +test('E2E6 P1-1: an open workflow step form keeps its node, typed step and focus across the poll and a failed read', { timeout: 90000 }, async t => { + const { b, ctl, refresh } = await fixture(t); + const form = '[data-wfg-step-form="0"]'; + await b.evaluate(`location.hash = '#/orgs/acme/workflows/intake?step=1'`); + await waitFor(b, `document.querySelector('${form} input[name=title]')?.value === 'Sort'`, 'step form'); + await b.evaluate(`{const f=document.querySelector('${form}');window.__form=f;const i=f.querySelector('input[name=title]');i.value='Sort, revised';i.dispatchEvent(new Event('input',{bubbles:true}));f.querySelector('input[name=role][value=coder]').click();i.focus();i.setSelectionRange(3,3)}true`); + await waitFor(b, `document.querySelector('${form}')?.hasAttribute('data-live-hold')`, 'the typed form holds'); await refresh({ poll: true }); - assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor]')===window.__editor`), true, 'the same editor node'); - assert.equal(await b.evaluate(`document.querySelectorAll('[data-wf-editor]').length`), 1); - assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor] input[name=title]').value`), 'Intake, revised'); - assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor] [data-wf-edit-step="0"] [name=roles]').value`), 'human, coder'); - assert.equal(await b.evaluate(`document.activeElement===document.querySelector('[data-wf-editor] input[name=title]')`), true, 'focus stays in the field'); + assert.equal(await b.evaluate(`document.querySelector('${form}')===window.__form`), true, 'the same form node'); + assert.equal(await b.evaluate(`document.querySelectorAll('${form}').length`), 1); + assert.equal(await b.evaluate(`document.querySelector('${form} input[name=title]').value`), 'Sort, revised'); + assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('${form} input[name=role]:checked')].map(i=>i.value)`), ['human', 'coder']); + assert.equal(await b.evaluate(`document.activeElement===document.querySelector('${form} input[name=title]')`), true, 'focus stays in the field'); assert.equal(await b.evaluate(`document.activeElement.selectionStart`), 3, 'the caret stays put'); - // A second refresh with focus elsewhere still keeps the open editor: it holds data-live-hold. + // A second repaint with focus elsewhere still keeps the typed form: it holds data-live-hold. await b.evaluate(`document.activeElement.blur();true`); - await refresh(); - assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor]')===window.__editor`), true); - assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor] input[name=title]').value`), 'Intake, revised'); - // Cancel closes it; the next refresh paints the list fresh. - await b.evaluate(`document.querySelector('[data-wf-cancel]').click();true`); - await waitFor(b, `!document.querySelector('[data-wf-editor]')`, 'cancel'); - await refresh(); - assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor]')`), null); + await refresh({ event: 'mosaic-workspace-render' }); + assert.equal(await b.evaluate(`document.querySelector('${form}')===window.__form`), true); + assert.equal(await b.evaluate(`document.querySelector('${form} input[name=title]').value`), 'Sort, revised'); + // A failed read keeps the same form, its typed step and focus, and says the read failed. + await b.evaluate(`document.querySelector('${form} input[name=title]').focus();true`); + ctl.workflowsFail = true; + await refresh({ poll: true }); + await waitFor(b, `/The last workflows read failed/.test(document.querySelector('[data-wfg-error]')?.textContent ?? '')`, 'the read failure is said'); + assert.equal(await b.evaluate(`document.querySelector('${form}')===window.__form`), true, 'the same form node after a failed read'); + assert.equal(await b.evaluate(`document.querySelector('${form} input[name=title]').value`), 'Sort, revised'); + assert.equal(await b.evaluate(`document.activeElement===document.querySelector('${form} input[name=title]')`), true, 'focus stays in the field'); + ctl.workflowsFail = false; + // Reset step puts the step back; the next repaint draws the form fresh, not held. + await b.evaluate(`document.querySelector('${form} [data-wfg-cancel]').click();true`); + await waitFor(b, `document.querySelector('${form} input[name=title]')?.value === 'Sort' && !document.querySelector('${form}').hasAttribute('data-live-hold')`, 'reset'); + await refresh({ event: 'mosaic-workspace-render' }); + await waitFor(b, `!document.querySelector('[data-wfg-error]') && document.querySelector('${form}') && document.querySelector('${form}')!==window.__form`, 'a fresh form after a good read'); }); test('E2E6 P1-1, P2-14: an unsaved autonomy choice, a picked pack project and a focused link survive the poll', { timeout: 60000 }, async t => { @@ -113,16 +124,17 @@ test('E2E6 P2-2: a pack apply re-reads the other sections and keeps its receipt' const before = { ...counts }; await b.evaluate(`document.querySelector('[data-pack-apply]').click();true`); await waitFor(b, `/^Applied\\./.test(document.querySelector('[data-packs-status]')?.textContent??'')`, 'apply'); - for (let i = 0; i < 300 && counts.workflows === before.workflows; i++) await new Promise(r => setTimeout(r, 30)); + // Both reads are waited for: the autonomy read can answer after the workflows read on a loaded host. + for (let i = 0; i < 300 && (counts.workflows === before.workflows || counts.autonomy === before.autonomy); i++) await new Promise(r => setTimeout(r, 30)); assert.ok(counts.workflows > before.workflows, 'workflows read again after the apply'); assert.ok(counts.autonomy > before.autonomy, 'autonomy read again after the apply'); await b.evaluate(`new Promise(r=>setTimeout(()=>r(true),300))`); assert.match(await b.evaluate(`document.querySelector('[data-packs-status]').textContent`), /^Applied\. Added board\./, 'the receipt survives the re-read'); }); -test('E2E6 review P3: a failed read keeps an open editor, Discard drops a held form, a focused button does not hold its section, and a clean form shows a failed read', { timeout: 60000 }, async t => { +test('E2E6 review P3: a failed read keeps a dirty form, Discard drops a held form, a focused button does not hold its section, and a clean form shows a failed read', { timeout: 60000 }, async t => { const { b, ctl, refresh } = await fixture(t); - await waitFor(b, `document.querySelector('[data-wf="intake"] [data-wf-edit]')&&document.querySelector('[data-autonomy-form] select[name=merge]')&&document.querySelector('[data-pack-preview-button]')`, 'sections'); + await waitFor(b, `document.querySelector('[data-autonomy-form] select[name=merge]')&&document.querySelector('[data-pack-preview-button]')`, 'sections'); // A focused Preview button alone no longer holds the packs section: the next poll shows a changed // pack and focus comes back to the rebuilt button through its data-focus-key. await b.evaluate(`document.querySelector('[data-pack-preview-button]').focus();true`); @@ -130,18 +142,11 @@ test('E2E6 review P3: a failed read keeps an open editor, Discard drops a held f await refresh({ poll: true }); await waitFor(b, `/Web project, renamed/.test(document.querySelector('[data-packs-org]').textContent)`, 'the renamed pack'); assert.match(await b.evaluate(`document.activeElement.dataset.focusKey??document.activeElement.tagName`), /^pack-preview:acme:web-project$/, 'focus returns to the rebuilt button'); - // One failed workflows read while the editor is open keeps the same editor node, draft and focus. - await b.evaluate(`document.querySelector('[data-wf="intake"] [data-wf-edit]').click();true`); - await waitFor(b, `document.querySelector('[data-wf-editor]')`, 'editor'); - await b.evaluate(`{const f=document.querySelector('[data-wf-editor]');window.__editor=f;const i=f.querySelector('input[name=title]');i.value='Typed during an outage';i.focus()}true`); - // A dirty autonomy form survives a failed autonomy read the same way. + // A dirty autonomy form survives a failed read (the workflow step form's case is the first test). await b.evaluate(`{const s=document.querySelector('[data-autonomy-form] select[name=merge]');s.value='in the loop';s.dispatchEvent(new Event('change',{bubbles:true}));window.__auto=document.querySelector('[data-autonomy-form]')}true`); - await b.evaluate(`document.querySelector('[data-wf-editor] input[name=title]').focus();true`); + await b.evaluate(`document.activeElement.blur();true`); ctl.workflowsFail = true; ctl.autonomyFail = true; await refresh({ poll: true }); - assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor]')===window.__editor`), true, 'the same editor node after a failed read'); - assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor] input[name=title]').value`), 'Typed during an outage'); - assert.equal(await b.evaluate(`document.activeElement===document.querySelector('[data-wf-editor] input[name=title]')`), true, 'focus stays in the field'); assert.equal(await b.evaluate(`document.querySelector('[data-autonomy-form]')===window.__auto`), true, 'the dirty autonomy form is kept after a failed read'); // Discard draws the last read in place of the held form. ctl.workflowsFail = false; ctl.autonomyFail = false; diff --git a/packages/webui/tests/packs-workflows-browser.test.mjs b/packages/webui/tests/packs-workflows-browser.test.mjs index fc70198d6..d8e3098e2 100644 --- a/packages/webui/tests/packs-workflows-browser.test.mjs +++ b/packages/webui/tests/packs-workflows-browser.test.mjs @@ -1,8 +1,9 @@ -// Starter packs SP6 (#1873): the owner's pack picker and workflow editor on an organization's page, -// driven in Chromium against stand-in pack verbs and a stand-in workflow read. It checks what the page -// shows from what the bus returns: the preview's marks, flagged lines, credential lines and noHire mark; -// a step role that no longer resolves; an organization-supplied title or label rendered as text; and -// the save and delete requests the editor sends. +// Starter packs SP6 (#1873): the owner's pack picker on an organization's page, and the organization's +// workflows, driven in Chromium against stand-in pack verbs and a stand-in workflow read. It checks what the +// page shows from what the bus returns: the preview's marks, flagged lines, credential lines and noHire mark; +// a step role that no longer resolves; an organization-supplied title or label rendered as text; and the save +// and delete requests the workflow pages send. SP17: the organization page's old workflow form is gone; the +// graph pages (#/orgs//workflows) are the one editor, so the workflow test drives those. import test from 'node:test'; import assert from 'node:assert/strict'; import { startServer } from '../src/serve.mjs'; @@ -134,76 +135,99 @@ test('SP6 pack picker without send previews but offers no apply', { timeout: 600 await waitFor(b, `document.querySelector('[data-pack-preview]')`, 'preview'); assert.equal(await b.evaluate(`document.querySelector('[data-pack-apply]')`), null); assert.match(await b.evaluate(`document.querySelector('[data-pack-preview]').textContent`), /started without send/); - assert.equal(await b.evaluate(`document.querySelector('[data-wf-edit],[data-wf-new]')`), null, 'no workflow change controls without send'); + // Without send the workflow read is not writable: the graph page shows the step as text and no form. + await b.evaluate(`location.hash = '#/orgs/acme/workflows/intake?step=1'`); + await waitFor(b, `document.querySelector('[data-wfg-detail] [data-wfg-field="roles"]')`, 'read-only step'); + assert.equal(await b.evaluate(`document.querySelector('[data-wfg-form],[data-wfg-save],[data-wfg-delete],[data-wf-edit],[data-wf-new]')`), null, 'no workflow change controls without send'); + assert.ok(await b.evaluate(`!!document.querySelector('[data-wfg-readonly]')`)); }); -test('SP6 workflows: list by scope, a step naming no current role, titles as text, edit, new and delete', { timeout: 60000 }, async t => { +test('SP6 workflows: list by scope, a step naming no current role, titles as text, edit, new and delete', { timeout: 90000 }, async t => { const { b, verbs, flows } = await fixture(t); - await waitFor(b, `document.querySelector('[data-wf="intake"]')`, 'workflow list'); - assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wf-scope-list]')].map(n=>n.dataset.wfScopeList)`), ['', 'site']); - assert.equal(await b.evaluate(`document.querySelector('[data-wf="intake"] [data-wf-title]').textContent`), `Intake ${XSS}`); - assert.equal(await b.evaluate(`document.querySelectorAll('[data-workflows] img').length`), 0, 'a workflow title never becomes markup'); + const press = sel => b.evaluate(`(()=>{const e=document.querySelector(${JSON.stringify(sel)});if(!e)throw Error('no '+${JSON.stringify(sel)});if(e.disabled)throw Error('disabled '+${JSON.stringify(sel)});e.click();return true})()`); + const fill = (sel, value) => b.evaluate(`(()=>{const e=document.querySelector(${JSON.stringify(sel)});e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('input',{bubbles:true}));return true})()`); + const text = sel => b.evaluate(`(document.querySelector(${JSON.stringify(sel)})?.textContent ?? '').replace(/\\s+/g,' ').trim()`); + const sets = () => verbs.filter(([v]) => v === 'workflow.set.console'); + // The organization page: the Workflows card, no old form. + await waitFor(b, `document.querySelectorAll('[data-wfg-card] [data-wfg-card-item]').length === 2`, 'workflow card'); + assert.equal(await b.evaluate(`document.querySelector('[data-workflows],[data-wf-edit],[data-wf-new]')`), null, 'the old organization-page editor is gone'); + assert.equal(await b.evaluate(`document.querySelectorAll('[data-org-dashboard] img').length`), 0, 'a workflow title never becomes markup'); + // The list: each scope, titles as text. + await b.evaluate(`location.hash = '#/orgs/acme/workflows'`); + await waitFor(b, `document.querySelector('[data-wfg-item="intake"]')`, 'workflow list'); + assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wfg-scope-list]')].map(n=>n.dataset.wfgScopeList)`), ['', 'site']); + assert.equal(await b.evaluate(`document.querySelector('[data-wfg-item="intake"] a[data-wfg-open]').textContent`), `Intake ${XSS}`); + assert.equal(await b.evaluate(`document.querySelectorAll('#bus-view img').length`), 0); assert.equal(await b.evaluate(`window.__sp6pwn===undefined`), true); - // triage (an org definition), human and coder (a template) resolve; ghost names no current role. - assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wf="intake"] [data-wf-step]')].map(s=>s.querySelectorAll('[data-wf-missing]').length)`), [0, 1]); - assert.match(await b.evaluate(`document.querySelectorAll('[data-wf="intake"] [data-wf-step]')[1].textContent`), /ghost names no current role/); - assert.equal(await b.evaluate(`document.querySelectorAll('[data-wf="ship"] [data-wf-missing]').length`), 0); - - // Edit: the ghost step shows the mark in the editor; fixing the role clears it; save sends the revision. - await b.evaluate(`document.querySelector('[data-wf="intake"] [data-wf-edit]').click();true`); - await waitFor(b, `document.querySelector('[data-wf-editor]')`, 'editor'); - assert.equal(await b.evaluate(`document.querySelector('[data-wf-edit-step="1"] [data-wf-step-missing]').textContent`), 'ghost names no current role'); - assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor] input[name=title]').value`), `Intake ${XSS}`); - await b.evaluate(`{const r=document.querySelector('[data-wf-edit-step="1"] [name=roles]');r.value='reviewer, x';r.dispatchEvent(new Event('input',{bubbles:true}))}true`); - assert.equal(await b.evaluate(`document.querySelector('[data-wf-edit-step="1"] [data-wf-step-missing]').textContent`), 'x names no current role'); - assert.equal(await b.evaluate(`document.querySelectorAll('[data-wf-edit-step="1"] b').length`), 0); - await b.evaluate(`{const r=document.querySelector('[data-wf-edit-step="1"] [name=roles]');r.value='reviewer';r.dispatchEvent(new Event('input',{bubbles:true}))}true`); - assert.equal(await b.evaluate(`document.querySelector('[data-wf-edit-step="1"] [data-wf-step-missing]').textContent`), ''); - await b.evaluate(`document.querySelector('[data-wf-editor] input[name=title]').value='Intake';document.querySelector('[data-wf-editor]').requestSubmit();true`); - await waitFor(b, `document.querySelector('[data-workflows-status]').textContent==='Saved intake.'`, 'save status'); - const saved = verbs.filter(([v]) => v === 'workflow.set.console').at(-1)[1]; - assert.deepEqual(saved, { revision: REV('a'), name: 'intake', workflow: { title: 'Intake', description: `Sort ${XSS}`, steps: [{ title: `Sort ${XSS}`, state: 'todo', roles: ['triage', 'human'] }, { title: 'Hand off', state: 'in-progress', roles: ['reviewer'] }] } }); - assert.equal(await b.evaluate(`document.querySelectorAll('[data-wf="intake"] [data-wf-missing]').length`), 0, 'the re-read shows the fixed step'); + // The graph: triage (an organization role), human and coder (a template) resolve; ghost names no current role. + await b.evaluate(`location.hash = '#/orgs/acme/workflows/intake'`); + await waitFor(b, `document.querySelectorAll('[data-wfg-graph] [data-wfg-step]').length === 2 && document.querySelector('[data-wfg-meta-form]')`, 'graph'); + assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wfg-graph] [data-wfg-step]')].map(s=>s.querySelectorAll('[data-wfg-missing]').length)`), [0, 1]); + assert.equal(await b.evaluate(`document.querySelectorAll('#bus-view img').length`), 0); + // The workflow title changes in the panel with no step selected; it is held until Save. + assert.equal(await b.evaluate(`document.querySelector('[data-wfg-meta-form] input[name=title]').value`), `Intake ${XSS}`); + await fill('[data-wfg-meta-form] input[name=title]', 'Intake'); + // Step 2's form marks ghost; swapping it for reviewer clears the mark in the graph. + await b.evaluate(`document.querySelector('[data-wfg-step="2"]').dispatchEvent(new MouseEvent('click',{bubbles:true,cancelable:true}));true`); + await waitFor(b, `document.querySelector('[data-wfg-step-form="1"]')`, 'step 2 form'); + assert.match(await text('[data-wfg-step-form="1"] [data-wfg-roles-pick]'), /ghost names no current role/); + await press('[data-wfg-step-form="1"] input[name="role"][value="ghost"]'); + await press('[data-wfg-step-form="1"] input[name="role"][value="reviewer"]'); + await waitFor(b, `document.querySelectorAll('[data-wfg-graph] [data-wfg-missing]').length === 0`, 'mark cleared in the graph'); + assert.equal(sets().length, 0, 'nothing sent before Save'); + await press('[data-wfg-step-form="1"] [data-wfg-save]'); + await waitFor(b, `/Saved intake\\./.test(document.querySelector('[data-wfg-status]')?.textContent ?? '')`, 'save status'); + assert.deepEqual(sets().at(-1)[1], { revision: REV('a'), name: 'intake', workflow: { title: 'Intake', description: `Sort ${XSS}`, steps: [{ title: `Sort ${XSS}`, state: 'todo', roles: ['triage', 'human'] }, { title: 'Hand off', state: 'in-progress', roles: ['reviewer'] }] } }); + assert.equal(await b.evaluate(`document.querySelector('#bus-view h1').textContent`), 'Intake'); + assert.equal(await b.evaluate(`document.querySelectorAll('[data-wfg-graph] [data-wfg-missing]').length`), 0, 'the saved workflow shows the fixed step'); // New, in the project scope: a bad name is refused on the page and sends nothing. - const sets = () => verbs.filter(([v]) => v === 'workflow.set.console').length; - const before = sets(); - await b.evaluate(`document.querySelector('[data-wf-new]').click();true`); - await waitFor(b, `document.querySelector('[data-wf-editor] select[name=scope]')`, 'new editor'); - await b.evaluate(`{const f=document.querySelector('[data-wf-editor]');f.elements.scope.value='site';f.elements.name.value='Bad Name';f.querySelector('[data-wf-edit-step="0"] [name=title]').value='Plan';f.querySelector('[data-wf-edit-step="0"] [name=roles]').value='human';f.requestSubmit()}true`); - await waitFor(b, `/lowercase/.test(document.querySelector('[data-workflows-status]').textContent)`, 'name refusal'); - assert.equal(sets(), before); - // The writer's name rule (PLAN_NAME): no underscore, dot or leading digit. Each is refused here, not at the bus. - for (const bad of ['release_1', 'v2.ship', '2nd-review']) { - await b.evaluate(`{const f=document.querySelector('[data-wf-editor]');f.elements.name.value=${JSON.stringify(bad)};f.requestSubmit()}true`); - assert.equal(await b.evaluate(`document.querySelector('[data-workflows-status]').textContent`), 'A workflow name is 1 to 64 lowercase letters, digits or dashes, starting with a letter.', bad); - assert.equal(sets(), before, `${bad} sends nothing`); + const before = sets().length; + await b.evaluate(`location.hash = '#/orgs/acme/workflows'`); + await waitFor(b, `document.querySelector('[data-wfg-new]')`, 'New workflow'); + await press('[data-wfg-new]'); + await waitFor(b, `document.querySelector('[data-wfg-newform] select[name=scope]')`, 'new form'); + await b.evaluate(`{const f=document.querySelector('[data-wfg-newform]');f.elements.scope.value='site';f.elements.scope.dispatchEvent(new Event('change',{bubbles:true}))}true`); + await fill('[data-wfg-newform] input[name=title]', 'Plan'); + await press('[data-wfg-newform] input[name="role"][value="human"]'); + // The writer's name rule (PLAN_NAME): lowercase, no underscore, dot or leading digit. Each is refused here, not at the bus. + for (const bad of ['Bad Name', 'release_1', 'v2.ship', '2nd-review']) { + await fill('[data-wfg-newform] input[name=name]', bad); + await press('[data-wfg-create]'); + await waitFor(b, `(document.querySelector('[data-wfg-newform] [data-wfg-why]')?.textContent ?? '') === 'A workflow name is 1 to 64 lowercase letters, digits or dashes, starting with a letter.'`, `${bad} refused`); + assert.equal(sets().length, before, `${bad} sends nothing`); + await fill('[data-wfg-newform] input[name=name]', ''); } - assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor] input[name=name]').placeholder`), 'lowercase letters, digits, dashes'); + assert.equal(await b.evaluate(`document.querySelector('[data-wfg-newform] input[name=name]').placeholder`), 'lowercase letters, digits, dashes'); // A new workflow under a name the scope already holds would replace it: refused, nothing sent. - await b.evaluate(`{const f=document.querySelector('[data-wf-editor]');f.elements.name.value='ship';f.requestSubmit()}true`); - assert.equal(await b.evaluate(`document.querySelector('[data-workflows-status]').textContent`), 'A workflow named ship already exists here. Edit it instead.'); - assert.equal(sets(), before, 'an existing name sends nothing'); - assert.equal(await b.evaluate(`document.querySelector('[data-wf-editor] select[name=scope]').value`), 'site', 'the editor keeps the chosen scope'); - await b.evaluate(`{const f=document.querySelector('[data-wf-editor]');f.elements.name.value='plan';f.requestSubmit()}true`); - await waitFor(b, `document.querySelector('[data-workflows-status]').textContent==='Saved plan.'`, 'new save'); - assert.deepEqual(verbs.filter(([v]) => v === 'workflow.set.console').at(-1)[1], { revision: REV('b'), name: 'plan', workflow: { steps: [{ title: 'Plan', state: 'todo', roles: ['human'] }] }, project: 'site' }); - assert.ok(await b.evaluate(`document.querySelector('[data-wf-scope-list="site"] [data-wf="plan"]')!==null`)); + await fill('[data-wfg-newform] input[name=name]', 'ship'); + await press('[data-wfg-create]'); + await waitFor(b, `(document.querySelector('[data-wfg-newform] [data-wfg-why]')?.textContent ?? '') === 'A workflow named ship already exists here. Edit it instead.'`, 'existing name refused'); + assert.equal(sets().length, before, 'an existing name sends nothing'); + assert.equal(await b.evaluate(`document.querySelector('[data-wfg-newform] select[name=scope]').value`), 'site', 'the form keeps the chosen scope'); + await fill('[data-wfg-newform] input[name=name]', 'plan'); + await press('[data-wfg-create]'); + await waitFor(b, `location.hash === '#/orgs/acme/workflows/plan?project=site&step=1' && document.querySelector('[data-wfg-save]') && !document.querySelector('[data-wfg-save]').disabled`, 'opens unsaved'); + assert.equal(sets().length, before, 'Create writes nothing'); + await press('[data-wfg-save]'); + await waitFor(b, `/Saved plan\\./.test(document.querySelector('[data-wfg-status]')?.textContent ?? '')`, 'new save'); + assert.deepEqual(sets().at(-1)[1], { revision: REV('b'), name: 'plan', project: 'site', workflow: { steps: [{ title: 'Plan', state: 'todo', roles: ['human'] }] } }); // Delete asks first; Keep sends nothing; Delete sends the project and the revision. - const del = `[data-wf-scope-list="site"] [data-wf="ship"]`; - await b.evaluate(`document.querySelector('${del} [data-wf-delete]').click();true`); - await waitFor(b, `document.querySelector('${del} [data-wf-delete-no]')`, 'delete confirm'); - await b.evaluate(`document.querySelector('${del} [data-wf-delete-no]').click();true`); - await waitFor(b, `document.querySelector('${del} [data-wf-delete]')`, 'kept'); - const n = sets(); - await b.evaluate(`document.querySelector('${del} [data-wf-delete]').click();true`); - await waitFor(b, `document.querySelector('${del} [data-wf-delete-yes]')`, 'delete confirm again'); - assert.equal(sets(), n); + await b.evaluate(`location.hash = '#/orgs/acme/workflows/ship?project=site'`); + await waitFor(b, `document.querySelector('[data-wfg-delete]') && document.querySelector('#bus-view h1')?.textContent === 'ship'`, 'ship graph'); + await press('[data-wfg-delete]'); + await waitFor(b, `document.querySelector('[data-wfg-delete-no]')`, 'delete confirm'); + await press('[data-wfg-delete-no]'); + await waitFor(b, `document.querySelector('[data-wfg-delete]') && !document.querySelector('[data-wfg-confirm]')`, 'kept'); + const n = sets().length; + await press('[data-wfg-delete]'); + await waitFor(b, `document.querySelector('[data-wfg-delete-yes]')`, 'delete confirm again'); + assert.equal(sets().length, n); const rev = flows().revision; - await b.evaluate(`document.querySelector('${del} [data-wf-delete-yes]').click();true`); - await waitFor(b, `document.querySelector('[data-workflows-status]').textContent==='Deleted ship.'`, 'delete status'); - assert.deepEqual(verbs.filter(([v]) => v === 'workflow.set.console').at(-1)[1], { revision: rev, name: 'ship', workflow: null, project: 'site' }); - assert.equal(await b.evaluate(`document.querySelector('${del}')`), null); + await press('[data-wfg-delete-yes]'); + await waitFor(b, `location.hash === '#/orgs/acme/workflows' && /Deleted ship\\./.test(document.querySelector('[data-wfg-list] [data-wfg-status]')?.textContent ?? '')`, 'delete status'); + assert.deepEqual(sets().at(-1)[1], { revision: rev, name: 'ship', workflow: null, project: 'site' }); + assert.equal(await b.evaluate(`document.querySelector('[data-wfg-scope-list="site"] [data-wfg-item="ship"]')`), null); assert.equal(await b.evaluate(`document.documentElement.scrollWidth<=innerWidth`), true); }); diff --git a/packages/webui/tests/workflows-browser.test.mjs b/packages/webui/tests/workflows-browser.test.mjs index 9b7ea502a..2af600dda 100644 --- a/packages/webui/tests/workflows-browser.test.mjs +++ b/packages/webui/tests/workflows-browser.test.mjs @@ -10,6 +10,10 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { startServer } from '../src/serve.mjs'; import { createDevOwner } from '../src/dev-owner.mjs'; +import { mkdtempSync } from 'node:fs'; +import { join } from 'node:path'; +import { createOrgAdmin } from '../src/org-admin.mjs'; +import { actionTrail } from '../src/action-trail.mjs'; import { browser } from './browser.mjs'; import { close } from './fixture.mjs'; @@ -45,11 +49,18 @@ const LIST = [ // page sent, and a refusal to give the next write. A write with another revision is a revision-conflict. const hex = n => n.toString(16).padStart(64, '0'); function store(writable) { - const st = { writable, docs: structuredClone(DOCS), revs: { acme: 'a'.repeat(64), bare: 'b'.repeat(64), gamma: 'c'.repeat(64) }, writes: [], refuse: null, n: 0 }; + const st = { writable, docs: structuredClone(DOCS), revs: { acme: 'a'.repeat(64), bare: 'b'.repeat(64), gamma: 'c'.repeat(64) }, writes: [], refuse: null, n: 0, held: {}, down: {} }; + // SP17 item 4: st.down[id] is 'restarting' (the bus does not answer: the list says unavailable, the file + // still reads, a write finds no bus host) or 'stopped' (the owner stopped it: the page does not read it). + st.view = org => (st.down[org.id] ? { ...org, busHealthy: false, ...(st.down[org.id] === 'stopped' ? { busStopped: true } : {}) } : org); + // SP17: hold('read') holds the next workflow read, which answers with the file as it was when the read + // began; hold('write') holds the next write before it reaches the file. Each returns the release. + st.hold = which => { let open; st.held[which] = new Promise(r => { open = r; }); return open; }; const fail = code => Object.assign(new Error(code), { code }); st.write = (id, verb, args) => { st.writes.push({ id, verb, args: structuredClone(args) }); if (verb !== 'workflow.set.console') throw fail('not-configured'); + if (st.down[id]) throw fail('no-bus-host'); if (st.refuse) { const code = st.refuse; st.refuse = null; throw fail(code); } if (args.revision !== st.revs[id]) throw fail('revision-conflict'); const doc = st.docs[id], scope = args.project ? doc.projects[args.project] : doc; @@ -63,20 +74,26 @@ function store(writable) { return st; } function organizations(reads, st) { - const member = org => ({ + const member = org0 => { const org = st.view(org0); return { id: org.id, doc: { appearance: { theme: org.theme }, roles: {}, projects: {} }, status: async () => (org.busHealthy ? { healthy: true, pid: 4242, boot: null } : { healthy: false, boot: { ok: false, at: at(90), lastGood: null, reason: 'stopped by the owner' } }), options: () => ({ bus: { inbox: async () => [], agents: async () => [], 'thread.claims': async () => [], tasks: async () => [] }, chat: { threads: async () => [], projects: async () => [] } }), - }); + }; }; return { - list: async () => LIST, + list: async () => LIST.map(st.view), members: async () => LIST.map(member), resolve: async id => { const org = LIST.find(o => o.id === id); if (!org) return null; - const workflowsRead = async () => { reads.push(id); if (st.failRead) throw Object.assign(new Error('org-unavailable'), { code: 'org-unavailable' }); return { revision: st.revs[id], document: structuredClone(st.docs[id] ?? {}), templates: ['writer'] }; }; + const workflowsRead = async () => { + reads.push(id); + if (st.failRead) throw Object.assign(new Error('org-unavailable'), { code: 'org-unavailable' }); + const answer = { revision: st.revs[id], document: structuredClone(st.docs[id] ?? {}), templates: ['writer'] }; + const h = st.held.read; if (h) { st.held.read = null; await h; } + return answer; + }; if (!org.busHealthy) return { busHealthy: false, reads: null, bus: {}, workflowsRead, chat: { projects: async () => [], threads: async () => [] } }; return { - busHealthy: true, workflowsRead, packsWrite: st.writable ? async (verb, args) => st.write(id, verb, args) : null, decisionWrite: async () => ({}), send: async () => ({}), + busHealthy: true, workflowsRead, packsWrite: st.writable ? async (verb, args) => { const h = st.held.write; if (h) { st.held.write = null; await h; } return st.write(id, verb, args); } : null, decisionWrite: async () => ({}), send: async () => ({}), requestRead: async verb => { if (verb === 'packs.console') return { packs: [] }; if (verb === 'autonomy.get.console') return { revision: 'e'.repeat(64), autonomy: {}, levels: {} }; throw Object.assign(new Error('not-configured'), { code: 'not-configured' }); }, reads: { business: async () => ({ business: { id, projects: [], instances: [] } }), settings: async () => ({}), queue: async () => ({ rows: [] }) }, bus: { instances: async () => ({ instances: {} }), agents: async () => [], 'thread.claims': async () => [], tasks: async () => [], inbox: async () => [], messages: async () => ({ messages: [] }) }, @@ -86,9 +103,10 @@ function organizations(reads, st) { }; } -async function setup(t, { path, viewport = [1440, 900], mode = null, writable = true } = {}) { +async function setup(t, { path, viewport = [1440, 900], mode = null, writable = true, admin = null } = {}) { const reads = [], st = store(writable); - const server = await startServer({ port: 0, sso: createDevOwner(), send: async () => ({}), log: () => {}, organizations: organizations(reads, st) }); + const extra = admin ? { orgAdmin: admin(st), trail: actionTrail(join(mkdtempSync(join(process.env.TMPDIR, 'wfg-')), 'console')) } : {}; + const server = await startServer({ port: 0, sso: createDevOwner(), send: async () => ({}), log: () => {}, organizations: organizations(reads, st), ...extra }); t.after(() => close(server)); const b = await browser({ machine: false, args: ['--disable-extensions'] }); t.after(() => b.close()); @@ -157,7 +175,8 @@ test('the graph draws one box per step in order with its roles and one arrowed e }); test('selecting a step shows what the data holds for it and survives a repaint', { timeout: 60000 }, async t => { - const { b, wait, reads } = await setup(t, { path: '#/orgs/acme/workflows/change' }); + // A reader's page: the roles and state are lines of text. A writer's page shows them as the step's form (below). + const { b, wait, reads } = await setup(t, { path: '#/orgs/acme/workflows/change', writable: false }); await wait(`${boxes}.length === 4`, 'four boxes'); assert.match(await b.evaluate(`document.querySelector('[data-wfg-detail]').textContent`), /Select a step/); await b.evaluate(`document.querySelector('[data-wfg-step="2"]').dispatchEvent(new MouseEvent('click',{bubbles:true,cancelable:true}));true`); @@ -262,6 +281,15 @@ test('the organization page card lists each workflow as a link to its graph', { assert.equal(await b.evaluate(`window.__sp9pwn===undefined`), true); // The card reuses the page's one workflow read; it sends no second one. assert.equal(reads.filter(id => id === 'acme').length, 1); + // SP17: under each workflow, each step links to its own form. + assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wfg-card] .wfg-cardlist > li:first-child [data-wfg-card-step]')].map(a=>[a.getAttribute('href'),a.textContent,a.getAttribute('aria-label')])`), [ + ['#/orgs/acme/workflows/change?step=1', 'Write the task', 'Change step 1, Write the task'], + ['#/orgs/acme/workflows/change?step=2', 'Implement the change', 'Change step 2, Implement the change'], + ['#/orgs/acme/workflows/change?step=3', 'Review the change', 'Change step 3, Review the change'], + ['#/orgs/acme/workflows/change?step=4', 'Approve the merge', 'Change step 4, Approve the merge'], + ]); + assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wfg-card] [data-wfg-card-step]')].map(a=>a.getAttribute('href')).filter(h=>/project=site/.test(h))`), ['#/orgs/acme/workflows/change?project=site&step=1', '#/orgs/acme/workflows/change?project=site&step=2']); + assert.equal(await b.evaluate(`document.documentElement.scrollWidth<=innerWidth`), true); await b.evaluate(`document.querySelector('[data-wfg-card] [data-wfg-card-item]').click();true`); await wait(`location.hash === '#/orgs/acme/workflows/change' && document.querySelectorAll('[data-wfg-graph] [data-wfg-step]').length === 4`, 'graph from card'); }); @@ -325,31 +353,36 @@ const fill = (sel, value) => `(()=>{const e=document.querySelector(${JSON.string const role = (form, name) => `${form} input[name="role"][value="${name}"]`; const text = sel => `(document.querySelector(${JSON.stringify(sel)})?.textContent ?? '').replace(/\\s+/g,' ').trim()`; -test('editing a step changes the graph on the page, and Save sends one POST with the revision the page read', { timeout: 60000 }, async t => { +const form = '[data-wfg-step-form]'; +const saveOn = `(()=>{const e=document.querySelector('[data-wfg-save]');return !!e&&!e.disabled})()`; + +test('a selected step is its edit form: a change draws in the graph, and Save sends one POST with the revision the page read', { timeout: 60000 }, async t => { const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?step=4' }); - await wait(`document.querySelector('[data-wfg-detail-title]')?.textContent === 'Approve the merge' && document.querySelector('[data-wfg-edit]')`, 'step 4 with Edit'); - // Nothing pending: no Unsaved, no Save. - assert.equal(await b.evaluate(`document.querySelector('[data-wfg-unsaved],[data-wfg-save],[data-wfg-discard]')`), null); - await b.evaluate(press('[data-wfg-edit]')); - await wait(`document.querySelector('[data-wfg-form] [data-wfg-form-title]')?.textContent === 'Edit step 4'`, 'step form'); - assert.equal(await b.evaluate(`document.activeElement.dataset.focusKey`), 'wfg-f-title'); - assert.equal(await b.evaluate(`document.querySelector('[data-wfg-form] input[name="title"]').value`), 'Approve the merge'); - assert.equal(await b.evaluate(`document.querySelector('[data-wfg-form] select[name="state"]').value`), 'done'); + await wait(`document.querySelector('[data-wfg-detail-title]')?.textContent === 'Approve the merge' && document.querySelector('${form}')`, 'step 4 with its form'); + // Nothing pending: no Unsaved, no Discard, no Reset, and Save is there but off. + assert.equal(await b.evaluate(`document.querySelector('[data-wfg-unsaved],[data-wfg-discard]')`), null); + assert.equal(await b.evaluate(`document.querySelector('${form} [data-wfg-save]').disabled`), true); + assert.equal(await b.evaluate(`document.querySelector('${form} [data-wfg-cancel]').hidden`), true); + assert.equal(await b.evaluate(`document.querySelector('${form} input[name="title"]').value`), 'Approve the merge'); + assert.equal(await b.evaluate(`document.querySelector('${form} select[name="state"]').value`), 'done'); // The picker offers human, the organization's roles and the templates; the step's unknown role is first, checked and marked. - assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wfg-form] input[name="role"]')].map(i=>[i.value,i.checked])`), [['merge-gate', true], ['human', true], ['coder', false], ['pm', false], ['reviewer', false], ['writer', false]]); - assert.ok(await b.evaluate(`!!document.querySelector('[data-wfg-form] [data-wfg-pick-missing]')`)); - await b.evaluate(fill('[data-wfg-form] input[name="title"]', 'Approve and merge')); - await b.evaluate(press(role('[data-wfg-form]', 'merge-gate'))); - await b.evaluate(press(role('[data-wfg-form]', 'reviewer'))); - await b.evaluate(press('[data-wfg-apply]')); - await wait(`${titles}[3] === 'Approve and merge' && document.querySelector('[data-wfg-unsaved]')`, 'pending change drawn'); + assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('${form} input[name="role"]')].map(i=>[i.value,i.checked])`), [['merge-gate', true], ['human', true], ['coder', false], ['pm', false], ['reviewer', false], ['writer', false]]); + assert.ok(await b.evaluate(`!!document.querySelector('${form} [data-wfg-pick-missing]')`)); + await b.evaluate(fill(`${form} input[name="title"]`, 'Approve and merge')); + await b.evaluate(press(role(form, 'merge-gate'))); + await b.evaluate(press(role(form, 'reviewer'))); + // The graph draws the step as typed; nothing is written yet. + await wait(`${titles}[3] === 'Approve and merge' && document.querySelector('[data-wfg-unsaved]') && ${saveOn}`, 'pending change drawn'); assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-wfg-step="4"] [data-wfg-roles] tspan')].map(t=>t.textContent)`), ['human', 'reviewer']); assert.equal(await b.evaluate(`document.querySelector('[data-wfg-step="4"] [data-wfg-missing]')`), null); assert.equal(await b.evaluate(text('[data-wfg-unsaved]')), 'Unsaved'); - assert.equal(await b.evaluate(`document.activeElement.dataset.focusKey`), 'wfg-save'); - assert.equal(st.writes.length, 0, 'Apply writes nothing'); + assert.equal(await b.evaluate(`document.querySelector('${form} [data-wfg-cancel]').hidden`), false, 'Reset step shows once the step differs'); + // The panel's Save is the only one; the bar does not repeat it. + assert.equal(await b.evaluate(`document.querySelectorAll('[data-wfg-save]').length`), 1); + assert.equal(st.writes.length, 0, 'typing writes nothing'); await b.evaluate(press('[data-wfg-save]')); await wait(`/Saved change\\./.test(${text('[data-wfg-status]')}) && !document.querySelector('[data-wfg-unsaved]')`, 'saved'); + assert.ok(await b.evaluate(`!!document.querySelector('${form} [data-wfg-status]')`), 'the status sits with the Save that was pressed'); assert.equal(st.writes.length, 1); assert.deepEqual(st.writes[0], { id: 'acme', verb: 'workflow.set.console', args: { revision: REV_A, name: 'change', workflow: { description: 'One change from task to merge.', @@ -359,9 +392,29 @@ test('editing a step changes the graph on the page, and Save sends one POST with { title: 'Review the change', state: 'in-review', roles: ['reviewer'] }, { title: 'Approve and merge', state: 'done', roles: ['human', 'reviewer'] }, ] } } }); - // The page now draws the file as saved, read again. await wait(`document.querySelector('[data-wfg-detail-title]')?.textContent === 'Approve and merge'`, 'detail after save'); assert.deepEqual(st.docs.acme.workflows.change.steps[3], { title: 'Approve and merge', state: 'done', roles: ['human', 'reviewer'] }); + // Reset step puts a typed step back as the page holds it. + await b.evaluate(fill(`${form} input[name="title"]`, 'Oops')); + await wait(`${titles}[3] === 'Oops'`, 'typed'); + await b.evaluate(press(`${form} [data-wfg-cancel]`)); + await wait(`document.querySelector('${form} input[name="title"]')?.value === 'Approve and merge' && ${titles}[3] === 'Approve and merge' && !document.querySelector('[data-wfg-unsaved]')`, 'reset'); + assert.equal(await b.evaluate(`window.MosaicWorkflows.hasDraft()`), false); +}); + +test('the workflow title and description change in the panel with no step selected, and save with the workflow', { timeout: 60000 }, async t => { + const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site' }); + await wait(`document.querySelector('[data-wfg-meta-form]')`, 'workflow form'); + assert.equal(await b.evaluate(`document.querySelector('[data-wfg-meta-form] input[name="title"]').value`), 'Site release'); + assert.equal(await b.evaluate(`document.querySelector('[data-wfg-meta-form] [data-wfg-save]').disabled`), true); + await b.evaluate(fill('[data-wfg-meta-form] input[name="title"]', 'Site launch')); + await b.evaluate(fill('[data-wfg-meta-form] textarea[name="description"]', 'From build to live.')); + await wait(`document.querySelector('[data-wfg-unsaved]') && ${saveOn}`, 'pending'); + await b.evaluate(press('[data-wfg-meta-form] [data-wfg-save]')); + await wait(`/Saved change\\./.test(${text('[data-wfg-status]')})`, 'saved'); + assert.deepEqual(st.writes[0].args, { revision: REV_A, name: 'change', project: 'site', workflow: { title: 'Site launch', description: 'From build to live.', steps: [ + { title: 'Build', state: 'in-progress', roles: ['coder'] }, { title: 'Ship', state: 'done', roles: ['human'] }] } }); + await wait(`document.querySelector('#bus-view h1')?.textContent === 'Site launch'`, 'heading after save'); }); test('add, move, remove and discard change only the page until Save', { timeout: 60000 }, async t => { @@ -370,16 +423,16 @@ test('add, move, remove and discard change only the page until Save', { timeout: // Add after the selected step. await b.evaluate(press('[data-wfg-add]')); await wait(`document.querySelector('[data-wfg-form-title]')?.textContent === 'New step 3'`, 'add form'); - await b.evaluate(fill('[data-wfg-form] input[name="title"]', 'Test the change')); - await b.evaluate(`(()=>{const e=document.querySelector('[data-wfg-form] select[name="state"]');e.value='in-review';e.dispatchEvent(new Event('input',{bubbles:true}));return true})()`); - // Apply with no role is refused in words, and the form stays. - await b.evaluate(press('[data-wfg-apply]')); + await b.evaluate(fill('[data-wfg-add-form] input[name="title"]', 'Test the change')); + await b.evaluate(`(()=>{const e=document.querySelector('[data-wfg-add-form] select[name="state"]');e.value='in-review';e.dispatchEvent(new Event('input',{bubbles:true}));return true})()`); + // Add step with no role is refused in words, and the form stays. + await b.evaluate(press('[data-wfg-add-step]')); await wait(`${text('[data-wfg-why]')} === 'Step 3 needs at least one role.'`, 'no role refused'); - await b.evaluate(press(role('[data-wfg-form]', 'coder'))); - await b.evaluate(press('[data-wfg-apply]')); + await b.evaluate(press(role('[data-wfg-add-form]', 'coder'))); + await b.evaluate(press('[data-wfg-add-step]')); await wait(`${boxes}.length === 5 && ${titles}[2] === 'Test the change'`, 'step added'); assert.equal(await b.evaluate(`location.hash`), '#/orgs/acme/workflows/change?step=3'); - assert.equal(await b.evaluate(text('[data-wfg-field="state"]')), 'Review'); + assert.equal(await b.evaluate(`document.querySelector('${form} select[name="state"]').value`), 'in-review'); assert.ok(await b.evaluate(`!!document.querySelector('[data-wfg-unsaved]')`)); // Move earlier and later. await b.evaluate(press('[data-wfg-up]')); @@ -399,9 +452,9 @@ test('add, move, remove and discard change only the page until Save', { timeout: await wait(`${text('[data-wfg-add]')} === 'Add a step at the end'`, 'add at end'); await b.evaluate(press('[data-wfg-add]')); await wait(`document.querySelector('[data-wfg-form-title]')?.textContent === 'New step 5'`, 'add-at-end form'); - await b.evaluate(fill('[data-wfg-form] input[name="title"]', 'Announce it')); - await b.evaluate(press(role('[data-wfg-form]', 'pm'))); - await b.evaluate(press('[data-wfg-apply]')); + await b.evaluate(fill('[data-wfg-add-form] input[name="title"]', 'Announce it')); + await b.evaluate(press(role('[data-wfg-add-form]', 'pm'))); + await b.evaluate(press('[data-wfg-add-step]')); await wait(`${boxes}.length === 5 && ${titles}[4] === 'Announce it' && /step=5/.test(location.hash)`, 'added at end'); // Discard drops all of it; nothing was written. await b.evaluate(press('[data-wfg-discard]')); @@ -412,24 +465,19 @@ test('add, move, remove and discard change only the page until Save', { timeout: test('a refused save says why next to Save and keeps the pending change', { timeout: 60000 }, async t => { const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?step=1' }); - await wait(`document.querySelector('[data-wfg-edit]')`, 'step 1'); - await b.evaluate(press('[data-wfg-edit]')); - await wait(`document.querySelector('[data-wfg-form]')`, 'form'); - await b.evaluate(fill('[data-wfg-form] input[name="title"]', 'Write the brief')); - await b.evaluate(press('[data-wfg-apply]')); - await wait(`${titles}[0] === 'Write the brief'`, 'pending'); - // Step 4 still names merge-gate: the page refuses before sending, in the same words as the form editor. + await wait(`document.querySelector('${form}')`, 'step 1'); + await b.evaluate(fill(`${form} input[name="title"]`, 'Write the brief')); + await wait(`${titles}[0] === 'Write the brief' && ${saveOn}`, 'pending'); + // Step 4 still names merge-gate: the page refuses before sending. await b.evaluate(press('[data-wfg-save]')); await wait(`${text('[data-wfg-status]')} === 'Step 4: merge-gate names no current role. Use an organization role, a role template or human.'`, 'unknown role refused'); assert.equal(st.writes.length, 0); assert.ok(await b.evaluate(`${titles}[0] === 'Write the brief' && !!document.querySelector('[data-wfg-unsaved]')`)); // Fix step 4, then the bus is down. await b.evaluate(pick(4)); - await wait(`document.querySelector('[data-wfg-detail-title]')?.textContent === 'Approve the merge'`, 'step 4'); - await b.evaluate(press('[data-wfg-edit]')); - await wait(`document.querySelector('[data-wfg-form-title]')?.textContent === 'Edit step 4'`, 'form 4'); - await b.evaluate(press(role('[data-wfg-form]', 'merge-gate'))); - await b.evaluate(press('[data-wfg-apply]')); + await wait(`document.querySelector('[data-wfg-detail-title]')?.textContent === 'Approve the merge' && document.querySelector('${form}')`, 'step 4'); + assert.equal(await b.evaluate(`${titles}[0]`), 'Write the brief', 'the step 1 edit went into the workflow'); + await b.evaluate(press(role(form, 'merge-gate'))); await wait(`!document.querySelector('[data-wfg-step="4"] [data-wfg-missing]')`, 'step 4 fixed'); st.refuse = 'no-bus-host'; await b.evaluate(press('[data-wfg-save]')); @@ -437,10 +485,11 @@ test('a refused save says why next to Save and keeps the pending change', { time assert.match(await b.evaluate(text('[data-wfg-status]')), /Your change is kept/); assert.equal(st.writes.length, 1); assert.equal(st.writes[0].args.revision, REV_A); - assert.ok(await b.evaluate(`${titles}[0] === 'Write the brief' && !!document.querySelector('[data-wfg-unsaved]') && !!document.querySelector('[data-wfg-save]')`)); + assert.deepEqual(st.writes[0].args.workflow.steps[3].roles, ['human']); + assert.ok(await b.evaluate(`${titles}[0] === 'Write the brief' && !!document.querySelector('[data-wfg-unsaved]') && ${saveOn}`)); assert.equal(st.docs.acme.workflows.change.steps[0].title, 'Write the task', 'nothing written'); - // The status sits in the bar with Save. - assert.ok(await b.evaluate(`!!document.querySelector('[data-wfg-bar] [data-wfg-status]') && !!document.querySelector('[data-wfg-bar] [data-wfg-save]')`)); + // The status sits in the panel form with its Save. + assert.ok(await b.evaluate(`!!document.querySelector('${form} [data-wfg-status]') && !!document.querySelector('${form} [data-wfg-save]')`)); // Another writer changes this workflow: the save is refused as stale, the change kept. st.change('acme', doc => { doc.workflows.change.description = 'Changed elsewhere.'; }); await b.evaluate(press('[data-wfg-save]')); @@ -453,17 +502,14 @@ test('a refused save says why next to Save and keeps the pending change', { time test('the poll does not draw over a pending change, takes a new revision when only other workflows changed, and says when this one changed', { timeout: 60000 }, async t => { const { b, wait, st, reads } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=2' }); // The site project's workflow names only current roles, so a save goes to the bus. - await wait(`document.querySelector('[data-wfg-edit]')`, 'step 2'); + await wait(`document.querySelector('${form}')`, 'step 2'); const repaint = async () => { const n = reads.length; await b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));true`); await wait(`true`); for (let i = 0; i < 100 && reads.length === n; i++) await new Promise(r => setTimeout(r, 30)); await new Promise(r => setTimeout(r, 150)); }; - // A form being typed in survives a repaint as typed. - await b.evaluate(press('[data-wfg-edit]')); - await wait(`document.querySelector('[data-wfg-form]')`, 'form'); - await b.evaluate(fill('[data-wfg-form] input[name="title"]', 'Ship the release')); - await repaint(); - assert.equal(await b.evaluate(`document.querySelector('[data-wfg-form] input[name="title"]')?.value`), 'Ship the release'); - await b.evaluate(press('[data-wfg-apply]')); - await wait(`${titles}[1] === 'Ship the release' && document.querySelector('[data-wfg-unsaved]')`, 'pending'); + // A form being typed in survives a repaint as typed, the same node. + await b.evaluate(fill(`${form} input[name="title"]`, 'Ship the release')); + await b.evaluate(`window.__form = document.querySelector('${form}'); true`); await repaint(); + assert.equal(await b.evaluate(`document.querySelector('${form} input[name="title"]')?.value`), 'Ship the release'); + assert.equal(await b.evaluate(`document.querySelector('${form}') === window.__form`), true); assert.equal(await b.evaluate(`${titles}[1]`), 'Ship the release', 'the poll keeps the pending change'); assert.ok(await b.evaluate(`!!document.querySelector('[data-wfg-unsaved]')`)); // Another workflow changes in the file: this one is as read, so the page takes the new revision and no warning shows. @@ -471,32 +517,69 @@ test('the poll does not draw over a pending change, takes a new revision when on const fresh = st.revs.acme; await repaint(); assert.equal(await b.evaluate(`document.querySelector('[data-wfg-stale]')`), null); - assert.equal(await b.evaluate(`${titles}[1]`), 'Ship the release'); + assert.equal(await b.evaluate(`document.querySelector('${form} input[name="title"]')?.value`), 'Ship the release'); await b.evaluate(press('[data-wfg-save]')); await wait(`/Saved change\\./.test(${text('[data-wfg-status]')})`, 'saved on the new revision'); assert.equal(st.writes.at(-1).args.revision, fresh); assert.equal(st.docs.acme.workflows.intake.title, 'Intake, renamed', 'the other workflow is untouched'); // Now this workflow changes underneath a pending change: the page says so and offers Discard. - await b.evaluate(press('[data-wfg-edit]')); - await wait(`document.querySelector('[data-wfg-form]')`, 'form again'); - await b.evaluate(fill('[data-wfg-form] input[name="title"]', 'Build it')); - await b.evaluate(press('[data-wfg-apply]')); + await b.evaluate(fill(`${form} input[name="title"]`, 'Build it')); await wait(`${titles}[1] === 'Build it'`, 'pending again'); - st.change('acme', doc => { doc.projects.site.workflows.change.description = 'Changed elsewhere.'; }); + // A change elsewhere to the step being typed in: the page says so instead of taking the file silently. + st.change('acme', doc => { const w = doc.projects.site.workflows.change; w.description = 'Changed elsewhere.'; w.steps[1].state = 'in-review'; }); await repaint(); await wait(`!!document.querySelector('[data-wfg-stale]')`, 'stale note'); assert.match(await b.evaluate(text('[data-wfg-stale]')), /changed this workflow since the page read it.*Discard to load the current version/); - assert.equal(await b.evaluate(`${titles}[1]`), 'Build it'); + assert.equal(await b.evaluate(`document.querySelector('${form} input[name="title"]')?.value`), 'Build it'); assert.ok(await b.evaluate(`!!document.querySelector('[data-wfg-discard]')`)); await b.evaluate(press('[data-wfg-discard]')); await wait(`${titles}[1] === 'Ship the release' && !document.querySelector('[data-wfg-stale],[data-wfg-unsaved]')`, 'discarded to current'); assert.match(await b.evaluate(`document.querySelector('#bus-view .sub').textContent`), /Changed elsewhere\./); }); +// SP17: changes step `step`'s title on the open graph page, so the change is pending and Save is on. +async function retitle(b, wait, step, title) { + await wait(`document.querySelector('${form}')?.dataset.wfgStepForm === '${step - 1}'`, 'step form'); + await b.evaluate(fill(`${form} input[name="title"]`, title)); + await wait(`${titles}[${step - 1}] === ${JSON.stringify(title)} && ${saveOn}`, 'pending change'); +} + +test('SP17: a Save in flight holds the poll, and the page shows the saved workflow from the answer', { timeout: 60000 }, async t => { + const { b, wait, st, reads } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=2' }); + await wait(`${boxes}.length === 2 && document.querySelector('[data-wfg-detail]')`, 'site graph'); + await retitle(b, wait, 2, 'Ship the release'); + // The write is held, so the Save is in flight. + const openWrite = st.hold('write'); + await b.evaluate(press('[data-wfg-save]')); + await wait(`document.querySelector('[data-wfg-save]')?.disabled === true`, 'save in flight'); + // A poll begins while the Save is in flight: its read takes the file as it was before the write. + const openRead = st.hold('read'), n = reads.length; + await b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));true`); + for (let i = 0; i < 200 && reads.length === n; i++) await new Promise(r => setTimeout(r, 20)); + assert.ok(reads.length > n, 'the poll read began'); + openWrite(); + await wait(`/Saved change\\./.test(${text('[data-wfg-status]')})`, 'saved'); + // The poll's read answers only now, with the file as it was before the Save. + openRead(); + await new Promise(r => setTimeout(r, 800)); + assert.deepEqual(await b.evaluate(titles), ['Build', 'Ship the release'], 'the step shows the saved title, not the read from before the Save'); + assert.equal(await b.evaluate(`document.querySelector('[data-wfg-stale],[data-wfg-unsaved]')`), null); + assert.equal(st.writes.length, 1, 'one write'); + // The page took the revision the write answered: the next Save is not refused as changed elsewhere. + const saved = st.revs.acme; + await retitle(b, wait, 2, 'Ship it'); + await b.evaluate(press('[data-wfg-save]')); + await wait(`/Saved change\\./.test(${text('[data-wfg-status]')}) && !document.querySelector('[data-wfg-unsaved]')`, 'second save'); + assert.equal(st.writes.length, 2); + assert.equal(st.writes[1].args.revision, saved); + assert.equal(st.docs.acme.projects.site.workflows.change.steps[1].title, 'Ship it'); +}); + test('a reader who cannot write sees no edit controls and one line saying who can', { timeout: 60000 }, async t => { const { b, wait } = await setup(t, { path: '#/orgs/acme/workflows/change?step=2', writable: false }); await wait(`document.querySelector('[data-wfg-detail-title]')?.textContent === 'Implement the change'`, 'step 2'); - assert.equal(await b.evaluate(`document.querySelector('[data-wfg-bar],[data-wfg-actions],[data-wfg-edit],[data-wfg-add],[data-wfg-save],[data-wfg-delete],[data-wfg-form]')`), null); + assert.equal(await b.evaluate(`document.querySelector('[data-wfg-bar],[data-wfg-actions],[data-wfg-add],[data-wfg-save],[data-wfg-delete],[data-wfg-form],#bus-view input,#bus-view select,#bus-view textarea')`), null); + assert.equal(await b.evaluate(text('[data-wfg-field="roles"]')), 'coder', 'a reader sees the roles as text'); assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('#bus-view [data-wfg-readonly]')].map(n=>n.textContent)`), ['Only the owner, on a Console started with send, can change workflows.']); assert.equal(await b.evaluate(`document.querySelectorAll('#bus-view button').length`), 0); await b.evaluate(`location.hash = '#/orgs/acme/workflows'`); @@ -560,27 +643,39 @@ test('the keyboard alone opens a step, edits it and saves', { timeout: 60000 }, await b.key('Enter'); await wait(`document.querySelector('[data-wfg-detail-title]')?.textContent === 'Build' && document.activeElement?.dataset.focusKey === 'wfg-step:1'`, 'Enter opens step 1'); const tabTo = async (sel, what) => { - for (let i = 0; i < 20; i++) { if (await b.evaluate(`document.activeElement?.matches(${JSON.stringify(sel)}) ?? false`)) return; await b.key('Tab'); } + for (let i = 0; i < 30; i++) { if (await b.evaluate(`document.activeElement?.matches(${JSON.stringify(sel)}) ?? false`)) return; await b.key('Tab'); } throw new Error(`Tab never reached ${what}`); }; - await tabTo('[data-wfg-edit]', 'Edit step'); - await b.key('Enter'); - await wait(`document.querySelector('[data-wfg-form-title]')?.textContent === 'Edit step 1' && document.activeElement?.dataset.focusKey === 'wfg-f-title'`, 'form with focus on the title'); + await tabTo(`${form} input[name="title"]`, 'the step title'); + // Tab selects the field's text; the right arrow puts the caret after it (the harness sends no End key). + await b.key('ArrowRight'); await b.call('Input.insertText', { text: ' now' }); - await tabTo(`[data-wfg-form] input[name="role"][value="reviewer"]`, 'the reviewer box'); + await tabTo(`${form} input[name="role"][value="reviewer"]`, 'the reviewer box'); await b.key(' ', 'Space'); - await tabTo('[data-wfg-apply]', 'Apply'); - await b.key('Enter'); - await wait(`${titles}[0] === 'Build now' && document.activeElement?.dataset.focusKey === 'wfg-save'`, 'applied, focus on Save'); + await tabTo(`${form} [data-wfg-save]`, 'Save'); + await wait(`${titles}[0] === 'Build now'`, 'typed into the graph'); await b.key('Enter'); await wait(`/Saved change\\./.test(${text('[data-wfg-status]')})`, 'saved'); assert.deepEqual(st.writes[0].args, { revision: REV_A, name: 'change', project: 'site', workflow: { title: 'Site release', steps: [ { title: 'Build now', state: 'in-progress', roles: ['coder', 'reviewer'] }, { title: 'Ship', state: 'done', roles: ['human'] }] } }); + // Enter in the title field is Save too, and Escape resets a typed step. + await wait(`document.querySelector('${form} input[name="title"]')?.value === 'Build now'`, 'form after save'); + await b.evaluate(`(()=>{const e=document.querySelector('${form} input[name="title"]');e.focus();e.setSelectionRange(e.value.length,e.value.length);return true})()`); + await b.call('Input.insertText', { text: '!' }); + await wait(`${titles}[0] === 'Build now!'`, 'typed'); + await b.key('Escape'); + await wait(`document.querySelector('${form} input[name="title"]')?.value === 'Build now' && !document.querySelector('[data-wfg-unsaved]')`, 'Escape reset the step'); + await b.evaluate(`(()=>{const e=document.querySelector('${form} input[name="title"]');e.focus();e.setSelectionRange(e.value.length,e.value.length);return true})()`); + await b.call('Input.insertText', { text: ', fast' }); + await b.key('Enter'); + await wait(`${titles}[0] === 'Build now, fast' && !document.querySelector('[data-wfg-unsaved]')`, 'saved by Enter'); + assert.equal(st.writes.length, 2); + assert.equal(st.writes[1].args.workflow.steps[0].title, 'Build now, fast'); }); test('switching organization with a pending workflow change asks first, through the existing draft guard', { timeout: 60000 }, async t => { const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=1' }); - await wait(`document.querySelector('[data-wfg-edit]') && document.querySelector('#breadcrumbs [data-crumb-org]')`, 'step 1'); + await wait(`document.querySelector('${form}') && document.querySelector('#breadcrumbs [data-crumb-org]')`, 'step 1'); await b.evaluate(press('[data-wfg-remove]')); await wait(`${boxes}.length === 1 && document.querySelector('[data-wfg-unsaved]')`, 'pending removal'); assert.equal(await b.evaluate(`window.MosaicWorkflows.hasDraft()`), true); @@ -596,27 +691,42 @@ test('switching organization with a pending workflow change asks first, through assert.equal(st.writes.length, 0); }); -test('Save with a step form holding edits not applied refuses in words and sends nothing; after Apply it sends them', { timeout: 60000 }, async t => { - const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=2' }); - await wait(`document.querySelector('[data-wfg-up]')`, 'step 2'); - // One change pending, so Save shows; then a step form is opened and typed in, not applied. - await b.evaluate(press('[data-wfg-up]')); - await wait(`${titles}[0] === 'Ship' && document.querySelector('[data-wfg-save]')`, 'moved'); - await b.evaluate(press('[data-wfg-edit]')); - await wait(`document.querySelector('[data-wfg-form]')`, 'form'); - await b.evaluate(fill('[data-wfg-form] input[name="title"]', 'Ship the release')); - await b.evaluate(press('[data-wfg-save]')); - await wait(`/Apply or cancel the step first/.test(${text('[data-wfg-status]')})`, 'save refused'); - assert.equal(await b.evaluate(text('[data-wfg-status]')), 'Not saved: step 1 has edits not applied. Apply or cancel the step first.'); +test('a typed step alone counts as a pending change for the switch guard', { timeout: 60000 }, async t => { + const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=1' }); + await wait(`document.querySelector('${form}') && document.querySelector('#breadcrumbs [data-crumb-org]')`, 'step 1'); + await b.evaluate(fill(`${form} input[name="title"]`, 'Build it')); + await wait(`window.MosaicWorkflows.hasDraft()`, 'typed is a draft'); + await b.evaluate(`location.hash = '#/orgs/bare/workflows'`); + await wait(`document.querySelector('dialog[aria-label="Unsaved draft"][open]')`, 'guard dialog'); + await b.evaluate(press('dialog [data-stay]')); + await wait(`!document.querySelector('dialog[open]') && document.querySelector('${form} input[name="title"]')?.value === 'Build it'`, 'stayed with the typed title'); assert.equal(st.writes.length, 0); - assert.equal(await b.evaluate(`document.querySelector('[data-wfg-form] input[name="title"]')?.value`), 'Ship the release', 'the typed title stays'); - await b.evaluate(press('[data-wfg-apply]')); - await wait(`${titles}[0] === 'Ship the release'`, 'applied'); - assert.equal(await b.evaluate(`document.querySelector('[data-wfg-status]')`), null, 'Apply clears the refusal'); +}); + +test('a step edit goes into the workflow when another step is opened or a step moves, and Save sends it; one the save check refuses stays in its form', { timeout: 60000 }, async t => { + const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=2' }); + await wait(`document.querySelector('[data-wfg-up]') && document.querySelector('${form}')`, 'step 2'); + // A typed title, then Move earlier: the step moves with its new title. + await b.evaluate(fill(`${form} input[name="title"]`, 'Ship the release')); + await b.evaluate(press('[data-wfg-up]')); + await wait(`${titles}[0] === 'Ship the release' && /step=1/.test(location.hash) && ${saveOn}`, 'moved with the edit'); + assert.equal(await b.evaluate(`document.querySelector('${form} input[name="title"]').value`), 'Ship the release'); + // An edit the save check refuses (no role left) stays: opening another step does not happen, and the form says why. + await b.evaluate(press(role(form, 'human'))); + await b.evaluate(pick(2)); + await wait(`${text('[data-wfg-why]')} === 'Step 1 needs at least one role.'`, 'refused in the form'); + assert.match(await b.evaluate(`location.hash`), /step=1/); + assert.equal(await b.evaluate(`document.activeElement?.dataset.focusKey`), 'wfg-f-title'); + // Save says the same and sends nothing. + await b.evaluate(press('[data-wfg-save]')); + await wait(`${text('[data-wfg-status]')} === 'Not saved: Step 1 needs at least one role.'`, 'save refused'); + assert.equal(st.writes.length, 0); + assert.equal(await b.evaluate(`document.querySelector('${form} input[name="title"]')?.value`), 'Ship the release', 'the typed title stays'); + await b.evaluate(press(role(form, 'coder'))); await b.evaluate(press('[data-wfg-save]')); await wait(`/Saved change\\./.test(${text('[data-wfg-status]')})`, 'saved'); assert.equal(st.writes.length, 1); - assert.deepEqual(st.writes[0].args.workflow.steps.map(s => s.title), ['Ship the release', 'Build']); + assert.deepEqual(st.writes[0].args.workflow.steps, [{ title: 'Ship the release', state: 'done', roles: ['coder'] }, { title: 'Build', state: 'in-progress', roles: ['coder'] }]); }); test('Delete on a view another writer has changed is refused, not deleted over', { timeout: 60000 }, async t => { @@ -624,7 +734,8 @@ test('Delete on a view another writer has changed is refused, not deleted over', await wait(`document.querySelector('[data-wfg-remove]')`, 'step 1'); await b.evaluate(press('[data-wfg-remove]')); await wait(`${boxes}.length === 1 && document.querySelector('[data-wfg-unsaved]')`, 'pending removal'); - st.change('acme', doc => { doc.projects.site.workflows.change.description = 'Changed elsewhere.'; }); + // A change elsewhere to the step being typed in: the page says so instead of taking the file silently. + st.change('acme', doc => { const w = doc.projects.site.workflows.change; w.description = 'Changed elsewhere.'; w.steps[1].state = 'in-review'; }); const n = reads.length; await b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));true`); await wait(`!!document.querySelector('[data-wfg-stale]')`, 'stale note'); @@ -660,10 +771,229 @@ test('a failed read says a pending change is kept, and it comes back when the re st.failRead = true; await b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));true`); await wait(`!!document.querySelector('[data-wfg-error]') && !!document.querySelector('[data-wfg-held]')`, 'error with kept note'); - assert.equal(await b.evaluate(text('[data-wfg-held]')), 'Unsaved change to change is kept on this page. It comes back when the workflows can be read.'); + // SP17: the page keeps drawing the last read with the change on it, and says the read failed. + assert.equal(await b.evaluate(text('[data-wfg-error]')), 'The last workflows read failed: The organization file could not be read. The page shows the read before it.'); + assert.equal(await b.evaluate(text('[data-wfg-held]')), 'Unsaved change to change is kept on this page.'); + assert.equal(await b.evaluate(`${boxes}.length`), 1, 'the pending removal is still drawn'); assert.equal(await b.evaluate(`window.MosaicWorkflows.hasDraft()`), true); st.failRead = false; await b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));true`); - await wait(`${boxes}.length === 1 && !!document.querySelector('[data-wfg-unsaved]') && !document.querySelector('[data-wfg-held]')`, 'back'); + await wait(`${boxes}.length === 1 && !!document.querySelector('[data-wfg-unsaved]') && !document.querySelector('[data-wfg-held],[data-wfg-error]')`, 'back'); assert.equal(st.writes.length, 0); }); + +// SP17 item 1: changing one field of one step of a saved workflow and saving it, from another organization's +// page: the organization in the sidebar, the step on its Workflows card, Save. Typing is not a click. Each +// click is a real pointer press at the element's centre, counted by the page. At 390 the sidebar sits behind +// the menu button, which is one more click; from the organization's own page it is two clicks at any width. +test('SP17: one field of one step changes and saves in three clicks', { timeout: 90000 }, async t => { + const cases = [ + { name: '1440 from another organization', viewport: [1440, 900], from: 'bare', want: [/Acme Studio/, 'Ship', 'Save'] }, + { name: '390 from another organization', viewport: [390, 844], from: 'bare', want: ['Open menu', /Acme Studio/, 'Ship', 'Save'] }, + { name: '390 from the organization page', viewport: [390, 844], from: 'acme', want: ['Ship', 'Save'] }, + ]; + for (const c of cases) { + await t.test(c.name, async t2 => { + const { b, wait, st } = await setup(t2, { path: `#/orgs/${c.from}/organization`, viewport: c.viewport }); + await wait(`document.querySelector('[data-org-dashboard] [data-wfg-card]')`, 'organization page'); + await b.evaluate(`window.__clicks = []; addEventListener('click', e => { if (e.isTrusted) { const a = e.target.closest('a,button'); __clicks.push(a?.getAttribute('aria-label') === 'Open menu' ? 'Open menu' : a?.textContent.trim() ?? e.target.tagName); } }, true); true`); + const click = async (sel, what) => { + await wait(`(()=>{const e=document.querySelector(${JSON.stringify(sel)});return !!e && !e.disabled && e.getClientRects().length>0})()`, what); + const { x, y } = await b.evaluate(`(()=>{const e=document.querySelector(${JSON.stringify(sel)});e.scrollIntoView({block:'center'});const r=e.getBoundingClientRect();return {x:r.left+r.width/2,y:r.top+r.height/2}})()`); + // What is under the pointer is the element meant, not something drawn over it. + assert.ok(await b.evaluate(`(()=>{const e=document.querySelector(${JSON.stringify(sel)}),h=document.elementFromPoint(${x},${y});return !!h&&(e===h||e.contains(h))})()`), `${what} is under the pointer`); + for (const type of ['mousePressed', 'mouseReleased']) await b.call('Input.dispatchMouseEvent', { type, x, y, button: 'left', clickCount: 1 }); + }; + if (c.from !== 'acme') { + if (c.viewport[0] === 390) { + await click('#nav-open', 'the menu button'); + await wait(`document.body.classList.contains('nav-open')`, 'menu open'); + await new Promise(r => setTimeout(r, 400)); + } + await click('[data-workspace-org="acme"] a', 'Acme in the sidebar'); + await wait(`location.hash === '#/orgs/acme/organization' && document.querySelector('[data-org-dashboard] [data-wfg-card] [data-wfg-card-step]') && !document.body.classList.contains('nav-open')`, 'acme page with its card'); + await new Promise(r => setTimeout(r, 400)); + } + await click('[data-wfg-card] [data-wfg-card-step][href="#/orgs/acme/workflows/change?project=site&step=2"]', 'step 2 on the card'); + // The step's title field has focus, the caret at the end, ready to type. + await wait(`document.activeElement?.matches('[data-wfg-step-form] input[name="title"]') && document.activeElement.value === 'Ship'`, 'focus in the title'); + assert.equal(await b.evaluate(`document.activeElement.selectionStart`), 4); + // The title and Save are both on screen without a scroll (SP17 shots: at 390 Save was below the fold). + const inView = sel => `(()=>{const r=document.querySelector(${JSON.stringify(sel)}).getBoundingClientRect();return r.top>=0&&r.bottom<=innerHeight})()`; + assert.equal(await b.evaluate(inView('[data-wfg-step-form] input[name="title"]')), true, 'title in view'); + assert.equal(await b.evaluate(inView('[data-wfg-step-form] [data-wfg-save]')), true, 'Save in view'); + assert.match(await b.evaluate(`document.getElementById('announce')?.textContent ?? ''`), /Step 2, Ship\. Change it and press Save\./); + await b.call('Input.insertText', { text: ' the release' }); + await click('[data-wfg-step-form] [data-wfg-save]', 'Save'); + await wait(`/Saved change\\./.test(${text('[data-wfg-status]')}) && !document.querySelector('[data-wfg-unsaved]')`, 'saved'); + // Focus stays in the step's title, and the line saying it saved is on screen. + await wait(`document.activeElement?.dataset.focusKey === 'wfg-f-title'`, 'focus kept in the form'); + assert.equal(await b.evaluate(inView('[data-wfg-step-form] [data-wfg-status]')), true, 'Saved line in view'); + const clicks = await b.evaluate(`__clicks`); + assert.equal(clicks.length, c.want.length, `${c.want.length} clicks: ${JSON.stringify(clicks)}`); + c.want.forEach((w, i) => (w instanceof RegExp ? assert.match(clicks[i], w) : assert.equal(clicks[i], w))); + assert.equal(st.writes.length, 1); + assert.deepEqual(st.writes[0].args, { revision: REV_A, name: 'change', project: 'site', workflow: { title: 'Site release', steps: [ + { title: 'Build', state: 'in-progress', roles: ['coder'] }, { title: 'Ship the release', state: 'done', roles: ['human'] }] } }); + }); + } +}); + +// SP17 item 4: an edit open when the organization's bus restarts is not lost without a word. The list is +// read again (as the bus banner and Restart bus do) and the page drawn again (as the poll does). +const relist = `(async()=>{await window.MosaicOrg.refreshList();document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));return true})()`; +const heldLinks = `[...document.querySelectorAll('[data-wfg-card] [data-wfg-held] [data-wfg-held-link]')].map(a=>[a.getAttribute('href'),a.textContent])`; + +test('SP17: a step edit open while the bus restarts, then stops, is kept and named, and saves when the bus is back', { timeout: 90000 }, async t => { + const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=2' }); + await retitle(b, wait, 2, 'Ship it'); + // Restarting: the bus does not answer, the file still reads. The form stays as typed; Save says why it did not save. + st.down.acme = 'restarting'; + await b.evaluate(relist); + await b.evaluate(`new Promise(r=>setTimeout(()=>r(true),300))`); + assert.equal(await b.evaluate(`document.querySelector('${form} input[name="title"]')?.value`), 'Ship it'); + await b.evaluate(press('[data-wfg-save]')); + await wait(`/the organization bus is not running/.test(document.querySelector('[data-wfg-status]')?.textContent ?? '')`, 'no bus host'); + assert.match(await b.evaluate(`document.body.innerText`), /Your change is kept/); + assert.equal(await b.evaluate(`document.querySelector('${form} input[name="title"]')?.value`), 'Ship it'); + // Stopped: the page does not read the organization. It says the change is kept, on this page and on the + // organization's card, which links back to it. + st.down.acme = 'stopped'; + await b.evaluate(relist); + await wait(`!document.querySelector('${form}') && !!document.querySelector('[data-wfg-held]')`, 'kept note while stopped'); + assert.equal(await b.evaluate(text('[data-wfg-held]')), 'Unsaved change to change is kept on this page. It comes back when the workflows can be read.'); + assert.equal(await b.evaluate(`window.MosaicWorkflows.hasDraft()`), true); + await b.evaluate(`location.hash = '#/orgs/acme/organization';true`); + await wait(`!!document.querySelector('[data-wfg-card][data-bus-stopped] [data-wfg-held]')`, 'card kept note while stopped'); + assert.deepEqual(await b.evaluate(heldLinks), [['#/orgs/acme/workflows/change?project=site', 'change (project site)']]); + // Back: the card still names it; its link opens the graph with the step as typed, and Save writes it. + delete st.down.acme; + await b.evaluate(relist); + await wait(`!document.querySelector('[data-wfg-card][data-bus-stopped]') && !!document.querySelector('[data-wfg-card] [data-wfg-held-link]')`, 'card back with kept note'); + await b.evaluate(`document.querySelector('[data-wfg-card] [data-wfg-held-link]').click();true`); + await wait(`location.hash === '#/orgs/acme/workflows/change?project=site' && ${titles}[1] === 'Ship it' && ${saveOn}`, 'kept change drawn'); + const before = st.writes.length; + await b.evaluate(press('[data-wfg-save]')); + await wait(`!document.querySelector('[data-wfg-unsaved]') && !${saveOn}`, 'saved'); + assert.equal(st.writes.length, before + 1); + assert.equal(st.writes.at(-1).args.revision, REV_A); + assert.equal(st.writes.at(-1).args.workflow.steps[1].title, 'Ship it'); + assert.equal(st.docs.acme.projects.site.workflows.change.steps[1].title, 'Ship it'); + assert.equal(await b.evaluate(`window.MosaicWorkflows.hasDraft()`), false); + await b.evaluate(`location.hash = '#/orgs/acme/organization';true`); + await wait(`!!document.querySelector('[data-wfg-card] [data-wfg-card-item]')`, 'card'); + assert.equal(await b.evaluate(`!!document.querySelector('[data-wfg-card] [data-wfg-held]')`), false, 'nothing is held once saved'); +}); + +test('SP17: Restart bus on the organization page with a step edit open keeps it, names it on the card, and it saves after', { timeout: 90000 }, async t => { + const restarts = []; + const admin = st => createOrgAdmin({ + service: { showOrg: async (ctx, id) => ({ id, revision: 1, doc: {} }) }, registry: { listOrgs: async () => [] }, context: async () => ({ configDir: '/cfg', dataRoot: '/data', instance: 'test' }), + bus: { + busStatus: async (ctx, id) => ({ org: id, healthy: !st.down[id], pid: st.down[id] ? null : 4242 }), + // The restart takes the bus down, and it comes back before the answer, as a real restart does. + busRestart: async (ctx, id) => { restarts.push(id); st.down[id] = 'restarting'; await new Promise(r => setTimeout(r, 200)); delete st.down[id]; return { org: id, pid: 4343, socket: '/data/s', root: `/data/org-runtime/${id}` }; }, + busStart: async () => { throw Error('not reached: the bus runs'); }, + }, + }); + const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=2', admin }); + await retitle(b, wait, 2, 'Ship it'); + await b.evaluate(`location.hash = '#/orgs/acme/organization';true`); + await wait(`!!document.querySelector('[data-org-dashboard] [data-bus-restart]') && !!document.querySelector('[data-wfg-card] [data-wfg-held-link]')`, 'restart button and kept note'); + assert.deepEqual(await b.evaluate(heldLinks), [['#/orgs/acme/workflows/change?project=site', 'change (project site)']]); + await b.evaluate(press('[data-org-dashboard] [data-bus-restart]')); + await wait(`/It answers/.test(document.querySelector('[data-org-dashboard] [data-bus-restart-receipt]')?.textContent || '')`, 'restart receipt'); + assert.deepEqual(restarts, ['acme']); + await b.evaluate(relist); + await wait(`!!document.querySelector('[data-wfg-card] [data-wfg-held-link]')`, 'kept note after the restart'); + assert.deepEqual(await b.evaluate(heldLinks), [['#/orgs/acme/workflows/change?project=site', 'change (project site)']]); + assert.equal(await b.evaluate(`window.MosaicWorkflows.hasDraft()`), true); + await b.evaluate(`document.querySelector('[data-wfg-card] [data-wfg-held-link]').click();true`); + await wait(`location.hash === '#/orgs/acme/workflows/change?project=site' && ${titles}[1] === 'Ship it' && ${saveOn}`, 'kept change drawn'); + await b.evaluate(press('[data-wfg-save]')); + await wait(`!document.querySelector('[data-wfg-unsaved]') && !${saveOn}`, 'saved'); + assert.equal(st.writes.length, 1); + assert.equal(st.writes[0].args.revision, REV_A); + assert.equal(st.docs.acme.projects.site.workflows.change.steps[1].title, 'Ship it'); +}); + +// SP17 review P2-1: an open edit of one step is not dropped when another step is opened from the card or the +// address and typed in. Both edits go in the one Save. +test('SP17: an edit of step 1 is kept when step 2 is opened from the card or the address and changed, and Save sends both', { timeout: 90000 }, async t => { + const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=1' }); + await retitle(b, wait, 1, 'Build it'); + // From the card: the card says the change is kept; its step link opens step 2. + await b.evaluate(`location.hash = '#/orgs/acme/organization';true`); + await wait(`!!document.querySelector('[data-wfg-card] [data-wfg-held-link]')`, 'card kept note'); + await b.evaluate(`document.querySelector('[data-wfg-card] a[data-wfg-card-step][href="#/orgs/acme/workflows/change?project=site&step=2"]').click();true`); + await wait(`document.querySelector('${form}')?.dataset.wfgStepForm === '1'`, 'step 2 form'); + assert.deepEqual(await b.evaluate(titles), ['Build it', 'Ship']); + await retitle(b, wait, 2, 'Ship it'); + assert.deepEqual(await b.evaluate(titles), ['Build it', 'Ship it'], 'typing in step 2 keeps step 1 as changed'); + await b.evaluate(press('[data-wfg-save]')); + await wait(`/Saved change\\./.test(${text('[data-wfg-status]')})`, 'saved'); + assert.deepEqual(st.writes.at(-1).args.workflow.steps.map(s => s.title), ['Build it', 'Ship it']); + // From the address: step 1 changed, then the address names step 2. + await b.evaluate(`location.hash = '#/orgs/acme/workflows/change?project=site&step=1';true`); + await retitle(b, wait, 1, 'Build again'); + await b.evaluate(`location.hash = '#/orgs/acme/workflows/change?project=site&step=2';true`); + await wait(`document.querySelector('${form}')?.dataset.wfgStepForm === '1'`, 'step 2 form from the address'); + await retitle(b, wait, 2, 'Ship again'); + assert.deepEqual(await b.evaluate(titles), ['Build again', 'Ship again']); + // Reset step on step 2 puts back step 2 only. + await b.evaluate(press('[data-wfg-cancel]')); + await wait(`${titles}[1] === 'Ship it'`, 'step 2 reset'); + assert.deepEqual(await b.evaluate(titles), ['Build again', 'Ship it'], 'Reset step on step 2 leaves step 1 changed'); + await b.evaluate(press('[data-wfg-save]')); + await wait(`/Saved change\\./.test(${text('[data-wfg-status]')})`, 'second save'); + assert.deepEqual(st.writes.at(-1).args.workflow.steps.map(s => s.title), ['Build again', 'Ship it']); +}); + +// SP17 review P2-2: nothing typed while a Save is in flight is dropped: the form's fields take no typing until +// the write answers. +test('SP17: while a Save is in flight the form takes no typing, and takes it again after', { timeout: 60000 }, async t => { + const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=2' }); + await retitle(b, wait, 2, 'Ship it'); + const fields = `[...document.querySelectorAll('${form} input[name="title"], ${form} select, ${form} [data-wfg-roles-pick]')].map(e=>e.disabled)`; + const openWrite = st.hold('write'); + await b.evaluate(press('[data-wfg-save]')); + await wait(`document.querySelector('[data-wfg-save]')?.disabled === true`, 'save in flight'); + assert.deepEqual(await b.evaluate(fields), [true, true, true], 'title, state and roles are off while saving'); + // A poll redraw during the write keeps them off. + await b.evaluate(`document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));true`); + await b.evaluate(`new Promise(r=>setTimeout(()=>r(true),300))`); + assert.deepEqual(await b.evaluate(fields), [true, true, true], 'still off after a redraw'); + openWrite(); + await wait(`/Saved change\\./.test(${text('[data-wfg-status]')})`, 'saved'); + assert.deepEqual(await b.evaluate(fields), [false, false, false], 'on again once saved'); + assert.equal(st.writes.at(-1).args.workflow.steps[1].title, 'Ship it'); + // A refused Save gives the fields back too. + await retitle(b, wait, 2, 'Ship again'); + st.down.acme = 'restarting'; + await b.evaluate(press('[data-wfg-save]')); + await wait(`/the organization bus is not running/.test(document.querySelector('[data-wfg-status]')?.textContent ?? '')`, 'refused'); + assert.deepEqual(await b.evaluate(fields), [false, false, false], 'on again after a refusal'); + assert.equal(await b.evaluate(`document.querySelector('${form} input[name="title"]').value`), 'Ship again'); +}); + +// SP17 review 2 P2-1: a new step typed in the add form is not dropped by the bar's Save: Save says it is not +// added yet and keeps the form; once added, Save sends it. +test('SP17: the bar Save with a new step typed in the add form says so and keeps it, and saves it once added', { timeout: 60000 }, async t => { + const { b, wait, st } = await setup(t, { path: '#/orgs/acme/workflows/change?project=site&step=1' }); + await retitle(b, wait, 1, 'Build it'); + await b.evaluate(press('[data-wfg-add]')); + await wait(`!!document.querySelector('[data-wfg-add-form]')`, 'add form'); + await b.evaluate(fill('[data-wfg-add-form] input[name="title"]', 'Check')); + await b.evaluate(`document.querySelector('[data-wfg-add-form] input[name="role"][value="human"]').click();true`); + await b.evaluate(press('[data-wfg-bar] [data-wfg-save]')); + await wait(`/new step 2 is not added yet/.test(${text('[data-wfg-bar] [data-wfg-status]')})`, 'refused in words'); + assert.equal(st.writes.length, 0, 'nothing written'); + assert.equal(await b.evaluate(`document.querySelector('[data-wfg-add-form] input[name="title"]')?.value`), 'Check', 'the typed step is kept'); + assert.equal(await b.evaluate(`document.activeElement === document.querySelector('[data-wfg-add-form] input[name="title"]')`), true, 'focus in the new step'); + assert.equal(await b.evaluate(`window.MosaicWorkflows.hasDraft()`), true); + await b.evaluate(press('[data-wfg-add-step]')); + await wait(`${titles}.length === 3`, 'step added'); + await b.evaluate(press('[data-wfg-save]')); + await wait(`/Saved change\\./.test(${text('[data-wfg-status]')})`, 'saved'); + assert.deepEqual(st.writes.at(-1).args.workflow.steps.map(s => [s.title, s.roles]), [['Build it', ['coder']], ['Check', ['human']], ['Ship', ['human']]]); +});