@kubohiroya/turbowarp-plus-editor-code-views 0.22.0 → 0.22.2

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.
@@ -0,0 +1,222 @@
1
+ import {paintScripts, type LayoutEvents} from './script-layout-workspace.ts';
2
+ import {readScriptRelations, type ScriptRelation} from './script-relations.ts';
3
+ import type {ScriptRelationContext} from './script-arrows.ts';
4
+ import {arrangeSemanticScripts, type SemanticPlacement} from './semantic-script-layout.ts';
5
+ import {applySemanticLayout, readSemanticWorkspace, type SemanticScript, type SemanticWorkspace} from './semantic-layout-workspace.ts';
6
+
7
+ const ns = 'http://www.w3.org/2000/svg';
8
+ export interface SemanticLayoutContext {
9
+ workspace: SemanticWorkspace;
10
+ events: LayoutEvents;
11
+ relations: ScriptRelationContext;
12
+ canArrange(): boolean;
13
+ }
14
+
15
+ export function openSemanticLayout(context: SemanticLayoutContext, locale: string) {
16
+ const {workspace, events, relations, canArrange} = context;
17
+ const document = workspace.getInjectionDiv().ownerDocument;
18
+ const window = document.defaultView!;
19
+ const ja = /^ja(?:-|$)/i.test(locale);
20
+ const t = (en: string, japanese: string) => ja ? japanese : en;
21
+ const dialog = document.createElement('dialog');
22
+ dialog.className = 'tw-script-layout-dialog';
23
+ dialog.setAttribute('aria-label', t('Rearrange scripts by relationships', 'スクリプトを意味に応じて再配置する'));
24
+ const title = document.createElement('h2');
25
+ title.textContent = dialog.getAttribute('aria-label');
26
+ const explanation = document.createElement('p');
27
+ explanation.textContent = t('Read static calls and messages from left to right. This does not guarantee execution order.',
28
+ '関数の呼び出しとメッセージ送受信を左から右にたどる配置です。実行順序を保証するものではありません。');
29
+ const preview = document.createElement('div');
30
+ preview.className = 'tw-script-layout-preview';
31
+ preview.tabIndex = 0;
32
+ preview.setAttribute('aria-label', t('Layout preview', '再配置のプレビュー'));
33
+ const footer = document.createElement('footer');
34
+ footer.className = 'tw-plus-dialog-actions';
35
+ const status = document.createElement('p');
36
+ status.setAttribute('role', 'status');
37
+ const cancel = document.createElement('button');
38
+ cancel.textContent = t('Cancel', 'キャンセル');
39
+ cancel.dataset.dialogAction = 'cancel';
40
+ const apply = document.createElement('button');
41
+ apply.textContent = t('Rearrange', '再配置する');
42
+ apply.dataset.dialogAction = 'confirm';
43
+ apply.disabled = true;
44
+ const recalculate = document.createElement('button');
45
+ recalculate.textContent = t('Recalculate', '再計算する');
46
+ footer.append(status, recalculate, cancel, apply);
47
+ dialog.append(title, explanation, preview, footer);
48
+ document.body.append(dialog);
49
+ let closed = false;
50
+ let run: AbortController | undefined;
51
+ let snapshot: ReturnType<typeof readSemanticWorkspace>;
52
+ let placements: SemanticPlacement<SemanticScript>[] = [];
53
+ let signature = '';
54
+ let originalTarget: ReturnType<ScriptRelationContext['getTarget']>;
55
+
56
+ function graph() {
57
+ return relations.getRelations?.() ?? readScriptRelations(relations.vm?.runtime?.targets ??
58
+ (relations.getTarget() ? [relations.getTarget()!] : []));
59
+ }
60
+ function revision() {
61
+ // Include program contents and external targets: unchanged bounds do not imply unchanged calls.
62
+ const targets = relations.vm?.runtime?.targets ?? [relations.getTarget()];
63
+ const geometry = readSemanticWorkspace(workspace);
64
+ return JSON.stringify({targets: targets.filter(t => t && t.isOriginal !== false).map(t => [t.id, t.blocks._blocks]),
65
+ graph: relations.getRelations?.(), scripts: geometry.scripts.map(s => [s.id, s.x, s.y, s.width, s.height]),
66
+ comments: geometry.comments.map(c => [c.id, c.rootId, c.x, c.y, c.width, c.height, c.origin, c.text])});
67
+ }
68
+ function stale() {
69
+ try {
70
+ const current = readSemanticWorkspace(workspace).scripts;
71
+ return !canArrange() || relations.getTarget()?.id !== originalTarget?.id || revision() !== signature ||
72
+ current.length !== snapshot.scripts.length || current.some(s =>
73
+ snapshot.scripts.find(original => original.id === s.id)?.block !== s.block);
74
+ } catch {return true;}
75
+ }
76
+ function close() {
77
+ if (closed) return;
78
+ closed = true;
79
+ run?.abort();
80
+ for (const [emitter, name] of subscriptions) emitter?.removeListener?.(name, invalidate);
81
+ if (dialog.open) dialog.close();
82
+ dialog.remove();
83
+ }
84
+ function invalidate() {
85
+ if (closed || !snapshot || !stale()) return;
86
+ run?.abort(); apply.disabled = true; recalculate.disabled = false;
87
+ status.textContent = t('The code changed. Recalculate the preview.', 'コードが変わりました。プレビューを再計算してください。');
88
+ }
89
+ const subscriptions = [
90
+ [relations.vm, 'workspaceUpdate'], [relations.vm, 'targetsUpdate'], [relations.vm?.runtime, 'PROJECT_CHANGED']
91
+ ] as const;
92
+ for (const [emitter, name] of subscriptions) emitter?.on?.(name, invalidate);
93
+
94
+ async function calculate() {
95
+ run?.abort();
96
+ const task = new window.AbortController(); run = task;
97
+ apply.disabled = true; recalculate.disabled = true; preview.replaceChildren();
98
+ status.textContent = t('Calculating layout…', '配置を計算しています…');
99
+ try {
100
+ events.fireNow_();
101
+ if (!canArrange()) throw new Error('Workspace is unavailable');
102
+ originalTarget = relations.getTarget();
103
+ if (!originalTarget) throw new Error('No target');
104
+ snapshot = readSemanticWorkspace(workspace);
105
+ signature = revision();
106
+ const edges = graph();
107
+ const started = window.performance.now();
108
+ const result = await arrangeSemanticScripts(snapshot.scripts, edges, originalTarget.id, {
109
+ signal: task.signal, obstacles: snapshot.obstacles,
110
+ yieldControl: () => new Promise(resolve => window.setTimeout(resolve, 0))
111
+ });
112
+ if (closed || run !== task || task.signal.aborted) return;
113
+ if (stale()) {invalidate(); return;}
114
+ placements = result.placements;
115
+ paintPreview(edges);
116
+ const external = edges.filter(e => e.destination && e.source.targetId !== e.destination.targetId &&
117
+ [e.source.targetId, e.destination.targetId].includes(originalTarget.id)).length;
118
+ const unresolved = edges.filter(e => e.source.targetId === originalTarget.id && e.unresolved).length;
119
+ status.textContent = t(`${placements.length} scripts · ${result.metrics.edges} links · ${external} external · ${unresolved} unresolved`,
120
+ `${placements.length}スクリプト・${result.metrics.edges}接続・外部${external}・未解決${unresolved}`);
121
+ preview.dataset.layoutMetrics = JSON.stringify({...result.metrics, milliseconds: window.performance.now() - started,
122
+ overlaps: 0, external, unresolved});
123
+ apply.disabled = !placements.some(p => p.x !== p.script.x || p.y !== p.script.y);
124
+ } catch (error) {
125
+ if (closed || run !== task || task.signal.aborted) return;
126
+ status.textContent = t('Unable to calculate a safe layout. The project has not changed.',
127
+ '安全な配置を計算できませんでした。作品は変更されていません。');
128
+ status.title = String(error);
129
+ } finally {if (!closed && run === task) recalculate.disabled = false;}
130
+ }
131
+
132
+ function paintPreview(edges: readonly ScriptRelation[]) {
133
+ paintScripts(preview, placements, .6);
134
+ const svg = preview.querySelector('svg')!;
135
+ const local = new Map(placements.map(p => [p.script.id, p]));
136
+ // Include loose comments and the complete cluster extents, even beyond the visible folded body.
137
+ for (const c of snapshot.comments) {
138
+ const p = local.get(c.rootId);
139
+ const x = c.x + (p ? p.x - p.script.x : 0), y = c.y + (p ? p.y - p.script.y : 0);
140
+ const rect = document.createElementNS(ns, 'rect');
141
+ for (const [key, value] of Object.entries({x, y, width: c.width, height: c.height, fill: '#fff2ae', stroke: '#9b8524'})) {
142
+ rect.setAttribute(key, String(value));
143
+ }
144
+ const text = document.createElementNS(ns, 'title'); text.textContent = t('Comment', 'コメント');
145
+ rect.append(text); svg.append(rect);
146
+ const content = document.createElementNS(ns, 'foreignObject');
147
+ for (const [key, value] of Object.entries({x: x + 8, y: y + 8,
148
+ width: Math.max(0, c.width - 16), height: Math.max(0, c.height - 16)})) content.setAttribute(key, String(value));
149
+ const prose = document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
150
+ prose.style.cssText = 'height:100%;overflow:hidden;white-space:pre-wrap;color:#332f20;font:14px sans-serif';
151
+ prose.textContent = c.text; content.append(prose); svg.append(content);
152
+ }
153
+ const layer = document.createElementNS(ns, 'g');
154
+ layer.setAttribute('data-semantic-relations', '');
155
+ for (const edge of edges) {
156
+ const source = edge.source.targetId === originalTarget.id ? local.get(edge.source.scriptId) : undefined;
157
+ const destination = edge.destination?.targetId === originalTarget.id ? local.get(edge.destination.scriptId) : undefined;
158
+ if (!source && !destination) continue;
159
+ const p = source ?? destination;
160
+ const end = destination ?? source;
161
+ const from = {x: p.x + (source ? p.script.width : -40), y: p.y + p.script.height / 2};
162
+ const to = {x: destination ? end.x : end.x + end.script.width + 40, y: end.y + end.script.height / 2};
163
+ const group = document.createElementNS(ns, 'g');
164
+ group.dataset.semanticRelation = edge.kind;
165
+ group.dataset.wait = String(edge.wait);
166
+ if (edge.unresolved) group.dataset.unresolved = edge.unresolved;
167
+ else if (!source || !destination) group.dataset.external = 'true';
168
+ const line = document.createElementNS(ns, 'path');
169
+ const middle = Math.max(from.x + 32, (from.x + to.x) / 2);
170
+ line.setAttribute('d', `M ${from.x} ${from.y} C ${middle} ${from.y} ${middle} ${to.y} ${to.x} ${to.y}`);
171
+ line.setAttribute('fill', 'none'); line.setAttribute('stroke', edge.kind === 'function' ? '#b65be6' : '#ba8a00');
172
+ line.setAttribute('stroke-width', '2');
173
+ if (edge.kind === 'message') line.setAttribute('stroke-dasharray', edge.wait ? '7 5' : '3.5 2.5');
174
+ const head = document.createElementNS(ns, 'path');
175
+ head.setAttribute('d', `M ${to.x - 7} ${to.y - 4} L ${to.x} ${to.y} L ${to.x - 7} ${to.y + 4}`);
176
+ head.setAttribute('fill', 'none'); head.setAttribute('stroke', line.getAttribute('stroke'));
177
+ const label = document.createElementNS(ns, 'title');
178
+ label.textContent = `${edge.label} ${edge.unresolved ? t('(unresolved)', '(未解決)') :
179
+ !source || !destination ? t('(external)', '(外部)') : ''}`;
180
+ group.append(line, head, label); layer.append(group);
181
+ if (edge.unresolved || !source || !destination) {
182
+ const text = document.createElementNS(ns, 'text');
183
+ text.setAttribute('x', String(to.x + 8)); text.setAttribute('y', String(to.y));
184
+ text.setAttribute('fill', 'currentColor'); text.setAttribute('font-size', '14');
185
+ const externalId = source ? edge.destination?.targetId : edge.source.targetId;
186
+ text.textContent = edge.unresolved ? `${edge.label || '?'} ${t('(unresolved)', '(未解決)')}` :
187
+ `${edge.label} ↗ ${relations.getTargetName?.(externalId) ??
188
+ relations.vm?.runtime?.targets?.find(target => target.id === externalId)?.getName?.() ?? t('external', '外部')}`;
189
+ group.append(text);
190
+ }
191
+ }
192
+ svg.prepend(layer);
193
+ const box = svg.getBBox();
194
+ const left = Math.min(0, box.x) - 16, top = Math.min(0, box.y) - 16;
195
+ const width = box.x + box.width - left + 32, height = box.y + box.height - top + 32;
196
+ svg.setAttribute('viewBox', `${left} ${top} ${width} ${height}`);
197
+ svg.setAttribute('width', String(width * .6));
198
+ svg.setAttribute('height', String(height * .6));
199
+ }
200
+
201
+ cancel.addEventListener('click', close);
202
+ dialog.addEventListener('close', close, {once: true});
203
+ dialog.addEventListener('cancel', close, {once: true});
204
+ dialog.addEventListener('keydown', e => e.stopPropagation());
205
+ recalculate.addEventListener('click', () => void calculate());
206
+ apply.addEventListener('click', () => {
207
+ events.fireNow_();
208
+ if (stale()) {invalidate(); return;}
209
+ try {applySemanticLayout(workspace, events, placements, snapshot.comments);}
210
+ catch (error) {
211
+ apply.disabled = true;
212
+ status.textContent = t('Unable to apply the layout. Original positions were restored.',
213
+ '配置を適用できませんでした。元の位置に戻しました。');
214
+ status.title = String(error); return;
215
+ }
216
+ close();
217
+ if (placements.length) workspace.centerOnBlock(placements[0].script.id);
218
+ });
219
+ dialog.showModal(); cancel.focus();
220
+ void calculate();
221
+ return {close};
222
+ }
@@ -0,0 +1,109 @@
1
+ import {readScripts, type LayoutBlock, type LayoutEvents, type LayoutWorkspace, type RenderedScript} from './script-layout-workspace.ts';
2
+ import type {ScriptBounds} from './script-layout.ts';
3
+ import type {SemanticPlacement} from './semantic-script-layout.ts';
4
+
5
+ type Point = {x: number; y: number};
6
+ export interface LayoutComment {
7
+ id: string;
8
+ block_?: LayoutBlock & {getRootBlock(): LayoutBlock};
9
+ getXY?(): Point;
10
+ getRelativeToSurfaceXY?(): Point;
11
+ getBoundingRectangle(): {topLeft: Point; bottomRight: Point};
12
+ moveTo?(x: number, y: number): void;
13
+ getText?(): string;
14
+ getSvgRoot?(): SVGElement;
15
+ bubble_?: {bubbleGroup_?: SVGElement};
16
+ }
17
+
18
+ export type SemanticWorkspace = LayoutWorkspace & {getTopComments?(ordered: boolean): LayoutComment[]};
19
+ export type SemanticEvents = LayoutEvents & {
20
+ FIRE_QUEUE_?: {type?: string; commentId?: string; recordUndo?: boolean}[];
21
+ disable?(): void;
22
+ enable?(): void;
23
+ };
24
+
25
+ export interface CommentSnapshot extends ScriptBounds {
26
+ comment: LayoutComment;
27
+ rootId?: string;
28
+ origin: Point;
29
+ text: string;
30
+ svg?: SVGElement;
31
+ }
32
+ export interface SemanticScript extends RenderedScript {
33
+ /** Full script rectangle before attached comments are included. */
34
+ bounds: ScriptBounds;
35
+ }
36
+
37
+ /** Read expanded bounds without changing the user's folding or moving any comments. */
38
+ export function readSemanticWorkspace(workspace: SemanticWorkspace) {
39
+ const scripts: SemanticScript[] = readScripts(workspace).map(script => {
40
+ const {topLeft, bottomRight} = script.block.getBoundingRectangle();
41
+ const bounds = {id: script.id, ...topLeft, width: bottomRight.x - topLeft.x, height: bottomRight.y - topLeft.y};
42
+ return {...script, ...bounds, bounds};
43
+ });
44
+ const byId = new Map(scripts.map(s => [s.id, s]));
45
+ const comments: CommentSnapshot[] = (workspace.getTopComments?.(false) ?? []).map(comment => {
46
+ const {topLeft, bottomRight} = comment.getBoundingRectangle();
47
+ const rootId = comment.block_?.getRootBlock().id;
48
+ if (rootId && (!comment.getXY || !comment.moveTo)) throw new Error('Comment cannot be moved safely');
49
+ return {id: comment.id, comment, rootId, origin: comment.getXY?.() ?? comment.getRelativeToSurfaceXY?.() ?? topLeft,
50
+ text: comment.getText?.() ?? '',
51
+ ...topLeft, width: bottomRight.x - topLeft.x, height: bottomRight.y - topLeft.y,
52
+ svg: comment.getSvgRoot?.() ?? comment.bubble_?.bubbleGroup_};
53
+ });
54
+ for (const comment of comments) {
55
+ const script = byId.get(comment.rootId);
56
+ if (!script) continue;
57
+ const right = Math.max(script.x + script.width, comment.x + comment.width);
58
+ const bottom = Math.max(script.y + script.height, comment.y + comment.height);
59
+ script.x = Math.min(script.x, comment.x); script.y = Math.min(script.y, comment.y);
60
+ script.width = right - script.x; script.height = bottom - script.y;
61
+ }
62
+ return {scripts, comments, obstacles: comments.filter(c => !byId.has(c.rootId))};
63
+ }
64
+
65
+ /** Roll back queued native moves before any of them reach the VM or the undo stacks. */
66
+ export function applySemanticLayout(workspace: SemanticWorkspace, events: SemanticEvents,
67
+ placements: SemanticPlacement<SemanticScript>[], comments: CommentSnapshot[]) {
68
+ const outer = events.getGroup();
69
+ const queue = events.FIRE_QUEUE_;
70
+ if (!queue || !events.disable || !events.enable) throw new Error('Transactional move events are unavailable');
71
+ const start = queue.length;
72
+ const roots = placements.map(p => ({block: p.script.block, position: p.script.block.getRelativeToSurfaceXY()}));
73
+ const byId = new Map(placements.map(p => [p.script.id, p]));
74
+ events.setGroup(true);
75
+ workspace.setResizesEnabled(false);
76
+ try {
77
+ for (const p of placements) {
78
+ const dx = p.x - p.script.x, dy = p.y - p.script.y;
79
+ if (dx || dy) p.script.block.moveBy(dx, dy);
80
+ }
81
+ for (const c of comments) {
82
+ const p = byId.get(c.rootId);
83
+ if (!p) continue;
84
+ c.comment.moveTo!(c.origin.x + p.x - p.script.x, c.origin.y + p.y - p.script.y);
85
+ }
86
+ // Native block moves already carry their attached comments on undo/redo. Recording an
87
+ // absolute comment move as well would move it twice on redo. Keep the notification for
88
+ // the VM (including child-window serialization), but let the block own its undo step.
89
+ const attached = new Set(comments.filter(c => byId.has(c.rootId)).map(c => c.id));
90
+ for (const event of queue.slice(start)) {
91
+ if (event.type === 'comment_move' && attached.has(event.commentId)) event.recordUndo = false;
92
+ }
93
+ } catch (error) {
94
+ queue.splice(start);
95
+ events.disable();
96
+ try {
97
+ for (const {block, position} of roots) {
98
+ const current = block.getRelativeToSurfaceXY();
99
+ block.moveBy(position.x - current.x, position.y - current.y);
100
+ }
101
+ for (const c of comments) if (byId.has(c.rootId)) c.comment.moveTo!(c.origin.x, c.origin.y);
102
+ } finally {events.enable();}
103
+ throw error;
104
+ } finally {
105
+ workspace.setResizesEnabled(true);
106
+ events.setGroup(outer);
107
+ }
108
+ events.fireNow_();
109
+ }
@@ -0,0 +1,254 @@
1
+ import Matter from 'matter-js';
2
+ import type {ScriptBounds} from './script-layout.ts';
3
+ import type {ScriptRelation} from './script-relations.ts';
4
+
5
+ export interface SemanticPlacement<T extends ScriptBounds = ScriptBounds> {
6
+ script: T;
7
+ x: number;
8
+ y: number;
9
+ column: number;
10
+ group: number;
11
+ }
12
+
13
+ export interface SemanticLayoutOptions {
14
+ signal?: AbortSignal;
15
+ /** Yield to the host without making the simulation depend on elapsed time. */
16
+ yieldControl?(): Promise<void>;
17
+ obstacles?: readonly ScriptBounds[];
18
+ }
19
+
20
+ export const semanticLayoutLimits = {scripts: 1000, relations: 10000, steps: 120};
21
+ const gap = 64;
22
+ const compareId = (a: string, b: string) => a < b ? -1 : Number(a > b);
23
+ const overlaps = (a: ScriptBounds, b: ScriptBounds) =>
24
+ a.x < b.x + b.width + gap && b.x < a.x + a.width + gap &&
25
+ a.y < b.y + b.height + gap && b.y < a.y + a.height + gap;
26
+
27
+ function check(signal?: AbortSignal) {
28
+ if (signal?.aborted) throw new Error('Layout cancelled');
29
+ }
30
+
31
+ /** Iterative Kosaraju traversal: recursive projects must not exhaust the JS stack. */
32
+ function components(ids: string[], outgoing: Map<string, string[]>, incoming: Map<string, string[]>) {
33
+ const seen = new Set<string>();
34
+ const finished: string[] = [];
35
+ for (const id of ids) {
36
+ if (seen.has(id)) continue;
37
+ const stack: [string, number][] = [[id, 0]];
38
+ seen.add(id);
39
+ while (stack.length) {
40
+ const entry = stack.at(-1)!;
41
+ const edges = outgoing.get(entry[0])!;
42
+ if (entry[1] === edges.length) {finished.push(entry[0]); stack.pop(); continue;}
43
+ const next = edges[entry[1]++];
44
+ if (!seen.has(next)) {seen.add(next); stack.push([next, 0]);}
45
+ }
46
+ }
47
+ seen.clear();
48
+ const groups: string[][] = [];
49
+ for (const id of finished.reverse()) {
50
+ if (seen.has(id)) continue;
51
+ const group: string[] = [], stack = [id];
52
+ seen.add(id);
53
+ while (stack.length) {
54
+ const current = stack.pop()!;
55
+ group.push(current);
56
+ for (const next of incoming.get(current)!) if (!seen.has(next)) {seen.add(next); stack.push(next);}
57
+ }
58
+ groups.push(group.sort(compareId));
59
+ }
60
+ return groups.sort((a, b) => compareId(a[0], b[0]));
61
+ }
62
+
63
+ /**
64
+ * Lay out the SCC condensation DAG in ranks, then relax rectangles with Matter.js.
65
+ * Canonical ID order, fixed steps and final packing keep repeated runs stable.
66
+ * Relations to other targets are shown by the preview, never used to move those targets.
67
+ */
68
+ export async function arrangeSemanticScripts<T extends ScriptBounds>(
69
+ scripts: readonly T[], relations: readonly ScriptRelation[], targetId: string, options: SemanticLayoutOptions = {}
70
+ ): Promise<{placements: SemanticPlacement<T>[]; metrics: {nodes: number; edges: number; steps: number; fallback: boolean}}> {
71
+ const {signal, obstacles = []} = options;
72
+ const yieldControl = options.yieldControl ?? (() => new Promise<void>(resolve => setTimeout(resolve, 0)));
73
+ check(signal);
74
+ if (scripts.length > semanticLayoutLimits.scripts || relations.length > semanticLayoutLimits.relations ||
75
+ obstacles.length > semanticLayoutLimits.scripts) throw new Error('Layout size limit exceeded');
76
+ const ordered = [...scripts].sort((a, b) => compareId(a.id, b.id));
77
+ if (new Set(ordered.map(s => s.id)).size !== ordered.length || [...ordered, ...obstacles].some(s =>
78
+ ![s.x, s.y, s.width, s.height].every(Number.isFinite) || s.width <= 0 || s.height <= 0)) {
79
+ throw new Error('Invalid script bounds');
80
+ }
81
+ const ids = ordered.map(s => s.id);
82
+ const outgoing = new Map(ids.map(id => [id, [] as string[]]));
83
+ const incoming = new Map(ids.map(id => [id, [] as string[]]));
84
+ const edges = new Set<string>();
85
+ for (const {source, destination, unresolved} of relations) {
86
+ if (unresolved || source.targetId !== targetId || destination?.targetId !== targetId ||
87
+ !outgoing.has(source.scriptId) || !incoming.has(destination.scriptId)) continue;
88
+ const key = JSON.stringify([source.scriptId, destination.scriptId]);
89
+ if (edges.has(key)) continue;
90
+ edges.add(key);
91
+ outgoing.get(source.scriptId)!.push(destination.scriptId);
92
+ incoming.get(destination.scriptId)!.push(source.scriptId);
93
+ }
94
+ for (const map of [outgoing, incoming]) for (const entries of map.values()) entries.sort(compareId);
95
+ const scc = components(ids, outgoing, incoming);
96
+ const owner = new Map(scc.flatMap((group, index) => group.map(id => [id, index] as const)));
97
+ const next = scc.map(() => new Set<number>()), before = scc.map(() => new Set<number>());
98
+ for (const [id, children] of outgoing) for (const child of children) {
99
+ const a = owner.get(id)!, b = owner.get(child)!;
100
+ if (a !== b) {next[a].add(b); before[b].add(a);}
101
+ }
102
+ const rank = scc.map(() => 0), remaining = before.map(set => set.size);
103
+ const ready = remaining.flatMap((n, i) => n ? [] : [i]);
104
+ for (let cursor = 0; cursor < ready.length; cursor++) {
105
+ const current = ready[cursor];
106
+ for (const child of next[current]) {
107
+ rank[child] = Math.max(rank[child], rank[current] + 1);
108
+ if (--remaining[child] === 0) ready.push(child);
109
+ }
110
+ }
111
+ // Separate weak components, including orphan scripts, into non-overlapping bands.
112
+ const band = new Map<string, number>();
113
+ let bandCount = 0;
114
+ for (const id of ids) {
115
+ if (band.has(id)) continue;
116
+ const stack = [id];
117
+ band.set(id, bandCount);
118
+ while (stack.length) {
119
+ const current = stack.pop()!;
120
+ for (const adjacent of [...outgoing.get(current)!, ...incoming.get(current)!]) {
121
+ if (!band.has(adjacent)) {band.set(adjacent, bandCount); stack.push(adjacent);}
122
+ }
123
+ }
124
+ bandCount++;
125
+ }
126
+ await yieldControl(); check(signal);
127
+ const widths = new Map<number, number>();
128
+ for (const script of ordered) {
129
+ const column = rank[owner.get(script.id)!];
130
+ widths.set(column, Math.max(widths.get(column) ?? 0, script.width));
131
+ }
132
+ const columnX: number[] = [];
133
+ let x = gap;
134
+ for (let column = 0; column < widths.size; column++) {
135
+ columnX[column] = x;
136
+ x += widths.get(column)! + gap * 2;
137
+ }
138
+ const placements: SemanticPlacement<T>[] = [];
139
+ let bandTop = gap;
140
+ for (let group = 0; group < bandCount; group++) {
141
+ const columns = new Map<number, T[]>();
142
+ for (const script of ordered) if (band.get(script.id) === group) {
143
+ const column = rank[owner.get(script.id)!];
144
+ const entries = columns.get(column) ?? [];
145
+ entries.push(script); columns.set(column, entries);
146
+ }
147
+ // Barycentric sweeps reduce crossings; SCC members stay contiguous.
148
+ const order = new Map<string, number>();
149
+ for (const entries of columns.values()) entries.forEach((s, i) => order.set(s.id, i));
150
+ const ranks = [...columns.keys()].sort((a, b) => a - b);
151
+ for (let sweep = 0; sweep < 4; sweep++) {
152
+ const neighbors = sweep % 2 ? outgoing : incoming;
153
+ for (const column of sweep % 2 ? [...ranks].reverse() : ranks) {
154
+ const mean = (id: string) => {
155
+ const members = scc[owner.get(id)!];
156
+ const values = members.flatMap(member => neighbors.get(member)!)
157
+ .filter(n => owner.get(n) !== owner.get(id)).map(n => order.get(n) ?? 0);
158
+ return values.length ? values.reduce((a, b) => a + b, 0) / values.length : order.get(members[0]) ?? 0;
159
+ };
160
+ const entries = columns.get(column)!;
161
+ entries.sort((a, b) => owner.get(a.id) === owner.get(b.id) ? compareId(a.id, b.id) :
162
+ mean(a.id) - mean(b.id) || owner.get(a.id)! - owner.get(b.id)!);
163
+ entries.forEach((s, i) => order.set(s.id, i));
164
+ }
165
+ }
166
+ let bottom = bandTop;
167
+ for (const column of ranks) {
168
+ let y = bandTop;
169
+ for (const script of columns.get(column)!) {
170
+ placements.push({script, x: columnX[column], y, column, group});
171
+ y += script.height + gap;
172
+ }
173
+ bottom = Math.max(bottom, y);
174
+ }
175
+ bandTop = bottom + gap * 2;
176
+ }
177
+ const engine = Matter.Engine.create({gravity: {x: 0, y: 0, scale: 0}, enableSleeping: false});
178
+ let steps = 0;
179
+ let fallback = false;
180
+ try {
181
+ const bodies = placements.map((p, index) => Matter.Bodies.rectangle(p.x + p.script.width / 2, p.y + p.script.height / 2,
182
+ p.script.width + gap, p.script.height + gap,
183
+ {id: index + 1, inertia: Infinity, restitution: 0, frictionAir: .35, friction: 0}));
184
+ const fixed = [...obstacles].sort((a, b) => compareId(a.id, b.id)).map((o, index) =>
185
+ Matter.Bodies.rectangle(o.x + o.width / 2, o.y + o.height / 2,
186
+ o.width + gap, o.height + gap, {id: bodies.length + index + 1, isStatic: true}));
187
+ Matter.Composite.add(engine.world, [...bodies, ...fixed]);
188
+ const byId = new Map(placements.map((p, i) => [p.script.id, i]));
189
+ // Attract related rectangles to the same reading band, without losing their rank.
190
+ const targets = placements.map(p => {
191
+ const parents = incoming.get(p.script.id)!.filter(id => owner.get(id) !== owner.get(p.script.id));
192
+ const centers = parents.map(id => {
193
+ const parent = placements[byId.get(id)!];
194
+ return parent.y + parent.script.height / 2;
195
+ });
196
+ return {x: p.x + p.script.width / 2, y: centers.length ?
197
+ centers.reduce((a, b) => a + b, 0) / centers.length : p.y + p.script.height / 2};
198
+ });
199
+ let stableSteps = 0;
200
+ for (; steps < semanticLayoutLimits.steps && bodies.length; steps++) {
201
+ if (steps % 8 === 0) {await yieldControl(); check(signal);}
202
+ bodies.forEach((body, i) => {
203
+ const target = targets[i];
204
+ Matter.Body.applyForce(body, body.position, {
205
+ x: (target.x - body.position.x) * body.mass * .00002,
206
+ y: (target.y - body.position.y) * body.mass * .00002
207
+ });
208
+ });
209
+ Matter.Engine.update(engine, 1000 / 60);
210
+ stableSteps = bodies.every(body => body.speed < .01) ? stableSteps + 1 : 0;
211
+ if (stableSteps >= 12) {steps++; break;}
212
+ }
213
+ if (steps === semanticLayoutLimits.steps) fallback = true;
214
+ // Snap ranks and preserve canonical within-column order after the physical relaxation.
215
+ let bottom = gap;
216
+ for (let group = 0; group < bandCount; group++) {
217
+ let groupBottom = bottom;
218
+ for (const column of [...widths.keys()].sort((a, b) => a - b)) {
219
+ let y = bottom;
220
+ for (const p of placements.filter(p => p.group === group && p.column === column)) {
221
+ const body = bodies[byId.get(p.script.id)!];
222
+ const relaxed = body.position.y - p.script.height / 2;
223
+ if (!Number.isFinite(relaxed)) fallback = true;
224
+ p.y = Math.ceil(Math.max(y, Number.isFinite(relaxed) ? relaxed : y));
225
+ // Keep loose comments fixed. Move past any intersecting obstacle.
226
+ let changed = true;
227
+ while (changed) {
228
+ changed = false;
229
+ for (const obstacle of obstacles) if (overlaps({...p.script, x: p.x, y: p.y}, obstacle)) {
230
+ p.y = obstacle.y + obstacle.height + gap;
231
+ changed = true; fallback = true;
232
+ }
233
+ }
234
+ y = p.y + p.script.height + gap;
235
+ }
236
+ groupBottom = Math.max(groupBottom, y);
237
+ }
238
+ bottom = groupBottom + gap * 2;
239
+ if (group % 32 === 0) {await yieldControl(); check(signal);}
240
+ }
241
+ const boxes = placements.map(p => ({...p.script, x: p.x, y: p.y}));
242
+ for (let i = 0; i < boxes.length; i++) {
243
+ if (![boxes[i].x, boxes[i].y].every(Number.isFinite) ||
244
+ boxes.slice(i + 1).some(b => overlaps(boxes[i], b)) || obstacles.some(o => overlaps(boxes[i], o))) {
245
+ throw new Error('Layout validation failed');
246
+ }
247
+ }
248
+ check(signal);
249
+ return {placements, metrics: {nodes: scripts.length, edges: edges.size, steps, fallback}};
250
+ } finally {
251
+ Matter.Composite.clear(engine.world, false);
252
+ Matter.Engine.clear(engine);
253
+ }
254
+ }
package/src/styles.css CHANGED
@@ -567,6 +567,10 @@
567
567
  --tw-script-relation-dash: 7 5;
568
568
  }
569
569
 
570
+ [data-script-relation="message"][data-wait="false"] {
571
+ --tw-script-relation-dash: 3.5 2.5;
572
+ }
573
+
570
574
  [data-script-relation-layer] {
571
575
  pointer-events: none;
572
576
  }
@@ -593,7 +597,7 @@
593
597
  stroke-opacity: 0.2;
594
598
  }
595
599
 
596
- /* Fade external connections without reducing the wait icon's opacity. */
600
+ /* Keep external connections faint, including during highlighting. */
597
601
  [data-script-relation-layer] > [data-script-relation][data-script-external] >
598
602
  :is(.tw-script-relation-line, .tw-script-relation-head, .tw-script-relation-badge) {
599
603
  opacity: 0.05;
@@ -634,24 +638,6 @@
634
638
  pointer-events: none;
635
639
  }
636
640
 
637
- .tw-script-relation-wait {
638
- pointer-events: visiblePainted;
639
- }
640
-
641
- .tw-script-relation-wait rect {
642
- fill: var(--ui-primary, Canvas);
643
- stroke: var(--tw-script-relation-stroke);
644
- stroke-width: 1;
645
- }
646
-
647
- .tw-script-relation-wait .tw-script-relation-wait-glyph {
648
- fill: none;
649
- stroke: var(--tw-script-relation-stroke);
650
- stroke-width: 1.4;
651
- stroke-linecap: round;
652
- stroke-linejoin: round;
653
- }
654
-
655
641
  .tw-script-relation-guide {
656
642
  position: absolute;
657
643
  z-index: 5;