@kubohiroya/turbowarp-plus-editor-code-views 0.19.0 → 0.21.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.
@@ -5,7 +5,9 @@ const ns = 'http://www.w3.org/2000/svg';
5
5
  const relationWaitGlyph = 'M1 1h14M1 15h14M2 1v3l12 8v3M14 1v3l-12 8v3M2 4h12M2 12h12';
6
6
  /** Keep the badge beside the receiving end of the cubic curve, leaving its stroke visible. */
7
7
  function waitBadgePoint(path, offset) {
8
- const [sx, sy, ax, ay, bx, by, tx, ty] = path.match(/-?(?:\d*\.?\d+)(?:e[+-]?\d+)?/gi).map(Number);
8
+ const values = path.match(/-?(?:\d*\.?\d+)(?:e[+-]?\d+)?/gi).map(Number);
9
+ const [sx, sy] = values;
10
+ const [bx, by, tx, ty] = values.slice(-4);
9
11
  const endX = tx - bx;
10
12
  const endY = ty - by;
11
13
  const dx = endX || endY ? endX : tx - sx;
@@ -15,33 +17,58 @@ function waitBadgePoint(path, offset) {
15
17
  return { x: tx - dx / length * offset * .75 - dy / length * offset * side,
16
18
  y: ty - dy / length * offset * .75 + dx / length * offset * side };
17
19
  }
18
- const outlines = new WeakMap();
20
+ const outlines = new Map();
19
21
  /** Intersect the actual outline, including a hat's overhang, rather than Blockly's layout padding. */
20
22
  function outlinePoint(shape, bounds, side, fraction) {
21
23
  const data = shape.getAttribute('d') ?? '';
22
- let outline = outlines.get(shape);
23
- if (!outline || outline.data !== data) {
24
+ let outline = outlines.get(data);
25
+ if (!outline) {
24
26
  const length = shape.getTotalLength();
25
- const count = Math.max(32, Math.min(1024, Math.ceil(length / 2)));
27
+ const count = Math.max(24, Math.min(96, Math.ceil(length / 8)));
26
28
  const points = Array.from({ length: count + 1 }, (_, index) => {
27
- const point = shape.getPointAtLength(length * index / count);
28
- return { x: point.x, y: point.y };
29
+ const distance = length * index / count;
30
+ const point = shape.getPointAtLength(distance);
31
+ return { x: point.x, y: point.y, distance };
29
32
  });
30
- outline = { data, points };
31
- outlines.set(shape, outline);
33
+ outline = { points, cuts: new Map() };
34
+ if (outlines.size >= 512)
35
+ outlines.delete(outlines.keys().next().value);
36
+ outlines.set(data, outline);
32
37
  }
33
38
  const y = bounds.y + bounds.height * fraction;
39
+ const key = `${side}:${y}`;
40
+ const cached = outline.cuts.get(key);
41
+ if (cached)
42
+ return cached;
34
43
  let edge;
35
44
  for (let index = 1; index < outline.points.length; index++) {
36
45
  const before = outline.points[index - 1];
37
46
  const after = outline.points[index];
38
47
  if ((before.y <= y && after.y >= y) || (before.y >= y && after.y <= y)) {
39
- const x = before.y === after.y ? (side === 'left' ? Math.min(before.x, after.x) : Math.max(before.x, after.x)) :
40
- before.x + (after.x - before.x) * (y - before.y) / (after.y - before.y);
48
+ let x;
49
+ if (before.y === after.y)
50
+ x = side === 'left' ? Math.min(before.x, after.x) : Math.max(before.x, after.x);
51
+ else {
52
+ // Refine only a crossing instead of sampling every two units along the entire outline.
53
+ let low = before.distance, high = after.distance;
54
+ for (let step = 0; step < 12; step++) {
55
+ const middle = (low + high) / 2;
56
+ const point = shape.getPointAtLength(middle);
57
+ x = point.x;
58
+ if (Math.abs(point.y - y) < .001)
59
+ break;
60
+ if ((point.y < y) === (before.y < y))
61
+ low = middle;
62
+ else
63
+ high = middle;
64
+ }
65
+ }
41
66
  edge = edge === undefined ? x : side === 'left' ? Math.min(edge, x) : Math.max(edge, x);
42
67
  }
43
68
  }
44
- return { x: edge ?? bounds.x + (side === 'right' ? bounds.width : 0), y };
69
+ const point = { x: edge ?? bounds.x + (side === 'right' ? bounds.width : 0), y };
70
+ outline.cuts.set(key, point);
71
+ return point;
45
72
  }
46
73
  // The shared workspace owns navigation even when an arrow is in a read-only preview.
47
74
  const navigators = new WeakMap();
@@ -55,7 +82,7 @@ const transform = (matrix, { x, y }) => ({
55
82
  y: matrix.b * x + matrix.d * y + matrix.f
56
83
  });
57
84
  /** One renderer and semantic stylesheet serve live code, folded scripts, previews and serial layouts. */
58
- export function attachScriptArrows({ workspace, vm, getTarget, getRelations, getLocale, getTargetName, navigate }) {
85
+ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, getLocale, getTargetName, navigate, initialVisibility }) {
59
86
  const injection = workspace.getInjectionDiv();
60
87
  const document = injection.ownerDocument;
61
88
  const view = document.defaultView;
@@ -64,7 +91,8 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
64
91
  layer.setAttribute('data-script-relation-layer', '');
65
92
  layer.setAttribute('aria-hidden', 'true');
66
93
  layer.setAttribute('pointer-events', 'none');
67
- canvas.prepend(layer);
94
+ // Keep arrow mutations outside the block canvas observed by the minimap and serial previews.
95
+ canvas.before(layer);
68
96
  const destinations = document.createElement('div');
69
97
  destinations.className = 'tw-script-relation-guide tw-script-relation-destinations';
70
98
  destinations.dataset.scriptRelationGuide = '';
@@ -84,6 +112,25 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
84
112
  let graph = [];
85
113
  let selected;
86
114
  let enabled = true;
115
+ let visibility = { ...initialVisibility ?? { function: true, message: true } };
116
+ let geometryChanged = true;
117
+ let lastMatrix;
118
+ let edgeDrawings = [];
119
+ const renderedGroups = new WeakMap();
120
+ const syncTransform = (matrix) => {
121
+ // Workspace dragging lends the two native canvases to a separate SVG which must keep exactly two children.
122
+ // Leave our layer in place and project that surface's transform back into its original parent instead.
123
+ const parent = layer.parentElement;
124
+ const relative = canvas.parentElement !== layer.parentElement && parent.getScreenCTM()?.inverse().multiply(matrix);
125
+ const transform = relative ? `matrix(${relative.a},${relative.b},${relative.c},${relative.d},${relative.e},${relative.f})` :
126
+ canvas.getAttribute('transform');
127
+ if (layer.getAttribute('transform') !== transform) {
128
+ if (transform === null)
129
+ layer.removeAttribute('transform');
130
+ else
131
+ layer.setAttribute('transform', transform);
132
+ }
133
+ };
87
134
  const markedScripts = new Map();
88
135
  const text = () => /^ja(?:-|$)/i.test(getLocale?.() ?? document.documentElement.lang) ? {
89
136
  title: '呼び出しの矢印', function: '関数呼び出し', message: 'メッセージ送信', wait: '送って待つ',
@@ -167,39 +214,113 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
167
214
  const convert = (point) => transform(inverse, transform(matrix, point));
168
215
  const first = convert(bounds);
169
216
  const last = convert({ x: bounds.x + bounds.width, y: bounds.y + bounds.height });
217
+ const points = new Map();
170
218
  return { id, box: { x: Math.min(first.x, last.x), y: Math.min(first.y, last.y),
171
219
  width: Math.abs(last.x - first.x), height: Math.abs(last.y - first.y) }, point(side, fraction) {
172
220
  const localSide = first.x <= last.x ? side : side === 'left' ? 'right' : 'left';
173
- return convert(path ? outlinePoint(path, bounds, localSide, fraction) :
174
- { x: bounds.x + (localSide === 'right' ? bounds.width : 0), y: bounds.y + bounds.height * fraction });
221
+ const key = `${localSide}:${fraction}`;
222
+ if (!points.has(key))
223
+ points.set(key, convert(path ? outlinePoint(path, bounds, localSide, fraction) :
224
+ { x: bounds.x + (localSide === 'right' ? bounds.width : 0), y: bounds.y + bounds.height * fraction }));
225
+ return points.get(key);
175
226
  } };
176
227
  }
228
+ function arrowGeometry({ relation, source, destination, count }, matrix, inverse, area, highlighted) {
229
+ // Anchor an external link to the viewport edge; the list itself remains keyboard accessible.
230
+ const local = source ?? destination;
231
+ const edgeX = source ? area.right - 12 : area.left + 12;
232
+ const screenY = transform(matrix, { x: local.box.x, y: local.box.y + local.box.height / 2 }).y;
233
+ const edge = transform(inverse, { x: edgeX, y: Math.max(area.top + 12, Math.min(area.bottom - 12, screenY)) });
234
+ let start = source ? source.point('right', 0.5) : edge;
235
+ let end = destination ? destination.point('left', Math.min(0.5, 24 / destination.box.height)) : edge;
236
+ const bend = Math.max(36, Math.abs(end.x - start.x) / 2);
237
+ let path = `M ${start.x} ${start.y} C ${start.x + bend} ${start.y}, ${end.x - bend} ${end.y}, ${end.x} ${end.y}`;
238
+ const recursive = source && destination && relation.source.scriptId === relation.destination.scriptId &&
239
+ relation.source.targetId === relation.destination.targetId;
240
+ let badgePoint = { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 - 6 };
241
+ if (recursive) {
242
+ start = source.point('right', 0.75);
243
+ end = destination.point('left', 0.25);
244
+ const right = Math.max(source.box.x + source.box.width, destination.box.x + destination.box.width) + 144;
245
+ const left = Math.min(source.box.x, destination.box.x) - 72;
246
+ const top = Math.min(source.box.y, destination.box.y) - 64;
247
+ const middle = (left + right) / 2;
248
+ path = `M ${start.x} ${start.y} C ${right} ${start.y}, ${right} ${top}, ${middle} ${top}` +
249
+ ` C ${left} ${top}, ${left} ${end.y}, ${end.x} ${end.y}`;
250
+ badgePoint = { x: middle, y: top - 6 };
251
+ }
252
+ const head = `M ${end.x - 9} ${end.y - 5} L ${end.x} ${end.y} L ${end.x - 9} ${end.y + 5}`;
253
+ let waitTransform;
254
+ if (relation.kind === 'message' && relation.wait) {
255
+ const scale = Math.hypot(matrix.a, matrix.b) || 1;
256
+ const point = waitBadgePoint(path, 24 / scale);
257
+ badgePoint = { x: point.x + 16 / scale, y: point.y + 4 / scale };
258
+ waitTransform = `translate(${point.x} ${point.y}) scale(${1 / scale})`;
259
+ }
260
+ return { path, head, recursive, badgePoint, waitTransform };
261
+ }
262
+ function drawArrow(drawing, matrix, inverse, area, highlighted) {
263
+ const { relation, source, destination, count } = drawing;
264
+ const { path, head, recursive, badgePoint, waitTransform } = arrowGeometry(drawing, matrix, inverse, area, highlighted);
265
+ const strings = text();
266
+ const group = element('g', {
267
+ 'data-script-relation': relation.kind,
268
+ 'data-source-block': source?.id ?? relation.source.blockId,
269
+ 'data-source-call': relation.source.blockId,
270
+ 'data-destination-block': destination?.id ?? relation.destination?.blockId ?? '',
271
+ 'data-count': String(count),
272
+ 'data-wait': String(relation.wait)
273
+ });
274
+ group.toggleAttribute('data-highlighted', Boolean(highlighted));
275
+ group.toggleAttribute('data-recursive', Boolean(recursive));
276
+ group.toggleAttribute('data-script-external', !source || !destination);
277
+ const description = element('title');
278
+ const waiting = relation.kind === 'message' && relation.wait;
279
+ description.textContent = `${strings[relation.kind]}: ${relation.label}${waiting ? ` · ${strings.wait}` : ''}`;
280
+ group.append(description, element('path', {
281
+ class: 'tw-script-relation-line',
282
+ d: path
283
+ }), element('path', {
284
+ class: 'tw-script-relation-head',
285
+ d: head
286
+ }));
287
+ if (waiting) {
288
+ const badge = element('g', { class: 'tw-script-relation-wait', 'aria-label': strings.wait,
289
+ transform: waitTransform });
290
+ const title = element('title');
291
+ title.textContent = strings.wait;
292
+ badge.append(title, element('rect', { x: '-10', y: '-10', width: '20', height: '20', rx: '4' }), element('path', { class: 'tw-script-relation-wait-glyph', d: relationWaitGlyph, transform: 'translate(-8 -8)' }));
293
+ group.append(badge);
294
+ }
295
+ if (count > 1) {
296
+ const badge = element('text', { x: String(badgePoint.x), y: String(badgePoint.y),
297
+ class: 'tw-script-relation-badge', 'text-anchor': waiting ? 'start' : 'middle' });
298
+ badge.textContent = `×${count}`;
299
+ group.append(badge);
300
+ }
301
+ return group;
302
+ }
177
303
  function render() {
178
304
  frame = undefined;
179
305
  if (disposed)
180
306
  return;
307
+ if (!enabled || !visibility.function && !visibility.message) {
308
+ clear();
309
+ return;
310
+ }
181
311
  const strings = text();
182
312
  const toolbox = injection.querySelector(':scope > .blocklyToolboxDiv');
183
313
  const toolboxBounds = toolbox?.getBoundingClientRect();
184
314
  const horizontal = toolbox?.hasAttribute('data-horizontal-block-palette');
185
315
  // The horizontal palette sits above the blocks, including in the Editor's default layout.
186
- destinations.style.top = `${horizontal ? Math.max(10, toolboxBounds.bottom - injection.getBoundingClientRect().top + 10) : 10}px`;
187
- destinations.replaceChildren();
188
- destinations.hidden = true;
316
+ const guideTop = horizontal ? Math.max(10, toolboxBounds.bottom - injection.getBoundingClientRect().top + 10) : 10;
189
317
  const drawingRoot = projection ?? canvas;
190
318
  const drawingLayer = projection ? projectedLayer : layer;
191
319
  if (!drawingLayer)
192
320
  return;
193
- drawingLayer.replaceChildren();
194
- drawingLayer.removeAttribute('data-script-dragging');
195
- layer.style.display = projection ? 'none' : '';
196
- if (!enabled) {
197
- markScripts(new Map());
198
- return;
199
- }
200
321
  const target = getTarget();
201
322
  if (!target) {
202
- markScripts(new Map());
323
+ clear();
203
324
  return;
204
325
  }
205
326
  const matrix = drawingRoot.getScreenCTM();
@@ -212,6 +333,37 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
212
333
  markScripts(new Map());
213
334
  return;
214
335
  }
336
+ // Read the viewport once, before committing any arrow or guide mutations.
337
+ const area = (projection ?? workspace.getParentSvg()).getBoundingClientRect();
338
+ const sameScale = lastMatrix && matrix.a === lastMatrix.a && matrix.b === lastMatrix.b &&
339
+ matrix.c === lastMatrix.c && matrix.d === lastMatrix.d;
340
+ if (!geometryChanged && !projection && sameScale) {
341
+ const geometry = edgeDrawings.map(item => ({ ...item,
342
+ shape: arrowGeometry(item.drawing, matrix, inverse, area, item.highlighted) }));
343
+ syncTransform(matrix);
344
+ for (const { group, shape } of geometry) {
345
+ const set = (node, name, value) => {
346
+ if (node && node.getAttribute(name) !== String(value))
347
+ node.setAttribute(name, String(value));
348
+ };
349
+ set(group.querySelector('.tw-script-relation-line'), 'd', shape.path);
350
+ set(group.querySelector('.tw-script-relation-head'), 'd', shape.head);
351
+ if (shape.waitTransform)
352
+ set(group.querySelector('.tw-script-relation-wait'), 'transform', shape.waitTransform);
353
+ const count = group.querySelector('.tw-script-relation-badge');
354
+ set(count, 'x', shape.badgePoint.x);
355
+ set(count, 'y', shape.badgePoint.y);
356
+ }
357
+ lastMatrix = matrix;
358
+ return;
359
+ }
360
+ geometryChanged = false;
361
+ lastMatrix = matrix;
362
+ edgeDrawings = [];
363
+ const paint = [];
364
+ const guides = document.createDocumentFragment();
365
+ const previousGroups = renderedGroups.get(drawingLayer);
366
+ const nextGroups = new Map();
215
367
  if (getRelations)
216
368
  graph = getRelations();
217
369
  else if (dirty) {
@@ -232,13 +384,21 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
232
384
  }
233
385
  const inDrag = (endpoint) => Boolean(endpoint && endpoint.targetId === target.id && draggedIds.has(endpoint.blockId));
234
386
  const incident = (relation) => inDrag(relation.source) || inDrag(relation.destination);
235
- drawingLayer.toggleAttribute('data-script-dragging', Boolean(dragging));
236
387
  const drawings = new Map();
388
+ const anchors = new Map();
389
+ const measuredAnchor = (endpoint) => {
390
+ const key = `${endpoint.targetId}\0${endpoint.scriptId}\0${endpoint.blockId}`;
391
+ if (!anchors.has(key))
392
+ anchors.set(key, anchor(endpoint, target, roots, inverse));
393
+ return anchors.get(key);
394
+ };
237
395
  for (const relation of graph) {
396
+ if (!visibility[relation.kind])
397
+ continue;
238
398
  if (relation.source.targetId !== target.id && relation.destination?.targetId !== target.id)
239
399
  continue;
240
- const source = anchor(relation.source, target, roots, inverse);
241
- const destination = relation.destination && anchor(relation.destination, target, roots, inverse);
400
+ const source = measuredAnchor(relation.source);
401
+ const destination = relation.destination && measuredAnchor(relation.destination);
242
402
  if (!source && !destination)
243
403
  continue;
244
404
  const key = JSON.stringify([relation.kind, source?.id ?? relation.source,
@@ -251,7 +411,7 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
251
411
  }
252
412
  const related = new Set();
253
413
  for (const relation of graph)
254
- if (dragging && incident(relation)) {
414
+ if (visibility[relation.kind] && dragging && incident(relation)) {
255
415
  if (inDrag(relation.source) && relation.destination?.targetId === target.id && !inDrag(relation.destination)) {
256
416
  related.add(relation.destination.scriptId);
257
417
  }
@@ -267,17 +427,17 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
267
427
  if (root && root.getClientRects().length && !root.closest('[data-tw-plus-hidden]'))
268
428
  marked.set(root, 'related');
269
429
  }
270
- markScripts(marked);
271
430
  // Frame the whole stack, including its body; the original block paint and runtime glow stay intact.
272
431
  for (const [root, role] of marked) {
273
432
  const bounds = root.getBoundingClientRect();
274
433
  const first = transform(inverse, { x: bounds.left, y: bounds.top });
275
434
  const last = transform(inverse, { x: bounds.right, y: bounds.bottom });
276
- drawingLayer.append(element('rect', { x: String(first.x - 7), y: String(first.y - 7),
435
+ paint.push(element('rect', { x: String(first.x - 7), y: String(first.y - 7),
277
436
  width: String(Math.max(0, last.x - first.x) + 14), height: String(Math.max(0, last.y - first.y) + 14),
278
437
  rx: '10', class: 'tw-script-relation-script-highlight', 'data-emphasis': role }));
279
438
  }
280
- for (const { relation, source, destination, count } of drawings.values()) {
439
+ for (const [key, drawing] of drawings) {
440
+ const { relation, source, destination, count } = drawing;
281
441
  const highlighted = dragging ? incident(relation) :
282
442
  emphasized && (emphasized === relation.source.scriptId || emphasized === relation.destination?.scriptId);
283
443
  let external;
@@ -296,76 +456,65 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
296
456
  external.toggleAttribute('data-highlighted', Boolean(highlighted));
297
457
  if (endpoint)
298
458
  external.addEventListener('click', () => go(endpoint));
299
- destinations.append(external);
300
- }
301
- // Anchor an external link to the viewport edge; the list itself remains keyboard accessible.
302
- const area = (projection ?? workspace.getParentSvg()).getBoundingClientRect();
303
- const local = source ?? destination;
304
- const edgeX = source ? area.right - 12 : area.left + 12;
305
- const screenY = transform(matrix, { x: local.box.x, y: local.box.y + local.box.height / 2 }).y;
306
- const edge = transform(inverse, { x: edgeX, y: Math.max(area.top + 12, Math.min(area.bottom - 12, screenY)) });
307
- const forward = !source || !destination || destination.box.x >= source.box.x + source.box.width / 2;
308
- let start = source ? source.point(forward ? 'right' : 'left', 0.5) : edge;
309
- let end = destination ? destination.point(forward ? 'left' : 'right', Math.min(0.5, 24 / destination.box.height)) : edge;
310
- let direction = forward ? 1 : -1;
311
- const bend = Math.max(36, Math.abs(end.x - start.x) / 2);
312
- let path = `M ${start.x} ${start.y} C ${start.x + bend * direction} ${start.y}, ${end.x - bend * direction} ${end.y}, ${end.x} ${end.y}`;
313
- const recursive = source && destination && relation.source.scriptId === relation.destination.scriptId &&
314
- relation.source.targetId === relation.destination.targetId;
315
- let badgePoint = { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 - 6 };
316
- if (recursive) {
317
- start = source.point('right', 0.75);
318
- end = destination.point('right', 0.25);
319
- const outside = Math.max(start.x, end.x) + 72;
320
- path = `M ${start.x} ${start.y} C ${outside} ${start.y + 32}, ${outside} ${end.y - 32}, ${end.x} ${end.y}`;
321
- direction = -1;
322
- badgePoint = { x: outside - 14, y: (start.y + end.y) / 2 - 6 };
323
- }
324
- const group = element('g', {
325
- 'data-script-relation': relation.kind,
326
- 'data-source-block': source?.id ?? relation.source.blockId,
327
- 'data-source-call': relation.source.blockId,
328
- 'data-destination-block': destination?.id ?? relation.destination?.blockId ?? '',
329
- 'data-count': String(count),
330
- 'data-wait': String(relation.wait)
331
- });
332
- group.toggleAttribute('data-highlighted', Boolean(highlighted));
333
- group.toggleAttribute('data-recursive', Boolean(recursive));
334
- const description = element('title');
335
- const waiting = relation.kind === 'message' && relation.wait;
336
- description.textContent = `${strings[relation.kind]}: ${relation.label}${waiting ? ` · ${strings.wait}` : ''}`;
337
- group.append(description, element('path', {
338
- class: 'tw-script-relation-line',
339
- d: path
340
- }), element('path', {
341
- class: 'tw-script-relation-head',
342
- d: `M ${end.x - 9 * direction} ${end.y - 5} L ${end.x} ${end.y} L ${end.x - 9 * direction} ${end.y + 5}`
343
- }));
344
- if (waiting) {
345
- const scale = Math.hypot(matrix.a, matrix.b) || 1;
346
- const point = waitBadgePoint(path, 24 / scale);
347
- badgePoint = { x: point.x + 16 / scale, y: point.y + 4 / scale };
348
- const badge = element('g', { class: 'tw-script-relation-wait', 'aria-label': strings.wait,
349
- transform: `translate(${point.x} ${point.y}) scale(${1 / scale})` });
350
- const title = element('title');
351
- title.textContent = strings.wait;
352
- badge.append(title, element('rect', { x: '-10', y: '-10', width: '20', height: '20', rx: '4' }), element('path', { class: 'tw-script-relation-wait-glyph', d: relationWaitGlyph, transform: 'translate(-8 -8)' }));
353
- group.append(badge);
354
- }
355
- if (count > 1) {
356
- const badge = element('text', { x: String(badgePoint.x), y: String(badgePoint.y),
357
- class: 'tw-script-relation-badge', 'text-anchor': waiting ? 'start' : 'middle' });
358
- badge.textContent = `×${count}`;
359
- group.append(badge);
459
+ guides.append(external);
360
460
  }
361
- drawingLayer.append(group);
461
+ let group = drawArrow(drawing, matrix, inverse, area, Boolean(highlighted));
462
+ const previous = previousGroups?.get(key);
463
+ if (previous?.isEqualNode(group))
464
+ group = previous;
465
+ nextGroups.set(key, group);
466
+ if (!source || !destination)
467
+ edgeDrawings.push({ key, drawing, group, highlighted: Boolean(highlighted) });
468
+ paint.push(group);
362
469
  }
470
+ syncTransform(matrix);
471
+ layer.style.display = projection ? 'none' : '';
472
+ drawingLayer.toggleAttribute('data-script-dragging', Boolean(dragging));
473
+ // Keep unchanged lines in place, including when an unrelated script was edited or dragged.
474
+ const wanted = new Set(paint);
475
+ for (const child of Array.from(drawingLayer.children))
476
+ if (!wanted.has(child))
477
+ child.remove();
478
+ let cursor = drawingLayer.firstChild;
479
+ for (const node of paint) {
480
+ if (node === cursor)
481
+ cursor = cursor.nextSibling;
482
+ else
483
+ drawingLayer.insertBefore(node, cursor);
484
+ }
485
+ renderedGroups.set(drawingLayer, nextGroups);
486
+ destinations.style.top = `${guideTop}px`;
487
+ destinations.replaceChildren(guides);
363
488
  destinations.hidden = !destinations.childElementCount;
489
+ markScripts(marked);
364
490
  }
365
- function update() {
491
+ function clear() {
492
+ if (layer.childElementCount)
493
+ layer.replaceChildren();
494
+ if (projectedLayer?.childElementCount)
495
+ projectedLayer.replaceChildren();
496
+ if (destinations.childElementCount)
497
+ destinations.replaceChildren();
498
+ destinations.hidden = true;
499
+ edgeDrawings = [];
500
+ lastMatrix = undefined;
501
+ renderedGroups.delete(layer);
502
+ if (projectedLayer)
503
+ renderedGroups.delete(projectedLayer);
504
+ markScripts(new Map());
505
+ }
506
+ function schedule() {
507
+ if (!enabled || !visibility.function && !visibility.message) {
508
+ clear();
509
+ return;
510
+ }
366
511
  if (!disposed && frame === undefined)
367
512
  frame = view.requestAnimationFrame(render);
368
513
  }
514
+ function update() {
515
+ geometryChanged = true;
516
+ schedule();
517
+ }
369
518
  function changed() { dirty = true; update(); }
370
519
  function scriptOf(id, target = getTarget()) {
371
520
  const blocks = target?.blocks._blocks;
@@ -386,16 +535,28 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
386
535
  update();
387
536
  }
388
537
  }
538
+ const dragSurface = injection.querySelector('.blocklyBlockDragSurface');
539
+ const workspaceDragSurface = injection.querySelector('.blocklyWsDragSurface');
389
540
  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-')))
541
+ // Panning also translates the empty drag surface. It has no endpoints until a block is dragged.
542
+ const dragging = injection.querySelector('[data-id].blocklyDragging');
543
+ const relevant = records.filter(record => record.target !== layer && !layer.contains(record.target) &&
544
+ !record.attributeName?.startsWith('data-script-relation-') &&
545
+ (dragging || !dragSurface?.contains(record.target)));
546
+ if (!relevant.length)
547
+ return;
548
+ if (!projection && relevant.every(record => record.type === 'attributes' &&
549
+ (record.target === canvas && record.attributeName === 'transform' || record.target === workspaceDragSurface)))
550
+ schedule();
551
+ else
392
552
  update();
393
553
  });
394
554
  mutations.observe(canvas, { attributes: true, childList: true, subtree: true });
395
555
  // Its CSS translation changes on every drag step, while the workspace canvas stays untouched.
396
- const dragSurface = injection.querySelector('.blocklyBlockDragSurface');
397
556
  if (dragSurface)
398
557
  mutations.observe(dragSurface, { attributes: true, childList: true, subtree: true });
558
+ if (workspaceDragSurface)
559
+ mutations.observe(workspaceDragSurface, { attributes: true, childList: true });
399
560
  const resized = new view.ResizeObserver(update);
400
561
  resized.observe(injection);
401
562
  const toolbox = injection.querySelector('.blocklyToolboxDiv');
@@ -413,6 +574,13 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
413
574
  return {
414
575
  update: changed,
415
576
  get enabled() { return enabled; },
577
+ get visibility() { return { ...visibility }; },
578
+ setVisibility(value) {
579
+ if (value.function === visibility.function && value.message === visibility.message)
580
+ return;
581
+ visibility = { ...value };
582
+ update();
583
+ },
416
584
  setEnabled(value) { enabled = value; update(); },
417
585
  setProjection(svg) {
418
586
  if (svg === projection) {
@@ -0,0 +1,34 @@
1
+ type ScriptFitWorkspace = {
2
+ RTL?: boolean;
3
+ options?: {
4
+ zoomOptions?: {
5
+ minScale?: number;
6
+ maxScale?: number;
7
+ };
8
+ };
9
+ scale: number;
10
+ getInjectionDiv(): HTMLElement;
11
+ getBlockById(id: string): {
12
+ getSvgRoot(): SVGGraphicsElement | null;
13
+ getRelativeToSurfaceXY(): {
14
+ x: number;
15
+ y: number;
16
+ };
17
+ } | null;
18
+ getMetrics(): {
19
+ viewWidth: number;
20
+ viewHeight: number;
21
+ contentLeft: number;
22
+ contentTop: number;
23
+ } | null;
24
+ resize?(): void;
25
+ setScale(scale: number): void;
26
+ scrollbar?: {
27
+ set(x: number, y: number): void;
28
+ };
29
+ };
30
+ /** Fit a visible script once. Hidden or not-yet-rendered workspaces can retry after their layout settles. */
31
+ export declare function fitScriptInWorkspace(workspace: ScriptFitWorkspace, scriptId: string, blocks: {
32
+ svgResize(workspace: ScriptFitWorkspace): void;
33
+ }): boolean;
34
+ export {};
@@ -0,0 +1,41 @@
1
+ const padding = 24;
2
+ const positive = (value, fallback) => Number.isFinite(value) && value > 0 ? value : fallback;
3
+ /** Fit a visible script once. Hidden or not-yet-rendered workspaces can retry after their layout settles. */
4
+ export function fitScriptInWorkspace(workspace, scriptId, blocks) {
5
+ const injection = workspace.getInjectionDiv();
6
+ const block = workspace.getBlockById(scriptId);
7
+ if (!block || !injection.clientWidth || !injection.clientHeight || !workspace.scrollbar)
8
+ return false;
9
+ const root = block.getSvgRoot();
10
+ if (!root)
11
+ return false;
12
+ // A split can have its new DOM size while Blockly's cached SVG size still belongs to the old pane.
13
+ blocks.svgResize(workspace);
14
+ workspace.resize?.();
15
+ const bounds = root.getBBox();
16
+ const metrics = workspace.getMetrics();
17
+ if (!metrics?.viewWidth || !metrics.viewHeight || !(bounds.width > 0) || !(bounds.height > 0))
18
+ return false;
19
+ // SVG bounds include nested reporters and the hat's overhang, but exclude folded, hidden bodies.
20
+ const origin = block.getRelativeToSurfaceXY();
21
+ const left = origin.x + bounds.x;
22
+ const top = origin.y + bounds.y;
23
+ const zoom = workspace.options?.zoomOptions;
24
+ const workspaceMin = positive(zoom?.minScale, 0.01);
25
+ const workspaceMax = Math.max(workspaceMin, positive(zoom?.maxScale, Infinity));
26
+ const minScale = Math.min(Math.max(0.5, workspaceMin), workspaceMax);
27
+ const maxScale = Math.max(minScale, Math.min(1.25, workspaceMax));
28
+ const fit = Math.min(Math.max(1, metrics.viewWidth - padding * 2) / bounds.width, Math.max(1, metrics.viewHeight - padding * 2) / bounds.height);
29
+ const scale = Math.max(minScale, Math.min(maxScale, fit));
30
+ workspace.setScale(scale);
31
+ const scaled = workspace.getMetrics();
32
+ if (!scaled)
33
+ return false;
34
+ const width = bounds.width * workspace.scale;
35
+ const height = bounds.height * workspace.scale;
36
+ const x = width > scaled.viewWidth - padding * 2 && workspace.RTL ?
37
+ scaled.viewWidth - padding - width : Math.max(padding, (scaled.viewWidth - width) / 2);
38
+ const y = workspace.scale <= minScale ? padding : Math.max(padding, (scaled.viewHeight - height) / 2);
39
+ workspace.scrollbar.set(left * workspace.scale - scaled.contentLeft - x, top * workspace.scale - scaled.contentTop - y);
40
+ return true;
41
+ }
@@ -2,7 +2,7 @@ import { type LayoutWorkspace } from './script-layout-workspace.ts';
2
2
  import { type RearrangementContext } from './script-layout-dialog.ts';
3
3
  import { type ScriptViewMenuBlocks, type ScriptViewMenuWorkspace } from './script-view-menu.ts';
4
4
  import type { PresentationElements } from './preview-chrome.ts';
5
- import { type ScriptRelationContext } from './script-arrows.ts';
5
+ import { type ScriptRelationContext, type ScriptRelationVisibility } from './script-arrows.ts';
6
6
  export type ScriptView = 'free' | 'z' | 'n';
7
7
  interface ViewOptions {
8
8
  workspace: LayoutWorkspace & ScriptViewMenuWorkspace;
@@ -20,6 +20,11 @@ export declare function attachScriptView({ workspace, ScratchBlocks, getLocale,
20
20
  relations: {
21
21
  update: () => void;
22
22
  readonly enabled: boolean;
23
+ readonly visibility: {
24
+ function: boolean;
25
+ message: boolean;
26
+ };
27
+ setVisibility(value: ScriptRelationVisibility): void;
23
28
  setEnabled(value: boolean): void;
24
29
  setProjection(svg: SVGSVGElement | null): void;
25
30
  dispose(): void;
@@ -50,12 +55,19 @@ interface DockedScriptLayoutOptions {
50
55
  /** The host's elements around the workspace. Without them, the workspace's own element is the surface. */
51
56
  presentationElements?: PresentationElements | null;
52
57
  }
58
+ export declare function getDockedRelationVisibility(vm: object): ScriptRelationVisibility;
59
+ export declare function setDockedRelationVisibility(vm: object, visibility: ScriptRelationVisibility): void;
53
60
  export declare function getDockedScriptLayout(vm: object): {
54
61
  view: {
55
62
  update: () => void;
56
63
  relations: {
57
64
  update: () => void;
58
65
  readonly enabled: boolean;
66
+ readonly visibility: {
67
+ function: boolean;
68
+ message: boolean;
69
+ };
70
+ setVisibility(value: ScriptRelationVisibility): void;
59
71
  setEnabled(value: boolean): void;
60
72
  setProjection(svg: SVGSVGElement | null): void;
61
73
  dispose(): void;
@@ -75,6 +87,11 @@ export declare function attachDockedScriptLayout({ vm, workspace, ScratchBlocks,
75
87
  relations: {
76
88
  update: () => void;
77
89
  readonly enabled: boolean;
90
+ readonly visibility: {
91
+ function: boolean;
92
+ message: boolean;
93
+ };
94
+ setVisibility(value: ScriptRelationVisibility): void;
78
95
  setEnabled(value: boolean): void;
79
96
  setProjection(svg: SVGSVGElement | null): void;
80
97
  dispose(): void;