// Line-level model behind the visual card editor. It mirrors the canonical // formatter output (abilities at column 0, nested calls indented two spaces) so // editing a node and serializing it back keeps the pseudocode valid. export interface GraphNode { id: number text: string kind: 'ability' | 'effect' | 'raw' children: GraphNode[] } let nextId = 1 export function nextNodeId(): number { return nextId++ } export function makeNode(text: string, kind: GraphNode['kind'], children: GraphNode[] = []): GraphNode { return { id: nextNodeId(), text, kind, children } } export function parseGraph(source: string): GraphNode[] { const roots: GraphNode[] = [] const stack: Array<{ indent: number; node: GraphNode }> = [] for (const raw of source.split('\n')) { if (!raw.trim()) continue const indent = (raw.match(/^[ \t]*/)?.[0] ?? '').replace(/\t/g, ' ').length const text = raw.trim() const kind: GraphNode['kind'] = text.startsWith('#') || text === '(no abilities)' ? 'raw' : indent === 0 ? 'ability' : 'effect' const node = makeNode(text, kind) while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop() if (stack.length) stack[stack.length - 1].node.children.push(node) else roots.push(node) stack.push({ indent, node }) } return roots } export function serializeGraph(list: GraphNode[], depth = 0): string { return list .map(node => { const line = ' '.repeat(depth) + node.text return node.children.length ? `${line}\n${serializeGraph(node.children, depth + 1)}` : line }) .join('\n') } /** Inserted at the top level by the visual editor's "Add ability" menu. */ export const ABILITY_PALETTE = [ { group: 'Triggered', items: [ { label: 'Enters the battlefield', value: 'on enters(this):' }, { label: 'Dies', value: 'on dies(this):' }, { label: 'Attacks', value: 'on attacks(this):' }, { label: 'Upkeep', value: 'on upkeep(you):' }, { label: 'Cast a spell', value: 'on cast(you, any spell):' }, { label: 'Deals damage', value: 'on deals_damage(this, any):' }, ], }, { group: 'Other', items: [ { label: 'Activated {T}', value: 'activate {T}:' }, { label: 'Activated {2}, {T}', value: 'activate {2}, {T}:' }, { label: 'Static', value: 'static:' }, { label: 'Static if a condition', value: 'static if it is your turn:' }, { label: 'Spell effect', value: 'spell:' }, { label: 'Keyword: Flying', value: 'keyword Flying' }, ], }, ] /** Appended below an ability or nested block. Keep every value parseable. */ export const EFFECT_PALETTE = [ { group: 'Removal', items: [ { label: 'Damage', value: 'damage(target creature, 3)' }, { label: 'Destroy', value: 'destroy(target creature)' }, { label: 'Exile', value: 'exile(target permanent)' }, { label: 'Tap', value: 'tap(target creature)' }, { label: 'Counter spell', value: 'counter(spell, target spell)' }, { label: 'Sacrifice', value: 'sacrifice(you, target creature)' }, ], }, { group: 'Cards and life', items: [ { label: 'Draw', value: 'draw(you, 1)' }, { label: 'Discard', value: 'discard(you, 1)' }, { label: 'Mill', value: 'mill(you, 1)' }, { label: 'Scry', value: 'scry(you, 2)' }, { label: 'Surveil', value: 'surveil(you, 1)' }, { label: 'Search library', value: 'search(you, creature, 1, to hand, shuffle)' }, { label: 'Look at top', value: 'look_top(you, 3)' }, { label: 'Gain life', value: 'gain_life(you, 2)' }, { label: 'Lose life', value: 'lose_life(opponent, 2)' }, { label: 'Energy', value: 'energy(you, 2)' }, ], }, { group: 'Board', items: [ { label: 'Create token', value: 'create_token(you, 1, 1/1 white soldier creature)' }, { label: 'Create copy token', value: 'create_token(you, 1, copy of the triggering object, not legendary)' }, { label: 'Put counters', value: 'put_counters(target creature, +1/+1, 1)' }, { label: 'Pump', value: 'pump(target creature, 2/2, until end of turn)' }, { label: 'Grant keyword', value: 'grant(each creature you control, Flying)' }, { label: 'Untap', value: 'untap(target permanent you control)' }, { label: 'Return to hand', value: 'return_to_hand(target creature)' }, { label: 'Add mana', value: 'add_mana(you, {G})' }, ], }, { group: 'Flow', items: [ { label: 'If condition', value: 'if you control at least 3 artifacts:' }, ], }, ] /** Static abilities accept a different effect vocabulary than triggered/spell ones. */ export const STATIC_EFFECT_PALETTE = [ { group: 'Static effects', items: [ { label: 'Pump', value: 'pump(each creature you control, 1/1)' }, { label: 'Grant keyword', value: 'grant(each creature you control, Flying)' }, { label: 'Enters tapped', value: 'enters_tapped(this)' }, { label: 'Enters with counters', value: 'enters_with_counters(this, +1/+1, 1)' }, { label: 'Restrict', value: 'restrict(target creature, cant_attack)' }, { label: 'Set base P/T', value: 'set_pt(target creature, base, 1/1)' }, ], }, ] /** Value nodes that can be wired into argument sockets. */ export const VALUE_PALETTE = [ { group: 'Players', items: [ { label: 'A player', value: 'target player' }, { label: 'Each opponent', value: 'each opponent' }, { label: 'Each player', value: 'each player' }, { label: 'You', value: 'you' }, { label: 'That player', value: 'that player' }, { label: 'Its controller', value: 'its controller' }, ], }, { group: 'Targets', items: [ { label: 'A creature', value: 'target creature' }, { label: 'A permanent', value: 'target permanent' }, { label: 'An artifact', value: 'target artifact' }, { label: 'A land', value: 'target land' }, { label: 'A spell', value: 'target spell' }, { label: 'An ability', value: 'target ability' }, { label: 'Any target', value: 'any target' }, { label: 'This', value: 'this' }, { label: 'The triggering object', value: 'the triggering object' }, { label: 'Each creature you control', value: 'each creature you control' }, { label: 'Each creature an opponent controls', value: 'each creature an opponent controls' }, ], }, { group: 'Selectors', items: [ { label: 'Creature', value: 'creature' }, { label: 'Artifact', value: 'artifact' }, { label: 'Enchantment', value: 'enchantment' }, { label: 'Land', value: 'land' }, { label: 'Red', value: 'red' }, { label: 'Creature you control', value: 'creature you control' }, { label: 'Artifact you control', value: 'artifact you control' }, { label: 'Tapped creature', value: 'tapped creature' }, { label: 'Power 4 or greater', value: 'creature with power 4 or greater' }, { label: 'Nontoken Dragon', value: 'each other nontoken dragon creature you control' }, { label: 'Nontoken Angel', value: "each nontoken angel you don't control" }, { label: 'Selector builder', value: '__selector__' }, ], }, { group: 'Tokens', items: [ { label: '1/1 white Soldier', value: '1/1 white soldier creature' }, { label: '1/1 red Goblin', value: '1/1 red goblin creature' }, { label: 'Copy of the triggering object', value: 'copy of the triggering object' }, { label: 'Copy, not legendary', value: 'copy of the triggering object, not legendary' }, ], }, { group: 'Values', items: [ { label: '1', value: '1' }, { label: '2', value: '2' }, { label: '3', value: '3' }, { label: 'X', value: 'X' }, { label: 'That much', value: 'that much' }, { label: 'Its power', value: 'its power' }, { label: 'Its toughness', value: 'its toughness' }, { label: 'Count creatures you control', value: 'count(creature you control)' }, { label: 'Cards in your hand', value: 'cards in your hand' }, ], }, { group: 'Costs', items: [ { label: 'Tap', value: '{T}' }, { label: 'Mana {2}', value: '{2}' }, { label: 'Pay 2 life', value: 'pay 2 life' }, { label: 'Sacrifice this', value: 'sacrifice this' }, { label: 'Discard 1 card(s)', value: 'discard 1 card(s)' }, { label: 'Mill 1 card(s)', value: 'mill 1 card(s)' }, { label: 'Remove 1 +1/+1 counter(s)', value: 'remove 1 +1/+1 counter(s) from this' }, ], }, { group: 'Conditions', items: [ { label: 'It is your turn', value: 'it is your turn' }, { label: 'This is tapped', value: 'this is tapped' }, { label: 'You control at least 3 artifacts', value: 'you control at least 3 artifacts' }, { label: 'You have at least 10 life', value: 'you have at least 10 life' }, ], }, { group: 'Durations', items: [ { label: 'Until end of turn', value: 'until end of turn' }, { label: 'Until your next turn', value: 'until your next turn' }, { label: 'Until the end of your next turn', value: 'until the end of your next turn' }, { label: 'While this remains', value: 'for as long as this remains on the battlefield' }, ], }, { group: 'Logic', items: [ { label: 'Selector OR', value: '__or__' }, { label: 'Selector AND', value: '__and__' }, ], }, ] /** Human labels for effect/ability argument sockets. */ export const ARG_HINTS: Record = { damage: ['target', 'amount', 'source'], damage_divided: ['amount', 'target'], draw: ['player', 'amount'], discard: ['player', 'amount'], mill: ['player', 'amount'], gain_life: ['player', 'amount'], lose_life: ['player', 'amount'], pump: ['target', 'power/toughness', 'duration'], set_pt: ['target', 'power/toughness', 'duration'], grant: ['target', 'keyword', 'duration'], put_counters: ['target', 'counter', 'amount'], remove_counters: ['target', 'counter', 'amount'], create_token: ['player', 'amount', 'token', 'options'], destroy: ['target'], exile: ['target'], tap: ['target'], untap: ['target'], regenerate: ['target'], return_to_hand: ['target'], put_on_top: ['target'], sacrifice: ['player', 'target'], counter: ['spell|ability', 'target'], return_to_battlefield: ['target', 'options'], scry: ['player', 'amount'], surveil: ['player', 'amount'], search: ['player', 'selector', 'amount', 'destination', 'options'], add_mana: ['player', 'mana'], fight: ['target', 'target'], energy: ['player', 'amount'], attach: ['target'], restrict: ['target', 'rule'], prevent_damage: ['target', 'amount', 'duration'], gain_control: ['target', 'duration'], look_top: ['player', 'amount', 'options'], pay: ['cost'], transform: ['target'], } /** Human labels for trigger event arguments. */ const TRIGGER_ARG_HINTS: Record = { enters: ['subject'], dies: ['subject'], attacks: ['subject'], blocks: ['subject'], attacks_or_blocks: ['subject'], enters_or_attacks: ['subject'], enters_or_dies: ['subject'], leaves_battlefield: ['subject'], deals_damage: ['subject', 'recipient'], deals_combat_damage: ['subject', 'recipient'], upkeep: ['player'], end_step: ['player'], begin_combat: ['player'], first_main_phase: ['player'], postcombat_main_phase: ['player'], cast: ['player', 'spell'], becomes_level: ['level'], draw: ['player'], counter_placed: ['subject', 'counter'], becomes_target: ['subject'], gain_life: ['player'], lose_life: ['player'], } const TRIGGER_SUBJECT_OPTIONS = [ 'this', 'each other creature', 'each creature you control', 'each other nontoken dragon creature you control', "each nontoken angel you don't control", ] const PLAYER_OPTIONS = ['you', 'target player', 'each opponent', 'each player', 'that player', 'its controller'] const AMOUNT_OPTIONS = ['1', '2', '3', '4', '5', 'X', 'that much', 'count(creature you control)'] const TOKEN_OPTIONS = [ '1/1 white soldier creature', '1/1 red goblin creature', 'copy of the triggering object', ] /** Argument slots with fixed choices become dropdowns in the visual editor. */ export const SLOT_OPTIONS: Record = { enters: [TRIGGER_SUBJECT_OPTIONS], create_token: [PLAYER_OPTIONS, AMOUNT_OPTIONS, TOKEN_OPTIONS, ['not legendary']], } /** Splits on `separator` outside parentheses, brackets, braces and quotes. */ export function splitTopLevel(text: string, separator: string): string[] { const parts: string[] = [] let depth = 0 let quote = false let escape = false let start = 0 for (let index = 0; index < text.length; index++) { const char = text[index] if (quote) { if (escape) escape = false else if (char === '\\') escape = true else if (char === '"') quote = false continue } if (char === '"') { quote = true continue } if (char === '(' || char === '[' || char === '{') depth++ else if (char === ')' || char === ']' || char === '}') depth-- else if (depth === 0 && text.startsWith(separator, index)) { parts.push(text.slice(start, index)) index += separator.length - 1 start = index + 1 } } parts.push(text.slice(start)) return parts } export function blockOf(text: string): { kind: 'if' | 'choose' | 'schedule'; value: string } | undefined { const ifMatch = text.match(/^if (.+):$/) if (ifMatch) return { kind: 'if', value: ifMatch[1] } const chooseMatch = text.match(/^choose (\d+(?:-\d+)?):$/) if (chooseMatch) return { kind: 'choose', value: chooseMatch[1] } const scheduleMatch = text.match(/^schedule\((next_upkeep|next_end_step)\):$/) if (scheduleMatch) return { kind: 'schedule', value: scheduleMatch[1] } return undefined } /** True for nodes that carry an indented body. Mode lines can nest too. */ export function isBlockText(text: string): boolean { return Boolean(blockOf(text)) || /^grant_ability\(.*\):$/.test(text) || /^\d+\.\s/.test(text) } /** Blocks that are invalid without at least one nested effect. */ function requiresBody(text: string): boolean { return Boolean(blockOf(text)) || /^grant_ability\(.*\):$/.test(text) } export function abilityRequiresEffects(text: string): boolean { return /^(?:on |activate |static|spell|chapter )/.test(text) } /** Reads a `name(arg, arg)` prefix, leaving any suffix after the closing paren. */ export function readCallPrefix(text: string): { name: string; args: string[]; end: number } | undefined { const match = text.match(/^([a-z][a-z0-9_]*)\s*\(/) if (!match) return undefined const open = match[0].length - 1 let depth = 0 let quote = false let escape = false for (let index = open; index < text.length; index++) { const char = text[index] if (quote) { if (escape) escape = false else if (char === '\\') escape = true else if (char === '"') quote = false continue } if (char === '"') { quote = true continue } if (char === '(') depth++ else if (char === ')') { depth-- if (depth === 0) { const inner = text.slice(open + 1, index).trim() return { name: match[1], args: inner ? splitTopLevel(inner, ',').map(arg => arg.trim()) : [], end: index + 1, } } } } return undefined } /** Reads a complete `name(arg, arg)` call; returns undefined for block headers. */ export function parseCall(text: string): { name: string; args: string[] } | undefined { const trimmed = text.trim() const call = readCallPrefix(trimmed) return call && call.end === trimmed.length ? { name: call.name, args: call.args } : undefined } /** * Splits a supported line into fixed text plus argument slots. Unsupported * lines return undefined and stay as free text. */ export function shapeFromText(text: string): NodeShape | undefined { if (text.startsWith('on ') && text.endsWith(':')) { const inner = text.slice(3, -1) const call = readCallPrefix(inner) if (call) { const suffix = inner.slice(call.end) return { name: `on ${call.name}`, head: `on ${call.name}(`, tail: `)${suffix}:`, separator: ', ', slots: call.args.map((arg, index) => { const options = SLOT_OPTIONS[call.name]?.[index] return { label: TRIGGER_ARG_HINTS[call.name]?.[index] ?? `arg${index + 1}`, text: arg, ...(options ? { options } : {}), } }), } } } if (text.startsWith('activate ') && text.endsWith(':')) { return { head: 'activate ', tail: ':', separator: ', ', slots: [{ label: 'cost', text: text.slice('activate '.length, -1) }], } } if (text.startsWith('static if ') && text.endsWith(':')) { return { head: 'static if ', tail: ':', separator: ', ', slots: [{ label: 'condition', text: text.slice('static if '.length, -1) }], } } const block = blockOf(text) if (block) { if (block.kind === 'if') { return { head: 'if ', tail: ':', separator: ', ', slots: [{ label: 'condition', text: block.value }] } } if (block.kind === 'choose') { return { head: 'choose ', tail: ':', separator: ', ', slots: [{ label: 'modes', text: block.value }] } } return { head: 'schedule(', tail: '):', separator: ', ', slots: [{ label: 'when', text: block.value }] } } const call = parseCall(text) if (call) { return { head: `${call.name}(`, tail: ')', separator: ', ', slots: call.args.map((arg, index) => { const options = SLOT_OPTIONS[call.name]?.[index] return { label: ARG_HINTS[call.name]?.[index] ?? `arg${index + 1}`, text: arg, ...(options ? { options } : {}), } }), } } return undefined } /** * Rebuilds every shaped line from its slots and connected value nodes. Value * nodes are evaluated recursively, so `or`/`and` combinators can nest. */ export function syncTexts(model: GraphModel): void { const byId = new Map(model.nodes.map(node => [node.id, node])) const valueEdges = new Map() for (const edge of model.edges) { if (edge.port === 'value' && edge.slot !== undefined) { valueEdges.set(`${edge.to}:${edge.slot}`, edge.from) } } function renderSlot(node: CanvasNode, index: number, stack: Set): string { const childId = valueEdges.get(`${node.id}:${index}`) const child = childId !== undefined ? byId.get(childId) : undefined return child ? render(child, stack) : node.shape?.slots[index]?.text ?? '' } function render(node: CanvasNode | undefined, stack: Set): string { if (!node) return '' if (stack.has(node.id)) return node.kind === 'value' ? node.literal ?? '' : '' stack.add(node.id) let text: string if (node.kind === 'value' && node.combine) { text = `${renderSlot(node, 0, stack)} ${node.combine} ${renderSlot(node, 1, stack)}` } else if (node.shape) { text = node.shape.head + node.shape.slots.map((_, index) => renderSlot(node, index, stack)).join(node.shape.separator) + node.shape.tail } else if (node.kind === 'value') { text = node.literal ?? node.text } else { text = node.text } stack.delete(node.id) node.text = text return text } for (const node of model.nodes) render(node, new Set()) } // --------------------------------------------------------------------------- // Node canvas. The tree above is converted into flat nodes with explicit // `next` (sibling) and `body` (indented) links. Source is regenerated by // following those links, so the canvas and the pseudocode stay in sync. // --------------------------------------------------------------------------- export interface NodeSlot { label: string text: string /** Fixed choices rendered as a dropdown instead of a free-text input. */ options?: string[] } /** A line split into a fixed shell and the slots a value node can fill. */ export interface NodeShape { name?: string head: string tail: string separator: string slots: NodeSlot[] } export interface CanvasNode { id: number text: string kind: 'ability' | 'effect' | 'raw' | 'value' x: number y: number shape?: NodeShape /** Value nodes: literal source text. */ literal?: string /** Value nodes: combines its two slots instead of using a literal. */ combine?: 'or' | 'and' valueLabel?: string } export type GraphPort = 'next' | 'body' | 'value' export interface GraphEdge { id: number from: number port: GraphPort to: number /** Target argument index when port is 'value'. */ slot?: number } export interface GraphModel { nodes: CanvasNode[] edges: GraphEdge[] } export interface GraphSource { source: string unlinked: number problems: string[] } export const NODE_WIDTH = 230 const CHAIN_GAP = 70 const BODY_INDENT = NODE_WIDTH + 20 const BODY_GAP = 70 const ROOT_GAP = 70 let nextEdgeId = 1 export function estimateNodeHeight(text: string, slots?: number, hasName?: boolean): number { const count = slots ?? parseCall(text)?.args.length ?? 0 if (!count) return hasName ? 84 : 74 return 64 + count * 48 + (hasName ? 24 : 0) } export function hasBodyPort(model: GraphModel, node: CanvasNode): boolean { return node.kind === 'effect' && (isBlockText(node.text) || model.edges.some(edge => edge.from === node.id && edge.port === 'body')) } /** Converts pseudocode into nodes and links, laid out roughly left to right. */ export function graphFromSource(source: string): GraphModel { const model: GraphModel = { nodes: [], edges: [] } let y = 40 for (const root of parseGraph(source)) { if (root.kind === 'raw') { model.nodes.push({ id: root.id, text: root.text, kind: 'raw', x: 40, y }) y += 64 continue } const bounds = layoutTreeChain(model, [root], 40, y, 0) y += bounds.height + ROOT_GAP } return model } function layoutTreeChain( model: GraphModel, list: GraphNode[], x: number, y: number, depth: number, ): { width: number; height: number } { let cursorX = x let maxHeight = 0 let previous: number | undefined for (const treeNode of list) { const kind: CanvasNode['kind'] = depth === 0 ? treeNode.kind : 'effect' const node: CanvasNode = { id: treeNode.id, text: treeNode.text, kind, x: cursorX, y, shape: shapeFromText(treeNode.text), } model.nodes.push(node) if (previous !== undefined) { model.edges.push({ id: nextEdgeId++, from: previous, port: 'next', to: node.id }) } previous = node.id const height = estimateNodeHeight(node.text, node.shape?.slots.length, Boolean(node.shape?.name)) let totalHeight = height let advance = NODE_WIDTH if (treeNode.children.length) { if (depth === 0) { // An ability's output is its effect chain, laid out to the right. const chain = layoutTreeChain(model, treeNode.children, cursorX + NODE_WIDTH + CHAIN_GAP, y, 1) model.edges.push({ id: nextEdgeId++, from: node.id, port: 'next', to: treeNode.children[0].id }) totalHeight = Math.max(totalHeight, chain.height) advance = NODE_WIDTH + CHAIN_GAP + chain.width } else { // Blocks own an indented body below and just right of their socket. const body = layoutTreeChain(model, treeNode.children, cursorX + BODY_INDENT, y + height + BODY_GAP, depth + 1) model.edges.push({ id: nextEdgeId++, from: node.id, port: 'body', to: treeNode.children[0].id }) totalHeight = Math.max(totalHeight, height + BODY_GAP + body.height) } } maxHeight = Math.max(maxHeight, totalHeight) cursorX += advance + CHAIN_GAP } return { width: cursorX - x, height: maxHeight } } /** Rebuilds pseudocode by walking next/body links from every ability root. */ export function sourceFromGraph(model: GraphModel): GraphSource { syncTexts(model) const byId = new Map(model.nodes.map(node => [node.id, node])) const outgoing = new Map() for (const edge of model.edges) { outgoing.set(`${edge.from}:${edge.port}`, edge) } const lines: string[] = [] const visited = new Set() const problems: string[] = [] const label = (text: string) => (text.length > 52 ? `${text.slice(0, 49)}…` : text) const checkModes = (startId: number) => { let mode = byId.get(startId) let expected = 1 const seenModes = new Set() while (mode && !seenModes.has(mode.id)) { seenModes.add(mode.id) const number = mode.text.match(/^(\d+)\.\s/) if (!number || Number(number[1]) !== expected) { problems.push('A choose body must be numbered 1, 2, 3…') return } expected++ const next = outgoing.get(`${mode.id}:next`) mode = next ? byId.get(next.to) : undefined } } const emitChain = (startId: number, depth: number) => { let current: number | undefined = startId while (current !== undefined) { if (visited.has(current)) { problems.push(`Cycle at ${label(byId.get(current)?.text ?? 'node')}`) return } const node = byId.get(current) if (!node) return visited.add(current) lines.push(`${' '.repeat(depth)}${node.text}`) const body = outgoing.get(`${current}:body`) if (body) { if (blockOf(node.text)?.kind === 'choose') checkModes(body.to) emitChain(body.to, depth + 1) } else if (requiresBody(node.text)) { problems.push(`"${label(node.text)}" has no body`) } current = outgoing.get(`${current}:next`)?.to } } for (const node of model.nodes) { if (node.kind === 'raw') { if (!visited.has(node.id)) { visited.add(node.id) lines.push(node.text) } continue } if (node.kind !== 'ability' || visited.has(node.id)) continue visited.add(node.id) lines.push(node.text) const next = outgoing.get(`${node.id}:next`) if (next) emitChain(next.to, 1) else if (abilityRequiresEffects(node.text)) problems.push(`"${label(node.text)}" has no effects`) } const usedValues = new Set(model.edges.filter(edge => edge.port === 'value').map(edge => edge.from)) const unlinked = model.nodes.filter(node => (node.kind === 'effect' && !visited.has(node.id)) || (node.kind === 'value' && !usedValues.has(node.id)), ).length if (unlinked) { problems.push(`${unlinked} unconnected node${unlinked === 1 ? '' : 's'} will be ignored`) } return { source: lines.join('\n'), unlinked, problems } } function reaches(model: GraphModel, start: number, target: number): boolean { const stack = [start] const seen = new Set() while (stack.length) { const id = stack.pop()! if (id === target) return true if (seen.has(id)) continue seen.add(id) for (const edge of model.edges) { if (edge.from === id) stack.push(edge.to) } } return false } /** Links an output socket to a node input or an argument slot. */ export function connectNodes( model: GraphModel, from: number, port: GraphPort, to: number, slot?: number, ): boolean { if (from === to) return false const source = model.nodes.find(node => node.id === from) const target = model.nodes.find(node => node.id === to) if (!source || !target) return false if (port === 'value') { if (source.kind !== 'value' || !target.shape || slot === undefined || !target.shape.slots[slot]) { return false } } else { if (target.kind !== 'effect') return false if (port === 'body' && !hasBodyPort(model, source)) return false } if (reaches(model, to, from)) return false if (port === 'value') { model.edges = model.edges.filter(edge => !(edge.port === 'value' && edge.to === to && edge.slot === slot) && !(edge.from === from && edge.port === 'value'), ) model.edges.push({ id: nextEdgeId++, from, port, to, slot }) } else { model.edges = model.edges.filter(edge => !((edge.port === 'next' || edge.port === 'body') && edge.to === to) && !(edge.from === from && edge.port === port), ) model.edges.push({ id: nextEdgeId++, from, port, to }) } return true }