Skip to content

Workflow Branching Developer Guide 2 Editor

Ed Mozley edited this page Nov 20, 2026 · 1 revision

Workflow branching - Developer Guide, part 2: the canvas editor

Part 1: the engine Β· Part 2 of 3 Β· Part 3: safety, saving and tests Β· Workflow branching - design Β· GH #364

The engine side of branching is small; the editor is where the work is. The canvas was built for a straight line - every box free-floating, ordered by its height on screen - and a branch is a box that contains other boxes. This page explains how the editor models that, draws it, lets you click and edit what is inside, and writes it back.

The files

File Change
🟑 assets/js/workflow-editor.js The branch model, drawing, clicks, detail panels, layout, save / load (?v=29)
🟑 assets/js/workflow-executions.js The execution log draws a branch and its path (?v=5)
πŸ”΅ assets/css/workflow.css .wf-br* styles, --wf-branch colour, dark mode (?v=14)
🟣 workflow/editor.php Add branch button + menu; the wfBodyBranch detail panel
🌐 lang/*/workflow.php workflow.branch.* (56 strings) and the help section, 9 languages

1. The canvas before branching

workflow-editor.js keeps one array, nodes. Each node is {id, kind, x, y, el, ...} with kind one of trigger, condition, action. On save the conditions and the actions are each sorted by y - the order on screen is the order of execution - and written out. Connectors are not stored; they are drawn from that same sorted order.

A branch fits in by being one more kind of top-level node, branch, sorted in with the actions by y. Everything inside it is not a canvas node: paths, their conditions and their actions live inside the branch object and are drawn inside its box.

2. The model

//    branch {id, kind:'branch', type, field, compare, lanes[], parent?}
//    lane   {id, kind:'lane', role: branch|case|otherwise|default, label,
//            match, values[], conds[], items[], parent: branch}
//    items in a lane: {kind:'action', type, args, parent: lane} or a branch
//    conds in a lane: {kind:'condition', field, op, value, parent: lane}
//  Every item gets a local id; registry maps it back for findNode().
const BRANCH_TYPES = ['branch_if', 'branch_switch'];
const MAX_BRANCH_DEPTH = 3;
const registry = new Map();

A lane is one path, drawn as a column. Its role says what it is: branch (an If branch), case, or the fallback - otherwise / default. The fallback is always the last lane.

Two design choices carry the rest of the editor:

  1. Nested items reuse the existing kinds. An action inside a lane is {kind: 'action', type, args} - the same shape as a canvas action node - and a condition is {kind: 'condition', field, op, value}. So the existing action and condition detail panels (showDetailForAction(), showDetailForCondition()) edit them unchanged: every action type's form, the merge-code picker, lookups, webhook test - all for free.
  2. Every item knows its parent. That is how a delete knows which list to take it out of, and how depthOf() counts nesting:
/** How many branches deep an item is (a top-level branch is 0). */
function depthOf(b) {
    let d = 0, p = b.parent;
    while (p) { if (p.kind === 'branch') d++; p = p.parent; }
    return d;
}

Finding anything by id

The old code looked up the selected node with nodes.find(x => x.id === selectedNodeId) in seven places. A nested item is not in nodes, so all seven now go through one function:

/** The selected thing by id: a canvas node, or anything inside a branch. */
function findNode(id) {
    return nodes.find(x => x.id === id) || registry.get(id) || null;
}
/** Give an item an id and remember it. */
function reg(o) { o.id = nextLocalId--; registry.set(o.id, o); return o; }

Ids are negative local numbers, the same counter the canvas already used (nextLocalId--), so a nested item's id can never collide with a node's.

⚠️ One lookup was missed at first and found by testing: selectNode() used nodes.find(x => x.id === id) - id, not selectedNodeId, so the search-and-replace skipped it. Clicking a path outlined it but opened nothing. A scripted click test caught it (the panel title stayed "Workflow"); it now calls findNode(id).

Redrawing after an edit

The detail panels redraw what they edit with n.el.innerHTML = renderNodeContent(n). A nested item has no element of its own - it is drawn inside its branch - so every such call now goes through:

/** Redraw an edited item: its own element, or the branch box it sits in. */
function refreshNode(n) {
    if (n && n.el && n.kind !== 'branch') { n.el.innerHTML = renderNodeContent(n); return; }
    renderAll();
}

renderAll() rebuilds the canvas but not the right-hand panel, so typing in a panel keeps its focus while the box updates.

3. Engine JSON ⇄ editor model

Loading turns a stored branch into the model; saving turns it back. The two functions are exact inverses - the round-trip test in part 3 saves from the editor and checks the stored JSON is unchanged.

/** Engine shape -> editor model. */
function branchFromStored(a, parent) {
    const args = a.args || {};
    const b = reg({ kind: 'branch', type: a.type, field: args.field || '', compare: args.compare === 'contains' ? 'contains' : 'equals', lanes: [], parent });
    const lane = (role, src) => {
        const l = reg({ kind: 'lane', role, label: (src && src.label) || '', match: (src && src.match) === 'any' ? 'any' : 'all',
                        values: Array.isArray(src && src.values) ? src.values.map(String) : [], conds: [], items: [], parent: b });
        ((src && src.conditions) || []).forEach(c => l.conds.push(reg({ kind: 'condition', field: c.field || '', op: c.op || 'equals', value: c.value ?? '', parent: l })));
        ((src && src.actions) || []).forEach(x => l.items.push(itemFromStored(x, l)));
        return l;
    };
    if (a.type === 'branch_if') {
        (args.branches || []).forEach(br => b.lanes.push(lane('branch', br)));
        b.lanes.push(lane('otherwise', args.otherwise || {}));
    } else {
        (args.cases || []).forEach(c => b.lanes.push(lane('case', c)));
        b.lanes.push(lane('default', args.default || {}));
    }
    return b;
}
/** One stored entry inside a path -> an action item or a nested branch. */
function itemFromStored(x, lane) {
    if (BRANCH_TYPES.includes(x.type)) return branchFromStored(x, lane);
    return reg({ kind: 'action', type: x.type || 'log_message', args: x.args || {}, parent: lane });
}

Note the fallback lane is pushed even when the stored branch has none - the editor can never show a branch without one.

/** Editor model -> engine shape. */
function branchToStored(b) {
    const items = l => l.items.map(i => i.kind === 'branch' ? branchToStored(i) : { type: i.type, args: i.args || {} });
    if (b.type === 'branch_if') {
        return { type: 'branch_if', args: {
            branches: b.lanes.filter(l => l.role === 'branch').map(l => ({ label: l.label, match: l.match,
                conditions: l.conds.map(c => ({ field: c.field, op: c.op, value: c.value })), actions: items(l) })),
            otherwise: { actions: items(b.lanes.find(l => l.role === 'otherwise') || { items: [] }) },
        } };
    }
    return { type: 'branch_switch', args: {
        field: b.field, compare: b.compare,
        cases: b.lanes.filter(l => l.role === 'case').map(l => ({ label: l.label, values: l.values, actions: items(l) })),
        default: { actions: items(b.lanes.find(l => l.role === 'default') || { items: [] }) },
    } };
}

Both recurse: a nested branch inside items goes back through branchFromStored() / branchToStored().

In loadWorkflow() and save():

// loadWorkflow(): a stored branch becomes a branch node
if (BRANCH_TYPES.includes(a.type)) {   // GH #364
    const b = branchFromStored(a, null);
    b.x = snap(x); b.y = snap(y);
    nodes.push(b);
    ...
}

// save(): branches are sorted in with the actions by y
const actionNodes = nodes.filter(n => n.kind === 'action' || n.kind === 'branch');
const actions = actionNodes
    .slice().sort((a, b) => a.y - b.y)
    .map(n => n.kind === 'branch' ? Object.assign(branchToStored(n), { x: n.x, y: n.y }) : ({ type: n.type, args: n.args || {}, x: n.x, y: n.y }));

collectWorkflowForApi() (what the AI co-author is sent) does the same, so the AI sees the branch in the workflow it is asked to improve.

4. Drawing a branch

A canvas node is normally a fixed-size box (SIZE[kind]). A branch is as big as its content, so createNodeEl() hands it off:

if (n.kind === 'branch') return createBranchEl(el, n);   // GH #364: sized by its content
function createBranchEl(el, n) {
    registryRebuild();
    el.innerHTML = branchHtml(n);
    el.addEventListener('mousedown', e => onBranchMouseDown(e, n));
    return el;
}

branchHtml() builds the box as one string, recursively - a nested branch is branchHtml() called from inside a lane:

function branchHtml(b) {
    const d = depthOf(b);
    const head = b.type === 'branch_if'
        ? '<span class="wf-br-kind">' + esc(BT('if_title')) + '</span>'
        : '<span class="wf-br-kind">' + esc(BT('switch_title')) + '</span> <span class="wf-br-field">' + esc((b.field || '?').split('.').pop()) + ' Β· ' + esc(b.compare === 'contains' ? BT('compare_contains') : BT('compare_equals')) + '</span>';
    const lanes = b.lanes.map(l => {
        const isDefault = l.role === 'otherwise' || l.role === 'default';
        const items = l.items.map(i => i.kind === 'branch' ? branchHtml(i) : chipHtml(i)).join('') || '<div class="wf-br-empty">' + esc(BT('nothing_here')) + '</div>';
        const addBranchBtns = d + 1 < MAX_BRANCH_DEPTH
            ? '<button type="button" class="wf-br-add-btn" data-add-branch="branch_if" data-lane="' + l.id + '">+ ' + esc(BT('add_if')) + '</button>'
            + '<button type="button" class="wf-br-add-btn" data-add-branch="branch_switch" data-lane="' + l.id + '">+ ' + esc(BT('add_choose')) + '</button>' : '';
        return '<div class="wf-br-lane' + (isDefault ? ' is-default' : '') + '">'
            + '<div class="wf-br-lane-head" data-sel="' + l.id + '">...title + summary...</div>'
            + '<div class="wf-br-items">' + items + '</div>'
            + '<div class="wf-br-add"><button type="button" class="wf-br-add-btn" data-add-action="' + l.id + '">+ ' + esc(BT('add_action')) + '</button>' + addBranchBtns + '</div>'
            + '</div>';
    }).join('');
    return '<div class="wf-br' + (d ? ' is-nested' : '') + '"' + (d ? ' data-sel="' + b.id + '"' : '') + '>'
        + '<div class="wf-br-head"' + (d ? '' : ' data-head="1"') + '>' + head + '</div>'
        + '<div class="wf-br-lanes">' + lanes + '</div></div>';
}
  • Every user-supplied string goes through esc() (labels, field names, values) - the box is built as HTML, so this matters; ids are numbers the editor made.
  • data-sel marks every clickable item with its registry id; data-head marks only the top-level box's heading, which is the drag handle.
  • The depth limit is enforced in the UI by not drawing + If / + Choose in a lane already at depth 2. The save routes enforce it again (part 3).
  • An action card is drawn by the same renderNodeContent() a canvas action box uses (chipHtml()), so it shows the same title and one-line summary.

Sizing: the bug Ed found on first look

A canvas box is position: absolute. An absolutely positioned element with width: auto shrinks to fit - but never wider than the space left to the right edge of its containing block. A branch placed at x = 220 on a 1,200px canvas had at most ~980px, the columns were squeezed to share it, and a nested If inside a column spilled out of it. Ed saw it the first time he opened the demo.

/* assets/css/workflow.css */
/* GH #364: a branch box is as wide as its content needs. Positioned absolutely on the canvas,
   its width would otherwise be capped by the space left to the canvas's right edge, squeezing
   the lanes narrower than a nested branch inside them - which then spilled out of its lane. */
.wf-node-branch, .wf-br { width: max-content; }
.wf-br-lane { flex: 0 0 auto; min-width: 180px; }
.wf-br-chip, .wf-br-lane-head { max-width: 260px; box-sizing: border-box; }
.wf-br-add { flex-wrap: nowrap; }

max-content lets the box grow to fit; the action cards and summaries are capped at 260px so a long message wraps instead of making one column enormous. The canvas grows to fit the box (updateCanvasSize()), so wide workflows scroll sideways.

The connectors and canvas sizing need a node's size; a branch's comes from its element after it is drawn:

/** A node's drawn size; a branch box is as big as its content. */
function sizeOf(n) {
    if (n.kind === 'branch') {
        return { w: (n.el && n.el.offsetWidth) || 360, h: (n.el && n.el.offsetHeight) || 220 };
    }
    return SIZE[n.kind];
}

Every SIZE[n.kind] in the drawing code (lowestNodeY(), drawConnector(), updateCanvasSize()) now calls sizeOf(n).

Layout: a growing box must not swallow what is below it

Adding a path or an action makes the box taller, and a box that was placed with room under it can grow over the next action. renderAll() ends by moving anything now underneath a branch down below it:

/**
 * GH #364: a branch box grows as paths and actions are added, so anything that now sits
 * under it - in its columns - is moved down below it, in order. Only ever downwards and
 * only what overlaps, so a layout somebody arranged is otherwise left as it is.
 */
function clearBranches() {
    const sorted = nodes.filter(n => n.kind !== 'trigger').slice().sort((a, b) => a.y - b.y);
    sorted.forEach(b => {
        if (b.kind !== 'branch') return;
        const bz = sizeOf(b);
        let floor = b.y + bz.h + ROW_GAP;
        sorted.forEach(n => {
            if (n === b || n.y < b.y) return;
            const nz = sizeOf(n);
            const overlapsX = n.x < b.x + bz.w && n.x + nz.w > b.x;
            if (overlapsX && n.y < floor) {
                n.y = snap(floor);
                if (n.el) n.el.style.top = n.y + 'px';
                floor = n.y + nz.h + ROW_GAP;
            }
        });
    });
}

Moving a node changes the execution order only if it changes its rank by y - and it never does here: nodes only move down, in their existing order, past a branch that was already above them.

5. Clicks inside a branch

The canvas's own mousedown starts a drag. Inside a branch the same click might mean "drag the box", "select this action", "select this path" or "add an action here", so the branch has its own handler that decides first:

function onBranchMouseDown(e, n) {
    const t = e.target;
    const addA = t.closest('[data-add-action]');
    const addB = t.closest('[data-add-branch]');
    if (addA || addB) {
        e.stopPropagation(); e.preventDefault();
        const lane = registry.get(+(addA ? addA.dataset.addAction : addB.dataset.lane));
        if (!lane) return;
        let item;
        if (addA) {
            const type = Object.keys(window.WF_ACTION_DEFS)[0];
            item = reg({ kind: 'action', type, args: newActionArgs(type), parent: lane });
        } else {
            item = newBranch(addB.dataset.addBranch, lane);
        }
        lane.items.push(item);
        renderAll();
        selectNode(item.id);
        markDirty();
        return;
    }
    const sel = t.closest('[data-sel]');
    if (sel && !t.closest('[data-head]')) {
        e.stopPropagation(); e.preventDefault();
        canvas.focus({ preventScroll: true });
        selectNode(+sel.dataset.sel);
        return;
    }
    onNodeMouseDown(e, n);   // the top-level head: drag the whole branch, or select it
}

closest() finds the innermost marked element, so a click on an action card inside a nested If selects that card, not the If around it. A new action gets the first action type with its defaults (newActionArgs(), the same argDefault() rules Add action uses) and opens in the panel, ready to change.

Selection outlines use the same id: updateSelectionVisuals() also toggles .selected on every [data-sel] whose id is the selected one.

Deleting

deleteSelected() (the Remove button and the Delete key) hands anything with a parent to deleteNested(), which enforces the rules the engine relies on:

function deleteNested(n) {
    if (n.kind === 'lane') {
        if (n.role === 'otherwise' || n.role === 'default') { window.showToast(BT('cannot_remove_default'), 'error'); return; }
        const b = n.parent;
        if (b.lanes.filter(l => l.role === n.role).length < 2) { window.showToast(BT(n.role === 'case' ? 'need_one_case' : 'need_one_branch'), 'error'); return; }
        b.lanes = b.lanes.filter(l => l !== n);
        ...
    } else if (n.kind === 'condition') {
        if (n.parent.conds.length < 2) { window.showToast(BT('need_one_condition'), 'error'); return; }
        ...
Can't remove Because
Otherwise / Default Ed's rule: the fallback is always there
The last If branch / the last case an If needs a branch, a Choose a case - the save routes refuse otherwise
A branch's last condition a branch with no conditions never matches (part 1)

The Otherwise / Default panel hides the Remove button altogether, so the refusal is rarely needed.

6. The detail panels

The right-hand panel gains one body, #wfBodyBranch, filled by two functions:

  • showDetailForBranch(b) - the whole branch: what it does, and for Choose the field (the trigger's fields, as for a condition) and match by (is one of, or contains - offered only for text fields). + Else if / + Case adds a path before the fallback: b.lanes.splice(b.lanes.length - 1, 0, l), which is what keeps Otherwise / Default last. Changing the field clears every case's values - a value picked for priority means nothing for requester email.
  • showDetailForLane(l) - one path: its name, then for an If branch all / any and its conditions (each opens the ordinary condition panel), for a case its values - a tick-list when the field has fixed values (WF_LOOKUP_VALUES), otherwise one per line.

Conditions and actions inside a branch open the existing panels, because they have the existing shapes (section 2).

7. The run history

Both run views recurse through steps. The execution log page (workflow-executions.js):

if (kind === 'branch') {
    const T = (k, p) => window.t('workflow.branch.' + k, p);
    const cls = s.status === 'failed' ? 'bad' : 'ok';
    let why = '';
    if (s.type === 'branch_switch') {
        why = '<div class="wfx-step-sub"><code>' + esc(s.field || '') + '</code> = <code>' + esc(JSON.stringify(s.actual ?? null)) + '</code>'
            + (s.reason === 'missing' ? ' - ' + esc(T('reason_missing')) : s.reason === 'no_match' ? ' - ' + esc(T('reason_no_match')) : '') + '</div>';
    } else {
        why = (s.checked || []).map(c => /* "Branch 1 "Urgent": matched  subject contains "urgent" βœ“" */ ...).join('');
    }
    const inner = (s.steps || []).map(renderStep).join('');   // recursion
    return '<div class="wfx-step wfx-branch">'
        + '<div class="wfx-step-head"><span class="wfx-step-status ' + cls + '">' + esc(T(s.type === 'branch_switch' ? 'switch' : 'if')) + '</span>'
        + '<strong>' + esc(branchTakenText(s)) + '</strong></div>' + why
        + '<div class="wfx-branch-steps">' + (inner || '<div class="wfx-step-sub"><em>' + esc(T('nothing_to_do')) + '</em></div>') + '</div>'
        + '</div>';
}
/** GH #364: "Took branch 2 "XYZ"", "Took Otherwise", "Took case 1", "Took Default" - the words for a branch's path. */
function branchTakenText(s) {
    const T = (k, p) => window.t('workflow.branch.' + k, p);
    const key = String(s.taken || '');
    const label = s.taken_label ? ' "' + s.taken_label + '"' : '';
    if (key.startsWith('branch:')) return T('took_branch', { n: +key.slice(7) + 1 }) + label;
    if (key.startsWith('case:'))   return T('took_case', { n: +key.slice(5) + 1 }) + label;
    return T(key === 'otherwise' ? 'took_otherwise' : 'took_default');
}

The stored index is zero-based; the screen says "case 2" (+ 1), matching the "Case 2" heading on the canvas. .wfx-branch-steps indents the path with a purple bar (--wf-branch).

The editor's Recent runs panel used to list a dry run's actions with step_log.filter(s => s.status === 'dry_run') - top level only, so actions inside a path would have vanished from the preview. It now walks the tree too (rowsFor(list, depth)), printing "Took case 1 "ABC Ltd"" above the path's previewed actions.

8. Strings

All under workflow.branch.*, read with window.t() (the page exports the workflow namespace). Placeholders: {n} in case_n, took_branch, took_case, branch_n. The help section's strings are workflow.help.branches_*. The 66 strings are in the 9 gated locales; the 8 translations were matched to each locale's existing words for workflow, condition, action and run history.

Continue: Part 3 - safety, saving and tests.

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally