示例
实用示例,实时演示。
挑一个示例全屏打开,运行效果和源码并排呈现。
挑一个示例全屏打开,运行效果和源码并排呈现。
把数字、文本和开关接进数学、比较和 If 节点,每个值都会随你的输入实时更新。函数本身也是图:它们的 Input 和 Output 节点,就是每个 Call 的端口,而 Call 还能指向自己所在的函数,所以 factorial 和 sum 靠 If 来设置递归的终止条件。引擎是普通 JavaScript:每个节点是一个生成器,通过 yield 请求输入,一个循环用自己的栈来驱动它们,所以 sum(50000) 嵌套五万层调用,只要大约十分之一秒,而且完全不碰 JavaScript 的调用栈。缺少终止条件的递归,只能靠步数上限来叫停。拖动会写入 x 和 y,并且只更新画布的作用域;运行计数表明,移动节点从不会触发图的运行。
Drag from an output dot to a node. Click a wire to cut it. Drag the background or scroll to pan; pinch or ⌘/Ctrl + scroll to zoom.
// app.ts: the editor. The nodes are HTML boxes in a list() over the shown // function's node objects, and the wires are SVG paths in a list() over its // wire objects, drawn from the same x and y. A drag writes x and y and calls // update("ng-canvas"), which leaves the toolbar and the side panel alone. An // edit runs the graph again, then calls update(). The run count on screen // shows that moving things never runs it. import "nuclo"; import { run } from "./engine.ts"; import { addFunction, addNode, callers, COMPARE, connect, disconnect, functions, inputs, LOGIC, MATH, outputs, params, removeFunction, removeNode, results, wireInto, type Fn, type GraphNode, type Kind, type Value, type View, type Wire } from "./graph.ts"; import { HEAD, ROW, W, s } from "./styles.ts"; const TITLES: Record<Kind, string> = { number: "Number", text: "Text", switch: "Switch", math: "Math", compare: "Compare", logic: "Logic", not: "Not", if: "If", input: "Input", output: "Output", call: "Call" }; const GROUPS: { label: string; kinds: Kind[] }[] = [ { label: "Values", kinds: ["number", "text", "switch"] }, { label: "Operators", kinds: ["math", "compare", "logic", "not"] }, { label: "Conditional", kinds: ["if"] }, { label: "Function ports", kinds: ["input", "output"] }, ]; const TONE: Record<Kind, keyof typeof s> = { number: "value", text: "value", switch: "value", math: "op", compare: "op", logic: "op", not: "op", if: "flow", input: "port", output: "port", call: "call" }; const OPS: Partial<Record<Kind, string[]>> = { math: Object.keys(MATH), compare: Object.keys(COMPARE), logic: LOGIC }; let fn = functions[0]; // the function on the canvas let trail = [{ fn }]; // how you got here: Open on a Call goes one level deeper. Wrapped, since a function can appear twice. let result = run(fn); let runs = 1; let selected: GraphNode | null = null; let notice = ""; let canvasEl: HTMLElement | null = null; let drag: | { kind: "pan"; x: number; y: number; from: View } // where the pointer went down, and the view then | { kind: "node"; node: GraphNode; dx: number; dy: number } // the grab point, inside the node | { kind: "wire"; from: GraphNode; out: number; x: number; y: number; over: GraphNode | null } // the loose end | null = null; const HOME: View = { x: 24, y: 24, zoom: 1 }; const view = () => fn.view ?? HOME; /** An edit: run the graph again and show everything it changed. */ function edited() { result = run(fn); runs++; update(); } function enter(next: Fn) { fn = next; selected = null; notice = ""; if (!fn.view) fit(fn); edited(); } function show(next: Fn, deeper = false) { trail = deeper ? [...trail, { fn: next }] : [{ fn: next }]; enter(next); } // ── Geometry ───────────────────────────────────────────────────────────── const rows = (n: GraphNode) => Math.max(inputs(n).length, outputs(n).length, 1) + (n.kind === "input" || n.kind === "output" ? 1 : 0); const portY = (n: GraphNode, i: number) => n.y + HEAD + i * ROW + ROW / 2; function curve(x1: number, y1: number, x2: number, y2: number) { const d = Math.max(40, Math.abs(x2 - x1) / 2); return `M${x1},${y1} C${x1 + d},${y1} ${x2 - d},${y2} ${x2},${y2}`; } const path = (w: Wire) => curve(w.from.x + W, portY(w.from, w.out), w.to.x, portY(w.to, w.in)); /** Pointer to canvas coordinates: undo the view's pan and zoom. */ function world(e: MouseEvent): [number, number] { const r = canvasEl!.getBoundingClientRect(); const v = view(); return [(e.clientX - r.left - v.x) / v.zoom, (e.clientY - r.top - v.y) / v.zoom]; } function fit(f: Fn) { const w = canvasEl?.clientWidth || 800; const h = canvasEl?.clientHeight || 500; if (!f.nodes.length) return void (f.view = { ...HOME }); const x0 = Math.min(...f.nodes.map((n) => n.x)); const y0 = Math.min(...f.nodes.map((n) => n.y)); const x1 = Math.max(...f.nodes.map((n) => n.x + W)); const y1 = Math.max(...f.nodes.map((n) => n.y + HEAD + rows(n) * ROW)); const zoom = Math.max(0.3, Math.min(1, (w - 48) / (x1 - x0), (h - 72) / (y1 - y0))); f.view = { zoom, x: (w - (x1 - x0) * zoom) / 2 - x0 * zoom, y: (h - 24 - (y1 - y0) * zoom) / 2 - y0 * zoom }; } function zoomAt(px: number, py: number, factor: number) { const v = view(); const zoom = Math.min(2, Math.max(0.25, v.zoom * factor)); fn.view = { zoom, x: px - ((px - v.x) * zoom) / v.zoom, y: py - ((py - v.y) * zoom) / v.zoom }; // the point under the pointer stays put } const nodeAt = (e: MouseEvent) => { const id = document.elementFromPoint(e.clientX, e.clientY)?.closest<HTMLElement>("[data-node]")?.dataset.node; return fn.nodes.find((n) => String(n.id) === id) ?? null; }; // ── Editing ────────────────────────────────────────────────────────────── function place(kind: Kind, fields: Partial<GraphNode> = {}) { const v = view(); const step = (fn.nodes.length % 5) * 18; // a few in a row do not land on top of each other const x = ((canvasEl?.clientWidth ?? 800) / 2 - v.x) / v.zoom - W / 2 + step; const y = ((canvasEl?.clientHeight ?? 500) / 2 - v.y) / v.zoom - 60 + step; selected = addNode(fn, kind, Math.round(x), Math.round(y), fields); edited(); } function remove(node: GraphNode) { removeNode(fn, node); if (selected === node) selected = null; edited(); } // Every drag captures the pointer on the canvas, so the canvas hears the moves // and the release wherever the pointer goes. function capture(e: PointerEvent, next: NonNullable<typeof drag>) { e.stopPropagation(); drag = next; notice = ""; canvasEl!.setPointerCapture(e.pointerId); update("ng-canvas"); } function grabNode(e: PointerEvent, node: GraphNode) { if (e.button !== 0) return; e.stopPropagation(); selected = node; if ((e.target as Element).closest("input, select, button, label")) return update("ng-canvas"); // the control keeps the pointer const [x, y] = world(e); capture(e, { kind: "node", node, dx: x - node.x, dy: y - node.y }); } function grabOutput(e: PointerEvent, node: GraphNode, out: number) { if (e.button !== 0) return; const [x, y] = world(e); capture(e, { kind: "wire", from: node, out, x, y, over: null }); } // Grabbing a wired input pulls the wire off it, still attached to its source. function grabInput(e: PointerEvent, node: GraphNode, i: number) { const w = wireInto(fn, node, i); if (e.button !== 0 || !w) return; disconnect(fn, w); const [x, y] = world(e); capture(e, { kind: "wire", from: w.from, out: w.out, x, y, over: node }); edited(); } function moved(e: PointerEvent) { if (!drag) return; if (drag.kind === "pan") fn.view = { ...drag.from, x: drag.from.x + e.clientX - drag.x, y: drag.from.y + e.clientY - drag.y }; else if (drag.kind === "node") { const [x, y] = world(e); drag.node.x = Math.round(x - drag.dx); drag.node.y = Math.round(y - drag.dy); } else { [drag.x, drag.y] = world(e); drag.over = nodeAt(e); } update("ng-canvas"); } // A wire dropped anywhere on a node goes into the input nearest the pointer. function released(e: PointerEvent) { const loose = drag?.kind === "wire" ? drag : null; drag = null; const to = loose && nodeAt(e); if (!loose || !to || !inputs(to).length) return update("ng-canvas"); const i = Math.max(0, Math.min(inputs(to).length - 1, Math.floor((world(e)[1] - to.y - HEAD) / ROW))); if (!connect(fn, loose.from, loose.out, to, i)) notice = "That wire would make a loop: a node can't wait for its own value. A Call can, so recurse with one."; edited(); } // ── Values ─────────────────────────────────────────────────────────────── function fmt(v: Value | undefined) { if (v === undefined) return "—"; if (typeof v === "string") return JSON.stringify(v); if (typeof v === "boolean") return String(v); return Math.abs(v) >= 1e15 ? v.toExponential(3) : v.toLocaleString("en", { maximumFractionDigits: 4 }); } const tone = (v: Value | undefined) => (typeof v === "number" ? s.num : typeof v === "string" ? s.str : v === true ? s.yes : v === false ? s.no : null); // A typed test value: a number, true or false, or else text. const parse = (text: string): Value => (text === "true" ? true : text === "false" ? false : text.trim() !== "" && !Number.isNaN(Number(text)) ? Number(text) : text); // ── Nodes ──────────────────────────────────────────────────────────────── const Field = (label: string, value: string, write: (text: string) => void, rerun = true) => input(s.field, { value, "aria-label": label, onInput: (e) => { write(e.currentTarget.value); if (rerun) edited(); else update(); } }); // The middle of row i: the node's own field, if it has one there. Built once: // a field keeps what you type, and update() never writes it back. function control(node: GraphNode, i: number): NodeModLike[] { const ops = OPS[node.kind]; if (ops && i === 0) { return [select(s.select, { "aria-label": "Operator", onChange: (e) => { node.op = e.currentTarget.value; edited(); } }, ...ops.map((op) => option({ value: op, selected: op === node.op }, op)))]; } if (i === 0) { switch (node.kind) { case "number": return [input(s.field, { type: "number", value: String(node.value), "aria-label": "Number", onInput: (e) => { node.value = e.currentTarget.valueAsNumber || 0; edited(); } })]; case "text": return [Field("Text", String(node.value), (t) => (node.value = t))]; case "switch": return [label(s.toggle, input({ type: "checkbox", checked: () => node.value === true, onChange: (e) => { node.value = e.currentTarget.checked; edited(); } }), span(() => String(node.value)))]; case "input": return [Field("Parameter name", node.name, (t) => (node.name = t), false)]; case "output": return [Field("Result name", node.name, (t) => (node.name = t), false)]; } } if (node.kind === "input") return [span(s.label, "test"), Field("Test value", String(node.value), (t) => (node.value = parse(t)))]; if (node.kind === "output") { return [div(s.big, { title: () => result.errors.get(node) ?? "" }, () => (result.errors.has(node) ? "stopped" : fmt(result.values.get(node)?.[0])))]; } return []; } function Row(node: GraphNode, i: number) { const named = OPS[node.kind] || node.kind === "not" || node.kind === "if" || node.kind === "call"; // ports with labels and values return div( s.row, when( () => i < inputs(node).length, span(s.socket, s.in, { title: () => `Input: ${inputs(node)[i]}`, onPointerDown: (e) => grabInput(e, node, i) }), named ? span(s.label, () => inputs(node)[i] ?? "") : null, ), ...control(node, i), when( () => i < outputs(node).length, named ? span(s.result, node.kind === "call" ? span(s.label, () => outputs(node)[i] ?? "") : null, span(() => (result.errors.has(node) ? "!" : fmt(result.values.get(node)?.[i])))) : null, span(s.socket, s.out, { title: () => `Output: ${outputs(node)[i]}. Drag to an input.`, onPointerDown: (e) => grabOutput(e, node, i) }), ), ); } function NodeView(node: GraphNode) { return div( s.node, { "data-node": String(node.id), class: () => cx(s.node, s[TONE[node.kind]], result.live.has(node) ? null : s.dim, result.errors.has(node) ? s.failed : null, node === selected ? s.selected : null, drag?.kind === "wire" && drag.over === node ? s.target : null).className, style: () => ({ transform: `translate(${node.x}px, ${node.y}px)` }), title: () => result.errors.get(node) ?? "", onPointerDown: (e) => grabNode(e, node), }, div( s.head, span(s.dot), span(s.title, () => (node.kind === "call" ? `${node.fn!.name}()` : TITLES[node.kind])), node.kind === "call" ? button(s.icon, { title: `Open ${node.fn!.name}`, "aria-label": "Open this function", onClick: () => show(node.fn!, true) }, "↗") : null, button(s.icon, { title: "Delete node (Delete)", "aria-label": "Delete node", onClick: () => remove(node) }, "×"), ), // A Call grows a row when its function gets a parameter: rows are plain indexes, so the others stay. list(() => Array.from({ length: rows(node) }, (_, i) => i), (i) => Row(node, i)), ); } // Each wire is two paths: the one you see, colored by the value on it, and a // wide invisible one that is easy to hit. Clicking it cuts the wire. const WireView = (w: Wire) => gSvg( s.link, pathSvg(s.wire, { d: () => path(w), class: () => cx(s.wire, tone(result.values.get(w.from)?.[w.out]), result.wires.has(w) ? null : s.faint).className }), pathSvg(s.hit, { d: () => path(w), onPointerDown: (e) => { if (e.button !== 0) return; e.stopPropagation(); disconnect(fn, w); edited(); } }), ); function Canvas() { return div( s.canvas, scope("ng-canvas"), { style: () => ({ backgroundSize: `${20 * view().zoom}px ${20 * view().zoom}px`, backgroundPosition: `${view().x}px ${view().y}px` }), onPointerDown: (e) => { if (e.button !== 0 || (e.target as Element).closest("button")) return; selected = null; capture(e, { kind: "pan", x: e.clientX, y: e.clientY, from: view() }); }, onPointerMove: moved, onPointerUp: released, onLostPointerCapture: () => { if (drag) { drag = null; update("ng-canvas"); } }, // the browser cancelled it }, // Scroll pans, like a page. Pinch, or Ctrl or ⌘ with the wheel, zooms. Not passive: the page must not scroll or zoom too. on("wheel", (e) => { e.preventDefault(); const r = canvasEl!.getBoundingClientRect(); if (e.ctrlKey || e.metaKey) zoomAt(e.clientX - r.left, e.clientY - r.top, Math.exp(-e.deltaY * 0.01)); else fn.view = { ...view(), x: view().x - e.deltaX, y: view().y - e.deltaY }; update("ng-canvas"); }, { passive: false }), on("mount", (el) => { canvasEl = el; requestAnimationFrame(() => { if (canvasEl && !fn.view) { fit(fn); update("ng-canvas"); } }); return () => { canvasEl = null; drag = null; }; // a drag cut short by closing the example must not go on at the next visit }), div( s.world, { style: () => ({ transform: `translate(${view().x}px, ${view().y}px) scale(${view().zoom})` }) }, svgSvg( s.wires, { "aria-hidden": "true" }, list(() => fn.wires, WireView), pathSvg(s.wire, s.loose, { d: () => (drag?.kind === "wire" ? curve(drag.from.x + W, portY(drag.from, drag.out), drag.x, drag.y) : "") }), ), list(() => fn.nodes, NodeView), ), p(s.hint, when(() => notice !== "", span(s.notice, () => notice)).else("Drag from an output dot to a node. Click a wire to cut it. Drag the background or scroll to pan; pinch or ⌘/Ctrl + scroll to zoom.")), div( s.zoom, button(s.btn, { "aria-label": "Zoom out", onClick: () => { const r = canvasEl!.getBoundingClientRect(); zoomAt(r.width / 2, r.height / 2, 1 / 1.25); update("ng-canvas"); } }, "−"), button(s.btn, { title: "Fit the graph in view", onClick: () => { fit(fn); update("ng-canvas"); } }, () => `${Math.round(view().zoom * 100)}%`), button(s.btn, { "aria-label": "Zoom in", onClick: () => { const r = canvasEl!.getBoundingClientRect(); zoomAt(r.width / 2, r.height / 2, 1.25); update("ng-canvas"); } }, "+"), ), ); } // ── Panels ─────────────────────────────────────────────────────────────── const signature = (f: Fn) => `(${params(f).map((n) => n.name).join(", ")}) → ${results(f).map((n) => n.name).join(", ") || "nothing"}`; const FnItem = (f: Fn) => button( s.fn, { class: () => cx(s.fn, f === fn ? s.current : null).className, "aria-current": () => String(f === fn), onClick: () => show(f) }, span(() => f.name), span(s.sig, () => signature(f)), ); function Side() { return aside( s.side, div( s.section, h3("Functions"), list(() => functions, FnItem), button(s.btn, { onClick: () => show(addFunction()) }, "+ New function"), ), div( s.section, h3("Add node"), ...GROUPS.map((g) => div(s.group, span(g.label), ...g.kinds.map((k) => button(s.add, s[TONE[k]], { onClick: () => place(k) }, TITLES[k])))), div(s.group, span("Call"), list(() => functions, (f) => button(s.add, s.call, { title: `Call ${f.name}`, onClick: () => place("call", { fn: f }) }, () => f.name))), ), ); } function Bar() { const users = () => callers(fn).length; return div( s.bar, nav( s.crumbs, { "aria-label": "Call path" }, list(() => trail, (c) => span( when(() => trail.indexOf(c) > 0, span({ "aria-hidden": "true" }, "›")), button(s.crumb, { "aria-current": () => String(c === trail.at(-1)), onClick: () => { trail = trail.slice(0, trail.indexOf(c) + 1); enter(c.fn); } }, () => c.fn.name), )), ), input(s.name, { value: () => fn.name, "aria-label": "Function name", onInput: (e) => { fn.name = e.currentTarget.value; update(); } }), button(s.btn, { disabled: () => fn === functions[0] || users() > 0, title: () => (fn === functions[0] ? "The first function stays" : users() ? `${users()} calls use it` : "Delete this function"), onClick: () => { removeFunction(fn); show(functions[0]); }, }, "Delete"), span(s.stats, () => `${runs} run${runs === 1 ? "" : "s"} · ${result.steps.toLocaleString("en")} steps · ${result.calls.toLocaleString("en")} calls · ${result.depth.toLocaleString("en")} deep · ${result.ms.toFixed(1)} ms`), ); } // Delete removes the selected node and Escape lets go of it, unless you are typing. function shortcuts(el: HTMLElement) { const onKey = (e: KeyboardEvent) => { if (!el.offsetParent || !selected || (e.target as Element).closest?.("input, select, textarea")) return; if (e.key === "Delete" || e.key === "Backspace") remove(selected); else if (e.key === "Escape") { selected = null; update("ng-canvas"); } else return; e.preventDefault(); }; document.addEventListener("keydown", onKey, true); return () => document.removeEventListener("keydown", onKey, true); } export function NodeGraph() { return div(s.app, on("mount", shortcuts), Side(), div(s.main, Bar(), Canvas())); }
// engine.ts: runs a function. Each node is a generator that asks for its // inputs one at a time with yield, and one loop drives them all from its own // stack array instead of the JavaScript call stack. A graph can be as deep as // you like, and a function can call itself until memory or the step budget runs // out: a call costs heap, never a stack frame. An If asks for its condition // first and then for one branch only, so the other branch never runs, which is // what lets a recursive function stop. import { COMPARE, MATH, params, results, unwired, wireInto, type Fn, type GraphNode, type Value, type Wire } from "./graph.ts"; /** One function call: its arguments, and the outputs of every node it has worked out so far. */ interface Frame { fn: Fn; args: Value[] | null; done: Map<GraphNode, Value[]>; depth: number; run: Result; trace: Set<Wire> | null } type Ask = { node: GraphNode; frame: Frame }; // "work out this node in this call" type Body = Generator<Ask, Value[], Value[]>; export interface Result { values: Map<GraphNode, Value[]>; // the outputs of the shown function's nodes errors: Map<GraphNode, string>; live: Set<GraphNode>; // the nodes an Output needed. The rest are worked out only to show their values. wires: Set<Wire>; // the wires an Output needed: not the ones into the branch an If skipped steps: number; // generator resumes, across every call calls: number; depth: number; // the deepest call ms: number; } export const BUDGET = 2_000_000; // steps: a recursion with no way out stops here // The value on the wire into input i, or the default when nothing is wired there. function* pull(node: GraphNode, i: number, frame: Frame): Generator<Ask, Value, Value[]> { const w = wireInto(frame.fn, node, i); if (w) frame.trace?.add(w); return w ? (yield { node: w.from, frame })[w.out] : unwired(node, i); } function* body(node: GraphNode, frame: Frame): Body { switch (node.kind) { case "number": case "text": case "switch": return [node.value]; // Called, it reads its argument. Shown on its own, its test value. case "input": return [frame.args ? (frame.args[params(frame.fn).indexOf(node)] ?? 0) : node.value]; case "output": return [yield* pull(node, 0, frame)]; case "not": return [!(yield* pull(node, 0, frame))]; case "if": return [(yield* pull(node, 0, frame)) ? yield* pull(node, 1, frame) : yield* pull(node, 2, frame)]; case "compare": return [COMPARE[node.op](yield* pull(node, 0, frame), yield* pull(node, 1, frame))]; case "math": { const a = yield* pull(node, 0, frame); const b = yield* pull(node, 1, frame); return [node.op === "+" && (typeof a === "string" || typeof b === "string") ? `${a}${b}` : MATH[node.op](Number(a), Number(b))]; } case "logic": { const a = Boolean(yield* pull(node, 0, frame)); if (node.op === "and" && !a) return [false]; // short-circuit: b is never asked for if (node.op === "or" && a) return [true]; const b = Boolean(yield* pull(node, 1, frame)); return [node.op === "xor" ? a !== b : b]; } case "call": { const fn = node.fn!; const args: Value[] = []; for (let i = 0; i < params(fn).length; i++) args.push(yield* pull(node, i, frame)); const inner: Frame = { fn, args, done: new Map(), depth: frame.depth + 1, run: frame.run, trace: null }; frame.run.calls++; frame.run.depth = Math.max(frame.run.depth, inner.depth); const out: Value[] = []; for (const r of results(fn)) out.push((yield { node: r, frame: inner })[0]); return out; } } } // Works out one node. The stack holds the generators that are waiting for a value: // the top one runs until it asks for a node, which is either known already in // that call or pushed on top. When a generator returns, its value goes to the one below. function drive(node: GraphNode, root: Frame) { const run = root.run; const stack: Ask[] = [{ node, frame: root }]; const gens: Body[] = [body(node, root)]; let value: Value[] = []; try { while (gens.length) { if (++run.steps > BUDGET) throw new Error(`Stopped after ${BUDGET.toLocaleString("en")} steps. Does every call reach a way out?`); const step = gens[gens.length - 1].next(value); if (step.done) { const { node, frame } = stack.pop()!; gens.pop(); frame.done.set(node, (value = step.value)); } else { const known = step.value.frame.done.get(step.value.node); if (known) value = known; else { stack.push(step.value); gens.push(body(step.value.node, step.value.frame)); } } } } catch (e) { // Every node of the shown function that was waiting on this one fails with it. for (const ask of stack) if (ask.frame === root) run.errors.set(ask.node, (e as Error).message); } } /** Runs `fn` with its Input nodes' test values: its Outputs first, then every other node, for display. */ export function run(fn: Fn): Result { const start = performance.now(); const result: Result = { values: new Map(), errors: new Map(), live: new Set(), wires: new Set(), steps: 0, calls: 0, depth: 0, ms: 0 }; const root: Frame = { fn, args: null, done: result.values, depth: 0, run: result, trace: result.wires }; const ask = (n: GraphNode) => { if (!result.values.has(n) && !result.errors.has(n)) drive(n, root); }; results(fn).forEach(ask); result.live = new Set([...result.values.keys(), ...result.errors.keys()]); root.trace = null; fn.nodes.forEach(ask); result.ms = performance.now() - start; return result; }
// graph.ts: the model. A function is a plain object that holds its nodes and // wires. A node is a plain object with a position and its own fields, and a // wire points straight at the two node objects it joins. "main" is a function // like any other: its Input and Output nodes are the ports of every Call to it, // and a Call can name any function, itself included. Nothing here knows about the UI. export type Value = number | boolean | string; export type Kind = "number" | "text" | "switch" | "math" | "compare" | "logic" | "not" | "if" | "input" | "output" | "call"; export interface GraphNode { id: number; kind: Kind; x: number; y: number; // px, on the canvas value: Value; // number, text, switch: the value. input: the test value used when its function runs on its own op: string; // math, compare, logic name: string; // input, output: the parameter or result name fn: Fn | null; // call: the function it calls } export interface Wire { from: GraphNode; out: number; to: GraphNode; in: number } export interface View { x: number; y: number; zoom: number } export interface Fn { name: string; nodes: GraphNode[]; wires: Wire[]; view: View | null } // view: null until it is first shown export const MATH: Record<string, (a: number, b: number) => number> = { "+": (a, b) => a + b, "−": (a, b) => a - b, "×": (a, b) => a * b, "÷": (a, b) => a / b, "%": (a, b) => a % b, min: Math.min, max: Math.max, }; export const COMPARE: Record<string, (a: Value, b: Value) => boolean> = { "<": (a, b) => a < b, "≤": (a, b) => a <= b, "=": (a, b) => a === b, "≠": (a, b) => a !== b, "≥": (a, b) => a >= b, ">": (a, b) => a > b, }; export const LOGIC = ["and", "or", "xor"]; /** The parameters and results of a function: its Input and Output nodes, in order. */ export const params = (fn: Fn) => fn.nodes.filter((n) => n.kind === "input"); export const results = (fn: Fn) => fn.nodes.filter((n) => n.kind === "output"); /** The names of a node's input ports (left) and output ports (right). */ export function inputs(n: GraphNode): string[] { switch (n.kind) { case "math": case "compare": case "logic": return ["a", "b"]; case "not": return ["in"]; case "if": return ["if", "then", "else"]; case "output": return [n.name]; case "call": return params(n.fn!).map((p) => p.name); default: return []; } } export function outputs(n: GraphNode): string[] { switch (n.kind) { case "output": return []; case "input": return [n.name]; case "call": return results(n.fn!).map((r) => r.name); default: return ["out"]; } } /** An input with no wire into it reads false where a condition is expected, and 0 everywhere else. */ export const unwired = (n: GraphNode, i: number): Value => (n.kind === "logic" || n.kind === "not" || (n.kind === "if" && i === 0) ? false : 0); export const wireInto = (fn: Fn, to: GraphNode, i: number) => fn.wires.find((w) => w.to === to && w.in === i); let nextId = 1; const DEFAULTS: Partial<Record<Kind, Partial<GraphNode>>> = { text: { value: "" }, switch: { value: false }, math: { op: "+" }, compare: { op: "<" }, logic: { op: "and" }, output: { name: "result" }, }; export function addNode(fn: Fn, kind: Kind, x: number, y: number, fields: Partial<GraphNode> = {}): GraphNode { const node: GraphNode = { id: nextId++, kind, x, y, value: 0, op: "", name: "", fn: null, ...DEFAULTS[kind], ...fields }; if (kind === "input" && !fields.name) node.name = String.fromCharCode(97 + (params(fn).length % 26)); // a, b, c… fn.nodes.push(node); return node; } /** True when a path of wires already leads from `a` to `b`. */ function reaches(fn: Fn, a: GraphNode, b: GraphNode) { const seen = new Set<GraphNode>(); const todo = [a]; for (let n = todo.pop(); n; n = todo.pop()) { if (n === b) return true; if (seen.has(n)) continue; seen.add(n); for (const w of fn.wires) if (w.from === n) todo.push(w.to); } return false; } /** * Wires an output to an input, replacing any wire already in that input. * Refuses a loop: a node that feeds itself has no first value. A Call * is how a function uses its own result. */ export function connect(fn: Fn, from: GraphNode, out: number, to: GraphNode, i: number): boolean { if (reaches(fn, to, from)) return false; const old = wireInto(fn, to, i); if (old) disconnect(fn, old); fn.wires.push({ from, out, to, in: i }); return true; } export function disconnect(fn: Fn, wire: Wire) { fn.wires.splice(fn.wires.indexOf(wire), 1); } /** * Removes a node and its wires. An Input or Output node is also a port of * every Call to its function, in every function: the wire on that port goes, * and the wires on the ports after it move up one. */ export function removeNode(fn: Fn, node: GraphNode) { const port = node.kind === "input" ? params(fn).indexOf(node) : node.kind === "output" ? results(fn).indexOf(node) : -1; fn.wires = fn.wires.filter((w) => w.from !== node && w.to !== node); fn.nodes.splice(fn.nodes.indexOf(node), 1); if (port === -1) return; for (const other of functions) { other.wires = other.wires.filter((w) => { const [call, key] = node.kind === "input" ? [w.to, "in" as const] : [w.from, "out" as const]; if (call.fn !== fn) return true; // only a Call has a fn if (w[key] === port) return false; if (w[key] > port) w[key]--; return true; }); } } /** The Call nodes, outside `fn` itself, that would break if it went away. */ export const callers = (fn: Fn) => functions.filter((f) => f !== fn).flatMap((f) => f.nodes.filter((n) => n.fn === fn)); export function addFunction(): Fn { const fn: Fn = { name: `function${functions.length}`, nodes: [], wires: [], view: null }; const x = addNode(fn, "input", 40, 60, { name: "x" }); connect(fn, x, 0, addNode(fn, "output", 300, 60), 0); functions.push(fn); return fn; } export function removeFunction(fn: Fn) { functions.splice(functions.indexOf(fn), 1); } // ── The starting graphs ────────────────────────────────────────────────── const define = (name: string): Fn => ({ name, nodes: [], wires: [], view: null }); const main = define("main"); const factorial = define("factorial"); const sum = define("sum"); export const functions: Fn[] = [main, factorial, sum]; // Wires `ins` into the inputs of `to`, in order: [node, output] pairs. function feed(fn: Fn, to: GraphNode, ...ins: [GraphNode, number][]) { ins.forEach(([from, out], i) => connect(fn, from, out, to, i)); return to; } // n! = n ≤ 1 ? 1 : n × (n − 1)! and sum(n) = n ≤ 0 ? 0 : n + sum(n − 1) // Same shape: the If asks for its condition, then for one branch only, so the // branch that calls the function again is skipped once n reaches the bottom. function recursive(fn: Fn, test: number, base: number, op: string, result: string) { const n = addNode(fn, "input", 30, 40, { name: "n", value: test }); const one = addNode(fn, "number", 30, 180, { value: 1 }); const stop = base === 1 ? one : addNode(fn, "number", 240, 290, { value: base }); const done = feed(fn, addNode(fn, "compare", 240, 30, { op: "≤" }), [n, 0], [stop, 0]); const less = feed(fn, addNode(fn, "math", 240, 150, { op: "−" }), [n, 0], [one, 0]); const again = feed(fn, addNode(fn, "call", 450, 170, { fn }), [less, 0]); const step = feed(fn, addNode(fn, "math", 660, 110, { op }), [n, 0], [again, 0]); const pick = feed(fn, addNode(fn, "if", 870, 40), [done, 0], [stop, 0], [step, 0]); feed(fn, addNode(fn, "output", 1080, 60, { name: result }), [pick, 0]); } recursive(factorial, 5, 1, "×", "n!"); recursive(sum, 100, 0, "+", "total"); { // A grade: pass when the score is at least 50 and the work was handed in. const score = addNode(main, "number", 30, 30, { value: 72 }); const bar = addNode(main, "number", 30, 110, { value: 50 }); const enough = feed(main, addNode(main, "compare", 240, 30, { op: "≥" }), [score, 0], [bar, 0]); const handedIn = addNode(main, "switch", 240, 140, { value: true }); const both = feed(main, addNode(main, "logic", 450, 60, { op: "and" }), [enough, 0], [handedIn, 0]); const pass = addNode(main, "text", 450, 170, { value: "pass" }); const fail = addNode(main, "text", 450, 240, { value: "fail" }); const pick = feed(main, addNode(main, "if", 660, 90), [both, 0], [pass, 0], [fail, 0]); feed(main, addNode(main, "output", 870, 110, { name: "grade" }), [pick, 0]); // Recursion: 6! asks factorial for 5!, which asks for 4!, down to 1!. const six = addNode(main, "number", 30, 340, { value: 6 }); const fact = feed(main, addNode(main, "call", 240, 340, { fn: factorial }), [six, 0]); feed(main, addNode(main, "output", 450, 330, { name: "6!" }), [fact, 0]); // Depth: sum(1000) is a thousand calls inside each other. const deep = addNode(main, "number", 30, 460, { value: 1000 }); const total = feed(main, addNode(main, "call", 240, 460, { fn: sum }), [deep, 0]); feed(main, addNode(main, "output", 450, 450, { name: "1 + … + n" }), [total, 0]); }
// styles.ts: the editor's look. Nodes have fixed row heights, so app.ts can // work out where every port is from a node's x and y, without measuring the DOM. import "nuclo"; export const W = 188; // a node's width, px export const HEAD = 32; // its header export const ROW = 28; // one row: an input port on the left, an output port on the right const mono = "ui-monospace, monospace"; const wide = "@media (min-width: 760px)"; // functions and nodes left, canvas right; stacked below const focus = { outline: "2px solid var(--c-primary)", outlineOffset: "1px" }; const control = { height: "30px", padding: "0 10px", borderRadius: "8px", border: "1px solid var(--c-border-light)", backgroundColor: "var(--c-bg)", color: "var(--c-text)", fontFamily: "inherit", fontSize: "0.8125rem", fontWeight: "600", whiteSpace: "nowrap", hover: { backgroundColor: "var(--c-bg-secondary)" }, "&:disabled": { opacity: "0.45", cursor: "default" }, "&:focus-visible": focus }; const small = { height: "22px", minWidth: "0", padding: "0 6px", borderRadius: "6px", border: "1px solid var(--c-border-light)", backgroundColor: "var(--c-bg)", color: "var(--c-text)", fontFamily: mono, fontSize: "0.75rem", "&:focus-visible": focus }; const accent = (color: string) => ({ raw: { "--ng-accent": color } }); export const s = { app: css("ng-app", { display: "flex", flexDirection: "column", gap: "12px", width: "100%", height: "100%", [wide]: { flexDirection: "row" } }), side: css("ng-side", { display: "grid", gridTemplateColumns: "1fr 1fr", alignContent: "start", gap: "14px", [wide]: { display: "flex", flexDirection: "column", flexShrink: 0, width: "204px", overflowY: "auto" } }), section: css("ng-section", { display: "flex", flexDirection: "column", gap: "6px", "& h3": { fontSize: "0.6875rem", fontWeight: "700", textTransform: "uppercase", letterSpacing: "0.05em", color: "var(--c-text-muted)" } }), fn: css("ng-fn", { display: "flex", flexDirection: "column", alignItems: "flex-start", gap: "1px", padding: "6px 10px", borderRadius: "8px", textAlign: "left", fontSize: "0.8125rem", fontWeight: "600", color: "var(--c-text)", hover: { backgroundColor: "var(--c-bg-secondary)" }, "&:focus-visible": focus }), current: css("ng-current", { backgroundColor: "var(--c-primary-alpha-13)", color: "var(--c-primary-ink)", hover: { backgroundColor: "var(--c-primary-alpha-13)" } }), sig: css("ng-sig", { fontFamily: mono, fontSize: "0.6875rem", fontWeight: "400", color: "var(--c-text-muted)", overflowWrap: "anywhere" }), btn: css("ng-btn", control), group: css("ng-group", { display: "grid", gridTemplateColumns: "1fr 1fr", gap: "4px", "& > span": { gridColumn: "1 / -1", marginTop: "4px", fontSize: "0.6875rem", color: "var(--c-text-muted)" } }), add: css("ng-add", { ...control, height: "28px", padding: "0 8px", overflow: "hidden", textOverflow: "ellipsis", fontWeight: "500", textAlign: "left", "&::before": { content: '""', display: "inline-block", width: "7px", height: "7px", marginRight: "6px", borderRadius: "50%", backgroundColor: "var(--ng-accent)" } }), main: css("ng-main", { display: "flex", flexDirection: "column", gap: "10px", flex: "1", minWidth: "0", minHeight: "0" }), bar: css("ng-bar", { display: "flex", flexWrap: "wrap", alignItems: "center", gap: "8px 12px" }), crumbs: css("ng-crumbs", { display: "flex", flexWrap: "wrap", alignItems: "center", gap: "2px", fontSize: "0.8125rem", "& > span": { color: "var(--c-text-muted)" } }), crumb: css("ng-crumb", { padding: "3px 6px", borderRadius: "6px", color: "var(--c-text-dim)", hover: { backgroundColor: "var(--c-bg-secondary)", color: "var(--c-text)" }, "&[aria-current=true]": { fontWeight: "700", color: "var(--c-text)" }, "&:focus-visible": focus }), name: css("ng-name", { ...control, width: "130px", fontWeight: "400", cursor: "text" }), stats: css("ng-stats", { flex: "1 1 auto", textAlign: "right", fontFamily: mono, fontSize: "0.6875rem", color: "var(--c-text-muted)", fontVariantNumeric: "tabular-nums" }), // The canvas: a dot grid that moves and scales with the view, and the world inside it. canvas: css("ng-canvas", { position: "relative", flex: "1", minHeight: "440px", overflow: "hidden", borderRadius: "12px", border: "1px solid var(--c-border)", backgroundColor: "var(--c-bg)", backgroundImage: "radial-gradient(circle, var(--c-border-light) 1px, transparent 1.5px)", touchAction: "none", [wide]: { minHeight: "0" } }), world: css("ng-world", { position: "absolute", left: "0", top: "0", transformOrigin: "0 0" }), wires: css("ng-wires", { position: "absolute", left: "0", top: "0", width: "1px", height: "1px", overflow: "visible", pointerEvents: "none" }), link: css("ng-link", { "&:hover > :first-child": { raw: { stroke: "var(--c-accent-warm)", "stroke-dasharray": "none" } } }), wire: css("ng-wire", { transition: "opacity 0.2s ease", raw: { fill: "none", stroke: "var(--c-text-muted)", "stroke-width": "2.5", "stroke-linecap": "round" } }), num: css("ng-num", { raw: { stroke: "var(--c-tok-number)" } }), str: css("ng-str", { raw: { stroke: "var(--c-tok-string)" } }), yes: css("ng-yes", { raw: { stroke: "var(--c-primary)" } }), no: css("ng-no", { raw: { stroke: "var(--c-text-muted)", "stroke-dasharray": "2 5" } }), faint: css("ng-faint", { opacity: "0.22" }), hit: css("ng-hit", { cursor: "pointer", raw: { fill: "none", stroke: "transparent", "stroke-width": "14", "pointer-events": "stroke" } }), loose: css("ng-loose", { raw: { stroke: "var(--c-primary)", "stroke-dasharray": "6 5" } }), zoom: css("ng-zoom", { position: "absolute", right: "10px", bottom: "10px", display: "flex", gap: "4px", "& button": { minWidth: "30px", fontVariantNumeric: "tabular-nums" } }), hint: css("ng-hint", { position: "absolute", left: "12px", right: "150px", bottom: "14px", fontSize: "0.75rem", lineHeight: "1.4", color: "var(--c-text-muted)", pointerEvents: "none" }), notice: css("ng-notice", { color: "var(--c-accent-warm)", fontWeight: "600" }), node: css("ng-node", { position: "absolute", left: "0", top: "0", width: `${W}px`, borderRadius: "10px", backgroundColor: "var(--c-bg-card)", boxShadow: "0 0 0 1px var(--c-border-light), 0 6px 18px rgba(0, 0, 0, 0.12)", fontSize: "0.75rem", userSelect: "none", cursor: "grab", transition: "opacity 0.2s ease" }), value: css("ng-value", accent("var(--c-tok-number)")), op: css("ng-op", accent("var(--c-tok-keyword)")), flow: css("ng-flow", accent("var(--c-primary)")), port: css("ng-port", accent("var(--c-tok-string)")), call: css("ng-call", accent("var(--c-tok-fn)")), selected: css("ng-selected", { zIndex: 2, boxShadow: "0 0 0 2px var(--c-primary), 0 10px 26px rgba(0, 0, 0, 0.18)" }), target: css("ng-target", { outline: "2px dashed var(--c-primary)", outlineOffset: "4px" }), dim: css("ng-dim", { opacity: "0.5" }), failed: css("ng-failed", { boxShadow: "0 0 0 2px var(--c-accent-warm)" }), head: css("ng-head", { display: "flex", alignItems: "center", gap: "6px", height: `${HEAD}px`, padding: "0 4px 0 10px", borderRadius: "10px 10px 0 0", backgroundColor: "var(--c-bg-secondary)", boxShadow: "inset 0 -1px 0 var(--c-border)", fontWeight: "700" }), dot: css("ng-dot", { flex: "none", width: "8px", height: "8px", borderRadius: "50%", backgroundColor: "var(--ng-accent)" }), title: css("ng-title", { flex: "1", minWidth: "0", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }), icon: css("ng-icon", { flex: "none", width: "22px", height: "22px", borderRadius: "6px", fontSize: "0.875rem", lineHeight: "1", color: "var(--c-text-muted)", hover: { color: "var(--c-text)", backgroundColor: "var(--c-bg-light)" }, "&:focus-visible": focus }), row: css("ng-row", { position: "relative", display: "flex", alignItems: "center", gap: "6px", height: `${ROW}px`, padding: "0 12px" }), socket: css("ng-socket", { position: "absolute", top: "50%", width: "12px", height: "12px", marginTop: "-6px", borderRadius: "50%", backgroundColor: "var(--ng-accent)", boxShadow: "0 0 0 2px var(--c-bg-card)", cursor: "crosshair", transition: "transform 0.1s ease", hover: { transform: "scale(1.4)" } }), in: css("ng-in", { left: "-6px" }), out: css("ng-out", { right: "-6px" }), label: css("ng-label", { flex: "none", fontFamily: mono, fontSize: "0.6875rem", color: "var(--c-text-muted)" }), result: css("ng-result", { display: "flex", alignItems: "baseline", gap: "6px", minWidth: "0", marginLeft: "auto", fontFamily: mono, fontWeight: "600", whiteSpace: "nowrap", "& > :last-child": { overflow: "hidden", textOverflow: "ellipsis" } }), field: css("ng-field", { ...small, flex: "1", width: "100%" }), select: css("ng-select", { ...small, flex: "1", fontFamily: "inherit", cursor: "pointer" }), toggle: css("ng-toggle", { display: "flex", alignItems: "center", gap: "8px", flex: "1", fontFamily: mono, cursor: "pointer", "& input": { accentColor: "var(--c-primary)", width: "15px", height: "15px", margin: "0" } }), big: css("ng-big", { flex: "1", minWidth: "0", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontFamily: mono, fontSize: "1rem", fontWeight: "700", color: "var(--c-primary-ink)" }), error: css("ng-error", { color: "var(--c-accent-warm)", fontSize: "0.75rem" }), };