@kubohiroya/turbowarp-plus-editor-code-views 0.20.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.
@@ -1,6 +1,8 @@
1
1
  import {isFoldedDefinition} from './procedure-edits.ts';
2
2
  import {readScriptRelations, type RelationTarget, type ScriptEndpoint, type ScriptRelation} from './script-relations.ts';
3
3
 
4
+ export type ScriptRelationVisibility = {function: boolean; message: boolean};
5
+
4
6
  export interface ScriptRelationContext {
5
7
  vm?: {
6
8
  runtime?: {targets?: readonly RelationTarget[]; on?(name: string, listener: () => void): void;
@@ -15,6 +17,7 @@ export interface ScriptRelationContext {
15
17
  getLocale?(): string;
16
18
  getTargetName?(id: string): string | undefined;
17
19
  navigate?(endpoint: ScriptEndpoint): void;
20
+ initialVisibility?: ScriptRelationVisibility;
18
21
  }
19
22
 
20
23
  type Point = {x: number; y: number};
@@ -27,7 +30,9 @@ const relationWaitGlyph = 'M1 1h14M1 15h14M2 1v3l12 8v3M14 1v3l-12 8v3M2 4h12M2
27
30
 
28
31
  /** Keep the badge beside the receiving end of the cubic curve, leaving its stroke visible. */
29
32
  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);
33
+ const values = path.match(/-?(?:\d*\.?\d+)(?:e[+-]?\d+)?/gi).map(Number);
34
+ const [sx, sy] = values;
35
+ const [bx, by, tx, ty] = values.slice(-4);
31
36
  const endX = tx - bx;
32
37
  const endY = ty - by;
33
38
  const dx = endX || endY ? endX : tx - sx;
@@ -37,34 +42,54 @@ function waitBadgePoint(path: string, offset: number): Point {
37
42
  return {x: tx - dx / length * offset * .75 - dy / length * offset * side,
38
43
  y: ty - dy / length * offset * .75 + dx / length * offset * side};
39
44
  }
40
- const outlines = new WeakMap<SVGGeometryElement, {data: string; points: Point[]}>();
45
+ type Outline = {points: (Point & {distance: number})[]; cuts: Map<string, Point>};
46
+ const outlines = new Map<string, Outline>();
41
47
 
42
48
  /** Intersect the actual outline, including a hat's overhang, rather than Blockly's layout padding. */
43
49
  function outlinePoint(shape: SVGGeometryElement, bounds: Box, side: 'left' | 'right', fraction: number): Point {
44
50
  const data = shape.getAttribute('d') ?? '';
45
- let outline = outlines.get(shape);
46
- if (!outline || outline.data !== data) {
51
+ let outline = outlines.get(data);
52
+ if (!outline) {
47
53
  const length = shape.getTotalLength();
48
- const count = Math.max(32, Math.min(1024, Math.ceil(length / 2)));
54
+ const count = Math.max(24, Math.min(96, Math.ceil(length / 8)));
49
55
  const points = Array.from({length: count + 1}, (_, index) => {
50
- const point = shape.getPointAtLength(length * index / count);
51
- return {x: point.x, y: point.y};
56
+ const distance = length * index / count;
57
+ const point = shape.getPointAtLength(distance);
58
+ return {x: point.x, y: point.y, distance};
52
59
  });
53
- outline = {data, points};
54
- outlines.set(shape, outline);
60
+ outline = {points, cuts: new Map()};
61
+ if (outlines.size >= 512) outlines.delete(outlines.keys().next().value);
62
+ outlines.set(data, outline);
55
63
  }
56
64
  const y = bounds.y + bounds.height * fraction;
65
+ const key = `${side}:${y}`;
66
+ const cached = outline.cuts.get(key);
67
+ if (cached) return cached;
57
68
  let edge: number | undefined;
58
69
  for (let index = 1; index < outline.points.length; index++) {
59
70
  const before = outline.points[index - 1];
60
71
  const after = outline.points[index];
61
72
  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);
73
+ let x: number;
74
+ if (before.y === after.y) x = side === 'left' ? Math.min(before.x, after.x) : Math.max(before.x, after.x);
75
+ else {
76
+ // Refine only a crossing instead of sampling every two units along the entire outline.
77
+ let low = before.distance, high = after.distance;
78
+ for (let step = 0; step < 12; step++) {
79
+ const middle = (low + high) / 2;
80
+ const point = shape.getPointAtLength(middle);
81
+ x = point.x;
82
+ if (Math.abs(point.y - y) < .001) break;
83
+ if ((point.y < y) === (before.y < y)) low = middle;
84
+ else high = middle;
85
+ }
86
+ }
64
87
  edge = edge === undefined ? x : side === 'left' ? Math.min(edge, x) : Math.max(edge, x);
65
88
  }
66
89
  }
67
- return {x: edge ?? bounds.x + (side === 'right' ? bounds.width : 0), y};
90
+ const point = {x: edge ?? bounds.x + (side === 'right' ? bounds.width : 0), y};
91
+ outline.cuts.set(key, point);
92
+ return point;
68
93
  }
69
94
 
70
95
  // The shared workspace owns navigation even when an arrow is in a read-only preview.
@@ -80,7 +105,8 @@ const transform = (matrix: DOMMatrix, {x, y}: Point): Point => ({
80
105
  });
81
106
 
82
107
  /** 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 & {
108
+ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getLocale, getTargetName, navigate,
109
+ initialVisibility}: ScriptRelationContext & {
84
110
  workspace: {
85
111
  getInjectionDiv(): HTMLElement;
86
112
  getCanvas(): SVGElement;
@@ -100,7 +126,8 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
100
126
  layer.setAttribute('data-script-relation-layer', '');
101
127
  layer.setAttribute('aria-hidden', 'true');
102
128
  layer.setAttribute('pointer-events', 'none');
103
- canvas.prepend(layer);
129
+ // Keep arrow mutations outside the block canvas observed by the minimap and serial previews.
130
+ canvas.before(layer);
104
131
  const destinations = document.createElement('div');
105
132
  destinations.className = 'tw-script-relation-guide tw-script-relation-destinations';
106
133
  destinations.dataset.scriptRelationGuide = '';
@@ -119,6 +146,23 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
119
146
  let graph: readonly ScriptRelation[] = [];
120
147
  let selected: string | undefined;
121
148
  let enabled = true;
149
+ let visibility: ScriptRelationVisibility = {...initialVisibility ?? {function: true, message: true}};
150
+ let geometryChanged = true;
151
+ let lastMatrix: DOMMatrix | undefined;
152
+ let edgeDrawings: {key: string; drawing: Drawing; group: SVGGElement; highlighted: boolean}[] = [];
153
+ const renderedGroups = new WeakMap<SVGGElement, Map<string, SVGGElement>>();
154
+ const syncTransform = (matrix: DOMMatrix) => {
155
+ // Workspace dragging lends the two native canvases to a separate SVG which must keep exactly two children.
156
+ // Leave our layer in place and project that surface's transform back into its original parent instead.
157
+ const parent = layer.parentElement as unknown as SVGGraphicsElement;
158
+ const relative = canvas.parentElement !== layer.parentElement && parent.getScreenCTM()?.inverse().multiply(matrix);
159
+ const transform = relative ? `matrix(${relative.a},${relative.b},${relative.c},${relative.d},${relative.e},${relative.f})` :
160
+ canvas.getAttribute('transform');
161
+ if (layer.getAttribute('transform') !== transform) {
162
+ if (transform === null) layer.removeAttribute('transform');
163
+ else layer.setAttribute('transform', transform);
164
+ }
165
+ };
122
166
  const markedScripts = new Map<SVGElement, 'source' | 'related'>();
123
167
  const text = () => /^ja(?:-|$)/i.test(getLocale?.() ?? document.documentElement.lang) ? {
124
168
  title: '呼び出しの矢印', function: '関数呼び出し', message: 'メッセージ送信', wait: '送って待つ',
@@ -194,34 +238,111 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
194
238
  const convert = (point: Point) => transform(inverse, transform(matrix, point));
195
239
  const first = convert(bounds);
196
240
  const last = convert({x: bounds.x + bounds.width, y: bounds.y + bounds.height});
241
+ const points = new Map<string, Point>();
197
242
  return {id, box: {x: Math.min(first.x, last.x), y: Math.min(first.y, last.y),
198
243
  width: Math.abs(last.x - first.x), height: Math.abs(last.y - first.y)}, point(side, fraction) {
199
244
  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});
245
+ const key = `${localSide}:${fraction}`;
246
+ if (!points.has(key)) points.set(key, convert(path ? outlinePoint(path, bounds, localSide, fraction) :
247
+ {x: bounds.x + (localSide === 'right' ? bounds.width : 0), y: bounds.y + bounds.height * fraction}));
248
+ return points.get(key);
202
249
  }};
203
250
  }
204
251
 
252
+ function arrowGeometry({relation, source, destination, count}: Drawing, matrix: DOMMatrix, inverse: DOMMatrix,
253
+ area: DOMRect, highlighted: boolean) {
254
+ // Anchor an external link to the viewport edge; the list itself remains keyboard accessible.
255
+ const local = source ?? destination;
256
+ const edgeX = source ? area.right - 12 : area.left + 12;
257
+ const screenY = transform(matrix, {x: local.box.x, y: local.box.y + local.box.height / 2}).y;
258
+ const edge = transform(inverse, {x: edgeX, y: Math.max(area.top + 12, Math.min(area.bottom - 12, screenY))});
259
+ let start = source ? source.point('right', 0.5) : edge;
260
+ let end = destination ? destination.point('left', Math.min(0.5, 24 / destination.box.height)) : edge;
261
+ const bend = Math.max(36, Math.abs(end.x - start.x) / 2);
262
+ let path = `M ${start.x} ${start.y} C ${start.x + bend} ${start.y}, ${end.x - bend} ${end.y}, ${end.x} ${end.y}`;
263
+ const recursive = source && destination && relation.source.scriptId === relation.destination.scriptId &&
264
+ relation.source.targetId === relation.destination.targetId;
265
+ let badgePoint = {x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 - 6};
266
+ if (recursive) {
267
+ start = source.point('right', 0.75);
268
+ end = destination.point('left', 0.25);
269
+ const right = Math.max(source.box.x + source.box.width, destination.box.x + destination.box.width) + 144;
270
+ const left = Math.min(source.box.x, destination.box.x) - 72;
271
+ const top = Math.min(source.box.y, destination.box.y) - 64;
272
+ const middle = (left + right) / 2;
273
+ path = `M ${start.x} ${start.y} C ${right} ${start.y}, ${right} ${top}, ${middle} ${top}` +
274
+ ` C ${left} ${top}, ${left} ${end.y}, ${end.x} ${end.y}`;
275
+ badgePoint = {x: middle, y: top - 6};
276
+ }
277
+ const head = `M ${end.x - 9} ${end.y - 5} L ${end.x} ${end.y} L ${end.x - 9} ${end.y + 5}`;
278
+ let waitTransform: string | undefined;
279
+ if (relation.kind === 'message' && relation.wait) {
280
+ const scale = Math.hypot(matrix.a, matrix.b) || 1;
281
+ const point = waitBadgePoint(path, 24 / scale);
282
+ badgePoint = {x: point.x + 16 / scale, y: point.y + 4 / scale};
283
+ waitTransform = `translate(${point.x} ${point.y}) scale(${1 / scale})`;
284
+ }
285
+ return {path, head, recursive, badgePoint, waitTransform};
286
+ }
287
+
288
+ function drawArrow(drawing: Drawing, matrix: DOMMatrix, inverse: DOMMatrix, area: DOMRect, highlighted: boolean) {
289
+ const {relation, source, destination, count} = drawing;
290
+ const {path, head, recursive, badgePoint, waitTransform} = arrowGeometry(drawing, matrix, inverse, area, highlighted);
291
+ const strings = text();
292
+ const group = element('g', {
293
+ 'data-script-relation': relation.kind,
294
+ 'data-source-block': source?.id ?? relation.source.blockId,
295
+ 'data-source-call': relation.source.blockId,
296
+ 'data-destination-block': destination?.id ?? relation.destination?.blockId ?? '',
297
+ 'data-count': String(count),
298
+ 'data-wait': String(relation.wait)
299
+ });
300
+ group.toggleAttribute('data-highlighted', Boolean(highlighted));
301
+ group.toggleAttribute('data-recursive', Boolean(recursive));
302
+ group.toggleAttribute('data-script-external', !source || !destination);
303
+ const description = element('title');
304
+ const waiting = relation.kind === 'message' && relation.wait;
305
+ description.textContent = `${strings[relation.kind]}: ${relation.label}${waiting ? ` · ${strings.wait}` : ''}`;
306
+ group.append(description, element('path', {
307
+ class: 'tw-script-relation-line',
308
+ d: path
309
+ }), element('path', {
310
+ class: 'tw-script-relation-head',
311
+ d: head
312
+ }));
313
+ if (waiting) {
314
+ const badge = element('g', {class: 'tw-script-relation-wait', 'aria-label': strings.wait,
315
+ transform: waitTransform});
316
+ const title = element('title');
317
+ title.textContent = strings.wait;
318
+ badge.append(title, element('rect', {x: '-10', y: '-10', width: '20', height: '20', rx: '4'}),
319
+ element('path', {class: 'tw-script-relation-wait-glyph', d: relationWaitGlyph, transform: 'translate(-8 -8)'}));
320
+ group.append(badge);
321
+ }
322
+ if (count > 1) {
323
+ const badge = element('text', {x: String(badgePoint.x), y: String(badgePoint.y),
324
+ class: 'tw-script-relation-badge', 'text-anchor': waiting ? 'start' : 'middle'});
325
+ badge.textContent = `×${count}`;
326
+ group.append(badge);
327
+ }
328
+ return group;
329
+ }
330
+
205
331
  function render() {
206
332
  frame = undefined;
207
333
  if (disposed) return;
334
+ if (!enabled || !visibility.function && !visibility.message) { clear(); return; }
208
335
  const strings = text();
209
336
  const toolbox = injection.querySelector<HTMLElement>(':scope > .blocklyToolboxDiv');
210
337
  const toolboxBounds = toolbox?.getBoundingClientRect();
211
338
  const horizontal = toolbox?.hasAttribute('data-horizontal-block-palette');
212
339
  // 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;
340
+ const guideTop = horizontal ? Math.max(10, toolboxBounds.bottom - injection.getBoundingClientRect().top + 10) : 10;
216
341
  const drawingRoot = projection ?? canvas;
217
342
  const drawingLayer = projection ? projectedLayer : layer;
218
343
  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
344
  const target = getTarget();
224
- if (!target) { markScripts(new Map()); return; }
345
+ if (!target) { clear(); return; }
225
346
  const matrix = (drawingRoot as SVGGraphicsElement).getScreenCTM();
226
347
  if (!matrix) { markScripts(new Map()); return; }
227
348
  const inverse = matrix.inverse();
@@ -229,6 +350,34 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
229
350
  markScripts(new Map());
230
351
  return;
231
352
  }
353
+ // Read the viewport once, before committing any arrow or guide mutations.
354
+ const area = (projection ?? workspace.getParentSvg()).getBoundingClientRect();
355
+ const sameScale = lastMatrix && matrix.a === lastMatrix.a && matrix.b === lastMatrix.b &&
356
+ matrix.c === lastMatrix.c && matrix.d === lastMatrix.d;
357
+ if (!geometryChanged && !projection && sameScale) {
358
+ const geometry = edgeDrawings.map(item => ({...item,
359
+ shape: arrowGeometry(item.drawing, matrix, inverse, area, item.highlighted)}));
360
+ syncTransform(matrix);
361
+ for (const {group, shape} of geometry) {
362
+ const set = (node: Element | null, name: string, value: string | number) => {
363
+ if (node && node.getAttribute(name) !== String(value)) node.setAttribute(name, String(value));
364
+ };
365
+ set(group.querySelector('.tw-script-relation-line'), 'd', shape.path);
366
+ set(group.querySelector('.tw-script-relation-head'), 'd', shape.head);
367
+ if (shape.waitTransform) set(group.querySelector('.tw-script-relation-wait'), 'transform', shape.waitTransform);
368
+ const count = group.querySelector('.tw-script-relation-badge');
369
+ set(count, 'x', shape.badgePoint.x); set(count, 'y', shape.badgePoint.y);
370
+ }
371
+ lastMatrix = matrix;
372
+ return;
373
+ }
374
+ geometryChanged = false;
375
+ lastMatrix = matrix;
376
+ edgeDrawings = [];
377
+ const paint: SVGElement[] = [];
378
+ const guides = document.createDocumentFragment();
379
+ const previousGroups = renderedGroups.get(drawingLayer);
380
+ const nextGroups = new Map<string, SVGGElement>();
232
381
  if (getRelations) graph = getRelations();
233
382
  else if (dirty) {
234
383
  graph = readScriptRelations(vm?.runtime?.targets ?? [target]);
@@ -246,12 +395,18 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
246
395
  }
247
396
  const inDrag = (endpoint?: ScriptEndpoint) => Boolean(endpoint && endpoint.targetId === target.id && draggedIds.has(endpoint.blockId));
248
397
  const incident = (relation: ScriptRelation) => inDrag(relation.source) || inDrag(relation.destination);
249
- drawingLayer.toggleAttribute('data-script-dragging', Boolean(dragging));
250
398
  const drawings = new Map<string, Drawing>();
399
+ const anchors = new Map<string, Anchor | undefined>();
400
+ const measuredAnchor = (endpoint: ScriptEndpoint) => {
401
+ const key = `${endpoint.targetId}\0${endpoint.scriptId}\0${endpoint.blockId}`;
402
+ if (!anchors.has(key)) anchors.set(key, anchor(endpoint, target, roots, inverse));
403
+ return anchors.get(key);
404
+ };
251
405
  for (const relation of graph) {
406
+ if (!visibility[relation.kind]) continue;
252
407
  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);
408
+ const source = measuredAnchor(relation.source);
409
+ const destination = relation.destination && measuredAnchor(relation.destination);
255
410
  if (!source && !destination) continue;
256
411
  const key = JSON.stringify([relation.kind, source?.id ?? relation.source,
257
412
  destination?.id ?? relation.destination, relation.wait, relation.unresolved, relation.label]);
@@ -260,7 +415,7 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
260
415
  else drawings.set(key, {relation, source, destination, count: 1});
261
416
  }
262
417
  const related = new Set<string>();
263
- for (const relation of graph) if (dragging && incident(relation)) {
418
+ for (const relation of graph) if (visibility[relation.kind] && dragging && incident(relation)) {
264
419
  if (inDrag(relation.source) && relation.destination?.targetId === target.id && !inDrag(relation.destination)) {
265
420
  related.add(relation.destination.scriptId);
266
421
  }
@@ -274,17 +429,17 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
274
429
  const root = blockRoot(id, roots);
275
430
  if (root && root.getClientRects().length && !root.closest('[data-tw-plus-hidden]')) marked.set(root, 'related');
276
431
  }
277
- markScripts(marked);
278
432
  // Frame the whole stack, including its body; the original block paint and runtime glow stay intact.
279
433
  for (const [root, role] of marked) {
280
434
  const bounds = root.getBoundingClientRect();
281
435
  const first = transform(inverse, {x: bounds.left, y: bounds.top});
282
436
  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),
437
+ paint.push(element('rect', {x: String(first.x - 7), y: String(first.y - 7),
284
438
  width: String(Math.max(0, last.x - first.x) + 14), height: String(Math.max(0, last.y - first.y) + 14),
285
439
  rx: '10', class: 'tw-script-relation-script-highlight', 'data-emphasis': role}));
286
440
  }
287
- for (const {relation, source, destination, count} of drawings.values()) {
441
+ for (const [key, drawing] of drawings) {
442
+ const {relation, source, destination, count} = drawing;
288
443
  const highlighted = dragging ? incident(relation) :
289
444
  emphasized && (emphasized === relation.source.scriptId || emphasized === relation.destination?.scriptId);
290
445
  let external: HTMLButtonElement | undefined;
@@ -302,77 +457,53 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
302
457
  external.setAttribute('aria-label', `${strings[relation.kind]}: ${external.textContent}`);
303
458
  external.toggleAttribute('data-highlighted', Boolean(highlighted));
304
459
  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);
460
+ guides.append(external);
367
461
  }
368
- drawingLayer.append(group);
462
+ let group = drawArrow(drawing, matrix, inverse, area, Boolean(highlighted));
463
+ const previous = previousGroups?.get(key);
464
+ if (previous?.isEqualNode(group)) group = previous;
465
+ nextGroups.set(key, group);
466
+ if (!source || !destination) edgeDrawings.push({key, drawing, group, highlighted: Boolean(highlighted)});
467
+ paint.push(group);
369
468
  }
469
+ syncTransform(matrix);
470
+ layer.style.display = projection ? 'none' : '';
471
+ drawingLayer.toggleAttribute('data-script-dragging', Boolean(dragging));
472
+ // Keep unchanged lines in place, including when an unrelated script was edited or dragged.
473
+ const wanted = new Set(paint);
474
+ for (const child of Array.from(drawingLayer.children)) if (!wanted.has(child as SVGElement)) child.remove();
475
+ let cursor = drawingLayer.firstChild;
476
+ for (const node of paint) {
477
+ if (node === cursor) cursor = cursor.nextSibling;
478
+ else drawingLayer.insertBefore(node, cursor);
479
+ }
480
+ renderedGroups.set(drawingLayer, nextGroups);
481
+ destinations.style.top = `${guideTop}px`;
482
+ destinations.replaceChildren(guides);
370
483
  destinations.hidden = !destinations.childElementCount;
484
+ markScripts(marked);
371
485
  }
372
486
 
373
- function update() {
487
+ function clear() {
488
+ if (layer.childElementCount) layer.replaceChildren();
489
+ if (projectedLayer?.childElementCount) projectedLayer.replaceChildren();
490
+ if (destinations.childElementCount) destinations.replaceChildren();
491
+ destinations.hidden = true;
492
+ edgeDrawings = [];
493
+ lastMatrix = undefined;
494
+ renderedGroups.delete(layer);
495
+ if (projectedLayer) renderedGroups.delete(projectedLayer);
496
+ markScripts(new Map());
497
+ }
498
+
499
+ function schedule() {
500
+ if (!enabled || !visibility.function && !visibility.message) { clear(); return; }
374
501
  if (!disposed && frame === undefined) frame = view.requestAnimationFrame(render);
375
502
  }
503
+ function update() {
504
+ geometryChanged = true;
505
+ schedule();
506
+ }
376
507
  function changed() { dirty = true; update(); }
377
508
  function scriptOf(id: string | undefined, target = getTarget()) {
378
509
  const blocks = target?.blocks._blocks;
@@ -386,14 +517,23 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
386
517
  const id = scriptOf(node?.dataset.id);
387
518
  if (id !== selected) { selected = id; update(); }
388
519
  }
520
+ const dragSurface = injection.querySelector('.blocklyBlockDragSurface');
521
+ const workspaceDragSurface = injection.querySelector('.blocklyWsDragSurface');
389
522
  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();
523
+ // Panning also translates the empty drag surface. It has no endpoints until a block is dragged.
524
+ const dragging = injection.querySelector('[data-id].blocklyDragging');
525
+ const relevant = records.filter(record => record.target !== layer && !layer.contains(record.target) &&
526
+ !record.attributeName?.startsWith('data-script-relation-') &&
527
+ (dragging || !dragSurface?.contains(record.target)));
528
+ if (!relevant.length) return;
529
+ if (!projection && relevant.every(record => record.type === 'attributes' &&
530
+ (record.target === canvas && record.attributeName === 'transform' || record.target === workspaceDragSurface))) schedule();
531
+ else update();
392
532
  });
393
533
  mutations.observe(canvas, {attributes: true, childList: true, subtree: true});
394
534
  // Its CSS translation changes on every drag step, while the workspace canvas stays untouched.
395
- const dragSurface = injection.querySelector('.blocklyBlockDragSurface');
396
535
  if (dragSurface) mutations.observe(dragSurface, {attributes: true, childList: true, subtree: true});
536
+ if (workspaceDragSurface) mutations.observe(workspaceDragSurface, {attributes: true, childList: true});
397
537
  const resized = new view.ResizeObserver(update);
398
538
  resized.observe(injection);
399
539
  const toolbox = injection.querySelector('.blocklyToolboxDiv');
@@ -410,6 +550,12 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
410
550
  return {
411
551
  update: changed,
412
552
  get enabled() { return enabled; },
553
+ get visibility() { return {...visibility}; },
554
+ setVisibility(value: ScriptRelationVisibility) {
555
+ if (value.function === visibility.function && value.message === visibility.message) return;
556
+ visibility = {...value};
557
+ update();
558
+ },
413
559
  setEnabled(value: boolean) { enabled = value; update(); },
414
560
  setProjection(svg: SVGSVGElement | null) {
415
561
  if (svg === projection) { update(); return; }
@@ -3,7 +3,8 @@ 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
+ import {attachScriptArrows, type ScriptRelationContext, type ScriptRelationVisibility} from './script-arrows.ts';
7
+ import {attachCodeZoomRange} from './code-zoom.ts';
7
8
 
8
9
  export type ScriptView = 'free' | 'z' | 'n';
9
10
 
@@ -30,6 +31,7 @@ export function attachScriptView({
30
31
  relations: relationContext
31
32
  }: ViewOptions) {
32
33
  const injection = workspace.getInjectionDiv();
34
+ const restoreZoomRange = attachCodeZoomRange(workspace);
33
35
  const host = mount ?? injection;
34
36
  const document = host.ownerDocument;
35
37
  const window = document.defaultView;
@@ -139,6 +141,7 @@ export function attachScriptView({
139
141
  get view() { return view; },
140
142
  setView,
141
143
  dispose() {
144
+ restoreZoomRange();
142
145
  resize.disconnect();
143
146
  observer.disconnect();
144
147
  language.disconnect();
@@ -164,6 +167,16 @@ interface DockedScriptLayoutOptions {
164
167
  }
165
168
 
166
169
  const dockedViews = new WeakMap<object, ReturnType<typeof attachDockedScriptLayout>>();
170
+ const relationVisibilities = new WeakMap<object, ScriptRelationVisibility>();
171
+
172
+ export function getDockedRelationVisibility(vm: object): ScriptRelationVisibility {
173
+ return {...relationVisibilities.get(vm) ?? {function: true, message: true}};
174
+ }
175
+
176
+ export function setDockedRelationVisibility(vm: object, visibility: ScriptRelationVisibility) {
177
+ relationVisibilities.set(vm, {...visibility});
178
+ dockedViews.get(vm)?.view.relations?.setVisibility(visibility);
179
+ }
167
180
 
168
181
  export function getDockedScriptLayout(vm: object) {
169
182
  return dockedViews.get(vm);
@@ -186,7 +199,8 @@ export function attachDockedScriptLayout({vm, workspace, ScratchBlocks, canUse,
186
199
  };
187
200
  const view = attachScriptView({workspace, ScratchBlocks, getLocale: () => injection.ownerDocument.documentElement.lang || locale,
188
201
  canShowBlock: canArrange, relations: {vm: vm as ScriptRelationContext['vm'],
189
- getTarget: () => vm.editingTarget as ReturnType<ScriptRelationContext['getTarget']>}});
202
+ getTarget: () => vm.editingTarget as ReturnType<ScriptRelationContext['getTarget']>,
203
+ initialVisibility: getDockedRelationVisibility(vm)}});
190
204
  host.setAttribute('data-code-hover-surface', '');
191
205
  let dialog: ReturnType<typeof openRearrangement> | undefined;
192
206
  const attachment = {
@@ -5,6 +5,7 @@ import {getCodeSession} from './workspace.ts';
5
5
 
6
6
  export {attachCodeWorkspace} from './workspace.ts';
7
7
  export {fitScriptInWorkspace} from './script-fit.ts';
8
+ export {attachWorkspaceOverview} from './workspace-overview.ts';
8
9
  export {attachFunctionCallMenu, createCodePaneAdapter, createFunction, mountProcedureEditor, readHatScripts, readSavedCodePane, readScriptRelationGraph} from './code-pane.ts';
9
10
  export type {SavedCodePane} from './code-pane.ts';
10
11
 
package/src/styles.css CHANGED
@@ -525,6 +525,38 @@
525
525
  --tw-script-message-stroke: light-dark(#a85a00, #ffbd66);
526
526
  }
527
527
 
528
+ .tw-workspace-overview {
529
+ position: absolute;
530
+ z-index: 1;
531
+ box-sizing: border-box;
532
+ overflow: hidden;
533
+ cursor: pointer;
534
+ color: var(--text-primary, #334155);
535
+ background: color-mix(in srgb, var(--ui-primary, white) 50%, transparent);
536
+ border: 1px solid var(--ui-black-transparent, #cbd5e1);
537
+ border-radius: 8px;
538
+ box-shadow: 0 2px 8px rgb(0 0 0 / 20%);
539
+ }
540
+ .tw-workspace-overview[hidden] { display: none; }
541
+ .tw-workspace-overview-viewport {
542
+ cursor: grab;
543
+ fill: currentColor;
544
+ fill-opacity: .06;
545
+ stroke: currentColor;
546
+ stroke-width: 1.5px;
547
+ vector-effect: non-scaling-stroke;
548
+ }
549
+ .tw-workspace-overview[data-dragging], .tw-workspace-overview[data-dragging] .tw-workspace-overview-viewport { cursor: grabbing; }
550
+ [dir] .tw-workspace-overview-watermark[data-plus-workspace-watermark] {
551
+ inset: auto var(--plus-watermark-right, 1.25rem) var(--plus-watermark-bottom, 1.25rem) auto;
552
+ }
553
+ .tw-workspace-overview-watermark > img {
554
+ display: block;
555
+ max-width: var(--plus-watermark-size, 64px);
556
+ max-height: var(--plus-watermark-size, 64px);
557
+ opacity: .6;
558
+ }
559
+
528
560
  [data-script-relation="function"] {
529
561
  --tw-script-relation-stroke: var(--tw-script-function-stroke);
530
562
  --tw-script-relation-dash: none;
@@ -543,7 +575,7 @@
543
575
  fill: none;
544
576
  stroke: var(--tw-script-relation-stroke);
545
577
  stroke-width: 1.8;
546
- stroke-opacity: 0.75;
578
+ stroke-opacity: 0.2;
547
579
  vector-effect: non-scaling-stroke;
548
580
  pointer-events: none;
549
581
  }
@@ -561,6 +593,14 @@
561
593
  stroke-opacity: 0.2;
562
594
  }
563
595
 
596
+ [data-script-relation-layer] > [data-script-relation][data-script-external] {
597
+ opacity: 0.05;
598
+ }
599
+
600
+ [data-script-relation-layer] > [data-script-relation][data-script-external] :is(.tw-script-relation-line, .tw-script-relation-head) {
601
+ stroke-opacity: 1;
602
+ }
603
+
564
604
  .tw-script-relation-script-highlight {
565
605
  fill: light-dark(#3373cc, #93c5fd);
566
606
  fill-opacity: 0.1;