@kubohiroya/turbowarp-plus-editor-code-views 0.18.0 → 0.20.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.
@@ -0,0 +1,440 @@
1
+ import {isFoldedDefinition} from './procedure-edits.ts';
2
+ import {readScriptRelations, type RelationTarget, type ScriptEndpoint, type ScriptRelation} from './script-relations.ts';
3
+
4
+ export interface ScriptRelationContext {
5
+ vm?: {
6
+ runtime?: {targets?: readonly RelationTarget[]; on?(name: string, listener: () => void): void;
7
+ removeListener?(name: string, listener: () => void): void};
8
+ on?(name: string, listener: () => void): void;
9
+ removeListener?(name: string, listener: () => void): void;
10
+ setEditingTarget?(id: string): void;
11
+ };
12
+ getTarget(): RelationTarget | undefined;
13
+ /** A child window receives the parent's graph rather than interpreting a partial project. */
14
+ getRelations?(): readonly ScriptRelation[];
15
+ getLocale?(): string;
16
+ getTargetName?(id: string): string | undefined;
17
+ navigate?(endpoint: ScriptEndpoint): void;
18
+ }
19
+
20
+ type Point = {x: number; y: number};
21
+ type Box = Point & {width: number; height: number};
22
+ type Anchor = {id: string; box: Box; point(side: 'left' | 'right', fraction: number): Point};
23
+ type Drawing = {relation: ScriptRelation; source?: Anchor; destination?: Anchor; count: number};
24
+ const ns = 'http://www.w3.org/2000/svg';
25
+ // Keep the same sixteen-unit hourglass as the call graph's relation badge.
26
+ const relationWaitGlyph = 'M1 1h14M1 15h14M2 1v3l12 8v3M14 1v3l-12 8v3M2 4h12M2 12h12';
27
+
28
+ /** Keep the badge beside the receiving end of the cubic curve, leaving its stroke visible. */
29
+ function waitBadgePoint(path: string, offset: number): Point {
30
+ const [sx, sy, ax, ay, bx, by, tx, ty] = path.match(/-?(?:\d*\.?\d+)(?:e[+-]?\d+)?/gi).map(Number);
31
+ const endX = tx - bx;
32
+ const endY = ty - by;
33
+ const dx = endX || endY ? endX : tx - sx;
34
+ const dy = endX || endY ? endY : ty - sy;
35
+ const length = Math.hypot(dx, dy) || 1;
36
+ const side = -dy < 0 || dy === 0 && dx > 0 ? -1 : 1;
37
+ return {x: tx - dx / length * offset * .75 - dy / length * offset * side,
38
+ y: ty - dy / length * offset * .75 + dx / length * offset * side};
39
+ }
40
+ const outlines = new WeakMap<SVGGeometryElement, {data: string; points: Point[]}>();
41
+
42
+ /** Intersect the actual outline, including a hat's overhang, rather than Blockly's layout padding. */
43
+ function outlinePoint(shape: SVGGeometryElement, bounds: Box, side: 'left' | 'right', fraction: number): Point {
44
+ const data = shape.getAttribute('d') ?? '';
45
+ let outline = outlines.get(shape);
46
+ if (!outline || outline.data !== data) {
47
+ const length = shape.getTotalLength();
48
+ const count = Math.max(32, Math.min(1024, Math.ceil(length / 2)));
49
+ const points = Array.from({length: count + 1}, (_, index) => {
50
+ const point = shape.getPointAtLength(length * index / count);
51
+ return {x: point.x, y: point.y};
52
+ });
53
+ outline = {data, points};
54
+ outlines.set(shape, outline);
55
+ }
56
+ const y = bounds.y + bounds.height * fraction;
57
+ let edge: number | undefined;
58
+ for (let index = 1; index < outline.points.length; index++) {
59
+ const before = outline.points[index - 1];
60
+ const after = outline.points[index];
61
+ if ((before.y <= y && after.y >= y) || (before.y >= y && after.y <= y)) {
62
+ const x = before.y === after.y ? (side === 'left' ? Math.min(before.x, after.x) : Math.max(before.x, after.x)) :
63
+ before.x + (after.x - before.x) * (y - before.y) / (after.y - before.y);
64
+ edge = edge === undefined ? x : side === 'left' ? Math.min(edge, x) : Math.max(edge, x);
65
+ }
66
+ }
67
+ return {x: edge ?? bounds.x + (side === 'right' ? bounds.width : 0), y};
68
+ }
69
+
70
+ // The shared workspace owns navigation even when an arrow is in a read-only preview.
71
+ const navigators = new WeakMap<object, (endpoint: ScriptEndpoint) => void>();
72
+ export function registerScriptRelationNavigation(vm: object, navigate: (endpoint: ScriptEndpoint) => void) {
73
+ navigators.set(vm, navigate);
74
+ return () => { if (navigators.get(vm) === navigate) navigators.delete(vm); };
75
+ }
76
+
77
+ const transform = (matrix: DOMMatrix, {x, y}: Point): Point => ({
78
+ x: matrix.a * x + matrix.c * y + matrix.e,
79
+ y: matrix.b * x + matrix.d * y + matrix.f
80
+ });
81
+
82
+ /** One renderer and semantic stylesheet serve live code, folded scripts, previews and serial layouts. */
83
+ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getLocale, getTargetName, navigate}: ScriptRelationContext & {
84
+ workspace: {
85
+ getInjectionDiv(): HTMLElement;
86
+ getCanvas(): SVGElement;
87
+ getParentSvg(): SVGElement;
88
+ getBlockById?(id: string): {width?: number; height?: number; getSvgRoot(): SVGElement | null} | null;
89
+ addChangeListener?(listener: (event: {type?: string}) => void): void;
90
+ removeChangeListener?(listener: (event: {type?: string}) => void): void;
91
+ centerOnBlock(id: string): void;
92
+ RTL?: boolean;
93
+ };
94
+ }) {
95
+ const injection = workspace.getInjectionDiv();
96
+ const document = injection.ownerDocument;
97
+ const view = document.defaultView;
98
+ const canvas = workspace.getCanvas();
99
+ const layer = document.createElementNS(ns, 'g');
100
+ layer.setAttribute('data-script-relation-layer', '');
101
+ layer.setAttribute('aria-hidden', 'true');
102
+ layer.setAttribute('pointer-events', 'none');
103
+ canvas.prepend(layer);
104
+ const destinations = document.createElement('div');
105
+ destinations.className = 'tw-script-relation-guide tw-script-relation-destinations';
106
+ destinations.dataset.scriptRelationGuide = '';
107
+ destinations.dataset.codeViewControl = '';
108
+ destinations.hidden = true;
109
+ // Blockly listens on the document; operating these controls must not delete or undo a block.
110
+ destinations.addEventListener('keydown', event => {
111
+ if (event.key !== 'Tab') event.stopPropagation();
112
+ });
113
+ injection.append(destinations);
114
+ let projection: SVGSVGElement | null = null;
115
+ let projectedLayer: SVGGElement | undefined;
116
+ let frame: number | undefined;
117
+ let disposed = false;
118
+ let dirty = true;
119
+ let graph: readonly ScriptRelation[] = [];
120
+ let selected: string | undefined;
121
+ let enabled = true;
122
+ const markedScripts = new Map<SVGElement, 'source' | 'related'>();
123
+ const text = () => /^ja(?:-|$)/i.test(getLocale?.() ?? document.documentElement.lang) ? {
124
+ title: '呼び出しの矢印', function: '関数呼び出し', message: 'メッセージ送信', wait: '送って待つ',
125
+ dynamic: '実行時に決定', missing: '接続先が見つかりません', ambiguous: '接続先が複数の定義に一致',
126
+ incoming: '呼び出し元', outgoing: '接続先', count: '件'
127
+ } : {
128
+ title: 'Script arrows', function: 'Function call', message: 'Message send', wait: 'Send and wait',
129
+ dynamic: 'Determined at runtime', missing: 'Destination not found', ambiguous: 'Multiple definitions match',
130
+ incoming: 'Source', outgoing: 'Destination', count: 'calls'
131
+ };
132
+
133
+ function element<K extends keyof SVGElementTagNameMap>(tag: K, attributes: Record<string, string> = {}) {
134
+ const node = document.createElementNS(ns, tag);
135
+ for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, value);
136
+ return node;
137
+ }
138
+
139
+ function markScripts(next: Map<SVGElement, 'source' | 'related'>) {
140
+ for (const [root, role] of markedScripts) {
141
+ if (next.get(root) !== role) root.removeAttribute(`data-script-relation-${role === 'source' ? 'drag-source' : 'related'}`);
142
+ }
143
+ for (const [root, role] of next) {
144
+ if (markedScripts.get(root) !== role) root.setAttribute(`data-script-relation-${role === 'source' ? 'drag-source' : 'related'}`, '');
145
+ }
146
+ markedScripts.clear();
147
+ for (const entry of next) markedScripts.set(...entry);
148
+ }
149
+
150
+ function blockRoot(id: string, roots: Map<string, SVGElement>) {
151
+ // Blockly lends a dragged stack to an SVG outside the canvas; the Block keeps its SVG identity.
152
+ return roots.get(id) ?? (!projection ? workspace.getBlockById?.(id)?.getSvgRoot() ?? undefined : undefined);
153
+ }
154
+
155
+ function go(endpoint: ScriptEndpoint) {
156
+ const target = getTarget();
157
+ const current = vm?.runtime?.targets?.find(item => item.id === endpoint.targetId);
158
+ if (vm && (!current || !current.blocks._blocks[endpoint.blockId])) return;
159
+ const handler = navigate ?? (vm && navigators.get(vm));
160
+ if (handler) handler(endpoint);
161
+ else {
162
+ if (endpoint.targetId !== target?.id) vm?.setEditingTarget?.(endpoint.targetId);
163
+ view.requestAnimationFrame(() => {
164
+ if (!disposed) workspace.centerOnBlock(endpoint.blockId);
165
+ });
166
+ }
167
+ }
168
+
169
+ function anchor(endpoint: ScriptEndpoint, target: RelationTarget, roots: Map<string, SVGElement>, inverse: DOMMatrix): Anchor | undefined {
170
+ if (endpoint.targetId !== target.id) return;
171
+ const top = blockRoot(endpoint.scriptId, roots);
172
+ // A script hidden by the one-script view is not the same as its folded body.
173
+ if (!top || !top.getClientRects().length || top.closest('[data-tw-plus-hidden]') ||
174
+ view.getComputedStyle(top).display === 'none') return;
175
+ const folded = isFoldedDefinition(target.blocks._blocks[endpoint.scriptId]);
176
+ let id = folded ? endpoint.scriptId : endpoint.blockId;
177
+ let root = blockRoot(id, roots);
178
+ // Native Blockly collapsing can also hide a caller inside a control block.
179
+ const visited = new Set<string>();
180
+ while (root && (!root.getClientRects().length || root.closest('[data-tw-plus-hidden]') ||
181
+ view.getComputedStyle(root).display === 'none') && !visited.has(id)) {
182
+ visited.add(id);
183
+ id = target.blocks._blocks[id]?.parent ?? '';
184
+ root = blockRoot(id, roots);
185
+ }
186
+ if (!root) return;
187
+ const path = root.querySelector<SVGGeometryElement>(':scope > .blocklyPath');
188
+ const matrix = (path ?? root as SVGGraphicsElement).getScreenCTM();
189
+ if (!matrix) return;
190
+ const block = workspace.getBlockById?.(id);
191
+ const bounds = path?.getBBox() ?? {x: workspace.RTL ? -(block?.width ?? 0) : 0,
192
+ y: 0, width: block?.width ?? 0, height: block?.height ?? 0};
193
+ if (!bounds.width || !bounds.height) return;
194
+ const convert = (point: Point) => transform(inverse, transform(matrix, point));
195
+ const first = convert(bounds);
196
+ const last = convert({x: bounds.x + bounds.width, y: bounds.y + bounds.height});
197
+ return {id, box: {x: Math.min(first.x, last.x), y: Math.min(first.y, last.y),
198
+ width: Math.abs(last.x - first.x), height: Math.abs(last.y - first.y)}, point(side, fraction) {
199
+ const localSide = first.x <= last.x ? side : side === 'left' ? 'right' : 'left';
200
+ return convert(path ? outlinePoint(path, bounds, localSide, fraction) :
201
+ {x: bounds.x + (localSide === 'right' ? bounds.width : 0), y: bounds.y + bounds.height * fraction});
202
+ }};
203
+ }
204
+
205
+ function render() {
206
+ frame = undefined;
207
+ if (disposed) return;
208
+ const strings = text();
209
+ const toolbox = injection.querySelector<HTMLElement>(':scope > .blocklyToolboxDiv');
210
+ const toolboxBounds = toolbox?.getBoundingClientRect();
211
+ const horizontal = toolbox?.hasAttribute('data-horizontal-block-palette');
212
+ // The horizontal palette sits above the blocks, including in the Editor's default layout.
213
+ destinations.style.top = `${horizontal ? Math.max(10, toolboxBounds.bottom - injection.getBoundingClientRect().top + 10) : 10}px`;
214
+ destinations.replaceChildren();
215
+ destinations.hidden = true;
216
+ const drawingRoot = projection ?? canvas;
217
+ const drawingLayer = projection ? projectedLayer : layer;
218
+ if (!drawingLayer) return;
219
+ drawingLayer.replaceChildren();
220
+ drawingLayer.removeAttribute('data-script-dragging');
221
+ layer.style.display = projection ? 'none' : '';
222
+ if (!enabled) { markScripts(new Map()); return; }
223
+ const target = getTarget();
224
+ if (!target) { markScripts(new Map()); return; }
225
+ const matrix = (drawingRoot as SVGGraphicsElement).getScreenCTM();
226
+ if (!matrix) { markScripts(new Map()); return; }
227
+ const inverse = matrix.inverse();
228
+ if (![inverse.a, inverse.b, inverse.c, inverse.d, inverse.e, inverse.f].every(Number.isFinite)) {
229
+ markScripts(new Map());
230
+ return;
231
+ }
232
+ if (getRelations) graph = getRelations();
233
+ else if (dirty) {
234
+ graph = readScriptRelations(vm?.runtime?.targets ?? [target]);
235
+ dirty = false;
236
+ }
237
+ const roots = new Map<string, SVGElement>();
238
+ for (const root of drawingRoot.querySelectorAll<SVGElement>('[data-id]')) roots.set(root.dataset.id, root);
239
+ const nativeSelection = [...roots.values()].find(root => root.classList.contains('blocklySelected'))?.dataset.id;
240
+ const emphasized = selected ?? scriptOf(nativeSelection, target);
241
+ const dragging = !projection && injection.querySelector<SVGElement>('[data-id].blocklyDragging');
242
+ const draggedIds = new Set<string>();
243
+ if (dragging) {
244
+ draggedIds.add(dragging.dataset.id);
245
+ for (const root of dragging.querySelectorAll<SVGElement>('[data-id]')) draggedIds.add(root.dataset.id);
246
+ }
247
+ const inDrag = (endpoint?: ScriptEndpoint) => Boolean(endpoint && endpoint.targetId === target.id && draggedIds.has(endpoint.blockId));
248
+ const incident = (relation: ScriptRelation) => inDrag(relation.source) || inDrag(relation.destination);
249
+ drawingLayer.toggleAttribute('data-script-dragging', Boolean(dragging));
250
+ const drawings = new Map<string, Drawing>();
251
+ for (const relation of graph) {
252
+ if (relation.source.targetId !== target.id && relation.destination?.targetId !== target.id) continue;
253
+ const source = anchor(relation.source, target, roots, inverse);
254
+ const destination = relation.destination && anchor(relation.destination, target, roots, inverse);
255
+ if (!source && !destination) continue;
256
+ const key = JSON.stringify([relation.kind, source?.id ?? relation.source,
257
+ destination?.id ?? relation.destination, relation.wait, relation.unresolved, relation.label]);
258
+ const existing = drawings.get(key);
259
+ if (existing) existing.count++;
260
+ else drawings.set(key, {relation, source, destination, count: 1});
261
+ }
262
+ const related = new Set<string>();
263
+ for (const relation of graph) if (dragging && incident(relation)) {
264
+ if (inDrag(relation.source) && relation.destination?.targetId === target.id && !inDrag(relation.destination)) {
265
+ related.add(relation.destination.scriptId);
266
+ }
267
+ if (inDrag(relation.destination) && relation.source.targetId === target.id && !inDrag(relation.source)) {
268
+ related.add(relation.source.scriptId);
269
+ }
270
+ }
271
+ const marked = new Map<SVGElement, 'source' | 'related'>();
272
+ if (dragging) marked.set(dragging, 'source');
273
+ for (const id of related) {
274
+ const root = blockRoot(id, roots);
275
+ if (root && root.getClientRects().length && !root.closest('[data-tw-plus-hidden]')) marked.set(root, 'related');
276
+ }
277
+ markScripts(marked);
278
+ // Frame the whole stack, including its body; the original block paint and runtime glow stay intact.
279
+ for (const [root, role] of marked) {
280
+ const bounds = root.getBoundingClientRect();
281
+ const first = transform(inverse, {x: bounds.left, y: bounds.top});
282
+ const last = transform(inverse, {x: bounds.right, y: bounds.bottom});
283
+ drawingLayer.append(element('rect', {x: String(first.x - 7), y: String(first.y - 7),
284
+ width: String(Math.max(0, last.x - first.x) + 14), height: String(Math.max(0, last.y - first.y) + 14),
285
+ rx: '10', class: 'tw-script-relation-script-highlight', 'data-emphasis': role}));
286
+ }
287
+ for (const {relation, source, destination, count} of drawings.values()) {
288
+ const highlighted = dragging ? incident(relation) :
289
+ emphasized && (emphasized === relation.source.scriptId || emphasized === relation.destination?.scriptId);
290
+ let external: HTMLButtonElement | undefined;
291
+ if ((!source || !destination) && highlighted) {
292
+ external = document.createElement('button');
293
+ external.type = 'button';
294
+ external.dataset.scriptRelation = relation.kind;
295
+ const endpoint = source ? relation.destination : relation.source;
296
+ const name = endpoint && (getTargetName?.(endpoint.targetId) ??
297
+ vm?.runtime?.targets?.find(item => item.id === endpoint.targetId)?.getName?.());
298
+ const reason = relation.unresolved && strings[relation.unresolved];
299
+ external.textContent = `${name ? `${name} · ` : ''}` +
300
+ `${relation.label}${reason ? ` · ${reason}` : ''}${relation.kind === 'message' && relation.wait ? ' ⏳' : ''}${count > 1 ? ` ×${count}` : ''}`;
301
+ external.disabled = !endpoint;
302
+ external.setAttribute('aria-label', `${strings[relation.kind]}: ${external.textContent}`);
303
+ external.toggleAttribute('data-highlighted', Boolean(highlighted));
304
+ if (endpoint) external.addEventListener('click', () => go(endpoint));
305
+ destinations.append(external);
306
+ }
307
+ // Anchor an external link to the viewport edge; the list itself remains keyboard accessible.
308
+ const area = (projection ?? workspace.getParentSvg()).getBoundingClientRect();
309
+ const local = source ?? destination;
310
+ const edgeX = source ? area.right - 12 : area.left + 12;
311
+ const screenY = transform(matrix, {x: local.box.x, y: local.box.y + local.box.height / 2}).y;
312
+ const edge = transform(inverse, {x: edgeX, y: Math.max(area.top + 12, Math.min(area.bottom - 12, screenY))});
313
+ const forward = !source || !destination || destination.box.x >= source.box.x + source.box.width / 2;
314
+ let start = source ? source.point(forward ? 'right' : 'left', 0.5) : edge;
315
+ let end = destination ? destination.point(forward ? 'left' : 'right', Math.min(0.5, 24 / destination.box.height)) : edge;
316
+ let direction = forward ? 1 : -1;
317
+ const bend = Math.max(36, Math.abs(end.x - start.x) / 2);
318
+ let path = `M ${start.x} ${start.y} C ${start.x + bend * direction} ${start.y}, ${end.x - bend * direction} ${end.y}, ${end.x} ${end.y}`;
319
+ const recursive = source && destination && relation.source.scriptId === relation.destination.scriptId &&
320
+ relation.source.targetId === relation.destination.targetId;
321
+ let badgePoint = {x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 - 6};
322
+ if (recursive) {
323
+ start = source.point('right', 0.75);
324
+ end = destination.point('right', 0.25);
325
+ const outside = Math.max(start.x, end.x) + 72;
326
+ path = `M ${start.x} ${start.y} C ${outside} ${start.y + 32}, ${outside} ${end.y - 32}, ${end.x} ${end.y}`;
327
+ direction = -1;
328
+ badgePoint = {x: outside - 14, y: (start.y + end.y) / 2 - 6};
329
+ }
330
+ const group = element('g', {
331
+ 'data-script-relation': relation.kind,
332
+ 'data-source-block': source?.id ?? relation.source.blockId,
333
+ 'data-source-call': relation.source.blockId,
334
+ 'data-destination-block': destination?.id ?? relation.destination?.blockId ?? '',
335
+ 'data-count': String(count),
336
+ 'data-wait': String(relation.wait)
337
+ });
338
+ group.toggleAttribute('data-highlighted', Boolean(highlighted));
339
+ group.toggleAttribute('data-recursive', Boolean(recursive));
340
+ const description = element('title');
341
+ const waiting = relation.kind === 'message' && relation.wait;
342
+ description.textContent = `${strings[relation.kind]}: ${relation.label}${waiting ? ` · ${strings.wait}` : ''}`;
343
+ group.append(description, element('path', {
344
+ class: 'tw-script-relation-line',
345
+ d: path
346
+ }), element('path', {
347
+ class: 'tw-script-relation-head',
348
+ d: `M ${end.x - 9 * direction} ${end.y - 5} L ${end.x} ${end.y} L ${end.x - 9 * direction} ${end.y + 5}`
349
+ }));
350
+ if (waiting) {
351
+ const scale = Math.hypot(matrix.a, matrix.b) || 1;
352
+ const point = waitBadgePoint(path, 24 / scale);
353
+ badgePoint = {x: point.x + 16 / scale, y: point.y + 4 / scale};
354
+ const badge = element('g', {class: 'tw-script-relation-wait', 'aria-label': strings.wait,
355
+ transform: `translate(${point.x} ${point.y}) scale(${1 / scale})`});
356
+ const title = element('title');
357
+ title.textContent = strings.wait;
358
+ badge.append(title, element('rect', {x: '-10', y: '-10', width: '20', height: '20', rx: '4'}),
359
+ element('path', {class: 'tw-script-relation-wait-glyph', d: relationWaitGlyph, transform: 'translate(-8 -8)'}));
360
+ group.append(badge);
361
+ }
362
+ if (count > 1) {
363
+ const badge = element('text', {x: String(badgePoint.x), y: String(badgePoint.y),
364
+ class: 'tw-script-relation-badge', 'text-anchor': waiting ? 'start' : 'middle'});
365
+ badge.textContent = `×${count}`;
366
+ group.append(badge);
367
+ }
368
+ drawingLayer.append(group);
369
+ }
370
+ destinations.hidden = !destinations.childElementCount;
371
+ }
372
+
373
+ function update() {
374
+ if (!disposed && frame === undefined) frame = view.requestAnimationFrame(render);
375
+ }
376
+ function changed() { dirty = true; update(); }
377
+ function scriptOf(id: string | undefined, target = getTarget()) {
378
+ const blocks = target?.blocks._blocks;
379
+ const visited = new Set<string>();
380
+ while (id && blocks?.[id]?.parent && !visited.has(id)) { visited.add(id); id = blocks[id].parent; }
381
+ return id;
382
+ }
383
+ function selectedScript(event: Event) {
384
+ if ((event.target as Element).closest?.('[data-script-relation-guide]')) return;
385
+ const node = (event.target as Element).closest?.('[data-id]') as SVGElement | null;
386
+ const id = scriptOf(node?.dataset.id);
387
+ if (id !== selected) { selected = id; update(); }
388
+ }
389
+ const mutations = new view.MutationObserver(records => {
390
+ if (records.some(record => record.target !== layer && !layer.contains(record.target) &&
391
+ !record.attributeName?.startsWith('data-script-relation-'))) update();
392
+ });
393
+ mutations.observe(canvas, {attributes: true, childList: true, subtree: true});
394
+ // Its CSS translation changes on every drag step, while the workspace canvas stays untouched.
395
+ const dragSurface = injection.querySelector('.blocklyBlockDragSurface');
396
+ if (dragSurface) mutations.observe(dragSurface, {attributes: true, childList: true, subtree: true});
397
+ const resized = new view.ResizeObserver(update);
398
+ resized.observe(injection);
399
+ const toolbox = injection.querySelector('.blocklyToolboxDiv');
400
+ if (toolbox) resized.observe(toolbox);
401
+ injection.addEventListener('pointerover', selectedScript);
402
+ injection.addEventListener('pointerdown', selectedScript);
403
+ const language = new view.MutationObserver(update);
404
+ language.observe(document.documentElement, {attributes: true, attributeFilter: ['lang']});
405
+ vm?.runtime?.on?.('PROJECT_CHANGED', changed);
406
+ vm?.on?.('targetsUpdate', changed);
407
+ vm?.on?.('workspaceUpdate', changed);
408
+ workspace.addChangeListener?.(changed);
409
+ update();
410
+ return {
411
+ update: changed,
412
+ get enabled() { return enabled; },
413
+ setEnabled(value: boolean) { enabled = value; update(); },
414
+ setProjection(svg: SVGSVGElement | null) {
415
+ if (svg === projection) { update(); return; }
416
+ projectedLayer?.remove();
417
+ projection = svg;
418
+ projectedLayer = svg ? element('g', {'data-script-relation-layer': '', 'aria-hidden': 'true', 'pointer-events': 'none'}) : undefined;
419
+ if (projectedLayer) svg.prepend(projectedLayer);
420
+ update();
421
+ },
422
+ dispose() {
423
+ disposed = true;
424
+ markScripts(new Map());
425
+ if (frame !== undefined) view.cancelAnimationFrame(frame);
426
+ mutations.disconnect();
427
+ resized.disconnect();
428
+ language.disconnect();
429
+ workspace.removeChangeListener?.(changed);
430
+ vm?.runtime?.removeListener?.('PROJECT_CHANGED', changed);
431
+ vm?.removeListener?.('targetsUpdate', changed);
432
+ vm?.removeListener?.('workspaceUpdate', changed);
433
+ injection.removeEventListener('pointerover', selectedScript);
434
+ injection.removeEventListener('pointerdown', selectedScript);
435
+ projectedLayer?.remove();
436
+ layer.remove();
437
+ destinations.remove();
438
+ }
439
+ };
440
+ }
@@ -0,0 +1,57 @@
1
+ type ScriptFitWorkspace = {
2
+ RTL?: boolean;
3
+ options?: {zoomOptions?: {minScale?: number; maxScale?: number}};
4
+ scale: number;
5
+ getInjectionDiv(): HTMLElement;
6
+ getBlockById(id: string): {
7
+ getSvgRoot(): SVGGraphicsElement | null;
8
+ getRelativeToSurfaceXY(): {x: number; y: number};
9
+ } | null;
10
+ getMetrics(): {viewWidth: number; viewHeight: number; contentLeft: number; contentTop: number} | null;
11
+ resize?(): void;
12
+ setScale(scale: number): void;
13
+ scrollbar?: {set(x: number, y: number): void};
14
+ };
15
+
16
+ const padding = 24;
17
+ const positive = (value: number | undefined, fallback: number) =>
18
+ Number.isFinite(value) && value > 0 ? value : fallback;
19
+
20
+ /** Fit a visible script once. Hidden or not-yet-rendered workspaces can retry after their layout settles. */
21
+ export function fitScriptInWorkspace(workspace: ScriptFitWorkspace, scriptId: string,
22
+ blocks: {svgResize(workspace: ScriptFitWorkspace): void}): boolean {
23
+ const injection = workspace.getInjectionDiv();
24
+ const block = workspace.getBlockById(scriptId);
25
+ if (!block || !injection.clientWidth || !injection.clientHeight || !workspace.scrollbar) return false;
26
+ const root = block.getSvgRoot();
27
+ if (!root) return false;
28
+ // A split can have its new DOM size while Blockly's cached SVG size still belongs to the old pane.
29
+ blocks.svgResize(workspace);
30
+ workspace.resize?.();
31
+ const bounds = root.getBBox();
32
+ const metrics = workspace.getMetrics();
33
+ if (!metrics?.viewWidth || !metrics.viewHeight || !(bounds.width > 0) || !(bounds.height > 0)) return false;
34
+ // SVG bounds include nested reporters and the hat's overhang, but exclude folded, hidden bodies.
35
+ const origin = block.getRelativeToSurfaceXY();
36
+ const left = origin.x + bounds.x;
37
+ const top = origin.y + bounds.y;
38
+ const zoom = workspace.options?.zoomOptions;
39
+ const workspaceMin = positive(zoom?.minScale, 0.01);
40
+ const workspaceMax = Math.max(workspaceMin, positive(zoom?.maxScale, Infinity));
41
+ const minScale = Math.min(Math.max(0.5, workspaceMin), workspaceMax);
42
+ const maxScale = Math.max(minScale, Math.min(1.25, workspaceMax));
43
+ const fit = Math.min(Math.max(1, metrics.viewWidth - padding * 2) / bounds.width,
44
+ Math.max(1, metrics.viewHeight - padding * 2) / bounds.height);
45
+ const scale = Math.max(minScale, Math.min(maxScale, fit));
46
+ workspace.setScale(scale);
47
+ const scaled = workspace.getMetrics();
48
+ if (!scaled) return false;
49
+ const width = bounds.width * workspace.scale;
50
+ const height = bounds.height * workspace.scale;
51
+ const x = width > scaled.viewWidth - padding * 2 && workspace.RTL ?
52
+ scaled.viewWidth - padding - width : Math.max(padding, (scaled.viewWidth - width) / 2);
53
+ const y = workspace.scale <= minScale ? padding : Math.max(padding, (scaled.viewHeight - height) / 2);
54
+ workspace.scrollbar.set(left * workspace.scale - scaled.contentLeft - x,
55
+ top * workspace.scale - scaled.contentTop - y);
56
+ return true;
57
+ }
@@ -3,6 +3,7 @@ import {paintScripts, readScripts, type LayoutWorkspace} from './script-layout-w
3
3
  import {openRearrangement, type RearrangementContext} from './script-layout-dialog.ts';
4
4
  import {attachScriptViewMenu, type ScriptViewMenuBlocks, type ScriptViewMenuWorkspace} from './script-view-menu.ts';
5
5
  import type {PresentationElements} from './preview-chrome.ts';
6
+ import {attachScriptArrows, type ScriptRelationContext} from './script-arrows.ts';
6
7
 
7
8
  export type ScriptView = 'free' | 'z' | 'n';
8
9
 
@@ -15,6 +16,7 @@ interface ViewOptions {
15
16
  canShowBlock?(): boolean;
16
17
  onChange?(view: ScriptView): void;
17
18
  hasWorkspaceMenu?(): boolean;
19
+ relations?: ScriptRelationContext;
18
20
  }
19
21
 
20
22
  const choices = [
@@ -24,7 +26,8 @@ const choices = [
24
26
  ] as const;
25
27
 
26
28
  export function attachScriptView({
27
- workspace, ScratchBlocks, getLocale, mount, initialView = 'free', canShowBlock, onChange, hasWorkspaceMenu = () => true
29
+ workspace, ScratchBlocks, getLocale, mount, initialView = 'free', canShowBlock, onChange, hasWorkspaceMenu = () => true,
30
+ relations: relationContext
28
31
  }: ViewOptions) {
29
32
  const injection = workspace.getInjectionDiv();
30
33
  const host = mount ?? injection;
@@ -40,7 +43,10 @@ export function attachScriptView({
40
43
  let view = initialView;
41
44
  let frame: number | undefined;
42
45
  const svg = workspace.getParentSvg();
43
- const observer = new window.MutationObserver(update);
46
+ const observer = new window.MutationObserver(records => {
47
+ if (records.some(record => !(record.target as Element).closest?.('[data-script-relation-layer]'))) update();
48
+ });
49
+ const relations = relationContext && attachScriptArrows({workspace, getLocale, ...relationContext});
44
50
  const japanese = () => /^ja(?:-|$)/i.test(getLocale());
45
51
 
46
52
  function labels() {
@@ -78,6 +84,7 @@ export function attachScriptView({
78
84
  surface.style.setProperty('--tw-script-view-right', !horizontal && bounds.right >= right - 2 ? `${bounds.width}px` : '0px');
79
85
  }
80
86
  paintScripts(contents, arrangeScripts(readScripts(workspace), view, 'vertical'), workspace.scale || 1);
87
+ relations?.setProjection(contents.querySelector('svg'));
81
88
  }
82
89
 
83
90
  function update() {
@@ -92,7 +99,10 @@ export function attachScriptView({
92
99
  surface.hidden = view === 'free';
93
100
  svg.toggleAttribute('data-script-serial', view !== 'free');
94
101
  labels();
95
- if (view === 'free') contents.replaceChildren();
102
+ if (view === 'free') {
103
+ relations?.setProjection(null);
104
+ contents.replaceChildren();
105
+ }
96
106
  else {
97
107
  observer.observe(workspace.getCanvas(), {attributes: true, childList: true, subtree: true});
98
108
  surface.scrollTo(0, 0);
@@ -124,6 +134,7 @@ export function attachScriptView({
124
134
  setView(initialView);
125
135
  return {
126
136
  update,
137
+ relations,
127
138
  labels,
128
139
  get view() { return view; },
129
140
  setView,
@@ -133,6 +144,7 @@ export function attachScriptView({
133
144
  language.disconnect();
134
145
  if (frame !== undefined) window.cancelAnimationFrame(frame);
135
146
  menu.dispose();
147
+ relations?.dispose();
136
148
  surface.remove();
137
149
  svg.removeAttribute('data-script-serial');
138
150
  }
@@ -173,7 +185,8 @@ export function attachDockedScriptLayout({vm, workspace, ScratchBlocks, canUse,
173
185
  (!group || group.classList.contains('dv-active-group')));
174
186
  };
175
187
  const view = attachScriptView({workspace, ScratchBlocks, getLocale: () => injection.ownerDocument.documentElement.lang || locale,
176
- canShowBlock: canArrange});
188
+ canShowBlock: canArrange, relations: {vm: vm as ScriptRelationContext['vm'],
189
+ getTarget: () => vm.editingTarget as ReturnType<ScriptRelationContext['getTarget']>}});
177
190
  host.setAttribute('data-code-hover-surface', '');
178
191
  let dialog: ReturnType<typeof openRearrangement> | undefined;
179
192
  const attachment = {