@kubohiroya/turbowarp-plus-editor-code-views 0.21.3 → 0.22.1

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,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,25 +23,27 @@ 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};
27
- const ns = 'http://www.w3.org/2000/svg';
28
- // Keep the same sixteen-unit hourglass as the call graph's relation badge.
29
- const relationWaitGlyph = 'M1 1h14M1 15h14M2 1v3l12 8v3M14 1v3l-12 8v3M2 4h12M2 12h12';
26
+ type Drawing = {relation: ScriptRelation; source?: Anchor; destination?: Anchor; count: number;
27
+ serialRoute?: {right: number; top: number; clearance: number; radius: number}};
30
28
 
31
- /** Keep the badge beside the receiving end of the cubic curve, leaving its stroke visible. */
32
- function waitBadgePoint(path: string, offset: number): Point {
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);
36
- const endX = tx - bx;
37
- const endY = ty - by;
38
- const dx = endX || endY ? endX : tx - sx;
39
- const dy = endX || endY ? endY : ty - sy;
40
- const length = Math.hypot(dx, dy) || 1;
41
- const side = -dy < 0 || dy === 0 && dx > 0 ? -1 : 1;
42
- return {x: tx - dx / length * offset * .75 - dy / length * offset * side,
43
- y: ty - dy / length * offset * .75 + dx / length * offset * side};
29
+ function roundedRoute(points: Point[], radii: readonly 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(radii[index - 1], 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}`;
44
45
  }
46
+ const ns = 'http://www.w3.org/2000/svg';
45
47
  type Outline = {points: (Point & {distance: number})[]; cuts: Map<string, Point>};
46
48
  const outlines = new Map<string, Outline>();
47
49
 
@@ -150,6 +152,8 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
150
152
  let geometryChanged = true;
151
153
  let lastMatrix: DOMMatrix | undefined;
152
154
  let edgeDrawings: {key: string; drawing: Drawing; group: SVGGElement; highlighted: boolean}[] = [];
155
+ let viewportDrawings: {drawing: Drawing; visible: boolean}[] = [];
156
+ let measuredAnchors = new Map<string, Anchor | undefined>();
153
157
  const renderedGroups = new WeakMap<SVGGElement, Map<string, SVGGElement>>();
154
158
  const syncTransform = (matrix: DOMMatrix) => {
155
159
  // Workspace dragging lends the two native canvases to a separate SVG which must keep exactly two children.
@@ -214,15 +218,25 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
214
218
  if (endpoint.targetId !== target.id) return;
215
219
  const top = blockRoot(endpoint.scriptId, roots);
216
220
  // 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;
221
+ if (!top || top.closest('[data-tw-plus-hidden]')) return;
222
+ // Native viewport culling hides the whole stack, but its real endpoints still exist.
223
+ const culled = !projection && top.style.display === 'none';
224
+ if (!culled && !top.getClientRects().length) return;
219
225
  const folded = isFoldedDefinition(target.blocks._blocks[endpoint.scriptId]);
220
226
  let id = folded ? endpoint.scriptId : endpoint.blockId;
221
227
  let root = blockRoot(id, roots);
222
228
  // Native Blockly collapsing can also hide a caller inside a control block.
223
229
  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)) {
230
+ const hidden = (node: SVGElement) => {
231
+ if (node.closest('[data-tw-plus-hidden]')) return true;
232
+ if (!culled) return !node.getClientRects().length || view.getComputedStyle(node).display === 'none';
233
+ // A collapsed parent below the culled stack still needs its visible proxy anchor.
234
+ for (let ancestor = node; ancestor && ancestor !== top; ancestor = ancestor.parentElement as unknown as SVGElement) {
235
+ if (view.getComputedStyle(ancestor).display === 'none') return true;
236
+ }
237
+ return false;
238
+ };
239
+ while (root && hidden(root) && !visited.has(id)) {
226
240
  visited.add(id);
227
241
  id = target.blocks._blocks[id]?.parent ?? '';
228
242
  root = blockRoot(id, roots);
@@ -249,7 +263,7 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
249
263
  }};
250
264
  }
251
265
 
252
- function arrowGeometry({relation, source, destination, count}: Drawing, matrix: DOMMatrix, inverse: DOMMatrix,
266
+ function arrowGeometry({relation, source, destination, count, serialRoute}: Drawing, matrix: DOMMatrix, inverse: DOMMatrix,
253
267
  area: DOMRect, highlighted: boolean) {
254
268
  // Anchor an external link to the viewport edge; the list itself remains keyboard accessible.
255
269
  const local = source ?? destination;
@@ -274,19 +288,21 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
274
288
  ` C ${left} ${top}, ${left} ${end.y}, ${end.x} ${end.y}`;
275
289
  badgePoint = {x: middle, y: top - 6};
276
290
  }
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 point = waitBadgePoint(path, 24);
281
- badgePoint = {x: point.x + 16, y: point.y + 4};
282
- waitTransform = `translate(${point.x} ${point.y})`;
291
+ if (serialRoute && source && destination) {
292
+ const {right, top, clearance, radius} = serialRoute;
293
+ // Leave room beside every script before turning vertically, then return through the gap above the hat.
294
+ const approach = end.x - clearance;
295
+ path = roundedRoute([start, {x: right, y: start.y}, {x: right, y: top},
296
+ {x: approach, y: top}, {x: approach, y: end.y}, end], [radius, radius, clearance, clearance]);
297
+ badgePoint = {x: right, y: (start.y + top) / 2};
283
298
  }
284
- return {path, head, recursive, badgePoint, waitTransform};
299
+ const head = `M ${end.x - 9} ${end.y - 5} L ${end.x} ${end.y} L ${end.x - 9} ${end.y + 5}`;
300
+ return {path, head, recursive, badgePoint};
285
301
  }
286
302
 
287
303
  function drawArrow(drawing: Drawing, matrix: DOMMatrix, inverse: DOMMatrix, area: DOMRect, highlighted: boolean) {
288
304
  const {relation, source, destination, count} = drawing;
289
- const {path, head, recursive, badgePoint, waitTransform} = arrowGeometry(drawing, matrix, inverse, area, highlighted);
305
+ const {path, head, recursive, badgePoint} = arrowGeometry(drawing, matrix, inverse, area, highlighted);
290
306
  const strings = text();
291
307
  const group = element('g', {
292
308
  'data-script-relation': relation.kind,
@@ -309,24 +325,25 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
309
325
  class: 'tw-script-relation-head',
310
326
  d: head
311
327
  }));
312
- if (waiting) {
313
- const badge = element('g', {class: 'tw-script-relation-wait', 'aria-label': strings.wait,
314
- transform: waitTransform});
315
- const title = element('title');
316
- title.textContent = strings.wait;
317
- badge.append(title, element('rect', {x: '-10', y: '-10', width: '20', height: '20', rx: '4'}),
318
- element('path', {class: 'tw-script-relation-wait-glyph', d: relationWaitGlyph, transform: 'translate(-8 -8)'}));
319
- group.append(badge);
320
- }
321
328
  if (count > 1) {
322
329
  const badge = element('text', {x: String(badgePoint.x), y: String(badgePoint.y),
323
- class: 'tw-script-relation-badge', 'text-anchor': waiting ? 'start' : 'middle'});
330
+ class: 'tw-script-relation-badge', 'text-anchor': 'middle'});
324
331
  badge.textContent = `×${count}`;
325
332
  group.append(badge);
326
333
  }
327
334
  return group;
328
335
  }
329
336
 
337
+ function inViewport({source, destination}: Drawing, matrix: DOMMatrix, area: DOMRect) {
338
+ return [source, destination].some(anchor => {
339
+ if (!anchor) return false;
340
+ const first = transform(matrix, anchor.box);
341
+ const last = transform(matrix, {x: anchor.box.x + anchor.box.width, y: anchor.box.y + anchor.box.height});
342
+ return Math.max(first.x, last.x) > area.left && Math.min(first.x, last.x) < area.right &&
343
+ Math.max(first.y, last.y) > area.top && Math.min(first.y, last.y) < area.bottom;
344
+ });
345
+ }
346
+
330
347
  function render() {
331
348
  frame = undefined;
332
349
  if (disposed) return;
@@ -353,7 +370,9 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
353
370
  const area = (projection ?? workspace.getParentSvg()).getBoundingClientRect();
354
371
  const sameScale = lastMatrix && matrix.a === lastMatrix.a && matrix.b === lastMatrix.b &&
355
372
  matrix.c === lastMatrix.c && matrix.d === lastMatrix.d;
356
- if (!geometryChanged && !projection && sameScale) {
373
+ const reuseAnchors = !geometryChanged && !projection && sameScale;
374
+ if (reuseAnchors &&
375
+ viewportDrawings.every(item => item.visible === inViewport(item.drawing, matrix, area))) {
357
376
  const geometry = edgeDrawings.map(item => ({...item,
358
377
  shape: arrowGeometry(item.drawing, matrix, inverse, area, item.highlighted)}));
359
378
  syncTransform(matrix);
@@ -363,7 +382,6 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
363
382
  };
364
383
  set(group.querySelector('.tw-script-relation-line'), 'd', shape.path);
365
384
  set(group.querySelector('.tw-script-relation-head'), 'd', shape.head);
366
- if (shape.waitTransform) set(group.querySelector('.tw-script-relation-wait'), 'transform', shape.waitTransform);
367
385
  const count = group.querySelector('.tw-script-relation-badge');
368
386
  set(count, 'x', shape.badgePoint.x); set(count, 'y', shape.badgePoint.y);
369
387
  }
@@ -373,6 +391,8 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
373
391
  geometryChanged = false;
374
392
  lastMatrix = matrix;
375
393
  edgeDrawings = [];
394
+ viewportDrawings = [];
395
+ if (!reuseAnchors) measuredAnchors = new Map();
376
396
  const paint: SVGElement[] = [];
377
397
  const guides = document.createDocumentFragment();
378
398
  const previousGroups = renderedGroups.get(drawingLayer);
@@ -395,11 +415,10 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
395
415
  const inDrag = (endpoint?: ScriptEndpoint) => Boolean(endpoint && endpoint.targetId === target.id && draggedIds.has(endpoint.blockId));
396
416
  const incident = (relation: ScriptRelation) => inDrag(relation.source) || inDrag(relation.destination);
397
417
  const drawings = new Map<string, Drawing>();
398
- const anchors = new Map<string, Anchor | undefined>();
399
418
  const measuredAnchor = (endpoint: ScriptEndpoint) => {
400
419
  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);
420
+ if (!measuredAnchors.has(key)) measuredAnchors.set(key, anchor(endpoint, target, roots, inverse));
421
+ return measuredAnchors.get(key);
403
422
  };
404
423
  for (const relation of graph) {
405
424
  if (!visibility[relation.kind]) continue;
@@ -413,6 +432,35 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
413
432
  if (existing) existing.count++;
414
433
  else drawings.set(key, {relation, source, destination, count: 1});
415
434
  }
435
+ if (projection) {
436
+ const unit = 1 / (Math.hypot(matrix.a, matrix.b) || 1);
437
+ const scripts = new Map<string, Box>();
438
+ for (const root of projection.querySelectorAll<SVGGraphicsElement>('[data-script-view-block]')) {
439
+ const rect = root.getBoundingClientRect();
440
+ const first = transform(inverse, {x: rect.left, y: rect.top});
441
+ const last = transform(inverse, {x: rect.right, y: rect.bottom});
442
+ scripts.set(root.getAttribute('data-script-view-block'),
443
+ {x: first.x, y: first.y, width: last.x - first.x, height: last.y - first.y});
444
+ }
445
+ const rightEdge = [...scripts.values()].reduce((edge, box) => Math.max(edge, box.x + box.width), 0);
446
+ let lane = 0;
447
+ for (const drawing of drawings.values()) {
448
+ if (!drawing.source || !drawing.destination) continue;
449
+ const destination = scripts.get(drawing.relation.destination.scriptId);
450
+ if (!destination) continue;
451
+ drawing.serialRoute = {right: rightEdge + (96 + lane * 16) * unit,
452
+ top: destination.y - (14 + lane % 4 * 6) * unit, clearance: 8 * unit, radius: 48 * unit};
453
+ lane++;
454
+ }
455
+ // Reserve actual scrollable SVG width for the right-hand routes while preserving the block scale.
456
+ const box = projection.viewBox.baseVal;
457
+ const width = Math.ceil(rightEdge + (112 + Math.max(0, lane - 1) * 16) * unit);
458
+ if (lane && width > box.width) {
459
+ const scale = Math.hypot(matrix.a, matrix.b);
460
+ projection.setAttribute('viewBox', `${box.x} ${box.y} ${width} ${box.height}`);
461
+ projection.setAttribute('width', String(width * scale));
462
+ }
463
+ }
416
464
  const related = new Set<string>();
417
465
  for (const relation of graph) if (visibility[relation.kind] && dragging && incident(relation)) {
418
466
  if (inDrag(relation.source) && relation.destination?.targetId === target.id && !inDrag(relation.destination)) {
@@ -428,7 +476,7 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
428
476
  const root = blockRoot(id, roots);
429
477
  if (root && root.getClientRects().length && !root.closest('[data-tw-plus-hidden]')) marked.set(root, 'related');
430
478
  }
431
- // Frame the whole stack, including its body; the original block paint and runtime glow stay intact.
479
+ // Shade the whole stack, including its body; the original block paint and runtime glow stay intact.
432
480
  for (const [root, role] of marked) {
433
481
  const bounds = root.getBoundingClientRect();
434
482
  const first = transform(inverse, {x: bounds.left, y: bounds.top});
@@ -438,6 +486,9 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
438
486
  rx: '10', class: 'tw-script-relation-script-highlight', 'data-emphasis': role}));
439
487
  }
440
488
  for (const [key, drawing] of drawings) {
489
+ const visible = inViewport(drawing, matrix, area);
490
+ viewportDrawings.push({drawing, visible});
491
+ if (!visible) continue;
441
492
  const {relation, source, destination, count} = drawing;
442
493
  const highlighted = dragging ? incident(relation) :
443
494
  emphasized && (emphasized === relation.source.scriptId || emphasized === relation.destination?.scriptId);
@@ -451,7 +502,7 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
451
502
  vm?.runtime?.targets?.find(item => item.id === endpoint.targetId)?.getName?.());
452
503
  const reason = relation.unresolved && strings[relation.unresolved];
453
504
  external.textContent = `${name ? `${name} · ` : ''}` +
454
- `${relation.label}${reason ? ` · ${reason}` : ''}${relation.kind === 'message' && relation.wait ? ' ⏳' : ''}${count > 1 ? ` ×${count}` : ''}`;
505
+ `${relation.label}${reason ? ` · ${reason}` : ''}${count > 1 ? ` ×${count}` : ''}`;
455
506
  external.disabled = !endpoint;
456
507
  external.setAttribute('aria-label', `${strings[relation.kind]}: ${external.textContent}`);
457
508
  external.toggleAttribute('data-highlighted', Boolean(highlighted));
@@ -489,6 +540,8 @@ export function attachScriptArrows({workspace, vm, getTarget, getRelations, getL
489
540
  if (destinations.childElementCount) destinations.replaceChildren();
490
541
  destinations.hidden = true;
491
542
  edgeDrawings = [];
543
+ viewportDrawings = [];
544
+ measuredAnchors.clear();
492
545
  lastMatrix = undefined;
493
546
  renderedGroups.delete(layer);
494
547
  if (projectedLayer) renderedGroups.delete(projectedLayer);
@@ -5,6 +5,9 @@ import {attachScriptViewMenu, type ScriptViewMenuBlocks, type ScriptViewMenuWork
5
5
  import type {PresentationElements} from './preview-chrome.ts';
6
6
  import {attachScriptArrows, type ScriptRelationContext, type ScriptRelationVisibility} from './script-arrows.ts';
7
7
  import {attachCodeZoomRange} from './code-zoom.ts';
8
+ import {setScriptProjection} from './script-projection.ts';
9
+ import {openSerialScriptEditor} from './serial-script-editor.ts';
10
+ import {isFoldedDefinition, setFoldedDefinition} from './procedure-edits.ts';
8
11
 
9
12
  export type ScriptView = 'free' | 'z' | 'n';
10
13
 
@@ -39,10 +42,15 @@ export function attachScriptView({
39
42
  surface.className = 'tw-script-view-surface';
40
43
  surface.dataset.codeViewControl = '';
41
44
  surface.tabIndex = 0;
42
- surface.toggleAttribute('data-can-show-block', Boolean(canShowBlock));
45
+ surface.toggleAttribute('data-can-show-block', Boolean(canShowBlock || relationContext?.vm));
43
46
  const contents = document.createElement('div');
44
47
  surface.append(contents);
48
+ const gutter = document.createElement('div');
49
+ gutter.className = 'tw-script-fold-gutter';
50
+ gutter.dataset.codeViewControl = '';
51
+ const foldButtons = new Map<string, {button: HTMLButtonElement; top: number}>();
45
52
  let view = initialView;
53
+ let editor: ReturnType<typeof openSerialScriptEditor>;
46
54
  let frame: number | undefined;
47
55
  const svg = workspace.getParentSvg();
48
56
  const observer = new window.MutationObserver(records => {
@@ -51,6 +59,69 @@ export function attachScriptView({
51
59
  const relations = relationContext && attachScriptArrows({workspace, getLocale, ...relationContext});
52
60
  const japanese = () => /^ja(?:-|$)/i.test(getLocale());
53
61
 
62
+ function setFold(ids: string[], value?: boolean) {
63
+ const target = relationContext?.getTarget();
64
+ const runtime = relationContext?.vm?.runtime as {emitProjectChanged?(): void} | undefined;
65
+ if (!target || !runtime?.emitProjectChanged || (canShowBlock && !canShowBlock())) return;
66
+ for (const id of ids) {
67
+ const block = target.blocks._blocks[id];
68
+ if (block) setFoldedDefinition(block, value ?? !isFoldedDefinition(block));
69
+ }
70
+ runtime.emitProjectChanged();
71
+ update();
72
+ }
73
+
74
+ function positionFoldButtons() {
75
+ gutter.style.left = `${surface.offsetLeft}px`;
76
+ gutter.style.top = `${surface.offsetTop}px`;
77
+ gutter.style.height = `${surface.clientHeight}px`;
78
+ for (const {button, top} of foldButtons.values()) button.style.top = `${top - surface.scrollTop}px`;
79
+ }
80
+
81
+ function paintFoldButtons(placements: ReturnType<typeof arrangeScripts>, scale: number) {
82
+ const target = relationContext?.getTarget();
83
+ const ids = new Set(placements.map(({script}) => script.id));
84
+ for (const [id, {button}] of foldButtons) if (!ids.has(id)) {button.remove(); foldButtons.delete(id);}
85
+ for (const {script, y} of placements) {
86
+ let entry = foldButtons.get(script.id);
87
+ if (!entry) {
88
+ const button = document.createElement('button');
89
+ button.type = 'button';
90
+ button.dataset.scriptFoldToggle = script.id;
91
+ button.addEventListener('click', event => {event.stopPropagation(); setFold([script.id]);});
92
+ button.addEventListener('pointerdown', event => event.stopPropagation());
93
+ entry = {button, top: 0};
94
+ foldButtons.set(script.id, entry);
95
+ gutter.append(button);
96
+ }
97
+ const block = target?.blocks._blocks[script.id];
98
+ const folded = isFoldedDefinition(block);
99
+ const label = japanese() ? (folded ? '折りたたみを解除' : '折りたたむ') : (folded ? 'Unfold script' : 'Fold script');
100
+ entry.top = y * scale;
101
+ entry.button.textContent = folded ? '▶' : '▼';
102
+ entry.button.disabled = !block || Boolean(canShowBlock && !canShowBlock());
103
+ entry.button.setAttribute('aria-label', label);
104
+ entry.button.setAttribute('aria-expanded', String(!folded));
105
+ entry.button.title = label;
106
+ }
107
+ positionFoldButtons();
108
+ }
109
+
110
+ function foldOptions() {
111
+ const target = relationContext?.getTarget();
112
+ const runtime = relationContext?.vm?.runtime as {emitProjectChanged?(): void} | undefined;
113
+ if (view === 'free' || !target || !runtime?.emitProjectChanged || (canShowBlock && !canShowBlock())) return [];
114
+ const roots = readScripts(workspace).map(script => target.blocks._blocks[script.id]).filter(Boolean);
115
+ const options = [
116
+ {value: true, text: japanese() ? 'すべて折りたたむ' : 'Fold all'},
117
+ {value: false, text: japanese() ? '折りたたみをすべて解除' : 'Unfold all'}
118
+ ];
119
+ return options.map(({value, text}) => ({text,
120
+ enabled: roots.some(block => isFoldedDefinition(block) !== value),
121
+ callback() {setFold(readScripts(workspace).map(script => script.id), value);}
122
+ }));
123
+ }
124
+
54
125
  function labels() {
55
126
  const choice = choices.find(choice => choice.view === view);
56
127
  surface.setAttribute('aria-label', japanese() ? choice.jaLabel : choice.label);
@@ -63,6 +134,7 @@ export function attachScriptView({
63
134
  const ja = japanese();
64
135
  return {
65
136
  label: ja ? 'コードの並びの見え方を変更する' : 'Change code layout view',
137
+ options: foldOptions(),
66
138
  choices: choices.map(choice => ({
67
139
  text: ja ? choice.jaLabel : choice.label,
68
140
  enabled: true,
@@ -85,8 +157,21 @@ export function attachScriptView({
85
157
  surface.style.setProperty('--tw-script-view-left', !horizontal && bounds.left <= left + 2 ? `${bounds.width}px` : '0px');
86
158
  surface.style.setProperty('--tw-script-view-right', !horizontal && bounds.right >= right - 2 ? `${bounds.width}px` : '0px');
87
159
  }
88
- paintScripts(contents, arrangeScripts(readScripts(workspace), view, 'vertical'), workspace.scale || 1);
89
- relations?.setProjection(contents.querySelector('svg'));
160
+ const scale = workspace.scale || 1;
161
+ const scripts = readScripts(workspace).map(script => {
162
+ // Include raised hats and labels, and exclude folded bodies, when measuring the visible gap.
163
+ const box = (script.root as SVGGraphicsElement).getBBox();
164
+ return {...script, x: script.origin.x + box.x, y: script.origin.y + box.y,
165
+ width: box.width, height: box.height};
166
+ });
167
+ const placements = arrangeScripts(scripts, view, 'vertical', Math.max(64, 48 / scale))
168
+ // Leave room for incoming arrowheads and return paths beside the fixed fold gutter.
169
+ .map(placement => ({...placement, x: placement.x + 40 / scale}));
170
+ paintScripts(contents, placements, scale);
171
+ paintFoldButtons(placements, scale);
172
+ const projection = contents.querySelector('svg');
173
+ relations?.setProjection(projection);
174
+ setScriptProjection(workspace, {surface, svg: projection});
90
175
  }
91
176
 
92
177
  function update() {
@@ -96,14 +181,20 @@ export function attachScriptView({
96
181
 
97
182
  function setView(next: ScriptView) {
98
183
  menu.close();
184
+ editor?.dispose();
185
+ editor = undefined;
99
186
  observer.disconnect();
100
187
  view = next;
101
188
  surface.hidden = view === 'free';
189
+ gutter.hidden = view === 'free';
102
190
  svg.toggleAttribute('data-script-serial', view !== 'free');
103
191
  labels();
104
192
  if (view === 'free') {
193
+ setScriptProjection(workspace);
105
194
  relations?.setProjection(null);
106
195
  contents.replaceChildren();
196
+ gutter.replaceChildren();
197
+ foldButtons.clear();
107
198
  }
108
199
  else {
109
200
  observer.observe(workspace.getCanvas(), {attributes: true, childList: true, subtree: true});
@@ -120,19 +211,33 @@ export function attachScriptView({
120
211
  surface.addEventListener('click', event => {
121
212
  event.stopPropagation();
122
213
  const id = (event.target as Element).closest('[data-script-view-block]')?.getAttribute('data-script-view-block');
123
- if (!id || !canShowBlock?.()) return;
214
+ if (!id || (canShowBlock && !canShowBlock())) return;
215
+ if (relationContext?.vm) {
216
+ editor?.dispose();
217
+ editor = openSerialScriptEditor(relationContext.vm, relationContext.getTarget(), id, document, getLocale());
218
+ if (editor) return;
219
+ }
220
+ if (!canShowBlock?.()) return;
124
221
  chooseView('free');
125
222
  workspace.centerOnBlock(id);
126
223
  });
127
224
  const resize = new window.ResizeObserver(update);
128
225
  resize.observe(host);
129
- const language = new window.MutationObserver(labels);
226
+ const language = new window.MutationObserver(() => {labels(); update();});
130
227
  language.observe(document.documentElement, {attributes: true, attributeFilter: ['lang']});
131
228
  // The Blockly keyboard listener is document-wide.
132
229
  surface.addEventListener('keydown', event => {
133
230
  if (event.key !== 'Tab') event.stopPropagation();
134
231
  });
135
- host.append(surface);
232
+ gutter.addEventListener('keydown', event => {
233
+ if (event.key !== 'Tab') event.stopPropagation();
234
+ });
235
+ host.append(surface, gutter);
236
+ surface.addEventListener('scroll', () => {
237
+ positionFoldButtons();
238
+ const projection = contents.querySelector('svg');
239
+ if (view !== 'free' && projection) setScriptProjection(workspace, {surface, svg: projection});
240
+ }, {passive: true});
136
241
  setView(initialView);
137
242
  return {
138
243
  update,
@@ -141,6 +246,8 @@ export function attachScriptView({
141
246
  get view() { return view; },
142
247
  setView,
143
248
  dispose() {
249
+ editor?.dispose();
250
+ setScriptProjection(workspace);
144
251
  restoreZoomRange();
145
252
  resize.disconnect();
146
253
  observer.disconnect();
@@ -149,6 +256,8 @@ export function attachScriptView({
149
256
  menu.dispose();
150
257
  relations?.dispose();
151
258
  surface.remove();
259
+ gutter.remove();
260
+ foldButtons.clear();
152
261
  svg.removeAttribute('data-script-serial');
153
262
  }
154
263
  };
@@ -40,9 +40,14 @@ export interface RenderedScript extends ScriptBounds {
40
40
  export function readScripts(workspace: LayoutWorkspace): RenderedScript[] {
41
41
  return workspace.getTopBlocks(false).flatMap(block => {
42
42
  const root = block.getSvgRoot();
43
- if (!root || !workspace.getCanvas().contains(root)) return [];
43
+ if (!root || !workspace.getCanvas().contains(root) || root.hasAttribute('data-tw-plus-hidden')) return [];
44
44
  const origin = block.getRelativeToSurfaceXY();
45
- const {topLeft, bottomRight} = block.getBoundingRectangle();
45
+ let {topLeft, bottomRight} = block.getBoundingRectangle();
46
+ if (root.querySelector(':scope > [data-tw-plus-folded-mark]')) {
47
+ const box = (root as SVGGraphicsElement).getBBox();
48
+ topLeft = {x: origin.x + box.x, y: origin.y + box.y};
49
+ bottomRight = {x: topLeft.x + box.width, y: topLeft.y + box.height};
50
+ }
46
51
  return [{
47
52
  id: block.id, block, root, origin, ...topLeft,
48
53
  width: bottomRight.x - topLeft.x, height: bottomRight.y - topLeft.y
@@ -15,7 +15,8 @@ export type LayoutDirection = 'vertical' | 'horizontal';
15
15
  const alignmentTolerance = 24;
16
16
  const spacing = 32;
17
17
 
18
- export function arrangeScripts<T extends ScriptBounds>(scripts: readonly T[], order: ScriptOrder, direction: LayoutDirection) {
18
+ export function arrangeScripts<T extends ScriptBounds>(scripts: readonly T[], order: ScriptOrder, direction: LayoutDirection,
19
+ gap = spacing) {
19
20
  const bandAxis = order === 'z' ? 'y' : 'x';
20
21
  const scanAxis = order === 'z' ? 'x' : 'y';
21
22
  const compare = (a: T, b: T, first: 'x' | 'y', second: 'x' | 'y') =>
@@ -29,12 +30,12 @@ export function arrangeScripts<T extends ScriptBounds>(scripts: readonly T[], or
29
30
  else bands.push([script]);
30
31
  }
31
32
 
32
- let offset = spacing;
33
+ let offset = gap;
33
34
  return bands.flatMap(band => band.sort((a, b) => compare(a, b, scanAxis, bandAxis))).map(script => {
34
35
  const vertical = direction === 'vertical';
35
36
  const x = vertical ? spacing : offset;
36
37
  const y = vertical ? offset : spacing;
37
- offset += Math.ceil(vertical ? script.height : script.width) + spacing;
38
+ offset += Math.ceil(vertical ? script.height : script.width) + gap;
38
39
  return {script, x, y};
39
40
  });
40
41
  }
@@ -0,0 +1,12 @@
1
+ export type ScriptProjection = {surface: HTMLElement; svg: SVGSVGElement};
2
+
3
+ const projections = new WeakMap<object, ScriptProjection>();
4
+
5
+ export const getScriptProjection = (workspace: object) => projections.get(workspace);
6
+
7
+ export function setScriptProjection(workspace: {getInjectionDiv(): HTMLElement}, projection?: ScriptProjection) {
8
+ if (projection) projections.set(workspace, projection);
9
+ else projections.delete(workspace);
10
+ const container = workspace.getInjectionDiv();
11
+ container.dispatchEvent(new container.ownerDocument.defaultView.Event('scriptprojectionchange'));
12
+ }
@@ -40,6 +40,7 @@ export interface ScriptViewMenuWorkspace {
40
40
 
41
41
  interface MenuConfig {
42
42
  label: string;
43
+ options?: MenuOption[];
43
44
  choices: (MenuOption & {checked: boolean})[];
44
45
  }
45
46
 
@@ -160,7 +161,7 @@ export function attachScriptViewMenu(
160
161
  // Only extend the options collected for this workspace, after the existing add-ons.
161
162
  ContextMenu.populate_ = (options, rtl) => {
162
163
  const config = getMenu();
163
- const menu = populate.call(ContextMenu, [...options, triggerOption(config.label)], rtl);
164
+ const menu = populate.call(ContextMenu, [...options, triggerOption(config.label), ...(config.options ?? [])], rtl);
164
165
  addSubmenu(menu, options.length, config, rtl, ContextMenu);
165
166
  return menu;
166
167
  };
@@ -177,7 +178,9 @@ export function attachScriptViewMenu(
177
178
  event.stopPropagation();
178
179
  const config = getMenu();
179
180
  const rtl = workspace.RTL;
180
- const menu = ContextMenu.populate_([triggerOption(config.label)], rtl);
181
+ const menu = ContextMenu.populate_([triggerOption(config.label), ...(config.options ?? []).map(option => ({...option,
182
+ callback() {WidgetDiv.hideIfOwner(surface); option.callback();}
183
+ }))], rtl);
181
184
  const outside = new document.defaultView.AbortController();
182
185
  WidgetDiv.show(surface, rtl, () => {
183
186
  outside.abort();
@@ -0,0 +1,41 @@
1
+ import {getCodeSession} from './workspace.ts';
2
+
3
+ /** Reuse the script editor: its root stays at its original project coordinates. */
4
+ export function openSerialScriptEditor(vm: object, target, id: string, document: Document, locale: string) {
5
+ const bridge = getCodeSession(vm).bridge;
6
+ if (!bridge || !target?.blocks._blocks[id]) 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: ReturnType<typeof bridge.editProcedure>;
22
+ try {
23
+ editor = bridge.editProcedure(area, {target, definitionId: id, editable: true, locale});
24
+ } catch (error) {
25
+ dialog.close();
26
+ dialog.remove();
27
+ throw error;
28
+ }
29
+ let closed = false;
30
+ const dispose = () => {
31
+ if (closed) return;
32
+ closed = true;
33
+ editor.flush();
34
+ editor.dispose();
35
+ dialog.close();
36
+ dialog.remove();
37
+ };
38
+ close.addEventListener('click', dispose);
39
+ dialog.addEventListener('cancel', event => {event.preventDefault(); dispose();});
40
+ return {dispose};
41
+ }