All files App.tsx

98.54% Statements 135/137
92.3% Branches 72/78
96.15% Functions 50/52
100% Lines 118/118

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299                                                1x       332x 332x 332x 332x 332x 332x                   108x                     1x   47x                 37x   37x 37x   30x   37x 37x       3x 3x 3x 3x 3x       3x                   110x 110x   110x 37x 73x 19x 54x 8x 1x     16x         46x 46x 46x 29x   110x                             160x 160x 160x 160x 160x 160x 160x 160x 160x 160x 160x 160x   160x 27x   26x 26x 26x 26x 26x 26x 26x 26x   1x       160x 160x 160x   160x 1x   159x 27x   132x 132x 132x 174x 132x 660x   160x 10x 10x 10x   160x 9x 6x 3x   160x 50x 160x 16x 16x 16x 16x 15x   7x   15x 15x 15x 15x 2x 2x   15x   1x     160x 1x 1x     160x           7x     1x             3x                     528x   2640x 660x 10x           189x   9x                       110x 39x   3x                       2x   102x         132x     132x            
import {
  Background,
  Controls,
  Handle,
  MarkerType,
  Position,
  ReactFlow,
  useEdgesState,
  useNodesState,
  type Connection,
  type Edge,
  type NodeProps,
} from '@xyflow/react';
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { connectionToEdge, fromFlow, newNode, nodeSummary, toFlow, type FlowNode } from './flow';
import { isTrigger, validateGraph } from './graph';
import type { Client, EditorData, NodeTypeInfo, ParamInfo, SaveProblem } from './types';
 
interface Labels {
  types: Map<string, NodeTypeInfo>;
  strings: Record<string, string>;
  marked: Set<string>;
}
 
const LabelsContext = createContext<Labels>({ types: new Map(), strings: {}, marked: new Set() });
 
/** A node on the canvas: its label, an input handle unless it is a trigger, and one output per branch. */
function NodeView({ id, data, selected }: NodeProps<FlowNode>) {
  const { types, strings, marked } = useContext(LabelsContext);
  const info = types.get(data.nodetype);
  const branches = info?.branches ?? [];
  const classes = ['tool_autoflow-node', selected ? 'is-selected' : '', marked.has(id) ? 'has-problem' : ''];
  const summary = nodeSummary(info, data.params) || data.nodetype;
  return (
    <div data-testid={`node-${id}`} className={classes.filter(Boolean).join(' ')}>
      {!isTrigger(data.nodetype) && <Handle type="target" position={Position.Top} />}
      <div className="tool_autoflow-node-label">{info?.label ?? data.nodetype}</div>
      <div className="tool_autoflow-node-type" title={summary}>{summary}</div>
      {branches.length === 0 ? (
        <Handle type="source" position={Position.Bottom} />
      ) : (
        <div className="tool_autoflow-branches">
          {branches.map((b) => (
            <div key={b} className="tool_autoflow-branch">
              <span>{strings[`branch:${b}`] ?? b}</span>
              <Handle type="source" id={b} position={Position.Bottom} />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
 
const nodeTypes = { autoflow: NodeView };
 
const isObject = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
 
/**
 * Function arguments: a JSON object. It is stored as an object once the text parses, so
 * placeholders are filled value by value on the server. Until then the text is kept as is.
 */
function JsonField({ id, value, onChange, invalid, required }: {
  id: string; value: unknown; onChange: (v: unknown) => void; invalid: string; required: boolean;
}) {
  const [text, setText] = useState(isObject(value) ? JSON.stringify(value, null, 2) : String(value ?? ''));
  let parsed: unknown;
  try {
    parsed = JSON.parse(text);
  } catch {
    parsed = undefined;
  }
  const valid = text.trim() === '' || isObject(parsed);
  return (
    <>
      <textarea id={id} className="form-control font-monospace" rows={6} value={text} required={required}
        onChange={(e) => {
          setText(e.target.value);
          let next: unknown = e.target.value;
          try {
            const candidate = JSON.parse(e.target.value);
            next = isObject(candidate) ? candidate : e.target.value;
          } catch {
            // Keep the text until it is a JSON object.
          }
          onChange(next);
        }} />
      {!valid && <div className="form-text text-danger">{invalid}</div>}
    </>
  );
}
 
function ParamField({ param, value, onChange, strings }: {
  param: ParamInfo; value: unknown; onChange: (v: unknown) => void; strings: Record<string, string>;
}) {
  const id = `tool_autoflow-param-${param.name}`;
  const text = value === undefined || value === null ? '' : String(value);
  let input;
  if (param.kind === 'json') {
    input = <JsonField id={id} value={value} onChange={onChange} invalid={strings.invalidjson} required={param.required} />;
  } else if (param.kind === 'textarea') {
    input = <textarea id={id} className="form-control" rows={4} value={text} required={param.required} onChange={(e) => onChange(e.target.value)} />;
  } else if (param.kind === 'select') {
    input = (
      <select id={id} className="form-select" value={text} required={param.required} onChange={(e) => onChange(e.target.value)}>
        <option value="">{strings.choose}</option>
        {param.options.map((o) => (
          <option key={o} value={o}>{param.optionlabels[o] ?? o}</option>
        ))}
      </select>
    );
  } else {
    const lists: Record<string, string> = { event: 'tool_autoflow-events', function: 'tool_autoflow-functions' };
    const list = lists[param.kind];
    input = <input id={id} className="form-control" list={list} value={text} required={param.required}
      onChange={(e) => onChange(e.target.value)} />;
  }
  return (
    <div className="mb-2">
      <label htmlFor={id} className={param.required ? 'form-label is-required' : 'form-label'}>{param.label}</label>
      {input}
    </div>
  );
}
 
export interface AppProps {
  client: Client;
  workflowid: number;
}
 
/** The workflow editor: toolbar, palette, canvas, node settings and problems. */
export function App({ client, workflowid }: AppProps) {
  const [data, setData] = useState<EditorData | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [nodes, setNodes, onNodesChange] = useNodesState<FlowNode>([]);
  const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>([]);
  const [selected, setSelected] = useState<string | null>(null);
  const [id, setId] = useState(workflowid);
  const [name, setName] = useState('');
  const [enabled, setEnabled] = useState(false);
  const [runas, setRunas] = useState('');
  const [runasname, setRunasname] = useState('');
  const [status, setStatus] = useState('');
  const [problems, setProblems] = useState<SaveProblem[]>([]);
 
  useEffect(() => {
    client.load(workflowid).then(
      (loaded) => {
        const flow = toFlow(loaded.graph);
        setNodes(flow.nodes);
        setEdges(flow.edges);
        setName(loaded.name);
        setEnabled(loaded.enabled);
        setRunas(String(loaded.runasuserid));
        setRunasname(loaded.runasname);
        setData(loaded);
      },
      (e: Error) => setLoadError(e.message),
    );
  }, [client, workflowid, setNodes, setEdges]);
 
  const types = useMemo(() => new Map((data?.nodetypes ?? []).map((t) => [t.type, t])), [data]);
  const marked = useMemo(() => new Set(problems.flatMap((p) => p.nodeids)), [problems]);
  const onConnect = useCallback((c: Connection) => setEdges((es) => [...es, connectionToEdge(c)]), [setEdges]);
 
  if (loadError !== null) {
    return <div role="alert" className="alert alert-danger">{loadError}</div>;
  }
  if (data === null) {
    return <div className="tool_autoflow-loading" aria-busy="true" />;
  }
  const strings = data.strings;
  const graph = fromFlow(nodes, edges);
  const clientProblems = validateGraph(graph);
  const current = nodes.find((n) => n.id === selected);
  const currentType = current ? types.get(current.data.nodetype) : undefined;
  const categories = [...new Set(data.nodetypes.map((t) => t.category))];
 
  const add = (type: string) => {
    const node = newNode(type, nodes.map((n) => n.id), nodes.length);
    setNodes((ns) => [...ns, node]);
    setSelected(node.id);
  };
  const remove = (nodeid: string) => {
    setNodes((ns) => ns.filter((n) => n.id !== nodeid));
    setEdges((es) => es.filter((e) => e.source !== nodeid && e.target !== nodeid));
    setSelected(null);
  };
  const setParam = (nodeid: string, key: string, value: unknown) =>
    setNodes((ns) => ns.map((n) => (n.id === nodeid ? { ...n, data: { ...n.data, params: { ...n.data.params, [key]: value } } } : n)));
  const save = async () => {
    setStatus(strings.saving);
    try {
      const runasuserid = data.canchooserunas ? Number(runas) || 0 : 0;
      const result = await client.save({ id, name, enabled, graph, runasuserid });
      if (id === 0) {
        // Keep the new workflow on reload.
        window.history.replaceState(null, '', `?id=${result.id}`);
      }
      setId(result.id);
      setEnabled(result.enabled);
      setProblems(result.errors);
      if (result.runasuserid !== undefined) {
        setRunas(String(result.runasuserid));
        setRunasname(result.runasname ?? '');
      }
      setStatus(strings.saved);
    } catch (e) {
      setStatus(`${strings.savefailed}: ${(e as Error).message}`);
    }
  };
  const run = async () => {
    await client.run(id);
    setStatus(strings.runqueued);
  };
 
  return (
    <LabelsContext.Provider value={{ types, strings, marked }}>
      <div className="tool_autoflow-editor">
        <div className="tool_autoflow-toolbar">
          <label htmlFor="tool_autoflow-name" className="visually-hidden sr-only">{strings.workflowname}</label>
          <input id="tool_autoflow-name" className="form-control" placeholder={strings.workflowname} value={name}
            onChange={(e) => setName(e.target.value)} />
          <div className="form-check">
            <input id="tool_autoflow-enabled" type="checkbox" className="form-check-input" checked={enabled}
              onChange={(e) => setEnabled(e.target.checked)} />
            <label htmlFor="tool_autoflow-enabled" className="form-check-label">{strings.enabled}</label>
          </div>
          {data.canchooserunas && (
            <div className="tool_autoflow-runas-field">
              <label htmlFor="tool_autoflow-runas" className="visually-hidden sr-only">{strings.runasuserid}</label>
              <input id="tool_autoflow-runas" type="number" min="1" className="form-control" value={runas}
                placeholder={strings.runasuserid} onChange={(e) => setRunas(e.target.value)} />
            </div>
          )}
          <span className="tool_autoflow-runas text-muted" data-testid="runas">{strings.runsas} {runasname}</span>
          <button type="button" className="btn btn-primary" onClick={save}>{strings.save}</button>
          <button type="button" className="btn btn-secondary" onClick={run} disabled={id === 0}>{strings.runnow}</button>
          <span className="tool_autoflow-status" role="status">{status}</span>
        </div>
        <div className="tool_autoflow-body">
          <section className="tool_autoflow-palette" aria-label={strings.palette}>
            {categories.map((category) => (
              <div key={category}>
                <h4>{strings[`cat:${category}`] ?? category}</h4>
                {data.nodetypes.filter((t) => t.category === category).map((t) => (
                  <button key={t.type} type="button" className="btn btn-outline-secondary btn-sm" title={t.description}
                    data-testid={`palette-${t.type}`} onClick={() => add(t.type)}>{t.label}</button>
                ))}
              </div>
            ))}
          </section>
          <div className="tool_autoflow-canvas">
            <ReactFlow nodes={nodes.map((n) => ({ ...n, selected: n.id === selected }))} edges={edges} nodeTypes={nodeTypes}
              onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} onConnect={onConnect}
              onNodeClick={(_, n) => setSelected(n.id)} onPaneClick={() => setSelected(null)} fitView
              defaultEdgeOptions={{ markerEnd: { type: MarkerType.ArrowClosed } }}
              fitViewOptions={{ maxZoom: 1 }}>
              <Background />
              <Controls />
            </ReactFlow>
          </div>
          <aside className="tool_autoflow-inspector" aria-label={strings.nodesettings}>
            {current && currentType ? (
              <>
                <h4>{currentType.label}</h4>
                {currentType.params.map((p) => (
                  <ParamField key={`${current.id}:${p.name}`} param={p} value={current.data.params[p.name]} strings={strings}
                    onChange={(v) => setParam(current.id, p.name, v)} />
                ))}
                <button type="button" className="btn btn-link text-danger" onClick={() => remove(current.id)}>{strings.deletenode}</button>
              </>
            ) : (
              <p>{strings.selectnode}</p>
            )}
          </aside>
        </div>
        {(clientProblems.length > 0 || problems.length > 0) && (
          <section className="tool_autoflow-problems" aria-label={strings.problems}>
            <h4>{strings.problems}</h4>
            <ul>
              {/* Stryker disable next-line StringLiteral: list keys never change what renders. */}
              {problems.map((p) => <li key={`s-${p.code}`}>{p.message}</li>)}
              {/* Stryker disable next-line StringLiteral: list keys never change what renders. */}
              {clientProblems.map((p) => <li key={`c-${p.code}`}>{strings[`error:${p.code}`] ?? p.code}</li>)}
            </ul>
          </section>
        )}
        <datalist id="tool_autoflow-events">
          {data.events.map((e) => <option key={e} value={e} />)}
        </datalist>
        <datalist id="tool_autoflow-functions">
          {data.functions.map((f) => <option key={f} value={f} />)}
        </datalist>
      </div>
    </LabelsContext.Provider>
  );
}