@codecanvas-ide/engine 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/parse.ts", "../src/project.ts", "../src/workspace.ts", "../src/remoteProject.ts", "../src/projectServer.ts", "../src/projectWorker.ts", "../src/edits.ts", "../src/diff.ts", "../src/conflicts.ts", "../src/layoutRules.ts", "../src/arrange.ts", "../src/layout.ts", "../src/html.ts", "../src/styles.ts", "../src/canvas.ts"],
4
- "sourcesContent": ["import ts from 'typescript';\nimport type { Block, BlockKind, CodeDiagnostic, FileModel, InsertStyle, Usage, UsageKind } from './types';\n\nconst PREVIEW_LINES = 6;\nconst CONTAINER_PREVIEW_LINES = 3;\nconst PREVIEW_WIDTH = 64;\n\ninterface Internals {\n sf: ts.SourceFile;\n builder: Builder;\n /** An old syntax tree can be updated incrementally only once. */\n reused: boolean;\n}\nconst internals = new WeakMap<FileModel, Internals>();\n\n/**\n * Parse a TypeScript file into a tree of blocks plus the usage links between them.\n * Pure function: same text in, same model out.\n */\nexport function parseFile(path: string, text: string): FileModel {\n const m = parseStructure(path, text);\n m.usages = computeUsages(m);\n return m;\n}\n\n/**\n * Fast part of parsing: blocks only (usages left empty). Pass the previous model of the same\n * file to parse incrementally, re-reading only the changed region.\n */\nexport function parseStructure(path: string, text: string, prev?: FileModel | null): FileModel {\n const kind = scriptKindOf(path);\n const old = prev && prev.path === path ? internals.get(prev) : undefined;\n let sf: ts.SourceFile;\n if (old && !old.reused) {\n old.reused = true;\n sf = ts.updateSourceFile(old.sf, text, changeRange(prev!.text, text));\n } else {\n sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, kind);\n }\n const b = new Builder(sf, text);\n b.collectStatements(sf.statements, null, 0);\n const syntax = (sf as unknown as { parseDiagnostics?: ts.DiagnosticWithLocation[] }).parseDiagnostics ?? [];\n const model: FileModel = {\n path,\n text,\n roots: b.roots,\n blocks: b.byId,\n usages: [],\n syntaxErrors: syntax.length,\n firstErrorLine: -1,\n diagnostics: [],\n indentUnit: detectIndentUnit(text),\n };\n model.diagnostics = syntax.map((d) => toCodeDiagnostic(model, sf, d, 'syntax'));\n model.firstErrorLine = model.diagnostics[0]?.line ?? -1;\n internals.set(model, { sf, builder: b, reused: false });\n return model;\n}\n\n/** Innermost block whose text range contains `offset`. */\nexport function blockAt(model: FileModel, offset: number): Block | null {\n let found: Block | null = null;\n let candidates = model.roots;\n for (;;) {\n const containing = candidates.find((b) => offset >= b.start && offset <= b.end);\n if (!containing) return found;\n found = containing;\n candidates = containing.children;\n }\n}\n\nexport function toCodeDiagnostic(model: FileModel, sf: ts.SourceFile, d: ts.Diagnostic, source: CodeDiagnostic['source']): CodeDiagnostic {\n const start = d.start ?? 0;\n return {\n start,\n length: d.length ?? 0,\n line: sf.getLineAndCharacterOfPosition(Math.min(start, sf.text.length)).line + 1,\n message: ts.flattenDiagnosticMessageText(d.messageText, '\\n'),\n source,\n severity: d.category === ts.DiagnosticCategory.Error ? 'error' : 'warning',\n blockId: blockAt(model, start)?.id ?? null,\n };\n}\n\n/** The builder that produced `model`: used by the project to resolve usages across files. */\nexport function builderOf(model: FileModel) {\n return internals.get(model)?.builder;\n}\n\n/** Slower part: resolve every name to its declaration and link the blocks. */\nexport function computeUsages(model: FileModel): Usage[] {\n const st = internals.get(model);\n if (!st) return [];\n if (st.reused) {\n // The tree was handed to a newer parse; re-parse from scratch to stay safe.\n return parseFile(model.path, model.text).usages;\n }\n return st.builder.collectUsages(st.sf, createProgram(st.sf).getTypeChecker());\n}\n\nfunction changeRange(a: string, b: string): ts.TextChangeRange {\n let s = 0;\n const n = Math.min(a.length, b.length);\n while (s < n && a.charCodeAt(s) === b.charCodeAt(s)) s++;\n let e = 0;\n while (e < n - s && a.charCodeAt(a.length - 1 - e) === b.charCodeAt(b.length - 1 - e)) e++;\n return ts.createTextChangeRange(ts.createTextSpan(s, a.length - e - s), b.length - e - s);\n}\n\n/** `exports.total = function () {}` or `module.exports.total = () => {}`: a function block named `total`. */\nfunction commonJsExportedFunction(s: ts.Statement): { assignment: ts.BinaryExpression; exportedName: ts.Identifier; fn: ts.FunctionExpression | ts.ArrowFunction } | null {\n if (!ts.isExpressionStatement(s) || !ts.isBinaryExpression(s.expression) || s.expression.operatorToken.kind !== ts.SyntaxKind.EqualsToken) return null;\n const { left, right } = s.expression;\n const fn = unwrap(right);\n const isFunction = ts.isFunctionExpression(fn) || ts.isArrowFunction(fn);\n if (!isFunction || !ts.isPropertyAccessExpression(left) || !ts.isIdentifier(left.name)) return null;\n const target = left.expression.getText();\n const isExportsObject = target === 'exports' || target === 'module.exports';\n return isExportsObject ? { assignment: s.expression, exportedName: left.name, fn } : null;\n}\n\n/** JavaScript files parse as JavaScript: in a `.js` file `<T>(x)` is a comparison, not a type argument. */\nexport function scriptKindOf(path: string): ts.ScriptKind {\n if (/\\.[cm]?jsx?$/.test(path)) return path.endsWith('x') ? ts.ScriptKind.JSX : ts.ScriptKind.JS;\n return path.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS;\n}\n\n/** A one-file program with no libs: enough for the checker to resolve names inside the file. */\nfunction createProgram(sf: ts.SourceFile): ts.Program {\n const options: ts.CompilerOptions = {\n noLib: true,\n noResolve: true,\n allowJs: true,\n target: ts.ScriptTarget.Latest,\n jsx: ts.JsxEmit.Preserve,\n types: [],\n };\n const host: ts.CompilerHost = {\n getSourceFile: (name) => (name === sf.fileName ? sf : undefined),\n getDefaultLibFileName: () => 'lib.d.ts',\n writeFile: () => {},\n getCurrentDirectory: () => '/',\n getCanonicalFileName: (f) => f,\n useCaseSensitiveFileNames: () => true,\n getNewLine: () => '\\n',\n fileExists: (f) => f === sf.fileName,\n readFile: () => undefined,\n getDirectories: () => [],\n };\n return ts.createProgram({ rootNames: [sf.fileName], options, host });\n}\n\nexport function detectIndentUnit(text: string): string {\n const m = /\\n(\\t+|[ ]{2,8})\\S/.exec(text);\n if (!m) return ' ';\n return m[1].startsWith('\\t') ? '\\t' : m[1].length >= 4 && m[1].length % 4 === 0 ? ' ' : ' ';\n}\n\ninterface Pending {\n kind: BlockKind;\n key: string;\n name: string;\n detail: string;\n tags: string[];\n rangeNodes: ts.Node[]; // nodes covered by the block (more than one for overloads/statement groups)\n declNodes: ts.Node[]; // nodes that \"declare\" the block, for usage resolution\n nameNode?: ts.Node;\n /** Node whose own code forms the preview. */\n previewRange: [number, number] | null;\n insert: InsertStyle;\n insertAt: number;\n /** Collect children of this block. */\n children?: (block: Block) => void;\n}\n\nclass Builder {\n roots: Block[] = [];\n byId = new Map<string, Block>();\n /**\n * Declaration node \u2192 block id, keyed by node position (see `nodeKey`) so a syntax tree parsed\n * elsewhere from the same text (the project's language service) maps to the same blocks.\n */\n private declToBlock = new Map<string, string>();\n /** Range node \u2192 block, to find which block contains a usage. Keyed like `declToBlock`. */\n private rangeToBlock = new Map<string, Block>();\n /** Every name a usage could resolve to. Other identifiers skip the (slow) checker. */\n readonly names = new Set<string>();\n\n constructor(\n private sf: ts.SourceFile,\n private text: string,\n ) {}\n\n // ---------- structure ----------\n\n collectStatements(stmts: readonly ts.Statement[], parent: Block | null, depth: number, declarationsOnly = false) {\n let group: ts.Statement[] = [];\n const flushGroup = () => {\n if (!group.length) return;\n const nodes = group;\n group = [];\n const first = nodes[0];\n const firstLine = this.text.slice(first.getStart(this.sf), first.end).split('\\n')[0].trim();\n this.add(\n {\n kind: 'statement',\n key: 'stmt:' + firstLine.slice(0, 40),\n name: truncate(firstLine, 48),\n detail: nodes.length > 1 ? `+${nodes.length - 1} more` : '',\n tags: [],\n rangeNodes: nodes,\n declNodes: [],\n previewRange: [nodes[0].getStart(this.sf), nodes[nodes.length - 1].end],\n insert: null,\n insertAt: -1,\n },\n parent,\n depth,\n );\n };\n\n for (let i = 0; i < stmts.length; i++) {\n const s = stmts[i];\n if (ts.isFunctionDeclaration(s)) {\n flushGroup();\n // Group overloads: `function f(a): x; function f(b): y; function f(c) {...}`\n const overloads: ts.FunctionDeclaration[] = [s];\n while (!overloads[overloads.length - 1].body) {\n const next = stmts[i + 1];\n if (next && ts.isFunctionDeclaration(next) && next.name?.text === s.name?.text) {\n overloads.push(next);\n i++;\n } else break;\n }\n this.addFunctionLike(overloads, s.name?.text ?? 'default', parent, depth);\n } else if (ts.isClassDeclaration(s)) {\n flushGroup();\n this.addClass(s, s, s.name?.text ?? 'default', parent, depth);\n } else if (ts.isVariableStatement(s)) {\n flushGroup();\n this.addVariableStatement(s, parent, depth, declarationsOnly);\n } else if (commonJsExportedFunction(s)) {\n flushGroup();\n const { assignment, exportedName, fn } = commonJsExportedFunction(s)!;\n // TypeScript declares the export on the assignment or its left side, depending on the form.\n const declNodes = [s, assignment, assignment.left];\n this.addFunctionLike([fn], exportedName.text, parent, depth, { rangeNodes: [s], declNodes, extraTags: ['export'], nameNode: exportedName });\n } else if (declarationsOnly) {\n continue;\n } else if (ts.isImportDeclaration(s) || ts.isImportEqualsDeclaration(s)) {\n flushGroup();\n this.addImport(s, parent, depth);\n } else if (ts.isInterfaceDeclaration(s) || ts.isTypeAliasDeclaration(s) || ts.isEnumDeclaration(s)) {\n flushGroup();\n const keyword = ts.isInterfaceDeclaration(s) ? 'interface' : ts.isEnumDeclaration(s) ? 'enum' : 'type';\n const typeParams = 'typeParameters' in s && s.typeParameters ? `<${s.typeParameters.map((t) => t.getText()).join(', ')}>` : '';\n const bodyStart = ts.isTypeAliasDeclaration(s) ? s.type.getStart(this.sf) : this.text.indexOf('{', s.name.end);\n this.add(\n {\n kind: 'type',\n key: s.name.text,\n name: s.name.text,\n detail: typeParams,\n tags: [...modifierTags(s), keyword],\n rangeNodes: [s],\n declNodes: [s],\n nameNode: s.name,\n previewRange: bodyStart >= 0 ? [bodyStart, s.end] : null,\n insert: null,\n insertAt: -1,\n },\n parent,\n depth,\n );\n } else if (ts.isModuleDeclaration(s) && s.body && ts.isModuleBlock(s.body)) {\n flushGroup();\n const body = s.body;\n this.add(\n {\n kind: 'namespace',\n key: s.name.getText(),\n name: s.name.getText(),\n detail: '',\n tags: [...modifierTags(s), 'namespace'],\n rangeNodes: [s],\n declNodes: [s],\n nameNode: s.name,\n previewRange: [body.getStart(this.sf) + 1, body.end - 1],\n insert: 'body',\n insertAt: body.end - 1,\n children: (blk) => this.collectStatements(body.statements, blk, depth + 1),\n },\n parent,\n depth,\n );\n } else {\n group.push(s);\n }\n }\n flushGroup();\n }\n\n private addImport(s: ts.ImportDeclaration | ts.ImportEqualsDeclaration, parent: Block | null, depth: number) {\n let spec: string;\n let names: string[] = [];\n if (ts.isImportDeclaration(s)) {\n spec = (s.moduleSpecifier as ts.StringLiteral).text;\n const clause = s.importClause;\n if (clause?.name) names.push(clause.name.text);\n const nb = clause?.namedBindings;\n if (nb && ts.isNamespaceImport(nb)) names.push('* as ' + nb.name.text);\n if (nb && ts.isNamedImports(nb)) names.push(...nb.elements.map((e) => e.name.text));\n if (!clause) names = ['(side effect)'];\n } else {\n spec = s.name.text;\n names = [s.moduleReference.getText()];\n this.names.add(s.name.text);\n }\n for (const n of names) this.names.add(n.replace('* as ', ''));\n this.add(\n {\n kind: 'import',\n key: 'import:' + spec,\n name: spec,\n detail: '',\n tags: ts.isImportDeclaration(s) && s.importClause?.isTypeOnly ? ['type'] : [],\n rangeNodes: [s],\n declNodes: [s],\n previewRange: null,\n insert: null,\n insertAt: -1,\n },\n parent,\n depth,\n wrapNames(names),\n );\n }\n\n private addFunctionLike(\n nodes: (ts.FunctionLikeDeclaration & ts.Node)[],\n name: string,\n parent: Block | null,\n depth: number,\n /** `nameNode`: where the name is when the function has none of its own (`const f = () => {}`). */\n opts: { rangeNodes?: ts.Node[]; declNodes?: ts.Node[]; key?: string; extraTags?: string[]; nameNode?: ts.Node } = {},\n ) {\n const impl = nodes[nodes.length - 1];\n const sig = nodes.find((n) => !!n.body) ?? impl;\n const body = impl.body;\n let previewRange: [number, number] | null = null;\n let insert: InsertStyle = null;\n let insertAt = -1;\n if (body && ts.isBlock(body)) {\n previewRange = [body.getStart(this.sf) + 1, body.end - 1];\n insert = 'body';\n // Insert nested code before a trailing `return`, otherwise before the closing brace.\n const last = body.statements[body.statements.length - 1];\n insertAt = last && ts.isReturnStatement(last) ? this.lineStartOf(last.getStart(this.sf)) : body.end - 1;\n } else if (body) {\n previewRange = [body.getStart(this.sf), body.end];\n }\n const typeParams = sig.typeParameters?.length ? `<${sig.typeParameters.map((t) => t.getText()).join(', ')}>` : '';\n const ret = sig.type ? ': ' + sig.type.getText() : '';\n const detail = squash(`${typeParams}(${sig.parameters.map((p) => p.getText()).join(', ')})${ret}`);\n const tags = [...(opts.extraTags ?? []), ...modifierTags(nodes[0])];\n if (nodes.length > 1) tags.push(`${nodes.length - 1} overload${nodes.length > 2 ? 's' : ''}`);\n if (impl.asteriskToken) tags.push('generator');\n this.add(\n {\n kind: 'function',\n key: opts.key ?? name,\n name,\n detail,\n tags,\n rangeNodes: opts.rangeNodes ?? nodes,\n declNodes: opts.declNodes ?? nodes,\n nameNode: opts.nameNode ?? impl.name,\n previewRange,\n insert,\n insertAt,\n children:\n body && ts.isBlock(body) ? (blk) => this.collectStatements(body.statements, blk, depth + 1, true) : undefined,\n },\n parent,\n depth,\n );\n }\n\n private addClass(\n cls: ts.ClassLikeDeclaration,\n rangeNode: ts.Node,\n name: string,\n parent: Block | null,\n depth: number,\n declNodes: ts.Node[] = [cls],\n extraTags: string[] = [],\n ) {\n const heritage = (cls.heritageClauses ?? []).map((h) => h.getText()).join(' ');\n const openBrace = this.text.indexOf('{', (cls.heritageClauses?.at(-1) ?? cls.typeParameters?.at(-1) ?? cls.name ?? cls).end);\n const typeParams = cls.typeParameters?.length ? `<${cls.typeParameters.map((t) => t.getText()).join(', ')}>` : '';\n this.add(\n {\n kind: 'class',\n key: name,\n name,\n detail: squash(typeParams + (heritage ? ' ' + heritage : '')),\n tags: [...extraTags, ...modifierTags(rangeNode === cls ? cls : rangeNode)],\n rangeNodes: [rangeNode],\n declNodes,\n nameNode: cls.name,\n previewRange: openBrace >= 0 ? [openBrace + 1, cls.end - 1] : null,\n insert: 'class',\n insertAt: cls.end - 1,\n children: (blk) => this.collectMembers(cls.members, blk, depth + 1),\n },\n parent,\n depth,\n );\n }\n\n private collectMembers(members: ts.NodeArray<ts.ClassElement>, parent: Block, depth: number) {\n for (let i = 0; i < members.length; i++) {\n const m = members[i];\n if (ts.isMethodDeclaration(m) || ts.isConstructorDeclaration(m)) {\n const name = ts.isConstructorDeclaration(m) ? 'constructor' : m.name.getText();\n const overloads: (ts.MethodDeclaration | ts.ConstructorDeclaration)[] = [m];\n while (!overloads[overloads.length - 1].body) {\n const next = members[i + 1];\n const nextName = next && (ts.isConstructorDeclaration(next) ? 'constructor' : ts.isMethodDeclaration(next) ? next.name.getText() : null);\n if (nextName === name) {\n overloads.push(next as ts.MethodDeclaration);\n i++;\n } else break;\n }\n this.addFunctionLike(overloads, name, parent, depth);\n } else if (ts.isGetAccessor(m) || ts.isSetAccessor(m)) {\n const name = m.name.getText();\n const word = ts.isGetAccessor(m) ? 'get' : 'set';\n this.addFunctionLike([m], name, parent, depth, { key: `${word} ${name}`, extraTags: [word] });\n } else if (ts.isPropertyDeclaration(m)) {\n const name = m.name.getText();\n const init = m.initializer && unwrap(m.initializer);\n if (init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {\n this.addFunctionLike([init], name, parent, depth, { rangeNodes: [m], declNodes: [m], extraTags: modifierTags(m), nameNode: m.name });\n } else {\n this.addVariable(m, m, name, m.type ? ': ' + m.type.getText() : '', modifierTags(m), parent, depth, m.initializer);\n }\n }\n }\n }\n\n private addVariableStatement(s: ts.VariableStatement, parent: Block | null, depth: number, functionsOnly: boolean) {\n const decls = s.declarationList.declarations;\n const keyword = s.declarationList.flags & ts.NodeFlags.Const ? 'const' : s.declarationList.flags & ts.NodeFlags.Let ? 'let' : 'var';\n for (const d of decls) {\n const rangeNode = decls.length === 1 ? s : d;\n const name = d.name.getText();\n const tags = [...modifierTags(s), keyword];\n const init = d.initializer && unwrap(d.initializer);\n if (init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {\n this.addFunctionLike([init], name, parent, depth, { rangeNodes: [rangeNode], declNodes: [d], extraTags: tags, nameNode: d.name });\n } else if (init && ts.isClassExpression(init)) {\n this.addClass(init, rangeNode, name, parent, depth, [d, init], tags);\n } else if (!functionsOnly) {\n this.addVariable(d, rangeNode, name, d.type ? ': ' + d.type.getText() : '', tags, parent, depth, d.initializer);\n }\n }\n }\n\n private addVariable(\n decl: ts.Node,\n rangeNode: ts.Node,\n name: string,\n type: string,\n tags: string[],\n parent: Block | null,\n depth: number,\n initializer: ts.Expression | undefined,\n ) {\n const init = initializer && unwrap(initializer);\n // Object literals with methods become containers of function blocks.\n const objectChildren =\n init && ts.isObjectLiteralExpression(init)\n ? init.properties.filter(\n (p) =>\n ts.isMethodDeclaration(p) ||\n (ts.isPropertyAssignment(p) && (ts.isArrowFunction(unwrap(p.initializer)) || ts.isFunctionExpression(unwrap(p.initializer)))),\n )\n : [];\n this.add(\n {\n kind: 'variable',\n key: name,\n name,\n detail: squash(type),\n tags,\n rangeNodes: [rangeNode],\n declNodes: [decl],\n nameNode: (decl as ts.NamedDeclaration).name,\n previewRange: initializer ? [initializer.getStart(this.sf), initializer.end] : null,\n insert: null,\n insertAt: -1,\n children: objectChildren.length\n ? (blk) => {\n for (const p of objectChildren) {\n const pname = p.name!.getText();\n if (ts.isMethodDeclaration(p)) this.addFunctionLike([p], pname, blk, depth + 1);\n else {\n const fn = unwrap((p as ts.PropertyAssignment).initializer) as ts.ArrowFunction;\n this.addFunctionLike([fn], pname, blk, depth + 1, { rangeNodes: [p], declNodes: [p], nameNode: p.name });\n }\n }\n }\n : undefined,\n },\n parent,\n depth,\n );\n }\n\n private add(p: Pending, parent: Block | null, depth: number, presetPreview?: string[]) {\n const first = p.rangeNodes[0];\n const last = p.rangeNodes[p.rangeNodes.length - 1];\n const start = this.startWithComments(first);\n const siblings = parent ? parent.children : this.roots;\n let key = p.key;\n if (siblings.some((s) => s.key === key)) {\n let n = 2;\n while (siblings.some((s) => s.key === `${p.key}#${n}`)) n++;\n key = `${p.key}#${n}`;\n }\n const id = parent ? `${parent.id}/${key}` : key;\n const block: Block = {\n id,\n key,\n kind: p.kind,\n name: p.name,\n detail: p.detail,\n tags: p.tags,\n start,\n end: last.end,\n nameStart: p.nameNode ? p.nameNode.getStart(this.sf) : -1,\n preview: [],\n previewMore: 0,\n children: [],\n parentId: parent?.id ?? null,\n depth,\n insert: p.insert,\n insertAt: p.insertAt,\n indent: this.indentAt(first.getStart(this.sf)),\n };\n siblings.push(block);\n this.byId.set(id, block);\n this.names.add(p.name);\n for (const n of p.rangeNodes) this.rangeToBlock.set(nodeKey(n), block);\n for (const n of p.declNodes) this.declToBlock.set(nodeKey(n), id);\n p.children?.(block);\n if (presetPreview) {\n block.preview = presetPreview;\n } else if (p.previewRange) {\n const max = block.children.length ? CONTAINER_PREVIEW_LINES : PREVIEW_LINES;\n const { lines, more } = makePreview(this.text, p.previewRange, block.children, max);\n block.preview = lines;\n block.previewMore = more;\n }\n return block;\n }\n\n /** Include doc comments directly above the node (no blank line in between). */\n private startWithComments(node: ts.Node): number {\n let start = node.getStart(this.sf);\n const comments = ts.getLeadingCommentRanges(this.text, node.pos) ?? [];\n for (let i = comments.length - 1; i >= 0; i--) {\n const gap = this.text.slice(comments[i].end, start);\n if (/\\S/.test(gap) || (gap.match(/\\n/g)?.length ?? 0) > 1) break;\n start = comments[i].pos;\n }\n return start;\n }\n\n private lineStartOf(pos: number): number {\n return this.text.lastIndexOf('\\n', pos - 1) + 1;\n }\n\n private indentAt(pos: number): string {\n const ls = this.lineStartOf(pos);\n return /^[ \\t]*/.exec(this.text.slice(ls, pos))![0];\n }\n\n // ---------- usages ----------\n\n blockIdForDeclaration(declaration: ts.Node): string | undefined {\n return this.declToBlock.get(nodeKey(declaration));\n }\n\n /**\n * Link every name used inside a block to the block that declares it. `sf` is a tree of the same\n * text (this builder's own, or the language service's when resolving across files).\n */\n collectUsages(sf: ts.SourceFile, checker: ts.TypeChecker, otherFiles?: OtherFileResolver): Usage[] {\n const byPair = new Map<string, Usage>();\n const visit = (node: ts.Node, current: Block | null) => {\n const blk = this.rangeToBlock.get(nodeKey(node));\n if (blk) current = blk;\n if (ts.isIdentifier(node) && current) this.recordUsage(node, current, checker, byPair, otherFiles);\n ts.forEachChild(node, (c) => visit(c, current));\n };\n visit(sf, null);\n return [...byPair.values()];\n }\n\n private recordUsage(id: ts.Identifier, from: Block, checker: ts.TypeChecker, out: Map<string, Usage>, otherFiles?: OtherFileResolver) {\n const isKnownName = this.names.has(id.text) || !!otherFiles?.projectNames.has(id.text);\n if (!isKnownName) return;\n const parent = id.parent;\n // Skip the names of declarations themselves. A shorthand `{ x }` is both a name and a use of `x`.\n const isDeclarationName = !!parent && (parent as ts.NamedDeclaration).name === id && !ts.isPropertyAccessExpression(parent) && !ts.isShorthandPropertyAssignment(parent);\n if (isDeclarationName) return;\n let sym: ts.Symbol | undefined;\n try {\n sym =\n parent && ts.isShorthandPropertyAssignment(parent)\n ? checker.getShorthandAssignmentValueSymbol(parent)\n : checker.getSymbolAtLocation(id);\n } catch {\n return;\n }\n if (!sym?.declarations) return;\n const kind = usageKind(id);\n let to: string | undefined;\n let importBlockId: string | undefined;\n for (const d of sym.declarations) {\n to = this.declToBlock.get(nodeKey(d));\n if (!to) {\n // Imported names point at their import statement.\n let n: ts.Node | undefined = d;\n while (n && !ts.isImportDeclaration(n) && !ts.isImportEqualsDeclaration(n) && !ts.isSourceFile(n)) n = n.parent;\n if (n && !ts.isSourceFile(n)) importBlockId = to = this.declToBlock.get(nodeKey(n));\n }\n if (to) break;\n }\n if (otherFiles) {\n const isImportedName = !!importBlockId && (sym.flags & ts.SymbolFlags.Alias) !== 0;\n const target = isImportedName ? safeAliasedSymbol(checker, sym) : to ? undefined : sym;\n const declaredElsewhere = target?.declarations?.find((d) => d.getSourceFile() !== id.getSourceFile());\n const external = declaredElsewhere && otherFiles.blockInOtherFile(declaredElsewhere);\n if (external) addUsage(out, { from: from.id, to: external.id, toPath: external.path, via: importBlockId, kind, count: 1 });\n }\n if (!to || to === from.id) return;\n // Skip links between a block and its own ancestors/descendants: they're already drawn nested.\n if (from.id.startsWith(to + '/') || to.startsWith(from.id + '/')) return;\n addUsage(out, { from: from.id, to, kind, count: 1 });\n }\n}\n\n/** Finds blocks declared in other files of the project. */\nexport interface OtherFileResolver {\n /** Names declared anywhere in the project. Identifiers with other names skip the checker. */\n projectNames: Set<string>;\n blockInOtherFile(declaration: ts.Node): { path: string; id: string } | null;\n}\n\nfunction addUsage(out: Map<string, Usage>, usage: Usage) {\n const pairKey = `${usage.from}>${usage.toPath ?? ''}:${usage.to}`;\n const existing = out.get(pairKey);\n if (!existing) return void out.set(pairKey, usage);\n existing.count++;\n if (usage.kind === 'call') existing.kind = 'call';\n}\n\nfunction safeAliasedSymbol(checker: ts.TypeChecker, symbol: ts.Symbol): ts.Symbol | undefined {\n try {\n return checker.getAliasedSymbol(symbol);\n } catch {\n return undefined;\n }\n}\n\n/** Identifies a node by kind and position, the same in any tree parsed from the same text. */\nfunction nodeKey(node: ts.Node): string {\n return `${node.kind}:${node.pos}:${node.end}`;\n}\n\nfunction usageKind(id: ts.Identifier): UsageKind {\n let n: ts.Node = id;\n if (ts.isPropertyAccessExpression(n.parent) && n.parent.name === n) n = n.parent;\n const p = n.parent;\n if ((ts.isCallExpression(p) || ts.isNewExpression(p)) && p.expression === n) return 'call';\n if (ts.isTaggedTemplateExpression(p) && p.tag === n) return 'call';\n if (ts.isJsxOpeningLikeElement(p) && p.tagName === n) return 'call';\n if (ts.isBinaryExpression(p) && p.left === n && p.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && p.operatorToken.kind <= ts.SyntaxKind.LastAssignment) return 'write';\n if ((ts.isPrefixUnaryExpression(p) || ts.isPostfixUnaryExpression(p)) && (p.operator === ts.SyntaxKind.PlusPlusToken || p.operator === ts.SyntaxKind.MinusMinusToken)) return 'write';\n if (ts.isTypeReferenceNode(p) || ts.isExpressionWithTypeArguments(p) || ts.isTypeQueryNode(p) || ts.isQualifiedName(p)) return 'type';\n return 'read';\n}\n\nfunction unwrap(e: ts.Expression): ts.Expression {\n while (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e) || ts.isTypeAssertionExpression(e)) e = e.expression;\n return e;\n}\n\nfunction modifierTags(n: ts.Node): string[] {\n const mods = ts.canHaveModifiers(n) ? ts.getModifiers(n) ?? [] : [];\n return mods.map((m) => m.getText());\n}\n\nfunction squash(s: string): string {\n return s.replace(/\\s+/g, ' ').replace(/\\(\\s+/g, '(').replace(/\\s+\\)/g, ')').replace(/,\\s*\\)/g, ')').trim();\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length > n ? s.slice(0, n - 1) + '\u2026' : s;\n}\n\nfunction wrapNames(names: string[]): string[] {\n const lines: string[] = [];\n let cur = '';\n for (const n of names) {\n const piece = cur ? cur + ', ' + n : n;\n if (piece.length > 40 && cur) {\n lines.push(cur + ',');\n cur = n;\n } else cur = piece;\n }\n if (cur) lines.push(cur);\n return lines.slice(0, PREVIEW_LINES);\n}\n\n/** Faint code preview: the block's own code with nested blocks cut out, dedented and trimmed. */\n/** The text of `range` with the given nested blocks cut out: a block's own code. */\nexport function codeWithoutChildren(text: string, range: [number, number], children: Block[]): string {\n let [a, b] = range;\n let src = '';\n const kids = children.filter((c) => c.start >= a && c.end <= b).sort((x, y) => x.start - y.start);\n for (const k of kids) {\n src += text.slice(a, k.start);\n a = k.end;\n }\n return src + text.slice(a, b);\n}\n\nexport function makePreview(text: string, range: [number, number], children: Block[], max: number): { lines: string[]; more: number } {\n const src = codeWithoutChildren(text, range, children);\n const kids = children.filter((c) => c.start >= range[0] && c.end <= range[1]);\n let lines = src.split('\\n').map((l) => l.replace(/\\s+$/, ''));\n // Drop blank lines at the edges and collapse runs of blanks.\n // With nested blocks cut out, lines of leftover punctuation (`,` `{` `}`) are just noise.\n if (kids.length) lines = lines.filter((l) => !/^[\\s{}[\\](),;]*$/.test(l) || !l.trim());\n lines = lines.filter((l, i) => l.trim() || (i > 0 && lines[i - 1].trim()));\n while (lines.length && !lines[0].trim()) lines.shift();\n while (lines.length && !lines[lines.length - 1].trim()) lines.pop();\n const indents = lines.slice(lines.length > 1 && !/^\\s/.test(lines[0]) ? 1 : 0).filter((l) => l.trim()).map((l) => /^[ \\t]*/.exec(l)![0].length);\n const minIndent = indents.length ? Math.min(...indents) : 0;\n lines = lines.map((l) => (/^\\s/.test(l) ? l.slice(minIndent) : l).replace(/\\t/g, ' '));\n const more = Math.max(0, lines.length - max);\n return { lines: lines.slice(0, max).map((l) => truncate(l, PREVIEW_WIDTH)), more };\n}\n", "import ts from 'typescript';\nimport type { TextEdit } from './edits';\nimport { builderOf, parseStructure, toCodeDiagnostic, type OtherFileResolver } from './parse';\nimport type { Block, CodeDiagnostic, FileModel, IncomingUsage, Usage } from './types';\nimport { configForFile, parseConfig, workspacePackagePaths, type ConfigFile, type Workspace } from './workspace';\n\nexport type { ConfigFile, Workspace } from './workspace';\n\nexport interface ProjectOptions {\n /**\n * Standard library declaration files by file name (`lib.es2022.d.ts` \u2192 text), including every\n * file they reference. Without them only syntax errors are reported, since every built-in\n * (`Math`, `Array`, `console`) would otherwise be a type error.\n */\n libFiles?: Record<string, string>;\n /** Lib entry files to load from `libFiles`. Defaults to ES2022 + DOM. */\n lib?: string[];\n compilerOptions?: ts.CompilerOptions;\n}\n\nexport type RenameResult = { ok: true; edits: Record<string, TextEdit[]> } | { ok: false; error: string };\n\n/** Usage links and errors of one file, found when typing pauses. */\nexport interface FileResolution {\n usages: Usage[];\n /** Usages in other files that point at blocks in this file. */\n incoming: IncomingUsage[];\n diagnostics: CodeDiagnostic[];\n}\n\n/**\n * What the canvas needs from a project. `Project` does all of it in place; `RemoteProject` keeps only\n * the per-keystroke parse and does the rest in a worker, so a pause in a big file can't stall the page.\n */\nexport interface CanvasProject {\n /** Per-keystroke path: parse this file into blocks, right away. */\n setFile(path: string, text: string): FileModel;\n getModel(path: string): FileModel | undefined;\n getText(path: string): string | undefined;\n /** Leave out the type errors when the host reports its own (`CodeCanvas.setDiagnostics`). */\n resolve(path: string, options?: { diagnostics?: boolean }): Promise<FileResolution>;\n renameBlock(path: string, blockId: string, newName: string): RenameResult | Promise<RenameResult>;\n}\n\ninterface ProjectFile {\n text: string;\n version: number;\n model: FileModel;\n snapshot?: TextSnapshot;\n usages?: Usage[];\n usagesProjectVersion?: number;\n /** Module specifiers resolved to project paths, for finding the files that import this one. */\n imports?: FileImports & { fileSetVersion: number; fileVersion: number };\n}\n\nconst LIB_DIR = '/__lib__/';\nconst DEFAULT_LIB = ['lib.es2022.d.ts', 'lib.dom.d.ts'];\n/** The program of the files no config covers. */\nconst NO_CONFIG = '';\n\ninterface FileImports {\n /** Files it imports or re-exports from. */\n importedPaths: Set<string>;\n /** Files it re-exports from (`export { x } from './x'`, `export * from './x'`). */\n reExportedPaths: Set<string>;\n}\n\n/** `const x = require('./x')` in CommonJS files. */\nconst REQUIRE_CALL = /\\brequire\\s*\\(\\s*(['\"])([^'\"]+)\\1\\s*\\)/;\n\n/** `export { x } from './x'`, `export * from './x'`, `export * as x from './x'`, with or without `type`. */\nconst RE_EXPORT = /^export\\s+(?:type\\s+)?(?:\\*(?:\\s+as\\s+[\\w$]+)?|\\{[^}]*\\})\\s*from\\s*(['\"])([^'\"]+)\\1/;\n\n/** What the workspace's configs say for the current set of files. */\ninterface ConfigPrograms {\n fileSetVersion: number;\n /** Compiler options by config path (`NO_CONFIG` for files no config covers). */\n optionsByConfig: Map<string, ts.CompilerOptions>;\n /** The files of each config's program, by config path. */\n pathsByConfig: Map<string, string[]>;\n configOfPath: Map<string, string>;\n}\n\n/**\n * Every file of a folder, parsed into blocks, with TypeScript programs for resolving usages, type\n * errors and renames across files: one per config file (a monorepo has one per package), else one.\n *\n * Two speeds: `setFile` is the per-keystroke path (incremental parse of that file only); usages,\n * diagnostics and renames go through the language service and are meant to run when typing pauses.\n */\nexport class Project implements CanvasProject {\n private files = new Map<string, ProjectFile>();\n private projectVersion = 0;\n private libFiles: Record<string, string> = {};\n private hasLib = false;\n private libOptions: ts.CompilerOptions = {};\n private projectNamesCache: { version: number; names: Set<string> } | null = null;\n private workspace: Workspace | null = null;\n private configPrograms: ConfigPrograms | null = null;\n /** Language services by config path, created when a file of that config is first resolved. */\n private services = new Map<string, ts.LanguageService>();\n /** Shared by the services, so a file several programs include is parsed once. */\n private documentRegistry = ts.createDocumentRegistry(true, '/');\n /** Changes when files are added or removed, or the settings change: where imports point may change then. */\n private fileSetVersion = 0;\n\n constructor(\n files: Record<string, string> = {},\n private projectOptions: ProjectOptions = {},\n ) {\n this.configure(projectOptions);\n for (const [path, text] of Object.entries(files)) this.setFile(path, text);\n }\n\n /** Load the standard library later, e.g. once it has been downloaded. Type errors show from then on. */\n setLibFiles(libFiles: Record<string, string>) {\n this.projectOptions = { ...this.projectOptions, libFiles };\n this.reconfigure();\n }\n\n /** Use the folder's tsconfig.json (or none, with null). */\n setConfigFile(config: ConfigFile | null) {\n this.setWorkspace(config ? { configFiles: [config] } : null);\n }\n\n /** Use the folder's config files and workspace packages (or none, with null). */\n setWorkspace(workspace: Workspace | null) {\n this.workspace = workspace;\n this.reconfigure();\n }\n\n private reconfigure() {\n for (const service of this.services.values()) service.dispose();\n this.services.clear();\n this.configure(this.projectOptions);\n this.projectVersion++;\n this.fileSetVersion++;\n }\n\n private configure(options: ProjectOptions) {\n this.libFiles = options.libFiles ?? {};\n const libEntries = (options.lib ?? DEFAULT_LIB).filter((name) => name in this.libFiles);\n this.hasLib = libEntries.length > 0;\n this.libOptions = this.hasLib ? { lib: libEntries, noLib: false } : { noLib: true };\n }\n\n /** Options for a program: the defaults, then the config's, then `ProjectOptions.compilerOptions`. */\n private compilerOptions(configOptions: ts.CompilerOptions, packagePaths: Record<string, string[]>): ts.CompilerOptions {\n // The config's own aliases win over the ones that point at workspace packages.\n const paths = { ...packagePaths, ...configOptions.paths };\n return {\n target: ts.ScriptTarget.ES2022,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n strict: true,\n jsx: ts.JsxEmit.Preserve,\n skipLibCheck: true,\n allowImportingTsExtensions: true,\n ...configOptions,\n ...(Object.keys(paths).length ? { paths } : {}),\n ...this.projectOptions.compilerOptions,\n // JavaScript files are part of the project even where a tsconfig.json leaves `allowJs` off.\n allowJs: true,\n // The project loads no @types packages, its standard library is the one given here, and it never emits.\n types: [],\n noEmit: true,\n ...this.libOptions,\n };\n }\n\n /** Which config each file uses, and the options of each. Worked out again when files are added or removed. */\n private programs(): ConfigPrograms {\n if (this.configPrograms?.fileSetVersion === this.fileSetVersion) return this.configPrograms;\n const projectPaths = [...this.files.keys()];\n const packagePaths = workspacePackagePaths(this.workspace?.packageFiles ?? {}, (path) => this.files.has(path));\n const configs = (this.workspace?.configFiles ?? []).map((config) => parseConfig(config, projectPaths)).filter((config) => !!config);\n const optionsByConfig = new Map([[NO_CONFIG, this.compilerOptions({}, packagePaths)]]);\n for (const config of configs) optionsByConfig.set(config.path, this.compilerOptions(config.options, packagePaths));\n const pathsByConfig = new Map<string, string[]>();\n const configOfPath = new Map<string, string>();\n for (const path of projectPaths) {\n const configPath = configForFile(path, configs)?.path ?? NO_CONFIG;\n configOfPath.set(path, configPath);\n pathsByConfig.set(configPath, [...(pathsByConfig.get(configPath) ?? []), path]);\n }\n this.configPrograms = { fileSetVersion: this.fileSetVersion, optionsByConfig, pathsByConfig, configOfPath };\n return this.configPrograms;\n }\n\n private configOf(path: string): string {\n return this.programs().configOfPath.get(path) ?? NO_CONFIG;\n }\n\n /** The options a file's imports resolve with: its own config's, whichever program includes it. */\n private optionsOfFile(path: string | null): ts.CompilerOptions {\n const { optionsByConfig } = this.programs();\n return optionsByConfig.get(path ? this.configOf(path) : NO_CONFIG) ?? optionsByConfig.get(NO_CONFIG)!;\n }\n\n private serviceOf(path: string): ts.LanguageService {\n return this.serviceOfConfig(this.configOf(path));\n }\n\n private serviceOfConfig(configPath: string): ts.LanguageService {\n let service = this.services.get(configPath);\n if (!service) {\n service = ts.createLanguageService(this.createHost(configPath), this.documentRegistry);\n this.services.set(configPath, service);\n }\n return service;\n }\n\n // ---------------------------------------------------------------- files (fast path)\n\n /** Add or update a file. Parses only this file, incrementally from its previous version. */\n setFile(path: string, text: string): FileModel {\n const existing = this.files.get(path);\n if (existing && existing.text === text) return existing.model;\n const model = parseStructure(path, text, existing?.model);\n this.files.set(path, { text, version: (existing?.version ?? 0) + 1, model });\n this.projectVersion++;\n if (!existing) this.fileSetVersion++;\n return model;\n }\n\n removeFile(path: string) {\n if (!this.files.delete(path)) return;\n this.projectVersion++;\n this.fileSetVersion++;\n }\n\n hasFile(path: string): boolean {\n return this.files.has(path);\n }\n\n paths(): string[] {\n return [...this.files.keys()];\n }\n\n getModel(path: string): FileModel | undefined {\n return this.files.get(path)?.model;\n }\n\n getText(path: string): string | undefined {\n return this.files.get(path)?.text;\n }\n\n // ---------------------------------------------------------------- resolving (when typing pauses)\n\n resolve(path: string, { diagnostics = true }: { diagnostics?: boolean } = {}): Promise<FileResolution> {\n return Promise.resolve({ usages: this.usages(path), incoming: this.usagesInto(path), diagnostics: diagnostics ? this.diagnostics(path) : [] });\n }\n\n /** Usage links from this file: within the file, and to blocks in other files (`toPath`). */\n usages(path: string): Usage[] {\n const file = this.files.get(path);\n if (!file) return [];\n if (file.usages && file.usagesProjectVersion === this.projectVersion) return file.usages;\n const program = this.serviceOf(path).getProgram();\n const sf = program?.getSourceFile(toFileName(path));\n const builder = builderOf(file.model);\n if (!program || !sf || !builder || sf.text !== file.text) return [];\n file.usages = builder.collectUsages(sf, program.getTypeChecker(), this.otherFileResolver());\n file.usagesProjectVersion = this.projectVersion;\n return file.usages;\n }\n\n /** Usages in other files that point at blocks in this file. */\n usagesInto(path: string): IncomingUsage[] {\n const incoming: IncomingUsage[] = [];\n for (const otherPath of this.importersThroughReExports(path)) {\n for (const usage of this.usages(otherPath)) {\n if (usage.toPath === path) incoming.push({ ...usage, fromPath: otherPath });\n }\n }\n return incoming;\n }\n\n /** Syntax errors, plus type errors when the standard library is loaded and the syntax is valid. */\n diagnostics(path: string): CodeDiagnostic[] {\n const file = this.files.get(path);\n if (!file) return [];\n const hasSyntaxErrors = file.model.diagnostics.length > 0;\n if (hasSyntaxErrors || !this.hasLib) return file.model.diagnostics;\n const service = this.serviceOf(path);\n const sf = service.getProgram()?.getSourceFile(toFileName(path));\n if (!sf || sf.text !== file.text) return [];\n return service.getSemanticDiagnostics(toFileName(path)).map((d) => toCodeDiagnostic(file.model, sf, d, 'type'));\n }\n\n /**\n * Text edits that rename a block and every usage of it, in every file of the project.\n * Usages in other files are renamed too, including imports (no `as` aliases are added).\n */\n renameBlock(path: string, blockId: string, newName: string): RenameResult {\n const file = this.files.get(path);\n const block = file?.model.blocks.get(blockId);\n if (!file || !block) return { ok: false, error: 'Block not found' };\n const isRenamable = block.nameStart >= 0 && block.kind !== 'import' && block.kind !== 'statement' && block.name !== 'constructor';\n if (!isRenamable) return { ok: false, error: `${block.name} can't be renamed` };\n if (newName === block.name) return { ok: true, edits: {} };\n if (!isValidIdentifier(newName)) return { ok: false, error: `\"${newName}\" is not a valid name` };\n if (namesVisibleFrom(file.model, block).has(newName)) return { ok: false, error: `${newName} already exists here` };\n if (file.model.diagnostics.length) return { ok: false, error: `Fix the syntax error on line ${file.model.firstErrorLine} first` };\n\n const fileName = toFileName(path);\n const info = this.serviceOf(path).getRenameInfo(fileName, block.nameStart, { allowRenameOfImportPath: false });\n if (!info.canRename) return { ok: false, error: info.localizedErrorMessage };\n const edits: Record<string, TextEdit[]> = {};\n const renamedLocations = new Set<string>();\n // Each program finds the usages in its own files; in a monorepo the importers can be in other packages.\n for (const configPath of this.configsUsing(path)) {\n const service = this.serviceOfConfig(configPath);\n if (!service.getProgram()?.getSourceFile(fileName)) continue;\n // Where an alias is dropped (`export { newName as oldName }`), the names imported through it change too.\n const renameStarts = [{ fileName, position: block.nameStart }];\n const visitedStarts = new Set<string>();\n for (let start = renameStarts.pop(); start; start = renameStarts.pop()) {\n const startKey = `${start.fileName}:${start.position}`;\n if (visitedStarts.has(startKey)) continue;\n visitedStarts.add(startKey);\n const locations = service.findRenameLocations(start.fileName, start.position, false, false, { providePrefixAndSuffixTextForRename: true }) ?? [];\n for (const location of locations) {\n const locationPath = fromFileName(location.fileName);\n if (!locationPath) continue;\n if (isAliasInSpecifier(location)) renameStarts.push({ fileName: location.fileName, position: location.textSpan.start });\n const locationKey = `${location.fileName}:${location.textSpan.start}`;\n if (renamedLocations.has(locationKey)) continue;\n renamedLocations.add(locationKey);\n const text = isAliasInSpecifier(location) ? newName : (location.prefixText ?? '') + newName + (location.suffixText ?? '');\n (edits[locationPath] ??= []).push({ start: location.textSpan.start, end: location.textSpan.start + location.textSpan.length, text });\n }\n }\n }\n for (const fileEdits of Object.values(edits)) fileEdits.sort((a, b) => a.start - b.start);\n return { ok: true, edits };\n }\n\n // ---------------------------------------------------------------- internals\n\n /** The configs of a file and of the files that can use its blocks: its importers, also through re-exports. */\n private configsUsing(path: string): string[] {\n const owner = this.configOf(path);\n const importerConfigs = this.importersThroughReExports(path).map((importer) => this.configOf(importer));\n return [owner, ...new Set(importerConfigs.filter((configPath) => configPath !== owner))];\n }\n\n /** Files that import `path`, or import a file that re-exports from it (an `index.ts` of a folder or package). */\n private importersThroughReExports(path: string): string[] {\n const importers = new Set<string>();\n const reExporters = [path];\n for (let reExported = reExporters.pop(); reExported !== undefined; reExported = reExporters.pop()) {\n for (const importer of this.importersOf(reExported)) {\n if (importers.has(importer) || importer === path) continue;\n importers.add(importer);\n if (this.importsOf(importer).reExportedPaths.has(reExported)) reExporters.push(importer);\n }\n }\n return [...importers];\n }\n\n private otherFileResolver(): OtherFileResolver {\n return {\n projectNames: this.projectNames(),\n blockInOtherFile: (declaration) => {\n const sf = declaration.getSourceFile();\n const path = fromFileName(sf.fileName);\n const file = path ? this.files.get(path) : undefined;\n if (!path || !file || file.text !== sf.text) return null;\n const id = builderOf(file.model)?.blockIdForDeclaration(declaration);\n return id ? { path, id } : null;\n },\n };\n }\n\n private projectNames(): Set<string> {\n if (this.projectNamesCache?.version === this.projectVersion) return this.projectNamesCache.names;\n const names = new Set<string>();\n for (const file of this.files.values()) for (const name of builderOf(file.model)?.names ?? []) names.add(name);\n this.projectNamesCache = { version: this.projectVersion, names };\n return names;\n }\n\n /** Files whose imports resolve to `path`. */\n private importersOf(path: string): string[] {\n const importers: string[] = [];\n for (const [otherPath, file] of this.files) {\n if (otherPath !== path && this.importsOf(otherPath, file).importedPaths.has(path)) importers.push(otherPath);\n }\n return importers;\n }\n\n private importsOf(path: string, file = this.files.get(path)!): FileImports {\n if (file.imports?.fileSetVersion === this.fileSetVersion && file.imports.fileVersion === file.version) return file.imports;\n const importedPaths = new Set<string>();\n const reExportedPaths = new Set<string>();\n const host = this.moduleResolutionHost();\n const resolve = (specifier: string) => {\n const result = ts.resolveModuleName(specifier, toFileName(path), this.optionsOfFile(path), host).resolvedModule;\n return result ? fromFileName(result.resolvedFileName) : null;\n };\n for (const block of file.model.roots) {\n const code = block.kind === 'statement' || block.kind === 'variable' ? file.text.slice(block.start, block.end) : '';\n const reExportSpecifier = block.kind === 'statement' ? RE_EXPORT.exec(code)?.[2] : undefined;\n const requiredSpecifier = block.kind === 'variable' ? REQUIRE_CALL.exec(code)?.[2] : undefined;\n const specifier = block.kind === 'import' ? block.name : (reExportSpecifier ?? requiredSpecifier);\n const target = specifier ? resolve(specifier) : null;\n if (!target) continue;\n importedPaths.add(target);\n if (reExportSpecifier) reExportedPaths.add(target);\n }\n file.imports = { importedPaths, reExportedPaths, fileSetVersion: this.fileSetVersion, fileVersion: file.version };\n return file.imports;\n }\n\n private moduleResolutionHost(): ts.ModuleResolutionHost {\n return {\n fileExists: (name) => this.fileExists(name),\n readFile: (name) => this.readFile(name),\n directoryExists: (dir) => this.directoryExists(dir),\n getCurrentDirectory: () => '/',\n };\n }\n\n private fileExists(name: string): boolean {\n if (name.startsWith(LIB_DIR)) return name.slice(LIB_DIR.length) in this.libFiles;\n const path = fromFileName(name);\n return !!path && this.files.has(path);\n }\n\n private readFile(name: string): string | undefined {\n if (name.startsWith(LIB_DIR)) return this.libFiles[name.slice(LIB_DIR.length)];\n const path = fromFileName(name);\n return path ? this.files.get(path)?.text : undefined;\n }\n\n private directoryExists(dir: string): boolean {\n const prefix = dir.replace(/^\\//, '').replace(/\\/?$/, '/');\n if (prefix === '/') return true;\n for (const path of this.files.keys()) if (path.startsWith(prefix)) return true;\n return false;\n }\n\n /** The host of one config's program. Its files are those that use the config; their imports come in from the rest. */\n private createHost(configPath: string): ts.LanguageServiceHost {\n return {\n getCompilationSettings: () => this.programs().optionsByConfig.get(configPath) ?? this.programs().optionsByConfig.get(NO_CONFIG)!,\n getProjectVersion: () => String(this.projectVersion),\n getScriptFileNames: () => (this.programs().pathsByConfig.get(configPath) ?? []).map(toFileName),\n getScriptVersion: (name) => {\n if (name.startsWith(LIB_DIR)) return '0';\n const path = fromFileName(name);\n return String((path && this.files.get(path)?.version) ?? 0);\n },\n getScriptSnapshot: (name) => {\n if (name.startsWith(LIB_DIR)) {\n const text = this.libFiles[name.slice(LIB_DIR.length)];\n return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text);\n }\n const path = fromFileName(name);\n const file = path ? this.files.get(path) : undefined;\n if (!file) return undefined;\n file.snapshot ??= new TextSnapshot(file.text);\n return file.snapshot;\n },\n getCurrentDirectory: () => '/',\n // A file another package's program pulls in keeps its own package's aliases.\n resolveModuleNameLiterals: (moduleLiterals, containingFile) => {\n const containingPath = fromFileName(containingFile);\n const options = this.optionsOfFile(containingPath);\n const host = this.moduleResolutionHost();\n return moduleLiterals.map((literal) => ts.resolveModuleName(literal.text, containingFile, options, host));\n },\n getDefaultLibFileName: () => LIB_DIR + 'lib.d.ts',\n fileExists: (name) => this.fileExists(name),\n readFile: (name) => this.readFile(name),\n directoryExists: (dir) => this.directoryExists(dir),\n getDirectories: () => [],\n useCaseSensitiveFileNames: () => true,\n };\n }\n}\n\n/**\n * TypeScript keeps names stable when renaming across an import or export (`import { newName as old }`).\n * Here a rename updates every usage, so specifiers get the plain new name instead.\n */\nfunction isAliasInSpecifier(location: ts.RenameLocation): boolean {\n return /\\bas\\s*$/.test(location.prefixText ?? '') || /^\\s*as\\b/.test(location.suffixText ?? '');\n}\n\n/** Lets the language service re-parse only the changed region of a file. */\nclass TextSnapshot implements ts.IScriptSnapshot {\n constructor(readonly text: string) {}\n getText(start: number, end: number) {\n return this.text.slice(start, end);\n }\n getLength() {\n return this.text.length;\n }\n getChangeRange(old: ts.IScriptSnapshot): ts.TextChangeRange | undefined {\n if (!(old instanceof TextSnapshot)) return undefined;\n return changedRegion(old.text, this.text);\n }\n}\n\nfunction changedRegion(before: string, after: string): ts.TextChangeRange {\n let start = 0;\n const shorter = Math.min(before.length, after.length);\n while (start < shorter && before.charCodeAt(start) === after.charCodeAt(start)) start++;\n let fromEnd = 0;\n while (fromEnd < shorter - start && before.charCodeAt(before.length - 1 - fromEnd) === after.charCodeAt(after.length - 1 - fromEnd)) fromEnd++;\n return ts.createTextChangeRange(ts.createTextSpan(start, before.length - fromEnd - start), after.length - fromEnd - start);\n}\n\n/** Project paths are relative (`src/cart.ts`); TypeScript sees them as absolute (`/src/cart.ts`). */\nfunction toFileName(path: string): string {\n return '/' + path;\n}\n\nfunction fromFileName(name: string): string | null {\n if (name.startsWith(LIB_DIR) || !name.startsWith('/')) return null;\n return name.slice(1);\n}\n\n/** Names a renamed block could clash with: its siblings, and outside classes every enclosing scope. */\nfunction namesVisibleFrom(model: FileModel, block: Block): Set<string> {\n const names = new Set<string>();\n const siblings = block.parentId ? model.blocks.get(block.parentId)!.children : model.roots;\n for (const sibling of siblings) if (sibling !== block) names.add(sibling.name);\n let parent = block.parentId ? model.blocks.get(block.parentId) : undefined;\n const isClassMember = parent?.insert === 'class';\n if (isClassMember) return names;\n while (parent) {\n const parentSiblings = parent.parentId ? model.blocks.get(parent.parentId)!.children : model.roots;\n for (const scopeBlock of [...parent.children, ...parentSiblings]) if (scopeBlock !== block) names.add(scopeBlock.name);\n parent = parent.parentId ? model.blocks.get(parent.parentId) : undefined;\n }\n return names;\n}\n\nfunction isValidIdentifier(name: string): boolean {\n const scanner = ts.createScanner(ts.ScriptTarget.Latest, true, ts.LanguageVariant.Standard, name);\n const token = scanner.scan();\n const isWholeText = scanner.getTokenEnd() === name.length && name.length > 0;\n // Contextual keywords (`type`, `of`, `async`\u2026) are valid names; reserved words are not.\n const isNameToken = token === ts.SyntaxKind.Identifier || (token > ts.SyntaxKind.LastReservedWord && token <= ts.SyntaxKind.LastKeyword);\n return isWholeText && isNameToken;\n}\n\n", "import ts from 'typescript';\n\n/**\n * A TypeScript config file of the folder (`tsconfig.json`, `tsconfig.app.json`, `jsconfig.json`).\n * Path aliases, `baseUrl` and module resolution decide which file an import points at.\n */\nexport interface ConfigFile {\n /** Project path, e.g. `tsconfig.json` or `packages/web/tsconfig.app.json`. */\n path: string;\n text: string;\n /** Configs it `extends`, by project path. Only relative `extends` are followed. */\n extendedFiles?: Record<string, string>;\n}\n\n/**\n * The folder's TypeScript settings. In a monorepo every package can have its own config: a file\n * uses the nearest config above it that includes it (`files`, `include`, `exclude`), as in VS Code.\n */\nexport interface Workspace {\n configFiles: ConfigFile[];\n /**\n * `package.json` files by project path. Packages of the workspace import each other by name\n * (`@acme/utils`); without `node_modules`, the name is resolved to the package's source.\n */\n packageFiles?: Record<string, string>;\n}\n\n/** One config file, read: its options, and which of the project's files it includes. */\nexport interface ParsedConfig {\n path: string;\n /** Folder of the config, `''` at the root, else ending in `/`. */\n folder: string;\n options: ts.CompilerOptions;\n includes(projectPath: string): boolean;\n}\n\n/** Read a config file. `projectPaths` are the project's files, for its `include` and `exclude` patterns. */\nexport function parseConfig(config: ConfigFile, projectPaths: string[]): ParsedConfig | null {\n const configFileName = '/' + config.path;\n const json = ts.parseConfigFileTextToJson(configFileName, config.text);\n if (json.error || !json.config) return null;\n const readConfig = (name: string) => (name === configFileName ? config.text : config.extendedFiles?.[name.slice(1)]);\n const host: ts.ParseConfigHost = {\n useCaseSensitiveFileNames: true,\n readDirectory: (rootDir, extensions, excludes, includes) => matchingPaths(projectPaths, rootDir, extensions, excludes ?? [], includes ?? ['**/*']),\n fileExists: (name) => readConfig(name) !== undefined,\n readFile: readConfig,\n };\n const folder = config.path.slice(0, config.path.lastIndexOf('/') + 1);\n const parsed = ts.parseJsonConfigFileContent(json.config, host, '/' + folder, undefined, configFileName);\n const included = new Set(parsed.fileNames.map((name) => name.slice(1)));\n return { path: config.path, folder, options: parsed.options, includes: (projectPath) => included.has(projectPath) };\n}\n\n/**\n * The config a file uses: the nearest one above it that includes it; failing that, the nearest one\n * above it (a file left out still gets its package's aliases). Null: no config is above it.\n */\nexport function configForFile(projectPath: string, configs: ParsedConfig[]): ParsedConfig | null {\n const above = configs.filter((config) => projectPath.startsWith(config.folder));\n const nearestFirst = [...above].sort((a, b) => b.folder.length - a.folder.length);\n return nearestFirst.find((config) => config.includes(projectPath)) ?? nearestFirst[0] ?? null;\n}\n\n/**\n * Path aliases that point each workspace package's name at its source: the file its `package.json`\n * names (`types`, `exports`, `module`, `main`), its TypeScript source when that is a build output\n * (`dist/index.js` \u2192 `src/index.ts`), or `src/index.ts`.\n */\nexport function workspacePackagePaths(packageFiles: Record<string, string>, hasFile: (projectPath: string) => boolean): Record<string, string[]> {\n const paths: Record<string, string[]> = {};\n for (const [packagePath, text] of Object.entries(packageFiles)) {\n const manifest = parsePackageJson(text);\n if (!manifest?.name) continue;\n const folder = packagePath.slice(0, packagePath.lastIndexOf('/') + 1);\n const entry = packageEntries(manifest)\n .flatMap((named) => [named, ...sourceOfBuildOutput(named)])\n .concat(['src/index.ts', 'src/index.tsx', 'index.ts', 'index.tsx'])\n .map((relative) => folder + relative.replace(/^\\.\\//, ''))\n .find(hasFile);\n if (entry) paths[manifest.name] = ['/' + entry];\n paths[manifest.name + '/*'] = ['/' + folder + 'src/*', '/' + folder + '*'];\n }\n return paths;\n}\n\ninterface PackageJson {\n name?: string;\n types?: string;\n typings?: string;\n module?: string;\n main?: string;\n exports?: unknown;\n}\n\nfunction parsePackageJson(text: string): PackageJson | null {\n try {\n const value: unknown = JSON.parse(text);\n return value && typeof value === 'object' ? (value as PackageJson) : null;\n } catch {\n return null;\n }\n}\n\n/** The files a package.json points at, most specific first. */\nfunction packageEntries(manifest: PackageJson): string[] {\n const rootExport = manifest.exports && typeof manifest.exports === 'object' && '.' in manifest.exports ? (manifest.exports as Record<string, unknown>)['.'] : manifest.exports;\n return [manifest.types, manifest.typings, ...exportTargets(rootExport), manifest.module, manifest.main].filter((entry): entry is string => typeof entry === 'string');\n}\n\n/** `\"./dist/index.js\"`, or the targets of conditions (`types`, `import`, `default`\u2026), in their order. */\nfunction exportTargets(target: unknown): string[] {\n if (typeof target === 'string') return [target];\n if (Array.isArray(target)) return target.flatMap(exportTargets);\n if (target && typeof target === 'object') return Object.values(target).flatMap(exportTargets);\n return [];\n}\n\n/** `dist/index.js` \u2192 `src/index.ts`, `src/index.tsx`, `dist/index.ts`\u2026 (built files aren't in the project). */\nfunction sourceOfBuildOutput(entry: string): string[] {\n const isBuildOutput = /\\.(d\\.ts|d\\.mts|js|mjs|cjs|jsx)$/.test(entry);\n if (!isBuildOutput) return [];\n const withoutExtension = entry.replace(/\\.(d\\.ts|d\\.mts|js|mjs|cjs|jsx)$/, '');\n const inSourceFolder = withoutExtension.replace(/(^|\\/)(dist|lib|build|out|esm|cjs)\\//, '$1src/');\n return [inSourceFolder, withoutExtension].flatMap((base) => [base + '.ts', base + '.tsx']);\n}\n\n/** Project files under `rootDir` with one of `extensions`, matching an include pattern and no exclude pattern. */\nfunction matchingPaths(projectPaths: string[], rootDir: string, extensions: readonly string[], excludes: readonly string[], includes: readonly string[]): string[] {\n const base = rootDir.replace(/^\\//, '').replace(/\\/?$/, '/').replace(/^\\/$/, '');\n const includePatterns = includes.map((spec) => configPattern(base, spec, 'files'));\n const excludePatterns = excludes.map((spec) => configPattern(base, spec, 'filesAndFolders'));\n return projectPaths\n .filter((path) => path.startsWith(base) && extensions.some((extension) => path.endsWith(extension)))\n .filter((path) => includePatterns.some((pattern) => pattern.test(path)) && !excludePatterns.some((pattern) => pattern.test(path)))\n .map((path) => '/' + path);\n}\n\n/**\n * A tsconfig `include`/`exclude` pattern as a regular expression over project paths: `*` and `?`\n * within a folder, `**` for any folders; a pattern without wildcards in its last part is a folder.\n */\nfunction configPattern(base: string, spec: string, matching: 'files' | 'filesAndFolders'): RegExp {\n const absolute = spec.startsWith('/') ? spec.slice(1) : normalizePath(base + spec.replace(/^\\.\\//, ''));\n const lastPart = absolute.slice(absolute.lastIndexOf('/') + 1);\n const isFolder = !/[*?]/.test(lastPart) && !/\\.[^.]+$/.test(lastPart);\n const pattern = isFolder ? absolute.replace(/\\/?$/, '/**/*') : absolute;\n let source = '';\n for (let index = 0; index < pattern.length; index++) {\n const char = pattern[index];\n if (pattern.startsWith('**/', index)) {\n source += '(?:[^/]+/)*';\n index += 2;\n } else if (char === '*') source += '[^/]*';\n else if (char === '?') source += '[^/]';\n else source += char.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&');\n }\n return new RegExp(`^${source}${matching === 'filesAndFolders' ? '(?:/.*)?' : ''}$`);\n}\n\n/** `a/./b/../c` \u2192 `a/c` */\nfunction normalizePath(path: string): string {\n const parts: string[] = [];\n for (const part of path.split('/')) {\n if (part === '..') parts.pop();\n else if (part !== '.' && part !== '') parts.push(part);\n }\n return parts.join('/');\n}\n", "import { parseStructure } from './parse';\nimport type { CanvasProject, ConfigFile, FileResolution, RenameResult, Workspace } from './project';\nimport type { ProjectServerMethod } from './projectServer';\nimport type { FileModel } from './types';\n\n/** Sends one call to the `ProjectServer` (in a worker) and resolves with its result. Calls arrive in order. */\nexport type ProjectServerCall = (method: ProjectServerMethod, args: unknown[]) => Promise<unknown>;\n\ninterface RemoteFile {\n text: string;\n /** Blocks of `text`, or of an older text while nothing asked for this file since it changed. */\n model?: FileModel;\n}\n\n/**\n * The canvas's project when the TypeScript work runs in a worker. The main thread only parses files\n * into blocks (the per-keystroke path, and lazily for files no canvas shows); usage links, errors and\n * renames are computed by a `ProjectServer` in the worker.\n */\nexport class RemoteProject implements CanvasProject {\n private files = new Map<string, RemoteFile>();\n\n constructor(private callServer: ProjectServerCall) {}\n\n /** Load many files at once. They're parsed in the worker; here only when a canvas needs them. */\n setFiles(files: Record<string, string>) {\n for (const [path, text] of Object.entries(files)) this.files.set(path, { text });\n void this.callServer('setFiles', [files]);\n }\n\n setFile(path: string, text: string): FileModel {\n this.setFileText(path, text);\n return this.getModel(path)!;\n }\n\n /** Update a file no canvas shows (e.g. typed in a text editor): no parse on this thread. */\n setFileText(path: string, text: string) {\n const existing = this.files.get(path);\n if (existing?.text === text) return;\n this.files.set(path, { text, model: existing?.model });\n void this.callServer('setFile', [path, text]);\n }\n\n removeFile(path: string) {\n if (!this.files.delete(path)) return;\n void this.callServer('removeFile', [path]);\n }\n\n setLibFiles(libFiles: Record<string, string>) {\n void this.callServer('setLibFiles', [libFiles]);\n }\n\n /** The folder's tsconfig.json (or none, with null). */\n setConfigFile(config: ConfigFile | null) {\n void this.callServer('setConfigFile', [config]);\n }\n\n /** The folder's config files (one per package in a monorepo) and package.json files (or none, with null). */\n setWorkspace(workspace: Workspace | null) {\n void this.callServer('setWorkspace', [workspace]);\n }\n\n getModel(path: string): FileModel | undefined {\n const file = this.files.get(path);\n if (!file) return undefined;\n const isModelOfCurrentText = file.model?.text === file.text;\n if (!isModelOfCurrentText) file.model = parseStructure(path, file.text, file.model);\n return file.model;\n }\n\n getText(path: string): string | undefined {\n return this.files.get(path)?.text;\n }\n\n paths(): string[] {\n return [...this.files.keys()];\n }\n\n resolve(path: string, options?: { diagnostics?: boolean }): Promise<FileResolution> {\n return this.callServer('resolve', [path, options]) as Promise<FileResolution>;\n }\n\n renameBlock(path: string, blockId: string, newName: string): Promise<RenameResult> {\n return this.callServer('renameBlock', [path, blockId, newName]) as Promise<RenameResult>;\n }\n}\n", "import { Project, type ConfigFile, type FileResolution, type RenameResult, type Workspace } from './project';\n\n/** Methods a `RemoteProject` can call. Arguments and results are plain data, so any message channel carries them. */\nconst SERVER_METHODS = ['setLibFiles', 'setConfigFile', 'setWorkspace', 'setFiles', 'setFile', 'removeFile', 'resolve', 'renameBlock'] as const;\nexport type ProjectServerMethod = (typeof SERVER_METHODS)[number];\n\n/** A `Project` behind plain-data methods: the worker side of a `RemoteProject`. */\nexport class ProjectServer {\n private project = new Project();\n\n setLibFiles(libFiles: Record<string, string>) {\n this.project.setLibFiles(libFiles);\n }\n\n setConfigFile(config: ConfigFile | null) {\n this.project.setConfigFile(config);\n }\n\n setWorkspace(workspace: Workspace | null) {\n this.project.setWorkspace(workspace);\n }\n\n setFiles(files: Record<string, string>) {\n for (const [path, text] of Object.entries(files)) this.project.setFile(path, text);\n }\n\n setFile(path: string, text: string) {\n this.project.setFile(path, text);\n }\n\n removeFile(path: string) {\n this.project.removeFile(path);\n }\n\n resolve(path: string, options?: { diagnostics?: boolean }): Promise<FileResolution> {\n return this.project.resolve(path, options);\n }\n\n renameBlock(path: string, blockId: string, newName: string): RenameResult {\n return this.project.renameBlock(path, blockId, newName);\n }\n}\n\nexport function callProjectServer(server: ProjectServer, method: string, args: unknown[]): unknown {\n const isServerMethod = (SERVER_METHODS as readonly string[]).includes(method);\n if (!isServerMethod) throw new Error(`Unknown project method: ${method}`);\n return (server[method as ProjectServerMethod] as (...args: unknown[]) => unknown)(...args);\n}\n", "import { callProjectServer, ProjectServer } from './projectServer';\nimport { RemoteProject } from './remoteProject';\n\n/** The part of a `Worker`, the worker's `self`, or a `MessagePort` that the project calls use. */\nexport interface MessagePortLike {\n postMessage(message: unknown): void;\n addEventListener(type: 'message', listener: (event: { data: unknown }) => void): void;\n /** MessagePorts only deliver messages after `start()`. */\n start?(): void;\n}\n\ninterface ProjectRequest {\n id: number;\n method: string;\n args: unknown[];\n}\n\ntype ProjectReply = { id: number; result: unknown } | { id: number; error: string };\n\n/** In a worker script: answer the `RemoteProject` on the other side of `port` (usually `self`). */\nexport function serveProject(port: MessagePortLike) {\n const server = new ProjectServer();\n port.addEventListener('message', async (event) => {\n const { id, method, args } = event.data as ProjectRequest;\n try {\n port.postMessage({ id, result: await callProjectServer(server, method, args) } satisfies ProjectReply);\n } catch (error) {\n port.postMessage({ id, error: error instanceof Error ? error.message : String(error) } satisfies ProjectReply);\n }\n });\n port.start?.();\n}\n\n/** On the main thread: a project whose TypeScript work runs in the worker behind `port`. */\nexport function connectProjectWorker(port: MessagePortLike): RemoteProject {\n let nextId = 0;\n const waiting = new Map<number, { resolve(result: unknown): void; reject(error: Error): void }>();\n port.addEventListener('message', (event) => {\n const reply = event.data as ProjectReply;\n const caller = waiting.get(reply.id);\n waiting.delete(reply.id);\n if ('error' in reply) caller?.reject(new Error(reply.error));\n else caller?.resolve(reply.result);\n });\n port.start?.();\n return new RemoteProject((method, args) => {\n const id = nextId++;\n port.postMessage({ id, method, args } satisfies ProjectRequest);\n return new Promise((resolve, reject) => waiting.set(id, { resolve, reject }));\n });\n}\n", "import ts from 'typescript';\nimport type { Block, FileModel } from './types';\n\n/** A single text replacement. */\nexport interface TextEdit {\n start: number;\n end: number;\n text: string;\n}\n\nexport function applyEdit(text: string, e: TextEdit): string {\n return text.slice(0, e.start) + e.text + text.slice(e.end);\n}\n\n/** Apply edits that don't overlap, given as offsets into the original text. */\nexport function applyEdits(text: string, edits: TextEdit[]): string {\n const lastFirst = [...edits].sort((a, b) => b.start - a.start);\n return lastFirst.reduce(applyEdit, text);\n}\n\n/** Result of a structural edit: the text change plus the id the new block will have. */\nexport interface InsertResult {\n edit: TextEdit;\n id: string;\n /** Selection to put in the editor, relative to the new block's start. */\n select: [number, number];\n}\n\nexport function replaceBlock(model: FileModel, id: string, code: string): TextEdit {\n const b = must(model, id);\n return { start: b.start, end: b.end, text: code };\n}\n\n/** Remove a block and the blank space it leaves behind. */\nexport function deleteBlock(model: FileModel, id: string): TextEdit {\n const b = must(model, id);\n const t = model.text;\n let start = t.lastIndexOf('\\n', b.start - 1) + 1; // include indentation\n if (/\\S/.test(t.slice(start, b.start))) start = b.start; // something else shares the line\n let end = b.end;\n const trail = /^[ \\t]*;?[ \\t]*(\\r?\\n)?/.exec(t.slice(end))!;\n end += trail[0].length;\n // Collapse surrounding blank lines to at most one.\n const before = /(\\r?\\n[ \\t]*)*$/.exec(t.slice(0, start))![0];\n const after = /^([ \\t]*\\r?\\n)*/.exec(t.slice(end))![0];\n const blankBefore = (before.match(/\\n/g) ?? []).length;\n const blankAfter = (after.match(/\\n/g) ?? []).length;\n if (blankBefore >= 2 && blankAfter >= 1) end += after.length;\n else if (start === 0 && blankAfter) end += after.length;\n return { start, end, text: '' };\n}\n\n/** Pick a name that isn't taken in the block's scope. */\nexport function uniqueName(model: FileModel, parentId: string | null, base: string): string {\n const taken = new Set<string>();\n const sibs = parentId ? must(model, parentId).children : model.roots;\n for (const s of sibs) taken.add(s.name);\n // Names in the file scope are visible everywhere, so avoid those too.\n for (const r of model.roots) taken.add(r.name);\n if (!taken.has(base)) return base;\n let n = 2;\n while (taken.has(base + n)) n++;\n return base + n;\n}\n\n/** Where nested code can go: the block itself if it can hold code, else its nearest container. */\nexport function containerFor(model: FileModel, id: string | null): Block | null {\n let b = id ? model.blocks.get(id) ?? null : null;\n while (b && !b.insert) b = b.parentId ? model.blocks.get(b.parentId) ?? null : null;\n return b;\n}\n\nexport function newFunction(model: FileModel, parentId: string | null, base = 'newFunction'): InsertResult {\n const parent = containerFor(model, parentId);\n const name = uniqueName(model, parent?.id ?? null, base);\n const u = model.indentUnit;\n const code = parent?.insert === 'class' ? `${name}() {\\n${u}\\n}` : `function ${name}() {\\n${u}\\n}`;\n const nameAt = code.indexOf(name);\n return insertCode(model, parent, code, name, [nameAt, nameAt + name.length]);\n}\n\n/** What the clipboard holds after copying a block. */\nexport interface BlockClip {\n code: string;\n name: string;\n kind: Block['kind'];\n /** Copied from inside a class (method/property syntax). */\n fromClass: boolean;\n}\n\nexport function copyBlock(model: FileModel, id: string): BlockClip {\n const b = must(model, id);\n const parent = b.parentId ? model.blocks.get(b.parentId) : null;\n return {\n code: dedent(model.text.slice(b.start, b.end), b.indent),\n name: b.name,\n kind: b.kind,\n fromClass: parent?.insert === 'class',\n };\n}\n\n/** Paste a copied block into `parentId` (or the file), converting method \u2194 function syntax as needed. */\nexport function pasteBlock(model: FileModel, parentId: string | null, clip: BlockClip): InsertResult {\n const parent = containerFor(model, parentId);\n const toClass = parent?.insert === 'class';\n let code = clip.code;\n if (toClass && !clip.fromClass) code = toMember(code);\n if (!toClass && clip.fromClass) code = toTopLevel(code);\n if (!clip.name) {\n // Not a declaration (plain statements): insert as-is; it becomes a statement block.\n const r = insertCode(model, parent, code, '', [0, 0]);\n return { ...r, id: '' };\n }\n const name = uniqueName(model, parent?.id ?? null, clip.name);\n if (name !== clip.name) code = renameDeclaration(code, toClass, name);\n return insertCode(model, parent, code, name, [0, 0]);\n}\n\nfunction insertCode(model: FileModel, parent: Block | null, code: string, name: string, select: [number, number]): InsertResult {\n const t = model.text;\n const key = name; // the parser keys declarations by name\n const id = parent ? `${parent.id}/${key}` : key;\n if (!parent) {\n const end = t.trimEnd().length;\n const sep = end === 0 ? '' : '\\n\\n';\n return { edit: { start: end, end: t.length, text: sep + code + '\\n' }, id, select };\n }\n const indent = parent.indent + model.indentUnit;\n const body = reindent(code, indent);\n const at = parent.insertAt;\n const lineStart = t.lastIndexOf('\\n', at - 1) + 1;\n if (!/\\S/.test(t.slice(lineStart, at))) {\n // Closing brace (or the trailing return) is on its own line: insert above it.\n const prevLineEnd = lineStart - 1;\n const prevLineStart = t.lastIndexOf('\\n', prevLineEnd - 1) + 1;\n const prevLine = t.slice(prevLineStart, prevLineEnd);\n const opener = /\\{\\s*$/.test(prevLine);\n const lead = opener || !/\\S/.test(prevLine) ? '' : '\\n';\n const trail = t[at] === '}' ? '' : '\\n';\n return { edit: { start: lineStart, end: lineStart, text: lead + indent + body + '\\n' + trail }, id, select };\n }\n // Brace on the same line, e.g. `class A {}`.\n return { edit: { start: at, end: at, text: '\\n' + indent + body + '\\n' + parent.indent }, id, select };\n}\n\nfunction reindent(code: string, indent: string): string {\n return code\n .split('\\n')\n .map((l, i) => (i === 0 || l === '' ? l : indent + l))\n .join('\\n');\n}\n\nfunction dedent(code: string, indent: string): string {\n if (!indent) return code;\n return code\n .split('\\n')\n .map((l, i) => (i > 0 && l.startsWith(indent) ? l.slice(indent.length) : l))\n .join('\\n');\n}\n\n/** `export async function f()` \u2192 `async f()`; `const x = 1;` \u2192 `x = 1;` */\nfunction toMember(code: string): string {\n const fn = /^((?:\\/\\*[\\s\\S]*?\\*\\/|\\/\\/[^\\n]*|\\s)*)(?:export\\s+)?(?:default\\s+)?(async\\s+)?function\\s*(\\*?)\\s*/.exec(code);\n if (fn) return fn[1] + (fn[2] ?? '') + fn[3] + code.slice(fn[0].length);\n const v = /^((?:\\/\\*[\\s\\S]*?\\*\\/|\\/\\/[^\\n]*|\\s)*)(?:export\\s+)?(?:const|let|var)\\s+/.exec(code);\n if (v) return v[1] + code.slice(v[0].length);\n return code;\n}\n\n/** `private static async f()` \u2192 `async function f()`; `x = 1;` \u2192 `const x = 1;` */\nfunction toTopLevel(code: string): string {\n const m = /^((?:\\/\\*[\\s\\S]*?\\*\\/|\\/\\/[^\\n]*|\\s)*)((?:(?:public|private|protected|static|readonly|override|abstract)\\s+)*)(async\\s+)?(\\*?)\\s*([A-Za-z_$][\\w$]*)\\s*(<|\\()/.exec(code);\n if (m) return `${m[1]}${m[3] ?? ''}function${m[4] ? '*' : ''} ${m[5]}${m[6]}` + code.slice(m[0].length);\n const p = /^((?:\\/\\*[\\s\\S]*?\\*\\/|\\/\\/[^\\n]*|\\s)*)((?:(?:public|private|protected|static|readonly|override)\\s+)*)([A-Za-z_$][\\w$]*)(\\s*[:=])/.exec(code);\n if (p) return `${p[1]}const ${p[3]}${p[4]}` + code.slice(p[0].length);\n return code;\n}\n\n/** Rename the declared name of a snippet, found by parsing it. */\nfunction renameDeclaration(code: string, inClass: boolean, name: string): string {\n const prefix = inClass ? 'class __cc__ {\\n' : '';\n const src = prefix + code + (inClass ? '\\n}' : '');\n const sf = ts.createSourceFile('snippet.ts', src, ts.ScriptTarget.Latest, true);\n let target: ts.Node | undefined;\n const first = sf.statements[0];\n if (inClass && first && ts.isClassDeclaration(first)) target = first.members[0]?.name;\n else if (first && (ts.isFunctionDeclaration(first) || ts.isClassDeclaration(first) || ts.isInterfaceDeclaration(first) || ts.isTypeAliasDeclaration(first) || ts.isEnumDeclaration(first)))\n target = first.name;\n else if (first && ts.isVariableStatement(first)) target = first.declarationList.declarations[0]?.name;\n if (!target) return code;\n const s = target.getStart(sf) - prefix.length;\n return code.slice(0, s) + name + code.slice(target.end - prefix.length);\n}\n\nfunction must(model: FileModel, id: string): Block {\n const b = model.blocks.get(id);\n if (!b) throw new Error(`No block ${id}`);\n return b;\n}\n\n/** Turn plain clipboard text (e.g. copied from another app) into a block clip. */\nexport function clipFromText(code: string): BlockClip {\n const text = code.replace(/\\s+$/, '');\n const sf = ts.createSourceFile('clip.ts', text, ts.ScriptTarget.Latest, true);\n const first = sf.statements[0];\n const diags = (sf as unknown as { parseDiagnostics: unknown[] }).parseDiagnostics ?? [];\n if (first && !diags.length) {\n let name: string | undefined;\n let kind: Block['kind'] = 'statement';\n if (ts.isFunctionDeclaration(first)) (name = first.name?.text), (kind = 'function');\n else if (ts.isClassDeclaration(first)) (name = first.name?.text), (kind = 'class');\n else if (ts.isVariableStatement(first)) (name = first.declarationList.declarations[0]?.name.getText()), (kind = 'variable');\n else if (ts.isInterfaceDeclaration(first) || ts.isTypeAliasDeclaration(first) || ts.isEnumDeclaration(first)) (name = first.name.text), (kind = 'type');\n if (name) return { code: text, name, kind, fromClass: false };\n }\n const wrapped = ts.createSourceFile('clip.ts', `class __cc__ {\\n${text}\\n}`, ts.ScriptTarget.Latest, true);\n const cls = wrapped.statements[0];\n const wd = (wrapped as unknown as { parseDiagnostics: unknown[] }).parseDiagnostics ?? [];\n if (cls && ts.isClassDeclaration(cls) && !wd.length && cls.members[0]?.name) {\n const m = cls.members[0];\n return { code: text, name: m.name!.getText(wrapped), kind: ts.isPropertyDeclaration(m) ? 'variable' : 'function', fromClass: true };\n }\n return { code: text, name: '', kind: 'statement', fromClass: false };\n}\n", "import { codeWithoutChildren } from './parse';\nimport type { Block, FileModel } from './types';\n\n/**\n * How a block compares with the base version of its file (e.g. the last commit).\n * - `containsChanges`: its own code is the same, but nested blocks changed.\n */\nexport type BlockChange = 'added' | 'changed' | 'containsChanges' | 'unchanged';\n\nexport interface DiffLine {\n kind: 'same' | 'added' | 'removed';\n text: string;\n}\n\nexport interface FileDiff {\n base: FileModel;\n /** The change of every block of the current version. */\n changes: Map<string, BlockChange>;\n /** Blocks of the base that are gone (only the outermost one of a removed subtree). */\n removed: Block[];\n}\n\n/** Compare two versions of a file block by block. Blocks are matched by id, so a renamed block is removed + added. */\nexport function diffModels(base: FileModel, current: FileModel): FileDiff {\n const changes = new Map<string, BlockChange>();\n for (const [id, block] of current.blocks) {\n const baseBlock = base.blocks.get(id);\n if (!baseBlock) changes.set(id, 'added');\n else if (sameCode(fullCode(base, baseBlock), fullCode(current, block))) changes.set(id, 'unchanged');\n else if (sameCode(ownCode(base, baseBlock), ownCode(current, block))) changes.set(id, 'containsChanges');\n else changes.set(id, 'changed');\n }\n const removed = [...base.blocks.values()].filter((block) => {\n const isGone = !current.blocks.has(block.id);\n const isParentGone = !!block.parentId && !current.blocks.has(block.parentId);\n return isGone && !isParentGone;\n });\n return { base, changes, removed };\n}\n\n/** Line diff of a block's own code (nested blocks left out) between the base and now. */\nexport function diffOwnCode(base: FileModel, baseBlock: Block | undefined, current: FileModel, block: Block): DiffLine[] {\n const before = baseBlock ? codeLines(ownCode(base, baseBlock)) : [];\n return diffLines(before, codeLines(ownCode(current, block)));\n}\n\n/** Shortest edit script between two lists of lines (longest common subsequence). */\nexport function diffLines(before: string[], after: string[]): DiffLine[] {\n let prefix = 0;\n while (prefix < before.length && prefix < after.length && before[prefix] === after[prefix]) prefix++;\n let suffix = 0;\n while (suffix < before.length - prefix && suffix < after.length - prefix && before[before.length - 1 - suffix] === after[after.length - 1 - suffix]) suffix++;\n const oldMiddle = before.slice(prefix, before.length - suffix);\n const newMiddle = after.slice(prefix, after.length - suffix);\n // common[i][j]: length of the longest common subsequence of oldMiddle[i..] and newMiddle[j..]\n const common = Array.from({ length: oldMiddle.length + 1 }, () => new Uint32Array(newMiddle.length + 1));\n for (let i = oldMiddle.length - 1; i >= 0; i--) {\n for (let j = newMiddle.length - 1; j >= 0; j--) {\n common[i][j] = oldMiddle[i] === newMiddle[j] ? common[i + 1][j + 1] + 1 : Math.max(common[i + 1][j], common[i][j + 1]);\n }\n }\n const middle: DiffLine[] = [];\n let i = 0;\n let j = 0;\n while (i < oldMiddle.length || j < newMiddle.length) {\n if (i < oldMiddle.length && j < newMiddle.length && oldMiddle[i] === newMiddle[j]) {\n middle.push({ kind: 'same', text: newMiddle[j] });\n i++;\n j++;\n } else if (i < oldMiddle.length && (j === newMiddle.length || common[i + 1][j] >= common[i][j + 1])) {\n // Removed lines come before the lines that replace them, as in any diff.\n middle.push({ kind: 'removed', text: oldMiddle[i++] });\n } else {\n middle.push({ kind: 'added', text: newMiddle[j++] });\n }\n }\n const same = (text: string): DiffLine => ({ kind: 'same', text });\n return [...before.slice(0, prefix).map(same), ...middle, ...after.slice(after.length - suffix).map(same)];\n}\n\n/** The changed lines, with one line of context around each change if there's room, to fit in `max` lines. */\nexport function diffPreview(lines: DiffLine[], max: number): { lines: DiffLine[]; more: number } {\n const isNearChange = (index: number) => [index - 1, index, index + 1].some((near) => lines[near] && lines[near].kind !== 'same');\n const changesWithContext = lines.filter((_, index) => isNearChange(index));\n const shown = changesWithContext.length <= max ? changesWithContext : lines.filter((line) => line.kind !== 'same');\n return { lines: shown.slice(0, max), more: Math.max(0, shown.length - max) };\n}\n\n/** Blank lines and trailing spaces don't count as changes (removing a nested block leaves some behind). */\nfunction sameCode(before: string, after: string): boolean {\n return codeLines(before).join('\\n') === codeLines(after).join('\\n');\n}\n\nfunction fullCode(model: FileModel, block: Block): string {\n return model.text.slice(block.start, block.end);\n}\n\nfunction ownCode(model: FileModel, block: Block): string {\n return codeWithoutChildren(model.text, [block.start, block.end], block.children);\n}\n\n/** Lines without trailing spaces or blank lines, dedented. */\nfunction codeLines(code: string): string[] {\n const lines = code.split('\\n').map((line) => line.replace(/\\s+$/, '').replace(/\\t/g, ' ')).filter((line) => line);\n const indents = lines.slice(1).filter((line) => line).map((line) => /^ */.exec(line)![0].length);\n const commonIndent = indents.length ? Math.min(...indents) : 0;\n return lines.map((line, index) => (index === 0 ? line.trimStart() : line.slice(Math.min(commonIndent, /^ */.exec(line)![0].length))));\n}\n", "import type { TextEdit } from './edits';\n\n/** Where one side of a conflict is in the file: its code, without the marker lines. */\nexport interface ConflictSide {\n start: number;\n end: number;\n}\n\n/**\n * A merge conflict as git writes it into the file:\n * `<<<<<<< current` \u2026 (`||||||| base` \u2026) `=======` \u2026 `>>>>>>> incoming`.\n */\nexport interface ConflictHunk {\n /** The whole section, marker lines included (up to and including the last marker's line break). */\n start: number;\n end: number;\n current: ConflictSide;\n incoming: ConflictSide;\n /** Only with `merge.conflictStyle = diff3` (or zdiff3). */\n base?: ConflictSide;\n /** What git wrote after the markers, e.g. `HEAD` and the branch name. */\n currentLabel: string;\n incomingLabel: string;\n}\n\nexport type ConflictChoice = 'current' | 'incoming' | 'both';\n\n/** One side of a conflicted file: each conflict replaced by that side's code. */\nexport interface ConflictSideText {\n text: string;\n /** Where each conflict's code is in `text`, in the order of the hunks. */\n hunkRanges: ConflictSide[];\n /** The file offset of an offset in `text`. */\n toFileOffset(offset: number): number;\n}\n\nconst CURRENT_MARKER = /^<{7}(?: (.*))?\\r?$/;\nconst BASE_MARKER = /^\\|{7}(?: .*)?\\r?$/;\nconst SEPARATOR = /^={7}\\r?$/;\nconst INCOMING_MARKER = /^>{7}(?: (.*))?\\r?$/;\n\n/** The merge conflicts in a file. Unfinished marker sections are left alone. */\nexport function findConflicts(text: string): ConflictHunk[] {\n const hunks: ConflictHunk[] = [];\n let open: { start: number; currentLabel: string; currentStart: number; currentEnd?: number; baseStart?: number; baseEnd?: number; incomingStart?: number } | null = null;\n let lineStart = 0;\n while (lineStart < text.length) {\n const newline = text.indexOf('\\n', lineStart);\n const lineEnd = newline === -1 ? text.length : newline;\n const nextLineStart = newline === -1 ? text.length : newline + 1;\n const line = text.slice(lineStart, lineEnd);\n const currentMarker = CURRENT_MARKER.exec(line);\n if (currentMarker) {\n // A new section starts; one left open before it wasn't a conflict.\n open = { start: lineStart, currentLabel: currentMarker[1] ?? '', currentStart: nextLineStart };\n } else if (open && BASE_MARKER.test(line) && open.currentEnd === undefined) {\n open.currentEnd = lineStart;\n open.baseStart = nextLineStart;\n } else if (open && SEPARATOR.test(line) && open.incomingStart === undefined) {\n if (open.baseStart !== undefined) open.baseEnd = lineStart;\n else open.currentEnd = lineStart;\n open.incomingStart = nextLineStart;\n } else if (open && open.incomingStart !== undefined) {\n const incomingMarker = INCOMING_MARKER.exec(line);\n if (incomingMarker) {\n hunks.push({\n start: open.start,\n end: nextLineStart,\n current: { start: open.currentStart, end: open.currentEnd! },\n incoming: { start: open.incomingStart, end: lineStart },\n base: open.baseStart !== undefined ? { start: open.baseStart, end: open.baseEnd! } : undefined,\n currentLabel: open.currentLabel,\n incomingLabel: incomingMarker[1] ?? '',\n });\n open = null;\n }\n }\n lineStart = nextLineStart;\n }\n return hunks;\n}\n\n/** The file with every conflict replaced by one side's code. */\nexport function conflictSideText(text: string, hunks: ConflictHunk[], side: 'current' | 'incoming'): ConflictSideText {\n // Pieces of the file copied into the side text: [sideStart, fileStart, length]\n const pieces: [number, number, number][] = [];\n const hunkRanges: ConflictSide[] = [];\n let sideText = '';\n let fileOffset = 0;\n const copy = (start: number, end: number) => {\n pieces.push([sideText.length, start, end - start]);\n sideText += text.slice(start, end);\n };\n for (const hunk of hunks) {\n copy(fileOffset, hunk.start);\n const code = hunk[side];\n const rangeStart = sideText.length;\n copy(code.start, code.end);\n hunkRanges.push({ start: rangeStart, end: sideText.length });\n fileOffset = hunk.end;\n }\n copy(fileOffset, text.length);\n return {\n text: sideText,\n hunkRanges,\n toFileOffset(offset: number) {\n const piece = pieces.findLast(([sideStart]) => sideStart <= offset) ?? pieces[0];\n return piece[1] + Math.min(offset - piece[0], piece[2]);\n },\n };\n}\n\n/** The edit that resolves one conflict: its whole section becomes the chosen code. */\nexport function resolveConflict(text: string, hunk: ConflictHunk, choice: ConflictChoice): TextEdit {\n const code = (side: ConflictSide) => text.slice(side.start, side.end);\n const resolved = choice === 'both' ? code(hunk.current) + code(hunk.incoming) : code(hunk[choice]);\n return { start: hunk.start, end: hunk.end, text: resolved };\n}\n", "import type { Block } from './types';\n\n/**\n * How the canvas arranges a group of sibling blocks (a file, or a class's members) the first time,\n * to make the file easy to read. The arranger (arrange.ts) applies these rules; they only decide.\n *\n * Three kinds of rules:\n * - zones: where a block goes (the left column, or a band from top to bottom)\n * - stacks: blocks that always go together, one above the other\n * - relatedness: which blocks end up next to each other\n * Plus one shape the arranger always applies, the newspaper: a function on the left, the functions it\n * calls in a column to its right, in the order it calls them.\n * Placement rules then decide where a block goes that appears later, without moving the others.\n */\n\nexport type Zone = 'left' | 'data' | 'types' | 'main' | 'bottom';\n\n/** The bands from top to bottom. The left column holds `left` blocks next to all of them. */\nexport const BAND_ORDER: Zone[] = ['data', 'types', 'main', 'bottom'];\n\nexport interface ZoneRule {\n zone: Zone;\n description: string;\n matches(block: Block): boolean;\n}\n\n/** First match wins. */\nexport const ZONE_RULES: ZoneRule[] = [\n { zone: 'left', description: 'Imports on the left', matches: (block) => block.kind === 'import' },\n { zone: 'data', description: 'Constants and other data at the top', matches: (block) => block.kind === 'variable' },\n { zone: 'types', description: 'Then interfaces, types and enums', matches: (block) => block.kind === 'type' },\n { zone: 'bottom', description: 'Code that runs when the file loads, at the bottom', matches: (block) => block.kind === 'statement' },\n { zone: 'main', description: 'Functions, classes and the rest in between', matches: () => true },\n];\n\nexport interface StackRule {\n description: string;\n /** Pairs to stack: the first block on top, the second right below it. */\n pairs(blocks: Block[]): [Block, Block][];\n}\n\nexport const STACK_RULES: StackRule[] = [\n {\n description: 'A getter above its setter: getTotal / setTotal, and get total / set total',\n pairs(blocks) {\n const pairs: [Block, Block][] = [];\n for (const getter of blocks) {\n const accessed = accessedName(getter, 'get');\n const setter = accessed && blocks.find((block) => block !== getter && accessedName(block, 'set') === accessed);\n if (setter) pairs.push([getter, setter]);\n }\n return pairs;\n },\n },\n];\n\n/** What a block knows about its siblings, read from its own code. */\nexport interface SiblingFacts {\n /** Sibling functions it calls, in the order of their first call. */\n calls: string[];\n /** Every sibling it names (calls included). */\n uses: Set<string>;\n}\n\nexport interface RelatednessRule {\n description: string;\n /** How strongly two blocks belong together (0: not at all). */\n score(a: Block, b: Block, factsOf: (block: Block) => SiblingFacts): number;\n}\n\nexport const RELATEDNESS_RULES: RelatednessRule[] = [\n {\n description: 'One calls or uses the other',\n score: (a, b, factsOf) => (factsOf(a).uses.has(b.id) || factsOf(b).uses.has(a.id) ? 3 : 0),\n },\n {\n description: 'They use the same things',\n score: (a, b, factsOf) => [...factsOf(a).uses].filter((id) => factsOf(b).uses.has(id)).length,\n },\n {\n description: 'Their names start the same way (formatPrice, formatDate)',\n score: (a, b) => (firstWord(a.name) && firstWord(a.name) === firstWord(b.name) ? 1 : 0),\n },\n];\n\n/** A sibling that already has a position, as placement rules see it. */\nexport interface PlacedSibling {\n block: Block;\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/** Where a new block should go: on one side of a placed sibling. The closest free spot to it wins. */\nexport interface PlacementSpot {\n sibling: PlacedSibling;\n side: 'right' | 'below' | 'above';\n}\n\nexport interface PlacementRule {\n description: string;\n spot(block: Block, placed: PlacedSibling[], factsOf: (block: Block) => SiblingFacts): PlacementSpot | undefined;\n}\n\n/**\n * Where a block that appears in an arranged file goes (typed in the text, or from another branch).\n * Nothing that is already placed moves. First match wins; with no match it goes next to the block\n * before it in the file.\n */\nexport const PLACEMENT_RULES: PlacementRule[] = [\n {\n description: 'A getter right above its setter, a setter right below its getter',\n spot(block, placed) {\n const siblings = [block, ...placed.map((sibling) => sibling.block)];\n for (const rule of STACK_RULES) {\n for (const [top, bottom] of rule.pairs(siblings)) {\n const placedBottom = top === block && placed.find((sibling) => sibling.block === bottom);\n if (placedBottom) return { sibling: placedBottom, side: 'above' };\n const placedTop = bottom === block && placed.find((sibling) => sibling.block === top);\n if (placedTop) return { sibling: placedTop, side: 'below' };\n }\n }\n return undefined;\n },\n },\n {\n description: 'Like a newspaper: a function goes in the column right of its caller, after the function called before it',\n spot(block, placed, factsOf) {\n if (!isFunctionLike(block)) return undefined;\n const caller = placed.find((sibling) => isFunctionLike(sibling.block) && factsOf(sibling.block).calls.includes(block.id));\n if (!caller) return undefined;\n const calls = factsOf(caller.block).calls;\n const isInCallerColumn = (sibling: PlacedSibling) => sibling !== caller && sibling.x >= caller.x + caller.w;\n const calledBefore = calls.slice(0, calls.indexOf(block.id)).reverse();\n const previousInColumn = calledBefore.map((id) => placed.find((sibling) => sibling.block.id === id && isInCallerColumn(sibling))).find(Boolean);\n return previousInColumn ? { sibling: previousInColumn, side: 'below' } : { sibling: caller, side: 'right' };\n },\n },\n {\n description: 'An import, constant or type below the last one of its kind before it in the file',\n spot(block, placed) {\n const zone = zoneOf(block);\n if (zone === 'main') return undefined;\n const sameZone = placed.filter((sibling) => zoneOf(sibling.block) === zone);\n const lastBefore = sameZone.filter((sibling) => sibling.block.start < block.start).at(-1) ?? sameZone[0];\n return lastBefore ? { sibling: lastBefore, side: 'below' } : undefined;\n },\n },\n {\n description: 'Below the block it is most related to',\n spot(block, placed, factsOf) {\n let best: PlacedSibling | undefined;\n let bestScore = 0;\n for (const sibling of placed) {\n const score = RELATEDNESS_RULES.reduce((total, rule) => total + rule.score(block, sibling.block, factsOf), 0);\n if (score > bestScore) {\n best = sibling;\n bestScore = score;\n }\n }\n return best ? { sibling: best, side: 'below' } : undefined;\n },\n },\n];\n\nexport const zoneOf = (block: Block): Zone => ZONE_RULES.find((rule) => rule.matches(block))!.zone;\n\n/**\n * How many levels of callees the newspaper shows to the right of a function. Deeper calls start a\n * shape of their own, so a long chain of calls doesn't become one very wide staircase.\n */\nexport const NEWSPAPER_DEPTH = 3;\n\n/** The newspaper shape applies to these: a caller and the functions it calls. */\nexport const isFunctionLike = (block: Block): boolean => block.kind === 'function';\n\n/** `getTotal` \u2192 `total` for 'get'; accessors `get total` \u2192 `total`. */\nfunction accessedName(block: Block, accessor: 'get' | 'set'): string | undefined {\n if (block.kind !== 'function') return undefined;\n if (block.tags.includes(accessor)) return block.name;\n const match = new RegExp(`^${accessor}([A-Z_$][\\\\w$]*)$`).exec(block.name);\n return match ? match[1].charAt(0).toLowerCase() + match[1].slice(1) : undefined;\n}\n\n/** The first word of a camelCase name, if it has more than one: `formatPrice` \u2192 `format`. */\nfunction firstWord(name: string): string | undefined {\n const match = /^([a-z]+)[A-Z0-9_]/.exec(name);\n const isAccessorWord = match?.[1] === 'get' || match?.[1] === 'set';\n return match && !isAccessorWord ? match[1] : undefined;\n}\n", "import {\n BAND_ORDER,\n isFunctionLike,\n NEWSPAPER_DEPTH,\n PLACEMENT_RULES,\n RELATEDNESS_RULES,\n STACK_RULES,\n zoneOf,\n type PlacedSibling,\n type PlacementSpot,\n type SiblingFacts,\n type Zone,\n} from './layoutRules';\nimport { codeWithoutChildren } from './parse';\nimport type { Block, Point } from './types';\n\n/** Blocks laid out together: a block, or blocks side by side (row) or one above the other (column). */\nexport type Arrangement = { block: string } | { row: Arrangement[] } | { column: Arrangement[] };\n\ninterface Size {\n w: number;\n h: number;\n}\n\n/** Blocks the rules keep together, and how. */\ninterface Unit {\n members: Block[];\n arrangement: Arrangement;\n zone: Zone;\n /** Source order of its first block. */\n order: number;\n}\n\n/**\n * Positions for sibling blocks that were never laid out, following the rules in layoutRules.ts.\n * Positions are relative to the group's origin; sizes come from the caller.\n */\nexport function arrangeSiblings(blocks: Block[], sizeOf: (id: string) => Size, text: string, gap: number, isFile: boolean): Map<string, Point> {\n const factsById = siblingFacts(blocks, text);\n const factsOf = (block: Block) => factsById.get(block.id)!;\n const units = stackedUnits(blocks);\n const zoneUnits = (zone: Zone) => units.filter((unit) => unit.zone === zone);\n\n const bands = BAND_ORDER.map((zone) => {\n const inZone = zoneUnits(zone);\n return zone === 'main' ? orderByRelatedness(newspaperTrees(inZone, factsOf), factsOf) : inZone;\n });\n\n const positions = new Map<string, Point>();\n let left = 0;\n const leftColumn = zoneUnits('left');\n if (leftColumn.length) {\n let y = 0;\n for (const unit of leftColumn) {\n place(unit.arrangement, 0, y, sizeOf, gap, positions);\n y += measure(unit.arrangement, sizeOf, gap).h + 12;\n }\n left = Math.max(...leftColumn.map((unit) => measure(unit.arrangement, sizeOf, gap).w)) + gap * 2;\n }\n\n // One row width for every band, so the bands line up: about as wide as the blocks are tall.\n const bandUnits = bands.flat();\n const area = bandUnits.reduce((sum, unit) => {\n const size = measure(unit.arrangement, sizeOf, gap);\n return sum + (size.w + gap) * (size.h + gap);\n }, 0);\n const widest = Math.max(0, ...bandUnits.map((unit) => measure(unit.arrangement, sizeOf, gap).w));\n const rowWidth = Math.max(widest, Math.sqrt(area * (isFile ? 1.7 : 2.4)));\n\n let y = 0;\n for (const band of bands.filter((band) => band.length)) {\n let x = 0;\n let rowHeight = 0;\n for (const unit of band) {\n const size = measure(unit.arrangement, sizeOf, gap);\n if (x > 0 && x + size.w > rowWidth) {\n x = 0;\n y += rowHeight + gap;\n rowHeight = 0;\n }\n place(unit.arrangement, left + x, y, sizeOf, gap, positions);\n x += size.w + gap;\n rowHeight = Math.max(rowHeight, size.h);\n }\n y += rowHeight + gap;\n }\n return positions;\n}\n\n/**\n * Where blocks that appeared among arranged siblings should go, by the placement rules (layoutRules.ts).\n * Reads the siblings' code once, for all the new blocks.\n */\nexport function newBlockSpots(siblings: Block[], text: string): (block: Block, placed: PlacedSibling[]) => PlacementSpot | undefined {\n let factsById: Map<string, SiblingFacts> | undefined;\n const factsOf = (sibling: Block) => factsById!.get(sibling.id)!;\n return (block, placed) => {\n factsById ??= siblingFacts(siblings, text);\n for (const rule of PLACEMENT_RULES) {\n const spot = rule.spot(block, placed, factsOf);\n if (spot) return spot;\n }\n return undefined;\n };\n}\n\n/** Each block in its zone, with stacked pairs (getter above setter) merged into one unit. */\nfunction stackedUnits(blocks: Block[]): Unit[] {\n const unitOf = new Map<Block, Unit>();\n const units: Unit[] = blocks.map((block, order) => {\n const unit: Unit = { members: [block], arrangement: { block: block.id }, zone: zoneOf(block), order };\n unitOf.set(block, unit);\n return unit;\n });\n for (const rule of STACK_RULES) {\n for (const [top, bottom] of rule.pairs(blocks)) {\n const topUnit = unitOf.get(top)!;\n const bottomUnit = unitOf.get(bottom)!;\n const canStack = topUnit !== bottomUnit && topUnit.members.length === 1 && bottomUnit.members.length === 1 && topUnit.zone === bottomUnit.zone;\n if (!canStack) continue;\n topUnit.members.push(bottom);\n topUnit.arrangement = { column: [{ block: top.id }, { block: bottom.id }] };\n topUnit.order = Math.min(topUnit.order, bottomUnit.order);\n unitOf.set(bottom, topUnit);\n units.splice(units.indexOf(bottomUnit), 1);\n }\n }\n return units;\n}\n\n/**\n * Like a newspaper: a function on the left, the functions it calls in a column to its right in the\n * order it calls them, and so on for those. A function called from several places goes with the first.\n */\nfunction newspaperTrees(units: Unit[], factsOf: (block: Block) => SiblingFacts): Unit[] {\n const unitOfBlock = new Map<string, Unit>();\n for (const unit of units) for (const member of unit.members) unitOfBlock.set(member.id, unit);\n const isFunctionUnit = (unit: Unit) => unit.members.some(isFunctionLike);\n const calledUnits = (unit: Unit): Unit[] => {\n if (!isFunctionUnit(unit)) return [];\n const called: Unit[] = [];\n for (const member of unit.members) {\n for (const id of factsOf(member).calls) {\n const calledUnit = unitOfBlock.get(id);\n if (calledUnit && calledUnit !== unit && isFunctionUnit(calledUnit) && !called.includes(calledUnit)) called.push(calledUnit);\n }\n }\n return called;\n };\n const isCalledBySibling = new Set(units.flatMap(calledUnits));\n const claimed = new Set<Unit>();\n const tree = (unit: Unit, depth: number): Arrangement => {\n if (depth >= NEWSPAPER_DEPTH) return unit.arrangement;\n // Claim every direct callee first, so a deeper call can't take one out of this column.\n const callees = calledUnits(unit).filter((callee) => !claimed.has(callee));\n for (const callee of callees) claimed.add(callee);\n if (!callees.length) return unit.arrangement;\n return { row: [unit.arrangement, { column: callees.map((callee) => tree(callee, depth + 1)) }] };\n };\n const trees: Unit[] = [];\n // Functions nobody here calls start a tree; then any left over (calls in a cycle), in source order.\n const starts = [...units.filter((unit) => !isCalledBySibling.has(unit)), ...units];\n for (const unit of starts) {\n if (claimed.has(unit)) continue;\n claimed.add(unit);\n const arrangement = tree(unit, 0);\n const members = [...units].filter((other) => other === unit || (claimed.has(other) && contains(arrangement, other)));\n trees.push({ ...unit, arrangement, members: members.flatMap((member) => member.members) });\n }\n return trees;\n}\n\n/** Related units next to each other: after each one comes the most related one left, if any. */\nfunction orderByRelatedness(units: Unit[], factsOf: (block: Block) => SiblingFacts): Unit[] {\n const relatedness = (a: Unit, b: Unit) =>\n a.members.reduce((sum, x) => sum + b.members.reduce((inner, y) => inner + RELATEDNESS_RULES.reduce((total, rule) => total + rule.score(x, y, factsOf), 0), 0), 0);\n const left = [...units].sort((a, b) => a.order - b.order);\n const ordered: Unit[] = [];\n while (left.length) {\n const last = ordered[ordered.length - 1];\n let next = left[0];\n if (last) {\n let best = 0;\n for (const candidate of left) {\n const score = relatedness(last, candidate);\n if (score > best) {\n best = score;\n next = candidate;\n }\n }\n }\n left.splice(left.indexOf(next), 1);\n ordered.push(next);\n }\n return ordered;\n}\n\n/** Which siblings each block calls (in order) and names, from its own code (nested blocks left out). */\nfunction siblingFacts(blocks: Block[], text: string): Map<string, SiblingFacts> {\n const idsByName = new Map<string, string[]>();\n for (const block of blocks) idsByName.set(block.name, [...(idsByName.get(block.name) ?? []), block.id]);\n const facts = new Map<string, SiblingFacts>();\n for (const block of blocks) {\n const code = codeWithoutChildren(text, [block.start, block.end], block.children);\n const calls: string[] = [];\n const uses = new Set<string>();\n for (const match of code.matchAll(/[A-Za-z_$][\\w$]*/g)) {\n const ids = idsByName.get(match[0])?.filter((id) => id !== block.id);\n if (!ids?.length) continue;\n const isCall = /^\\s*\\(/.test(code.slice(match.index + match[0].length, match.index + match[0].length + 40));\n for (const id of ids) {\n uses.add(id);\n if (isCall && !calls.includes(id)) calls.push(id);\n }\n }\n facts.set(block.id, { calls, uses });\n }\n return facts;\n}\n\nconst measured = new WeakMap<Arrangement, Size>();\n\nfunction measure(arrangement: Arrangement, sizeOf: (id: string) => Size, gap: number): Size {\n if ('block' in arrangement) return sizeOf(arrangement.block);\n const known = measured.get(arrangement);\n if (known) return known;\n const size = measureGroup(arrangement, sizeOf, gap);\n measured.set(arrangement, size);\n return size;\n}\n\nfunction measureGroup(arrangement: { row: Arrangement[] } | { column: Arrangement[] }, sizeOf: (id: string) => Size, gap: number): Size {\n const sizes = ('row' in arrangement ? arrangement.row : arrangement.column).map((item) => measure(item, sizeOf, gap));\n const gaps = gap * (sizes.length - 1);\n return 'row' in arrangement\n ? { w: sizes.reduce((sum, size) => sum + size.w, 0) + gaps, h: Math.max(...sizes.map((size) => size.h)) }\n : { w: Math.max(...sizes.map((size) => size.w)), h: sizes.reduce((sum, size) => sum + size.h, 0) + gaps };\n}\n\nfunction place(arrangement: Arrangement, x: number, y: number, sizeOf: (id: string) => Size, gap: number, positions: Map<string, Point>) {\n if ('block' in arrangement) {\n positions.set(arrangement.block, { x: Math.round(x), y: Math.round(y) });\n return;\n }\n const isRow = 'row' in arrangement;\n let offset = 0;\n for (const item of isRow ? arrangement.row : arrangement.column) {\n place(item, isRow ? x + offset : x, isRow ? y : y + offset, sizeOf, gap, positions);\n const size = measure(item, sizeOf, gap);\n offset += (isRow ? size.w : size.h) + gap;\n }\n}\n\nfunction contains(arrangement: Arrangement, unit: Unit): boolean {\n if ('block' in arrangement) return unit.members.some((member) => member.id === arrangement.block);\n return ('row' in arrangement ? arrangement.row : arrangement.column).some((item) => contains(item, unit));\n}\n", "import { arrangeSiblings, newBlockSpots } from './arrange';\nimport type { PlacementSpot } from './layoutRules';\nimport type { Block, FileLayout, FileModel, Point } from './types';\n\n/** Visual metrics. Monospace everywhere so sizes can be computed without measuring the DOM. */\nexport const M = {\n headerH: 32,\n headerCharW: 7.9, // 13px monospace\n previewLineH: 15,\n previewCharW: 6.7, // 11px monospace\n previewPad: 10,\n pad: 14, // inner padding of containers\n gap: 28, // spacing between sibling blocks\n minW: 180,\n maxW: 460,\n miniH: 46, // collapsed container: faint mini-map of children\n fileHeader: 44,\n filePad: 48,\n};\n\nexport interface Geo {\n id: string;\n block: Block;\n /** Position relative to the parent's content origin. */\n x: number;\n y: number;\n w: number;\n h: number;\n /** Absolute world position. */\n ax: number;\n ay: number;\n /** Y offset (inside the block) where nested blocks start. */\n contentTop: number;\n collapsed: boolean;\n /** Hidden because an ancestor is collapsed. */\n hidden: boolean;\n}\n\nexport interface FileGeometry {\n geo: Map<string, Geo>;\n /** Order to draw blocks: parents before children. */\n order: Geo[];\n frame: { x: number; y: number; w: number; h: number };\n /** Positions that were assigned during this pass (new blocks). Save them so they stay put. */\n assigned: Record<string, Point>;\n}\n\nexport function emptyLayout(): FileLayout {\n return { version: 1, blocks: {} };\n}\n\n/**\n * Compute every block's size and position. Saved positions are always respected.\n * Blocks without a saved position get one: a tidy flow layout for a never-laid-out file,\n * otherwise a free spot near their neighbors (or the hint, e.g. where the user clicked).\n */\nexport function computeGeometry(\n model: FileModel,\n layout: FileLayout,\n hints: Record<string, Point> = {},\n opts: { resolveOverlaps?: boolean } = {},\n): FileGeometry {\n const resolve = opts.resolveOverlaps ?? true;\n const geo = new Map<string, Geo>();\n const assigned: Record<string, Point> = {};\n const collapsed = new Set(layout.collapsed ?? []);\n\n const pos = (id: string): Point | undefined => layout.blocks[id] ?? assigned[id];\n\n // 1) sizes, bottom-up, and placement of each block's children\n const measure = (b: Block, hidden: boolean): Geo => {\n const isCollapsed = collapsed.has(b.id) && b.children.length > 0;\n const kids = b.children.map((c) => measure(c, hidden || isCollapsed));\n placeSiblings(kids, false);\n const head = headerChars(b);\n const previewChars = Math.max(0, ...b.preview.map((l) => l.length));\n const leafW = clamp(Math.ceil(Math.max(head * M.headerCharW, previewChars * M.previewCharW) + 28), M.minW, M.maxW);\n const lines = b.preview.length + (b.previewMore ? 1 : 0);\n const previewH = lines ? lines * M.previewLineH + M.previewPad : 4;\n let w = leafW;\n let h = M.headerH + previewH;\n let contentTop = h;\n if (kids.length && isCollapsed) {\n h += M.miniH;\n } else if (kids.length) {\n contentTop = h + 6;\n const right = Math.max(...kids.map((k) => k.x + k.w));\n const bottom = Math.max(...kids.map((k) => k.y + k.h));\n w = Math.max(leafW, right + M.pad * 2);\n h = contentTop + bottom + M.pad;\n }\n const g: Geo = { id: b.id, block: b, x: 0, y: 0, w, h, ax: 0, ay: 0, contentTop, collapsed: isCollapsed, hidden };\n geo.set(b.id, g);\n return g;\n };\n\n /** Give positions to siblings that don't have one. */\n const placeSiblings = (sibs: Geo[], isFile: boolean) => {\n if (!sibs.length) return;\n // Nothing here was ever laid out (new file, or a pasted class): arrange it by the layout rules.\n const isNeverLaidOut = sibs.every((g) => !layout.blocks[g.id] && !hints[g.id]);\n if (isNeverLaidOut) {\n const sizeOf = (id: string) => geo.get(id)!;\n const arranged = arrangeSiblings(sibs.map((g) => g.block), sizeOf, model.text, M.gap, isFile);\n for (const g of sibs) assigned[g.id] = arranged.get(g.id)!;\n }\n const placed: Geo[] = [];\n const unplaced: Geo[] = [];\n for (const g of sibs) {\n const p = pos(g.id);\n if (p) {\n g.x = p.x;\n g.y = p.y;\n placed.push(g);\n } else unplaced.push(g);\n }\n const spotByRules = newBlockSpots(sibs.map((sibling) => sibling.block), model.text);\n for (const g of unplaced) {\n const hint = hints[g.id];\n const ruleSpot = hint || !placed.length ? undefined : spotByRules(g.block, placed);\n let p: Point;\n if (hint) p = freeSpotNear(hint, g, placed, !isFile);\n else if (ruleSpot?.side === 'below') p = freeSpotDown(pointBeside(ruleSpot, g), g, placed, !isFile);\n else if (ruleSpot) p = freeSpotNear(pointBeside(ruleSpot, g), g, placed, !isFile);\n else {\n const previousPlacedInFile = sibs.slice(0, sibs.indexOf(g)).reverse().find((sibling) => placed.includes(sibling));\n p = findFreeSpot(g, placed, previousPlacedInFile, !isFile);\n }\n g.x = p.x;\n g.y = p.y;\n assigned[g.id] = p;\n placed.push(g);\n }\n if (resolve) pushApart(sibs, assigned);\n };\n\n const roots = model.roots.map((r) => measure(r, false));\n placeSiblings(roots, true);\n\n // 2) absolute positions, top-down\n const order: Geo[] = [];\n const place = (g: Geo, ox: number, oy: number) => {\n g.ax = ox + g.x;\n g.ay = oy + g.y;\n order.push(g);\n for (const c of g.block.children) place(geo.get(c.id)!, g.ax + M.pad, g.ay + g.contentTop);\n };\n for (const r of roots) place(r, 0, 0);\n\n let minX = 0,\n minY = 0,\n maxX = 640,\n maxY = 360;\n if (roots.length) {\n minX = Math.min(...roots.map((g) => g.x));\n minY = Math.min(...roots.map((g) => g.y));\n maxX = Math.max(...roots.map((g) => g.x + g.w));\n maxY = Math.max(...roots.map((g) => g.y + g.h));\n }\n const frame = {\n x: minX - M.filePad,\n y: minY - M.filePad - M.fileHeader,\n w: Math.max(maxX - minX, 480) + M.filePad * 2,\n h: Math.max(maxY - minY, 240) + M.filePad * 2 + M.fileHeader,\n };\n return { geo, order, frame, assigned };\n}\n\n/**\n * Where to draw blocks the open version doesn't have (removed since the diff base, or only in the\n * incoming side of a conflict): where they were in their own version, relative to their parent,\n * or the closest free spot to it if a block of this version is there now.\n * Each block's parent must be in `current`. Blocks inside a collapsed or hidden parent are left out.\n */\nexport function placeGhostBlocks(ghosts: Block[], ghostGeometry: FileGeometry, currentModel: FileModel, current: FileGeometry): Map<string, Point> {\n const positions = new Map<string, Point>();\n const placedGhostsByParent = new Map<string | null, Rect[]>();\n for (const ghost of ghosts) {\n const ghostGeo = ghostGeometry.geo.get(ghost.id);\n if (!ghostGeo) continue;\n const parentId = ghost.parentId ?? null;\n const parentGeo = parentId ? current.geo.get(parentId) : undefined;\n if (parentId && !parentGeo) continue;\n if (parentGeo && (parentGeo.hidden || parentGeo.collapsed)) continue;\n const currentSiblings = parentId ? currentModel.blocks.get(parentId)!.children : currentModel.roots;\n const placedGhosts = placedGhostsByParent.get(parentId) ?? [];\n const taken = [...currentSiblings.map((sibling) => current.geo.get(sibling.id)!), ...placedGhosts];\n const spot = freeSpotNear({ x: ghostGeo.x, y: ghostGeo.y }, ghostGeo, taken, !!parentGeo);\n placedGhosts.push({ ...spot, w: ghostGeo.w, h: ghostGeo.h });\n placedGhostsByParent.set(parentId, placedGhosts);\n positions.set(ghost.id, parentGeo ? { x: parentGeo.ax + M.pad + spot.x, y: parentGeo.ay + parentGeo.contentTop + spot.y } : spot);\n }\n return positions;\n}\n\n/**\n * A block that grew (e.g. a class got a new method) may now cover its neighbors.\n * Push each covered block just far enough down or right, and save its new spot.\n */\nfunction pushApart(sibs: Geo[], assigned: Record<string, Point>) {\n for (let iter = 0; iter < 100; iter++) {\n let moved = false;\n const sorted = [...sibs].sort((a, b) => a.y - b.y || a.x - b.x);\n for (let i = 0; i < sorted.length; i++) {\n for (let j = i + 1; j < sorted.length; j++) {\n const a = sorted[i];\n const b = sorted[j];\n if (!overlaps(a, b, 4)) continue;\n const down = a.y + a.h + M.gap - b.y;\n const right = b.x > a.x ? a.x + a.w + M.gap - b.x : Infinity;\n if (right < down) b.x += right;\n else b.y += down;\n assigned[b.id] = { x: Math.round(b.x), y: Math.round(b.y) };\n moved = true;\n }\n }\n if (!moved) break;\n }\n}\n\n/** The top-left corner for a block of `size` on that side of the sibling. */\nfunction pointBeside(spot: PlacementSpot, size: { w: number; h: number }): Point {\n const { sibling, side } = spot;\n if (side === 'right') return { x: sibling.x + sibling.w + M.gap, y: sibling.y };\n if (side === 'below') return { x: sibling.x, y: sibling.y + sibling.h + M.gap };\n return { x: sibling.x, y: sibling.y - size.h - M.gap };\n}\n\nfunction headerChars(b: Block): number {\n const tags = b.tags.filter((t) => t !== 'export').join(' ');\n return 4 + b.name.length + Math.min(b.detail.length, 40) + (tags ? tags.length + 2 : 0) + 3;\n}\n\ninterface Rect {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\nfunction overlaps(a: Rect, b: Rect, gap = M.gap / 2): boolean {\n return a.x < b.x + b.w + gap && a.x + a.w + gap > b.x && a.y < b.y + b.h + gap && a.y + a.h + gap > b.y;\n}\n\nfunction fits(r: Rect, placed: Rect[], clampPositive: boolean): boolean {\n if (clampPositive && (r.x < 0 || r.y < 0)) return false;\n return !placed.some((p) => overlaps(r, p));\n}\n\n/** A free spot next to the previous sibling (in source order), so related code lands nearby. */\nfunction findFreeSpot(g: Geo, placed: Geo[], prev: Geo | undefined, clampPositive: boolean): Point {\n if (!placed.length) return { x: 0, y: 0 };\n const cands: Point[] = [];\n if (prev) cands.push({ x: prev.x, y: prev.y + prev.h + M.gap }, { x: prev.x + prev.w + M.gap, y: prev.y });\n const origin = prev ?? placed[0];\n const others = [...placed].sort((a, b) => dist(a, origin) - dist(b, origin));\n for (const p of others) cands.push({ x: p.x, y: p.y + p.h + M.gap }, { x: p.x + p.w + M.gap, y: p.y });\n for (const c of cands) if (fits({ ...c, w: g.w, h: g.h }, placed, clampPositive)) return c;\n const bottom = Math.max(...placed.map((p) => p.y + p.h));\n return { x: Math.min(...placed.map((p) => p.x)), y: bottom + M.gap };\n}\n\n/** The closest free spot to `at` (e.g. where a block was dropped or created). */\nexport function freeSpotNear(at: Point, g: { w: number; h: number; id?: string }, placed: Rect[], clampPositive: boolean): Point {\n const start = clampPositive ? { x: Math.max(0, at.x), y: Math.max(0, at.y) } : at;\n const others = placed.filter((p) => (p as Geo).id === undefined || (p as Geo).id !== g.id);\n if (fits({ ...start, w: g.w, h: g.h }, others, clampPositive)) return round(start);\n const cands: Point[] = [];\n for (const p of others) {\n cands.push(\n { x: p.x + p.w + M.gap, y: start.y },\n { x: start.x, y: p.y + p.h + M.gap },\n { x: p.x - g.w - M.gap, y: start.y },\n { x: start.x, y: p.y - g.h - M.gap },\n { x: p.x + p.w + M.gap, y: p.y },\n { x: p.x, y: p.y + p.h + M.gap },\n );\n }\n cands.sort((a, b) => dist(a, start) - dist(b, start));\n for (const c of cands) if (fits({ ...c, w: g.w, h: g.h }, others, clampPositive)) return round(c);\n const bottom = Math.max(...others.map((p) => p.y + p.h));\n return round({ x: start.x, y: bottom + M.gap });\n}\n\n/** The first free spot at or below `at`, in the same column (keeps a column in order). */\nfunction freeSpotDown(at: Point, g: { w: number; h: number }, placed: Rect[], clampPositive: boolean): Point {\n const spot = clampPositive ? { x: Math.max(0, at.x), y: Math.max(0, at.y) } : { ...at };\n const blockCoveringSpot = () => placed.find((p) => overlaps({ x: spot.x, y: spot.y, w: g.w, h: g.h }, p));\n for (let covering = blockCoveringSpot(); covering; covering = blockCoveringSpot()) spot.y = covering.y + covering.h + M.gap;\n return round(spot);\n}\n\nfunction dist(a: Point, b: Point) {\n return Math.hypot(a.x - b.x, a.y - b.y);\n}\n\nfunction clamp(v: number, lo: number, hi: number) {\n return Math.min(hi, Math.max(lo, v));\n}\n\nfunction round(p: Point): Point {\n return { x: Math.round(p.x), y: Math.round(p.y) };\n}\n\n/**\n * When a block is renamed its id changes. If exactly one block disappeared and one appeared\n * under the same parent, carry the old position (and its children's) over to the new id.\n */\nexport function carryRenames(prev: FileModel | null, next: FileModel, layout: FileLayout): boolean {\n if (!prev) return false;\n const removedByParent = new Map<string | null, Block[]>();\n const addedByParent = new Map<string | null, Block[]>();\n for (const [id, b] of prev.blocks) if (!next.blocks.has(id)) push(removedByParent, b.parentId, b);\n for (const [id, b] of next.blocks) if (!prev.blocks.has(id)) push(addedByParent, b.parentId, b);\n let changed = false;\n for (const [parent, added] of addedByParent) {\n const removed = removedByParent.get(parent);\n if (added.length !== 1 || removed?.length !== 1) continue;\n const from = removed[0].id;\n const to = added[0].id;\n for (const key of Object.keys(layout.blocks)) {\n if (key === from || key.startsWith(from + '/')) {\n const nk = to + key.slice(from.length);\n if (!layout.blocks[nk]) layout.blocks[nk] = layout.blocks[key];\n changed = true;\n }\n }\n if (layout.collapsed?.includes(from)) layout.collapsed.push(to);\n }\n return changed;\n}\n\nfunction push<K, V>(m: Map<K, V[]>, k: K, v: V) {\n const a = m.get(k);\n if (a) a.push(v);\n else m.set(k, [v]);\n}\n\n/** Layout ready to be written to `.codecanvas/`: only live blocks, sorted keys, whole numbers. */\nexport function serializeLayout(layout: FileLayout, model: FileModel | null): string {\n const blocks: Record<string, Point> = {};\n for (const k of Object.keys(layout.blocks).sort()) {\n if (model && !model.blocks.has(k)) continue;\n const p = layout.blocks[k];\n blocks[k] = { x: Math.round(p.x), y: Math.round(p.y) };\n }\n const out: FileLayout = { version: 1, blocks };\n const collapsed = (layout.collapsed ?? []).filter((c) => !model || model.blocks.has(c)).sort();\n if (collapsed.length) out.collapsed = [...new Set(collapsed)];\n return JSON.stringify(out, null, 2) + '\\n';\n}\n", "interface HtmlPolicy {\n createHTML(html: string): unknown;\n}\n\nlet policy: HtmlPolicy | null | undefined;\n\n/**\n * Pages that enforce Trusted Types (VS Code's window does) reject plain strings in `innerHTML`.\n * There, HTML goes through the `codecanvas` policy, which the host must allow in its CSP.\n * Callers escape every value they put in the HTML (`esc`), so the policy passes it through as is.\n */\nfunction trustedHtmlPolicy(): HtmlPolicy | null {\n if (policy !== undefined) return policy;\n const factory = (globalThis as { trustedTypes?: { createPolicy(name: string, rules: { createHTML(html: string): string }): HtmlPolicy } }).trustedTypes;\n try {\n policy = factory ? factory.createPolicy('codecanvas', { createHTML: (html) => html }) : null;\n } catch {\n policy = null;\n }\n return policy;\n}\n\nexport function setHTML(element: Element, html: string) {\n const htmlPolicy = trustedHtmlPolicy();\n element.innerHTML = (htmlPolicy ? htmlPolicy.createHTML(html) : html) as string;\n}\n", "/** Canvas styles. Injected once. Hosts can override the CSS variables on `.cc-root`. */\nexport const CSS = /* css */ `\n.cc-root {\n --cc-bg: #15171c;\n --cc-dot: rgba(255,255,255,.07);\n --cc-frame-bg: rgba(255,255,255,.025);\n --cc-frame-border: rgba(255,255,255,.10);\n --cc-text: #e8eaee;\n --cc-muted: #9aa1ad;\n --cc-faint: #c4cad4;\n --cc-panel: #1f2229;\n --cc-panel-border: rgba(255,255,255,.12);\n --cc-accent: #7aa2ff;\n --cc-danger: #ff6b6b;\n --cc-shadow: 0 10px 30px rgba(0,0,0,.45);\n\n --k-import: #6b7280; --k-import-head: #3b3f46; --k-import-bg: #25272c;\n --k-class: #34b27a; --k-class-head: #1d6b4a; --k-class-bg: rgba(52,178,122,.08);\n --k-function: #ec5fa5; --k-function-head: #8f2f62; --k-function-bg: rgba(236,95,165,.09);\n --k-variable: #4b8ef7; --k-variable-head: #23508f; --k-variable-bg: rgba(75,142,247,.09);\n --k-type: #d4a92a; --k-type-head: #6e5714; --k-type-bg: rgba(212,169,42,.08);\n --k-namespace: #9b8cf8; --k-namespace-head: #4d4291; --k-namespace-bg: rgba(155,140,248,.08);\n --k-statement: #7c8799; --k-statement-head: #39414f; --k-statement-bg: rgba(124,135,153,.08);\n\n position: relative; overflow: hidden; width: 100%; height: 100%;\n background-color: var(--cc-bg);\n background-image: radial-gradient(var(--cc-dot) 1.2px, transparent 1.3px);\n color: var(--cc-text);\n font: 13px/1.3 ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", sans-serif;\n touch-action: none; user-select: none; -webkit-user-select: none; outline: none;\n -webkit-tap-highlight-color: transparent;\n}\n.cc-root[data-theme=\"light\"] {\n --cc-bg: #f6f7f9; --cc-dot: rgba(0,0,0,.09);\n --cc-frame-bg: rgba(255,255,255,.7); --cc-frame-border: rgba(0,0,0,.12);\n --cc-text: #1d2129; --cc-muted: #5d6573; --cc-faint: #39404c;\n --cc-panel: #ffffff; --cc-panel-border: rgba(0,0,0,.12); --cc-accent: #3366e6;\n --cc-shadow: 0 10px 30px rgba(20,30,50,.18);\n --k-import: #6b7280; --k-import-head: #4b5058; --k-import-bg: #eceef1;\n --k-class: #1f9963; --k-class-head: #1f9963; --k-class-bg: rgba(31,153,99,.07);\n --k-function: #d63e8c; --k-function-head: #d63e8c; --k-function-bg: rgba(214,62,140,.07);\n --k-variable: #2f6fe0; --k-variable-head: #2f6fe0; --k-variable-bg: rgba(47,111,224,.07);\n --k-type: #b58a0c; --k-type-head: #a87f08; --k-type-bg: rgba(181,138,12,.08);\n --k-namespace: #6f5ce6; --k-namespace-head: #6f5ce6; --k-namespace-bg: rgba(111,92,230,.07);\n --k-statement: #64708a; --k-statement-head: #64708a; --k-statement-bg: rgba(100,112,138,.07);\n}\n.cc-world { position: absolute; left: 0; top: 0; transform-origin: 0 0; }\n.cc-root.cc-moving .cc-world { will-change: transform; }\n.cc-frame { position: absolute; border: 1px solid var(--cc-frame-border); background: var(--cc-frame-bg); border-radius: 18px; }\n.cc-frame-title { position: absolute; left: 20px; top: 12px; font: 600 15px/20px var(--cc-font, \"JetBrains Mono\", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); color: var(--cc-muted); white-space: nowrap; }\n.cc-empty { position: absolute; font-size: 15px; color: var(--cc-muted); white-space: nowrap; }\n\n.cc-block {\n position: absolute; left: 0; top: 0; box-sizing: border-box; border-radius: 10px;\n border: 1.5px solid var(--k); background: var(--kbg); overflow: hidden; contain: layout style;\n cursor: default;\n}\n.cc-block.k-import { --k: var(--k-import); --kh: var(--k-import-head); --kbg: var(--k-import-bg); }\n.cc-block.k-class { --k: var(--k-class); --kh: var(--k-class-head); --kbg: var(--k-class-bg); }\n.cc-block.k-function { --k: var(--k-function); --kh: var(--k-function-head); --kbg: var(--k-function-bg); }\n.cc-block.k-variable { --k: var(--k-variable); --kh: var(--k-variable-head); --kbg: var(--k-variable-bg); }\n.cc-block.k-type { --k: var(--k-type); --kh: var(--k-type-head); --kbg: var(--k-type-bg); }\n.cc-block.k-namespace { --k: var(--k-namespace); --kh: var(--k-namespace-head); --kbg: var(--k-namespace-bg); }\n.cc-block.k-statement { --k: var(--k-statement); --kh: var(--k-statement-head); --kbg: var(--k-statement-bg); }\n.cc-block.k-import, .cc-root:not([data-theme=\"light\"]) .cc-block.k-import { border-color: #555a63; }\n\n.cc-head {\n display: flex; align-items: center; gap: 7px; height: 32px; padding: 0 10px; box-sizing: border-box;\n background: var(--kh); color: #fff; white-space: nowrap; overflow: hidden;\n font: 13px/32px var(--cc-font, \"JetBrains Mono\", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);\n}\n.cc-kind { font-size: 10px; text-transform: uppercase; letter-spacing: .06em; opacity: .75; flex: none; }\n.cc-name { font-weight: 700; flex: none; max-width: 70%; overflow: hidden; text-overflow: ellipsis; }\n.cc-detail { opacity: .8; overflow: hidden; text-overflow: ellipsis; min-width: 0; flex: 1 1 auto; }\n.cc-tags { font-size: 10px; opacity: .7; flex: none; }\n.cc-exp { width: 6px; height: 6px; border-radius: 50%; background: #fff; opacity: .8; flex: none; }\n.cc-fold {\n flex: none; margin-left: auto; width: 22px; height: 22px; border: 0; border-radius: 6px; padding: 0;\n background: rgba(255,255,255,.14); color: #fff; font-size: 12px; line-height: 22px; cursor: pointer;\n}\n.cc-fold:hover { background: rgba(255,255,255,.28); }\n.cc-prev {\n margin: 0; padding: 5px 12px 0; white-space: pre; overflow: hidden; color: var(--cc-faint); opacity: .5;\n font: 11px/15px var(--cc-font, \"JetBrains Mono\", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);\n}\n.cc-more { opacity: .7; font-style: italic; }\n.cc-mini { position: relative; margin: 6px 12px 0; height: 34px; opacity: .45; }\n.cc-mini > i { position: absolute; border-radius: 2px; border: 1px solid var(--cc-faint); background: rgba(255,255,255,.06); }\n.cc-mini > i.k-class { border-color: var(--k-class); } .cc-mini > i.k-function { border-color: var(--k-function); }\n.cc-mini > i.k-variable { border-color: var(--k-variable); } .cc-mini > i.k-type { border-color: var(--k-type); }\n\n.cc-err {\n flex: none; min-width: 18px; height: 18px; padding: 0 5px; box-sizing: border-box; border-radius: 9px;\n background: var(--cc-danger); color: #fff; font: 700 11px/18px ui-sans-serif, system-ui, sans-serif; text-align: center;\n}\n.cc-block.cc-has-error { border-color: var(--cc-danger); }\n.cc-root.lod-2 .cc-err { min-width: 34px; height: 34px; border-radius: 17px; font-size: 22px; line-height: 34px; }\n.cc-rename {\n font: inherit; font-weight: 700; color: #fff; background: rgba(0,0,0,.35); border: 1px solid var(--cc-accent);\n border-radius: 4px; padding: 0 4px; height: 22px; outline: none; user-select: text; -webkit-user-select: text; max-width: 100%;\n}\n.cc-rename.invalid { border-color: var(--cc-danger); }\n.cc-name:has(.cc-rename) { max-width: none; overflow: visible; }\n\n/* merge conflicts */\n.cc-block.cc-conflict { border-color: #f0883e; box-shadow: 0 0 0 2px rgba(240, 136, 62, .35); }\n.cc-conflict-chip {\n flex: none; min-width: 18px; height: 18px; border-radius: 9px; background: #f0883e; color: #1b1300;\n font: 900 13px/18px ui-sans-serif, system-ui, sans-serif; text-align: center;\n}\n.cc-root.lod-2 .cc-conflict-chip { min-width: 34px; height: 34px; border-radius: 17px; font-size: 24px; line-height: 34px; }\n.cc-block.cc-conflict-incoming {\n --k: #f0883e; --kh: #8a4a17; --kbg: rgba(240, 136, 62, .08);\n border-style: dashed; pointer-events: none; opacity: .9;\n}\n.cc-diff-chip.incoming { background: #f0883e; }\n.cc-banner.cc-banner-conflicts { border-color: #f0883e; }\n\n/* changes against a base version (setDiffBase) */\n.cc-block.cc-diff-unchanged { filter: saturate(.3) brightness(.92); }\n.cc-diff-chip {\n flex: none; min-width: 18px; height: 18px; padding: 0 4px; box-sizing: border-box; border-radius: 5px;\n font: 800 13px/18px ui-sans-serif, system-ui, sans-serif; text-align: center; color: #fff;\n}\n.cc-diff-chip.added { background: #2ea043; }\n.cc-diff-chip.changed { background: #d29922; }\n.cc-diff-chip.removed { background: var(--cc-danger); }\n.cc-root.lod-2 .cc-diff-chip { min-width: 34px; height: 34px; border-radius: 8px; font-size: 24px; line-height: 34px; }\n.cc-block.cc-diff-removed {\n --k: var(--cc-danger); --kh: #9c2f2f; --kbg: rgba(255, 107, 107, .10);\n border-style: dashed; pointer-events: none; opacity: .9;\n}\n.cc-root[data-theme=\"light\"] .cc-block.cc-diff-removed { --kh: #d64545; --kbg: rgba(214, 69, 69, .08); }\n.cc-prev.cc-diff-prev { opacity: .95; }\n.cc-diff-prev > span { display: block; margin: 0 -12px; padding: 0 12px; }\n.cc-diff-prev .cc-line-same { opacity: .5; }\n.cc-diff-prev .cc-line-added { background: rgba(46, 160, 67, .30); }\n.cc-diff-prev .cc-line-removed { background: rgba(248, 81, 73, .26); text-decoration: line-through; text-decoration-color: rgba(248, 81, 73, .7); }\n.cc-diff-summary { padding: 0 8px; font-size: 12px; color: var(--cc-muted); white-space: nowrap; }\n\n.cc-block.cc-sel { box-shadow: 0 0 0 2px var(--cc-bg), 0 0 0 4px var(--k); }\n.cc-block.cc-editing { box-shadow: 0 0 0 2px var(--cc-bg), 0 0 0 4px var(--cc-accent); }\n.cc-block.cc-dragging { box-shadow: var(--cc-shadow); opacity: .92; z-index: 9999 !important; }\n.cc-root.has-hl .cc-block.cc-linked { box-shadow: 0 0 0 2px var(--k); }\n\n.cc-edges { position: absolute; left: 0; top: 0; overflow: visible; pointer-events: none; }\n.cc-edge { fill: none; stroke-width: 1.5; opacity: .22; }\n.cc-edge.u-type { stroke-dasharray: 4 4; }\n.cc-root.has-hl .cc-edge { opacity: .07; }\n.cc-root.has-hl .cc-edge.hl { opacity: .95; stroke-width: 2.5; }\n\n/* level of detail when zoomed out */\n.cc-root.lod-1 .cc-tags { visibility: hidden; }\n.cc-root.lod-2 .cc-prev, .cc-root.lod-2 .cc-detail, .cc-root.lod-2 .cc-mini { visibility: hidden; }\n.cc-root.lod-2 .cc-head { font-size: 26px; }\n.cc-root.lod-2 .cc-kind, .cc-root.lod-2 .cc-fold { display: none; }\n.cc-root.lod-2 .cc-frame-title { font-size: 40px; line-height: 44px; top: -8px; }\n\n/* overlays (screen space) */\n.cc-banner {\n position: absolute; left: 50%; top: 12px; transform: translateX(-50%); z-index: 20; display: flex; gap: 10px; align-items: center;\n padding: 8px 12px; border-radius: 10px; background: var(--cc-panel); border: 1px solid var(--cc-danger); box-shadow: var(--cc-shadow);\n font-size: 13px; max-width: calc(100% - 32px);\n}\n.cc-banner[hidden], .cc-bar[hidden], .cc-refs[hidden] { display: none; }\n.cc-toast {\n position: absolute; left: 50%; bottom: 76px; transform: translateX(-50%); z-index: 30; padding: 8px 14px; border-radius: 10px;\n background: var(--cc-panel); border: 1px solid var(--cc-panel-border); box-shadow: var(--cc-shadow); font-size: 13px;\n transition: opacity .2s; pointer-events: none; max-width: calc(100% - 32px);\n}\n.cc-bar {\n position: absolute; left: 50%; bottom: 16px; transform: translateX(-50%); z-index: 20; display: flex; align-items: center; gap: 4px;\n padding: 5px; border-radius: 12px; background: var(--cc-panel); border: 1px solid var(--cc-panel-border); box-shadow: var(--cc-shadow);\n width: max-content; max-width: calc(100% - 24px); box-sizing: border-box; flex-wrap: wrap; justify-content: center;\n}\n.cc-bar .cc-chip { padding: 0 10px 0 6px; font: 600 12px/30px var(--cc-font, \"JetBrains Mono\", ui-monospace, Menlo, monospace); white-space: nowrap; display: flex; align-items: center; gap: 6px; max-width: 220px; overflow: hidden; text-overflow: ellipsis; }\n.cc-bar .cc-chip i { width: 10px; height: 10px; border-radius: 3px; background: var(--k); flex: none; }\n.cc-btn {\n border: 0; background: transparent; color: var(--cc-text); font: 500 13px/30px inherit; font-family: inherit; padding: 0 10px; border-radius: 8px;\n cursor: pointer; white-space: nowrap; min-height: 32px;\n}\n.cc-btn:hover { background: rgba(127,127,127,.16); }\n.cc-btn.danger { color: var(--cc-danger); }\n.cc-btn.primary { background: var(--cc-accent); color: #fff; }\n.cc-sep { width: 1px; height: 20px; background: var(--cc-panel-border); margin: 0 2px; flex: none; }\n.cc-refs {\n position: absolute; left: 50%; bottom: 64px; transform: translateX(-50%); z-index: 21; width: min(360px, calc(100% - 24px)); max-height: 45%;\n overflow: auto; border-radius: 12px; background: var(--cc-panel); border: 1px solid var(--cc-panel-border); box-shadow: var(--cc-shadow); padding: 6px;\n}\n.cc-refs h4 { margin: 8px 8px 4px; font-size: 11px; text-transform: uppercase; letter-spacing: .06em; color: var(--cc-muted); }\n.cc-refs button {\n display: flex; width: 100%; align-items: center; gap: 8px; border: 0; background: transparent; color: var(--cc-text); text-align: left;\n padding: 6px 8px; border-radius: 8px; cursor: pointer; font: 12px/18px var(--cc-font, \"JetBrains Mono\", ui-monospace, Menlo, monospace);\n}\n.cc-refs button:hover { background: rgba(127,127,127,.16); }\n.cc-refs button i { width: 10px; height: 10px; border-radius: 3px; background: var(--k); flex: none; }\n.cc-refs button span:last-child { margin-left: auto; color: var(--cc-muted); }\n.cc-refs button:disabled { cursor: default; opacity: .7; }\n.cc-refs button:disabled:hover { background: transparent; }\n.cc-refs .cc-file { color: var(--cc-muted); }\n.cc-refs .cc-error-row { --k: var(--cc-danger); align-items: flex-start; }\n.cc-refs .cc-error-row i { border-radius: 50%; margin-top: 4px; }\n.cc-refs .cc-error-row span:nth-child(2) { white-space: pre-wrap; font-family: ui-sans-serif, system-ui, sans-serif; }\n.cc-refs .cc-error-row span:last-child { white-space: nowrap; }\n.cc-refs .none { padding: 4px 8px 8px; color: var(--cc-muted); font-size: 12px; }\n\n.cc-editor {\n position: absolute; z-index: 25; display: flex; flex-direction: column; border-radius: 12px; overflow: hidden;\n background: var(--cc-panel); border: 1px solid var(--cc-panel-border); box-shadow: var(--cc-shadow);\n}\n.cc-editor-head { display: flex; align-items: center; gap: 8px; padding: 4px 6px 4px 12px; border-bottom: 1px solid var(--cc-panel-border); }\n.cc-editor-head .cc-chip { flex: 1; min-width: 0; font: 600 12px/30px var(--cc-font, \"JetBrains Mono\", ui-monospace, Menlo, monospace); display: flex; align-items: center; gap: 6px; overflow: hidden; white-space: nowrap; }\n.cc-editor-head .cc-chip i { width: 10px; height: 10px; border-radius: 3px; background: var(--k); flex: none; }\n.cc-editor-body { flex: 1; min-height: 0; overflow: auto; user-select: text; -webkit-user-select: text; touch-action: auto; }\n.cc-editor-hint { font-size: 11px; color: var(--cc-muted); white-space: nowrap; }\n@media (max-width: 640px) { .cc-editor-hint { display: none; } }\n`;\n\nlet injected = false;\nexport function injectStyles(doc: Document = document) {\n if (injected) return;\n injected = true;\n const s = doc.createElement('style');\n s.dataset.codecanvas = '';\n s.textContent = CSS;\n doc.head.appendChild(s);\n}\n", "import * as E from './edits';\nimport { carryRenames, computeGeometry, emptyLayout, freeSpotNear, M, placeGhostBlocks, type FileGeometry, type Geo } from './layout';\nimport { Project, type CanvasProject } from './project';\nimport { setHTML } from './html';\nimport { injectStyles } from './styles';\nimport { conflictSideText, findConflicts, resolveConflict, type ConflictChoice, type ConflictHunk, type ConflictSide, type ConflictSideText } from './conflicts';\nimport { diffModels, diffOwnCode, diffPreview, type BlockChange, type FileDiff } from './diff';\nimport { blockAt, parseStructure } from './parse';\nimport type { Block, CodeDiagnostic, FileLayout, FileModel, HostDiagnostic, IncomingUsage, Point, Usage } from './types';\n\nexport interface EditorOptions {\n parent: HTMLElement;\n text: string;\n /** Where `text` is in the file, for an editor that shows just this part of the whole document. */\n start: number;\n end: number;\n /** Selection to apply on open, relative to `text`. */\n selection?: [number, number];\n /** While changes are shown: the block's code in the base version ('' for an added block). Show a diff against it. */\n diffBase?: string;\n /** For editors on their own copy of `text`. Editors that edit the file itself don't call it. */\n onChange(text: string): void;\n /** User pressed Escape / Mod-Enter inside the editor. */\n onClose(): void;\n}\nexport interface EditorHandle {\n focus(): void;\n destroy(): void;\n /**\n * The editor edits the file's document directly (e.g. Monaco on the real file, for IntelliSense).\n * The canvas then gets its changes through `setText` and keeps the editor open, following the block.\n */\n editsFile?: boolean;\n}\n/** The host provides the code editor used inside blocks (CodeMirror in the playground, Monaco in the IDE). */\nexport type EditorFactory = (o: EditorOptions) => EditorHandle;\n\nexport interface CodeCanvasOptions {\n createEditor: EditorFactory;\n /** The canvas changed the file's text. */\n /**\n * The canvas changed the file's text. When the same action changed other files too (a rename),\n * `otherFiles` lists them, already updated in the project: the host should treat it all as one undo step.\n */\n onTextChange(text: string, otherFiles?: OtherFileChange[]): void;\n /**\n * Block positions or collapsed state changed. Save with `serializeLayout`. `automatic` changes\n * (first layout, blocks added in the text, renames) don't come from the user arranging the canvas:\n * a host may keep those out of the repo until there's a `user` change.\n */\n onLayoutChange(layout: FileLayout, reason: LayoutChangeReason): void;\n onUndo?(): void;\n onRedo?(): void;\n onCameraChange?(scale: number): void;\n theme?: 'dark' | 'light';\n /**\n * The project the file belongs to, for references across files and type errors. Keep it updated\n * with the other files' text. Without one, the canvas only sees the open file.\n */\n project?: CanvasProject;\n /** The selected block changed (null: nothing selected). */\n onSelect?(block: Block | null): void;\n /** The user picked a block in another file, e.g. in the references list. */\n onOpenBlock?(path: string, blockId: string): void;\n}\n\nexport type LayoutChangeReason = 'user' | 'automatic';\n\n/** Another file changed by the same canvas action, e.g. usages renamed there. */\nexport interface OtherFileChange {\n path: string;\n before: string;\n after: string;\n /** The file's model before the change, to carry renamed blocks' saved positions (`carryRenames`). */\n previousModel: FileModel | undefined;\n}\n\ninterface Camera {\n x: number;\n y: number;\n s: number;\n}\n\ntype Gesture =\n | { t: 'pending'; id: number; sx: number; sy: number; touch: boolean; target: Element | null }\n | { t: 'pan'; id: number; sx: number; sy: number; cam: Camera }\n | { t: 'drag'; id: number; sx: number; sy: number; block: string; orig: Point; nested: boolean }\n | { t: 'pinch'; d0: number; m0: Point; cam: Camera }\n | null;\n\nconst KIND_LABEL: Record<Block['kind'], string> = {\n import: 'import',\n class: 'class',\n function: 'fn',\n variable: 'var',\n type: 'type',\n namespace: 'ns',\n statement: 'code',\n};\nconst DIFF_CHIPS: Record<BlockChange | 'removed' | 'incoming', string> = {\n added: '<span class=\"cc-diff-chip added\" title=\"Added\">+</span>',\n changed: '<span class=\"cc-diff-chip changed\" title=\"Changed\">~</span>',\n removed: '<span class=\"cc-diff-chip removed\" title=\"Removed\">\u2212</span>',\n incoming: '<span class=\"cc-diff-chip incoming\" title=\"Incoming\">+</span>',\n containsChanges: '',\n unchanged: '',\n};\nconst LABEL_TAGS = new Set(['const', 'let', 'var', 'interface', 'type', 'enum', 'namespace', 'get', 'set']);\nconst MIN_SCALE = 0.04;\nconst MAX_SCALE = 4;\n\n/**\n * The visual editor for one file. Text is the source of truth: every action on the canvas\n * becomes a text edit, and every text change re-renders the canvas.\n */\nexport class CodeCanvas {\n readonly root: HTMLElement;\n private world: HTMLElement;\n private frameEl: HTMLElement;\n private blocksEl: HTMLElement;\n private svg: SVGSVGElement;\n private bar: HTMLElement;\n private refsEl: HTMLElement;\n private banner: HTMLElement;\n private toastEl: HTMLElement;\n\n private path = '';\n private text = '';\n /** Latest parse. */\n private model: FileModel | null = null;\n /** What's on screen: the latest parse without syntax errors. */\n private view: FileModel | null = null;\n private layout: FileLayout = emptyLayout();\n private geom: FileGeometry | null = null;\n private hints: Record<string, Point> = {};\n\n private cam: Camera = { x: 0, y: 0, s: 1 };\n private camQueued = false;\n private movingTimer = 0;\n private anim = 0;\n private lod = -1;\n /** The camera still shows the whole file as `fit` left it: resizing the view fits it again. */\n private fittedToView = false;\n\n private els = new Map<string, { el: HTMLElement; sig: string; box: string }>();\n private edges: { key: string; from: string; to: string; el: SVGPathElement }[] = [];\n private selected: string | null = null;\n private hovered: string | null = null;\n private refsOpen = false;\n private project: CanvasProject;\n /** Errors on screen: type errors from the last resolve, or syntax errors mapped onto the last good view. */\n private diagnostics: CodeDiagnostic[] = [];\n private incomingUsages: IncomingUsage[] = [];\n /** The version changes are shown against (`setDiffBase`), and its geometry, computed once. */\n private diffBase: { model: FileModel; layout: FileLayout | null; geometry?: FileGeometry } | null = null;\n private diffCache: { view: FileModel; diff: FileDiff } | null = null;\n /** Merge conflicts in the text. The canvas then shows its current side, marking the blocks they touch. */\n private conflicts: FileConflicts | null = null;\n private ghostBlockEls: Record<'removed' | 'incoming', HTMLElement[]> = { removed: [], incoming: [] };\n /** Errors from the host (`setDiagnostics`), shown instead of the project's type errors. */\n private hostDiagnostics: HostDiagnostic[] | null = null;\n private renaming: { id: string; input: HTMLInputElement; isApplying?: boolean } | null = null;\n\n /** The layout before the last Arrange, until the next layout change: Undo arrange puts it back. */\n private layoutBeforeArrange: FileLayout | null = null;\n /** Where the camera was before the block editor moved it out of the way, and where it moved it to. */\n private cameraBeforeEditor: { before: Camera; shifted: Camera } | null = null;\n private editing: { start: number; len: number; id: string | null; handle: EditorHandle; el: HTMLElement } | null = null;\n private clip: E.BlockClip | null = null;\n\n private pointers = new Map<number, Point>();\n private gesture: Gesture = null;\n private lastTap = { t: 0, x: 0, y: 0, id: '' as string | null };\n private lastPointer: Point | null = null;\n private toastTimer = 0;\n private ro: ResizeObserver;\n private barObserver: ResizeObserver;\n private cleanup: (() => void)[] = [];\n\n constructor(\n container: HTMLElement,\n private opts: CodeCanvasOptions,\n ) {\n this.project = opts.project ?? new Project();\n injectStyles(container.ownerDocument);\n const root = (this.root = el('div', 'cc-root'));\n root.tabIndex = 0;\n root.dataset.theme = opts.theme ?? 'dark';\n this.world = el('div', 'cc-world');\n this.frameEl = el('div', 'cc-frame');\n this.blocksEl = el('div', 'cc-blocks');\n this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n this.svg.classList.add('cc-edges');\n setHTML(this.svg, `<defs>${(['import', 'class', 'function', 'variable', 'type', 'namespace', 'statement'] as const)\n .map(\n (k) =>\n `<marker id=\"cc-arrow-${k}\" viewBox=\"0 0 10 10\" refX=\"9\" refY=\"5\" markerWidth=\"7\" markerHeight=\"7\" orient=\"auto-start-reverse\"><path d=\"M0 0L10 5L0 10z\" fill=\"var(--k-${k})\"/></marker>`,\n )\n .join('')}</defs>`);\n this.world.append(this.frameEl, this.blocksEl, this.svg);\n this.banner = el('div', 'cc-banner');\n this.banner.hidden = true;\n this.toastEl = el('div', 'cc-toast');\n this.toastEl.style.opacity = '0';\n this.bar = el('div', 'cc-bar');\n this.refsEl = el('div', 'cc-refs');\n this.refsEl.hidden = true;\n root.append(this.world, this.banner, this.refsEl, this.bar, this.toastEl);\n container.appendChild(root);\n this.bindEvents();\n this.ro = new ResizeObserver(() => (this.fittedToView ? this.fit(false) : this.queueCamera()));\n this.ro.observe(root);\n // The toolbar wraps onto more rows in a narrow view: keep the panels above it.\n this.barObserver = new ResizeObserver(([entry]) => {\n const barTop = entry.borderBoxSize?.[0]?.blockSize ?? this.bar.offsetHeight;\n this.refsEl.style.bottom = barTop + 28 + 'px';\n this.toastEl.style.bottom = barTop + 40 + 'px';\n });\n this.barObserver.observe(this.bar);\n this.renderBar();\n }\n\n // ---------------------------------------------------------------- public API\n\n /** Show a file. Fits it to the view. */\n openFile(path: string, text: string, layout?: FileLayout | null) {\n this.closeEditor();\n this.path = path;\n this.text = text;\n this.layout = layout ? structuredClone(layout) : emptyLayout();\n this.model = this.view = null;\n this.selected = this.hovered = null;\n this.refsOpen = false;\n this.renaming = null;\n this.diagnostics = [];\n this.hostDiagnostics = null;\n this.diffBase = null;\n this.diffCache = null;\n this.conflicts = null;\n this.layoutBeforeArrange = null;\n this.incomingUsages = [];\n this.hints = {};\n for (const { el } of this.els.values()) el.remove();\n this.els.clear();\n this.parseNow();\n this.fit(false);\n this.renderBar();\n }\n\n /** The text changed outside the canvas (e.g. the text editor). */\n setText(text: string) {\n if (text === this.text) return;\n const isEditedByOpenEditor = !!this.editing?.handle.editsFile;\n if (isEditedByOpenEditor) this.followEditedRange(this.text, text);\n else if (this.editing) this.closeEditor();\n this.cancelRename();\n this.text = text;\n this.parseNow();\n }\n\n /**\n * Show the changes since a base version of the file (e.g. the last commit): unchanged blocks are\n * desaturated, added and changed ones get a chip, removed ones show in red where they were.\n * `layout` is the base version's saved layout, for placing removed blocks. Null hides the changes.\n */\n setDiffBase(base: { text: string; layout?: FileLayout | null } | null) {\n this.diffBase = base ? { model: parseStructure(this.path, base.text), layout: base.layout ?? null } : null;\n this.diffCache = null;\n this.render();\n this.renderBar();\n }\n\n get isShowingChanges(): boolean {\n return !!this.diffBase;\n }\n\n private conflictsOf(hunks: ConflictHunk[], current: ConflictSideText, currentModel: FileModel): FileConflicts {\n const incoming = conflictSideText(this.text, hunks, 'incoming');\n const incomingModel = parseStructure(this.path, incoming.text);\n const hunksByBlock = new Map<string, number[]>();\n const markTouched = (id: string, hunkIndex: number) => {\n const list = hunksByBlock.get(id) ?? [];\n if (!list.includes(hunkIndex)) list.push(hunkIndex);\n hunksByBlock.set(id, list);\n };\n const incomingOnly: Block[] = [];\n hunks.forEach((_, hunkIndex) => {\n for (const block of innermostBlocksTouching(currentModel, current.hunkRanges[hunkIndex])) markTouched(block.id, hunkIndex);\n for (const block of innermostBlocksTouching(incomingModel, incoming.hunkRanges[hunkIndex])) {\n // A block only the incoming side has: its outermost new block, drawn as a ghost.\n let outermostNew: Block | undefined = currentModel.blocks.has(block.id) ? undefined : block;\n while (outermostNew?.parentId && !currentModel.blocks.has(outermostNew.parentId)) outermostNew = incomingModel.blocks.get(outermostNew.parentId);\n if (!outermostNew) markTouched(block.id, hunkIndex);\n else if (!incomingOnly.includes(outermostNew)) incomingOnly.push(outermostNew);\n }\n });\n return { hunks, current, incomingModel, hunksByBlock, incomingOnly };\n }\n\n /** Resolve the conflicts that touch a block: their sections become the chosen side. */\n keepConflictSide(id: string, choice: ConflictChoice) {\n const conflicts = this.conflicts;\n const hunkIndexes = conflicts?.hunksByBlock.get(id);\n if (!conflicts || !hunkIndexes) return;\n const edits = hunkIndexes.map((index) => resolveConflict(this.text, conflicts.hunks[index], choice));\n this.commit(E.applyEdits(this.text, edits));\n const remaining = this.conflicts?.hunks.length ?? 0;\n this.toast(remaining ? `Resolved. ${plural(remaining, 'conflict')} left` : 'All conflicts in this file are resolved');\n }\n\n /** While changes are shown: the block's code in the base version, '' if it's new. */\n private baseCodeOf(block: Block | null): string | undefined {\n const diff = this.currentDiff();\n if (!diff || !block) return undefined;\n const baseBlock = diff.base.blocks.get(block.id);\n return baseBlock ? diff.base.text.slice(baseBlock.start, baseBlock.end) : '';\n }\n\n /** The changes of what's on screen, while a diff base is set. */\n private currentDiff(): FileDiff | null {\n if (!this.diffBase || !this.view) return null;\n if (this.diffCache?.view !== this.view) this.diffCache = { view: this.view, diff: diffModels(this.diffBase.model, this.view) };\n return this.diffCache.diff;\n }\n\n /**\n * Errors reported by the host, e.g. VS Code's Problems. While set, the canvas shows these instead of\n * resolving type errors itself. Pass null to go back to the project's own.\n */\n setDiagnostics(diagnostics: HostDiagnostic[] | null) {\n this.hostDiagnostics = diagnostics;\n // The conflict markers themselves are errors to the host; the conflict banner says it better.\n if (!this.view || this.stale || this.conflicts) return;\n this.diagnostics = this.hostDiagnosticsOnBlocks(this.view);\n this.updateErrorMarkers();\n this.renderBar();\n }\n\n setLayout(layout: FileLayout) {\n this.layout = structuredClone(layout);\n this.relayout();\n }\n\n getLayout(): FileLayout {\n return structuredClone(this.layout);\n }\n\n getModel(): FileModel | null {\n return this.model;\n }\n\n /** Re-resolve usages and errors, e.g. after other files of the project changed. */\n refreshProject() {\n if (this.view && !this.stale) this.scheduleUsages(this.view, true);\n }\n\n getDiagnostics(): CodeDiagnostic[] {\n return [...this.diagnostics];\n }\n\n setTheme(theme: 'dark' | 'light') {\n this.root.dataset.theme = theme;\n }\n\n get scale() {\n return this.cam.s;\n }\n\n /** Lay the whole file out again by the layout rules (layoutRules.ts), forgetting saved positions. */\n arrange() {\n if (!this.view) return;\n const before = structuredClone(this.layout);\n this.layout = { ...emptyLayout(), collapsed: this.layout.collapsed };\n this.hints = {};\n this.relayout();\n this.emitLayout('user');\n this.layoutBeforeArrange = before;\n this.fit();\n this.renderBar();\n }\n\n undoArrange() {\n const before = this.layoutBeforeArrange;\n if (!before) return;\n this.layout = before;\n this.relayout();\n this.emitLayout('user');\n this.fit();\n this.renderBar();\n }\n\n /** Fit the whole file in the view. */\n fit(animate = true) {\n if (!this.geom) return;\n const f = this.geom.frame;\n const { width: vw, height: vh } = this.root.getBoundingClientRect();\n if (!vw || !vh) {\n // Not laid out yet; try again next frame.\n requestAnimationFrame(() => this.root.isConnected && this.fit(animate));\n return;\n }\n const pad = 24;\n const bottom = 64;\n const s = clamp(Math.min((vw - pad * 2) / f.w, (vh - pad - bottom) / f.h, 1.1), MIN_SCALE, MAX_SCALE);\n const to = { s, x: (vw - f.w * s) / 2 - f.x * s, y: pad + (vh - pad - bottom - f.h * s) / 2 - f.y * s };\n this.moveCamera(to, animate);\n this.fittedToView = true;\n }\n\n zoomBy(factor: number) {\n const r = this.root.getBoundingClientRect();\n this.zoomAt({ x: r.width / 2, y: r.height / 2 }, factor, true);\n }\n\n /** Center a block and select it. */\n reveal(id: string) {\n const g = this.geom?.geo.get(id);\n if (!g) return;\n this.select(id);\n const { width: vw, height: vh } = this.root.getBoundingClientRect();\n const s = clamp(Math.min(Math.max(this.cam.s, 0.85), (vw - 80) / g.w, (vh - 160) / g.h), MIN_SCALE, 1.4);\n this.moveCamera({ s, x: vw / 2 - (g.ax + g.w / 2) * s, y: (vh - 60) / 2 - (g.ay + g.h / 2) * s }, true);\n }\n\n select(id: string | null) {\n if (id === this.selected) return;\n this.selected = id;\n if (!id) this.refsOpen = false;\n this.updateHighlight();\n this.renderBar();\n this.opts.onSelect?.((id && this.view?.blocks.get(id)) || null);\n }\n\n destroy() {\n this.closeEditor();\n this.ro.disconnect();\n this.barObserver.disconnect();\n for (const c of this.cleanup) c();\n this.root.remove();\n }\n\n // ---------------------------------------------------------------- model\n\n private usageTimer = 0;\n\n private parseNow() {\n const hunks = this.text.includes('<<<<<<<') ? findConflicts(this.text) : [];\n const currentSide = hunks.length ? conflictSideText(this.text, hunks, 'current') : null;\n // With conflict markers the text isn't TypeScript: show its current side, without the project's links.\n const m = currentSide ? parseStructure(this.path, currentSide.text, this.model) : this.project.setFile(this.path, this.text);\n this.model = m;\n this.conflicts = currentSide ? this.conflictsOf(hunks, currentSide, m) : null;\n const stale = m.syntaxErrors > 0 && this.view !== null;\n if (this.conflicts) this.diagnostics = [];\n else if (stale) this.diagnostics = this.syntaxDiagnosticsOnView(m);\n else if (m.syntaxErrors) this.diagnostics = m.diagnostics;\n else if (this.hostDiagnostics) this.diagnostics = this.hostDiagnosticsOnBlocks(m);\n else this.diagnostics = this.diagnostics.filter((d) => !d.blockId || m.blocks.has(d.blockId));\n if (!stale) {\n // Usage lines are slower to compute: keep the previous ones until typing pauses.\n if (this.view) m.usages = this.view.usages.filter((u) => m.blocks.has(u.from) && m.blocks.has(u.to));\n if (carryRenames(this.view, m, this.layout)) this.emitLayout('automatic');\n this.view = m;\n if (this.selected && !m.blocks.has(this.selected)) this.selected = null;\n if (this.editing) {\n // Follow the block being edited, even if it was renamed.\n const b = [...m.blocks.values()].find((x) => x.start === this.editing!.start);\n this.editing.id = b?.id ?? null;\n if (b && this.selected !== b.id) this.selected = b.id;\n }\n this.relayout();\n if (!this.conflicts) this.scheduleUsages(m);\n }\n const isShowingConflicts = !!this.conflicts && !stale;\n this.banner.hidden = !stale && !isShowingConflicts;\n this.banner.classList.toggle('cc-banner-conflicts', isShowingConflicts);\n if (isShowingConflicts) {\n setHTML(this.banner, `<span>${plural(this.conflicts!.hunks.length, 'merge conflict')} in this file. Select a block marked ! to keep a side, or edit it.</span>`);\n } else if (stale) {\n this.updateErrorMarkers();\n setHTML(this.banner, `<span>Syntax error on line ${m.firstErrorLine}. The diagram is paused until it's fixed.</span>`);\n if (!this.editing) {\n const b = button('Edit file', () => this.openRangeEditor(0, this.text.length, null), 'primary');\n this.banner.appendChild(b);\n }\n }\n this.renderBar();\n }\n\n /** Usage links and type errors go through the project's language service: only once typing pauses. */\n private scheduleUsages(m: FileModel, soon = false) {\n clearTimeout(this.usageTimer);\n const run = async () => {\n if (this.view !== m) return;\n const resolution = await this.project.resolve(this.path, { diagnostics: !this.hostDiagnostics });\n // The text may have changed while the project worked: that result is for an older version.\n if (this.view !== m) return;\n m.usages = resolution.usages;\n this.incomingUsages = resolution.incoming;\n this.diagnostics = this.hostDiagnostics ? this.hostDiagnosticsOnBlocks(m) : resolution.diagnostics;\n if (!this.geom) return;\n this.renderEdges();\n this.updateHighlight();\n this.updateErrorMarkers();\n this.renderBar();\n };\n const pauseMs = soon ? 0 : m.text.length < 20000 ? 30 : 180;\n this.usageTimer = window.setTimeout(() => void run(), pauseMs);\n }\n\n private hostDiagnosticsOnBlocks(model: FileModel): CodeDiagnostic[] {\n return (this.hostDiagnostics ?? []).map((d) => ({ ...d, blockId: blockAt(model, d.start)?.id ?? null }));\n }\n\n /** The text changed while an editor on the file is open: keep tracking the part of the file it shows. */\n private followEditedRange(before: string, after: string) {\n const editing = this.editing!;\n const change = changedRegion(before, after);\n const lengthChange = after.length - before.length;\n const isBeforeEditedRange = change.end <= editing.start && change.start < editing.start;\n const isInsideEditedRange = change.start >= editing.start && change.start <= editing.start + editing.len;\n if (isBeforeEditedRange) editing.start += lengthChange;\n else if (isInsideEditedRange) editing.len = Math.max(0, editing.len + lengthChange);\n }\n\n /** While the syntax is broken the last good view stays on screen: put its errors on the closest block it still has. */\n private syntaxDiagnosticsOnView(model: FileModel): CodeDiagnostic[] {\n const closestShownBlock = (id: string | null): string | null => {\n let current = id;\n while (current && !this.view?.blocks.has(current)) current = model.blocks.get(current)?.parentId ?? null;\n return current;\n };\n return model.diagnostics.map((d) => ({ ...d, blockId: closestShownBlock(d.blockId) }));\n }\n\n private get stale() {\n return !!this.model && this.model !== this.view;\n }\n\n /** Apply a text edit made on the canvas. */\n private commit(text: string, otherFiles?: OtherFileChange[]) {\n this.text = text;\n this.opts.onTextChange(text, otherFiles);\n this.parseNow();\n }\n\n private relayout() {\n if (!this.view) return;\n const g = computeGeometry(this.view, this.layout, this.hints);\n this.geom = g;\n const assigned = Object.keys(g.assigned);\n if (assigned.length) {\n // A hint is where the user created or pasted a block.\n const isPlacedByUser = assigned.some((id) => id in this.hints);\n for (const id of assigned) {\n this.layout.blocks[id] = g.assigned[id];\n delete this.hints[id];\n }\n this.emitLayout(isPlacedByUser ? 'user' : 'automatic');\n }\n this.render();\n }\n\n private emitLayout(reason: LayoutChangeReason) {\n if (reason === 'user') this.layoutBeforeArrange = null;\n this.opts.onLayoutChange(structuredClone(this.layout), reason);\n }\n\n // ---------------------------------------------------------------- rendering\n\n private render() {\n const g = this.geom;\n const view = this.view;\n if (!g || !view) return;\n const f = g.frame;\n Object.assign(this.frameEl.style, { transform: `translate(${f.x}px,${f.y}px)`, width: f.w + 'px', height: f.h + 'px' });\n setHTML(this.frameEl, `<div class=\"cc-frame-title\">${esc(this.path)}</div>${\n view.roots.length ? '' : `<div class=\"cc-empty\" style=\"left:${M.filePad}px;top:${M.filePad + M.fileHeader}px\">Empty file. Double-click (or double-tap) to create a function.</div>`\n }`);\n\n const seen = new Set<string>();\n const diff = this.currentDiff();\n for (const geo of g.order) {\n const id = geo.id;\n seen.add(id);\n let entry = this.els.get(id);\n if (geo.hidden) {\n if (entry) entry.el.style.display = 'none';\n continue;\n }\n if (!entry) {\n const e = el('div', 'cc-block');\n e.dataset.id = id;\n this.blocksEl.appendChild(e);\n entry = { el: e, sig: '', box: '' };\n this.els.set(id, entry);\n }\n const b = geo.block;\n const mini = geo.collapsed ? this.miniMap(geo) : '';\n const change = diff?.changes.get(id);\n const changedLines = change === 'changed' ? this.changedLinesPreview(diff!, b) : '';\n const isConflicted = !!this.conflicts?.hunksByBlock.has(id);\n const sig = `${b.kind}|${b.name}|${b.detail}|${b.tags.join()}|${b.preview.join('\\n')}|${b.previewMore}|${geo.collapsed}|${b.children.length}|${mini}|${change ?? ''}|${changedLines}|${isConflicted}`;\n if (sig !== entry.sig) {\n entry.sig = sig;\n entry.el.className = `cc-block k-${b.kind}${change ? ` cc-diff-${change}` : ''}${isConflicted ? ' cc-conflict' : ''}`;\n setHTML(entry.el, this.blockHTML(b, geo, mini, change, changedLines, isConflicted));\n }\n const box = `${geo.ax},${geo.ay},${geo.w},${geo.h},${b.depth}`;\n if (box !== entry.box) {\n entry.box = box;\n const s = entry.el.style;\n s.transform = `translate(${geo.ax}px,${geo.ay}px)`;\n s.width = geo.w + 'px';\n s.height = geo.h + 'px';\n s.zIndex = String(b.depth + 1);\n s.display = '';\n }\n }\n for (const [id, entry] of this.els) {\n if (!seen.has(id)) {\n entry.el.remove();\n this.els.delete(id);\n }\n }\n this.renderRemovedBlocks(diff);\n this.renderIncomingBlocks();\n this.renderEdges();\n this.updateHighlight();\n this.updateErrorMarkers();\n }\n\n /** Blocks only the incoming side of a conflict has, drawn dashed where they would go. */\n private renderIncomingBlocks() {\n const conflicts = this.conflicts;\n if (!conflicts?.incomingOnly.length || !this.geom) return this.drawGhostBlocks('incoming', [], null);\n conflicts.geometry ??= computeGeometry(conflicts.incomingModel, this.layout, {}, { resolveOverlaps: false });\n this.drawGhostBlocks('incoming', conflicts.incomingOnly, conflicts.geometry);\n }\n\n /** A changed block's preview: its changed lines with a line of context, as many as fit. */\n private changedLinesPreview(diff: FileDiff, block: Block): string {\n const lines = diffOwnCode(diff.base, diff.base.blocks.get(block.id), this.view!, block);\n const fitting = Math.max(1, block.preview.length);\n const preview = diffPreview(lines, fitting);\n const marker = { same: ' ', added: '+', removed: '\u2212' };\n const sharedIndent = Math.min(...preview.lines.map((line) => /^ */.exec(line.text)![0].length));\n const rows = preview.lines.map((line) => `<span class=\"cc-line-${line.kind}\">${marker[line.kind]} ${esc(line.text.slice(sharedIndent))}</span>`);\n const more = preview.more ? `<span class=\"cc-more\">\u2026 ${preview.more} more changed line${preview.more > 1 ? 's' : ''}</span>` : '';\n // Each row is a block of its own (for its background), so no newlines between them.\n return rows.join('') + more;\n }\n\n /** Removed blocks stay visible, in red, where they were in the base version. They can't be selected. */\n private renderRemovedBlocks(diff: FileDiff | null) {\n if (!diff?.removed.length || !this.diffBase || !this.geom) return this.drawGhostBlocks('removed', [], null);\n this.diffBase.geometry ??= computeGeometry(diff.base, this.diffBase.layout ?? this.layout, {}, { resolveOverlaps: false });\n this.drawGhostBlocks('removed', diff.removed, this.diffBase.geometry);\n }\n\n /** Blocks of another version (removed, or incoming in a conflict): drawn, but not part of this file. */\n private drawGhostBlocks(kind: 'removed' | 'incoming', ghosts: Block[], ghostGeometry: FileGeometry | null) {\n for (const ghostEl of this.ghostBlockEls[kind]) ghostEl.remove();\n this.ghostBlockEls[kind] = [];\n if (!ghostGeometry || !this.geom || !this.view) return;\n const positions = placeGhostBlocks(ghosts, ghostGeometry, this.view, this.geom);\n for (const block of ghosts) {\n const position = positions.get(block.id);\n const ghostGeo = ghostGeometry.geo.get(block.id);\n if (!position || !ghostGeo) continue;\n const ghostEl = el('div', `cc-block k-${block.kind} ${kind === 'removed' ? 'cc-diff-removed' : 'cc-conflict-incoming'}`);\n setHTML(ghostEl, this.blockHTML(block, { ...ghostGeo, collapsed: true }, '', kind));\n Object.assign(ghostEl.style, { transform: `translate(${position.x}px,${position.y}px)`, width: ghostGeo.w + 'px', height: ghostGeo.h + 'px', zIndex: String(block.depth + 1) });\n ghostEl.title = kind === 'removed' ? `${block.name}: removed` : `${block.name}: only in the incoming side of a merge conflict`;\n this.blocksEl.appendChild(ghostEl);\n this.ghostBlockEls[kind].push(ghostEl);\n }\n }\n\n /** Diagnostics grouped by the block that shows them: the innermost visible block containing each error. */\n private diagnosticsByShownBlock(): Map<string, CodeDiagnostic[]> {\n const byBlock = new Map<string, CodeDiagnostic[]>();\n const geometry = this.geom;\n if (!geometry) return byBlock;\n for (const d of this.diagnostics) {\n let geo = d.blockId ? geometry.geo.get(d.blockId) : undefined;\n while (geo?.hidden && geo.block.parentId) geo = geometry.geo.get(geo.block.parentId);\n if (!geo) continue;\n const list = byBlock.get(geo.id);\n if (list) list.push(d);\n else byBlock.set(geo.id, [d]);\n }\n return byBlock;\n }\n\n private updateErrorMarkers() {\n const byBlock = this.diagnosticsByShownBlock();\n for (const [id, { el: blockEl }] of this.els) {\n const list = byBlock.get(id);\n const head = blockEl.querySelector('.cc-head');\n let badge = head?.querySelector<HTMLElement>('.cc-err') ?? null;\n blockEl.classList.toggle('cc-has-error', !!list);\n if (!list) {\n badge?.remove();\n continue;\n }\n if (!badge && head) {\n badge = el('span', 'cc-err');\n head.insertBefore(badge, head.querySelector('.cc-fold'));\n }\n if (!badge) continue;\n badge.textContent = String(list.length);\n badge.title = list.map((d) => `Line ${d.line}: ${d.message}`).join('\\n');\n }\n }\n\n private blockHTML(b: Block, geo: Geo, mini: string, change?: BlockChange | 'removed' | 'incoming', changedLines = '', isConflicted = false): string {\n const label = blockLabel(b);\n const tags = b.tags.filter((t) => t !== label && t !== 'export' && (b.kind === 'import' || !LABEL_TAGS.has(t))).join(' ');\n const exp = b.tags.includes('export') ? '<span class=\"cc-exp\" title=\"exported\"></span>' : '';\n const isRemoved = change === 'removed' || change === 'incoming';\n const fold = b.children.length && !isRemoved ? `<button class=\"cc-fold\" title=\"${geo.collapsed ? 'Expand' : 'Collapse'}\">${geo.collapsed ? '\u25B8' : '\u25BE'}</button>` : '';\n const prev = changedLines\n ? `<pre class=\"cc-prev cc-diff-prev\">${changedLines}</pre>`\n : b.preview.length\n ? `<pre class=\"cc-prev\">${esc(b.preview.join('\\n'))}${b.previewMore ? `\\n<span class=\"cc-more\">\u2026 ${b.previewMore} more line${b.previewMore > 1 ? 's' : ''}</span>` : ''}</pre>`\n : '';\n const diffChip = (change ? DIFF_CHIPS[change] : '') + (isConflicted ? '<span class=\"cc-conflict-chip\" title=\"Merge conflict\">!</span>' : '');\n return `<div class=\"cc-head\"><span class=\"cc-kind\">${esc(label)}</span>${exp}<span class=\"cc-name\">${esc(b.name)}</span>${diffChip}<span class=\"cc-detail\">${esc(\n b.detail,\n )}</span>${tags ? `<span class=\"cc-tags\">${esc(tags)}</span>` : ''}${fold}</div>${prev}${mini ? `<div class=\"cc-mini\">${mini}</div>` : ''}`;\n }\n\n /** Faint miniature of a collapsed block's nested blocks. */\n private miniMap(geo: Geo): string {\n const kids = geo.block.children.map((c) => this.geom!.geo.get(c.id)!);\n const right = Math.max(...kids.map((k) => k.x + k.w));\n const bottom = Math.max(...kids.map((k) => k.y + k.h));\n const bw = geo.w - 24;\n const bh = 34;\n const s = Math.min(bw / right, bh / bottom);\n return kids\n .map(\n (k) =>\n `<i class=\"k-${k.block.kind}\" style=\"left:${(k.x * s).toFixed(1)}px;top:${(k.y * s).toFixed(1)}px;width:${Math.max(2, k.w * s).toFixed(1)}px;height:${Math.max(\n 2,\n k.h * s,\n ).toFixed(1)}px\"></i>`,\n )\n .join('');\n }\n\n private renderEdges() {\n const g = this.geom!;\n const view = this.view!;\n const visible = (id: string): Geo | undefined => {\n let geo = g.geo.get(id);\n while (geo?.hidden && geo.block.parentId) geo = g.geo.get(geo.block.parentId);\n return geo;\n };\n const want = new Map<string, { from: Geo; to: Geo; kind: string; usage: string; uf: string; ut: string }>();\n for (const u of view.usages) {\n if (u.toPath) continue; // in another file: listed in the references, not drawn\n const a = visible(u.from);\n const b = visible(u.to);\n if (!a || !b || a === b) continue;\n if (a.id.startsWith(b.id + '/') || b.id.startsWith(a.id + '/')) continue;\n const key = `${a.id}>${b.id}`;\n if (!want.has(key)) want.set(key, { from: a, to: b, kind: b.block.kind, usage: u.kind, uf: u.from, ut: u.to });\n }\n const old = new Map(this.edges.map((e) => [e.key, e]));\n const next: typeof this.edges = [];\n for (const [key, w] of want) {\n let e = old.get(key);\n if (e) old.delete(key);\n else {\n const p = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n this.svg.appendChild(p);\n e = { key, from: w.from.id, to: w.to.id, el: p };\n }\n e.el.setAttribute('class', `cc-edge u-${w.usage}`);\n e.el.setAttribute('stroke', `var(--k-${w.kind})`);\n e.el.setAttribute('marker-end', `url(#cc-arrow-${w.kind})`);\n e.el.setAttribute('d', edgePath(w.from, w.to));\n next.push(e);\n }\n for (const e of old.values()) e.el.remove();\n this.edges = next;\n }\n\n private updateHighlight() {\n const h = this.selected ?? this.hovered;\n const inH = (id: string) => !!h && (id === h || id.startsWith(h + '/'));\n const linked = new Set<string>();\n for (const e of this.edges) {\n const on = inH(e.from) || inH(e.to);\n e.el.classList.toggle('hl', on);\n if (on) {\n linked.add(e.from);\n linked.add(e.to);\n }\n }\n this.root.classList.toggle('has-hl', !!h);\n for (const [id, { el: e }] of this.els) {\n e.classList.toggle('cc-sel', id === this.selected);\n e.classList.toggle('cc-linked', linked.has(id) && !inH(id));\n e.classList.toggle('cc-editing', !!this.editing && id === this.editing.id);\n }\n if (this.refsOpen) this.renderRefs();\n }\n\n // ---------------------------------------------------------------- camera\n\n private queueCamera() {\n if (this.camQueued) return;\n this.camQueued = true;\n requestAnimationFrame(() => {\n this.camQueued = false;\n this.applyCamera();\n });\n }\n\n private applyCamera() {\n const { x, y, s } = this.cam;\n this.world.style.transform = `translate(${x}px,${y}px) scale(${s})`;\n const grid = 24 * s;\n this.root.style.backgroundSize = s < 0.25 ? '0 0' : `${grid}px ${grid}px`;\n this.root.style.backgroundPosition = `${x}px ${y}px`;\n const lod = s < 0.3 ? 2 : s < 0.55 ? 1 : 0;\n if (lod !== this.lod) {\n this.lod = lod;\n this.root.classList.toggle('lod-1', lod >= 1);\n this.root.classList.toggle('lod-2', lod >= 2);\n }\n // Promote to a GPU layer only while moving, so text is re-rasterized crisply once it stops.\n this.root.classList.add('cc-moving');\n clearTimeout(this.movingTimer);\n this.movingTimer = window.setTimeout(() => this.root.classList.remove('cc-moving'), 160);\n this.opts.onCameraChange?.(s);\n }\n\n private setCamera(c: Camera) {\n this.fittedToView = false;\n cancelAnimationFrame(this.anim);\n this.cam = { x: c.x, y: c.y, s: clamp(c.s, MIN_SCALE, MAX_SCALE) };\n this.queueCamera();\n }\n\n private moveCamera(to: Camera, animate: boolean) {\n this.fittedToView = false;\n cancelAnimationFrame(this.anim);\n if (!animate || matchMedia('(prefers-reduced-motion: reduce)').matches) {\n this.setCamera(to);\n return;\n }\n const from = { ...this.cam };\n const t0 = performance.now();\n const dur = 280;\n const step = (now: number) => {\n const k = Math.min(1, (now - t0) / dur);\n const e = 1 - Math.pow(1 - k, 3);\n // Interpolate scale in log space so zooming feels even.\n const s = Math.exp(Math.log(from.s) + (Math.log(to.s) - Math.log(from.s)) * e);\n this.cam = { s, x: from.x + (to.x - from.x) * e, y: from.y + (to.y - from.y) * e };\n this.applyCamera();\n if (k < 1) this.anim = requestAnimationFrame(step);\n };\n this.anim = requestAnimationFrame(step);\n }\n\n private zoomAt(p: Point, factor: number, animate = false) {\n const s = clamp(this.cam.s * factor, MIN_SCALE, MAX_SCALE);\n const wx = (p.x - this.cam.x) / this.cam.s;\n const wy = (p.y - this.cam.y) / this.cam.s;\n this.moveCamera({ s, x: p.x - wx * s, y: p.y - wy * s }, animate);\n }\n\n private toWorld(clientX: number, clientY: number): Point {\n const r = this.root.getBoundingClientRect();\n return { x: (clientX - r.left - this.cam.x) / this.cam.s, y: (clientY - r.top - this.cam.y) / this.cam.s };\n }\n\n private local(e: { clientX: number; clientY: number }): Point {\n const r = this.root.getBoundingClientRect();\n return { x: e.clientX - r.left, y: e.clientY - r.top };\n }\n\n // ---------------------------------------------------------------- hit testing\n\n /** What's under a world point: a block (header or leaf), or empty space inside a container/the file. */\n private hitTest(p: Point): { block: string | null; container: string | null } {\n const g = this.geom;\n if (!g) return { block: null, container: null };\n let hit: Geo | null = null;\n for (let i = g.order.length - 1; i >= 0; i--) {\n const geo = g.order[i];\n if (geo.hidden) continue;\n if (p.x >= geo.ax && p.x <= geo.ax + geo.w && p.y >= geo.ay && p.y <= geo.ay + geo.h) {\n if (!hit || geo.block.depth > hit.block.depth) hit = geo;\n }\n }\n if (!hit) return { block: null, container: null };\n const hasKids = hit.block.children.length > 0 && !hit.collapsed;\n if (hasKids && p.y > hit.ay + hit.contentTop) return { block: null, container: hit.id };\n return { block: hit.id, container: hit.block.parentId };\n }\n\n // ---------------------------------------------------------------- events\n\n private bindEvents() {\n const r = this.root;\n const on = <K extends keyof HTMLElementEventMap>(t: EventTarget, type: K | string, fn: (e: never) => void, o?: AddEventListenerOptions) => {\n t.addEventListener(type, fn as EventListener, o);\n this.cleanup.push(() => t.removeEventListener(type, fn as EventListener, o));\n };\n on(r, 'pointerdown', (e: PointerEvent) => this.onDown(e));\n on(r, 'pointermove', (e: PointerEvent) => this.onMove(e));\n on(r, 'pointerup', (e: PointerEvent) => this.onUp(e));\n on(r, 'pointercancel', (e: PointerEvent) => this.onUp(e, true));\n on(r, 'wheel', (e: WheelEvent) => this.onWheel(e), { passive: false });\n on(r, 'keydown', (e: KeyboardEvent) => this.onKey(e));\n on(r, 'pointerover', (e: PointerEvent) => {\n if (e.pointerType !== 'mouse' || this.gesture) return;\n const id = (e.target as Element).closest?.('.cc-block')?.getAttribute('data-id') ?? null;\n if (id !== this.hovered) {\n this.hovered = id;\n this.updateHighlight();\n }\n });\n on(r, 'pointerleave', () => {\n if (this.hovered) {\n this.hovered = null;\n this.updateHighlight();\n }\n });\n // Safari pinch gestures\n on(r, 'gesturestart', (e: Event) => e.preventDefault());\n const doc = r.ownerDocument;\n on(doc, 'copy', (e: ClipboardEvent) => this.onClipboard(e, 'copy'));\n on(doc, 'cut', (e: ClipboardEvent) => this.onClipboard(e, 'cut'));\n on(doc, 'paste', (e: ClipboardEvent) => this.onClipboard(e, 'paste'));\n }\n\n private isOverlay(t: EventTarget | null) {\n return !!(t as Element)?.closest?.('.cc-editor, .cc-bar, .cc-refs, .cc-banner, .cc-rename');\n }\n\n private onDown(e: PointerEvent) {\n if (this.isOverlay(e.target)) return;\n if (e.pointerType === 'mouse' && e.button !== 0 && e.button !== 1) return;\n this.root.focus({ preventScroll: true });\n this.root.setPointerCapture(e.pointerId);\n this.pointers.set(e.pointerId, this.local(e));\n if (this.pointers.size === 2) {\n // Pinch: abandon a drag in progress.\n if (this.gesture?.t === 'drag') this.endDrag(false);\n const [a, b] = [...this.pointers.values()];\n this.gesture = { t: 'pinch', d0: Math.hypot(a.x - b.x, a.y - b.y), m0: mid(a, b), cam: { ...this.cam } };\n return;\n }\n if (this.pointers.size > 2) return;\n const p = this.local(e);\n if (e.button === 1) {\n this.gesture = { t: 'pan', id: e.pointerId, sx: p.x, sy: p.y, cam: { ...this.cam } };\n return;\n }\n this.gesture = { t: 'pending', id: e.pointerId, sx: p.x, sy: p.y, touch: e.pointerType !== 'mouse', target: e.target as Element };\n }\n\n private onMove(e: PointerEvent): void {\n const p = this.local(e);\n if (e.pointerType === 'mouse') this.lastPointer = this.toWorld(e.clientX, e.clientY);\n if (!this.pointers.has(e.pointerId)) return;\n this.pointers.set(e.pointerId, p);\n const g = this.gesture;\n if (!g) return;\n if (g.t === 'pinch') {\n if (this.pointers.size < 2) return;\n const [a, b] = [...this.pointers.values()];\n const d = Math.hypot(a.x - b.x, a.y - b.y);\n const m = mid(a, b);\n const s = clamp(g.cam.s * (d / g.d0), MIN_SCALE, MAX_SCALE);\n const wx = (g.m0.x - g.cam.x) / g.cam.s;\n const wy = (g.m0.y - g.cam.y) / g.cam.s;\n this.setCamera({ s, x: m.x - wx * s, y: m.y - wy * s });\n return;\n }\n if (g.id !== e.pointerId) return;\n const dx = p.x - g.sx;\n const dy = p.y - g.sy;\n if (g.t === 'pending') {\n if (Math.hypot(dx, dy) < (g.touch ? 8 : 4)) return;\n const w = this.toWorld(e.clientX - dx, e.clientY - dy);\n const hit = g.target?.closest('.cc-fold') ? { block: null } : this.hitTest(w);\n const geo = hit.block ? this.geom!.geo.get(hit.block) : null;\n if (geo && !this.stale) {\n this.gesture = { t: 'drag', id: g.id, sx: g.sx, sy: g.sy, block: geo.id, orig: { x: geo.x, y: geo.y }, nested: !!geo.block.parentId };\n this.els.get(geo.id)?.el.classList.add('cc-dragging');\n this.hovered = geo.id;\n } else {\n this.gesture = { t: 'pan', id: g.id, sx: g.sx, sy: g.sy, cam: { ...this.cam } };\n }\n return this.onMove(e);\n }\n if (g.t === 'pan') {\n this.setCamera({ ...g.cam, x: g.cam.x + dx, y: g.cam.y + dy });\n } else if (g.t === 'drag') {\n let x = g.orig.x + dx / this.cam.s;\n let y = g.orig.y + dy / this.cam.s;\n if (g.nested) (x = Math.max(0, x)), (y = Math.max(0, y));\n this.layout.blocks[g.block] = { x: Math.round(x), y: Math.round(y) };\n if (!this.camQueued) this.relayoutSoon();\n }\n }\n\n private relayoutQueued = false;\n private relayoutSoon() {\n if (this.relayoutQueued) return;\n this.relayoutQueued = true;\n requestAnimationFrame(() => {\n this.relayoutQueued = false;\n if (!this.view) return;\n // While dragging, don't push other blocks around; the drop finds a free spot instead.\n this.geom = computeGeometry(this.view, this.layout, this.hints, { resolveOverlaps: false });\n this.render();\n });\n }\n\n private onUp(e: PointerEvent, cancelled = false) {\n if (!this.pointers.has(e.pointerId)) return;\n this.pointers.delete(e.pointerId);\n const g = this.gesture;\n if (!g) return;\n if (g.t === 'pinch') {\n if (this.pointers.size === 0) this.gesture = null;\n else {\n // One finger left: continue as a pan from here.\n const [id, p] = [...this.pointers.entries()][0];\n this.gesture = { t: 'pan', id, sx: p.x, sy: p.y, cam: { ...this.cam } };\n }\n return;\n }\n if (g.id !== e.pointerId) return;\n if (g.t === 'drag') return this.endDrag(!cancelled);\n this.gesture = null;\n if (g.t !== 'pending' || cancelled) return;\n this.onTap(e, g.target);\n }\n\n private endDrag(commit: boolean) {\n const g = this.gesture?.t === 'drag' ? this.gesture : null;\n this.gesture = null;\n if (!g) return;\n this.els.get(g.block)?.el.classList.remove('cc-dragging');\n if (!commit) {\n this.layout.blocks[g.block] = g.orig;\n this.relayout();\n return;\n }\n // Drop: nudge to the nearest free spot so blocks never end up on top of each other.\n const geom = computeGeometry(this.view!, this.layout, this.hints, { resolveOverlaps: false });\n const geo = geom.geo.get(g.block);\n if (geo) {\n const parent = geo.block.parentId;\n const sibs = [...geom.geo.values()].filter((s) => s.block.parentId === parent && s.id !== g.block);\n this.layout.blocks[g.block] = freeSpotNear({ x: geo.x, y: geo.y }, geo, sibs, !!parent);\n }\n this.relayout();\n this.emitLayout('user');\n }\n\n private onTap(e: PointerEvent, target: Element | null) {\n const fold = target?.closest('.cc-fold');\n const w = this.toWorld(e.clientX, e.clientY);\n const hit = this.hitTest(w);\n const now = performance.now();\n const p = this.local(e);\n const dbl = now - this.lastTap.t < 350 && Math.hypot(p.x - this.lastTap.x, p.y - this.lastTap.y) < 24 && this.lastTap.id === (hit.block ?? '@' + hit.container);\n this.lastTap = { t: dbl ? 0 : now, x: p.x, y: p.y, id: hit.block ?? '@' + hit.container };\n if (fold && hit.block) return this.toggleCollapse(hit.block);\n if (hit.block) {\n // First click selects (shows usage lines), clicking the selected block edits it.\n if (this.selected === hit.block && !this.editing) return this.openEditor(hit.block);\n if (this.editing && this.editing.id !== hit.block) this.closeEditor();\n this.select(hit.block);\n return;\n }\n // Empty space: double-click creates a function there.\n if (dbl) return this.createFunctionAt(w, hit.container);\n if (this.editing) this.closeEditor();\n this.select(hit.container);\n }\n\n private onWheel(e: WheelEvent) {\n if (this.isOverlay(e.target)) return;\n e.preventDefault();\n const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? 400 : 1;\n const p = this.local(e);\n if (e.ctrlKey || e.metaKey) {\n this.zoomAt(p, Math.exp(-e.deltaY * unit * 0.0025));\n } else {\n const dx = (e.shiftKey && !e.deltaX ? e.deltaY : e.deltaX) * unit;\n const dy = (e.shiftKey && !e.deltaX ? 0 : e.deltaY) * unit;\n this.setCamera({ ...this.cam, x: this.cam.x - dx, y: this.cam.y - dy });\n }\n }\n\n private onKey(e: KeyboardEvent) {\n // The block editor may have handled the key (Escape) and removed itself from the page already.\n const isHandledByEditor = e.defaultPrevented;\n if (isHandledByEditor || (this.isOverlay(e.target) && e.target !== this.root)) return;\n const mod = e.metaKey || e.ctrlKey;\n const k = e.key;\n if (mod && k.toLowerCase() === 'z') {\n e.preventDefault();\n return e.shiftKey ? this.opts.onRedo?.() : this.opts.onUndo?.();\n }\n if (mod && k.toLowerCase() === 'y') {\n e.preventDefault();\n return this.opts.onRedo?.();\n }\n if (mod && k.toLowerCase() === 'd' && this.selected) {\n e.preventDefault();\n return this.duplicate(this.selected);\n }\n if (mod) return;\n if (k === 'Escape') return this.editing ? this.closeEditor() : this.select(null);\n if (k === 'Enter' && this.selected) {\n e.preventDefault();\n return this.openEditor(this.selected);\n }\n if (k === 'F2' && this.selected) {\n e.preventDefault();\n return this.startRename(this.selected);\n }\n if ((k === 'Delete' || k === 'Backspace') && this.selected) {\n e.preventDefault();\n return this.deleteBlock(this.selected);\n }\n if (k === '0' || k === '!') return this.fit();\n if (k === '=' || k === '+') return this.zoomBy(1.25);\n if (k === '-' || k === '_') return this.zoomBy(0.8);\n if (k === 'n' || k === 'N') return this.createFunctionAtCenter();\n if (k === 'r' && this.selected) {\n this.refsOpen = !this.refsOpen;\n return this.renderBar();\n }\n }\n\n private onClipboard(e: ClipboardEvent, type: 'copy' | 'cut' | 'paste') {\n const active = this.root.ownerDocument.activeElement;\n if (active !== this.root) return;\n if (type === 'paste') {\n const custom = e.clipboardData?.getData('application/x-codecanvas');\n const textData = e.clipboardData?.getData('text/plain');\n let clip: E.BlockClip | null = null;\n if (custom) {\n try {\n clip = JSON.parse(custom);\n } catch {}\n }\n if (!clip && textData) clip = E.clipFromText(textData);\n if (clip) {\n e.preventDefault();\n this.paste(clip);\n }\n return;\n }\n if (!this.selected || !this.view || this.stale) return;\n const clip = E.copyBlock(this.view, this.selected);\n this.clip = clip;\n e.clipboardData?.setData('text/plain', clip.code);\n e.clipboardData?.setData('application/x-codecanvas', JSON.stringify(clip));\n e.preventDefault();\n if (type === 'cut') this.deleteBlock(this.selected);\n else this.toast(`Copied ${clip.name || 'block'}`);\n this.renderBar();\n }\n\n // ---------------------------------------------------------------- actions\n\n private guard(): boolean {\n if (this.stale || !this.view) {\n this.toast(`Fix the syntax error on line ${this.model?.firstErrorLine} first`);\n return false;\n }\n return true;\n }\n\n /** Edits that add, remove or rename blocks work on the text's structure, which conflicts break. */\n private guardStructureEdit(): boolean {\n if (!this.guard()) return false;\n if (this.conflicts) {\n this.toast('Resolve the merge conflicts in this file first');\n return false;\n }\n return true;\n }\n\n private toggleCollapse(id: string) {\n const set = new Set(this.layout.collapsed ?? []);\n if (set.has(id)) set.delete(id);\n else set.add(id);\n this.layout.collapsed = [...set];\n this.relayout();\n this.emitLayout('user');\n }\n\n private createFunctionAt(w: Point, containerId: string | null) {\n if (!this.guardStructureEdit()) return;\n const view = this.view!;\n const container = E.containerFor(view, containerId);\n const r = E.newFunction(view, container?.id ?? null);\n this.hints[r.id] = this.relativeTo(container?.id ?? null, { x: w.x - 24, y: w.y - 16 });\n this.applyInsert(r);\n }\n\n private createFunctionAtCenter() {\n const rect = this.root.getBoundingClientRect();\n const w = this.toWorld(rect.left + rect.width / 2, rect.top + rect.height / 2);\n const target = this.selected ? E.containerFor(this.view!, this.selected)?.id ?? null : this.hitTest(w).container;\n if (target) {\n const g = this.geom!.geo.get(target)!;\n return this.createFunctionAt({ x: g.ax + M.pad + 24, y: g.ay + g.h }, target);\n }\n this.createFunctionAt(w, null);\n }\n\n /** Convert a world point into coordinates relative to a container's content origin. */\n private relativeTo(containerId: string | null, w: Point): Point {\n if (!containerId) return { x: Math.round(w.x), y: Math.round(w.y) };\n const g = this.geom!.geo.get(containerId)!;\n return { x: Math.max(0, Math.round(w.x - g.ax - M.pad)), y: Math.max(0, Math.round(w.y - g.ay - g.contentTop)) };\n }\n\n private applyInsert(r: E.InsertResult, edit = true) {\n this.commit(E.applyEdit(this.text, r.edit));\n if (r.id && this.view?.blocks.has(r.id)) {\n this.select(r.id);\n if (edit) this.openEditor(r.id, r.select);\n }\n }\n\n private deleteBlock(id: string) {\n if (!this.guardStructureEdit()) return;\n const b = this.view!.blocks.get(id);\n if (!b) return;\n if (this.editing) this.closeEditor();\n this.select(b.parentId);\n this.commit(E.applyEdit(this.text, E.deleteBlock(this.view!, id)));\n this.toast(`Deleted ${b.name}. Undo with ${isMac() ? '\u2318' : 'Ctrl'}+Z`);\n }\n\n private duplicate(id: string) {\n if (!this.guardStructureEdit()) return;\n const view = this.view!;\n const b = view.blocks.get(id);\n if (!b || b.kind === 'import' || b.kind === 'statement') return;\n const clip = E.copyBlock(view, id);\n const r = E.pasteBlock(view, b.parentId, clip);\n const geo = this.geom!.geo.get(id)!;\n if (r.id) this.hints[r.id] = { x: geo.x + 24, y: geo.y + geo.h + M.gap };\n this.applyInsert(r, false);\n }\n\n private copy(id: string) {\n if (!this.view || this.stale) return;\n this.clip = E.copyBlock(this.view, id);\n navigator.clipboard?.writeText(this.clip.code).catch(() => {});\n this.toast(`Copied ${this.clip.name}`);\n this.renderBar();\n }\n\n private paste(clip: E.BlockClip | null = this.clip) {\n if (!clip || !this.guardStructureEdit()) return;\n const view = this.view!;\n // Paste where the pointer is, or into the selected container.\n let target: string | null = null;\n let at: Point | null = null;\n if (this.lastPointer) {\n const hit = this.hitTest(this.lastPointer);\n target = hit.block ? E.containerFor(view, hit.block)?.id ?? null : hit.container;\n at = this.lastPointer;\n } else if (this.selected) {\n target = E.containerFor(view, this.selected)?.id ?? null;\n }\n const r = E.pasteBlock(view, target, clip);\n if (r.id && at) this.hints[r.id] = this.relativeTo(target, { x: at.x - 24, y: at.y - 16 });\n this.applyInsert(r, false);\n }\n\n // ---------------------------------------------------------------- rename\n\n /** Show a name field in the block's header. Enter renames the block and its usages in every file. */\n startRename(id: string) {\n if (!this.guardStructureEdit()) return;\n const block = this.view!.blocks.get(id);\n if (!block) return;\n if (!isRenamable(block)) return this.toast(`${block.name} can't be renamed`);\n if (this.editing) this.closeEditor();\n this.cancelRename();\n this.select(id);\n // The field is drawn at canvas scale: zoom in first if it would be too small to read.\n if (this.cam.s < 0.6) this.reveal(id);\n const nameEl = this.els.get(id)?.el.querySelector('.cc-name');\n if (!nameEl) return;\n const input = document.createElement('input');\n input.className = 'cc-rename';\n input.value = block.name;\n input.spellcheck = false;\n input.setAttribute('aria-label', `New name for ${block.name}`);\n const fitWidth = () => (input.style.width = `${Math.max(input.value.length, 4) + 2}ch`);\n fitWidth();\n input.addEventListener('input', () => {\n fitWidth();\n input.classList.remove('invalid');\n });\n input.addEventListener('keydown', (e) => {\n e.stopPropagation();\n if (e.key === 'Enter') {\n e.preventDefault();\n this.commitRename();\n } else if (e.key === 'Escape') {\n e.preventDefault();\n this.cancelRename();\n this.root.focus({ preventScroll: true });\n }\n });\n input.addEventListener('blur', () => this.cancelRename());\n nameEl.replaceChildren(input);\n this.renaming = { id, input };\n input.focus({ preventScroll: true });\n input.select();\n }\n\n private cancelRename() {\n const renaming = this.renaming;\n if (!renaming) return;\n this.renaming = null;\n const name = this.view?.blocks.get(renaming.id)?.name ?? '';\n renaming.input.parentElement?.replaceChildren(document.createTextNode(name));\n }\n\n private async commitRename() {\n const renaming = this.renaming;\n const block = renaming && this.view?.blocks.get(renaming.id);\n if (!renaming || !block) return this.cancelRename();\n if (renaming.isApplying) return;\n const newName = renaming.input.value.trim();\n if (newName === block.name) {\n this.cancelRename();\n return this.root.focus({ preventScroll: true });\n }\n renaming.isApplying = true;\n const textAtRequest = this.text;\n const result = await this.project.renameBlock(this.path, block.id, newName);\n renaming.isApplying = false;\n if (this.renaming !== renaming) return; // cancelled meanwhile\n if (this.text !== textAtRequest) {\n // The edits are offsets into the text the project saw.\n renaming.input.classList.add('invalid');\n return this.toast('The file changed. Press Enter to rename again');\n }\n if (!result.ok) {\n renaming.input.classList.add('invalid');\n return this.toast(result.error);\n }\n // Cleared first: re-rendering the block removes the field, which fires its blur.\n this.renaming = null;\n const ownEdits = result.edits[this.path] ?? [];\n const shiftBeforeBlock = ownEdits.filter((e) => e.end <= block.start).reduce((sum, e) => sum + e.text.length - (e.end - e.start), 0);\n const otherPaths = Object.keys(result.edits).filter((path) => path !== this.path);\n const otherFiles = otherPaths.map((path): OtherFileChange => {\n const previousModel = this.project.getModel(path);\n const before = this.project.getText(path) ?? '';\n const after = E.applyEdits(before, result.edits[path]);\n this.project.setFile(path, after);\n return { path, before, after, previousModel };\n });\n this.commit(E.applyEdits(this.text, ownEdits), otherFiles.length ? otherFiles : undefined);\n const renamed = [...(this.view?.blocks.values() ?? [])].find((b) => b.start === block.start + shiftBeforeBlock && b.name === newName);\n if (renamed) this.select(renamed.id);\n this.root.focus({ preventScroll: true });\n this.toast(otherPaths.length ? `Renamed to ${newName} in ${otherPaths.length + 1} files` : `Renamed to ${newName}`);\n }\n\n // ---------------------------------------------------------------- inline editor\n\n openEditor(id: string, selection?: [number, number]) {\n if (!this.guard()) return;\n const b = this.view!.blocks.get(id);\n if (!b) return;\n if (this.conflicts) {\n // The block's real text, conflict markers included, so both sides can be merged by hand.\n const touching = (this.conflicts.hunksByBlock.get(id) ?? []).map((index) => this.conflicts!.hunks[index]);\n const start = Math.min(this.conflicts.current.toFileOffset(b.start), ...touching.map((hunk) => hunk.start));\n const end = Math.max(this.conflicts.current.toFileOffset(b.end), ...touching.map((hunk) => hunk.end));\n return this.openRangeEditor(start, end, b);\n }\n this.openRangeEditor(b.start, b.end, b, selection);\n }\n\n private openRangeEditor(start: number, end: number, b: Block | null, selection?: [number, number]) {\n this.closeEditor({ restoreCamera: false });\n this.refsOpen = false;\n const panel = el('div', 'cc-editor');\n const head = el('div', 'cc-editor-head');\n const chip = el('div', 'cc-chip');\n chip.classList.add(`k-${b?.kind ?? 'statement'}`);\n chip.style.setProperty('--k', `var(--k-${b?.kind ?? 'statement'})`);\n setHTML(chip, `<i></i><span>${esc(b ? b.name : this.path)}</span>`);\n const hint = el('span', 'cc-editor-hint');\n hint.textContent = 'Esc to close';\n head.append(chip, hint, button('Done', () => this.closeEditor(), 'primary'));\n const body = el('div', 'cc-editor-body');\n panel.append(head, body);\n this.root.appendChild(panel);\n\n const code = this.text.slice(start, end);\n const lines = code.split('\\n').length;\n const { width: vw, height: vh } = this.root.getBoundingClientRect();\n const mobile = vw < 700;\n if (mobile) {\n Object.assign(panel.style, { left: '0', right: '0', bottom: '0', height: Math.round(vh * 0.52) + 'px', borderRadius: '14px 14px 0 0' });\n } else {\n const w = Math.min(640, vw - 32);\n const h = Math.min(vh - 32, Math.max(160, lines * 19 + 70));\n Object.assign(panel.style, { right: '16px', top: '16px', width: w + 'px', height: h + 'px' });\n }\n // Keep the block visible next to (or above) the editor.\n if (b) {\n const g = this.geom?.geo.get(b.id);\n if (g) {\n const s = this.cam.s;\n const sx = g.ax * s + this.cam.x;\n const sy = g.ay * s + this.cam.y;\n let dx = 0,\n dy = 0;\n if (mobile) {\n const avail = vh * 0.48;\n if (sy < 12 || sy > avail - 60) dy = 24 - sy;\n if (sx < 12 || sx + Math.min(g.w * s, vw) > vw) dx = 16 - sx;\n } else {\n const right = vw - Math.min(640, vw - 32) - 32;\n if (sx + g.w * s > right) dx = Math.max(right - (sx + g.w * s), 24 - sx);\n if (sx + dx < 12) dx = 24 - sx;\n if (sy < 12 || sy > vh - 80) dy = 40 - sy;\n }\n if (dx || dy) {\n const shifted = { ...this.cam, x: this.cam.x + dx, y: this.cam.y + dy };\n // Switching to another block's editor keeps the first camera: closing goes back to it.\n this.cameraBeforeEditor = { before: this.cameraBeforeEditor?.before ?? { ...this.cam }, shifted };\n this.moveCamera(shifted, true);\n }\n }\n }\n const handle = this.opts.createEditor({\n parent: body,\n text: code,\n start,\n end,\n selection,\n diffBase: this.conflicts ? undefined : this.baseCodeOf(b),\n onChange: (t) => this.onEditorChange(t),\n onClose: () => {\n this.closeEditor();\n this.root.focus({ preventScroll: true });\n },\n });\n this.editing = { start, len: code.length, id: b?.id ?? null, handle, el: panel };\n if (b) this.selected = b.id;\n this.banner.querySelector('button')?.remove();\n this.updateHighlight();\n this.renderBar();\n handle.focus();\n }\n\n private onEditorChange(code: string) {\n const ed = this.editing;\n if (!ed) return;\n const text = this.text.slice(0, ed.start) + code + this.text.slice(ed.start + ed.len);\n ed.len = code.length;\n this.commit(text);\n }\n\n closeEditor({ restoreCamera = true }: { restoreCamera?: boolean } = {}) {\n const ed = this.editing;\n if (!ed) return;\n this.editing = null;\n const cameraBeforeEditor = this.cameraBeforeEditor;\n if (restoreCamera) {\n this.cameraBeforeEditor = null;\n // Back to where the canvas was before the editor moved it, unless the user moved it since.\n const isStillWhereEditorPutIt = !!cameraBeforeEditor && Math.abs(this.cam.x - cameraBeforeEditor.shifted.x) < 1 && Math.abs(this.cam.y - cameraBeforeEditor.shifted.y) < 1 && this.cam.s === cameraBeforeEditor.shifted.s;\n if (isStillWhereEditorPutIt) this.moveCamera(cameraBeforeEditor.before, true);\n }\n ed.handle.destroy();\n ed.el.remove();\n if (this.stale) this.parseNow(); // re-show the \"Edit file\" button\n this.updateHighlight();\n this.renderBar();\n }\n\n // ---------------------------------------------------------------- toolbar & references\n\n private renderBar() {\n const bar = this.bar;\n bar.replaceChildren();\n bar.hidden = !!this.editing;\n const b = this.selected ? this.view?.blocks.get(this.selected) : null;\n if (b) {\n const chip = el('div', 'cc-chip');\n chip.style.setProperty('--k', `var(--k-${b.kind})`);\n setHTML(chip, `<i></i>${esc(b.name)}`);\n const refs = this.refsFor(b.id);\n const errors = this.diagnosticsInside(b.id);\n if (this.conflicts) {\n const isConflicted = this.conflicts.hunksByBlock.has(b.id);\n const firstHunk = isConflicted ? this.conflicts.hunks[this.conflicts.hunksByBlock.get(b.id)![0]] : undefined;\n const keep = (label: string, choice: ConflictChoice, side?: string) => {\n const keepButton = button(label, () => this.keepConflictSide(b.id, choice), choice === 'current' ? 'primary' : undefined);\n if (side) keepButton.title = side;\n return keepButton;\n };\n bar.append(\n chip,\n el('div', 'cc-sep'),\n ...(firstHunk ? [keep('Keep current', 'current', firstHunk.currentLabel), keep('Keep incoming', 'incoming', firstHunk.incomingLabel), keep('Keep both', 'both'), el('div', 'cc-sep')] : []),\n button('Edit', () => this.openEditor(b.id)),\n button('Copy', () => this.copy(b.id)),\n );\n return this.renderRefs();\n }\n bar.append(\n chip,\n el('div', 'cc-sep'),\n ...(errors.length ? [button(plural(errors.length, 'error'), () => this.toggleRefs(), 'danger')] : []),\n button('Edit', () => this.openEditor(b.id)),\n ...(isRenamable(b) ? [button('Rename', () => this.startRename(b.id))] : []),\n button(`Refs ${refs.incoming.length + refs.outgoing.length}`, () => this.toggleRefs()),\n button('Copy', () => this.copy(b.id)),\n ...(b.kind !== 'import' && b.kind !== 'statement' ? [button('Duplicate', () => this.duplicate(b.id))] : []),\n ...(b.insert ? [button('+ Inside', () => this.createFunctionAtCenter())] : []),\n button('Delete', () => this.deleteBlock(b.id), 'danger'),\n );\n } else {\n const firstErrorBlock = this.diagnostics.find((d) => d.blockId)?.blockId;\n if (firstErrorBlock) bar.append(button(plural(this.diagnostics.length, 'error'), () => this.showErrorsOf(firstErrorBlock), 'danger'));\n const diff = this.currentDiff();\n if (diff) bar.append(changesSummary(diff), el('div', 'cc-sep'));\n bar.append(button('+ Function', () => this.createFunctionAtCenter()));\n if (this.clip) bar.append(button('Paste', () => (this.lastPointer = null, this.paste())));\n bar.append(\n this.layoutBeforeArrange ? button('Undo arrange', () => this.undoArrange()) : button('Arrange', () => this.arrange()),\n el('div', 'cc-sep'),\n button('Fit', () => this.fit()),\n button('\u2212', () => this.zoomBy(0.8)),\n button('+', () => this.zoomBy(1.25)),\n );\n }\n this.renderRefs();\n }\n\n private toggleRefs() {\n this.refsOpen = !this.refsOpen;\n this.renderBar();\n }\n\n private showErrorsOf(id: string) {\n this.reveal(id);\n this.refsOpen = true;\n this.renderBar();\n }\n\n private diagnosticsInside(id: string): CodeDiagnostic[] {\n return this.diagnostics.filter((d) => d.blockId === id || !!d.blockId?.startsWith(id + '/'));\n }\n\n private refsFor(id: string): { incoming: (Usage | IncomingUsage)[]; outgoing: Usage[] } {\n const usages = this.view?.usages ?? [];\n const inside = (x: string) => x === id || x.startsWith(id + '/');\n // An import link is replaced by the specific blocks it reaches in the other file.\n const importsReachedElsewhere = new Set(usages.filter((u) => u.toPath && u.via).map((u) => `${u.from}>${u.via}`));\n const isImportLinkWithTargets = (u: Usage) => !u.toPath && importsReachedElsewhere.has(`${u.from}>${u.to}`);\n return {\n incoming: [...usages.filter((u) => !u.toPath && inside(u.to) && !inside(u.from)), ...this.incomingUsages.filter((u) => inside(u.to))],\n outgoing: usages.filter((u) => inside(u.from) && (u.toPath || !inside(u.to)) && !isImportLinkWithTargets(u)),\n };\n }\n\n private renderRefs() {\n const panel = this.refsEl;\n const selected = this.selected ? this.view?.blocks.get(this.selected) : null;\n panel.hidden = !this.refsOpen || !selected || !!this.editing;\n if (panel.hidden || !selected) return;\n const { incoming, outgoing } = this.refsFor(selected.id);\n const errors = this.diagnosticsInside(selected.id);\n const heading = (text: string) => Object.assign(el('h4'), { textContent: text });\n const note = (text: string) => Object.assign(el('div', 'none'), { textContent: text });\n const row = (path: string | undefined, blockId: string, usage: Usage) => {\n const isOtherFile = !!path && path !== this.path;\n const model = isOtherFile ? this.project.getModel(path) : this.view;\n const block = model?.blocks.get(blockId);\n const btn = keepsCanvasFocus(document.createElement('button'));\n btn.style.setProperty('--k', `var(--k-${block?.kind ?? 'statement'})`);\n const name = block && model ? displayName(model, block) : blockId;\n const label = isOtherFile ? `<span class=\"cc-file\">${esc(fileName(path))} \u203A</span> ${esc(name)}` : esc(name);\n setHTML(btn, `<i></i><span>${label}</span><span>${usage.kind}${usage.count > 1 ? ' \u00D7' + usage.count : ''}</span>`);\n btn.onclick = () => (isOtherFile ? this.opts.onOpenBlock?.(path, blockId) : this.reveal(blockId));\n btn.disabled = isOtherFile && !this.opts.onOpenBlock;\n return btn;\n };\n panel.replaceChildren();\n if (errors.length) {\n panel.append(heading(`Errors (${errors.length})`));\n for (const d of errors) {\n const btn = keepsCanvasFocus(document.createElement('button'));\n btn.className = 'cc-error-row';\n setHTML(btn, `<i></i><span>${esc(d.message)}</span><span>line ${d.line}</span>`);\n btn.onclick = () => this.openEditorAtDiagnostic(d);\n panel.append(btn);\n }\n }\n panel.append(heading(`Used by (${incoming.length})`));\n if (incoming.length) for (const u of incoming) panel.append(row('fromPath' in u ? u.fromPath : undefined, u.from, u));\n else panel.append(note('Not used anywhere'));\n panel.append(heading(`Uses (${outgoing.length})`));\n if (outgoing.length) for (const u of outgoing) panel.append(row(u.toPath, u.to, u));\n else panel.append(note('Uses nothing from this project'));\n }\n\n private openEditorAtDiagnostic(d: CodeDiagnostic) {\n if (this.stale) return this.openRangeEditor(0, this.text.length, null, [d.start, d.start + d.length]);\n const block = d.blockId ? this.view?.blocks.get(d.blockId) : undefined;\n if (!block) return;\n const offset = d.start - block.start;\n this.openEditor(block.id, [offset, offset + d.length]);\n }\n\n private toast(msg: string) {\n this.toastEl.textContent = msg;\n this.toastEl.style.opacity = '1';\n clearTimeout(this.toastTimer);\n this.toastTimer = window.setTimeout(() => (this.toastEl.style.opacity = '0'), 2200);\n }\n}\n\n// ---------------------------------------------------------------- helpers\n\n/** Small label at the start of a block header: `fn`, `class`, `const`, `interface`, `get`\u2026 */\nfunction blockLabel(b: Block): string {\n if (b.kind === 'function') return b.tags.find((t) => t === 'get' || t === 'set') ?? 'fn';\n if (b.kind === 'variable' || b.kind === 'type') return b.tags.find((t) => LABEL_TAGS.has(t)) ?? KIND_LABEL[b.kind];\n return KIND_LABEL[b.kind];\n}\n\ninterface FileConflicts {\n hunks: ConflictHunk[];\n /** The text the canvas shows: each conflict replaced by its current side. */\n current: ConflictSideText;\n incomingModel: FileModel;\n /** Blocks each conflict touches (innermost ones), by block id: indexes into `hunks`. */\n hunksByBlock: Map<string, number[]>;\n /** Outermost blocks only the incoming side has. */\n incomingOnly: Block[];\n geometry?: FileGeometry;\n}\n\n/** The innermost blocks whose text overlaps `range` (or contains it, when it's empty). */\nfunction innermostBlocksTouching(model: FileModel, range: ConflictSide): Block[] {\n // An empty side (code only the other side has) touches a block only from inside, e.g. a class it's added to.\n const touches = (block: Block) => (range.start === range.end ? block.start < range.start && range.start < block.end : block.start < range.end && range.start < block.end);\n const found: Block[] = [];\n const visit = (blocks: Block[]) => {\n for (const block of blocks.filter(touches)) {\n const touchingChildren = block.children.filter(touches);\n if (touchingChildren.length) visit(block.children);\n else found.push(block);\n }\n };\n visit(model.roots);\n return found;\n}\n\n/** The part of `before` that differs from `after`: `before.slice(start, end)` became the rest. */\nfunction changedRegion(before: string, after: string): { start: number; end: number } {\n let start = 0;\n const shorter = Math.min(before.length, after.length);\n while (start < shorter && before.charCodeAt(start) === after.charCodeAt(start)) start++;\n let fromEnd = 0;\n while (fromEnd < shorter - start && before.charCodeAt(before.length - 1 - fromEnd) === after.charCodeAt(after.length - 1 - fromEnd)) fromEnd++;\n return { start, end: before.length - fromEnd };\n}\n\nfunction isRenamable(b: Block): boolean {\n return b.nameStart >= 0 && b.kind !== 'import' && b.kind !== 'statement' && b.name !== 'constructor';\n}\n\n/** `Cart.total`, `import ./pricing` */\nfunction displayName(model: FileModel, b: Block): string {\n if (b.kind === 'import') return 'import ' + b.name;\n const names = [b.name];\n let parent = b.parentId ? model.blocks.get(b.parentId) : null;\n while (parent) {\n names.unshift(parent.name);\n parent = parent.parentId ? model.blocks.get(parent.parentId) : null;\n }\n return names.join('.');\n}\n\nfunction fileName(path: string): string {\n return path.slice(path.lastIndexOf('/') + 1);\n}\n\nfunction changesSummary(diff: FileDiff): HTMLElement {\n const changes = [...diff.changes.values()];\n const counts = [\n [changes.filter((change) => change === 'changed').length, 'changed'],\n [changes.filter((change) => change === 'added').length, 'added'],\n [diff.removed.length, 'removed'],\n ] as const;\n const parts = counts.filter(([count]) => count > 0).map(([count, word]) => `${count} ${word}`);\n return Object.assign(el('span', 'cc-diff-summary'), { textContent: parts.length ? parts.join(' \u00B7 ') : 'No changes' });\n}\n\nfunction plural(count: number, word: string): string {\n return `${count} ${word}${count === 1 ? '' : 's'}`;\n}\n\nfunction edgePath(a: Geo, b: Geo): string {\n const ay = a.ay + Math.min(a.h / 2, 16);\n const by = b.ay + Math.min(b.h / 2, 16);\n if (b.ax >= a.ax + a.w + 8) return curveH(a.ax + a.w, ay, b.ax, by);\n if (b.ax + b.w <= a.ax - 8) return curveH(a.ax, ay, b.ax + b.w, by);\n const ax = a.ax + a.w / 2;\n const bx = b.ax + b.w / 2;\n if (b.ay > a.ay) return curveV(ax, a.ay + a.h, bx, b.ay);\n return curveV(ax, a.ay, bx, b.ay + b.h);\n}\n\nfunction curveH(x1: number, y1: number, x2: number, y2: number) {\n const c = Math.max(30, Math.abs(x2 - x1) * 0.5) * Math.sign(x2 - x1 || 1);\n return `M${x1} ${y1}C${x1 + c} ${y1} ${x2 - c} ${y2} ${x2} ${y2}`;\n}\n\nfunction curveV(x1: number, y1: number, x2: number, y2: number) {\n const c = Math.max(30, Math.abs(y2 - y1) * 0.5) * Math.sign(y2 - y1 || 1);\n return `M${x1} ${y1}C${x1} ${y1 + c} ${x2} ${y2 - c} ${x2} ${y2}`;\n}\n\nfunction el(tag: string, cls?: string): HTMLElement {\n const e = document.createElement(tag);\n if (cls) e.className = cls;\n return e;\n}\n\nfunction button(label: string, onClick: () => void, variant?: string): HTMLButtonElement {\n const b = keepsCanvasFocus(document.createElement('button'));\n b.className = 'cc-btn' + (variant ? ' ' + variant : '');\n b.textContent = label;\n b.addEventListener('click', (e) => {\n e.stopPropagation();\n onClick();\n });\n return b;\n}\n\n/** Clicking the button leaves keyboard focus on the canvas, so its shortcuts (F2, Delete\u2026) keep working. */\nfunction keepsCanvasFocus<T extends HTMLElement>(element: T): T {\n element.addEventListener('pointerdown', (e) => e.preventDefault());\n return element;\n}\n\nfunction esc(s: string): string {\n return s.replace(/[&<>\"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;' })[c]!);\n}\n\nfunction clamp(v: number, lo: number, hi: number) {\n return Math.min(hi, Math.max(lo, v));\n}\n\nfunction mid(a: Point, b: Point): Point {\n return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };\n}\n\nfunction isMac() {\n return /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);\n}\n"],
5
- "mappings": ";AAAA,OAAO,QAAQ;AAGf,IAAM,gBAAgB;AACtB,IAAM,0BAA0B;AAChC,IAAM,gBAAgB;AAQtB,IAAM,YAAY,oBAAI,QAA8B;AAM7C,SAAS,UAAU,MAAc,MAAyB;AAC/D,QAAM,IAAI,eAAe,MAAM,IA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ources": ["../src/parse.ts", "../src/react.ts", "../src/syntax.ts", "../src/project.ts", "../src/workspace.ts", "../src/remoteProject.ts", "../src/projectServer.ts", "../src/projectWorker.ts", "../src/edits.ts", "../src/diff.ts", "../src/conflicts.ts", "../src/layoutRules.ts", "../src/arrange.ts", "../src/layout.ts", "../src/html.ts", "../src/styles.ts", "../src/canvas.ts"],
4
+ "sourcesContent": ["import ts from 'typescript';\nimport { componentFunctionOf, fileLanguageOf, isComponentClass, isComponentName, isHookName, returnsJsx, stateHookOf } from './react';\nimport type { StateHook } from './react';\nimport { unwrap } from './syntax';\nimport type { Block, BlockKind, CodeDiagnostic, FileModel, InsertStyle, Usage, UsageKind } from './types';\n\nconst PREVIEW_LINES = 6;\nconst CONTAINER_PREVIEW_LINES = 3;\nconst PREVIEW_WIDTH = 64;\n\ninterface Internals {\n sf: ts.SourceFile;\n builder: Builder;\n /** An old syntax tree can be updated incrementally only once. */\n reused: boolean;\n}\nconst internals = new WeakMap<FileModel, Internals>();\n\n/**\n * Parse a TypeScript file into a tree of blocks plus the usage links between them.\n * Pure function: same text in, same model out.\n */\nexport function parseFile(path: string, text: string): FileModel {\n const m = parseStructure(path, text);\n m.usages = computeUsages(m);\n return m;\n}\n\n/**\n * Fast part of parsing: blocks only (usages left empty). Pass the previous model of the same\n * file to parse incrementally, re-reading only the changed region.\n */\nexport function parseStructure(path: string, text: string, prev?: FileModel | null): FileModel {\n const kind = scriptKindOf(path);\n const old = prev && prev.path === path ? internals.get(prev) : undefined;\n let sf: ts.SourceFile;\n if (old && !old.reused) {\n old.reused = true;\n sf = ts.updateSourceFile(old.sf, text, changeRange(prev!.text, text));\n } else {\n sf = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true, kind);\n }\n const language = fileLanguageOf(path, sf);\n const b = new Builder(sf, text, language.isReact);\n b.collectStatements(sf.statements, null, 0);\n const syntax = (sf as unknown as { parseDiagnostics?: ts.DiagnosticWithLocation[] }).parseDiagnostics ?? [];\n const model: FileModel = {\n path,\n text,\n roots: b.roots,\n blocks: b.byId,\n usages: [],\n syntaxErrors: syntax.length,\n firstErrorLine: -1,\n diagnostics: [],\n indentUnit: detectIndentUnit(text),\n language,\n };\n model.diagnostics = syntax.map((d) => toCodeDiagnostic(model, sf, d, 'syntax'));\n model.firstErrorLine = model.diagnostics[0]?.line ?? -1;\n internals.set(model, { sf, builder: b, reused: false });\n return model;\n}\n\n/** Innermost block whose text range contains `offset`. */\nexport function blockAt(model: FileModel, offset: number): Block | null {\n let found: Block | null = null;\n let candidates = model.roots;\n for (;;) {\n const containing = candidates.find((b) => offset >= b.start && offset <= b.end);\n if (!containing) return found;\n found = containing;\n candidates = containing.children;\n }\n}\n\nexport function toCodeDiagnostic(model: FileModel, sf: ts.SourceFile, d: ts.Diagnostic, source: CodeDiagnostic['source']): CodeDiagnostic {\n const start = d.start ?? 0;\n return {\n start,\n length: d.length ?? 0,\n line: sf.getLineAndCharacterOfPosition(Math.min(start, sf.text.length)).line + 1,\n message: ts.flattenDiagnosticMessageText(d.messageText, '\\n'),\n source,\n severity: d.category === ts.DiagnosticCategory.Error ? 'error' : 'warning',\n blockId: blockAt(model, start)?.id ?? null,\n };\n}\n\n/** The builder that produced `model`: used by the project to resolve usages across files. */\nexport function builderOf(model: FileModel) {\n return internals.get(model)?.builder;\n}\n\n/** Slower part: resolve every name to its declaration and link the blocks. */\nexport function computeUsages(model: FileModel): Usage[] {\n const st = internals.get(model);\n if (!st) return [];\n if (st.reused) {\n // The tree was handed to a newer parse; re-parse from scratch to stay safe.\n return parseFile(model.path, model.text).usages;\n }\n return st.builder.collectUsages(st.sf, createProgram(st.sf).getTypeChecker());\n}\n\nfunction changeRange(a: string, b: string): ts.TextChangeRange {\n let s = 0;\n const n = Math.min(a.length, b.length);\n while (s < n && a.charCodeAt(s) === b.charCodeAt(s)) s++;\n let e = 0;\n while (e < n - s && a.charCodeAt(a.length - 1 - e) === b.charCodeAt(b.length - 1 - e)) e++;\n return ts.createTextChangeRange(ts.createTextSpan(s, a.length - e - s), b.length - e - s);\n}\n\n/** `exports.total = function () {}` or `module.exports.total = () => {}`: a function block named `total`. */\nfunction commonJsExportedFunction(s: ts.Statement): { assignment: ts.BinaryExpression; exportedName: ts.Identifier; fn: ts.FunctionExpression | ts.ArrowFunction } | null {\n if (!ts.isExpressionStatement(s) || !ts.isBinaryExpression(s.expression) || s.expression.operatorToken.kind !== ts.SyntaxKind.EqualsToken) return null;\n const { left, right } = s.expression;\n const fn = unwrap(right);\n const isFunction = ts.isFunctionExpression(fn) || ts.isArrowFunction(fn);\n if (!isFunction || !ts.isPropertyAccessExpression(left) || !ts.isIdentifier(left.name)) return null;\n const target = left.expression.getText();\n const isExportsObject = target === 'exports' || target === 'module.exports';\n return isExportsObject ? { assignment: s.expression, exportedName: left.name, fn } : null;\n}\n\n/** JavaScript files parse as JavaScript: in a `.js` file `<T>(x)` is a comparison, not a type argument. */\nexport function scriptKindOf(path: string): ts.ScriptKind {\n if (/\\.[cm]?jsx?$/.test(path)) return path.endsWith('x') ? ts.ScriptKind.JSX : ts.ScriptKind.JS;\n return path.endsWith('x') ? ts.ScriptKind.TSX : ts.ScriptKind.TS;\n}\n\n/** A one-file program with no libs: enough for the checker to resolve names inside the file. */\nfunction createProgram(sf: ts.SourceFile): ts.Program {\n const options: ts.CompilerOptions = {\n noLib: true,\n noResolve: true,\n allowJs: true,\n target: ts.ScriptTarget.Latest,\n jsx: ts.JsxEmit.Preserve,\n types: [],\n };\n const host: ts.CompilerHost = {\n getSourceFile: (name) => (name === sf.fileName ? sf : undefined),\n getDefaultLibFileName: () => 'lib.d.ts',\n writeFile: () => {},\n getCurrentDirectory: () => '/',\n getCanonicalFileName: (f) => f,\n useCaseSensitiveFileNames: () => true,\n getNewLine: () => '\\n',\n fileExists: (f) => f === sf.fileName,\n readFile: () => undefined,\n getDirectories: () => [],\n };\n return ts.createProgram({ rootNames: [sf.fileName], options, host });\n}\n\nexport function detectIndentUnit(text: string): string {\n const m = /\\n(\\t+|[ ]{2,8})\\S/.exec(text);\n if (!m) return ' ';\n return m[1].startsWith('\\t') ? '\\t' : m[1].length >= 4 && m[1].length % 4 === 0 ? ' ' : ' ';\n}\n\ninterface Pending {\n kind: BlockKind;\n key: string;\n name: string;\n detail: string;\n tags: string[];\n rangeNodes: ts.Node[]; // nodes covered by the block (more than one for overloads/statement groups)\n declNodes: ts.Node[]; // nodes that \"declare\" the block, for usage resolution\n nameNode?: ts.Node;\n /** Node whose own code forms the preview. */\n previewRange: [number, number] | null;\n insert: InsertStyle;\n insertAt: number;\n /** Collect children of this block. */\n children?: (block: Block) => void;\n}\n\nclass Builder {\n roots: Block[] = [];\n byId = new Map<string, Block>();\n /**\n * Declaration node \u2192 block id, keyed by node position (see `nodeKey`) so a syntax tree parsed\n * elsewhere from the same text (the project's language service) maps to the same blocks.\n */\n private declToBlock = new Map<string, string>();\n /** Range node \u2192 block, to find which block contains a usage. Keyed like `declToBlock`. */\n private rangeToBlock = new Map<string, Block>();\n /** Every name a usage could resolve to. Other identifiers skip the (slow) checker. */\n readonly names = new Set<string>();\n /** Setters of React state (`setCount`), keyed like `declToBlock`: using one writes the state. */\n private stateSetters = new Set<string>();\n\n constructor(\n private sf: ts.SourceFile,\n private text: string,\n private isReact: boolean,\n ) {}\n\n // ---------- structure ----------\n\n collectStatements(stmts: readonly ts.Statement[], parent: Block | null, depth: number, declarationsOnly = false) {\n let group: ts.Statement[] = [];\n const flushGroup = () => {\n if (!group.length) return;\n const nodes = group;\n group = [];\n const first = nodes[0];\n const firstLine = this.text.slice(first.getStart(this.sf), first.end).split('\\n')[0].trim();\n this.add(\n {\n kind: 'statement',\n key: 'stmt:' + firstLine.slice(0, 40),\n name: truncate(firstLine, 48),\n detail: nodes.length > 1 ? `+${nodes.length - 1} more` : '',\n tags: [],\n rangeNodes: nodes,\n declNodes: [],\n previewRange: [nodes[0].getStart(this.sf), nodes[nodes.length - 1].end],\n insert: null,\n insertAt: -1,\n },\n parent,\n depth,\n );\n };\n\n for (let i = 0; i < stmts.length; i++) {\n const s = stmts[i];\n if (ts.isFunctionDeclaration(s)) {\n flushGroup();\n // Group overloads: `function f(a): x; function f(b): y; function f(c) {...}`\n const overloads: ts.FunctionDeclaration[] = [s];\n while (!overloads[overloads.length - 1].body) {\n const next = stmts[i + 1];\n if (next && ts.isFunctionDeclaration(next) && next.name?.text === s.name?.text) {\n overloads.push(next);\n i++;\n } else break;\n }\n const name = s.name?.text ?? 'default';\n const isComponent = this.isReact && isComponentName(name) && returnsJsx(overloads[overloads.length - 1]);\n this.addFunctionLike(overloads, name, parent, depth, { kind: isComponent ? 'component' : 'function' });\n } else if (ts.isClassDeclaration(s)) {\n flushGroup();\n this.addClass(s, s, s.name?.text ?? 'default', parent, depth);\n } else if (ts.isVariableStatement(s)) {\n flushGroup();\n this.addVariableStatement(s, parent, depth, declarationsOnly);\n } else if (commonJsExportedFunction(s)) {\n flushGroup();\n const { assignment, exportedName, fn } = commonJsExportedFunction(s)!;\n // TypeScript declares the export on the assignment or its left side, depending on the form.\n const declNodes = [s, assignment, assignment.left];\n this.addFunctionLike([fn], exportedName.text, parent, depth, { rangeNodes: [s], declNodes, extraTags: ['export'], nameNode: exportedName });\n } else if (declarationsOnly) {\n continue;\n } else if (ts.isImportDeclaration(s) || ts.isImportEqualsDeclaration(s)) {\n flushGroup();\n this.addImport(s, parent, depth);\n } else if (ts.isInterfaceDeclaration(s) || ts.isTypeAliasDeclaration(s) || ts.isEnumDeclaration(s)) {\n flushGroup();\n const keyword = ts.isInterfaceDeclaration(s) ? 'interface' : ts.isEnumDeclaration(s) ? 'enum' : 'type';\n const typeParams = 'typeParameters' in s && s.typeParameters ? `<${s.typeParameters.map((t) => t.getText()).join(', ')}>` : '';\n const bodyStart = ts.isTypeAliasDeclaration(s) ? s.type.getStart(this.sf) : this.text.indexOf('{', s.name.end);\n this.add(\n {\n kind: 'type',\n key: s.name.text,\n name: s.name.text,\n detail: typeParams,\n tags: [...modifierTags(s), keyword],\n rangeNodes: [s],\n declNodes: [s],\n nameNode: s.name,\n previewRange: bodyStart >= 0 ? [bodyStart, s.end] : null,\n insert: null,\n insertAt: -1,\n },\n parent,\n depth,\n );\n } else if (ts.isModuleDeclaration(s) && s.body && ts.isModuleBlock(s.body)) {\n flushGroup();\n const body = s.body;\n this.add(\n {\n kind: 'namespace',\n key: s.name.getText(),\n name: s.name.getText(),\n detail: '',\n tags: [...modifierTags(s), 'namespace'],\n rangeNodes: [s],\n declNodes: [s],\n nameNode: s.name,\n previewRange: [body.getStart(this.sf) + 1, body.end - 1],\n insert: 'body',\n insertAt: body.end - 1,\n children: (blk) => this.collectStatements(body.statements, blk, depth + 1),\n },\n parent,\n depth,\n );\n } else {\n group.push(s);\n }\n }\n flushGroup();\n }\n\n private addImport(s: ts.ImportDeclaration | ts.ImportEqualsDeclaration, parent: Block | null, depth: number) {\n let spec: string;\n let names: string[] = [];\n if (ts.isImportDeclaration(s)) {\n spec = (s.moduleSpecifier as ts.StringLiteral).text;\n const clause = s.importClause;\n if (clause?.name) names.push(clause.name.text);\n const nb = clause?.namedBindings;\n if (nb && ts.isNamespaceImport(nb)) names.push('* as ' + nb.name.text);\n if (nb && ts.isNamedImports(nb)) names.push(...nb.elements.map((e) => e.name.text));\n if (!clause) names = ['(side effect)'];\n } else {\n spec = s.name.text;\n names = [s.moduleReference.getText()];\n this.names.add(s.name.text);\n }\n for (const n of names) this.names.add(n.replace('* as ', ''));\n this.add(\n {\n kind: 'import',\n key: 'import:' + spec,\n name: spec,\n detail: '',\n tags: ts.isImportDeclaration(s) && s.importClause?.isTypeOnly ? ['type'] : [],\n rangeNodes: [s],\n declNodes: [s],\n previewRange: null,\n insert: null,\n insertAt: -1,\n },\n parent,\n depth,\n wrapNames(names),\n );\n }\n\n private addFunctionLike(\n nodes: (ts.FunctionLikeDeclaration & ts.Node)[],\n name: string,\n parent: Block | null,\n depth: number,\n /** `nameNode`: where the name is when the function has none of its own (`const f = () => {}`). */\n opts: { kind?: 'function' | 'component'; rangeNodes?: ts.Node[]; declNodes?: ts.Node[]; key?: string; extraTags?: string[]; nameNode?: ts.Node } = {},\n ) {\n const impl = nodes[nodes.length - 1];\n const sig = nodes.find((n) => !!n.body) ?? impl;\n const body = impl.body;\n let previewRange: [number, number] | null = null;\n let insert: InsertStyle = null;\n let insertAt = -1;\n if (body && ts.isBlock(body)) {\n previewRange = [body.getStart(this.sf) + 1, body.end - 1];\n insert = 'body';\n // Insert nested code before a trailing `return`, otherwise before the closing brace.\n const last = body.statements[body.statements.length - 1];\n insertAt = last && ts.isReturnStatement(last) ? this.lineStartOf(last.getStart(this.sf)) : body.end - 1;\n } else if (body) {\n previewRange = [body.getStart(this.sf), body.end];\n }\n const typeParams = sig.typeParameters?.length ? `<${sig.typeParameters.map((t) => t.getText()).join(', ')}>` : '';\n const ret = sig.type ? ': ' + sig.type.getText() : '';\n const detail = squash(`${typeParams}(${sig.parameters.map((p) => p.getText()).join(', ')})${ret}`);\n const tags = [...(opts.extraTags ?? []), ...modifierTags(nodes[0])];\n if (this.isReact && isHookName(name)) tags.push('hook');\n if (nodes.length > 1) tags.push(`${nodes.length - 1} overload${nodes.length > 2 ? 's' : ''}`);\n if (impl.asteriskToken) tags.push('generator');\n this.add(\n {\n kind: opts.kind ?? 'function',\n key: opts.key ?? name,\n name,\n detail,\n tags,\n rangeNodes: opts.rangeNodes ?? nodes,\n declNodes: opts.declNodes ?? nodes,\n nameNode: opts.nameNode ?? impl.name,\n previewRange,\n insert,\n insertAt,\n children:\n body && ts.isBlock(body) ? (blk) => this.collectStatements(body.statements, blk, depth + 1, true) : undefined,\n },\n parent,\n depth,\n );\n }\n\n private addClass(\n cls: ts.ClassLikeDeclaration,\n rangeNode: ts.Node,\n name: string,\n parent: Block | null,\n depth: number,\n declNodes: ts.Node[] = [cls],\n extraTags: string[] = [],\n ) {\n const heritage = (cls.heritageClauses ?? []).map((h) => h.getText()).join(' ');\n const openBrace = this.text.indexOf('{', (cls.heritageClauses?.at(-1) ?? cls.typeParameters?.at(-1) ?? cls.name ?? cls).end);\n const typeParams = cls.typeParameters?.length ? `<${cls.typeParameters.map((t) => t.getText()).join(', ')}>` : '';\n this.add(\n {\n kind: this.isReact && isComponentClass(cls) ? 'component' : 'class',\n key: name,\n name,\n detail: squash(typeParams + (heritage ? ' ' + heritage : '')),\n tags: [...extraTags, ...modifierTags(rangeNode === cls ? cls : rangeNode)],\n rangeNodes: [rangeNode],\n declNodes,\n nameNode: cls.name,\n previewRange: openBrace >= 0 ? [openBrace + 1, cls.end - 1] : null,\n insert: 'class',\n insertAt: cls.end - 1,\n children: (blk) => this.collectMembers(cls.members, blk, depth + 1),\n },\n parent,\n depth,\n );\n }\n\n private collectMembers(members: ts.NodeArray<ts.ClassElement>, parent: Block, depth: number) {\n for (let i = 0; i < members.length; i++) {\n const m = members[i];\n if (ts.isMethodDeclaration(m) || ts.isConstructorDeclaration(m)) {\n const name = ts.isConstructorDeclaration(m) ? 'constructor' : m.name.getText();\n const overloads: (ts.MethodDeclaration | ts.ConstructorDeclaration)[] = [m];\n while (!overloads[overloads.length - 1].body) {\n const next = members[i + 1];\n const nextName = next && (ts.isConstructorDeclaration(next) ? 'constructor' : ts.isMethodDeclaration(next) ? next.name.getText() : null);\n if (nextName === name) {\n overloads.push(next as ts.MethodDeclaration);\n i++;\n } else break;\n }\n this.addFunctionLike(overloads, name, parent, depth);\n } else if (ts.isGetAccessor(m) || ts.isSetAccessor(m)) {\n const name = m.name.getText();\n const word = ts.isGetAccessor(m) ? 'get' : 'set';\n this.addFunctionLike([m], name, parent, depth, { key: `${word} ${name}`, extraTags: [word] });\n } else if (ts.isPropertyDeclaration(m)) {\n const name = m.name.getText();\n const init = m.initializer && unwrap(m.initializer);\n if (init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {\n this.addFunctionLike([init], name, parent, depth, { rangeNodes: [m], declNodes: [m], extraTags: modifierTags(m), nameNode: m.name });\n } else {\n this.addVariable(m, m, name, m.type ? ': ' + m.type.getText() : '', modifierTags(m), parent, depth, m.initializer);\n }\n }\n }\n }\n\n private addVariableStatement(s: ts.VariableStatement, parent: Block | null, depth: number, functionsOnly: boolean) {\n const decls = s.declarationList.declarations;\n const keyword = s.declarationList.flags & ts.NodeFlags.Const ? 'const' : s.declarationList.flags & ts.NodeFlags.Let ? 'let' : 'var';\n for (const d of decls) {\n const rangeNode = decls.length === 1 ? s : d;\n const name = d.name.getText();\n const tags = [...modifierTags(s), keyword];\n const stateHook = this.isReact ? stateHookOf(d) : undefined;\n if (stateHook) {\n this.addState(stateHook, rangeNode, tags, parent, depth);\n continue;\n }\n const init = d.initializer && unwrap(d.initializer);\n const componentFunction = this.isReact && init && isComponentName(name) ? componentFunctionOf(init) : undefined;\n if (componentFunction) {\n this.addFunctionLike([componentFunction], name, parent, depth, { kind: 'component', rangeNodes: [rangeNode], declNodes: [d], extraTags: tags, nameNode: d.name });\n } else if (init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))) {\n this.addFunctionLike([init], name, parent, depth, { rangeNodes: [rangeNode], declNodes: [d], extraTags: tags, nameNode: d.name });\n } else if (init && ts.isClassExpression(init)) {\n this.addClass(init, rangeNode, name, parent, depth, [d, init], tags);\n } else if (!functionsOnly) {\n this.addVariable(d, rangeNode, name, d.type ? ': ' + d.type.getText() : '', tags, parent, depth, d.initializer);\n }\n }\n }\n\n /** `const [count, setCount] = useState(0)`: a state block named `count`; using `setCount` writes it. */\n private addState(hook: StateHook, rangeNode: ts.Node, tags: string[], parent: Block | null, depth: number) {\n const named = (hook.value ?? hook.setter)!;\n const setterName = hook.setter?.name.getText();\n const [firstArg, ...otherArgs] = hook.call.arguments;\n const args = firstArg ? truncate(squash(firstArg.getText()), 24) + (otherArgs.length ? ', \u2026' : '') : '';\n if (hook.setter && setterName) {\n this.stateSetters.add(nodeKey(hook.setter));\n this.names.add(setterName);\n }\n this.add(\n {\n kind: 'state',\n key: named.name.getText(),\n name: named.name.getText(),\n detail: `${hook.call.expression.getText()}(${args})`,\n tags: setterName && hook.value ? [...tags, setterName] : tags,\n rangeNodes: [rangeNode],\n declNodes: [hook.value, hook.setter].filter((declaration) => !!declaration),\n nameNode: named.name,\n previewRange: [hook.call.getStart(this.sf), hook.call.end],\n insert: null,\n insertAt: -1,\n },\n parent,\n depth,\n );\n }\n\n private addVariable(\n decl: ts.Node,\n rangeNode: ts.Node,\n name: string,\n type: string,\n tags: string[],\n parent: Block | null,\n depth: number,\n initializer: ts.Expression | undefined,\n ) {\n const init = initializer && unwrap(initializer);\n // Object literals with methods become containers of function blocks.\n const objectChildren =\n init && ts.isObjectLiteralExpression(init)\n ? init.properties.filter(\n (p) =>\n ts.isMethodDeclaration(p) ||\n (ts.isPropertyAssignment(p) && (ts.isArrowFunction(unwrap(p.initializer)) || ts.isFunctionExpression(unwrap(p.initializer)))),\n )\n : [];\n this.add(\n {\n kind: 'variable',\n key: name,\n name,\n detail: squash(type),\n tags,\n rangeNodes: [rangeNode],\n declNodes: [decl],\n nameNode: (decl as ts.NamedDeclaration).name,\n previewRange: initializer ? [initializer.getStart(this.sf), initializer.end] : null,\n insert: null,\n insertAt: -1,\n children: objectChildren.length\n ? (blk) => {\n for (const p of objectChildren) {\n const pname = p.name!.getText();\n if (ts.isMethodDeclaration(p)) this.addFunctionLike([p], pname, blk, depth + 1);\n else {\n const fn = unwrap((p as ts.PropertyAssignment).initializer) as ts.ArrowFunction;\n this.addFunctionLike([fn], pname, blk, depth + 1, { rangeNodes: [p], declNodes: [p], nameNode: p.name });\n }\n }\n }\n : undefined,\n },\n parent,\n depth,\n );\n }\n\n private add(p: Pending, parent: Block | null, depth: number, presetPreview?: string[]) {\n const first = p.rangeNodes[0];\n const last = p.rangeNodes[p.rangeNodes.length - 1];\n const start = this.startWithComments(first);\n const siblings = parent ? parent.children : this.roots;\n let key = p.key;\n if (siblings.some((s) => s.key === key)) {\n let n = 2;\n while (siblings.some((s) => s.key === `${p.key}#${n}`)) n++;\n key = `${p.key}#${n}`;\n }\n const id = parent ? `${parent.id}/${key}` : key;\n const block: Block = {\n id,\n key,\n kind: p.kind,\n name: p.name,\n detail: p.detail,\n tags: p.tags,\n start,\n end: last.end,\n nameStart: p.nameNode ? p.nameNode.getStart(this.sf) : -1,\n preview: [],\n previewMore: 0,\n children: [],\n parentId: parent?.id ?? null,\n depth,\n insert: p.insert,\n insertAt: p.insertAt,\n indent: this.indentAt(first.getStart(this.sf)),\n };\n siblings.push(block);\n this.byId.set(id, block);\n this.names.add(p.name);\n for (const n of p.rangeNodes) this.rangeToBlock.set(nodeKey(n), block);\n for (const n of p.declNodes) this.declToBlock.set(nodeKey(n), id);\n p.children?.(block);\n if (presetPreview) {\n block.preview = presetPreview;\n } else if (p.previewRange) {\n const max = block.children.length ? CONTAINER_PREVIEW_LINES : PREVIEW_LINES;\n const { lines, more } = makePreview(this.text, p.previewRange, block.children, max);\n block.preview = lines;\n block.previewMore = more;\n }\n return block;\n }\n\n /** Include doc comments directly above the node (no blank line in between). */\n private startWithComments(node: ts.Node): number {\n let start = node.getStart(this.sf);\n const comments = ts.getLeadingCommentRanges(this.text, node.pos) ?? [];\n for (let i = comments.length - 1; i >= 0; i--) {\n const gap = this.text.slice(comments[i].end, start);\n if (/\\S/.test(gap) || (gap.match(/\\n/g)?.length ?? 0) > 1) break;\n start = comments[i].pos;\n }\n return start;\n }\n\n private lineStartOf(pos: number): number {\n return this.text.lastIndexOf('\\n', pos - 1) + 1;\n }\n\n private indentAt(pos: number): string {\n const ls = this.lineStartOf(pos);\n return /^[ \\t]*/.exec(this.text.slice(ls, pos))![0];\n }\n\n // ---------- usages ----------\n\n blockIdForDeclaration(declaration: ts.Node): string | undefined {\n return this.declToBlock.get(nodeKey(declaration));\n }\n\n /**\n * Link every name used inside a block to the block that declares it. `sf` is a tree of the same\n * text (this builder's own, or the language service's when resolving across files).\n */\n collectUsages(sf: ts.SourceFile, checker: ts.TypeChecker, otherFiles?: OtherFileResolver): Usage[] {\n const byPair = new Map<string, Usage>();\n const visit = (node: ts.Node, current: Block | null) => {\n const blk = this.rangeToBlock.get(nodeKey(node));\n if (blk) current = blk;\n if (ts.isIdentifier(node) && current) this.recordUsage(node, current, checker, byPair, otherFiles);\n ts.forEachChild(node, (c) => visit(c, current));\n };\n visit(sf, null);\n return [...byPair.values()];\n }\n\n private recordUsage(id: ts.Identifier, from: Block, checker: ts.TypeChecker, out: Map<string, Usage>, otherFiles?: OtherFileResolver) {\n const isKnownName = this.names.has(id.text) || !!otherFiles?.projectNames.has(id.text);\n if (!isKnownName) return;\n const parent = id.parent;\n // Skip the names of declarations themselves. A shorthand `{ x }` is both a name and a use of `x`.\n const isDeclarationName = !!parent && (parent as ts.NamedDeclaration).name === id && !ts.isPropertyAccessExpression(parent) && !ts.isShorthandPropertyAssignment(parent);\n if (isDeclarationName) return;\n let sym: ts.Symbol | undefined;\n try {\n sym =\n parent && ts.isShorthandPropertyAssignment(parent)\n ? checker.getShorthandAssignmentValueSymbol(parent)\n : checker.getSymbolAtLocation(id);\n } catch {\n return;\n }\n if (!sym?.declarations) return;\n let kind = usageKind(id);\n let to: string | undefined;\n let importBlockId: string | undefined;\n for (const d of sym.declarations) {\n to = this.declToBlock.get(nodeKey(d));\n if (this.stateSetters.has(nodeKey(d))) kind = 'write';\n if (!to) {\n // Imported names point at their import statement.\n let n: ts.Node | undefined = d;\n while (n && !ts.isImportDeclaration(n) && !ts.isImportEqualsDeclaration(n) && !ts.isSourceFile(n)) n = n.parent;\n if (n && !ts.isSourceFile(n)) importBlockId = to = this.declToBlock.get(nodeKey(n));\n }\n if (to) break;\n }\n if (otherFiles) {\n const isImportedName = !!importBlockId && (sym.flags & ts.SymbolFlags.Alias) !== 0;\n const target = isImportedName ? safeAliasedSymbol(checker, sym) : to ? undefined : sym;\n const declaredElsewhere = target?.declarations?.find((d) => d.getSourceFile() !== id.getSourceFile());\n const external = declaredElsewhere && otherFiles.blockInOtherFile(declaredElsewhere);\n if (external) addUsage(out, { from: from.id, to: external.id, toPath: external.path, via: importBlockId, kind, count: 1 });\n }\n if (!to || to === from.id) return;\n // Skip links between a block and its own ancestors/descendants: they're already drawn nested.\n if (from.id.startsWith(to + '/') || to.startsWith(from.id + '/')) return;\n addUsage(out, { from: from.id, to, kind, count: 1 });\n }\n}\n\n/** Finds blocks declared in other files of the project. */\nexport interface OtherFileResolver {\n /** Names declared anywhere in the project. Identifiers with other names skip the checker. */\n projectNames: Set<string>;\n blockInOtherFile(declaration: ts.Node): { path: string; id: string } | null;\n}\n\nfunction addUsage(out: Map<string, Usage>, usage: Usage) {\n const pairKey = `${usage.from}>${usage.toPath ?? ''}:${usage.to}`;\n const existing = out.get(pairKey);\n if (!existing) return void out.set(pairKey, usage);\n existing.count++;\n if (usage.kind === 'call') existing.kind = 'call';\n else if (usage.kind === 'write' && existing.kind === 'read') existing.kind = 'write';\n}\n\nfunction safeAliasedSymbol(checker: ts.TypeChecker, symbol: ts.Symbol): ts.Symbol | undefined {\n try {\n return checker.getAliasedSymbol(symbol);\n } catch {\n return undefined;\n }\n}\n\n/** Identifies a node by kind and position, the same in any tree parsed from the same text. */\nfunction nodeKey(node: ts.Node): string {\n return `${node.kind}:${node.pos}:${node.end}`;\n}\n\nfunction usageKind(id: ts.Identifier): UsageKind {\n if (isJsxTagName(id)) return 'render';\n let n: ts.Node = id;\n if (ts.isPropertyAccessExpression(n.parent) && n.parent.name === n) n = n.parent;\n const p = n.parent;\n if ((ts.isCallExpression(p) || ts.isNewExpression(p)) && p.expression === n) return 'call';\n if (ts.isTaggedTemplateExpression(p) && p.tag === n) return 'call';\n if (ts.isJsxOpeningLikeElement(p) && p.tagName === n) return 'render';\n if (ts.isBinaryExpression(p) && p.left === n && p.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && p.operatorToken.kind <= ts.SyntaxKind.LastAssignment) return 'write';\n if ((ts.isPrefixUnaryExpression(p) || ts.isPostfixUnaryExpression(p)) && (p.operator === ts.SyntaxKind.PlusPlusToken || p.operator === ts.SyntaxKind.MinusMinusToken)) return 'write';\n if (ts.isTypeReferenceNode(p) || ts.isExpressionWithTypeArguments(p) || ts.isTypeQueryNode(p) || ts.isQualifiedName(p)) return 'type';\n return 'read';\n}\n\n/** `Cart` in `<Cart />` and `</Cart>`, and `Menu` in `<Menu.Item />`. */\nfunction isJsxTagName(id: ts.Identifier): boolean {\n let tag: ts.Node = id;\n while (ts.isPropertyAccessExpression(tag.parent) && tag.parent.expression === tag) tag = tag.parent;\n const element = tag.parent;\n return (ts.isJsxOpeningLikeElement(element) || ts.isJsxClosingElement(element)) && element.tagName === tag;\n}\n\nfunction modifierTags(n: ts.Node): string[] {\n const mods = ts.canHaveModifiers(n) ? ts.getModifiers(n) ?? [] : [];\n return mods.map((m) => m.getText());\n}\n\nfunction squash(s: string): string {\n return s.replace(/\\s+/g, ' ').replace(/\\(\\s+/g, '(').replace(/\\s+\\)/g, ')').replace(/,\\s*\\)/g, ')').trim();\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length > n ? s.slice(0, n - 1) + '\u2026' : s;\n}\n\nfunction wrapNames(names: string[]): string[] {\n const lines: string[] = [];\n let cur = '';\n for (const n of names) {\n const piece = cur ? cur + ', ' + n : n;\n if (piece.length > 40 && cur) {\n lines.push(cur + ',');\n cur = n;\n } else cur = piece;\n }\n if (cur) lines.push(cur);\n return lines.slice(0, PREVIEW_LINES);\n}\n\n/** Faint code preview: the block's own code with nested blocks cut out, dedented and trimmed. */\n/** The text of `range` with the given nested blocks cut out: a block's own code. */\nexport function codeWithoutChildren(text: string, range: [number, number], children: Block[]): string {\n let [a, b] = range;\n let src = '';\n const kids = children.filter((c) => c.start >= a && c.end <= b).sort((x, y) => x.start - y.start);\n for (const k of kids) {\n src += text.slice(a, k.start);\n a = k.end;\n }\n return src + text.slice(a, b);\n}\n\nexport function makePreview(text: string, range: [number, number], children: Block[], max: number): { lines: string[]; more: number } {\n const src = codeWithoutChildren(text, range, children);\n const kids = children.filter((c) => c.start >= range[0] && c.end <= range[1]);\n let lines = src.split('\\n').map((l) => l.replace(/\\s+$/, ''));\n // Drop blank lines at the edges and collapse runs of blanks.\n // With nested blocks cut out, lines of leftover punctuation (`,` `{` `}`) are just noise.\n if (kids.length) lines = lines.filter((l) => !/^[\\s{}[\\](),;]*$/.test(l) || !l.trim());\n lines = lines.filter((l, i) => l.trim() || (i > 0 && lines[i - 1].trim()));\n while (lines.length && !lines[0].trim()) lines.shift();\n while (lines.length && !lines[lines.length - 1].trim()) lines.pop();\n const indents = lines.slice(lines.length > 1 && !/^\\s/.test(lines[0]) ? 1 : 0).filter((l) => l.trim()).map((l) => /^[ \\t]*/.exec(l)![0].length);\n const minIndent = indents.length ? Math.min(...indents) : 0;\n lines = lines.map((l) => (/^\\s/.test(l) ? l.slice(minIndent) : l).replace(/\\t/g, ' '));\n const more = Math.max(0, lines.length - max);\n return { lines: lines.slice(0, max).map((l) => truncate(l, PREVIEW_WIDTH)), more };\n}\n", "import ts from 'typescript';\nimport { unwrap } from './syntax';\nimport type { FileLanguage, LanguageLabel } from './types';\n\nconst REACT_MODULE = /^(react|react-dom|react-native)(\\/|$)/;\n\n/**\n * JavaScript or TypeScript, and whether React mode is on: a `.jsx`/`.tsx` file, a file with JSX in\n * it, or a file that imports React.\n */\nexport function fileLanguageOf(path: string, sf: ts.SourceFile): FileLanguage {\n const script = /\\.[cm]?jsx?$/.test(path) ? 'js' : 'ts';\n const hasJsxExtension = /\\.[jt]sx$/.test(path);\n // Only .tsx allows JSX in TypeScript; in JavaScript any file can have it.\n const mayHaveJsx = script === 'js' && /<[A-Za-z>]/.test(sf.text);\n const hasJsx = hasJsxExtension || (mayHaveJsx && containsJsx(sf));\n const isReact = hasJsx || importsReact(sf);\n return { script, hasJsx, isReact, label: languageLabel(script, hasJsx, isReact) };\n}\n\nfunction languageLabel(script: 'js' | 'ts', hasJsx: boolean, isReact: boolean): LanguageLabel {\n if (hasJsx) return script === 'js' ? 'React JSX' : 'React TSX';\n if (isReact) return script === 'js' ? 'React JS' : 'React TS';\n return script === 'js' ? 'JS' : 'TS';\n}\n\nexport function isJsx(node: ts.Node): boolean {\n return ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node);\n}\n\nfunction containsJsx(node: ts.Node): boolean {\n return isJsx(node) || !!ts.forEachChild(node, (child) => containsJsx(child) || undefined);\n}\n\n/** `import \u2026 from 'react'`, `export \u2026 from 'react-dom/client'`, `require('react')` at the top level. */\nfunction importsReact(sf: ts.SourceFile): boolean {\n return sf.statements.some((statement) => {\n const isImportOrReExport = ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement);\n if (isImportOrReExport) return !!statement.moduleSpecifier && ts.isStringLiteral(statement.moduleSpecifier) && REACT_MODULE.test(statement.moduleSpecifier.text);\n if (ts.isImportEqualsDeclaration(statement)) return ts.isExternalModuleReference(statement.moduleReference) && isReactModuleName(statement.moduleReference.expression);\n if (ts.isVariableStatement(statement)) return statement.declarationList.declarations.some((declaration) => !!declaration.initializer && isRequireOfReact(declaration.initializer));\n return false;\n });\n}\n\n/** `require('react')`, also `require('react').useState`. */\nfunction isRequireOfReact(expression: ts.Expression): boolean {\n if (ts.isPropertyAccessExpression(expression)) return isRequireOfReact(expression.expression);\n const isRequireCall = ts.isCallExpression(expression) && ts.isIdentifier(expression.expression) && expression.expression.text === 'require';\n return isRequireCall && expression.arguments.length === 1 && isReactModuleName(expression.arguments[0]);\n}\n\nfunction isReactModuleName(expression: ts.Expression): boolean {\n return ts.isStringLiteral(expression) && REACT_MODULE.test(expression.text);\n}\n\ntype FunctionNode = ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction;\n\nconst COMPONENT_WRAPPERS = new Set(['memo', 'forwardRef', 'React.memo', 'React.forwardRef']);\nconst COMPONENT_BASE_CLASSES = new Set(['Component', 'PureComponent', 'React.Component', 'React.PureComponent']);\n\n/** React only treats capitalized names as components: `<cart />` is an HTML tag. */\nexport const isComponentName = (name: string): boolean => /^[A-Z]/.test(name);\n\n/** A function that returns JSX from its own body (not from a callback inside it). */\nexport function returnsJsx(fn: ts.FunctionLikeDeclaration): boolean {\n if (!fn.body) return false;\n if (!ts.isBlock(fn.body)) return isJsxValue(fn.body);\n const hasJsxReturn = (node: ts.Node): boolean => {\n if (ts.isReturnStatement(node)) return !!node.expression && isJsxValue(node.expression);\n if (ts.isFunctionLike(node) || ts.isClassLike(node)) return false;\n return !!ts.forEachChild(node, (child) => hasJsxReturn(child) || undefined);\n };\n return hasJsxReturn(fn.body);\n}\n\n/** `<div />`, `(<div />)`, `open ? <Menu /> : null`, `items.length > 0 && <List />`. */\nfunction isJsxValue(expression: ts.Expression): boolean {\n const value = unwrap(expression);\n if (isJsx(value)) return true;\n if (ts.isConditionalExpression(value)) return isJsxValue(value.whenTrue) || isJsxValue(value.whenFalse);\n if (ts.isBinaryExpression(value)) return isJsxValue(value.left) || isJsxValue(value.right);\n return false;\n}\n\n/**\n * The function of a component assigned to a variable: an arrow or function that returns JSX, or\n * the function inside `memo(\u2026)` / `forwardRef(\u2026)`, also nested.\n */\nexport function componentFunctionOf(initializer: ts.Expression): FunctionNode | undefined {\n const value = unwrap(initializer);\n if (ts.isArrowFunction(value) || ts.isFunctionExpression(value)) return returnsJsx(value) ? value : undefined;\n const isWrapperCall = ts.isCallExpression(value) && value.arguments.length > 0 && COMPONENT_WRAPPERS.has(value.expression.getText());\n if (!isWrapperCall) return undefined;\n const wrapped = unwrap(value.arguments[0]);\n if (ts.isArrowFunction(wrapped) || ts.isFunctionExpression(wrapped)) return wrapped;\n return componentFunctionOf(wrapped);\n}\n\n/** `class Cart extends Component`, `extends React.PureComponent<Props>` */\nexport function isComponentClass(cls: ts.ClassLikeDeclaration): boolean {\n const extendsClause = cls.heritageClauses?.find((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword);\n const baseClass = extendsClause?.types[0]?.expression.getText();\n return !!baseClass && COMPONENT_BASE_CLASSES.has(baseClass);\n}\n\nconst STATE_HOOKS = new Set(['useState', 'useReducer', 'React.useState', 'React.useReducer']);\n\n/** `const [count, setCount] = useState(0)`: the hook call and the declarations of the value and its setter. */\nexport interface StateHook {\n call: ts.CallExpression;\n value?: ts.BindingElement | ts.VariableDeclaration;\n setter?: ts.BindingElement;\n}\n\nexport function stateHookOf(declaration: ts.VariableDeclaration): StateHook | undefined {\n const call = declaration.initializer && unwrap(declaration.initializer);\n const isStateHookCall = !!call && ts.isCallExpression(call) && STATE_HOOKS.has(call.expression.getText());\n if (!isStateHookCall) return undefined;\n if (ts.isIdentifier(declaration.name)) return { call, value: declaration };\n if (!ts.isArrayBindingPattern(declaration.name)) return undefined;\n const [value, setter] = declaration.name.elements.map((element) => (ts.isBindingElement(element) && ts.isIdentifier(element.name) ? element : undefined));\n return value || setter ? { call, value, setter } : undefined;\n}\n\n/** `useCart`, `useLocalStorage`: React runs functions named like this as hooks. */\nexport const isHookName = (name: string): boolean => /^use[A-Z0-9]/.test(name);\n", "import ts from 'typescript';\n\n/** The expression inside parentheses and type assertions: `(x as Y)` \u2192 `x`. */\nexport function unwrap(e: ts.Expression): ts.Expression {\n while (ts.isParenthesizedExpression(e) || ts.isAsExpression(e) || ts.isSatisfiesExpression(e) || ts.isTypeAssertionExpression(e)) e = e.expression;\n return e;\n}\n", "import ts from 'typescript';\nimport type { TextEdit } from './edits';\nimport { builderOf, parseStructure, toCodeDiagnostic, type OtherFileResolver } from './parse';\nimport type { Block, CodeDiagnostic, FileModel, IncomingUsage, Usage } from './types';\nimport { configForFile, parseConfig, workspacePackagePaths, type ConfigFile, type Workspace } from './workspace';\n\nexport type { ConfigFile, Workspace } from './workspace';\n\nexport interface ProjectOptions {\n /**\n * Standard library declaration files by file name (`lib.es2022.d.ts` \u2192 text), including every\n * file they reference. Without them only syntax errors are reported, since every built-in\n * (`Math`, `Array`, `console`) would otherwise be a type error.\n */\n libFiles?: Record<string, string>;\n /** Lib entry files to load from `libFiles`. Defaults to ES2022 + DOM. */\n lib?: string[];\n compilerOptions?: ts.CompilerOptions;\n}\n\nexport type RenameResult = { ok: true; edits: Record<string, TextEdit[]> } | { ok: false; error: string };\n\n/** Usage links and errors of one file, found when typing pauses. */\nexport interface FileResolution {\n usages: Usage[];\n /** Usages in other files that point at blocks in this file. */\n incoming: IncomingUsage[];\n diagnostics: CodeDiagnostic[];\n}\n\n/**\n * What the canvas needs from a project. `Project` does all of it in place; `RemoteProject` keeps only\n * the per-keystroke parse and does the rest in a worker, so a pause in a big file can't stall the page.\n */\nexport interface CanvasProject {\n /** Per-keystroke path: parse this file into blocks, right away. */\n setFile(path: string, text: string): FileModel;\n getModel(path: string): FileModel | undefined;\n getText(path: string): string | undefined;\n /** Leave out the type errors when the host reports its own (`CodeCanvas.setDiagnostics`). */\n resolve(path: string, options?: { diagnostics?: boolean }): Promise<FileResolution>;\n renameBlock(path: string, blockId: string, newName: string): RenameResult | Promise<RenameResult>;\n}\n\ninterface ProjectFile {\n text: string;\n version: number;\n model: FileModel;\n snapshot?: TextSnapshot;\n usages?: Usage[];\n usagesProjectVersion?: number;\n /** Module specifiers resolved to project paths, for finding the files that import this one. */\n imports?: FileImports & { fileSetVersion: number; fileVersion: number };\n}\n\nconst LIB_DIR = '/__lib__/';\nconst DEFAULT_LIB = ['lib.es2022.d.ts', 'lib.dom.d.ts'];\n/** The program of the files no config covers. */\nconst NO_CONFIG = '';\n\ninterface FileImports {\n /** Files it imports or re-exports from. */\n importedPaths: Set<string>;\n /** Files it re-exports from (`export { x } from './x'`, `export * from './x'`). */\n reExportedPaths: Set<string>;\n}\n\n/** `const x = require('./x')` in CommonJS files. */\nconst REQUIRE_CALL = /\\brequire\\s*\\(\\s*(['\"])([^'\"]+)\\1\\s*\\)/;\n\n/** `export { x } from './x'`, `export * from './x'`, `export * as x from './x'`, with or without `type`. */\nconst RE_EXPORT = /^export\\s+(?:type\\s+)?(?:\\*(?:\\s+as\\s+[\\w$]+)?|\\{[^}]*\\})\\s*from\\s*(['\"])([^'\"]+)\\1/;\n\n/** What the workspace's configs say for the current set of files. */\ninterface ConfigPrograms {\n fileSetVersion: number;\n /** Compiler options by config path (`NO_CONFIG` for files no config covers). */\n optionsByConfig: Map<string, ts.CompilerOptions>;\n /** The files of each config's program, by config path. */\n pathsByConfig: Map<string, string[]>;\n configOfPath: Map<string, string>;\n}\n\n/**\n * Every file of a folder, parsed into blocks, with TypeScript programs for resolving usages, type\n * errors and renames across files: one per config file (a monorepo has one per package), else one.\n *\n * Two speeds: `setFile` is the per-keystroke path (incremental parse of that file only); usages,\n * diagnostics and renames go through the language service and are meant to run when typing pauses.\n */\nexport class Project implements CanvasProject {\n private files = new Map<string, ProjectFile>();\n private projectVersion = 0;\n private libFiles: Record<string, string> = {};\n private hasLib = false;\n private libOptions: ts.CompilerOptions = {};\n private projectNamesCache: { version: number; names: Set<string> } | null = null;\n private workspace: Workspace | null = null;\n private configPrograms: ConfigPrograms | null = null;\n /** Language services by config path, created when a file of that config is first resolved. */\n private services = new Map<string, ts.LanguageService>();\n /** Shared by the services, so a file several programs include is parsed once. */\n private documentRegistry = ts.createDocumentRegistry(true, '/');\n /** Changes when files are added or removed, or the settings change: where imports point may change then. */\n private fileSetVersion = 0;\n\n constructor(\n files: Record<string, string> = {},\n private projectOptions: ProjectOptions = {},\n ) {\n this.configure(projectOptions);\n for (const [path, text] of Object.entries(files)) this.setFile(path, text);\n }\n\n /** Load the standard library later, e.g. once it has been downloaded. Type errors show from then on. */\n setLibFiles(libFiles: Record<string, string>) {\n this.projectOptions = { ...this.projectOptions, libFiles };\n this.reconfigure();\n }\n\n /** Use the folder's tsconfig.json (or none, with null). */\n setConfigFile(config: ConfigFile | null) {\n this.setWorkspace(config ? { configFiles: [config] } : null);\n }\n\n /** Use the folder's config files and workspace packages (or none, with null). */\n setWorkspace(workspace: Workspace | null) {\n this.workspace = workspace;\n this.reconfigure();\n }\n\n private reconfigure() {\n for (const service of this.services.values()) service.dispose();\n this.services.clear();\n this.configure(this.projectOptions);\n this.projectVersion++;\n this.fileSetVersion++;\n }\n\n private configure(options: ProjectOptions) {\n this.libFiles = options.libFiles ?? {};\n const libEntries = (options.lib ?? DEFAULT_LIB).filter((name) => name in this.libFiles);\n this.hasLib = libEntries.length > 0;\n this.libOptions = this.hasLib ? { lib: libEntries, noLib: false } : { noLib: true };\n }\n\n /** Options for a program: the defaults, then the config's, then `ProjectOptions.compilerOptions`. */\n private compilerOptions(configOptions: ts.CompilerOptions, packagePaths: Record<string, string[]>): ts.CompilerOptions {\n // The config's own aliases win over the ones that point at workspace packages.\n const paths = { ...packagePaths, ...configOptions.paths };\n return {\n target: ts.ScriptTarget.ES2022,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n strict: true,\n jsx: ts.JsxEmit.Preserve,\n skipLibCheck: true,\n allowImportingTsExtensions: true,\n ...configOptions,\n ...(Object.keys(paths).length ? { paths } : {}),\n ...this.projectOptions.compilerOptions,\n // JavaScript files are part of the project even where a tsconfig.json leaves `allowJs` off.\n allowJs: true,\n // The project loads no @types packages, its standard library is the one given here, and it never emits.\n types: [],\n noEmit: true,\n ...this.libOptions,\n };\n }\n\n /** Which config each file uses, and the options of each. Worked out again when files are added or removed. */\n private programs(): ConfigPrograms {\n if (this.configPrograms?.fileSetVersion === this.fileSetVersion) return this.configPrograms;\n const projectPaths = [...this.files.keys()];\n const packagePaths = workspacePackagePaths(this.workspace?.packageFiles ?? {}, (path) => this.files.has(path));\n const configs = (this.workspace?.configFiles ?? []).map((config) => parseConfig(config, projectPaths)).filter((config) => !!config);\n const optionsByConfig = new Map([[NO_CONFIG, this.compilerOptions({}, packagePaths)]]);\n for (const config of configs) optionsByConfig.set(config.path, this.compilerOptions(config.options, packagePaths));\n const pathsByConfig = new Map<string, string[]>();\n const configOfPath = new Map<string, string>();\n for (const path of projectPaths) {\n const configPath = configForFile(path, configs)?.path ?? NO_CONFIG;\n configOfPath.set(path, configPath);\n pathsByConfig.set(configPath, [...(pathsByConfig.get(configPath) ?? []), path]);\n }\n this.configPrograms = { fileSetVersion: this.fileSetVersion, optionsByConfig, pathsByConfig, configOfPath };\n return this.configPrograms;\n }\n\n private configOf(path: string): string {\n return this.programs().configOfPath.get(path) ?? NO_CONFIG;\n }\n\n /** The options a file's imports resolve with: its own config's, whichever program includes it. */\n private optionsOfFile(path: string | null): ts.CompilerOptions {\n const { optionsByConfig } = this.programs();\n return optionsByConfig.get(path ? this.configOf(path) : NO_CONFIG) ?? optionsByConfig.get(NO_CONFIG)!;\n }\n\n private serviceOf(path: string): ts.LanguageService {\n return this.serviceOfConfig(this.configOf(path));\n }\n\n private serviceOfConfig(configPath: string): ts.LanguageService {\n let service = this.services.get(configPath);\n if (!service) {\n service = ts.createLanguageService(this.createHost(configPath), this.documentRegistry);\n this.services.set(configPath, service);\n }\n return service;\n }\n\n // ---------------------------------------------------------------- files (fast path)\n\n /** Add or update a file. Parses only this file, incrementally from its previous version. */\n setFile(path: string, text: string): FileModel {\n const existing = this.files.get(path);\n if (existing && existing.text === text) return existing.model;\n const model = parseStructure(path, text, existing?.model);\n this.files.set(path, { text, version: (existing?.version ?? 0) + 1, model });\n this.projectVersion++;\n if (!existing) this.fileSetVersion++;\n return model;\n }\n\n removeFile(path: string) {\n if (!this.files.delete(path)) return;\n this.projectVersion++;\n this.fileSetVersion++;\n }\n\n hasFile(path: string): boolean {\n return this.files.has(path);\n }\n\n paths(): string[] {\n return [...this.files.keys()];\n }\n\n getModel(path: string): FileModel | undefined {\n return this.files.get(path)?.model;\n }\n\n getText(path: string): string | undefined {\n return this.files.get(path)?.text;\n }\n\n // ---------------------------------------------------------------- resolving (when typing pauses)\n\n resolve(path: string, { diagnostics = true }: { diagnostics?: boolean } = {}): Promise<FileResolution> {\n return Promise.resolve({ usages: this.usages(path), incoming: this.usagesInto(path), diagnostics: diagnostics ? this.diagnostics(path) : [] });\n }\n\n /** Usage links from this file: within the file, and to blocks in other files (`toPath`). */\n usages(path: string): Usage[] {\n const file = this.files.get(path);\n if (!file) return [];\n if (file.usages && file.usagesProjectVersion === this.projectVersion) return file.usages;\n const program = this.serviceOf(path).getProgram();\n const sf = program?.getSourceFile(toFileName(path));\n const builder = builderOf(file.model);\n if (!program || !sf || !builder || sf.text !== file.text) return [];\n file.usages = builder.collectUsages(sf, program.getTypeChecker(), this.otherFileResolver());\n file.usagesProjectVersion = this.projectVersion;\n return file.usages;\n }\n\n /** Usages in other files that point at blocks in this file. */\n usagesInto(path: string): IncomingUsage[] {\n const incoming: IncomingUsage[] = [];\n for (const otherPath of this.importersThroughReExports(path)) {\n for (const usage of this.usages(otherPath)) {\n if (usage.toPath === path) incoming.push({ ...usage, fromPath: otherPath });\n }\n }\n return incoming;\n }\n\n /** Syntax errors, plus type errors when the standard library is loaded and the syntax is valid. */\n diagnostics(path: string): CodeDiagnostic[] {\n const file = this.files.get(path);\n if (!file) return [];\n const hasSyntaxErrors = file.model.diagnostics.length > 0;\n if (hasSyntaxErrors || !this.hasLib) return file.model.diagnostics;\n const service = this.serviceOf(path);\n const sf = service.getProgram()?.getSourceFile(toFileName(path));\n if (!sf || sf.text !== file.text) return [];\n return service.getSemanticDiagnostics(toFileName(path)).map((d) => toCodeDiagnostic(file.model, sf, d, 'type'));\n }\n\n /**\n * Text edits that rename a block and every usage of it, in every file of the project.\n * Usages in other files are renamed too, including imports (no `as` aliases are added).\n */\n renameBlock(path: string, blockId: string, newName: string): RenameResult {\n const file = this.files.get(path);\n const block = file?.model.blocks.get(blockId);\n if (!file || !block) return { ok: false, error: 'Block not found' };\n const isRenamable = block.nameStart >= 0 && block.kind !== 'import' && block.kind !== 'statement' && block.name !== 'constructor';\n if (!isRenamable) return { ok: false, error: `${block.name} can't be renamed` };\n if (newName === block.name) return { ok: true, edits: {} };\n if (!isValidIdentifier(newName)) return { ok: false, error: `\"${newName}\" is not a valid name` };\n if (namesVisibleFrom(file.model, block).has(newName)) return { ok: false, error: `${newName} already exists here` };\n if (file.model.diagnostics.length) return { ok: false, error: `Fix the syntax error on line ${file.model.firstErrorLine} first` };\n\n const fileName = toFileName(path);\n const info = this.serviceOf(path).getRenameInfo(fileName, block.nameStart, { allowRenameOfImportPath: false });\n if (!info.canRename) return { ok: false, error: info.localizedErrorMessage };\n const edits: Record<string, TextEdit[]> = {};\n const renamedLocations = new Set<string>();\n // Each program finds the usages in its own files; in a monorepo the importers can be in other packages.\n for (const configPath of this.configsUsing(path)) {\n const service = this.serviceOfConfig(configPath);\n if (!service.getProgram()?.getSourceFile(fileName)) continue;\n // Where an alias is dropped (`export { newName as oldName }`), the names imported through it change too.\n const renameStarts = [{ fileName, position: block.nameStart }];\n const visitedStarts = new Set<string>();\n for (let start = renameStarts.pop(); start; start = renameStarts.pop()) {\n const startKey = `${start.fileName}:${start.position}`;\n if (visitedStarts.has(startKey)) continue;\n visitedStarts.add(startKey);\n const locations = service.findRenameLocations(start.fileName, start.position, false, false, { providePrefixAndSuffixTextForRename: true }) ?? [];\n for (const location of locations) {\n const locationPath = fromFileName(location.fileName);\n if (!locationPath) continue;\n if (isAliasInSpecifier(location)) renameStarts.push({ fileName: location.fileName, position: location.textSpan.start });\n const locationKey = `${location.fileName}:${location.textSpan.start}`;\n if (renamedLocations.has(locationKey)) continue;\n renamedLocations.add(locationKey);\n const text = isAliasInSpecifier(location) ? newName : (location.prefixText ?? '') + newName + (location.suffixText ?? '');\n (edits[locationPath] ??= []).push({ start: location.textSpan.start, end: location.textSpan.start + location.textSpan.length, text });\n }\n }\n }\n for (const fileEdits of Object.values(edits)) fileEdits.sort((a, b) => a.start - b.start);\n return { ok: true, edits };\n }\n\n // ---------------------------------------------------------------- internals\n\n /** The configs of a file and of the files that can use its blocks: its importers, also through re-exports. */\n private configsUsing(path: string): string[] {\n const owner = this.configOf(path);\n const importerConfigs = this.importersThroughReExports(path).map((importer) => this.configOf(importer));\n return [owner, ...new Set(importerConfigs.filter((configPath) => configPath !== owner))];\n }\n\n /** Files that import `path`, or import a file that re-exports from it (an `index.ts` of a folder or package). */\n private importersThroughReExports(path: string): string[] {\n const importers = new Set<string>();\n const reExporters = [path];\n for (let reExported = reExporters.pop(); reExported !== undefined; reExported = reExporters.pop()) {\n for (const importer of this.importersOf(reExported)) {\n if (importers.has(importer) || importer === path) continue;\n importers.add(importer);\n if (this.importsOf(importer).reExportedPaths.has(reExported)) reExporters.push(importer);\n }\n }\n return [...importers];\n }\n\n private otherFileResolver(): OtherFileResolver {\n return {\n projectNames: this.projectNames(),\n blockInOtherFile: (declaration) => {\n const sf = declaration.getSourceFile();\n const path = fromFileName(sf.fileName);\n const file = path ? this.files.get(path) : undefined;\n if (!path || !file || file.text !== sf.text) return null;\n const id = builderOf(file.model)?.blockIdForDeclaration(declaration);\n return id ? { path, id } : null;\n },\n };\n }\n\n private projectNames(): Set<string> {\n if (this.projectNamesCache?.version === this.projectVersion) return this.projectNamesCache.names;\n const names = new Set<string>();\n for (const file of this.files.values()) for (const name of builderOf(file.model)?.names ?? []) names.add(name);\n this.projectNamesCache = { version: this.projectVersion, names };\n return names;\n }\n\n /** Files whose imports resolve to `path`. */\n private importersOf(path: string): string[] {\n const importers: string[] = [];\n for (const [otherPath, file] of this.files) {\n if (otherPath !== path && this.importsOf(otherPath, file).importedPaths.has(path)) importers.push(otherPath);\n }\n return importers;\n }\n\n private importsOf(path: string, file = this.files.get(path)!): FileImports {\n if (file.imports?.fileSetVersion === this.fileSetVersion && file.imports.fileVersion === file.version) return file.imports;\n const importedPaths = new Set<string>();\n const reExportedPaths = new Set<string>();\n const host = this.moduleResolutionHost();\n const resolve = (specifier: string) => {\n const result = ts.resolveModuleName(specifier, toFileName(path), this.optionsOfFile(path), host).resolvedModule;\n return result ? fromFileName(result.resolvedFileName) : null;\n };\n for (const block of file.model.roots) {\n const code = block.kind === 'statement' || block.kind === 'variable' ? file.text.slice(block.start, block.end) : '';\n const reExportSpecifier = block.kind === 'statement' ? RE_EXPORT.exec(code)?.[2] : undefined;\n const requiredSpecifier = block.kind === 'variable' ? REQUIRE_CALL.exec(code)?.[2] : undefined;\n const specifier = block.kind === 'import' ? block.name : (reExportSpecifier ?? requiredSpecifier);\n const target = specifier ? resolve(specifier) : null;\n if (!target) continue;\n importedPaths.add(target);\n if (reExportSpecifier) reExportedPaths.add(target);\n }\n file.imports = { importedPaths, reExportedPaths, fileSetVersion: this.fileSetVersion, fileVersion: file.version };\n return file.imports;\n }\n\n private moduleResolutionHost(): ts.ModuleResolutionHost {\n return {\n fileExists: (name) => this.fileExists(name),\n readFile: (name) => this.readFile(name),\n directoryExists: (dir) => this.directoryExists(dir),\n getCurrentDirectory: () => '/',\n };\n }\n\n private fileExists(name: string): boolean {\n if (name.startsWith(LIB_DIR)) return name.slice(LIB_DIR.length) in this.libFiles;\n const path = fromFileName(name);\n return !!path && this.files.has(path);\n }\n\n private readFile(name: string): string | undefined {\n if (name.startsWith(LIB_DIR)) return this.libFiles[name.slice(LIB_DIR.length)];\n const path = fromFileName(name);\n return path ? this.files.get(path)?.text : undefined;\n }\n\n private directoryExists(dir: string): boolean {\n const prefix = dir.replace(/^\\//, '').replace(/\\/?$/, '/');\n if (prefix === '/') return true;\n for (const path of this.files.keys()) if (path.startsWith(prefix)) return true;\n return false;\n }\n\n /** The host of one config's program. Its files are those that use the config; their imports come in from the rest. */\n private createHost(configPath: string): ts.LanguageServiceHost {\n return {\n getCompilationSettings: () => this.programs().optionsByConfig.get(configPath) ?? this.programs().optionsByConfig.get(NO_CONFIG)!,\n getProjectVersion: () => String(this.projectVersion),\n getScriptFileNames: () => (this.programs().pathsByConfig.get(configPath) ?? []).map(toFileName),\n getScriptVersion: (name) => {\n if (name.startsWith(LIB_DIR)) return '0';\n const path = fromFileName(name);\n return String((path && this.files.get(path)?.version) ?? 0);\n },\n getScriptSnapshot: (name) => {\n if (name.startsWith(LIB_DIR)) {\n const text = this.libFiles[name.slice(LIB_DIR.length)];\n return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text);\n }\n const path = fromFileName(name);\n const file = path ? this.files.get(path) : undefined;\n if (!file) return undefined;\n file.snapshot ??= new TextSnapshot(file.text);\n return file.snapshot;\n },\n getCurrentDirectory: () => '/',\n // A file another package's program pulls in keeps its own package's aliases.\n resolveModuleNameLiterals: (moduleLiterals, containingFile) => {\n const containingPath = fromFileName(containingFile);\n const options = this.optionsOfFile(containingPath);\n const host = this.moduleResolutionHost();\n return moduleLiterals.map((literal) => ts.resolveModuleName(literal.text, containingFile, options, host));\n },\n getDefaultLibFileName: () => LIB_DIR + 'lib.d.ts',\n fileExists: (name) => this.fileExists(name),\n readFile: (name) => this.readFile(name),\n directoryExists: (dir) => this.directoryExists(dir),\n getDirectories: () => [],\n useCaseSensitiveFileNames: () => true,\n };\n }\n}\n\n/**\n * TypeScript keeps names stable when renaming across an import or export (`import { newName as old }`).\n * Here a rename updates every usage, so specifiers get the plain new name instead.\n */\nfunction isAliasInSpecifier(location: ts.RenameLocation): boolean {\n return /\\bas\\s*$/.test(location.prefixText ?? '') || /^\\s*as\\b/.test(location.suffixText ?? '');\n}\n\n/** Lets the language service re-parse only the changed region of a file. */\nclass TextSnapshot implements ts.IScriptSnapshot {\n constructor(readonly text: string) {}\n getText(start: number, end: number) {\n return this.text.slice(start, end);\n }\n getLength() {\n return this.text.length;\n }\n getChangeRange(old: ts.IScriptSnapshot): ts.TextChangeRange | undefined {\n if (!(old instanceof TextSnapshot)) return undefined;\n return changedRegion(old.text, this.text);\n }\n}\n\nfunction changedRegion(before: string, after: string): ts.TextChangeRange {\n let start = 0;\n const shorter = Math.min(before.length, after.length);\n while (start < shorter && before.charCodeAt(start) === after.charCodeAt(start)) start++;\n let fromEnd = 0;\n while (fromEnd < shorter - start && before.charCodeAt(before.length - 1 - fromEnd) === after.charCodeAt(after.length - 1 - fromEnd)) fromEnd++;\n return ts.createTextChangeRange(ts.createTextSpan(start, before.length - fromEnd - start), after.length - fromEnd - start);\n}\n\n/** Project paths are relative (`src/cart.ts`); TypeScript sees them as absolute (`/src/cart.ts`). */\nfunction toFileName(path: string): string {\n return '/' + path;\n}\n\nfunction fromFileName(name: string): string | null {\n if (name.startsWith(LIB_DIR) || !name.startsWith('/')) return null;\n return name.slice(1);\n}\n\n/** Names a renamed block could clash with: its siblings, and outside classes every enclosing scope. */\nfunction namesVisibleFrom(model: FileModel, block: Block): Set<string> {\n const names = new Set<string>();\n const siblings = block.parentId ? model.blocks.get(block.parentId)!.children : model.roots;\n for (const sibling of siblings) if (sibling !== block) names.add(sibling.name);\n let parent = block.parentId ? model.blocks.get(block.parentId) : undefined;\n const isClassMember = parent?.insert === 'class';\n if (isClassMember) return names;\n while (parent) {\n const parentSiblings = parent.parentId ? model.blocks.get(parent.parentId)!.children : model.roots;\n for (const scopeBlock of [...parent.children, ...parentSiblings]) if (scopeBlock !== block) names.add(scopeBlock.name);\n parent = parent.parentId ? model.blocks.get(parent.parentId) : undefined;\n }\n return names;\n}\n\nfunction isValidIdentifier(name: string): boolean {\n const scanner = ts.createScanner(ts.ScriptTarget.Latest, true, ts.LanguageVariant.Standard, name);\n const token = scanner.scan();\n const isWholeText = scanner.getTokenEnd() === name.length && name.length > 0;\n // Contextual keywords (`type`, `of`, `async`\u2026) are valid names; reserved words are not.\n const isNameToken = token === ts.SyntaxKind.Identifier || (token > ts.SyntaxKind.LastReservedWord && token <= ts.SyntaxKind.LastKeyword);\n return isWholeText && isNameToken;\n}\n\n", "import ts from 'typescript';\n\n/**\n * A TypeScript config file of the folder (`tsconfig.json`, `tsconfig.app.json`, `jsconfig.json`).\n * Path aliases, `baseUrl` and module resolution decide which file an import points at.\n */\nexport interface ConfigFile {\n /** Project path, e.g. `tsconfig.json` or `packages/web/tsconfig.app.json`. */\n path: string;\n text: string;\n /** Configs it `extends`, by project path. Only relative `extends` are followed. */\n extendedFiles?: Record<string, string>;\n}\n\n/**\n * The folder's TypeScript settings. In a monorepo every package can have its own config: a file\n * uses the nearest config above it that includes it (`files`, `include`, `exclude`), as in VS Code.\n */\nexport interface Workspace {\n configFiles: ConfigFile[];\n /**\n * `package.json` files by project path. Packages of the workspace import each other by name\n * (`@acme/utils`); without `node_modules`, the name is resolved to the package's source.\n */\n packageFiles?: Record<string, string>;\n}\n\n/** One config file, read: its options, and which of the project's files it includes. */\nexport interface ParsedConfig {\n path: string;\n /** Folder of the config, `''` at the root, else ending in `/`. */\n folder: string;\n options: ts.CompilerOptions;\n includes(projectPath: string): boolean;\n}\n\n/** Read a config file. `projectPaths` are the project's files, for its `include` and `exclude` patterns. */\nexport function parseConfig(config: ConfigFile, projectPaths: string[]): ParsedConfig | null {\n const configFileName = '/' + config.path;\n const json = ts.parseConfigFileTextToJson(configFileName, config.text);\n if (json.error || !json.config) return null;\n const readConfig = (name: string) => (name === configFileName ? config.text : config.extendedFiles?.[name.slice(1)]);\n const host: ts.ParseConfigHost = {\n useCaseSensitiveFileNames: true,\n readDirectory: (rootDir, extensions, excludes, includes) => matchingPaths(projectPaths, rootDir, extensions, excludes ?? [], includes ?? ['**/*']),\n fileExists: (name) => readConfig(name) !== undefined,\n readFile: readConfig,\n };\n const folder = config.path.slice(0, config.path.lastIndexOf('/') + 1);\n const parsed = ts.parseJsonConfigFileContent(json.config, host, '/' + folder, undefined, configFileName);\n const included = new Set(parsed.fileNames.map((name) => name.slice(1)));\n return { path: config.path, folder, options: parsed.options, includes: (projectPath) => included.has(projectPath) };\n}\n\n/**\n * The config a file uses: the nearest one above it that includes it; failing that, the nearest one\n * above it (a file left out still gets its package's aliases). Null: no config is above it.\n */\nexport function configForFile(projectPath: string, configs: ParsedConfig[]): ParsedConfig | null {\n const above = configs.filter((config) => projectPath.startsWith(config.folder));\n const nearestFirst = [...above].sort((a, b) => b.folder.length - a.folder.length);\n return nearestFirst.find((config) => config.includes(projectPath)) ?? nearestFirst[0] ?? null;\n}\n\n/**\n * Path aliases that point each workspace package's name at its source: the file its `package.json`\n * names (`types`, `exports`, `module`, `main`), its TypeScript source when that is a build output\n * (`dist/index.js` \u2192 `src/index.ts`), or `src/index.ts`.\n */\nexport function workspacePackagePaths(packageFiles: Record<string, string>, hasFile: (projectPath: string) => boolean): Record<string, string[]> {\n const paths: Record<string, string[]> = {};\n for (const [packagePath, text] of Object.entries(packageFiles)) {\n const manifest = parsePackageJson(text);\n if (!manifest?.name) continue;\n const folder = packagePath.slice(0, packagePath.lastIndexOf('/') + 1);\n const entry = packageEntries(manifest)\n .flatMap((named) => [named, ...sourceOfBuildOutput(named)])\n .concat(['src/index.ts', 'src/index.tsx', 'index.ts', 'index.tsx'])\n .map((relative) => folder + relative.replace(/^\\.\\//, ''))\n .find(hasFile);\n if (entry) paths[manifest.name] = ['/' + entry];\n paths[manifest.name + '/*'] = ['/' + folder + 'src/*', '/' + folder + '*'];\n }\n return paths;\n}\n\ninterface PackageJson {\n name?: string;\n types?: string;\n typings?: string;\n module?: string;\n main?: string;\n exports?: unknown;\n}\n\nfunction parsePackageJson(text: string): PackageJson | null {\n try {\n const value: unknown = JSON.parse(text);\n return value && typeof value === 'object' ? (value as PackageJson) : null;\n } catch {\n return null;\n }\n}\n\n/** The files a package.json points at, most specific first. */\nfunction packageEntries(manifest: PackageJson): string[] {\n const rootExport = manifest.exports && typeof manifest.exports === 'object' && '.' in manifest.exports ? (manifest.exports as Record<string, unknown>)['.'] : manifest.exports;\n return [manifest.types, manifest.typings, ...exportTargets(rootExport), manifest.module, manifest.main].filter((entry): entry is string => typeof entry === 'string');\n}\n\n/** `\"./dist/index.js\"`, or the targets of conditions (`types`, `import`, `default`\u2026), in their order. */\nfunction exportTargets(target: unknown): string[] {\n if (typeof target === 'string') return [target];\n if (Array.isArray(target)) return target.flatMap(exportTargets);\n if (target && typeof target === 'object') return Object.values(target).flatMap(exportTargets);\n return [];\n}\n\n/** `dist/index.js` \u2192 `src/index.ts`, `src/index.tsx`, `dist/index.ts`\u2026 (built files aren't in the project). */\nfunction sourceOfBuildOutput(entry: string): string[] {\n const isBuildOutput = /\\.(d\\.ts|d\\.mts|js|mjs|cjs|jsx)$/.test(entry);\n if (!isBuildOutput) return [];\n const withoutExtension = entry.replace(/\\.(d\\.ts|d\\.mts|js|mjs|cjs|jsx)$/, '');\n const inSourceFolder = withoutExtension.replace(/(^|\\/)(dist|lib|build|out|esm|cjs)\\//, '$1src/');\n return [inSourceFolder, withoutExtension].flatMap((base) => [base + '.ts', base + '.tsx']);\n}\n\n/** Project files under `rootDir` with one of `extensions`, matching an include pattern and no exclude pattern. */\nfunction matchingPaths(projectPaths: string[], rootDir: string, extensions: readonly string[], excludes: readonly string[], includes: readonly string[]): string[] {\n const base = rootDir.replace(/^\\//, '').replace(/\\/?$/, '/').replace(/^\\/$/, '');\n const includePatterns = includes.map((spec) => configPattern(base, spec, 'files'));\n const excludePatterns = excludes.map((spec) => configPattern(base, spec, 'filesAndFolders'));\n return projectPaths\n .filter((path) => path.startsWith(base) && extensions.some((extension) => path.endsWith(extension)))\n .filter((path) => includePatterns.some((pattern) => pattern.test(path)) && !excludePatterns.some((pattern) => pattern.test(path)))\n .map((path) => '/' + path);\n}\n\n/**\n * A tsconfig `include`/`exclude` pattern as a regular expression over project paths: `*` and `?`\n * within a folder, `**` for any folders; a pattern without wildcards in its last part is a folder.\n */\nfunction configPattern(base: string, spec: string, matching: 'files' | 'filesAndFolders'): RegExp {\n const absolute = spec.startsWith('/') ? spec.slice(1) : normalizePath(base + spec.replace(/^\\.\\//, ''));\n const lastPart = absolute.slice(absolute.lastIndexOf('/') + 1);\n const isFolder = !/[*?]/.test(lastPart) && !/\\.[^.]+$/.test(lastPart);\n const pattern = isFolder ? absolute.replace(/\\/?$/, '/**/*') : absolute;\n let source = '';\n for (let index = 0; index < pattern.length; index++) {\n const char = pattern[index];\n if (pattern.startsWith('**/', index)) {\n source += '(?:[^/]+/)*';\n index += 2;\n } else if (char === '*') source += '[^/]*';\n else if (char === '?') source += '[^/]';\n else source += char.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&');\n }\n return new RegExp(`^${source}${matching === 'filesAndFolders' ? '(?:/.*)?' : ''}$`);\n}\n\n/** `a/./b/../c` \u2192 `a/c` */\nfunction normalizePath(path: string): string {\n const parts: string[] = [];\n for (const part of path.split('/')) {\n if (part === '..') parts.pop();\n else if (part !== '.' && part !== '') parts.push(part);\n }\n return parts.join('/');\n}\n", "import { parseStructure } from './parse';\nimport type { CanvasProject, ConfigFile, FileResolution, RenameResult, Workspace } from './project';\nimport type { ProjectServerMethod } from './projectServer';\nimport type { FileModel } from './types';\n\n/** Sends one call to the `ProjectServer` (in a worker) and resolves with its result. Calls arrive in order. */\nexport type ProjectServerCall = (method: ProjectServerMethod, args: unknown[]) => Promise<unknown>;\n\ninterface RemoteFile {\n text: string;\n /** Blocks of `text`, or of an older text while nothing asked for this file since it changed. */\n model?: FileModel;\n}\n\n/**\n * The canvas's project when the TypeScript work runs in a worker. The main thread only parses files\n * into blocks (the per-keystroke path, and lazily for files no canvas shows); usage links, errors and\n * renames are computed by a `ProjectServer` in the worker.\n */\nexport class RemoteProject implements CanvasProject {\n private files = new Map<string, RemoteFile>();\n\n constructor(private callServer: ProjectServerCall) {}\n\n /** Load many files at once. They're parsed in the worker; here only when a canvas needs them. */\n setFiles(files: Record<string, string>) {\n for (const [path, text] of Object.entries(files)) this.files.set(path, { text });\n void this.callServer('setFiles', [files]);\n }\n\n setFile(path: string, text: string): FileModel {\n this.setFileText(path, text);\n return this.getModel(path)!;\n }\n\n /** Update a file no canvas shows (e.g. typed in a text editor): no parse on this thread. */\n setFileText(path: string, text: string) {\n const existing = this.files.get(path);\n if (existing?.text === text) return;\n this.files.set(path, { text, model: existing?.model });\n void this.callServer('setFile', [path, text]);\n }\n\n removeFile(path: string) {\n if (!this.files.delete(path)) return;\n void this.callServer('removeFile', [path]);\n }\n\n setLibFiles(libFiles: Record<string, string>) {\n void this.callServer('setLibFiles', [libFiles]);\n }\n\n /** The folder's tsconfig.json (or none, with null). */\n setConfigFile(config: ConfigFile | null) {\n void this.callServer('setConfigFile', [config]);\n }\n\n /** The folder's config files (one per package in a monorepo) and package.json files (or none, with null). */\n setWorkspace(workspace: Workspace | null) {\n void this.callServer('setWorkspace', [workspace]);\n }\n\n getModel(path: string): FileModel | undefined {\n const file = this.files.get(path);\n if (!file) return undefined;\n const isModelOfCurrentText = file.model?.text === file.text;\n if (!isModelOfCurrentText) file.model = parseStructure(path, file.text, file.model);\n return file.model;\n }\n\n getText(path: string): string | undefined {\n return this.files.get(path)?.text;\n }\n\n paths(): string[] {\n return [...this.files.keys()];\n }\n\n resolve(path: string, options?: { diagnostics?: boolean }): Promise<FileResolution> {\n return this.callServer('resolve', [path, options]) as Promise<FileResolution>;\n }\n\n renameBlock(path: string, blockId: string, newName: string): Promise<RenameResult> {\n return this.callServer('renameBlock', [path, blockId, newName]) as Promise<RenameResult>;\n }\n}\n", "import { Project, type ConfigFile, type FileResolution, type RenameResult, type Workspace } from './project';\n\n/** Methods a `RemoteProject` can call. Arguments and results are plain data, so any message channel carries them. */\nconst SERVER_METHODS = ['setLibFiles', 'setConfigFile', 'setWorkspace', 'setFiles', 'setFile', 'removeFile', 'resolve', 'renameBlock'] as const;\nexport type ProjectServerMethod = (typeof SERVER_METHODS)[number];\n\n/** A `Project` behind plain-data methods: the worker side of a `RemoteProject`. */\nexport class ProjectServer {\n private project = new Project();\n\n setLibFiles(libFiles: Record<string, string>) {\n this.project.setLibFiles(libFiles);\n }\n\n setConfigFile(config: ConfigFile | null) {\n this.project.setConfigFile(config);\n }\n\n setWorkspace(workspace: Workspace | null) {\n this.project.setWorkspace(workspace);\n }\n\n setFiles(files: Record<string, string>) {\n for (const [path, text] of Object.entries(files)) this.project.setFile(path, text);\n }\n\n setFile(path: string, text: string) {\n this.project.setFile(path, text);\n }\n\n removeFile(path: string) {\n this.project.removeFile(path);\n }\n\n resolve(path: string, options?: { diagnostics?: boolean }): Promise<FileResolution> {\n return this.project.resolve(path, options);\n }\n\n renameBlock(path: string, blockId: string, newName: string): RenameResult {\n return this.project.renameBlock(path, blockId, newName);\n }\n}\n\nexport function callProjectServer(server: ProjectServer, method: string, args: unknown[]): unknown {\n const isServerMethod = (SERVER_METHODS as readonly string[]).includes(method);\n if (!isServerMethod) throw new Error(`Unknown project method: ${method}`);\n return (server[method as ProjectServerMethod] as (...args: unknown[]) => unknown)(...args);\n}\n", "import { callProjectServer, ProjectServer } from './projectServer';\nimport { RemoteProject } from './remoteProject';\n\n/** The part of a `Worker`, the worker's `self`, or a `MessagePort` that the project calls use. */\nexport interface MessagePortLike {\n postMessage(message: unknown): void;\n addEventListener(type: 'message', listener: (event: { data: unknown }) => void): void;\n /** MessagePorts only deliver messages after `start()`. */\n start?(): void;\n}\n\ninterface ProjectRequest {\n id: number;\n method: string;\n args: unknown[];\n}\n\ntype ProjectReply = { id: number; result: unknown } | { id: number; error: string };\n\n/** In a worker script: answer the `RemoteProject` on the other side of `port` (usually `self`). */\nexport function serveProject(port: MessagePortLike) {\n const server = new ProjectServer();\n port.addEventListener('message', async (event) => {\n const { id, method, args } = event.data as ProjectRequest;\n try {\n port.postMessage({ id, result: await callProjectServer(server, method, args) } satisfies ProjectReply);\n } catch (error) {\n port.postMessage({ id, error: error instanceof Error ? error.message : String(error) } satisfies ProjectReply);\n }\n });\n port.start?.();\n}\n\n/** On the main thread: a project whose TypeScript work runs in the worker behind `port`. */\nexport function connectProjectWorker(port: MessagePortLike): RemoteProject {\n let nextId = 0;\n const waiting = new Map<number, { resolve(result: unknown): void; reject(error: Error): void }>();\n port.addEventListener('message', (event) => {\n const reply = event.data as ProjectReply;\n const caller = waiting.get(reply.id);\n waiting.delete(reply.id);\n if ('error' in reply) caller?.reject(new Error(reply.error));\n else caller?.resolve(reply.result);\n });\n port.start?.();\n return new RemoteProject((method, args) => {\n const id = nextId++;\n port.postMessage({ id, method, args } satisfies ProjectRequest);\n return new Promise((resolve, reject) => waiting.set(id, { resolve, reject }));\n });\n}\n", "import ts from 'typescript';\nimport type { Block, FileModel } from './types';\n\n/** A single text replacement. */\nexport interface TextEdit {\n start: number;\n end: number;\n text: string;\n}\n\nexport function applyEdit(text: string, e: TextEdit): string {\n return text.slice(0, e.start) + e.text + text.slice(e.end);\n}\n\n/** Apply edits that don't overlap, given as offsets into the original text. */\nexport function applyEdits(text: string, edits: TextEdit[]): string {\n const lastFirst = [...edits].sort((a, b) => b.start - a.start);\n return lastFirst.reduce(applyEdit, text);\n}\n\n/** Result of a structural edit: the text change plus the id the new block will have. */\nexport interface InsertResult {\n edit: TextEdit;\n id: string;\n /** Selection to put in the editor, relative to the new block's start. */\n select: [number, number];\n}\n\nexport function replaceBlock(model: FileModel, id: string, code: string): TextEdit {\n const b = must(model, id);\n return { start: b.start, end: b.end, text: code };\n}\n\n/** Remove a block and the blank space it leaves behind. */\nexport function deleteBlock(model: FileModel, id: string): TextEdit {\n const b = must(model, id);\n const t = model.text;\n let start = t.lastIndexOf('\\n', b.start - 1) + 1; // include indentation\n if (/\\S/.test(t.slice(start, b.start))) start = b.start; // something else shares the line\n let end = b.end;\n const trail = /^[ \\t]*;?[ \\t]*(\\r?\\n)?/.exec(t.slice(end))!;\n end += trail[0].length;\n // Collapse surrounding blank lines to at most one.\n const before = /(\\r?\\n[ \\t]*)*$/.exec(t.slice(0, start))![0];\n const after = /^([ \\t]*\\r?\\n)*/.exec(t.slice(end))![0];\n const blankBefore = (before.match(/\\n/g) ?? []).length;\n const blankAfter = (after.match(/\\n/g) ?? []).length;\n if (blankBefore >= 2 && blankAfter >= 1) end += after.length;\n else if (start === 0 && blankAfter) end += after.length;\n return { start, end, text: '' };\n}\n\n/** Pick a name that isn't taken in the block's scope. */\nexport function uniqueName(model: FileModel, parentId: string | null, base: string): string {\n const taken = new Set<string>();\n const sibs = parentId ? must(model, parentId).children : model.roots;\n for (const s of sibs) taken.add(s.name);\n // Names in the file scope are visible everywhere, so avoid those too.\n for (const r of model.roots) taken.add(r.name);\n if (!taken.has(base)) return base;\n let n = 2;\n while (taken.has(base + n)) n++;\n return base + n;\n}\n\n/** Where nested code can go: the block itself if it can hold code, else its nearest container. */\nexport function containerFor(model: FileModel, id: string | null): Block | null {\n let b = id ? model.blocks.get(id) ?? null : null;\n while (b && !b.insert) b = b.parentId ? model.blocks.get(b.parentId) ?? null : null;\n return b;\n}\n\nexport function newFunction(model: FileModel, parentId: string | null, base = 'newFunction'): InsertResult {\n const parent = containerFor(model, parentId);\n const name = uniqueName(model, parent?.id ?? null, base);\n const u = model.indentUnit;\n const code = parent?.insert === 'class' ? `${name}() {\\n${u}\\n}` : `function ${name}() {\\n${u}\\n}`;\n const nameAt = code.indexOf(name);\n return insertCode(model, parent, code, name, [nameAt, nameAt + name.length]);\n}\n\n/** What the clipboard holds after copying a block. */\nexport interface BlockClip {\n code: string;\n name: string;\n kind: Block['kind'];\n /** Copied from inside a class (method/property syntax). */\n fromClass: boolean;\n}\n\nexport function copyBlock(model: FileModel, id: string): BlockClip {\n const b = must(model, id);\n const parent = b.parentId ? model.blocks.get(b.parentId) : null;\n return {\n code: dedent(model.text.slice(b.start, b.end), b.indent),\n name: b.name,\n kind: b.kind,\n fromClass: parent?.insert === 'class',\n };\n}\n\n/** Paste a copied block into `parentId` (or the file), converting method \u2194 function syntax as needed. */\nexport function pasteBlock(model: FileModel, parentId: string | null, clip: BlockClip): InsertResult {\n const parent = containerFor(model, parentId);\n const toClass = parent?.insert === 'class';\n let code = clip.code;\n if (toClass && !clip.fromClass) code = toMember(code);\n if (!toClass && clip.fromClass) code = toTopLevel(code);\n if (!clip.name) {\n // Not a declaration (plain statements): insert as-is; it becomes a statement block.\n const r = insertCode(model, parent, code, '', [0, 0]);\n return { ...r, id: '' };\n }\n const name = uniqueName(model, parent?.id ?? null, clip.name);\n if (name !== clip.name) code = renameDeclaration(code, toClass, name);\n return insertCode(model, parent, code, name, [0, 0]);\n}\n\nfunction insertCode(model: FileModel, parent: Block | null, code: string, name: string, select: [number, number]): InsertResult {\n const t = model.text;\n const key = name; // the parser keys declarations by name\n const id = parent ? `${parent.id}/${key}` : key;\n if (!parent) {\n const end = t.trimEnd().length;\n const sep = end === 0 ? '' : '\\n\\n';\n return { edit: { start: end, end: t.length, text: sep + code + '\\n' }, id, select };\n }\n const indent = parent.indent + model.indentUnit;\n const body = reindent(code, indent);\n const at = parent.insertAt;\n const lineStart = t.lastIndexOf('\\n', at - 1) + 1;\n if (!/\\S/.test(t.slice(lineStart, at))) {\n // Closing brace (or the trailing return) is on its own line: insert above it.\n const prevLineEnd = lineStart - 1;\n const prevLineStart = t.lastIndexOf('\\n', prevLineEnd - 1) + 1;\n const prevLine = t.slice(prevLineStart, prevLineEnd);\n const opener = /\\{\\s*$/.test(prevLine);\n const lead = opener || !/\\S/.test(prevLine) ? '' : '\\n';\n const trail = t[at] === '}' ? '' : '\\n';\n return { edit: { start: lineStart, end: lineStart, text: lead + indent + body + '\\n' + trail }, id, select };\n }\n // Brace on the same line, e.g. `class A {}`.\n return { edit: { start: at, end: at, text: '\\n' + indent + body + '\\n' + parent.indent }, id, select };\n}\n\nfunction reindent(code: string, indent: string): string {\n return code\n .split('\\n')\n .map((l, i) => (i === 0 || l === '' ? l : indent + l))\n .join('\\n');\n}\n\nfunction dedent(code: string, indent: string): string {\n if (!indent) return code;\n return code\n .split('\\n')\n .map((l, i) => (i > 0 && l.startsWith(indent) ? l.slice(indent.length) : l))\n .join('\\n');\n}\n\n/** `export async function f()` \u2192 `async f()`; `const x = 1;` \u2192 `x = 1;` */\nfunction toMember(code: string): string {\n const fn = /^((?:\\/\\*[\\s\\S]*?\\*\\/|\\/\\/[^\\n]*|\\s)*)(?:export\\s+)?(?:default\\s+)?(async\\s+)?function\\s*(\\*?)\\s*/.exec(code);\n if (fn) return fn[1] + (fn[2] ?? '') + fn[3] + code.slice(fn[0].length);\n const v = /^((?:\\/\\*[\\s\\S]*?\\*\\/|\\/\\/[^\\n]*|\\s)*)(?:export\\s+)?(?:const|let|var)\\s+/.exec(code);\n if (v) return v[1] + code.slice(v[0].length);\n return code;\n}\n\n/** `private static async f()` \u2192 `async function f()`; `x = 1;` \u2192 `const x = 1;` */\nfunction toTopLevel(code: string): string {\n const m = /^((?:\\/\\*[\\s\\S]*?\\*\\/|\\/\\/[^\\n]*|\\s)*)((?:(?:public|private|protected|static|readonly|override|abstract)\\s+)*)(async\\s+)?(\\*?)\\s*([A-Za-z_$][\\w$]*)\\s*(<|\\()/.exec(code);\n if (m) return `${m[1]}${m[3] ?? ''}function${m[4] ? '*' : ''} ${m[5]}${m[6]}` + code.slice(m[0].length);\n const p = /^((?:\\/\\*[\\s\\S]*?\\*\\/|\\/\\/[^\\n]*|\\s)*)((?:(?:public|private|protected|static|readonly|override)\\s+)*)([A-Za-z_$][\\w$]*)(\\s*[:=])/.exec(code);\n if (p) return `${p[1]}const ${p[3]}${p[4]}` + code.slice(p[0].length);\n return code;\n}\n\n/** Rename the declared name of a snippet, found by parsing it. */\nfunction renameDeclaration(code: string, inClass: boolean, name: string): string {\n const prefix = inClass ? 'class __cc__ {\\n' : '';\n const src = prefix + code + (inClass ? '\\n}' : '');\n const sf = ts.createSourceFile('snippet.ts', src, ts.ScriptTarget.Latest, true);\n let target: ts.Node | undefined;\n const first = sf.statements[0];\n if (inClass && first && ts.isClassDeclaration(first)) target = first.members[0]?.name;\n else if (first && (ts.isFunctionDeclaration(first) || ts.isClassDeclaration(first) || ts.isInterfaceDeclaration(first) || ts.isTypeAliasDeclaration(first) || ts.isEnumDeclaration(first)))\n target = first.name;\n else if (first && ts.isVariableStatement(first)) target = first.declarationList.declarations[0]?.name;\n if (!target) return code;\n const s = target.getStart(sf) - prefix.length;\n return code.slice(0, s) + name + code.slice(target.end - prefix.length);\n}\n\nfunction must(model: FileModel, id: string): Block {\n const b = model.blocks.get(id);\n if (!b) throw new Error(`No block ${id}`);\n return b;\n}\n\n/** Turn plain clipboard text (e.g. copied from another app) into a block clip. */\nexport function clipFromText(code: string): BlockClip {\n const text = code.replace(/\\s+$/, '');\n const sf = ts.createSourceFile('clip.ts', text, ts.ScriptTarget.Latest, true);\n const first = sf.statements[0];\n const diags = (sf as unknown as { parseDiagnostics: unknown[] }).parseDiagnostics ?? [];\n if (first && !diags.length) {\n let name: string | undefined;\n let kind: Block['kind'] = 'statement';\n if (ts.isFunctionDeclaration(first)) (name = first.name?.text), (kind = 'function');\n else if (ts.isClassDeclaration(first)) (name = first.name?.text), (kind = 'class');\n else if (ts.isVariableStatement(first)) (name = first.declarationList.declarations[0]?.name.getText()), (kind = 'variable');\n else if (ts.isInterfaceDeclaration(first) || ts.isTypeAliasDeclaration(first) || ts.isEnumDeclaration(first)) (name = first.name.text), (kind = 'type');\n if (name) return { code: text, name, kind, fromClass: false };\n }\n const wrapped = ts.createSourceFile('clip.ts', `class __cc__ {\\n${text}\\n}`, ts.ScriptTarget.Latest, true);\n const cls = wrapped.statements[0];\n const wd = (wrapped as unknown as { parseDiagnostics: unknown[] }).parseDiagnostics ?? [];\n if (cls && ts.isClassDeclaration(cls) && !wd.length && cls.members[0]?.name) {\n const m = cls.members[0];\n return { code: text, name: m.name!.getText(wrapped), kind: ts.isPropertyDeclaration(m) ? 'variable' : 'function', fromClass: true };\n }\n return { code: text, name: '', kind: 'statement', fromClass: false };\n}\n", "import { codeWithoutChildren } from './parse';\nimport type { Block, FileModel } from './types';\n\n/**\n * How a block compares with the base version of its file (e.g. the last commit).\n * - `containsChanges`: its own code is the same, but nested blocks changed.\n */\nexport type BlockChange = 'added' | 'changed' | 'containsChanges' | 'unchanged';\n\nexport interface DiffLine {\n kind: 'same' | 'added' | 'removed';\n text: string;\n}\n\nexport interface FileDiff {\n base: FileModel;\n /** The change of every block of the current version. */\n changes: Map<string, BlockChange>;\n /** Blocks of the base that are gone (only the outermost one of a removed subtree). */\n removed: Block[];\n}\n\n/** Compare two versions of a file block by block. Blocks are matched by id, so a renamed block is removed + added. */\nexport function diffModels(base: FileModel, current: FileModel): FileDiff {\n const changes = new Map<string, BlockChange>();\n for (const [id, block] of current.blocks) {\n const baseBlock = base.blocks.get(id);\n if (!baseBlock) changes.set(id, 'added');\n else if (sameCode(fullCode(base, baseBlock), fullCode(current, block))) changes.set(id, 'unchanged');\n else if (sameCode(ownCode(base, baseBlock), ownCode(current, block))) changes.set(id, 'containsChanges');\n else changes.set(id, 'changed');\n }\n const removed = [...base.blocks.values()].filter((block) => {\n const isGone = !current.blocks.has(block.id);\n const isParentGone = !!block.parentId && !current.blocks.has(block.parentId);\n return isGone && !isParentGone;\n });\n return { base, changes, removed };\n}\n\n/** Line diff of a block's own code (nested blocks left out) between the base and now. */\nexport function diffOwnCode(base: FileModel, baseBlock: Block | undefined, current: FileModel, block: Block): DiffLine[] {\n const before = baseBlock ? codeLines(ownCode(base, baseBlock)) : [];\n return diffLines(before, codeLines(ownCode(current, block)));\n}\n\n/** Shortest edit script between two lists of lines (longest common subsequence). */\nexport function diffLines(before: string[], after: string[]): DiffLine[] {\n let prefix = 0;\n while (prefix < before.length && prefix < after.length && before[prefix] === after[prefix]) prefix++;\n let suffix = 0;\n while (suffix < before.length - prefix && suffix < after.length - prefix && before[before.length - 1 - suffix] === after[after.length - 1 - suffix]) suffix++;\n const oldMiddle = before.slice(prefix, before.length - suffix);\n const newMiddle = after.slice(prefix, after.length - suffix);\n // common[i][j]: length of the longest common subsequence of oldMiddle[i..] and newMiddle[j..]\n const common = Array.from({ length: oldMiddle.length + 1 }, () => new Uint32Array(newMiddle.length + 1));\n for (let i = oldMiddle.length - 1; i >= 0; i--) {\n for (let j = newMiddle.length - 1; j >= 0; j--) {\n common[i][j] = oldMiddle[i] === newMiddle[j] ? common[i + 1][j + 1] + 1 : Math.max(common[i + 1][j], common[i][j + 1]);\n }\n }\n const middle: DiffLine[] = [];\n let i = 0;\n let j = 0;\n while (i < oldMiddle.length || j < newMiddle.length) {\n if (i < oldMiddle.length && j < newMiddle.length && oldMiddle[i] === newMiddle[j]) {\n middle.push({ kind: 'same', text: newMiddle[j] });\n i++;\n j++;\n } else if (i < oldMiddle.length && (j === newMiddle.length || common[i + 1][j] >= common[i][j + 1])) {\n // Removed lines come before the lines that replace them, as in any diff.\n middle.push({ kind: 'removed', text: oldMiddle[i++] });\n } else {\n middle.push({ kind: 'added', text: newMiddle[j++] });\n }\n }\n const same = (text: string): DiffLine => ({ kind: 'same', text });\n return [...before.slice(0, prefix).map(same), ...middle, ...after.slice(after.length - suffix).map(same)];\n}\n\n/** The changed lines, with one line of context around each change if there's room, to fit in `max` lines. */\nexport function diffPreview(lines: DiffLine[], max: number): { lines: DiffLine[]; more: number } {\n const isNearChange = (index: number) => [index - 1, index, index + 1].some((near) => lines[near] && lines[near].kind !== 'same');\n const changesWithContext = lines.filter((_, index) => isNearChange(index));\n const shown = changesWithContext.length <= max ? changesWithContext : lines.filter((line) => line.kind !== 'same');\n return { lines: shown.slice(0, max), more: Math.max(0, shown.length - max) };\n}\n\n/** Blank lines and trailing spaces don't count as changes (removing a nested block leaves some behind). */\nfunction sameCode(before: string, after: string): boolean {\n return codeLines(before).join('\\n') === codeLines(after).join('\\n');\n}\n\nfunction fullCode(model: FileModel, block: Block): string {\n return model.text.slice(block.start, block.end);\n}\n\nfunction ownCode(model: FileModel, block: Block): string {\n return codeWithoutChildren(model.text, [block.start, block.end], block.children);\n}\n\n/** Lines without trailing spaces or blank lines, dedented. */\nfunction codeLines(code: string): string[] {\n const lines = code.split('\\n').map((line) => line.replace(/\\s+$/, '').replace(/\\t/g, ' ')).filter((line) => line);\n const indents = lines.slice(1).filter((line) => line).map((line) => /^ */.exec(line)![0].length);\n const commonIndent = indents.length ? Math.min(...indents) : 0;\n return lines.map((line, index) => (index === 0 ? line.trimStart() : line.slice(Math.min(commonIndent, /^ */.exec(line)![0].length))));\n}\n", "import type { TextEdit } from './edits';\n\n/** Where one side of a conflict is in the file: its code, without the marker lines. */\nexport interface ConflictSide {\n start: number;\n end: number;\n}\n\n/**\n * A merge conflict as git writes it into the file:\n * `<<<<<<< current` \u2026 (`||||||| base` \u2026) `=======` \u2026 `>>>>>>> incoming`.\n */\nexport interface ConflictHunk {\n /** The whole section, marker lines included (up to and including the last marker's line break). */\n start: number;\n end: number;\n current: ConflictSide;\n incoming: ConflictSide;\n /** Only with `merge.conflictStyle = diff3` (or zdiff3). */\n base?: ConflictSide;\n /** What git wrote after the markers, e.g. `HEAD` and the branch name. */\n currentLabel: string;\n incomingLabel: string;\n}\n\nexport type ConflictChoice = 'current' | 'incoming' | 'both';\n\n/** One side of a conflicted file: each conflict replaced by that side's code. */\nexport interface ConflictSideText {\n text: string;\n /** Where each conflict's code is in `text`, in the order of the hunks. */\n hunkRanges: ConflictSide[];\n /** The file offset of an offset in `text`. */\n toFileOffset(offset: number): number;\n}\n\nconst CURRENT_MARKER = /^<{7}(?: (.*))?\\r?$/;\nconst BASE_MARKER = /^\\|{7}(?: .*)?\\r?$/;\nconst SEPARATOR = /^={7}\\r?$/;\nconst INCOMING_MARKER = /^>{7}(?: (.*))?\\r?$/;\n\n/** The merge conflicts in a file. Unfinished marker sections are left alone. */\nexport function findConflicts(text: string): ConflictHunk[] {\n const hunks: ConflictHunk[] = [];\n let open: { start: number; currentLabel: string; currentStart: number; currentEnd?: number; baseStart?: number; baseEnd?: number; incomingStart?: number } | null = null;\n let lineStart = 0;\n while (lineStart < text.length) {\n const newline = text.indexOf('\\n', lineStart);\n const lineEnd = newline === -1 ? text.length : newline;\n const nextLineStart = newline === -1 ? text.length : newline + 1;\n const line = text.slice(lineStart, lineEnd);\n const currentMarker = CURRENT_MARKER.exec(line);\n if (currentMarker) {\n // A new section starts; one left open before it wasn't a conflict.\n open = { start: lineStart, currentLabel: currentMarker[1] ?? '', currentStart: nextLineStart };\n } else if (open && BASE_MARKER.test(line) && open.currentEnd === undefined) {\n open.currentEnd = lineStart;\n open.baseStart = nextLineStart;\n } else if (open && SEPARATOR.test(line) && open.incomingStart === undefined) {\n if (open.baseStart !== undefined) open.baseEnd = lineStart;\n else open.currentEnd = lineStart;\n open.incomingStart = nextLineStart;\n } else if (open && open.incomingStart !== undefined) {\n const incomingMarker = INCOMING_MARKER.exec(line);\n if (incomingMarker) {\n hunks.push({\n start: open.start,\n end: nextLineStart,\n current: { start: open.currentStart, end: open.currentEnd! },\n incoming: { start: open.incomingStart, end: lineStart },\n base: open.baseStart !== undefined ? { start: open.baseStart, end: open.baseEnd! } : undefined,\n currentLabel: open.currentLabel,\n incomingLabel: incomingMarker[1] ?? '',\n });\n open = null;\n }\n }\n lineStart = nextLineStart;\n }\n return hunks;\n}\n\n/** The file with every conflict replaced by one side's code. */\nexport function conflictSideText(text: string, hunks: ConflictHunk[], side: 'current' | 'incoming'): ConflictSideText {\n // Pieces of the file copied into the side text: [sideStart, fileStart, length]\n const pieces: [number, number, number][] = [];\n const hunkRanges: ConflictSide[] = [];\n let sideText = '';\n let fileOffset = 0;\n const copy = (start: number, end: number) => {\n pieces.push([sideText.length, start, end - start]);\n sideText += text.slice(start, end);\n };\n for (const hunk of hunks) {\n copy(fileOffset, hunk.start);\n const code = hunk[side];\n const rangeStart = sideText.length;\n copy(code.start, code.end);\n hunkRanges.push({ start: rangeStart, end: sideText.length });\n fileOffset = hunk.end;\n }\n copy(fileOffset, text.length);\n return {\n text: sideText,\n hunkRanges,\n toFileOffset(offset: number) {\n const piece = pieces.findLast(([sideStart]) => sideStart <= offset) ?? pieces[0];\n return piece[1] + Math.min(offset - piece[0], piece[2]);\n },\n };\n}\n\n/** The edit that resolves one conflict: its whole section becomes the chosen code. */\nexport function resolveConflict(text: string, hunk: ConflictHunk, choice: ConflictChoice): TextEdit {\n const code = (side: ConflictSide) => text.slice(side.start, side.end);\n const resolved = choice === 'both' ? code(hunk.current) + code(hunk.incoming) : code(hunk[choice]);\n return { start: hunk.start, end: hunk.end, text: resolved };\n}\n", "import type { Block } from './types';\n\n/**\n * How the canvas arranges a group of sibling blocks (a file, or a class's members) the first time,\n * to make the file easy to read. The arranger (arrange.ts) applies these rules; they only decide.\n *\n * Three kinds of rules:\n * - zones: where a block goes (the left column, or a band from top to bottom)\n * - stacks: blocks that always go together, one above the other\n * - relatedness: which blocks end up next to each other\n * Plus one shape the arranger always applies, the newspaper: a function on the left, the functions it\n * calls in a column to its right, in the order it calls them.\n * Placement rules then decide where a block goes that appears later, without moving the others.\n */\n\nexport type Zone = 'left' | 'data' | 'types' | 'main' | 'bottom';\n\n/** The bands from top to bottom. The left column holds `left` blocks next to all of them. */\nexport const BAND_ORDER: Zone[] = ['data', 'types', 'main', 'bottom'];\n\nexport interface ZoneRule {\n zone: Zone;\n description: string;\n matches(block: Block): boolean;\n}\n\n/** First match wins. */\nexport const ZONE_RULES: ZoneRule[] = [\n { zone: 'left', description: 'Imports on the left', matches: (block) => block.kind === 'import' },\n { zone: 'data', description: 'Constants, other data and React state at the top', matches: (block) => block.kind === 'variable' || block.kind === 'state' },\n { zone: 'types', description: 'Then interfaces, types and enums', matches: (block) => block.kind === 'type' },\n { zone: 'bottom', description: 'Code that runs when the file loads, at the bottom', matches: (block) => block.kind === 'statement' },\n { zone: 'main', description: 'Functions, classes and the rest in between', matches: () => true },\n];\n\nexport interface StackRule {\n description: string;\n /** Pairs to stack: the first block on top, the second right below it. */\n pairs(blocks: Block[]): [Block, Block][];\n}\n\nexport const STACK_RULES: StackRule[] = [\n {\n description: 'A getter above its setter: getTotal / setTotal, and get total / set total',\n pairs(blocks) {\n const pairs: [Block, Block][] = [];\n for (const getter of blocks) {\n const accessed = accessedName(getter, 'get');\n const setter = accessed && blocks.find((block) => block !== getter && accessedName(block, 'set') === accessed);\n if (setter) pairs.push([getter, setter]);\n }\n return pairs;\n },\n },\n];\n\n/** What a block knows about its siblings, read from its own code. */\nexport interface SiblingFacts {\n /** Sibling functions it calls and components it renders, in the order of their first use. */\n calls: string[];\n /** Every sibling it names (calls included). */\n uses: Set<string>;\n}\n\nexport interface RelatednessRule {\n description: string;\n /** How strongly two blocks belong together (0: not at all). */\n score(a: Block, b: Block, factsOf: (block: Block) => SiblingFacts): number;\n}\n\nexport const RELATEDNESS_RULES: RelatednessRule[] = [\n {\n description: 'One calls or uses the other',\n score: (a, b, factsOf) => (factsOf(a).uses.has(b.id) || factsOf(b).uses.has(a.id) ? 3 : 0),\n },\n {\n description: 'They use the same things',\n score: (a, b, factsOf) => [...factsOf(a).uses].filter((id) => factsOf(b).uses.has(id)).length,\n },\n {\n description: 'Their names start the same way (formatPrice, formatDate)',\n score: (a, b) => (firstWord(a.name) && firstWord(a.name) === firstWord(b.name) ? 1 : 0),\n },\n];\n\n/** A sibling that already has a position, as placement rules see it. */\nexport interface PlacedSibling {\n block: Block;\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/** Where a new block should go: on one side of a placed sibling. The closest free spot to it wins. */\nexport interface PlacementSpot {\n sibling: PlacedSibling;\n side: 'right' | 'below' | 'above';\n}\n\nexport interface PlacementRule {\n description: string;\n spot(block: Block, placed: PlacedSibling[], factsOf: (block: Block) => SiblingFacts): PlacementSpot | undefined;\n}\n\n/**\n * Where a block that appears in an arranged file goes (typed in the text, or from another branch).\n * Nothing that is already placed moves. First match wins; with no match it goes next to the block\n * before it in the file.\n */\nexport const PLACEMENT_RULES: PlacementRule[] = [\n {\n description: 'A getter right above its setter, a setter right below its getter',\n spot(block, placed) {\n const siblings = [block, ...placed.map((sibling) => sibling.block)];\n for (const rule of STACK_RULES) {\n for (const [top, bottom] of rule.pairs(siblings)) {\n const placedBottom = top === block && placed.find((sibling) => sibling.block === bottom);\n if (placedBottom) return { sibling: placedBottom, side: 'above' };\n const placedTop = bottom === block && placed.find((sibling) => sibling.block === top);\n if (placedTop) return { sibling: placedTop, side: 'below' };\n }\n }\n return undefined;\n },\n },\n {\n description: 'Like a newspaper: a function goes in the column right of its caller, after the function called before it',\n spot(block, placed, factsOf) {\n if (!isFunctionLike(block)) return undefined;\n const caller = placed.find((sibling) => isFunctionLike(sibling.block) && factsOf(sibling.block).calls.includes(block.id));\n if (!caller) return undefined;\n const calls = factsOf(caller.block).calls;\n const isInCallerColumn = (sibling: PlacedSibling) => sibling !== caller && sibling.x >= caller.x + caller.w;\n const calledBefore = calls.slice(0, calls.indexOf(block.id)).reverse();\n const previousInColumn = calledBefore.map((id) => placed.find((sibling) => sibling.block.id === id && isInCallerColumn(sibling))).find(Boolean);\n return previousInColumn ? { sibling: previousInColumn, side: 'below' } : { sibling: caller, side: 'right' };\n },\n },\n {\n description: 'An import, constant or type below the last one of its kind before it in the file',\n spot(block, placed) {\n const zone = zoneOf(block);\n if (zone === 'main') return undefined;\n const sameZone = placed.filter((sibling) => zoneOf(sibling.block) === zone);\n const lastBefore = sameZone.filter((sibling) => sibling.block.start < block.start).at(-1) ?? sameZone[0];\n return lastBefore ? { sibling: lastBefore, side: 'below' } : undefined;\n },\n },\n {\n description: 'Below the block it is most related to',\n spot(block, placed, factsOf) {\n let best: PlacedSibling | undefined;\n let bestScore = 0;\n for (const sibling of placed) {\n const score = RELATEDNESS_RULES.reduce((total, rule) => total + rule.score(block, sibling.block, factsOf), 0);\n if (score > bestScore) {\n best = sibling;\n bestScore = score;\n }\n }\n return best ? { sibling: best, side: 'below' } : undefined;\n },\n },\n];\n\nexport const zoneOf = (block: Block): Zone => ZONE_RULES.find((rule) => rule.matches(block))!.zone;\n\n/**\n * How many levels of callees the newspaper shows to the right of a function. Deeper calls start a\n * shape of their own, so a long chain of calls doesn't become one very wide staircase.\n */\nexport const NEWSPAPER_DEPTH = 3;\n\n/** The newspaper shape applies to these: a caller and the functions it calls. */\nexport const isFunctionLike = (block: Block): boolean => block.kind === 'function' || block.kind === 'component';\n\n/** `getTotal` \u2192 `total` for 'get'; accessors `get total` \u2192 `total`. */\nfunction accessedName(block: Block, accessor: 'get' | 'set'): string | undefined {\n if (block.kind !== 'function') return undefined;\n if (block.tags.includes(accessor)) return block.name;\n const match = new RegExp(`^${accessor}([A-Z_$][\\\\w$]*)$`).exec(block.name);\n return match ? match[1].charAt(0).toLowerCase() + match[1].slice(1) : undefined;\n}\n\n/** The first word of a camelCase name, if it has more than one: `formatPrice` \u2192 `format`. */\nfunction firstWord(name: string): string | undefined {\n const match = /^([a-z]+)[A-Z0-9_]/.exec(name);\n const isAccessorWord = match?.[1] === 'get' || match?.[1] === 'set';\n return match && !isAccessorWord ? match[1] : undefined;\n}\n", "import {\n BAND_ORDER,\n isFunctionLike,\n NEWSPAPER_DEPTH,\n PLACEMENT_RULES,\n RELATEDNESS_RULES,\n STACK_RULES,\n zoneOf,\n type PlacedSibling,\n type PlacementSpot,\n type SiblingFacts,\n type Zone,\n} from './layoutRules';\nimport { codeWithoutChildren } from './parse';\nimport type { Block, Point } from './types';\n\n/** Blocks laid out together: a block, or blocks side by side (row) or one above the other (column). */\nexport type Arrangement = { block: string } | { row: Arrangement[] } | { column: Arrangement[] };\n\ninterface Size {\n w: number;\n h: number;\n}\n\n/** Blocks the rules keep together, and how. */\ninterface Unit {\n members: Block[];\n arrangement: Arrangement;\n zone: Zone;\n /** Source order of its first block. */\n order: number;\n}\n\n/**\n * Positions for sibling blocks that were never laid out, following the rules in layoutRules.ts.\n * Positions are relative to the group's origin; sizes come from the caller.\n */\nexport function arrangeSiblings(blocks: Block[], sizeOf: (id: string) => Size, text: string, gap: number, isFile: boolean): Map<string, Point> {\n const factsById = siblingFacts(blocks, text);\n const factsOf = (block: Block) => factsById.get(block.id)!;\n const units = stackedUnits(blocks);\n const zoneUnits = (zone: Zone) => units.filter((unit) => unit.zone === zone);\n\n const bands = BAND_ORDER.map((zone) => {\n const inZone = zoneUnits(zone);\n return zone === 'main' ? orderByRelatedness(newspaperTrees(inZone, factsOf), factsOf) : inZone;\n });\n\n const positions = new Map<string, Point>();\n let left = 0;\n const leftColumn = zoneUnits('left');\n if (leftColumn.length) {\n let y = 0;\n for (const unit of leftColumn) {\n place(unit.arrangement, 0, y, sizeOf, gap, positions);\n y += measure(unit.arrangement, sizeOf, gap).h + 12;\n }\n left = Math.max(...leftColumn.map((unit) => measure(unit.arrangement, sizeOf, gap).w)) + gap * 2;\n }\n\n // One row width for every band, so the bands line up: about as wide as the blocks are tall.\n const bandUnits = bands.flat();\n const area = bandUnits.reduce((sum, unit) => {\n const size = measure(unit.arrangement, sizeOf, gap);\n return sum + (size.w + gap) * (size.h + gap);\n }, 0);\n const widest = Math.max(0, ...bandUnits.map((unit) => measure(unit.arrangement, sizeOf, gap).w));\n const rowWidth = Math.max(widest, Math.sqrt(area * (isFile ? 1.7 : 2.4)));\n\n let y = 0;\n for (const band of bands.filter((band) => band.length)) {\n let x = 0;\n let rowHeight = 0;\n for (const unit of band) {\n const size = measure(unit.arrangement, sizeOf, gap);\n if (x > 0 && x + size.w > rowWidth) {\n x = 0;\n y += rowHeight + gap;\n rowHeight = 0;\n }\n place(unit.arrangement, left + x, y, sizeOf, gap, positions);\n x += size.w + gap;\n rowHeight = Math.max(rowHeight, size.h);\n }\n y += rowHeight + gap;\n }\n return positions;\n}\n\n/**\n * Where blocks that appeared among arranged siblings should go, by the placement rules (layoutRules.ts).\n * Reads the siblings' code once, for all the new blocks.\n */\nexport function newBlockSpots(siblings: Block[], text: string): (block: Block, placed: PlacedSibling[]) => PlacementSpot | undefined {\n let factsById: Map<string, SiblingFacts> | undefined;\n const factsOf = (sibling: Block) => factsById!.get(sibling.id)!;\n return (block, placed) => {\n factsById ??= siblingFacts(siblings, text);\n for (const rule of PLACEMENT_RULES) {\n const spot = rule.spot(block, placed, factsOf);\n if (spot) return spot;\n }\n return undefined;\n };\n}\n\n/** Each block in its zone, with stacked pairs (getter above setter) merged into one unit. */\nfunction stackedUnits(blocks: Block[]): Unit[] {\n const unitOf = new Map<Block, Unit>();\n const units: Unit[] = blocks.map((block, order) => {\n const unit: Unit = { members: [block], arrangement: { block: block.id }, zone: zoneOf(block), order };\n unitOf.set(block, unit);\n return unit;\n });\n for (const rule of STACK_RULES) {\n for (const [top, bottom] of rule.pairs(blocks)) {\n const topUnit = unitOf.get(top)!;\n const bottomUnit = unitOf.get(bottom)!;\n const canStack = topUnit !== bottomUnit && topUnit.members.length === 1 && bottomUnit.members.length === 1 && topUnit.zone === bottomUnit.zone;\n if (!canStack) continue;\n topUnit.members.push(bottom);\n topUnit.arrangement = { column: [{ block: top.id }, { block: bottom.id }] };\n topUnit.order = Math.min(topUnit.order, bottomUnit.order);\n unitOf.set(bottom, topUnit);\n units.splice(units.indexOf(bottomUnit), 1);\n }\n }\n return units;\n}\n\n/**\n * Like a newspaper: a function on the left, the functions it calls in a column to its right in the\n * order it calls them, and so on for those. A function called from several places goes with the first.\n */\nfunction newspaperTrees(units: Unit[], factsOf: (block: Block) => SiblingFacts): Unit[] {\n const unitOfBlock = new Map<string, Unit>();\n for (const unit of units) for (const member of unit.members) unitOfBlock.set(member.id, unit);\n const isFunctionUnit = (unit: Unit) => unit.members.some(isFunctionLike);\n const calledUnits = (unit: Unit): Unit[] => {\n if (!isFunctionUnit(unit)) return [];\n const called: Unit[] = [];\n for (const member of unit.members) {\n for (const id of factsOf(member).calls) {\n const calledUnit = unitOfBlock.get(id);\n if (calledUnit && calledUnit !== unit && isFunctionUnit(calledUnit) && !called.includes(calledUnit)) called.push(calledUnit);\n }\n }\n return called;\n };\n const isCalledBySibling = new Set(units.flatMap(calledUnits));\n const claimed = new Set<Unit>();\n const tree = (unit: Unit, depth: number): Arrangement => {\n if (depth >= NEWSPAPER_DEPTH) return unit.arrangement;\n // Claim every direct callee first, so a deeper call can't take one out of this column.\n const callees = calledUnits(unit).filter((callee) => !claimed.has(callee));\n for (const callee of callees) claimed.add(callee);\n if (!callees.length) return unit.arrangement;\n return { row: [unit.arrangement, { column: callees.map((callee) => tree(callee, depth + 1)) }] };\n };\n const trees: Unit[] = [];\n // Functions nobody here calls start a tree; then any left over (calls in a cycle), in source order.\n const starts = [...units.filter((unit) => !isCalledBySibling.has(unit)), ...units];\n for (const unit of starts) {\n if (claimed.has(unit)) continue;\n claimed.add(unit);\n const arrangement = tree(unit, 0);\n const members = [...units].filter((other) => other === unit || (claimed.has(other) && contains(arrangement, other)));\n trees.push({ ...unit, arrangement, members: members.flatMap((member) => member.members) });\n }\n return trees;\n}\n\n/** Related units next to each other: after each one comes the most related one left, if any. */\nfunction orderByRelatedness(units: Unit[], factsOf: (block: Block) => SiblingFacts): Unit[] {\n const relatedness = (a: Unit, b: Unit) =>\n a.members.reduce((sum, x) => sum + b.members.reduce((inner, y) => inner + RELATEDNESS_RULES.reduce((total, rule) => total + rule.score(x, y, factsOf), 0), 0), 0);\n const left = [...units].sort((a, b) => a.order - b.order);\n const ordered: Unit[] = [];\n while (left.length) {\n const last = ordered[ordered.length - 1];\n let next = left[0];\n if (last) {\n let best = 0;\n for (const candidate of left) {\n const score = relatedness(last, candidate);\n if (score > best) {\n best = score;\n next = candidate;\n }\n }\n }\n left.splice(left.indexOf(next), 1);\n ordered.push(next);\n }\n return ordered;\n}\n\n/** Which siblings each block calls (in order) and names, from its own code (nested blocks left out). */\nfunction siblingFacts(blocks: Block[], text: string): Map<string, SiblingFacts> {\n const idsByName = new Map<string, string[]>();\n for (const block of blocks) idsByName.set(block.name, [...(idsByName.get(block.name) ?? []), block.id]);\n const componentIds = new Set(blocks.filter((block) => block.kind === 'component').map((block) => block.id));\n const facts = new Map<string, SiblingFacts>();\n for (const block of blocks) {\n const code = codeWithoutChildren(text, [block.start, block.end], block.children);\n const calls: string[] = [];\n const uses = new Set<string>();\n for (const match of code.matchAll(/[A-Za-z_$][\\w$]*/g)) {\n const ids = idsByName.get(match[0])?.filter((id) => id !== block.id);\n if (!ids?.length) continue;\n const isCall = /^\\s*\\(/.test(code.slice(match.index + match[0].length, match.index + match[0].length + 40));\n // Rendering a component (`<Cart`, `</Cart`) places it like a call.\n const isJsxTag = /<\\/?$/.test(code.slice(Math.max(0, match.index - 2), match.index));\n for (const id of ids) {\n uses.add(id);\n const isRender = isJsxTag && componentIds.has(id);\n if ((isCall || isRender) && !calls.includes(id)) calls.push(id);\n }\n }\n facts.set(block.id, { calls, uses });\n }\n return facts;\n}\n\nconst measured = new WeakMap<Arrangement, Size>();\n\nfunction measure(arrangement: Arrangement, sizeOf: (id: string) => Size, gap: number): Size {\n if ('block' in arrangement) return sizeOf(arrangement.block);\n const known = measured.get(arrangement);\n if (known) return known;\n const size = measureGroup(arrangement, sizeOf, gap);\n measured.set(arrangement, size);\n return size;\n}\n\nfunction measureGroup(arrangement: { row: Arrangement[] } | { column: Arrangement[] }, sizeOf: (id: string) => Size, gap: number): Size {\n const sizes = ('row' in arrangement ? arrangement.row : arrangement.column).map((item) => measure(item, sizeOf, gap));\n const gaps = gap * (sizes.length - 1);\n return 'row' in arrangement\n ? { w: sizes.reduce((sum, size) => sum + size.w, 0) + gaps, h: Math.max(...sizes.map((size) => size.h)) }\n : { w: Math.max(...sizes.map((size) => size.w)), h: sizes.reduce((sum, size) => sum + size.h, 0) + gaps };\n}\n\nfunction place(arrangement: Arrangement, x: number, y: number, sizeOf: (id: string) => Size, gap: number, positions: Map<string, Point>) {\n if ('block' in arrangement) {\n positions.set(arrangement.block, { x: Math.round(x), y: Math.round(y) });\n return;\n }\n const isRow = 'row' in arrangement;\n let offset = 0;\n for (const item of isRow ? arrangement.row : arrangement.column) {\n place(item, isRow ? x + offset : x, isRow ? y : y + offset, sizeOf, gap, positions);\n const size = measure(item, sizeOf, gap);\n offset += (isRow ? size.w : size.h) + gap;\n }\n}\n\nfunction contains(arrangement: Arrangement, unit: Unit): boolean {\n if ('block' in arrangement) return unit.members.some((member) => member.id === arrangement.block);\n return ('row' in arrangement ? arrangement.row : arrangement.column).some((item) => contains(item, unit));\n}\n", "import { arrangeSiblings, newBlockSpots } from './arrange';\nimport type { PlacementSpot } from './layoutRules';\nimport type { Block, FileLayout, FileModel, Point } from './types';\n\n/** Visual metrics. Monospace everywhere so sizes can be computed without measuring the DOM. */\nexport const M = {\n headerH: 32,\n headerCharW: 7.9, // 13px monospace\n previewLineH: 15,\n previewCharW: 6.7, // 11px monospace\n previewPad: 10,\n pad: 14, // inner padding of containers\n gap: 28, // spacing between sibling blocks\n minW: 180,\n maxW: 460,\n miniH: 46, // collapsed container: faint mini-map of children\n fileHeader: 44,\n filePad: 48,\n};\n\nexport interface Geo {\n id: string;\n block: Block;\n /** Position relative to the parent's content origin. */\n x: number;\n y: number;\n w: number;\n h: number;\n /** Absolute world position. */\n ax: number;\n ay: number;\n /** Y offset (inside the block) where nested blocks start. */\n contentTop: number;\n collapsed: boolean;\n /** Hidden because an ancestor is collapsed. */\n hidden: boolean;\n}\n\nexport interface FileGeometry {\n geo: Map<string, Geo>;\n /** Order to draw blocks: parents before children. */\n order: Geo[];\n frame: { x: number; y: number; w: number; h: number };\n /** Positions that were assigned during this pass (new blocks). Save them so they stay put. */\n assigned: Record<string, Point>;\n}\n\nexport function emptyLayout(): FileLayout {\n return { version: 1, blocks: {} };\n}\n\n/**\n * Compute every block's size and position. Saved positions are always respected.\n * Blocks without a saved position get one: a tidy flow layout for a never-laid-out file,\n * otherwise a free spot near their neighbors (or the hint, e.g. where the user clicked).\n */\nexport function computeGeometry(\n model: FileModel,\n layout: FileLayout,\n hints: Record<string, Point> = {},\n opts: { resolveOverlaps?: boolean } = {},\n): FileGeometry {\n const resolve = opts.resolveOverlaps ?? true;\n const geo = new Map<string, Geo>();\n const assigned: Record<string, Point> = {};\n const collapsed = new Set(layout.collapsed ?? []);\n\n const pos = (id: string): Point | undefined => layout.blocks[id] ?? assigned[id];\n\n // 1) sizes, bottom-up, and placement of each block's children\n const measure = (b: Block, hidden: boolean): Geo => {\n const isCollapsed = collapsed.has(b.id) && b.children.length > 0;\n const kids = b.children.map((c) => measure(c, hidden || isCollapsed));\n placeSiblings(kids, false);\n const head = headerChars(b);\n const previewChars = Math.max(0, ...b.preview.map((l) => l.length));\n const leafW = clamp(Math.ceil(Math.max(head * M.headerCharW, previewChars * M.previewCharW) + 28), M.minW, M.maxW);\n const lines = b.preview.length + (b.previewMore ? 1 : 0);\n const previewH = lines ? lines * M.previewLineH + M.previewPad : 4;\n let w = leafW;\n let h = M.headerH + previewH;\n let contentTop = h;\n if (kids.length && isCollapsed) {\n h += M.miniH;\n } else if (kids.length) {\n contentTop = h + 6;\n const right = Math.max(...kids.map((k) => k.x + k.w));\n const bottom = Math.max(...kids.map((k) => k.y + k.h));\n w = Math.max(leafW, right + M.pad * 2);\n h = contentTop + bottom + M.pad;\n }\n const g: Geo = { id: b.id, block: b, x: 0, y: 0, w, h, ax: 0, ay: 0, contentTop, collapsed: isCollapsed, hidden };\n geo.set(b.id, g);\n return g;\n };\n\n /** Give positions to siblings that don't have one. */\n const placeSiblings = (sibs: Geo[], isFile: boolean) => {\n if (!sibs.length) return;\n // Nothing here was ever laid out (new file, or a pasted class): arrange it by the layout rules.\n const isNeverLaidOut = sibs.every((g) => !layout.blocks[g.id] && !hints[g.id]);\n if (isNeverLaidOut) {\n const sizeOf = (id: string) => geo.get(id)!;\n const arranged = arrangeSiblings(sibs.map((g) => g.block), sizeOf, model.text, M.gap, isFile);\n for (const g of sibs) assigned[g.id] = arranged.get(g.id)!;\n }\n const placed: Geo[] = [];\n const unplaced: Geo[] = [];\n for (const g of sibs) {\n const p = pos(g.id);\n if (p) {\n g.x = p.x;\n g.y = p.y;\n placed.push(g);\n } else unplaced.push(g);\n }\n const spotByRules = newBlockSpots(sibs.map((sibling) => sibling.block), model.text);\n for (const g of unplaced) {\n const hint = hints[g.id];\n const ruleSpot = hint || !placed.length ? undefined : spotByRules(g.block, placed);\n let p: Point;\n if (hint) p = freeSpotNear(hint, g, placed, !isFile);\n else if (ruleSpot?.side === 'below') p = freeSpotDown(pointBeside(ruleSpot, g), g, placed, !isFile);\n else if (ruleSpot) p = freeSpotNear(pointBeside(ruleSpot, g), g, placed, !isFile);\n else {\n const previousPlacedInFile = sibs.slice(0, sibs.indexOf(g)).reverse().find((sibling) => placed.includes(sibling));\n p = findFreeSpot(g, placed, previousPlacedInFile, !isFile);\n }\n g.x = p.x;\n g.y = p.y;\n assigned[g.id] = p;\n placed.push(g);\n }\n if (resolve) pushApart(sibs, assigned);\n };\n\n const roots = model.roots.map((r) => measure(r, false));\n placeSiblings(roots, true);\n\n // 2) absolute positions, top-down\n const order: Geo[] = [];\n const place = (g: Geo, ox: number, oy: number) => {\n g.ax = ox + g.x;\n g.ay = oy + g.y;\n order.push(g);\n for (const c of g.block.children) place(geo.get(c.id)!, g.ax + M.pad, g.ay + g.contentTop);\n };\n for (const r of roots) place(r, 0, 0);\n\n let minX = 0,\n minY = 0,\n maxX = 640,\n maxY = 360;\n if (roots.length) {\n minX = Math.min(...roots.map((g) => g.x));\n minY = Math.min(...roots.map((g) => g.y));\n maxX = Math.max(...roots.map((g) => g.x + g.w));\n maxY = Math.max(...roots.map((g) => g.y + g.h));\n }\n const frame = {\n x: minX - M.filePad,\n y: minY - M.filePad - M.fileHeader,\n w: Math.max(maxX - minX, 480) + M.filePad * 2,\n h: Math.max(maxY - minY, 240) + M.filePad * 2 + M.fileHeader,\n };\n return { geo, order, frame, assigned };\n}\n\n/**\n * Where to draw blocks the open version doesn't have (removed since the diff base, or only in the\n * incoming side of a conflict): where they were in their own version, relative to their parent,\n * or the closest free spot to it if a block of this version is there now.\n * Each block's parent must be in `current`. Blocks inside a collapsed or hidden parent are left out.\n */\nexport function placeGhostBlocks(ghosts: Block[], ghostGeometry: FileGeometry, currentModel: FileModel, current: FileGeometry): Map<string, Point> {\n const positions = new Map<string, Point>();\n const placedGhostsByParent = new Map<string | null, Rect[]>();\n for (const ghost of ghosts) {\n const ghostGeo = ghostGeometry.geo.get(ghost.id);\n if (!ghostGeo) continue;\n const parentId = ghost.parentId ?? null;\n const parentGeo = parentId ? current.geo.get(parentId) : undefined;\n if (parentId && !parentGeo) continue;\n if (parentGeo && (parentGeo.hidden || parentGeo.collapsed)) continue;\n const currentSiblings = parentId ? currentModel.blocks.get(parentId)!.children : currentModel.roots;\n const placedGhosts = placedGhostsByParent.get(parentId) ?? [];\n const taken = [...currentSiblings.map((sibling) => current.geo.get(sibling.id)!), ...placedGhosts];\n const spot = freeSpotNear({ x: ghostGeo.x, y: ghostGeo.y }, ghostGeo, taken, !!parentGeo);\n placedGhosts.push({ ...spot, w: ghostGeo.w, h: ghostGeo.h });\n placedGhostsByParent.set(parentId, placedGhosts);\n positions.set(ghost.id, parentGeo ? { x: parentGeo.ax + M.pad + spot.x, y: parentGeo.ay + parentGeo.contentTop + spot.y } : spot);\n }\n return positions;\n}\n\n/**\n * A block that grew (e.g. a class got a new method) may now cover its neighbors.\n * Push each covered block just far enough down or right, and save its new spot.\n */\nfunction pushApart(sibs: Geo[], assigned: Record<string, Point>) {\n for (let iter = 0; iter < 100; iter++) {\n let moved = false;\n const sorted = [...sibs].sort((a, b) => a.y - b.y || a.x - b.x);\n for (let i = 0; i < sorted.length; i++) {\n for (let j = i + 1; j < sorted.length; j++) {\n const a = sorted[i];\n const b = sorted[j];\n if (!overlaps(a, b, 4)) continue;\n const down = a.y + a.h + M.gap - b.y;\n const right = b.x > a.x ? a.x + a.w + M.gap - b.x : Infinity;\n if (right < down) b.x += right;\n else b.y += down;\n assigned[b.id] = { x: Math.round(b.x), y: Math.round(b.y) };\n moved = true;\n }\n }\n if (!moved) break;\n }\n}\n\n/** The top-left corner for a block of `size` on that side of the sibling. */\nfunction pointBeside(spot: PlacementSpot, size: { w: number; h: number }): Point {\n const { sibling, side } = spot;\n if (side === 'right') return { x: sibling.x + sibling.w + M.gap, y: sibling.y };\n if (side === 'below') return { x: sibling.x, y: sibling.y + sibling.h + M.gap };\n return { x: sibling.x, y: sibling.y - size.h - M.gap };\n}\n\nfunction headerChars(b: Block): number {\n const tags = b.tags.filter((t) => t !== 'export').join(' ');\n return 4 + b.name.length + Math.min(b.detail.length, 40) + (tags ? tags.length + 2 : 0) + 3;\n}\n\ninterface Rect {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\nfunction overlaps(a: Rect, b: Rect, gap = M.gap / 2): boolean {\n return a.x < b.x + b.w + gap && a.x + a.w + gap > b.x && a.y < b.y + b.h + gap && a.y + a.h + gap > b.y;\n}\n\nfunction fits(r: Rect, placed: Rect[], clampPositive: boolean): boolean {\n if (clampPositive && (r.x < 0 || r.y < 0)) return false;\n return !placed.some((p) => overlaps(r, p));\n}\n\n/** A free spot next to the previous sibling (in source order), so related code lands nearby. */\nfunction findFreeSpot(g: Geo, placed: Geo[], prev: Geo | undefined, clampPositive: boolean): Point {\n if (!placed.length) return { x: 0, y: 0 };\n const cands: Point[] = [];\n if (prev) cands.push({ x: prev.x, y: prev.y + prev.h + M.gap }, { x: prev.x + prev.w + M.gap, y: prev.y });\n const origin = prev ?? placed[0];\n const others = [...placed].sort((a, b) => dist(a, origin) - dist(b, origin));\n for (const p of others) cands.push({ x: p.x, y: p.y + p.h + M.gap }, { x: p.x + p.w + M.gap, y: p.y });\n for (const c of cands) if (fits({ ...c, w: g.w, h: g.h }, placed, clampPositive)) return c;\n const bottom = Math.max(...placed.map((p) => p.y + p.h));\n return { x: Math.min(...placed.map((p) => p.x)), y: bottom + M.gap };\n}\n\n/** The closest free spot to `at` (e.g. where a block was dropped or created). */\nexport function freeSpotNear(at: Point, g: { w: number; h: number; id?: string }, placed: Rect[], clampPositive: boolean): Point {\n const start = clampPositive ? { x: Math.max(0, at.x), y: Math.max(0, at.y) } : at;\n const others = placed.filter((p) => (p as Geo).id === undefined || (p as Geo).id !== g.id);\n if (fits({ ...start, w: g.w, h: g.h }, others, clampPositive)) return round(start);\n const cands: Point[] = [];\n for (const p of others) {\n cands.push(\n { x: p.x + p.w + M.gap, y: start.y },\n { x: start.x, y: p.y + p.h + M.gap },\n { x: p.x - g.w - M.gap, y: start.y },\n { x: start.x, y: p.y - g.h - M.gap },\n { x: p.x + p.w + M.gap, y: p.y },\n { x: p.x, y: p.y + p.h + M.gap },\n );\n }\n cands.sort((a, b) => dist(a, start) - dist(b, start));\n for (const c of cands) if (fits({ ...c, w: g.w, h: g.h }, others, clampPositive)) return round(c);\n const bottom = Math.max(...others.map((p) => p.y + p.h));\n return round({ x: start.x, y: bottom + M.gap });\n}\n\n/** The first free spot at or below `at`, in the same column (keeps a column in order). */\nfunction freeSpotDown(at: Point, g: { w: number; h: number }, placed: Rect[], clampPositive: boolean): Point {\n const spot = clampPositive ? { x: Math.max(0, at.x), y: Math.max(0, at.y) } : { ...at };\n const blockCoveringSpot = () => placed.find((p) => overlaps({ x: spot.x, y: spot.y, w: g.w, h: g.h }, p));\n for (let covering = blockCoveringSpot(); covering; covering = blockCoveringSpot()) spot.y = covering.y + covering.h + M.gap;\n return round(spot);\n}\n\nfunction dist(a: Point, b: Point) {\n return Math.hypot(a.x - b.x, a.y - b.y);\n}\n\nfunction clamp(v: number, lo: number, hi: number) {\n return Math.min(hi, Math.max(lo, v));\n}\n\nfunction round(p: Point): Point {\n return { x: Math.round(p.x), y: Math.round(p.y) };\n}\n\n/**\n * When a block is renamed its id changes. If exactly one block disappeared and one appeared\n * under the same parent, carry the old position (and its children's) over to the new id.\n */\nexport function carryRenames(prev: FileModel | null, next: FileModel, layout: FileLayout): boolean {\n if (!prev) return false;\n const removedByParent = new Map<string | null, Block[]>();\n const addedByParent = new Map<string | null, Block[]>();\n for (const [id, b] of prev.blocks) if (!next.blocks.has(id)) push(removedByParent, b.parentId, b);\n for (const [id, b] of next.blocks) if (!prev.blocks.has(id)) push(addedByParent, b.parentId, b);\n let changed = false;\n for (const [parent, added] of addedByParent) {\n const removed = removedByParent.get(parent);\n if (added.length !== 1 || removed?.length !== 1) continue;\n const from = removed[0].id;\n const to = added[0].id;\n for (const key of Object.keys(layout.blocks)) {\n if (key === from || key.startsWith(from + '/')) {\n const nk = to + key.slice(from.length);\n if (!layout.blocks[nk]) layout.blocks[nk] = layout.blocks[key];\n changed = true;\n }\n }\n if (layout.collapsed?.includes(from)) layout.collapsed.push(to);\n }\n return changed;\n}\n\nfunction push<K, V>(m: Map<K, V[]>, k: K, v: V) {\n const a = m.get(k);\n if (a) a.push(v);\n else m.set(k, [v]);\n}\n\n/** Layout ready to be written to `.codecanvas/`: only live blocks, sorted keys, whole numbers. */\nexport function serializeLayout(layout: FileLayout, model: FileModel | null): string {\n const blocks: Record<string, Point> = {};\n for (const k of Object.keys(layout.blocks).sort()) {\n if (model && !model.blocks.has(k)) continue;\n const p = layout.blocks[k];\n blocks[k] = { x: Math.round(p.x), y: Math.round(p.y) };\n }\n const out: FileLayout = { version: 1, blocks };\n const collapsed = (layout.collapsed ?? []).filter((c) => !model || model.blocks.has(c)).sort();\n if (collapsed.length) out.collapsed = [...new Set(collapsed)];\n return JSON.stringify(out, null, 2) + '\\n';\n}\n", "interface HtmlPolicy {\n createHTML(html: string): unknown;\n}\n\nlet policy: HtmlPolicy | null | undefined;\n\n/**\n * Pages that enforce Trusted Types (VS Code's window does) reject plain strings in `innerHTML`.\n * There, HTML goes through the `codecanvas` policy, which the host must allow in its CSP.\n * Callers escape every value they put in the HTML (`esc`), so the policy passes it through as is.\n */\nfunction trustedHtmlPolicy(): HtmlPolicy | null {\n if (policy !== undefined) return policy;\n const factory = (globalThis as { trustedTypes?: { createPolicy(name: string, rules: { createHTML(html: string): string }): HtmlPolicy } }).trustedTypes;\n try {\n policy = factory ? factory.createPolicy('codecanvas', { createHTML: (html) => html }) : null;\n } catch {\n policy = null;\n }\n return policy;\n}\n\nexport function setHTML(element: Element, html: string) {\n const htmlPolicy = trustedHtmlPolicy();\n element.innerHTML = (htmlPolicy ? htmlPolicy.createHTML(html) : html) as string;\n}\n", "/** Canvas styles. Injected once. Hosts can override the CSS variables on `.cc-root`. */\nexport const CSS = /* css */ `\n.cc-root {\n --cc-bg: #15171c;\n --cc-dot: rgba(255,255,255,.07);\n --cc-frame-bg: rgba(255,255,255,.025);\n --cc-frame-border: rgba(255,255,255,.10);\n --cc-text: #e8eaee;\n --cc-muted: #9aa1ad;\n --cc-faint: #c4cad4;\n --cc-panel: #1f2229;\n --cc-panel-border: rgba(255,255,255,.12);\n --cc-accent: #7aa2ff;\n --cc-danger: #ff6b6b;\n --cc-shadow: 0 10px 30px rgba(0,0,0,.45);\n\n --k-import: #6b7280; --k-import-head: #3b3f46; --k-import-bg: #25272c;\n --k-class: #34b27a; --k-class-head: #1d6b4a; --k-class-bg: rgba(52,178,122,.08);\n --k-function: #ec5fa5; --k-function-head: #8f2f62; --k-function-bg: rgba(236,95,165,.09);\n --k-component: #22b8cf; --k-component-head: #146c7a; --k-component-bg: rgba(34,184,207,.09);\n --k-state: #f0883e; --k-state-head: #8a4614; --k-state-bg: rgba(240,136,62,.09);\n --k-variable: #4b8ef7; --k-variable-head: #23508f; --k-variable-bg: rgba(75,142,247,.09);\n --k-type: #d4a92a; --k-type-head: #6e5714; --k-type-bg: rgba(212,169,42,.08);\n --k-namespace: #9b8cf8; --k-namespace-head: #4d4291; --k-namespace-bg: rgba(155,140,248,.08);\n --k-statement: #7c8799; --k-statement-head: #39414f; --k-statement-bg: rgba(124,135,153,.08);\n\n position: relative; overflow: hidden; width: 100%; height: 100%;\n background-color: var(--cc-bg);\n background-image: radial-gradient(var(--cc-dot) 1.2px, transparent 1.3px);\n color: var(--cc-text);\n font: 13px/1.3 ui-sans-serif, system-ui, -apple-system, \"Segoe UI\", sans-serif;\n touch-action: none; user-select: none; -webkit-user-select: none; outline: none;\n -webkit-tap-highlight-color: transparent;\n}\n.cc-root[data-theme=\"light\"] {\n --cc-bg: #f6f7f9; --cc-dot: rgba(0,0,0,.09);\n --cc-frame-bg: rgba(255,255,255,.7); --cc-frame-border: rgba(0,0,0,.12);\n --cc-text: #1d2129; --cc-muted: #5d6573; --cc-faint: #39404c;\n --cc-panel: #ffffff; --cc-panel-border: rgba(0,0,0,.12); --cc-accent: #3366e6;\n --cc-shadow: 0 10px 30px rgba(20,30,50,.18);\n --k-import: #6b7280; --k-import-head: #4b5058; --k-import-bg: #eceef1;\n --k-class: #1f9963; --k-class-head: #1f9963; --k-class-bg: rgba(31,153,99,.07);\n --k-function: #d63e8c; --k-function-head: #d63e8c; --k-function-bg: rgba(214,62,140,.07);\n --k-component: #0f8fa3; --k-component-head: #0f8fa3; --k-component-bg: rgba(15,143,163,.07);\n --k-state: #d4691c; --k-state-head: #d4691c; --k-state-bg: rgba(212,105,28,.07);\n --k-variable: #2f6fe0; --k-variable-head: #2f6fe0; --k-variable-bg: rgba(47,111,224,.07);\n --k-type: #b58a0c; --k-type-head: #a87f08; --k-type-bg: rgba(181,138,12,.08);\n --k-namespace: #6f5ce6; --k-namespace-head: #6f5ce6; --k-namespace-bg: rgba(111,92,230,.07);\n --k-statement: #64708a; --k-statement-head: #64708a; --k-statement-bg: rgba(100,112,138,.07);\n}\n.cc-world { position: absolute; left: 0; top: 0; transform-origin: 0 0; }\n.cc-root.cc-moving .cc-world { will-change: transform; }\n.cc-frame { position: absolute; border: 1px solid var(--cc-frame-border); background: var(--cc-frame-bg); border-radius: 18px; }\n.cc-frame-title { position: absolute; left: 20px; top: 12px; font: 600 15px/20px var(--cc-font, \"JetBrains Mono\", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); color: var(--cc-muted); white-space: nowrap; }\n.cc-empty { position: absolute; font-size: 15px; color: var(--cc-muted); white-space: nowrap; }\n\n.cc-block {\n position: absolute; left: 0; top: 0; box-sizing: border-box; border-radius: 10px;\n border: 1.5px solid var(--k); background: var(--kbg); overflow: hidden; contain: layout style;\n cursor: default;\n}\n.cc-block.k-import { --k: var(--k-import); --kh: var(--k-import-head); --kbg: var(--k-import-bg); }\n.cc-block.k-class { --k: var(--k-class); --kh: var(--k-class-head); --kbg: var(--k-class-bg); }\n.cc-block.k-function { --k: var(--k-function); --kh: var(--k-function-head); --kbg: var(--k-function-bg); }\n.cc-block.k-component { --k: var(--k-component); --kh: var(--k-component-head); --kbg: var(--k-component-bg); }\n.cc-block.k-state { --k: var(--k-state); --kh: var(--k-state-head); --kbg: var(--k-state-bg); }\n.cc-block.k-variable { --k: var(--k-variable); --kh: var(--k-variable-head); --kbg: var(--k-variable-bg); }\n.cc-block.k-type { --k: var(--k-type); --kh: var(--k-type-head); --kbg: var(--k-type-bg); }\n.cc-block.k-namespace { --k: var(--k-namespace); --kh: var(--k-namespace-head); --kbg: var(--k-namespace-bg); }\n.cc-block.k-statement { --k: var(--k-statement); --kh: var(--k-statement-head); --kbg: var(--k-statement-bg); }\n.cc-block.k-import, .cc-root:not([data-theme=\"light\"]) .cc-block.k-import { border-color: #555a63; }\n\n.cc-head {\n display: flex; align-items: center; gap: 7px; height: 32px; padding: 0 10px; box-sizing: border-box;\n background: var(--kh); color: #fff; white-space: nowrap; overflow: hidden;\n font: 13px/32px var(--cc-font, \"JetBrains Mono\", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);\n}\n.cc-kind { font-size: 10px; text-transform: uppercase; letter-spacing: .06em; opacity: .75; flex: none; }\n.cc-name { font-weight: 700; flex: none; max-width: 70%; overflow: hidden; text-overflow: ellipsis; }\n.cc-detail { opacity: .8; overflow: hidden; text-overflow: ellipsis; min-width: 0; flex: 1 1 auto; }\n.cc-tags { font-size: 10px; opacity: .7; flex: none; }\n.cc-exp { width: 6px; height: 6px; border-radius: 50%; background: #fff; opacity: .8; flex: none; }\n.cc-fold {\n flex: none; margin-left: auto; width: 22px; height: 22px; border: 0; border-radius: 6px; padding: 0;\n background: rgba(255,255,255,.14); color: #fff; font-size: 12px; line-height: 22px; cursor: pointer;\n}\n.cc-fold:hover { background: rgba(255,255,255,.28); }\n.cc-prev {\n margin: 0; padding: 5px 12px 0; white-space: pre; overflow: hidden; color: var(--cc-faint); opacity: .5;\n font: 11px/15px var(--cc-font, \"JetBrains Mono\", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);\n}\n.cc-more { opacity: .7; font-style: italic; }\n.cc-mini { position: relative; margin: 6px 12px 0; height: 34px; opacity: .45; }\n.cc-mini > i { position: absolute; border-radius: 2px; border: 1px solid var(--cc-faint); background: rgba(255,255,255,.06); }\n.cc-mini > i.k-class { border-color: var(--k-class); } .cc-mini > i.k-function { border-color: var(--k-function); }\n.cc-mini > i.k-component { border-color: var(--k-component); } .cc-mini > i.k-state { border-color: var(--k-state); }\n.cc-mini > i.k-variable { border-color: var(--k-variable); } .cc-mini > i.k-type { border-color: var(--k-type); }\n\n.cc-err {\n flex: none; min-width: 18px; height: 18px; padding: 0 5px; box-sizing: border-box; border-radius: 9px;\n background: var(--cc-danger); color: #fff; font: 700 11px/18px ui-sans-serif, system-ui, sans-serif; text-align: center;\n}\n.cc-block.cc-has-error { border-color: var(--cc-danger); }\n.cc-root.lod-2 .cc-err { min-width: 34px; height: 34px; border-radius: 17px; font-size: 22px; line-height: 34px; }\n.cc-rename {\n font: inherit; font-weight: 700; color: #fff; background: rgba(0,0,0,.35); border: 1px solid var(--cc-accent);\n border-radius: 4px; padding: 0 4px; height: 22px; outline: none; user-select: text; -webkit-user-select: text; max-width: 100%;\n}\n.cc-rename.invalid { border-color: var(--cc-danger); }\n.cc-name:has(.cc-rename) { max-width: none; overflow: visible; }\n\n/* merge conflicts */\n.cc-block.cc-conflict { border-color: #f0883e; box-shadow: 0 0 0 2px rgba(240, 136, 62, .35); }\n.cc-conflict-chip {\n flex: none; min-width: 18px; height: 18px; border-radius: 9px; background: #f0883e; color: #1b1300;\n font: 900 13px/18px ui-sans-serif, system-ui, sans-serif; text-align: center;\n}\n.cc-root.lod-2 .cc-conflict-chip { min-width: 34px; height: 34px; border-radius: 17px; font-size: 24px; line-height: 34px; }\n.cc-block.cc-conflict-incoming {\n --k: #f0883e; --kh: #8a4a17; --kbg: rgba(240, 136, 62, .08);\n border-style: dashed; pointer-events: none; opacity: .9;\n}\n.cc-diff-chip.incoming { background: #f0883e; }\n.cc-banner.cc-banner-conflicts { border-color: #f0883e; }\n\n/* changes against a base version (setDiffBase) */\n.cc-block.cc-diff-unchanged { filter: saturate(.3) brightness(.92); }\n.cc-diff-chip {\n flex: none; min-width: 18px; height: 18px; padding: 0 4px; box-sizing: border-box; border-radius: 5px;\n font: 800 13px/18px ui-sans-serif, system-ui, sans-serif; text-align: center; color: #fff;\n}\n.cc-diff-chip.added { background: #2ea043; }\n.cc-diff-chip.changed { background: #d29922; }\n.cc-diff-chip.removed { background: var(--cc-danger); }\n.cc-root.lod-2 .cc-diff-chip { min-width: 34px; height: 34px; border-radius: 8px; font-size: 24px; line-height: 34px; }\n.cc-block.cc-diff-removed {\n --k: var(--cc-danger); --kh: #9c2f2f; --kbg: rgba(255, 107, 107, .10);\n border-style: dashed; pointer-events: none; opacity: .9;\n}\n.cc-root[data-theme=\"light\"] .cc-block.cc-diff-removed { --kh: #d64545; --kbg: rgba(214, 69, 69, .08); }\n.cc-prev.cc-diff-prev { opacity: .95; }\n.cc-diff-prev > span { display: block; margin: 0 -12px; padding: 0 12px; }\n.cc-diff-prev .cc-line-same { opacity: .5; }\n.cc-diff-prev .cc-line-added { background: rgba(46, 160, 67, .30); }\n.cc-diff-prev .cc-line-removed { background: rgba(248, 81, 73, .26); text-decoration: line-through; text-decoration-color: rgba(248, 81, 73, .7); }\n.cc-diff-summary { padding: 0 8px; font-size: 12px; color: var(--cc-muted); white-space: nowrap; }\n\n.cc-block.cc-sel { box-shadow: 0 0 0 2px var(--cc-bg), 0 0 0 4px var(--k); }\n.cc-block.cc-editing { box-shadow: 0 0 0 2px var(--cc-bg), 0 0 0 4px var(--cc-accent); }\n.cc-block.cc-dragging { box-shadow: var(--cc-shadow); opacity: .92; z-index: 9999 !important; }\n.cc-root.has-hl .cc-block.cc-linked { box-shadow: 0 0 0 2px var(--k); }\n\n.cc-edges { position: absolute; left: 0; top: 0; overflow: visible; pointer-events: none; }\n.cc-edge { fill: none; stroke-width: 1.5; opacity: .22; }\n.cc-edge.u-type { stroke-dasharray: 4 4; }\n.cc-root.has-hl .cc-edge { opacity: .07; }\n.cc-root.has-hl .cc-edge.hl { opacity: .95; stroke-width: 2.5; }\n\n/* level of detail when zoomed out */\n.cc-root.lod-1 .cc-tags { visibility: hidden; }\n.cc-root.lod-2 .cc-prev, .cc-root.lod-2 .cc-detail, .cc-root.lod-2 .cc-mini { visibility: hidden; }\n.cc-root.lod-2 .cc-head { font-size: 26px; }\n.cc-root.lod-2 .cc-kind, .cc-root.lod-2 .cc-fold { display: none; }\n.cc-root.lod-2 .cc-frame-title { font-size: 40px; line-height: 44px; top: -8px; }\n\n/* overlays (screen space) */\n.cc-banner {\n position: absolute; left: 50%; top: 12px; transform: translateX(-50%); z-index: 20; display: flex; gap: 10px; align-items: center;\n padding: 8px 12px; border-radius: 10px; background: var(--cc-panel); border: 1px solid var(--cc-danger); box-shadow: var(--cc-shadow);\n font-size: 13px; max-width: calc(100% - 32px);\n}\n.cc-banner[hidden], .cc-bar[hidden], .cc-refs[hidden] { display: none; }\n.cc-toast {\n position: absolute; left: 50%; bottom: 76px; transform: translateX(-50%); z-index: 30; padding: 8px 14px; border-radius: 10px;\n background: var(--cc-panel); border: 1px solid var(--cc-panel-border); box-shadow: var(--cc-shadow); font-size: 13px;\n transition: opacity .2s; pointer-events: none; max-width: calc(100% - 32px);\n}\n.cc-bar {\n position: absolute; left: 50%; bottom: 16px; transform: translateX(-50%); z-index: 20; display: flex; align-items: center; gap: 4px;\n padding: 5px; border-radius: 12px; background: var(--cc-panel); border: 1px solid var(--cc-panel-border); box-shadow: var(--cc-shadow);\n width: max-content; max-width: calc(100% - 24px); box-sizing: border-box; flex-wrap: wrap; justify-content: center;\n}\n.cc-bar .cc-chip { padding: 0 10px 0 6px; font: 600 12px/30px var(--cc-font, \"JetBrains Mono\", ui-monospace, Menlo, monospace); white-space: nowrap; display: flex; align-items: center; gap: 6px; max-width: 220px; overflow: hidden; text-overflow: ellipsis; }\n.cc-bar .cc-chip i { width: 10px; height: 10px; border-radius: 3px; background: var(--k); flex: none; }\n.cc-btn {\n border: 0; background: transparent; color: var(--cc-text); font: 500 13px/30px inherit; font-family: inherit; padding: 0 10px; border-radius: 8px;\n cursor: pointer; white-space: nowrap; min-height: 32px;\n}\n.cc-btn:hover { background: rgba(127,127,127,.16); }\n.cc-btn.danger { color: var(--cc-danger); }\n.cc-btn.primary { background: var(--cc-accent); color: #fff; }\n.cc-language { padding: 0 8px; font: 600 11px/30px var(--cc-font, \"JetBrains Mono\", ui-monospace, Menlo, monospace); color: var(--cc-muted); white-space: nowrap; }\n.cc-sep { width: 1px; height: 20px; background: var(--cc-panel-border); margin: 0 2px; flex: none; }\n.cc-refs {\n position: absolute; left: 50%; bottom: 64px; transform: translateX(-50%); z-index: 21; width: min(360px, calc(100% - 24px)); max-height: 45%;\n overflow: auto; border-radius: 12px; background: var(--cc-panel); border: 1px solid var(--cc-panel-border); box-shadow: var(--cc-shadow); padding: 6px;\n}\n.cc-refs h4 { margin: 8px 8px 4px; font-size: 11px; text-transform: uppercase; letter-spacing: .06em; color: var(--cc-muted); }\n.cc-refs button {\n display: flex; width: 100%; align-items: center; gap: 8px; border: 0; background: transparent; color: var(--cc-text); text-align: left;\n padding: 6px 8px; border-radius: 8px; cursor: pointer; font: 12px/18px var(--cc-font, \"JetBrains Mono\", ui-monospace, Menlo, monospace);\n}\n.cc-refs button:hover { background: rgba(127,127,127,.16); }\n.cc-refs button i { width: 10px; height: 10px; border-radius: 3px; background: var(--k); flex: none; }\n.cc-refs button span:last-child { margin-left: auto; color: var(--cc-muted); }\n.cc-refs button:disabled { cursor: default; opacity: .7; }\n.cc-refs button:disabled:hover { background: transparent; }\n.cc-refs .cc-file { color: var(--cc-muted); }\n.cc-refs .cc-error-row { --k: var(--cc-danger); align-items: flex-start; }\n.cc-refs .cc-error-row i { border-radius: 50%; margin-top: 4px; }\n.cc-refs .cc-error-row span:nth-child(2) { white-space: pre-wrap; font-family: ui-sans-serif, system-ui, sans-serif; }\n.cc-refs .cc-error-row span:last-child { white-space: nowrap; }\n.cc-refs .none { padding: 4px 8px 8px; color: var(--cc-muted); font-size: 12px; }\n\n.cc-editor {\n position: absolute; z-index: 25; display: flex; flex-direction: column; border-radius: 12px; overflow: hidden;\n background: var(--cc-panel); border: 1px solid var(--cc-panel-border); box-shadow: var(--cc-shadow);\n}\n.cc-editor-head { display: flex; align-items: center; gap: 8px; padding: 4px 6px 4px 12px; border-bottom: 1px solid var(--cc-panel-border); }\n.cc-editor-head .cc-chip { flex: 1; min-width: 0; font: 600 12px/30px var(--cc-font, \"JetBrains Mono\", ui-monospace, Menlo, monospace); display: flex; align-items: center; gap: 6px; overflow: hidden; white-space: nowrap; }\n.cc-editor-head .cc-chip i { width: 10px; height: 10px; border-radius: 3px; background: var(--k); flex: none; }\n.cc-editor-body { flex: 1; min-height: 0; overflow: auto; user-select: text; -webkit-user-select: text; touch-action: auto; }\n.cc-editor-hint { font-size: 11px; color: var(--cc-muted); white-space: nowrap; }\n@media (max-width: 640px) { .cc-editor-hint { display: none; } }\n`;\n\nlet injected = false;\nexport function injectStyles(doc: Document = document) {\n if (injected) return;\n injected = true;\n const s = doc.createElement('style');\n s.dataset.codecanvas = '';\n s.textContent = CSS;\n doc.head.appendChild(s);\n}\n", "import * as E from './edits';\nimport { carryRenames, computeGeometry, emptyLayout, freeSpotNear, M, placeGhostBlocks, type FileGeometry, type Geo } from './layout';\nimport { Project, type CanvasProject } from './project';\nimport { setHTML } from './html';\nimport { injectStyles } from './styles';\nimport { conflictSideText, findConflicts, resolveConflict, type ConflictChoice, type ConflictHunk, type ConflictSide, type ConflictSideText } from './conflicts';\nimport { diffModels, diffOwnCode, diffPreview, type BlockChange, type FileDiff } from './diff';\nimport { blockAt, parseStructure } from './parse';\nimport type { Block, CodeDiagnostic, FileLayout, FileModel, HostDiagnostic, IncomingUsage, Point, Usage } from './types';\n\nexport interface EditorOptions {\n parent: HTMLElement;\n text: string;\n /** Where `text` is in the file, for an editor that shows just this part of the whole document. */\n start: number;\n end: number;\n /** Selection to apply on open, relative to `text`. */\n selection?: [number, number];\n /** While changes are shown: the block's code in the base version ('' for an added block). Show a diff against it. */\n diffBase?: string;\n /** For editors on their own copy of `text`. Editors that edit the file itself don't call it. */\n onChange(text: string): void;\n /** User pressed Escape / Mod-Enter inside the editor. */\n onClose(): void;\n}\nexport interface EditorHandle {\n focus(): void;\n destroy(): void;\n /**\n * The editor edits the file's document directly (e.g. Monaco on the real file, for IntelliSense).\n * The canvas then gets its changes through `setText` and keeps the editor open, following the block.\n */\n editsFile?: boolean;\n}\n/** The host provides the code editor used inside blocks (CodeMirror in the playground, Monaco in the IDE). */\nexport type EditorFactory = (o: EditorOptions) => EditorHandle;\n\nexport interface CodeCanvasOptions {\n createEditor: EditorFactory;\n /** The canvas changed the file's text. */\n /**\n * The canvas changed the file's text. When the same action changed other files too (a rename),\n * `otherFiles` lists them, already updated in the project: the host should treat it all as one undo step.\n */\n onTextChange(text: string, otherFiles?: OtherFileChange[]): void;\n /**\n * Block positions or collapsed state changed. Save with `serializeLayout`. `automatic` changes\n * (first layout, blocks added in the text, renames) don't come from the user arranging the canvas:\n * a host may keep those out of the repo until there's a `user` change.\n */\n onLayoutChange(layout: FileLayout, reason: LayoutChangeReason): void;\n onUndo?(): void;\n onRedo?(): void;\n onCameraChange?(scale: number): void;\n theme?: 'dark' | 'light';\n /**\n * The project the file belongs to, for references across files and type errors. Keep it updated\n * with the other files' text. Without one, the canvas only sees the open file.\n */\n project?: CanvasProject;\n /** The selected block changed (null: nothing selected). */\n onSelect?(block: Block | null): void;\n /** The user picked a block in another file, e.g. in the references list. */\n onOpenBlock?(path: string, blockId: string): void;\n}\n\nexport type LayoutChangeReason = 'user' | 'automatic';\n\n/** Another file changed by the same canvas action, e.g. usages renamed there. */\nexport interface OtherFileChange {\n path: string;\n before: string;\n after: string;\n /** The file's model before the change, to carry renamed blocks' saved positions (`carryRenames`). */\n previousModel: FileModel | undefined;\n}\n\ninterface Camera {\n x: number;\n y: number;\n s: number;\n}\n\ntype Gesture =\n | { t: 'pending'; id: number; sx: number; sy: number; touch: boolean; target: Element | null }\n | { t: 'pan'; id: number; sx: number; sy: number; cam: Camera }\n | { t: 'drag'; id: number; sx: number; sy: number; block: string; orig: Point; nested: boolean }\n | { t: 'pinch'; d0: number; m0: Point; cam: Camera }\n | null;\n\nconst KIND_LABEL: Record<Block['kind'], string> = {\n import: 'import',\n class: 'class',\n function: 'fn',\n component: 'component',\n state: 'state',\n variable: 'var',\n type: 'type',\n namespace: 'ns',\n statement: 'code',\n};\nconst DIFF_CHIPS: Record<BlockChange | 'removed' | 'incoming', string> = {\n added: '<span class=\"cc-diff-chip added\" title=\"Added\">+</span>',\n changed: '<span class=\"cc-diff-chip changed\" title=\"Changed\">~</span>',\n removed: '<span class=\"cc-diff-chip removed\" title=\"Removed\">\u2212</span>',\n incoming: '<span class=\"cc-diff-chip incoming\" title=\"Incoming\">+</span>',\n containsChanges: '',\n unchanged: '',\n};\nconst LABEL_TAGS = new Set(['const', 'let', 'var', 'interface', 'type', 'enum', 'namespace', 'get', 'set']);\nconst MIN_SCALE = 0.04;\nconst MAX_SCALE = 4;\n\n/**\n * The visual editor for one file. Text is the source of truth: every action on the canvas\n * becomes a text edit, and every text change re-renders the canvas.\n */\nexport class CodeCanvas {\n readonly root: HTMLElement;\n private world: HTMLElement;\n private frameEl: HTMLElement;\n private blocksEl: HTMLElement;\n private svg: SVGSVGElement;\n private bar: HTMLElement;\n private refsEl: HTMLElement;\n private banner: HTMLElement;\n private toastEl: HTMLElement;\n\n private path = '';\n private text = '';\n /** Latest parse. */\n private model: FileModel | null = null;\n /** What's on screen: the latest parse without syntax errors. */\n private view: FileModel | null = null;\n private layout: FileLayout = emptyLayout();\n private geom: FileGeometry | null = null;\n private hints: Record<string, Point> = {};\n\n private cam: Camera = { x: 0, y: 0, s: 1 };\n private camQueued = false;\n private movingTimer = 0;\n private anim = 0;\n private lod = -1;\n /** The camera still shows the whole file as `fit` left it: resizing the view fits it again. */\n private fittedToView = false;\n\n private els = new Map<string, { el: HTMLElement; sig: string; box: string }>();\n private edges: { key: string; from: string; to: string; el: SVGPathElement }[] = [];\n private selected: string | null = null;\n private hovered: string | null = null;\n private refsOpen = false;\n private project: CanvasProject;\n /** Errors on screen: type errors from the last resolve, or syntax errors mapped onto the last good view. */\n private diagnostics: CodeDiagnostic[] = [];\n private incomingUsages: IncomingUsage[] = [];\n /** The version changes are shown against (`setDiffBase`), and its geometry, computed once. */\n private diffBase: { model: FileModel; layout: FileLayout | null; geometry?: FileGeometry } | null = null;\n private diffCache: { view: FileModel; diff: FileDiff } | null = null;\n /** Merge conflicts in the text. The canvas then shows its current side, marking the blocks they touch. */\n private conflicts: FileConflicts | null = null;\n private ghostBlockEls: Record<'removed' | 'incoming', HTMLElement[]> = { removed: [], incoming: [] };\n /** Errors from the host (`setDiagnostics`), shown instead of the project's type errors. */\n private hostDiagnostics: HostDiagnostic[] | null = null;\n private renaming: { id: string; input: HTMLInputElement; isApplying?: boolean } | null = null;\n\n /** The layout before the last Arrange, until the next layout change: Undo arrange puts it back. */\n private layoutBeforeArrange: FileLayout | null = null;\n /** Where the camera was before the block editor moved it out of the way, and where it moved it to. */\n private cameraBeforeEditor: { before: Camera; shifted: Camera } | null = null;\n private editing: { start: number; len: number; id: string | null; handle: EditorHandle; el: HTMLElement } | null = null;\n private clip: E.BlockClip | null = null;\n\n private pointers = new Map<number, Point>();\n private gesture: Gesture = null;\n private lastTap = { t: 0, x: 0, y: 0, id: '' as string | null };\n private lastPointer: Point | null = null;\n private toastTimer = 0;\n private ro: ResizeObserver;\n private barObserver: ResizeObserver;\n private cleanup: (() => void)[] = [];\n\n constructor(\n container: HTMLElement,\n private opts: CodeCanvasOptions,\n ) {\n this.project = opts.project ?? new Project();\n injectStyles(container.ownerDocument);\n const root = (this.root = el('div', 'cc-root'));\n root.tabIndex = 0;\n root.dataset.theme = opts.theme ?? 'dark';\n this.world = el('div', 'cc-world');\n this.frameEl = el('div', 'cc-frame');\n this.blocksEl = el('div', 'cc-blocks');\n this.svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n this.svg.classList.add('cc-edges');\n setHTML(this.svg, `<defs>${(['import', 'class', 'function', 'component', 'state', 'variable', 'type', 'namespace', 'statement'] as const)\n .map(\n (k) =>\n `<marker id=\"cc-arrow-${k}\" viewBox=\"0 0 10 10\" refX=\"9\" refY=\"5\" markerWidth=\"7\" markerHeight=\"7\" orient=\"auto-start-reverse\"><path d=\"M0 0L10 5L0 10z\" fill=\"var(--k-${k})\"/></marker>`,\n )\n .join('')}</defs>`);\n this.world.append(this.frameEl, this.blocksEl, this.svg);\n this.banner = el('div', 'cc-banner');\n this.banner.hidden = true;\n this.toastEl = el('div', 'cc-toast');\n this.toastEl.style.opacity = '0';\n this.bar = el('div', 'cc-bar');\n this.refsEl = el('div', 'cc-refs');\n this.refsEl.hidden = true;\n root.append(this.world, this.banner, this.refsEl, this.bar, this.toastEl);\n container.appendChild(root);\n this.bindEvents();\n this.ro = new ResizeObserver(() => (this.fittedToView ? this.fit(false) : this.queueCamera()));\n this.ro.observe(root);\n // The toolbar wraps onto more rows in a narrow view: keep the panels above it.\n this.barObserver = new ResizeObserver(([entry]) => {\n const barTop = entry.borderBoxSize?.[0]?.blockSize ?? this.bar.offsetHeight;\n this.refsEl.style.bottom = barTop + 28 + 'px';\n this.toastEl.style.bottom = barTop + 40 + 'px';\n });\n this.barObserver.observe(this.bar);\n this.renderBar();\n }\n\n // ---------------------------------------------------------------- public API\n\n /** Show a file. Fits it to the view. */\n openFile(path: string, text: string, layout?: FileLayout | null) {\n this.closeEditor();\n this.path = path;\n this.text = text;\n this.layout = layout ? structuredClone(layout) : emptyLayout();\n this.model = this.view = null;\n this.selected = this.hovered = null;\n this.refsOpen = false;\n this.renaming = null;\n this.diagnostics = [];\n this.hostDiagnostics = null;\n this.diffBase = null;\n this.diffCache = null;\n this.conflicts = null;\n this.layoutBeforeArrange = null;\n this.incomingUsages = [];\n this.hints = {};\n for (const { el } of this.els.values()) el.remove();\n this.els.clear();\n this.parseNow();\n this.fit(false);\n this.renderBar();\n }\n\n /** The text changed outside the canvas (e.g. the text editor). */\n setText(text: string) {\n if (text === this.text) return;\n const isEditedByOpenEditor = !!this.editing?.handle.editsFile;\n if (isEditedByOpenEditor) this.followEditedRange(this.text, text);\n else if (this.editing) this.closeEditor();\n this.cancelRename();\n this.text = text;\n this.parseNow();\n }\n\n /**\n * Show the changes since a base version of the file (e.g. the last commit): unchanged blocks are\n * desaturated, added and changed ones get a chip, removed ones show in red where they were.\n * `layout` is the base version's saved layout, for placing removed blocks. Null hides the changes.\n */\n setDiffBase(base: { text: string; layout?: FileLayout | null } | null) {\n this.diffBase = base ? { model: parseStructure(this.path, base.text), layout: base.layout ?? null } : null;\n this.diffCache = null;\n this.render();\n this.renderBar();\n }\n\n get isShowingChanges(): boolean {\n return !!this.diffBase;\n }\n\n private conflictsOf(hunks: ConflictHunk[], current: ConflictSideText, currentModel: FileModel): FileConflicts {\n const incoming = conflictSideText(this.text, hunks, 'incoming');\n const incomingModel = parseStructure(this.path, incoming.text);\n const hunksByBlock = new Map<string, number[]>();\n const markTouched = (id: string, hunkIndex: number) => {\n const list = hunksByBlock.get(id) ?? [];\n if (!list.includes(hunkIndex)) list.push(hunkIndex);\n hunksByBlock.set(id, list);\n };\n const incomingOnly: Block[] = [];\n hunks.forEach((_, hunkIndex) => {\n for (const block of innermostBlocksTouching(currentModel, current.hunkRanges[hunkIndex])) markTouched(block.id, hunkIndex);\n for (const block of innermostBlocksTouching(incomingModel, incoming.hunkRanges[hunkIndex])) {\n // A block only the incoming side has: its outermost new block, drawn as a ghost.\n let outermostNew: Block | undefined = currentModel.blocks.has(block.id) ? undefined : block;\n while (outermostNew?.parentId && !currentModel.blocks.has(outermostNew.parentId)) outermostNew = incomingModel.blocks.get(outermostNew.parentId);\n if (!outermostNew) markTouched(block.id, hunkIndex);\n else if (!incomingOnly.includes(outermostNew)) incomingOnly.push(outermostNew);\n }\n });\n return { hunks, current, incomingModel, hunksByBlock, incomingOnly };\n }\n\n /** Resolve the conflicts that touch a block: their sections become the chosen side. */\n keepConflictSide(id: string, choice: ConflictChoice) {\n const conflicts = this.conflicts;\n const hunkIndexes = conflicts?.hunksByBlock.get(id);\n if (!conflicts || !hunkIndexes) return;\n const edits = hunkIndexes.map((index) => resolveConflict(this.text, conflicts.hunks[index], choice));\n this.commit(E.applyEdits(this.text, edits));\n const remaining = this.conflicts?.hunks.length ?? 0;\n this.toast(remaining ? `Resolved. ${plural(remaining, 'conflict')} left` : 'All conflicts in this file are resolved');\n }\n\n /** While changes are shown: the block's code in the base version, '' if it's new. */\n private baseCodeOf(block: Block | null): string | undefined {\n const diff = this.currentDiff();\n if (!diff || !block) return undefined;\n const baseBlock = diff.base.blocks.get(block.id);\n return baseBlock ? diff.base.text.slice(baseBlock.start, baseBlock.end) : '';\n }\n\n /** The changes of what's on screen, while a diff base is set. */\n private currentDiff(): FileDiff | null {\n if (!this.diffBase || !this.view) return null;\n if (this.diffCache?.view !== this.view) this.diffCache = { view: this.view, diff: diffModels(this.diffBase.model, this.view) };\n return this.diffCache.diff;\n }\n\n /**\n * Errors reported by the host, e.g. VS Code's Problems. While set, the canvas shows these instead of\n * resolving type errors itself. Pass null to go back to the project's own.\n */\n setDiagnostics(diagnostics: HostDiagnostic[] | null) {\n this.hostDiagnostics = diagnostics;\n // The conflict markers themselves are errors to the host; the conflict banner says it better.\n if (!this.view || this.stale || this.conflicts) return;\n this.diagnostics = this.hostDiagnosticsOnBlocks(this.view);\n this.updateErrorMarkers();\n this.renderBar();\n }\n\n setLayout(layout: FileLayout) {\n this.layout = structuredClone(layout);\n this.relayout();\n }\n\n getLayout(): FileLayout {\n return structuredClone(this.layout);\n }\n\n getModel(): FileModel | null {\n return this.model;\n }\n\n /** Re-resolve usages and errors, e.g. after other files of the project changed. */\n refreshProject() {\n if (this.view && !this.stale) this.scheduleUsages(this.view, true);\n }\n\n getDiagnostics(): CodeDiagnostic[] {\n return [...this.diagnostics];\n }\n\n setTheme(theme: 'dark' | 'light') {\n this.root.dataset.theme = theme;\n }\n\n get scale() {\n return this.cam.s;\n }\n\n /** Lay the whole file out again by the layout rules (layoutRules.ts), forgetting saved positions. */\n arrange() {\n if (!this.view) return;\n const before = structuredClone(this.layout);\n this.layout = { ...emptyLayout(), collapsed: this.layout.collapsed };\n this.hints = {};\n this.relayout();\n this.emitLayout('user');\n this.layoutBeforeArrange = before;\n this.fit();\n this.renderBar();\n }\n\n undoArrange() {\n const before = this.layoutBeforeArrange;\n if (!before) return;\n this.layout = before;\n this.relayout();\n this.emitLayout('user');\n this.fit();\n this.renderBar();\n }\n\n /** Fit the whole file in the view. */\n fit(animate = true) {\n if (!this.geom) return;\n const f = this.geom.frame;\n const { width: vw, height: vh } = this.root.getBoundingClientRect();\n if (!vw || !vh) {\n // Not laid out yet; try again next frame.\n requestAnimationFrame(() => this.root.isConnected && this.fit(animate));\n return;\n }\n const pad = 24;\n const bottom = 64;\n const s = clamp(Math.min((vw - pad * 2) / f.w, (vh - pad - bottom) / f.h, 1.1), MIN_SCALE, MAX_SCALE);\n const to = { s, x: (vw - f.w * s) / 2 - f.x * s, y: pad + (vh - pad - bottom - f.h * s) / 2 - f.y * s };\n this.moveCamera(to, animate);\n this.fittedToView = true;\n }\n\n zoomBy(factor: number) {\n const r = this.root.getBoundingClientRect();\n this.zoomAt({ x: r.width / 2, y: r.height / 2 }, factor, true);\n }\n\n /** Center a block and select it. */\n reveal(id: string) {\n const g = this.geom?.geo.get(id);\n if (!g) return;\n this.select(id);\n const { width: vw, height: vh } = this.root.getBoundingClientRect();\n const s = clamp(Math.min(Math.max(this.cam.s, 0.85), (vw - 80) / g.w, (vh - 160) / g.h), MIN_SCALE, 1.4);\n this.moveCamera({ s, x: vw / 2 - (g.ax + g.w / 2) * s, y: (vh - 60) / 2 - (g.ay + g.h / 2) * s }, true);\n }\n\n select(id: string | null) {\n if (id === this.selected) return;\n this.selected = id;\n if (!id) this.refsOpen = false;\n this.updateHighlight();\n this.renderBar();\n this.opts.onSelect?.((id && this.view?.blocks.get(id)) || null);\n }\n\n destroy() {\n this.closeEditor();\n this.ro.disconnect();\n this.barObserver.disconnect();\n for (const c of this.cleanup) c();\n this.root.remove();\n }\n\n // ---------------------------------------------------------------- model\n\n private usageTimer = 0;\n\n private parseNow() {\n const hunks = this.text.includes('<<<<<<<') ? findConflicts(this.text) : [];\n const currentSide = hunks.length ? conflictSideText(this.text, hunks, 'current') : null;\n // With conflict markers the text isn't TypeScript: show its current side, without the project's links.\n const m = currentSide ? parseStructure(this.path, currentSide.text, this.model) : this.project.setFile(this.path, this.text);\n this.model = m;\n this.conflicts = currentSide ? this.conflictsOf(hunks, currentSide, m) : null;\n const stale = m.syntaxErrors > 0 && this.view !== null;\n if (this.conflicts) this.diagnostics = [];\n else if (stale) this.diagnostics = this.syntaxDiagnosticsOnView(m);\n else if (m.syntaxErrors) this.diagnostics = m.diagnostics;\n else if (this.hostDiagnostics) this.diagnostics = this.hostDiagnosticsOnBlocks(m);\n else this.diagnostics = this.diagnostics.filter((d) => !d.blockId || m.blocks.has(d.blockId));\n if (!stale) {\n // Usage lines are slower to compute: keep the previous ones until typing pauses.\n if (this.view) m.usages = this.view.usages.filter((u) => m.blocks.has(u.from) && m.blocks.has(u.to));\n if (carryRenames(this.view, m, this.layout)) this.emitLayout('automatic');\n this.view = m;\n if (this.selected && !m.blocks.has(this.selected)) this.selected = null;\n if (this.editing) {\n // Follow the block being edited, even if it was renamed.\n const b = [...m.blocks.values()].find((x) => x.start === this.editing!.start);\n this.editing.id = b?.id ?? null;\n if (b && this.selected !== b.id) this.selected = b.id;\n }\n this.relayout();\n if (!this.conflicts) this.scheduleUsages(m);\n }\n const isShowingConflicts = !!this.conflicts && !stale;\n this.banner.hidden = !stale && !isShowingConflicts;\n this.banner.classList.toggle('cc-banner-conflicts', isShowingConflicts);\n if (isShowingConflicts) {\n setHTML(this.banner, `<span>${plural(this.conflicts!.hunks.length, 'merge conflict')} in this file. Select a block marked ! to keep a side, or edit it.</span>`);\n } else if (stale) {\n this.updateErrorMarkers();\n setHTML(this.banner, `<span>Syntax error on line ${m.firstErrorLine}. The diagram is paused until it's fixed.</span>`);\n if (!this.editing) {\n const b = button('Edit file', () => this.openRangeEditor(0, this.text.length, null), 'primary');\n this.banner.appendChild(b);\n }\n }\n this.renderBar();\n }\n\n /** Usage links and type errors go through the project's language service: only once typing pauses. */\n private scheduleUsages(m: FileModel, soon = false) {\n clearTimeout(this.usageTimer);\n const run = async () => {\n if (this.view !== m) return;\n const resolution = await this.project.resolve(this.path, { diagnostics: !this.hostDiagnostics });\n // The text may have changed while the project worked: that result is for an older version.\n if (this.view !== m) return;\n m.usages = resolution.usages;\n this.incomingUsages = resolution.incoming;\n this.diagnostics = this.hostDiagnostics ? this.hostDiagnosticsOnBlocks(m) : resolution.diagnostics;\n if (!this.geom) return;\n this.renderEdges();\n this.updateHighlight();\n this.updateErrorMarkers();\n this.renderBar();\n };\n const pauseMs = soon ? 0 : m.text.length < 20000 ? 30 : 180;\n this.usageTimer = window.setTimeout(() => void run(), pauseMs);\n }\n\n private hostDiagnosticsOnBlocks(model: FileModel): CodeDiagnostic[] {\n return (this.hostDiagnostics ?? []).map((d) => ({ ...d, blockId: blockAt(model, d.start)?.id ?? null }));\n }\n\n /** The text changed while an editor on the file is open: keep tracking the part of the file it shows. */\n private followEditedRange(before: string, after: string) {\n const editing = this.editing!;\n const change = changedRegion(before, after);\n const lengthChange = after.length - before.length;\n const isBeforeEditedRange = change.end <= editing.start && change.start < editing.start;\n const isInsideEditedRange = change.start >= editing.start && change.start <= editing.start + editing.len;\n if (isBeforeEditedRange) editing.start += lengthChange;\n else if (isInsideEditedRange) editing.len = Math.max(0, editing.len + lengthChange);\n }\n\n /** While the syntax is broken the last good view stays on screen: put its errors on the closest block it still has. */\n private syntaxDiagnosticsOnView(model: FileModel): CodeDiagnostic[] {\n const closestShownBlock = (id: string | null): string | null => {\n let current = id;\n while (current && !this.view?.blocks.has(current)) current = model.blocks.get(current)?.parentId ?? null;\n return current;\n };\n return model.diagnostics.map((d) => ({ ...d, blockId: closestShownBlock(d.blockId) }));\n }\n\n private get stale() {\n return !!this.model && this.model !== this.view;\n }\n\n /** Apply a text edit made on the canvas. */\n private commit(text: string, otherFiles?: OtherFileChange[]) {\n this.text = text;\n this.opts.onTextChange(text, otherFiles);\n this.parseNow();\n }\n\n private relayout() {\n if (!this.view) return;\n const g = computeGeometry(this.view, this.layout, this.hints);\n this.geom = g;\n const assigned = Object.keys(g.assigned);\n if (assigned.length) {\n // A hint is where the user created or pasted a block.\n const isPlacedByUser = assigned.some((id) => id in this.hints);\n for (const id of assigned) {\n this.layout.blocks[id] = g.assigned[id];\n delete this.hints[id];\n }\n this.emitLayout(isPlacedByUser ? 'user' : 'automatic');\n }\n this.render();\n }\n\n private emitLayout(reason: LayoutChangeReason) {\n if (reason === 'user') this.layoutBeforeArrange = null;\n this.opts.onLayoutChange(structuredClone(this.layout), reason);\n }\n\n // ---------------------------------------------------------------- rendering\n\n private render() {\n const g = this.geom;\n const view = this.view;\n if (!g || !view) return;\n const f = g.frame;\n Object.assign(this.frameEl.style, { transform: `translate(${f.x}px,${f.y}px)`, width: f.w + 'px', height: f.h + 'px' });\n setHTML(this.frameEl, `<div class=\"cc-frame-title\">${esc(this.path)}</div>${\n view.roots.length ? '' : `<div class=\"cc-empty\" style=\"left:${M.filePad}px;top:${M.filePad + M.fileHeader}px\">Empty file. Double-click (or double-tap) to create a function.</div>`\n }`);\n\n const seen = new Set<string>();\n const diff = this.currentDiff();\n for (const geo of g.order) {\n const id = geo.id;\n seen.add(id);\n let entry = this.els.get(id);\n if (geo.hidden) {\n if (entry) entry.el.style.display = 'none';\n continue;\n }\n if (!entry) {\n const e = el('div', 'cc-block');\n e.dataset.id = id;\n this.blocksEl.appendChild(e);\n entry = { el: e, sig: '', box: '' };\n this.els.set(id, entry);\n }\n const b = geo.block;\n const mini = geo.collapsed ? this.miniMap(geo) : '';\n const change = diff?.changes.get(id);\n const changedLines = change === 'changed' ? this.changedLinesPreview(diff!, b) : '';\n const isConflicted = !!this.conflicts?.hunksByBlock.has(id);\n const sig = `${b.kind}|${b.name}|${b.detail}|${b.tags.join()}|${b.preview.join('\\n')}|${b.previewMore}|${geo.collapsed}|${b.children.length}|${mini}|${change ?? ''}|${changedLines}|${isConflicted}`;\n if (sig !== entry.sig) {\n entry.sig = sig;\n entry.el.className = `cc-block k-${b.kind}${change ? ` cc-diff-${change}` : ''}${isConflicted ? ' cc-conflict' : ''}`;\n setHTML(entry.el, this.blockHTML(b, geo, mini, change, changedLines, isConflicted));\n }\n const box = `${geo.ax},${geo.ay},${geo.w},${geo.h},${b.depth}`;\n if (box !== entry.box) {\n entry.box = box;\n const s = entry.el.style;\n s.transform = `translate(${geo.ax}px,${geo.ay}px)`;\n s.width = geo.w + 'px';\n s.height = geo.h + 'px';\n s.zIndex = String(b.depth + 1);\n s.display = '';\n }\n }\n for (const [id, entry] of this.els) {\n if (!seen.has(id)) {\n entry.el.remove();\n this.els.delete(id);\n }\n }\n this.renderRemovedBlocks(diff);\n this.renderIncomingBlocks();\n this.renderEdges();\n this.updateHighlight();\n this.updateErrorMarkers();\n }\n\n /** Blocks only the incoming side of a conflict has, drawn dashed where they would go. */\n private renderIncomingBlocks() {\n const conflicts = this.conflicts;\n if (!conflicts?.incomingOnly.length || !this.geom) return this.drawGhostBlocks('incoming', [], null);\n conflicts.geometry ??= computeGeometry(conflicts.incomingModel, this.layout, {}, { resolveOverlaps: false });\n this.drawGhostBlocks('incoming', conflicts.incomingOnly, conflicts.geometry);\n }\n\n /** A changed block's preview: its changed lines with a line of context, as many as fit. */\n private changedLinesPreview(diff: FileDiff, block: Block): string {\n const lines = diffOwnCode(diff.base, diff.base.blocks.get(block.id), this.view!, block);\n const fitting = Math.max(1, block.preview.length);\n const preview = diffPreview(lines, fitting);\n const marker = { same: ' ', added: '+', removed: '\u2212' };\n const sharedIndent = Math.min(...preview.lines.map((line) => /^ */.exec(line.text)![0].length));\n const rows = preview.lines.map((line) => `<span class=\"cc-line-${line.kind}\">${marker[line.kind]} ${esc(line.text.slice(sharedIndent))}</span>`);\n const more = preview.more ? `<span class=\"cc-more\">\u2026 ${preview.more} more changed line${preview.more > 1 ? 's' : ''}</span>` : '';\n // Each row is a block of its own (for its background), so no newlines between them.\n return rows.join('') + more;\n }\n\n /** Removed blocks stay visible, in red, where they were in the base version. They can't be selected. */\n private renderRemovedBlocks(diff: FileDiff | null) {\n if (!diff?.removed.length || !this.diffBase || !this.geom) return this.drawGhostBlocks('removed', [], null);\n this.diffBase.geometry ??= computeGeometry(diff.base, this.diffBase.layout ?? this.layout, {}, { resolveOverlaps: false });\n this.drawGhostBlocks('removed', diff.removed, this.diffBase.geometry);\n }\n\n /** Blocks of another version (removed, or incoming in a conflict): drawn, but not part of this file. */\n private drawGhostBlocks(kind: 'removed' | 'incoming', ghosts: Block[], ghostGeometry: FileGeometry | null) {\n for (const ghostEl of this.ghostBlockEls[kind]) ghostEl.remove();\n this.ghostBlockEls[kind] = [];\n if (!ghostGeometry || !this.geom || !this.view) return;\n const positions = placeGhostBlocks(ghosts, ghostGeometry, this.view, this.geom);\n for (const block of ghosts) {\n const position = positions.get(block.id);\n const ghostGeo = ghostGeometry.geo.get(block.id);\n if (!position || !ghostGeo) continue;\n const ghostEl = el('div', `cc-block k-${block.kind} ${kind === 'removed' ? 'cc-diff-removed' : 'cc-conflict-incoming'}`);\n setHTML(ghostEl, this.blockHTML(block, { ...ghostGeo, collapsed: true }, '', kind));\n Object.assign(ghostEl.style, { transform: `translate(${position.x}px,${position.y}px)`, width: ghostGeo.w + 'px', height: ghostGeo.h + 'px', zIndex: String(block.depth + 1) });\n ghostEl.title = kind === 'removed' ? `${block.name}: removed` : `${block.name}: only in the incoming side of a merge conflict`;\n this.blocksEl.appendChild(ghostEl);\n this.ghostBlockEls[kind].push(ghostEl);\n }\n }\n\n /** Diagnostics grouped by the block that shows them: the innermost visible block containing each error. */\n private diagnosticsByShownBlock(): Map<string, CodeDiagnostic[]> {\n const byBlock = new Map<string, CodeDiagnostic[]>();\n const geometry = this.geom;\n if (!geometry) return byBlock;\n for (const d of this.diagnostics) {\n let geo = d.blockId ? geometry.geo.get(d.blockId) : undefined;\n while (geo?.hidden && geo.block.parentId) geo = geometry.geo.get(geo.block.parentId);\n if (!geo) continue;\n const list = byBlock.get(geo.id);\n if (list) list.push(d);\n else byBlock.set(geo.id, [d]);\n }\n return byBlock;\n }\n\n private updateErrorMarkers() {\n const byBlock = this.diagnosticsByShownBlock();\n for (const [id, { el: blockEl }] of this.els) {\n const list = byBlock.get(id);\n const head = blockEl.querySelector('.cc-head');\n let badge = head?.querySelector<HTMLElement>('.cc-err') ?? null;\n blockEl.classList.toggle('cc-has-error', !!list);\n if (!list) {\n badge?.remove();\n continue;\n }\n if (!badge && head) {\n badge = el('span', 'cc-err');\n head.insertBefore(badge, head.querySelector('.cc-fold'));\n }\n if (!badge) continue;\n badge.textContent = String(list.length);\n badge.title = list.map((d) => `Line ${d.line}: ${d.message}`).join('\\n');\n }\n }\n\n private blockHTML(b: Block, geo: Geo, mini: string, change?: BlockChange | 'removed' | 'incoming', changedLines = '', isConflicted = false): string {\n const label = blockLabel(b);\n const tags = b.tags.filter((t) => t !== label && t !== 'export' && (b.kind === 'import' || !LABEL_TAGS.has(t))).join(' ');\n const exp = b.tags.includes('export') ? '<span class=\"cc-exp\" title=\"exported\"></span>' : '';\n const isRemoved = change === 'removed' || change === 'incoming';\n const fold = b.children.length && !isRemoved ? `<button class=\"cc-fold\" title=\"${geo.collapsed ? 'Expand' : 'Collapse'}\">${geo.collapsed ? '\u25B8' : '\u25BE'}</button>` : '';\n const prev = changedLines\n ? `<pre class=\"cc-prev cc-diff-prev\">${changedLines}</pre>`\n : b.preview.length\n ? `<pre class=\"cc-prev\">${esc(b.preview.join('\\n'))}${b.previewMore ? `\\n<span class=\"cc-more\">\u2026 ${b.previewMore} more line${b.previewMore > 1 ? 's' : ''}</span>` : ''}</pre>`\n : '';\n const diffChip = (change ? DIFF_CHIPS[change] : '') + (isConflicted ? '<span class=\"cc-conflict-chip\" title=\"Merge conflict\">!</span>' : '');\n return `<div class=\"cc-head\"><span class=\"cc-kind\">${esc(label)}</span>${exp}<span class=\"cc-name\">${esc(b.name)}</span>${diffChip}<span class=\"cc-detail\">${esc(\n b.detail,\n )}</span>${tags ? `<span class=\"cc-tags\">${esc(tags)}</span>` : ''}${fold}</div>${prev}${mini ? `<div class=\"cc-mini\">${mini}</div>` : ''}`;\n }\n\n /** Faint miniature of a collapsed block's nested blocks. */\n private miniMap(geo: Geo): string {\n const kids = geo.block.children.map((c) => this.geom!.geo.get(c.id)!);\n const right = Math.max(...kids.map((k) => k.x + k.w));\n const bottom = Math.max(...kids.map((k) => k.y + k.h));\n const bw = geo.w - 24;\n const bh = 34;\n const s = Math.min(bw / right, bh / bottom);\n return kids\n .map(\n (k) =>\n `<i class=\"k-${k.block.kind}\" style=\"left:${(k.x * s).toFixed(1)}px;top:${(k.y * s).toFixed(1)}px;width:${Math.max(2, k.w * s).toFixed(1)}px;height:${Math.max(\n 2,\n k.h * s,\n ).toFixed(1)}px\"></i>`,\n )\n .join('');\n }\n\n private renderEdges() {\n const g = this.geom!;\n const view = this.view!;\n const visible = (id: string): Geo | undefined => {\n let geo = g.geo.get(id);\n while (geo?.hidden && geo.block.parentId) geo = g.geo.get(geo.block.parentId);\n return geo;\n };\n const want = new Map<string, { from: Geo; to: Geo; kind: string; usage: string; uf: string; ut: string }>();\n for (const u of view.usages) {\n if (u.toPath) continue; // in another file: listed in the references, not drawn\n const a = visible(u.from);\n const b = visible(u.to);\n if (!a || !b || a === b) continue;\n if (a.id.startsWith(b.id + '/') || b.id.startsWith(a.id + '/')) continue;\n const key = `${a.id}>${b.id}`;\n if (!want.has(key)) want.set(key, { from: a, to: b, kind: b.block.kind, usage: u.kind, uf: u.from, ut: u.to });\n }\n const old = new Map(this.edges.map((e) => [e.key, e]));\n const next: typeof this.edges = [];\n for (const [key, w] of want) {\n let e = old.get(key);\n if (e) old.delete(key);\n else {\n const p = document.createElementNS('http://www.w3.org/2000/svg', 'path');\n this.svg.appendChild(p);\n e = { key, from: w.from.id, to: w.to.id, el: p };\n }\n e.el.setAttribute('class', `cc-edge u-${w.usage}`);\n e.el.setAttribute('stroke', `var(--k-${w.kind})`);\n e.el.setAttribute('marker-end', `url(#cc-arrow-${w.kind})`);\n e.el.setAttribute('d', edgePath(w.from, w.to));\n next.push(e);\n }\n for (const e of old.values()) e.el.remove();\n this.edges = next;\n }\n\n private updateHighlight() {\n const h = this.selected ?? this.hovered;\n const inH = (id: string) => !!h && (id === h || id.startsWith(h + '/'));\n const linked = new Set<string>();\n for (const e of this.edges) {\n const on = inH(e.from) || inH(e.to);\n e.el.classList.toggle('hl', on);\n if (on) {\n linked.add(e.from);\n linked.add(e.to);\n }\n }\n this.root.classList.toggle('has-hl', !!h);\n for (const [id, { el: e }] of this.els) {\n e.classList.toggle('cc-sel', id === this.selected);\n e.classList.toggle('cc-linked', linked.has(id) && !inH(id));\n e.classList.toggle('cc-editing', !!this.editing && id === this.editing.id);\n }\n if (this.refsOpen) this.renderRefs();\n }\n\n // ---------------------------------------------------------------- camera\n\n private queueCamera() {\n if (this.camQueued) return;\n this.camQueued = true;\n requestAnimationFrame(() => {\n this.camQueued = false;\n this.applyCamera();\n });\n }\n\n private applyCamera() {\n const { x, y, s } = this.cam;\n this.world.style.transform = `translate(${x}px,${y}px) scale(${s})`;\n const grid = 24 * s;\n this.root.style.backgroundSize = s < 0.25 ? '0 0' : `${grid}px ${grid}px`;\n this.root.style.backgroundPosition = `${x}px ${y}px`;\n const lod = s < 0.3 ? 2 : s < 0.55 ? 1 : 0;\n if (lod !== this.lod) {\n this.lod = lod;\n this.root.classList.toggle('lod-1', lod >= 1);\n this.root.classList.toggle('lod-2', lod >= 2);\n }\n // Promote to a GPU layer only while moving, so text is re-rasterized crisply once it stops.\n this.root.classList.add('cc-moving');\n clearTimeout(this.movingTimer);\n this.movingTimer = window.setTimeout(() => this.root.classList.remove('cc-moving'), 160);\n this.opts.onCameraChange?.(s);\n }\n\n private setCamera(c: Camera) {\n this.fittedToView = false;\n cancelAnimationFrame(this.anim);\n this.cam = { x: c.x, y: c.y, s: clamp(c.s, MIN_SCALE, MAX_SCALE) };\n this.queueCamera();\n }\n\n private moveCamera(to: Camera, animate: boolean) {\n this.fittedToView = false;\n cancelAnimationFrame(this.anim);\n if (!animate || matchMedia('(prefers-reduced-motion: reduce)').matches) {\n this.setCamera(to);\n return;\n }\n const from = { ...this.cam };\n const t0 = performance.now();\n const dur = 280;\n const step = (now: number) => {\n const k = Math.min(1, (now - t0) / dur);\n const e = 1 - Math.pow(1 - k, 3);\n // Interpolate scale in log space so zooming feels even.\n const s = Math.exp(Math.log(from.s) + (Math.log(to.s) - Math.log(from.s)) * e);\n this.cam = { s, x: from.x + (to.x - from.x) * e, y: from.y + (to.y - from.y) * e };\n this.applyCamera();\n if (k < 1) this.anim = requestAnimationFrame(step);\n };\n this.anim = requestAnimationFrame(step);\n }\n\n private zoomAt(p: Point, factor: number, animate = false) {\n const s = clamp(this.cam.s * factor, MIN_SCALE, MAX_SCALE);\n const wx = (p.x - this.cam.x) / this.cam.s;\n const wy = (p.y - this.cam.y) / this.cam.s;\n this.moveCamera({ s, x: p.x - wx * s, y: p.y - wy * s }, animate);\n }\n\n private toWorld(clientX: number, clientY: number): Point {\n const r = this.root.getBoundingClientRect();\n return { x: (clientX - r.left - this.cam.x) / this.cam.s, y: (clientY - r.top - this.cam.y) / this.cam.s };\n }\n\n private local(e: { clientX: number; clientY: number }): Point {\n const r = this.root.getBoundingClientRect();\n return { x: e.clientX - r.left, y: e.clientY - r.top };\n }\n\n // ---------------------------------------------------------------- hit testing\n\n /** What's under a world point: a block (header or leaf), or empty space inside a container/the file. */\n private hitTest(p: Point): { block: string | null; container: string | null } {\n const g = this.geom;\n if (!g) return { block: null, container: null };\n let hit: Geo | null = null;\n for (let i = g.order.length - 1; i >= 0; i--) {\n const geo = g.order[i];\n if (geo.hidden) continue;\n if (p.x >= geo.ax && p.x <= geo.ax + geo.w && p.y >= geo.ay && p.y <= geo.ay + geo.h) {\n if (!hit || geo.block.depth > hit.block.depth) hit = geo;\n }\n }\n if (!hit) return { block: null, container: null };\n const hasKids = hit.block.children.length > 0 && !hit.collapsed;\n if (hasKids && p.y > hit.ay + hit.contentTop) return { block: null, container: hit.id };\n return { block: hit.id, container: hit.block.parentId };\n }\n\n // ---------------------------------------------------------------- events\n\n private bindEvents() {\n const r = this.root;\n const on = <K extends keyof HTMLElementEventMap>(t: EventTarget, type: K | string, fn: (e: never) => void, o?: AddEventListenerOptions) => {\n t.addEventListener(type, fn as EventListener, o);\n this.cleanup.push(() => t.removeEventListener(type, fn as EventListener, o));\n };\n on(r, 'pointerdown', (e: PointerEvent) => this.onDown(e));\n on(r, 'pointermove', (e: PointerEvent) => this.onMove(e));\n on(r, 'pointerup', (e: PointerEvent) => this.onUp(e));\n on(r, 'pointercancel', (e: PointerEvent) => this.onUp(e, true));\n on(r, 'wheel', (e: WheelEvent) => this.onWheel(e), { passive: false });\n on(r, 'keydown', (e: KeyboardEvent) => this.onKey(e));\n on(r, 'pointerover', (e: PointerEvent) => {\n if (e.pointerType !== 'mouse' || this.gesture) return;\n const id = (e.target as Element).closest?.('.cc-block')?.getAttribute('data-id') ?? null;\n if (id !== this.hovered) {\n this.hovered = id;\n this.updateHighlight();\n }\n });\n on(r, 'pointerleave', () => {\n if (this.hovered) {\n this.hovered = null;\n this.updateHighlight();\n }\n });\n // Safari pinch gestures\n on(r, 'gesturestart', (e: Event) => e.preventDefault());\n const doc = r.ownerDocument;\n on(doc, 'copy', (e: ClipboardEvent) => this.onClipboard(e, 'copy'));\n on(doc, 'cut', (e: ClipboardEvent) => this.onClipboard(e, 'cut'));\n on(doc, 'paste', (e: ClipboardEvent) => this.onClipboard(e, 'paste'));\n }\n\n private isOverlay(t: EventTarget | null) {\n return !!(t as Element)?.closest?.('.cc-editor, .cc-bar, .cc-refs, .cc-banner, .cc-rename');\n }\n\n private onDown(e: PointerEvent) {\n if (this.isOverlay(e.target)) return;\n if (e.pointerType === 'mouse' && e.button !== 0 && e.button !== 1) return;\n this.root.focus({ preventScroll: true });\n this.root.setPointerCapture(e.pointerId);\n this.pointers.set(e.pointerId, this.local(e));\n if (this.pointers.size === 2) {\n // Pinch: abandon a drag in progress.\n if (this.gesture?.t === 'drag') this.endDrag(false);\n const [a, b] = [...this.pointers.values()];\n this.gesture = { t: 'pinch', d0: Math.hypot(a.x - b.x, a.y - b.y), m0: mid(a, b), cam: { ...this.cam } };\n return;\n }\n if (this.pointers.size > 2) return;\n const p = this.local(e);\n if (e.button === 1) {\n this.gesture = { t: 'pan', id: e.pointerId, sx: p.x, sy: p.y, cam: { ...this.cam } };\n return;\n }\n this.gesture = { t: 'pending', id: e.pointerId, sx: p.x, sy: p.y, touch: e.pointerType !== 'mouse', target: e.target as Element };\n }\n\n private onMove(e: PointerEvent): void {\n const p = this.local(e);\n if (e.pointerType === 'mouse') this.lastPointer = this.toWorld(e.clientX, e.clientY);\n if (!this.pointers.has(e.pointerId)) return;\n this.pointers.set(e.pointerId, p);\n const g = this.gesture;\n if (!g) return;\n if (g.t === 'pinch') {\n if (this.pointers.size < 2) return;\n const [a, b] = [...this.pointers.values()];\n const d = Math.hypot(a.x - b.x, a.y - b.y);\n const m = mid(a, b);\n const s = clamp(g.cam.s * (d / g.d0), MIN_SCALE, MAX_SCALE);\n const wx = (g.m0.x - g.cam.x) / g.cam.s;\n const wy = (g.m0.y - g.cam.y) / g.cam.s;\n this.setCamera({ s, x: m.x - wx * s, y: m.y - wy * s });\n return;\n }\n if (g.id !== e.pointerId) return;\n const dx = p.x - g.sx;\n const dy = p.y - g.sy;\n if (g.t === 'pending') {\n if (Math.hypot(dx, dy) < (g.touch ? 8 : 4)) return;\n const w = this.toWorld(e.clientX - dx, e.clientY - dy);\n const hit = g.target?.closest('.cc-fold') ? { block: null } : this.hitTest(w);\n const geo = hit.block ? this.geom!.geo.get(hit.block) : null;\n if (geo && !this.stale) {\n this.gesture = { t: 'drag', id: g.id, sx: g.sx, sy: g.sy, block: geo.id, orig: { x: geo.x, y: geo.y }, nested: !!geo.block.parentId };\n this.els.get(geo.id)?.el.classList.add('cc-dragging');\n this.hovered = geo.id;\n } else {\n this.gesture = { t: 'pan', id: g.id, sx: g.sx, sy: g.sy, cam: { ...this.cam } };\n }\n return this.onMove(e);\n }\n if (g.t === 'pan') {\n this.setCamera({ ...g.cam, x: g.cam.x + dx, y: g.cam.y + dy });\n } else if (g.t === 'drag') {\n let x = g.orig.x + dx / this.cam.s;\n let y = g.orig.y + dy / this.cam.s;\n if (g.nested) (x = Math.max(0, x)), (y = Math.max(0, y));\n this.layout.blocks[g.block] = { x: Math.round(x), y: Math.round(y) };\n if (!this.camQueued) this.relayoutSoon();\n }\n }\n\n private relayoutQueued = false;\n private relayoutSoon() {\n if (this.relayoutQueued) return;\n this.relayoutQueued = true;\n requestAnimationFrame(() => {\n this.relayoutQueued = false;\n if (!this.view) return;\n // While dragging, don't push other blocks around; the drop finds a free spot instead.\n this.geom = computeGeometry(this.view, this.layout, this.hints, { resolveOverlaps: false });\n this.render();\n });\n }\n\n private onUp(e: PointerEvent, cancelled = false) {\n if (!this.pointers.has(e.pointerId)) return;\n this.pointers.delete(e.pointerId);\n const g = this.gesture;\n if (!g) return;\n if (g.t === 'pinch') {\n if (this.pointers.size === 0) this.gesture = null;\n else {\n // One finger left: continue as a pan from here.\n const [id, p] = [...this.pointers.entries()][0];\n this.gesture = { t: 'pan', id, sx: p.x, sy: p.y, cam: { ...this.cam } };\n }\n return;\n }\n if (g.id !== e.pointerId) return;\n if (g.t === 'drag') return this.endDrag(!cancelled);\n this.gesture = null;\n if (g.t !== 'pending' || cancelled) return;\n this.onTap(e, g.target);\n }\n\n private endDrag(commit: boolean) {\n const g = this.gesture?.t === 'drag' ? this.gesture : null;\n this.gesture = null;\n if (!g) return;\n this.els.get(g.block)?.el.classList.remove('cc-dragging');\n if (!commit) {\n this.layout.blocks[g.block] = g.orig;\n this.relayout();\n return;\n }\n // Drop: nudge to the nearest free spot so blocks never end up on top of each other.\n const geom = computeGeometry(this.view!, this.layout, this.hints, { resolveOverlaps: false });\n const geo = geom.geo.get(g.block);\n if (geo) {\n const parent = geo.block.parentId;\n const sibs = [...geom.geo.values()].filter((s) => s.block.parentId === parent && s.id !== g.block);\n this.layout.blocks[g.block] = freeSpotNear({ x: geo.x, y: geo.y }, geo, sibs, !!parent);\n }\n this.relayout();\n this.emitLayout('user');\n }\n\n private onTap(e: PointerEvent, target: Element | null) {\n const fold = target?.closest('.cc-fold');\n const w = this.toWorld(e.clientX, e.clientY);\n const hit = this.hitTest(w);\n const now = performance.now();\n const p = this.local(e);\n const dbl = now - this.lastTap.t < 350 && Math.hypot(p.x - this.lastTap.x, p.y - this.lastTap.y) < 24 && this.lastTap.id === (hit.block ?? '@' + hit.container);\n this.lastTap = { t: dbl ? 0 : now, x: p.x, y: p.y, id: hit.block ?? '@' + hit.container };\n if (fold && hit.block) return this.toggleCollapse(hit.block);\n if (hit.block) {\n // First click selects (shows usage lines), clicking the selected block edits it.\n if (this.selected === hit.block && !this.editing) return this.openEditor(hit.block);\n if (this.editing && this.editing.id !== hit.block) this.closeEditor();\n this.select(hit.block);\n return;\n }\n // Empty space: double-click creates a function there.\n if (dbl) return this.createFunctionAt(w, hit.container);\n if (this.editing) this.closeEditor();\n this.select(hit.container);\n }\n\n private onWheel(e: WheelEvent) {\n if (this.isOverlay(e.target)) return;\n e.preventDefault();\n const unit = e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? 400 : 1;\n const p = this.local(e);\n if (e.ctrlKey || e.metaKey) {\n this.zoomAt(p, Math.exp(-e.deltaY * unit * 0.0025));\n } else {\n const dx = (e.shiftKey && !e.deltaX ? e.deltaY : e.deltaX) * unit;\n const dy = (e.shiftKey && !e.deltaX ? 0 : e.deltaY) * unit;\n this.setCamera({ ...this.cam, x: this.cam.x - dx, y: this.cam.y - dy });\n }\n }\n\n private onKey(e: KeyboardEvent) {\n // The block editor may have handled the key (Escape) and removed itself from the page already.\n const isHandledByEditor = e.defaultPrevented;\n if (isHandledByEditor || (this.isOverlay(e.target) && e.target !== this.root)) return;\n const mod = e.metaKey || e.ctrlKey;\n const k = e.key;\n if (mod && k.toLowerCase() === 'z') {\n e.preventDefault();\n return e.shiftKey ? this.opts.onRedo?.() : this.opts.onUndo?.();\n }\n if (mod && k.toLowerCase() === 'y') {\n e.preventDefault();\n return this.opts.onRedo?.();\n }\n if (mod && k.toLowerCase() === 'd' && this.selected) {\n e.preventDefault();\n return this.duplicate(this.selected);\n }\n if (mod) return;\n if (k === 'Escape') return this.editing ? this.closeEditor() : this.select(null);\n if (k === 'Enter' && this.selected) {\n e.preventDefault();\n return this.openEditor(this.selected);\n }\n if (k === 'F2' && this.selected) {\n e.preventDefault();\n return this.startRename(this.selected);\n }\n if ((k === 'Delete' || k === 'Backspace') && this.selected) {\n e.preventDefault();\n return this.deleteBlock(this.selected);\n }\n if (k === '0' || k === '!') return this.fit();\n if (k === '=' || k === '+') return this.zoomBy(1.25);\n if (k === '-' || k === '_') return this.zoomBy(0.8);\n if (k === 'n' || k === 'N') return this.createFunctionAtCenter();\n if (k === 'r' && this.selected) {\n this.refsOpen = !this.refsOpen;\n return this.renderBar();\n }\n }\n\n private onClipboard(e: ClipboardEvent, type: 'copy' | 'cut' | 'paste') {\n const active = this.root.ownerDocument.activeElement;\n if (active !== this.root) return;\n if (type === 'paste') {\n const custom = e.clipboardData?.getData('application/x-codecanvas');\n const textData = e.clipboardData?.getData('text/plain');\n let clip: E.BlockClip | null = null;\n if (custom) {\n try {\n clip = JSON.parse(custom);\n } catch {}\n }\n if (!clip && textData) clip = E.clipFromText(textData);\n if (clip) {\n e.preventDefault();\n this.paste(clip);\n }\n return;\n }\n if (!this.selected || !this.view || this.stale) return;\n const clip = E.copyBlock(this.view, this.selected);\n this.clip = clip;\n e.clipboardData?.setData('text/plain', clip.code);\n e.clipboardData?.setData('application/x-codecanvas', JSON.stringify(clip));\n e.preventDefault();\n if (type === 'cut') this.deleteBlock(this.selected);\n else this.toast(`Copied ${clip.name || 'block'}`);\n this.renderBar();\n }\n\n // ---------------------------------------------------------------- actions\n\n private guard(): boolean {\n if (this.stale || !this.view) {\n this.toast(`Fix the syntax error on line ${this.model?.firstErrorLine} first`);\n return false;\n }\n return true;\n }\n\n /** Edits that add, remove or rename blocks work on the text's structure, which conflicts break. */\n private guardStructureEdit(): boolean {\n if (!this.guard()) return false;\n if (this.conflicts) {\n this.toast('Resolve the merge conflicts in this file first');\n return false;\n }\n return true;\n }\n\n private toggleCollapse(id: string) {\n const set = new Set(this.layout.collapsed ?? []);\n if (set.has(id)) set.delete(id);\n else set.add(id);\n this.layout.collapsed = [...set];\n this.relayout();\n this.emitLayout('user');\n }\n\n private createFunctionAt(w: Point, containerId: string | null) {\n if (!this.guardStructureEdit()) return;\n const view = this.view!;\n const container = E.containerFor(view, containerId);\n const r = E.newFunction(view, container?.id ?? null);\n this.hints[r.id] = this.relativeTo(container?.id ?? null, { x: w.x - 24, y: w.y - 16 });\n this.applyInsert(r);\n }\n\n private createFunctionAtCenter() {\n const rect = this.root.getBoundingClientRect();\n const w = this.toWorld(rect.left + rect.width / 2, rect.top + rect.height / 2);\n const target = this.selected ? E.containerFor(this.view!, this.selected)?.id ?? null : this.hitTest(w).container;\n if (target) {\n const g = this.geom!.geo.get(target)!;\n return this.createFunctionAt({ x: g.ax + M.pad + 24, y: g.ay + g.h }, target);\n }\n this.createFunctionAt(w, null);\n }\n\n /** Convert a world point into coordinates relative to a container's content origin. */\n private relativeTo(containerId: string | null, w: Point): Point {\n if (!containerId) return { x: Math.round(w.x), y: Math.round(w.y) };\n const g = this.geom!.geo.get(containerId)!;\n return { x: Math.max(0, Math.round(w.x - g.ax - M.pad)), y: Math.max(0, Math.round(w.y - g.ay - g.contentTop)) };\n }\n\n private applyInsert(r: E.InsertResult, edit = true) {\n this.commit(E.applyEdit(this.text, r.edit));\n if (r.id && this.view?.blocks.has(r.id)) {\n this.select(r.id);\n if (edit) this.openEditor(r.id, r.select);\n }\n }\n\n private deleteBlock(id: string) {\n if (!this.guardStructureEdit()) return;\n const b = this.view!.blocks.get(id);\n if (!b) return;\n if (this.editing) this.closeEditor();\n this.select(b.parentId);\n this.commit(E.applyEdit(this.text, E.deleteBlock(this.view!, id)));\n this.toast(`Deleted ${b.name}. Undo with ${isMac() ? '\u2318' : 'Ctrl'}+Z`);\n }\n\n private duplicate(id: string) {\n if (!this.guardStructureEdit()) return;\n const view = this.view!;\n const b = view.blocks.get(id);\n if (!b || b.kind === 'import' || b.kind === 'statement') return;\n const clip = E.copyBlock(view, id);\n const r = E.pasteBlock(view, b.parentId, clip);\n const geo = this.geom!.geo.get(id)!;\n if (r.id) this.hints[r.id] = { x: geo.x + 24, y: geo.y + geo.h + M.gap };\n this.applyInsert(r, false);\n }\n\n private copy(id: string) {\n if (!this.view || this.stale) return;\n this.clip = E.copyBlock(this.view, id);\n navigator.clipboard?.writeText(this.clip.code).catch(() => {});\n this.toast(`Copied ${this.clip.name}`);\n this.renderBar();\n }\n\n private paste(clip: E.BlockClip | null = this.clip) {\n if (!clip || !this.guardStructureEdit()) return;\n const view = this.view!;\n // Paste where the pointer is, or into the selected container.\n let target: string | null = null;\n let at: Point | null = null;\n if (this.lastPointer) {\n const hit = this.hitTest(this.lastPointer);\n target = hit.block ? E.containerFor(view, hit.block)?.id ?? null : hit.container;\n at = this.lastPointer;\n } else if (this.selected) {\n target = E.containerFor(view, this.selected)?.id ?? null;\n }\n const r = E.pasteBlock(view, target, clip);\n if (r.id && at) this.hints[r.id] = this.relativeTo(target, { x: at.x - 24, y: at.y - 16 });\n this.applyInsert(r, false);\n }\n\n // ---------------------------------------------------------------- rename\n\n /** Show a name field in the block's header. Enter renames the block and its usages in every file. */\n startRename(id: string) {\n if (!this.guardStructureEdit()) return;\n const block = this.view!.blocks.get(id);\n if (!block) return;\n if (!isRenamable(block)) return this.toast(`${block.name} can't be renamed`);\n if (this.editing) this.closeEditor();\n this.cancelRename();\n this.select(id);\n // The field is drawn at canvas scale: zoom in first if it would be too small to read.\n if (this.cam.s < 0.6) this.reveal(id);\n const nameEl = this.els.get(id)?.el.querySelector('.cc-name');\n if (!nameEl) return;\n const input = document.createElement('input');\n input.className = 'cc-rename';\n input.value = block.name;\n input.spellcheck = false;\n input.setAttribute('aria-label', `New name for ${block.name}`);\n const fitWidth = () => (input.style.width = `${Math.max(input.value.length, 4) + 2}ch`);\n fitWidth();\n input.addEventListener('input', () => {\n fitWidth();\n input.classList.remove('invalid');\n });\n input.addEventListener('keydown', (e) => {\n e.stopPropagation();\n if (e.key === 'Enter') {\n e.preventDefault();\n this.commitRename();\n } else if (e.key === 'Escape') {\n e.preventDefault();\n this.cancelRename();\n this.root.focus({ preventScroll: true });\n }\n });\n input.addEventListener('blur', () => this.cancelRename());\n nameEl.replaceChildren(input);\n this.renaming = { id, input };\n input.focus({ preventScroll: true });\n input.select();\n }\n\n private cancelRename() {\n const renaming = this.renaming;\n if (!renaming) return;\n this.renaming = null;\n const name = this.view?.blocks.get(renaming.id)?.name ?? '';\n renaming.input.parentElement?.replaceChildren(document.createTextNode(name));\n }\n\n private async commitRename() {\n const renaming = this.renaming;\n const block = renaming && this.view?.blocks.get(renaming.id);\n if (!renaming || !block) return this.cancelRename();\n if (renaming.isApplying) return;\n const newName = renaming.input.value.trim();\n if (newName === block.name) {\n this.cancelRename();\n return this.root.focus({ preventScroll: true });\n }\n renaming.isApplying = true;\n const textAtRequest = this.text;\n const result = await this.project.renameBlock(this.path, block.id, newName);\n renaming.isApplying = false;\n if (this.renaming !== renaming) return; // cancelled meanwhile\n if (this.text !== textAtRequest) {\n // The edits are offsets into the text the project saw.\n renaming.input.classList.add('invalid');\n return this.toast('The file changed. Press Enter to rename again');\n }\n if (!result.ok) {\n renaming.input.classList.add('invalid');\n return this.toast(result.error);\n }\n // Cleared first: re-rendering the block removes the field, which fires its blur.\n this.renaming = null;\n const ownEdits = result.edits[this.path] ?? [];\n const shiftBeforeBlock = ownEdits.filter((e) => e.end <= block.start).reduce((sum, e) => sum + e.text.length - (e.end - e.start), 0);\n const otherPaths = Object.keys(result.edits).filter((path) => path !== this.path);\n const otherFiles = otherPaths.map((path): OtherFileChange => {\n const previousModel = this.project.getModel(path);\n const before = this.project.getText(path) ?? '';\n const after = E.applyEdits(before, result.edits[path]);\n this.project.setFile(path, after);\n return { path, before, after, previousModel };\n });\n this.commit(E.applyEdits(this.text, ownEdits), otherFiles.length ? otherFiles : undefined);\n const renamed = [...(this.view?.blocks.values() ?? [])].find((b) => b.start === block.start + shiftBeforeBlock && b.name === newName);\n if (renamed) this.select(renamed.id);\n this.root.focus({ preventScroll: true });\n this.toast(otherPaths.length ? `Renamed to ${newName} in ${otherPaths.length + 1} files` : `Renamed to ${newName}`);\n }\n\n // ---------------------------------------------------------------- inline editor\n\n openEditor(id: string, selection?: [number, number]) {\n if (!this.guard()) return;\n const b = this.view!.blocks.get(id);\n if (!b) return;\n if (this.conflicts) {\n // The block's real text, conflict markers included, so both sides can be merged by hand.\n const touching = (this.conflicts.hunksByBlock.get(id) ?? []).map((index) => this.conflicts!.hunks[index]);\n const start = Math.min(this.conflicts.current.toFileOffset(b.start), ...touching.map((hunk) => hunk.start));\n const end = Math.max(this.conflicts.current.toFileOffset(b.end), ...touching.map((hunk) => hunk.end));\n return this.openRangeEditor(start, end, b);\n }\n this.openRangeEditor(b.start, b.end, b, selection);\n }\n\n private openRangeEditor(start: number, end: number, b: Block | null, selection?: [number, number]) {\n this.closeEditor({ restoreCamera: false });\n this.refsOpen = false;\n const panel = el('div', 'cc-editor');\n const head = el('div', 'cc-editor-head');\n const chip = el('div', 'cc-chip');\n chip.classList.add(`k-${b?.kind ?? 'statement'}`);\n chip.style.setProperty('--k', `var(--k-${b?.kind ?? 'statement'})`);\n setHTML(chip, `<i></i><span>${esc(b ? b.name : this.path)}</span>`);\n const hint = el('span', 'cc-editor-hint');\n hint.textContent = 'Esc to close';\n head.append(chip, hint, button('Done', () => this.closeEditor(), 'primary'));\n const body = el('div', 'cc-editor-body');\n panel.append(head, body);\n this.root.appendChild(panel);\n\n const code = this.text.slice(start, end);\n const lines = code.split('\\n').length;\n const { width: vw, height: vh } = this.root.getBoundingClientRect();\n const mobile = vw < 700;\n if (mobile) {\n Object.assign(panel.style, { left: '0', right: '0', bottom: '0', height: Math.round(vh * 0.52) + 'px', borderRadius: '14px 14px 0 0' });\n } else {\n const w = Math.min(640, vw - 32);\n const h = Math.min(vh - 32, Math.max(160, lines * 19 + 70));\n Object.assign(panel.style, { right: '16px', top: '16px', width: w + 'px', height: h + 'px' });\n }\n // Keep the block visible next to (or above) the editor.\n if (b) {\n const g = this.geom?.geo.get(b.id);\n if (g) {\n const s = this.cam.s;\n const sx = g.ax * s + this.cam.x;\n const sy = g.ay * s + this.cam.y;\n let dx = 0,\n dy = 0;\n if (mobile) {\n const avail = vh * 0.48;\n if (sy < 12 || sy > avail - 60) dy = 24 - sy;\n if (sx < 12 || sx + Math.min(g.w * s, vw) > vw) dx = 16 - sx;\n } else {\n const right = vw - Math.min(640, vw - 32) - 32;\n if (sx + g.w * s > right) dx = Math.max(right - (sx + g.w * s), 24 - sx);\n if (sx + dx < 12) dx = 24 - sx;\n if (sy < 12 || sy > vh - 80) dy = 40 - sy;\n }\n if (dx || dy) {\n const shifted = { ...this.cam, x: this.cam.x + dx, y: this.cam.y + dy };\n // Switching to another block's editor keeps the first camera: closing goes back to it.\n this.cameraBeforeEditor = { before: this.cameraBeforeEditor?.before ?? { ...this.cam }, shifted };\n this.moveCamera(shifted, true);\n }\n }\n }\n const handle = this.opts.createEditor({\n parent: body,\n text: code,\n start,\n end,\n selection,\n diffBase: this.conflicts ? undefined : this.baseCodeOf(b),\n onChange: (t) => this.onEditorChange(t),\n onClose: () => {\n this.closeEditor();\n this.root.focus({ preventScroll: true });\n },\n });\n this.editing = { start, len: code.length, id: b?.id ?? null, handle, el: panel };\n if (b) this.selected = b.id;\n this.banner.querySelector('button')?.remove();\n this.updateHighlight();\n this.renderBar();\n handle.focus();\n }\n\n private onEditorChange(code: string) {\n const ed = this.editing;\n if (!ed) return;\n const text = this.text.slice(0, ed.start) + code + this.text.slice(ed.start + ed.len);\n ed.len = code.length;\n this.commit(text);\n }\n\n closeEditor({ restoreCamera = true }: { restoreCamera?: boolean } = {}) {\n const ed = this.editing;\n if (!ed) return;\n this.editing = null;\n const cameraBeforeEditor = this.cameraBeforeEditor;\n if (restoreCamera) {\n this.cameraBeforeEditor = null;\n // Back to where the canvas was before the editor moved it, unless the user moved it since.\n const isStillWhereEditorPutIt = !!cameraBeforeEditor && Math.abs(this.cam.x - cameraBeforeEditor.shifted.x) < 1 && Math.abs(this.cam.y - cameraBeforeEditor.shifted.y) < 1 && this.cam.s === cameraBeforeEditor.shifted.s;\n if (isStillWhereEditorPutIt) this.moveCamera(cameraBeforeEditor.before, true);\n }\n ed.handle.destroy();\n ed.el.remove();\n if (this.stale) this.parseNow(); // re-show the \"Edit file\" button\n this.updateHighlight();\n this.renderBar();\n }\n\n // ---------------------------------------------------------------- toolbar & references\n\n private renderBar() {\n const bar = this.bar;\n bar.replaceChildren();\n bar.hidden = !!this.editing;\n const b = this.selected ? this.view?.blocks.get(this.selected) : null;\n if (b) {\n const chip = el('div', 'cc-chip');\n chip.style.setProperty('--k', `var(--k-${b.kind})`);\n setHTML(chip, `<i></i>${esc(b.name)}`);\n const refs = this.refsFor(b.id);\n const errors = this.diagnosticsInside(b.id);\n if (this.conflicts) {\n const isConflicted = this.conflicts.hunksByBlock.has(b.id);\n const firstHunk = isConflicted ? this.conflicts.hunks[this.conflicts.hunksByBlock.get(b.id)![0]] : undefined;\n const keep = (label: string, choice: ConflictChoice, side?: string) => {\n const keepButton = button(label, () => this.keepConflictSide(b.id, choice), choice === 'current' ? 'primary' : undefined);\n if (side) keepButton.title = side;\n return keepButton;\n };\n bar.append(\n chip,\n el('div', 'cc-sep'),\n ...(firstHunk ? [keep('Keep current', 'current', firstHunk.currentLabel), keep('Keep incoming', 'incoming', firstHunk.incomingLabel), keep('Keep both', 'both'), el('div', 'cc-sep')] : []),\n button('Edit', () => this.openEditor(b.id)),\n button('Copy', () => this.copy(b.id)),\n ...this.languageLabelParts(),\n );\n return this.renderRefs();\n }\n bar.append(\n chip,\n el('div', 'cc-sep'),\n ...(errors.length ? [button(plural(errors.length, 'error'), () => this.toggleRefs(), 'danger')] : []),\n button('Edit', () => this.openEditor(b.id)),\n ...(isRenamable(b) ? [button('Rename', () => this.startRename(b.id))] : []),\n button(`Refs ${refs.incoming.length + refs.outgoing.length}`, () => this.toggleRefs()),\n button('Copy', () => this.copy(b.id)),\n ...(b.kind !== 'import' && b.kind !== 'statement' ? [button('Duplicate', () => this.duplicate(b.id))] : []),\n ...(b.insert ? [button('+ Inside', () => this.createFunctionAtCenter())] : []),\n button('Delete', () => this.deleteBlock(b.id), 'danger'),\n );\n } else {\n const firstErrorBlock = this.diagnostics.find((d) => d.blockId)?.blockId;\n if (firstErrorBlock) bar.append(button(plural(this.diagnostics.length, 'error'), () => this.showErrorsOf(firstErrorBlock), 'danger'));\n const diff = this.currentDiff();\n if (diff) bar.append(changesSummary(diff), el('div', 'cc-sep'));\n bar.append(button('+ Function', () => this.createFunctionAtCenter()));\n if (this.clip) bar.append(button('Paste', () => (this.lastPointer = null, this.paste())));\n bar.append(\n this.layoutBeforeArrange ? button('Undo arrange', () => this.undoArrange()) : button('Arrange', () => this.arrange()),\n el('div', 'cc-sep'),\n button('Fit', () => this.fit()),\n button('\u2212', () => this.zoomBy(0.8)),\n button('+', () => this.zoomBy(1.25)),\n );\n }\n bar.append(...this.languageLabelParts());\n this.renderRefs();\n }\n\n private languageLabelParts(): HTMLElement[] {\n if (!this.view) return [];\n const label = el('span', 'cc-language');\n label.textContent = this.view.language.label;\n return [el('div', 'cc-sep'), label];\n }\n\n private toggleRefs() {\n this.refsOpen = !this.refsOpen;\n this.renderBar();\n }\n\n private showErrorsOf(id: string) {\n this.reveal(id);\n this.refsOpen = true;\n this.renderBar();\n }\n\n private diagnosticsInside(id: string): CodeDiagnostic[] {\n return this.diagnostics.filter((d) => d.blockId === id || !!d.blockId?.startsWith(id + '/'));\n }\n\n private refsFor(id: string): { incoming: (Usage | IncomingUsage)[]; outgoing: Usage[] } {\n const usages = this.view?.usages ?? [];\n const inside = (x: string) => x === id || x.startsWith(id + '/');\n // An import link is replaced by the specific blocks it reaches in the other file.\n const importsReachedElsewhere = new Set(usages.filter((u) => u.toPath && u.via).map((u) => `${u.from}>${u.via}`));\n const isImportLinkWithTargets = (u: Usage) => !u.toPath && importsReachedElsewhere.has(`${u.from}>${u.to}`);\n return {\n incoming: [...usages.filter((u) => !u.toPath && inside(u.to) && !inside(u.from)), ...this.incomingUsages.filter((u) => inside(u.to))],\n outgoing: usages.filter((u) => inside(u.from) && (u.toPath || !inside(u.to)) && !isImportLinkWithTargets(u)),\n };\n }\n\n private renderRefs() {\n const panel = this.refsEl;\n const selected = this.selected ? this.view?.blocks.get(this.selected) : null;\n panel.hidden = !this.refsOpen || !selected || !!this.editing;\n if (panel.hidden || !selected) return;\n const { incoming, outgoing } = this.refsFor(selected.id);\n const errors = this.diagnosticsInside(selected.id);\n const heading = (text: string) => Object.assign(el('h4'), { textContent: text });\n const note = (text: string) => Object.assign(el('div', 'none'), { textContent: text });\n const row = (path: string | undefined, blockId: string, usage: Usage) => {\n const isOtherFile = !!path && path !== this.path;\n const model = isOtherFile ? this.project.getModel(path) : this.view;\n const block = model?.blocks.get(blockId);\n const btn = keepsCanvasFocus(document.createElement('button'));\n btn.style.setProperty('--k', `var(--k-${block?.kind ?? 'statement'})`);\n const name = block && model ? displayName(model, block) : blockId;\n const label = isOtherFile ? `<span class=\"cc-file\">${esc(fileName(path))} \u203A</span> ${esc(name)}` : esc(name);\n setHTML(btn, `<i></i><span>${label}</span><span>${usage.kind === 'render' ? 'renders' : usage.kind}${usage.count > 1 ? ' \u00D7' + usage.count : ''}</span>`);\n btn.onclick = () => (isOtherFile ? this.opts.onOpenBlock?.(path, blockId) : this.reveal(blockId));\n btn.disabled = isOtherFile && !this.opts.onOpenBlock;\n return btn;\n };\n panel.replaceChildren();\n if (errors.length) {\n panel.append(heading(`Errors (${errors.length})`));\n for (const d of errors) {\n const btn = keepsCanvasFocus(document.createElement('button'));\n btn.className = 'cc-error-row';\n setHTML(btn, `<i></i><span>${esc(d.message)}</span><span>line ${d.line}</span>`);\n btn.onclick = () => this.openEditorAtDiagnostic(d);\n panel.append(btn);\n }\n }\n panel.append(heading(`Used by (${incoming.length})`));\n if (incoming.length) for (const u of incoming) panel.append(row('fromPath' in u ? u.fromPath : undefined, u.from, u));\n else panel.append(note('Not used anywhere'));\n panel.append(heading(`Uses (${outgoing.length})`));\n if (outgoing.length) for (const u of outgoing) panel.append(row(u.toPath, u.to, u));\n else panel.append(note('Uses nothing from this project'));\n }\n\n private openEditorAtDiagnostic(d: CodeDiagnostic) {\n if (this.stale) return this.openRangeEditor(0, this.text.length, null, [d.start, d.start + d.length]);\n const block = d.blockId ? this.view?.blocks.get(d.blockId) : undefined;\n if (!block) return;\n const offset = d.start - block.start;\n this.openEditor(block.id, [offset, offset + d.length]);\n }\n\n private toast(msg: string) {\n this.toastEl.textContent = msg;\n this.toastEl.style.opacity = '1';\n clearTimeout(this.toastTimer);\n this.toastTimer = window.setTimeout(() => (this.toastEl.style.opacity = '0'), 2200);\n }\n}\n\n// ---------------------------------------------------------------- helpers\n\n/** Small label at the start of a block header: `fn`, `class`, `const`, `interface`, `get`\u2026 */\nfunction blockLabel(b: Block): string {\n if (b.kind === 'function') return b.tags.find((t) => t === 'get' || t === 'set') ?? 'fn';\n if (b.kind === 'variable' || b.kind === 'type') return b.tags.find((t) => LABEL_TAGS.has(t)) ?? KIND_LABEL[b.kind];\n return KIND_LABEL[b.kind];\n}\n\ninterface FileConflicts {\n hunks: ConflictHunk[];\n /** The text the canvas shows: each conflict replaced by its current side. */\n current: ConflictSideText;\n incomingModel: FileModel;\n /** Blocks each conflict touches (innermost ones), by block id: indexes into `hunks`. */\n hunksByBlock: Map<string, number[]>;\n /** Outermost blocks only the incoming side has. */\n incomingOnly: Block[];\n geometry?: FileGeometry;\n}\n\n/** The innermost blocks whose text overlaps `range` (or contains it, when it's empty). */\nfunction innermostBlocksTouching(model: FileModel, range: ConflictSide): Block[] {\n // An empty side (code only the other side has) touches a block only from inside, e.g. a class it's added to.\n const touches = (block: Block) => (range.start === range.end ? block.start < range.start && range.start < block.end : block.start < range.end && range.start < block.end);\n const found: Block[] = [];\n const visit = (blocks: Block[]) => {\n for (const block of blocks.filter(touches)) {\n const touchingChildren = block.children.filter(touches);\n if (touchingChildren.length) visit(block.children);\n else found.push(block);\n }\n };\n visit(model.roots);\n return found;\n}\n\n/** The part of `before` that differs from `after`: `before.slice(start, end)` became the rest. */\nfunction changedRegion(before: string, after: string): { start: number; end: number } {\n let start = 0;\n const shorter = Math.min(before.length, after.length);\n while (start < shorter && before.charCodeAt(start) === after.charCodeAt(start)) start++;\n let fromEnd = 0;\n while (fromEnd < shorter - start && before.charCodeAt(before.length - 1 - fromEnd) === after.charCodeAt(after.length - 1 - fromEnd)) fromEnd++;\n return { start, end: before.length - fromEnd };\n}\n\nfunction isRenamable(b: Block): boolean {\n return b.nameStart >= 0 && b.kind !== 'import' && b.kind !== 'statement' && b.name !== 'constructor';\n}\n\n/** `Cart.total`, `import ./pricing` */\nfunction displayName(model: FileModel, b: Block): string {\n if (b.kind === 'import') return 'import ' + b.name;\n const names = [b.name];\n let parent = b.parentId ? model.blocks.get(b.parentId) : null;\n while (parent) {\n names.unshift(parent.name);\n parent = parent.parentId ? model.blocks.get(parent.parentId) : null;\n }\n return names.join('.');\n}\n\nfunction fileName(path: string): string {\n return path.slice(path.lastIndexOf('/') + 1);\n}\n\nfunction changesSummary(diff: FileDiff): HTMLElement {\n const changes = [...diff.changes.values()];\n const counts = [\n [changes.filter((change) => change === 'changed').length, 'changed'],\n [changes.filter((change) => change === 'added').length, 'added'],\n [diff.removed.length, 'removed'],\n ] as const;\n const parts = counts.filter(([count]) => count > 0).map(([count, word]) => `${count} ${word}`);\n return Object.assign(el('span', 'cc-diff-summary'), { textContent: parts.length ? parts.join(' \u00B7 ') : 'No changes' });\n}\n\nfunction plural(count: number, word: string): string {\n return `${count} ${word}${count === 1 ? '' : 's'}`;\n}\n\nfunction edgePath(a: Geo, b: Geo): string {\n const ay = a.ay + Math.min(a.h / 2, 16);\n const by = b.ay + Math.min(b.h / 2, 16);\n if (b.ax >= a.ax + a.w + 8) return curveH(a.ax + a.w, ay, b.ax, by);\n if (b.ax + b.w <= a.ax - 8) return curveH(a.ax, ay, b.ax + b.w, by);\n const ax = a.ax + a.w / 2;\n const bx = b.ax + b.w / 2;\n if (b.ay > a.ay) return curveV(ax, a.ay + a.h, bx, b.ay);\n return curveV(ax, a.ay, bx, b.ay + b.h);\n}\n\nfunction curveH(x1: number, y1: number, x2: number, y2: number) {\n const c = Math.max(30, Math.abs(x2 - x1) * 0.5) * Math.sign(x2 - x1 || 1);\n return `M${x1} ${y1}C${x1 + c} ${y1} ${x2 - c} ${y2} ${x2} ${y2}`;\n}\n\nfunction curveV(x1: number, y1: number, x2: number, y2: number) {\n const c = Math.max(30, Math.abs(y2 - y1) * 0.5) * Math.sign(y2 - y1 || 1);\n return `M${x1} ${y1}C${x1} ${y1 + c} ${x2} ${y2 - c} ${x2} ${y2}`;\n}\n\nfunction el(tag: string, cls?: string): HTMLElement {\n const e = document.createElement(tag);\n if (cls) e.className = cls;\n return e;\n}\n\nfunction button(label: string, onClick: () => void, variant?: string): HTMLButtonElement {\n const b = keepsCanvasFocus(document.createElement('button'));\n b.className = 'cc-btn' + (variant ? ' ' + variant : '');\n b.textContent = label;\n b.addEventListener('click', (e) => {\n e.stopPropagation();\n onClick();\n });\n return b;\n}\n\n/** Clicking the button leaves keyboard focus on the canvas, so its shortcuts (F2, Delete\u2026) keep working. */\nfunction keepsCanvasFocus<T extends HTMLElement>(element: T): T {\n element.addEventListener('pointerdown', (e) => e.preventDefault());\n return element;\n}\n\nfunction esc(s: string): string {\n return s.replace(/[&<>\"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '\"': '&quot;' })[c]!);\n}\n\nfunction clamp(v: number, lo: number, hi: number) {\n return Math.min(hi, Math.max(lo, v));\n}\n\nfunction mid(a: Point, b: Point): Point {\n return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };\n}\n\nfunction isMac() {\n return /Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent);\n}\n"],
5
+ "mappings": ";AAAA,OAAOA,SAAQ;;;ACAf,OAAOC,SAAQ;;;ACAf,OAAO,QAAQ;AAGR,SAAS,OAAO,GAAiC;AACtD,SAAO,GAAG,0BAA0B,CAAC,KAAK,GAAG,eAAe,CAAC,KAAK,GAAG,sBAAsB,CAAC,KAAK,GAAG,0BAA0B,CAAC,EAAG,KAAI,EAAE;AACxI,SAAO;AACT;;;ADFA,IAAM,eAAe;AAMd,SAAS,eAAe,M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