@kubohiroya/turbowarp-plus-editor-code-views 0.21.3 → 0.22.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.
@@ -1,6 +1,6 @@
1
1
  const alignmentTolerance = 24;
2
2
  const spacing = 32;
3
- export function arrangeScripts(scripts, order, direction) {
3
+ export function arrangeScripts(scripts, order, direction, gap = spacing) {
4
4
  const bandAxis = order === 'z' ? 'y' : 'x';
5
5
  const scanAxis = order === 'z' ? 'x' : 'y';
6
6
  const compare = (a, b, first, second) => a[first] - b[first] || a[second] - b[second] || (a.id < b.id ? -1 : Number(a.id > b.id));
@@ -14,12 +14,12 @@ export function arrangeScripts(scripts, order, direction) {
14
14
  else
15
15
  bands.push([script]);
16
16
  }
17
- let offset = spacing;
17
+ let offset = gap;
18
18
  return bands.flatMap(band => band.sort((a, b) => compare(a, b, scanAxis, bandAxis))).map(script => {
19
19
  const vertical = direction === 'vertical';
20
20
  const x = vertical ? spacing : offset;
21
21
  const y = vertical ? offset : spacing;
22
- offset += Math.ceil(vertical ? script.height : script.width) + spacing;
22
+ offset += Math.ceil(vertical ? script.height : script.width) + gap;
23
23
  return { script, x, y };
24
24
  });
25
25
  }
@@ -0,0 +1,8 @@
1
+ export type ScriptProjection = {
2
+ surface: HTMLElement;
3
+ svg: SVGSVGElement;
4
+ };
5
+ export declare const getScriptProjection: (workspace: object) => ScriptProjection;
6
+ export declare function setScriptProjection(workspace: {
7
+ getInjectionDiv(): HTMLElement;
8
+ }, projection?: ScriptProjection): void;
@@ -0,0 +1,10 @@
1
+ const projections = new WeakMap();
2
+ export const getScriptProjection = (workspace) => projections.get(workspace);
3
+ export function setScriptProjection(workspace, projection) {
4
+ if (projection)
5
+ projections.set(workspace, projection);
6
+ else
7
+ projections.delete(workspace);
8
+ const container = workspace.getInjectionDiv();
9
+ container.dispatchEvent(new container.ownerDocument.defaultView.Event('scriptprojectionchange'));
10
+ }
@@ -35,6 +35,7 @@ export interface ScriptViewMenuWorkspace {
35
35
  }
36
36
  interface MenuConfig {
37
37
  label: string;
38
+ options?: MenuOption[];
38
39
  choices: (MenuOption & {
39
40
  checked: boolean;
40
41
  })[];
@@ -108,7 +108,7 @@ export function attachScriptViewMenu({ ContextMenu, WidgetDiv }, workspace, host
108
108
  // Only extend the options collected for this workspace, after the existing add-ons.
109
109
  ContextMenu.populate_ = (options, rtl) => {
110
110
  const config = getMenu();
111
- const menu = populate.call(ContextMenu, [...options, triggerOption(config.label)], rtl);
111
+ const menu = populate.call(ContextMenu, [...options, triggerOption(config.label), ...(config.options ?? [])], rtl);
112
112
  addSubmenu(menu, options.length, config, rtl, ContextMenu);
113
113
  return menu;
114
114
  };
@@ -126,7 +126,9 @@ export function attachScriptViewMenu({ ContextMenu, WidgetDiv }, workspace, host
126
126
  event.stopPropagation();
127
127
  const config = getMenu();
128
128
  const rtl = workspace.RTL;
129
- const menu = ContextMenu.populate_([triggerOption(config.label)], rtl);
129
+ const menu = ContextMenu.populate_([triggerOption(config.label), ...(config.options ?? []).map(option => ({ ...option,
130
+ callback() { WidgetDiv.hideIfOwner(surface); option.callback(); }
131
+ }))], rtl);
130
132
  const outside = new document.defaultView.AbortController();
131
133
  WidgetDiv.show(surface, rtl, () => {
132
134
  outside.abort();
@@ -0,0 +1,4 @@
1
+ /** Reuse the script editor: its root stays at its original project coordinates. */
2
+ export declare function openSerialScriptEditor(vm: object, target: any, id: string, document: Document, locale: string): {
3
+ dispose: () => void;
4
+ };
@@ -0,0 +1,43 @@
1
+ import { getCodeSession } from "./workspace.js";
2
+ /** Reuse the script editor: its root stays at its original project coordinates. */
3
+ export function openSerialScriptEditor(vm, target, id, document, locale) {
4
+ const bridge = getCodeSession(vm).bridge;
5
+ if (!bridge || !target?.blocks._blocks[id])
6
+ return;
7
+ const dialog = document.createElement('dialog');
8
+ dialog.className = 'tw-serial-script-editor';
9
+ const title = document.createElement('h2');
10
+ title.textContent = /^ja(?:-|$)/i.test(locale) ? 'スクリプトを編集' : 'Edit script';
11
+ title.id = `script-editor-${document.defaultView.crypto.randomUUID()}`;
12
+ dialog.setAttribute('aria-labelledby', title.id);
13
+ const area = document.createElement('div');
14
+ area.dataset.serialScriptEditor = id;
15
+ const close = document.createElement('button');
16
+ close.type = 'button';
17
+ close.textContent = /^ja(?:-|$)/i.test(locale) ? '閉じる' : 'Close';
18
+ dialog.append(title, area, close);
19
+ document.body.append(dialog);
20
+ dialog.showModal();
21
+ let editor;
22
+ try {
23
+ editor = bridge.editProcedure(area, { target, definitionId: id, editable: true, locale });
24
+ }
25
+ catch (error) {
26
+ dialog.close();
27
+ dialog.remove();
28
+ throw error;
29
+ }
30
+ let closed = false;
31
+ const dispose = () => {
32
+ if (closed)
33
+ return;
34
+ closed = true;
35
+ editor.flush();
36
+ editor.dispose();
37
+ dialog.close();
38
+ dialog.remove();
39
+ };
40
+ close.addEventListener('click', dispose);
41
+ dialog.addEventListener('cancel', event => { event.preventDefault(); dispose(); });
42
+ return { dispose };
43
+ }
@@ -1,3 +1,4 @@
1
+ import { getScriptProjection } from "./script-projection.js";
1
2
  const svgNamespace = 'http://www.w3.org/2000/svg';
2
3
  /** A cached overview drawn from public block geometry; offscreen culling never changes the project map. */
3
4
  export function attachWorkspaceOverview({ workspace, ScratchBlocks, zoomHeight = 0, getCorner, watermark, getWatermark }) {
@@ -34,25 +35,46 @@ export function attachWorkspaceOverview({ workspace, ScratchBlocks, zoomHeight =
34
35
  function refreshShapes() {
35
36
  const retained = new Set();
36
37
  const additions = document.createDocumentFragment();
37
- for (const block of workspace.getAllBlocks(false)) {
38
- const root = block.getSvgRoot();
39
- if (!root || !canvas.contains(root) || root.closest('[data-tw-plus-hidden]'))
40
- continue;
41
- const source = root.querySelector(':scope > .blocklyPath');
42
- const data = source?.getAttribute('d');
43
- if (!data)
44
- continue;
45
- retained.add(block.id);
46
- let path = paths.get(block.id);
38
+ const paint = (id, data, fill, transform) => {
39
+ retained.add(id);
40
+ let path = paths.get(id);
47
41
  if (!path) {
48
42
  path = element('path');
49
- paths.set(block.id, path);
43
+ paths.set(id, path);
50
44
  additions.append(path);
51
45
  }
52
- const position = block.getRelativeToSurfaceXY();
53
46
  attribute(path, 'd', data);
54
- attribute(path, 'fill', source.getAttribute('fill') || block.getColour());
55
- attribute(path, 'transform', `translate(${position.x} ${position.y})${block.RTL ? ' scale(-1 1)' : ''}`);
47
+ attribute(path, 'fill', fill);
48
+ attribute(path, 'transform', transform);
49
+ };
50
+ const projection = getScriptProjection(workspace);
51
+ if (projection) {
52
+ const inverse = projection.svg.getScreenCTM()?.inverse();
53
+ if (inverse)
54
+ for (const source of projection.svg.querySelectorAll('.blocklyPath')) {
55
+ if (source.closest('[data-tw-plus-hidden]'))
56
+ continue;
57
+ const id = source.closest('[data-id]')?.getAttribute('data-id');
58
+ const data = source.getAttribute('d');
59
+ const matrix = source.getScreenCTM();
60
+ if (!id || !data || !matrix)
61
+ continue;
62
+ const transform = inverse.multiply(matrix);
63
+ paint(id, data, source.getAttribute('fill') || view.getComputedStyle(source).fill, `matrix(${transform.a} ${transform.b} ${transform.c} ${transform.d} ${transform.e} ${transform.f})`);
64
+ }
65
+ }
66
+ else {
67
+ for (const block of workspace.getAllBlocks(false)) {
68
+ const root = block.getSvgRoot();
69
+ if (!root || !canvas.contains(root) || root.closest('[data-tw-plus-hidden]'))
70
+ continue;
71
+ const source = root.querySelector(':scope > .blocklyPath');
72
+ const data = source?.getAttribute('d');
73
+ if (!data)
74
+ continue;
75
+ const position = block.getRelativeToSurfaceXY();
76
+ paint(block.id, data, source.getAttribute('fill') || block.getColour(), `translate(${position.x} ${position.y})${block.RTL ? ' scale(-1 1)' : ''}`);
77
+ }
56
78
  }
57
79
  for (const [id, path] of paths)
58
80
  if (!retained.has(id)) {
@@ -73,12 +95,17 @@ export function attachWorkspaceOverview({ workspace, ScratchBlocks, zoomHeight =
73
95
  return;
74
96
  }
75
97
  const scale = workspace.scale;
76
- const x = metrics.viewLeft / scale, y = metrics.viewTop / scale;
77
- const width = metrics.viewWidth / scale, height = metrics.viewHeight / scale;
98
+ const projection = getScriptProjection(workspace);
99
+ const x = projection ? projection.surface.scrollLeft / scale : metrics.viewLeft / scale;
100
+ const y = projection ? projection.surface.scrollTop / scale : metrics.viewTop / scale;
101
+ const width = (projection ? projection.surface.clientWidth : metrics.viewWidth) / scale;
102
+ const height = (projection ? projection.surface.clientHeight : metrics.viewHeight) / scale;
78
103
  const content = metrics.contentWidth > 0 && metrics.contentHeight > 0;
79
- const area = content ? { x: metrics.contentLeft / scale, y: metrics.contentTop / scale,
80
- width: metrics.contentWidth / scale, height: metrics.contentHeight / scale } : { x, y, width, height };
81
- if (!workspace.scrollbar && content) {
104
+ const box = projection?.svg.viewBox.baseVal;
105
+ const area = box ? { x: box.x, y: box.y, width: Math.max(box.width, width), height: Math.max(box.height, height) } :
106
+ content ? { x: metrics.contentLeft / scale, y: metrics.contentTop / scale,
107
+ width: metrics.contentWidth / scale, height: metrics.contentHeight / scale } : { x, y, width, height };
108
+ if (!projection && !workspace.scrollbar && content) {
82
109
  const right = Math.max(x + width, area.x + area.width), bottom = Math.max(y + height, area.y + area.height);
83
110
  area.x = Math.min(x, area.x);
84
111
  area.y = Math.min(y, area.y);
@@ -102,9 +129,9 @@ export function attachWorkspaceOverview({ workspace, ScratchBlocks, zoomHeight =
102
129
  if (needsShapes)
103
130
  refreshShapes();
104
131
  map.toggleAttribute('hidden', false);
105
- const box = `${area.x} ${area.y} ${area.width} ${area.height}`;
106
- attribute(map, 'viewBox', box);
107
- attribute(clip, 'viewBox', box);
132
+ const viewBox = `${area.x} ${area.y} ${area.width} ${area.height}`;
133
+ attribute(map, 'viewBox', viewBox);
134
+ attribute(clip, 'viewBox', viewBox);
108
135
  for (const [name, value] of Object.entries(area))
109
136
  attribute(clip, name, value);
110
137
  for (const [name, value] of Object.entries({ x, y, width, height }))
@@ -144,9 +171,21 @@ export function attachWorkspaceOverview({ workspace, ScratchBlocks, zoomHeight =
144
171
  const resize = new view.ResizeObserver(schedule);
145
172
  resize.observe(container);
146
173
  const events = new view.AbortController();
174
+ let projectedSVG;
175
+ container.addEventListener('scriptprojectionchange', () => {
176
+ const next = getScriptProjection(workspace)?.svg;
177
+ needsShapes ||= next !== projectedSVG;
178
+ projectedSVG = next;
179
+ schedule();
180
+ }, { signal: events.signal });
147
181
  view.addEventListener('resize', schedule, { signal: events.signal });
148
182
  view.addEventListener('scroll', schedule, { signal: events.signal, passive: true });
149
183
  const moveView = (left, top) => {
184
+ const projection = getScriptProjection(workspace);
185
+ if (projection) {
186
+ projection.surface.scrollTo(left * workspace.scale, top * workspace.scale);
187
+ return;
188
+ }
150
189
  const metrics = workspace.getMetrics();
151
190
  if (!metrics || !workspace.scrollbar)
152
191
  return;
@@ -156,14 +195,16 @@ export function attachWorkspaceOverview({ workspace, ScratchBlocks, zoomHeight =
156
195
  let pointer;
157
196
  const point = (event, inverse) => new view.DOMPoint(event.clientX, event.clientY).matrixTransform(inverse);
158
197
  map.addEventListener('pointerdown', event => {
159
- if (!event.isPrimary || event.button !== 0 || pointer || !workspace.scrollbar)
198
+ const projection = getScriptProjection(workspace);
199
+ if (!event.isPrimary || event.button !== 0 || pointer || (!projection && !workspace.scrollbar))
160
200
  return;
161
201
  const matrix = map.getScreenCTM(), metrics = workspace.getMetrics();
162
202
  if (!matrix || !metrics)
163
203
  return;
164
204
  const inverse = matrix.inverse();
165
205
  pointer = { id: event.pointerId, x: event.clientX, y: event.clientY, start: point(event, inverse), inverse,
166
- left: metrics.viewLeft / workspace.scale, top: metrics.viewTop / workspace.scale,
206
+ left: projection ? projection.surface.scrollLeft / workspace.scale : metrics.viewLeft / workspace.scale,
207
+ top: projection ? projection.surface.scrollTop / workspace.scale : metrics.viewTop / workspace.scale,
167
208
  viewport: event.target === viewport, moved: false };
168
209
  map.setPointerCapture(event.pointerId);
169
210
  }, { signal: events.signal });
@@ -190,8 +231,9 @@ export function attachWorkspaceOverview({ workspace, ScratchBlocks, zoomHeight =
190
231
  move(event);
191
232
  if (!pointer.moved) {
192
233
  const current = point(event, pointer.inverse), metrics = workspace.getMetrics();
234
+ const projection = getScriptProjection(workspace);
193
235
  if (metrics)
194
- moveView(current.x - metrics.viewWidth / (2 * workspace.scale), current.y - metrics.viewHeight / (2 * workspace.scale));
236
+ moveView(current.x - (projection ? projection.surface.clientWidth : metrics.viewWidth) / (2 * workspace.scale), current.y - (projection ? projection.surface.clientHeight : metrics.viewHeight) / (2 * workspace.scale));
195
237
  ScratchBlocks.hideChaff(true);
196
238
  }
197
239
  }
@@ -100,6 +100,7 @@ export declare function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspa
100
100
  focusBlock?: string;
101
101
  }): {
102
102
  workspace: any;
103
+ flush(): void;
103
104
  showBlock(id: string): void;
104
105
  dispose(): void;
105
106
  };
package/dist/workspace.js CHANGED
@@ -163,7 +163,7 @@ function attachScriptVisibility({ vm, blocks, workspace, homeDocument, onError }
163
163
  const labels = () => japanese() ? { fold: '折りたたみ', unfold: '折りたたみを解除', folded: '折りたたみ中' } :
164
164
  { fold: 'Fold', unfold: 'Unfold', folded: 'Folded' };
165
165
  const vmBlock = (id) => vm.editingTarget?.blocks._blocks[id];
166
- const isFolded = (block) => isHatBlock(block) && isFoldedDefinition(vmBlock(block.id));
166
+ const isFolded = (block) => isFoldedDefinition(vmBlock(block.id));
167
167
  let focus;
168
168
  // The GUI can attach the code area again; what an earlier attachment left on the workspace is not its own.
169
169
  const own = (name) => Object.prototype.hasOwnProperty.call(workspace, name) && !workspace[name][focusOverride] ?
@@ -364,7 +364,7 @@ function attachScriptVisibility({ vm, blocks, workspace, homeDocument, onError }
364
364
  /** Paint the folded scripts of a read-only workspace, such as the preview of a code view. */
365
365
  function paintPreviewFolds(blocks, preview, target, label) {
366
366
  for (const top of preview.getTopBlocks(false)) {
367
- paintFold(top, isHatBlock(top) && isFoldedDefinition(target.blocks._blocks[top.id]), label);
367
+ paintFold(top, isFoldedDefinition(target.blocks._blocks[top.id]), label);
368
368
  }
369
369
  }
370
370
  export function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspace, options, onError, presentationElements = null }) {
@@ -988,6 +988,7 @@ function attachProcedureEditor({ vm, blocks, workspace, options, onError, homeDo
988
988
  modal.appendChild(popup);
989
989
  return {
990
990
  workspace: editor,
991
+ flush() { blocks.Events.fireNow_(); },
991
992
  showBlock(id) {
992
993
  pendingBlock = id;
993
994
  reveal();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-code-views",
3
- "version": "0.21.3",
3
+ "version": "0.22.0",
4
4
  "description": "Code views for TurboWarp Plus Editor: code in tabs and windows, the detached block palette, script layout and block field editing",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
package/src/code-pane.ts CHANGED
@@ -427,26 +427,64 @@ export function readScriptRelationGraph(targets: readonly RelationTarget[], Scra
427
427
  /**
428
428
  * Add “Show this function” at the top of the menu of every block that calls a function, in the code area and
429
429
  * in the script editors. `find` names the function a block calls, if any; `open` shows it.
430
+ * With `scriptEditor`, free-layout blocks first offer to edit their own containing script.
430
431
  */
431
- export function attachFunctionCallMenu(ScratchBlocks, {label, find, open}: {
432
+ export function attachFunctionCallMenu(ScratchBlocks, {label, find, open, scriptEditor}: {
432
433
  label(): string;
433
434
  find(blockId: string): string | undefined;
434
435
  open(functionId: string): void;
436
+ scriptEditor?: {vm: any; locale: string;
437
+ open(scriptId: string, blockId: string, section: 'functions' | 'calls'): void};
435
438
  }) {
436
439
  const prototype = ScratchBlocks.BlockSvg.prototype;
437
440
  const showContextMenu = prototype.showContextMenu_;
438
441
  const patched = function (event) {
439
442
  const functionId = this.isInFlyout ? undefined : find(this.id);
440
- if (!functionId) return showContextMenu.call(this, event);
443
+ const target = scriptEditor?.vm.editingTarget;
444
+ const layout = scriptEditor && getDockedScriptLayout(scriptEditor.vm);
445
+ const script = scriptEditor && !this.isInFlyout && !this.workspace.options.readOnly &&
446
+ this.workspace === ScratchBlocks.getMainWorkspace?.() && layout?.view.view === 'free' &&
447
+ layout.canArrange() && !getCodeSession(scriptEditor.vm).bridge?.focusedScript ? this.getRootBlock() : undefined;
448
+ const scriptId = script && target?.blocks._blocks[script.id] ? script.id : undefined;
449
+ if (!functionId && !scriptId) return showContextMenu.call(this, event);
450
+ const blockId = this.id;
451
+ const japanese = scriptEditor && /^ja(?:-|$)/i.test(scriptEditor.locale);
452
+ const scriptOptions = scriptId ? [
453
+ {section: 'functions' as const, text: japanese ?
454
+ 'このスクリプトを個別の画面で編集する' : 'Edit this script in a separate view'},
455
+ {section: 'calls' as const, text: japanese ?
456
+ 'このスクリプトの呼び出し関係を開く' : 'Open relationships for this script'}
457
+ ].map(({section, text}) => ({text, twPlusMenuIcon: section, separator: false, enabled: true, callback() {
458
+ if (scriptEditor.vm.editingTarget === target && target.blocks._blocks[scriptId]) {
459
+ scriptEditor.open(scriptId, blockId, section);
460
+ }
461
+ }})) : [];
441
462
  const owned = Object.prototype.hasOwnProperty.call(this, 'customContextMenu');
442
463
  const custom = this.customContextMenu;
443
464
  this.customContextMenu = function (options) {
444
465
  custom?.call(this, options);
445
- options.unshift({text: label(), enabled: true, callback: () => open(functionId)});
466
+ if (functionId) options.unshift({text: label(), enabled: true, callback: () => open(functionId)});
467
+ options.unshift(...scriptOptions);
468
+ };
469
+ const {ContextMenu} = ScratchBlocks;
470
+ const populate = scriptOptions.length ? ContextMenu.populate_ : undefined;
471
+ if (scriptOptions.length) ContextMenu.populate_ = function (options, rtl) {
472
+ // Addons reorder ContextMenu.show's options after customContextMenu. Prioritize the final list,
473
+ // in place so their separator indices and the host's icon decoration still use the same order.
474
+ for (const priority of [...scriptOptions].reverse()) {
475
+ const index = options.findIndex(option => option.callback === priority.callback);
476
+ if (index > 0) options.unshift(...options.splice(index, 1));
477
+ }
478
+ for (const option of scriptOptions) option.separator = false;
479
+ if (options.length > 2) options[2].separator = true;
480
+ const menu = populate.call(this, options, rtl);
481
+ menu.getChildAt(2)?.getElement().classList.add('tw-script-editor-menu-divider');
482
+ return menu;
446
483
  };
447
484
  try {
448
485
  return showContextMenu.call(this, event);
449
486
  } finally {
487
+ if (scriptOptions.length) ContextMenu.populate_ = populate;
450
488
  if (owned) this.customContextMenu = custom;
451
489
  else delete this.customContextMenu;
452
490
  }
@@ -1,8 +1,10 @@
1
1
  // SPDX-License-Identifier: MPL-2.0
2
2
  import React from 'react';
3
3
 
4
- export function createContextMenuIcons({enabled, addonMessages, styles}: {
4
+ export function createContextMenuIcons({enabled, addonMessages, styles, renderSectionIcon, createSectionIcon}: {
5
5
  enabled: boolean; addonMessages: Record<string, string>; styles: Record<string, string>;
6
+ renderSectionIcon?(section: 'functions' | 'calls', className: string): React.ReactNode;
7
+ createSectionIcon?(document: Document, section: 'functions' | 'calls', className: string): SVGSVGElement;
6
8
  }) {
7
9
  const paths = {
8
10
  open: 'M13 4h7v7m0-7-9 9m-1-8H4v15h15v-6',
@@ -118,7 +120,8 @@ export function createContextMenuIcons({enabled, addonMessages, styles}: {
118
120
  return actions[id];
119
121
  };
120
122
 
121
- const renderMenuIcon = action => paths[action] ? React.createElement('svg', {
123
+ const renderMenuIcon = action => (action === 'functions' || action === 'calls') && renderSectionIcon ?
124
+ renderSectionIcon(action, styles.icon) : paths[action] ? React.createElement('svg', {
122
125
  className: styles.icon, 'aria-hidden': 'true', focusable: 'false', viewBox: '0 0 24 24'
123
126
  }, React.createElement('path', {d: paths[action]})) : null;
124
127
 
@@ -128,6 +131,9 @@ export function createContextMenuIcons({enabled, addonMessages, styles}: {
128
131
  const installed = new WeakSet();
129
132
 
130
133
  function createContextMenuIcon (document, action) {
134
+ if ((action === 'functions' || action === 'calls') && createSectionIcon) {
135
+ return createSectionIcon(document, action, styles.icon);
136
+ }
131
137
  if (!Object.hasOwn(paths, action)) return null;
132
138
  const icon = document.createElementNS(svgNamespace, 'svg');
133
139
  icon.setAttribute('class', styles.icon);
@@ -23,12 +23,31 @@ export interface ScriptRelationContext {
23
23
  type Point = {x: number; y: number};
24
24
  type Box = Point & {width: number; height: number};
25
25
  type Anchor = {id: string; box: Box; point(side: 'left' | 'right', fraction: number): Point};
26
- type Drawing = {relation: ScriptRelation; source?: Anchor; destination?: Anchor; count: number};
26
+ type Drawing = {relation: ScriptRelation; source?: Anchor; destination?: Anchor; count: number;
27
+ serialRoute?: {right: number; top: number; clearance: number}};
28
+
29
+ function roundedRoute(points: Point[], radius: number) {
30
+ let path = `M ${points[0].x} ${points[0].y}`;
31
+ for (let index = 1; index < points.length - 1; index++) {
32
+ const before = points[index - 1], corner = points[index], after = points[index + 1];
33
+ const entering = Math.hypot(corner.x - before.x, corner.y - before.y);
34
+ const leaving = Math.hypot(after.x - corner.x, after.y - corner.y);
35
+ const size = Math.min(radius, entering / 2, leaving / 2);
36
+ if (!size) {path += ` L ${corner.x} ${corner.y}`; continue;}
37
+ const first = {x: corner.x + (before.x - corner.x) * size / entering,
38
+ y: corner.y + (before.y - corner.y) * size / entering};
39
+ const last = {x: corner.x + (after.x - corner.x) * size / leaving,
40
+ y: corner.y + (after.y - corner.y) * size / leaving};
41
+ path += ` L ${first.x} ${first.y} Q ${corner.x} ${corner.y} ${last.x} ${last.y}`;
42
+ }
43
+ const end = points.at(-1);
44
+ return `${path} L ${end.x} ${end.y}`;
45
+ }
27
46
  const ns = 'http://www.w3.org/2000/svg';
28
47
  // Keep the same sixteen-unit hourglass as the call graph's relation badge.
29
48
  const relationWaitGlyph = 'M1 1h14M1 15h14M2 1v3l12 8v3M14 1v3l-12 8v3M2 4h12M2 12h12';
30
49
 
31
- /** Keep the badge beside the receiving end of the cubic curve, leaving its stroke visible. */
50
+ /** Keep the badge beside the receiving end of the path, leaving its stroke visible. */
32
51
  function waitBadgePoint(path: string, offset: number): Point {
33
52
  const values = path.match(/-?(?:\d*\.?\d+)(?:e[+-]?\d+)?/gi).map(Number);
34
53
  const [sx, sy] = values;
@@ -150,6 +169,8 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
150
169
  let geometryChanged = true;
151
170
  let lastMatrix: DOMMatrix | undefined;
152
171
  let edgeDrawings: {key: string; drawing: Drawing; group: SVGGElement; highlighted: boolean}[] = [];
172
+ let viewportDrawings: {drawing: Drawing; visible: boolean}[] = [];
173
+ let measuredAnchors = new Map<string, Anchor | undefined>();
153
174
  const renderedGroups = new WeakMap<SVGGElement, Map<string, SVGGElement>>();
154
175
  const syncTransform = (matrix: DOMMatrix) => {
155
176
  // Workspace dragging lends the two native canvases to a separate SVG which must keep exactly two children.
@@ -214,15 +235,25 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
214
235
  if (endpoint.targetId !== target.id) return;
215
236
  const top = blockRoot(endpoint.scriptId, roots);
216
237
  // A script hidden by the one-script view is not the same as its folded body.
217
- if (!top || !top.getClientRects().length || top.closest('[data-tw-plus-hidden]') ||
218
- view.getComputedStyle(top).display === 'none') return;
238
+ if (!top || top.closest('[data-tw-plus-hidden]')) return;
239
+ // Native viewport culling hides the whole stack, but its real endpoints still exist.
240
+ const culled = !projection && top.style.display === 'none';
241
+ if (!culled && !top.getClientRects().length) return;
219
242
  const folded = isFoldedDefinition(target.blocks._blocks[endpoint.scriptId]);
220
243
  let id = folded ? endpoint.scriptId : endpoint.blockId;
221
244
  let root = blockRoot(id, roots);
222
245
  // Native Blockly collapsing can also hide a caller inside a control block.
223
246
  const visited = new Set<string>();
224
- while (root && (!root.getClientRects().length || root.closest('[data-tw-plus-hidden]') ||
225
- view.getComputedStyle(root).display === 'none') && !visited.has(id)) {
247
+ const hidden = (node: SVGElement) => {
248
+ if (node.closest('[data-tw-plus-hidden]')) return true;
249
+ if (!culled) return !node.getClientRects().length || view.getComputedStyle(node).display === 'none';
250
+ // A collapsed parent below the culled stack still needs its visible proxy anchor.
251
+ for (let ancestor = node; ancestor && ancestor !== top; ancestor = ancestor.parentElement as unknown as SVGElement) {
252
+ if (view.getComputedStyle(ancestor).display === 'none') return true;
253
+ }
254
+ return false;
255
+ };
256
+ while (root && hidden(root) && !visited.has(id)) {
226
257
  visited.add(id);
227
258
  id = target.blocks._blocks[id]?.parent ?? '';
228
259
  root = blockRoot(id, roots);
@@ -249,7 +280,7 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
249
280
  }};
250
281
  }
251
282
 
252
- function arrowGeometry({relation, source, destination, count}: Drawing, matrix: DOMMatrix, inverse: DOMMatrix,
283
+ function arrowGeometry({relation, source, destination, count, serialRoute}: Drawing, matrix: DOMMatrix, inverse: DOMMatrix,
253
284
  area: DOMRect, highlighted: boolean) {
254
285
  // Anchor an external link to the viewport edge; the list itself remains keyboard accessible.
255
286
  const local = source ?? destination;
@@ -274,6 +305,14 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
274
305
  ` C ${left} ${top}, ${left} ${end.y}, ${end.x} ${end.y}`;
275
306
  badgePoint = {x: middle, y: top - 6};
276
307
  }
308
+ if (serialRoute && source && destination) {
309
+ const {right, top, clearance} = serialRoute;
310
+ // Leave room beside every script before turning vertically, then return through the gap above the hat.
311
+ const approach = end.x - clearance;
312
+ path = roundedRoute([start, {x: right, y: start.y}, {x: right, y: top},
313
+ {x: approach, y: top}, {x: approach, y: end.y}, end], clearance);
314
+ badgePoint = {x: right, y: (start.y + top) / 2};
315
+ }
277
316
  const head = `M ${end.x - 9} ${end.y - 5} L ${end.x} ${end.y} L ${end.x - 9} ${end.y + 5}`;
278
317
  let waitTransform: string | undefined;
279
318
  if (relation.kind === 'message' && relation.wait) {
@@ -327,6 +366,16 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
327
366
  return group;
328
367
  }
329
368
 
369
+ function inViewport({source, destination}: Drawing, matrix: DOMMatrix, area: DOMRect) {
370
+ return [source, destination].some(anchor => {
371
+ if (!anchor) return false;
372
+ const first = transform(matrix, anchor.box);
373
+ const last = transform(matrix, {x: anchor.box.x + anchor.box.width, y: anchor.box.y + anchor.box.height});
374
+ return Math.max(first.x, last.x) > area.left && Math.min(first.x, last.x) < area.right &&
375
+ Math.max(first.y, last.y) > area.top && Math.min(first.y, last.y) < area.bottom;
376
+ });
377
+ }
378
+
330
379
  function render() {
331
380
  frame = undefined;
332
381
  if (disposed) return;
@@ -353,7 +402,9 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
353
402
  const area = (projection ?? workspace.getParentSvg()).getBoundingClientRect();
354
403
  const sameScale = lastMatrix && matrix.a === lastMatrix.a && matrix.b === lastMatrix.b &&
355
404
  matrix.c === lastMatrix.c && matrix.d === lastMatrix.d;
356
- if (!geometryChanged && !projection && sameScale) {
405
+ const reuseAnchors = !geometryChanged && !projection && sameScale;
406
+ if (reuseAnchors &&
407
+ viewportDrawings.every(item => item.visible === inViewport(item.drawing, matrix, area))) {
357
408
  const geometry = edgeDrawings.map(item => ({...item,
358
409
  shape: arrowGeometry(item.drawing, matrix, inverse, area, item.highlighted)}));
359
410
  syncTransform(matrix);
@@ -373,6 +424,8 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
373
424
  geometryChanged = false;
374
425
  lastMatrix = matrix;
375
426
  edgeDrawings = [];
427
+ viewportDrawings = [];
428
+ if (!reuseAnchors) measuredAnchors = new Map();
376
429
  const paint: SVGElement[] = [];
377
430
  const guides = document.createDocumentFragment();
378
431
  const previousGroups = renderedGroups.get(drawingLayer);
@@ -395,11 +448,10 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
395
448
  const inDrag = (endpoint?: ScriptEndpoint) => Boolean(endpoint && endpoint.targetId === target.id && draggedIds.has(endpoint.blockId));
396
449
  const incident = (relation: ScriptRelation) => inDrag(relation.source) || inDrag(relation.destination);
397
450
  const drawings = new Map<string, Drawing>();
398
- const anchors = new Map<string, Anchor | undefined>();
399
451
  const measuredAnchor = (endpoint: ScriptEndpoint) => {
400
452
  const key = `${endpoint.targetId}\0${endpoint.scriptId}\0${endpoint.blockId}`;
401
- if (!anchors.has(key)) anchors.set(key, anchor(endpoint, target, roots, inverse));
402
- return anchors.get(key);
453
+ if (!measuredAnchors.has(key)) measuredAnchors.set(key, anchor(endpoint, target, roots, inverse));
454
+ return measuredAnchors.get(key);
403
455
  };
404
456
  for (const relation of graph) {
405
457
  if (!visibility[relation.kind]) continue;
@@ -413,6 +465,35 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
413
465
  if (existing) existing.count++;
414
466
  else drawings.set(key, {relation, source, destination, count: 1});
415
467
  }
468
+ if (projection) {
469
+ const unit = 1 / (Math.hypot(matrix.a, matrix.b) || 1);
470
+ const scripts = new Map<string, Box>();
471
+ for (const root of projection.querySelectorAll<SVGGraphicsElement>('[data-script-view-block]')) {
472
+ const rect = root.getBoundingClientRect();
473
+ const first = transform(inverse, {x: rect.left, y: rect.top});
474
+ const last = transform(inverse, {x: rect.right, y: rect.bottom});
475
+ scripts.set(root.getAttribute('data-script-view-block'),
476
+ {x: first.x, y: first.y, width: last.x - first.x, height: last.y - first.y});
477
+ }
478
+ const rightEdge = [...scripts.values()].reduce((edge, box) => Math.max(edge, box.x + box.width), 0);
479
+ let lane = 0;
480
+ for (const drawing of drawings.values()) {
481
+ if (!drawing.source || !drawing.destination) continue;
482
+ const destination = scripts.get(drawing.relation.destination.scriptId);
483
+ if (!destination) continue;
484
+ drawing.serialRoute = {right: rightEdge + (96 + lane * 16) * unit,
485
+ top: destination.y - (14 + lane % 4 * 6) * unit, clearance: 8 * unit};
486
+ lane++;
487
+ }
488
+ // Reserve actual scrollable SVG width for the right-hand routes while preserving the block scale.
489
+ const box = projection.viewBox.baseVal;
490
+ const width = Math.ceil(rightEdge + (112 + Math.max(0, lane - 1) * 16) * unit);
491
+ if (lane && width > box.width) {
492
+ const scale = Math.hypot(matrix.a, matrix.b);
493
+ projection.setAttribute('viewBox', `${box.x} ${box.y} ${width} ${box.height}`);
494
+ projection.setAttribute('width', String(width * scale));
495
+ }
496
+ }
416
497
  const related = new Set<string>();
417
498
  for (const relation of graph) if (visibility[relation.kind] && dragging && incident(relation)) {
418
499
  if (inDrag(relation.source) && relation.destination?.targetId === target.id && !inDrag(relation.destination)) {
@@ -428,7 +509,7 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
428
509
  const root = blockRoot(id, roots);
429
510
  if (root && root.getClientRects().length && !root.closest('[data-tw-plus-hidden]')) marked.set(root, 'related');
430
511
  }
431
- // Frame the whole stack, including its body; the original block paint and runtime glow stay intact.
512
+ // Shade the whole stack, including its body; the original block paint and runtime glow stay intact.
432
513
  for (const [root, role] of marked) {
433
514
  const bounds = root.getBoundingClientRect();
434
515
  const first = transform(inverse, {x: bounds.left, y: bounds.top});
@@ -438,6 +519,9 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
438
519
  rx: '10', class: 'tw-script-relation-script-highlight', 'data-emphasis': role}));
439
520
  }
440
521
  for (const [key, drawing] of drawings) {
522
+ const visible = inViewport(drawing, matrix, area);
523
+ viewportDrawings.push({drawing, visible});
524
+ if (!visible) continue;
441
525
  const {relation, source, destination, count} = drawing;
442
526
  const highlighted = dragging ? incident(relation) :
443
527
  emphasized && (emphasized === relation.source.scriptId || emphasized === relation.destination?.scriptId);
@@ -489,6 +573,8 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
489
573
  if (destinations.childElementCount) destinations.replaceChildren();
490
574
  destinations.hidden = true;
491
575
  edgeDrawings = [];
576
+ viewportDrawings = [];
577
+ measuredAnchors.clear();
492
578
  lastMatrix = undefined;
493
579
  renderedGroups.delete(layer);
494
580
  if (projectedLayer) renderedGroups.delete(projectedLayer);