@mica-js/editor 0.4.0 → 0.5.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/fused.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"fused.js","names":["lockKey","requireFinite","takenIds","takenIds","distanceToSegment","samePoint","replaceViewLayout","distanceToSegment","_Fragment","_Fragment","_Fragment"],"sources":["../src/fused/context/keys.ts","../src/fused/context/condition.ts","../src/fused/context/scope.ts","../src/fused/devices.ts","../src/fused/document/errors.ts","../src/fused/document/edits.ts","../src/fused/document/copy.ts","../src/fused/canvas/geometry.ts","../src/fused/wiring.ts","../src/fused/document/verify.ts","../src/fused/document/session.ts","../src/fused/contributions/registry.ts","../src/fused/views/layout.ts","../src/fused/parts/activity-bar-part.tsx","../src/fused/canvas/renderer.ts","../src/fused/parts/canvas-part.tsx","../src/fused/parts/sidebar-part.tsx","../src/fused/parts/toolbar-part.tsx","../src/fused/views/instances.tsx","../src/fused/views/program.tsx","../src/fused/views/inspector.tsx","../src/fused/views/problems.tsx","../src/fused/parts/html-views-part.tsx","../src/fused/parts/workbench-part.tsx","../src/fused/workbench.tsx"],"sourcesContent":["import type { IDisposable } from '@mica-js/core/lifecycle';\n\n/** Scalar value a context key carries; a key that nobody registered reads as `undefined`. */\nexport type ContextValue = string | number | boolean;\n\n/**\n * Who owns a key. `workbench` is the editor itself and is the only owner allowed to claim the\n * namespaces in {@link BUILT_IN_CONTEXT_PREFIXES}; `host` covers every contributed view,\n * container and device package.\n */\nexport type ContextKeyOwner = 'workbench' | 'host';\n\n/**\n * Namespaces reserved for editor-owned state. A host-owned scope can never register these names,\n * so a contributed view cannot shadow workbench state such as the active selection or the editor\n * mode; the editor registers them from a workbench-owned scope.\n */\nexport const BUILT_IN_CONTEXT_PREFIXES: readonly string[] = ['workbench.', 'editor.'];\n\n/** Why a context key or scope operation was rejected. */\nexport type ContextRegistrationErrorReason =\n | 'duplicate-key'\n | 'invalid-key'\n | 'reserved-prefix'\n | 'owner-escalation'\n | 'type-mismatch'\n | 'disposed';\n\n/** Raised when a key, a value or a scope operation violates the context registry contract. */\nexport class ContextRegistrationError extends Error {\n constructor(\n message: string,\n readonly reason: ContextRegistrationErrorReason,\n readonly keyName: string | undefined,\n ) {\n super(message);\n this.name = 'ContextRegistrationError';\n }\n}\n\n/**\n * Widens a literal default to its primitive, so `createKey('workbench.mode', 'edit')` yields\n * `IContextKey<string>` and `set('simulate')` type-checks.\n */\nexport type ContextValueType<T> = T extends string\n ? string\n : T extends number\n ? number\n : T extends boolean\n ? boolean\n : ContextValue;\n\n/** Extra ownership metadata for one key; the default is the owning scope's owner. */\nexport interface IContextKeyOptions {\n /**\n * Declares who owns the key. A reserved prefix still requires the creating scope to be\n * workbench-owned, so this option never unlocks built-in names from a host scope.\n */\n readonly owner?: ContextKeyOwner;\n}\n\n/**\n * A typed key created inside a scope. `set` stores a local value, `reset` drops it so the key\n * falls back to its parent and then to {@link IContextKey.defaultValue}, and `dispose` removes\n * the key from its scope for good.\n */\nexport interface IContextKey<T extends ContextValue = ContextValue> extends IDisposable {\n /** Dotted name expressions reference, for example `workbench.selection.kind`. */\n readonly name: string;\n readonly defaultValue: T;\n readonly owner: ContextKeyOwner;\n /** Value stored in the owning scope; `undefined` while the key falls back to its parent. */\n readonly value: T | undefined;\n readonly disposed: boolean;\n set(value: T): void;\n reset(): void;\n}\n","import type { ContextValue } from './keys';\n\n/**\n * Reads a key by name. Unknown names return `undefined`, so independently contributed views may\n * reference keys that are registered later without an error.\n */\nexport type ContextLookup = (id: string) => ContextValue | undefined;\n\n/**\n * A parsed condition. Parsing validates once; `evaluate` is pure and reads keys through the\n * supplied lookup, so callers can evaluate the same condition against several scopes.\n */\nexport interface ICondition {\n readonly expression: string;\n /**\n * Key names the expression reads, in first-seen order. Subscribe selectively by filtering\n * `IContextChangeEvent.names` with this list.\n */\n readonly keys: readonly string[];\n evaluate(lookup: ContextLookup): boolean;\n}\n\n/** Raised for malformed expressions; `position` is the character offset of the problem. */\nexport class ConditionError extends Error {\n constructor(\n message: string,\n readonly expression: string,\n readonly position: number,\n ) {\n super(`${message} (position ${position}) in \"${expression}\"`);\n this.name = 'ConditionError';\n }\n}\n\ntype TokenKind =\n 'and' | 'or' | 'not' | 'equals' | 'not-equals' | 'open' | 'close' | 'literal' | 'key';\n\ninterface IToken {\n readonly kind: TokenKind;\n readonly text: string;\n readonly position: number;\n readonly value?: ContextValue | undefined;\n}\n\ntype ConditionNode =\n | { readonly kind: 'literal'; readonly value: ContextValue | undefined }\n | { readonly kind: 'key'; readonly id: string }\n | { readonly kind: 'not'; readonly operand: ConditionNode }\n | { readonly kind: 'and'; readonly left: ConditionNode; readonly right: ConditionNode }\n | { readonly kind: 'or'; readonly left: ConditionNode; readonly right: ConditionNode }\n | {\n readonly kind: 'compare';\n readonly operator: '==' | '!=';\n readonly left: ConditionNode;\n readonly right: ConditionNode;\n };\n\nconst INTEGER_OR_DECIMAL = /^-?[0-9]+(?:\\.[0-9]+)?/;\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_.:-]*/;\n\n/**\n * Parses a condition expression.\n *\n * Supported syntax: `&&`, `||`, `!`, parentheses, `==`, `!=`, key references and the scalar\n * literals `true`, `false`, `undefined`, `null`, numbers and single- or double-quoted strings.\n * `!` binds tighter than comparisons, which bind tighter than `&&`, which binds tighter than\n * `||`; chained comparisons need explicit parentheses. There is no `eval`/`Function` usage.\n *\n * @throws {ConditionError} when the expression is empty, has unbalanced parentheses, misses an\n * operand or operator, uses an unsupported operator/character or leaves a trailing token.\n */\nexport function parseCondition(expression: string): ICondition {\n return new ConditionParser(expression).parse();\n}\n\nclass ConditionParser {\n readonly #expression: string;\n readonly #tokens: readonly IToken[];\n readonly #keys = new Set<string>();\n #index = 0;\n\n constructor(expression: string) {\n this.#expression = expression;\n this.#tokens = tokenize(expression);\n }\n\n parse(): ICondition {\n if (this.#tokens.length === 0) {\n throw new ConditionError('Expression is empty', this.#expression, 0);\n }\n const root = this.#parseOr();\n const trailing = this.#peek();\n if (trailing !== undefined) {\n throw new ConditionError(\n `Unexpected \"${trailing.text}\"`,\n this.#expression,\n trailing.position,\n );\n }\n return {\n expression: this.#expression,\n keys: Object.freeze([...this.#keys]),\n evaluate: (lookup) => evaluateNode(root, lookup),\n };\n }\n\n #parseOr(): ConditionNode {\n let node = this.#parseAnd();\n while (this.#accept('or') !== undefined) {\n node = { kind: 'or', left: node, right: this.#parseAnd() };\n }\n return node;\n }\n\n #parseAnd(): ConditionNode {\n let node = this.#parseComparison();\n while (this.#accept('and') !== undefined) {\n node = { kind: 'and', left: node, right: this.#parseComparison() };\n }\n return node;\n }\n\n #parseComparison(): ConditionNode {\n const left = this.#parseUnary();\n const operator = this.#accept('equals') ?? this.#accept('not-equals');\n if (operator === undefined) return left;\n const right = this.#parseUnary();\n const chained = this.#peek();\n if (chained !== undefined && (chained.kind === 'equals' || chained.kind === 'not-equals')) {\n throw new ConditionError(\n 'Chained comparisons need parentheses',\n this.#expression,\n chained.position,\n );\n }\n return {\n kind: 'compare',\n operator: operator.kind === 'equals' ? '==' : '!=',\n left,\n right,\n };\n }\n\n #parseUnary(): ConditionNode {\n if (this.#accept('not') !== undefined) {\n return { kind: 'not', operand: this.#parseUnary() };\n }\n return this.#parsePrimary();\n }\n\n #parsePrimary(): ConditionNode {\n const token = this.#peek();\n if (token === undefined) {\n throw new ConditionError(\n 'Unexpected end of expression',\n this.#expression,\n this.#expression.length,\n );\n }\n if (token.kind === 'open') {\n this.#index += 1;\n const inner = this.#parseOr();\n const close = this.#peek();\n if (close?.kind !== 'close') {\n throw new ConditionError(\n 'Missing \")\"',\n this.#expression,\n close?.position ?? this.#expression.length,\n );\n }\n this.#index += 1;\n return inner;\n }\n if (token.kind === 'literal') {\n this.#index += 1;\n return { kind: 'literal', value: token.value };\n }\n if (token.kind === 'key') {\n this.#index += 1;\n this.#keys.add(token.text);\n return { kind: 'key', id: token.text };\n }\n throw new ConditionError(`Unexpected \"${token.text}\"`, this.#expression, token.position);\n }\n\n #peek(): IToken | undefined {\n return this.#tokens[this.#index];\n }\n\n #accept(kind: TokenKind): IToken | undefined {\n const token = this.#tokens[this.#index];\n if (token?.kind !== kind) return undefined;\n this.#index += 1;\n return token;\n }\n}\n\nfunction tokenize(expression: string): IToken[] {\n const tokens: IToken[] = [];\n let index = 0;\n while (index < expression.length) {\n const char = expression[index]!;\n if (/\\s/.test(char)) {\n index += 1;\n continue;\n }\n const position = index;\n if (char === '&' || char === '|') {\n if (expression[index + 1] !== char) {\n throw new ConditionError(\n `Unexpected \"${char}\"; use \"${char}${char}\"`,\n expression,\n position,\n );\n }\n tokens.push({ kind: char === '&' ? 'and' : 'or', text: `${char}${char}`, position });\n index += 2;\n continue;\n }\n if (char === '=') {\n if (expression[index + 1] !== '=') {\n throw new ConditionError('Unexpected \"=\"; use \"==\"', expression, position);\n }\n tokens.push({ kind: 'equals', text: '==', position });\n index += 2;\n continue;\n }\n if (char === '!') {\n if (expression[index + 1] === '=') {\n tokens.push({ kind: 'not-equals', text: '!=', position });\n index += 2;\n } else {\n tokens.push({ kind: 'not', text: '!', position });\n index += 1;\n }\n continue;\n }\n if (char === '(' || char === ')') {\n tokens.push({ kind: char === '(' ? 'open' : 'close', text: char, position });\n index += 1;\n continue;\n }\n if (char === \"'\" || char === '\"') {\n const text = readString(expression, index);\n tokens.push({ kind: 'literal', text, position, value: parseString(text) });\n index += text.length;\n continue;\n }\n if (/[0-9]/.test(char) || (char === '-' && /[0-9]/.test(expression[index + 1] ?? ''))) {\n const match = INTEGER_OR_DECIMAL.exec(expression.slice(index));\n if (match === null) {\n throw new ConditionError('Invalid number', expression, position);\n }\n const text = match[0];\n tokens.push({ kind: 'literal', text, position, value: Number(text) });\n index += text.length;\n continue;\n }\n if (/[A-Za-z_]/.test(char)) {\n const match = IDENTIFIER.exec(expression.slice(index));\n if (match === null) {\n throw new ConditionError(`Unexpected \"${char}\"`, expression, position);\n }\n const text = match[0];\n const value = KEYWORD_VALUES.get(text);\n if (KEYWORD_VALUES.has(text)) {\n tokens.push({ kind: 'literal', text, position, value });\n } else {\n tokens.push({ kind: 'key', text, position });\n }\n index += text.length;\n continue;\n }\n throw new ConditionError(`Unexpected character \"${char}\"`, expression, position);\n }\n return tokens;\n}\n\nconst KEYWORD_VALUES = new Map<string, ContextValue | undefined>([\n ['true', true],\n ['false', false],\n ['undefined', undefined],\n ['null', undefined],\n]);\n\n/** @returns the whole quoted literal, quotes included. */\nfunction readString(expression: string, start: number): string {\n const quote = expression[start]!;\n let index = start + 1;\n while (index < expression.length) {\n const char = expression[index]!;\n if (char === '\\\\') {\n index += 2;\n continue;\n }\n if (char === quote) return expression.slice(start, index + 1);\n index += 1;\n }\n throw new ConditionError('Unterminated string literal', expression, start);\n}\n\nfunction parseString(text: string): string {\n let value = '';\n for (let index = 1; index < text.length - 1; index += 1) {\n const char = text[index]!;\n if (char !== '\\\\') {\n value += char;\n continue;\n }\n const escaped = text[index + 1] ?? '';\n value += ESCAPES.get(escaped) ?? escaped;\n index += 1;\n }\n return value;\n}\n\nconst ESCAPES = new Map<string, string>([\n ['n', '\\n'],\n ['r', '\\r'],\n ['t', '\\t'],\n]);\n\nfunction evaluateNode(node: ConditionNode, lookup: ContextLookup): boolean {\n switch (node.kind) {\n case 'literal':\n return truthy(node.value);\n case 'key':\n return truthy(lookup(node.id));\n case 'not':\n return !evaluateNode(node.operand, lookup);\n case 'and':\n return evaluateNode(node.left, lookup) && evaluateNode(node.right, lookup);\n case 'or':\n return evaluateNode(node.left, lookup) || evaluateNode(node.right, lookup);\n case 'compare': {\n const left = resolveOperand(node.left, lookup);\n const right = resolveOperand(node.right, lookup);\n return node.operator === '==' ? left === right : left !== right;\n }\n }\n}\n\nfunction resolveOperand(node: ConditionNode, lookup: ContextLookup): ContextValue | undefined {\n switch (node.kind) {\n case 'literal':\n return node.value;\n case 'key':\n return lookup(node.id);\n default:\n return truthy(evaluateNode(node, lookup));\n }\n}\n\nfunction truthy(value: ContextValue | undefined): boolean {\n if (value === undefined) return false;\n if (typeof value === 'number') return value !== 0 && !Number.isNaN(value);\n if (typeof value === 'boolean') return value;\n return value.length > 0;\n}\n","import { Emitter, type Event, type IDisposable } from '@mica-js/core/lifecycle';\nimport { parseCondition, type ICondition } from './condition';\nimport {\n BUILT_IN_CONTEXT_PREFIXES,\n ContextRegistrationError,\n type ContextKeyOwner,\n type ContextValue,\n type ContextValueType,\n type IContextKey,\n type IContextKeyOptions,\n} from './keys';\n\n/** One effective value transition reported by a scope. */\nexport interface IContextChange {\n readonly name: string;\n readonly previous: ContextValue | undefined;\n readonly value: ContextValue | undefined;\n}\n\n/**\n * Delivered once per scope and flush. `changes` carries previous and new effective values;\n * `names` lists the same keys for callers that only filter or invalidate.\n */\nexport interface IContextChangeEvent {\n readonly scope: IContextScope;\n readonly changes: readonly IContextChange[];\n readonly names: readonly string[];\n}\n\nexport interface IContextScopeOptions {\n /** Defaults to `workbench` for the root service and `host` for child scopes. */\n readonly owner?: ContextKeyOwner;\n /** Defaults to {@link BUILT_IN_CONTEXT_PREFIXES}. */\n readonly reservedPrefixes?: readonly string[];\n}\n\n/** Constructor shape; `parent` stays internal so callers link scopes through `createScope`. */\ninterface IContextScopeInit extends IContextScopeOptions {\n readonly parent?: ContextScope;\n}\n\n/**\n * Workbench-side entry point: the root scope plus key creation. The editor owns one service and\n * hands {@link IContextKeyService.createScope} children to containers and views; those children\n * are host-owned and cannot claim reserved prefixes.\n */\nexport interface IContextKeyService extends IDisposable {\n readonly owner: ContextKeyOwner;\n readonly disposed: boolean;\n /** Fires with the effective changes of this scope only. */\n readonly onDidChange: Event<IContextChangeEvent>;\n /**\n * Creates and registers a typed key in this scope.\n *\n * @throws {ContextRegistrationError} for malformed names, invalid defaults, duplicate names in\n * this scope, reserved prefixes outside a workbench scope, or a disposed scope.\n */\n createKey<T extends ContextValue>(\n name: string,\n defaultValue: T,\n options?: IContextKeyOptions,\n ): IContextKey<ContextValueType<T>>;\n /** Effective value: local, then nearest ancestor, then the key default; `undefined` if unknown. */\n getValue(name: string): ContextValue | undefined;\n /**\n * Creates a child scope that falls back to this one.\n *\n * @param options.owner Defaults to `host`; `workbench` requires a workbench-owned parent.\n */\n createScope(options?: IContextScopeOptions): IContextScope;\n /** Defers and merges change notifications of this whole tree; fires once per scope on exit. */\n batch(run: () => void): void;\n /** Parses an expression once; see {@link ICondition.keys} for selective subscriptions. */\n compile(expression: string): ICondition;\n /** Parses `expression` when needed and evaluates it against this scope's effective values. */\n evaluate(expression: ICondition | string): boolean;\n}\n\nexport interface IContextScope extends IContextKeyService {\n readonly parent: IContextScope | undefined;\n /** Distance from the workbench root; the root is `0`. */\n readonly depth: number;\n}\n\n/**\n * Creates the editor-owned root. It defaults to `owner: 'workbench'`, so built-in keys register\n * directly; hand containers and views children from `createScope()`, which default to `host` and\n * reject reserved prefixes.\n */\nexport function createContextKeyService(options: IContextScopeOptions = {}): IContextKeyService {\n return new ContextScope(options);\n}\n\ninterface IStoredKey {\n readonly name: string;\n readonly defaultValue: ContextValue;\n readonly owner: ContextKeyOwner;\n readonly value: ContextValue | undefined;\n assign(value: ContextValue | undefined): void;\n markDisposed(): void;\n}\n\ninterface IPendingChange {\n readonly key: IStoredKey;\n readonly previous: ContextValue | undefined;\n}\n\nconst KEY_NAME = /^[A-Za-z_][A-Za-z0-9_.:-]*$/;\n\nclass ContextKey<T extends ContextValue> implements IContextKey<T>, IStoredKey {\n readonly name: string;\n readonly defaultValue: T;\n readonly owner: ContextKeyOwner;\n readonly #scope: ContextScope;\n #value: T | undefined;\n #disposed = false;\n\n constructor(name: string, defaultValue: T, owner: ContextKeyOwner, scope: ContextScope) {\n this.name = name;\n this.defaultValue = defaultValue;\n this.owner = owner;\n this.#scope = scope;\n }\n\n get value(): T | undefined {\n return this.#value;\n }\n\n get disposed(): boolean {\n return this.#disposed;\n }\n\n set(value: T): void {\n this.#assertAlive();\n if (typeof value !== typeof this.defaultValue) {\n throw new ContextRegistrationError(\n `Context key \"${this.name}\" expects a ${typeof this.defaultValue} value.`,\n 'type-mismatch',\n this.name,\n );\n }\n this.#scope.assignValue(this, value);\n }\n\n reset(): void {\n this.#assertAlive();\n if (this.#value === undefined) return;\n this.#scope.assignValue(this, undefined);\n }\n\n dispose(): void {\n if (this.#disposed) return;\n this.#disposed = true;\n this.#scope.removeKey(this);\n }\n\n assign(value: ContextValue | undefined): void {\n this.#value = value as T | undefined;\n }\n\n markDisposed(): void {\n this.#disposed = true;\n }\n\n #assertAlive(): void {\n if (this.#disposed) {\n throw new ContextRegistrationError(\n `Context key \"${this.name}\" is disposed.`,\n 'disposed',\n this.name,\n );\n }\n }\n}\n\nclass ContextBatch {\n readonly #pending = new Map<ContextScope, Map<string, IPendingChange>>();\n readonly #deferred: (() => void)[] = [];\n #depth = 0;\n #flushing = false;\n\n enter(): void {\n this.#depth += 1;\n }\n\n exit(): void {\n this.#depth -= 1;\n this.#flushWhenIdle();\n }\n\n add(scope: ContextScope, key: IStoredKey, previous: ContextValue | undefined): void {\n let entries = this.#pending.get(scope);\n if (entries === undefined) {\n entries = new Map();\n this.#pending.set(scope, entries);\n }\n if (!entries.has(key.name)) entries.set(key.name, { key, previous });\n this.#flushWhenIdle();\n }\n\n hasPending(scope: ContextScope, name: string): boolean {\n return this.#pending.get(scope)?.has(name) ?? false;\n }\n\n /** Runs now when idle, or after the next flush so deferred teardown cannot swallow events. */\n defer(run: () => void): void {\n if (this.#depth === 0 && !this.#flushing) {\n run();\n return;\n }\n this.#deferred.push(run);\n }\n\n /** Fires merged changes ancestors-first so descendants can skip keys they report themselves. */\n #flushWhenIdle(): void {\n if (this.#depth > 0 || this.#flushing) return;\n this.#flushing = true;\n try {\n while (this.#pending.size > 0) {\n const scopes = [...this.#pending.keys()].sort((left, right) => left.depth - right.depth);\n for (const scope of scopes) {\n const entries = this.#pending.get(scope);\n if (entries === undefined) continue;\n this.#pending.delete(scope);\n const changes: IContextChange[] = [];\n for (const entry of entries.values()) {\n const value = scope.getValue(entry.key.name);\n if (value !== entry.previous) {\n changes.push({ name: entry.key.name, previous: entry.previous, value });\n }\n }\n if (changes.length > 0) scope.notifyChanges(changes);\n }\n }\n } finally {\n this.#flushing = false;\n this.#runDeferred();\n }\n }\n\n #runDeferred(): void {\n while (this.#deferred.length > 0) {\n this.#deferred.shift()!();\n }\n if (this.#pending.size > 0) this.#flushWhenIdle();\n }\n}\n\nclass ContextScope implements IContextScope {\n readonly #parent: ContextScope | undefined;\n readonly #owner: ContextKeyOwner;\n readonly #reservedPrefixes: readonly string[];\n readonly #registrations = new Map<string, IStoredKey>();\n readonly #changes = new Emitter<IContextChangeEvent>();\n readonly #batch: ContextBatch;\n readonly #parentSubscription: IDisposable | undefined;\n readonly #depth: number;\n #disposed = false;\n\n /** Fires with this scope's effective changes only, never with an overridden parent change. */\n readonly onDidChange: Event<IContextChangeEvent> = this.#changes.event;\n\n constructor(options: IContextScopeInit = {}) {\n const parent = options.parent;\n this.#parent = parent;\n this.#owner = options.owner ?? 'workbench';\n this.#reservedPrefixes = options.reservedPrefixes ?? BUILT_IN_CONTEXT_PREFIXES;\n this.#depth = parent === undefined ? 0 : parent.depth + 1;\n this.#batch = parent === undefined ? new ContextBatch() : parent.#batch;\n this.#parentSubscription = parent?.onDidChange((event) => {\n if (this.#disposed) return;\n const changes = event.changes.filter((change) => this.#tracks(change.name));\n if (changes.length > 0) this.notifyChanges(changes);\n });\n }\n\n get parent(): IContextScope | undefined {\n return this.#parent;\n }\n\n get owner(): ContextKeyOwner {\n return this.#owner;\n }\n\n get depth(): number {\n return this.#depth;\n }\n\n get disposed(): boolean {\n return this.#disposed;\n }\n\n createKey<T extends ContextValue>(\n name: string,\n defaultValue: T,\n options: IContextKeyOptions = {},\n ): IContextKey<ContextValueType<T>> {\n this.#assertMutable();\n if (!KEY_NAME.test(name)) {\n throw new ContextRegistrationError(\n `Invalid context key name \"${name}\"; expected dotted segments such as \"workbench.selection.kind\".`,\n 'invalid-key',\n name,\n );\n }\n const kind = typeof defaultValue;\n if (kind !== 'string' && kind !== 'number' && kind !== 'boolean') {\n throw new ContextRegistrationError(\n `Context key \"${name}\" needs a string, number or boolean default.`,\n 'invalid-key',\n name,\n );\n }\n if (this.#registrations.has(name)) {\n throw new ContextRegistrationError(\n `Context key \"${name}\" is already registered in this scope.`,\n 'duplicate-key',\n name,\n );\n }\n const owner = options.owner ?? this.#owner;\n const reserved = this.#reservedPrefixes.some((prefix) => name.startsWith(prefix));\n if (reserved && (this.#owner !== 'workbench' || owner !== 'workbench')) {\n throw new ContextRegistrationError(\n `Context key \"${name}\" uses a reserved prefix; only a workbench-owned key in a workbench scope may register it.`,\n 'reserved-prefix',\n name,\n );\n }\n const key = new ContextKey(name, defaultValue as unknown as ContextValueType<T>, owner, this);\n this.#registrations.set(name, key);\n return key;\n }\n\n getValue(name: string): ContextValue | undefined {\n return this.#resolve(name);\n }\n\n createScope(options: IContextScopeOptions = {}): IContextScope {\n this.#assertMutable();\n const owner = options.owner ?? 'host';\n if (owner === 'workbench' && this.#owner !== 'workbench') {\n throw new ContextRegistrationError(\n 'Only a workbench-owned scope can create a workbench scope.',\n 'owner-escalation',\n undefined,\n );\n }\n return new ContextScope({\n parent: this,\n owner,\n ...(options.reservedPrefixes === undefined\n ? {}\n : { reservedPrefixes: options.reservedPrefixes }),\n });\n }\n\n batch(run: () => void): void {\n this.#assertMutable();\n this.#batch.enter();\n try {\n run();\n } finally {\n this.#batch.exit();\n }\n }\n\n compile(expression: string): ICondition {\n return parseCondition(expression);\n }\n\n evaluate(expression: ICondition | string): boolean {\n const condition = typeof expression === 'string' ? parseCondition(expression) : expression;\n return condition.evaluate((name) => this.#resolve(name));\n }\n\n dispose(): void {\n if (this.#disposed) return;\n this.#batch.enter();\n try {\n for (const key of [...this.#registrations.values()]) {\n const previous = this.effectiveValue(key);\n this.#registrations.delete(key.name);\n key.markDisposed();\n this.#batch.add(this, key, previous);\n }\n } finally {\n this.#batch.exit();\n }\n this.#disposed = true;\n this.#batch.defer(() => {\n this.#parentSubscription?.dispose();\n this.#changes.dispose();\n });\n }\n\n /** @internal Stored by the batch flush and by key assignment. */\n assignValue(key: IStoredKey, value: ContextValue | undefined): void {\n this.#assertMutable();\n if (this.#registrations.get(key.name) !== key) return;\n const previous = this.effectiveValue(key);\n key.assign(value);\n this.#batch.add(this, key, previous);\n }\n\n /** @internal Called by `dispose` of a key; the scope reports the fallback value. */\n removeKey(key: IStoredKey): void {\n if (this.#disposed) return;\n if (this.#registrations.get(key.name) !== key) return;\n const previous = this.effectiveValue(key);\n this.#registrations.delete(key.name);\n this.#batch.add(this, key, previous);\n }\n\n /** @internal Effective value including the key default when no scope registered it. */\n effectiveValue(key: IStoredKey): ContextValue {\n return this.#resolve(key.name) ?? key.defaultValue;\n }\n\n /** @internal Fires one merged event for this scope; children propagate from it. */\n notifyChanges(changes: readonly IContextChange[]): void {\n this.#changes.fire({\n scope: this,\n changes,\n names: changes.map((change) => change.name),\n });\n }\n\n /** A child tracks a parent change while it owns no local value and has no pending change. */\n #tracks(name: string): boolean {\n return (\n this.#registrations.get(name)?.value === undefined && !this.#batch.hasPending(this, name)\n );\n }\n\n /**\n * Nearest local value, else the default of the nearest scope that registered the name, else\n * `undefined` for names no scope knows.\n */\n #resolve(name: string): ContextValue | undefined {\n const value = this.#valueInChain(name);\n if (value !== undefined) return value;\n const key = this.#registrations.get(name);\n if (key !== undefined) return key.defaultValue;\n return this.#parent === undefined ? undefined : this.#parent.#resolve(name);\n }\n\n #valueInChain(name: string): ContextValue | undefined {\n const value = this.#registrations.get(name)?.value;\n if (value !== undefined) return value;\n return this.#parent === undefined ? undefined : this.#parent.#valueInChain(name);\n }\n\n #assertMutable(): void {\n if (this.#disposed) throw new Error('Context scope is disposed.');\n }\n}\n","/**\n * Verified device packages of the fused workbench (RFC 0020 / RFC 0022).\n *\n * Editing needs more than the raw registry: before a device may be placed, its locked release has\n * to prove its identity and file digests, its `view2d.geometry` (inline or a declared file) has to\n * parse against the manifest pins, and the referenced body image has to exist in the release file\n * list. This cache performs exactly that and hands the renderer the verified manifest, the parsed\n * geometry and the verified file table, so no view script and no package bytes are ever guessed.\n */\nimport type { IDisposable } from '@mica-js/core/lifecycle';\nimport { parseGeometry2D } from '@mica-js/document/fused';\nimport type {\n DeviceLock,\n FusedDocument,\n Geometry2D,\n PackageFiles,\n UnifiedDeviceManifest,\n} from '@mica-js/document/fused';\nimport { openDevicePackage, PreparationError } from '@mica-js/sdk/fused';\nimport type { VerifiedPackage } from '@mica-js/sdk/fused';\nimport type { IDeviceProvider } from './providers';\n\n/** Upper bound for a declared geometry file; a release entry above it is treated as hostile. */\nconst MAX_GEOMETRY_BYTES = 4 * 1024 * 1024;\n\n/** One locked device release, verified and ready to be placed and drawn. */\nexport interface IPreparedDevice {\n readonly lock: DeviceLock;\n readonly manifest: UnifiedDeviceManifest;\n readonly geometry: Geometry2D;\n /** Verified release file table and reader; body images and other assets are read from here. */\n readonly files: PackageFiles;\n}\n\nexport interface IDeviceCache extends IDisposable {\n /** Opens, verifies and caches one locked release; concurrent calls share one read. */\n get(lock: DeviceLock): Promise<IPreparedDevice>;\n /** Prepared release of a device id that was opened before, keyed by the full device id. */\n getLoaded(id: string): IPreparedDevice | undefined;\n /**\n * Every prepared device keyed by the full device id.\n *\n * The map identity survives edits and only changes when a release is opened, so a renderer can\n * iterate it and keep per-device caches.\n */\n getLoadedDevices(): ReadonlyMap<string, IPreparedDevice>;\n /** @throws when the device id has not been prepared yet. */\n requireLoaded(id: string): IPreparedDevice;\n /** Prepares every device an instance references; unlocked devices are rejected. */\n prepareDocument(document: FusedDocument): Promise<ReadonlyMap<string, IPreparedDevice>>;\n}\n\n/**\n * Verified package cache shared by the document session and the canvas renderer.\n *\n * Failures are not cached: a release that cannot be verified is reported to the caller and may be\n * opened again once the registry can serve it.\n */\nexport class DeviceCache implements IDeviceCache {\n readonly #registry: IDeviceProvider;\n readonly #loaded = new Map<string, IPreparedDevice>();\n readonly #byId = new Map<string, IPreparedDevice>();\n readonly #pending = new Map<string, Promise<IPreparedDevice>>();\n #snapshot: ReadonlyMap<string, IPreparedDevice> = new Map();\n #snapshotStale = false;\n #disposed = false;\n\n constructor(registry: IDeviceProvider) {\n this.#registry = registry;\n }\n\n get(lock: DeviceLock): Promise<IPreparedDevice> {\n this.#assertActive();\n const key = lockKey(lock);\n const loaded = this.#loaded.get(key);\n if (loaded !== undefined) {\n return Promise.resolve(loaded);\n }\n const pending = this.#pending.get(key);\n if (pending !== undefined) {\n return pending;\n }\n const request = this.#open(lock).finally(() => {\n this.#pending.delete(key);\n });\n this.#pending.set(key, request);\n return request;\n }\n\n getLoaded(id: string): IPreparedDevice | undefined {\n return this.#byId.get(id);\n }\n\n getLoadedDevices(): ReadonlyMap<string, IPreparedDevice> {\n if (this.#snapshotStale) {\n this.#snapshot = new Map(this.#byId);\n this.#snapshotStale = false;\n }\n return this.#snapshot;\n }\n\n requireLoaded(id: string): IPreparedDevice {\n const device = this.#byId.get(id);\n if (device === undefined) {\n throw new Error(`Device ${JSON.stringify(id)} has not been prepared.`);\n }\n return device;\n }\n\n async prepareDocument(document: FusedDocument): Promise<ReadonlyMap<string, IPreparedDevice>> {\n this.#assertActive();\n const prepared = new Map<string, IPreparedDevice>();\n await Promise.all(\n [...new Set(document.instances.map((instance) => instance.device))].map(async (deviceId) => {\n const dependency = document.dependencies[deviceId];\n if (dependency === undefined) {\n throw new PreparationError([\n problem(\n 'document/unlocked-device',\n `Instance device \"${deviceId}\" is not locked by \"dependencies\".`,\n ),\n ]);\n }\n const device = await this.get({\n id: deviceId,\n version: dependency.version,\n integrity: dependency.integrity,\n });\n prepared.set(deviceId, device);\n }),\n );\n return prepared;\n }\n\n /** Drops every cached release; late opens finish but do not repopulate the cache. */\n dispose(): void {\n this.#disposed = true;\n this.#loaded.clear();\n this.#byId.clear();\n this.#pending.clear();\n this.#snapshot = new Map();\n this.#snapshotStale = false;\n }\n\n async #open(lock: DeviceLock): Promise<IPreparedDevice> {\n const verified = await openDevicePackage(this.#registry, lock);\n const geometry = await readGeometry(verified);\n this.#assertActive();\n const device: IPreparedDevice = Object.freeze({\n lock: verified.lock,\n manifest: verified.manifest,\n geometry,\n files: verified.source,\n });\n this.#loaded.set(lockKey(verified.lock), device);\n this.#byId.set(verified.lock.id, device);\n this.#snapshotStale = true;\n return device;\n }\n\n #assertActive(): void {\n if (this.#disposed) {\n throw new Error('Device cache is disposed.');\n }\n }\n}\n\nfunction lockKey(lock: DeviceLock): string {\n return `${lock.id}@${lock.version}#${lock.integrity}`;\n}\n\nasync function readGeometry(verified: VerifiedPackage): Promise<Geometry2D> {\n const id = verified.lock.id;\n const declared = verified.manifest.view2d?.geometry;\n if (declared === undefined) {\n throw new PreparationError([\n problem(\n 'view2d/invalid-geometry',\n `${id} declares no \"view2d.geometry\", so it cannot be placed on the schematic.`,\n '/view2d',\n ),\n ]);\n }\n const pins = Object.keys(verified.manifest.pins ?? {});\n let geometry: Geometry2D;\n if (typeof declared === 'string') {\n const bytes = await verified.read(declared, MAX_GEOMETRY_BYTES);\n let text: string;\n try {\n text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch {\n throw new PreparationError([\n problem(\n 'view2d/invalid-geometry',\n `${id}/${declared} is not valid UTF-8 text.`,\n '/view2d/geometry',\n ),\n ]);\n }\n geometry = parseGeometry2D(text, pins);\n } else {\n geometry = parseGeometry2D(declared, pins);\n }\n if (geometry.bodyImage !== undefined && !Object.hasOwn(verified.files, geometry.bodyImage)) {\n throw new PreparationError([\n problem(\n 'package/missing-entry',\n `${id} declares the body image ${geometry.bodyImage}, which the release does not list.`,\n '/view2d/geometry/bodyImage',\n ),\n ]);\n }\n return geometry;\n}\n\nfunction problem(\n code: string,\n message: string,\n pointer = '',\n): {\n readonly code: string;\n readonly message: string;\n readonly pointer: string;\n} {\n return { code, message, pointer };\n}\n","/**\n * Errors of the fused workbench document session.\n *\n * Every rejection carries a stable `code`; contract violations of `@mica-js/document/fused` and\n * package preparation problems keep their own code and JSON Pointer in `problems`, so the host can\n * report them without re-parsing anything.\n */\nimport { FusedDocumentError } from '@mica-js/document/fused';\nimport { PreparationError } from '@mica-js/sdk/fused';\nimport type { AccessDecision } from '../providers';\n\n/** One problem behind a rejected document operation. */\nexport interface IFusedSessionProblem {\n readonly code: string;\n readonly message: string;\n /** JSON Pointer of the offending member; absent when the problem has no document location. */\n readonly pointer?: string;\n}\n\nexport interface IFusedSessionErrorOptions {\n readonly problems?: readonly IFusedSessionProblem[];\n /** The access decision that denied the operation. */\n readonly decision?: AccessDecision;\n readonly cause?: unknown;\n}\n\n/** Rejection of one document session operation. */\nexport class FusedSessionError extends Error {\n readonly code: string;\n readonly problems: readonly IFusedSessionProblem[];\n readonly decision: AccessDecision | undefined;\n\n constructor(code: string, message: string, options: IFusedSessionErrorOptions = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = 'FusedSessionError';\n this.code = code;\n this.problems = options.problems ?? [];\n this.decision = options.decision;\n }\n}\n\n/** Rejection of one operation by the access policy, carrying the decision that denied it. */\nexport function accessDenied(\n code: string,\n decision: Extract<AccessDecision, { readonly allowed: false }>,\n): FusedSessionError {\n return new FusedSessionError(code, decision.message, { decision });\n}\n\n/** Normalizes any rejection into the session's error type, keeping contract diagnostics. */\nexport function toSessionError(\n cause: unknown,\n fallbackCode = 'edit/invalid-document',\n): FusedSessionError {\n if (cause instanceof FusedSessionError) {\n return cause;\n }\n if (cause instanceof FusedDocumentError) {\n const problems = cause.diagnostics.map((entry) => ({\n code: entry.code,\n message: entry.message,\n ...(entry.pointer === '' ? {} : { pointer: entry.pointer }),\n }));\n return new FusedSessionError('edit/invalid-document', cause.message, {\n problems,\n cause,\n });\n }\n if (cause instanceof PreparationError) {\n return new FusedSessionError('device/unavailable', cause.message, {\n problems: cause.problems,\n cause,\n });\n }\n const message = cause instanceof Error ? cause.message : String(cause);\n return new FusedSessionError(fallbackCode, message, { cause });\n}\n","/**\n * Pure document edits of the fused workbench (RFC 0024).\n *\n * Every function takes the current immutable document and returns the next one; nothing here\n * verifies packages or notifies listeners. `FusedDocumentSession` gates permission, verifies the\n * result and commits one transaction, so these functions stay testable on their own.\n */\nimport type {\n ConnectionNode,\n ConnectionWire,\n DeviceDependency,\n Endpoint,\n FusedDocument,\n FusedInstance,\n InstanceViewLayout,\n NetLabel,\n Placement2D,\n Point2D,\n PropertyValue,\n VoltageReference,\n} from '@mica-js/document/fused';\nimport type { IPreparedDevice } from '../devices';\nimport { FusedSessionError } from './errors';\n\n/** Element reference the canvas selects and edits. */\nexport interface IFusedDocumentTarget {\n readonly kind: 'instance' | 'wire' | 'node' | 'label' | 'reference';\n readonly id: string;\n}\n\nexport interface IFusedTextTarget {\n readonly kind: 'designator' | 'label' | 'reference';\n readonly id: string;\n}\n\n/** Changes only the position of the selected text, preserving its owning electrical object. */\nexport function setTextOffset(\n document: FusedDocument,\n target: IFusedTextTarget,\n offset: Point2D,\n): FusedDocument {\n const point = { x: requireFinite(offset.x, 'offset.x'), y: requireFinite(offset.y, 'offset.y') };\n if (target.kind === 'designator')\n return mapInstances(document, [target.id], (instance) => ({\n ...instance,\n designatorOffset: point,\n }));\n if (target.kind === 'label') {\n if (!document.labels.some((value) => value.id === target.id))\n throw new FusedSessionError('edit/invalid-request', `Unknown label: ${target.id}`);\n return {\n ...document,\n labels: document.labels.map((value) =>\n value.id === target.id ? { ...value, offset: point } : value,\n ),\n };\n }\n const reference = document.references.find((value) => value.id === target.id);\n const label = reference?.label;\n if (reference === undefined || label === undefined)\n throw new FusedSessionError(\n 'edit/invalid-request',\n `Reference has no movable net label: ${target.id}`,\n );\n return {\n ...document,\n references: document.references.map((value) =>\n value === reference ? { ...value, label: { ...label, offset: point } } : value,\n ),\n };\n}\n\n/** Allocates one element id; the session defaults to `crypto.randomUUID`. */\nexport type IdFactory = () => string;\n\nexport interface IAddInstanceResult {\n readonly document: FusedDocument;\n readonly instanceId: string;\n}\n\nexport interface IFusedLabelOptions {\n readonly offset?: Point2D;\n}\n\nexport interface IFusedReferenceOptions {\n /** Clockwise rotation in degrees around the anchor; defaults to `0`. */\n readonly rotation?: number;\n /** Net name owned by the symbol together with its display offset. */\n readonly label?: { readonly name: string; readonly offset?: Point2D };\n}\n\n/**\n * Adds one placed instance and locks the release it needs.\n *\n * Physical devices drop `width`/`height` (the package geometry sizes them); flexible devices\n * require both as finite positive numbers.\n *\n * @throws {FusedSessionError} when the placement is unusable or the device id is locked to another\n * release; the dependency table is never rewritten for a new version.\n */\nexport function addInstance(\n document: FusedDocument,\n device: IPreparedDevice,\n placement: Placement2D,\n createId: IdFactory,\n): IAddInstanceResult {\n const dependencies = withDependency(document.dependencies, device.lock);\n const normalized = normalizePlacement(placement, device.geometry.sizing);\n const designator = allocateDesignator(\n device.manifest.designatorPrefix ?? 'U',\n usedDesignators(document),\n );\n const instanceId = takeFreshId(takenIds(document), createId);\n const instance: FusedInstance = {\n id: instanceId,\n device: device.lock.id,\n designator,\n placement: normalized,\n };\n return {\n document: { ...document, dependencies, instances: [...document.instances, instance] },\n instanceId,\n };\n}\n\n/**\n * Removes instances, wires, nodes, labels and references as one change.\n *\n * Removing an instance also removes its labels, references and attached wires; removing a node\n * removes what hangs on it; removing a reference drops its node anchor once nothing else uses it.\n */\nexport function removeTargets(\n document: FusedDocument,\n targets: readonly IFusedDocumentTarget[],\n): FusedDocument {\n const instances = new Map(document.instances.map((instance) => [instance.id, instance]));\n const nodes = new Map(document.nodes.map((node) => [node.id, node]));\n const wires = new Map(document.wires.map((wire) => [wire.id, wire]));\n const labels = new Map(document.labels.map((label) => [label.id, label]));\n const references = new Map(document.references.map((reference) => [reference.id, reference]));\n\n const removedInstances = new Set<string>();\n const removedNodes = new Set<string>();\n const removedWires = new Set<string>();\n const removedLabels = new Set<string>();\n const removedReferences = new Set<string>();\n const prunedAnchors = new Set<string>();\n\n for (const target of targets) {\n switch (target.kind) {\n case 'instance':\n removedInstances.add(requireEntry(instances, target).id);\n break;\n case 'node':\n removedNodes.add(requireEntry(nodes, target).id);\n break;\n case 'wire':\n removedWires.add(requireEntry(wires, target).id);\n break;\n case 'label':\n removedLabels.add(requireEntry(labels, target).id);\n break;\n case 'reference': {\n const reference = requireEntry(references, target);\n removedReferences.add(reference.id);\n if (reference.target.kind === 'node') {\n prunedAnchors.add(reference.target.node);\n }\n break;\n }\n default:\n throw new FusedSessionError(\n 'edit/invalid-request',\n `Unknown target kind ${JSON.stringify((target as { kind?: unknown }).kind)}.`,\n );\n }\n }\n\n const endpointRemoved = (endpoint: Endpoint): boolean =>\n endpoint.kind === 'pin'\n ? removedInstances.has(endpoint.instance)\n : removedNodes.has(endpoint.node);\n\n for (const wire of document.wires) {\n if (endpointRemoved(wire.from) || endpointRemoved(wire.to)) {\n removedWires.add(wire.id);\n }\n }\n for (const label of document.labels) {\n if (endpointRemoved(label.target)) {\n removedLabels.add(label.id);\n }\n }\n for (const reference of document.references) {\n if (endpointRemoved(reference.target)) {\n removedReferences.add(reference.id);\n }\n }\n\n if (\n removedInstances.size === 0 &&\n removedNodes.size === 0 &&\n removedWires.size === 0 &&\n removedLabels.size === 0 &&\n removedReferences.size === 0\n ) {\n return document;\n }\n\n const keptWires = document.wires.filter((wire) => !removedWires.has(wire.id));\n const keptLabels = document.labels.filter((label) => !removedLabels.has(label.id));\n const keptReferences = document.references.filter(\n (reference) => !removedReferences.has(reference.id),\n );\n\n // RFC 0024: deleting a symbol drops its anchor node once no wire, label or other reference uses it.\n for (const nodeId of prunedAnchors) {\n if (removedNodes.has(nodeId)) {\n continue;\n }\n const used =\n keptWires.some((wire) => touchesNode(wire, nodeId)) ||\n keptLabels.some((label) => label.target.kind === 'node' && label.target.node === nodeId) ||\n keptReferences.some(\n (reference) => reference.target.kind === 'node' && reference.target.node === nodeId,\n );\n if (!used) {\n removedNodes.add(nodeId);\n }\n }\n\n return {\n ...document,\n instances: document.instances.filter((instance) => !removedInstances.has(instance.id)),\n nodes: document.nodes.filter((node) => !removedNodes.has(node.id)),\n wires: keptWires,\n labels: keptLabels,\n references: keptReferences,\n };\n}\n\n/** Offsets instances by a scene-space delta; connections and rotation stay untouched. */\nexport function moveInstances(\n document: FusedDocument,\n instanceIds: readonly string[],\n delta: Point2D,\n): FusedDocument {\n const dx = requireFinite(delta?.x, 'delta.x');\n const dy = requireFinite(delta?.y, 'delta.y');\n return mapInstances(document, instanceIds, (instance) => ({\n ...instance,\n placement: {\n ...instance.placement,\n x: instance.placement.x + dx,\n y: instance.placement.y + dy,\n },\n }));\n}\n\n/** Moves one instance so its origin lands on `position`. */\nexport function setInstancePosition(\n document: FusedDocument,\n instanceId: string,\n position: Point2D,\n): FusedDocument {\n const x = requireFinite(position?.x, 'position.x');\n const y = requireFinite(position?.y, 'position.y');\n return mapInstances(document, [instanceId], (instance) => ({\n ...instance,\n placement: { ...instance.placement, x, y },\n }));\n}\n\n/** Rotates instances clockwise by `degrees`, normalized to `[0, 360)`. */\nexport function rotateInstances(\n document: FusedDocument,\n instanceIds: readonly string[],\n degrees: number,\n): FusedDocument {\n const delta = requireFinite(degrees, 'degrees');\n return mapInstances(document, instanceIds, (instance) => ({\n ...instance,\n placement: {\n ...instance.placement,\n rotation: normalizeDegrees(instance.placement.rotation + delta),\n },\n }));\n}\n\n/** Rotates selected devices and reference symbols around their own electrical anchors. */\nexport function rotateTargets(\n document: FusedDocument,\n targets: readonly IFusedDocumentTarget[],\n degrees: number,\n): FusedDocument {\n const delta = requireFinite(degrees, 'degrees');\n const rotated = rotateInstances(\n document,\n targets.filter((value) => value.kind === 'instance').map((value) => value.id),\n delta,\n );\n const ids = new Set(\n targets.filter((value) => value.kind === 'reference').map((value) => value.id),\n );\n for (const id of ids) {\n if (!document.references.some((value) => value.id === id))\n throw new FusedSessionError('edit/invalid-request', `Unknown reference: ${id}`);\n }\n if (ids.size === 0) return rotated;\n return {\n ...rotated,\n references: rotated.references.map((value) =>\n ids.has(value.id)\n ? { ...value, rotation: normalizeDegrees((value.rotation ?? 0) + delta) }\n : value,\n ),\n };\n}\n\n/**\n * Renames one instance designator.\n *\n * A saved designator must be a non-empty string that no other instance uses; the value is validated\n * before the commit, so the document never carries a duplicate.\n *\n * @throws {FusedSessionError} (`edit/duplicate-designator`) when another instance owns the name.\n */\nexport function renameDesignator(\n document: FusedDocument,\n instanceId: string,\n designator: string,\n): FusedDocument {\n if (typeof designator !== 'string' || designator.length === 0) {\n throw new FusedSessionError('edit/invalid-request', 'A designator must be a non-empty string.');\n }\n const instance = requireInstance(document, instanceId);\n if (instance.designator === designator) {\n return document;\n }\n const clash = document.instances.some(\n (entry) => entry.id !== instanceId && entry.designator === designator,\n );\n if (clash) {\n throw new FusedSessionError(\n 'edit/duplicate-designator',\n `Designator \"${designator}\" is already used by another instance.`,\n );\n }\n return replaceInstance(document, { ...instance, designator });\n}\n\n/** Stores one property override; `null` is a valid value when the device declares it nullable. */\nexport function setInstanceProperty(\n document: FusedDocument,\n instanceId: string,\n key: string,\n value: PropertyValue,\n): FusedDocument {\n if (typeof key !== 'string' || key.length === 0) {\n throw new FusedSessionError(\n 'edit/invalid-request',\n 'A property key must be a non-empty string.',\n );\n }\n const instance = requireInstance(document, instanceId);\n return replaceInstance(document, {\n ...instance,\n properties: { ...(instance.properties ?? {}), [key]: value },\n });\n}\n\n/** Drops one property override; an unknown key is a no-op. */\nexport function removeInstanceProperty(\n document: FusedDocument,\n instanceId: string,\n key: string,\n): FusedDocument {\n const instance = requireInstance(document, instanceId);\n const properties = instance.properties;\n if (properties === undefined || !Object.hasOwn(properties, key)) {\n return document;\n }\n const next: Record<string, PropertyValue> = {};\n for (const [name, value] of Object.entries(properties)) {\n if (name !== key) {\n next[name] = value;\n }\n }\n return replaceInstance(\n document,\n Object.keys(next).length === 0\n ? omitKeys(instance, 'properties')\n : { ...instance, properties: next },\n );\n}\n\n/** Adds a free or junction node at `point`. */\nexport function addNode(\n document: FusedDocument,\n point: Point2D,\n kind: ConnectionNode['kind'],\n createId: IdFactory,\n): { readonly document: FusedDocument; readonly nodeId: string } {\n const x = requireFinite(point?.x, 'point.x');\n const y = requireFinite(point?.y, 'point.y');\n if (kind !== 'junction' && kind !== 'free') {\n throw new FusedSessionError(\n 'edit/invalid-request',\n 'A node kind must be \"junction\" or \"free\".',\n );\n }\n const nodeId = takeFreshId(takenIds(document), createId);\n const node: ConnectionNode = { id: nodeId, kind, x, y };\n return { document: { ...document, nodes: [...document.nodes, node] }, nodeId };\n}\n\n/** Adds one wire between two existing endpoints; `bends` are the intermediate points only. */\nexport function addWire(\n document: FusedDocument,\n from: Endpoint,\n to: Endpoint,\n bends: readonly Point2D[],\n createId: IdFactory,\n): { readonly document: FusedDocument; readonly wireId: string } {\n requireEndpoint(document, from, 'from');\n requireEndpoint(document, to, 'to');\n if (sameEndpoint(from, to)) {\n throw new FusedSessionError(\n 'edit/invalid-request',\n 'A wire must connect two different endpoints.',\n );\n }\n const points = (bends ?? []).map((bend, index) => ({\n x: requireFinite(bend?.x, `bends[${String(index)}].x`),\n y: requireFinite(bend?.y, `bends[${String(index)}].y`),\n }));\n const wireId = takeFreshId(takenIds(document), createId);\n const wire: ConnectionWire = { id: wireId, from, to, bends: points };\n return { document: { ...document, wires: [...document.wires, wire] }, wireId };\n}\n\n/** Declares a net name on one endpoint. */\nexport function addLabel(\n document: FusedDocument,\n target: Endpoint,\n name: string,\n options: IFusedLabelOptions = {},\n createId: IdFactory,\n): { readonly document: FusedDocument; readonly labelId: string } {\n requireEndpoint(document, target, 'target');\n if (typeof name !== 'string' || name.length === 0) {\n throw new FusedSessionError('edit/invalid-request', 'A net name must be a non-empty string.');\n }\n const offset = readOffset(options.offset, 'options.offset');\n const labelId = takeFreshId(takenIds(document), createId);\n const label: NetLabel = {\n id: labelId,\n target,\n name,\n ...(offset === undefined ? {} : { offset }),\n };\n return { document: { ...document, labels: [...document.labels, label] }, labelId };\n}\n\n/** Attaches an ideal voltage reference, optionally with the built-in power or ground symbol. */\nexport function addReference(\n document: FusedDocument,\n target: Endpoint,\n voltage: number,\n symbol: VoltageReference['symbol'],\n options: IFusedReferenceOptions = {},\n createId: IdFactory,\n): { readonly document: FusedDocument; readonly referenceId: string } {\n requireEndpoint(document, target, 'target');\n const value = requireFinite(voltage, 'voltage');\n if (symbol !== undefined && symbol !== 'power' && symbol !== 'ground') {\n throw new FusedSessionError(\n 'edit/invalid-request',\n 'A reference symbol must be \"power\", \"ground\" or omitted.',\n );\n }\n if (symbol === 'ground' && value !== 0) {\n throw new FusedSessionError(\n 'edit/invalid-request',\n 'The ground symbol requires a reference voltage of 0.',\n );\n }\n const rotation =\n options.rotation === undefined\n ? undefined\n : requireFinite(options.rotation, 'options.rotation');\n const label = readReferenceLabel(options.label);\n const referenceId = takeFreshId(takenIds(document), createId);\n const reference: VoltageReference = {\n id: referenceId,\n target,\n voltage: value,\n ...(symbol === undefined ? {} : { symbol }),\n ...(rotation === undefined || rotation === 0 ? {} : { rotation }),\n ...(label === undefined ? {} : { label }),\n };\n return {\n document: { ...document, references: [...document.references, reference] },\n referenceId,\n };\n}\n\n/** Stores the per-instance sidebar and HTML view layout; `undefined` restores the defaults. */\nexport function setViewLayout(\n document: FusedDocument,\n instanceId: string,\n layout: InstanceViewLayout | undefined,\n): FusedDocument {\n const instance = requireInstance(document, instanceId);\n return replaceInstance(\n document,\n layout === undefined ? omitViewLayout(instance) : { ...instance, viewLayout: layout },\n );\n}\n\n/** Finds one instance. */\nexport function findInstance(\n document: FusedDocument,\n instanceId: string,\n): FusedInstance | undefined {\n return document.instances.find((instance) => instance.id === instanceId);\n}\n\n/** Locks `lock` in the dependency table, refusing to replace a different release. */\nexport function withDependency(\n dependencies: Readonly<Record<string, DeviceDependency>>,\n lock: { readonly id: string; readonly version: string; readonly integrity: string },\n): Readonly<Record<string, DeviceDependency>> {\n const existing = dependencies[lock.id];\n if (existing !== undefined) {\n if (existing.version !== lock.version || existing.integrity !== lock.integrity) {\n throw new FusedSessionError(\n 'document/locked-conflict',\n `\"${lock.id}\" is already locked to ${existing.version}; replace the dependency explicitly instead of overwriting it.`,\n );\n }\n return dependencies;\n }\n return { ...dependencies, [lock.id]: { version: lock.version, integrity: lock.integrity } };\n}\n\n/** Smallest unused `<prefix><n>` designator, starting at 1 (RFC 0024). */\nexport function allocateDesignator(prefix: string, used: ReadonlySet<string>): string {\n for (let index = 1; ; index += 1) {\n const candidate = `${prefix}${String(index)}`;\n if (!used.has(candidate)) {\n return candidate;\n }\n }\n}\n\nexport function usedDesignators(document: FusedDocument): Set<string> {\n const used = new Set<string>();\n for (const instance of document.instances) {\n if (instance.designator !== undefined) {\n used.add(instance.designator);\n }\n }\n return used;\n}\n\n/** Every element id the document already uses; new ids must not collide with any of them. */\nexport function takenIds(document: FusedDocument): Set<string> {\n return new Set<string>([\n ...document.instances.map((entry) => entry.id),\n ...document.nodes.map((entry) => entry.id),\n ...document.wires.map((entry) => entry.id),\n ...document.labels.map((entry) => entry.id),\n ...document.references.map((entry) => entry.id),\n ]);\n}\n\n/** Allocates an id that `taken` does not contain and records it. */\nexport function takeFreshId(taken: Set<string>, createId: IdFactory): string {\n for (let attempt = 0; attempt < 128; attempt += 1) {\n const id = createId();\n if (!taken.has(id)) {\n taken.add(id);\n return id;\n }\n }\n throw new FusedSessionError('edit/invalid-request', 'Could not allocate a unique element id.');\n}\n\n/** Validates that an endpoint names an object of this document. */\nexport function requireEndpoint(document: FusedDocument, endpoint: Endpoint, label: string): void {\n if (endpoint === null || typeof endpoint !== 'object') {\n throw new FusedSessionError(\n 'edit/invalid-request',\n `\"${label}\" must be a pin or node endpoint.`,\n );\n }\n if (endpoint.kind === 'pin') {\n if (\n typeof endpoint.instance !== 'string' ||\n !document.instances.some((instance) => instance.id === endpoint.instance)\n ) {\n throw new FusedSessionError(\n 'edit/unknown-target',\n `\"${label}\" references the unknown instance ${JSON.stringify(endpoint.instance)}.`,\n );\n }\n if (typeof endpoint.pin !== 'string' || endpoint.pin.length === 0) {\n throw new FusedSessionError('edit/invalid-request', `\"${label}\" needs a pin id.`);\n }\n return;\n }\n if (endpoint.kind === 'node') {\n if (\n typeof endpoint.node !== 'string' ||\n !document.nodes.some((node) => node.id === endpoint.node)\n ) {\n throw new FusedSessionError(\n 'edit/unknown-target',\n `\"${label}\" references the unknown node ${JSON.stringify(endpoint.node)}.`,\n );\n }\n return;\n }\n throw new FusedSessionError('edit/invalid-request', `\"${label}\" has an unknown endpoint kind.`);\n}\n\nfunction normalizePlacement(placement: Placement2D, sizing: 'physical' | 'flexible'): Placement2D {\n if (placement === null || typeof placement !== 'object') {\n throw new FusedSessionError('edit/invalid-request', 'A placement object is required.');\n }\n const x = requireFinite(placement.x, 'placement.x');\n const y = requireFinite(placement.y, 'placement.y');\n const rotation = requireFinite(placement.rotation ?? 0, 'placement.rotation');\n if (sizing === 'physical') {\n return { x, y, rotation };\n }\n return {\n x,\n y,\n rotation,\n width: requirePositive(placement.width, 'placement.width'),\n height: requirePositive(placement.height, 'placement.height'),\n };\n}\n\nfunction mapInstances(\n document: FusedDocument,\n instanceIds: readonly string[],\n update: (instance: FusedInstance) => FusedInstance,\n): FusedDocument {\n const ids = new Set(instanceIds);\n for (const id of ids) {\n requireInstance(document, id);\n }\n if (ids.size === 0) {\n return document;\n }\n return {\n ...document,\n instances: document.instances.map((instance) =>\n ids.has(instance.id) ? update(instance) : instance,\n ),\n };\n}\n\nfunction replaceInstance(document: FusedDocument, instance: FusedInstance): FusedDocument {\n return {\n ...document,\n instances: document.instances.map((entry) => (entry.id === instance.id ? instance : entry)),\n };\n}\n\nfunction requireInstance(document: FusedDocument, instanceId: string): FusedInstance {\n const instance = findInstance(document, instanceId);\n if (instance === undefined) {\n throw new FusedSessionError(\n 'edit/unknown-target',\n `Unknown instance ${JSON.stringify(instanceId)}.`,\n );\n }\n return instance;\n}\n\nfunction requireEntry<T extends { readonly id: string }>(\n entries: ReadonlyMap<string, T>,\n target: IFusedDocumentTarget,\n): T {\n const entry = entries.get(target.id);\n if (entry === undefined) {\n throw new FusedSessionError(\n 'edit/unknown-target',\n `Unknown ${target.kind} ${JSON.stringify(target.id)}.`,\n );\n }\n return entry;\n}\n\nfunction touchesNode(wire: ConnectionWire, nodeId: string): boolean {\n return (\n (wire.from.kind === 'node' && wire.from.node === nodeId) ||\n (wire.to.kind === 'node' && wire.to.node === nodeId)\n );\n}\n\nexport function sameEndpoint(a: Endpoint, b: Endpoint): boolean {\n if (a.kind === 'pin' && b.kind === 'pin') {\n return a.instance === b.instance && a.pin === b.pin;\n }\n if (a.kind === 'node' && b.kind === 'node') {\n return a.node === b.node;\n }\n return false;\n}\n\nfunction normalizeDegrees(value: number): number {\n const normalized = value % 360;\n return normalized < 0 ? normalized + 360 : normalized;\n}\n\nfunction readOffset(value: Point2D | undefined, label: string): Point2D | undefined {\n if (value === undefined) {\n return undefined;\n }\n return { x: requireFinite(value.x, `${label}.x`), y: requireFinite(value.y, `${label}.y`) };\n}\n\nfunction readReferenceLabel(\n value: IFusedReferenceOptions['label'],\n): { readonly name: string; readonly offset?: Point2D } | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (typeof value.name !== 'string' || value.name.length === 0) {\n throw new FusedSessionError(\n 'edit/invalid-request',\n 'A reference label needs a non-empty net name.',\n );\n }\n const offset = readOffset(value.offset, 'options.label.offset');\n return { name: value.name, ...(offset === undefined ? {} : { offset }) };\n}\n\nfunction omitViewLayout(instance: FusedInstance): FusedInstance {\n return omitKeys(instance, 'viewLayout');\n}\n\nfunction omitKeys(\n instance: FusedInstance,\n ...keys: readonly (keyof FusedInstance)[]\n): FusedInstance {\n const next: Record<string, unknown> = { ...instance };\n for (const key of keys) {\n delete next[key];\n }\n return next as unknown as FusedInstance;\n}\n\nfunction requireFinite(value: number, label: string): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new FusedSessionError('edit/invalid-request', `\"${label}\" must be a finite number.`);\n }\n return value;\n}\n\nfunction requirePositive(value: number | undefined, label: string): number {\n const number = requireFinite(value as number, label);\n if (number <= 0) {\n throw new FusedSessionError('edit/invalid-request', `\"${label}\" must be a positive number.`);\n }\n return number;\n}\n","/**\n * Clipboard of a fused subgraph (RFC 0024).\n *\n * A copy keeps only what stays inside the selection: instances and nodes that were selected, the\n * wires between them, and the labels and references attached to them. Edges to objects outside the\n * selection are neither copied nor retargeted; a paste allocates new ids and designators and maps\n * every internal reference onto the copy.\n */\nimport type {\n ConnectionNode,\n ConnectionWire,\n DeviceDependency,\n Endpoint,\n FusedDocument,\n FusedInstance,\n NetLabel,\n Point2D,\n VoltageReference,\n} from '@mica-js/document/fused';\nimport type { IPreparedDevice } from '../devices';\nimport { FusedSessionError } from './errors';\nimport type { IFusedDocumentTarget } from './edits';\nimport {\n allocateDesignator,\n takeFreshId,\n takenIds,\n usedDesignators,\n withDependency,\n} from './edits';\nimport type { IdFactory } from './edits';\n\n/** Selected subgraph and the locks its devices need. */\nexport interface IFusedClipboard {\n readonly dependencies: Readonly<Record<string, DeviceDependency>>;\n readonly instances: readonly FusedInstance[];\n readonly nodes: readonly ConnectionNode[];\n readonly wires: readonly ConnectionWire[];\n readonly labels: readonly NetLabel[];\n readonly references: readonly VoltageReference[];\n}\n\n/**\n * Extracts the selected subgraph; a pure read that records no history.\n *\n * Unknown target ids are ignored. Returns `undefined` when the selection holds no instance or node.\n */\nexport function copyTargets(\n document: FusedDocument,\n targets: readonly IFusedDocumentTarget[],\n): IFusedClipboard | undefined {\n const instanceIds = new Set(\n targets.filter((target) => target.kind === 'instance').map((target) => target.id),\n );\n const nodeIds = new Set(\n targets.filter((target) => target.kind === 'node').map((target) => target.id),\n );\n const instances = document.instances.filter((instance) => instanceIds.has(instance.id));\n const nodes = document.nodes.filter((node) => nodeIds.has(node.id));\n if (instances.length === 0 && nodes.length === 0) {\n return undefined;\n }\n const selectedInstances = new Set(instances.map((instance) => instance.id));\n const selectedNodes = new Set(nodes.map((node) => node.id));\n const inside = (endpoint: Endpoint): boolean =>\n endpoint.kind === 'pin'\n ? selectedInstances.has(endpoint.instance)\n : selectedNodes.has(endpoint.node);\n\n const dependencies: Record<string, DeviceDependency> = {};\n for (const instance of instances) {\n const dependency = document.dependencies[instance.device];\n if (dependency !== undefined) {\n dependencies[instance.device] = dependency;\n }\n }\n\n return {\n dependencies,\n instances,\n nodes,\n wires: document.wires.filter((wire) => inside(wire.from) && inside(wire.to)),\n labels: document.labels.filter((label) => inside(label.target)),\n references: document.references.filter((reference) => inside(reference.target)),\n };\n}\n\n/**\n * Inserts a copied subgraph at `offset` with new ids, designators and internal references.\n *\n * @throws {FusedSessionError} when a copied device is not locked by the clipboard, its release\n * conflicts with the document lock, or it has not been prepared.\n */\nexport function pasteClipboard(\n document: FusedDocument,\n clipboard: IFusedClipboard,\n offset: Point2D,\n prepared: ReadonlyMap<string, IPreparedDevice>,\n createId: IdFactory,\n): FusedDocument {\n const dx = requireFinite(offset?.x, 'offset.x');\n const dy = requireFinite(offset?.y, 'offset.y');\n if (clipboard.instances.length === 0) {\n return document;\n }\n\n let dependencies = document.dependencies;\n for (const instance of clipboard.instances) {\n const device = prepared.get(instance.device);\n if (device === undefined) {\n throw new FusedSessionError(\n 'device/unavailable',\n `Cannot paste ${instance.device}: its release has not been prepared.`,\n );\n }\n dependencies = withDependency(dependencies, device.lock);\n }\n\n const taken = takenIds(document);\n const designators = usedDesignators(document);\n const instanceIds = new Map<string, string>();\n const instances = clipboard.instances.map((instance) => {\n const id = takeFreshId(taken, createId);\n instanceIds.set(instance.id, id);\n const prefix = prepared.get(instance.device)?.manifest.designatorPrefix ?? 'U';\n const designator = allocateDesignator(prefix, designators);\n designators.add(designator);\n return {\n ...instance,\n id,\n designator,\n placement: {\n ...instance.placement,\n x: instance.placement.x + dx,\n y: instance.placement.y + dy,\n },\n };\n });\n\n const nodeIds = new Map<string, string>();\n const nodes = clipboard.nodes.map((node) => {\n const id = takeFreshId(taken, createId);\n nodeIds.set(node.id, id);\n return { ...node, id, x: node.x + dx, y: node.y + dy };\n });\n\n const remap = (endpoint: Endpoint): Endpoint | undefined => {\n if (endpoint.kind === 'pin') {\n const instance = instanceIds.get(endpoint.instance);\n return instance === undefined ? undefined : { kind: 'pin', instance, pin: endpoint.pin };\n }\n const node = nodeIds.get(endpoint.node);\n return node === undefined ? undefined : { kind: 'node', node };\n };\n\n const wires: ConnectionWire[] = [];\n for (const wire of clipboard.wires) {\n const from = remap(wire.from);\n const to = remap(wire.to);\n if (from === undefined || to === undefined) {\n continue;\n }\n wires.push({\n id: takeFreshId(taken, createId),\n from,\n to,\n bends: wire.bends.map((bend) => ({ x: bend.x + dx, y: bend.y + dy })),\n });\n }\n\n const labels: NetLabel[] = [];\n for (const label of clipboard.labels) {\n const target = remap(label.target);\n if (target === undefined) {\n continue;\n }\n labels.push({ ...label, id: takeFreshId(taken, createId), target });\n }\n\n const references: VoltageReference[] = [];\n for (const reference of clipboard.references) {\n const target = remap(reference.target);\n if (target === undefined) {\n continue;\n }\n references.push({ ...reference, id: takeFreshId(taken, createId), target });\n }\n\n return {\n ...document,\n dependencies,\n instances: [...document.instances, ...instances],\n nodes: [...document.nodes, ...nodes],\n wires: [...document.wires, ...wires],\n labels: [...document.labels, ...labels],\n references: [...document.references, ...references],\n };\n}\n\nfunction requireFinite(value: number, label: string): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new FusedSessionError('edit/invalid-request', `\"${label}\" must be a finite number.`);\n }\n return value;\n}\n","import type {\n Endpoint,\n FusedDocument,\n FusedInstance,\n Geometry2D,\n NetLabel,\n Point2D,\n Rect2D,\n UnifiedDeviceManifest,\n VoltageReference,\n} from '@mica-js/document/fused';\nimport type { IFusedTextTarget } from '../document/edits';\n\nexport interface ICanvasDevice {\n readonly manifest: UnifiedDeviceManifest;\n readonly geometry: Geometry2D;\n}\n\nexport interface IViewport {\n readonly scale: number;\n readonly x: number;\n readonly y: number;\n}\n\nexport function toScene(point: Point2D, viewport: IViewport): Point2D {\n return { x: (point.x - viewport.x) / viewport.scale, y: (point.y - viewport.y) / viewport.scale };\n}\n\nexport function toScreen(point: Point2D, viewport: IViewport): Point2D {\n return { x: point.x * viewport.scale + viewport.x, y: point.y * viewport.scale + viewport.y };\n}\n\nexport function localToScene(\n instance: FusedInstance,\n geometry: Geometry2D,\n point: Point2D,\n): Point2D {\n const placement = instance.placement;\n const flexible = geometry.sizing === 'flexible';\n const x = flexible\n ? ((point.x - geometry.bounds.x) * (placement.width ?? geometry.bounds.width)) /\n geometry.bounds.width\n : point.x;\n const y = flexible\n ? ((point.y - geometry.bounds.y) * (placement.height ?? geometry.bounds.height)) /\n geometry.bounds.height\n : point.y;\n const angle = (placement.rotation * Math.PI) / 180;\n return {\n x: placement.x + x * Math.cos(angle) - y * Math.sin(angle),\n y: placement.y + x * Math.sin(angle) + y * Math.cos(angle),\n };\n}\n\nexport function sceneToLocal(\n instance: FusedInstance,\n geometry: Geometry2D,\n point: Point2D,\n): Point2D {\n const angle = (-instance.placement.rotation * Math.PI) / 180;\n const dx = point.x - instance.placement.x;\n const dy = point.y - instance.placement.y;\n const x = dx * Math.cos(angle) - dy * Math.sin(angle);\n const y = dx * Math.sin(angle) + dy * Math.cos(angle);\n if (geometry.sizing !== 'flexible') return { x, y };\n return {\n x:\n (x * geometry.bounds.width) / (instance.placement.width ?? geometry.bounds.width) +\n geometry.bounds.x,\n y:\n (y * geometry.bounds.height) / (instance.placement.height ?? geometry.bounds.height) +\n geometry.bounds.y,\n };\n}\n\nexport function contains(rect: Rect2D, point: Point2D): boolean {\n return (\n point.x >= rect.x &&\n point.y >= rect.y &&\n point.x <= rect.x + rect.width &&\n point.y <= rect.y + rect.height\n );\n}\n\nexport function endpointPosition(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n endpoint: Endpoint,\n): Point2D {\n if (endpoint.kind === 'node') {\n const node = document.nodes.find((value) => value.id === endpoint.node);\n if (node === undefined) throw new Error(`Unknown connection node: ${endpoint.node}`);\n return node;\n }\n const instance = document.instances.find((value) => value.id === endpoint.instance);\n const device = instance === undefined ? undefined : devices.get(instance.device);\n const pin = device?.geometry.pins[endpoint.pin];\n if (instance === undefined || device === undefined || pin === undefined)\n throw new Error(`Unknown pin: ${endpoint.instance}/${endpoint.pin}`);\n return localToScene(instance, device.geometry, pin.position);\n}\n\nexport interface IPinHit {\n readonly endpoint: Endpoint;\n readonly point: Point2D;\n readonly title: string;\n}\n\nexport function pickPins(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n point: Point2D,\n tolerance: number,\n): readonly IPinHit[] {\n return document.instances.flatMap((instance) => {\n const device = devices.get(instance.device);\n if (device === undefined) return [];\n return Object.entries(device.geometry.pins).flatMap(([pin, geometry]) => {\n const position = localToScene(instance, device.geometry, geometry.position);\n return Math.hypot(position.x - point.x, position.y - point.y) <= tolerance\n ? [\n {\n endpoint: { kind: 'pin' as const, instance: instance.id, pin },\n point: position,\n title: `${instance.designator ?? instance.id} · ${device.manifest.pins?.[pin]?.label ?? pin}`,\n },\n ]\n : [];\n });\n });\n}\n\nexport function pickInstance(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n point: Point2D,\n visible: (instance: FusedInstance) => boolean = () => true,\n): FusedInstance | undefined {\n return [...document.instances].reverse().find((instance) => {\n const device = devices.get(instance.device);\n return (\n device !== undefined &&\n visible(instance) &&\n contains(device.geometry.bounds, sceneToLocal(instance, device.geometry, point))\n );\n });\n}\n\nexport function labelBounds(label: NetLabel): Rect2D {\n return {\n x: label.offset?.x ?? 0.3,\n y: (label.offset?.y ?? -0.35) - 0.75,\n width: Math.max(0.5, label.name.length * 0.5),\n height: 0.9,\n };\n}\n\nexport function designatorPosition(instance: FusedInstance, geometry: Geometry2D): Point2D {\n const anchor = geometry.designator ?? { x: geometry.bodyBounds.x, y: geometry.bodyBounds.y };\n return localToScene(instance, geometry, {\n x: anchor.x + (instance.designatorOffset?.x ?? 0),\n y: anchor.y + (instance.designatorOffset?.y ?? 0),\n });\n}\n\nexport function referenceTextBounds(reference: VoltageReference): Rect2D {\n const name = reference.label?.name ?? `${reference.voltage} V`;\n return {\n x: reference.label?.offset?.x ?? 0.7,\n y: (reference.label?.offset?.y ?? -1.4) - 0.75,\n width: Math.max(0.5, name.length * 0.5),\n height: 0.9,\n };\n}\n\nfunction referenceToLocal(reference: VoltageReference, delta: Point2D): Point2D {\n const angle = -((reference.rotation ?? 0) * Math.PI) / 180;\n return {\n x: delta.x * Math.cos(angle) - delta.y * Math.sin(angle),\n y: delta.x * Math.sin(angle) + delta.y * Math.cos(angle),\n };\n}\n\nexport function pickText(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n point: Point2D,\n scale: number,\n): IFusedTextTarget | undefined {\n for (const reference of [...document.references].reverse()) {\n if (reference.symbol === 'ground' || reference.label === undefined) continue;\n const anchor = endpointPosition(document, devices, reference.target);\n const local = referenceToLocal(reference, { x: point.x - anchor.x, y: point.y - anchor.y });\n if (containsExpanded(referenceTextBounds(reference), local, 2 / scale))\n return { kind: 'reference', id: reference.id };\n }\n for (const label of [...document.labels].reverse()) {\n const anchor = endpointPosition(document, devices, label.target);\n if (\n containsExpanded(\n labelBounds(label),\n { x: point.x - anchor.x, y: point.y - anchor.y },\n 2 / scale,\n )\n )\n return { kind: 'label', id: label.id };\n }\n for (const instance of [...document.instances].reverse()) {\n const geometry = devices.get(instance.device)?.geometry;\n if (instance.designator === undefined || geometry === undefined) continue;\n const anchor = designatorPosition(instance, geometry);\n if (\n containsExpanded(\n {\n x: anchor.x,\n y: anchor.y - 16 / scale,\n width: (instance.designator.length * 7) / scale,\n height: 13 / scale,\n },\n point,\n 2 / scale,\n )\n )\n return { kind: 'designator', id: instance.id };\n }\n return undefined;\n}\n\n/** Converts a scene-space text drag into the persisted offset in its owner's coordinates. */\nexport function textDragOffset(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n target: IFusedTextTarget,\n delta: Point2D,\n): Point2D {\n if (target.kind === 'designator') {\n const instance = document.instances.find((value) => value.id === target.id);\n const geometry = instance === undefined ? undefined : devices.get(instance.device)?.geometry;\n if (instance === undefined || geometry === undefined)\n throw new Error(`Unknown designator: ${target.id}`);\n const origin = sceneToLocal(instance, geometry, instance.placement);\n const moved = sceneToLocal(instance, geometry, {\n x: instance.placement.x + delta.x,\n y: instance.placement.y + delta.y,\n });\n return {\n x: (instance.designatorOffset?.x ?? 0) + moved.x - origin.x,\n y: (instance.designatorOffset?.y ?? 0) + moved.y - origin.y,\n };\n }\n if (target.kind === 'label') {\n const label = document.labels.find((value) => value.id === target.id);\n if (label === undefined) throw new Error(`Unknown label: ${target.id}`);\n return { x: (label.offset?.x ?? 0.3) + delta.x, y: (label.offset?.y ?? -0.35) + delta.y };\n }\n const reference = document.references.find((value) => value.id === target.id);\n if (reference?.label === undefined)\n throw new Error(`Reference has no movable net label: ${target.id}`);\n const local = referenceToLocal(reference, delta);\n return {\n x: (reference.label.offset?.x ?? 0.7) + local.x,\n y: (reference.label.offset?.y ?? -1.4) + local.y,\n };\n}\n\nexport function referenceSymbolBounds(reference: VoltageReference): Rect2D {\n return reference.symbol === 'ground'\n ? { x: -0.7, y: -1.8, width: 1.4, height: 1.8 }\n : { x: -0.5, y: -1.3, width: 1, height: 1.3 };\n}\n\nexport function referenceBounds(reference: VoltageReference): Rect2D {\n const symbol = referenceSymbolBounds(reference);\n if (reference.symbol === 'ground') return symbol;\n const text = referenceTextBounds(reference);\n const left = Math.min(symbol.x, text.x);\n const top = Math.min(symbol.y, text.y);\n return {\n x: left,\n y: top,\n width: Math.max(symbol.x + symbol.width, text.x + text.width) - left,\n height: Math.max(symbol.y + symbol.height, text.y + text.height) - top,\n };\n}\n\n/** Annotation symbols use the same anchor, rotation and bounds for painting and picking. */\nexport function pickAnnotation(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n point: Point2D,\n tolerance: number,\n): { readonly kind: 'reference' | 'label'; readonly id: string } | undefined {\n for (const reference of [...document.references].reverse()) {\n const anchor = endpointPosition(document, devices, reference.target);\n const local = referenceToLocal(reference, { x: point.x - anchor.x, y: point.y - anchor.y });\n if (containsExpanded(referenceBounds(reference), local, tolerance))\n return { kind: 'reference', id: reference.id };\n }\n for (const label of [...document.labels].reverse()) {\n const anchor = endpointPosition(document, devices, label.target);\n if (\n containsExpanded(\n labelBounds(label),\n { x: point.x - anchor.x, y: point.y - anchor.y },\n tolerance,\n )\n )\n return { kind: 'label', id: label.id };\n }\n return undefined;\n}\n\nfunction containsExpanded(bounds: Rect2D, point: Point2D, tolerance: number): boolean {\n return contains(\n {\n x: bounds.x - tolerance,\n y: bounds.y - tolerance,\n width: bounds.width + tolerance * 2,\n height: bounds.height + tolerance * 2,\n },\n point,\n );\n}\n\nexport interface IBodyOverlap {\n readonly first: FusedInstance;\n readonly second: FusedInstance;\n}\n\nexport function findBodyOverlaps(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n): readonly IBodyOverlap[] {\n const bodies = document.instances.flatMap((instance) => {\n const geometry = devices.get(instance.device)?.geometry;\n if (geometry === undefined) return [];\n const rect = geometry.bodyBounds;\n return [\n {\n instance,\n points: [\n { x: rect.x, y: rect.y },\n { x: rect.x + rect.width, y: rect.y },\n { x: rect.x + rect.width, y: rect.y + rect.height },\n { x: rect.x, y: rect.y + rect.height },\n ].map((point) => localToScene(instance, geometry, point)),\n },\n ];\n });\n const overlaps: IBodyOverlap[] = [];\n for (const [index, first] of bodies.entries()) {\n for (const second of bodies.slice(index + 1)) {\n const separated = [first.points, second.points].some((points) =>\n points.some((point, edge) => {\n const next = points[(edge + 1) % points.length];\n if (next === undefined) return false;\n const axis = { x: point.y - next.y, y: next.x - point.x };\n const length = Math.hypot(axis.x, axis.y);\n const project = (value: Point2D) => (value.x * axis.x + value.y * axis.y) / length;\n const a = first.points.map(project);\n const b = second.points.map(project);\n return Math.max(...a) <= Math.min(...b) + 1e-9 || Math.max(...b) <= Math.min(...a) + 1e-9;\n }),\n );\n if (!separated) overlaps.push({ first: first.instance, second: second.instance });\n }\n }\n return overlaps;\n}\n\nexport function distanceToSegment(point: Point2D, a: Point2D, b: Point2D): number {\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const length = dx * dx + dy * dy;\n const t =\n length === 0\n ? 0\n : Math.max(0, Math.min(1, ((point.x - a.x) * dx + (point.y - a.y) * dy) / length));\n return Math.hypot(point.x - a.x - t * dx, point.y - a.y - t * dy);\n}\n\nexport function pickWireSegment(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n point: Point2D,\n tolerance: number,\n): { readonly wireId: string; readonly segment: number } | undefined {\n let hit: { wireId: string; segment: number; distance: number } | undefined;\n for (const wire of document.wires) {\n const points = [\n endpointPosition(document, devices, wire.from),\n ...wire.bends,\n endpointPosition(document, devices, wire.to),\n ];\n for (let segment = 0; segment < points.length - 1; segment++) {\n const from = points[segment]!;\n const to = points[segment + 1]!;\n if (from.x === to.x && from.y === to.y) continue;\n const distance = distanceToSegment(point, from, to);\n if (distance <= tolerance && (hit === undefined || distance < hit.distance))\n hit = { wireId: wire.id, segment, distance };\n }\n }\n return hit;\n}\n\nexport function fitViewport(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n width: number,\n height: number,\n): IViewport {\n const points = [\n ...document.nodes,\n ...document.wires.flatMap((wire) => wire.bends),\n ...document.instances.flatMap((instance) => {\n const bounds = devices.get(instance.device)?.geometry.bounds;\n const geometry = devices.get(instance.device)?.geometry;\n return bounds === undefined || geometry === undefined\n ? []\n : [\n { x: bounds.x, y: bounds.y },\n { x: bounds.x + bounds.width, y: bounds.y },\n { x: bounds.x, y: bounds.y + bounds.height },\n { x: bounds.x + bounds.width, y: bounds.y + bounds.height },\n ].map((point) => localToScene(instance, geometry, point));\n }),\n ];\n if (!points.length) return { scale: 10, x: width / 2, y: height / 2 };\n const left = Math.min(...points.map((point) => point.x));\n const top = Math.min(...points.map((point) => point.y));\n const right = Math.max(...points.map((point) => point.x));\n const bottom = Math.max(...points.map((point) => point.y));\n const scale = Math.max(\n 0.25,\n Math.min(\n 50,\n Math.max(1, width - 96) / Math.max(1, right - left),\n Math.max(1, height - 96) / Math.max(1, bottom - top),\n ),\n );\n return {\n scale,\n x: width / 2 - ((left + right) / 2) * scale,\n y: height / 2 - ((top + bottom) / 2) * scale,\n };\n}\n","/**\n * Orthogonal wire routing and anchor materialization of the fused workbench (RFC 0024).\n *\n * A fused wire persists only its intermediate bends; the full polyline is the from anchor, the\n * bends and the to anchor. Device anchors move with rotation, scaling and placement, so every\n * mutation that can move an anchor has to rebuild the bends until each leg is horizontal or\n * vertical — the same rule the separate schematic editor applies.\n *\n * The rules are shared with that editor instead of growing a second algorithm:\n * `orthogonalWaypoints` picks the elbow with the long axis first, `extendWirePath` folds retraced\n * collinear legs, and the endpoint absorption below is the same \"shift the neighbour, stop at the\n * next corner\" pass, bounded so it can never move the far anchor of a wire.\n */\nimport type {\n ConnectionNode,\n ConnectionWire,\n Endpoint,\n FusedDocument,\n Point2D,\n} from '@mica-js/document/fused';\nimport { projectOnSegment } from '@mica-js/document/schematic';\nimport { extendWirePath, orthogonalWaypoints } from '../schematic/editor/snapping/wire';\nimport { localToScene, type ICanvasDevice } from './canvas/geometry';\nimport { planPolylineSegmentDrag } from '../schematic/editing/segment-drag';\nimport { FusedSessionError } from './document/errors';\nimport { addNode, addWire, sameEndpoint, type IdFactory } from './document/edits';\n\n/** Verified device geometry keyed by full device id; prepared devices and canvas devices match. */\nexport type WiringDevices = ReadonlyMap<string, ICanvasDevice>;\n\n/** Explicit wire membership is based on endpoint identity, never coordinate overlap. */\nexport function hasWireConnection(document: FusedDocument, endpoint: Endpoint): boolean {\n return document.wires.some(\n (wire) => sameEndpoint(wire.from, endpoint) || sameEndpoint(wire.to, endpoint),\n );\n}\n\n/** Distance under which a tapped point counts as lying on a wire, in scene millimetres. */\nconst TAP_EPSILON = 1e-6;\n\n/**\n * Turns any point sequence into one orthogonal polyline.\n *\n * Consecutive points that are not aligned receive the elbow of `orthogonalWaypoints` (long axis\n * first), and retraced collinear legs collapse the way the schematic wire tool collapses them.\n *\n * ```ts\n * orthogonalPath([{ x: 0, y: 0 }, { x: 10, y: 6 }]);\n * // [{ 0, 0 }, { 10, 0 }, { 10, 6 }]\n * ```\n */\nexport function orthogonalPath(points: readonly Point2D[]): readonly Point2D[] {\n const [first, ...rest] = points;\n if (first === undefined) {\n return [];\n }\n let path: Point2D[] = [{ x: first.x, y: first.y }];\n for (const point of rest) {\n path = extendWirePath(path, { x: point.x, y: point.y }, undefined);\n }\n return path;\n}\n\n/** Whether every leg of the polyline is horizontal or vertical. */\nexport function isOrthogonalPolyline(points: readonly Point2D[]): boolean {\n for (let index = 1; index < points.length; index += 1) {\n const previous = points[index - 1];\n const point = points[index];\n if (previous === undefined || point === undefined) {\n return false;\n }\n if (previous.x !== point.x && previous.y !== point.y) {\n return false;\n }\n }\n return true;\n}\n\n/** Scene position of one connection endpoint, or `undefined` when it cannot be resolved. */\nexport function endpointPoint(\n document: FusedDocument,\n devices: WiringDevices,\n endpoint: Endpoint,\n): Point2D | undefined {\n if (endpoint.kind === 'node') {\n const node = document.nodes.find((candidate) => candidate.id === endpoint.node);\n return node === undefined ? undefined : { x: node.x, y: node.y };\n }\n const instance = document.instances.find((candidate) => candidate.id === endpoint.instance);\n if (instance === undefined) {\n return undefined;\n }\n const geometry = devices.get(instance.device)?.geometry;\n const pin = geometry?.pins[endpoint.pin];\n if (geometry === undefined || pin === undefined) {\n return undefined;\n }\n return localToScene(instance, geometry, pin.position);\n}\n\n/** Full polyline of one wire: the from anchor, the stored bends and the to anchor. */\nexport function wirePolyline(\n document: FusedDocument,\n devices: WiringDevices,\n wire: ConnectionWire,\n): readonly Point2D[] | undefined {\n const from = endpointPoint(document, devices, wire.from);\n const to = endpointPoint(document, devices, wire.to);\n if (from === undefined || to === undefined) {\n return undefined;\n }\n return [from, ...wire.bends, to];\n}\n\n/** Slides one wire segment while retaining both explicit electrical endpoints. */\nexport function moveWireSegment(\n document: FusedDocument,\n devices: WiringDevices,\n wireId: string,\n segment: number,\n delta: Point2D,\n): FusedDocument {\n const wire = document.wires.find((value) => value.id === wireId);\n const points = wire === undefined ? undefined : wirePolyline(document, devices, wire);\n const start = points?.[segment];\n const end = points?.[segment + 1];\n if (\n points === undefined ||\n !Number.isInteger(segment) ||\n start === undefined ||\n end === undefined ||\n !Number.isFinite(delta.x) ||\n !Number.isFinite(delta.y)\n )\n throw new FusedSessionError('edit/invalid-request', 'Invalid wire segment drag');\n const normal = start.y === end.y ? { x: 0, y: delta.y } : { x: delta.x, y: 0 };\n const first = points[0]!;\n const last = points[points.length - 1]!;\n const moved = planPolylineSegmentDrag(\n points,\n segment,\n normal,\n (point) =>\n (point.x === first.x && point.y === first.y) || (point.x === last.x && point.y === last.y),\n );\n if (moved === undefined) return document;\n const bends = orthogonalPath(moved).slice(1, -1);\n return {\n ...document,\n wires: document.wires.map((value) => (value.id === wireId ? { ...value, bends } : value)),\n };\n}\n\n/** A dragged pin-attached terminal gains its own anchor and an explicit connecting wire. */\nexport function moveReference(\n document: FusedDocument,\n devices: WiringDevices,\n referenceId: string,\n position: Point2D,\n createId: IdFactory,\n): FusedDocument {\n const reference = document.references.find((value) => value.id === referenceId);\n if (reference === undefined || !Number.isFinite(position.x) || !Number.isFinite(position.y))\n throw new FusedSessionError('edit/invalid-request', 'Invalid terminal drag');\n const origin = endpointPoint(document, devices, reference.target);\n if (origin === undefined)\n throw new FusedSessionError('edit/invalid-request', 'Unknown terminal anchor');\n if (origin.x === position.x && origin.y === position.y) return document;\n const target = reference.target;\n if (target.kind === 'node') {\n const node = document.nodes.find((value) => value.id === target.node);\n const shared =\n node?.kind === 'junction' ||\n document.references.some(\n (value) =>\n value.id !== referenceId &&\n value.target.kind === 'node' &&\n value.target.node === target.node,\n ) ||\n document.labels.some(\n (value) => value.target.kind === 'node' && value.target.node === target.node,\n ) ||\n document.wires.filter(\n (value) =>\n (value.from.kind === 'node' && value.from.node === target.node) ||\n (value.to.kind === 'node' && value.to.node === target.node),\n ).length > 1;\n if (!shared) {\n return routeDocumentWires(\n {\n ...document,\n nodes: document.nodes.map((value) =>\n value.id === target.node ? { ...value, ...position } : value,\n ),\n },\n devices,\n document,\n );\n }\n }\n const added = addNode(document, position, 'free', createId);\n const endpoint: Endpoint = { kind: 'node', node: added.nodeId };\n const moved: FusedDocument = {\n ...added.document,\n references: added.document.references.map((value) =>\n value.id === referenceId ? { ...value, target: endpoint } : value,\n ),\n };\n return addWire(\n moved,\n reference.target,\n endpoint,\n routeWireBends(moved, devices, reference.target, endpoint, []),\n createId,\n ).document;\n}\n\n/**\n * Bends for a new wire from `from` to `to` through the requested waypoints.\n *\n * The waypoints stay in the order the caller picked them; only the legs between them are\n * orthogonalized.\n */\nexport function routeWireBends(\n document: FusedDocument,\n devices: WiringDevices,\n from: Endpoint,\n to: Endpoint,\n bends: readonly Point2D[],\n): readonly Point2D[] {\n const start = endpointPoint(document, devices, from);\n const end = endpointPoint(document, devices, to);\n if (start === undefined || end === undefined) {\n return bends;\n }\n const path = orthogonalPath([start, ...bends, end]);\n return path.length < 2 ? [] : path.slice(1, -1);\n}\n\n/**\n * Rebuilds the bends of every wire whose legs are no longer orthogonal.\n *\n * `previous` is the document before the mutation. With it, endpoints that moved are absorbed the\n * way a symbol drag absorbs them: neighbouring bends shift, a rigid move translates the whole run\n * and the far anchor never moves. Without it (or for a wire the mutation also edited) the affected\n * wire is routed as one canonical orthogonal path.\n *\n * Wires that are already orthogonal are returned untouched, so existing geometry is preserved.\n */\nexport function routeDocumentWires(\n document: FusedDocument,\n devices: WiringDevices,\n previous?: FusedDocument,\n): FusedDocument {\n if (document.wires.length === 0) {\n return document;\n }\n const previousWires = new Map((previous?.wires ?? []).map((wire) => [wire.id, wire]));\n let changed = false;\n const wires = document.wires.map((wire) => {\n const line = wirePolyline(document, devices, wire);\n if (line === undefined || isOrthogonalPolyline(line)) {\n return wire;\n }\n const rerouted = rerouteWire(wire, line, devices, previous, previousWires.get(wire.id));\n const bends = rerouted.slice(1, -1);\n if (samePoints(bends, wire.bends)) {\n return wire;\n }\n changed = true;\n return { ...wire, bends };\n });\n return changed ? { ...document, wires } : document;\n}\n\n/**\n * Resolves one placement anchor to a real endpoint without mutating anything.\n *\n * - An existing {@link Endpoint} passes through unchanged.\n * - A point on a pin or on a connection node resolves to that endpoint.\n * - A point on a wire splits every host wire there and returns one shared junction node, so the\n * caller's next wire, label or reference is electrically connected.\n * - Any other point becomes a free node.\n *\n * The function is pure: the input document is never changed, so an abandoned gesture persists\n * nothing and an Escape leaves no orphan node or wire behind.\n */\nexport function materializeAnchor(\n document: FusedDocument,\n anchor: Endpoint | Point2D,\n devices: WiringDevices,\n createId: () => string,\n): { readonly document: FusedDocument; readonly endpoint: Endpoint } {\n if (isEndpoint(anchor)) {\n return { document, endpoint: anchor };\n }\n const point = readPoint(anchor);\n\n const pin = pinAt(document, devices, point);\n if (pin !== undefined) {\n return { document, endpoint: pin };\n }\n const node = document.nodes.find((candidate) => samePoint(candidate, point));\n if (node !== undefined) {\n return { document, endpoint: { kind: 'node', node: node.id } };\n }\n\n const candidates = document.wires.flatMap((wire) => {\n const line = wirePolyline(document, devices, wire);\n if (line === undefined) {\n return [];\n }\n const split = locateOnPolyline(line, point);\n return split === undefined ? [] : [{ wire, split, line }];\n });\n const origin = candidates[0]?.split.point;\n // Only wires that meet at the very same point share the junction; a near miss stays untouched.\n const hosts =\n origin === undefined\n ? []\n : candidates.filter((candidate) => samePoint(candidate.split.point, origin));\n const taken = takenIds(document);\n if (hosts.length === 0) {\n const nodeId = freshId(taken, createId);\n const free: ConnectionNode = { id: nodeId, kind: 'free', x: point.x, y: point.y };\n return {\n document: { ...document, nodes: [...document.nodes, free] },\n endpoint: { kind: 'node', node: nodeId },\n };\n }\n\n const junction: ConnectionNode = {\n id: freshId(taken, createId),\n kind: 'junction',\n x: hosts[0]?.split.point.x ?? point.x,\n y: hosts[0]?.split.point.y ?? point.y,\n };\n const endpoint: Endpoint = { kind: 'node', node: junction.id };\n const hostsById = new Map(hosts.map((host) => [host.wire.id, host]));\n const wires: ConnectionWire[] = [];\n for (const wire of document.wires) {\n const host = hostsById.get(wire.id);\n if (host === undefined) {\n wires.push(wire);\n continue;\n }\n const halves = splitWire(wire, host.split, host.line, endpoint, taken, createId);\n wires.push(...halves);\n }\n return {\n document: { ...document, nodes: [...document.nodes, junction], wires },\n endpoint,\n };\n}\n\ninterface IHostSplit {\n /** Index of the split vertex in the full polyline, or `-1` when it lies inside a segment. */\n readonly vertex: number;\n /** Segment index that contains the split point. */\n readonly segment: number;\n readonly point: Point2D;\n}\n\nfunction splitWire(\n wire: ConnectionWire,\n split: IHostSplit,\n line: readonly Point2D[],\n junction: Endpoint,\n taken: Set<string>,\n createId: () => string,\n): readonly ConnectionWire[] {\n const last = line.length - 1;\n // The split point becomes the junction anchor, so it is dropped from both bend lists.\n const head = split.vertex >= 0 ? line.slice(1, split.vertex) : line.slice(1, split.segment + 1);\n const tail =\n split.vertex >= 0 ? line.slice(split.vertex + 1, last) : line.slice(split.segment + 1, last);\n return [\n { id: freshId(taken, createId), from: wire.from, to: junction, bends: head },\n { id: freshId(taken, createId), from: junction, to: wire.to, bends: tail },\n ];\n}\n\nfunction locateOnPolyline(line: readonly Point2D[], point: Point2D): IHostSplit | undefined {\n const last = line.length - 1;\n for (let vertex = 1; vertex < last; vertex += 1) {\n const candidate = line[vertex];\n if (candidate !== undefined && samePoint(candidate, point)) {\n return { vertex, segment: vertex, point: { x: candidate.x, y: candidate.y } };\n }\n }\n for (let segment = 0; segment < last; segment += 1) {\n const from = line[segment];\n const to = line[segment + 1];\n if (from === undefined || to === undefined) {\n continue;\n }\n const projected = projectOnSegment(point, from, to);\n const distance = Math.hypot(projected.x - point.x, projected.y - point.y);\n if (distance > TAP_EPSILON) {\n continue;\n }\n if (segment === 0 && samePoint(projected, from)) {\n continue;\n }\n if (segment === last - 1 && samePoint(projected, to)) {\n continue;\n }\n return { vertex: -1, segment, point: { x: projected.x, y: projected.y } };\n }\n return undefined;\n}\n\nfunction pinAt(\n document: FusedDocument,\n devices: WiringDevices,\n point: Point2D,\n): Endpoint | undefined {\n for (const instance of document.instances) {\n const geometry = devices.get(instance.device)?.geometry;\n if (geometry === undefined) {\n continue;\n }\n for (const pin of Object.keys(geometry.pins)) {\n const anchor = geometry.pins[pin];\n if (anchor === undefined) {\n continue;\n }\n const scene = localToScene(instance, geometry, anchor.position);\n if (samePoint(scene, point)) {\n return { kind: 'pin', instance: instance.id, pin };\n }\n }\n }\n return undefined;\n}\n\nfunction rerouteWire(\n wire: ConnectionWire,\n line: readonly Point2D[],\n devices: WiringDevices,\n previous: FusedDocument | undefined,\n previousWire: ConnectionWire | undefined,\n): readonly Point2D[] {\n const start = line[0];\n const end = line[line.length - 1];\n if (start === undefined || end === undefined) {\n return orthogonalPath(line);\n }\n if (previous !== undefined && previousWire !== undefined) {\n const oldFrom = endpointPoint(previous, devices, previousWire.from);\n const oldTo = endpointPoint(previous, devices, previousWire.to);\n const sameBends = samePoints(previousWire.bends, wire.bends);\n if (oldFrom !== undefined && oldTo !== undefined && sameBends) {\n const startDelta = { x: start.x - oldFrom.x, y: start.y - oldFrom.y };\n const endDelta = { x: end.x - oldTo.x, y: end.y - oldTo.y };\n if (startDelta.x === endDelta.x && startDelta.y === endDelta.y) {\n // A whole run that moves together keeps its shape; only the anchors changed.\n const translated = [\n { x: start.x, y: start.y },\n ...wire.bends.map((bend) => ({\n x: bend.x + startDelta.x,\n y: bend.y + startDelta.y,\n })),\n { x: end.x, y: end.y },\n ];\n if (isOrthogonalPolyline(translated)) {\n return translated;\n }\n }\n let points: Point2D[] = [\n { x: oldFrom.x, y: oldFrom.y },\n ...wire.bends.map((bend) => ({ x: bend.x, y: bend.y })),\n { x: oldTo.x, y: oldTo.y },\n ];\n points = absorbEndpoint(points, 'start', { x: start.x, y: start.y });\n points = absorbEndpoint(points, 'end', { x: end.x, y: end.y });\n if (isOrthogonalPolyline(points)) {\n return points;\n }\n }\n }\n return orthogonalPath(line);\n}\n\n/**\n * Moves one anchor of an orthogonal polyline and absorbs the displacement by shifting the next\n * bend, exactly like the schematic symbol drag.\n *\n * Unlike the original pass, the loop stops one vertex before the far anchor: a fused wire must keep\n * both of its connection endpoints, so a displacement that reaches the other end is taken by a new\n * elbow instead of by moving that anchor.\n */\nfunction absorbEndpoint(\n points: readonly Point2D[],\n end: 'start' | 'end',\n target: Point2D,\n): Point2D[] {\n const next = points.map((point) => ({ x: point.x, y: point.y }));\n const last = next.length - 1;\n if (last < 1) {\n return next;\n }\n if (end === 'start') {\n next[0] = { x: target.x, y: target.y };\n for (let index = 0; index < last; index += 1) {\n const a = next[index];\n const b = next[index + 1];\n if (a === undefined || b === undefined || a.x === b.x || a.y === b.y) {\n break;\n }\n if (index + 1 === last) {\n next.splice(last, 0, elbow(a, b));\n break;\n }\n next[index + 1] = shifted(points, index, a, b);\n }\n return next;\n }\n next[last] = { x: target.x, y: target.y };\n for (let index = last; index > 0; index -= 1) {\n const a = next[index - 1];\n const b = next[index];\n if (a === undefined || b === undefined || a.x === b.x || a.y === b.y) {\n break;\n }\n if (index - 1 === 0) {\n next.splice(index, 0, elbow(a, b));\n break;\n }\n next[index - 1] = shifted(points, index - 1, a, b);\n }\n return next;\n}\n\n/** Restores the original orientation of one leg by moving its far vertex. */\nfunction shifted(points: readonly Point2D[], index: number, a: Point2D, b: Point2D): Point2D {\n const before = points[index];\n const after = points[index + 1];\n const horizontal = before !== undefined && after !== undefined && before.y === after.y;\n return horizontal ? { x: b.x, y: a.y } : { x: a.x, y: b.y };\n}\n\n/** The elbow of `orthogonalWaypoints` between two diagonal points. */\nfunction elbow(a: Point2D, b: Point2D): Point2D {\n const [first] = orthogonalWaypoints(a, b);\n return first === undefined ? { x: a.x, y: b.y } : { x: first.x, y: first.y };\n}\n\nfunction isEndpoint(value: Endpoint | Point2D): value is Endpoint {\n const kind = (value as { kind?: unknown }).kind;\n return kind === 'pin' || kind === 'node';\n}\n\nfunction readPoint(point: Point2D): Point2D {\n if (\n point === null ||\n typeof point !== 'object' ||\n !Number.isFinite(point.x) ||\n !Number.isFinite(point.y)\n ) {\n throw new TypeError('An anchor point needs finite \"x\" and \"y\" numbers.');\n }\n return { x: point.x, y: point.y };\n}\n\nfunction samePoint(left: Point2D, right: Point2D): boolean {\n return left.x === right.x && left.y === right.y;\n}\n\nfunction samePoints(left: readonly Point2D[], right: readonly Point2D[]): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((point, index) => {\n const other = right[index];\n return other !== undefined && samePoint(point, other);\n });\n}\n\nfunction takenIds(document: FusedDocument): Set<string> {\n return new Set<string>([\n ...document.instances.map((entry) => entry.id),\n ...document.nodes.map((entry) => entry.id),\n ...document.wires.map((entry) => entry.id),\n ...document.labels.map((entry) => entry.id),\n ...document.references.map((entry) => entry.id),\n ]);\n}\n\nfunction freshId(taken: Set<string>, createId: () => string): string {\n for (let attempt = 0; attempt < 128; attempt += 1) {\n const id = createId();\n if (!taken.has(id)) {\n taken.add(id);\n return id;\n }\n }\n throw new Error('Could not allocate a unique element id for the anchor.');\n}\n","/**\n * Verification every committed document state has to pass (RFC 0024).\n *\n * A mutation is only accepted once the candidate parses, every device it references opens as the\n * locked release with usable geometry, the per-instance view layouts name declared views, and the\n * explicit connection graph derives without name or voltage conflicts.\n */\nimport { deriveFusedTopology, parseFusedDocument } from '@mica-js/document/fused';\nimport type { FusedDocument, FusedTopology, UnifiedDeviceManifest } from '@mica-js/document/fused';\nimport type { IDeviceCache, IPreparedDevice } from '../devices';\nimport { routeDocumentWires } from '../wiring';\nimport { FusedSessionError } from './errors';\nimport type { IFusedSessionProblem } from './errors';\n\nexport interface IVerifiedFusedDocument {\n readonly document: FusedDocument;\n readonly devices: ReadonlyMap<string, IPreparedDevice>;\n readonly topology: FusedTopology;\n}\n\nexport interface IVerifyFusedDocumentOptions {\n /**\n * Rebuilds every wire whose legs are no longer orthogonal, using the loaded device geometry.\n *\n * Content mutations route; a layout check must not change content, so it leaves wires alone.\n */\n readonly routeWires?: boolean;\n /** Document before the mutation, so moved anchors are absorbed the way a symbol drag absorbs them. */\n readonly previous?: FusedDocument;\n}\n\n/**\n * Parses and verifies one candidate document.\n *\n * @throws {FusedDocumentError} for contract violations, {PreparationError} for package problems and\n * {FusedSessionError} for a view layout the owning device does not declare.\n */\nexport async function verifyFusedDocument(\n value: unknown,\n devices: IDeviceCache,\n options: IVerifyFusedDocumentOptions = {},\n): Promise<IVerifiedFusedDocument> {\n let document = parseFusedDocument(value);\n const prepared = await devices.prepareDocument(document);\n for (const instance of document.instances) {\n const properties = prepared.get(instance.device)?.manifest.properties;\n for (const [key, value] of Object.entries(instance.properties ?? {})) {\n if (\n value !== null &&\n typeof value === 'object' &&\n value.mode === 'project' &&\n properties?.[key]?.type !== 'program'\n )\n throw new FusedSessionError(\n 'edit/invalid-document',\n `Only program properties can reference a project: ${instance.id}/${key}.`,\n );\n }\n }\n if (options.routeWires === true) {\n const routed = routeDocumentWires(document, prepared, options.previous);\n if (routed !== document) {\n document = parseFusedDocument(routed);\n }\n }\n checkViewLayouts(document, prepared);\n const manifests = new Map<string, UnifiedDeviceManifest>(\n [...prepared].map(([deviceId, device]) => [deviceId, device.manifest]),\n );\n const topology = deriveFusedTopology(document, manifests);\n return { document, devices: prepared, topology };\n}\n\n/**\n * Checks every saved layout against the views its device declares (RFC 0024).\n *\n * The document parser cannot do this: view ids live in the device manifest.\n */\nfunction checkViewLayouts(\n document: FusedDocument,\n prepared: ReadonlyMap<string, IPreparedDevice>,\n): void {\n const problems: IFusedSessionProblem[] = [];\n document.instances.forEach((instance, index) => {\n const layout = instance.viewLayout;\n if (layout === undefined) {\n return;\n }\n const declared = prepared.get(instance.device)?.manifest.view ?? {};\n layout.views.forEach((view, at) => {\n if (!Object.hasOwn(declared, view.viewId)) {\n problems.push({\n code: 'document/invalid-view-layout',\n message: `Instance \"${instance.id}\" lays out the view \"${view.viewId}\", which ${instance.device} does not declare.`,\n pointer: `/instances/${String(index)}/viewLayout/views/${String(at)}/viewId`,\n });\n }\n });\n });\n if (problems.length > 0) {\n throw new FusedSessionError(\n 'edit/invalid-document',\n problems[0]?.message ?? 'A saved view layout is invalid.',\n { problems },\n );\n }\n}\n","/**\n * Document and editing session of the fused workbench (RFC 0024).\n *\n * The session owns the immutable document, the unified undo history and the saved marker. It is the\n * single writer: every operation is serialized, re-checks the access policy right before the commit,\n * verifies the candidate against the locked packages and only then publishes one content event.\n *\n * Permission and run locking are enforced centrally for every write, including view layouts:\n *\n * - `edit` denied: no mutation at all; the document stays browsable and unsaved content is kept.\n * - running: properties, connections and other content stay read-only, view layouts stay editable,\n * and undo/redo only walks layout transactions at the top of the history.\n */\nimport { DisposableStore, Emitter } from '@mica-js/core/lifecycle';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport { parseFusedDocument } from '@mica-js/document/fused';\nimport type {\n DeviceLock,\n Endpoint,\n FusedDocument,\n FusedTopology,\n InstanceViewLayout,\n Placement2D,\n Point2D,\n PropertyValue,\n} from '@mica-js/document/fused';\nimport type {\n AccessDecision,\n IDeviceProvider,\n IDocumentAccess,\n IWorkbenchAccessProvider,\n} from '../providers';\nimport { DeviceCache } from '../devices';\nimport type { IDeviceCache, IPreparedDevice } from '../devices';\nimport {\n addInstance,\n addLabel,\n addNode,\n addReference,\n addWire,\n moveInstances,\n removeInstanceProperty,\n removeTargets,\n renameDesignator,\n rotateInstances,\n setInstancePosition,\n setInstanceProperty,\n setViewLayout as replaceViewLayout,\n} from './edits';\nimport type { IFusedDocumentTarget, IFusedLabelOptions, IFusedReferenceOptions } from './edits';\nimport { copyTargets, pasteClipboard } from './copy';\nimport { routeWireBends } from '../wiring';\nimport type { IFusedClipboard } from './copy';\nimport { verifyFusedDocument } from './verify';\nimport type { IVerifiedFusedDocument } from './verify';\nimport { accessDenied, FusedSessionError, toSessionError } from './errors';\n\nconst DEFAULT_HISTORY_LIMIT = 200;\n\ntype DeniedDecision = Extract<AccessDecision, { readonly allowed: false }>;\ntype WriteMode = 'content' | 'layout';\n\nexport interface IFusedDocumentSessionOptions {\n readonly document: FusedDocument;\n readonly saveDocument?: (document: FusedDocument) => Promise<void>;\n /** Locked package registry; the session owns its verified cache. */\n readonly devices: IDeviceProvider;\n readonly access: IWorkbenchAccessProvider;\n /** Maximum number of undo steps kept; defaults to 200. */\n readonly historyLimit?: number;\n /** Element id factory; defaults to `crypto.randomUUID`. */\n readonly createId?: () => string;\n}\n\nexport interface IFusedDocumentState {\n readonly canUndo: boolean;\n readonly canRedo: boolean;\n readonly dirty: boolean;\n /** No mutation of any kind is allowed: the access policy denies editing this document. */\n readonly readOnly: boolean;\n /** A run is in progress; content and topology are read-only while layouts stay editable. */\n readonly running: boolean;\n readonly canEditContent: boolean;\n readonly canEditLayout: boolean;\n readonly access: IDocumentAccess;\n}\n\nexport interface IFusedTransactionOptions {\n /** Declares a view-layout-only change: allowed while running, and rejected if it alters content. */\n readonly layoutOnly?: boolean;\n}\n\ninterface IHistoryEntry {\n readonly before: FusedDocument;\n readonly after: FusedDocument;\n readonly contentChanged: boolean;\n readonly beforeTopology: FusedTopology | undefined;\n readonly afterTopology: FusedTopology;\n readonly beforeDevices: ReadonlyMap<string, IPreparedDevice>;\n readonly afterDevices: ReadonlyMap<string, IPreparedDevice>;\n}\n\n/**\n * One open fused document with its editing history.\n *\n * Create it with {@link FusedDocumentSession.open}; every method below documents whether it needs\n * `edit` permission and how it behaves while a run is active.\n */\nexport class FusedDocumentSession {\n readonly #saveDocument: ((document: FusedDocument) => Promise<void>) | undefined;\n readonly #access: IWorkbenchAccessProvider;\n readonly #packages: DeviceCache;\n readonly #createId: () => string;\n readonly #historyLimit: number;\n readonly #subscriptions = new DisposableStore();\n readonly #content = new Emitter<FusedDocument>();\n readonly #state = new Emitter<IFusedDocumentState>();\n readonly #errors = new Emitter<FusedSessionError>();\n readonly #keys = new WeakMap<FusedDocument, string>();\n readonly #contentKeys = new WeakMap<FusedDocument, string>();\n #document: FusedDocument;\n #savedKey: string;\n #past: IHistoryEntry[] = [];\n #future: IHistoryEntry[] = [];\n #decisions: IDocumentAccess;\n #prepared: ReadonlyMap<string, IPreparedDevice> = new Map();\n #topology: FusedTopology | undefined;\n #preparationError: FusedSessionError | undefined;\n #running = false;\n #queue: Promise<void> = Promise.resolve();\n #pendingAccess: Promise<void> | undefined;\n #evaluationRevision = 0;\n #appliedRevision = 0;\n #disposed = false;\n #lastStateSignature = '';\n\n private constructor(\n options: IFusedDocumentSessionOptions,\n document: FusedDocument,\n decisions: IDocumentAccess,\n ) {\n this.#saveDocument = options.saveDocument;\n this.#access = options.access;\n this.#packages = new DeviceCache(options.devices);\n this.#createId = options.createId ?? (() => globalThis.crypto.randomUUID());\n this.#historyLimit = options.historyLimit ?? DEFAULT_HISTORY_LIMIT;\n this.#document = document;\n this.#savedKey = canonicalJson(document);\n this.#decisions = decisions;\n }\n\n /**\n * Reads and parses `<uri>` and opens a session on it.\n *\n * A document whose packages or connection graph cannot be verified still opens for browsing; the\n * failure is reported by {@link getPreparationError} and every content edit then fails closed.\n *\n * @throws {FusedSessionError} when the supplied document violates RFC 0024 or the access policy\n * cannot be evaluated.\n */\n static async open(options: IFusedDocumentSessionOptions): Promise<FusedDocumentSession> {\n let document: FusedDocument;\n try {\n document = parseFusedDocument(options.document);\n } catch (cause) {\n throw toSessionError(cause, 'edit/invalid-document');\n }\n const decisions = await evaluateDecisions(options.access, document);\n const session = new FusedDocumentSession(options, document, decisions);\n await session.#start();\n session.#subscriptions.add(\n options.access.onDidChange(() => {\n session.#refreshAccessInBackground();\n }),\n );\n return session;\n }\n\n /** Fires once per committed change, undo and redo; rejected operations never fire it. */\n readonly onDidChangeContent: Event<FusedDocument> = this.#content.event;\n /** Fires whenever undo/redo, dirty, read-only or running change. */\n readonly onDidChangeState: Event<IFusedDocumentState> = this.#state.event;\n /** Fires for every rejected operation and access-policy failure with its code and problems. */\n readonly onDidError: Event<FusedSessionError> = this.#errors.event;\n\n /** Current immutable snapshot; the same reference until the next commit. */\n getDocument(): FusedDocument {\n this.#assertAlive();\n return this.#document;\n }\n\n getState(): IFusedDocumentState {\n this.#assertAlive();\n const readOnly = !this.#decisions.edit.allowed;\n const top = this.#past.at(-1);\n const next = this.#future.at(-1);\n return {\n canUndo: top !== undefined && (!this.#running || !top.contentChanged),\n canRedo: next !== undefined && (!this.#running || !next.contentChanged),\n dirty: this.#documentKey(this.#document) !== this.#savedKey,\n readOnly,\n running: this.#running,\n canEditContent: !readOnly && !this.#running,\n canEditLayout: !readOnly,\n access: this.#decisions,\n };\n }\n\n /** Decisions of the last evaluation; `run` is independent of `edit`. */\n getAccess(): IDocumentAccess {\n this.#assertAlive();\n return this.#decisions;\n }\n\n isRunning(): boolean {\n return this.#running;\n }\n\n /** Verified package cache shared with the canvas renderer; the session disposes it. */\n getDevices(): IDeviceCache {\n return this.#packages;\n }\n\n /** Nets of the last verified state, or `undefined` when the document never verified. */\n getTopology(): FusedTopology | undefined {\n this.#assertAlive();\n return this.#topology;\n }\n\n /** Why the document could not be verified on open; cleared by the next verified commit. */\n getPreparationError(): FusedSessionError | undefined {\n return this.#preparationError;\n }\n\n /** Manifests, geometry and verified files of every device the document uses. */\n getPreparedDevices(): Promise<ReadonlyMap<string, IPreparedDevice>> {\n return this.#enqueue(async () => {\n const prepared = await this.#packages.prepareDocument(this.#document);\n this.#prepared = sameDevices(this.#prepared, prepared) ? this.#prepared : prepared;\n return this.#prepared;\n });\n }\n\n /** Re-evaluates the access policy, for example after an external sign-in change. */\n refreshAccess(): Promise<void> {\n return this.#enqueue(async () => {\n await this.#settleAccess();\n await this.#evaluate();\n this.#publishState();\n });\n }\n\n /**\n * Locks or unlocks content editing for a run.\n *\n * Enabling needs the independent `run` permission; disabling always succeeds. The flag never\n * changes the document, history or dirty marker.\n */\n setRunning(running: boolean): Promise<void> {\n return this.#enqueue(async () => {\n await this.#settleAccess();\n const decisions = await this.#evaluate();\n if (running) {\n const decision = decisions.run;\n if (!decision.allowed) {\n throw accessDenied('access/run-denied', decision);\n }\n }\n if (running === this.#running) {\n this.#publishState();\n return;\n }\n this.#running = running;\n this.#publishState();\n });\n }\n\n /**\n * Applies one arbitrary, already built document as one transaction.\n *\n * This is the generic write gate: it checks the access policy like every named operation, so a\n * caller cannot bypass read-only or run locking through it. Use `layoutOnly` for view layouts.\n *\n * @throws {FusedSessionError} for denied permission, a running lock, or an invalid candidate.\n */\n transact(\n update: (document: FusedDocument) => FusedDocument | Promise<FusedDocument>,\n options: IFusedTransactionOptions = {},\n ): Promise<FusedDocument> {\n return this.#write(options.layoutOnly === true ? 'layout' : 'content', async (current) => {\n const candidate = await update(current);\n if (candidate === null || typeof candidate !== 'object') {\n throw new FusedSessionError(\n 'edit/invalid-request',\n 'A transaction must return the next document.',\n );\n }\n return { document: candidate, result: candidate };\n });\n }\n\n /**\n * Places one device, locking its release and allocating the smallest free designator.\n *\n * Needs `edit` permission, a verified package with geometry and body image, and a policy that\n * allows adding this device. An existing lock of another release is rejected, never replaced.\n *\n * @returns the new instance id.\n */\n addDevice(lock: DeviceLock, placement: Placement2D): Promise<string> {\n return this.#write('content', async (current) => {\n const device = await this.#packages.get(lock);\n this.#requireUnchangedLock(current, device.lock);\n const added = addInstance(current, device, placement, this.#createId);\n return { document: added.document, result: added.instanceId };\n });\n }\n\n /** Removes the targets as one transaction; instances cascade to their wires, labels and references. */\n remove(targets: readonly IFusedDocumentTarget[]): Promise<FusedDocument> {\n return this.#edit((current) => removeTargets(current, targets));\n }\n\n /** Moves one instance so its origin lands on `position`. */\n moveInstance(instanceId: string, position: Point2D): Promise<FusedDocument> {\n return this.#edit((current) => setInstancePosition(current, instanceId, position));\n }\n\n /** Offsets instances by a scene-space delta, for a finished drag. */\n moveInstances(instanceIds: readonly string[], delta: Point2D): Promise<FusedDocument> {\n return this.#edit((current) => moveInstances(current, instanceIds, delta));\n }\n\n /** Rotates instances clockwise by `degrees`. */\n rotateInstances(instanceIds: readonly string[], degrees: number): Promise<FusedDocument> {\n return this.#edit((current) => rotateInstances(current, instanceIds, degrees));\n }\n\n /** Rotates one instance clockwise by `degrees`; the canvas sends the drag delta. */\n rotateInstance(instanceId: string, degrees: number): Promise<FusedDocument> {\n return this.#edit((current) => rotateInstances(current, [instanceId], degrees));\n }\n\n /**\n * Renames one instance designator.\n *\n * @throws {FusedSessionError} (`edit/duplicate-designator`) when another instance owns the name.\n */\n renameDesignator(instanceId: string, designator: string): Promise<FusedDocument> {\n return this.#edit((current) => renameDesignator(current, instanceId, designator));\n }\n\n /** Stores one property override on an instance. */\n setProperty(instanceId: string, key: string, value: PropertyValue): Promise<FusedDocument> {\n return this.#edit((current) => setInstanceProperty(current, instanceId, key, value));\n }\n\n /** Drops one property override; an unknown key is a no-op. */\n removeProperty(instanceId: string, key: string): Promise<FusedDocument> {\n return this.#edit((current) => removeInstanceProperty(current, instanceId, key));\n }\n\n /** Adds a free or junction node; `id` is the new node id. */\n addNode(point: Point2D, kind: 'junction' | 'free'): Promise<string> {\n return this.#write('content', async (current) => {\n const added = addNode(current, point, kind, this.#createId);\n return { document: added.document, result: added.nodeId };\n });\n }\n\n /**\n * Connects two endpoints; `bends` are the intermediate waypoints only.\n *\n * The persisted bends are routed against the loaded pin geometry, so the new wire has no\n * diagonal leg even when the two anchors are not aligned.\n */\n addWire(from: Endpoint, to: Endpoint, bends: readonly Point2D[] = []): Promise<string> {\n return this.#write('content', async (current) => {\n const devices = await this.#packages.prepareDocument(current);\n const routed = routeWireBends(current, devices, from, to, bends);\n const added = addWire(current, from, to, routed, this.#createId);\n return { document: added.document, result: added.wireId };\n });\n }\n\n /** Attaches an ideal voltage reference, optionally drawn as the power or ground symbol. */\n addReference(\n target: Endpoint,\n voltage: number,\n symbol?: 'power' | 'ground',\n options: IFusedReferenceOptions = {},\n ): Promise<string> {\n return this.#write('content', async (current) => {\n const added = addReference(current, target, voltage, symbol, options, this.#createId);\n return { document: added.document, result: added.referenceId };\n });\n }\n\n /** Declares a net name on one endpoint. */\n addLabel(target: Endpoint, name: string, options: IFusedLabelOptions = {}): Promise<string> {\n return this.#write('content', async (current) => {\n const added = addLabel(current, target, name, options, this.#createId);\n return { document: added.document, result: added.labelId };\n });\n }\n\n /**\n * Stores the per-instance view layout, or restores the defaults with `undefined`.\n *\n * This is a layout transaction: it is allowed while running and rejected if it changes content.\n */\n setViewLayout(\n instanceId: string,\n layout: InstanceViewLayout | undefined,\n ): Promise<FusedDocument> {\n return this.#write('layout', async (current) => {\n const next = replaceViewLayout(current, instanceId, layout);\n return { document: next, result: next };\n });\n }\n\n /** Extracts the selected subgraph; a pure read that records no history. */\n copy(targets: readonly IFusedDocumentTarget[]): IFusedClipboard | undefined {\n this.#assertAlive();\n return copyTargets(this.#document, targets);\n }\n\n /**\n * Inserts a copied subgraph as one transaction.\n *\n * Copied devices must be locked by the clipboard, verified through their package and allowed by\n * the device-addition policy; connected edges outside the copy are not reproduced.\n */\n paste(clipboard: IFusedClipboard, offset: Point2D = { x: 0, y: 0 }): Promise<FusedDocument> {\n return this.#write('content', async (current) => {\n if (clipboard === null || typeof clipboard !== 'object') {\n throw new FusedSessionError('edit/invalid-request', 'The clipboard payload is missing.');\n }\n if (clipboard.instances.length === 0) {\n throw new FusedSessionError('edit/invalid-request', 'The clipboard holds no instances.');\n }\n const prepared = new Map<string, IPreparedDevice>();\n for (const deviceId of new Set(clipboard.instances.map((instance) => instance.device))) {\n const dependency = clipboard.dependencies[deviceId];\n if (dependency === undefined) {\n throw new FusedSessionError(\n 'edit/invalid-request',\n `The clipboard does not lock \"${deviceId}\".`,\n );\n }\n const device = await this.#packages.get({\n id: deviceId,\n version: dependency.version,\n integrity: dependency.integrity,\n });\n this.#requireUnchangedLock(current, device.lock);\n prepared.set(deviceId, device);\n }\n const next = pasteClipboard(current, clipboard, offset, prepared, this.#createId);\n return { document: next, result: next };\n });\n }\n\n /**\n * Rewrites the `.sch` file with the current content and marks it saved.\n *\n * Needs `edit` permission. Edits made while the write is pending run afterwards and keep the\n * document dirty; the saved marker is restored by undoing back to the written snapshot.\n */\n save(): Promise<void> {\n return this.#enqueue(async () => {\n await this.#settleAccess();\n this.#requireEdit('layout');\n const document = this.#document;\n await this.#authorize('layout', document, document);\n if (this.#saveDocument === undefined)\n throw new FusedSessionError(\n 'save/unavailable',\n 'The host does not provide document saving.',\n );\n try {\n await this.#saveDocument(document);\n } catch (cause) {\n throw new FusedSessionError('save/failed', 'Cannot save the document.', { cause });\n }\n this.#assertAlive();\n this.#savedKey = this.#documentKey(document);\n this.#publishState();\n });\n }\n\n /** Undoes the top step; while running only a layout step at the top of the history is undone. */\n undo(): Promise<void> {\n return this.#enqueue(async () => {\n const entry = this.#past.at(-1);\n if (entry === undefined) {\n return;\n }\n const mode: WriteMode = entry.contentChanged ? 'content' : 'layout';\n await this.#settleAccess();\n this.#requireHistoryStep(entry);\n await this.#authorize(mode, entry.before, this.#document);\n this.#past.pop();\n this.#future.push(entry);\n this.#restore(entry.before, entry.beforeDevices, entry.beforeTopology);\n });\n }\n\n /** Redoes the top undone step with the same run-locking rules as {@link undo}. */\n redo(): Promise<void> {\n return this.#enqueue(async () => {\n const entry = this.#future.at(-1);\n if (entry === undefined) {\n return;\n }\n const mode: WriteMode = entry.contentChanged ? 'content' : 'layout';\n await this.#settleAccess();\n this.#requireHistoryStep(entry);\n await this.#authorize(mode, entry.after, this.#document);\n this.#future.pop();\n this.#past.push(entry);\n this.#restore(entry.after, entry.afterDevices, entry.afterTopology);\n });\n }\n\n /** Releases the access subscription, the package cache and every event; content is untouched. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n this.#subscriptions.dispose();\n this.#packages.dispose();\n this.#content.dispose();\n this.#state.dispose();\n this.#errors.dispose();\n }\n\n async #start(): Promise<void> {\n try {\n const verified = await verifyFusedDocument(this.#document, this.#packages);\n this.#document = verified.document;\n this.#prepared = verified.devices;\n this.#topology = verified.topology;\n } catch (cause) {\n this.#preparationError = toSessionError(cause, 'device/unavailable');\n }\n this.#savedKey = this.#documentKey(this.#document);\n this.#lastStateSignature = this.#stateSignature();\n }\n\n #edit(update: (current: FusedDocument) => FusedDocument): Promise<FusedDocument> {\n return this.#write('content', async (current) => {\n const next = update(current);\n return { document: next, result: next };\n });\n }\n\n async #write<R>(\n mode: WriteMode,\n build: (\n current: FusedDocument,\n ) => Promise<{ readonly document: FusedDocument; readonly result: R }>,\n ): Promise<R> {\n return this.#enqueue(async () => {\n // A provider change that is still being evaluated blocks the write before any work is done.\n await this.#settleAccess();\n this.#requireEdit(mode);\n const current = this.#document;\n const built = await build(current);\n const verified = await verifyFusedDocument(built.document, this.#packages, {\n routeWires: mode === 'content',\n previous: current,\n });\n await this.#authorize(mode, verified.document, current);\n this.#commit(verified, current, mode);\n return built.result;\n });\n }\n\n #commit(verified: IVerifiedFusedDocument, current: FusedDocument, mode: WriteMode): void {\n const next = verified.document;\n const contentChanged = this.#contentKey(next) !== this.#contentKey(current);\n if (mode === 'layout' && contentChanged) {\n throw new FusedSessionError(\n 'edit/layout-mismatch',\n 'A layout transaction must not change devices, connections, labels or references.',\n );\n }\n if (this.#documentKey(next) === this.#documentKey(current)) {\n return;\n }\n this.#past.push({\n before: current,\n after: next,\n contentChanged,\n beforeTopology: this.#topology,\n afterTopology: verified.topology,\n beforeDevices: this.#prepared,\n afterDevices: verified.devices,\n });\n if (this.#past.length > this.#historyLimit) {\n this.#past.shift();\n }\n this.#future = [];\n this.#topology = verified.topology;\n this.#prepared = sameDevices(this.#prepared, verified.devices)\n ? this.#prepared\n : verified.devices;\n this.#preparationError = undefined;\n this.#document = next;\n this.#content.fire(next);\n this.#publishState();\n }\n\n #restore(\n document: FusedDocument,\n devices: ReadonlyMap<string, IPreparedDevice>,\n topology: FusedTopology | undefined,\n ): void {\n this.#document = document;\n this.#prepared = devices;\n this.#topology = topology;\n this.#content.fire(document);\n this.#publishState();\n }\n\n #requireEdit(mode: WriteMode): void {\n this.#requireDecision(mode, this.#decisions);\n }\n\n #requireDecision(mode: WriteMode, decisions: IDocumentAccess): void {\n this.#assertAlive();\n const edit = decisions.edit;\n if (!edit.allowed) {\n throw accessDenied('access/edit-denied', edit);\n }\n if (mode === 'content' && this.#running) {\n throw new FusedSessionError(\n 'access/running',\n 'Devices and connections are read-only while the circuit runs; stop the run first.',\n );\n }\n }\n\n /**\n * Authorizes one mutation against the candidate document.\n *\n * Waits for provider-triggered re-checks, evaluates the policy for the candidate itself, then\n * verifies that every instance and release the candidate introduces may be added. Both checks\n * repeat when the policy changes while they run; nothing is committed before this returns.\n */\n async #authorize(mode: WriteMode, target: FusedDocument, current: FusedDocument): Promise<void> {\n this.#assertAlive();\n for (let pass = 0; pass < 4; pass += 1) {\n await this.#settleAccess();\n const decisions = await this.#evaluate(target);\n if (this.#pendingAccess !== undefined) {\n continue;\n }\n this.#requireDecision(mode, decisions);\n await this.#requireAdditions(current, target);\n if (this.#pendingAccess !== undefined) {\n continue;\n }\n return;\n }\n throw new FusedSessionError(\n 'access/check-failed',\n 'The access policy kept changing while the operation was authorized.',\n );\n }\n\n /**\n * Checks the device-addition policy for every instance and release the target introduces.\n *\n * Generic transactions, undo and redo pass through here as well, so no entry point can introduce\n * a locked release that `canAddDevice` forbids.\n */\n async #requireAdditions(current: FusedDocument, target: FusedDocument): Promise<void> {\n const existingInstances = new Set(current.instances.map((instance) => instance.id));\n const locks = new Map<string, DeviceLock>();\n for (const instance of target.instances) {\n if (existingInstances.has(instance.id)) {\n continue;\n }\n const dependency = target.dependencies[instance.device];\n if (dependency === undefined) {\n continue;\n }\n locks.set(lockKey(instance.device, dependency), {\n id: instance.device,\n version: dependency.version,\n integrity: dependency.integrity,\n });\n }\n for (const [deviceId, dependency] of Object.entries(target.dependencies)) {\n if (current.dependencies[deviceId] !== undefined) {\n continue;\n }\n locks.set(lockKey(deviceId, dependency), {\n id: deviceId,\n version: dependency.version,\n integrity: dependency.integrity,\n });\n }\n for (const lock of locks.values()) {\n await this.#requireCanAddDevice(target, lock);\n }\n }\n\n #requireHistoryStep(entry: IHistoryEntry): void {\n this.#requireEdit(entry.contentChanged ? 'content' : 'layout');\n }\n\n #requireUnchangedLock(document: FusedDocument, lock: DeviceLock): void {\n const existing = document.dependencies[lock.id];\n if (\n existing !== undefined &&\n (existing.version !== lock.version || existing.integrity !== lock.integrity)\n ) {\n throw new FusedSessionError(\n 'document/locked-conflict',\n `\"${lock.id}\" is already locked to ${existing.version}; the document here does not replace an existing lock.`,\n );\n }\n }\n\n async #requireCanAddDevice(document: FusedDocument, device: DeviceLock): Promise<void> {\n let decision: AccessDecision;\n try {\n decision = await this.#access.canAddDevice({\n document,\n device,\n });\n } catch (cause) {\n throw new FusedSessionError(\n 'access/check-failed',\n 'The access policy cannot decide whether this device may be added.',\n { cause },\n );\n }\n const normalized = normalizeDecision(decision, 'device addition');\n if (!normalized.allowed) {\n throw accessDenied('access/add-denied', normalized);\n }\n }\n\n /**\n * Evaluates the access policy for `target`, the document a decision applies to.\n *\n * The returned decisions are the ones the caller must authorize with; the cached state only\n * follows the newest evaluation, so an older, slower answer cannot override a newer one.\n */\n async #evaluate(target: FusedDocument = this.#document): Promise<IDocumentAccess> {\n this.#assertAlive();\n const revision = (this.#evaluationRevision += 1);\n let decisions: IDocumentAccess;\n try {\n decisions = await evaluateDecisions(this.#access, target);\n } catch (cause) {\n if (revision > this.#appliedRevision) {\n this.#appliedRevision = revision;\n // Fail closed: a policy that cannot decide grants nothing until the next successful refresh.\n const message = 'The access policy could not evaluate this document.';\n this.#decisions = {\n edit: denied('access/check-failed', message),\n run: denied('access/check-failed', message),\n };\n this.#publishState();\n }\n throw cause;\n }\n if (revision > this.#appliedRevision) {\n this.#appliedRevision = revision;\n this.#decisions = decisions;\n }\n return decisions;\n }\n\n /**\n * Starts the re-check a provider change demands, outside the write queue.\n *\n * Writes wait for it through {@link #settleAccess}; its failure is reported and already left in\n * the fail-closed decisions.\n */\n #refreshAccessInBackground(): void {\n if (this.#disposed) {\n return;\n }\n const pending = this.#evaluate().then(() => {\n this.#publishState();\n });\n const tracked = pending.finally(() => {\n if (this.#pendingAccess === tracked) {\n this.#pendingAccess = undefined;\n }\n });\n this.#pendingAccess = tracked;\n void tracked.catch((cause: unknown) => {\n const error = toSessionError(cause, 'access/check-failed');\n if (!this.#disposed && error.code !== 'session/disposed') {\n this.#errors.fire(error);\n }\n });\n }\n\n /** Waits until no provider-triggered re-check is in flight. */\n async #settleAccess(): Promise<void> {\n for (let pass = 0; pass < 8; pass += 1) {\n const pending = this.#pendingAccess;\n if (pending === undefined) {\n return;\n }\n try {\n await pending;\n } catch {\n // Reported by the refresh; the decisions are already fail-closed.\n }\n if (this.#pendingAccess === pending) {\n this.#pendingAccess = undefined;\n return;\n }\n }\n }\n\n #publishState(): void {\n if (this.#disposed) {\n return;\n }\n const signature = this.#stateSignature();\n if (signature === this.#lastStateSignature) {\n return;\n }\n this.#lastStateSignature = signature;\n this.#state.fire(this.getState());\n }\n\n #stateSignature(): string {\n const state = this.getState();\n return JSON.stringify([\n state.canUndo,\n state.canRedo,\n state.dirty,\n state.readOnly,\n state.running,\n state.access.edit.allowed,\n state.access.edit.allowed ? '' : state.access.edit.code,\n state.access.run.allowed,\n state.access.run.allowed ? '' : state.access.run.code,\n ]);\n }\n\n #documentKey(document: FusedDocument): string {\n let key = this.#keys.get(document);\n if (key === undefined) {\n key = canonicalJson(document);\n this.#keys.set(document, key);\n }\n return key;\n }\n\n #contentKey(document: FusedDocument): string {\n let key = this.#contentKeys.get(document);\n if (key === undefined) {\n key = canonicalJson({\n ...document,\n instances: document.instances.map(({ viewLayout, ...rest }) => {\n void viewLayout;\n return rest;\n }),\n });\n this.#contentKeys.set(document, key);\n }\n return key;\n }\n\n #enqueue<T>(run: () => Promise<T>): Promise<T> {\n const result = this.#queue.then(async () => {\n this.#assertAlive();\n try {\n return await run();\n } catch (cause) {\n const error = toSessionError(cause, 'edit/invalid-document');\n if (!this.#disposed && error.code !== 'session/disposed') {\n this.#errors.fire(error);\n }\n throw error;\n }\n });\n this.#queue = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n #assertAlive(): void {\n if (this.#disposed) {\n throw new FusedSessionError('session/disposed', 'The document session is disposed.');\n }\n }\n}\n\n/** Serializes the document for writing: readable strict JSON with a trailing newline. */\nexport function serializeFusedDocument(document: FusedDocument): string {\n return `${JSON.stringify(document, null, 2)}\\n`;\n}\n\nasync function evaluateDecisions(\n access: IWorkbenchAccessProvider,\n document: FusedDocument,\n): Promise<IDocumentAccess> {\n let decisions: IDocumentAccess | undefined;\n try {\n decisions = await access.evaluateDocument({ document });\n } catch (cause) {\n throw new FusedSessionError(\n 'access/check-failed',\n 'The access policy cannot evaluate this document.',\n { cause },\n );\n }\n return {\n edit: normalizeDecision(decisions?.edit, 'edit'),\n run: normalizeDecision(decisions?.run, 'run'),\n };\n}\n\nfunction normalizeDecision(decision: AccessDecision | undefined, label: string): AccessDecision {\n if (decision === undefined || decision === null || typeof decision !== 'object') {\n return denied('access/unavailable', `The access policy returned no ${label} decision.`);\n }\n if (decision.allowed === true) {\n return { allowed: true };\n }\n if (typeof decision.code === 'string' && typeof decision.message === 'string') {\n return { allowed: false, code: decision.code, message: decision.message };\n }\n return denied(\n 'access/invalid-decision',\n `The access policy returned a malformed ${label} decision.`,\n );\n}\n\nfunction denied(code: string, message: string): DeniedDecision {\n return { allowed: false, code, message };\n}\n\n/** Identity of one locked release inside a document's dependency table. */\nfunction lockKey(\n deviceId: string,\n dependency: { readonly version: string; readonly integrity: string },\n): string {\n return `${deviceId}@${dependency.version}#${dependency.integrity}`;\n}\n\n/** Keeps the prepared-device map identity while every entry is the same verified object. */\nfunction sameDevices(\n previous: ReadonlyMap<string, IPreparedDevice>,\n next: ReadonlyMap<string, IPreparedDevice>,\n): boolean {\n if (previous === next) {\n return true;\n }\n if (previous.size !== next.size) {\n return false;\n }\n for (const [deviceId, device] of previous) {\n if (next.get(deviceId) !== device) {\n return false;\n }\n }\n return true;\n}\n\nfunction canonicalJson(value: unknown): string {\n if (value === null || typeof value === 'boolean' || typeof value === 'number') {\n return JSON.stringify(value) ?? 'null';\n }\n if (typeof value === 'string') {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map((item) => canonicalJson(item)).join(',')}]`;\n }\n const record = value as Record<string, unknown>;\n const members = Object.keys(record)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`);\n return `{${members.join(',')}}`;\n}\n","import type { ICondition, IContextKeyService } from '../context';\nimport type {\n IWorkbenchContributions,\n IWorkbenchToolbarItem,\n IWorkbenchView,\n IWorkbenchViewContainer,\n} from '../types';\n\ntype Contribution = IWorkbenchViewContainer | IWorkbenchView | IWorkbenchToolbarItem;\n\nexport class ContributionRegistry {\n readonly containers: readonly IWorkbenchViewContainer[];\n readonly views: readonly IWorkbenchView[];\n readonly toolbar: readonly IWorkbenchToolbarItem[];\n readonly #conditions = new Map<string, ICondition>();\n readonly #context: IContextKeyService;\n\n constructor(\n context: IContextKeyService,\n builtin: IWorkbenchContributions,\n host: IWorkbenchContributions = {},\n ) {\n this.#context = context;\n const ids = new Set<string>();\n const collect = <T extends Contribution>(\n defaults: readonly T[] = [],\n additions: readonly T[] = [],\n ): readonly T[] => {\n for (const item of additions)\n if (item.id.startsWith('mica.')) throw new Error(`Reserved contribution ID: ${item.id}`);\n return Object.freeze(\n [...defaults, ...additions]\n .map((item) => {\n if (!/^[A-Za-z][A-Za-z0-9_-]*(?:\\.[A-Za-z0-9_-]+)+$/.test(item.id))\n throw new Error(`Contribution IDs must be namespaced: ${item.id}`);\n if (ids.has(item.id)) throw new Error(`Duplicate contribution ID: ${item.id}`);\n if (!item.title.trim()) throw new Error(`Missing contribution title: ${item.id}`);\n if (item.order !== undefined && !Number.isFinite(item.order))\n throw new Error(`Invalid contribution order: ${item.id}`);\n ids.add(item.id);\n if (item.when !== undefined)\n this.#conditions.set(`${item.id}:when`, context.compile(item.when));\n if ('enablement' in item && typeof item.enablement === 'string')\n this.#conditions.set(`${item.id}:enablement`, context.compile(item.enablement));\n const copy: T = { ...item };\n Object.freeze(copy);\n return copy;\n })\n .sort((a, b) => (a.order ?? 0) - (b.order ?? 0) || a.id.localeCompare(b.id)),\n );\n };\n this.containers = collect(builtin.containers, host.containers);\n this.views = collect(builtin.views, host.views);\n this.toolbar = Object.freeze(\n [...collect(builtin.toolbar, host.toolbar)].sort(\n (a, b) =>\n (a.group ?? '').localeCompare(b.group ?? '') ||\n (a.order ?? 0) - (b.order ?? 0) ||\n a.id.localeCompare(b.id),\n ),\n );\n for (const item of this.containers)\n if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(item.icon))\n throw new Error(`Invalid container icon: ${item.id}`);\n for (const view of this.views)\n if (!this.containers.some((container) => container.id === view.containerId))\n throw new Error(`Unknown view container ${view.containerId} for ${view.id}`);\n for (const view of this.views)\n if (typeof view.mount !== 'function') throw new Error(`Missing view mount: ${view.id}`);\n for (const item of this.toolbar) {\n if (typeof item.execute !== 'function')\n throw new Error(`Missing toolbar execute: ${item.id}`);\n if (item.icon !== undefined && !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(item.icon))\n throw new Error(`Invalid toolbar icon: ${item.id}`);\n }\n }\n\n visible(item: Contribution, context = this.#context): boolean {\n const condition = this.#conditions.get(`${item.id}:when`);\n return condition === undefined || context.evaluate(condition);\n }\n\n enabled(item: IWorkbenchToolbarItem, context = this.#context): boolean {\n const condition = this.#conditions.get(`${item.id}:enablement`);\n return condition === undefined || context.evaluate(condition);\n }\n\n affected(names: ReadonlySet<string>): boolean {\n return [...this.#conditions.values()].some((condition) =>\n [...condition.keys].some((key) => names.has(key)),\n );\n }\n}\n","import type { InstanceViewLayout, UnifiedDeviceManifest } from '@mica-js/document/fused';\n\nexport function resolveViewLayout(\n saved: InstanceViewLayout | undefined,\n manifest: UnifiedDeviceManifest,\n availableHeight: number,\n): InstanceViewLayout {\n const declared = Object.entries(manifest.view ?? {});\n const height = Math.max(120, Math.floor((availableHeight - 240) / Math.max(1, declared.length)));\n const views = declared.map(\n ([viewId, view]) =>\n saved?.views.find((entry) => entry.viewId === viewId) ?? {\n viewId,\n location: view.defaultLocation ?? 'sidebar',\n height,\n collapsed: false,\n },\n );\n if (saved !== undefined)\n views.sort((a, b) => {\n const index = (id: string) => {\n const found = saved.views.findIndex((entry) => entry.viewId === id);\n return found < 0 ? saved.views.length + declared.findIndex(([name]) => name === id) : found;\n };\n return index(a.viewId) - index(b.viewId);\n });\n return { properties: saved?.properties ?? { height: 200, collapsed: false }, views };\n}\n","import type { IWorkbenchViewContainer } from '../types';\n\nexport function Icon({ name }: { readonly name: string }) {\n return <span aria-hidden=\"true\" className={`codicon codicon-${name}`} />;\n}\n\nexport function ActivityBarPart(props: {\n readonly containers: readonly IWorkbenchViewContainer[];\n readonly active: string | undefined;\n readonly problemCount: number;\n readonly onActivate: (id: string) => void;\n}) {\n return (\n <nav className=\"mica-wb-activity-bar\" aria-label=\"工作台视图\">\n {props.containers.map((container) => (\n <button\n key={container.id}\n title={container.title}\n aria-label={container.title}\n aria-pressed={props.active === container.id}\n className={props.active === container.id ? 'is-active' : ''}\n onClick={() => props.onActivate(container.id)}\n >\n <Icon name={container.icon} />\n {container.id === 'mica.problems' && props.problemCount > 0 && (\n <span className=\"mica-wb-badge\">{props.problemCount}</span>\n )}\n </button>\n ))}\n </nav>\n );\n}\n","import type { FusedDocument, Point2D } from '@mica-js/document/fused';\nimport type { IWorkbenchTarget, WorkbenchMode } from '../types';\nimport {\n designatorPosition,\n endpointPosition,\n labelBounds,\n localToScene,\n referenceSymbolBounds,\n type ICanvasDevice,\n type IViewport,\n} from './geometry';\nimport type { WorkbenchThemeColors } from '../theme';\nimport { moveReference, moveWireSegment, orthogonalPath, routeDocumentWires } from '../wiring';\nimport { setTextOffset, type IFusedTextTarget } from '../document/edits';\n\nexport interface IRenderState {\n readonly document: FusedDocument;\n readonly devices: ReadonlyMap<string, ICanvasDevice>;\n readonly images: ReadonlyMap<string, CanvasImageSource>;\n readonly overlays: ReadonlyMap<string, ImageBitmap>;\n readonly viewport: IViewport;\n readonly mode: WorkbenchMode;\n readonly selection: readonly IWorkbenchTarget[];\n readonly preview?: {\n readonly from: Point2D;\n readonly bends: readonly Point2D[];\n readonly to: Point2D;\n };\n readonly drag?: { readonly instanceId: string; readonly position: Point2D };\n readonly wireDrag?: {\n readonly wireId: string;\n readonly segment: number;\n readonly delta: Point2D;\n };\n readonly textDrag?: { readonly target: IFusedTextTarget; readonly offset: Point2D };\n readonly referenceDrag?: { readonly referenceId: string; readonly position: Point2D };\n readonly ghost?: {\n readonly device: string;\n readonly position: Point2D;\n readonly rotation: number;\n };\n readonly annotation?: {\n readonly kind: 'power' | 'ground' | 'label';\n readonly position: Point2D;\n readonly name: string;\n readonly rotation: number;\n };\n readonly colors: WorkbenchThemeColors;\n}\n\nexport function drawCanvas(\n canvas: HTMLCanvasElement,\n width: number,\n height: number,\n state: IRenderState,\n): void {\n const context = canvas.getContext('2d');\n if (context === null) throw new Error('Canvas2D is not available');\n const ratio = globalThis.devicePixelRatio || 1;\n const bitmapWidth = Math.max(1, Math.round(width * ratio));\n const bitmapHeight = Math.max(1, Math.round(height * ratio));\n if (canvas.width !== bitmapWidth) canvas.width = bitmapWidth;\n if (canvas.height !== bitmapHeight) canvas.height = bitmapHeight;\n context.setTransform(ratio, 0, 0, ratio, 0, 0);\n context.fillStyle = state.colors['canvas.background'];\n context.fillRect(0, 0, width, height);\n const { scale, x, y } = state.viewport;\n context.translate(x, y);\n context.scale(scale, scale);\n const ink = state.colors['canvas.foreground'];\n context.lineWidth = 1 / scale;\n if (state.mode === 'edit') {\n let grid = 1;\n while (grid * scale < 10) grid *= 5;\n context.fillStyle = state.colors['canvas.grid'];\n for (let gx = Math.floor(-x / scale / grid) * grid; gx < (width - x) / scale; gx += grid)\n for (let gy = Math.floor(-y / scale / grid) * grid; gy < (height - y) / scale; gy += grid)\n context.fillRect(gx, gy, 1 / scale, 1 / scale);\n }\n let document =\n state.drag === undefined\n ? state.document\n : routeDocumentWires(\n {\n ...state.document,\n instances: state.document.instances.map((instance) =>\n instance.id === state.drag?.instanceId\n ? { ...instance, placement: { ...instance.placement, ...state.drag.position } }\n : instance,\n ),\n },\n state.devices,\n state.document,\n );\n if (state.wireDrag !== undefined)\n document = moveWireSegment(\n document,\n state.devices,\n state.wireDrag.wireId,\n state.wireDrag.segment,\n state.wireDrag.delta,\n );\n if (state.textDrag !== undefined)\n document = setTextOffset(document, state.textDrag.target, state.textDrag.offset);\n if (state.referenceDrag !== undefined) {\n let previewId = 0;\n document = moveReference(\n document,\n state.devices,\n state.referenceDrag.referenceId,\n state.referenceDrag.position,\n () => `__reference_drag_${previewId++}__`,\n );\n }\n const stroke = (points: readonly Point2D[]): void => {\n context.beginPath();\n points.forEach((point, index) => {\n if (index === 0) context.moveTo(point.x, point.y);\n else context.lineTo(point.x, point.y);\n });\n context.stroke();\n };\n if (state.mode === 'edit') {\n for (const wire of document.wires) {\n context.strokeStyle = state.selection.some(\n (target) => target.kind === 'wire' && target.id === wire.id,\n )\n ? state.colors['canvas.selection']\n : state.colors['canvas.wire'];\n context.lineWidth =\n (state.selection.some((target) => target.id === wire.id) ? 2.5 : 1.5) / scale;\n stroke(\n orthogonalPath([\n endpointPosition(document, state.devices, wire.from),\n ...wire.bends,\n endpointPosition(document, state.devices, wire.to),\n ]),\n );\n }\n context.fillStyle = ink;\n for (const node of document.nodes) {\n context.beginPath();\n context.arc(node.x, node.y, (node.kind === 'junction' ? 3 : 2) / scale, 0, Math.PI * 2);\n context.fill();\n }\n context.lineWidth = 1.5 / scale;\n context.strokeStyle = state.colors['canvas.pin'];\n if (state.preview !== undefined) {\n context.setLineDash([5 / scale, 4 / scale]);\n stroke(orthogonalPath([state.preview.from, ...state.preview.bends, state.preview.to]));\n context.setLineDash([]);\n }\n }\n const instances =\n state.ghost === undefined\n ? document.instances\n : [\n ...document.instances,\n {\n id: '__preview__',\n device: state.ghost.device,\n placement: { ...state.ghost.position, rotation: state.ghost.rotation },\n },\n ];\n for (const instance of instances) {\n const device = state.devices.get(instance.device);\n if (device === undefined) continue;\n const geometry = device.geometry;\n const bounds = geometry.bounds;\n const body =\n state.mode === 'edit' || (instance.display?.body ?? document.display?.body ?? true);\n const overlay = state.overlays.get(instance.id);\n if (!body && overlay === undefined) continue;\n context.save();\n if (instance.id === '__preview__') context.globalAlpha = 0.5;\n context.translate(instance.placement.x, instance.placement.y);\n context.rotate((instance.placement.rotation * Math.PI) / 180);\n if (geometry.sizing === 'flexible') {\n context.scale(\n (instance.placement.width ?? bounds.width) / bounds.width,\n (instance.placement.height ?? bounds.height) / bounds.height,\n );\n context.translate(-bounds.x, -bounds.y);\n }\n if (body) {\n const image = state.images.get(instance.device);\n if (image !== undefined)\n context.drawImage(image, bounds.x, bounds.y, bounds.width, bounds.height);\n }\n if (overlay !== undefined)\n context.drawImage(overlay, bounds.x, bounds.y, bounds.width, bounds.height);\n if (state.selection.some((target) => target.kind === 'instance' && target.id === instance.id)) {\n context.strokeStyle = state.colors['canvas.selection'];\n context.lineWidth = 1.5 / scale;\n context.setLineDash([4 / scale, 3 / scale]);\n context.strokeRect(\n bounds.x - 3 / scale,\n bounds.y - 3 / scale,\n bounds.width + 6 / scale,\n bounds.height + 6 / scale,\n );\n context.setLineDash([]);\n }\n context.restore();\n if (\n (state.mode === 'edit' || (document.display?.designators ?? true)) &&\n instance.designator !== undefined\n ) {\n const anchor = designatorPosition(instance, geometry);\n context.font = `600 ${11 / scale}px system-ui`;\n context.fillStyle = ink;\n context.fillText(instance.designator, anchor.x, anchor.y - 5 / scale);\n }\n if (state.mode === 'edit') {\n const selected = state.selection.some((target) => target.id === instance.id);\n for (const [id, pin] of Object.entries(geometry.pins)) {\n const point = localToScene(instance, geometry, pin.position);\n context.strokeStyle = state.colors['canvas.pin'];\n context.lineWidth = 1.25 / scale;\n context.beginPath();\n context.arc(point.x, point.y, 2.5 / scale, 0, Math.PI * 2);\n context.stroke();\n if (selected || scale >= 3) {\n context.font = `${10 / scale}px system-ui`;\n context.fillStyle = ink;\n const length = Math.hypot(pin.outward.x, pin.outward.y);\n const label =\n pin.label?.visible === false ? undefined : (device.manifest.pins?.[id]?.label ?? id);\n if (label === undefined) continue;\n if (pin.label?.position !== undefined) {\n const labelPoint = localToScene(instance, geometry, pin.label.position);\n context.textAlign = 'left';\n context.fillText(label, labelPoint.x, labelPoint.y);\n } else {\n const outwardPoint = localToScene(instance, geometry, {\n x: pin.position.x + pin.outward.x / length,\n y: pin.position.y + pin.outward.y / length,\n });\n const dx = outwardPoint.x - point.x;\n const dy = outwardPoint.y - point.y;\n context.textAlign = dx < -0.1 ? 'right' : 'left';\n context.fillText(\n label,\n point.x + (dx * 7) / scale,\n point.y + (dy * 7) / scale + 3 / scale,\n );\n }\n }\n }\n context.textAlign = 'left';\n }\n }\n if (state.mode === 'edit') {\n const annotations: FusedDocument =\n state.annotation === undefined\n ? document\n : {\n ...document,\n nodes: [\n ...document.nodes,\n { id: '__annotation__', kind: 'free', ...state.annotation.position },\n ],\n labels:\n state.annotation.kind === 'label'\n ? [\n ...document.labels,\n {\n id: '__annotation__',\n target: { kind: 'node', node: '__annotation__' },\n name: state.annotation.name,\n },\n ]\n : document.labels,\n references:\n state.annotation.kind === 'label'\n ? document.references\n : [\n ...document.references,\n {\n id: '__annotation__',\n target: { kind: 'node', node: '__annotation__' },\n symbol: state.annotation.kind,\n voltage: state.annotation.kind === 'ground' ? 0 : 5,\n rotation: state.annotation.rotation,\n },\n ],\n };\n context.strokeStyle = ink;\n context.fillStyle = ink;\n context.lineWidth = 0.1;\n context.font = '0.75px system-ui';\n for (const label of annotations.labels) {\n const point = endpointPosition(annotations, state.devices, label.target);\n context.save();\n if (label.id === '__annotation__') context.globalAlpha = 0.5;\n if (state.selection.some((target) => target.kind === 'label' && target.id === label.id)) {\n const bounds = labelBounds(label);\n context.strokeStyle = state.colors['canvas.selection'];\n context.lineWidth = 1.5 / scale;\n context.setLineDash([4 / scale, 3 / scale]);\n context.strokeRect(\n point.x + bounds.x - 3 / scale,\n point.y + bounds.y - 3 / scale,\n bounds.width + 6 / scale,\n bounds.height + 6 / scale,\n );\n context.setLineDash([]);\n }\n context.fillText(\n label.name,\n point.x + (label.offset?.x ?? 0.3),\n point.y + (label.offset?.y ?? -0.35),\n );\n context.restore();\n }\n for (const reference of annotations.references) {\n const point = endpointPosition(annotations, state.devices, reference.target);\n context.save();\n if (reference.id === '__annotation__') context.globalAlpha = 0.5;\n context.translate(point.x, point.y);\n context.rotate(((reference.rotation ?? 0) * Math.PI) / 180);\n if (\n state.selection.some((target) => target.kind === 'reference' && target.id === reference.id)\n ) {\n const bounds = referenceSymbolBounds(reference);\n context.strokeStyle = state.colors['canvas.selection'];\n context.lineWidth = 1.5 / scale;\n context.setLineDash([4 / scale, 3 / scale]);\n context.strokeRect(\n bounds.x - 3 / scale,\n bounds.y - 3 / scale,\n bounds.width + 6 / scale,\n bounds.height + 6 / scale,\n );\n context.setLineDash([]);\n }\n context.strokeStyle = ink;\n context.lineWidth = 0.1;\n const unit = 0.1;\n stroke([\n { x: 0, y: 0 },\n { x: 0, y: -12 * unit },\n ]);\n if (reference.symbol === 'ground') {\n for (let index = 0; index < 3; index++)\n stroke([\n { x: (-7 + index * 2) * unit, y: (-12 - index * 3) * unit },\n { x: (7 - index * 2) * unit, y: (-12 - index * 3) * unit },\n ]);\n } else {\n stroke([\n { x: -5 * unit, y: -8 * unit },\n { x: 0, y: -13 * unit },\n { x: 5 * unit, y: -8 * unit },\n ]);\n }\n if (reference.symbol !== 'ground')\n context.fillText(\n reference.label?.name ?? `${reference.voltage} V`,\n reference.label?.offset?.x ?? 7 * unit,\n reference.label?.offset?.y ?? -14 * unit,\n );\n context.restore();\n }\n }\n}\n","import {\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n type PointerEvent as ReactPointerEvent,\n} from 'react';\nimport type { DeviceLock, Endpoint, FusedDocument, Point2D } from '@mica-js/document/fused';\nimport type { IWorkbenchState, IWorkbenchTarget } from '../types';\nimport {\n contains,\n distanceToSegment,\n endpointPosition,\n fitViewport,\n pickInstance,\n pickAnnotation,\n pickPins,\n pickWireSegment,\n pickText,\n textDragOffset,\n sceneToLocal,\n toScene,\n type ICanvasDevice,\n type IPinHit,\n type IViewport,\n} from '../canvas/geometry';\nimport { drawCanvas } from '../canvas/renderer';\nimport { hasWireConnection, orthogonalPath } from '../wiring';\nimport { projectOnSegment } from '@mica-js/document/schematic';\nimport { readCanvasTheme, type IResolvedWorkbenchTheme } from '../theme';\nimport type { IFusedTextTarget } from '../document/edits';\n\nexport interface ICanvasHandle {\n readonly scale: number;\n fit(): void;\n zoom(factor: number): void;\n reveal(instanceId: string): void;\n}\n\nexport interface IViewInput {\n readonly type: 'pointerdown' | 'pointermove' | 'pointerup';\n readonly position: Point2D;\n readonly button: number;\n readonly buttons: number;\n}\n\nexport interface ICanvasPartProps {\n readonly document: FusedDocument;\n readonly devices: ReadonlyMap<string, ICanvasDevice>;\n readonly images: ReadonlyMap<string, CanvasImageSource>;\n readonly overlays: ReadonlyMap<string, ImageBitmap>;\n readonly state: IWorkbenchState;\n readonly selection: readonly IWorkbenchTarget[];\n readonly placement: DeviceLock | undefined;\n readonly placementRotation: number;\n readonly labelName: string;\n readonly theme: IResolvedWorkbenchTheme;\n readonly frame: number;\n readonly onReady: (handle: ICanvasHandle | undefined) => void;\n readonly onSelection: (selection: readonly IWorkbenchTarget[]) => void;\n readonly onOpenProperties: () => void;\n readonly onPlace: (device: DeviceLock, position: Point2D) => Promise<void>;\n readonly onMove: (instanceId: string, position: Point2D) => Promise<void>;\n readonly onMoveSegment: (wireId: string, segment: number, delta: Point2D) => Promise<void>;\n readonly onMoveText: (target: IFusedTextTarget, offset: Point2D) => Promise<void>;\n readonly onMoveReference: (referenceId: string, position: Point2D) => Promise<void>;\n readonly onStartWire: () => Promise<void>;\n readonly onConnect: (\n from: Endpoint | Point2D,\n to: Endpoint | Point2D,\n bends: readonly Point2D[],\n ) => Promise<void>;\n readonly onEndpoint: (endpoint: Endpoint | Point2D) => Promise<void>;\n readonly onCancel: () => void;\n readonly onDelete: () => Promise<void>;\n readonly onInput: (instanceId: string, input: IViewInput) => void;\n readonly onError: (error: unknown) => void;\n readonly onFocus: (focused: boolean) => void;\n readonly onViewport: () => void;\n readonly children?: React.ReactNode;\n}\n\nexport function CanvasPart(props: ICanvasPartProps) {\n const host = useRef<HTMLDivElement>(null);\n const canvas = useRef<HTMLCanvasElement>(null);\n const [size, setSize] = useState({ width: 1, height: 1 });\n const [viewport, setViewport] = useState<IViewport>({ x: 80, y: 80, scale: 10 });\n const [pointer, setPointer] = useState<Point2D>({ x: 0, y: 0 });\n const [hovered, setHovered] = useState(false);\n const committing = useRef(false);\n const [connection, setConnection] = useState<{\n readonly endpoint: Endpoint | Point2D;\n readonly bends: readonly Point2D[];\n }>();\n const pendingWireStart = useRef<Endpoint | Point2D | undefined>(undefined);\n const [drag, setDrag] = useState<{ readonly instanceId: string; readonly position: Point2D }>();\n const [wireDrag, setWireDrag] = useState<{\n readonly wireId: string;\n readonly segment: number;\n readonly delta: Point2D;\n }>();\n const [textDrag, setTextDrag] = useState<{\n readonly target: IFusedTextTarget;\n readonly offset: Point2D;\n }>();\n const [referenceDrag, setReferenceDrag] = useState<{\n readonly referenceId: string;\n readonly position: Point2D;\n }>();\n const [candidates, setCandidates] = useState<readonly IPinHit[]>([]);\n const gesture = useRef<\n | {\n readonly kind: 'pan' | 'move';\n readonly pointerId: number;\n readonly start: Point2D;\n readonly original: Point2D;\n readonly instanceId?: string;\n }\n | {\n readonly kind: 'wire';\n readonly pointerId: number;\n readonly start: Point2D;\n readonly wireId: string;\n readonly segment: number;\n }\n | {\n readonly kind: 'text';\n readonly pointerId: number;\n readonly start: Point2D;\n readonly target: IFusedTextTarget;\n }\n | {\n readonly kind: 'reference';\n readonly pointerId: number;\n readonly start: Point2D;\n readonly original: Point2D;\n readonly referenceId: string;\n moved: boolean;\n }\n | undefined\n >(undefined);\n const business = useRef<\n | {\n readonly instanceId: string;\n readonly pointerId: number;\n position: Point2D;\n readonly button: number;\n }\n | undefined\n >(undefined);\n const current = useRef(props);\n current.current = props;\n\n const run = (task: Promise<void>) => {\n void task.catch(props.onError);\n };\n const fit = () =>\n setViewport(fitViewport(props.document, props.devices, size.width, size.height));\n const zoom = (factor: number, center: Point2D = { x: size.width / 2, y: size.height / 2 }) => {\n setViewport((value) => {\n const scale = Math.max(0.25, Math.min(100, value.scale * factor));\n return {\n scale,\n x: center.x - ((center.x - value.x) * scale) / value.scale,\n y: center.y - ((center.y - value.y) * scale) / value.scale,\n };\n });\n };\n const currentZoom = useRef(zoom);\n currentZoom.current = zoom;\n useEffect(() => {\n const element = canvas.current;\n if (element === null) return;\n const wheel = (event: WheelEvent) => {\n event.preventDefault();\n const rect = element.getBoundingClientRect();\n currentZoom.current(Math.exp(-event.deltaY * 0.001), {\n x: event.clientX - rect.left,\n y: event.clientY - rect.top,\n });\n };\n element.addEventListener('wheel', wheel, { passive: false });\n return () => element.removeEventListener('wheel', wheel);\n }, []);\n const reveal = (instanceId: string) => {\n const instance = props.document.instances.find((item) => item.id === instanceId);\n if (instance === undefined) throw new Error(`Unknown instance: ${instanceId}`);\n setViewport((value) => ({\n ...value,\n x: size.width / 2 - instance.placement.x * value.scale,\n y: size.height / 2 - instance.placement.y * value.scale,\n }));\n canvas.current?.focus();\n };\n function cancelGesture(): void {\n const active = business.current;\n const pointerId = active?.pointerId ?? gesture.current?.pointerId;\n business.current = undefined;\n gesture.current = undefined;\n setDrag(undefined);\n setWireDrag(undefined);\n setTextDrag(undefined);\n setReferenceDrag(undefined);\n if (active !== undefined)\n current.current.onInput(active.instanceId, {\n type: 'pointerup',\n position: active.position,\n button: active.button,\n buttons: 0,\n });\n if (pointerId !== undefined && canvas.current?.hasPointerCapture(pointerId))\n canvas.current.releasePointerCapture(pointerId);\n }\n useLayoutEffect(() => {\n props.onReady({ fit, zoom, reveal, scale: viewport.scale });\n return () => props.onReady(undefined);\n });\n useEffect(() => props.onViewport(), [viewport.scale]);\n useLayoutEffect(() => {\n const element = host.current;\n if (element === null) return;\n let initialized = false;\n const observer = new ResizeObserver(([entry]) => {\n if (entry === undefined) return;\n const { width, height } = entry.contentRect;\n setSize({ width, height });\n if (!initialized && width > 0 && height > 0) {\n initialized = true;\n setViewport(fitViewport(current.current.document, current.current.devices, width, height));\n }\n });\n observer.observe(element);\n return () => observer.disconnect();\n }, []);\n useEffect(() => {\n const endpoint = pendingWireStart.current;\n pendingWireStart.current = undefined;\n setConnection(\n props.state.mode === 'edit' &&\n !props.state.readOnly &&\n props.state.tool === 'wire' &&\n endpoint !== undefined\n ? { endpoint, bends: [] }\n : undefined,\n );\n setCandidates([]);\n cancelGesture();\n }, [props.state.mode, props.state.tool, props.state.readOnly]);\n useEffect(() => {\n const release = () => cancelGesture();\n window.addEventListener('blur', release);\n return () => window.removeEventListener('blur', release);\n }, []);\n const annotationTool =\n props.state.tool === 'power' || props.state.tool === 'ground' || props.state.tool === 'label'\n ? props.state.tool\n : undefined;\n useEffect(() => {\n if (canvas.current === null) return;\n const frame = requestAnimationFrame(() => {\n if (canvas.current === null) return;\n try {\n drawCanvas(canvas.current, size.width, size.height, {\n document: props.document,\n devices: props.devices,\n images: props.images,\n overlays: props.overlays,\n viewport,\n mode: props.state.mode,\n selection: props.selection,\n colors: readCanvasTheme(canvas.current),\n ...(drag === undefined ? {} : { drag }),\n ...(wireDrag === undefined ? {} : { wireDrag }),\n ...(textDrag === undefined ? {} : { textDrag }),\n ...(referenceDrag === undefined ? {} : { referenceDrag }),\n ...(!hovered || props.placement === undefined\n ? {}\n : {\n ghost: {\n device: props.placement.id,\n position: pointer,\n rotation: props.placementRotation,\n },\n }),\n ...(!hovered ||\n props.state.mode !== 'edit' ||\n props.state.readOnly ||\n annotationTool === undefined\n ? {}\n : {\n annotation: {\n kind: annotationTool,\n position: pointer,\n name: props.labelName,\n rotation: props.placementRotation,\n },\n }),\n ...(connection === undefined\n ? {}\n : {\n preview: {\n from: anchorPoint(connection.endpoint),\n bends: connection.bends,\n to: pointer,\n },\n }),\n });\n } catch (error) {\n props.onError(error);\n }\n });\n return () => cancelAnimationFrame(frame);\n }, [\n props.document,\n props.devices,\n props.images,\n props.overlays,\n props.selection,\n props.state.mode,\n props.theme,\n props.frame,\n props.placement,\n props.placementRotation,\n props.labelName,\n props.state.tool,\n props.state.readOnly,\n hovered,\n viewport,\n size,\n connection,\n pointer,\n drag,\n wireDrag,\n textDrag,\n referenceDrag,\n ]);\n\n function local(\n event: Pick<ReactPointerEvent<HTMLCanvasElement>, 'currentTarget' | 'clientX' | 'clientY'>,\n ): Point2D {\n const rect = event.currentTarget.getBoundingClientRect();\n return { x: event.clientX - rect.left, y: event.clientY - rect.top };\n }\n const snap = (point: Point2D, alt: boolean): Point2D =>\n alt ? point : { x: Math.round(point.x), y: Math.round(point.y) };\n function anchorPoint(anchor: Endpoint | Point2D): Point2D {\n return 'kind' in anchor ? endpointPosition(props.document, props.devices, anchor) : anchor;\n }\n function snappedAnchor(point: Point2D, alt: boolean): Endpoint | Point2D {\n const annotation = pickAnnotation(props.document, props.devices, point, 3 / viewport.scale);\n if (annotation?.kind === 'reference') {\n const reference = props.document.references.find((value) => value.id === annotation.id);\n if (reference !== undefined) return reference.target;\n }\n const pin = pickPins(props.document, props.devices, point, 7 / viewport.scale)[0];\n if (pin !== undefined) return pin.endpoint;\n const node = props.document.nodes.find(\n (value) => Math.hypot(value.x - point.x, value.y - point.y) <= 7 / viewport.scale,\n );\n if (node !== undefined) return { kind: 'node', node: node.id };\n let best: { point: Point2D; distance: number } | undefined;\n for (const wire of props.document.wires) {\n const points = orthogonalPath([\n endpointPosition(props.document, props.devices, wire.from),\n ...wire.bends,\n endpointPosition(props.document, props.devices, wire.to),\n ]);\n for (let index = 1; index < points.length; index++) {\n const from = points[index - 1];\n const to = points[index];\n if (from === undefined || to === undefined) continue;\n const projected = projectOnSegment(point, from, to);\n const distance = Math.hypot(projected.x - point.x, projected.y - point.y);\n if (distance > 7 / viewport.scale || (best !== undefined && distance >= best.distance))\n continue;\n const grid = snap(projected, alt);\n const onAxis = from.x === to.x ? { x: from.x, y: grid.y } : { x: grid.x, y: from.y };\n best = { point: projectOnSegment(onAxis, from, to), distance };\n }\n }\n return best?.point ?? snap(point, alt);\n }\n function commit(action: () => Promise<void>): void {\n if (committing.current) return;\n committing.current = true;\n void action()\n .catch(props.onError)\n .finally(() => {\n committing.current = false;\n });\n }\n function useEndpoint(endpoint: Endpoint | Point2D) {\n setCandidates([]);\n if (props.state.tool === 'select') {\n if ('kind' in endpoint)\n props.onSelection([\n endpoint.kind === 'pin'\n ? { kind: 'instance', id: endpoint.instance }\n : { kind: 'node', id: endpoint.node },\n ]);\n startWire(endpoint);\n return;\n }\n if (props.state.tool !== 'wire') {\n commit(() => props.onEndpoint(endpoint));\n return;\n }\n if (connection === undefined) setConnection({ endpoint, bends: [] });\n else {\n commit(async () => {\n await props.onConnect(connection.endpoint, endpoint, connection.bends);\n setConnection(undefined);\n props.onCancel();\n });\n }\n }\n function startWire(endpoint: Endpoint | Point2D): void {\n if (props.state.readOnly || props.state.mode !== 'edit') return;\n if ('kind' in endpoint && hasWireConnection(props.document, endpoint)) return;\n if (props.state.tool === 'wire') {\n setConnection({ endpoint, bends: [] });\n return;\n }\n pendingWireStart.current = endpoint;\n commit(async () => {\n try {\n await props.onStartWire();\n } catch (error) {\n pendingWireStart.current = undefined;\n throw error;\n }\n });\n }\n function input(event: ReactPointerEvent<HTMLCanvasElement>, type: IViewInput['type']): void {\n const active = business.current;\n if (active === undefined || active.pointerId !== event.pointerId) return;\n const instance = props.document.instances.find((value) => value.id === active.instanceId);\n const geometry =\n instance === undefined ? undefined : props.devices.get(instance.device)?.geometry;\n if (instance === undefined || geometry === undefined) return;\n active.position = sceneToLocal(instance, geometry, toScene(local(event), viewport));\n props.onInput(instance.id, {\n type,\n position: active.position,\n button: active.button,\n buttons: type === 'pointerup' ? 0 : event.buttons,\n });\n }\n return (\n <div className=\"mica-wb-canvas-part\" ref={host}>\n <canvas\n ref={canvas}\n tabIndex={0}\n aria-label=\"电路画布\"\n className={`mica-wb-canvas mica-wb-tool-${props.state.tool}`}\n onFocus={() => props.onFocus(true)}\n onBlur={() => {\n cancelGesture();\n props.onFocus(false);\n }}\n onContextMenu={(event) => {\n event.preventDefault();\n setConnection(undefined);\n props.onCancel();\n }}\n onKeyDown={(event) => {\n if (event.key === 'Escape') {\n setConnection(undefined);\n setCandidates([]);\n cancelGesture();\n props.onCancel();\n }\n if (\n (event.key === 'Delete' || event.key === 'Backspace') &&\n !props.state.readOnly &&\n props.state.mode === 'edit'\n ) {\n event.preventDefault();\n setConnection(undefined);\n setCandidates([]);\n cancelGesture();\n props.onCancel();\n run(props.onDelete());\n }\n }}\n onPointerDown={(event) => {\n if (gesture.current !== undefined || business.current !== undefined) return;\n event.currentTarget.focus();\n const screen = local(event);\n const point = toScene(screen, viewport);\n if (event.button === 1) {\n gesture.current = {\n kind: 'pan',\n pointerId: event.pointerId,\n start: screen,\n original: { x: viewport.x, y: viewport.y },\n };\n event.currentTarget.setPointerCapture(event.pointerId);\n event.preventDefault();\n return;\n }\n if (event.button !== 0 || props.state.busy || committing.current) return;\n if (props.state.mode === 'run') {\n const instance = pickInstance(\n props.document,\n props.devices,\n point,\n (value) =>\n props.overlays.has(value.id) ||\n ((value.display?.body ?? props.document.display?.body ?? true) &&\n props.images.has(value.device)),\n );\n if (instance === undefined) return;\n const geometry = props.devices.get(instance.device)?.geometry;\n if (\n geometry === undefined ||\n !contains(geometry.bounds, sceneToLocal(instance, geometry, point))\n )\n return;\n props.onSelection([{ kind: 'instance', id: instance.id }]);\n business.current = {\n instanceId: instance.id,\n pointerId: event.pointerId,\n position: sceneToLocal(instance, geometry, point),\n button: event.button,\n };\n event.currentTarget.setPointerCapture(event.pointerId);\n input(event, 'pointerdown');\n return;\n }\n const placing = props.placement;\n if (placing !== undefined && !props.state.readOnly) {\n commit(() => props.onPlace(placing, snap(point, event.altKey)));\n return;\n }\n if (props.state.tool !== 'select' && !props.state.readOnly) {\n if (props.state.tool === 'wire') {\n const annotation = pickAnnotation(\n props.document,\n props.devices,\n point,\n 3 / viewport.scale,\n );\n if (annotation?.kind === 'reference') {\n const reference = props.document.references.find(\n (value) => value.id === annotation.id,\n );\n if (reference !== undefined) {\n useEndpoint(reference.target);\n return;\n }\n }\n }\n const pins = pickPins(props.document, props.devices, point, 7 / viewport.scale);\n if (pins.length > 1) {\n setCandidates(pins);\n return;\n }\n if (pins[0] !== undefined) {\n useEndpoint(pins[0].endpoint);\n return;\n }\n const node = props.document.nodes.find(\n (value) => Math.hypot(value.x - point.x, value.y - point.y) <= 7 / viewport.scale,\n );\n if (node !== undefined) {\n useEndpoint({ kind: 'node', node: node.id });\n return;\n }\n const anchor = snappedAnchor(point, event.altKey);\n if (props.state.tool !== 'wire') useEndpoint(anchor);\n else if (\n 'kind' in anchor ||\n props.document.wires.some((wire) => {\n const points = [\n endpointPosition(props.document, props.devices, wire.from),\n ...wire.bends,\n endpointPosition(props.document, props.devices, wire.to),\n ];\n return points.some(\n (value, index) =>\n index > 0 &&\n distanceToSegment(anchorPoint(anchor), points[index - 1] ?? value, value) <\n 1e-8,\n );\n })\n )\n useEndpoint(anchor);\n else if (connection === undefined) setConnection({ endpoint: anchor, bends: [] });\n else\n setConnection({\n ...connection,\n bends: orthogonalPath([\n anchorPoint(connection.endpoint),\n ...connection.bends,\n anchorPoint(anchor),\n ]).slice(1),\n });\n return;\n }\n const text = pickText(props.document, props.devices, point, viewport.scale);\n if (text !== undefined) {\n const target: IWorkbenchTarget = {\n kind: text.kind === 'designator' ? 'instance' : text.kind,\n id: text.id,\n };\n props.onSelection(\n event.shiftKey\n ? [...props.selection.filter((value) => value.id !== target.id), target]\n : [target],\n );\n if (!props.state.readOnly) {\n gesture.current = {\n kind: 'text',\n pointerId: event.pointerId,\n start: point,\n target: text,\n };\n event.currentTarget.setPointerCapture(event.pointerId);\n }\n return;\n }\n const annotation = pickAnnotation(\n props.document,\n props.devices,\n point,\n 3 / viewport.scale,\n );\n if (annotation !== undefined) {\n props.onSelection(\n event.shiftKey\n ? [...props.selection.filter((value) => value.id !== annotation.id), annotation]\n : [annotation],\n );\n if (annotation.kind === 'reference' && !props.state.readOnly) {\n const reference = props.document.references.find(\n (value) => value.id === annotation.id,\n );\n if (reference !== undefined) {\n gesture.current = {\n kind: 'reference',\n pointerId: event.pointerId,\n start: point,\n original: endpointPosition(props.document, props.devices, reference.target),\n referenceId: reference.id,\n moved: false,\n };\n event.currentTarget.setPointerCapture(event.pointerId);\n }\n }\n return;\n }\n if (!props.state.readOnly) {\n const pins = pickPins(props.document, props.devices, point, 7 / viewport.scale);\n if (pins.length > 1) {\n setCandidates(pins);\n return;\n }\n if (pins[0] !== undefined) {\n useEndpoint(pins[0].endpoint);\n return;\n }\n const node = props.document.nodes.find(\n (value) => Math.hypot(value.x - point.x, value.y - point.y) <= 7 / viewport.scale,\n );\n if (node !== undefined) {\n useEndpoint({ kind: 'node', node: node.id });\n return;\n }\n }\n const instance = pickInstance(props.document, props.devices, point);\n if (instance !== undefined) {\n const target: IWorkbenchTarget = { kind: 'instance', id: instance.id };\n props.onSelection(\n event.shiftKey\n ? [...props.selection.filter((value) => value.id !== instance.id), target]\n : [target],\n );\n if (!props.state.readOnly && !props.state.busy) {\n gesture.current = {\n kind: 'move',\n pointerId: event.pointerId,\n start: point,\n original: instance.placement,\n instanceId: instance.id,\n };\n event.currentTarget.setPointerCapture(event.pointerId);\n }\n return;\n }\n const wire = pickWireSegment(props.document, props.devices, point, 6 / viewport.scale);\n props.onSelection(wire === undefined ? [] : [{ kind: 'wire', id: wire.wireId }]);\n if (wire !== undefined && !props.state.readOnly) {\n gesture.current = {\n kind: 'wire',\n pointerId: event.pointerId,\n start: point,\n wireId: wire.wireId,\n segment: wire.segment,\n };\n event.currentTarget.setPointerCapture(event.pointerId);\n }\n }}\n onDoubleClick={(event) => {\n if (props.state.mode !== 'edit' || props.state.busy || props.placement !== undefined)\n return;\n if (props.state.tool === 'wire') {\n if (connection !== undefined)\n useEndpoint(snappedAnchor(toScene(local(event), viewport), event.altKey));\n return;\n }\n const instance = pickInstance(\n props.document,\n props.devices,\n toScene(local(event), viewport),\n );\n if (instance === undefined) return;\n props.onSelection([{ kind: 'instance', id: instance.id }]);\n props.onOpenProperties();\n }}\n onPointerMove={(event) => {\n const point = toScene(local(event), viewport);\n setPointer(\n props.placement !== undefined || props.state.tool === 'select'\n ? snap(point, event.altKey)\n : anchorPoint(snappedAnchor(point, event.altKey)),\n );\n if (business.current !== undefined) {\n input(event, 'pointermove');\n return;\n }\n const active = gesture.current;\n if (active !== undefined && active.pointerId !== event.pointerId) return;\n if (active?.kind === 'pan') {\n const screen = local(event);\n setViewport({\n ...viewport,\n x: active.original.x + screen.x - active.start.x,\n y: active.original.y + screen.y - active.start.y,\n });\n } else if (active?.kind === 'move' && active.instanceId !== undefined) {\n setDrag({\n instanceId: active.instanceId,\n position: snap(\n {\n x: active.original.x + point.x - active.start.x,\n y: active.original.y + point.y - active.start.y,\n },\n event.altKey,\n ),\n });\n } else if (active?.kind === 'wire') {\n setWireDrag({\n wireId: active.wireId,\n segment: active.segment,\n delta: snap(\n { x: point.x - active.start.x, y: point.y - active.start.y },\n event.altKey,\n ),\n });\n } else if (active?.kind === 'text') {\n const delta = snap(\n { x: point.x - active.start.x, y: point.y - active.start.y },\n event.altKey,\n );\n setTextDrag({\n target: active.target,\n offset: textDragOffset(props.document, props.devices, active.target, delta),\n });\n } else if (active?.kind === 'reference') {\n if (\n Math.hypot(point.x - active.start.x, point.y - active.start.y) * viewport.scale >=\n 3\n )\n active.moved = true;\n if (active.moved)\n setReferenceDrag({\n referenceId: active.referenceId,\n position: snap(\n {\n x: active.original.x + point.x - active.start.x,\n y: active.original.y + point.y - active.start.y,\n },\n event.altKey,\n ),\n });\n }\n }}\n onPointerUp={(event) => {\n if (business.current?.pointerId === event.pointerId) {\n input(event, 'pointerup');\n business.current = undefined;\n }\n const active = gesture.current;\n if (active !== undefined && active.pointerId !== event.pointerId) return;\n if (active?.kind === 'move' && active.instanceId !== undefined) {\n const point = toScene(local(event), viewport);\n const position = snap(\n {\n x: active.original.x + point.x - active.start.x,\n y: active.original.y + point.y - active.start.y,\n },\n event.altKey,\n );\n if (position.x !== active.original.x || position.y !== active.original.y)\n run(props.onMove(active.instanceId, position));\n } else if (active?.kind === 'wire') {\n const point = toScene(local(event), viewport);\n const delta = snap(\n { x: point.x - active.start.x, y: point.y - active.start.y },\n event.altKey,\n );\n if (delta.x !== 0 || delta.y !== 0)\n commit(() => props.onMoveSegment(active.wireId, active.segment, delta));\n } else if (active?.kind === 'text') {\n const point = toScene(local(event), viewport);\n const delta = snap(\n { x: point.x - active.start.x, y: point.y - active.start.y },\n event.altKey,\n );\n if (delta.x !== 0 || delta.y !== 0)\n commit(() =>\n props.onMoveText(\n active.target,\n textDragOffset(props.document, props.devices, active.target, delta),\n ),\n );\n else if (active.target.kind === 'reference') {\n const reference = props.document.references.find(\n (value) => value.id === active.target.id,\n );\n if (reference !== undefined) startWire(reference.target);\n }\n } else if (active?.kind === 'reference') {\n if (active.moved) {\n const point = toScene(local(event), viewport);\n const position = snap(\n {\n x: active.original.x + point.x - active.start.x,\n y: active.original.y + point.y - active.start.y,\n },\n event.altKey,\n );\n if (position.x !== active.original.x || position.y !== active.original.y)\n commit(() => props.onMoveReference(active.referenceId, position));\n } else {\n const reference = props.document.references.find(\n (value) => value.id === active.referenceId,\n );\n if (reference !== undefined) startWire(reference.target);\n }\n }\n gesture.current = undefined;\n setDrag(undefined);\n setWireDrag(undefined);\n setTextDrag(undefined);\n setReferenceDrag(undefined);\n if (event.currentTarget.hasPointerCapture(event.pointerId))\n event.currentTarget.releasePointerCapture(event.pointerId);\n }}\n onPointerEnter={() => setHovered(true)}\n onPointerLeave={() => setHovered(false)}\n onPointerCancel={(event) => {\n if (\n business.current?.pointerId === event.pointerId ||\n gesture.current?.pointerId === event.pointerId\n )\n cancelGesture();\n }}\n onLostPointerCapture={(event) => {\n if (\n business.current?.pointerId === event.pointerId ||\n gesture.current?.pointerId === event.pointerId\n )\n cancelGesture();\n }}\n />\n {candidates.length > 0 && (\n <div className=\"mica-wb-pin-candidates\" role=\"dialog\" aria-label=\"选择引脚\">\n {candidates.map((value) => (\n <button key={value.title} onClick={() => useEndpoint(value.endpoint)}>\n {value.title}\n </button>\n ))}\n <button onClick={() => setCandidates([])}>取消</button>\n </div>\n )}\n <div className=\"mica-wb-viewport-controls\" aria-label=\"视口控制\">\n <button title=\"缩小\" aria-label=\"缩小\" onClick={() => zoom(1 / 1.2)}>\n −\n </button>\n <span>{Math.round(viewport.scale * 10)}%</span>\n <button title=\"放大\" aria-label=\"放大\" onClick={() => zoom(1.2)}>\n +\n </button>\n <button title=\"适应画布\" aria-label=\"适应画布\" onClick={fit}>\n 适应\n </button>\n </div>\n {props.children}\n </div>\n );\n}\n","import { useEffect, useRef, useState } from 'react';\nimport type { Disposable } from '@mica-js/core/lifecycle';\nimport type {\n IWorkbenchDiagnostic,\n IWorkbenchExtensionContext,\n IWorkbenchView,\n IWorkbenchViewContainer,\n} from '../types';\nimport { Icon } from './activity-bar-part';\n\nfunction ContributedView(props: {\n readonly hideHeader: boolean;\n readonly view: IWorkbenchView;\n readonly context: IWorkbenchExtensionContext;\n readonly report: (diagnostic: IWorkbenchDiagnostic) => void;\n}) {\n const element = useRef<HTMLDivElement>(null);\n const [error, setError] = useState<string>();\n useEffect(() => {\n const target = element.current;\n if (target === null) return;\n const abort = new AbortController();\n const scope = props.context.contextKeys.createScope();\n let result: Disposable | undefined;\n const fail = (error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n if (!abort.signal.aborted) setError(message);\n props.report({\n code: 'workbench/view-failed',\n message: `${props.view.title}: ${message}`,\n severity: 'error',\n });\n };\n setError(undefined);\n void Promise.resolve()\n .then(() =>\n props.view.mount(target, { ...props.context, contextKeys: scope, signal: abort.signal }),\n )\n .then((disposable) => {\n if (typeof disposable?.dispose !== 'function')\n throw new TypeError(`视图 ${props.view.id} 必须返回 Disposable`);\n if (abort.signal.aborted) disposable.dispose();\n else result = disposable;\n })\n .catch(fail);\n return () => {\n abort.abort();\n scope.dispose();\n try {\n result?.dispose();\n } catch (error) {\n fail(error);\n }\n };\n }, [props.view, props.context]);\n return (\n <section className=\"mica-wb-contributed-view\" aria-label={props.view.title}>\n {!props.hideHeader && <h3>{props.view.title}</h3>}\n {error !== undefined && <p role=\"alert\">{error}</p>}\n <div ref={element} className=\"mica-wb-view-mount\" />\n </section>\n );\n}\n\nexport function SidebarPart(props: {\n readonly container: IWorkbenchViewContainer;\n readonly views: readonly IWorkbenchView[];\n readonly context: IWorkbenchExtensionContext;\n readonly onClose: () => void;\n readonly report: (diagnostic: IWorkbenchDiagnostic) => void;\n readonly children?: React.ReactNode;\n readonly hideHeader?: boolean;\n readonly title?: string | undefined;\n readonly actions?: React.ReactNode;\n readonly properties?: boolean;\n readonly singleView?: boolean;\n}) {\n const sidebar = useRef<HTMLElement>(null);\n return (\n <aside\n ref={sidebar}\n className={`mica-wb-sidebar${props.properties ? ' mica-wb-sidebar-properties' : ''}${props.singleView ? ' mica-wb-sidebar-single' : ''}`}\n aria-label={props.container.title}\n >\n <div\n role=\"separator\"\n aria-label=\"调整侧栏宽度\"\n aria-orientation=\"vertical\"\n tabIndex={0}\n className=\"mica-wb-sidebar-resizer\"\n onKeyDown={(event) => {\n if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;\n event.preventDefault();\n const root = sidebar.current?.closest<HTMLElement>('.mica-workbench');\n if (root !== null && root !== undefined)\n root.style.setProperty(\n '--mica-sidebar-width',\n `${Math.max(240, Math.min(480, (sidebar.current?.offsetWidth ?? 320) + (event.key === 'ArrowLeft' ? 20 : -20)))}px`,\n );\n }}\n onPointerDown={(event) => {\n const root = sidebar.current?.closest<HTMLElement>('.mica-workbench');\n if (root === null || root === undefined) return;\n event.currentTarget.setPointerCapture(event.pointerId);\n const start = event.clientX;\n const width = sidebar.current?.offsetWidth ?? 320;\n const handle = event.currentTarget;\n const move = (input: PointerEvent) =>\n root.style.setProperty(\n '--mica-sidebar-width',\n `${Math.max(240, Math.min(480, width + start - input.clientX))}px`,\n );\n const end = () => {\n handle.removeEventListener('pointermove', move);\n handle.removeEventListener('pointerup', end);\n handle.removeEventListener('pointercancel', end);\n };\n handle.addEventListener('pointermove', move);\n handle.addEventListener('pointerup', end);\n handle.addEventListener('pointercancel', end);\n }}\n />\n {!props.hideHeader && (\n <header className=\"mica-wb-sidebar-header\">\n <span>\n {props.title ??\n (props.singleView\n ? (props.views[0]?.title ?? props.container.title)\n : props.container.title)}\n </span>\n <span className=\"mica-wb-panel-actions\">\n {props.actions}\n <button title=\"收起侧栏\" aria-label=\"收起侧栏\" onClick={props.onClose}>\n <Icon name=\"chevron-right\" />\n </button>\n </span>\n </header>\n )}\n <div className=\"mica-wb-sidebar-content\">\n {props.children}\n {props.views.map((view) => (\n <ContributedView\n key={view.id}\n hideHeader={props.singleView === true}\n view={view}\n context={props.context}\n report={props.report}\n />\n ))}\n </div>\n </aside>\n );\n}\n","import { useLayoutEffect, useRef, useState } from 'react';\nimport type { IWorkbenchExtensionContext, IWorkbenchState, IWorkbenchToolbarItem } from '../types';\nimport type { ContributionRegistry } from '../contributions/registry';\nimport { Icon } from './activity-bar-part';\n\nexport function ToolbarPart(props: {\n readonly state: IWorkbenchState;\n readonly registry: ContributionRegistry;\n readonly context: IWorkbenchExtensionContext;\n readonly onError: (error: unknown) => void;\n}) {\n const [more, setMore] = useState(false);\n const toolbar = useRef<HTMLDivElement>(null);\n const modeGroup = useRef<HTMLDivElement>(null);\n const measurements = useRef<HTMLDivElement>(null);\n const divider = useRef<HTMLSpanElement>(null);\n const [layout, setLayout] = useState({ compact: false, count: Infinity });\n const items = props.registry.toolbar.filter((item) => props.registry.visible(item));\n useLayoutEffect(() => {\n const element = toolbar.current;\n const mode = modeGroup.current;\n const measure = measurements.current;\n const parent = element?.parentElement;\n if (!element || !mode || !measure || !parent) return;\n const update = () => {\n const style = getComputedStyle(element);\n const number = (value: string) => Number.parseFloat(value) || 0;\n const available = parent.clientWidth - number(style.left) * 2;\n const base =\n mode.getBoundingClientRect().width +\n number(style.paddingLeft) +\n number(style.paddingRight) +\n number(style.borderLeftWidth) +\n number(style.borderRightWidth);\n const separator = divider.current;\n const separatorStyle = separator && getComputedStyle(separator);\n const separatorWidth =\n separator && separatorStyle\n ? separator.getBoundingClientRect().width +\n number(separatorStyle.marginLeft) +\n number(separatorStyle.marginRight)\n : 0;\n const rows = [...measure.children];\n const widths = (row: Element | undefined) =>\n row ? [...row.children].map((child) => child.getBoundingClientRect().width) : [];\n const full = widths(rows[0]);\n const compact = widths(rows[1]);\n const gap = number(style.columnGap);\n const itemGap = rows[0] ? number(getComputedStyle(rows[0]).columnGap) : 0;\n const moreWidth = rows[2]?.getBoundingClientRect().width ?? 0;\n const required = (values: number[], count: number, overflow: boolean) =>\n base +\n separatorWidth +\n values.slice(0, count).reduce((sum, width) => sum + width, 0) +\n Math.max(0, count - 1) * itemGap +\n (overflow ? moreWidth : 0) +\n ((count > 0 ? 1 : 0) + (overflow ? 1 : 0) + (items.length > 0 ? 1 : 0)) * gap;\n let next = { compact: false, count: items.length };\n if (required(full, full.length, false) > available) {\n next = { compact: true, count: items.length };\n if (required(compact, compact.length, false) > available) {\n while (next.count > 0 && required(compact, next.count, true) > available) next.count--;\n }\n }\n setLayout((current) =>\n current.compact === next.compact && current.count === next.count ? current : next,\n );\n if (next.count === items.length) setMore(false);\n };\n const observer = new ResizeObserver(update);\n observer.observe(parent);\n observer.observe(mode);\n for (const row of measure.children) observer.observe(row);\n update();\n return () => observer.disconnect();\n }, [items]);\n const visible = items.slice(0, layout.count);\n const overflow = items.slice(layout.count);\n const execute = (item: IWorkbenchToolbarItem) => {\n setMore(false);\n if (!props.registry.enabled(item)) return;\n try {\n void Promise.resolve(item.execute(props.context)).catch(props.onError);\n } catch (error) {\n props.onError(error);\n }\n };\n const itemButton = (item: IWorkbenchToolbarItem) => (\n <button\n key={item.id}\n className={item.icon === undefined ? undefined : 'mica-wb-icon-tool'}\n title={item.title}\n aria-label={item.title}\n disabled={!props.registry.enabled(item)}\n aria-pressed={\n item.id.startsWith('mica.tool.')\n ? props.state.tool === item.id.slice('mica.tool.'.length)\n : undefined\n }\n onClick={() => execute(item)}\n >\n {item.icon !== undefined && <Icon name={item.icon} />}\n <span className=\"mica-wb-toolbar-label\">{item.title}</span>\n </button>\n );\n return (\n <div ref={toolbar} className=\"mica-wb-toolbar\" role=\"toolbar\" aria-label=\"电路工具\">\n <div ref={measurements} className=\"mica-wb-toolbar-measure\" aria-hidden=\"true\" inert>\n <div className=\"mica-wb-tools-inline\">{items.map(itemButton)}</div>\n <div className=\"mica-wb-tools-inline\" data-compact=\"true\">\n {items.map(itemButton)}\n </div>\n <span className=\"mica-wb-more-button\">\n <Icon name=\"ellipsis\" />\n </span>\n </div>\n <div\n ref={modeGroup}\n className=\"mica-wb-mode\"\n role=\"group\"\n aria-label=\"工作台模式\"\n data-mode={props.state.mode}\n >\n {(['edit', 'run'] as const).map((mode) => (\n <button\n key={mode}\n aria-pressed={props.state.mode === mode}\n disabled={props.state.busy}\n className={props.state.mode === mode ? 'is-active' : ''}\n onClick={() => {\n setMore(false);\n void props.context.workbench.setMode(mode).catch(props.onError);\n }}\n >\n <Icon name={mode === 'edit' ? 'edit' : 'play'} />\n {mode === 'edit' ? '编辑' : '运行'}\n </button>\n ))}\n </div>\n {items.length > 0 && (\n <>\n <span ref={divider} className=\"mica-wb-toolbar-divider\" />\n {visible.length > 0 && (\n <div className=\"mica-wb-tools-inline\" data-compact={layout.compact}>\n {visible.map(itemButton)}\n </div>\n )}\n {overflow.length > 0 && (\n <>\n <button\n className=\"mica-wb-more-button\"\n aria-label=\"更多工具\"\n title=\"更多工具\"\n aria-expanded={more}\n onClick={() => setMore(!more)}\n >\n <Icon name=\"ellipsis\" />\n </button>\n {more && (\n <div className=\"mica-wb-more-menu\" aria-label=\"其他工具\">\n {overflow.map(itemButton)}\n </div>\n )}\n </>\n )}\n </>\n )}\n </div>\n );\n}\n","import { useState } from 'react';\nimport type { FusedDocument } from '@mica-js/document/fused';\nimport type { ICanvasDevice } from '../canvas/geometry';\nimport type { IWorkbenchTarget } from '../types';\n\nexport function InstancesView(props: {\n readonly document: FusedDocument;\n readonly devices: ReadonlyMap<string, ICanvasDevice>;\n readonly selection: readonly IWorkbenchTarget[];\n readonly onSelect: (id: string) => void;\n}) {\n const [query, setQuery] = useState('');\n const instances = props.document.instances.filter((instance) =>\n `${instance.designator ?? ''} ${props.devices.get(instance.device)?.manifest.displayName ?? instance.device}`\n .toLowerCase()\n .includes(query.toLowerCase()),\n );\n return (\n <section className=\"mica-wb-instances\" aria-label=\"已放置器件\">\n <input\n type=\"search\"\n aria-label=\"搜索已放置器件\"\n placeholder=\"搜索位号或器件\"\n value={query}\n onChange={(event) => setQuery(event.target.value)}\n />\n <div role=\"list\" className=\"mica-wb-object-list\">\n {instances.map((instance) => (\n <button\n role=\"listitem\"\n key={instance.id}\n className={\n props.selection.some((target) => target.id === instance.id) ? 'is-active' : ''\n }\n onClick={() => props.onSelect(instance.id)}\n >\n <strong>{instance.designator ?? '—'}</strong>\n <span>\n {props.devices.get(instance.device)?.manifest.displayName ?? instance.device}\n </span>\n </button>\n ))}\n </div>\n {instances.length === 0 && (\n <p className=\"mica-wb-empty\">{query ? '没有匹配的器件' : '尚未放置器件'}</p>\n )}\n </section>\n );\n}\n","import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';\nimport type { ReactNode, RefObject } from 'react';\nimport type { DevicePropertyDescriptor, PropertyValue } from '@mica-js/document/fused';\nimport type { ProgramProject, ProgramSources, ProgramTarget } from '@mica-js/sdk/fused';\nimport type { IAssetProvider } from '../providers';\nimport type { FusedPresentationValue } from '../runtime/protocol';\nimport { Icon } from '../parts/activity-bar-part';\n\nexport function programPackageCandidates(\n paths: readonly string[],\n loader: ProgramTarget['loader'],\n formats: readonly string[] = [],\n): readonly string[] {\n if (loader === 'memory')\n return paths\n .filter((path) => path.startsWith('assets/') && formats.includes(programFormat(path) ?? ''))\n .sort();\n const directories = new Set<string>();\n for (const path of paths) {\n if (!path.startsWith('assets/')) continue;\n const parts = path.split('/');\n for (let i = 1; i < parts.length; i++) directories.add(parts.slice(0, i).join('/'));\n }\n return [...directories].sort();\n}\n\nexport function programFormat(path: string): 'bin' | 'hex' | 'elf' | undefined {\n const ext = path.split('.').at(-1)?.toLowerCase();\n return ext === 'bin'\n ? 'bin'\n : ext === 'hex' || ext === 'ihx'\n ? 'hex'\n : ext === 'elf' || ext === 'axf'\n ? 'elf'\n : undefined;\n}\n\nexport function validateProgramProjects(\n values: readonly ProgramProject[],\n): readonly ProgramProject[] {\n if (\n !Array.isArray(values) ||\n values.some(\n (value) =>\n !value ||\n typeof value.id !== 'string' ||\n !value.id.trim() ||\n typeof value.title !== 'string' ||\n !value.title.trim(),\n ) ||\n new Set(values.map((value) => value.id)).size !== values.length\n )\n throw new Error('program/project-selection-failed: 项目信息无效');\n return values;\n}\n\nfunction ResourcePopover(props: {\n readonly id: string;\n readonly anchor: RefObject<HTMLButtonElement | null>;\n readonly open: boolean;\n readonly onClose: () => void;\n readonly label: string;\n readonly className: string;\n readonly children: ReactNode;\n}) {\n const element = useRef<HTMLDivElement>(null);\n useLayoutEffect(() => {\n const popup = element.current;\n const anchor = props.anchor.current;\n if (!props.open || popup === null || anchor === null) return;\n popup.showPopover();\n const place = () => {\n const rect = anchor.getBoundingClientRect();\n const width = popup.offsetWidth;\n const height = popup.offsetHeight;\n popup.style.left = `${Math.max(8, Math.min(rect.right - width, window.innerWidth - width - 8))}px`;\n popup.style.top = `${Math.max(8, Math.min(rect.bottom + 4 + height <= window.innerHeight - 8 ? rect.bottom + 4 : rect.top - height - 4, window.innerHeight - height - 8))}px`;\n };\n place();\n const observer = new ResizeObserver(place);\n observer.observe(popup);\n window.addEventListener('resize', place);\n window.addEventListener('scroll', place, true);\n return () => {\n observer.disconnect();\n window.removeEventListener('resize', place);\n window.removeEventListener('scroll', place, true);\n };\n }, [props.open, props.anchor]);\n return props.open ? (\n <div\n id={props.id}\n ref={element}\n popover=\"auto\"\n className={`mica-wb-resource-popover ${props.className}`}\n aria-label={props.label}\n onToggle={(event) => {\n if (!event.currentTarget.matches(':popover-open')) props.onClose();\n }}\n >\n {props.children}\n </div>\n ) : null;\n}\n\nexport function ResourceField(props: {\n readonly name: string;\n readonly descriptor: DevicePropertyDescriptor;\n readonly value: PropertyValue | undefined;\n readonly overridden: boolean;\n readonly target: ProgramTarget;\n readonly sources: ProgramSources | undefined;\n readonly assets: IAssetProvider | undefined;\n readonly packagePaths: readonly string[];\n readonly snapshot: FusedPresentationValue | undefined;\n readonly disabled: boolean;\n readonly set: (value: PropertyValue) => void;\n readonly reset: () => void;\n readonly validate: (value: PropertyValue, signal: AbortSignal) => Promise<Uint8Array | undefined>;\n readonly commit: (value: PropertyValue, signal: AbortSignal) => Promise<void>;\n readonly onOpenProject: (id: string) => void;\n readonly onError: (error: unknown) => void;\n}) {\n const { descriptor, target, sources } = props;\n const reference =\n props.value !== null && typeof props.value === 'object' ? props.value : undefined;\n const [menu, setMenu] = useState(false);\n const [packagePicker, setPackagePicker] = useState(false);\n const [details, setDetails] = useState(false);\n const [busy, setBusy] = useState(false);\n const [error, setError] = useState('');\n const [retry, setRetry] = useState(0);\n const [projectFormat, setProjectFormat] = useState<string>();\n const [address, setAddress] = useState('');\n const [preview, setPreview] = useState<string>();\n const menuId = useId();\n const detailsId = useId();\n const menuButton = useRef<HTMLButtonElement>(null);\n const detailsButton = useRef<HTMLButtonElement>(null);\n const pending = useRef<AbortController | undefined>(undefined);\n const retryChoice = useRef<\n ((signal: AbortSignal) => Promise<PropertyValue | undefined>) | undefined\n >(undefined);\n const signature = JSON.stringify([target, props.value]);\n useEffect(() => {\n pending.current?.abort();\n setBusy(false);\n setError('');\n setMenu(false);\n setPackagePicker(false);\n retryChoice.current = undefined;\n return () => {\n pending.current?.abort();\n };\n }, [signature, props.disabled, sources, props.assets]);\n const fail = (cause: unknown) => {\n setError(cause instanceof Error ? cause.message : String(cause));\n props.onError(cause);\n };\n const perform = async (choose: (signal: AbortSignal) => Promise<PropertyValue | undefined>) => {\n if (props.disabled || busy) return;\n pending.current?.abort();\n const controller = new AbortController();\n pending.current = controller;\n setMenu(false);\n setBusy(true);\n setError('');\n retryChoice.current = choose;\n try {\n const value = await choose(controller.signal);\n if (value === undefined || controller.signal.aborted) return;\n retryChoice.current = async () => value;\n await props.validate(value, controller.signal);\n if (controller.signal.aborted) return;\n await props.commit(value, controller.signal);\n setPackagePicker(false);\n } catch (cause) {\n if (!controller.signal.aborted) fail(cause);\n } finally {\n if (!controller.signal.aborted) setBusy(false);\n }\n };\n const program = descriptor.type === 'program';\n const memory = target.loader === 'memory';\n const sourceName = reference?.mode === 'package' ? reference.src : reference?.name;\n const name = reference?.mode === 'project' ? (reference.name ?? reference.projectId) : sourceName;\n const source =\n reference?.mode === 'asset'\n ? '资产库'\n : reference?.mode === 'project'\n ? '项目'\n : reference?.mode === 'package'\n ? '内置资源'\n : '';\n const sourceIcon =\n reference?.mode === 'asset' ? 'cloud' : reference?.mode === 'project' ? 'project' : 'package';\n const hasDetails = (program && memory) || (!program && reference?.mode === 'asset');\n const detailsTitle = program ? '装载设置' : '资源详情';\n useEffect(() => {\n setPreview(undefined);\n if (descriptor.type !== 'image' || !reference) return;\n const controller = new AbortController();\n let url: string | undefined;\n void props\n .validate(reference, controller.signal)\n .then((bytes) => {\n if (controller.signal.aborted || bytes === undefined) return;\n const type = sourceName?.toLowerCase().endsWith('.svg') ? 'image/svg+xml' : 'image/png';\n url = URL.createObjectURL(new Blob([bytes.slice().buffer], { type }));\n setPreview(url);\n })\n .catch((cause) => {\n if (!controller.signal.aborted) fail(cause);\n });\n return () => {\n controller.abort();\n if (url) URL.revokeObjectURL(url);\n };\n }, [signature, props.assets, retry]);\n const candidates = program\n ? programPackageCandidates(props.packagePaths, target.loader, descriptor.formats)\n : props.packagePaths\n .filter(\n (path) =>\n path.startsWith('assets/') &&\n (descriptor.type === 'image'\n ? /\\.(png|svg)$/i.test(path)\n : descriptor.type === 'firmware'\n ? programFormat(path) !== undefined\n : !descriptor.extensions?.length ||\n descriptor.extensions.some((ext) =>\n path.toLowerCase().endsWith(ext.toLowerCase()),\n )),\n )\n .sort();\n const format = reference?.mode === 'project' ? projectFormat : programFormat(sourceName ?? '');\n const defaults = program ? descriptor.defaults : undefined;\n const selectedSpace =\n reference && 'addressSpace' in reference\n ? (reference.addressSpace ?? defaults?.addressSpace)\n : defaults?.addressSpace;\n const loadAddress =\n reference && 'loadAddress' in reference\n ? (reference.loadAddress ?? defaults?.loadAddress)\n : defaults?.loadAddress;\n const spaces = descriptor.addressSpaces ?? {};\n useEffect(\n () => setAddress(loadAddress === undefined ? '' : `0x${loadAddress.toString(16)}`),\n [loadAddress, signature],\n );\n useEffect(() => {\n setProjectFormat(undefined);\n if (!details || reference?.mode !== 'project' || !sources?.projects) return;\n const controller = new AbortController();\n void sources.projects\n .resolve(reference.projectId, target, controller.signal)\n .then((artifact) => {\n if (controller.signal.aborted) return;\n if (artifact.kind !== target.loader) throw new Error('program/loader-mismatch');\n setProjectFormat(artifact.kind === 'memory' ? artifact.format : undefined);\n })\n .catch((cause) => {\n if (!controller.signal.aborted) fail(cause);\n });\n return () => controller.abort();\n }, [details, signature, sources, retry]);\n const validAddress = (space: string, value: number) => {\n const range = spaces[space];\n return (\n range &&\n Number.isSafeInteger(value) &&\n value >= range.start &&\n value < range.start + range.size\n );\n };\n const saveAddress = () => {\n if (props.disabled || !reference || format !== 'bin') return;\n const value = /^(?:0x[0-9a-f]+|[0-9]+)$/i.test(address.trim()) ? Number(address) : NaN;\n if (!selectedSpace || !validAddress(selectedSpace, value)) {\n fail(new Error('program/out-of-range: 装载地址不在空间范围内'));\n return;\n }\n void perform(async () => ({ ...reference, loadAddress: value }));\n };\n const snapshot = props.snapshot;\n return (\n <div\n className=\"mica-wb-program-control\"\n onKeyDown={(event) => {\n if (event.key === 'Escape') {\n if (menu) menuButton.current?.focus();\n else if (details) detailsButton.current?.focus();\n setMenu(false);\n setDetails(false);\n setPackagePicker(false);\n }\n }}\n >\n <div className=\"mica-wb-resource-control\">\n {preview && <img className=\"mica-wb-resource-preview\" src={preview} alt=\"\" />}\n <div className=\"mica-wb-resource-summary\">\n {source && (\n <span className=\"mica-wb-resource-source\" title={source} aria-label={source}>\n <Icon name={sourceIcon} />\n </span>\n )}\n <span className=\"mica-wb-resource-name\" title={name}>\n {name ?? '未设置'}\n </span>\n {source && !props.overridden && <small>默认</small>}\n </div>\n <button\n ref={menuButton}\n className=\"mica-wb-resource-action\"\n aria-label={`${name ? '更换' : '选择'}${descriptor.title ?? props.name}来源`}\n title={`${name ? '更换' : '选择'}来源`}\n aria-controls={menuId}\n aria-expanded={menu}\n disabled={props.disabled || busy}\n onClick={() => setMenu(!menu)}\n >\n <Icon name=\"chevron-down\" />\n </button>\n {hasDetails && (\n <button\n ref={detailsButton}\n className=\"mica-wb-resource-action\"\n aria-label={detailsTitle}\n title={detailsTitle}\n aria-controls={detailsId}\n aria-expanded={details}\n onClick={() => setDetails(!details)}\n >\n <Icon name={program ? 'settings-gear' : 'info'} />\n </button>\n )}\n {reference?.mode === 'project' && (\n <button\n title=\"打开项目\"\n aria-label=\"打开项目\"\n onClick={() => props.onOpenProject(reference.projectId)}\n >\n <Icon name=\"go-to-file\" />\n </button>\n )}\n </div>\n <ResourcePopover\n id={menuId}\n anchor={menuButton}\n open={menu}\n onClose={() => setMenu(false)}\n className=\"mica-wb-resource-menu\"\n label=\"资源来源\"\n >\n <button\n disabled={!props.assets}\n onClick={() =>\n void perform(async (signal) => {\n const asset = await props.assets!.select({\n kind:\n program || descriptor.type === 'firmware'\n ? 'program'\n : descriptor.type === 'image'\n ? 'image'\n : 'binary',\n ...(program\n ? { formats: memory ? descriptor.formats : ['zip'] }\n : descriptor.type === 'binary' && descriptor.extensions\n ? { formats: descriptor.extensions.map((ext) => ext.slice(1)) }\n : descriptor.type === 'firmware'\n ? { formats: ['bin', 'hex', 'elf'] }\n : {}),\n signal,\n });\n if (asset === undefined) return undefined;\n if (\n typeof asset.id !== 'string' ||\n !asset.id.trim() ||\n typeof asset.name !== 'string' ||\n !asset.name.trim()\n )\n throw new Error('asset/invalid-selection: 资产信息无效');\n return { mode: 'asset', assetId: asset.id, name: asset.name };\n })\n }\n >\n 从资产库选择…\n </button>\n {program && (\n <button\n disabled={!sources?.projects?.select}\n onClick={() =>\n void perform(async (signal) => {\n const project = await sources!.projects!.select!(\n { ...target, templateIds: [...(descriptor.templates ?? [])] },\n signal,\n );\n if (project === undefined) return undefined;\n validateProgramProjects([project]);\n return { mode: 'project', projectId: project.id, name: project.title };\n })\n }\n >\n 从项目选择…\n </button>\n )}\n <button\n onClick={() => {\n setMenu(false);\n setPackagePicker(true);\n }}\n >\n 从内置资源选择…\n </button>\n {props.overridden && descriptor.default !== undefined && (\n <button\n onClick={() => {\n setMenu(false);\n props.reset();\n }}\n >\n 恢复默认\n </button>\n )}\n {descriptor.nullable && props.value !== null && (\n <button\n onClick={() => {\n setMenu(false);\n props.set(null);\n }}\n >\n 清除\n </button>\n )}\n </ResourcePopover>\n {packagePicker && (\n <div className=\"mica-wb-resource-control\">\n <select\n aria-label=\"内置资源\"\n disabled={busy || props.disabled}\n value=\"\"\n onChange={(event) => {\n const src = event.target.value;\n if (src) void perform(async () => ({ mode: 'package', src }));\n }}\n >\n <option value=\"\">选择内置资源</option>\n {candidates.map((path) => (\n <option key={path} value={path}>\n {path}\n </option>\n ))}\n </select>\n {!candidates.length && <span>没有匹配的内置资源</span>}\n <button disabled={busy} onClick={() => setPackagePicker(false)}>\n 取消\n </button>\n </div>\n )}\n {busy && <span role=\"status\">选择/校验中…</span>}\n {error && (\n <div role=\"alert\">\n {error}\n <button\n disabled={busy}\n onClick={() => {\n setError('');\n setRetry((value) => value + 1);\n if (!props.disabled && retryChoice.current) void perform(retryChoice.current);\n }}\n >\n 重试\n </button>\n </div>\n )}\n <ResourcePopover\n id={detailsId}\n anchor={detailsButton}\n open={details && hasDetails}\n onClose={() => setDetails(false)}\n className=\"mica-wb-resource-details\"\n label={detailsTitle}\n >\n {!program && reference?.mode === 'asset' && (\n <div className=\"mica-wb-resource-details\">UUID:{reference.assetId}</div>\n )}\n {program && (\n <div className=\"mica-wb-resource-details\">\n {reference?.mode === 'asset' && <div>UUID:{reference.assetId}</div>}\n {memory && (\n <>\n <div>格式:{format?.toUpperCase() ?? '等待产物信息'}</div>\n {format === 'elf' &&\n Object.entries(spaces).map(([id, space]) => (\n <div key={id}>\n {space.title ?? id}: [0x{space.start.toString(16)}, 0x\n {(space.start + space.size).toString(16)})\n </div>\n ))}\n {(format === 'bin' || format === 'hex') && (\n <label>\n 地址空间\n <select\n aria-label=\"地址空间\"\n value={selectedSpace ?? ''}\n disabled={\n props.disabled || busy || Object.keys(spaces).length < 2 || !reference\n }\n onChange={(event) => {\n const addressSpace = event.target.value;\n if (\n format === 'bin' &&\n loadAddress !== undefined &&\n !validAddress(addressSpace, loadAddress)\n ) {\n fail(new Error('program/out-of-range'));\n return;\n }\n if (reference) void perform(async () => ({ ...reference, addressSpace }));\n }}\n >\n {Object.entries(spaces).map(([id, space]) => (\n <option key={id} value={id}>\n {space.title ?? id}\n </option>\n ))}\n </select>\n </label>\n )}\n {format === 'bin' && (\n <label>\n 装载地址\n <input\n aria-label=\"装载地址\"\n value={address}\n disabled={props.disabled || busy || !reference}\n onChange={(event) => setAddress(event.target.value)}\n onBlur={saveAddress}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault();\n saveAddress();\n }\n }}\n />\n </label>\n )}\n {snapshot &&\n typeof snapshot === 'object' &&\n 'kind' in snapshot &&\n snapshot.kind === 'firmware' &&\n snapshot.segments.map((segment, index) => (\n <div key={index}>\n {segment.addressSpace}: 0x{segment.address.toString(16)} ·{' '}\n {segment.bytes.byteLength} 字节\n </div>\n ))}\n </>\n )}\n </div>\n )}\n </ResourcePopover>\n </div>\n );\n}\n","import { useEffect, useState } from 'react';\nimport type {\n DevicePropertyDescriptor,\n FusedInstance,\n PropertyValue,\n UnifiedDeviceManifest,\n} from '@mica-js/document/fused';\nimport type { IAssetProvider } from '../providers';\nimport { Icon } from '../parts/activity-bar-part';\nimport { ResourceField } from './program';\nimport type { ProgramSources, ProgramTarget } from '@mica-js/sdk/fused';\nimport type { FusedPresentationProps } from '../runtime/protocol';\n\ninterface IPropertyProps {\n readonly name: string;\n readonly descriptor: DevicePropertyDescriptor;\n readonly value: PropertyValue | undefined;\n readonly overridden: boolean;\n readonly disabled: boolean;\n readonly set: (value: PropertyValue) => void;\n readonly reset: () => void;\n readonly onError: (error: unknown) => void;\n readonly assets: IAssetProvider | undefined;\n readonly validate: (value: PropertyValue, signal: AbortSignal) => Promise<Uint8Array | undefined>;\n readonly commitResource: (value: PropertyValue, signal: AbortSignal) => Promise<void>;\n readonly openProject: (id: string) => void;\n readonly programSources: ProgramSources | undefined;\n readonly programTarget: ProgramTarget;\n readonly packagePaths: readonly string[];\n readonly snapshot: FusedPresentationProps[string] | undefined;\n}\n\nfunction PropertyField(props: IPropertyProps) {\n const value = props.value;\n const descriptor = props.descriptor;\n const [draft, setDraft] = useState(typeof value === 'object' ? '' : String(value ?? ''));\n useEffect(() => setDraft(typeof value === 'object' ? '' : String(value ?? '')), [value]);\n const commit = () => {\n if (props.disabled || draft === String(value ?? '')) return;\n if (descriptor.type === 'integer' || descriptor.type === 'number') {\n const number = Number(draft);\n if (\n draft.trim() === '' ||\n !Number.isFinite(number) ||\n (descriptor.type === 'integer' && !Number.isInteger(number))\n ) {\n props.onError(\n new Error(`${props.name} 需要有效的${descriptor.type === 'integer' ? '整数' : '数值'}`),\n );\n return;\n }\n props.set(number);\n } else props.set(draft);\n };\n return (\n <div className=\"mica-wb-property\">\n <label title={descriptor.description}>{descriptor.title ?? props.name}</label>\n <div className=\"mica-wb-property-control\">\n {['program', 'image', 'binary', 'firmware'].includes(descriptor.type) ? (\n <ResourceField\n name={props.name}\n descriptor={descriptor}\n value={value}\n target={props.programTarget}\n sources={props.programSources}\n packagePaths={props.packagePaths}\n snapshot={props.snapshot}\n disabled={props.disabled}\n overridden={props.overridden}\n assets={props.assets}\n validate={props.validate}\n commit={props.commitResource}\n reset={props.reset}\n set={props.set}\n onOpenProject={props.openProject}\n onError={props.onError}\n />\n ) : descriptor.type === 'boolean' ? (\n <input\n type=\"checkbox\"\n aria-label={descriptor.title ?? props.name}\n checked={value === true}\n disabled={props.disabled}\n onChange={(event) => props.set(event.target.checked)}\n />\n ) : descriptor.type === 'enum' ? (\n <select\n aria-label={descriptor.title ?? props.name}\n value={String(value ?? '')}\n disabled={props.disabled}\n onChange={(event) => props.set(event.target.value)}\n >\n {value === undefined && <option value=\"\">未设置</option>}\n {descriptor.options?.map((option) => (\n <option key={option.value} value={option.value}>\n {option.label}\n </option>\n ))}\n </select>\n ) : (\n <input\n aria-label={descriptor.title ?? props.name}\n type={\n descriptor.type === 'color'\n ? 'color'\n : descriptor.type === 'number' || descriptor.type === 'integer'\n ? 'number'\n : 'text'\n }\n value={draft}\n min={descriptor.min}\n max={descriptor.max}\n step={descriptor.step ?? (descriptor.type === 'integer' ? 1 : 'any')}\n disabled={props.disabled}\n onChange={(event) => setDraft(event.target.value)}\n onBlur={commit}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault();\n commit();\n }\n }}\n />\n )}\n {props.overridden &&\n !['program', 'image', 'binary', 'firmware'].includes(descriptor.type) && (\n <button\n title=\"恢复默认值\"\n aria-label={`恢复 ${props.name} 的默认值`}\n disabled={props.disabled}\n onClick={props.reset}\n >\n <Icon name=\"discard\" />\n </button>\n )}\n </div>\n </div>\n );\n}\n\nexport function InspectorView(props: {\n readonly instance: FusedInstance | undefined;\n readonly manifest: UnifiedDeviceManifest | undefined;\n readonly selectionCount: number;\n readonly disabled: boolean;\n readonly assets?: IAssetProvider | undefined;\n readonly programs?: ProgramSources | undefined;\n readonly packagePaths?: readonly string[];\n readonly snapshots?: FusedPresentationProps | undefined;\n readonly onSet: (key: string, value: PropertyValue) => void;\n readonly onReset: (key: string) => void;\n readonly onValidate: (\n key: string,\n value: PropertyValue,\n signal: AbortSignal,\n ) => Promise<Uint8Array | undefined>;\n readonly onCommit: (key: string, value: PropertyValue, signal: AbortSignal) => Promise<void>;\n readonly onOpenProject: (id: string) => void;\n readonly onError: (error: unknown) => void;\n readonly actions?: React.ReactNode;\n readonly hideHeader?: boolean;\n readonly fill?: boolean;\n readonly collapsed?: boolean;\n readonly height: number | undefined;\n readonly onToggle?: (collapsed: boolean) => void;\n}) {\n const header = (\n <summary\n className=\"mica-wb-panel-title\"\n style={props.hideHeader ? { display: 'none' } : undefined}\n >\n <span className=\"mica-wb-panel-caption\">\n <Icon name={props.collapsed ? 'chevron-right' : 'chevron-down'} />\n 属性\n </span>\n <span\n className=\"mica-wb-panel-actions\"\n onClick={(event) => {\n event.preventDefault();\n event.stopPropagation();\n }}\n >\n {props.actions}\n </span>\n </summary>\n );\n const toggled = (event: React.SyntheticEvent<HTMLDetailsElement>) => {\n if (!props.hideHeader && event.currentTarget.open === props.collapsed)\n props.onToggle?.(!event.currentTarget.open);\n };\n if (props.instance === undefined || props.manifest === undefined)\n return (\n <section\n className={`mica-wb-inspector${props.fill && (props.hideHeader || !props.collapsed) ? ' is-fill' : ''}`}\n aria-label=\"器件属性\"\n data-view-id=\"mica.properties\"\n >\n <details open={props.hideHeader || !props.collapsed} onToggle={toggled}>\n {header}\n <p className=\"mica-wb-empty\">\n {props.selectionCount > 1\n ? `已选择 ${props.selectionCount} 个对象`\n : '选择器件以查看其属性'}\n </p>\n </details>\n </section>\n );\n const properties = Object.entries(props.manifest.properties ?? {}).sort(\n ([a, x], [b, y]) => (x.order ?? 0) - (y.order ?? 0) || a.localeCompare(b),\n );\n return (\n <section\n className={`mica-wb-inspector${props.fill && (props.hideHeader || !props.collapsed) ? ' is-fill' : ''}`}\n aria-label=\"器件属性\"\n data-view-id=\"mica.properties\"\n >\n <details open={props.hideHeader || !props.collapsed} onToggle={toggled}>\n {header}\n <div\n className=\"mica-wb-property-fields\"\n style={{ height: props.fill ? undefined : props.height }}\n >\n <dl className=\"mica-wb-identity\">\n <dt>位号</dt>\n <dd>{props.instance.designator ?? '—'}</dd>\n <dt>器件</dt>\n <dd>{props.manifest.displayName}</dd>\n </dl>\n {properties.map(([name, descriptor]) => (\n <PropertyField\n key={`${props.instance?.id}:${name}`}\n name={name}\n descriptor={descriptor}\n programSources={props.programs}\n programTarget={{\n deviceId: props.instance!.device,\n property: name,\n loader: descriptor.type === 'program' ? descriptor.loader! : 'memory',\n }}\n packagePaths={props.packagePaths ?? []}\n snapshot={props.snapshots?.[name]}\n value={\n Object.hasOwn(props.instance?.properties ?? {}, name)\n ? props.instance?.properties?.[name]\n : descriptor.default\n }\n overridden={Object.hasOwn(props.instance?.properties ?? {}, name)}\n disabled={props.disabled}\n set={(value) => props.onSet(name, value)}\n reset={() => props.onReset(name)}\n onError={props.onError}\n assets={props.assets}\n validate={(value, signal) => props.onValidate(name, value, signal)}\n commitResource={(value, signal) => props.onCommit(name, value, signal)}\n openProject={props.onOpenProject}\n />\n ))}\n </div>\n </details>\n </section>\n );\n}\n","import type { IWorkbenchDiagnostic } from '../types';\n\nexport function ProblemsView(props: {\n readonly diagnostics: readonly IWorkbenchDiagnostic[];\n readonly onReveal: (id: string) => void;\n}) {\n return (\n <section className=\"mica-wb-problems\" aria-label=\"问题\">\n {props.diagnostics.length === 0 && <p className=\"mica-wb-empty\">没有发现问题</p>}\n {props.diagnostics.map((diagnostic, index) => (\n <button\n key={`${diagnostic.code}:${index}`}\n className={`mica-wb-diagnostic is-${diagnostic.severity}`}\n onClick={() => {\n if (diagnostic.instanceId !== undefined) props.onReveal(diagnostic.instanceId);\n }}\n >\n <strong>{diagnostic.code}</strong>\n <span>{diagnostic.message}</span>\n </button>\n ))}\n </section>\n );\n}\n","import { useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport type {\n FloatingBounds,\n FusedInstance,\n InstanceViewLayout,\n UnifiedDeviceManifest,\n} from '@mica-js/document/fused';\nimport type { IHtmlViewHandle } from '../html';\nimport { isHtmlViewError } from '../html';\nimport type { IWorkbenchUI } from './workbench-part';\nimport { Icon } from './activity-bar-part';\n\nfunction ViewSlot({\n handle,\n height,\n visible,\n}: {\n readonly handle: IHtmlViewHandle | undefined;\n readonly height?: number;\n readonly visible: boolean;\n}) {\n const slot = useRef<HTMLDivElement>(null);\n useLayoutEffect(() => {\n if (handle === undefined) return;\n handle.attach(slot.current);\n handle.setVisible(visible);\n return () => handle.attach(null);\n }, [handle, visible]);\n return (\n <div ref={slot} className=\"mica-wb-html-slot\" style={{ height }}>\n {handle?.state === 'failed' && <p role=\"alert\">{handle.failure?.message}</p>}\n {(handle === undefined || handle.state === 'loading') && <p role=\"status\">正在加载视图…</p>}\n </div>\n );\n}\n\nexport function PanelResizer(props: {\n readonly height: number;\n readonly onPreview: (height: number | undefined) => void;\n readonly onCommit: (height: number) => void;\n}) {\n const drag = useRef<{ readonly y: number; readonly height: number } | undefined>(undefined);\n return (\n <div\n className=\"mica-wb-panel-resizer\"\n role=\"separator\"\n aria-label=\"调整视图大小\"\n aria-orientation=\"horizontal\"\n tabIndex={0}\n onKeyDown={(event) => {\n if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return;\n event.preventDefault();\n props.onCommit(Math.max(64, props.height + (event.key === 'ArrowDown' ? 20 : -20)));\n }}\n onPointerDown={(event) => {\n drag.current = { y: event.clientY, height: props.height };\n event.currentTarget.setPointerCapture(event.pointerId);\n }}\n onPointerMove={(event) => {\n const value = drag.current;\n if (value === undefined) return;\n props.onPreview(Math.max(64, value.height + event.clientY - value.y));\n }}\n onPointerUp={(event) => {\n const value = drag.current;\n drag.current = undefined;\n if (value !== undefined)\n props.onCommit(Math.max(64, value.height + event.clientY - value.y));\n props.onPreview(undefined);\n if (event.currentTarget.hasPointerCapture(event.pointerId))\n event.currentTarget.releasePointerCapture(event.pointerId);\n }}\n onLostPointerCapture={() => {\n drag.current = undefined;\n props.onPreview(undefined);\n }}\n />\n );\n}\n\nexport function HtmlViewsPart(props: {\n readonly ui: IWorkbenchUI;\n readonly instance: FusedInstance;\n readonly manifest: UnifiedDeviceManifest;\n readonly layout: InstanceViewLayout;\n}) {\n const { ui, instance, manifest, layout } = props;\n const [draft, setDraft] = useState<Readonly<Record<string, number | undefined>>>({});\n const ordering = useRef<string | undefined>(undefined);\n const running = ui.workbench.getState().mode === 'run' && !ui.workbench.getState().busy;\n const run = (task: Promise<unknown>) => void task.catch(ui.error);\n const lastExpanded = layout.views\n .filter(\n (view) =>\n view.location === 'sidebar' &&\n !view.collapsed &&\n manifest.view?.[view.viewId] !== undefined,\n )\n .at(-1)?.viewId;\n useEffect(() => {\n if (!running) return;\n for (const view of layout.views) {\n if (view.location !== 'sidebar') continue;\n const handle = ui.htmlViews.get(instance.id, view.viewId);\n if (view.collapsed) handle?.setVisible(false);\n else if (handle === undefined)\n void ui.htmlViews\n .open({ instanceId: instance.id, viewId: view.viewId, location: 'sidebar' })\n .catch((reason: unknown) => {\n if (ui.context.signal.aborted) return;\n const selection = ui.workbench.getSelection();\n if (\n isHtmlViewError(reason) &&\n reason.code === 'view/unavailable-mode' &&\n (ui.workbench.getState().mode !== 'run' ||\n selection.length !== 1 ||\n selection[0]?.id !== instance.id)\n )\n return;\n ui.error(reason);\n });\n else handle.setVisible(true);\n }\n }, [running, instance.id, layout, ui]);\n const change = (viewId: string, patch: Partial<InstanceViewLayout['views'][number]>) =>\n run(\n ui.changeViewLayout(instance.id, {\n ...layout,\n views: layout.views.map((view) => (view.viewId === viewId ? { ...view, ...patch } : view)),\n }),\n );\n return (\n <div className=\"mica-wb-html-views\">\n {layout.views\n .filter((view) => view.location === 'sidebar')\n .map((view) => {\n const definition = manifest.view?.[view.viewId];\n if (definition === undefined) return null;\n const handle = ui.htmlViews.get(instance.id, view.viewId);\n return (\n <section\n className={`mica-wb-html-view${view.viewId === lastExpanded ? ' is-fill' : ''}`}\n key={view.viewId}\n aria-label={definition.title}\n >\n <div\n className=\"mica-wb-panel-title\"\n draggable\n onDragStart={(event) => {\n ordering.current = view.viewId;\n event.dataTransfer.setData('text/plain', view.viewId);\n event.dataTransfer.effectAllowed = 'move';\n }}\n onDragOver={(event) => {\n if (ordering.current !== undefined) event.preventDefault();\n }}\n onDrop={(event) => {\n event.preventDefault();\n const from = ordering.current;\n ordering.current = undefined;\n if (from === undefined || from === view.viewId) return;\n const ordered = [...layout.views];\n const source = ordered.findIndex((entry) => entry.viewId === from);\n const target = ordered.findIndex((entry) => entry.viewId === view.viewId);\n const [item] = ordered.splice(source, 1);\n if (item !== undefined) {\n ordered.splice(target, 0, item);\n run(ui.changeViewLayout(instance.id, { ...layout, views: ordered }));\n }\n }}\n onDragEnd={() => {\n ordering.current = undefined;\n }}\n >\n <button\n aria-expanded={!view.collapsed}\n onClick={() => change(view.viewId, { collapsed: !view.collapsed })}\n >\n <Icon name={view.collapsed ? 'chevron-right' : 'chevron-down'} />\n {definition.title}\n </button>\n <span className=\"mica-wb-panel-actions\">\n <button\n title=\"上移视图\"\n aria-label={`上移${definition.title}`}\n onClick={() => {\n const ordered = [...layout.views];\n const index = ordered.findIndex((entry) => entry.viewId === view.viewId);\n if (index <= 0) return;\n const previous = ordered[index - 1];\n if (previous === undefined) return;\n ordered[index - 1] = view;\n ordered[index] = previous;\n run(ui.changeViewLayout(instance.id, { ...layout, views: ordered }));\n }}\n >\n <Icon name=\"arrow-up\" />\n </button>\n <button\n title=\"浮动视图\"\n aria-label={`将${definition.title}设为浮动`}\n onClick={() =>\n run(\n ui.workbench.executeCommand('view.setLocation', {\n instanceId: instance.id,\n viewId: view.viewId,\n location: 'floating',\n }),\n )\n }\n >\n <Icon name=\"link-external\" />\n </button>\n </span>\n </div>\n {!view.collapsed &&\n (running ? (\n <ViewSlot handle={handle} height={draft[view.viewId] ?? view.height} visible />\n ) : (\n <p className=\"mica-wb-empty\">切换到运行模式后可打开此视图。</p>\n ))}\n {!view.collapsed && (\n <PanelResizer\n height={view.height}\n onPreview={(height) =>\n setDraft((current) => ({ ...current, [view.viewId]: height }))\n }\n onCommit={(height) => change(view.viewId, { height })}\n />\n )}\n </section>\n );\n })}\n </div>\n );\n}\n\nexport function FloatingViewsPart({ ui }: { readonly ui: IWorkbenchUI }) {\n return (\n <div className=\"mica-wb-floating-layer\">\n {ui.htmlViews.views\n .filter((view) => view.location === 'floating' && view.state !== 'closed')\n .map((view) => (\n <FloatingView key={view.key} ui={ui} handle={view} />\n ))}\n </div>\n );\n}\n\nconst floatingResizeHandles = [\n ['n', '上'],\n ['ne', '右上'],\n ['e', '右'],\n ['se', '右下'],\n ['s', '下'],\n ['sw', '左下'],\n ['w', '左'],\n ['nw', '左上'],\n] as const;\ntype FloatingResizeEdge = (typeof floatingResizeHandles)[number][0];\n\nfunction FloatingView({\n ui,\n handle,\n}: {\n readonly ui: IWorkbenchUI;\n readonly handle: IHtmlViewHandle;\n}) {\n const pane = useRef<HTMLElement>(null);\n const [preview, setPreview] = useState<FloatingBounds>();\n const [area, setArea] = useState({ width: 640, height: 480 });\n const drag = useRef<\n | {\n readonly kind: 'move' | FloatingResizeEdge;\n readonly x: number;\n readonly y: number;\n readonly bounds: FloatingBounds;\n next: FloatingBounds;\n }\n | undefined\n >(undefined);\n const instance = ui.workbench\n .getDocument()\n .instances.find((item) => item.id === handle.instanceId);\n const layout = ui.viewLayout(handle.instanceId);\n const saved = layout.views.find((view) => view.viewId === handle.viewId)?.floatingBounds;\n const requested = preview ??\n saved ?? { x: (area.width - 360) / 2, y: 80, width: 360, height: 280 };\n const constrain = (value: FloatingBounds): FloatingBounds => {\n const width = Math.max(180, Math.min(value.width, area.width));\n const height = Math.max(100, Math.min(value.height, area.height));\n return {\n width,\n height,\n x: Math.max(0, Math.min(value.x, area.width - width)),\n y: Math.max(0, Math.min(value.y, area.height - height)),\n };\n };\n const resize = (original: FloatingBounds, edge: FloatingResizeEdge, dx: number, dy: number) => {\n const next = { ...original };\n if (edge.includes('e'))\n next.width = Math.max(180, Math.min(original.width + dx, area.width - original.x));\n if (edge.includes('s'))\n next.height = Math.max(100, Math.min(original.height + dy, area.height - original.y));\n if (edge.includes('w')) {\n const right = original.x + original.width;\n next.x = Math.max(0, Math.min(original.x + dx, right - 180));\n next.width = right - next.x;\n }\n if (edge.includes('n')) {\n const bottom = original.y + original.height;\n next.y = Math.max(0, Math.min(original.y + dy, bottom - 100));\n next.height = bottom - next.y;\n }\n return next;\n };\n const bounds = constrain(requested);\n const cancel = () => {\n drag.current = undefined;\n setPreview(undefined);\n };\n useEffect(() => {\n window.addEventListener('blur', cancel);\n return () => window.removeEventListener('blur', cancel);\n }, []);\n useLayoutEffect(() => {\n const host = pane.current?.parentElement;\n if (host === null || host === undefined) return;\n const observer = new ResizeObserver(([entry]) => {\n if (entry !== undefined)\n setArea({ width: entry.contentRect.width, height: entry.contentRect.height });\n });\n observer.observe(host);\n return () => observer.disconnect();\n }, []);\n useLayoutEffect(() => ui.htmlViews.refresh(), [bounds.x, bounds.y, bounds.width, bounds.height]);\n const commit = (value: FloatingBounds) =>\n void ui\n .changeViewLayout(handle.instanceId, {\n ...layout,\n views: layout.views.map((view) =>\n view.viewId === handle.viewId ? { ...view, floatingBounds: constrain(value) } : view,\n ),\n })\n .catch(ui.error);\n const start = (event: React.PointerEvent<HTMLElement>, kind: 'move' | FloatingResizeEdge) => {\n if (event.button !== 0 || drag.current !== undefined) return;\n if (event.target instanceof Element && event.target.closest('button') !== null) return;\n event.preventDefault();\n drag.current = { kind, x: event.clientX, y: event.clientY, bounds, next: bounds };\n event.currentTarget.setPointerCapture(event.pointerId);\n };\n const move = (event: React.PointerEvent<HTMLElement>) => {\n const active = drag.current;\n if (active === undefined) return;\n active.next =\n active.kind === 'move'\n ? {\n ...active.bounds,\n x: active.bounds.x + event.clientX - active.x,\n y: active.bounds.y + event.clientY - active.y,\n }\n : resize(active.bounds, active.kind, event.clientX - active.x, event.clientY - active.y);\n setPreview(active.next);\n };\n const end = (event: React.PointerEvent<HTMLElement>) => {\n const active = drag.current;\n if (active !== undefined) move(event);\n drag.current = undefined;\n if (active !== undefined) commit(active.next);\n setPreview(undefined);\n if (event.currentTarget.hasPointerCapture(event.pointerId))\n event.currentTarget.releasePointerCapture(event.pointerId);\n };\n return (\n <section\n ref={pane}\n className=\"mica-wb-floating-view\"\n role=\"dialog\"\n aria-label={`${instance?.designator ?? handle.instanceId} · ${handle.title}`}\n style={{ left: bounds.x, top: bounds.y, width: bounds.width, height: bounds.height }}\n >\n <div\n className=\"mica-wb-panel-title\"\n onPointerDown={(event) => start(event, 'move')}\n onPointerMove={move}\n onPointerUp={end}\n onPointerCancel={cancel}\n onLostPointerCapture={cancel}\n >\n <span>\n {instance?.designator ?? handle.instanceId} · {handle.title}\n </span>\n <span className=\"mica-wb-panel-actions\">\n <button\n title=\"停靠视图\"\n aria-label={`停靠${handle.title}`}\n onClick={() =>\n void ui.workbench\n .executeCommand('view.setLocation', {\n instanceId: handle.instanceId,\n viewId: handle.viewId,\n location: 'sidebar',\n })\n .catch(ui.error)\n }\n >\n <Icon name=\"layout-sidebar-right\" />\n </button>\n <button\n title=\"关闭视图\"\n aria-label={`关闭${handle.title}`}\n onClick={() => handle.close()}\n >\n <Icon name=\"close\" />\n </button>\n </span>\n </div>\n <ViewSlot handle={handle} visible />\n {floatingResizeHandles.map(([edge, label]) => (\n <div\n key={edge}\n className={`mica-wb-floating-resizer mica-wb-floating-resizer-${edge}`}\n role=\"separator\"\n aria-label={`调整浮动视图大小(${label})`}\n aria-orientation={edge === 'n' || edge === 's' ? 'horizontal' : 'vertical'}\n aria-valuetext={`${Math.round(bounds.width)} × ${Math.round(bounds.height)}`}\n tabIndex={edge === 'se' ? 0 : -1}\n onKeyDown={(event) => {\n const step = event.shiftKey ? 40 : 10;\n const dx = event.key === 'ArrowLeft' ? -step : event.key === 'ArrowRight' ? step : 0;\n const dy = event.key === 'ArrowUp' ? -step : event.key === 'ArrowDown' ? step : 0;\n if (dx === 0 && dy === 0) return;\n event.preventDefault();\n commit(resize(bounds, edge, dx, dy));\n }}\n onPointerDown={(event) => start(event, edge)}\n onPointerMove={move}\n onPointerUp={end}\n onPointerCancel={cancel}\n onLostPointerCapture={cancel}\n />\n ))}\n </section>\n );\n}\n","import { useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type {\n DeviceLock,\n Endpoint,\n InstanceViewLayout,\n PropertyValue,\n Point2D,\n} from '@mica-js/document/fused';\nimport type { IHtmlViewHost } from '../html';\nimport type {\n IWorkbench,\n IWorkbenchDiagnostic,\n IWorkbenchExtensionContext,\n IWorkbenchOptions,\n} from '../types';\nimport type { ICanvasDevice } from '../canvas/geometry';\nimport type { ContributionRegistry } from '../contributions/registry';\nimport { ActivityBarPart } from './activity-bar-part';\nimport { CanvasPart, type ICanvasHandle, type IViewInput } from './canvas-part';\nimport { SidebarPart } from './sidebar-part';\nimport { ToolbarPart } from './toolbar-part';\nimport { InstancesView } from '../views/instances';\nimport { InspectorView } from '../views/inspector';\nimport { ProblemsView } from '../views/problems';\nimport { FloatingViewsPart, HtmlViewsPart, PanelResizer } from './html-views-part';\nimport { Icon } from './activity-bar-part';\nimport { readCanvasTheme, resolveTheme, themeStyle, type IWorkbenchTheme } from '../theme';\nimport type { FusedPresentationProps } from '../runtime/protocol';\n\nexport interface IWorkbenchUI {\n readonly workbench: IWorkbench;\n readonly options: IWorkbenchOptions;\n readonly context: IWorkbenchExtensionContext;\n readonly theme: IWorkbenchTheme;\n readonly htmlViews: IHtmlViewHost;\n readonly viewLayout: (instanceId: string) => InstanceViewLayout;\n readonly changeViewLayout: (\n instanceId: string,\n layout: InstanceViewLayout | undefined,\n ) => Promise<void>;\n readonly contributions: ContributionRegistry;\n readonly onDidUpdate: Event<void>;\n readonly devices: ReadonlyMap<string, ICanvasDevice>;\n readonly images: ReadonlyMap<string, CanvasImageSource>;\n readonly overlays: ReadonlyMap<string, ImageBitmap>;\n readonly diagnostics: readonly IWorkbenchDiagnostic[];\n readonly placement: DeviceLock | undefined;\n readonly placementRotation: number;\n readonly version: number;\n readonly setCanvas: (canvas: ICanvasHandle | undefined) => void;\n readonly report: (diagnostic: IWorkbenchDiagnostic) => void;\n readonly error: (error: unknown) => void;\n readonly input: (instanceId: string, event: IViewInput) => void;\n readonly labelName: string;\n readonly setLabelName: (name: string) => void;\n readonly connect: (\n from: Endpoint | Point2D,\n to: Endpoint | Point2D,\n bends: readonly Point2D[],\n ) => Promise<void>;\n readonly endpoint: (endpoint: Endpoint | Point2D) => Promise<void>;\n readonly cancel: () => void;\n readonly focus: (focused: boolean) => void;\n readonly viewport: () => void;\n readonly reveal: (instanceId: string) => void;\n readonly validateResource: (\n instanceId: string,\n key: string,\n value: PropertyValue,\n signal: AbortSignal,\n ) => Promise<Uint8Array | undefined>;\n readonly commitResource: (\n instanceId: string,\n key: string,\n expected: PropertyValue | undefined,\n value: PropertyValue,\n signal: AbortSignal,\n ) => Promise<void>;\n readonly openProject: (projectId: string) => void;\n readonly programPackagePaths: (deviceId: string) => readonly string[];\n readonly programSnapshot: (instanceId: string) => FusedPresentationProps | undefined;\n}\n\nexport function WorkbenchPart({ ui }: { readonly ui: IWorkbenchUI }) {\n const frame = useSyncExternalStore(\n (callback) => {\n const subscription = ui.onDidUpdate(callback);\n return () => subscription.dispose();\n },\n () => ui.version,\n );\n const [systemDark, setSystemDark] = useState(\n () => matchMedia('(prefers-color-scheme: dark)').matches,\n );\n const root = useRef<HTMLDivElement>(null);\n const [propertyHeight, setPropertyHeight] = useState<number>();\n const [emptyPropertiesCollapsed, setEmptyPropertiesCollapsed] = useState(false);\n useEffect(() => {\n const media = matchMedia('(prefers-color-scheme: dark)');\n const changed = () => setSystemDark(media.matches);\n media.addEventListener('change', changed);\n return () => media.removeEventListener('change', changed);\n }, []);\n const state = ui.workbench.getState();\n const document = ui.workbench.getDocument();\n const selection = ui.workbench.getSelection();\n const active = ui.contributions.containers.find(\n (container) => container.id === state.activeContainer && ui.contributions.visible(container),\n );\n const single =\n selection.length === 1 && selection[0]?.kind === 'instance'\n ? document.instances.find((instance) => instance.id === selection[0]?.id)\n : undefined;\n const manifest = single === undefined ? undefined : ui.devices.get(single.device)?.manifest;\n const layout =\n single === undefined || manifest === undefined ? undefined : ui.viewLayout(single.id);\n const run = (task: Promise<unknown>) => {\n void task.catch(ui.error);\n };\n const setProperty = (key: string, value: PropertyValue) => {\n if (single !== undefined)\n run(ui.workbench.executeCommand('device.setProperty', { instanceId: single.id, key, value }));\n };\n const propertyCollapsed = layout?.properties.collapsed ?? emptyPropertiesCollapsed;\n const toggleProperties = (collapsed: boolean) => {\n if (single === undefined || layout === undefined) setEmptyPropertiesCollapsed(collapsed);\n else\n run(\n ui.changeViewLayout(single.id, {\n ...layout,\n properties: { ...layout.properties, collapsed },\n }),\n );\n };\n const deviceViewIds = new Set<string>();\n const floating = new Map<\n string,\n { instanceId: string; viewId: string; title: string; icon: string | undefined }\n >();\n if (state.mode === 'run') {\n for (const view of layout?.views ?? []) {\n const definition = manifest?.view?.[view.viewId];\n if (single === undefined || definition === undefined) continue;\n const key = `${single.id}/${view.viewId}`;\n deviceViewIds.add(key);\n if (view.location === 'floating')\n floating.set(key, {\n instanceId: single.id,\n viewId: view.viewId,\n title: definition.title,\n icon: definition.icon,\n });\n }\n for (const handle of ui.htmlViews.views) {\n if (handle.location !== 'floating' || handle.state === 'closed') continue;\n deviceViewIds.add(`${handle.instanceId}/${handle.viewId}`);\n floating.set(`${handle.instanceId}/${handle.viewId}`, {\n instanceId: handle.instanceId,\n viewId: handle.viewId,\n title: handle.title,\n icon: undefined,\n });\n }\n }\n const multipleInfoViews =\n deviceViewIds.size > 0 ||\n ui.contributions.views.some(\n (view) => view.containerId === 'mica.properties' && ui.contributions.visible(view),\n );\n const propertyActions =\n single === undefined || layout === undefined ? undefined : (\n <button\n title=\"恢复视图布局\"\n aria-label=\"恢复视图布局\"\n onClick={() => run(ui.changeViewLayout(single.id, undefined))}\n >\n <Icon name=\"discard\" />\n </button>\n );\n const floatingActions = [...floating]\n .filter(([, view]) => ui.htmlViews.get(view.instanceId, view.viewId) === undefined)\n .map(([key, view]) => (\n <button\n key={key}\n title={view.title}\n aria-label={`${document.instances.find((instance) => instance.id === view.instanceId)?.designator ?? view.instanceId} ${view.title}`}\n disabled={state.busy}\n onClick={() =>\n run(\n ui.workbench.executeCommand('view.open', {\n instanceId: view.instanceId,\n viewId: view.viewId,\n }),\n )\n }\n >\n <Icon name={view.icon ?? 'link-external'} />\n </button>\n ));\n const theme = useMemo(() => resolveTheme(ui.theme, systemDark), [ui.theme, systemDark]);\n // Device HTML views mirror the *computed* colors, so a host `var(...)` token is already resolved\n // when the environment writes it into its author document.\n useLayoutEffect(() => {\n const element = root.current;\n if (element === null) return;\n ui.htmlViews.setTheme({\n appearance: theme.appearance,\n colors: readCanvasTheme(element),\n });\n }, [ui.htmlViews, theme]);\n return (\n <div\n ref={root}\n className={`mica-workbench mica-wb-${theme.appearance} ${active === undefined ? '' : 'mica-wb-sidebar-open'}`}\n style={{ ...themeStyle(theme), colorScheme: theme.appearance }}\n data-theme={theme.appearance}\n role=\"region\"\n aria-label=\"电路工作台\"\n lang=\"zh-CN\"\n aria-busy={state.busy}\n onKeyDown={(event) => {\n if (event.key === 'Escape' && (ui.placement !== undefined || state.tool !== 'select')) {\n event.preventDefault();\n ui.cancel();\n return;\n }\n const target = event.target;\n if (\n target instanceof HTMLElement &&\n (target.matches('input,textarea,select') || target.isContentEditable)\n )\n return;\n if (event.code === 'Space' && state.mode === 'edit' && !state.readOnly && !state.busy) {\n event.preventDefault();\n if (!event.repeat) run(ui.workbench.executeCommand('selection.rotate', { degrees: 90 }));\n return;\n }\n if (!(event.ctrlKey || event.metaKey)) return;\n if (event.key.toLowerCase() === 's') {\n event.preventDefault();\n run(ui.workbench.save());\n }\n if (event.key.toLowerCase() === 'z') {\n event.preventDefault();\n run(ui.workbench.executeCommand(event.shiftKey ? 'document.redo' : 'document.undo'));\n }\n if (event.key.toLowerCase() === 'y') {\n event.preventDefault();\n run(ui.workbench.executeCommand('document.redo'));\n }\n }}\n >\n <CanvasPart\n document={document}\n devices={ui.devices}\n images={ui.images}\n overlays={ui.overlays}\n state={state}\n selection={selection}\n placement={ui.placement}\n placementRotation={ui.placementRotation}\n labelName={ui.labelName}\n theme={theme}\n frame={frame}\n onReady={ui.setCanvas}\n onSelection={(targets) => ui.workbench.setSelection(targets)}\n onOpenProperties={() =>\n run(\n ui.workbench.executeCommand('workbench.openContainer', {\n id: 'mica.properties',\n focus: true,\n }),\n )\n }\n onPlace={async (device, position) => {\n await ui.workbench.executeCommand('device.add', {\n device,\n placement: { ...position, rotation: ui.placementRotation },\n });\n ui.cancel();\n }}\n onMove={async (instanceId, position) => {\n await ui.workbench.executeCommand('device.move', { instanceId, position });\n }}\n onMoveSegment={async (wireId, segment, delta) => {\n await ui.workbench.executeCommand('wire.moveSegment', { wireId, segment, delta });\n }}\n onMoveText={async (target, offset) => {\n await ui.workbench.executeCommand('text.move', { target, offset });\n }}\n onMoveReference={async (referenceId, position) => {\n await ui.workbench.executeCommand('reference.move', { referenceId, position });\n }}\n onStartWire={async () => {\n await ui.workbench.executeCommand('canvas.setTool', { tool: 'wire' });\n }}\n onConnect={ui.connect}\n onEndpoint={ui.endpoint}\n onCancel={ui.cancel}\n onDelete={async () => {\n await ui.workbench.executeCommand('selection.delete');\n }}\n onInput={ui.input}\n onError={ui.error}\n onFocus={ui.focus}\n onViewport={ui.viewport}\n >\n <ToolbarPart\n state={state}\n registry={ui.contributions}\n context={ui.context}\n onError={ui.error}\n />\n {state.busy && (\n <div className=\"mica-wb-status\" role=\"status\">\n 正在准备…\n </div>\n )}\n {!state.busy && state.mode === 'edit' && state.readOnly && (\n <div className=\"mica-wb-status\" role=\"status\">\n 只读\n </div>\n )}\n {!state.busy && ui.placement !== undefined && (\n <div className=\"mica-wb-status\" role=\"status\">\n 单击放置 · 空格旋转 · Esc 取消\n </div>\n )}\n {!state.busy &&\n state.mode === 'edit' &&\n !state.readOnly &&\n ['power', 'ground', 'label'].includes(state.tool) && (\n <div className=\"mica-wb-status\" role=\"status\">\n {state.tool === 'label' && (\n <label>\n 网标{' '}\n <input\n aria-label=\"网标名称\"\n value={ui.labelName}\n onChange={(event) => ui.setLabelName(event.target.value)}\n />\n </label>\n )}\n 单击放置 · Esc 取消\n </div>\n )}\n {ui.diagnostics.some((diagnostic) => diagnostic.severity === 'error') && (\n <button\n className=\"mica-wb-problem-indicator\"\n onClick={() =>\n run(ui.workbench.executeCommand('workbench.openContainer', { id: 'mica.problems' }))\n }\n >\n {ui.diagnostics.filter((diagnostic) => diagnostic.severity === 'error').length} problems\n </button>\n )}\n </CanvasPart>\n {active !== undefined && (\n <SidebarPart\n properties={active.id === 'mica.properties'}\n singleView={\n active.id === 'mica.properties'\n ? !multipleInfoViews\n : ui.contributions.views.filter(\n (view) => view.containerId === active.id && ui.contributions.visible(view),\n ).length +\n (active.id === 'mica.instances' || active.id === 'mica.problems' ? 1 : 0) ===\n 1\n }\n title={\n active.id === 'mica.properties' ? (multipleInfoViews ? '信息' : '属性') : undefined\n }\n actions={\n active.id === 'mica.properties'\n ? multipleInfoViews\n ? floatingActions\n : propertyActions\n : undefined\n }\n container={active}\n views={ui.contributions.views.filter(\n (view) => view.containerId === active.id && ui.contributions.visible(view),\n )}\n context={ui.context}\n onClose={() => run(ui.workbench.executeCommand('workbench.closeContainer'))}\n report={ui.report}\n >\n {active.id === 'mica.instances' && (\n <InstancesView\n document={document}\n devices={ui.devices}\n selection={selection}\n onSelect={ui.reveal}\n />\n )}\n {active.id === 'mica.properties' && (\n <>\n <InspectorView\n hideHeader={!multipleInfoViews}\n fill={\n state.mode !== 'run' ||\n !layout?.views.some(\n (view) =>\n view.location === 'sidebar' &&\n !view.collapsed &&\n manifest?.view?.[view.viewId] !== undefined,\n )\n }\n instance={single}\n manifest={\n single === undefined ? undefined : ui.devices.get(single.device)?.manifest\n }\n selectionCount={selection.length}\n disabled={state.readOnly || state.mode !== 'edit' || state.busy}\n assets={ui.options.assetProvider}\n programs={ui.options.programs}\n packagePaths={single === undefined ? [] : ui.programPackagePaths(single.device)}\n snapshots={single === undefined ? undefined : ui.programSnapshot(single.id)}\n onSet={setProperty}\n onReset={(key) => {\n if (single !== undefined)\n run(\n ui.workbench.executeCommand('device.removeProperty', {\n instanceId: single.id,\n key,\n }),\n );\n }}\n onValidate={async (key, value, signal) => {\n if (single === undefined) throw new Error('No device is selected');\n return ui.validateResource(single.id, key, value, signal);\n }}\n onCommit={async (key, value, signal) => {\n if (single === undefined) throw new Error('No device is selected');\n await ui.commitResource(single.id, key, single.properties?.[key], value, signal);\n }}\n onOpenProject={ui.openProject}\n onError={ui.error}\n collapsed={propertyCollapsed}\n height={\n multipleInfoViews ? (propertyHeight ?? layout?.properties.height) : undefined\n }\n onToggle={toggleProperties}\n actions={multipleInfoViews ? propertyActions : undefined}\n />\n {single !== undefined && manifest !== undefined && layout !== undefined && (\n <>\n {multipleInfoViews && !layout.properties.collapsed && (\n <PanelResizer\n height={layout.properties.height}\n onPreview={setPropertyHeight}\n onCommit={(height) =>\n run(\n ui.changeViewLayout(single.id, {\n ...layout,\n properties: { ...layout.properties, height },\n }),\n )\n }\n />\n )}\n {state.mode === 'run' && (\n <HtmlViewsPart ui={ui} instance={single} manifest={manifest} layout={layout} />\n )}\n </>\n )}\n </>\n )}\n {active.id === 'mica.problems' && (\n <ProblemsView diagnostics={ui.diagnostics} onReveal={ui.reveal} />\n )}\n </SidebarPart>\n )}\n <ActivityBarPart\n containers={ui.contributions.containers.filter((container) =>\n ui.contributions.visible(container),\n )}\n active={active?.id}\n problemCount={ui.diagnostics.length}\n onActivate={(id) => {\n if (id === state.activeContainer)\n run(ui.workbench.executeCommand('workbench.closeContainer'));\n else run(ui.workbench.executeCommand('workbench.openContainer', { id, focus: true }));\n }}\n />\n <FloatingViewsPart ui={ui} />\n </div>\n );\n}\n","import { createRoot } from 'react-dom/client';\nimport { flushSync } from 'react-dom';\nimport { DisposableStore, Emitter } from '@mica-js/core/lifecycle';\nimport { timePs } from '@mica-js/core';\nimport type {\n DeviceLock,\n Endpoint,\n FusedDocument,\n InstanceViewLayout,\n Point2D,\n} from '@mica-js/document/fused';\nimport { parseFusedDocument } from '@mica-js/document/fused';\nimport { openDevicePackage, resolveInstanceProperties } from '@mica-js/sdk/fused';\nimport { createContextKeyService } from './context';\nimport { FusedDocumentSession } from './document';\nimport {\n addLabel,\n addReference,\n addWire,\n rotateTargets,\n setTextOffset,\n setInstanceProperty,\n} from './document/edits';\nimport { materializeAnchor, moveReference, moveWireSegment, routeDocumentWires } from './wiring';\nimport { ContributionRegistry } from './contributions/registry';\nimport { findBodyOverlaps } from './canvas/geometry';\nimport { createHtmlViewHost, type IHtmlViewHost } from './html';\nimport { resolveViewLayout } from './views/layout';\nimport { normalizeTheme, type WorkbenchTheme } from './theme';\nimport { createFusedRuntime, type IFusedRuntime } from './runtime';\nimport type { IWorkbenchAccessProvider } from './providers';\nimport type {\n IWorkbench,\n IWorkbenchCommandMap,\n IWorkbenchContributions,\n IWorkbenchDiagnostic,\n IWorkbenchExtensionContext,\n IWorkbenchOptions,\n IWorkbenchState,\n IWorkbenchTarget,\n WorkbenchCommandArgs,\n WorkbenchMode,\n WorkbenchTool,\n} from './types';\nimport { WorkbenchPart, type IWorkbenchUI } from './parts/workbench-part';\nimport type { ICanvasHandle, IViewInput } from './parts/canvas-part';\nimport './styles/workbench.css';\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction errorCode(error: unknown): string {\n return typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n typeof error.code === 'string'\n ? error.code\n : 'workbench/operation-failed';\n}\n\nfunction validateViewBase(template: string): void {\n const url = new URL(template.replace('${id}', 'mica-view'));\n if (\n !['http:', 'https:'].includes(url.protocol) ||\n !template.endsWith('/') ||\n template.split('${id}').length !== 2 ||\n !new URL(template).hostname.split('.').includes('${id}')\n ) {\n throw new Error(\n 'viewBaseUrlTemplate must be an absolute HTTP(S) directory URL with one ${id} hostname label',\n );\n }\n}\n\nasync function decodeResourceImage(\n bytes: Uint8Array,\n name: string,\n): Promise<ImageBitmap | HTMLImageElement> {\n const svg = name.toLowerCase().endsWith('.svg');\n const blob = new Blob([bytes.slice().buffer], {\n type: svg ? 'image/svg+xml' : 'application/octet-stream',\n });\n if (!svg) return createImageBitmap(blob);\n const source = URL.createObjectURL(blob);\n try {\n const image = new Image();\n image.src = source;\n await image.decode();\n return image;\n } finally {\n URL.revokeObjectURL(source);\n }\n}\n\nexport async function createWorkbench(options: IWorkbenchOptions): Promise<IWorkbench> {\n validateViewBase(options.viewBaseUrlTemplate);\n function validateTheme(value: WorkbenchTheme | undefined) {\n const result = normalizeTheme(value);\n for (const [token, color] of Object.entries(result.colors ?? {}))\n if (!CSS.supports('color', color))\n throw new Error(`Invalid CSS color for ${token}: ${color}`);\n return result;\n }\n let theme = validateTheme(options.theme);\n const step = options.step ?? timePs(10_000_000);\n if (!Number.isSafeInteger(step) || step <= 0)\n throw new Error('Workbench step must be a positive integer number of picoseconds');\n const disposables = new DisposableStore();\n const abort = new AbortController();\n const content = disposables.add(new Emitter<FusedDocument>());\n const selectionChanged = disposables.add(new Emitter<readonly IWorkbenchTarget[]>());\n const stateChanged = disposables.add(new Emitter<IWorkbenchState>());\n const diagnosticsChanged = disposables.add(new Emitter<IWorkbenchDiagnostic>());\n const openProject = disposables.add(new Emitter<{ readonly projectId: string }>());\n const uiChanged = disposables.add(new Emitter<void>());\n const defaultAccessChanged = disposables.add(new Emitter<void>());\n const access: IWorkbenchAccessProvider = {\n onDidChange: options.accessProvider?.onDidChange ?? defaultAccessChanged.event,\n async evaluateDocument(context) {\n const decision = (await options.accessProvider?.evaluateDocument(context)) ?? {\n edit: { allowed: true as const },\n run: { allowed: true as const },\n };\n return {\n ...decision,\n edit: options.readOnly\n ? {\n allowed: false,\n code: 'document/read-only',\n message: 'The host opened this document read-only',\n }\n : decision.edit,\n };\n },\n async canAddDevice(context) {\n return (await options.accessProvider?.canAddDevice(context)) ?? { allowed: true };\n },\n };\n const rootContext = disposables.add(\n createContextKeyService({\n owner: 'workbench',\n reservedPrefixes: [\n 'workbench.',\n 'editor.',\n 'document.',\n 'history.',\n 'selection.',\n 'viewContainer.',\n 'canvas.',\n ],\n }),\n );\n const contextKeys = disposables.add(rootContext.createScope());\n const keys = {\n mode: rootContext.createKey<WorkbenchMode>('workbench.mode', 'edit'),\n busy: rootContext.createKey('workbench.busy', false),\n editable: rootContext.createKey('document.editable', false),\n dirty: rootContext.createKey('document.dirty', false),\n undo: rootContext.createKey('history.canUndo', false),\n redo: rootContext.createKey('history.canRedo', false),\n selection: rootContext.createKey('selection.count', 0),\n container: rootContext.createKey('viewContainer.active', ''),\n focus: rootContext.createKey('canvas.focused', false),\n };\n let documentSession: FusedDocumentSession;\n try {\n documentSession = await FusedDocumentSession.open({\n document: options.document,\n ...(options.saveDocument === undefined ? {} : { saveDocument: options.saveDocument }),\n devices: options.deviceProvider,\n access,\n });\n } catch (error) {\n disposables.dispose();\n throw error;\n }\n\n let disposed = false;\n let disposal: Promise<void> | undefined;\n let mode: WorkbenchMode = 'edit';\n let busy = false;\n let tool: WorkbenchTool = 'select';\n let labelName = 'NET1';\n let activeContainer: string | undefined;\n let selection: readonly IWorkbenchTarget[] = Object.freeze([]);\n let placement: DeviceLock | undefined;\n let placementRotation = 0;\n let canvas: ICanvasHandle | undefined;\n let runtime: IFusedRuntime | undefined;\n let runtimeDocument: FusedDocument | undefined;\n let runtimeGeneration = 0;\n let htmlViews: IHtmlViewHost | undefined;\n const transientLayouts = new Map<string, InstanceViewLayout | undefined>();\n let transition = Promise.resolve();\n let presentation = Promise.resolve();\n let presentationSignature = '';\n let version = 0;\n const images = new Map<string, ImageBitmap | HTMLImageElement>();\n const imageLocks = new Map<string, string>();\n const overlays = new Map<string, ImageBitmap>();\n const diagnostics: IWorkbenchDiagnostic[] = [];\n const mount = globalThis.document.createElement('div');\n mount.style.cssText = 'width:100%;height:100%;min-height:0;min-width:0;';\n const environment = globalThis.document.createElement('div');\n environment.hidden = true;\n const root = createRoot(mount);\n let registry: ContributionRegistry;\n let state = computeState();\n\n function assertReady(): void {\n if (disposed) throw new Error('Workbench is disposed');\n }\n function computeState(): IWorkbenchState {\n const value = documentSession.getState();\n return Object.freeze({\n mode,\n busy,\n dirty: value.dirty,\n readOnly: value.readOnly,\n canUndo: value.canUndo,\n canRedo: value.canRedo,\n tool,\n activeContainer,\n });\n }\n function update(): void {\n if (disposed) return;\n const next = computeState();\n const changed = JSON.stringify(next) !== JSON.stringify(state);\n state = next;\n rootContext.batch(() => {\n keys.mode.set(mode);\n keys.busy.set(busy);\n keys.editable.set(documentSession.getState().canEditContent && mode === 'edit' && !busy);\n keys.dirty.set(state.dirty);\n keys.undo.set(state.canUndo);\n keys.redo.set(state.canRedo);\n keys.selection.set(selection.length);\n keys.container.set(activeContainer ?? '');\n });\n version++;\n uiChanged.fire();\n if (changed) stateChanged.fire(state);\n }\n const report = (diagnostic: IWorkbenchDiagnostic): void => {\n if (disposed) return;\n if (\n diagnostics.some(\n (value) =>\n value.code === diagnostic.code &&\n value.message === diagnostic.message &&\n value.instanceId === diagnostic.instanceId,\n )\n )\n return;\n diagnostics.push(Object.freeze({ ...diagnostic }));\n diagnosticsChanged.fire(diagnostic);\n update();\n };\n const error = (reason: unknown): void =>\n report({ code: errorCode(reason), message: errorMessage(reason), severity: 'error' });\n function refreshLayoutDiagnostics(): void {\n const retained = diagnostics.filter((item) => item.code !== 'layout/body-overlap');\n diagnostics.splice(0, diagnostics.length, ...retained);\n for (const { first, second } of findBodyOverlaps(\n documentSession.getDocument(),\n documentSession.getDevices().getLoadedDevices(),\n ))\n report({\n code: 'layout/body-overlap',\n message: `${first.designator ?? first.id} overlaps ${second.designator ?? second.id}`,\n severity: 'warning',\n instanceId: first.id,\n });\n }\n function setSelection(targets: readonly IWorkbenchTarget[]): void {\n assertReady();\n const doc = documentSession.getDocument();\n const seen = new Set<string>();\n const lists = {\n instance: doc.instances,\n wire: doc.wires,\n node: doc.nodes,\n label: doc.labels,\n reference: doc.references,\n };\n for (const target of targets) {\n if (!lists[target.kind]?.some((item) => item.id === target.id))\n throw new Error(`Unknown selection target: ${target.kind}/${target.id}`);\n if (seen.has(target.id)) throw new Error(`Duplicate selection target: ${target.id}`);\n seen.add(target.id);\n }\n const previous =\n selection.length === 1 && selection[0]?.kind === 'instance' ? selection[0].id : undefined;\n selection = Object.freeze(targets.map((target) => Object.freeze({ ...target })));\n const single =\n selection.length === 1 && selection[0]?.kind === 'instance' ? selection[0].id : undefined;\n if (previous !== undefined && previous !== single) {\n const instance = doc.instances.find((item) => item.id === previous);\n const manifest =\n instance === undefined\n ? undefined\n : documentSession.getDevices().getLoaded(instance.device)?.manifest;\n if (manifest !== undefined)\n for (const view of viewLayout(previous).views)\n if (view.location === 'sidebar') htmlViews?.close(previous, view.viewId);\n }\n for (const view of htmlViews?.views ?? [])\n if (view.location === 'sidebar' && view.instanceId !== single) view.close();\n selectionChanged.fire(selection);\n update();\n }\n function clearOverlays(): void {\n for (const image of overlays.values()) image.close();\n overlays.clear();\n }\n async function releaseRuntime(): Promise<void> {\n htmlViews?.closeAll();\n runtimeGeneration++;\n const previous = runtime;\n runtimeDocument = undefined;\n runtime = undefined;\n clearOverlays();\n await previous?.dispose();\n }\n async function loadImages(): Promise<void> {\n for (const [id, device] of documentSession.getDevices().getLoadedDevices()) {\n if (imageLocks.get(id) === device.lock.integrity) continue;\n const path = device.geometry.bodyImage;\n if (path === undefined) {\n imageLocks.set(id, device.lock.integrity);\n continue;\n }\n const bytes = await device.files.read(path);\n const image = await decodeResourceImage(bytes, path);\n if (disposed) {\n if (image instanceof ImageBitmap) image.close();\n return;\n }\n const previous = images.get(id);\n if (previous instanceof ImageBitmap) previous.close();\n images.set(id, image);\n imageLocks.set(id, device.lock.integrity);\n }\n }\n async function createRuntime(targetMode: WorkbenchMode): Promise<IFusedRuntime | undefined> {\n const generation = ++runtimeGeneration;\n const document = documentSession.getDocument();\n const devices = documentSession.getDevices().getLoadedDevices();\n if (\n targetMode === 'edit' &&\n !document.instances.some((instance) => {\n const manifest = devices.get(instance.device)?.manifest;\n return (\n manifest?.view2d?.entry !== undefined ||\n Object.values(manifest?.properties ?? {}).some((property) => property.type === 'program')\n );\n })\n )\n return undefined;\n const result = await createFusedRuntime({\n ...(options.audio === undefined ? {} : { audio: options.audio }),\n document,\n registry: options.deviceProvider,\n step,\n mode: targetMode,\n container: environment,\n ...(options.programs === undefined ? {} : { programs: options.programs }),\n resolveResource: (request) => {\n if (request.reference.mode !== 'asset' || options.assetProvider === undefined)\n throw new Error('No asset provider is configured');\n return options.assetProvider.read(request.reference.assetId, abort.signal);\n },\n onDiagnostic: (diagnostic) => {\n if (generation !== runtimeGeneration) return;\n report({\n code: diagnostic.code,\n message: diagnostic.message,\n severity: 'error',\n ...(diagnostic.instanceId === undefined ? {} : { instanceId: diagnostic.instanceId }),\n });\n },\n onOverlay: (frame) => {\n if (disposed || generation !== runtimeGeneration) {\n frame.bitmap.close();\n return;\n }\n overlays.get(frame.instanceId)?.close();\n overlays.set(frame.instanceId, frame.bitmap);\n update();\n },\n measure: (instance) => {\n const geometry = devices.get(instance.device)?.geometry;\n if (geometry === undefined) throw new Error(`Missing geometry for ${instance.instanceId}`);\n const scale = (canvas?.scale ?? 12) * (globalThis.devicePixelRatio || 1);\n return {\n width: Math.max(1, Math.ceil(geometry.bounds.width * scale)),\n height: Math.max(1, Math.ceil(geometry.bounds.height * scale)),\n scale,\n };\n },\n });\n if (disposed || generation !== runtimeGeneration) {\n await result.dispose();\n throw new Error('Workbench was disposed during runtime preparation');\n }\n runtimeDocument = document;\n return result;\n }\n function refreshPresentation(): void {\n presentation = presentation\n .then(async () => {\n if (disposed) return;\n await loadImages();\n if (disposed) return;\n if (mode === 'edit' && !busy) {\n const signature = JSON.stringify([\n documentSession.getDocument().dependencies,\n documentSession\n .getDocument()\n .instances.map((instance) => [\n instance.id,\n instance.device,\n instance.properties,\n instance.placement.width,\n instance.placement.height,\n ]),\n ]);\n if (signature !== presentationSignature) {\n await releaseRuntime();\n runtime = await createRuntime('edit');\n presentationSignature = signature;\n }\n }\n update();\n })\n .catch(error);\n }\n async function setMode(next: WorkbenchMode): Promise<void> {\n assertReady();\n if (next !== 'edit' && next !== 'run')\n throw new Error(`Invalid workbench mode: ${String(next)}`);\n const task = transition.then(async () => {\n assertReady();\n if (next === mode) return;\n busy = true;\n placement = undefined;\n tool = 'select';\n update();\n try {\n await presentation;\n if (next === 'run') {\n await documentSession.setRunning(true);\n await releaseRuntime();\n runtime = await createRuntime('run');\n await documentSession.refreshAccess();\n const permission = documentSession.getAccess().run;\n if (!permission.allowed) throw new Error(permission.message);\n mode = 'run';\n } else {\n try {\n await releaseRuntime();\n } finally {\n await documentSession.setRunning(false);\n mode = 'edit';\n presentationSignature = '';\n }\n }\n } catch (reason) {\n const failures = [reason];\n if (next === 'run') {\n try {\n await releaseRuntime();\n } catch (cleanupError) {\n failures.push(cleanupError);\n }\n try {\n await documentSession.setRunning(false);\n } catch (cleanupError) {\n failures.push(cleanupError);\n }\n mode = 'edit';\n presentationSignature = '';\n }\n const failure =\n failures.length === 1\n ? reason\n : new AggregateError(failures, 'Failed to enter and release the run session');\n error(failure);\n throw failure;\n } finally {\n busy = false;\n update();\n if (mode === 'edit') refreshPresentation();\n }\n });\n transition = task.then(\n () => undefined,\n () => undefined,\n );\n return task;\n }\n function assertEditable(): void {\n assertReady();\n if (busy || mode !== 'edit' || !documentSession.getState().canEditContent)\n throw new Error('Document is not editable');\n }\n async function placeDevice(device: DeviceLock): Promise<void> {\n assertEditable();\n await documentSession.refreshAccess();\n assertEditable();\n const dependency = documentSession.getDocument().dependencies[device.id];\n if (\n dependency !== undefined &&\n (dependency.version !== device.version || dependency.integrity !== device.integrity)\n )\n throw new Error(`A different release of ${device.id} is already locked by this document`);\n const decision = await access.canAddDevice({\n document: documentSession.getDocument(),\n device,\n });\n if (!decision.allowed) throw new Error(decision.message);\n await documentSession.getDevices().get(device);\n await loadImages();\n assertEditable();\n placement = { ...device };\n placementRotation = 0;\n tool = 'select';\n if (options.container.clientWidth <= 720) activeContainer = undefined;\n update();\n }\n function viewLayout(instanceId: string): InstanceViewLayout {\n const instance = documentSession.getDocument().instances.find((item) => item.id === instanceId);\n const manifest =\n instance === undefined\n ? undefined\n : documentSession.getDevices().getLoaded(instance.device)?.manifest;\n if (instance === undefined || manifest === undefined)\n throw new Error(`Unknown device instance: ${instanceId}`);\n return resolveViewLayout(\n transientLayouts.has(instanceId) ? transientLayouts.get(instanceId) : instance.viewLayout,\n manifest,\n options.container.clientHeight,\n );\n }\n async function changeViewLayout(\n instanceId: string,\n layout: InstanceViewLayout | undefined,\n ): Promise<void> {\n assertReady();\n viewLayout(instanceId);\n if (documentSession.getState().canEditLayout) {\n await documentSession.setViewLayout(instanceId, layout);\n transientLayouts.delete(instanceId);\n } else {\n const document = documentSession.getDocument();\n const candidate = parseFusedDocument(\n JSON.stringify({\n ...document,\n instances: document.instances.map((instance) =>\n instance.id === instanceId ? { ...instance, viewLayout: layout } : instance,\n ),\n }),\n );\n transientLayouts.set(\n instanceId,\n candidate.instances.find((instance) => instance.id === instanceId)?.viewLayout,\n );\n }\n for (const handle of htmlViews?.views ?? []) {\n if (handle.instanceId !== instanceId) continue;\n const target = viewLayout(instanceId).views.find((view) => view.viewId === handle.viewId);\n if (target === undefined) handle.close();\n else {\n handle.setLocation(target.location);\n handle.setVisible(!target.collapsed || target.location === 'floating');\n }\n }\n update();\n }\n async function openView(\n instanceId: string,\n viewId: string,\n location?: 'sidebar' | 'floating',\n ): Promise<void> {\n assertReady();\n if (mode !== 'run' || busy || htmlViews === undefined)\n throw new Error('Device HTML views are available in Run mode');\n const layout = viewLayout(instanceId);\n const target = layout.views.find((view) => view.viewId === viewId);\n if (target === undefined) throw new Error(`Unknown device view: ${viewId}`);\n const nextLocation = location ?? target.location;\n if (target.collapsed || target.location !== nextLocation)\n await changeViewLayout(instanceId, {\n ...layout,\n views: layout.views.map((view) =>\n view.viewId === viewId ? { ...view, collapsed: false, location: nextLocation } : view,\n ),\n });\n if (nextLocation === 'sidebar') {\n setSelection([{ kind: 'instance', id: instanceId }]);\n activeContainer = 'mica.properties';\n }\n const handle = await htmlViews.open({ instanceId, viewId, location: nextLocation });\n handle.setLocation(nextLocation);\n handle.setVisible(true);\n update();\n handle.focus();\n }\n const handlers: {\n [K in keyof IWorkbenchCommandMap]: (\n params: IWorkbenchCommandMap[K]['params'],\n ) => Promise<IWorkbenchCommandMap[K]['result']> | IWorkbenchCommandMap[K]['result'];\n } = {\n 'workbench.openContainer': async ({ id, focus }) => {\n const container = registry.containers.find((value) => value.id === id);\n if (container === undefined || !registry.visible(container))\n throw new Error(`Unavailable view container: ${id}`);\n activeContainer = id;\n update();\n if (focus)\n requestAnimationFrame(() =>\n mount\n .querySelector<HTMLElement>(\n '.mica-wb-sidebar input, .mica-wb-sidebar button, .mica-wb-sidebar [tabindex=\"0\"]',\n )\n ?.focus(),\n );\n },\n 'workbench.closeContainer': async () => {\n activeContainer = undefined;\n update();\n },\n 'workbench.setMode': ({ mode }) => setMode(mode),\n 'canvas.fit': async () => {\n canvas?.fit();\n },\n 'canvas.zoom': async ({ factor }) => {\n if (!(factor > 0) || !Number.isFinite(factor))\n throw new Error('Zoom factor must be positive');\n canvas?.zoom(factor);\n },\n 'canvas.setTool': async ({ tool: next }) => {\n if (!['select', 'wire', 'power', 'ground', 'label'].includes(next))\n throw new Error(`Unknown tool: ${String(next)}`);\n if (next !== 'select') assertEditable();\n tool = next;\n if (next === 'label') {\n const used = new Set(documentSession.getDocument().labels.map((label) => label.name));\n let index = 1;\n while (used.has(`NET${index}`)) index++;\n labelName = `NET${index}`;\n }\n placement = undefined;\n placementRotation = 0;\n update();\n },\n 'device.place': ({ device }) => placeDevice(device),\n 'device.add': async ({ device, placement }) => {\n assertEditable();\n const id = await documentSession.addDevice(device, placement);\n setSelection([{ kind: 'instance', id }]);\n return id;\n },\n 'device.setProperty': async ({ instanceId, key, value }) => {\n assertEditable();\n await documentSession.setProperty(instanceId, key, value);\n },\n 'device.removeProperty': async ({ instanceId, key }) => {\n assertEditable();\n await documentSession.removeProperty(instanceId, key);\n },\n 'device.move': async ({ instanceId, position }) => {\n assertEditable();\n await documentSession.moveInstance(instanceId, position);\n },\n 'device.rotate': async ({ instanceId, degrees }) => {\n assertEditable();\n await documentSession.rotateInstance(instanceId, degrees);\n },\n 'selection.delete': async () => {\n assertEditable();\n await documentSession.remove(selection);\n setSelection([]);\n },\n 'selection.rotate': async ({ degrees }) => {\n assertEditable();\n if (!Number.isFinite(degrees)) throw new Error('Rotation must be finite');\n if (placement !== undefined || tool === 'power' || tool === 'ground') {\n placementRotation = (((placementRotation + degrees) % 360) + 360) % 360;\n update();\n return;\n }\n await documentSession.transact((current) => rotateTargets(current, selection, degrees));\n },\n 'wire.moveSegment': async ({ wireId, segment, delta }) => {\n assertEditable();\n await documentSession.transact((current) =>\n moveWireSegment(\n current,\n documentSession.getDevices().getLoadedDevices(),\n wireId,\n segment,\n delta,\n ),\n );\n },\n 'text.move': async ({ target, offset }) => {\n assertEditable();\n await documentSession.transact((current) => setTextOffset(current, target, offset));\n },\n 'reference.move': async ({ referenceId, position }) => {\n assertEditable();\n await documentSession.transact((current) =>\n moveReference(\n current,\n documentSession.getDevices().getLoadedDevices(),\n referenceId,\n position,\n () => crypto.randomUUID(),\n ),\n );\n },\n 'wire.add': ({ from, to, bends }) => {\n assertEditable();\n return documentSession.addWire(from, to, bends);\n },\n 'reference.add': ({ target, voltage, symbol }) => {\n assertEditable();\n return documentSession.addReference(target, voltage, symbol);\n },\n 'label.add': ({ target, name }) => {\n assertEditable();\n return documentSession.addLabel(target, name);\n },\n 'document.undo': () => documentSession.undo(),\n 'document.redo': () => documentSession.redo(),\n 'document.save': () => documentSession.save(),\n 'view.open': ({ instanceId, viewId, location }) => openView(instanceId, viewId, location),\n 'view.setLocation': ({ instanceId, viewId, location }) =>\n openView(instanceId, viewId, location),\n 'view.close': async ({ instanceId, viewId }) => {\n const layout = viewLayout(instanceId);\n if (!layout.views.some((view) => view.viewId === viewId))\n throw new Error(`Unknown device view: ${viewId}`);\n htmlViews?.close(instanceId, viewId);\n await changeViewLayout(instanceId, {\n ...layout,\n views: layout.views.map((view) =>\n view.viewId === viewId && view.location === 'sidebar'\n ? { ...view, collapsed: true }\n : view,\n ),\n });\n },\n 'view.setLayout': ({ instanceId, layout }) => changeViewLayout(instanceId, layout),\n };\n const workbench: IWorkbench = {\n contextKeys,\n onDidChangeContent: content.event,\n onDidChangeSelection: selectionChanged.event,\n onDidChangeState: stateChanged.event,\n onDidReportDiagnostic: diagnosticsChanged.event,\n onDidRequestOpenProject: openProject.event,\n getDocument: () => {\n assertReady();\n return documentSession.getDocument();\n },\n getState: () => {\n assertReady();\n return state;\n },\n getSelection: () => {\n assertReady();\n return selection;\n },\n getTheme: () => {\n assertReady();\n return theme;\n },\n setTheme(value) {\n assertReady();\n theme = validateTheme(value);\n update();\n },\n setSelection,\n setMode: (mode) => workbench.executeCommand('workbench.setMode', { mode }),\n save: () => workbench.executeCommand('document.save'),\n async executeCommand<K extends keyof IWorkbenchCommandMap>(\n id: K,\n ...args: WorkbenchCommandArgs<IWorkbenchCommandMap[K]>\n ): Promise<IWorkbenchCommandMap[K]['result']> {\n try {\n assertReady();\n const handler = handlers[id];\n if (handler === undefined) throw new Error(`Unknown workbench command: ${String(id)}`);\n return await handler(args[0] as IWorkbenchCommandMap[K]['params']);\n } catch (reason) {\n error(reason);\n throw reason;\n }\n },\n dispose() {\n if (disposal !== undefined) return disposal;\n disposed = true;\n abort.abort();\n disposal = (async () => {\n const errors: unknown[] = [];\n const release = async (action: () => void | Promise<void>) => {\n try {\n await action();\n } catch (reason) {\n errors.push(reason);\n }\n };\n await release(() => root.unmount());\n await release(async () => {\n await transition;\n await presentation;\n await releaseRuntime();\n });\n await release(() => documentSession.dispose());\n await release(() => htmlViews?.dispose());\n await release(() => disposables.dispose());\n clearOverlays();\n for (const image of images.values()) if (image instanceof ImageBitmap) image.close();\n images.clear();\n mount.remove();\n environment.remove();\n if (errors.length)\n throw new AggregateError(errors, 'Failed to release workbench resources');\n })();\n return disposal;\n },\n };\n const context: IWorkbenchExtensionContext = { workbench, contextKeys, signal: abort.signal };\n const builtins: IWorkbenchContributions = {\n containers: [\n { id: 'mica.instances', title: '器件列表', icon: 'list-tree', order: 100 },\n { id: 'mica.properties', title: '信息', icon: 'info', order: -1000 },\n { id: 'mica.problems', title: '问题', icon: 'warning', order: 300 },\n ],\n toolbar: (['select', 'wire', 'power', 'ground', 'label'] as const).map((value, index) => ({\n id: `mica.tool.${value}`,\n title: {\n select: '选择',\n wire: '接线',\n power: '电源',\n ground: '接地',\n label: '网标',\n }[value],\n icon: { select: 'cursor', wire: 'plug', power: 'zap', ground: 'circuit-board', label: 'tag' }[\n value\n ],\n group: 'edit',\n order: index * 10,\n when: \"workbench.mode == 'edit'\",\n enablement: value === 'select' ? '!workbench.busy' : 'document.editable && !workbench.busy',\n execute: (context) => context.workbench.executeCommand('canvas.setTool', { tool: value }),\n })),\n };\n try {\n registry = new ContributionRegistry(contextKeys, builtins, options.contributions);\n htmlViews = createHtmlViewHost({\n viewBaseUrlTemplate: options.viewBaseUrlTemplate,\n container: options.container,\n registry: options.deviceProvider,\n describe(instanceId) {\n if (mode !== 'run' || busy || runtime === undefined) return undefined;\n const presentation = runtime.display.instances.find(\n (item) => item.instanceId === instanceId,\n );\n const manifest =\n presentation === undefined\n ? undefined\n : documentSession.getDevices().getLoaded(presentation.device)?.manifest;\n if (presentation === undefined || manifest === undefined) return undefined;\n return {\n device: presentation.device,\n lock: presentation.lock,\n props: presentation.props,\n methods: presentation.methods,\n events: presentation.events,\n hasModel: manifest.model !== undefined,\n views: manifest.view ?? {},\n };\n },\n model(instanceId) {\n const instance = documentSession\n .getDocument()\n .instances.find((item) => item.id === instanceId);\n if (\n instance === undefined ||\n documentSession.getDevices().getLoaded(instance.device)?.manifest.model === undefined\n )\n return undefined;\n if (runtime === undefined) throw new Error('The view model session is disconnected');\n return runtime.getModel(instanceId);\n },\n onDiagnostic: (failure) =>\n report({\n code: failure.code,\n message: `${failure.title}: ${failure.message}`,\n instanceId: failure.instanceId,\n severity: 'error',\n }),\n });\n } catch (reason) {\n await workbench.dispose();\n throw reason;\n }\n disposables.add(htmlViews.onDidChange(update));\n const ui: IWorkbenchUI = {\n workbench,\n options,\n context,\n get theme() {\n return theme;\n },\n htmlViews,\n viewLayout,\n changeViewLayout,\n contributions: registry,\n onDidUpdate: uiChanged.event,\n get devices() {\n return documentSession.getDevices().getLoadedDevices();\n },\n images,\n overlays,\n diagnostics,\n get placement() {\n return placement;\n },\n get placementRotation() {\n return placementRotation;\n },\n get version() {\n return version;\n },\n setCanvas: (value) => {\n canvas = value;\n },\n report,\n error,\n input: (instanceId, event: IViewInput) => {\n try {\n runtime?.display.input(instanceId, event);\n } catch (reason) {\n error(reason);\n }\n },\n get labelName() {\n return labelName;\n },\n setLabelName: (name) => {\n labelName = name;\n update();\n },\n connect: async (from, to, bends) => {\n assertEditable();\n await documentSession.transact((current) => {\n const devices = documentSession.getDevices().getLoadedDevices();\n const first = materializeAnchor(routeDocumentWires(current, devices), from, devices, () =>\n crypto.randomUUID(),\n );\n const last = materializeAnchor(first.document, to, devices, () => crypto.randomUUID());\n return addWire(last.document, first.endpoint, last.endpoint, bends, () =>\n crypto.randomUUID(),\n ).document;\n });\n },\n endpoint: async (target: Endpoint | Point2D) => {\n assertEditable();\n const activeTool = tool;\n const rotation = placementRotation;\n const name = labelName.trim();\n if (activeTool !== 'power' && activeTool !== 'ground' && activeTool !== 'label')\n throw new Error('未选择端子或网标放置工具');\n if (activeTool === 'label' && name === '') throw new Error('网标名称不能为空');\n await documentSession.transact((current) => {\n const anchor = materializeAnchor(\n routeDocumentWires(current, documentSession.getDevices().getLoadedDevices()),\n target,\n documentSession.getDevices().getLoadedDevices(),\n () => crypto.randomUUID(),\n );\n return activeTool === 'label'\n ? addLabel(anchor.document, anchor.endpoint, name, {}, () => crypto.randomUUID()).document\n : addReference(\n anchor.document,\n anchor.endpoint,\n activeTool === 'ground' ? 0 : 5,\n activeTool,\n { rotation },\n () => crypto.randomUUID(),\n ).document;\n });\n if (tool === activeTool) {\n tool = 'select';\n update();\n }\n },\n cancel: () => {\n placement = undefined;\n placementRotation = 0;\n tool = 'select';\n update();\n },\n focus: (value) => keys.focus.set(value),\n viewport: () => runtime?.display.invalidate(),\n reveal: (id) => {\n setSelection([{ kind: 'instance', id }]);\n canvas?.reveal(id);\n },\n validateResource: async (instanceId, key, value, signal) => {\n const instance = documentSession\n .getDocument()\n .instances.find((value) => value.id === instanceId);\n const descriptor =\n instance === undefined\n ? undefined\n : documentSession.getDevices().getLoaded(instance.device)?.manifest.properties?.[key];\n if (\n descriptor === undefined ||\n !['image', 'binary', 'firmware', 'program'].includes(descriptor.type)\n )\n throw new Error('Unknown resource property');\n if (instance === undefined) throw new Error('Unknown resource instance');\n const device = documentSession.getDevices().requireLoaded(instance.device);\n const verified = await openDevicePackage(options.deviceProvider, device.lock);\n signal.throwIfAborted();\n const resolved = await resolveInstanceProperties({\n instanceId,\n package: verified,\n descriptors: { [key]: descriptor },\n overrides: { [key]: value },\n irProperties: new Map(),\n pointer: ['properties'],\n signal,\n ...(options.programs === undefined ? {} : { programs: options.programs }),\n resolveResource: (request) => {\n if (request.reference.mode !== 'asset' || options.assetProvider === undefined)\n throw new Error('No asset provider is configured');\n return options.assetProvider.read(request.reference.assetId, signal);\n },\n });\n signal.throwIfAborted();\n const resource = resolved.props[key];\n if (\n resource &&\n typeof resource === 'object' &&\n 'slice' in resource &&\n typeof resource.slice === 'function'\n ) {\n const bytes: unknown = resource.slice();\n if (!(bytes instanceof Uint8Array)) throw new Error('Resource did not resolve to bytes');\n if (descriptor.type === 'image') {\n const sourceName =\n value !== null && typeof value === 'object'\n ? value.mode === 'package'\n ? value.src\n : (value.name ?? '')\n : '';\n const bitmap = await decodeResourceImage(bytes, sourceName);\n try {\n if (\n descriptor.maxPixels !== undefined &&\n bitmap.width * bitmap.height > descriptor.maxPixels\n )\n throw new Error('Image exceeds the property pixel limit');\n } finally {\n if (bitmap instanceof ImageBitmap) bitmap.close();\n }\n }\n signal.throwIfAborted();\n return bytes;\n }\n return undefined;\n },\n commitResource: async (instanceId, key, expected, value, signal) => {\n await documentSession.transact((current) => {\n signal.throwIfAborted();\n assertEditable();\n const instance = current.instances.find((entry) => entry.id === instanceId);\n if (\n instance === undefined ||\n JSON.stringify(instance.properties?.[key]) !== JSON.stringify(expected)\n )\n throw new Error('resource/target-changed: 属性已改变,请重新选择资源');\n return setInstanceProperty(current, instanceId, key, value);\n });\n },\n openProject: (projectId) => openProject.fire({ projectId }),\n programPackagePaths: (deviceId) =>\n Object.keys(documentSession.getDevices().getLoaded(deviceId)?.files.files ?? {}),\n programSnapshot: (instanceId) => {\n const prepared = runtimeDocument?.instances.find((instance) => instance.id === instanceId);\n const current = documentSession\n .getDocument()\n .instances.find((instance) => instance.id === instanceId);\n if (\n !prepared ||\n !current ||\n prepared.device !== current.device ||\n JSON.stringify(prepared.properties) !== JSON.stringify(current.properties)\n )\n return undefined;\n return runtime?.display.instances.find((instance) => instance.instanceId === instanceId)\n ?.props;\n },\n };\n disposables.add(\n documentSession.onDidChangeContent((value) => {\n const ids = new Set(\n [\n ...value.instances,\n ...value.wires,\n ...value.nodes,\n ...value.labels,\n ...value.references,\n ].map((item) => item.id),\n );\n if (selection.some((target) => !ids.has(target.id))) {\n selection = Object.freeze(selection.filter((target) => ids.has(target.id)));\n selectionChanged.fire(selection);\n }\n content.fire(value);\n for (const handle of htmlViews?.views ?? []) {\n if (!value.instances.some((instance) => instance.id === handle.instanceId)) {\n handle.close();\n continue;\n }\n const target = viewLayout(handle.instanceId).views.find(\n (view) => view.viewId === handle.viewId,\n );\n if (target === undefined) handle.close();\n else {\n handle.setLocation(target.location);\n handle.setVisible(target.location === 'floating' || !target.collapsed);\n }\n }\n refreshLayoutDiagnostics();\n update();\n refreshPresentation();\n }),\n );\n disposables.add(\n documentSession.onDidChangeState(() => {\n update();\n if (mode === 'run' && !documentSession.getAccess().run.allowed)\n void setMode('edit').catch(error);\n }),\n );\n disposables.add(documentSession.onDidError(error));\n disposables.add(\n contextKeys.onDidChange((event) => {\n if (registry.affected(new Set(event.names))) {\n version++;\n uiChanged.fire();\n }\n }),\n );\n options.container.append(mount, environment);\n try {\n const audio = options.audio?.context;\n if (audio !== undefined) {\n let resuming = false;\n const unlockAudio = (event: Event) => {\n if (!event.isTrusted || audio.state !== 'suspended' || resuming) return;\n // Touch and pen activation is available on release rather than pointerdown.\n if (event.type === 'pointerdown' && 'pointerType' in event && event.pointerType !== 'mouse')\n return;\n resuming = true;\n void audio\n .resume()\n .catch((reason: unknown) => {\n report({ code: 'audio/failed', message: errorMessage(reason), severity: 'error' });\n })\n .finally(() => {\n resuming = false;\n });\n };\n for (const type of ['pointerdown', 'pointerup', 'keydown']) {\n options.container.ownerDocument.addEventListener(type, unlockAudio, {\n capture: true,\n signal: abort.signal,\n });\n }\n }\n await loadImages();\n refreshLayoutDiagnostics();\n update();\n flushSync(() => root.render(<WorkbenchPart ui={ui} />));\n const preparationError = documentSession.getPreparationError();\n if (preparationError !== undefined) error(preparationError);\n refreshPresentation();\n return workbench;\n } catch (reason) {\n await workbench.dispose();\n throw reason;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,IAAa,4BAA+C,CAAC,cAAc,SAAS;;AAYpF,IAAa,2BAAb,cAA8C,MAAM;CAGvC;CACA;CAHX,YACE,SACA,QACA,SACA;EACA,MAAM,OAAO;EAHJ,KAAA,SAAA;EACA,KAAA,UAAA;EAGT,KAAK,OAAO;CACd;AACF;;;;ACfA,IAAa,iBAAb,cAAoC,MAAM;CAG7B;CACA;CAHX,YACE,SACA,YACA,UACA;EACA,MAAM,GAAG,QAAQ,aAAa,SAAS,QAAQ,WAAW,EAAE;EAHnD,KAAA,aAAA;EACA,KAAA,WAAA;EAGT,KAAK,OAAO;CACd;AACF;AAyBA,IAAM,qBAAqB;AAC3B,IAAM,aAAa;;;;;;;;;;;;AAanB,SAAgB,eAAe,YAAgC;CAC7D,OAAO,I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,QAAa,MAAM,CAAC,CAAC,MAAM,KAAK;CACpC,CAAC,CACH;CACA,YAAY,IAAI,gBAAgB,WAAW,KAAK,CAAC;CACjD,YAAY,IACV,YAAY,aAAa,UAAU;EACjC,IAAI,SAAS,SAAS,IAAI,IAAI,MAAM,KAAK,CAAC,GAAG;GAC3C;GACA,UAAU,KAAK;EACjB;CACF,CAAC,CACH;CACA,QAAQ,UAAU,OAAO,OAAO,WAAW;CAC3C,IAAI;EACF,MAAM,QAAQ,QAAQ,OAAO;EAC7B,IAAI,UAAU,KAAA,GAAW;GACvB,IAAI,WAAW;GACf,MAAM,eAAe,UAAiB;IACpC,IAAI,CAAC,MAAM,aAAa,MAAM,UAAU,eAAe,UAAU;IAEjE,IAAI,MAAM,SAAS,iBAAiB,iBAAiB,SAAS,MAAM,gBAAgB,SAClF;IACF,WAAW;IACX,MACG,OAAO,CAAC,CACR,OAAO,WAAoB;KAC1B,OAAO;MAAE,MAAM;MAAgB,SAAS,aAAa,MAAM;MAAG,UAAU;KAAQ,CAAC;IACnF,CAAC,CAAC,CACD,cAAc;KACb,WAAW;IACb,CAAC;GACL;GACA,KAAK,MAAM,QAAQ;IAAC;IAAe;IAAa;GAAS,GACvD,QAAQ,UAAU,cAAc,iBAAiB,MAAM,aAAa;IAClE,SAAS;IACT,QAAQ,MAAM;GAChB,CAAC;EAEL;EACA,MAAM,WAAW;EACjB,yBAAyB;EACzB,OAAO;EACP,gBAAgB,KAAK,OAAO,oBAAC,eAAD,EAAmB,GAAK,CAAA,CAAC,CAAC;EACtD,MAAM,mBAAmB,gBAAgB,oBAAoB;EAC7D,IAAI,qBAAqB,KAAA,GAAW,MAAM,gBAAgB;EAC1D,oBAAoB;EACpB,OAAO;CACT,SAAS,QAAQ;EACf,MAAM,UAAU,QAAQ;EACxB,MAAM;CACR;AACF"}
1
+ {"version":3,"file":"fused.js","names":["lockKey","requireFinite","takenIds","takenIds","distanceToSegment","samePoint","replaceViewLayout","distanceToSegment","_Fragment","_Fragment","_Fragment","_Fragment"],"sources":["../src/fused/context/keys.ts","../src/fused/context/condition.ts","../src/fused/context/scope.ts","../src/fused/devices.ts","../src/fused/document/errors.ts","../src/fused/document/edits.ts","../src/fused/document/copy.ts","../src/fused/canvas/geometry.ts","../src/fused/wiring.ts","../src/fused/document/verify.ts","../src/fused/document/session.ts","../src/fused/contributions/registry.ts","../src/fused/views/layout.ts","../src/fused/parts/activity-bar-part.tsx","../src/fused/canvas/renderer.ts","../src/fused/parts/canvas-part.tsx","../src/fused/parts/sidebar-part.tsx","../src/fused/parts/toolbar-part.tsx","../src/fused/views/instances.tsx","../src/fused/views/program.tsx","../src/fused/views/inspector.tsx","../src/fused/views/problems.tsx","../src/fused/parts/html-views-part.tsx","../src/fused/parts/workbench-part.tsx","../src/fused/workbench.tsx"],"sourcesContent":["import type { IDisposable } from '@mica-js/core/lifecycle';\n\n/** Scalar value a context key carries; a key that nobody registered reads as `undefined`. */\nexport type ContextValue = string | number | boolean;\n\n/**\n * Who owns a key. `workbench` is the editor itself and is the only owner allowed to claim the\n * namespaces in {@link BUILT_IN_CONTEXT_PREFIXES}; `host` covers every contributed view,\n * container and device package.\n */\nexport type ContextKeyOwner = 'workbench' | 'host';\n\n/**\n * Namespaces reserved for editor-owned state. A host-owned scope can never register these names,\n * so a contributed view cannot shadow workbench state such as the active selection or the editor\n * mode; the editor registers them from a workbench-owned scope.\n */\nexport const BUILT_IN_CONTEXT_PREFIXES: readonly string[] = ['workbench.', 'editor.'];\n\n/** Why a context key or scope operation was rejected. */\nexport type ContextRegistrationErrorReason =\n | 'duplicate-key'\n | 'invalid-key'\n | 'reserved-prefix'\n | 'owner-escalation'\n | 'type-mismatch'\n | 'disposed';\n\n/** Raised when a key, a value or a scope operation violates the context registry contract. */\nexport class ContextRegistrationError extends Error {\n constructor(\n message: string,\n readonly reason: ContextRegistrationErrorReason,\n readonly keyName: string | undefined,\n ) {\n super(message);\n this.name = 'ContextRegistrationError';\n }\n}\n\n/**\n * Widens a literal default to its primitive, so `createKey('workbench.mode', 'edit')` yields\n * `IContextKey<string>` and `set('simulate')` type-checks.\n */\nexport type ContextValueType<T> = T extends string\n ? string\n : T extends number\n ? number\n : T extends boolean\n ? boolean\n : ContextValue;\n\n/** Extra ownership metadata for one key; the default is the owning scope's owner. */\nexport interface IContextKeyOptions {\n /**\n * Declares who owns the key. A reserved prefix still requires the creating scope to be\n * workbench-owned, so this option never unlocks built-in names from a host scope.\n */\n readonly owner?: ContextKeyOwner;\n}\n\n/**\n * A typed key created inside a scope. `set` stores a local value, `reset` drops it so the key\n * falls back to its parent and then to {@link IContextKey.defaultValue}, and `dispose` removes\n * the key from its scope for good.\n */\nexport interface IContextKey<T extends ContextValue = ContextValue> extends IDisposable {\n /** Dotted name expressions reference, for example `workbench.selection.kind`. */\n readonly name: string;\n readonly defaultValue: T;\n readonly owner: ContextKeyOwner;\n /** Value stored in the owning scope; `undefined` while the key falls back to its parent. */\n readonly value: T | undefined;\n readonly disposed: boolean;\n set(value: T): void;\n reset(): void;\n}\n","import type { ContextValue } from './keys';\n\n/**\n * Reads a key by name. Unknown names return `undefined`, so independently contributed views may\n * reference keys that are registered later without an error.\n */\nexport type ContextLookup = (id: string) => ContextValue | undefined;\n\n/**\n * A parsed condition. Parsing validates once; `evaluate` is pure and reads keys through the\n * supplied lookup, so callers can evaluate the same condition against several scopes.\n */\nexport interface ICondition {\n readonly expression: string;\n /**\n * Key names the expression reads, in first-seen order. Subscribe selectively by filtering\n * `IContextChangeEvent.names` with this list.\n */\n readonly keys: readonly string[];\n evaluate(lookup: ContextLookup): boolean;\n}\n\n/** Raised for malformed expressions; `position` is the character offset of the problem. */\nexport class ConditionError extends Error {\n constructor(\n message: string,\n readonly expression: string,\n readonly position: number,\n ) {\n super(`${message} (position ${position}) in \"${expression}\"`);\n this.name = 'ConditionError';\n }\n}\n\ntype TokenKind =\n 'and' | 'or' | 'not' | 'equals' | 'not-equals' | 'open' | 'close' | 'literal' | 'key';\n\ninterface IToken {\n readonly kind: TokenKind;\n readonly text: string;\n readonly position: number;\n readonly value?: ContextValue | undefined;\n}\n\ntype ConditionNode =\n | { readonly kind: 'literal'; readonly value: ContextValue | undefined }\n | { readonly kind: 'key'; readonly id: string }\n | { readonly kind: 'not'; readonly operand: ConditionNode }\n | { readonly kind: 'and'; readonly left: ConditionNode; readonly right: ConditionNode }\n | { readonly kind: 'or'; readonly left: ConditionNode; readonly right: ConditionNode }\n | {\n readonly kind: 'compare';\n readonly operator: '==' | '!=';\n readonly left: ConditionNode;\n readonly right: ConditionNode;\n };\n\nconst INTEGER_OR_DECIMAL = /^-?[0-9]+(?:\\.[0-9]+)?/;\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_.:-]*/;\n\n/**\n * Parses a condition expression.\n *\n * Supported syntax: `&&`, `||`, `!`, parentheses, `==`, `!=`, key references and the scalar\n * literals `true`, `false`, `undefined`, `null`, numbers and single- or double-quoted strings.\n * `!` binds tighter than comparisons, which bind tighter than `&&`, which binds tighter than\n * `||`; chained comparisons need explicit parentheses. There is no `eval`/`Function` usage.\n *\n * @throws {ConditionError} when the expression is empty, has unbalanced parentheses, misses an\n * operand or operator, uses an unsupported operator/character or leaves a trailing token.\n */\nexport function parseCondition(expression: string): ICondition {\n return new ConditionParser(expression).parse();\n}\n\nclass ConditionParser {\n readonly #expression: string;\n readonly #tokens: readonly IToken[];\n readonly #keys = new Set<string>();\n #index = 0;\n\n constructor(expression: string) {\n this.#expression = expression;\n this.#tokens = tokenize(expression);\n }\n\n parse(): ICondition {\n if (this.#tokens.length === 0) {\n throw new ConditionError('Expression is empty', this.#expression, 0);\n }\n const root = this.#parseOr();\n const trailing = this.#peek();\n if (trailing !== undefined) {\n throw new ConditionError(\n `Unexpected \"${trailing.text}\"`,\n this.#expression,\n trailing.position,\n );\n }\n return {\n expression: this.#expression,\n keys: Object.freeze([...this.#keys]),\n evaluate: (lookup) => evaluateNode(root, lookup),\n };\n }\n\n #parseOr(): ConditionNode {\n let node = this.#parseAnd();\n while (this.#accept('or') !== undefined) {\n node = { kind: 'or', left: node, right: this.#parseAnd() };\n }\n return node;\n }\n\n #parseAnd(): ConditionNode {\n let node = this.#parseComparison();\n while (this.#accept('and') !== undefined) {\n node = { kind: 'and', left: node, right: this.#parseComparison() };\n }\n return node;\n }\n\n #parseComparison(): ConditionNode {\n const left = this.#parseUnary();\n const operator = this.#accept('equals') ?? this.#accept('not-equals');\n if (operator === undefined) return left;\n const right = this.#parseUnary();\n const chained = this.#peek();\n if (chained !== undefined && (chained.kind === 'equals' || chained.kind === 'not-equals')) {\n throw new ConditionError(\n 'Chained comparisons need parentheses',\n this.#expression,\n chained.position,\n );\n }\n return {\n kind: 'compare',\n operator: operator.kind === 'equals' ? '==' : '!=',\n left,\n right,\n };\n }\n\n #parseUnary(): ConditionNode {\n if (this.#accept('not') !== undefined) {\n return { kind: 'not', operand: this.#parseUnary() };\n }\n return this.#parsePrimary();\n }\n\n #parsePrimary(): ConditionNode {\n const token = this.#peek();\n if (token === undefined) {\n throw new ConditionError(\n 'Unexpected end of expression',\n this.#expression,\n this.#expression.length,\n );\n }\n if (token.kind === 'open') {\n this.#index += 1;\n const inner = this.#parseOr();\n const close = this.#peek();\n if (close?.kind !== 'close') {\n throw new ConditionError(\n 'Missing \")\"',\n this.#expression,\n close?.position ?? this.#expression.length,\n );\n }\n this.#index += 1;\n return inner;\n }\n if (token.kind === 'literal') {\n this.#index += 1;\n return { kind: 'literal', value: token.value };\n }\n if (token.kind === 'key') {\n this.#index += 1;\n this.#keys.add(token.text);\n return { kind: 'key', id: token.text };\n }\n throw new ConditionError(`Unexpected \"${token.text}\"`, this.#expression, token.position);\n }\n\n #peek(): IToken | undefined {\n return this.#tokens[this.#index];\n }\n\n #accept(kind: TokenKind): IToken | undefined {\n const token = this.#tokens[this.#index];\n if (token?.kind !== kind) return undefined;\n this.#index += 1;\n return token;\n }\n}\n\nfunction tokenize(expression: string): IToken[] {\n const tokens: IToken[] = [];\n let index = 0;\n while (index < expression.length) {\n const char = expression[index]!;\n if (/\\s/.test(char)) {\n index += 1;\n continue;\n }\n const position = index;\n if (char === '&' || char === '|') {\n if (expression[index + 1] !== char) {\n throw new ConditionError(\n `Unexpected \"${char}\"; use \"${char}${char}\"`,\n expression,\n position,\n );\n }\n tokens.push({ kind: char === '&' ? 'and' : 'or', text: `${char}${char}`, position });\n index += 2;\n continue;\n }\n if (char === '=') {\n if (expression[index + 1] !== '=') {\n throw new ConditionError('Unexpected \"=\"; use \"==\"', expression, position);\n }\n tokens.push({ kind: 'equals', text: '==', position });\n index += 2;\n continue;\n }\n if (char === '!') {\n if (expression[index + 1] === '=') {\n tokens.push({ kind: 'not-equals', text: '!=', position });\n index += 2;\n } else {\n tokens.push({ kind: 'not', text: '!', position });\n index += 1;\n }\n continue;\n }\n if (char === '(' || char === ')') {\n tokens.push({ kind: char === '(' ? 'open' : 'close', text: char, position });\n index += 1;\n continue;\n }\n if (char === \"'\" || char === '\"') {\n const text = readString(expression, index);\n tokens.push({ kind: 'literal', text, position, value: parseString(text) });\n index += text.length;\n continue;\n }\n if (/[0-9]/.test(char) || (char === '-' && /[0-9]/.test(expression[index + 1] ?? ''))) {\n const match = INTEGER_OR_DECIMAL.exec(expression.slice(index));\n if (match === null) {\n throw new ConditionError('Invalid number', expression, position);\n }\n const text = match[0];\n tokens.push({ kind: 'literal', text, position, value: Number(text) });\n index += text.length;\n continue;\n }\n if (/[A-Za-z_]/.test(char)) {\n const match = IDENTIFIER.exec(expression.slice(index));\n if (match === null) {\n throw new ConditionError(`Unexpected \"${char}\"`, expression, position);\n }\n const text = match[0];\n const value = KEYWORD_VALUES.get(text);\n if (KEYWORD_VALUES.has(text)) {\n tokens.push({ kind: 'literal', text, position, value });\n } else {\n tokens.push({ kind: 'key', text, position });\n }\n index += text.length;\n continue;\n }\n throw new ConditionError(`Unexpected character \"${char}\"`, expression, position);\n }\n return tokens;\n}\n\nconst KEYWORD_VALUES = new Map<string, ContextValue | undefined>([\n ['true', true],\n ['false', false],\n ['undefined', undefined],\n ['null', undefined],\n]);\n\n/** @returns the whole quoted literal, quotes included. */\nfunction readString(expression: string, start: number): string {\n const quote = expression[start]!;\n let index = start + 1;\n while (index < expression.length) {\n const char = expression[index]!;\n if (char === '\\\\') {\n index += 2;\n continue;\n }\n if (char === quote) return expression.slice(start, index + 1);\n index += 1;\n }\n throw new ConditionError('Unterminated string literal', expression, start);\n}\n\nfunction parseString(text: string): string {\n let value = '';\n for (let index = 1; index < text.length - 1; index += 1) {\n const char = text[index]!;\n if (char !== '\\\\') {\n value += char;\n continue;\n }\n const escaped = text[index + 1] ?? '';\n value += ESCAPES.get(escaped) ?? escaped;\n index += 1;\n }\n return value;\n}\n\nconst ESCAPES = new Map<string, string>([\n ['n', '\\n'],\n ['r', '\\r'],\n ['t', '\\t'],\n]);\n\nfunction evaluateNode(node: ConditionNode, lookup: ContextLookup): boolean {\n switch (node.kind) {\n case 'literal':\n return truthy(node.value);\n case 'key':\n return truthy(lookup(node.id));\n case 'not':\n return !evaluateNode(node.operand, lookup);\n case 'and':\n return evaluateNode(node.left, lookup) && evaluateNode(node.right, lookup);\n case 'or':\n return evaluateNode(node.left, lookup) || evaluateNode(node.right, lookup);\n case 'compare': {\n const left = resolveOperand(node.left, lookup);\n const right = resolveOperand(node.right, lookup);\n return node.operator === '==' ? left === right : left !== right;\n }\n }\n}\n\nfunction resolveOperand(node: ConditionNode, lookup: ContextLookup): ContextValue | undefined {\n switch (node.kind) {\n case 'literal':\n return node.value;\n case 'key':\n return lookup(node.id);\n default:\n return truthy(evaluateNode(node, lookup));\n }\n}\n\nfunction truthy(value: ContextValue | undefined): boolean {\n if (value === undefined) return false;\n if (typeof value === 'number') return value !== 0 && !Number.isNaN(value);\n if (typeof value === 'boolean') return value;\n return value.length > 0;\n}\n","import { Emitter, type Event, type IDisposable } from '@mica-js/core/lifecycle';\nimport { parseCondition, type ICondition } from './condition';\nimport {\n BUILT_IN_CONTEXT_PREFIXES,\n ContextRegistrationError,\n type ContextKeyOwner,\n type ContextValue,\n type ContextValueType,\n type IContextKey,\n type IContextKeyOptions,\n} from './keys';\n\n/** One effective value transition reported by a scope. */\nexport interface IContextChange {\n readonly name: string;\n readonly previous: ContextValue | undefined;\n readonly value: ContextValue | undefined;\n}\n\n/**\n * Delivered once per scope and flush. `changes` carries previous and new effective values;\n * `names` lists the same keys for callers that only filter or invalidate.\n */\nexport interface IContextChangeEvent {\n readonly scope: IContextScope;\n readonly changes: readonly IContextChange[];\n readonly names: readonly string[];\n}\n\nexport interface IContextScopeOptions {\n /** Defaults to `workbench` for the root service and `host` for child scopes. */\n readonly owner?: ContextKeyOwner;\n /** Defaults to {@link BUILT_IN_CONTEXT_PREFIXES}. */\n readonly reservedPrefixes?: readonly string[];\n}\n\n/** Constructor shape; `parent` stays internal so callers link scopes through `createScope`. */\ninterface IContextScopeInit extends IContextScopeOptions {\n readonly parent?: ContextScope;\n}\n\n/**\n * Workbench-side entry point: the root scope plus key creation. The editor owns one service and\n * hands {@link IContextKeyService.createScope} children to containers and views; those children\n * are host-owned and cannot claim reserved prefixes.\n */\nexport interface IContextKeyService extends IDisposable {\n readonly owner: ContextKeyOwner;\n readonly disposed: boolean;\n /** Fires with the effective changes of this scope only. */\n readonly onDidChange: Event<IContextChangeEvent>;\n /**\n * Creates and registers a typed key in this scope.\n *\n * @throws {ContextRegistrationError} for malformed names, invalid defaults, duplicate names in\n * this scope, reserved prefixes outside a workbench scope, or a disposed scope.\n */\n createKey<T extends ContextValue>(\n name: string,\n defaultValue: T,\n options?: IContextKeyOptions,\n ): IContextKey<ContextValueType<T>>;\n /** Effective value: local, then nearest ancestor, then the key default; `undefined` if unknown. */\n getValue(name: string): ContextValue | undefined;\n /**\n * Creates a child scope that falls back to this one.\n *\n * @param options.owner Defaults to `host`; `workbench` requires a workbench-owned parent.\n */\n createScope(options?: IContextScopeOptions): IContextScope;\n /** Defers and merges change notifications of this whole tree; fires once per scope on exit. */\n batch(run: () => void): void;\n /** Parses an expression once; see {@link ICondition.keys} for selective subscriptions. */\n compile(expression: string): ICondition;\n /** Parses `expression` when needed and evaluates it against this scope's effective values. */\n evaluate(expression: ICondition | string): boolean;\n}\n\nexport interface IContextScope extends IContextKeyService {\n readonly parent: IContextScope | undefined;\n /** Distance from the workbench root; the root is `0`. */\n readonly depth: number;\n}\n\n/**\n * Creates the editor-owned root. It defaults to `owner: 'workbench'`, so built-in keys register\n * directly; hand containers and views children from `createScope()`, which default to `host` and\n * reject reserved prefixes.\n */\nexport function createContextKeyService(options: IContextScopeOptions = {}): IContextKeyService {\n return new ContextScope(options);\n}\n\ninterface IStoredKey {\n readonly name: string;\n readonly defaultValue: ContextValue;\n readonly owner: ContextKeyOwner;\n readonly value: ContextValue | undefined;\n assign(value: ContextValue | undefined): void;\n markDisposed(): void;\n}\n\ninterface IPendingChange {\n readonly key: IStoredKey;\n readonly previous: ContextValue | undefined;\n}\n\nconst KEY_NAME = /^[A-Za-z_][A-Za-z0-9_.:-]*$/;\n\nclass ContextKey<T extends ContextValue> implements IContextKey<T>, IStoredKey {\n readonly name: string;\n readonly defaultValue: T;\n readonly owner: ContextKeyOwner;\n readonly #scope: ContextScope;\n #value: T | undefined;\n #disposed = false;\n\n constructor(name: string, defaultValue: T, owner: ContextKeyOwner, scope: ContextScope) {\n this.name = name;\n this.defaultValue = defaultValue;\n this.owner = owner;\n this.#scope = scope;\n }\n\n get value(): T | undefined {\n return this.#value;\n }\n\n get disposed(): boolean {\n return this.#disposed;\n }\n\n set(value: T): void {\n this.#assertAlive();\n if (typeof value !== typeof this.defaultValue) {\n throw new ContextRegistrationError(\n `Context key \"${this.name}\" expects a ${typeof this.defaultValue} value.`,\n 'type-mismatch',\n this.name,\n );\n }\n this.#scope.assignValue(this, value);\n }\n\n reset(): void {\n this.#assertAlive();\n if (this.#value === undefined) return;\n this.#scope.assignValue(this, undefined);\n }\n\n dispose(): void {\n if (this.#disposed) return;\n this.#disposed = true;\n this.#scope.removeKey(this);\n }\n\n assign(value: ContextValue | undefined): void {\n this.#value = value as T | undefined;\n }\n\n markDisposed(): void {\n this.#disposed = true;\n }\n\n #assertAlive(): void {\n if (this.#disposed) {\n throw new ContextRegistrationError(\n `Context key \"${this.name}\" is disposed.`,\n 'disposed',\n this.name,\n );\n }\n }\n}\n\nclass ContextBatch {\n readonly #pending = new Map<ContextScope, Map<string, IPendingChange>>();\n readonly #deferred: (() => void)[] = [];\n #depth = 0;\n #flushing = false;\n\n enter(): void {\n this.#depth += 1;\n }\n\n exit(): void {\n this.#depth -= 1;\n this.#flushWhenIdle();\n }\n\n add(scope: ContextScope, key: IStoredKey, previous: ContextValue | undefined): void {\n let entries = this.#pending.get(scope);\n if (entries === undefined) {\n entries = new Map();\n this.#pending.set(scope, entries);\n }\n if (!entries.has(key.name)) entries.set(key.name, { key, previous });\n this.#flushWhenIdle();\n }\n\n hasPending(scope: ContextScope, name: string): boolean {\n return this.#pending.get(scope)?.has(name) ?? false;\n }\n\n /** Runs now when idle, or after the next flush so deferred teardown cannot swallow events. */\n defer(run: () => void): void {\n if (this.#depth === 0 && !this.#flushing) {\n run();\n return;\n }\n this.#deferred.push(run);\n }\n\n /** Fires merged changes ancestors-first so descendants can skip keys they report themselves. */\n #flushWhenIdle(): void {\n if (this.#depth > 0 || this.#flushing) return;\n this.#flushing = true;\n try {\n while (this.#pending.size > 0) {\n const scopes = [...this.#pending.keys()].sort((left, right) => left.depth - right.depth);\n for (const scope of scopes) {\n const entries = this.#pending.get(scope);\n if (entries === undefined) continue;\n this.#pending.delete(scope);\n const changes: IContextChange[] = [];\n for (const entry of entries.values()) {\n const value = scope.getValue(entry.key.name);\n if (value !== entry.previous) {\n changes.push({ name: entry.key.name, previous: entry.previous, value });\n }\n }\n if (changes.length > 0) scope.notifyChanges(changes);\n }\n }\n } finally {\n this.#flushing = false;\n this.#runDeferred();\n }\n }\n\n #runDeferred(): void {\n while (this.#deferred.length > 0) {\n this.#deferred.shift()!();\n }\n if (this.#pending.size > 0) this.#flushWhenIdle();\n }\n}\n\nclass ContextScope implements IContextScope {\n readonly #parent: ContextScope | undefined;\n readonly #owner: ContextKeyOwner;\n readonly #reservedPrefixes: readonly string[];\n readonly #registrations = new Map<string, IStoredKey>();\n readonly #changes = new Emitter<IContextChangeEvent>();\n readonly #batch: ContextBatch;\n readonly #parentSubscription: IDisposable | undefined;\n readonly #depth: number;\n #disposed = false;\n\n /** Fires with this scope's effective changes only, never with an overridden parent change. */\n readonly onDidChange: Event<IContextChangeEvent> = this.#changes.event;\n\n constructor(options: IContextScopeInit = {}) {\n const parent = options.parent;\n this.#parent = parent;\n this.#owner = options.owner ?? 'workbench';\n this.#reservedPrefixes = options.reservedPrefixes ?? BUILT_IN_CONTEXT_PREFIXES;\n this.#depth = parent === undefined ? 0 : parent.depth + 1;\n this.#batch = parent === undefined ? new ContextBatch() : parent.#batch;\n this.#parentSubscription = parent?.onDidChange((event) => {\n if (this.#disposed) return;\n const changes = event.changes.filter((change) => this.#tracks(change.name));\n if (changes.length > 0) this.notifyChanges(changes);\n });\n }\n\n get parent(): IContextScope | undefined {\n return this.#parent;\n }\n\n get owner(): ContextKeyOwner {\n return this.#owner;\n }\n\n get depth(): number {\n return this.#depth;\n }\n\n get disposed(): boolean {\n return this.#disposed;\n }\n\n createKey<T extends ContextValue>(\n name: string,\n defaultValue: T,\n options: IContextKeyOptions = {},\n ): IContextKey<ContextValueType<T>> {\n this.#assertMutable();\n if (!KEY_NAME.test(name)) {\n throw new ContextRegistrationError(\n `Invalid context key name \"${name}\"; expected dotted segments such as \"workbench.selection.kind\".`,\n 'invalid-key',\n name,\n );\n }\n const kind = typeof defaultValue;\n if (kind !== 'string' && kind !== 'number' && kind !== 'boolean') {\n throw new ContextRegistrationError(\n `Context key \"${name}\" needs a string, number or boolean default.`,\n 'invalid-key',\n name,\n );\n }\n if (this.#registrations.has(name)) {\n throw new ContextRegistrationError(\n `Context key \"${name}\" is already registered in this scope.`,\n 'duplicate-key',\n name,\n );\n }\n const owner = options.owner ?? this.#owner;\n const reserved = this.#reservedPrefixes.some((prefix) => name.startsWith(prefix));\n if (reserved && (this.#owner !== 'workbench' || owner !== 'workbench')) {\n throw new ContextRegistrationError(\n `Context key \"${name}\" uses a reserved prefix; only a workbench-owned key in a workbench scope may register it.`,\n 'reserved-prefix',\n name,\n );\n }\n const key = new ContextKey(name, defaultValue as unknown as ContextValueType<T>, owner, this);\n this.#registrations.set(name, key);\n return key;\n }\n\n getValue(name: string): ContextValue | undefined {\n return this.#resolve(name);\n }\n\n createScope(options: IContextScopeOptions = {}): IContextScope {\n this.#assertMutable();\n const owner = options.owner ?? 'host';\n if (owner === 'workbench' && this.#owner !== 'workbench') {\n throw new ContextRegistrationError(\n 'Only a workbench-owned scope can create a workbench scope.',\n 'owner-escalation',\n undefined,\n );\n }\n return new ContextScope({\n parent: this,\n owner,\n ...(options.reservedPrefixes === undefined\n ? {}\n : { reservedPrefixes: options.reservedPrefixes }),\n });\n }\n\n batch(run: () => void): void {\n this.#assertMutable();\n this.#batch.enter();\n try {\n run();\n } finally {\n this.#batch.exit();\n }\n }\n\n compile(expression: string): ICondition {\n return parseCondition(expression);\n }\n\n evaluate(expression: ICondition | string): boolean {\n const condition = typeof expression === 'string' ? parseCondition(expression) : expression;\n return condition.evaluate((name) => this.#resolve(name));\n }\n\n dispose(): void {\n if (this.#disposed) return;\n this.#batch.enter();\n try {\n for (const key of [...this.#registrations.values()]) {\n const previous = this.effectiveValue(key);\n this.#registrations.delete(key.name);\n key.markDisposed();\n this.#batch.add(this, key, previous);\n }\n } finally {\n this.#batch.exit();\n }\n this.#disposed = true;\n this.#batch.defer(() => {\n this.#parentSubscription?.dispose();\n this.#changes.dispose();\n });\n }\n\n /** @internal Stored by the batch flush and by key assignment. */\n assignValue(key: IStoredKey, value: ContextValue | undefined): void {\n this.#assertMutable();\n if (this.#registrations.get(key.name) !== key) return;\n const previous = this.effectiveValue(key);\n key.assign(value);\n this.#batch.add(this, key, previous);\n }\n\n /** @internal Called by `dispose` of a key; the scope reports the fallback value. */\n removeKey(key: IStoredKey): void {\n if (this.#disposed) return;\n if (this.#registrations.get(key.name) !== key) return;\n const previous = this.effectiveValue(key);\n this.#registrations.delete(key.name);\n this.#batch.add(this, key, previous);\n }\n\n /** @internal Effective value including the key default when no scope registered it. */\n effectiveValue(key: IStoredKey): ContextValue {\n return this.#resolve(key.name) ?? key.defaultValue;\n }\n\n /** @internal Fires one merged event for this scope; children propagate from it. */\n notifyChanges(changes: readonly IContextChange[]): void {\n this.#changes.fire({\n scope: this,\n changes,\n names: changes.map((change) => change.name),\n });\n }\n\n /** A child tracks a parent change while it owns no local value and has no pending change. */\n #tracks(name: string): boolean {\n return (\n this.#registrations.get(name)?.value === undefined && !this.#batch.hasPending(this, name)\n );\n }\n\n /**\n * Nearest local value, else the default of the nearest scope that registered the name, else\n * `undefined` for names no scope knows.\n */\n #resolve(name: string): ContextValue | undefined {\n const value = this.#valueInChain(name);\n if (value !== undefined) return value;\n const key = this.#registrations.get(name);\n if (key !== undefined) return key.defaultValue;\n return this.#parent === undefined ? undefined : this.#parent.#resolve(name);\n }\n\n #valueInChain(name: string): ContextValue | undefined {\n const value = this.#registrations.get(name)?.value;\n if (value !== undefined) return value;\n return this.#parent === undefined ? undefined : this.#parent.#valueInChain(name);\n }\n\n #assertMutable(): void {\n if (this.#disposed) throw new Error('Context scope is disposed.');\n }\n}\n","/**\n * Verified device packages of the fused workbench (RFC 0020 / RFC 0022).\n *\n * Editing needs more than the raw registry: before a device may be placed, its locked release has\n * to prove its identity and file digests, its `view2d.geometry` (inline or a declared file) has to\n * parse against the manifest pins, and the referenced body image has to exist in the release file\n * list. This cache performs exactly that and hands the renderer the verified manifest, the parsed\n * geometry and the verified file table, so no view script and no package bytes are ever guessed.\n */\nimport type { IDisposable } from '@mica-js/core/lifecycle';\nimport { parseGeometry2D } from '@mica-js/document/fused';\nimport type {\n DeviceLock,\n FusedDocument,\n Geometry2D,\n PackageFiles,\n UnifiedDeviceManifest,\n} from '@mica-js/document/fused';\nimport { openDevicePackage, PreparationError } from '@mica-js/sdk/fused';\nimport type { VerifiedPackage } from '@mica-js/sdk/fused';\nimport type { IDeviceProvider } from './providers';\n\n/** Upper bound for a declared geometry file; a release entry above it is treated as hostile. */\nconst MAX_GEOMETRY_BYTES = 4 * 1024 * 1024;\n\n/** One locked device release, verified and ready to be placed and drawn. */\nexport interface IPreparedDevice {\n readonly lock: DeviceLock;\n readonly manifest: UnifiedDeviceManifest;\n readonly geometry: Geometry2D;\n /** Verified release file table and reader; body images and other assets are read from here. */\n readonly files: PackageFiles;\n}\n\nexport interface IDeviceCache extends IDisposable {\n /** Opens, verifies and caches one locked release; concurrent calls share one read. */\n get(lock: DeviceLock): Promise<IPreparedDevice>;\n /** Prepared release of a device id that was opened before, keyed by the full device id. */\n getLoaded(id: string): IPreparedDevice | undefined;\n /**\n * Every prepared device keyed by the full device id.\n *\n * The map identity survives edits and only changes when a release is opened, so a renderer can\n * iterate it and keep per-device caches.\n */\n getLoadedDevices(): ReadonlyMap<string, IPreparedDevice>;\n /** @throws when the device id has not been prepared yet. */\n requireLoaded(id: string): IPreparedDevice;\n /** Prepares every device an instance references; unlocked devices are rejected. */\n prepareDocument(document: FusedDocument): Promise<ReadonlyMap<string, IPreparedDevice>>;\n}\n\n/**\n * Verified package cache shared by the document session and the canvas renderer.\n *\n * Failures are not cached: a release that cannot be verified is reported to the caller and may be\n * opened again once the registry can serve it.\n */\nexport class DeviceCache implements IDeviceCache {\n readonly #registry: IDeviceProvider;\n readonly #loaded = new Map<string, IPreparedDevice>();\n readonly #byId = new Map<string, IPreparedDevice>();\n readonly #pending = new Map<string, Promise<IPreparedDevice>>();\n #snapshot: ReadonlyMap<string, IPreparedDevice> = new Map();\n #snapshotStale = false;\n #disposed = false;\n\n constructor(registry: IDeviceProvider) {\n this.#registry = registry;\n }\n\n get(lock: DeviceLock): Promise<IPreparedDevice> {\n this.#assertActive();\n const key = lockKey(lock);\n const loaded = this.#loaded.get(key);\n if (loaded !== undefined) {\n return Promise.resolve(loaded);\n }\n const pending = this.#pending.get(key);\n if (pending !== undefined) {\n return pending;\n }\n const request = this.#open(lock).finally(() => {\n this.#pending.delete(key);\n });\n this.#pending.set(key, request);\n return request;\n }\n\n getLoaded(id: string): IPreparedDevice | undefined {\n return this.#byId.get(id);\n }\n\n getLoadedDevices(): ReadonlyMap<string, IPreparedDevice> {\n if (this.#snapshotStale) {\n this.#snapshot = new Map(this.#byId);\n this.#snapshotStale = false;\n }\n return this.#snapshot;\n }\n\n requireLoaded(id: string): IPreparedDevice {\n const device = this.#byId.get(id);\n if (device === undefined) {\n throw new Error(`Device ${JSON.stringify(id)} has not been prepared.`);\n }\n return device;\n }\n\n async prepareDocument(document: FusedDocument): Promise<ReadonlyMap<string, IPreparedDevice>> {\n this.#assertActive();\n const prepared = new Map<string, IPreparedDevice>();\n await Promise.all(\n [...new Set(document.instances.map((instance) => instance.device))].map(async (deviceId) => {\n const dependency = document.dependencies[deviceId];\n if (dependency === undefined) {\n throw new PreparationError([\n problem(\n 'document/unlocked-device',\n `Instance device \"${deviceId}\" is not locked by \"dependencies\".`,\n ),\n ]);\n }\n const device = await this.get({\n id: deviceId,\n version: dependency.version,\n integrity: dependency.integrity,\n });\n prepared.set(deviceId, device);\n }),\n );\n return prepared;\n }\n\n /** Drops every cached release; late opens finish but do not repopulate the cache. */\n dispose(): void {\n this.#disposed = true;\n this.#loaded.clear();\n this.#byId.clear();\n this.#pending.clear();\n this.#snapshot = new Map();\n this.#snapshotStale = false;\n }\n\n async #open(lock: DeviceLock): Promise<IPreparedDevice> {\n const verified = await openDevicePackage(this.#registry, lock);\n const geometry = await readGeometry(verified);\n this.#assertActive();\n const device: IPreparedDevice = Object.freeze({\n lock: verified.lock,\n manifest: verified.manifest,\n geometry,\n files: verified.source,\n });\n this.#loaded.set(lockKey(verified.lock), device);\n this.#byId.set(verified.lock.id, device);\n this.#snapshotStale = true;\n return device;\n }\n\n #assertActive(): void {\n if (this.#disposed) {\n throw new Error('Device cache is disposed.');\n }\n }\n}\n\nfunction lockKey(lock: DeviceLock): string {\n return `${lock.id}@${lock.version}#${lock.integrity}`;\n}\n\nasync function readGeometry(verified: VerifiedPackage): Promise<Geometry2D> {\n const id = verified.lock.id;\n const declared = verified.manifest.view2d?.geometry;\n if (declared === undefined) {\n throw new PreparationError([\n problem(\n 'view2d/invalid-geometry',\n `${id} declares no \"view2d.geometry\", so it cannot be placed on the schematic.`,\n '/view2d',\n ),\n ]);\n }\n const pins = Object.keys(verified.manifest.pins ?? {});\n let geometry: Geometry2D;\n if (typeof declared === 'string') {\n const bytes = await verified.read(declared, MAX_GEOMETRY_BYTES);\n let text: string;\n try {\n text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch {\n throw new PreparationError([\n problem(\n 'view2d/invalid-geometry',\n `${id}/${declared} is not valid UTF-8 text.`,\n '/view2d/geometry',\n ),\n ]);\n }\n geometry = parseGeometry2D(text, pins);\n } else {\n geometry = parseGeometry2D(declared, pins);\n }\n if (geometry.bodyImage !== undefined && !Object.hasOwn(verified.files, geometry.bodyImage)) {\n throw new PreparationError([\n problem(\n 'package/missing-entry',\n `${id} declares the body image ${geometry.bodyImage}, which the release does not list.`,\n '/view2d/geometry/bodyImage',\n ),\n ]);\n }\n return geometry;\n}\n\nfunction problem(\n code: string,\n message: string,\n pointer = '',\n): {\n readonly code: string;\n readonly message: string;\n readonly pointer: string;\n} {\n return { code, message, pointer };\n}\n","/**\n * Errors of the fused workbench document session.\n *\n * Every rejection carries a stable `code`; contract violations of `@mica-js/document/fused` and\n * package preparation problems keep their own code and JSON Pointer in `problems`, so the host can\n * report them without re-parsing anything.\n */\nimport { FusedDocumentError } from '@mica-js/document/fused';\nimport { PreparationError } from '@mica-js/sdk/fused';\nimport type { AccessDecision } from '../providers';\n\n/** One problem behind a rejected document operation. */\nexport interface IFusedSessionProblem {\n readonly code: string;\n readonly message: string;\n /** JSON Pointer of the offending member; absent when the problem has no document location. */\n readonly pointer?: string;\n}\n\nexport interface IFusedSessionErrorOptions {\n readonly problems?: readonly IFusedSessionProblem[];\n /** The access decision that denied the operation. */\n readonly decision?: AccessDecision;\n readonly cause?: unknown;\n}\n\n/** Rejection of one document session operation. */\nexport class FusedSessionError extends Error {\n readonly code: string;\n readonly problems: readonly IFusedSessionProblem[];\n readonly decision: AccessDecision | undefined;\n\n constructor(code: string, message: string, options: IFusedSessionErrorOptions = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause });\n this.name = 'FusedSessionError';\n this.code = code;\n this.problems = options.problems ?? [];\n this.decision = options.decision;\n }\n}\n\n/** Rejection of one operation by the access policy, carrying the decision that denied it. */\nexport function accessDenied(\n code: string,\n decision: Extract<AccessDecision, { readonly allowed: false }>,\n): FusedSessionError {\n return new FusedSessionError(code, decision.message, { decision });\n}\n\n/** Normalizes any rejection into the session's error type, keeping contract diagnostics. */\nexport function toSessionError(\n cause: unknown,\n fallbackCode = 'edit/invalid-document',\n): FusedSessionError {\n if (cause instanceof FusedSessionError) {\n return cause;\n }\n if (cause instanceof FusedDocumentError) {\n const problems = cause.diagnostics.map((entry) => ({\n code: entry.code,\n message: entry.message,\n ...(entry.pointer === '' ? {} : { pointer: entry.pointer }),\n }));\n return new FusedSessionError('edit/invalid-document', cause.message, {\n problems,\n cause,\n });\n }\n if (cause instanceof PreparationError) {\n return new FusedSessionError('device/unavailable', cause.message, {\n problems: cause.problems,\n cause,\n });\n }\n const message = cause instanceof Error ? cause.message : String(cause);\n return new FusedSessionError(fallbackCode, message, { cause });\n}\n","/**\n * Pure document edits of the fused workbench (RFC 0024).\n *\n * Every function takes the current immutable document and returns the next one; nothing here\n * verifies packages or notifies listeners. `FusedDocumentSession` gates permission, verifies the\n * result and commits one transaction, so these functions stay testable on their own.\n */\nimport type {\n ConnectionNode,\n ConnectionWire,\n DeviceDependency,\n Endpoint,\n FusedDocument,\n FusedInstance,\n InstanceViewLayout,\n NetLabel,\n Placement2D,\n Point2D,\n PropertyValue,\n VoltageReference,\n} from '@mica-js/document/fused';\nimport type { IPreparedDevice } from '../devices';\nimport { FusedSessionError } from './errors';\n\n/** Element reference the canvas selects and edits. */\nexport interface IFusedDocumentTarget {\n readonly kind: 'instance' | 'wire' | 'node' | 'label' | 'reference';\n readonly id: string;\n}\n\nexport interface IFusedTextTarget {\n readonly kind: 'designator' | 'label' | 'reference';\n readonly id: string;\n}\n\n/** Changes only the position of the selected text, preserving its owning electrical object. */\nexport function setTextOffset(\n document: FusedDocument,\n target: IFusedTextTarget,\n offset: Point2D,\n): FusedDocument {\n const point = { x: requireFinite(offset.x, 'offset.x'), y: requireFinite(offset.y, 'offset.y') };\n if (target.kind === 'designator')\n return mapInstances(document, [target.id], (instance) => ({\n ...instance,\n designatorOffset: point,\n }));\n if (target.kind === 'label') {\n if (!document.labels.some((value) => value.id === target.id))\n throw new FusedSessionError('edit/invalid-request', `Unknown label: ${target.id}`);\n return {\n ...document,\n labels: document.labels.map((value) =>\n value.id === target.id ? { ...value, offset: point } : value,\n ),\n };\n }\n const reference = document.references.find((value) => value.id === target.id);\n const label = reference?.label;\n if (reference === undefined || label === undefined)\n throw new FusedSessionError(\n 'edit/invalid-request',\n `Reference has no movable net label: ${target.id}`,\n );\n return {\n ...document,\n references: document.references.map((value) =>\n value === reference ? { ...value, label: { ...label, offset: point } } : value,\n ),\n };\n}\n\n/** Renames the net one label declares; the anchor and display offset stay as they are. */\nexport function setLabelName(\n document: FusedDocument,\n labelId: string,\n name: string,\n): FusedDocument {\n const label = document.labels.find((value) => value.id === labelId);\n if (label === undefined)\n throw new FusedSessionError('edit/unknown-target', `Unknown label ${JSON.stringify(labelId)}.`);\n const next = requireNetName(name);\n if (next === label.name) return document;\n return {\n ...document,\n labels: document.labels.map((value) =>\n value.id === labelId ? { ...value, name: next } : value,\n ),\n };\n}\n\n/** Sets the ideal voltage of one reference; a ground symbol stays at 0 V. */\nexport function setReferenceVoltage(\n document: FusedDocument,\n referenceId: string,\n voltage: number,\n): FusedDocument {\n const reference = requireReference(document, referenceId);\n const next = requireFinite(voltage, 'voltage');\n if (reference.symbol === 'ground' && next !== 0)\n throw new FusedSessionError('edit/invalid-request', 'A ground symbol keeps 0 V.');\n if (next === reference.voltage) return document;\n return {\n ...document,\n references: document.references.map((value) =>\n value.id === referenceId ? { ...value, voltage: next } : value,\n ),\n };\n}\n\n/** Renames or removes the net name a power symbol owns. */\nexport function setReferenceLabelName(\n document: FusedDocument,\n referenceId: string,\n name: string | undefined,\n): FusedDocument {\n const reference = requireReference(document, referenceId);\n if (reference.symbol === undefined)\n throw new FusedSessionError('edit/invalid-request', 'Only a reference symbol owns a net name.');\n if (reference.symbol === 'ground')\n throw new FusedSessionError('edit/invalid-request', 'A ground symbol is always GND.');\n const label =\n name === undefined\n ? undefined\n : {\n name: requireNetName(name),\n ...(reference.label?.offset === undefined ? {} : { offset: reference.label.offset }),\n };\n if (label?.name === reference.label?.name) return document;\n const { id, target, voltage, symbol, rotation } = reference;\n const next: VoltageReference = {\n id,\n target,\n voltage,\n ...(symbol === undefined ? {} : { symbol }),\n ...(rotation === undefined ? {} : { rotation }),\n ...(label === undefined ? {} : { label }),\n };\n return {\n ...document,\n references: document.references.map((value) => (value.id === referenceId ? next : value)),\n };\n}\n\n/** Allocates one element id; the session defaults to `crypto.randomUUID`. */\nexport type IdFactory = () => string;\nexport interface IAddInstanceResult {\n readonly document: FusedDocument;\n readonly instanceId: string;\n}\n\nexport interface IFusedLabelOptions {\n readonly offset?: Point2D;\n}\n\nexport interface IFusedReferenceOptions {\n /** Clockwise rotation in degrees around the anchor; defaults to `0`. */\n readonly rotation?: number;\n /** Net name owned by the symbol together with its display offset. */\n readonly label?: { readonly name: string; readonly offset?: Point2D };\n}\n\n/**\n * Adds one placed instance and locks the release it needs.\n *\n * Physical devices drop `width`/`height` (the package geometry sizes them); flexible devices\n * require both as finite positive numbers.\n *\n * @throws {FusedSessionError} when the placement is unusable or the device id is locked to another\n * release; the dependency table is never rewritten for a new version.\n */\nexport function addInstance(\n document: FusedDocument,\n device: IPreparedDevice,\n placement: Placement2D,\n createId: IdFactory,\n): IAddInstanceResult {\n const dependencies = withDependency(document.dependencies, device.lock);\n const normalized = normalizePlacement(placement, device.geometry.sizing);\n const designator = allocateDesignator(\n device.manifest.designatorPrefix ?? 'U',\n usedDesignators(document),\n );\n const instanceId = takeFreshId(takenIds(document), createId);\n const instance: FusedInstance = {\n id: instanceId,\n device: device.lock.id,\n designator,\n placement: normalized,\n };\n return {\n document: { ...document, dependencies, instances: [...document.instances, instance] },\n instanceId,\n };\n}\n\n/**\n * Removes instances, wires, nodes, labels and references as one change.\n *\n * Removing an instance also removes its labels, references and attached wires; removing a node\n * removes what hangs on it; removing a reference drops its node anchor once nothing else uses it.\n */\nexport function removeTargets(\n document: FusedDocument,\n targets: readonly IFusedDocumentTarget[],\n): FusedDocument {\n const instances = new Map(document.instances.map((instance) => [instance.id, instance]));\n const nodes = new Map(document.nodes.map((node) => [node.id, node]));\n const wires = new Map(document.wires.map((wire) => [wire.id, wire]));\n const labels = new Map(document.labels.map((label) => [label.id, label]));\n const references = new Map(document.references.map((reference) => [reference.id, reference]));\n\n const removedInstances = new Set<string>();\n const removedNodes = new Set<string>();\n const removedWires = new Set<string>();\n const removedLabels = new Set<string>();\n const removedReferences = new Set<string>();\n const prunedAnchors = new Set<string>();\n\n for (const target of targets) {\n switch (target.kind) {\n case 'instance':\n removedInstances.add(requireEntry(instances, target).id);\n break;\n case 'node':\n removedNodes.add(requireEntry(nodes, target).id);\n break;\n case 'wire':\n removedWires.add(requireEntry(wires, target).id);\n break;\n case 'label':\n removedLabels.add(requireEntry(labels, target).id);\n break;\n case 'reference': {\n const reference = requireEntry(references, target);\n removedReferences.add(reference.id);\n if (reference.target.kind === 'node') {\n prunedAnchors.add(reference.target.node);\n }\n break;\n }\n default:\n throw new FusedSessionError(\n 'edit/invalid-request',\n `Unknown target kind ${JSON.stringify((target as { kind?: unknown }).kind)}.`,\n );\n }\n }\n\n const endpointRemoved = (endpoint: Endpoint): boolean =>\n endpoint.kind === 'pin'\n ? removedInstances.has(endpoint.instance)\n : removedNodes.has(endpoint.node);\n\n for (const wire of document.wires) {\n if (endpointRemoved(wire.from) || endpointRemoved(wire.to)) {\n removedWires.add(wire.id);\n }\n }\n for (const label of document.labels) {\n if (endpointRemoved(label.target)) {\n removedLabels.add(label.id);\n }\n }\n for (const reference of document.references) {\n if (endpointRemoved(reference.target)) {\n removedReferences.add(reference.id);\n }\n }\n\n if (\n removedInstances.size === 0 &&\n removedNodes.size === 0 &&\n removedWires.size === 0 &&\n removedLabels.size === 0 &&\n removedReferences.size === 0\n ) {\n return document;\n }\n\n const keptWires = document.wires.filter((wire) => !removedWires.has(wire.id));\n const keptLabels = document.labels.filter((label) => !removedLabels.has(label.id));\n const keptReferences = document.references.filter(\n (reference) => !removedReferences.has(reference.id),\n );\n\n // RFC 0024: deleting a symbol drops its anchor node once no wire, label or other reference uses it.\n for (const nodeId of prunedAnchors) {\n if (removedNodes.has(nodeId)) {\n continue;\n }\n const used =\n keptWires.some((wire) => touchesNode(wire, nodeId)) ||\n keptLabels.some((label) => label.target.kind === 'node' && label.target.node === nodeId) ||\n keptReferences.some(\n (reference) => reference.target.kind === 'node' && reference.target.node === nodeId,\n );\n if (!used) {\n removedNodes.add(nodeId);\n }\n }\n\n return {\n ...document,\n instances: document.instances.filter((instance) => !removedInstances.has(instance.id)),\n nodes: document.nodes.filter((node) => !removedNodes.has(node.id)),\n wires: keptWires,\n labels: keptLabels,\n references: keptReferences,\n };\n}\n\n/** Offsets instances by a scene-space delta; connections and rotation stay untouched. */\nexport function moveInstances(\n document: FusedDocument,\n instanceIds: readonly string[],\n delta: Point2D,\n): FusedDocument {\n const dx = requireFinite(delta?.x, 'delta.x');\n const dy = requireFinite(delta?.y, 'delta.y');\n return mapInstances(document, instanceIds, (instance) => ({\n ...instance,\n placement: {\n ...instance.placement,\n x: instance.placement.x + dx,\n y: instance.placement.y + dy,\n },\n }));\n}\n\n/** Moves one instance so its origin lands on `position`. */\nexport function setInstancePosition(\n document: FusedDocument,\n instanceId: string,\n position: Point2D,\n): FusedDocument {\n const x = requireFinite(position?.x, 'position.x');\n const y = requireFinite(position?.y, 'position.y');\n return mapInstances(document, [instanceId], (instance) => ({\n ...instance,\n placement: { ...instance.placement, x, y },\n }));\n}\n\n/** Rotates instances clockwise by `degrees`, normalized to `[0, 360)`. */\nexport function rotateInstances(\n document: FusedDocument,\n instanceIds: readonly string[],\n degrees: number,\n): FusedDocument {\n const delta = requireFinite(degrees, 'degrees');\n return mapInstances(document, instanceIds, (instance) => ({\n ...instance,\n placement: {\n ...instance.placement,\n rotation: normalizeDegrees(instance.placement.rotation + delta),\n },\n }));\n}\n\n/** Sets the clockwise rotation of one reference symbol around its anchor. */\nexport function setReferenceRotation(\n document: FusedDocument,\n referenceId: string,\n rotation: number,\n): FusedDocument {\n const reference = requireReference(document, referenceId);\n const next = normalizeDegrees(requireFinite(rotation, 'rotation'));\n if (next === (reference.rotation ?? 0)) return document;\n return {\n ...document,\n references: document.references.map((value) =>\n value.id === referenceId ? { ...value, rotation: next } : value,\n ),\n };\n}\n\n/** Rotates selected devices and reference symbols around their own electrical anchors. */ export function rotateTargets(\n document: FusedDocument,\n targets: readonly IFusedDocumentTarget[],\n degrees: number,\n): FusedDocument {\n const delta = requireFinite(degrees, 'degrees');\n const rotated = rotateInstances(\n document,\n targets.filter((value) => value.kind === 'instance').map((value) => value.id),\n delta,\n );\n const ids = new Set(\n targets.filter((value) => value.kind === 'reference').map((value) => value.id),\n );\n for (const id of ids) {\n if (!document.references.some((value) => value.id === id))\n throw new FusedSessionError('edit/invalid-request', `Unknown reference: ${id}`);\n }\n if (ids.size === 0) return rotated;\n return {\n ...rotated,\n references: rotated.references.map((value) =>\n ids.has(value.id)\n ? { ...value, rotation: normalizeDegrees((value.rotation ?? 0) + delta) }\n : value,\n ),\n };\n}\n\n/**\n * Renames one instance designator.\n *\n * A saved designator must be a non-empty string that no other instance uses; the value is validated\n * before the commit, so the document never carries a duplicate.\n *\n * @throws {FusedSessionError} (`edit/duplicate-designator`) when another instance owns the name.\n */\nexport function renameDesignator(\n document: FusedDocument,\n instanceId: string,\n designator: string,\n): FusedDocument {\n if (typeof designator !== 'string' || designator.length === 0) {\n throw new FusedSessionError('edit/invalid-request', 'A designator must be a non-empty string.');\n }\n const instance = requireInstance(document, instanceId);\n if (instance.designator === designator) {\n return document;\n }\n const clash = document.instances.some(\n (entry) => entry.id !== instanceId && entry.designator === designator,\n );\n if (clash) {\n throw new FusedSessionError(\n 'edit/duplicate-designator',\n `Designator \"${designator}\" is already used by another instance.`,\n );\n }\n return replaceInstance(document, { ...instance, designator });\n}\n\n/** Stores one property override; `null` is a valid value when the device declares it nullable. */\nexport function setInstanceProperty(\n document: FusedDocument,\n instanceId: string,\n key: string,\n value: PropertyValue,\n): FusedDocument {\n if (typeof key !== 'string' || key.length === 0) {\n throw new FusedSessionError(\n 'edit/invalid-request',\n 'A property key must be a non-empty string.',\n );\n }\n const instance = requireInstance(document, instanceId);\n return replaceInstance(document, {\n ...instance,\n properties: { ...(instance.properties ?? {}), [key]: value },\n });\n}\n\n/** Drops one property override; an unknown key is a no-op. */\nexport function removeInstanceProperty(\n document: FusedDocument,\n instanceId: string,\n key: string,\n): FusedDocument {\n const instance = requireInstance(document, instanceId);\n const properties = instance.properties;\n if (properties === undefined || !Object.hasOwn(properties, key)) {\n return document;\n }\n const next: Record<string, PropertyValue> = {};\n for (const [name, value] of Object.entries(properties)) {\n if (name !== key) {\n next[name] = value;\n }\n }\n return replaceInstance(\n document,\n Object.keys(next).length === 0\n ? omitKeys(instance, 'properties')\n : { ...instance, properties: next },\n );\n}\n\n/** Adds a free or junction node at `point`. */\nexport function addNode(\n document: FusedDocument,\n point: Point2D,\n kind: ConnectionNode['kind'],\n createId: IdFactory,\n): { readonly document: FusedDocument; readonly nodeId: string } {\n const x = requireFinite(point?.x, 'point.x');\n const y = requireFinite(point?.y, 'point.y');\n if (kind !== 'junction' && kind !== 'free') {\n throw new FusedSessionError(\n 'edit/invalid-request',\n 'A node kind must be \"junction\" or \"free\".',\n );\n }\n const nodeId = takeFreshId(takenIds(document), createId);\n const node: ConnectionNode = { id: nodeId, kind, x, y };\n return { document: { ...document, nodes: [...document.nodes, node] }, nodeId };\n}\n\n/** Adds one wire between two existing endpoints; `bends` are the intermediate points only. */\nexport function addWire(\n document: FusedDocument,\n from: Endpoint,\n to: Endpoint,\n bends: readonly Point2D[],\n createId: IdFactory,\n): { readonly document: FusedDocument; readonly wireId: string } {\n requireEndpoint(document, from, 'from');\n requireEndpoint(document, to, 'to');\n if (sameEndpoint(from, to)) {\n throw new FusedSessionError(\n 'edit/invalid-request',\n 'A wire must connect two different endpoints.',\n );\n }\n const points = (bends ?? []).map((bend, index) => ({\n x: requireFinite(bend?.x, `bends[${String(index)}].x`),\n y: requireFinite(bend?.y, `bends[${String(index)}].y`),\n }));\n const wireId = takeFreshId(takenIds(document), createId);\n const wire: ConnectionWire = { id: wireId, from, to, bends: points };\n return { document: { ...document, wires: [...document.wires, wire] }, wireId };\n}\n\n/** Declares a net name on one endpoint. */\nexport function addLabel(\n document: FusedDocument,\n target: Endpoint,\n name: string,\n options: IFusedLabelOptions = {},\n createId: IdFactory,\n): { readonly document: FusedDocument; readonly labelId: string } {\n requireEndpoint(document, target, 'target');\n if (typeof name !== 'string' || name.length === 0) {\n throw new FusedSessionError('edit/invalid-request', 'A net name must be a non-empty string.');\n }\n const offset = readOffset(options.offset, 'options.offset');\n const labelId = takeFreshId(takenIds(document), createId);\n const label: NetLabel = {\n id: labelId,\n target,\n name,\n ...(offset === undefined ? {} : { offset }),\n };\n return { document: { ...document, labels: [...document.labels, label] }, labelId };\n}\n\n/** Attaches an ideal voltage reference, optionally with the built-in power or ground symbol. */\nexport function addReference(\n document: FusedDocument,\n target: Endpoint,\n voltage: number,\n symbol: VoltageReference['symbol'],\n options: IFusedReferenceOptions = {},\n createId: IdFactory,\n): { readonly document: FusedDocument; readonly referenceId: string } {\n requireEndpoint(document, target, 'target');\n const value = requireFinite(voltage, 'voltage');\n if (symbol !== undefined && symbol !== 'power' && symbol !== 'ground') {\n throw new FusedSessionError(\n 'edit/invalid-request',\n 'A reference symbol must be \"power\", \"ground\" or omitted.',\n );\n }\n if (symbol === 'ground' && value !== 0) {\n throw new FusedSessionError(\n 'edit/invalid-request',\n 'The ground symbol requires a reference voltage of 0.',\n );\n }\n const rotation =\n options.rotation === undefined\n ? undefined\n : requireFinite(options.rotation, 'options.rotation');\n const label = readReferenceLabel(options.label);\n const referenceId = takeFreshId(takenIds(document), createId);\n const reference: VoltageReference = {\n id: referenceId,\n target,\n voltage: value,\n ...(symbol === undefined ? {} : { symbol }),\n ...(rotation === undefined || rotation === 0 ? {} : { rotation }),\n ...(label === undefined ? {} : { label }),\n };\n return {\n document: { ...document, references: [...document.references, reference] },\n referenceId,\n };\n}\n\n/** Stores the per-instance sidebar and HTML view layout; `undefined` restores the defaults. */\nexport function setViewLayout(\n document: FusedDocument,\n instanceId: string,\n layout: InstanceViewLayout | undefined,\n): FusedDocument {\n const instance = requireInstance(document, instanceId);\n return replaceInstance(\n document,\n layout === undefined ? omitViewLayout(instance) : { ...instance, viewLayout: layout },\n );\n}\n\n/** Finds one instance. */\nexport function findInstance(\n document: FusedDocument,\n instanceId: string,\n): FusedInstance | undefined {\n return document.instances.find((instance) => instance.id === instanceId);\n}\n\n/** Locks `lock` in the dependency table, refusing to replace a different release. */\nexport function withDependency(\n dependencies: Readonly<Record<string, DeviceDependency>>,\n lock: { readonly id: string; readonly version: string; readonly integrity: string },\n): Readonly<Record<string, DeviceDependency>> {\n const existing = dependencies[lock.id];\n if (existing !== undefined) {\n if (existing.version !== lock.version || existing.integrity !== lock.integrity) {\n throw new FusedSessionError(\n 'document/locked-conflict',\n `\"${lock.id}\" is already locked to ${existing.version}; replace the dependency explicitly instead of overwriting it.`,\n );\n }\n return dependencies;\n }\n return { ...dependencies, [lock.id]: { version: lock.version, integrity: lock.integrity } };\n}\n\n/** Smallest unused `<prefix><n>` designator, starting at 1 (RFC 0024). */\nexport function allocateDesignator(prefix: string, used: ReadonlySet<string>): string {\n for (let index = 1; ; index += 1) {\n const candidate = `${prefix}${String(index)}`;\n if (!used.has(candidate)) {\n return candidate;\n }\n }\n}\n\nexport function usedDesignators(document: FusedDocument): Set<string> {\n const used = new Set<string>();\n for (const instance of document.instances) {\n if (instance.designator !== undefined) {\n used.add(instance.designator);\n }\n }\n return used;\n}\n\n/** Every element id the document already uses; new ids must not collide with any of them. */\nexport function takenIds(document: FusedDocument): Set<string> {\n return new Set<string>([\n ...document.instances.map((entry) => entry.id),\n ...document.nodes.map((entry) => entry.id),\n ...document.wires.map((entry) => entry.id),\n ...document.labels.map((entry) => entry.id),\n ...document.references.map((entry) => entry.id),\n ]);\n}\n\n/** Allocates an id that `taken` does not contain and records it. */\nexport function takeFreshId(taken: Set<string>, createId: IdFactory): string {\n for (let attempt = 0; attempt < 128; attempt += 1) {\n const id = createId();\n if (!taken.has(id)) {\n taken.add(id);\n return id;\n }\n }\n throw new FusedSessionError('edit/invalid-request', 'Could not allocate a unique element id.');\n}\n\n/** Validates that an endpoint names an object of this document. */\nexport function requireEndpoint(document: FusedDocument, endpoint: Endpoint, label: string): void {\n if (endpoint === null || typeof endpoint !== 'object') {\n throw new FusedSessionError(\n 'edit/invalid-request',\n `\"${label}\" must be a pin or node endpoint.`,\n );\n }\n if (endpoint.kind === 'pin') {\n if (\n typeof endpoint.instance !== 'string' ||\n !document.instances.some((instance) => instance.id === endpoint.instance)\n ) {\n throw new FusedSessionError(\n 'edit/unknown-target',\n `\"${label}\" references the unknown instance ${JSON.stringify(endpoint.instance)}.`,\n );\n }\n if (typeof endpoint.pin !== 'string' || endpoint.pin.length === 0) {\n throw new FusedSessionError('edit/invalid-request', `\"${label}\" needs a pin id.`);\n }\n return;\n }\n if (endpoint.kind === 'node') {\n if (\n typeof endpoint.node !== 'string' ||\n !document.nodes.some((node) => node.id === endpoint.node)\n ) {\n throw new FusedSessionError(\n 'edit/unknown-target',\n `\"${label}\" references the unknown node ${JSON.stringify(endpoint.node)}.`,\n );\n }\n return;\n }\n throw new FusedSessionError('edit/invalid-request', `\"${label}\" has an unknown endpoint kind.`);\n}\n\nfunction normalizePlacement(placement: Placement2D, sizing: 'physical' | 'flexible'): Placement2D {\n if (placement === null || typeof placement !== 'object') {\n throw new FusedSessionError('edit/invalid-request', 'A placement object is required.');\n }\n const x = requireFinite(placement.x, 'placement.x');\n const y = requireFinite(placement.y, 'placement.y');\n const rotation = requireFinite(placement.rotation ?? 0, 'placement.rotation');\n if (sizing === 'physical') {\n return { x, y, rotation };\n }\n return {\n x,\n y,\n rotation,\n width: requirePositive(placement.width, 'placement.width'),\n height: requirePositive(placement.height, 'placement.height'),\n };\n}\n\nfunction mapInstances(\n document: FusedDocument,\n instanceIds: readonly string[],\n update: (instance: FusedInstance) => FusedInstance,\n): FusedDocument {\n const ids = new Set(instanceIds);\n for (const id of ids) {\n requireInstance(document, id);\n }\n if (ids.size === 0) {\n return document;\n }\n return {\n ...document,\n instances: document.instances.map((instance) =>\n ids.has(instance.id) ? update(instance) : instance,\n ),\n };\n}\n\nfunction replaceInstance(document: FusedDocument, instance: FusedInstance): FusedDocument {\n return {\n ...document,\n instances: document.instances.map((entry) => (entry.id === instance.id ? instance : entry)),\n };\n}\n\nfunction requireInstance(document: FusedDocument, instanceId: string): FusedInstance {\n const instance = findInstance(document, instanceId);\n if (instance === undefined) {\n throw new FusedSessionError(\n 'edit/unknown-target',\n `Unknown instance ${JSON.stringify(instanceId)}.`,\n );\n }\n return instance;\n}\n\nfunction requireReference(document: FusedDocument, referenceId: string): VoltageReference {\n const reference = document.references.find((value) => value.id === referenceId);\n if (reference === undefined) {\n throw new FusedSessionError(\n 'edit/unknown-target',\n `Unknown reference ${JSON.stringify(referenceId)}.`,\n );\n }\n return reference;\n}\n\nfunction requireNetName(name: string): string {\n const trimmed = typeof name === 'string' ? name.trim() : '';\n if (trimmed.length === 0) {\n throw new FusedSessionError('edit/invalid-request', 'A net name must be a non-empty string.');\n }\n return trimmed;\n}\n\nfunction requireEntry<T extends { readonly id: string }>(\n entries: ReadonlyMap<string, T>,\n target: IFusedDocumentTarget,\n): T {\n const entry = entries.get(target.id);\n if (entry === undefined) {\n throw new FusedSessionError(\n 'edit/unknown-target',\n `Unknown ${target.kind} ${JSON.stringify(target.id)}.`,\n );\n }\n return entry;\n}\n\nfunction touchesNode(wire: ConnectionWire, nodeId: string): boolean {\n return (\n (wire.from.kind === 'node' && wire.from.node === nodeId) ||\n (wire.to.kind === 'node' && wire.to.node === nodeId)\n );\n}\n\nexport function sameEndpoint(a: Endpoint, b: Endpoint): boolean {\n if (a.kind === 'pin' && b.kind === 'pin') {\n return a.instance === b.instance && a.pin === b.pin;\n }\n if (a.kind === 'node' && b.kind === 'node') {\n return a.node === b.node;\n }\n return false;\n}\n\nfunction normalizeDegrees(value: number): number {\n const normalized = value % 360;\n return normalized < 0 ? normalized + 360 : normalized;\n}\n\nfunction readOffset(value: Point2D | undefined, label: string): Point2D | undefined {\n if (value === undefined) {\n return undefined;\n }\n return { x: requireFinite(value.x, `${label}.x`), y: requireFinite(value.y, `${label}.y`) };\n}\n\nfunction readReferenceLabel(\n value: IFusedReferenceOptions['label'],\n): { readonly name: string; readonly offset?: Point2D } | undefined {\n if (value === undefined) {\n return undefined;\n }\n if (typeof value.name !== 'string' || value.name.length === 0) {\n throw new FusedSessionError(\n 'edit/invalid-request',\n 'A reference label needs a non-empty net name.',\n );\n }\n const offset = readOffset(value.offset, 'options.label.offset');\n return { name: value.name, ...(offset === undefined ? {} : { offset }) };\n}\n\nfunction omitViewLayout(instance: FusedInstance): FusedInstance {\n return omitKeys(instance, 'viewLayout');\n}\n\nfunction omitKeys(\n instance: FusedInstance,\n ...keys: readonly (keyof FusedInstance)[]\n): FusedInstance {\n const next: Record<string, unknown> = { ...instance };\n for (const key of keys) {\n delete next[key];\n }\n return next as unknown as FusedInstance;\n}\n\nfunction requireFinite(value: number, label: string): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new FusedSessionError('edit/invalid-request', `\"${label}\" must be a finite number.`);\n }\n return value;\n}\n\nfunction requirePositive(value: number | undefined, label: string): number {\n const number = requireFinite(value as number, label);\n if (number <= 0) {\n throw new FusedSessionError('edit/invalid-request', `\"${label}\" must be a positive number.`);\n }\n return number;\n}\n","/**\n * Clipboard of a fused subgraph (RFC 0024).\n *\n * A copy keeps only what stays inside the selection: instances and nodes that were selected, the\n * wires between them, and the labels and references attached to them. Edges to objects outside the\n * selection are neither copied nor retargeted; a paste allocates new ids and designators and maps\n * every internal reference onto the copy.\n */\nimport type {\n ConnectionNode,\n ConnectionWire,\n DeviceDependency,\n Endpoint,\n FusedDocument,\n FusedInstance,\n NetLabel,\n Point2D,\n VoltageReference,\n} from '@mica-js/document/fused';\nimport type { IPreparedDevice } from '../devices';\nimport { FusedSessionError } from './errors';\nimport type { IFusedDocumentTarget } from './edits';\nimport {\n allocateDesignator,\n takeFreshId,\n takenIds,\n usedDesignators,\n withDependency,\n} from './edits';\nimport type { IdFactory } from './edits';\n\n/** Selected subgraph and the locks its devices need. */\nexport interface IFusedClipboard {\n readonly dependencies: Readonly<Record<string, DeviceDependency>>;\n readonly instances: readonly FusedInstance[];\n readonly nodes: readonly ConnectionNode[];\n readonly wires: readonly ConnectionWire[];\n readonly labels: readonly NetLabel[];\n readonly references: readonly VoltageReference[];\n}\n\n/**\n * Extracts the selected subgraph; a pure read that records no history.\n *\n * Unknown target ids are ignored. Returns `undefined` when the selection holds no instance or node.\n */\nexport function copyTargets(\n document: FusedDocument,\n targets: readonly IFusedDocumentTarget[],\n): IFusedClipboard | undefined {\n const instanceIds = new Set(\n targets.filter((target) => target.kind === 'instance').map((target) => target.id),\n );\n const nodeIds = new Set(\n targets.filter((target) => target.kind === 'node').map((target) => target.id),\n );\n const instances = document.instances.filter((instance) => instanceIds.has(instance.id));\n const nodes = document.nodes.filter((node) => nodeIds.has(node.id));\n if (instances.length === 0 && nodes.length === 0) {\n return undefined;\n }\n const selectedInstances = new Set(instances.map((instance) => instance.id));\n const selectedNodes = new Set(nodes.map((node) => node.id));\n const inside = (endpoint: Endpoint): boolean =>\n endpoint.kind === 'pin'\n ? selectedInstances.has(endpoint.instance)\n : selectedNodes.has(endpoint.node);\n\n const dependencies: Record<string, DeviceDependency> = {};\n for (const instance of instances) {\n const dependency = document.dependencies[instance.device];\n if (dependency !== undefined) {\n dependencies[instance.device] = dependency;\n }\n }\n\n return {\n dependencies,\n instances,\n nodes,\n wires: document.wires.filter((wire) => inside(wire.from) && inside(wire.to)),\n labels: document.labels.filter((label) => inside(label.target)),\n references: document.references.filter((reference) => inside(reference.target)),\n };\n}\n\n/**\n * Inserts a copied subgraph at `offset` with new ids, designators and internal references.\n *\n * @throws {FusedSessionError} when a copied device is not locked by the clipboard, its release\n * conflicts with the document lock, or it has not been prepared.\n */\nexport function pasteClipboard(\n document: FusedDocument,\n clipboard: IFusedClipboard,\n offset: Point2D,\n prepared: ReadonlyMap<string, IPreparedDevice>,\n createId: IdFactory,\n): FusedDocument {\n const dx = requireFinite(offset?.x, 'offset.x');\n const dy = requireFinite(offset?.y, 'offset.y');\n if (clipboard.instances.length === 0) {\n return document;\n }\n\n let dependencies = document.dependencies;\n for (const instance of clipboard.instances) {\n const device = prepared.get(instance.device);\n if (device === undefined) {\n throw new FusedSessionError(\n 'device/unavailable',\n `Cannot paste ${instance.device}: its release has not been prepared.`,\n );\n }\n dependencies = withDependency(dependencies, device.lock);\n }\n\n const taken = takenIds(document);\n const designators = usedDesignators(document);\n const instanceIds = new Map<string, string>();\n const instances = clipboard.instances.map((instance) => {\n const id = takeFreshId(taken, createId);\n instanceIds.set(instance.id, id);\n const prefix = prepared.get(instance.device)?.manifest.designatorPrefix ?? 'U';\n const designator = allocateDesignator(prefix, designators);\n designators.add(designator);\n return {\n ...instance,\n id,\n designator,\n placement: {\n ...instance.placement,\n x: instance.placement.x + dx,\n y: instance.placement.y + dy,\n },\n };\n });\n\n const nodeIds = new Map<string, string>();\n const nodes = clipboard.nodes.map((node) => {\n const id = takeFreshId(taken, createId);\n nodeIds.set(node.id, id);\n return { ...node, id, x: node.x + dx, y: node.y + dy };\n });\n\n const remap = (endpoint: Endpoint): Endpoint | undefined => {\n if (endpoint.kind === 'pin') {\n const instance = instanceIds.get(endpoint.instance);\n return instance === undefined ? undefined : { kind: 'pin', instance, pin: endpoint.pin };\n }\n const node = nodeIds.get(endpoint.node);\n return node === undefined ? undefined : { kind: 'node', node };\n };\n\n const wires: ConnectionWire[] = [];\n for (const wire of clipboard.wires) {\n const from = remap(wire.from);\n const to = remap(wire.to);\n if (from === undefined || to === undefined) {\n continue;\n }\n wires.push({\n id: takeFreshId(taken, createId),\n from,\n to,\n bends: wire.bends.map((bend) => ({ x: bend.x + dx, y: bend.y + dy })),\n });\n }\n\n const labels: NetLabel[] = [];\n for (const label of clipboard.labels) {\n const target = remap(label.target);\n if (target === undefined) {\n continue;\n }\n labels.push({ ...label, id: takeFreshId(taken, createId), target });\n }\n\n const references: VoltageReference[] = [];\n for (const reference of clipboard.references) {\n const target = remap(reference.target);\n if (target === undefined) {\n continue;\n }\n references.push({ ...reference, id: takeFreshId(taken, createId), target });\n }\n\n return {\n ...document,\n dependencies,\n instances: [...document.instances, ...instances],\n nodes: [...document.nodes, ...nodes],\n wires: [...document.wires, ...wires],\n labels: [...document.labels, ...labels],\n references: [...document.references, ...references],\n };\n}\n\nfunction requireFinite(value: number, label: string): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new FusedSessionError('edit/invalid-request', `\"${label}\" must be a finite number.`);\n }\n return value;\n}\n","import type {\n Endpoint,\n FusedDocument,\n FusedInstance,\n Geometry2D,\n NetLabel,\n Point2D,\n Rect2D,\n UnifiedDeviceManifest,\n VoltageReference,\n} from '@mica-js/document/fused';\nimport type { IFusedTextTarget } from '../document/edits';\n\nexport interface ICanvasDevice {\n readonly manifest: UnifiedDeviceManifest;\n readonly geometry: Geometry2D;\n}\n\nexport interface IViewport {\n readonly scale: number;\n readonly x: number;\n readonly y: number;\n}\n\nexport function toScene(point: Point2D, viewport: IViewport): Point2D {\n return { x: (point.x - viewport.x) / viewport.scale, y: (point.y - viewport.y) / viewport.scale };\n}\n\nexport function toScreen(point: Point2D, viewport: IViewport): Point2D {\n return { x: point.x * viewport.scale + viewport.x, y: point.y * viewport.scale + viewport.y };\n}\n\nexport function localToScene(\n instance: FusedInstance,\n geometry: Geometry2D,\n point: Point2D,\n): Point2D {\n const placement = instance.placement;\n const flexible = geometry.sizing === 'flexible';\n const x = flexible\n ? ((point.x - geometry.bounds.x) * (placement.width ?? geometry.bounds.width)) /\n geometry.bounds.width\n : point.x;\n const y = flexible\n ? ((point.y - geometry.bounds.y) * (placement.height ?? geometry.bounds.height)) /\n geometry.bounds.height\n : point.y;\n const angle = (placement.rotation * Math.PI) / 180;\n return {\n x: placement.x + x * Math.cos(angle) - y * Math.sin(angle),\n y: placement.y + x * Math.sin(angle) + y * Math.cos(angle),\n };\n}\n\nexport function sceneToLocal(\n instance: FusedInstance,\n geometry: Geometry2D,\n point: Point2D,\n): Point2D {\n const angle = (-instance.placement.rotation * Math.PI) / 180;\n const dx = point.x - instance.placement.x;\n const dy = point.y - instance.placement.y;\n const x = dx * Math.cos(angle) - dy * Math.sin(angle);\n const y = dx * Math.sin(angle) + dy * Math.cos(angle);\n if (geometry.sizing !== 'flexible') return { x, y };\n return {\n x:\n (x * geometry.bounds.width) / (instance.placement.width ?? geometry.bounds.width) +\n geometry.bounds.x,\n y:\n (y * geometry.bounds.height) / (instance.placement.height ?? geometry.bounds.height) +\n geometry.bounds.y,\n };\n}\n\nexport function contains(rect: Rect2D, point: Point2D): boolean {\n return (\n point.x >= rect.x &&\n point.y >= rect.y &&\n point.x <= rect.x + rect.width &&\n point.y <= rect.y + rect.height\n );\n}\n\nexport function endpointPosition(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n endpoint: Endpoint,\n): Point2D {\n if (endpoint.kind === 'node') {\n const node = document.nodes.find((value) => value.id === endpoint.node);\n if (node === undefined) throw new Error(`Unknown connection node: ${endpoint.node}`);\n return node;\n }\n const instance = document.instances.find((value) => value.id === endpoint.instance);\n const device = instance === undefined ? undefined : devices.get(instance.device);\n const pin = device?.geometry.pins[endpoint.pin];\n if (instance === undefined || device === undefined || pin === undefined)\n throw new Error(`Unknown pin: ${endpoint.instance}/${endpoint.pin}`);\n return localToScene(instance, device.geometry, pin.position);\n}\n\nexport interface IPinHit {\n readonly endpoint: Endpoint;\n readonly point: Point2D;\n readonly title: string;\n}\n\nexport function pickPins(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n point: Point2D,\n tolerance: number,\n): readonly IPinHit[] {\n return document.instances.flatMap((instance) => {\n const device = devices.get(instance.device);\n if (device === undefined) return [];\n return Object.entries(device.geometry.pins).flatMap(([pin, geometry]) => {\n const position = localToScene(instance, device.geometry, geometry.position);\n return Math.hypot(position.x - point.x, position.y - point.y) <= tolerance\n ? [\n {\n endpoint: { kind: 'pin' as const, instance: instance.id, pin },\n point: position,\n title: `${instance.designator ?? instance.id} · ${device.manifest.pins?.[pin]?.label ?? pin}`,\n },\n ]\n : [];\n });\n });\n}\n\nexport function pickInstance(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n point: Point2D,\n visible: (instance: FusedInstance) => boolean = () => true,\n): FusedInstance | undefined {\n return [...document.instances].reverse().find((instance) => {\n const device = devices.get(instance.device);\n return (\n device !== undefined &&\n visible(instance) &&\n contains(device.geometry.bounds, sceneToLocal(instance, device.geometry, point))\n );\n });\n}\n\nexport function labelBounds(label: NetLabel): Rect2D {\n return {\n x: label.offset?.x ?? 0.3,\n y: (label.offset?.y ?? -0.35) - 0.75,\n width: Math.max(0.5, label.name.length * 0.5),\n height: 0.9,\n };\n}\n\nexport function designatorPosition(instance: FusedInstance, geometry: Geometry2D): Point2D {\n const anchor = geometry.designator ?? { x: geometry.bodyBounds.x, y: geometry.bodyBounds.y };\n return localToScene(instance, geometry, {\n x: anchor.x + (instance.designatorOffset?.x ?? 0),\n y: anchor.y + (instance.designatorOffset?.y ?? 0),\n });\n}\n\nexport function referenceTextBounds(reference: VoltageReference): Rect2D {\n const name = reference.label?.name ?? `${reference.voltage} V`;\n return {\n x: reference.label?.offset?.x ?? 0.7,\n y: (reference.label?.offset?.y ?? -1.4) - 0.75,\n width: Math.max(0.5, name.length * 0.5),\n height: 0.9,\n };\n}\n\nfunction referenceToLocal(reference: VoltageReference, delta: Point2D): Point2D {\n const angle = -((reference.rotation ?? 0) * Math.PI) / 180;\n return {\n x: delta.x * Math.cos(angle) - delta.y * Math.sin(angle),\n y: delta.x * Math.sin(angle) + delta.y * Math.cos(angle),\n };\n}\n\nexport function pickText(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n point: Point2D,\n scale: number,\n): IFusedTextTarget | undefined {\n for (const reference of [...document.references].reverse()) {\n if (reference.symbol === 'ground' || reference.label === undefined) continue;\n const anchor = endpointPosition(document, devices, reference.target);\n const local = referenceToLocal(reference, { x: point.x - anchor.x, y: point.y - anchor.y });\n if (containsExpanded(referenceTextBounds(reference), local, 2 / scale))\n return { kind: 'reference', id: reference.id };\n }\n for (const label of [...document.labels].reverse()) {\n const anchor = endpointPosition(document, devices, label.target);\n if (\n containsExpanded(\n labelBounds(label),\n { x: point.x - anchor.x, y: point.y - anchor.y },\n 2 / scale,\n )\n )\n return { kind: 'label', id: label.id };\n }\n for (const instance of [...document.instances].reverse()) {\n const geometry = devices.get(instance.device)?.geometry;\n if (instance.designator === undefined || geometry === undefined) continue;\n const anchor = designatorPosition(instance, geometry);\n if (\n containsExpanded(\n {\n x: anchor.x,\n y: anchor.y - 16 / scale,\n width: (instance.designator.length * 7) / scale,\n height: 13 / scale,\n },\n point,\n 2 / scale,\n )\n )\n return { kind: 'designator', id: instance.id };\n }\n return undefined;\n}\n\n/** Converts a scene-space text drag into the persisted offset in its owner's coordinates. */\nexport function textDragOffset(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n target: IFusedTextTarget,\n delta: Point2D,\n): Point2D {\n if (target.kind === 'designator') {\n const instance = document.instances.find((value) => value.id === target.id);\n const geometry = instance === undefined ? undefined : devices.get(instance.device)?.geometry;\n if (instance === undefined || geometry === undefined)\n throw new Error(`Unknown designator: ${target.id}`);\n const origin = sceneToLocal(instance, geometry, instance.placement);\n const moved = sceneToLocal(instance, geometry, {\n x: instance.placement.x + delta.x,\n y: instance.placement.y + delta.y,\n });\n return {\n x: (instance.designatorOffset?.x ?? 0) + moved.x - origin.x,\n y: (instance.designatorOffset?.y ?? 0) + moved.y - origin.y,\n };\n }\n if (target.kind === 'label') {\n const label = document.labels.find((value) => value.id === target.id);\n if (label === undefined) throw new Error(`Unknown label: ${target.id}`);\n return { x: (label.offset?.x ?? 0.3) + delta.x, y: (label.offset?.y ?? -0.35) + delta.y };\n }\n const reference = document.references.find((value) => value.id === target.id);\n if (reference?.label === undefined)\n throw new Error(`Reference has no movable net label: ${target.id}`);\n const local = referenceToLocal(reference, delta);\n return {\n x: (reference.label.offset?.x ?? 0.7) + local.x,\n y: (reference.label.offset?.y ?? -1.4) + local.y,\n };\n}\n\nexport function referenceSymbolBounds(reference: VoltageReference): Rect2D {\n return reference.symbol === 'ground'\n ? { x: -0.7, y: -1.8, width: 1.4, height: 1.8 }\n : { x: -0.5, y: -1.3, width: 1, height: 1.3 };\n}\n\nexport function referenceBounds(reference: VoltageReference): Rect2D {\n const symbol = referenceSymbolBounds(reference);\n if (reference.symbol === 'ground') return symbol;\n const text = referenceTextBounds(reference);\n const left = Math.min(symbol.x, text.x);\n const top = Math.min(symbol.y, text.y);\n return {\n x: left,\n y: top,\n width: Math.max(symbol.x + symbol.width, text.x + text.width) - left,\n height: Math.max(symbol.y + symbol.height, text.y + text.height) - top,\n };\n}\n\n/** Annotation symbols use the same anchor, rotation and bounds for painting and picking. */\nexport function pickAnnotation(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n point: Point2D,\n tolerance: number,\n): { readonly kind: 'reference' | 'label'; readonly id: string } | undefined {\n for (const reference of [...document.references].reverse()) {\n const anchor = endpointPosition(document, devices, reference.target);\n const local = referenceToLocal(reference, { x: point.x - anchor.x, y: point.y - anchor.y });\n if (containsExpanded(referenceBounds(reference), local, tolerance))\n return { kind: 'reference', id: reference.id };\n }\n for (const label of [...document.labels].reverse()) {\n const anchor = endpointPosition(document, devices, label.target);\n if (\n containsExpanded(\n labelBounds(label),\n { x: point.x - anchor.x, y: point.y - anchor.y },\n tolerance,\n )\n )\n return { kind: 'label', id: label.id };\n }\n return undefined;\n}\n\nfunction containsExpanded(bounds: Rect2D, point: Point2D, tolerance: number): boolean {\n return contains(\n {\n x: bounds.x - tolerance,\n y: bounds.y - tolerance,\n width: bounds.width + tolerance * 2,\n height: bounds.height + tolerance * 2,\n },\n point,\n );\n}\n\nexport interface IBodyOverlap {\n readonly first: FusedInstance;\n readonly second: FusedInstance;\n}\n\nexport function findBodyOverlaps(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n): readonly IBodyOverlap[] {\n const bodies = document.instances.flatMap((instance) => {\n const geometry = devices.get(instance.device)?.geometry;\n if (geometry === undefined) return [];\n const rect = geometry.bodyBounds;\n return [\n {\n instance,\n points: [\n { x: rect.x, y: rect.y },\n { x: rect.x + rect.width, y: rect.y },\n { x: rect.x + rect.width, y: rect.y + rect.height },\n { x: rect.x, y: rect.y + rect.height },\n ].map((point) => localToScene(instance, geometry, point)),\n },\n ];\n });\n const overlaps: IBodyOverlap[] = [];\n for (const [index, first] of bodies.entries()) {\n for (const second of bodies.slice(index + 1)) {\n const separated = [first.points, second.points].some((points) =>\n points.some((point, edge) => {\n const next = points[(edge + 1) % points.length];\n if (next === undefined) return false;\n const axis = { x: point.y - next.y, y: next.x - point.x };\n const length = Math.hypot(axis.x, axis.y);\n const project = (value: Point2D) => (value.x * axis.x + value.y * axis.y) / length;\n const a = first.points.map(project);\n const b = second.points.map(project);\n return Math.max(...a) <= Math.min(...b) + 1e-9 || Math.max(...b) <= Math.min(...a) + 1e-9;\n }),\n );\n if (!separated) overlaps.push({ first: first.instance, second: second.instance });\n }\n }\n return overlaps;\n}\n\nexport function distanceToSegment(point: Point2D, a: Point2D, b: Point2D): number {\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const length = dx * dx + dy * dy;\n const t =\n length === 0\n ? 0\n : Math.max(0, Math.min(1, ((point.x - a.x) * dx + (point.y - a.y) * dy) / length));\n return Math.hypot(point.x - a.x - t * dx, point.y - a.y - t * dy);\n}\n\nexport function pickWireSegment(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n point: Point2D,\n tolerance: number,\n): { readonly wireId: string; readonly segment: number } | undefined {\n let hit: { wireId: string; segment: number; distance: number } | undefined;\n for (const wire of document.wires) {\n const points = [\n endpointPosition(document, devices, wire.from),\n ...wire.bends,\n endpointPosition(document, devices, wire.to),\n ];\n for (let segment = 0; segment < points.length - 1; segment++) {\n const from = points[segment]!;\n const to = points[segment + 1]!;\n if (from.x === to.x && from.y === to.y) continue;\n const distance = distanceToSegment(point, from, to);\n if (distance <= tolerance && (hit === undefined || distance < hit.distance))\n hit = { wireId: wire.id, segment, distance };\n }\n }\n return hit;\n}\n\nexport function fitViewport(\n document: FusedDocument,\n devices: ReadonlyMap<string, ICanvasDevice>,\n width: number,\n height: number,\n): IViewport {\n const points = [\n ...document.nodes,\n ...document.wires.flatMap((wire) => wire.bends),\n ...document.instances.flatMap((instance) => {\n const bounds = devices.get(instance.device)?.geometry.bounds;\n const geometry = devices.get(instance.device)?.geometry;\n return bounds === undefined || geometry === undefined\n ? []\n : [\n { x: bounds.x, y: bounds.y },\n { x: bounds.x + bounds.width, y: bounds.y },\n { x: bounds.x, y: bounds.y + bounds.height },\n { x: bounds.x + bounds.width, y: bounds.y + bounds.height },\n ].map((point) => localToScene(instance, geometry, point));\n }),\n ];\n if (!points.length) return { scale: 10, x: width / 2, y: height / 2 };\n const left = Math.min(...points.map((point) => point.x));\n const top = Math.min(...points.map((point) => point.y));\n const right = Math.max(...points.map((point) => point.x));\n const bottom = Math.max(...points.map((point) => point.y));\n const scale = Math.max(\n 0.25,\n Math.min(\n 50,\n Math.max(1, width - 96) / Math.max(1, right - left),\n Math.max(1, height - 96) / Math.max(1, bottom - top),\n ),\n );\n return {\n scale,\n x: width / 2 - ((left + right) / 2) * scale,\n y: height / 2 - ((top + bottom) / 2) * scale,\n };\n}\n","/**\n * Orthogonal wire routing and anchor materialization of the fused workbench (RFC 0024).\n *\n * A fused wire persists only its intermediate bends; the full polyline is the from anchor, the\n * bends and the to anchor. Device anchors move with rotation, scaling and placement, so every\n * mutation that can move an anchor has to rebuild the bends until each leg is horizontal or\n * vertical — the same rule the separate schematic editor applies.\n *\n * The rules are shared with that editor instead of growing a second algorithm:\n * `orthogonalWaypoints` picks the elbow with the long axis first, `extendWirePath` folds retraced\n * collinear legs, and the endpoint absorption below is the same \"shift the neighbour, stop at the\n * next corner\" pass, bounded so it can never move the far anchor of a wire.\n */\nimport type {\n ConnectionNode,\n ConnectionWire,\n Endpoint,\n FusedDocument,\n Point2D,\n} from '@mica-js/document/fused';\nimport { projectOnSegment } from '@mica-js/document/schematic';\nimport { extendWirePath, orthogonalWaypoints } from '../schematic/editor/snapping/wire';\nimport { localToScene, type ICanvasDevice } from './canvas/geometry';\nimport { planPolylineSegmentDrag } from '../schematic/editing/segment-drag';\nimport { FusedSessionError } from './document/errors';\nimport { addNode, addWire, sameEndpoint, type IdFactory } from './document/edits';\n\n/** Verified device geometry keyed by full device id; prepared devices and canvas devices match. */\nexport type WiringDevices = ReadonlyMap<string, ICanvasDevice>;\n\n/** Explicit wire membership is based on endpoint identity, never coordinate overlap. */\nexport function hasWireConnection(document: FusedDocument, endpoint: Endpoint): boolean {\n return document.wires.some(\n (wire) => sameEndpoint(wire.from, endpoint) || sameEndpoint(wire.to, endpoint),\n );\n}\n\n/** Distance under which a tapped point counts as lying on a wire, in scene millimetres. */\nconst TAP_EPSILON = 1e-6;\n\n/**\n * Turns any point sequence into one orthogonal polyline.\n *\n * Consecutive points that are not aligned receive the elbow of `orthogonalWaypoints` (long axis\n * first), and retraced collinear legs collapse the way the schematic wire tool collapses them.\n *\n * ```ts\n * orthogonalPath([{ x: 0, y: 0 }, { x: 10, y: 6 }]);\n * // [{ 0, 0 }, { 10, 0 }, { 10, 6 }]\n * ```\n */\nexport function orthogonalPath(points: readonly Point2D[]): readonly Point2D[] {\n const [first, ...rest] = points;\n if (first === undefined) {\n return [];\n }\n let path: Point2D[] = [{ x: first.x, y: first.y }];\n for (const point of rest) {\n path = extendWirePath(path, { x: point.x, y: point.y }, undefined);\n }\n return path;\n}\n\n/** Whether every leg of the polyline is horizontal or vertical. */\nexport function isOrthogonalPolyline(points: readonly Point2D[]): boolean {\n for (let index = 1; index < points.length; index += 1) {\n const previous = points[index - 1];\n const point = points[index];\n if (previous === undefined || point === undefined) {\n return false;\n }\n if (previous.x !== point.x && previous.y !== point.y) {\n return false;\n }\n }\n return true;\n}\n\n/** Scene position of one connection endpoint, or `undefined` when it cannot be resolved. */\nexport function endpointPoint(\n document: FusedDocument,\n devices: WiringDevices,\n endpoint: Endpoint,\n): Point2D | undefined {\n if (endpoint.kind === 'node') {\n const node = document.nodes.find((candidate) => candidate.id === endpoint.node);\n return node === undefined ? undefined : { x: node.x, y: node.y };\n }\n const instance = document.instances.find((candidate) => candidate.id === endpoint.instance);\n if (instance === undefined) {\n return undefined;\n }\n const geometry = devices.get(instance.device)?.geometry;\n const pin = geometry?.pins[endpoint.pin];\n if (geometry === undefined || pin === undefined) {\n return undefined;\n }\n return localToScene(instance, geometry, pin.position);\n}\n\n/** Full polyline of one wire: the from anchor, the stored bends and the to anchor. */\nexport function wirePolyline(\n document: FusedDocument,\n devices: WiringDevices,\n wire: ConnectionWire,\n): readonly Point2D[] | undefined {\n const from = endpointPoint(document, devices, wire.from);\n const to = endpointPoint(document, devices, wire.to);\n if (from === undefined || to === undefined) {\n return undefined;\n }\n return [from, ...wire.bends, to];\n}\n\n/** Slides one wire segment while retaining both explicit electrical endpoints. */\nexport function moveWireSegment(\n document: FusedDocument,\n devices: WiringDevices,\n wireId: string,\n segment: number,\n delta: Point2D,\n): FusedDocument {\n const wire = document.wires.find((value) => value.id === wireId);\n const points = wire === undefined ? undefined : wirePolyline(document, devices, wire);\n const start = points?.[segment];\n const end = points?.[segment + 1];\n if (\n points === undefined ||\n !Number.isInteger(segment) ||\n start === undefined ||\n end === undefined ||\n !Number.isFinite(delta.x) ||\n !Number.isFinite(delta.y)\n )\n throw new FusedSessionError('edit/invalid-request', 'Invalid wire segment drag');\n const normal = start.y === end.y ? { x: 0, y: delta.y } : { x: delta.x, y: 0 };\n const first = points[0]!;\n const last = points[points.length - 1]!;\n const moved = planPolylineSegmentDrag(\n points,\n segment,\n normal,\n (point) =>\n (point.x === first.x && point.y === first.y) || (point.x === last.x && point.y === last.y),\n );\n if (moved === undefined) return document;\n const bends = orthogonalPath(moved).slice(1, -1);\n return {\n ...document,\n wires: document.wires.map((value) => (value.id === wireId ? { ...value, bends } : value)),\n };\n}\n\n/** A dragged pin-attached terminal gains its own anchor and an explicit connecting wire. */\nexport function moveReference(\n document: FusedDocument,\n devices: WiringDevices,\n referenceId: string,\n position: Point2D,\n createId: IdFactory,\n): FusedDocument {\n const reference = document.references.find((value) => value.id === referenceId);\n if (reference === undefined || !Number.isFinite(position.x) || !Number.isFinite(position.y))\n throw new FusedSessionError('edit/invalid-request', 'Invalid terminal drag');\n const origin = endpointPoint(document, devices, reference.target);\n if (origin === undefined)\n throw new FusedSessionError('edit/invalid-request', 'Unknown terminal anchor');\n if (origin.x === position.x && origin.y === position.y) return document;\n const target = reference.target;\n if (target.kind === 'node') {\n const node = document.nodes.find((value) => value.id === target.node);\n const shared =\n node?.kind === 'junction' ||\n document.references.some(\n (value) =>\n value.id !== referenceId &&\n value.target.kind === 'node' &&\n value.target.node === target.node,\n ) ||\n document.labels.some(\n (value) => value.target.kind === 'node' && value.target.node === target.node,\n ) ||\n document.wires.filter(\n (value) =>\n (value.from.kind === 'node' && value.from.node === target.node) ||\n (value.to.kind === 'node' && value.to.node === target.node),\n ).length > 1;\n if (!shared) {\n return routeDocumentWires(\n {\n ...document,\n nodes: document.nodes.map((value) =>\n value.id === target.node ? { ...value, ...position } : value,\n ),\n },\n devices,\n document,\n );\n }\n }\n const added = addNode(document, position, 'free', createId);\n const endpoint: Endpoint = { kind: 'node', node: added.nodeId };\n const moved: FusedDocument = {\n ...added.document,\n references: added.document.references.map((value) =>\n value.id === referenceId ? { ...value, target: endpoint } : value,\n ),\n };\n return addWire(\n moved,\n reference.target,\n endpoint,\n routeWireBends(moved, devices, reference.target, endpoint, []),\n createId,\n ).document;\n}\n\n/**\n * The free node a standalone net label owns, when dragging the label should carry its anchor.\n *\n * A label dropped on empty canvas owns the node it created: nothing else names that node, it is\n * not a branch and at most one wire hangs on it. A label naming a pin, a junction or a shared node\n * only owns its text, so its name may sit anywhere without dragging the connection with it.\n */\nexport function labelAnchorNode(document: FusedDocument, labelId: string): string | undefined {\n const label = document.labels.find((value) => value.id === labelId);\n const target = label?.target;\n if (target?.kind !== 'node') return undefined;\n const node = document.nodes.find((value) => value.id === target.node);\n if (node === undefined || node.kind === 'junction') return undefined;\n const shared =\n document.labels.some(\n (value) =>\n value.id !== labelId && value.target.kind === 'node' && value.target.node === node.id,\n ) ||\n document.references.some(\n (value) => value.target.kind === 'node' && value.target.node === node.id,\n ) ||\n document.wires.filter(\n (value) =>\n (value.from.kind === 'node' && value.from.node === node.id) ||\n (value.to.kind === 'node' && value.to.node === node.id),\n ).length > 1;\n return shared ? undefined : node.id;\n}\n\n/** Moves a standalone net label as one object: the connection point and the name travel together. */\nexport function moveLabel(\n document: FusedDocument,\n devices: WiringDevices,\n labelId: string,\n position: Point2D,\n): FusedDocument {\n const nodeId = labelAnchorNode(document, labelId);\n if (nodeId === undefined || !Number.isFinite(position.x) || !Number.isFinite(position.y))\n throw new FusedSessionError('edit/invalid-request', 'Invalid net label drag');\n const node = document.nodes.find((value) => value.id === nodeId);\n if (node === undefined)\n throw new FusedSessionError('edit/invalid-request', 'Unknown net label anchor');\n if (node.x === position.x && node.y === position.y) return document;\n return routeDocumentWires(\n {\n ...document,\n nodes: document.nodes.map((value) =>\n value.id === nodeId ? { ...value, x: position.x, y: position.y } : value,\n ),\n },\n devices,\n document,\n );\n}\n\n/**\n * Bends for a new wire from `from` to `to` through the requested waypoints.\n *\n * The waypoints stay in the order the caller picked them; only the legs between them are\n * orthogonalized.\n */\nexport function routeWireBends(\n document: FusedDocument,\n devices: WiringDevices,\n from: Endpoint,\n to: Endpoint,\n bends: readonly Point2D[],\n): readonly Point2D[] {\n const start = endpointPoint(document, devices, from);\n const end = endpointPoint(document, devices, to);\n if (start === undefined || end === undefined) {\n return bends;\n }\n const path = orthogonalPath([start, ...bends, end]);\n return path.length < 2 ? [] : path.slice(1, -1);\n}\n\n/**\n * Rebuilds the bends of every wire whose legs are no longer orthogonal.\n *\n * `previous` is the document before the mutation. With it, endpoints that moved are absorbed the\n * way a symbol drag absorbs them: neighbouring bends shift, a rigid move translates the whole run\n * and the far anchor never moves. Without it (or for a wire the mutation also edited) the affected\n * wire is routed as one canonical orthogonal path.\n *\n * Wires that are already orthogonal are returned untouched, so existing geometry is preserved.\n */\nexport function routeDocumentWires(\n document: FusedDocument,\n devices: WiringDevices,\n previous?: FusedDocument,\n): FusedDocument {\n if (document.wires.length === 0) {\n return document;\n }\n const previousWires = new Map((previous?.wires ?? []).map((wire) => [wire.id, wire]));\n let changed = false;\n const wires = document.wires.map((wire) => {\n const line = wirePolyline(document, devices, wire);\n if (line === undefined || isOrthogonalPolyline(line)) {\n return wire;\n }\n const rerouted = rerouteWire(wire, line, devices, previous, previousWires.get(wire.id));\n const bends = rerouted.slice(1, -1);\n if (samePoints(bends, wire.bends)) {\n return wire;\n }\n changed = true;\n return { ...wire, bends };\n });\n return changed ? { ...document, wires } : document;\n}\n\n/**\n * Resolves one placement anchor to a real endpoint without mutating anything.\n *\n * - An existing {@link Endpoint} passes through unchanged.\n * - A point on a pin or on a connection node resolves to that endpoint.\n * - A point on a wire splits every host wire there and returns one shared junction node, so the\n * caller's next wire, label or reference is electrically connected.\n * - Any other point becomes a free node.\n *\n * The function is pure: the input document is never changed, so an abandoned gesture persists\n * nothing and an Escape leaves no orphan node or wire behind.\n */\nexport function materializeAnchor(\n document: FusedDocument,\n anchor: Endpoint | Point2D,\n devices: WiringDevices,\n createId: () => string,\n): { readonly document: FusedDocument; readonly endpoint: Endpoint } {\n if (isEndpoint(anchor)) {\n return { document, endpoint: anchor };\n }\n const point = readPoint(anchor);\n\n const pin = pinAt(document, devices, point);\n if (pin !== undefined) {\n return { document, endpoint: pin };\n }\n const node = document.nodes.find((candidate) => samePoint(candidate, point));\n if (node !== undefined) {\n return { document, endpoint: { kind: 'node', node: node.id } };\n }\n\n const candidates = document.wires.flatMap((wire) => {\n const line = wirePolyline(document, devices, wire);\n if (line === undefined) {\n return [];\n }\n const split = locateOnPolyline(line, point);\n return split === undefined ? [] : [{ wire, split, line }];\n });\n const origin = candidates[0]?.split.point;\n // Only wires that meet at the very same point share the junction; a near miss stays untouched.\n const hosts =\n origin === undefined\n ? []\n : candidates.filter((candidate) => samePoint(candidate.split.point, origin));\n const taken = takenIds(document);\n if (hosts.length === 0) {\n const nodeId = freshId(taken, createId);\n const free: ConnectionNode = { id: nodeId, kind: 'free', x: point.x, y: point.y };\n return {\n document: { ...document, nodes: [...document.nodes, free] },\n endpoint: { kind: 'node', node: nodeId },\n };\n }\n\n const junction: ConnectionNode = {\n id: freshId(taken, createId),\n kind: 'junction',\n x: hosts[0]?.split.point.x ?? point.x,\n y: hosts[0]?.split.point.y ?? point.y,\n };\n const endpoint: Endpoint = { kind: 'node', node: junction.id };\n const hostsById = new Map(hosts.map((host) => [host.wire.id, host]));\n const wires: ConnectionWire[] = [];\n for (const wire of document.wires) {\n const host = hostsById.get(wire.id);\n if (host === undefined) {\n wires.push(wire);\n continue;\n }\n const halves = splitWire(wire, host.split, host.line, endpoint, taken, createId);\n wires.push(...halves);\n }\n return {\n document: { ...document, nodes: [...document.nodes, junction], wires },\n endpoint,\n };\n}\n\ninterface IHostSplit {\n /** Index of the split vertex in the full polyline, or `-1` when it lies inside a segment. */\n readonly vertex: number;\n /** Segment index that contains the split point. */\n readonly segment: number;\n readonly point: Point2D;\n}\n\nfunction splitWire(\n wire: ConnectionWire,\n split: IHostSplit,\n line: readonly Point2D[],\n junction: Endpoint,\n taken: Set<string>,\n createId: () => string,\n): readonly ConnectionWire[] {\n const last = line.length - 1;\n // The split point becomes the junction anchor, so it is dropped from both bend lists.\n const head = split.vertex >= 0 ? line.slice(1, split.vertex) : line.slice(1, split.segment + 1);\n const tail =\n split.vertex >= 0 ? line.slice(split.vertex + 1, last) : line.slice(split.segment + 1, last);\n return [\n { id: freshId(taken, createId), from: wire.from, to: junction, bends: head },\n { id: freshId(taken, createId), from: junction, to: wire.to, bends: tail },\n ];\n}\n\nfunction locateOnPolyline(line: readonly Point2D[], point: Point2D): IHostSplit | undefined {\n const last = line.length - 1;\n for (let vertex = 1; vertex < last; vertex += 1) {\n const candidate = line[vertex];\n if (candidate !== undefined && samePoint(candidate, point)) {\n return { vertex, segment: vertex, point: { x: candidate.x, y: candidate.y } };\n }\n }\n for (let segment = 0; segment < last; segment += 1) {\n const from = line[segment];\n const to = line[segment + 1];\n if (from === undefined || to === undefined) {\n continue;\n }\n const projected = projectOnSegment(point, from, to);\n const distance = Math.hypot(projected.x - point.x, projected.y - point.y);\n if (distance > TAP_EPSILON) {\n continue;\n }\n if (segment === 0 && samePoint(projected, from)) {\n continue;\n }\n if (segment === last - 1 && samePoint(projected, to)) {\n continue;\n }\n return { vertex: -1, segment, point: { x: projected.x, y: projected.y } };\n }\n return undefined;\n}\n\nfunction pinAt(\n document: FusedDocument,\n devices: WiringDevices,\n point: Point2D,\n): Endpoint | undefined {\n for (const instance of document.instances) {\n const geometry = devices.get(instance.device)?.geometry;\n if (geometry === undefined) {\n continue;\n }\n for (const pin of Object.keys(geometry.pins)) {\n const anchor = geometry.pins[pin];\n if (anchor === undefined) {\n continue;\n }\n const scene = localToScene(instance, geometry, anchor.position);\n if (samePoint(scene, point)) {\n return { kind: 'pin', instance: instance.id, pin };\n }\n }\n }\n return undefined;\n}\n\nfunction rerouteWire(\n wire: ConnectionWire,\n line: readonly Point2D[],\n devices: WiringDevices,\n previous: FusedDocument | undefined,\n previousWire: ConnectionWire | undefined,\n): readonly Point2D[] {\n const start = line[0];\n const end = line[line.length - 1];\n if (start === undefined || end === undefined) {\n return orthogonalPath(line);\n }\n if (previous !== undefined && previousWire !== undefined) {\n const oldFrom = endpointPoint(previous, devices, previousWire.from);\n const oldTo = endpointPoint(previous, devices, previousWire.to);\n const sameBends = samePoints(previousWire.bends, wire.bends);\n if (oldFrom !== undefined && oldTo !== undefined && sameBends) {\n const startDelta = { x: start.x - oldFrom.x, y: start.y - oldFrom.y };\n const endDelta = { x: end.x - oldTo.x, y: end.y - oldTo.y };\n if (startDelta.x === endDelta.x && startDelta.y === endDelta.y) {\n // A whole run that moves together keeps its shape; only the anchors changed.\n const translated = [\n { x: start.x, y: start.y },\n ...wire.bends.map((bend) => ({\n x: bend.x + startDelta.x,\n y: bend.y + startDelta.y,\n })),\n { x: end.x, y: end.y },\n ];\n if (isOrthogonalPolyline(translated)) {\n return translated;\n }\n }\n let points: Point2D[] = [\n { x: oldFrom.x, y: oldFrom.y },\n ...wire.bends.map((bend) => ({ x: bend.x, y: bend.y })),\n { x: oldTo.x, y: oldTo.y },\n ];\n points = absorbEndpoint(points, 'start', { x: start.x, y: start.y });\n points = absorbEndpoint(points, 'end', { x: end.x, y: end.y });\n if (isOrthogonalPolyline(points)) {\n return points;\n }\n }\n }\n return orthogonalPath(line);\n}\n\n/**\n * Moves one anchor of an orthogonal polyline and absorbs the displacement by shifting the next\n * bend, exactly like the schematic symbol drag.\n *\n * Unlike the original pass, the loop stops one vertex before the far anchor: a fused wire must keep\n * both of its connection endpoints, so a displacement that reaches the other end is taken by a new\n * elbow instead of by moving that anchor.\n */\nfunction absorbEndpoint(\n points: readonly Point2D[],\n end: 'start' | 'end',\n target: Point2D,\n): Point2D[] {\n const next = points.map((point) => ({ x: point.x, y: point.y }));\n const last = next.length - 1;\n if (last < 1) {\n return next;\n }\n if (end === 'start') {\n next[0] = { x: target.x, y: target.y };\n for (let index = 0; index < last; index += 1) {\n const a = next[index];\n const b = next[index + 1];\n if (a === undefined || b === undefined || a.x === b.x || a.y === b.y) {\n break;\n }\n if (index + 1 === last) {\n next.splice(last, 0, elbow(a, b));\n break;\n }\n next[index + 1] = shifted(points, index, a, b);\n }\n return next;\n }\n next[last] = { x: target.x, y: target.y };\n for (let index = last; index > 0; index -= 1) {\n const a = next[index - 1];\n const b = next[index];\n if (a === undefined || b === undefined || a.x === b.x || a.y === b.y) {\n break;\n }\n if (index - 1 === 0) {\n next.splice(index, 0, elbow(a, b));\n break;\n }\n next[index - 1] = shifted(points, index - 1, a, b);\n }\n return next;\n}\n\n/** Restores the original orientation of one leg by moving its far vertex. */\nfunction shifted(points: readonly Point2D[], index: number, a: Point2D, b: Point2D): Point2D {\n const before = points[index];\n const after = points[index + 1];\n const horizontal = before !== undefined && after !== undefined && before.y === after.y;\n return horizontal ? { x: b.x, y: a.y } : { x: a.x, y: b.y };\n}\n\n/** The elbow of `orthogonalWaypoints` between two diagonal points. */\nfunction elbow(a: Point2D, b: Point2D): Point2D {\n const [first] = orthogonalWaypoints(a, b);\n return first === undefined ? { x: a.x, y: b.y } : { x: first.x, y: first.y };\n}\n\nfunction isEndpoint(value: Endpoint | Point2D): value is Endpoint {\n const kind = (value as { kind?: unknown }).kind;\n return kind === 'pin' || kind === 'node';\n}\n\nfunction readPoint(point: Point2D): Point2D {\n if (\n point === null ||\n typeof point !== 'object' ||\n !Number.isFinite(point.x) ||\n !Number.isFinite(point.y)\n ) {\n throw new TypeError('An anchor point needs finite \"x\" and \"y\" numbers.');\n }\n return { x: point.x, y: point.y };\n}\n\nfunction samePoint(left: Point2D, right: Point2D): boolean {\n return left.x === right.x && left.y === right.y;\n}\n\nfunction samePoints(left: readonly Point2D[], right: readonly Point2D[]): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((point, index) => {\n const other = right[index];\n return other !== undefined && samePoint(point, other);\n });\n}\n\nfunction takenIds(document: FusedDocument): Set<string> {\n return new Set<string>([\n ...document.instances.map((entry) => entry.id),\n ...document.nodes.map((entry) => entry.id),\n ...document.wires.map((entry) => entry.id),\n ...document.labels.map((entry) => entry.id),\n ...document.references.map((entry) => entry.id),\n ]);\n}\n\nfunction freshId(taken: Set<string>, createId: () => string): string {\n for (let attempt = 0; attempt < 128; attempt += 1) {\n const id = createId();\n if (!taken.has(id)) {\n taken.add(id);\n return id;\n }\n }\n throw new Error('Could not allocate a unique element id for the anchor.');\n}\n","/**\n * Verification every committed document state has to pass (RFC 0024).\n *\n * A mutation is only accepted once the candidate parses, every device it references opens as the\n * locked release with usable geometry, the per-instance view layouts name declared views, and the\n * explicit connection graph derives without name or voltage conflicts.\n */\nimport { deriveFusedTopology, parseFusedDocument } from '@mica-js/document/fused';\nimport type { FusedDocument, FusedTopology, UnifiedDeviceManifest } from '@mica-js/document/fused';\nimport type { IDeviceCache, IPreparedDevice } from '../devices';\nimport { routeDocumentWires } from '../wiring';\nimport { FusedSessionError } from './errors';\nimport type { IFusedSessionProblem } from './errors';\n\nexport interface IVerifiedFusedDocument {\n readonly document: FusedDocument;\n readonly devices: ReadonlyMap<string, IPreparedDevice>;\n readonly topology: FusedTopology;\n}\n\nexport interface IVerifyFusedDocumentOptions {\n /**\n * Rebuilds every wire whose legs are no longer orthogonal, using the loaded device geometry.\n *\n * Content mutations route; a layout check must not change content, so it leaves wires alone.\n */\n readonly routeWires?: boolean;\n /** Document before the mutation, so moved anchors are absorbed the way a symbol drag absorbs them. */\n readonly previous?: FusedDocument;\n}\n\n/**\n * Parses and verifies one candidate document.\n *\n * @throws {FusedDocumentError} for contract violations, {PreparationError} for package problems and\n * {FusedSessionError} for a view layout the owning device does not declare.\n */\nexport async function verifyFusedDocument(\n value: unknown,\n devices: IDeviceCache,\n options: IVerifyFusedDocumentOptions = {},\n): Promise<IVerifiedFusedDocument> {\n let document = parseFusedDocument(value);\n const prepared = await devices.prepareDocument(document);\n for (const instance of document.instances) {\n const properties = prepared.get(instance.device)?.manifest.properties;\n for (const [key, value] of Object.entries(instance.properties ?? {})) {\n if (\n value !== null &&\n typeof value === 'object' &&\n value.mode === 'project' &&\n properties?.[key]?.type !== 'program'\n )\n throw new FusedSessionError(\n 'edit/invalid-document',\n `Only program properties can reference a project: ${instance.id}/${key}.`,\n );\n }\n }\n if (options.routeWires === true) {\n const routed = routeDocumentWires(document, prepared, options.previous);\n if (routed !== document) {\n document = parseFusedDocument(routed);\n }\n }\n checkViewLayouts(document, prepared);\n const manifests = new Map<string, UnifiedDeviceManifest>(\n [...prepared].map(([deviceId, device]) => [deviceId, device.manifest]),\n );\n const topology = deriveFusedTopology(document, manifests);\n return { document, devices: prepared, topology };\n}\n\n/**\n * Checks every saved layout against the views its device declares (RFC 0024).\n *\n * The document parser cannot do this: view ids live in the device manifest.\n */\nfunction checkViewLayouts(\n document: FusedDocument,\n prepared: ReadonlyMap<string, IPreparedDevice>,\n): void {\n const problems: IFusedSessionProblem[] = [];\n document.instances.forEach((instance, index) => {\n const layout = instance.viewLayout;\n if (layout === undefined) {\n return;\n }\n const declared = prepared.get(instance.device)?.manifest.view ?? {};\n layout.views.forEach((view, at) => {\n if (!Object.hasOwn(declared, view.viewId)) {\n problems.push({\n code: 'document/invalid-view-layout',\n message: `Instance \"${instance.id}\" lays out the view \"${view.viewId}\", which ${instance.device} does not declare.`,\n pointer: `/instances/${String(index)}/viewLayout/views/${String(at)}/viewId`,\n });\n }\n });\n });\n if (problems.length > 0) {\n throw new FusedSessionError(\n 'edit/invalid-document',\n problems[0]?.message ?? 'A saved view layout is invalid.',\n { problems },\n );\n }\n}\n","/**\n * Document and editing session of the fused workbench (RFC 0024).\n *\n * The session owns the immutable document, the unified undo history and the saved marker. It is the\n * single writer: every operation is serialized, re-checks the access policy right before the commit,\n * verifies the candidate against the locked packages and only then publishes one content event.\n *\n * Permission and run locking are enforced centrally for every write, including view layouts:\n *\n * - `edit` denied: no mutation at all; the document stays browsable and unsaved content is kept.\n * - running: properties, connections and other content stay read-only, view layouts stay editable,\n * and undo/redo only walks layout transactions at the top of the history.\n */\nimport { DisposableStore, Emitter } from '@mica-js/core/lifecycle';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport { parseFusedDocument } from '@mica-js/document/fused';\nimport type {\n DeviceLock,\n Endpoint,\n FusedDocument,\n FusedTopology,\n InstanceViewLayout,\n Placement2D,\n Point2D,\n PropertyValue,\n} from '@mica-js/document/fused';\nimport type {\n AccessDecision,\n IDeviceProvider,\n IDocumentAccess,\n IWorkbenchAccessProvider,\n} from '../providers';\nimport { DeviceCache } from '../devices';\nimport type { IDeviceCache, IPreparedDevice } from '../devices';\nimport {\n addInstance,\n addLabel,\n addNode,\n addReference,\n addWire,\n moveInstances,\n removeInstanceProperty,\n removeTargets,\n renameDesignator,\n rotateInstances,\n setInstancePosition,\n setInstanceProperty,\n setViewLayout as replaceViewLayout,\n} from './edits';\nimport type { IFusedDocumentTarget, IFusedLabelOptions, IFusedReferenceOptions } from './edits';\nimport { copyTargets, pasteClipboard } from './copy';\nimport { routeWireBends } from '../wiring';\nimport type { IFusedClipboard } from './copy';\nimport { verifyFusedDocument } from './verify';\nimport type { IVerifiedFusedDocument } from './verify';\nimport { accessDenied, FusedSessionError, toSessionError } from './errors';\n\nconst DEFAULT_HISTORY_LIMIT = 200;\n\ntype DeniedDecision = Extract<AccessDecision, { readonly allowed: false }>;\ntype WriteMode = 'content' | 'layout';\n\nexport interface IFusedDocumentSessionOptions {\n readonly document: FusedDocument;\n readonly saveDocument?: (document: FusedDocument) => Promise<void>;\n /** Locked package registry; the session owns its verified cache. */\n readonly devices: IDeviceProvider;\n readonly access: IWorkbenchAccessProvider;\n /** Maximum number of undo steps kept; defaults to 200. */\n readonly historyLimit?: number;\n /** Element id factory; defaults to `crypto.randomUUID`. */\n readonly createId?: () => string;\n}\n\nexport interface IFusedDocumentState {\n readonly canUndo: boolean;\n readonly canRedo: boolean;\n readonly dirty: boolean;\n /** No mutation of any kind is allowed: the access policy denies editing this document. */\n readonly readOnly: boolean;\n /** A run is in progress; content and topology are read-only while layouts stay editable. */\n readonly running: boolean;\n readonly canEditContent: boolean;\n readonly canEditLayout: boolean;\n readonly access: IDocumentAccess;\n}\n\nexport interface IFusedTransactionOptions {\n /** Declares a view-layout-only change: allowed while running, and rejected if it alters content. */\n readonly layoutOnly?: boolean;\n}\n\ninterface IHistoryEntry {\n readonly before: FusedDocument;\n readonly after: FusedDocument;\n readonly contentChanged: boolean;\n readonly beforeTopology: FusedTopology | undefined;\n readonly afterTopology: FusedTopology;\n readonly beforeDevices: ReadonlyMap<string, IPreparedDevice>;\n readonly afterDevices: ReadonlyMap<string, IPreparedDevice>;\n}\n\n/**\n * One open fused document with its editing history.\n *\n * Create it with {@link FusedDocumentSession.open}; every method below documents whether it needs\n * `edit` permission and how it behaves while a run is active.\n */\nexport class FusedDocumentSession {\n readonly #saveDocument: ((document: FusedDocument) => Promise<void>) | undefined;\n readonly #access: IWorkbenchAccessProvider;\n readonly #packages: DeviceCache;\n readonly #createId: () => string;\n readonly #historyLimit: number;\n readonly #subscriptions = new DisposableStore();\n readonly #content = new Emitter<FusedDocument>();\n readonly #state = new Emitter<IFusedDocumentState>();\n readonly #errors = new Emitter<FusedSessionError>();\n readonly #keys = new WeakMap<FusedDocument, string>();\n readonly #contentKeys = new WeakMap<FusedDocument, string>();\n #document: FusedDocument;\n #savedKey: string;\n #past: IHistoryEntry[] = [];\n #future: IHistoryEntry[] = [];\n #decisions: IDocumentAccess;\n #prepared: ReadonlyMap<string, IPreparedDevice> = new Map();\n #topology: FusedTopology | undefined;\n #preparationError: FusedSessionError | undefined;\n #running = false;\n #queue: Promise<void> = Promise.resolve();\n #pendingAccess: Promise<void> | undefined;\n #evaluationRevision = 0;\n #appliedRevision = 0;\n #disposed = false;\n #lastStateSignature = '';\n\n private constructor(\n options: IFusedDocumentSessionOptions,\n document: FusedDocument,\n decisions: IDocumentAccess,\n ) {\n this.#saveDocument = options.saveDocument;\n this.#access = options.access;\n this.#packages = new DeviceCache(options.devices);\n this.#createId = options.createId ?? (() => globalThis.crypto.randomUUID());\n this.#historyLimit = options.historyLimit ?? DEFAULT_HISTORY_LIMIT;\n this.#document = document;\n this.#savedKey = canonicalJson(document);\n this.#decisions = decisions;\n }\n\n /**\n * Reads and parses `<uri>` and opens a session on it.\n *\n * A document whose packages or connection graph cannot be verified still opens for browsing; the\n * failure is reported by {@link getPreparationError} and every content edit then fails closed.\n *\n * @throws {FusedSessionError} when the supplied document violates RFC 0024 or the access policy\n * cannot be evaluated.\n */\n static async open(options: IFusedDocumentSessionOptions): Promise<FusedDocumentSession> {\n let document: FusedDocument;\n try {\n document = parseFusedDocument(options.document);\n } catch (cause) {\n throw toSessionError(cause, 'edit/invalid-document');\n }\n const decisions = await evaluateDecisions(options.access, document);\n const session = new FusedDocumentSession(options, document, decisions);\n await session.#start();\n session.#subscriptions.add(\n options.access.onDidChange(() => {\n session.#refreshAccessInBackground();\n }),\n );\n return session;\n }\n\n /** Fires once per committed change, undo and redo; rejected operations never fire it. */\n readonly onDidChangeContent: Event<FusedDocument> = this.#content.event;\n /** Fires whenever undo/redo, dirty, read-only or running change. */\n readonly onDidChangeState: Event<IFusedDocumentState> = this.#state.event;\n /** Fires for every rejected operation and access-policy failure with its code and problems. */\n readonly onDidError: Event<FusedSessionError> = this.#errors.event;\n\n /** Current immutable snapshot; the same reference until the next commit. */\n getDocument(): FusedDocument {\n this.#assertAlive();\n return this.#document;\n }\n\n getState(): IFusedDocumentState {\n this.#assertAlive();\n const readOnly = !this.#decisions.edit.allowed;\n const top = this.#past.at(-1);\n const next = this.#future.at(-1);\n return {\n canUndo: top !== undefined && (!this.#running || !top.contentChanged),\n canRedo: next !== undefined && (!this.#running || !next.contentChanged),\n dirty: this.#documentKey(this.#document) !== this.#savedKey,\n readOnly,\n running: this.#running,\n canEditContent: !readOnly && !this.#running,\n canEditLayout: !readOnly,\n access: this.#decisions,\n };\n }\n\n /** Decisions of the last evaluation; `run` is independent of `edit`. */\n getAccess(): IDocumentAccess {\n this.#assertAlive();\n return this.#decisions;\n }\n\n isRunning(): boolean {\n return this.#running;\n }\n\n /** Verified package cache shared with the canvas renderer; the session disposes it. */\n getDevices(): IDeviceCache {\n return this.#packages;\n }\n\n /** Nets of the last verified state, or `undefined` when the document never verified. */\n getTopology(): FusedTopology | undefined {\n this.#assertAlive();\n return this.#topology;\n }\n\n /** Why the document could not be verified on open; cleared by the next verified commit. */\n getPreparationError(): FusedSessionError | undefined {\n return this.#preparationError;\n }\n\n /** Manifests, geometry and verified files of every device the document uses. */\n getPreparedDevices(): Promise<ReadonlyMap<string, IPreparedDevice>> {\n return this.#enqueue(async () => {\n const prepared = await this.#packages.prepareDocument(this.#document);\n this.#prepared = sameDevices(this.#prepared, prepared) ? this.#prepared : prepared;\n return this.#prepared;\n });\n }\n\n /** Re-evaluates the access policy, for example after an external sign-in change. */\n refreshAccess(): Promise<void> {\n return this.#enqueue(async () => {\n await this.#settleAccess();\n await this.#evaluate();\n this.#publishState();\n });\n }\n\n /**\n * Locks or unlocks content editing for a run.\n *\n * Enabling needs the independent `run` permission; disabling always succeeds. The flag never\n * changes the document, history or dirty marker.\n */\n setRunning(running: boolean): Promise<void> {\n return this.#enqueue(async () => {\n await this.#settleAccess();\n const decisions = await this.#evaluate();\n if (running) {\n const decision = decisions.run;\n if (!decision.allowed) {\n throw accessDenied('access/run-denied', decision);\n }\n }\n if (running === this.#running) {\n this.#publishState();\n return;\n }\n this.#running = running;\n this.#publishState();\n });\n }\n\n /**\n * Applies one arbitrary, already built document as one transaction.\n *\n * This is the generic write gate: it checks the access policy like every named operation, so a\n * caller cannot bypass read-only or run locking through it. Use `layoutOnly` for view layouts.\n *\n * @throws {FusedSessionError} for denied permission, a running lock, or an invalid candidate.\n */\n transact(\n update: (document: FusedDocument) => FusedDocument | Promise<FusedDocument>,\n options: IFusedTransactionOptions = {},\n ): Promise<FusedDocument> {\n return this.#write(options.layoutOnly === true ? 'layout' : 'content', async (current) => {\n const candidate = await update(current);\n if (candidate === null || typeof candidate !== 'object') {\n throw new FusedSessionError(\n 'edit/invalid-request',\n 'A transaction must return the next document.',\n );\n }\n return { document: candidate, result: candidate };\n });\n }\n\n /**\n * Places one device, locking its release and allocating the smallest free designator.\n *\n * Needs `edit` permission, a verified package with geometry and body image, and a policy that\n * allows adding this device. An existing lock of another release is rejected, never replaced.\n *\n * @returns the new instance id.\n */\n addDevice(lock: DeviceLock, placement: Placement2D): Promise<string> {\n return this.#write('content', async (current) => {\n const device = await this.#packages.get(lock);\n this.#requireUnchangedLock(current, device.lock);\n const added = addInstance(current, device, placement, this.#createId);\n return { document: added.document, result: added.instanceId };\n });\n }\n\n /** Removes the targets as one transaction; instances cascade to their wires, labels and references. */\n remove(targets: readonly IFusedDocumentTarget[]): Promise<FusedDocument> {\n return this.#edit((current) => removeTargets(current, targets));\n }\n\n /** Moves one instance so its origin lands on `position`. */\n moveInstance(instanceId: string, position: Point2D): Promise<FusedDocument> {\n return this.#edit((current) => setInstancePosition(current, instanceId, position));\n }\n\n /** Offsets instances by a scene-space delta, for a finished drag. */\n moveInstances(instanceIds: readonly string[], delta: Point2D): Promise<FusedDocument> {\n return this.#edit((current) => moveInstances(current, instanceIds, delta));\n }\n\n /** Rotates instances clockwise by `degrees`. */\n rotateInstances(instanceIds: readonly string[], degrees: number): Promise<FusedDocument> {\n return this.#edit((current) => rotateInstances(current, instanceIds, degrees));\n }\n\n /** Rotates one instance clockwise by `degrees`; the canvas sends the drag delta. */\n rotateInstance(instanceId: string, degrees: number): Promise<FusedDocument> {\n return this.#edit((current) => rotateInstances(current, [instanceId], degrees));\n }\n\n /**\n * Renames one instance designator.\n *\n * @throws {FusedSessionError} (`edit/duplicate-designator`) when another instance owns the name.\n */\n renameDesignator(instanceId: string, designator: string): Promise<FusedDocument> {\n return this.#edit((current) => renameDesignator(current, instanceId, designator));\n }\n\n /** Stores one property override on an instance. */\n setProperty(instanceId: string, key: string, value: PropertyValue): Promise<FusedDocument> {\n return this.#edit((current) => setInstanceProperty(current, instanceId, key, value));\n }\n\n /** Drops one property override; an unknown key is a no-op. */\n removeProperty(instanceId: string, key: string): Promise<FusedDocument> {\n return this.#edit((current) => removeInstanceProperty(current, instanceId, key));\n }\n\n /** Adds a free or junction node; `id` is the new node id. */\n addNode(point: Point2D, kind: 'junction' | 'free'): Promise<string> {\n return this.#write('content', async (current) => {\n const added = addNode(current, point, kind, this.#createId);\n return { document: added.document, result: added.nodeId };\n });\n }\n\n /**\n * Connects two endpoints; `bends` are the intermediate waypoints only.\n *\n * The persisted bends are routed against the loaded pin geometry, so the new wire has no\n * diagonal leg even when the two anchors are not aligned.\n */\n addWire(from: Endpoint, to: Endpoint, bends: readonly Point2D[] = []): Promise<string> {\n return this.#write('content', async (current) => {\n const devices = await this.#packages.prepareDocument(current);\n const routed = routeWireBends(current, devices, from, to, bends);\n const added = addWire(current, from, to, routed, this.#createId);\n return { document: added.document, result: added.wireId };\n });\n }\n\n /** Attaches an ideal voltage reference, optionally drawn as the power or ground symbol. */\n addReference(\n target: Endpoint,\n voltage: number,\n symbol?: 'power' | 'ground',\n options: IFusedReferenceOptions = {},\n ): Promise<string> {\n return this.#write('content', async (current) => {\n const added = addReference(current, target, voltage, symbol, options, this.#createId);\n return { document: added.document, result: added.referenceId };\n });\n }\n\n /** Declares a net name on one endpoint. */\n addLabel(target: Endpoint, name: string, options: IFusedLabelOptions = {}): Promise<string> {\n return this.#write('content', async (current) => {\n const added = addLabel(current, target, name, options, this.#createId);\n return { document: added.document, result: added.labelId };\n });\n }\n\n /**\n * Stores the per-instance view layout, or restores the defaults with `undefined`.\n *\n * This is a layout transaction: it is allowed while running and rejected if it changes content.\n */\n setViewLayout(\n instanceId: string,\n layout: InstanceViewLayout | undefined,\n ): Promise<FusedDocument> {\n return this.#write('layout', async (current) => {\n const next = replaceViewLayout(current, instanceId, layout);\n return { document: next, result: next };\n });\n }\n\n /** Extracts the selected subgraph; a pure read that records no history. */\n copy(targets: readonly IFusedDocumentTarget[]): IFusedClipboard | undefined {\n this.#assertAlive();\n return copyTargets(this.#document, targets);\n }\n\n /**\n * Inserts a copied subgraph as one transaction.\n *\n * Copied devices must be locked by the clipboard, verified through their package and allowed by\n * the device-addition policy; connected edges outside the copy are not reproduced.\n */\n paste(clipboard: IFusedClipboard, offset: Point2D = { x: 0, y: 0 }): Promise<FusedDocument> {\n return this.#write('content', async (current) => {\n if (clipboard === null || typeof clipboard !== 'object') {\n throw new FusedSessionError('edit/invalid-request', 'The clipboard payload is missing.');\n }\n if (clipboard.instances.length === 0) {\n throw new FusedSessionError('edit/invalid-request', 'The clipboard holds no instances.');\n }\n const prepared = new Map<string, IPreparedDevice>();\n for (const deviceId of new Set(clipboard.instances.map((instance) => instance.device))) {\n const dependency = clipboard.dependencies[deviceId];\n if (dependency === undefined) {\n throw new FusedSessionError(\n 'edit/invalid-request',\n `The clipboard does not lock \"${deviceId}\".`,\n );\n }\n const device = await this.#packages.get({\n id: deviceId,\n version: dependency.version,\n integrity: dependency.integrity,\n });\n this.#requireUnchangedLock(current, device.lock);\n prepared.set(deviceId, device);\n }\n const next = pasteClipboard(current, clipboard, offset, prepared, this.#createId);\n return { document: next, result: next };\n });\n }\n\n /**\n * Rewrites the `.sch` file with the current content and marks it saved.\n *\n * Needs `edit` permission. Edits made while the write is pending run afterwards and keep the\n * document dirty; the saved marker is restored by undoing back to the written snapshot.\n */\n save(): Promise<void> {\n return this.#enqueue(async () => {\n await this.#settleAccess();\n this.#requireEdit('layout');\n const document = this.#document;\n await this.#authorize('layout', document, document);\n if (this.#saveDocument === undefined)\n throw new FusedSessionError(\n 'save/unavailable',\n 'The host does not provide document saving.',\n );\n try {\n await this.#saveDocument(document);\n } catch (cause) {\n throw new FusedSessionError('save/failed', 'Cannot save the document.', { cause });\n }\n this.#assertAlive();\n this.#savedKey = this.#documentKey(document);\n this.#publishState();\n });\n }\n\n /** Undoes the top step; while running only a layout step at the top of the history is undone. */\n undo(): Promise<void> {\n return this.#enqueue(async () => {\n const entry = this.#past.at(-1);\n if (entry === undefined) {\n return;\n }\n const mode: WriteMode = entry.contentChanged ? 'content' : 'layout';\n await this.#settleAccess();\n this.#requireHistoryStep(entry);\n await this.#authorize(mode, entry.before, this.#document);\n this.#past.pop();\n this.#future.push(entry);\n this.#restore(entry.before, entry.beforeDevices, entry.beforeTopology);\n });\n }\n\n /** Redoes the top undone step with the same run-locking rules as {@link undo}. */\n redo(): Promise<void> {\n return this.#enqueue(async () => {\n const entry = this.#future.at(-1);\n if (entry === undefined) {\n return;\n }\n const mode: WriteMode = entry.contentChanged ? 'content' : 'layout';\n await this.#settleAccess();\n this.#requireHistoryStep(entry);\n await this.#authorize(mode, entry.after, this.#document);\n this.#future.pop();\n this.#past.push(entry);\n this.#restore(entry.after, entry.afterDevices, entry.afterTopology);\n });\n }\n\n /** Releases the access subscription, the package cache and every event; content is untouched. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n this.#subscriptions.dispose();\n this.#packages.dispose();\n this.#content.dispose();\n this.#state.dispose();\n this.#errors.dispose();\n }\n\n async #start(): Promise<void> {\n try {\n const verified = await verifyFusedDocument(this.#document, this.#packages);\n this.#document = verified.document;\n this.#prepared = verified.devices;\n this.#topology = verified.topology;\n } catch (cause) {\n this.#preparationError = toSessionError(cause, 'device/unavailable');\n }\n this.#savedKey = this.#documentKey(this.#document);\n this.#lastStateSignature = this.#stateSignature();\n }\n\n #edit(update: (current: FusedDocument) => FusedDocument): Promise<FusedDocument> {\n return this.#write('content', async (current) => {\n const next = update(current);\n return { document: next, result: next };\n });\n }\n\n async #write<R>(\n mode: WriteMode,\n build: (\n current: FusedDocument,\n ) => Promise<{ readonly document: FusedDocument; readonly result: R }>,\n ): Promise<R> {\n return this.#enqueue(async () => {\n // A provider change that is still being evaluated blocks the write before any work is done.\n await this.#settleAccess();\n this.#requireEdit(mode);\n const current = this.#document;\n const built = await build(current);\n const verified = await verifyFusedDocument(built.document, this.#packages, {\n routeWires: mode === 'content',\n previous: current,\n });\n await this.#authorize(mode, verified.document, current);\n this.#commit(verified, current, mode);\n return built.result;\n });\n }\n\n #commit(verified: IVerifiedFusedDocument, current: FusedDocument, mode: WriteMode): void {\n const next = verified.document;\n const contentChanged = this.#contentKey(next) !== this.#contentKey(current);\n if (mode === 'layout' && contentChanged) {\n throw new FusedSessionError(\n 'edit/layout-mismatch',\n 'A layout transaction must not change devices, connections, labels or references.',\n );\n }\n if (this.#documentKey(next) === this.#documentKey(current)) {\n return;\n }\n this.#past.push({\n before: current,\n after: next,\n contentChanged,\n beforeTopology: this.#topology,\n afterTopology: verified.topology,\n beforeDevices: this.#prepared,\n afterDevices: verified.devices,\n });\n if (this.#past.length > this.#historyLimit) {\n this.#past.shift();\n }\n this.#future = [];\n this.#topology = verified.topology;\n this.#prepared = sameDevices(this.#prepared, verified.devices)\n ? this.#prepared\n : verified.devices;\n this.#preparationError = undefined;\n this.#document = next;\n this.#content.fire(next);\n this.#publishState();\n }\n\n #restore(\n document: FusedDocument,\n devices: ReadonlyMap<string, IPreparedDevice>,\n topology: FusedTopology | undefined,\n ): void {\n this.#document = document;\n this.#prepared = devices;\n this.#topology = topology;\n this.#content.fire(document);\n this.#publishState();\n }\n\n #requireEdit(mode: WriteMode): void {\n this.#requireDecision(mode, this.#decisions);\n }\n\n #requireDecision(mode: WriteMode, decisions: IDocumentAccess): void {\n this.#assertAlive();\n const edit = decisions.edit;\n if (!edit.allowed) {\n throw accessDenied('access/edit-denied', edit);\n }\n if (mode === 'content' && this.#running) {\n throw new FusedSessionError(\n 'access/running',\n 'Devices and connections are read-only while the circuit runs; stop the run first.',\n );\n }\n }\n\n /**\n * Authorizes one mutation against the candidate document.\n *\n * Waits for provider-triggered re-checks, evaluates the policy for the candidate itself, then\n * verifies that every instance and release the candidate introduces may be added. Both checks\n * repeat when the policy changes while they run; nothing is committed before this returns.\n */\n async #authorize(mode: WriteMode, target: FusedDocument, current: FusedDocument): Promise<void> {\n this.#assertAlive();\n for (let pass = 0; pass < 4; pass += 1) {\n await this.#settleAccess();\n const decisions = await this.#evaluate(target);\n if (this.#pendingAccess !== undefined) {\n continue;\n }\n this.#requireDecision(mode, decisions);\n await this.#requireAdditions(current, target);\n if (this.#pendingAccess !== undefined) {\n continue;\n }\n return;\n }\n throw new FusedSessionError(\n 'access/check-failed',\n 'The access policy kept changing while the operation was authorized.',\n );\n }\n\n /**\n * Checks the device-addition policy for every instance and release the target introduces.\n *\n * Generic transactions, undo and redo pass through here as well, so no entry point can introduce\n * a locked release that `canAddDevice` forbids.\n */\n async #requireAdditions(current: FusedDocument, target: FusedDocument): Promise<void> {\n const existingInstances = new Set(current.instances.map((instance) => instance.id));\n const locks = new Map<string, DeviceLock>();\n for (const instance of target.instances) {\n if (existingInstances.has(instance.id)) {\n continue;\n }\n const dependency = target.dependencies[instance.device];\n if (dependency === undefined) {\n continue;\n }\n locks.set(lockKey(instance.device, dependency), {\n id: instance.device,\n version: dependency.version,\n integrity: dependency.integrity,\n });\n }\n for (const [deviceId, dependency] of Object.entries(target.dependencies)) {\n if (current.dependencies[deviceId] !== undefined) {\n continue;\n }\n locks.set(lockKey(deviceId, dependency), {\n id: deviceId,\n version: dependency.version,\n integrity: dependency.integrity,\n });\n }\n for (const lock of locks.values()) {\n await this.#requireCanAddDevice(target, lock);\n }\n }\n\n #requireHistoryStep(entry: IHistoryEntry): void {\n this.#requireEdit(entry.contentChanged ? 'content' : 'layout');\n }\n\n #requireUnchangedLock(document: FusedDocument, lock: DeviceLock): void {\n const existing = document.dependencies[lock.id];\n if (\n existing !== undefined &&\n (existing.version !== lock.version || existing.integrity !== lock.integrity)\n ) {\n throw new FusedSessionError(\n 'document/locked-conflict',\n `\"${lock.id}\" is already locked to ${existing.version}; the document here does not replace an existing lock.`,\n );\n }\n }\n\n async #requireCanAddDevice(document: FusedDocument, device: DeviceLock): Promise<void> {\n let decision: AccessDecision;\n try {\n decision = await this.#access.canAddDevice({\n document,\n device,\n });\n } catch (cause) {\n throw new FusedSessionError(\n 'access/check-failed',\n 'The access policy cannot decide whether this device may be added.',\n { cause },\n );\n }\n const normalized = normalizeDecision(decision, 'device addition');\n if (!normalized.allowed) {\n throw accessDenied('access/add-denied', normalized);\n }\n }\n\n /**\n * Evaluates the access policy for `target`, the document a decision applies to.\n *\n * The returned decisions are the ones the caller must authorize with; the cached state only\n * follows the newest evaluation, so an older, slower answer cannot override a newer one.\n */\n async #evaluate(target: FusedDocument = this.#document): Promise<IDocumentAccess> {\n this.#assertAlive();\n const revision = (this.#evaluationRevision += 1);\n let decisions: IDocumentAccess;\n try {\n decisions = await evaluateDecisions(this.#access, target);\n } catch (cause) {\n if (revision > this.#appliedRevision) {\n this.#appliedRevision = revision;\n // Fail closed: a policy that cannot decide grants nothing until the next successful refresh.\n const message = 'The access policy could not evaluate this document.';\n this.#decisions = {\n edit: denied('access/check-failed', message),\n run: denied('access/check-failed', message),\n };\n this.#publishState();\n }\n throw cause;\n }\n if (revision > this.#appliedRevision) {\n this.#appliedRevision = revision;\n this.#decisions = decisions;\n }\n return decisions;\n }\n\n /**\n * Starts the re-check a provider change demands, outside the write queue.\n *\n * Writes wait for it through {@link #settleAccess}; its failure is reported and already left in\n * the fail-closed decisions.\n */\n #refreshAccessInBackground(): void {\n if (this.#disposed) {\n return;\n }\n const pending = this.#evaluate().then(() => {\n this.#publishState();\n });\n const tracked = pending.finally(() => {\n if (this.#pendingAccess === tracked) {\n this.#pendingAccess = undefined;\n }\n });\n this.#pendingAccess = tracked;\n void tracked.catch((cause: unknown) => {\n const error = toSessionError(cause, 'access/check-failed');\n if (!this.#disposed && error.code !== 'session/disposed') {\n this.#errors.fire(error);\n }\n });\n }\n\n /** Waits until no provider-triggered re-check is in flight. */\n async #settleAccess(): Promise<void> {\n for (let pass = 0; pass < 8; pass += 1) {\n const pending = this.#pendingAccess;\n if (pending === undefined) {\n return;\n }\n try {\n await pending;\n } catch {\n // Reported by the refresh; the decisions are already fail-closed.\n }\n if (this.#pendingAccess === pending) {\n this.#pendingAccess = undefined;\n return;\n }\n }\n }\n\n #publishState(): void {\n if (this.#disposed) {\n return;\n }\n const signature = this.#stateSignature();\n if (signature === this.#lastStateSignature) {\n return;\n }\n this.#lastStateSignature = signature;\n this.#state.fire(this.getState());\n }\n\n #stateSignature(): string {\n const state = this.getState();\n return JSON.stringify([\n state.canUndo,\n state.canRedo,\n state.dirty,\n state.readOnly,\n state.running,\n state.access.edit.allowed,\n state.access.edit.allowed ? '' : state.access.edit.code,\n state.access.run.allowed,\n state.access.run.allowed ? '' : state.access.run.code,\n ]);\n }\n\n #documentKey(document: FusedDocument): string {\n let key = this.#keys.get(document);\n if (key === undefined) {\n key = canonicalJson(document);\n this.#keys.set(document, key);\n }\n return key;\n }\n\n #contentKey(document: FusedDocument): string {\n let key = this.#contentKeys.get(document);\n if (key === undefined) {\n key = canonicalJson({\n ...document,\n instances: document.instances.map(({ viewLayout, ...rest }) => {\n void viewLayout;\n return rest;\n }),\n });\n this.#contentKeys.set(document, key);\n }\n return key;\n }\n\n #enqueue<T>(run: () => Promise<T>): Promise<T> {\n const result = this.#queue.then(async () => {\n this.#assertAlive();\n try {\n return await run();\n } catch (cause) {\n const error = toSessionError(cause, 'edit/invalid-document');\n if (!this.#disposed && error.code !== 'session/disposed') {\n this.#errors.fire(error);\n }\n throw error;\n }\n });\n this.#queue = result.then(\n () => undefined,\n () => undefined,\n );\n return result;\n }\n\n #assertAlive(): void {\n if (this.#disposed) {\n throw new FusedSessionError('session/disposed', 'The document session is disposed.');\n }\n }\n}\n\n/** Serializes the document for writing: readable strict JSON with a trailing newline. */\nexport function serializeFusedDocument(document: FusedDocument): string {\n return `${JSON.stringify(document, null, 2)}\\n`;\n}\n\nasync function evaluateDecisions(\n access: IWorkbenchAccessProvider,\n document: FusedDocument,\n): Promise<IDocumentAccess> {\n let decisions: IDocumentAccess | undefined;\n try {\n decisions = await access.evaluateDocument({ document });\n } catch (cause) {\n throw new FusedSessionError(\n 'access/check-failed',\n 'The access policy cannot evaluate this document.',\n { cause },\n );\n }\n return {\n edit: normalizeDecision(decisions?.edit, 'edit'),\n run: normalizeDecision(decisions?.run, 'run'),\n };\n}\n\nfunction normalizeDecision(decision: AccessDecision | undefined, label: string): AccessDecision {\n if (decision === undefined || decision === null || typeof decision !== 'object') {\n return denied('access/unavailable', `The access policy returned no ${label} decision.`);\n }\n if (decision.allowed === true) {\n return { allowed: true };\n }\n if (typeof decision.code === 'string' && typeof decision.message === 'string') {\n return { allowed: false, code: decision.code, message: decision.message };\n }\n return denied(\n 'access/invalid-decision',\n `The access policy returned a malformed ${label} decision.`,\n );\n}\n\nfunction denied(code: string, message: string): DeniedDecision {\n return { allowed: false, code, message };\n}\n\n/** Identity of one locked release inside a document's dependency table. */\nfunction lockKey(\n deviceId: string,\n dependency: { readonly version: string; readonly integrity: string },\n): string {\n return `${deviceId}@${dependency.version}#${dependency.integrity}`;\n}\n\n/** Keeps the prepared-device map identity while every entry is the same verified object. */\nfunction sameDevices(\n previous: ReadonlyMap<string, IPreparedDevice>,\n next: ReadonlyMap<string, IPreparedDevice>,\n): boolean {\n if (previous === next) {\n return true;\n }\n if (previous.size !== next.size) {\n return false;\n }\n for (const [deviceId, device] of previous) {\n if (next.get(deviceId) !== device) {\n return false;\n }\n }\n return true;\n}\n\nfunction canonicalJson(value: unknown): string {\n if (value === null || typeof value === 'boolean' || typeof value === 'number') {\n return JSON.stringify(value) ?? 'null';\n }\n if (typeof value === 'string') {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map((item) => canonicalJson(item)).join(',')}]`;\n }\n const record = value as Record<string, unknown>;\n const members = Object.keys(record)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`);\n return `{${members.join(',')}}`;\n}\n","import type { ICondition, IContextKeyService } from '../context';\nimport type {\n IWorkbenchContributions,\n IWorkbenchToolbarItem,\n IWorkbenchView,\n IWorkbenchViewContainer,\n} from '../types';\n\ntype Contribution = IWorkbenchViewContainer | IWorkbenchView | IWorkbenchToolbarItem;\n\nexport class ContributionRegistry {\n readonly containers: readonly IWorkbenchViewContainer[];\n readonly views: readonly IWorkbenchView[];\n readonly toolbar: readonly IWorkbenchToolbarItem[];\n readonly #conditions = new Map<string, ICondition>();\n readonly #context: IContextKeyService;\n\n constructor(\n context: IContextKeyService,\n builtin: IWorkbenchContributions,\n host: IWorkbenchContributions = {},\n ) {\n this.#context = context;\n const ids = new Set<string>();\n const collect = <T extends Contribution>(\n defaults: readonly T[] = [],\n additions: readonly T[] = [],\n ): readonly T[] => {\n for (const item of additions)\n if (item.id.startsWith('mica.')) throw new Error(`Reserved contribution ID: ${item.id}`);\n return Object.freeze(\n [...defaults, ...additions]\n .map((item) => {\n if (!/^[A-Za-z][A-Za-z0-9_-]*(?:\\.[A-Za-z0-9_-]+)+$/.test(item.id))\n throw new Error(`Contribution IDs must be namespaced: ${item.id}`);\n if (ids.has(item.id)) throw new Error(`Duplicate contribution ID: ${item.id}`);\n if (!item.title.trim()) throw new Error(`Missing contribution title: ${item.id}`);\n if (item.order !== undefined && !Number.isFinite(item.order))\n throw new Error(`Invalid contribution order: ${item.id}`);\n ids.add(item.id);\n if (item.when !== undefined)\n this.#conditions.set(`${item.id}:when`, context.compile(item.when));\n if ('enablement' in item && typeof item.enablement === 'string')\n this.#conditions.set(`${item.id}:enablement`, context.compile(item.enablement));\n const copy: T = { ...item };\n Object.freeze(copy);\n return copy;\n })\n .sort((a, b) => (a.order ?? 0) - (b.order ?? 0) || a.id.localeCompare(b.id)),\n );\n };\n this.containers = collect(builtin.containers, host.containers);\n this.views = collect(builtin.views, host.views);\n this.toolbar = Object.freeze(\n [...collect(builtin.toolbar, host.toolbar)].sort(\n (a, b) =>\n (a.group ?? '').localeCompare(b.group ?? '') ||\n (a.order ?? 0) - (b.order ?? 0) ||\n a.id.localeCompare(b.id),\n ),\n );\n for (const item of this.containers)\n if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(item.icon))\n throw new Error(`Invalid container icon: ${item.id}`);\n for (const view of this.views)\n if (!this.containers.some((container) => container.id === view.containerId))\n throw new Error(`Unknown view container ${view.containerId} for ${view.id}`);\n for (const view of this.views)\n if (typeof view.mount !== 'function') throw new Error(`Missing view mount: ${view.id}`);\n for (const item of this.toolbar) {\n if (typeof item.execute !== 'function')\n throw new Error(`Missing toolbar execute: ${item.id}`);\n if (item.icon !== undefined && !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(item.icon))\n throw new Error(`Invalid toolbar icon: ${item.id}`);\n }\n }\n\n visible(item: Contribution, context = this.#context): boolean {\n const condition = this.#conditions.get(`${item.id}:when`);\n return condition === undefined || context.evaluate(condition);\n }\n\n enabled(item: IWorkbenchToolbarItem, context = this.#context): boolean {\n const condition = this.#conditions.get(`${item.id}:enablement`);\n return condition === undefined || context.evaluate(condition);\n }\n\n affected(names: ReadonlySet<string>): boolean {\n return [...this.#conditions.values()].some((condition) =>\n [...condition.keys].some((key) => names.has(key)),\n );\n }\n}\n","import type { InstanceViewLayout, UnifiedDeviceManifest } from '@mica-js/document/fused';\n\nexport function resolveViewLayout(\n saved: InstanceViewLayout | undefined,\n manifest: UnifiedDeviceManifest,\n availableHeight: number,\n): InstanceViewLayout {\n const declared = Object.entries(manifest.view ?? {});\n const height = Math.max(120, Math.floor((availableHeight - 240) / Math.max(1, declared.length)));\n const views = declared.map(\n ([viewId, view]) =>\n saved?.views.find((entry) => entry.viewId === viewId) ?? {\n viewId,\n location: view.defaultLocation ?? 'sidebar',\n height,\n collapsed: false,\n },\n );\n if (saved !== undefined)\n views.sort((a, b) => {\n const index = (id: string) => {\n const found = saved.views.findIndex((entry) => entry.viewId === id);\n return found < 0 ? saved.views.length + declared.findIndex(([name]) => name === id) : found;\n };\n return index(a.viewId) - index(b.viewId);\n });\n return { properties: saved?.properties ?? { height: 200, collapsed: false }, views };\n}\n","import type { IWorkbenchViewContainer } from '../types';\n\nexport function Icon({ name }: { readonly name: string }) {\n return <span aria-hidden=\"true\" className={`codicon codicon-${name}`} />;\n}\n\nexport function ActivityBarPart(props: {\n readonly containers: readonly IWorkbenchViewContainer[];\n readonly active: string | undefined;\n readonly problemCount: number;\n readonly onActivate: (id: string) => void;\n}) {\n return (\n <nav className=\"mica-wb-activity-bar\" aria-label=\"工作台视图\">\n {props.containers.map((container) => (\n <button\n key={container.id}\n title={container.title}\n aria-label={container.title}\n aria-pressed={props.active === container.id}\n className={props.active === container.id ? 'is-active' : ''}\n onClick={() => props.onActivate(container.id)}\n >\n <Icon name={container.icon} />\n {container.id === 'mica.problems' && props.problemCount > 0 && (\n <span className=\"mica-wb-badge\">{props.problemCount}</span>\n )}\n </button>\n ))}\n </nav>\n );\n}\n","import type { FusedDocument, Point2D } from '@mica-js/document/fused';\nimport type { IWorkbenchTarget, WorkbenchMode } from '../types';\nimport {\n designatorPosition,\n endpointPosition,\n labelBounds,\n localToScene,\n referenceSymbolBounds,\n type ICanvasDevice,\n type IViewport,\n} from './geometry';\nimport type { WorkbenchThemeColors } from '../theme';\nimport {\n labelAnchorNode,\n moveLabel,\n moveReference,\n moveWireSegment,\n orthogonalPath,\n routeDocumentWires,\n} from '../wiring';\nimport { setTextOffset, type IFusedTextTarget } from '../document/edits';\n\nexport interface IRenderState {\n readonly document: FusedDocument;\n readonly devices: ReadonlyMap<string, ICanvasDevice>;\n readonly images: ReadonlyMap<string, CanvasImageSource>;\n readonly overlays: ReadonlyMap<string, ImageBitmap>;\n readonly viewport: IViewport;\n readonly mode: WorkbenchMode;\n readonly selection: readonly IWorkbenchTarget[];\n readonly preview?: {\n readonly from: Point2D;\n readonly bends: readonly Point2D[];\n readonly to: Point2D;\n };\n readonly drag?: { readonly instanceId: string; readonly position: Point2D };\n readonly wireDrag?: {\n readonly wireId: string;\n readonly segment: number;\n readonly delta: Point2D;\n };\n readonly textDrag?: { readonly target: IFusedTextTarget; readonly offset: Point2D };\n readonly referenceDrag?: { readonly referenceId: string; readonly position: Point2D };\n readonly labelDrag?: { readonly labelId: string; readonly position: Point2D };\n readonly ghost?: {\n readonly device: string;\n readonly position: Point2D;\n readonly rotation: number;\n };\n readonly annotation?: {\n readonly kind: 'power' | 'ground' | 'label';\n readonly position: Point2D;\n readonly name: string;\n readonly rotation: number;\n };\n readonly colors: WorkbenchThemeColors;\n}\n\nexport function drawCanvas(\n canvas: HTMLCanvasElement,\n width: number,\n height: number,\n state: IRenderState,\n): void {\n const context = canvas.getContext('2d');\n if (context === null) throw new Error('Canvas2D is not available');\n const ratio = globalThis.devicePixelRatio || 1;\n const bitmapWidth = Math.max(1, Math.round(width * ratio));\n const bitmapHeight = Math.max(1, Math.round(height * ratio));\n if (canvas.width !== bitmapWidth) canvas.width = bitmapWidth;\n if (canvas.height !== bitmapHeight) canvas.height = bitmapHeight;\n context.setTransform(ratio, 0, 0, ratio, 0, 0);\n context.fillStyle = state.colors['canvas.background'];\n context.fillRect(0, 0, width, height);\n const { scale, x, y } = state.viewport;\n context.translate(x, y);\n context.scale(scale, scale);\n const ink = state.colors['canvas.foreground'];\n context.lineWidth = 1 / scale;\n if (state.mode === 'edit') {\n let grid = 1;\n while (grid * scale < 10) grid *= 5;\n context.fillStyle = state.colors['canvas.grid'];\n for (let gx = Math.floor(-x / scale / grid) * grid; gx < (width - x) / scale; gx += grid)\n for (let gy = Math.floor(-y / scale / grid) * grid; gy < (height - y) / scale; gy += grid)\n context.fillRect(gx, gy, 1 / scale, 1 / scale);\n }\n let document =\n state.drag === undefined\n ? state.document\n : routeDocumentWires(\n {\n ...state.document,\n instances: state.document.instances.map((instance) =>\n instance.id === state.drag?.instanceId\n ? { ...instance, placement: { ...instance.placement, ...state.drag.position } }\n : instance,\n ),\n },\n state.devices,\n state.document,\n );\n if (state.wireDrag !== undefined)\n document = moveWireSegment(\n document,\n state.devices,\n state.wireDrag.wireId,\n state.wireDrag.segment,\n state.wireDrag.delta,\n );\n if (state.textDrag !== undefined)\n document = setTextOffset(document, state.textDrag.target, state.textDrag.offset);\n if (state.referenceDrag !== undefined) {\n let previewId = 0;\n document = moveReference(\n document,\n state.devices,\n state.referenceDrag.referenceId,\n state.referenceDrag.position,\n () => `__reference_drag_${previewId++}__`,\n );\n }\n if (\n state.labelDrag !== undefined &&\n labelAnchorNode(document, state.labelDrag.labelId) !== undefined\n )\n document = moveLabel(\n document,\n state.devices,\n state.labelDrag.labelId,\n state.labelDrag.position,\n );\n const stroke = (points: readonly Point2D[]): void => {\n context.beginPath();\n points.forEach((point, index) => {\n if (index === 0) context.moveTo(point.x, point.y);\n else context.lineTo(point.x, point.y);\n });\n context.stroke();\n };\n if (state.mode === 'edit') {\n for (const wire of document.wires) {\n context.strokeStyle = state.selection.some(\n (target) => target.kind === 'wire' && target.id === wire.id,\n )\n ? state.colors['canvas.selection']\n : state.colors['canvas.wire'];\n context.lineWidth =\n (state.selection.some((target) => target.id === wire.id) ? 2.5 : 1.5) / scale;\n stroke(\n orthogonalPath([\n endpointPosition(document, state.devices, wire.from),\n ...wire.bends,\n endpointPosition(document, state.devices, wire.to),\n ]),\n );\n }\n context.fillStyle = ink;\n for (const node of document.nodes) {\n context.beginPath();\n context.arc(node.x, node.y, (node.kind === 'junction' ? 3 : 2) / scale, 0, Math.PI * 2);\n context.fill();\n }\n context.lineWidth = 1.5 / scale;\n context.strokeStyle = state.colors['canvas.pin'];\n if (state.preview !== undefined) {\n context.setLineDash([5 / scale, 4 / scale]);\n stroke(orthogonalPath([state.preview.from, ...state.preview.bends, state.preview.to]));\n context.setLineDash([]);\n }\n }\n const instances =\n state.ghost === undefined\n ? document.instances\n : [\n ...document.instances,\n {\n id: '__preview__',\n device: state.ghost.device,\n placement: { ...state.ghost.position, rotation: state.ghost.rotation },\n },\n ];\n for (const instance of instances) {\n const device = state.devices.get(instance.device);\n if (device === undefined) continue;\n const geometry = device.geometry;\n const bounds = geometry.bounds;\n const body =\n state.mode === 'edit' || (instance.display?.body ?? document.display?.body ?? true);\n const overlay = state.overlays.get(instance.id);\n if (!body && overlay === undefined) continue;\n context.save();\n if (instance.id === '__preview__') context.globalAlpha = 0.5;\n context.translate(instance.placement.x, instance.placement.y);\n context.rotate((instance.placement.rotation * Math.PI) / 180);\n if (geometry.sizing === 'flexible') {\n context.scale(\n (instance.placement.width ?? bounds.width) / bounds.width,\n (instance.placement.height ?? bounds.height) / bounds.height,\n );\n context.translate(-bounds.x, -bounds.y);\n }\n if (body) {\n const image = state.images.get(instance.device);\n if (image !== undefined)\n context.drawImage(image, bounds.x, bounds.y, bounds.width, bounds.height);\n }\n if (overlay !== undefined)\n context.drawImage(overlay, bounds.x, bounds.y, bounds.width, bounds.height);\n if (state.selection.some((target) => target.kind === 'instance' && target.id === instance.id)) {\n context.strokeStyle = state.colors['canvas.selection'];\n context.lineWidth = 1.5 / scale;\n context.setLineDash([4 / scale, 3 / scale]);\n context.strokeRect(\n bounds.x - 3 / scale,\n bounds.y - 3 / scale,\n bounds.width + 6 / scale,\n bounds.height + 6 / scale,\n );\n context.setLineDash([]);\n }\n context.restore();\n if (\n (state.mode === 'edit' || (document.display?.designators ?? true)) &&\n instance.designator !== undefined\n ) {\n const anchor = designatorPosition(instance, geometry);\n context.font = `600 ${11 / scale}px system-ui`;\n context.fillStyle = ink;\n context.fillText(instance.designator, anchor.x, anchor.y - 5 / scale);\n }\n if (state.mode === 'edit') {\n const selected = state.selection.some((target) => target.id === instance.id);\n for (const [id, pin] of Object.entries(geometry.pins)) {\n const point = localToScene(instance, geometry, pin.position);\n context.strokeStyle = state.colors['canvas.pin'];\n context.lineWidth = 1.25 / scale;\n context.beginPath();\n context.arc(point.x, point.y, 2.5 / scale, 0, Math.PI * 2);\n context.stroke();\n if (selected || scale >= 3) {\n context.font = `${10 / scale}px system-ui`;\n context.fillStyle = ink;\n const length = Math.hypot(pin.outward.x, pin.outward.y);\n const label =\n pin.label?.visible === false ? undefined : (device.manifest.pins?.[id]?.label ?? id);\n if (label === undefined) continue;\n if (pin.label?.position !== undefined) {\n const labelPoint = localToScene(instance, geometry, pin.label.position);\n context.textAlign = 'left';\n context.fillText(label, labelPoint.x, labelPoint.y);\n } else {\n const outwardPoint = localToScene(instance, geometry, {\n x: pin.position.x + pin.outward.x / length,\n y: pin.position.y + pin.outward.y / length,\n });\n const dx = outwardPoint.x - point.x;\n const dy = outwardPoint.y - point.y;\n context.textAlign = dx < -0.1 ? 'right' : 'left';\n context.fillText(\n label,\n point.x + (dx * 7) / scale,\n point.y + (dy * 7) / scale + 3 / scale,\n );\n }\n }\n }\n context.textAlign = 'left';\n }\n }\n if (state.mode === 'edit') {\n const annotations: FusedDocument =\n state.annotation === undefined\n ? document\n : {\n ...document,\n nodes: [\n ...document.nodes,\n { id: '__annotation__', kind: 'free', ...state.annotation.position },\n ],\n labels:\n state.annotation.kind === 'label'\n ? [\n ...document.labels,\n {\n id: '__annotation__',\n target: { kind: 'node', node: '__annotation__' },\n name: state.annotation.name,\n },\n ]\n : document.labels,\n references:\n state.annotation.kind === 'label'\n ? document.references\n : [\n ...document.references,\n {\n id: '__annotation__',\n target: { kind: 'node', node: '__annotation__' },\n symbol: state.annotation.kind,\n voltage: state.annotation.kind === 'ground' ? 0 : 5,\n rotation: state.annotation.rotation,\n },\n ],\n };\n context.strokeStyle = ink;\n context.fillStyle = ink;\n context.lineWidth = 0.1;\n context.font = '0.75px system-ui';\n for (const label of annotations.labels) {\n const point = endpointPosition(annotations, state.devices, label.target);\n context.save();\n if (label.id === '__annotation__') context.globalAlpha = 0.5;\n if (state.selection.some((target) => target.kind === 'label' && target.id === label.id)) {\n const bounds = labelBounds(label);\n context.strokeStyle = state.colors['canvas.selection'];\n context.lineWidth = 1.5 / scale;\n context.setLineDash([4 / scale, 3 / scale]);\n context.strokeRect(\n point.x + bounds.x - 3 / scale,\n point.y + bounds.y - 3 / scale,\n bounds.width + 6 / scale,\n bounds.height + 6 / scale,\n );\n context.setLineDash([]);\n }\n context.fillText(\n label.name,\n point.x + (label.offset?.x ?? 0.3),\n point.y + (label.offset?.y ?? -0.35),\n );\n context.restore();\n }\n for (const reference of annotations.references) {\n const point = endpointPosition(annotations, state.devices, reference.target);\n context.save();\n if (reference.id === '__annotation__') context.globalAlpha = 0.5;\n context.translate(point.x, point.y);\n context.rotate(((reference.rotation ?? 0) * Math.PI) / 180);\n if (\n state.selection.some((target) => target.kind === 'reference' && target.id === reference.id)\n ) {\n const bounds = referenceSymbolBounds(reference);\n context.strokeStyle = state.colors['canvas.selection'];\n context.lineWidth = 1.5 / scale;\n context.setLineDash([4 / scale, 3 / scale]);\n context.strokeRect(\n bounds.x - 3 / scale,\n bounds.y - 3 / scale,\n bounds.width + 6 / scale,\n bounds.height + 6 / scale,\n );\n context.setLineDash([]);\n }\n context.strokeStyle = ink;\n context.lineWidth = 0.1;\n const unit = 0.1;\n stroke([\n { x: 0, y: 0 },\n { x: 0, y: -12 * unit },\n ]);\n if (reference.symbol === 'ground') {\n for (let index = 0; index < 3; index++)\n stroke([\n { x: (-7 + index * 2) * unit, y: (-12 - index * 3) * unit },\n { x: (7 - index * 2) * unit, y: (-12 - index * 3) * unit },\n ]);\n } else {\n stroke([\n { x: -5 * unit, y: -8 * unit },\n { x: 0, y: -13 * unit },\n { x: 5 * unit, y: -8 * unit },\n ]);\n }\n if (reference.symbol !== 'ground')\n context.fillText(\n reference.label?.name ?? `${reference.voltage} V`,\n reference.label?.offset?.x ?? 7 * unit,\n reference.label?.offset?.y ?? -14 * unit,\n );\n context.restore();\n }\n }\n}\n","import {\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n type PointerEvent as ReactPointerEvent,\n} from 'react';\nimport type { DeviceLock, Endpoint, FusedDocument, Point2D } from '@mica-js/document/fused';\nimport type { IWorkbenchState, IWorkbenchTarget } from '../types';\nimport {\n contains,\n distanceToSegment,\n endpointPosition,\n fitViewport,\n pickInstance,\n pickAnnotation,\n pickPins,\n pickWireSegment,\n pickText,\n textDragOffset,\n sceneToLocal,\n toScene,\n type ICanvasDevice,\n type IPinHit,\n type IViewport,\n} from '../canvas/geometry';\nimport { drawCanvas } from '../canvas/renderer';\nimport { hasWireConnection, labelAnchorNode, orthogonalPath } from '../wiring';\nimport { projectOnSegment } from '@mica-js/document/schematic';\nimport { readCanvasTheme, type IResolvedWorkbenchTheme } from '../theme';\nimport type { IFusedTextTarget } from '../document/edits';\n\nexport interface ICanvasHandle {\n readonly scale: number;\n fit(): void;\n zoom(factor: number): void;\n reveal(instanceId: string): void;\n}\n\nexport interface IViewInput {\n readonly type: 'pointerdown' | 'pointermove' | 'pointerup';\n readonly position: Point2D;\n readonly button: number;\n readonly buttons: number;\n}\n\nexport interface ICanvasPartProps {\n readonly document: FusedDocument;\n readonly devices: ReadonlyMap<string, ICanvasDevice>;\n readonly images: ReadonlyMap<string, CanvasImageSource>;\n readonly overlays: ReadonlyMap<string, ImageBitmap>;\n readonly state: IWorkbenchState;\n readonly selection: readonly IWorkbenchTarget[];\n readonly placement: DeviceLock | undefined;\n readonly placementRotation: number;\n readonly labelName: string;\n readonly theme: IResolvedWorkbenchTheme;\n readonly frame: number;\n readonly onReady: (handle: ICanvasHandle | undefined) => void;\n readonly onSelection: (selection: readonly IWorkbenchTarget[]) => void;\n readonly onOpenProperties: () => void;\n readonly onPlace: (device: DeviceLock, position: Point2D) => Promise<void>;\n readonly onMove: (instanceId: string, position: Point2D) => Promise<void>;\n readonly onMoveSegment: (wireId: string, segment: number, delta: Point2D) => Promise<void>;\n readonly onMoveText: (target: IFusedTextTarget, offset: Point2D) => Promise<void>;\n readonly onMoveReference: (referenceId: string, position: Point2D) => Promise<void>;\n readonly onMoveLabel: (labelId: string, position: Point2D) => Promise<void>;\n readonly onStartWire: () => Promise<void>;\n readonly onConnect: (\n from: Endpoint | Point2D,\n to: Endpoint | Point2D,\n bends: readonly Point2D[],\n ) => Promise<void>;\n readonly onEndpoint: (endpoint: Endpoint | Point2D) => Promise<void>;\n readonly onCancel: () => void;\n readonly onDelete: () => Promise<void>;\n readonly onInput: (instanceId: string, input: IViewInput) => void;\n readonly onError: (error: unknown) => void;\n readonly onFocus: (focused: boolean) => void;\n readonly onViewport: () => void;\n readonly children?: React.ReactNode;\n}\n\nexport function CanvasPart(props: ICanvasPartProps) {\n const host = useRef<HTMLDivElement>(null);\n const canvas = useRef<HTMLCanvasElement>(null);\n const [size, setSize] = useState({ width: 1, height: 1 });\n const [viewport, setViewport] = useState<IViewport>({ x: 80, y: 80, scale: 10 });\n const [pointer, setPointer] = useState<Point2D>({ x: 0, y: 0 });\n const [hovered, setHovered] = useState(false);\n const committing = useRef(false);\n const [connection, setConnection] = useState<{\n readonly endpoint: Endpoint | Point2D;\n readonly bends: readonly Point2D[];\n }>();\n const pendingWireStart = useRef<Endpoint | Point2D | undefined>(undefined);\n const [drag, setDrag] = useState<{ readonly instanceId: string; readonly position: Point2D }>();\n const [wireDrag, setWireDrag] = useState<{\n readonly wireId: string;\n readonly segment: number;\n readonly delta: Point2D;\n }>();\n const [textDrag, setTextDrag] = useState<{\n readonly target: IFusedTextTarget;\n readonly offset: Point2D;\n }>();\n const [referenceDrag, setReferenceDrag] = useState<{\n readonly referenceId: string;\n readonly position: Point2D;\n }>();\n const [labelDrag, setLabelDrag] = useState<{\n readonly labelId: string;\n readonly position: Point2D;\n }>();\n const [candidates, setCandidates] = useState<readonly IPinHit[]>([]);\n const gesture = useRef<\n | {\n readonly kind: 'pan' | 'move';\n readonly pointerId: number;\n readonly start: Point2D;\n readonly original: Point2D;\n readonly instanceId?: string;\n }\n | {\n readonly kind: 'wire';\n readonly pointerId: number;\n readonly start: Point2D;\n readonly wireId: string;\n readonly segment: number;\n }\n | {\n readonly kind: 'text';\n readonly pointerId: number;\n readonly start: Point2D;\n readonly target: IFusedTextTarget;\n }\n | {\n readonly kind: 'reference';\n readonly pointerId: number;\n readonly start: Point2D;\n readonly original: Point2D;\n readonly referenceId: string;\n moved: boolean;\n }\n | {\n readonly kind: 'label';\n readonly pointerId: number;\n readonly start: Point2D;\n readonly original: Point2D;\n readonly labelId: string;\n moved: boolean;\n }\n | undefined\n >(undefined);\n const business = useRef<\n | {\n readonly instanceId: string;\n readonly pointerId: number;\n position: Point2D;\n readonly button: number;\n }\n | undefined\n >(undefined);\n const current = useRef(props);\n current.current = props;\n\n const run = (task: Promise<void>) => {\n void task.catch(props.onError);\n };\n const fit = () =>\n setViewport(fitViewport(props.document, props.devices, size.width, size.height));\n const zoom = (factor: number, center: Point2D = { x: size.width / 2, y: size.height / 2 }) => {\n setViewport((value) => {\n const scale = Math.max(0.25, Math.min(100, value.scale * factor));\n return {\n scale,\n x: center.x - ((center.x - value.x) * scale) / value.scale,\n y: center.y - ((center.y - value.y) * scale) / value.scale,\n };\n });\n };\n const currentZoom = useRef(zoom);\n currentZoom.current = zoom;\n useEffect(() => {\n const element = canvas.current;\n if (element === null) return;\n const wheel = (event: WheelEvent) => {\n event.preventDefault();\n const rect = element.getBoundingClientRect();\n currentZoom.current(Math.exp(-event.deltaY * 0.001), {\n x: event.clientX - rect.left,\n y: event.clientY - rect.top,\n });\n };\n element.addEventListener('wheel', wheel, { passive: false });\n return () => element.removeEventListener('wheel', wheel);\n }, []);\n const reveal = (instanceId: string) => {\n const instance = props.document.instances.find((item) => item.id === instanceId);\n if (instance === undefined) throw new Error(`Unknown instance: ${instanceId}`);\n setViewport((value) => ({\n ...value,\n x: size.width / 2 - instance.placement.x * value.scale,\n y: size.height / 2 - instance.placement.y * value.scale,\n }));\n canvas.current?.focus();\n };\n function cancelGesture(): void {\n const active = business.current;\n const pointerId = active?.pointerId ?? gesture.current?.pointerId;\n business.current = undefined;\n gesture.current = undefined;\n setDrag(undefined);\n setWireDrag(undefined);\n setTextDrag(undefined);\n setReferenceDrag(undefined);\n setLabelDrag(undefined);\n if (active !== undefined)\n current.current.onInput(active.instanceId, {\n type: 'pointerup',\n position: active.position,\n button: active.button,\n buttons: 0,\n });\n if (pointerId !== undefined && canvas.current?.hasPointerCapture(pointerId))\n canvas.current.releasePointerCapture(pointerId);\n }\n useLayoutEffect(() => {\n props.onReady({ fit, zoom, reveal, scale: viewport.scale });\n return () => props.onReady(undefined);\n });\n useEffect(() => props.onViewport(), [viewport.scale]);\n useLayoutEffect(() => {\n const element = host.current;\n if (element === null) return;\n let initialized = false;\n const observer = new ResizeObserver(([entry]) => {\n if (entry === undefined) return;\n const { width, height } = entry.contentRect;\n setSize({ width, height });\n if (!initialized && width > 0 && height > 0) {\n initialized = true;\n setViewport(fitViewport(current.current.document, current.current.devices, width, height));\n }\n });\n observer.observe(element);\n return () => observer.disconnect();\n }, []);\n useEffect(() => {\n const endpoint = pendingWireStart.current;\n pendingWireStart.current = undefined;\n setConnection(\n props.state.mode === 'edit' &&\n !props.state.readOnly &&\n props.state.tool === 'wire' &&\n endpoint !== undefined\n ? { endpoint, bends: [] }\n : undefined,\n );\n setCandidates([]);\n cancelGesture();\n }, [props.state.mode, props.state.tool, props.state.readOnly]);\n useEffect(() => {\n const release = () => cancelGesture();\n window.addEventListener('blur', release);\n return () => window.removeEventListener('blur', release);\n }, []);\n const annotationTool =\n props.state.tool === 'power' || props.state.tool === 'ground' || props.state.tool === 'label'\n ? props.state.tool\n : undefined;\n useEffect(() => {\n if (canvas.current === null) return;\n const frame = requestAnimationFrame(() => {\n if (canvas.current === null) return;\n try {\n drawCanvas(canvas.current, size.width, size.height, {\n document: props.document,\n devices: props.devices,\n images: props.images,\n overlays: props.overlays,\n viewport,\n mode: props.state.mode,\n selection: props.selection,\n colors: readCanvasTheme(canvas.current),\n ...(drag === undefined ? {} : { drag }),\n ...(wireDrag === undefined ? {} : { wireDrag }),\n ...(textDrag === undefined ? {} : { textDrag }),\n ...(referenceDrag === undefined ? {} : { referenceDrag }),\n ...(labelDrag === undefined ? {} : { labelDrag }),\n ...(!hovered || props.placement === undefined\n ? {}\n : {\n ghost: {\n device: props.placement.id,\n position: pointer,\n rotation: props.placementRotation,\n },\n }),\n ...(!hovered ||\n props.state.mode !== 'edit' ||\n props.state.readOnly ||\n annotationTool === undefined\n ? {}\n : {\n annotation: {\n kind: annotationTool,\n position: pointer,\n name: props.labelName,\n rotation: props.placementRotation,\n },\n }),\n ...(connection === undefined\n ? {}\n : {\n preview: {\n from: anchorPoint(connection.endpoint),\n bends: connection.bends,\n to: pointer,\n },\n }),\n });\n } catch (error) {\n props.onError(error);\n }\n });\n return () => cancelAnimationFrame(frame);\n }, [\n props.document,\n props.devices,\n props.images,\n props.overlays,\n props.selection,\n props.state.mode,\n props.theme,\n props.frame,\n props.placement,\n props.placementRotation,\n props.labelName,\n props.state.tool,\n props.state.readOnly,\n hovered,\n viewport,\n size,\n connection,\n pointer,\n drag,\n wireDrag,\n textDrag,\n referenceDrag,\n labelDrag,\n ]);\n\n function local(\n event: Pick<ReactPointerEvent<HTMLCanvasElement>, 'currentTarget' | 'clientX' | 'clientY'>,\n ): Point2D {\n const rect = event.currentTarget.getBoundingClientRect();\n return { x: event.clientX - rect.left, y: event.clientY - rect.top };\n }\n const snap = (point: Point2D, alt: boolean): Point2D =>\n alt ? point : { x: Math.round(point.x), y: Math.round(point.y) };\n function anchorPoint(anchor: Endpoint | Point2D): Point2D {\n return 'kind' in anchor ? endpointPosition(props.document, props.devices, anchor) : anchor;\n }\n function snappedAnchor(point: Point2D, alt: boolean): Endpoint | Point2D {\n const annotation = pickAnnotation(props.document, props.devices, point, 3 / viewport.scale);\n if (annotation?.kind === 'reference') {\n const reference = props.document.references.find((value) => value.id === annotation.id);\n if (reference !== undefined) return reference.target;\n }\n const pin = pickPins(props.document, props.devices, point, 7 / viewport.scale)[0];\n if (pin !== undefined) return pin.endpoint;\n const node = props.document.nodes.find(\n (value) => Math.hypot(value.x - point.x, value.y - point.y) <= 7 / viewport.scale,\n );\n if (node !== undefined) return { kind: 'node', node: node.id };\n let best: { point: Point2D; distance: number } | undefined;\n for (const wire of props.document.wires) {\n const points = orthogonalPath([\n endpointPosition(props.document, props.devices, wire.from),\n ...wire.bends,\n endpointPosition(props.document, props.devices, wire.to),\n ]);\n for (let index = 1; index < points.length; index++) {\n const from = points[index - 1];\n const to = points[index];\n if (from === undefined || to === undefined) continue;\n const projected = projectOnSegment(point, from, to);\n const distance = Math.hypot(projected.x - point.x, projected.y - point.y);\n if (distance > 7 / viewport.scale || (best !== undefined && distance >= best.distance))\n continue;\n const grid = snap(projected, alt);\n const onAxis = from.x === to.x ? { x: from.x, y: grid.y } : { x: grid.x, y: from.y };\n best = { point: projectOnSegment(onAxis, from, to), distance };\n }\n }\n return best?.point ?? snap(point, alt);\n }\n function commit(action: () => Promise<void>): void {\n if (committing.current) return;\n committing.current = true;\n void action()\n .catch(props.onError)\n .finally(() => {\n committing.current = false;\n });\n }\n function useEndpoint(endpoint: Endpoint | Point2D) {\n setCandidates([]);\n if (props.state.tool === 'select') {\n if ('kind' in endpoint)\n props.onSelection([\n endpoint.kind === 'pin'\n ? { kind: 'instance', id: endpoint.instance }\n : { kind: 'node', id: endpoint.node },\n ]);\n startWire(endpoint);\n return;\n }\n if (props.state.tool !== 'wire') {\n commit(() => props.onEndpoint(endpoint));\n return;\n }\n if (connection === undefined) setConnection({ endpoint, bends: [] });\n else {\n commit(async () => {\n await props.onConnect(connection.endpoint, endpoint, connection.bends);\n setConnection(undefined);\n props.onCancel();\n });\n }\n }\n /** Wire starts only on the electrical anchor, not on the rest of the terminal symbol. */\n function atAnchor(endpoint: Endpoint, point: Point2D): boolean {\n const anchor = anchorPoint(endpoint);\n return Math.hypot(anchor.x - point.x, anchor.y - point.y) <= 7 / viewport.scale;\n }\n function startWire(endpoint: Endpoint | Point2D): void {\n if (props.state.readOnly || props.state.mode !== 'edit') return;\n if ('kind' in endpoint && hasWireConnection(props.document, endpoint)) return;\n if (props.state.tool === 'wire') {\n setConnection({ endpoint, bends: [] });\n return;\n }\n pendingWireStart.current = endpoint;\n commit(async () => {\n try {\n await props.onStartWire();\n } catch (error) {\n pendingWireStart.current = undefined;\n throw error;\n }\n });\n }\n function input(event: ReactPointerEvent<HTMLCanvasElement>, type: IViewInput['type']): void {\n const active = business.current;\n if (active === undefined || active.pointerId !== event.pointerId) return;\n const instance = props.document.instances.find((value) => value.id === active.instanceId);\n const geometry =\n instance === undefined ? undefined : props.devices.get(instance.device)?.geometry;\n if (instance === undefined || geometry === undefined) return;\n active.position = sceneToLocal(instance, geometry, toScene(local(event), viewport));\n props.onInput(instance.id, {\n type,\n position: active.position,\n button: active.button,\n buttons: type === 'pointerup' ? 0 : event.buttons,\n });\n }\n return (\n <div className=\"mica-wb-canvas-part\" ref={host}>\n <canvas\n ref={canvas}\n tabIndex={0}\n aria-label=\"电路画布\"\n className={`mica-wb-canvas mica-wb-tool-${props.state.tool}`}\n onFocus={() => props.onFocus(true)}\n onBlur={() => {\n cancelGesture();\n props.onFocus(false);\n }}\n onContextMenu={(event) => {\n event.preventDefault();\n setConnection(undefined);\n props.onCancel();\n }}\n onKeyDown={(event) => {\n if (event.key === 'Escape') {\n setConnection(undefined);\n setCandidates([]);\n cancelGesture();\n props.onCancel();\n }\n if (\n (event.key === 'Delete' || event.key === 'Backspace') &&\n !props.state.readOnly &&\n props.state.mode === 'edit'\n ) {\n event.preventDefault();\n setConnection(undefined);\n setCandidates([]);\n cancelGesture();\n props.onCancel();\n run(props.onDelete());\n }\n }}\n onPointerDown={(event) => {\n if (gesture.current !== undefined || business.current !== undefined) return;\n event.currentTarget.focus();\n const screen = local(event);\n const point = toScene(screen, viewport);\n if (event.button === 1) {\n gesture.current = {\n kind: 'pan',\n pointerId: event.pointerId,\n start: screen,\n original: { x: viewport.x, y: viewport.y },\n };\n event.currentTarget.setPointerCapture(event.pointerId);\n event.preventDefault();\n return;\n }\n if (event.button !== 0 || props.state.busy || committing.current) return;\n if (props.state.mode === 'run') {\n const instance = pickInstance(\n props.document,\n props.devices,\n point,\n (value) =>\n props.overlays.has(value.id) ||\n ((value.display?.body ?? props.document.display?.body ?? true) &&\n props.images.has(value.device)),\n );\n if (instance === undefined) return;\n const geometry = props.devices.get(instance.device)?.geometry;\n if (\n geometry === undefined ||\n !contains(geometry.bounds, sceneToLocal(instance, geometry, point))\n )\n return;\n props.onSelection([{ kind: 'instance', id: instance.id }]);\n business.current = {\n instanceId: instance.id,\n pointerId: event.pointerId,\n position: sceneToLocal(instance, geometry, point),\n button: event.button,\n };\n event.currentTarget.setPointerCapture(event.pointerId);\n input(event, 'pointerdown');\n return;\n }\n const placing = props.placement;\n if (placing !== undefined && !props.state.readOnly) {\n commit(() => props.onPlace(placing, snap(point, event.altKey)));\n return;\n }\n if (props.state.tool !== 'select' && !props.state.readOnly) {\n if (props.state.tool === 'wire') {\n const annotation = pickAnnotation(\n props.document,\n props.devices,\n point,\n 3 / viewport.scale,\n );\n if (annotation?.kind === 'reference') {\n const reference = props.document.references.find(\n (value) => value.id === annotation.id,\n );\n if (reference !== undefined) {\n useEndpoint(reference.target);\n return;\n }\n }\n }\n const pins = pickPins(props.document, props.devices, point, 7 / viewport.scale);\n if (pins.length > 1) {\n setCandidates(pins);\n return;\n }\n if (pins[0] !== undefined) {\n useEndpoint(pins[0].endpoint);\n return;\n }\n const node = props.document.nodes.find(\n (value) => Math.hypot(value.x - point.x, value.y - point.y) <= 7 / viewport.scale,\n );\n if (node !== undefined) {\n useEndpoint({ kind: 'node', node: node.id });\n return;\n }\n const anchor = snappedAnchor(point, event.altKey);\n if (props.state.tool !== 'wire') useEndpoint(anchor);\n else if (\n 'kind' in anchor ||\n props.document.wires.some((wire) => {\n const points = [\n endpointPosition(props.document, props.devices, wire.from),\n ...wire.bends,\n endpointPosition(props.document, props.devices, wire.to),\n ];\n return points.some(\n (value, index) =>\n index > 0 &&\n distanceToSegment(anchorPoint(anchor), points[index - 1] ?? value, value) <\n 1e-8,\n );\n })\n )\n useEndpoint(anchor);\n else if (connection === undefined) setConnection({ endpoint: anchor, bends: [] });\n else\n setConnection({\n ...connection,\n bends: orthogonalPath([\n anchorPoint(connection.endpoint),\n ...connection.bends,\n anchorPoint(anchor),\n ]).slice(1),\n });\n return;\n }\n const text = pickText(props.document, props.devices, point, viewport.scale);\n if (text !== undefined) {\n const target: IWorkbenchTarget = {\n kind: text.kind === 'designator' ? 'instance' : text.kind,\n id: text.id,\n };\n props.onSelection(\n event.shiftKey\n ? [...props.selection.filter((value) => value.id !== target.id), target]\n : [target],\n );\n if (!props.state.readOnly) {\n const anchor =\n text.kind === 'label' ? labelAnchorNode(props.document, text.id) : undefined;\n const node = props.document.nodes.find((value) => value.id === anchor);\n if (anchor !== undefined && node !== undefined) {\n gesture.current = {\n kind: 'label',\n pointerId: event.pointerId,\n start: point,\n original: { x: node.x, y: node.y },\n labelId: text.id,\n moved: false,\n };\n } else {\n gesture.current = {\n kind: 'text',\n pointerId: event.pointerId,\n start: point,\n target: text,\n };\n }\n event.currentTarget.setPointerCapture(event.pointerId);\n }\n return;\n }\n const annotation = pickAnnotation(\n props.document,\n props.devices,\n point,\n 3 / viewport.scale,\n );\n if (annotation !== undefined) {\n props.onSelection(\n event.shiftKey\n ? [...props.selection.filter((value) => value.id !== annotation.id), annotation]\n : [annotation],\n );\n if (annotation.kind === 'reference' && !props.state.readOnly) {\n const reference = props.document.references.find(\n (value) => value.id === annotation.id,\n );\n if (reference !== undefined) {\n gesture.current = {\n kind: 'reference',\n pointerId: event.pointerId,\n start: point,\n original: endpointPosition(props.document, props.devices, reference.target),\n referenceId: reference.id,\n moved: false,\n };\n event.currentTarget.setPointerCapture(event.pointerId);\n }\n }\n return;\n }\n if (!props.state.readOnly) {\n const pins = pickPins(props.document, props.devices, point, 7 / viewport.scale);\n if (pins.length > 1) {\n setCandidates(pins);\n return;\n }\n if (pins[0] !== undefined) {\n useEndpoint(pins[0].endpoint);\n return;\n }\n const node = props.document.nodes.find(\n (value) => Math.hypot(value.x - point.x, value.y - point.y) <= 7 / viewport.scale,\n );\n if (node !== undefined) {\n useEndpoint({ kind: 'node', node: node.id });\n return;\n }\n }\n const instance = pickInstance(props.document, props.devices, point);\n if (instance !== undefined) {\n const target: IWorkbenchTarget = { kind: 'instance', id: instance.id };\n props.onSelection(\n event.shiftKey\n ? [...props.selection.filter((value) => value.id !== instance.id), target]\n : [target],\n );\n if (!props.state.readOnly && !props.state.busy) {\n gesture.current = {\n kind: 'move',\n pointerId: event.pointerId,\n start: point,\n original: instance.placement,\n instanceId: instance.id,\n };\n event.currentTarget.setPointerCapture(event.pointerId);\n }\n return;\n }\n const wire = pickWireSegment(props.document, props.devices, point, 6 / viewport.scale);\n props.onSelection(wire === undefined ? [] : [{ kind: 'wire', id: wire.wireId }]);\n if (wire !== undefined && !props.state.readOnly) {\n gesture.current = {\n kind: 'wire',\n pointerId: event.pointerId,\n start: point,\n wireId: wire.wireId,\n segment: wire.segment,\n };\n event.currentTarget.setPointerCapture(event.pointerId);\n }\n }}\n onDoubleClick={(event) => {\n if (props.state.mode !== 'edit' || props.state.busy || props.placement !== undefined)\n return;\n if (props.state.tool === 'wire') {\n if (connection !== undefined)\n useEndpoint(snappedAnchor(toScene(local(event), viewport), event.altKey));\n return;\n }\n const instance = pickInstance(\n props.document,\n props.devices,\n toScene(local(event), viewport),\n );\n if (instance === undefined) return;\n props.onSelection([{ kind: 'instance', id: instance.id }]);\n props.onOpenProperties();\n }}\n onPointerMove={(event) => {\n const point = toScene(local(event), viewport);\n setPointer(\n props.placement !== undefined || props.state.tool === 'select'\n ? snap(point, event.altKey)\n : anchorPoint(snappedAnchor(point, event.altKey)),\n );\n if (business.current !== undefined) {\n input(event, 'pointermove');\n return;\n }\n const active = gesture.current;\n if (active !== undefined && active.pointerId !== event.pointerId) return;\n if (active?.kind === 'pan') {\n const screen = local(event);\n setViewport({\n ...viewport,\n x: active.original.x + screen.x - active.start.x,\n y: active.original.y + screen.y - active.start.y,\n });\n } else if (active?.kind === 'move' && active.instanceId !== undefined) {\n setDrag({\n instanceId: active.instanceId,\n position: snap(\n {\n x: active.original.x + point.x - active.start.x,\n y: active.original.y + point.y - active.start.y,\n },\n event.altKey,\n ),\n });\n } else if (active?.kind === 'wire') {\n setWireDrag({\n wireId: active.wireId,\n segment: active.segment,\n delta: snap(\n { x: point.x - active.start.x, y: point.y - active.start.y },\n event.altKey,\n ),\n });\n } else if (active?.kind === 'text') {\n const delta = snap(\n { x: point.x - active.start.x, y: point.y - active.start.y },\n event.altKey,\n );\n setTextDrag({\n target: active.target,\n offset: textDragOffset(props.document, props.devices, active.target, delta),\n });\n } else if (active?.kind === 'label') {\n if (\n Math.hypot(point.x - active.start.x, point.y - active.start.y) * viewport.scale >=\n 3\n )\n active.moved = true;\n if (active.moved)\n setLabelDrag({\n labelId: active.labelId,\n position: snap(\n {\n x: active.original.x + point.x - active.start.x,\n y: active.original.y + point.y - active.start.y,\n },\n event.altKey,\n ),\n });\n } else if (active?.kind === 'reference') {\n if (\n Math.hypot(point.x - active.start.x, point.y - active.start.y) * viewport.scale >=\n 3\n )\n active.moved = true;\n if (active.moved)\n setReferenceDrag({\n referenceId: active.referenceId,\n position: snap(\n {\n x: active.original.x + point.x - active.start.x,\n y: active.original.y + point.y - active.start.y,\n },\n event.altKey,\n ),\n });\n }\n }}\n onPointerUp={(event) => {\n if (business.current?.pointerId === event.pointerId) {\n input(event, 'pointerup');\n business.current = undefined;\n }\n const active = gesture.current;\n if (active !== undefined && active.pointerId !== event.pointerId) return;\n if (active?.kind === 'move' && active.instanceId !== undefined) {\n const point = toScene(local(event), viewport);\n const position = snap(\n {\n x: active.original.x + point.x - active.start.x,\n y: active.original.y + point.y - active.start.y,\n },\n event.altKey,\n );\n if (position.x !== active.original.x || position.y !== active.original.y)\n run(props.onMove(active.instanceId, position));\n } else if (active?.kind === 'wire') {\n const point = toScene(local(event), viewport);\n const delta = snap(\n { x: point.x - active.start.x, y: point.y - active.start.y },\n event.altKey,\n );\n if (delta.x !== 0 || delta.y !== 0)\n commit(() => props.onMoveSegment(active.wireId, active.segment, delta));\n } else if (active?.kind === 'text') {\n const point = toScene(local(event), viewport);\n const delta = snap(\n { x: point.x - active.start.x, y: point.y - active.start.y },\n event.altKey,\n );\n if (delta.x !== 0 || delta.y !== 0)\n commit(() =>\n props.onMoveText(\n active.target,\n textDragOffset(props.document, props.devices, active.target, delta),\n ),\n );\n else if (active.target.kind === 'reference') {\n const reference = props.document.references.find(\n (value) => value.id === active.target.id,\n );\n if (reference !== undefined && atAnchor(reference.target, active.start))\n startWire(reference.target);\n }\n } else if (active?.kind === 'label') {\n if (active.moved) {\n const point = toScene(local(event), viewport);\n const position = snap(\n {\n x: active.original.x + point.x - active.start.x,\n y: active.original.y + point.y - active.start.y,\n },\n event.altKey,\n );\n if (position.x !== active.original.x || position.y !== active.original.y)\n commit(() => props.onMoveLabel(active.labelId, position));\n }\n } else if (active?.kind === 'reference') {\n if (active.moved) {\n const point = toScene(local(event), viewport);\n const position = snap(\n {\n x: active.original.x + point.x - active.start.x,\n y: active.original.y + point.y - active.start.y,\n },\n event.altKey,\n );\n if (position.x !== active.original.x || position.y !== active.original.y)\n commit(() => props.onMoveReference(active.referenceId, position));\n } else {\n const reference = props.document.references.find(\n (value) => value.id === active.referenceId,\n );\n if (reference !== undefined && atAnchor(reference.target, active.start))\n startWire(reference.target);\n }\n }\n gesture.current = undefined;\n setDrag(undefined);\n setWireDrag(undefined);\n setTextDrag(undefined);\n setReferenceDrag(undefined);\n setLabelDrag(undefined);\n if (event.currentTarget.hasPointerCapture(event.pointerId))\n event.currentTarget.releasePointerCapture(event.pointerId);\n }}\n onPointerEnter={() => setHovered(true)}\n onPointerLeave={() => setHovered(false)}\n onPointerCancel={(event) => {\n if (\n business.current?.pointerId === event.pointerId ||\n gesture.current?.pointerId === event.pointerId\n )\n cancelGesture();\n }}\n onLostPointerCapture={(event) => {\n if (\n business.current?.pointerId === event.pointerId ||\n gesture.current?.pointerId === event.pointerId\n )\n cancelGesture();\n }}\n />\n {candidates.length > 0 && (\n <div className=\"mica-wb-pin-candidates\" role=\"dialog\" aria-label=\"选择引脚\">\n {candidates.map((value) => (\n <button key={value.title} onClick={() => useEndpoint(value.endpoint)}>\n {value.title}\n </button>\n ))}\n <button onClick={() => setCandidates([])}>取消</button>\n </div>\n )}\n <div className=\"mica-wb-viewport-controls\" aria-label=\"视口控制\">\n <button title=\"缩小\" aria-label=\"缩小\" onClick={() => zoom(1 / 1.2)}>\n −\n </button>\n <span>{Math.round(viewport.scale * 10)}%</span>\n <button title=\"放大\" aria-label=\"放大\" onClick={() => zoom(1.2)}>\n +\n </button>\n <button title=\"适应画布\" aria-label=\"适应画布\" onClick={fit}>\n 适应\n </button>\n </div>\n {props.children}\n </div>\n );\n}\n","import { useEffect, useRef, useState } from 'react';\nimport type { Disposable } from '@mica-js/core/lifecycle';\nimport type {\n IWorkbenchDiagnostic,\n IWorkbenchExtensionContext,\n IWorkbenchView,\n IWorkbenchViewContainer,\n} from '../types';\nimport { Icon } from './activity-bar-part';\n\nfunction ContributedView(props: {\n readonly hideHeader: boolean;\n readonly view: IWorkbenchView;\n readonly context: IWorkbenchExtensionContext;\n readonly report: (diagnostic: IWorkbenchDiagnostic) => void;\n}) {\n const element = useRef<HTMLDivElement>(null);\n const [error, setError] = useState<string>();\n useEffect(() => {\n const target = element.current;\n if (target === null) return;\n const abort = new AbortController();\n const scope = props.context.contextKeys.createScope();\n let result: Disposable | undefined;\n const fail = (error: unknown) => {\n const message = error instanceof Error ? error.message : String(error);\n if (!abort.signal.aborted) setError(message);\n props.report({\n code: 'workbench/view-failed',\n message: `${props.view.title}: ${message}`,\n severity: 'error',\n });\n };\n setError(undefined);\n void Promise.resolve()\n .then(() =>\n props.view.mount(target, { ...props.context, contextKeys: scope, signal: abort.signal }),\n )\n .then((disposable) => {\n if (typeof disposable?.dispose !== 'function')\n throw new TypeError(`视图 ${props.view.id} 必须返回 Disposable`);\n if (abort.signal.aborted) disposable.dispose();\n else result = disposable;\n })\n .catch(fail);\n return () => {\n abort.abort();\n scope.dispose();\n try {\n result?.dispose();\n } catch (error) {\n fail(error);\n }\n };\n }, [props.view, props.context]);\n return (\n <section className=\"mica-wb-contributed-view\" aria-label={props.view.title}>\n {!props.hideHeader && <h3>{props.view.title}</h3>}\n {error !== undefined && <p role=\"alert\">{error}</p>}\n <div ref={element} className=\"mica-wb-view-mount\" />\n </section>\n );\n}\n\nexport function SidebarPart(props: {\n readonly container: IWorkbenchViewContainer;\n readonly views: readonly IWorkbenchView[];\n readonly context: IWorkbenchExtensionContext;\n readonly onClose: () => void;\n readonly report: (diagnostic: IWorkbenchDiagnostic) => void;\n readonly children?: React.ReactNode;\n readonly hideHeader?: boolean;\n readonly title?: string | undefined;\n readonly actions?: React.ReactNode;\n readonly properties?: boolean;\n readonly singleView?: boolean;\n}) {\n const sidebar = useRef<HTMLElement>(null);\n return (\n <aside\n ref={sidebar}\n className={`mica-wb-sidebar${props.properties ? ' mica-wb-sidebar-properties' : ''}${props.singleView ? ' mica-wb-sidebar-single' : ''}`}\n aria-label={props.container.title}\n >\n <div\n role=\"separator\"\n aria-label=\"调整侧栏宽度\"\n aria-orientation=\"vertical\"\n tabIndex={0}\n className=\"mica-wb-sidebar-resizer\"\n onKeyDown={(event) => {\n if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;\n event.preventDefault();\n const root = sidebar.current?.closest<HTMLElement>('.mica-workbench');\n if (root !== null && root !== undefined)\n root.style.setProperty(\n '--mica-sidebar-width',\n `${Math.max(240, Math.min(480, (sidebar.current?.offsetWidth ?? 320) + (event.key === 'ArrowLeft' ? 20 : -20)))}px`,\n );\n }}\n onPointerDown={(event) => {\n const root = sidebar.current?.closest<HTMLElement>('.mica-workbench');\n if (root === null || root === undefined) return;\n event.currentTarget.setPointerCapture(event.pointerId);\n const start = event.clientX;\n const width = sidebar.current?.offsetWidth ?? 320;\n const handle = event.currentTarget;\n const move = (input: PointerEvent) =>\n root.style.setProperty(\n '--mica-sidebar-width',\n `${Math.max(240, Math.min(480, width + start - input.clientX))}px`,\n );\n const end = () => {\n handle.removeEventListener('pointermove', move);\n handle.removeEventListener('pointerup', end);\n handle.removeEventListener('pointercancel', end);\n };\n handle.addEventListener('pointermove', move);\n handle.addEventListener('pointerup', end);\n handle.addEventListener('pointercancel', end);\n }}\n />\n {!props.hideHeader && (\n <header className=\"mica-wb-sidebar-header\">\n <span>\n {props.title ??\n (props.singleView\n ? (props.views[0]?.title ?? props.container.title)\n : props.container.title)}\n </span>\n <span className=\"mica-wb-panel-actions\">\n {props.actions}\n <button title=\"收起侧栏\" aria-label=\"收起侧栏\" onClick={props.onClose}>\n <Icon name=\"chevron-right\" />\n </button>\n </span>\n </header>\n )}\n <div className=\"mica-wb-sidebar-content\">\n {props.children}\n {props.views.map((view) => (\n <ContributedView\n key={view.id}\n hideHeader={props.singleView === true}\n view={view}\n context={props.context}\n report={props.report}\n />\n ))}\n </div>\n </aside>\n );\n}\n","import { useLayoutEffect, useRef, useState } from 'react';\nimport type { IWorkbenchExtensionContext, IWorkbenchState, IWorkbenchToolbarItem } from '../types';\nimport type { ContributionRegistry } from '../contributions/registry';\nimport { Icon } from './activity-bar-part';\n\nexport function ToolbarPart(props: {\n readonly state: IWorkbenchState;\n readonly registry: ContributionRegistry;\n readonly context: IWorkbenchExtensionContext;\n readonly onError: (error: unknown) => void;\n}) {\n const [more, setMore] = useState(false);\n const toolbar = useRef<HTMLDivElement>(null);\n const modeGroup = useRef<HTMLDivElement>(null);\n const measurements = useRef<HTMLDivElement>(null);\n const divider = useRef<HTMLSpanElement>(null);\n const [layout, setLayout] = useState({ compact: false, count: Infinity });\n const items = props.registry.toolbar.filter((item) => props.registry.visible(item));\n useLayoutEffect(() => {\n const element = toolbar.current;\n const mode = modeGroup.current;\n const measure = measurements.current;\n const parent = element?.parentElement;\n if (!element || !mode || !measure || !parent) return;\n const update = () => {\n const style = getComputedStyle(element);\n const number = (value: string) => Number.parseFloat(value) || 0;\n const available = parent.clientWidth - number(style.left) * 2;\n const base =\n mode.getBoundingClientRect().width +\n number(style.paddingLeft) +\n number(style.paddingRight) +\n number(style.borderLeftWidth) +\n number(style.borderRightWidth);\n const separator = divider.current;\n const separatorStyle = separator && getComputedStyle(separator);\n const separatorWidth =\n separator && separatorStyle\n ? separator.getBoundingClientRect().width +\n number(separatorStyle.marginLeft) +\n number(separatorStyle.marginRight)\n : 0;\n const rows = [...measure.children];\n const widths = (row: Element | undefined) =>\n row ? [...row.children].map((child) => child.getBoundingClientRect().width) : [];\n const full = widths(rows[0]);\n const compact = widths(rows[1]);\n const gap = number(style.columnGap);\n const itemGap = rows[0] ? number(getComputedStyle(rows[0]).columnGap) : 0;\n const moreWidth = rows[2]?.getBoundingClientRect().width ?? 0;\n const required = (values: number[], count: number, overflow: boolean) =>\n base +\n separatorWidth +\n values.slice(0, count).reduce((sum, width) => sum + width, 0) +\n Math.max(0, count - 1) * itemGap +\n (overflow ? moreWidth : 0) +\n ((count > 0 ? 1 : 0) + (overflow ? 1 : 0) + (items.length > 0 ? 1 : 0)) * gap;\n let next = { compact: false, count: items.length };\n if (required(full, full.length, false) > available) {\n next = { compact: true, count: items.length };\n if (required(compact, compact.length, false) > available) {\n while (next.count > 0 && required(compact, next.count, true) > available) next.count--;\n }\n }\n setLayout((current) =>\n current.compact === next.compact && current.count === next.count ? current : next,\n );\n if (next.count === items.length) setMore(false);\n };\n const observer = new ResizeObserver(update);\n observer.observe(parent);\n observer.observe(mode);\n for (const row of measure.children) observer.observe(row);\n update();\n return () => observer.disconnect();\n }, [items]);\n const visible = items.slice(0, layout.count);\n const overflow = items.slice(layout.count);\n const execute = (item: IWorkbenchToolbarItem) => {\n setMore(false);\n if (!props.registry.enabled(item)) return;\n try {\n void Promise.resolve(item.execute(props.context)).catch(props.onError);\n } catch (error) {\n props.onError(error);\n }\n };\n const itemButton = (item: IWorkbenchToolbarItem) => (\n <button\n key={item.id}\n className={item.icon === undefined ? undefined : 'mica-wb-icon-tool'}\n title={item.title}\n aria-label={item.title}\n disabled={!props.registry.enabled(item)}\n aria-pressed={\n item.id.startsWith('mica.tool.')\n ? props.state.tool === item.id.slice('mica.tool.'.length)\n : undefined\n }\n onClick={() => execute(item)}\n >\n {item.icon !== undefined && <Icon name={item.icon} />}\n <span className=\"mica-wb-toolbar-label\">{item.title}</span>\n </button>\n );\n return (\n <div ref={toolbar} className=\"mica-wb-toolbar\" role=\"toolbar\" aria-label=\"电路工具\">\n <div ref={measurements} className=\"mica-wb-toolbar-measure\" aria-hidden=\"true\" inert>\n <div className=\"mica-wb-tools-inline\">{items.map(itemButton)}</div>\n <div className=\"mica-wb-tools-inline\" data-compact=\"true\">\n {items.map(itemButton)}\n </div>\n <span className=\"mica-wb-more-button\">\n <Icon name=\"ellipsis\" />\n </span>\n </div>\n <div\n ref={modeGroup}\n className=\"mica-wb-mode\"\n role=\"group\"\n aria-label=\"工作台模式\"\n data-mode={props.state.mode}\n >\n {(['edit', 'run'] as const).map((mode) => (\n <button\n key={mode}\n aria-pressed={props.state.mode === mode}\n disabled={props.state.busy}\n className={props.state.mode === mode ? 'is-active' : ''}\n onClick={() => {\n setMore(false);\n void props.context.workbench.setMode(mode).catch(props.onError);\n }}\n >\n <Icon name={mode === 'edit' ? 'edit' : 'play'} />\n {mode === 'edit' ? '编辑' : '运行'}\n </button>\n ))}\n </div>\n {items.length > 0 && (\n <>\n <span ref={divider} className=\"mica-wb-toolbar-divider\" />\n {visible.length > 0 && (\n <div className=\"mica-wb-tools-inline\" data-compact={layout.compact}>\n {visible.map(itemButton)}\n </div>\n )}\n {overflow.length > 0 && (\n <>\n <button\n className=\"mica-wb-more-button\"\n aria-label=\"更多工具\"\n title=\"更多工具\"\n aria-expanded={more}\n onClick={() => setMore(!more)}\n >\n <Icon name=\"ellipsis\" />\n </button>\n {more && (\n <div className=\"mica-wb-more-menu\" aria-label=\"其他工具\">\n {overflow.map(itemButton)}\n </div>\n )}\n </>\n )}\n </>\n )}\n </div>\n );\n}\n","import { useState } from 'react';\nimport type { FusedDocument } from '@mica-js/document/fused';\nimport type { ICanvasDevice } from '../canvas/geometry';\nimport type { IWorkbenchTarget } from '../types';\n\nexport function InstancesView(props: {\n readonly document: FusedDocument;\n readonly devices: ReadonlyMap<string, ICanvasDevice>;\n readonly selection: readonly IWorkbenchTarget[];\n readonly onSelect: (id: string) => void;\n}) {\n const [query, setQuery] = useState('');\n const instances = props.document.instances.filter((instance) =>\n `${instance.designator ?? ''} ${props.devices.get(instance.device)?.manifest.displayName ?? instance.device}`\n .toLowerCase()\n .includes(query.toLowerCase()),\n );\n return (\n <section className=\"mica-wb-instances\" aria-label=\"已放置器件\">\n <input\n type=\"search\"\n aria-label=\"搜索已放置器件\"\n placeholder=\"搜索位号或器件\"\n value={query}\n onChange={(event) => setQuery(event.target.value)}\n />\n <div role=\"list\" className=\"mica-wb-object-list\">\n {instances.map((instance) => (\n <button\n role=\"listitem\"\n key={instance.id}\n className={\n props.selection.some((target) => target.id === instance.id) ? 'is-active' : ''\n }\n onClick={() => props.onSelect(instance.id)}\n >\n <strong>{instance.designator ?? '—'}</strong>\n <span>\n {props.devices.get(instance.device)?.manifest.displayName ?? instance.device}\n </span>\n </button>\n ))}\n </div>\n {instances.length === 0 && (\n <p className=\"mica-wb-empty\">{query ? '没有匹配的器件' : '尚未放置器件'}</p>\n )}\n </section>\n );\n}\n","import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react';\nimport type { ReactNode, RefObject } from 'react';\nimport type { DevicePropertyDescriptor, PropertyValue } from '@mica-js/document/fused';\nimport type { ProgramProject, ProgramSources, ProgramTarget } from '@mica-js/sdk/fused';\nimport type { IAssetProvider } from '../providers';\nimport type { FusedPresentationValue } from '../runtime/protocol';\nimport { Icon } from '../parts/activity-bar-part';\n\nexport function programPackageCandidates(\n paths: readonly string[],\n loader: ProgramTarget['loader'],\n formats: readonly string[] = [],\n): readonly string[] {\n if (loader === 'memory')\n return paths\n .filter((path) => path.startsWith('assets/') && formats.includes(programFormat(path) ?? ''))\n .sort();\n const directories = new Set<string>();\n for (const path of paths) {\n if (!path.startsWith('assets/')) continue;\n const parts = path.split('/');\n for (let i = 1; i < parts.length; i++) directories.add(parts.slice(0, i).join('/'));\n }\n return [...directories].sort();\n}\n\nexport function programFormat(path: string): 'bin' | 'hex' | 'elf' | undefined {\n const ext = path.split('.').at(-1)?.toLowerCase();\n return ext === 'bin'\n ? 'bin'\n : ext === 'hex' || ext === 'ihx'\n ? 'hex'\n : ext === 'elf' || ext === 'axf'\n ? 'elf'\n : undefined;\n}\n\nexport function validateProgramProjects(\n values: readonly ProgramProject[],\n): readonly ProgramProject[] {\n if (\n !Array.isArray(values) ||\n values.some(\n (value) =>\n !value ||\n typeof value.id !== 'string' ||\n !value.id.trim() ||\n typeof value.title !== 'string' ||\n !value.title.trim(),\n ) ||\n new Set(values.map((value) => value.id)).size !== values.length\n )\n throw new Error('program/project-selection-failed: 项目信息无效');\n return values;\n}\n\nfunction ResourcePopover(props: {\n readonly id: string;\n readonly anchor: RefObject<HTMLButtonElement | null>;\n readonly open: boolean;\n readonly onClose: () => void;\n readonly label: string;\n readonly className: string;\n readonly children: ReactNode;\n}) {\n const element = useRef<HTMLDivElement>(null);\n useLayoutEffect(() => {\n const popup = element.current;\n const anchor = props.anchor.current;\n if (!props.open || popup === null || anchor === null) return;\n popup.showPopover();\n const place = () => {\n const rect = anchor.getBoundingClientRect();\n const width = popup.offsetWidth;\n const height = popup.offsetHeight;\n popup.style.left = `${Math.max(8, Math.min(rect.right - width, window.innerWidth - width - 8))}px`;\n popup.style.top = `${Math.max(8, Math.min(rect.bottom + 4 + height <= window.innerHeight - 8 ? rect.bottom + 4 : rect.top - height - 4, window.innerHeight - height - 8))}px`;\n };\n place();\n const observer = new ResizeObserver(place);\n observer.observe(popup);\n window.addEventListener('resize', place);\n window.addEventListener('scroll', place, true);\n return () => {\n observer.disconnect();\n window.removeEventListener('resize', place);\n window.removeEventListener('scroll', place, true);\n };\n }, [props.open, props.anchor]);\n return props.open ? (\n <div\n id={props.id}\n ref={element}\n popover=\"auto\"\n className={`mica-wb-resource-popover ${props.className}`}\n aria-label={props.label}\n onToggle={(event) => {\n if (!event.currentTarget.matches(':popover-open')) props.onClose();\n }}\n >\n {props.children}\n </div>\n ) : null;\n}\n\nexport function ResourceField(props: {\n readonly name: string;\n readonly descriptor: DevicePropertyDescriptor;\n readonly value: PropertyValue | undefined;\n readonly overridden: boolean;\n readonly target: ProgramTarget;\n readonly sources: ProgramSources | undefined;\n readonly assets: IAssetProvider | undefined;\n readonly packagePaths: readonly string[];\n readonly snapshot: FusedPresentationValue | undefined;\n readonly disabled: boolean;\n readonly set: (value: PropertyValue) => void;\n readonly reset: () => void;\n readonly validate: (value: PropertyValue, signal: AbortSignal) => Promise<Uint8Array | undefined>;\n readonly commit: (value: PropertyValue, signal: AbortSignal) => Promise<void>;\n readonly onOpenProject: (id: string) => void;\n readonly onError: (error: unknown) => void;\n}) {\n const { descriptor, target, sources } = props;\n const reference =\n props.value !== null && typeof props.value === 'object' ? props.value : undefined;\n const [menu, setMenu] = useState(false);\n const [packagePicker, setPackagePicker] = useState(false);\n const [details, setDetails] = useState(false);\n const [busy, setBusy] = useState(false);\n const [error, setError] = useState('');\n const [retry, setRetry] = useState(0);\n const [projectFormat, setProjectFormat] = useState<string>();\n const [address, setAddress] = useState('');\n const [preview, setPreview] = useState<string>();\n const menuId = useId();\n const detailsId = useId();\n const menuButton = useRef<HTMLButtonElement>(null);\n const detailsButton = useRef<HTMLButtonElement>(null);\n const pending = useRef<AbortController | undefined>(undefined);\n const retryChoice = useRef<\n ((signal: AbortSignal) => Promise<PropertyValue | undefined>) | undefined\n >(undefined);\n const signature = JSON.stringify([target, props.value]);\n useEffect(() => {\n pending.current?.abort();\n setBusy(false);\n setError('');\n setMenu(false);\n setPackagePicker(false);\n retryChoice.current = undefined;\n return () => {\n pending.current?.abort();\n };\n }, [signature, props.disabled, sources, props.assets]);\n const fail = (cause: unknown) => {\n setError(cause instanceof Error ? cause.message : String(cause));\n props.onError(cause);\n };\n const perform = async (choose: (signal: AbortSignal) => Promise<PropertyValue | undefined>) => {\n if (props.disabled || busy) return;\n pending.current?.abort();\n const controller = new AbortController();\n pending.current = controller;\n setMenu(false);\n setBusy(true);\n setError('');\n retryChoice.current = choose;\n try {\n const value = await choose(controller.signal);\n if (value === undefined || controller.signal.aborted) return;\n retryChoice.current = async () => value;\n await props.validate(value, controller.signal);\n if (controller.signal.aborted) return;\n await props.commit(value, controller.signal);\n setPackagePicker(false);\n } catch (cause) {\n if (!controller.signal.aborted) fail(cause);\n } finally {\n if (!controller.signal.aborted) setBusy(false);\n }\n };\n const program = descriptor.type === 'program';\n const memory = target.loader === 'memory';\n const sourceName = reference?.mode === 'package' ? reference.src : reference?.name;\n const name = reference?.mode === 'project' ? (reference.name ?? reference.projectId) : sourceName;\n const source =\n reference?.mode === 'asset'\n ? '资产库'\n : reference?.mode === 'project'\n ? '项目'\n : reference?.mode === 'package'\n ? '内置资源'\n : '';\n const sourceIcon =\n reference?.mode === 'asset' ? 'cloud' : reference?.mode === 'project' ? 'project' : 'package';\n const hasDetails = (program && memory) || (!program && reference?.mode === 'asset');\n const detailsTitle = program ? '装载设置' : '资源详情';\n useEffect(() => {\n setPreview(undefined);\n if (descriptor.type !== 'image' || !reference) return;\n const controller = new AbortController();\n let url: string | undefined;\n void props\n .validate(reference, controller.signal)\n .then((bytes) => {\n if (controller.signal.aborted || bytes === undefined) return;\n const type = sourceName?.toLowerCase().endsWith('.svg') ? 'image/svg+xml' : 'image/png';\n url = URL.createObjectURL(new Blob([bytes.slice().buffer], { type }));\n setPreview(url);\n })\n .catch((cause) => {\n if (!controller.signal.aborted) fail(cause);\n });\n return () => {\n controller.abort();\n if (url) URL.revokeObjectURL(url);\n };\n }, [signature, props.assets, retry]);\n const candidates = program\n ? programPackageCandidates(props.packagePaths, target.loader, descriptor.formats)\n : props.packagePaths\n .filter(\n (path) =>\n path.startsWith('assets/') &&\n (descriptor.type === 'image'\n ? /\\.(png|svg)$/i.test(path)\n : descriptor.type === 'firmware'\n ? programFormat(path) !== undefined\n : !descriptor.extensions?.length ||\n descriptor.extensions.some((ext) =>\n path.toLowerCase().endsWith(ext.toLowerCase()),\n )),\n )\n .sort();\n const format = reference?.mode === 'project' ? projectFormat : programFormat(sourceName ?? '');\n const defaults = program ? descriptor.defaults : undefined;\n const selectedSpace =\n reference && 'addressSpace' in reference\n ? (reference.addressSpace ?? defaults?.addressSpace)\n : defaults?.addressSpace;\n const loadAddress =\n reference && 'loadAddress' in reference\n ? (reference.loadAddress ?? defaults?.loadAddress)\n : defaults?.loadAddress;\n const spaces = descriptor.addressSpaces ?? {};\n useEffect(\n () => setAddress(loadAddress === undefined ? '' : `0x${loadAddress.toString(16)}`),\n [loadAddress, signature],\n );\n useEffect(() => {\n setProjectFormat(undefined);\n if (!details || reference?.mode !== 'project' || !sources?.projects) return;\n const controller = new AbortController();\n void sources.projects\n .resolve(reference.projectId, target, controller.signal)\n .then((artifact) => {\n if (controller.signal.aborted) return;\n if (artifact.kind !== target.loader) throw new Error('program/loader-mismatch');\n setProjectFormat(artifact.kind === 'memory' ? artifact.format : undefined);\n })\n .catch((cause) => {\n if (!controller.signal.aborted) fail(cause);\n });\n return () => controller.abort();\n }, [details, signature, sources, retry]);\n const validAddress = (space: string, value: number) => {\n const range = spaces[space];\n return (\n range &&\n Number.isSafeInteger(value) &&\n value >= range.start &&\n value < range.start + range.size\n );\n };\n const saveAddress = () => {\n if (props.disabled || !reference || format !== 'bin') return;\n const value = /^(?:0x[0-9a-f]+|[0-9]+)$/i.test(address.trim()) ? Number(address) : NaN;\n if (!selectedSpace || !validAddress(selectedSpace, value)) {\n fail(new Error('program/out-of-range: 装载地址不在空间范围内'));\n return;\n }\n void perform(async () => ({ ...reference, loadAddress: value }));\n };\n const snapshot = props.snapshot;\n return (\n <div\n className=\"mica-wb-program-control\"\n onKeyDown={(event) => {\n if (event.key === 'Escape') {\n if (menu) menuButton.current?.focus();\n else if (details) detailsButton.current?.focus();\n setMenu(false);\n setDetails(false);\n setPackagePicker(false);\n }\n }}\n >\n <div className=\"mica-wb-resource-control\">\n {preview && <img className=\"mica-wb-resource-preview\" src={preview} alt=\"\" />}\n <div className=\"mica-wb-resource-summary\">\n {source && (\n <span className=\"mica-wb-resource-source\" title={source} aria-label={source}>\n <Icon name={sourceIcon} />\n </span>\n )}\n <span className=\"mica-wb-resource-name\" title={name}>\n {name ?? '未设置'}\n </span>\n {source && !props.overridden && <small>默认</small>}\n </div>\n <button\n ref={menuButton}\n className=\"mica-wb-resource-action\"\n aria-label={`${name ? '更换' : '选择'}${descriptor.title ?? props.name}来源`}\n title={`${name ? '更换' : '选择'}来源`}\n aria-controls={menuId}\n aria-expanded={menu}\n disabled={props.disabled || busy}\n onClick={() => setMenu(!menu)}\n >\n <Icon name=\"chevron-down\" />\n </button>\n {hasDetails && (\n <button\n ref={detailsButton}\n className=\"mica-wb-resource-action\"\n aria-label={detailsTitle}\n title={detailsTitle}\n aria-controls={detailsId}\n aria-expanded={details}\n onClick={() => setDetails(!details)}\n >\n <Icon name={program ? 'settings-gear' : 'info'} />\n </button>\n )}\n {reference?.mode === 'project' && (\n <button\n title=\"打开项目\"\n aria-label=\"打开项目\"\n onClick={() => props.onOpenProject(reference.projectId)}\n >\n <Icon name=\"go-to-file\" />\n </button>\n )}\n </div>\n <ResourcePopover\n id={menuId}\n anchor={menuButton}\n open={menu}\n onClose={() => setMenu(false)}\n className=\"mica-wb-resource-menu\"\n label=\"资源来源\"\n >\n <button\n disabled={!props.assets}\n onClick={() =>\n void perform(async (signal) => {\n const asset = await props.assets!.select({\n kind:\n program || descriptor.type === 'firmware'\n ? 'program'\n : descriptor.type === 'image'\n ? 'image'\n : 'binary',\n ...(program\n ? { formats: memory ? descriptor.formats : ['zip'] }\n : descriptor.type === 'binary' && descriptor.extensions\n ? { formats: descriptor.extensions.map((ext) => ext.slice(1)) }\n : descriptor.type === 'firmware'\n ? { formats: ['bin', 'hex', 'elf'] }\n : {}),\n signal,\n });\n if (asset === undefined) return undefined;\n if (\n typeof asset.id !== 'string' ||\n !asset.id.trim() ||\n typeof asset.name !== 'string' ||\n !asset.name.trim()\n )\n throw new Error('asset/invalid-selection: 资产信息无效');\n return { mode: 'asset', assetId: asset.id, name: asset.name };\n })\n }\n >\n 从资产库选择…\n </button>\n {program && (\n <button\n disabled={!sources?.projects?.select}\n onClick={() =>\n void perform(async (signal) => {\n const project = await sources!.projects!.select!(\n { ...target, templateIds: [...(descriptor.templates ?? [])] },\n signal,\n );\n if (project === undefined) return undefined;\n validateProgramProjects([project]);\n return { mode: 'project', projectId: project.id, name: project.title };\n })\n }\n >\n 从项目选择…\n </button>\n )}\n <button\n onClick={() => {\n setMenu(false);\n setPackagePicker(true);\n }}\n >\n 从内置资源选择…\n </button>\n {props.overridden && descriptor.default !== undefined && (\n <button\n onClick={() => {\n setMenu(false);\n props.reset();\n }}\n >\n 恢复默认\n </button>\n )}\n {descriptor.nullable && props.value !== null && (\n <button\n onClick={() => {\n setMenu(false);\n props.set(null);\n }}\n >\n 清除\n </button>\n )}\n </ResourcePopover>\n {packagePicker && (\n <div className=\"mica-wb-resource-control\">\n <select\n aria-label=\"内置资源\"\n disabled={busy || props.disabled}\n value=\"\"\n onChange={(event) => {\n const src = event.target.value;\n if (src) void perform(async () => ({ mode: 'package', src }));\n }}\n >\n <option value=\"\">选择内置资源</option>\n {candidates.map((path) => (\n <option key={path} value={path}>\n {path}\n </option>\n ))}\n </select>\n {!candidates.length && <span>没有匹配的内置资源</span>}\n <button disabled={busy} onClick={() => setPackagePicker(false)}>\n 取消\n </button>\n </div>\n )}\n {busy && <span role=\"status\">选择/校验中…</span>}\n {error && (\n <div role=\"alert\">\n {error}\n <button\n disabled={busy}\n onClick={() => {\n setError('');\n setRetry((value) => value + 1);\n if (!props.disabled && retryChoice.current) void perform(retryChoice.current);\n }}\n >\n 重试\n </button>\n </div>\n )}\n <ResourcePopover\n id={detailsId}\n anchor={detailsButton}\n open={details && hasDetails}\n onClose={() => setDetails(false)}\n className=\"mica-wb-resource-details\"\n label={detailsTitle}\n >\n {!program && reference?.mode === 'asset' && (\n <div className=\"mica-wb-resource-details\">UUID:{reference.assetId}</div>\n )}\n {program && (\n <div className=\"mica-wb-resource-details\">\n {reference?.mode === 'asset' && <div>UUID:{reference.assetId}</div>}\n {memory && (\n <>\n <div>格式:{format?.toUpperCase() ?? '等待产物信息'}</div>\n {format === 'elf' &&\n Object.entries(spaces).map(([id, space]) => (\n <div key={id}>\n {space.title ?? id}: [0x{space.start.toString(16)}, 0x\n {(space.start + space.size).toString(16)})\n </div>\n ))}\n {(format === 'bin' || format === 'hex') && (\n <label>\n 地址空间\n <select\n aria-label=\"地址空间\"\n value={selectedSpace ?? ''}\n disabled={\n props.disabled || busy || Object.keys(spaces).length < 2 || !reference\n }\n onChange={(event) => {\n const addressSpace = event.target.value;\n if (\n format === 'bin' &&\n loadAddress !== undefined &&\n !validAddress(addressSpace, loadAddress)\n ) {\n fail(new Error('program/out-of-range'));\n return;\n }\n if (reference) void perform(async () => ({ ...reference, addressSpace }));\n }}\n >\n {Object.entries(spaces).map(([id, space]) => (\n <option key={id} value={id}>\n {space.title ?? id}\n </option>\n ))}\n </select>\n </label>\n )}\n {format === 'bin' && (\n <label>\n 装载地址\n <input\n aria-label=\"装载地址\"\n value={address}\n disabled={props.disabled || busy || !reference}\n onChange={(event) => setAddress(event.target.value)}\n onBlur={saveAddress}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault();\n saveAddress();\n }\n }}\n />\n </label>\n )}\n {snapshot &&\n typeof snapshot === 'object' &&\n 'kind' in snapshot &&\n snapshot.kind === 'firmware' &&\n snapshot.segments.map((segment, index) => (\n <div key={index}>\n {segment.addressSpace}: 0x{segment.address.toString(16)} ·{' '}\n {segment.bytes.byteLength} 字节\n </div>\n ))}\n </>\n )}\n </div>\n )}\n </ResourcePopover>\n </div>\n );\n}\n","import { useEffect, useState } from 'react';\nimport type {\n ConnectionNode,\n ConnectionWire,\n DevicePropertyDescriptor,\n FusedInstance,\n NetLabel,\n PropertyValue,\n UnifiedDeviceManifest,\n VoltageReference,\n} from '@mica-js/document/fused';\nimport type { IAssetProvider } from '../providers';\nimport { Icon } from '../parts/activity-bar-part';\nimport { ResourceField } from './program';\nimport type { ProgramSources, ProgramTarget } from '@mica-js/sdk/fused';\nimport type { FusedPresentationProps } from '../runtime/protocol';\n\ninterface IPropertyProps {\n readonly name: string;\n readonly descriptor: DevicePropertyDescriptor;\n readonly value: PropertyValue | undefined;\n readonly overridden: boolean;\n readonly disabled: boolean;\n readonly set: (value: PropertyValue) => void;\n readonly reset: () => void;\n readonly onError: (error: unknown) => void;\n readonly assets: IAssetProvider | undefined;\n readonly validate: (value: PropertyValue, signal: AbortSignal) => Promise<Uint8Array | undefined>;\n readonly commitResource: (value: PropertyValue, signal: AbortSignal) => Promise<void>;\n readonly openProject: (id: string) => void;\n readonly programSources: ProgramSources | undefined;\n readonly programTarget: ProgramTarget;\n readonly packagePaths: readonly string[];\n readonly snapshot: FusedPresentationProps[string] | undefined;\n}\n\nfunction PropertyField(props: IPropertyProps) {\n const value = props.value;\n const descriptor = props.descriptor;\n const [draft, setDraft] = useState(typeof value === 'object' ? '' : String(value ?? ''));\n useEffect(() => setDraft(typeof value === 'object' ? '' : String(value ?? '')), [value]);\n const commit = () => {\n if (props.disabled || draft === String(value ?? '')) return;\n if (descriptor.type === 'integer' || descriptor.type === 'number') {\n const number = Number(draft);\n if (\n draft.trim() === '' ||\n !Number.isFinite(number) ||\n (descriptor.type === 'integer' && !Number.isInteger(number))\n ) {\n props.onError(\n new Error(`${props.name} 需要有效的${descriptor.type === 'integer' ? '整数' : '数值'}`),\n );\n return;\n }\n props.set(number);\n } else props.set(draft);\n };\n return (\n <div className=\"mica-wb-property\">\n <label title={descriptor.description}>{descriptor.title ?? props.name}</label>\n <div className=\"mica-wb-property-control\">\n {['program', 'image', 'binary', 'firmware'].includes(descriptor.type) ? (\n <ResourceField\n name={props.name}\n descriptor={descriptor}\n value={value}\n target={props.programTarget}\n sources={props.programSources}\n packagePaths={props.packagePaths}\n snapshot={props.snapshot}\n disabled={props.disabled}\n overridden={props.overridden}\n assets={props.assets}\n validate={props.validate}\n commit={props.commitResource}\n reset={props.reset}\n set={props.set}\n onOpenProject={props.openProject}\n onError={props.onError}\n />\n ) : descriptor.type === 'boolean' ? (\n <input\n type=\"checkbox\"\n aria-label={descriptor.title ?? props.name}\n checked={value === true}\n disabled={props.disabled}\n onChange={(event) => props.set(event.target.checked)}\n />\n ) : descriptor.type === 'enum' ? (\n <select\n aria-label={descriptor.title ?? props.name}\n value={String(value ?? '')}\n disabled={props.disabled}\n onChange={(event) => props.set(event.target.value)}\n >\n {value === undefined && <option value=\"\">未设置</option>}\n {descriptor.options?.map((option) => (\n <option key={option.value} value={option.value}>\n {option.label}\n </option>\n ))}\n </select>\n ) : (\n <input\n aria-label={descriptor.title ?? props.name}\n type={\n descriptor.type === 'color'\n ? 'color'\n : descriptor.type === 'number' || descriptor.type === 'integer'\n ? 'number'\n : 'text'\n }\n value={draft}\n min={descriptor.min}\n max={descriptor.max}\n step={descriptor.step ?? (descriptor.type === 'integer' ? 1 : 'any')}\n disabled={props.disabled}\n onChange={(event) => setDraft(event.target.value)}\n onBlur={commit}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault();\n commit();\n }\n }}\n />\n )}\n {props.overridden &&\n !['program', 'image', 'binary', 'firmware'].includes(descriptor.type) && (\n <button\n title=\"恢复默认值\"\n aria-label={`恢复 ${props.name} 的默认值`}\n disabled={props.disabled}\n onClick={props.reset}\n >\n <Icon name=\"discard\" />\n </button>\n )}\n </div>\n </div>\n );\n}\n\n/** Everything a selection can describe when it is not a device instance. */\nexport type IInspectorAnnotation =\n | {\n readonly kind: 'reference';\n readonly reference: VoltageReference;\n readonly endpoint: string;\n }\n | { readonly kind: 'label'; readonly label: NetLabel; readonly endpoint: string }\n | {\n readonly kind: 'wire';\n readonly wire: ConnectionWire;\n readonly from: string;\n readonly to: string;\n }\n | { readonly kind: 'node'; readonly node: ConnectionNode };\n\n/** Text or number cell that commits on blur and Enter, restoring `Escape`. */\nfunction CommitInput(props: {\n readonly label: string;\n readonly value: string;\n readonly numeric: boolean;\n readonly placeholder?: string;\n readonly disabled: boolean;\n readonly commit: (value: string) => void;\n}) {\n const [draft, setDraft] = useState(props.value);\n useEffect(() => setDraft(props.value), [props.value]);\n const commit = () => {\n if (props.disabled || draft === props.value) return;\n props.commit(draft);\n };\n return (\n <input\n aria-label={props.label}\n type={props.numeric ? 'number' : 'text'}\n value={draft}\n placeholder={props.placeholder}\n disabled={props.disabled}\n onChange={(event) => setDraft(event.target.value)}\n onBlur={commit}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n event.preventDefault();\n commit();\n } else if (event.key === 'Escape') {\n event.preventDefault();\n setDraft(props.value);\n }\n }}\n />\n );\n}\n\nfunction AnnotationField(props: { readonly label: string; readonly children: React.ReactNode }) {\n return (\n <div className=\"mica-wb-property\">\n <label>{props.label}</label>\n <div className=\"mica-wb-property-control\">{props.children}</div>\n </div>\n );\n}\n\nconst REFERENCE_TITLES: Readonly<Record<'power' | 'ground' | 'constraint', string>> = {\n power: '电源端',\n ground: '接地端',\n constraint: '电压参考',\n};\n\nfunction AnnotationFields(props: {\n readonly annotation: IInspectorAnnotation;\n readonly disabled: boolean;\n readonly onRenameLabel: (labelId: string, name: string) => void;\n readonly onSetVoltage: (referenceId: string, voltage: number) => void;\n readonly onSetReferenceName: (referenceId: string, name: string | undefined) => void;\n readonly onSetRotation: (referenceId: string, rotation: number) => void;\n readonly onError: (error: unknown) => void;\n}) {\n const annotation = props.annotation;\n if (annotation.kind === 'node')\n return (\n <dl className=\"mica-wb-identity\">\n <dt>对象</dt>\n <dd>连接节点</dd>\n <dt>类型</dt>\n <dd>{annotation.node.kind === 'junction' ? '分支点' : '自由端点'}</dd>\n <dt>坐标</dt>\n <dd>{`${String(annotation.node.x)}, ${String(annotation.node.y)} mm`}</dd>\n </dl>\n );\n if (annotation.kind === 'wire')\n return (\n <dl className=\"mica-wb-identity\">\n <dt>对象</dt>\n <dd>导线</dd>\n <dt>起点</dt>\n <dd>{annotation.from}</dd>\n <dt>终点</dt>\n <dd>{annotation.to}</dd>\n <dt>折点</dt>\n <dd>{String(annotation.wire.bends.length)}</dd>\n </dl>\n );\n if (annotation.kind === 'label')\n return (\n <>\n <dl className=\"mica-wb-identity\">\n <dt>对象</dt>\n <dd>网标</dd>\n <dt>连接端</dt>\n <dd>{annotation.endpoint}</dd>\n </dl>\n <AnnotationField label=\"网名\">\n <CommitInput\n label=\"网名\"\n numeric={false}\n value={annotation.label.name}\n disabled={props.disabled}\n commit={(draft) => {\n const name = draft.trim();\n if (name.length === 0) {\n props.onError(new Error('网名不能为空'));\n return;\n }\n props.onRenameLabel(annotation.label.id, name);\n }}\n />\n </AnnotationField>\n </>\n );\n const reference = annotation.reference;\n const ground = reference.symbol === 'ground';\n return (\n <>\n <dl className=\"mica-wb-identity\">\n <dt>对象</dt>\n <dd>{REFERENCE_TITLES[reference.symbol ?? 'constraint']}</dd>\n <dt>连接端</dt>\n <dd>{annotation.endpoint}</dd>\n {ground ? (\n <>\n <dt>电压</dt>\n <dd>0 V</dd>\n </>\n ) : undefined}\n </dl>\n {reference.symbol === undefined ? undefined : (\n <AnnotationField label=\"角度(°)\">\n <CommitInput\n label=\"角度\"\n numeric\n value={String(reference.rotation ?? 0)}\n disabled={props.disabled}\n commit={(draft) => {\n const rotation = Number(draft);\n if (draft.trim() === '' || !Number.isFinite(rotation)) {\n props.onError(new Error('角度需要有效数值'));\n return;\n }\n props.onSetRotation(reference.id, rotation);\n }}\n />\n </AnnotationField>\n )}\n {ground ? undefined : (\n <AnnotationField label=\"电压(V)\">\n <CommitInput\n label=\"电压\"\n numeric\n value={String(reference.voltage)}\n disabled={props.disabled}\n commit={(draft) => {\n const voltage = Number(draft);\n if (draft.trim() === '' || !Number.isFinite(voltage)) {\n props.onError(new Error('电压需要有效数值'));\n return;\n }\n props.onSetVoltage(reference.id, voltage);\n }}\n />\n </AnnotationField>\n )}\n {reference.symbol === 'power' ? (\n <AnnotationField label=\"网名\">\n <CommitInput\n label=\"网名\"\n numeric={false}\n value={reference.label?.name ?? ''}\n placeholder=\"未命名\"\n disabled={props.disabled}\n commit={(draft) => {\n const name = draft.trim();\n props.onSetReferenceName(reference.id, name.length === 0 ? undefined : name);\n }}\n />\n </AnnotationField>\n ) : undefined}\n </>\n );\n}\n\nexport function InspectorView(props: {\n readonly instance: FusedInstance | undefined;\n readonly manifest: UnifiedDeviceManifest | undefined;\n /** Selected terminal, net label, wire or node when no device instance is selected. */\n readonly annotation?: IInspectorAnnotation | undefined;\n readonly selectionCount: number;\n readonly disabled: boolean;\n readonly assets?: IAssetProvider | undefined;\n readonly programs?: ProgramSources | undefined;\n readonly packagePaths?: readonly string[];\n readonly snapshots?: FusedPresentationProps | undefined;\n readonly onSet: (key: string, value: PropertyValue) => void;\n readonly onReset: (key: string) => void;\n readonly onRenameLabel: (labelId: string, name: string) => void;\n readonly onSetVoltage: (referenceId: string, voltage: number) => void;\n readonly onSetReferenceName: (referenceId: string, name: string | undefined) => void;\n readonly onSetRotation: (referenceId: string, rotation: number) => void;\n readonly onValidate: (\n key: string,\n value: PropertyValue,\n signal: AbortSignal,\n ) => Promise<Uint8Array | undefined>;\n readonly onCommit: (key: string, value: PropertyValue, signal: AbortSignal) => Promise<void>;\n readonly onOpenProject: (id: string) => void;\n readonly onError: (error: unknown) => void;\n readonly actions?: React.ReactNode;\n readonly hideHeader?: boolean;\n readonly fill?: boolean;\n readonly collapsed?: boolean;\n readonly height: number | undefined;\n readonly onToggle?: (collapsed: boolean) => void;\n}) {\n const header = (\n <summary\n className=\"mica-wb-panel-title\"\n style={props.hideHeader ? { display: 'none' } : undefined}\n >\n <span className=\"mica-wb-panel-caption\">\n <Icon name={props.collapsed ? 'chevron-right' : 'chevron-down'} />\n 属性\n </span>\n <span\n className=\"mica-wb-panel-actions\"\n onClick={(event) => {\n event.preventDefault();\n event.stopPropagation();\n }}\n >\n {props.actions}\n </span>\n </summary>\n );\n const toggled = (event: React.SyntheticEvent<HTMLDetailsElement>) => {\n if (!props.hideHeader && event.currentTarget.open === props.collapsed)\n props.onToggle?.(!event.currentTarget.open);\n };\n if (props.instance === undefined || props.manifest === undefined)\n return (\n <section\n className={`mica-wb-inspector${props.fill && (props.hideHeader || !props.collapsed) ? ' is-fill' : ''}`}\n aria-label=\"器件属性\"\n data-view-id=\"mica.properties\"\n >\n <details open={props.hideHeader || !props.collapsed} onToggle={toggled}>\n {header}\n {props.annotation === undefined ? (\n <p className=\"mica-wb-empty\">\n {props.selectionCount > 1\n ? `已选择 ${props.selectionCount} 个对象`\n : '选择器件以查看其属性'}\n </p>\n ) : (\n <div\n className=\"mica-wb-property-fields\"\n style={{ height: props.fill ? undefined : props.height }}\n >\n <AnnotationFields\n annotation={props.annotation}\n disabled={props.disabled}\n onRenameLabel={props.onRenameLabel}\n onSetVoltage={props.onSetVoltage}\n onSetReferenceName={props.onSetReferenceName}\n onSetRotation={props.onSetRotation}\n onError={props.onError}\n />\n </div>\n )}\n </details>\n </section>\n );\n const properties = Object.entries(props.manifest.properties ?? {}).sort(\n ([a, x], [b, y]) => (x.order ?? 0) - (y.order ?? 0) || a.localeCompare(b),\n );\n return (\n <section\n className={`mica-wb-inspector${props.fill && (props.hideHeader || !props.collapsed) ? ' is-fill' : ''}`}\n aria-label=\"器件属性\"\n data-view-id=\"mica.properties\"\n >\n <details open={props.hideHeader || !props.collapsed} onToggle={toggled}>\n {header}\n <div\n className=\"mica-wb-property-fields\"\n style={{ height: props.fill ? undefined : props.height }}\n >\n <dl className=\"mica-wb-identity\">\n <dt>位号</dt>\n <dd>{props.instance.designator ?? '—'}</dd>\n <dt>器件</dt>\n <dd>{props.manifest.displayName}</dd>\n </dl>\n {properties.map(([name, descriptor]) => (\n <PropertyField\n key={`${props.instance?.id}:${name}`}\n name={name}\n descriptor={descriptor}\n programSources={props.programs}\n programTarget={{\n deviceId: props.instance!.device,\n property: name,\n loader: descriptor.type === 'program' ? descriptor.loader! : 'memory',\n }}\n packagePaths={props.packagePaths ?? []}\n snapshot={props.snapshots?.[name]}\n value={\n Object.hasOwn(props.instance?.properties ?? {}, name)\n ? props.instance?.properties?.[name]\n : descriptor.default\n }\n overridden={Object.hasOwn(props.instance?.properties ?? {}, name)}\n disabled={props.disabled}\n set={(value) => props.onSet(name, value)}\n reset={() => props.onReset(name)}\n onError={props.onError}\n assets={props.assets}\n validate={(value, signal) => props.onValidate(name, value, signal)}\n commitResource={(value, signal) => props.onCommit(name, value, signal)}\n openProject={props.onOpenProject}\n />\n ))}\n </div>\n </details>\n </section>\n );\n}\n","import type { IWorkbenchDiagnostic } from '../types';\n\nexport function ProblemsView(props: {\n readonly diagnostics: readonly IWorkbenchDiagnostic[];\n readonly onReveal: (id: string) => void;\n}) {\n return (\n <section className=\"mica-wb-problems\" aria-label=\"问题\">\n {props.diagnostics.length === 0 && <p className=\"mica-wb-empty\">没有发现问题</p>}\n {props.diagnostics.map((diagnostic, index) => (\n <button\n key={`${diagnostic.code}:${index}`}\n className={`mica-wb-diagnostic is-${diagnostic.severity}`}\n onClick={() => {\n if (diagnostic.instanceId !== undefined) props.onReveal(diagnostic.instanceId);\n }}\n >\n <strong>{diagnostic.code}</strong>\n <span>{diagnostic.message}</span>\n </button>\n ))}\n </section>\n );\n}\n","import { useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport type {\n FloatingBounds,\n FusedInstance,\n InstanceViewLayout,\n UnifiedDeviceManifest,\n} from '@mica-js/document/fused';\nimport type { IHtmlViewHandle } from '../html';\nimport { isHtmlViewError } from '../html';\nimport type { IWorkbenchUI } from './workbench-part';\nimport { Icon } from './activity-bar-part';\n\nfunction ViewSlot({\n handle,\n height,\n visible,\n}: {\n readonly handle: IHtmlViewHandle | undefined;\n readonly height?: number;\n readonly visible: boolean;\n}) {\n const slot = useRef<HTMLDivElement>(null);\n useLayoutEffect(() => {\n if (handle === undefined) return;\n handle.attach(slot.current);\n handle.setVisible(visible);\n return () => handle.attach(null);\n }, [handle, visible]);\n return (\n <div ref={slot} className=\"mica-wb-html-slot\" style={{ height }}>\n {handle?.state === 'failed' && <p role=\"alert\">{handle.failure?.message}</p>}\n {(handle === undefined || handle.state === 'loading') && <p role=\"status\">正在加载视图…</p>}\n </div>\n );\n}\n\nexport function PanelResizer(props: {\n readonly height: number;\n readonly onPreview: (height: number | undefined) => void;\n readonly onCommit: (height: number) => void;\n}) {\n const drag = useRef<{ readonly y: number; readonly height: number } | undefined>(undefined);\n return (\n <div\n className=\"mica-wb-panel-resizer\"\n role=\"separator\"\n aria-label=\"调整视图大小\"\n aria-orientation=\"horizontal\"\n tabIndex={0}\n onKeyDown={(event) => {\n if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return;\n event.preventDefault();\n props.onCommit(Math.max(64, props.height + (event.key === 'ArrowDown' ? 20 : -20)));\n }}\n onPointerDown={(event) => {\n drag.current = { y: event.clientY, height: props.height };\n event.currentTarget.setPointerCapture(event.pointerId);\n }}\n onPointerMove={(event) => {\n const value = drag.current;\n if (value === undefined) return;\n props.onPreview(Math.max(64, value.height + event.clientY - value.y));\n }}\n onPointerUp={(event) => {\n const value = drag.current;\n drag.current = undefined;\n if (value !== undefined)\n props.onCommit(Math.max(64, value.height + event.clientY - value.y));\n props.onPreview(undefined);\n if (event.currentTarget.hasPointerCapture(event.pointerId))\n event.currentTarget.releasePointerCapture(event.pointerId);\n }}\n onLostPointerCapture={() => {\n drag.current = undefined;\n props.onPreview(undefined);\n }}\n />\n );\n}\n\nexport function HtmlViewsPart(props: {\n readonly ui: IWorkbenchUI;\n readonly instance: FusedInstance;\n readonly manifest: UnifiedDeviceManifest;\n readonly layout: InstanceViewLayout;\n}) {\n const { ui, instance, manifest, layout } = props;\n const [draft, setDraft] = useState<Readonly<Record<string, number | undefined>>>({});\n const ordering = useRef<string | undefined>(undefined);\n const running = ui.workbench.getState().mode === 'run' && !ui.workbench.getState().busy;\n const run = (task: Promise<unknown>) => void task.catch(ui.error);\n const lastExpanded = layout.views\n .filter(\n (view) =>\n view.location === 'sidebar' &&\n !view.collapsed &&\n manifest.view?.[view.viewId] !== undefined,\n )\n .at(-1)?.viewId;\n useEffect(() => {\n if (!running) return;\n for (const view of layout.views) {\n if (view.location !== 'sidebar') continue;\n const handle = ui.htmlViews.get(instance.id, view.viewId);\n if (view.collapsed) handle?.setVisible(false);\n else if (handle === undefined)\n void ui.htmlViews\n .open({ instanceId: instance.id, viewId: view.viewId, location: 'sidebar' })\n .catch((reason: unknown) => {\n if (ui.context.signal.aborted) return;\n const selection = ui.workbench.getSelection();\n if (\n isHtmlViewError(reason) &&\n reason.code === 'view/unavailable-mode' &&\n (ui.workbench.getState().mode !== 'run' ||\n selection.length !== 1 ||\n selection[0]?.id !== instance.id)\n )\n return;\n ui.error(reason);\n });\n else handle.setVisible(true);\n }\n }, [running, instance.id, layout, ui]);\n const change = (viewId: string, patch: Partial<InstanceViewLayout['views'][number]>) =>\n run(\n ui.changeViewLayout(instance.id, {\n ...layout,\n views: layout.views.map((view) => (view.viewId === viewId ? { ...view, ...patch } : view)),\n }),\n );\n return (\n <div className=\"mica-wb-html-views\">\n {layout.views\n .filter((view) => view.location === 'sidebar')\n .map((view) => {\n const definition = manifest.view?.[view.viewId];\n if (definition === undefined) return null;\n const handle = ui.htmlViews.get(instance.id, view.viewId);\n return (\n <section\n className={`mica-wb-html-view${view.viewId === lastExpanded ? ' is-fill' : ''}`}\n key={view.viewId}\n aria-label={definition.title}\n >\n <div\n className=\"mica-wb-panel-title\"\n draggable\n onDragStart={(event) => {\n ordering.current = view.viewId;\n event.dataTransfer.setData('text/plain', view.viewId);\n event.dataTransfer.effectAllowed = 'move';\n }}\n onDragOver={(event) => {\n if (ordering.current !== undefined) event.preventDefault();\n }}\n onDrop={(event) => {\n event.preventDefault();\n const from = ordering.current;\n ordering.current = undefined;\n if (from === undefined || from === view.viewId) return;\n const ordered = [...layout.views];\n const source = ordered.findIndex((entry) => entry.viewId === from);\n const target = ordered.findIndex((entry) => entry.viewId === view.viewId);\n const [item] = ordered.splice(source, 1);\n if (item !== undefined) {\n ordered.splice(target, 0, item);\n run(ui.changeViewLayout(instance.id, { ...layout, views: ordered }));\n }\n }}\n onDragEnd={() => {\n ordering.current = undefined;\n }}\n >\n <button\n aria-expanded={!view.collapsed}\n onClick={() => change(view.viewId, { collapsed: !view.collapsed })}\n >\n <Icon name={view.collapsed ? 'chevron-right' : 'chevron-down'} />\n {definition.title}\n </button>\n <span className=\"mica-wb-panel-actions\">\n <button\n title=\"上移视图\"\n aria-label={`上移${definition.title}`}\n onClick={() => {\n const ordered = [...layout.views];\n const index = ordered.findIndex((entry) => entry.viewId === view.viewId);\n if (index <= 0) return;\n const previous = ordered[index - 1];\n if (previous === undefined) return;\n ordered[index - 1] = view;\n ordered[index] = previous;\n run(ui.changeViewLayout(instance.id, { ...layout, views: ordered }));\n }}\n >\n <Icon name=\"arrow-up\" />\n </button>\n <button\n title=\"浮动视图\"\n aria-label={`将${definition.title}设为浮动`}\n onClick={() =>\n run(\n ui.workbench.executeCommand('view.setLocation', {\n instanceId: instance.id,\n viewId: view.viewId,\n location: 'floating',\n }),\n )\n }\n >\n <Icon name=\"link-external\" />\n </button>\n </span>\n </div>\n {!view.collapsed &&\n (running ? (\n <ViewSlot handle={handle} height={draft[view.viewId] ?? view.height} visible />\n ) : (\n <p className=\"mica-wb-empty\">切换到运行模式后可打开此视图。</p>\n ))}\n {!view.collapsed && (\n <PanelResizer\n height={view.height}\n onPreview={(height) =>\n setDraft((current) => ({ ...current, [view.viewId]: height }))\n }\n onCommit={(height) => change(view.viewId, { height })}\n />\n )}\n </section>\n );\n })}\n </div>\n );\n}\n\nexport function FloatingViewsPart({ ui }: { readonly ui: IWorkbenchUI }) {\n return (\n <div className=\"mica-wb-floating-layer\">\n {ui.htmlViews.views\n .filter((view) => view.location === 'floating' && view.state !== 'closed')\n .map((view) => (\n <FloatingView key={view.key} ui={ui} handle={view} />\n ))}\n </div>\n );\n}\n\nconst floatingResizeHandles = [\n ['n', '上'],\n ['ne', '右上'],\n ['e', '右'],\n ['se', '右下'],\n ['s', '下'],\n ['sw', '左下'],\n ['w', '左'],\n ['nw', '左上'],\n] as const;\ntype FloatingResizeEdge = (typeof floatingResizeHandles)[number][0];\n\nfunction FloatingView({\n ui,\n handle,\n}: {\n readonly ui: IWorkbenchUI;\n readonly handle: IHtmlViewHandle;\n}) {\n const pane = useRef<HTMLElement>(null);\n const [preview, setPreview] = useState<FloatingBounds>();\n const [area, setArea] = useState({ width: 640, height: 480 });\n const drag = useRef<\n | {\n readonly kind: 'move' | FloatingResizeEdge;\n readonly x: number;\n readonly y: number;\n readonly bounds: FloatingBounds;\n next: FloatingBounds;\n }\n | undefined\n >(undefined);\n const instance = ui.workbench\n .getDocument()\n .instances.find((item) => item.id === handle.instanceId);\n const layout = ui.viewLayout(handle.instanceId);\n const saved = layout.views.find((view) => view.viewId === handle.viewId)?.floatingBounds;\n const requested = preview ??\n saved ?? { x: (area.width - 360) / 2, y: 80, width: 360, height: 280 };\n const constrain = (value: FloatingBounds): FloatingBounds => {\n const width = Math.max(180, Math.min(value.width, area.width));\n const height = Math.max(100, Math.min(value.height, area.height));\n return {\n width,\n height,\n x: Math.max(0, Math.min(value.x, area.width - width)),\n y: Math.max(0, Math.min(value.y, area.height - height)),\n };\n };\n const resize = (original: FloatingBounds, edge: FloatingResizeEdge, dx: number, dy: number) => {\n const next = { ...original };\n if (edge.includes('e'))\n next.width = Math.max(180, Math.min(original.width + dx, area.width - original.x));\n if (edge.includes('s'))\n next.height = Math.max(100, Math.min(original.height + dy, area.height - original.y));\n if (edge.includes('w')) {\n const right = original.x + original.width;\n next.x = Math.max(0, Math.min(original.x + dx, right - 180));\n next.width = right - next.x;\n }\n if (edge.includes('n')) {\n const bottom = original.y + original.height;\n next.y = Math.max(0, Math.min(original.y + dy, bottom - 100));\n next.height = bottom - next.y;\n }\n return next;\n };\n const bounds = constrain(requested);\n const cancel = () => {\n drag.current = undefined;\n setPreview(undefined);\n };\n useEffect(() => {\n window.addEventListener('blur', cancel);\n return () => window.removeEventListener('blur', cancel);\n }, []);\n useLayoutEffect(() => {\n const host = pane.current?.parentElement;\n if (host === null || host === undefined) return;\n const observer = new ResizeObserver(([entry]) => {\n if (entry !== undefined)\n setArea({ width: entry.contentRect.width, height: entry.contentRect.height });\n });\n observer.observe(host);\n return () => observer.disconnect();\n }, []);\n useLayoutEffect(() => ui.htmlViews.refresh(), [bounds.x, bounds.y, bounds.width, bounds.height]);\n const commit = (value: FloatingBounds) =>\n void ui\n .changeViewLayout(handle.instanceId, {\n ...layout,\n views: layout.views.map((view) =>\n view.viewId === handle.viewId ? { ...view, floatingBounds: constrain(value) } : view,\n ),\n })\n .catch(ui.error);\n const start = (event: React.PointerEvent<HTMLElement>, kind: 'move' | FloatingResizeEdge) => {\n if (event.button !== 0 || drag.current !== undefined) return;\n if (event.target instanceof Element && event.target.closest('button') !== null) return;\n event.preventDefault();\n drag.current = { kind, x: event.clientX, y: event.clientY, bounds, next: bounds };\n event.currentTarget.setPointerCapture(event.pointerId);\n };\n const move = (event: React.PointerEvent<HTMLElement>) => {\n const active = drag.current;\n if (active === undefined) return;\n active.next =\n active.kind === 'move'\n ? {\n ...active.bounds,\n x: active.bounds.x + event.clientX - active.x,\n y: active.bounds.y + event.clientY - active.y,\n }\n : resize(active.bounds, active.kind, event.clientX - active.x, event.clientY - active.y);\n setPreview(active.next);\n };\n const end = (event: React.PointerEvent<HTMLElement>) => {\n const active = drag.current;\n if (active !== undefined) move(event);\n drag.current = undefined;\n if (active !== undefined) commit(active.next);\n setPreview(undefined);\n if (event.currentTarget.hasPointerCapture(event.pointerId))\n event.currentTarget.releasePointerCapture(event.pointerId);\n };\n return (\n <section\n ref={pane}\n className=\"mica-wb-floating-view\"\n role=\"dialog\"\n aria-label={`${instance?.designator ?? handle.instanceId} · ${handle.title}`}\n style={{ left: bounds.x, top: bounds.y, width: bounds.width, height: bounds.height }}\n >\n <div\n className=\"mica-wb-panel-title\"\n onPointerDown={(event) => start(event, 'move')}\n onPointerMove={move}\n onPointerUp={end}\n onPointerCancel={cancel}\n onLostPointerCapture={cancel}\n >\n <span>\n {instance?.designator ?? handle.instanceId} · {handle.title}\n </span>\n <span className=\"mica-wb-panel-actions\">\n <button\n title=\"停靠视图\"\n aria-label={`停靠${handle.title}`}\n onClick={() =>\n void ui.workbench\n .executeCommand('view.setLocation', {\n instanceId: handle.instanceId,\n viewId: handle.viewId,\n location: 'sidebar',\n })\n .catch(ui.error)\n }\n >\n <Icon name=\"layout-sidebar-right\" />\n </button>\n <button\n title=\"关闭视图\"\n aria-label={`关闭${handle.title}`}\n onClick={() => handle.close()}\n >\n <Icon name=\"close\" />\n </button>\n </span>\n </div>\n <ViewSlot handle={handle} visible />\n {floatingResizeHandles.map(([edge, label]) => (\n <div\n key={edge}\n className={`mica-wb-floating-resizer mica-wb-floating-resizer-${edge}`}\n role=\"separator\"\n aria-label={`调整浮动视图大小(${label})`}\n aria-orientation={edge === 'n' || edge === 's' ? 'horizontal' : 'vertical'}\n aria-valuetext={`${Math.round(bounds.width)} × ${Math.round(bounds.height)}`}\n tabIndex={edge === 'se' ? 0 : -1}\n onKeyDown={(event) => {\n const step = event.shiftKey ? 40 : 10;\n const dx = event.key === 'ArrowLeft' ? -step : event.key === 'ArrowRight' ? step : 0;\n const dy = event.key === 'ArrowUp' ? -step : event.key === 'ArrowDown' ? step : 0;\n if (dx === 0 && dy === 0) return;\n event.preventDefault();\n commit(resize(bounds, edge, dx, dy));\n }}\n onPointerDown={(event) => start(event, edge)}\n onPointerMove={move}\n onPointerUp={end}\n onPointerCancel={cancel}\n onLostPointerCapture={cancel}\n />\n ))}\n </section>\n );\n}\n","import { useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport type { Event } from '@mica-js/core/lifecycle';\nimport type {\n DeviceLock,\n Endpoint,\n InstanceViewLayout,\n PropertyValue,\n Point2D,\n} from '@mica-js/document/fused';\nimport type { IHtmlViewHost } from '../html';\nimport type {\n IWorkbench,\n IWorkbenchDiagnostic,\n IWorkbenchExtensionContext,\n IWorkbenchOptions,\n} from '../types';\nimport type { ICanvasDevice } from '../canvas/geometry';\nimport type { ContributionRegistry } from '../contributions/registry';\nimport { ActivityBarPart } from './activity-bar-part';\nimport { CanvasPart, type ICanvasHandle, type IViewInput } from './canvas-part';\nimport { SidebarPart } from './sidebar-part';\nimport { ToolbarPart } from './toolbar-part';\nimport { InstancesView } from '../views/instances';\nimport { InspectorView, type IInspectorAnnotation } from '../views/inspector';\nimport { ProblemsView } from '../views/problems';\nimport { FloatingViewsPart, HtmlViewsPart, PanelResizer } from './html-views-part';\nimport { Icon } from './activity-bar-part';\nimport { readCanvasTheme, resolveTheme, themeStyle, type IWorkbenchTheme } from '../theme';\nimport type { FusedPresentationProps } from '../runtime/protocol';\n\nexport interface IWorkbenchUI {\n readonly workbench: IWorkbench;\n readonly options: IWorkbenchOptions;\n readonly context: IWorkbenchExtensionContext;\n readonly theme: IWorkbenchTheme;\n readonly htmlViews: IHtmlViewHost;\n readonly viewLayout: (instanceId: string) => InstanceViewLayout;\n readonly changeViewLayout: (\n instanceId: string,\n layout: InstanceViewLayout | undefined,\n ) => Promise<void>;\n readonly contributions: ContributionRegistry;\n readonly onDidUpdate: Event<void>;\n readonly devices: ReadonlyMap<string, ICanvasDevice>;\n readonly images: ReadonlyMap<string, CanvasImageSource>;\n readonly overlays: ReadonlyMap<string, ImageBitmap>;\n readonly diagnostics: readonly IWorkbenchDiagnostic[];\n readonly placement: DeviceLock | undefined;\n readonly placementRotation: number;\n readonly version: number;\n readonly setCanvas: (canvas: ICanvasHandle | undefined) => void;\n readonly report: (diagnostic: IWorkbenchDiagnostic) => void;\n readonly error: (error: unknown) => void;\n readonly input: (instanceId: string, event: IViewInput) => void;\n readonly labelName: string;\n readonly setLabelName: (name: string) => void;\n readonly connect: (\n from: Endpoint | Point2D,\n to: Endpoint | Point2D,\n bends: readonly Point2D[],\n ) => Promise<void>;\n readonly endpoint: (endpoint: Endpoint | Point2D) => Promise<void>;\n readonly cancel: () => void;\n readonly focus: (focused: boolean) => void;\n readonly viewport: () => void;\n readonly reveal: (instanceId: string) => void;\n readonly validateResource: (\n instanceId: string,\n key: string,\n value: PropertyValue,\n signal: AbortSignal,\n ) => Promise<Uint8Array | undefined>;\n readonly commitResource: (\n instanceId: string,\n key: string,\n expected: PropertyValue | undefined,\n value: PropertyValue,\n signal: AbortSignal,\n ) => Promise<void>;\n readonly openProject: (projectId: string) => void;\n readonly programPackagePaths: (deviceId: string) => readonly string[];\n readonly programSnapshot: (instanceId: string) => FusedPresentationProps | undefined;\n}\n\nexport function WorkbenchPart({ ui }: { readonly ui: IWorkbenchUI }) {\n const frame = useSyncExternalStore(\n (callback) => {\n const subscription = ui.onDidUpdate(callback);\n return () => subscription.dispose();\n },\n () => ui.version,\n );\n const [systemDark, setSystemDark] = useState(\n () => matchMedia('(prefers-color-scheme: dark)').matches,\n );\n const root = useRef<HTMLDivElement>(null);\n const [propertyHeight, setPropertyHeight] = useState<number>();\n const [emptyPropertiesCollapsed, setEmptyPropertiesCollapsed] = useState(false);\n useEffect(() => {\n const media = matchMedia('(prefers-color-scheme: dark)');\n const changed = () => setSystemDark(media.matches);\n media.addEventListener('change', changed);\n return () => media.removeEventListener('change', changed);\n }, []);\n const state = ui.workbench.getState();\n const document = ui.workbench.getDocument();\n const selection = ui.workbench.getSelection();\n const active = ui.contributions.containers.find(\n (container) => container.id === state.activeContainer && ui.contributions.visible(container),\n );\n const single =\n selection.length === 1 && selection[0]?.kind === 'instance'\n ? document.instances.find((instance) => instance.id === selection[0]?.id)\n : undefined;\n const manifest = single === undefined ? undefined : ui.devices.get(single.device)?.manifest;\n const describeEndpoint = (endpoint: Endpoint): string => {\n if (endpoint.kind === 'node') return '连接节点';\n const instance = document.instances.find((value) => value.id === endpoint.instance);\n const label =\n instance === undefined\n ? undefined\n : (ui.devices.get(instance.device)?.manifest.pins?.[endpoint.pin]?.label ?? endpoint.pin);\n return `${instance?.designator ?? endpoint.instance} · ${label ?? endpoint.pin}`;\n };\n const annotation: IInspectorAnnotation | undefined = (() => {\n const target = selection.length === 1 ? selection[0] : undefined;\n if (target === undefined || target.kind === 'instance') return undefined;\n if (target.kind === 'reference') {\n const reference = document.references.find((value) => value.id === target.id);\n return reference === undefined\n ? undefined\n : { kind: 'reference', reference, endpoint: describeEndpoint(reference.target) };\n }\n if (target.kind === 'label') {\n const label = document.labels.find((value) => value.id === target.id);\n return label === undefined\n ? undefined\n : { kind: 'label', label, endpoint: describeEndpoint(label.target) };\n }\n if (target.kind === 'wire') {\n const wire = document.wires.find((value) => value.id === target.id);\n return wire === undefined\n ? undefined\n : {\n kind: 'wire',\n wire,\n from: describeEndpoint(wire.from),\n to: describeEndpoint(wire.to),\n };\n }\n const node = document.nodes.find((value) => value.id === target.id);\n return node === undefined ? undefined : { kind: 'node', node };\n })();\n const layout =\n single === undefined || manifest === undefined ? undefined : ui.viewLayout(single.id);\n const run = (task: Promise<unknown>) => {\n void task.catch(ui.error);\n };\n const setProperty = (key: string, value: PropertyValue) => {\n if (single !== undefined)\n run(ui.workbench.executeCommand('device.setProperty', { instanceId: single.id, key, value }));\n };\n const propertyCollapsed = layout?.properties.collapsed ?? emptyPropertiesCollapsed;\n const toggleProperties = (collapsed: boolean) => {\n if (single === undefined || layout === undefined) setEmptyPropertiesCollapsed(collapsed);\n else\n run(\n ui.changeViewLayout(single.id, {\n ...layout,\n properties: { ...layout.properties, collapsed },\n }),\n );\n };\n const deviceViewIds = new Set<string>();\n const floating = new Map<\n string,\n { instanceId: string; viewId: string; title: string; icon: string | undefined }\n >();\n if (state.mode === 'run') {\n for (const view of layout?.views ?? []) {\n const definition = manifest?.view?.[view.viewId];\n if (single === undefined || definition === undefined) continue;\n const key = `${single.id}/${view.viewId}`;\n deviceViewIds.add(key);\n if (view.location === 'floating')\n floating.set(key, {\n instanceId: single.id,\n viewId: view.viewId,\n title: definition.title,\n icon: definition.icon,\n });\n }\n for (const handle of ui.htmlViews.views) {\n if (handle.location !== 'floating' || handle.state === 'closed') continue;\n deviceViewIds.add(`${handle.instanceId}/${handle.viewId}`);\n floating.set(`${handle.instanceId}/${handle.viewId}`, {\n instanceId: handle.instanceId,\n viewId: handle.viewId,\n title: handle.title,\n icon: undefined,\n });\n }\n }\n const multipleInfoViews =\n deviceViewIds.size > 0 ||\n ui.contributions.views.some(\n (view) => view.containerId === 'mica.properties' && ui.contributions.visible(view),\n );\n const propertyActions =\n single === undefined || layout === undefined ? undefined : (\n <button\n title=\"恢复视图布局\"\n aria-label=\"恢复视图布局\"\n onClick={() => run(ui.changeViewLayout(single.id, undefined))}\n >\n <Icon name=\"discard\" />\n </button>\n );\n const floatingActions = [...floating]\n .filter(([, view]) => ui.htmlViews.get(view.instanceId, view.viewId) === undefined)\n .map(([key, view]) => (\n <button\n key={key}\n title={view.title}\n aria-label={`${document.instances.find((instance) => instance.id === view.instanceId)?.designator ?? view.instanceId} ${view.title}`}\n disabled={state.busy}\n onClick={() =>\n run(\n ui.workbench.executeCommand('view.open', {\n instanceId: view.instanceId,\n viewId: view.viewId,\n }),\n )\n }\n >\n <Icon name={view.icon ?? 'link-external'} />\n </button>\n ));\n const theme = useMemo(() => resolveTheme(ui.theme, systemDark), [ui.theme, systemDark]);\n // Device HTML views mirror the *computed* colors, so a host `var(...)` token is already resolved\n // when the environment writes it into its author document.\n useLayoutEffect(() => {\n const element = root.current;\n if (element === null) return;\n ui.htmlViews.setTheme({\n appearance: theme.appearance,\n colors: readCanvasTheme(element),\n });\n }, [ui.htmlViews, theme]);\n return (\n <div\n ref={root}\n className={`mica-workbench mica-wb-${theme.appearance} ${active === undefined ? '' : 'mica-wb-sidebar-open'}`}\n style={{ ...themeStyle(theme), colorScheme: theme.appearance }}\n data-theme={theme.appearance}\n role=\"region\"\n aria-label=\"电路工作台\"\n lang=\"zh-CN\"\n aria-busy={state.busy}\n onKeyDown={(event) => {\n if (event.key === 'Escape' && (ui.placement !== undefined || state.tool !== 'select')) {\n event.preventDefault();\n ui.cancel();\n return;\n }\n const target = event.target;\n if (\n target instanceof HTMLElement &&\n (target.matches('input,textarea,select') || target.isContentEditable)\n )\n return;\n if (event.code === 'Space' && state.mode === 'edit' && !state.readOnly && !state.busy) {\n event.preventDefault();\n if (!event.repeat) run(ui.workbench.executeCommand('selection.rotate', { degrees: 90 }));\n return;\n }\n if (!(event.ctrlKey || event.metaKey)) return;\n if (event.key.toLowerCase() === 's') {\n event.preventDefault();\n run(ui.workbench.save());\n }\n if (event.key.toLowerCase() === 'z') {\n event.preventDefault();\n run(ui.workbench.executeCommand(event.shiftKey ? 'document.redo' : 'document.undo'));\n }\n if (event.key.toLowerCase() === 'y') {\n event.preventDefault();\n run(ui.workbench.executeCommand('document.redo'));\n }\n }}\n >\n <CanvasPart\n document={document}\n devices={ui.devices}\n images={ui.images}\n overlays={ui.overlays}\n state={state}\n selection={selection}\n placement={ui.placement}\n placementRotation={ui.placementRotation}\n labelName={ui.labelName}\n theme={theme}\n frame={frame}\n onReady={ui.setCanvas}\n onSelection={(targets) => ui.workbench.setSelection(targets)}\n onOpenProperties={() =>\n run(\n ui.workbench.executeCommand('workbench.openContainer', {\n id: 'mica.properties',\n focus: true,\n }),\n )\n }\n onPlace={async (device, position) => {\n await ui.workbench.executeCommand('device.add', {\n device,\n placement: { ...position, rotation: ui.placementRotation },\n });\n ui.cancel();\n }}\n onMove={async (instanceId, position) => {\n await ui.workbench.executeCommand('device.move', { instanceId, position });\n }}\n onMoveSegment={async (wireId, segment, delta) => {\n await ui.workbench.executeCommand('wire.moveSegment', { wireId, segment, delta });\n }}\n onMoveText={async (target, offset) => {\n await ui.workbench.executeCommand('text.move', { target, offset });\n }}\n onMoveReference={async (referenceId, position) => {\n await ui.workbench.executeCommand('reference.move', { referenceId, position });\n }}\n onMoveLabel={async (labelId, position) => {\n await ui.workbench.executeCommand('label.move', { labelId, position });\n }}\n onStartWire={async () => {\n await ui.workbench.executeCommand('canvas.setTool', { tool: 'wire' });\n }}\n onConnect={ui.connect}\n onEndpoint={ui.endpoint}\n onCancel={ui.cancel}\n onDelete={async () => {\n await ui.workbench.executeCommand('selection.delete');\n }}\n onInput={ui.input}\n onError={ui.error}\n onFocus={ui.focus}\n onViewport={ui.viewport}\n >\n <ToolbarPart\n state={state}\n registry={ui.contributions}\n context={ui.context}\n onError={ui.error}\n />\n {state.busy && (\n <div className=\"mica-wb-status\" role=\"status\">\n 正在准备…\n </div>\n )}\n {!state.busy && state.mode === 'edit' && state.readOnly && (\n <div className=\"mica-wb-status\" role=\"status\">\n 只读\n </div>\n )}\n {!state.busy && ui.placement !== undefined && (\n <div className=\"mica-wb-status\" role=\"status\">\n 单击放置 · 空格旋转 · Esc 取消\n </div>\n )}\n {!state.busy &&\n state.mode === 'edit' &&\n !state.readOnly &&\n ['power', 'ground', 'label'].includes(state.tool) && (\n <div className=\"mica-wb-status\" role=\"status\">\n {state.tool === 'label' && (\n <label>\n 网标{' '}\n <input\n aria-label=\"网标名称\"\n value={ui.labelName}\n onChange={(event) => ui.setLabelName(event.target.value)}\n />\n </label>\n )}\n 单击放置 · Esc 取消\n </div>\n )}\n {ui.diagnostics.some((diagnostic) => diagnostic.severity === 'error') && (\n <button\n className=\"mica-wb-problem-indicator\"\n onClick={() =>\n run(ui.workbench.executeCommand('workbench.openContainer', { id: 'mica.problems' }))\n }\n >\n {ui.diagnostics.filter((diagnostic) => diagnostic.severity === 'error').length} problems\n </button>\n )}\n </CanvasPart>\n {active !== undefined && (\n <SidebarPart\n properties={active.id === 'mica.properties'}\n singleView={\n active.id === 'mica.properties'\n ? !multipleInfoViews\n : ui.contributions.views.filter(\n (view) => view.containerId === active.id && ui.contributions.visible(view),\n ).length +\n (active.id === 'mica.instances' || active.id === 'mica.problems' ? 1 : 0) ===\n 1\n }\n title={\n active.id === 'mica.properties' ? (multipleInfoViews ? '信息' : '属性') : undefined\n }\n actions={\n active.id === 'mica.properties'\n ? multipleInfoViews\n ? floatingActions\n : propertyActions\n : undefined\n }\n container={active}\n views={ui.contributions.views.filter(\n (view) => view.containerId === active.id && ui.contributions.visible(view),\n )}\n context={ui.context}\n onClose={() => run(ui.workbench.executeCommand('workbench.closeContainer'))}\n report={ui.report}\n >\n {active.id === 'mica.instances' && (\n <InstancesView\n document={document}\n devices={ui.devices}\n selection={selection}\n onSelect={ui.reveal}\n />\n )}\n {active.id === 'mica.properties' && (\n <>\n <InspectorView\n hideHeader={!multipleInfoViews}\n fill={\n state.mode !== 'run' ||\n !layout?.views.some(\n (view) =>\n view.location === 'sidebar' &&\n !view.collapsed &&\n manifest?.view?.[view.viewId] !== undefined,\n )\n }\n instance={single}\n manifest={\n single === undefined ? undefined : ui.devices.get(single.device)?.manifest\n }\n annotation={annotation}\n onRenameLabel={(labelId, name) =>\n run(ui.workbench.executeCommand('label.setName', { labelId, name }))\n }\n onSetVoltage={(referenceId, voltage) =>\n run(ui.workbench.executeCommand('reference.setVoltage', { referenceId, voltage }))\n }\n onSetReferenceName={(referenceId, name) =>\n run(ui.workbench.executeCommand('reference.setName', { referenceId, name }))\n }\n onSetRotation={(referenceId, rotation) =>\n run(\n ui.workbench.executeCommand('reference.setRotation', { referenceId, rotation }),\n )\n }\n selectionCount={selection.length}\n disabled={state.readOnly || state.mode !== 'edit' || state.busy}\n assets={ui.options.assetProvider}\n programs={ui.options.programs}\n packagePaths={single === undefined ? [] : ui.programPackagePaths(single.device)}\n snapshots={single === undefined ? undefined : ui.programSnapshot(single.id)}\n onSet={setProperty}\n onReset={(key) => {\n if (single !== undefined)\n run(\n ui.workbench.executeCommand('device.removeProperty', {\n instanceId: single.id,\n key,\n }),\n );\n }}\n onValidate={async (key, value, signal) => {\n if (single === undefined) throw new Error('No device is selected');\n return ui.validateResource(single.id, key, value, signal);\n }}\n onCommit={async (key, value, signal) => {\n if (single === undefined) throw new Error('No device is selected');\n await ui.commitResource(single.id, key, single.properties?.[key], value, signal);\n }}\n onOpenProject={ui.openProject}\n onError={ui.error}\n collapsed={propertyCollapsed}\n height={\n multipleInfoViews ? (propertyHeight ?? layout?.properties.height) : undefined\n }\n onToggle={toggleProperties}\n actions={multipleInfoViews ? propertyActions : undefined}\n />\n {single !== undefined && manifest !== undefined && layout !== undefined && (\n <>\n {multipleInfoViews && !layout.properties.collapsed && (\n <PanelResizer\n height={layout.properties.height}\n onPreview={setPropertyHeight}\n onCommit={(height) =>\n run(\n ui.changeViewLayout(single.id, {\n ...layout,\n properties: { ...layout.properties, height },\n }),\n )\n }\n />\n )}\n {state.mode === 'run' && (\n <HtmlViewsPart ui={ui} instance={single} manifest={manifest} layout={layout} />\n )}\n </>\n )}\n </>\n )}\n {active.id === 'mica.problems' && (\n <ProblemsView diagnostics={ui.diagnostics} onReveal={ui.reveal} />\n )}\n </SidebarPart>\n )}\n <ActivityBarPart\n containers={ui.contributions.containers.filter((container) =>\n ui.contributions.visible(container),\n )}\n active={active?.id}\n problemCount={ui.diagnostics.length}\n onActivate={(id) => {\n if (id === state.activeContainer)\n run(ui.workbench.executeCommand('workbench.closeContainer'));\n else run(ui.workbench.executeCommand('workbench.openContainer', { id, focus: true }));\n }}\n />\n <FloatingViewsPart ui={ui} />\n </div>\n );\n}\n","import { createRoot } from 'react-dom/client';\nimport { flushSync } from 'react-dom';\nimport { DisposableStore, Emitter } from '@mica-js/core/lifecycle';\nimport { timePs } from '@mica-js/core';\nimport type {\n DeviceLock,\n Endpoint,\n FusedDocument,\n InstanceViewLayout,\n Point2D,\n} from '@mica-js/document/fused';\nimport { parseFusedDocument } from '@mica-js/document/fused';\nimport { openDevicePackage, resolveInstanceProperties } from '@mica-js/sdk/fused';\nimport { createContextKeyService } from './context';\nimport { FusedDocumentSession } from './document';\nimport {\n addLabel,\n addReference,\n addWire,\n rotateTargets,\n setLabelName,\n setReferenceLabelName,\n setReferenceRotation,\n setReferenceVoltage,\n setTextOffset,\n setInstanceProperty,\n} from './document/edits';\nimport {\n materializeAnchor,\n moveLabel,\n moveReference,\n moveWireSegment,\n routeDocumentWires,\n} from './wiring';\nimport { ContributionRegistry } from './contributions/registry';\nimport { findBodyOverlaps } from './canvas/geometry';\nimport { createHtmlViewHost, type IHtmlViewHost } from './html';\nimport { resolveViewLayout } from './views/layout';\nimport { normalizeTheme, type WorkbenchTheme } from './theme';\nimport { createFusedRuntime, type IFusedRuntime } from './runtime';\nimport type { IWorkbenchAccessProvider } from './providers';\nimport type {\n IWorkbench,\n IWorkbenchCommandMap,\n IWorkbenchContributions,\n IWorkbenchDiagnostic,\n IWorkbenchExtensionContext,\n IWorkbenchOptions,\n IWorkbenchState,\n IWorkbenchTarget,\n WorkbenchCommandArgs,\n WorkbenchMode,\n WorkbenchTool,\n} from './types';\nimport { WorkbenchPart, type IWorkbenchUI } from './parts/workbench-part';\nimport type { ICanvasHandle, IViewInput } from './parts/canvas-part';\nimport './styles/workbench.css';\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction errorCode(error: unknown): string {\n return typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n typeof error.code === 'string'\n ? error.code\n : 'workbench/operation-failed';\n}\n\nfunction validateViewBase(template: string): void {\n const url = new URL(template.replace('${id}', 'mica-view'));\n if (\n !['http:', 'https:'].includes(url.protocol) ||\n !template.endsWith('/') ||\n template.split('${id}').length !== 2 ||\n !new URL(template).hostname.split('.').includes('${id}')\n ) {\n throw new Error(\n 'viewBaseUrlTemplate must be an absolute HTTP(S) directory URL with one ${id} hostname label',\n );\n }\n}\n\nasync function decodeResourceImage(\n bytes: Uint8Array,\n name: string,\n): Promise<ImageBitmap | HTMLImageElement> {\n const svg = name.toLowerCase().endsWith('.svg');\n const blob = new Blob([bytes.slice().buffer], {\n type: svg ? 'image/svg+xml' : 'application/octet-stream',\n });\n if (!svg) return createImageBitmap(blob);\n const source = URL.createObjectURL(blob);\n try {\n const image = new Image();\n image.src = source;\n await image.decode();\n return image;\n } finally {\n URL.revokeObjectURL(source);\n }\n}\n\nexport async function createWorkbench(options: IWorkbenchOptions): Promise<IWorkbench> {\n validateViewBase(options.viewBaseUrlTemplate);\n function validateTheme(value: WorkbenchTheme | undefined) {\n const result = normalizeTheme(value);\n for (const [token, color] of Object.entries(result.colors ?? {}))\n if (!CSS.supports('color', color))\n throw new Error(`Invalid CSS color for ${token}: ${color}`);\n return result;\n }\n let theme = validateTheme(options.theme);\n const step = options.step ?? timePs(10_000_000);\n if (!Number.isSafeInteger(step) || step <= 0)\n throw new Error('Workbench step must be a positive integer number of picoseconds');\n const disposables = new DisposableStore();\n const abort = new AbortController();\n const content = disposables.add(new Emitter<FusedDocument>());\n const selectionChanged = disposables.add(new Emitter<readonly IWorkbenchTarget[]>());\n const stateChanged = disposables.add(new Emitter<IWorkbenchState>());\n const diagnosticsChanged = disposables.add(new Emitter<IWorkbenchDiagnostic>());\n const openProject = disposables.add(new Emitter<{ readonly projectId: string }>());\n const uiChanged = disposables.add(new Emitter<void>());\n const defaultAccessChanged = disposables.add(new Emitter<void>());\n const access: IWorkbenchAccessProvider = {\n onDidChange: options.accessProvider?.onDidChange ?? defaultAccessChanged.event,\n async evaluateDocument(context) {\n const decision = (await options.accessProvider?.evaluateDocument(context)) ?? {\n edit: { allowed: true as const },\n run: { allowed: true as const },\n };\n return {\n ...decision,\n edit: options.readOnly\n ? {\n allowed: false,\n code: 'document/read-only',\n message: 'The host opened this document read-only',\n }\n : decision.edit,\n };\n },\n async canAddDevice(context) {\n return (await options.accessProvider?.canAddDevice(context)) ?? { allowed: true };\n },\n };\n const rootContext = disposables.add(\n createContextKeyService({\n owner: 'workbench',\n reservedPrefixes: [\n 'workbench.',\n 'editor.',\n 'document.',\n 'history.',\n 'selection.',\n 'viewContainer.',\n 'canvas.',\n ],\n }),\n );\n const contextKeys = disposables.add(rootContext.createScope());\n const keys = {\n mode: rootContext.createKey<WorkbenchMode>('workbench.mode', 'edit'),\n busy: rootContext.createKey('workbench.busy', false),\n editable: rootContext.createKey('document.editable', false),\n dirty: rootContext.createKey('document.dirty', false),\n undo: rootContext.createKey('history.canUndo', false),\n redo: rootContext.createKey('history.canRedo', false),\n selection: rootContext.createKey('selection.count', 0),\n container: rootContext.createKey('viewContainer.active', ''),\n focus: rootContext.createKey('canvas.focused', false),\n };\n let documentSession: FusedDocumentSession;\n try {\n documentSession = await FusedDocumentSession.open({\n document: options.document,\n ...(options.saveDocument === undefined ? {} : { saveDocument: options.saveDocument }),\n devices: options.deviceProvider,\n access,\n });\n } catch (error) {\n disposables.dispose();\n throw error;\n }\n\n let disposed = false;\n let disposal: Promise<void> | undefined;\n let mode: WorkbenchMode = 'edit';\n let busy = false;\n let tool: WorkbenchTool = 'select';\n let labelName = 'NET1';\n let activeContainer: string | undefined;\n let selection: readonly IWorkbenchTarget[] = Object.freeze([]);\n let placement: DeviceLock | undefined;\n let placementRotation = 0;\n let canvas: ICanvasHandle | undefined;\n let runtime: IFusedRuntime | undefined;\n let runtimeDocument: FusedDocument | undefined;\n let runtimeGeneration = 0;\n let htmlViews: IHtmlViewHost | undefined;\n const transientLayouts = new Map<string, InstanceViewLayout | undefined>();\n let transition = Promise.resolve();\n let presentation = Promise.resolve();\n let presentationSignature = '';\n let version = 0;\n const images = new Map<string, ImageBitmap | HTMLImageElement>();\n const imageLocks = new Map<string, string>();\n const overlays = new Map<string, ImageBitmap>();\n const diagnostics: IWorkbenchDiagnostic[] = [];\n const mount = globalThis.document.createElement('div');\n mount.style.cssText = 'width:100%;height:100%;min-height:0;min-width:0;';\n const environment = globalThis.document.createElement('div');\n environment.hidden = true;\n const root = createRoot(mount);\n let registry: ContributionRegistry;\n let state = computeState();\n\n function assertReady(): void {\n if (disposed) throw new Error('Workbench is disposed');\n }\n function computeState(): IWorkbenchState {\n const value = documentSession.getState();\n return Object.freeze({\n mode,\n busy,\n dirty: value.dirty,\n readOnly: value.readOnly,\n canUndo: value.canUndo,\n canRedo: value.canRedo,\n tool,\n activeContainer,\n });\n }\n function update(): void {\n if (disposed) return;\n const next = computeState();\n const changed = JSON.stringify(next) !== JSON.stringify(state);\n state = next;\n rootContext.batch(() => {\n keys.mode.set(mode);\n keys.busy.set(busy);\n keys.editable.set(documentSession.getState().canEditContent && mode === 'edit' && !busy);\n keys.dirty.set(state.dirty);\n keys.undo.set(state.canUndo);\n keys.redo.set(state.canRedo);\n keys.selection.set(selection.length);\n keys.container.set(activeContainer ?? '');\n });\n version++;\n uiChanged.fire();\n if (changed) stateChanged.fire(state);\n }\n const report = (diagnostic: IWorkbenchDiagnostic): void => {\n if (disposed) return;\n if (\n diagnostics.some(\n (value) =>\n value.code === diagnostic.code &&\n value.message === diagnostic.message &&\n value.instanceId === diagnostic.instanceId,\n )\n )\n return;\n diagnostics.push(Object.freeze({ ...diagnostic }));\n diagnosticsChanged.fire(diagnostic);\n update();\n };\n const error = (reason: unknown): void =>\n report({ code: errorCode(reason), message: errorMessage(reason), severity: 'error' });\n function refreshLayoutDiagnostics(): void {\n const retained = diagnostics.filter((item) => item.code !== 'layout/body-overlap');\n diagnostics.splice(0, diagnostics.length, ...retained);\n for (const { first, second } of findBodyOverlaps(\n documentSession.getDocument(),\n documentSession.getDevices().getLoadedDevices(),\n ))\n report({\n code: 'layout/body-overlap',\n message: `${first.designator ?? first.id} overlaps ${second.designator ?? second.id}`,\n severity: 'warning',\n instanceId: first.id,\n });\n }\n function setSelection(targets: readonly IWorkbenchTarget[]): void {\n assertReady();\n const doc = documentSession.getDocument();\n const seen = new Set<string>();\n const lists = {\n instance: doc.instances,\n wire: doc.wires,\n node: doc.nodes,\n label: doc.labels,\n reference: doc.references,\n };\n for (const target of targets) {\n if (!lists[target.kind]?.some((item) => item.id === target.id))\n throw new Error(`Unknown selection target: ${target.kind}/${target.id}`);\n if (seen.has(target.id)) throw new Error(`Duplicate selection target: ${target.id}`);\n seen.add(target.id);\n }\n const previous =\n selection.length === 1 && selection[0]?.kind === 'instance' ? selection[0].id : undefined;\n selection = Object.freeze(targets.map((target) => Object.freeze({ ...target })));\n const single =\n selection.length === 1 && selection[0]?.kind === 'instance' ? selection[0].id : undefined;\n if (previous !== undefined && previous !== single) {\n const instance = doc.instances.find((item) => item.id === previous);\n const manifest =\n instance === undefined\n ? undefined\n : documentSession.getDevices().getLoaded(instance.device)?.manifest;\n if (manifest !== undefined)\n for (const view of viewLayout(previous).views)\n if (view.location === 'sidebar') htmlViews?.close(previous, view.viewId);\n }\n for (const view of htmlViews?.views ?? [])\n if (view.location === 'sidebar' && view.instanceId !== single) view.close();\n selectionChanged.fire(selection);\n update();\n }\n function clearOverlays(): void {\n for (const image of overlays.values()) image.close();\n overlays.clear();\n }\n async function releaseRuntime(): Promise<void> {\n htmlViews?.closeAll();\n runtimeGeneration++;\n const previous = runtime;\n runtimeDocument = undefined;\n runtime = undefined;\n clearOverlays();\n await previous?.dispose();\n }\n async function loadImages(): Promise<void> {\n for (const [id, device] of documentSession.getDevices().getLoadedDevices()) {\n if (imageLocks.get(id) === device.lock.integrity) continue;\n const path = device.geometry.bodyImage;\n if (path === undefined) {\n imageLocks.set(id, device.lock.integrity);\n continue;\n }\n const bytes = await device.files.read(path);\n const image = await decodeResourceImage(bytes, path);\n if (disposed) {\n if (image instanceof ImageBitmap) image.close();\n return;\n }\n const previous = images.get(id);\n if (previous instanceof ImageBitmap) previous.close();\n images.set(id, image);\n imageLocks.set(id, device.lock.integrity);\n }\n }\n async function createRuntime(targetMode: WorkbenchMode): Promise<IFusedRuntime | undefined> {\n const generation = ++runtimeGeneration;\n const document = documentSession.getDocument();\n const devices = documentSession.getDevices().getLoadedDevices();\n if (\n targetMode === 'edit' &&\n !document.instances.some((instance) => {\n const manifest = devices.get(instance.device)?.manifest;\n return (\n manifest?.view2d?.entry !== undefined ||\n Object.values(manifest?.properties ?? {}).some((property) => property.type === 'program')\n );\n })\n )\n return undefined;\n const result = await createFusedRuntime({\n ...(options.audio === undefined ? {} : { audio: options.audio }),\n document,\n registry: options.deviceProvider,\n step,\n mode: targetMode,\n container: environment,\n ...(options.programs === undefined ? {} : { programs: options.programs }),\n resolveResource: (request) => {\n if (request.reference.mode !== 'asset' || options.assetProvider === undefined)\n throw new Error('No asset provider is configured');\n return options.assetProvider.read(request.reference.assetId, abort.signal);\n },\n onDiagnostic: (diagnostic) => {\n if (generation !== runtimeGeneration) return;\n report({\n code: diagnostic.code,\n message: diagnostic.message,\n severity: 'error',\n ...(diagnostic.instanceId === undefined ? {} : { instanceId: diagnostic.instanceId }),\n });\n },\n onOverlay: (frame) => {\n if (disposed || generation !== runtimeGeneration) {\n frame.bitmap.close();\n return;\n }\n overlays.get(frame.instanceId)?.close();\n overlays.set(frame.instanceId, frame.bitmap);\n update();\n },\n measure: (instance) => {\n const geometry = devices.get(instance.device)?.geometry;\n if (geometry === undefined) throw new Error(`Missing geometry for ${instance.instanceId}`);\n const scale = (canvas?.scale ?? 12) * (globalThis.devicePixelRatio || 1);\n return {\n width: Math.max(1, Math.ceil(geometry.bounds.width * scale)),\n height: Math.max(1, Math.ceil(geometry.bounds.height * scale)),\n scale,\n };\n },\n });\n if (disposed || generation !== runtimeGeneration) {\n await result.dispose();\n throw new Error('Workbench was disposed during runtime preparation');\n }\n runtimeDocument = document;\n return result;\n }\n function refreshPresentation(): void {\n presentation = presentation\n .then(async () => {\n if (disposed) return;\n await loadImages();\n if (disposed) return;\n if (mode === 'edit' && !busy) {\n const signature = JSON.stringify([\n documentSession.getDocument().dependencies,\n documentSession\n .getDocument()\n .instances.map((instance) => [\n instance.id,\n instance.device,\n instance.properties,\n instance.placement.width,\n instance.placement.height,\n ]),\n ]);\n if (signature !== presentationSignature) {\n await releaseRuntime();\n runtime = await createRuntime('edit');\n presentationSignature = signature;\n }\n }\n update();\n })\n .catch(error);\n }\n async function setMode(next: WorkbenchMode): Promise<void> {\n assertReady();\n if (next !== 'edit' && next !== 'run')\n throw new Error(`Invalid workbench mode: ${String(next)}`);\n const task = transition.then(async () => {\n assertReady();\n if (next === mode) return;\n busy = true;\n placement = undefined;\n tool = 'select';\n update();\n try {\n await presentation;\n if (next === 'run') {\n await documentSession.setRunning(true);\n await releaseRuntime();\n runtime = await createRuntime('run');\n await documentSession.refreshAccess();\n const permission = documentSession.getAccess().run;\n if (!permission.allowed) throw new Error(permission.message);\n mode = 'run';\n } else {\n try {\n await releaseRuntime();\n } finally {\n await documentSession.setRunning(false);\n mode = 'edit';\n presentationSignature = '';\n }\n }\n } catch (reason) {\n const failures = [reason];\n if (next === 'run') {\n try {\n await releaseRuntime();\n } catch (cleanupError) {\n failures.push(cleanupError);\n }\n try {\n await documentSession.setRunning(false);\n } catch (cleanupError) {\n failures.push(cleanupError);\n }\n mode = 'edit';\n presentationSignature = '';\n }\n const failure =\n failures.length === 1\n ? reason\n : new AggregateError(failures, 'Failed to enter and release the run session');\n error(failure);\n throw failure;\n } finally {\n busy = false;\n update();\n if (mode === 'edit') refreshPresentation();\n }\n });\n transition = task.then(\n () => undefined,\n () => undefined,\n );\n return task;\n }\n function assertEditable(): void {\n assertReady();\n if (busy || mode !== 'edit' || !documentSession.getState().canEditContent)\n throw new Error('Document is not editable');\n }\n async function placeDevice(device: DeviceLock): Promise<void> {\n assertEditable();\n await documentSession.refreshAccess();\n assertEditable();\n const dependency = documentSession.getDocument().dependencies[device.id];\n if (\n dependency !== undefined &&\n (dependency.version !== device.version || dependency.integrity !== device.integrity)\n )\n throw new Error(`A different release of ${device.id} is already locked by this document`);\n const decision = await access.canAddDevice({\n document: documentSession.getDocument(),\n device,\n });\n if (!decision.allowed) throw new Error(decision.message);\n await documentSession.getDevices().get(device);\n await loadImages();\n assertEditable();\n placement = { ...device };\n placementRotation = 0;\n tool = 'select';\n if (options.container.clientWidth <= 720) activeContainer = undefined;\n update();\n }\n function viewLayout(instanceId: string): InstanceViewLayout {\n const instance = documentSession.getDocument().instances.find((item) => item.id === instanceId);\n const manifest =\n instance === undefined\n ? undefined\n : documentSession.getDevices().getLoaded(instance.device)?.manifest;\n if (instance === undefined || manifest === undefined)\n throw new Error(`Unknown device instance: ${instanceId}`);\n return resolveViewLayout(\n transientLayouts.has(instanceId) ? transientLayouts.get(instanceId) : instance.viewLayout,\n manifest,\n options.container.clientHeight,\n );\n }\n async function changeViewLayout(\n instanceId: string,\n layout: InstanceViewLayout | undefined,\n ): Promise<void> {\n assertReady();\n viewLayout(instanceId);\n if (documentSession.getState().canEditLayout) {\n await documentSession.setViewLayout(instanceId, layout);\n transientLayouts.delete(instanceId);\n } else {\n const document = documentSession.getDocument();\n const candidate = parseFusedDocument(\n JSON.stringify({\n ...document,\n instances: document.instances.map((instance) =>\n instance.id === instanceId ? { ...instance, viewLayout: layout } : instance,\n ),\n }),\n );\n transientLayouts.set(\n instanceId,\n candidate.instances.find((instance) => instance.id === instanceId)?.viewLayout,\n );\n }\n for (const handle of htmlViews?.views ?? []) {\n if (handle.instanceId !== instanceId) continue;\n const target = viewLayout(instanceId).views.find((view) => view.viewId === handle.viewId);\n if (target === undefined) handle.close();\n else {\n handle.setLocation(target.location);\n handle.setVisible(!target.collapsed || target.location === 'floating');\n }\n }\n update();\n }\n async function openView(\n instanceId: string,\n viewId: string,\n location?: 'sidebar' | 'floating',\n ): Promise<void> {\n assertReady();\n if (mode !== 'run' || busy || htmlViews === undefined)\n throw new Error('Device HTML views are available in Run mode');\n const layout = viewLayout(instanceId);\n const target = layout.views.find((view) => view.viewId === viewId);\n if (target === undefined) throw new Error(`Unknown device view: ${viewId}`);\n const nextLocation = location ?? target.location;\n if (target.collapsed || target.location !== nextLocation)\n await changeViewLayout(instanceId, {\n ...layout,\n views: layout.views.map((view) =>\n view.viewId === viewId ? { ...view, collapsed: false, location: nextLocation } : view,\n ),\n });\n if (nextLocation === 'sidebar') {\n setSelection([{ kind: 'instance', id: instanceId }]);\n activeContainer = 'mica.properties';\n }\n const handle = await htmlViews.open({ instanceId, viewId, location: nextLocation });\n handle.setLocation(nextLocation);\n handle.setVisible(true);\n update();\n handle.focus();\n }\n const handlers: {\n [K in keyof IWorkbenchCommandMap]: (\n params: IWorkbenchCommandMap[K]['params'],\n ) => Promise<IWorkbenchCommandMap[K]['result']> | IWorkbenchCommandMap[K]['result'];\n } = {\n 'workbench.openContainer': async ({ id, focus }) => {\n const container = registry.containers.find((value) => value.id === id);\n if (container === undefined || !registry.visible(container))\n throw new Error(`Unavailable view container: ${id}`);\n activeContainer = id;\n update();\n if (focus)\n requestAnimationFrame(() =>\n mount\n .querySelector<HTMLElement>(\n '.mica-wb-sidebar input, .mica-wb-sidebar button, .mica-wb-sidebar [tabindex=\"0\"]',\n )\n ?.focus(),\n );\n },\n 'workbench.closeContainer': async () => {\n activeContainer = undefined;\n update();\n },\n 'workbench.setMode': ({ mode }) => setMode(mode),\n 'canvas.fit': async () => {\n canvas?.fit();\n },\n 'canvas.zoom': async ({ factor }) => {\n if (!(factor > 0) || !Number.isFinite(factor))\n throw new Error('Zoom factor must be positive');\n canvas?.zoom(factor);\n },\n 'canvas.setTool': async ({ tool: next }) => {\n if (!['select', 'wire', 'power', 'ground', 'label'].includes(next))\n throw new Error(`Unknown tool: ${String(next)}`);\n if (next !== 'select') assertEditable();\n tool = next;\n if (next === 'label') {\n const used = new Set(documentSession.getDocument().labels.map((label) => label.name));\n let index = 1;\n while (used.has(`NET${index}`)) index++;\n labelName = `NET${index}`;\n }\n placement = undefined;\n placementRotation = 0;\n update();\n },\n 'device.place': ({ device }) => placeDevice(device),\n 'device.add': async ({ device, placement }) => {\n assertEditable();\n const id = await documentSession.addDevice(device, placement);\n setSelection([{ kind: 'instance', id }]);\n return id;\n },\n 'device.setProperty': async ({ instanceId, key, value }) => {\n assertEditable();\n await documentSession.setProperty(instanceId, key, value);\n },\n 'device.removeProperty': async ({ instanceId, key }) => {\n assertEditable();\n await documentSession.removeProperty(instanceId, key);\n },\n 'device.move': async ({ instanceId, position }) => {\n assertEditable();\n await documentSession.moveInstance(instanceId, position);\n },\n 'device.rotate': async ({ instanceId, degrees }) => {\n assertEditable();\n await documentSession.rotateInstance(instanceId, degrees);\n },\n 'selection.delete': async () => {\n assertEditable();\n await documentSession.remove(selection);\n setSelection([]);\n },\n 'selection.rotate': async ({ degrees }) => {\n assertEditable();\n if (!Number.isFinite(degrees)) throw new Error('Rotation must be finite');\n if (placement !== undefined || tool === 'power' || tool === 'ground') {\n placementRotation = (((placementRotation + degrees) % 360) + 360) % 360;\n update();\n return;\n }\n await documentSession.transact((current) => rotateTargets(current, selection, degrees));\n },\n 'wire.moveSegment': async ({ wireId, segment, delta }) => {\n assertEditable();\n await documentSession.transact((current) =>\n moveWireSegment(\n current,\n documentSession.getDevices().getLoadedDevices(),\n wireId,\n segment,\n delta,\n ),\n );\n },\n 'text.move': async ({ target, offset }) => {\n assertEditable();\n await documentSession.transact((current) => setTextOffset(current, target, offset));\n },\n 'reference.move': async ({ referenceId, position }) => {\n assertEditable();\n await documentSession.transact((current) =>\n moveReference(\n current,\n documentSession.getDevices().getLoadedDevices(),\n referenceId,\n position,\n () => crypto.randomUUID(),\n ),\n );\n },\n 'label.move': async ({ labelId, position }) => {\n assertEditable();\n await documentSession.transact((current) =>\n moveLabel(current, documentSession.getDevices().getLoadedDevices(), labelId, position),\n );\n },\n 'label.setName': async ({ labelId, name }) => {\n assertEditable();\n await documentSession.transact((current) => setLabelName(current, labelId, name));\n },\n 'reference.setVoltage': async ({ referenceId, voltage }) => {\n assertEditable();\n await documentSession.transact((current) =>\n setReferenceVoltage(current, referenceId, voltage),\n );\n },\n 'reference.setName': async ({ referenceId, name }) => {\n assertEditable();\n await documentSession.transact((current) =>\n setReferenceLabelName(current, referenceId, name),\n );\n },\n 'reference.setRotation': async ({ referenceId, rotation }) => {\n assertEditable();\n await documentSession.transact((current) =>\n setReferenceRotation(current, referenceId, rotation),\n );\n },\n 'wire.add': ({ from, to, bends }) => {\n assertEditable();\n return documentSession.addWire(from, to, bends);\n },\n 'reference.add': ({ target, voltage, symbol }) => {\n assertEditable();\n return documentSession.addReference(target, voltage, symbol);\n },\n 'label.add': ({ target, name }) => {\n assertEditable();\n return documentSession.addLabel(target, name);\n },\n 'document.undo': () => documentSession.undo(),\n 'document.redo': () => documentSession.redo(),\n 'document.save': () => documentSession.save(),\n 'view.open': ({ instanceId, viewId, location }) => openView(instanceId, viewId, location),\n 'view.setLocation': ({ instanceId, viewId, location }) =>\n openView(instanceId, viewId, location),\n 'view.close': async ({ instanceId, viewId }) => {\n const layout = viewLayout(instanceId);\n if (!layout.views.some((view) => view.viewId === viewId))\n throw new Error(`Unknown device view: ${viewId}`);\n htmlViews?.close(instanceId, viewId);\n await changeViewLayout(instanceId, {\n ...layout,\n views: layout.views.map((view) =>\n view.viewId === viewId && view.location === 'sidebar'\n ? { ...view, collapsed: true }\n : view,\n ),\n });\n },\n 'view.setLayout': ({ instanceId, layout }) => changeViewLayout(instanceId, layout),\n };\n const workbench: IWorkbench = {\n contextKeys,\n onDidChangeContent: content.event,\n onDidChangeSelection: selectionChanged.event,\n onDidChangeState: stateChanged.event,\n onDidReportDiagnostic: diagnosticsChanged.event,\n onDidRequestOpenProject: openProject.event,\n getDocument: () => {\n assertReady();\n return documentSession.getDocument();\n },\n getState: () => {\n assertReady();\n return state;\n },\n getSelection: () => {\n assertReady();\n return selection;\n },\n getTheme: () => {\n assertReady();\n return theme;\n },\n setTheme(value) {\n assertReady();\n theme = validateTheme(value);\n update();\n },\n setSelection,\n setMode: (mode) => workbench.executeCommand('workbench.setMode', { mode }),\n save: () => workbench.executeCommand('document.save'),\n async executeCommand<K extends keyof IWorkbenchCommandMap>(\n id: K,\n ...args: WorkbenchCommandArgs<IWorkbenchCommandMap[K]>\n ): Promise<IWorkbenchCommandMap[K]['result']> {\n try {\n assertReady();\n const handler = handlers[id];\n if (handler === undefined) throw new Error(`Unknown workbench command: ${String(id)}`);\n return await handler(args[0] as IWorkbenchCommandMap[K]['params']);\n } catch (reason) {\n error(reason);\n throw reason;\n }\n },\n dispose() {\n if (disposal !== undefined) return disposal;\n disposed = true;\n abort.abort();\n disposal = (async () => {\n const errors: unknown[] = [];\n const release = async (action: () => void | Promise<void>) => {\n try {\n await action();\n } catch (reason) {\n errors.push(reason);\n }\n };\n await release(() => root.unmount());\n await release(async () => {\n await transition;\n await presentation;\n await releaseRuntime();\n });\n await release(() => documentSession.dispose());\n await release(() => htmlViews?.dispose());\n await release(() => disposables.dispose());\n clearOverlays();\n for (const image of images.values()) if (image instanceof ImageBitmap) image.close();\n images.clear();\n mount.remove();\n environment.remove();\n if (errors.length)\n throw new AggregateError(errors, 'Failed to release workbench resources');\n })();\n return disposal;\n },\n };\n const context: IWorkbenchExtensionContext = { workbench, contextKeys, signal: abort.signal };\n const builtins: IWorkbenchContributions = {\n containers: [\n { id: 'mica.instances', title: '器件列表', icon: 'list-tree', order: 100 },\n { id: 'mica.properties', title: '信息', icon: 'info', order: -1000 },\n { id: 'mica.problems', title: '问题', icon: 'warning', order: 300 },\n ],\n toolbar: (['select', 'wire', 'power', 'ground', 'label'] as const).map((value, index) => ({\n id: `mica.tool.${value}`,\n title: {\n select: '选择',\n wire: '接线',\n power: '电源',\n ground: '接地',\n label: '网标',\n }[value],\n icon: { select: 'cursor', wire: 'plug', power: 'zap', ground: 'circuit-board', label: 'tag' }[\n value\n ],\n group: 'edit',\n order: index * 10,\n when: \"workbench.mode == 'edit'\",\n enablement: value === 'select' ? '!workbench.busy' : 'document.editable && !workbench.busy',\n execute: (context) => context.workbench.executeCommand('canvas.setTool', { tool: value }),\n })),\n };\n try {\n registry = new ContributionRegistry(contextKeys, builtins, options.contributions);\n htmlViews = createHtmlViewHost({\n viewBaseUrlTemplate: options.viewBaseUrlTemplate,\n container: options.container,\n registry: options.deviceProvider,\n describe(instanceId) {\n if (mode !== 'run' || busy || runtime === undefined) return undefined;\n const presentation = runtime.display.instances.find(\n (item) => item.instanceId === instanceId,\n );\n const manifest =\n presentation === undefined\n ? undefined\n : documentSession.getDevices().getLoaded(presentation.device)?.manifest;\n if (presentation === undefined || manifest === undefined) return undefined;\n return {\n device: presentation.device,\n lock: presentation.lock,\n props: presentation.props,\n methods: presentation.methods,\n events: presentation.events,\n hasModel: manifest.model !== undefined,\n views: manifest.view ?? {},\n };\n },\n model(instanceId) {\n const instance = documentSession\n .getDocument()\n .instances.find((item) => item.id === instanceId);\n if (\n instance === undefined ||\n documentSession.getDevices().getLoaded(instance.device)?.manifest.model === undefined\n )\n return undefined;\n if (runtime === undefined) throw new Error('The view model session is disconnected');\n return runtime.getModel(instanceId);\n },\n onDiagnostic: (failure) =>\n report({\n code: failure.code,\n message: `${failure.title}: ${failure.message}`,\n instanceId: failure.instanceId,\n severity: 'error',\n }),\n });\n } catch (reason) {\n await workbench.dispose();\n throw reason;\n }\n disposables.add(htmlViews.onDidChange(update));\n const ui: IWorkbenchUI = {\n workbench,\n options,\n context,\n get theme() {\n return theme;\n },\n htmlViews,\n viewLayout,\n changeViewLayout,\n contributions: registry,\n onDidUpdate: uiChanged.event,\n get devices() {\n return documentSession.getDevices().getLoadedDevices();\n },\n images,\n overlays,\n diagnostics,\n get placement() {\n return placement;\n },\n get placementRotation() {\n return placementRotation;\n },\n get version() {\n return version;\n },\n setCanvas: (value) => {\n canvas = value;\n },\n report,\n error,\n input: (instanceId, event: IViewInput) => {\n try {\n runtime?.display.input(instanceId, event);\n } catch (reason) {\n error(reason);\n }\n },\n get labelName() {\n return labelName;\n },\n setLabelName: (name) => {\n labelName = name;\n update();\n },\n connect: async (from, to, bends) => {\n assertEditable();\n await documentSession.transact((current) => {\n const devices = documentSession.getDevices().getLoadedDevices();\n const first = materializeAnchor(routeDocumentWires(current, devices), from, devices, () =>\n crypto.randomUUID(),\n );\n const last = materializeAnchor(first.document, to, devices, () => crypto.randomUUID());\n return addWire(last.document, first.endpoint, last.endpoint, bends, () =>\n crypto.randomUUID(),\n ).document;\n });\n },\n endpoint: async (target: Endpoint | Point2D) => {\n assertEditable();\n const activeTool = tool;\n const rotation = placementRotation;\n const name = labelName.trim();\n if (activeTool !== 'power' && activeTool !== 'ground' && activeTool !== 'label')\n throw new Error('未选择端子或网标放置工具');\n if (activeTool === 'label' && name === '') throw new Error('网标名称不能为空');\n await documentSession.transact((current) => {\n const anchor = materializeAnchor(\n routeDocumentWires(current, documentSession.getDevices().getLoadedDevices()),\n target,\n documentSession.getDevices().getLoadedDevices(),\n () => crypto.randomUUID(),\n );\n return activeTool === 'label'\n ? addLabel(anchor.document, anchor.endpoint, name, {}, () => crypto.randomUUID()).document\n : addReference(\n anchor.document,\n anchor.endpoint,\n activeTool === 'ground' ? 0 : 5,\n activeTool,\n { rotation },\n () => crypto.randomUUID(),\n ).document;\n });\n if (tool === activeTool) {\n tool = 'select';\n update();\n }\n },\n cancel: () => {\n placement = undefined;\n placementRotation = 0;\n tool = 'select';\n update();\n },\n focus: (value) => keys.focus.set(value),\n viewport: () => runtime?.display.invalidate(),\n reveal: (id) => {\n setSelection([{ kind: 'instance', id }]);\n canvas?.reveal(id);\n },\n validateResource: async (instanceId, key, value, signal) => {\n const instance = documentSession\n .getDocument()\n .instances.find((value) => value.id === instanceId);\n const descriptor =\n instance === undefined\n ? undefined\n : documentSession.getDevices().getLoaded(instance.device)?.manifest.properties?.[key];\n if (\n descriptor === undefined ||\n !['image', 'binary', 'firmware', 'program'].includes(descriptor.type)\n )\n throw new Error('Unknown resource property');\n if (instance === undefined) throw new Error('Unknown resource instance');\n const device = documentSession.getDevices().requireLoaded(instance.device);\n const verified = await openDevicePackage(options.deviceProvider, device.lock);\n signal.throwIfAborted();\n const resolved = await resolveInstanceProperties({\n instanceId,\n package: verified,\n descriptors: { [key]: descriptor },\n overrides: { [key]: value },\n irProperties: new Map(),\n pointer: ['properties'],\n signal,\n ...(options.programs === undefined ? {} : { programs: options.programs }),\n resolveResource: (request) => {\n if (request.reference.mode !== 'asset' || options.assetProvider === undefined)\n throw new Error('No asset provider is configured');\n return options.assetProvider.read(request.reference.assetId, signal);\n },\n });\n signal.throwIfAborted();\n const resource = resolved.props[key];\n if (\n resource &&\n typeof resource === 'object' &&\n 'slice' in resource &&\n typeof resource.slice === 'function'\n ) {\n const bytes: unknown = resource.slice();\n if (!(bytes instanceof Uint8Array)) throw new Error('Resource did not resolve to bytes');\n if (descriptor.type === 'image') {\n const sourceName =\n value !== null && typeof value === 'object'\n ? value.mode === 'package'\n ? value.src\n : (value.name ?? '')\n : '';\n const bitmap = await decodeResourceImage(bytes, sourceName);\n try {\n if (\n descriptor.maxPixels !== undefined &&\n bitmap.width * bitmap.height > descriptor.maxPixels\n )\n throw new Error('Image exceeds the property pixel limit');\n } finally {\n if (bitmap instanceof ImageBitmap) bitmap.close();\n }\n }\n signal.throwIfAborted();\n return bytes;\n }\n return undefined;\n },\n commitResource: async (instanceId, key, expected, value, signal) => {\n await documentSession.transact((current) => {\n signal.throwIfAborted();\n assertEditable();\n const instance = current.instances.find((entry) => entry.id === instanceId);\n if (\n instance === undefined ||\n JSON.stringify(instance.properties?.[key]) !== JSON.stringify(expected)\n )\n throw new Error('resource/target-changed: 属性已改变,请重新选择资源');\n return setInstanceProperty(current, instanceId, key, value);\n });\n },\n openProject: (projectId) => openProject.fire({ projectId }),\n programPackagePaths: (deviceId) =>\n Object.keys(documentSession.getDevices().getLoaded(deviceId)?.files.files ?? {}),\n programSnapshot: (instanceId) => {\n const prepared = runtimeDocument?.instances.find((instance) => instance.id === instanceId);\n const current = documentSession\n .getDocument()\n .instances.find((instance) => instance.id === instanceId);\n if (\n !prepared ||\n !current ||\n prepared.device !== current.device ||\n JSON.stringify(prepared.properties) !== JSON.stringify(current.properties)\n )\n return undefined;\n return runtime?.display.instances.find((instance) => instance.instanceId === instanceId)\n ?.props;\n },\n };\n disposables.add(\n documentSession.onDidChangeContent((value) => {\n const ids = new Set(\n [\n ...value.instances,\n ...value.wires,\n ...value.nodes,\n ...value.labels,\n ...value.references,\n ].map((item) => item.id),\n );\n if (selection.some((target) => !ids.has(target.id))) {\n selection = Object.freeze(selection.filter((target) => ids.has(target.id)));\n selectionChanged.fire(selection);\n }\n content.fire(value);\n for (const handle of htmlViews?.views ?? []) {\n if (!value.instances.some((instance) => instance.id === handle.instanceId)) {\n handle.close();\n continue;\n }\n const target = viewLayout(handle.instanceId).views.find(\n (view) => view.viewId === handle.viewId,\n );\n if (target === undefined) handle.close();\n else {\n handle.setLocation(target.location);\n handle.setVisible(target.location === 'floating' || !target.collapsed);\n }\n }\n refreshLayoutDiagnostics();\n update();\n refreshPresentation();\n }),\n );\n disposables.add(\n documentSession.onDidChangeState(() => {\n update();\n if (mode === 'run' && !documentSession.getAccess().run.allowed)\n void setMode('edit').catch(error);\n }),\n );\n disposables.add(documentSession.onDidError(error));\n disposables.add(\n contextKeys.onDidChange((event) => {\n if (registry.affected(new Set(event.names))) {\n version++;\n uiChanged.fire();\n }\n }),\n );\n options.container.append(mount, environment);\n try {\n const audio = options.audio?.context;\n if (audio !== undefined) {\n let resuming = false;\n const unlockAudio = (event: Event) => {\n if (!event.isTrusted || audio.state !== 'suspended' || resuming) return;\n // Touch and pen activation is available on release rather than pointerdown.\n if (event.type === 'pointerdown' && 'pointerType' in event && event.pointerType !== 'mouse')\n return;\n resuming = true;\n void audio\n .resume()\n .catch((reason: unknown) => {\n report({ code: 'audio/failed', message: errorMessage(reason), severity: 'error' });\n })\n .finally(() => {\n resuming = false;\n });\n };\n for (const type of ['pointerdown', 'pointerup', 'keydown']) {\n options.container.ownerDocument.addEventListener(type, unlockAudio, {\n capture: true,\n signal: abort.signal,\n });\n }\n }\n await loadImages();\n refreshLayoutDiagnostics();\n update();\n flushSync(() => root.render(<WorkbenchPart ui={ui} />));\n const preparationError = documentSession.getPreparationError();\n if (preparationError !== undefined) error(preparationError);\n refreshPresentation();\n return workbench;\n } catch (reason) {\n await workbench.dispose();\n throw reason;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,IAAa,4BAA+C,CAAC,cAAc,SAAS;;AAYpF,IAAa,2BAAb,cAA8C,MAAM;CAGvC;CACA;CAHX,YACE,SACA,QACA,SACA;EACA,MAAM,OAAO;EAHJ,KAAA,SAAA;EACA,KAAA,UAAA;EAGT,KAAK,OAAO;CACd;AACF;;;;ACfA,IAAa,iBAAb,cAAoC,MAAM;C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