import type { Asset, BehaviorAsset } from '../../core/model/Asset'; import { findAsset, findAssetOf } from '../../core/model/Project'; import { AssetTabEditor } from '../AssetTabEditor'; import type { EditorState } from '../state'; import { Breadcrumb } from './Breadcrumb'; import { GraphCanvas } from './GraphCanvas'; import { SnapToggle } from './SnapToggle'; import { backTo, descend, follow, type Trail } from './trail'; /** Room kept for the "N nodes · M links" readout, wide enough for a three-digit graph. */ const INFO_WIDTH = 150; export class GraphEditor extends AssetTabEditor { private readonly snap = new SnapToggle(() => this.canvas); readonly breadcrumb = new Breadcrumb(); private trail: Trail = []; constructor(state: EditorState) { super(state, { noun: 'Behavior', infoWidth: INFO_WIDTH }); this.breadcrumb.onPick = (index) => this.open(this.trail[index]!, backTo(this.trail, index)); this.mount(new GraphCanvas(state), this.snap.widgets, this.breadcrumb); this.canvas.onOpenBehavior = (id) => this.open(id, descend(this.trail, this.currentAssetId, id)); // Play swaps in the runtime copy of the project, and back. state.on('mode', () => this.refresh()); } /** * The bar goes up before the graph switches: switching fits the view to the canvas, and a bar * appearing afterwards would cut the bottom of the fitted graph off. */ private open(assetId: string, trail: Trail): void { this.trail = trail; this.showTrail(); this.state.select({ kind: 'asset', assetId }); this.refresh(); } protected override refresh(): void { super.refresh(); const project = this.state.project; this.trail = follow(this.trail, this.currentAssetId, (id) => Boolean(findAssetOf(project, id, 'behavior')), ); this.showTrail(); } private showTrail(): void { const names = this.trail.map((id) => findAsset(this.state.project, id)?.name ?? ''); if (this.breadcrumb.show(names)) this.relayout(); } protected override selectedId(): string { return this.state.selectedBehaviorId ?? ''; } protected override isMine(asset: Asset): asset is BehaviorAsset { return asset.type === 'behavior'; } protected override infoText(asset: BehaviorAsset): string { const nodes = asset.graph.nodes.length; const links = asset.graph.edges.length; return `${nodes} ${nodes === 1 ? 'node' : 'nodes'} · ${links} ${links === 1 ? 'link' : 'links'}`; } protected override syncExtras(asset: BehaviorAsset | null): void { this.snap.setEnabled(Boolean(asset)); } }