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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.ja.md CHANGED
@@ -10,6 +10,12 @@ TurboWarp Plus Editor のコードの画面。1つの作品と1つの取り消
10
10
 
11
11
  ホストが独立したワークスペースを表示する場合は、ルートまたは `./sprite-code-windows` の `fitScriptInWorkspace(workspace, scriptId, ScratchBlocks)` を使える。表示領域やブロックがまだない場合は `false` を返すので、レイアウト後に再試行する。
12
12
 
13
+ Z/N配置のミニマップは、表示中のスクリプトの並びとスクロール範囲を示す。スクリプトをクリックすると内容の編集画面を開き、閉じた後もZ/N配置を保つ。編集画面では先頭ブロックを固定し、作品に保存する自由配置の座標を動かさない。スクリプト間の余白は64単位以上、画面上で48px以上を確保する。背景の右クリックメニューで「すべて折りたたむ」「折りたたみをすべて解除」を利用できる。
14
+
15
+ Z/N配置内の矢印は、スクリプト群の右外側へ96px以上張り出し、経路を分けて上下に曲がる。左縁の▼/▶ボタンは各スクリプトの上端に並び、クリックやEnter/Spaceで個別に折りたたみを切り替えられる。横スクロール中も左縁に残り、縦スクロールとズームにはスクリプトと一緒に追従する。
16
+
17
+ これらの変更の切り戻しは、本変更を revert して再ビルドする。ホストのパッケージ固定を以前の版へ戻す場合は、機能移管で追加された API との互換性も確認する。自由配置へ切り替えるだけでも元の配置を表示できる。折りたたみは既存の作品内フラグを使用するため、「折りたたみをすべて解除」で解除できる。
18
+
13
19
  ## 入口
14
20
 
15
21
  | import | 内容 |
@@ -47,6 +53,8 @@ TurboWarp Plus Editor のコードの画面。1つの作品と1つの取り消
47
53
 
48
54
  Editor は GUI の React 16 にこれらを描画するので、React 16.14 以降に対応する。
49
55
 
56
+ 自由配置のブロックの右クリックメニューの先頭に「このスクリプトを個別の画面で編集する」、2番目に「このスクリプトの呼び出し関係を開く」を表示する。途中のブロックや関数呼び出しを選んだ場合も、そのブロックを含むスクリプト全体を開く。ホストは `attachFunctionCallMenu` の `scriptEditor: {vm, locale, open(scriptId, blockId, section)}` を既存の個別編集ペインへ接続する。`section` は先頭の項目では `functions`、2番目では `calls`。左側をハット・関数一覧または中央フォーカスした呼び出し関係にし、右側で編集する。Z/N表示、パレット、読み取り専用、個別編集中の画面には追加しない。既存の「この関数を表示」は呼び出し先を開く項目としてその下に残す。切り戻す場合は `scriptEditor` の接続を外す。
57
+
50
58
  ## スクリプト間の矢印
51
59
 
52
60
  コードの背面に、関数呼び出しを紫系の実線、メッセージ送信を橙系の破線で表示する。「送って待つ」には待機の印を添える。通常配置、Z/N 配置、折り畳み、プレビュー、別窓で同じ表現を使う。関数の再帰はスクリプトの外へ回る線で示す。選択・ホバーによる強調は太さと不透明度で行い、関係種別の色・線種は変えない。
@@ -55,11 +63,13 @@ Editor は GUI の React 16 にこれらを描画するので、React 16.14 以
55
63
 
56
64
  通常の線と矢印の先端は20%の濃さにし、選択・ホバー・ドラッグに関連する線を強調する。ドラッグ開始時に無関係な線だけが急に薄くなることはない。
57
65
 
66
+ 矢印は、始点または終点のブロックの少なくとも一方が画面内にある場合に表示し、両方が画面外なら表示しない。画面外のブロックがネイティブの軽量化で非表示になっても接続位置を保持し、実際の接続位置へ向かう矢印を描く。スクロール・ズームでもこの表示判定を更新する。
67
+
58
68
  関係は作品データから読み、折り畳みによって表示から消えた呼び出しも保持する。展開中は呼び出しブロックから、折り畳み中は見えているハットから結ぶ。同じハットと宛先へ重なる呼び出しは件数を表示する。別スプライトや一スクリプト表示の外にある接続先は、画面端の案内から辿れる。変数などで呼び出し先が変わるものは「実行時に決定」と示し、見えていない既定値を宛先とみなさない。
59
69
 
60
70
  接続元または接続先を同じパネル内に描けない矢印は、線・矢印の先端・待機の印・件数を5%の濃さで表示する。ホバー・選択・ドラッグによる強調中も同じ濃さを維持する。
61
71
 
62
- スクリプトをドラッグしている間は、そこへ入る・そこから出る矢印を太く濃くし、画面にある相手のスクリプト全体を枠で強調する。関係しない矢印は薄くし、画面外の相手は接続先の案内を強調する。関数とメッセージの色・線種は維持する。折り畳み中も同じように働き、ドラッグの終了・矢印の非表示・画面の破棄で一時的な枠を解除する。移動中に Blockly がブロックを別の SVG へ移しても追従する。
72
+ スクリプトをドラッグしている間は、そこへ入る・そこから出る矢印を太く濃くし、画面にある相手のスクリプト全体を薄い背景色で強調する。バウンディングボックスのボーダーは表示しない。関係しない矢印は薄くし、画面外の相手は接続先の案内を強調する。関数とメッセージの色・線種は維持する。折り畳み中も同じように働き、ドラッグの終了・矢印の非表示・画面の破棄で一時的な強調を解除する。移動中に Blockly がブロックを別の SVG へ移しても追従する。
63
73
 
64
74
  `attachDockedScriptLayout` と `attachCodeWorkspace` のプレビュー・関数エディタには自動で付く。VM を持たない表示では、`attachScriptView` に `relations: {getTarget, getRelations, getTargetName, navigate}` を渡す。`getRelations` は親の `createCodeSession` が渡す `scriptRelations`、`getTarget` はその対象の `blocks` を使う。`getTargetName` は既存の対象一覧から名前を返し、同じメッセージを受信する別スプライトを案内で識別できるようにする。投影の受信後は `view.relations.update()` を呼ぶ。関係だけの更新は `relations`、接続先への移動は `relation-navigate`/`relation-focus` で既存の編集回収・対象切り替えを経由する。編集中の窓には履歴の更新のために XML を再読み込みさせない。
65
75
 
@@ -89,11 +89,17 @@ export declare function readScriptRelationGraph(targets: readonly RelationTarget
89
89
  /**
90
90
  * Add “Show this function” at the top of the menu of every block that calls a function, in the code area and
91
91
  * in the script editors. `find` names the function a block calls, if any; `open` shows it.
92
+ * With `scriptEditor`, free-layout blocks first offer to edit their own containing script.
92
93
  */
93
- export declare function attachFunctionCallMenu(ScratchBlocks: any, { label, find, open }: {
94
+ export declare function attachFunctionCallMenu(ScratchBlocks: any, { label, find, open, scriptEditor }: {
94
95
  label(): string;
95
96
  find(blockId: string): string | undefined;
96
97
  open(functionId: string): void;
98
+ scriptEditor?: {
99
+ vm: any;
100
+ locale: string;
101
+ open(scriptId: string, blockId: string, section: 'functions' | 'calls'): void;
102
+ };
97
103
  }): () => void;
98
104
  /** Add a function definition of this name to a target through the code area's bridge. Resolves with the new hat's id. */
99
105
  export declare function createFunction(vm: any, targetId: string, kind: 'procedure' | 'named', name: string, options?: {
package/dist/code-pane.js CHANGED
@@ -440,24 +440,66 @@ export function readScriptRelationGraph(targets, ScratchBlocks) {
440
440
  /**
441
441
  * Add “Show this function” at the top of the menu of every block that calls a function, in the code area and
442
442
  * in the script editors. `find` names the function a block calls, if any; `open` shows it.
443
+ * With `scriptEditor`, free-layout blocks first offer to edit their own containing script.
443
444
  */
444
- export function attachFunctionCallMenu(ScratchBlocks, { label, find, open }) {
445
+ export function attachFunctionCallMenu(ScratchBlocks, { label, find, open, scriptEditor }) {
445
446
  const prototype = ScratchBlocks.BlockSvg.prototype;
446
447
  const showContextMenu = prototype.showContextMenu_;
447
448
  const patched = function (event) {
448
449
  const functionId = this.isInFlyout ? undefined : find(this.id);
449
- if (!functionId)
450
+ const target = scriptEditor?.vm.editingTarget;
451
+ const layout = scriptEditor && getDockedScriptLayout(scriptEditor.vm);
452
+ const script = scriptEditor && !this.isInFlyout && !this.workspace.options.readOnly &&
453
+ this.workspace === ScratchBlocks.getMainWorkspace?.() && layout?.view.view === 'free' &&
454
+ layout.canArrange() && !getCodeSession(scriptEditor.vm).bridge?.focusedScript ? this.getRootBlock() : undefined;
455
+ const scriptId = script && target?.blocks._blocks[script.id] ? script.id : undefined;
456
+ if (!functionId && !scriptId)
450
457
  return showContextMenu.call(this, event);
458
+ const blockId = this.id;
459
+ const japanese = scriptEditor && /^ja(?:-|$)/i.test(scriptEditor.locale);
460
+ const scriptOptions = scriptId ? [
461
+ { section: 'functions', text: japanese ?
462
+ 'このスクリプトを個別の画面で編集する' : 'Edit this script in a separate view' },
463
+ { section: 'calls', text: japanese ?
464
+ 'このスクリプトの呼び出し関係を開く' : 'Open relationships for this script' }
465
+ ].map(({ section, text }) => ({ text, twPlusMenuIcon: section, separator: false, enabled: true, callback() {
466
+ if (scriptEditor.vm.editingTarget === target && target.blocks._blocks[scriptId]) {
467
+ scriptEditor.open(scriptId, blockId, section);
468
+ }
469
+ } })) : [];
451
470
  const owned = Object.prototype.hasOwnProperty.call(this, 'customContextMenu');
452
471
  const custom = this.customContextMenu;
453
472
  this.customContextMenu = function (options) {
454
473
  custom?.call(this, options);
455
- options.unshift({ text: label(), enabled: true, callback: () => open(functionId) });
474
+ if (functionId)
475
+ options.unshift({ text: label(), enabled: true, callback: () => open(functionId) });
476
+ options.unshift(...scriptOptions);
456
477
  };
478
+ const { ContextMenu } = ScratchBlocks;
479
+ const populate = scriptOptions.length ? ContextMenu.populate_ : undefined;
480
+ if (scriptOptions.length)
481
+ ContextMenu.populate_ = function (options, rtl) {
482
+ // Addons reorder ContextMenu.show's options after customContextMenu. Prioritize the final list,
483
+ // in place so their separator indices and the host's icon decoration still use the same order.
484
+ for (const priority of [...scriptOptions].reverse()) {
485
+ const index = options.findIndex(option => option.callback === priority.callback);
486
+ if (index > 0)
487
+ options.unshift(...options.splice(index, 1));
488
+ }
489
+ for (const option of scriptOptions)
490
+ option.separator = false;
491
+ if (options.length > 2)
492
+ options[2].separator = true;
493
+ const menu = populate.call(this, options, rtl);
494
+ menu.getChildAt(2)?.getElement().classList.add('tw-script-editor-menu-divider');
495
+ return menu;
496
+ };
457
497
  try {
458
498
  return showContextMenu.call(this, event);
459
499
  }
460
500
  finally {
501
+ if (scriptOptions.length)
502
+ ContextMenu.populate_ = populate;
461
503
  if (owned)
462
504
  this.customContextMenu = custom;
463
505
  else
@@ -1,11 +1,13 @@
1
1
  import React from 'react';
2
- export declare function createContextMenuIcons({ enabled, addonMessages, styles }: {
2
+ export declare function createContextMenuIcons({ enabled, addonMessages, styles, renderSectionIcon, createSectionIcon }: {
3
3
  enabled: boolean;
4
4
  addonMessages: Record<string, string>;
5
5
  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
- renderMenuIcon: (action: any) => React.ReactSVGElement;
8
- renderContextMenuIcon: (action: any) => React.ReactSVGElement;
9
+ renderMenuIcon: (action: any) => React.ReactNode;
10
+ renderContextMenuIcon: (action: any) => React.ReactNode;
9
11
  attachAssetContextMenuIcons: (document: any, getMessages: any) => {
10
12
  dispose: () => any;
11
13
  };
@@ -1,6 +1,6 @@
1
1
  // SPDX-License-Identifier: MPL-2.0
2
2
  import React from 'react';
3
- export function createContextMenuIcons({ enabled, addonMessages, styles }) {
3
+ export function createContextMenuIcons({ enabled, addonMessages, styles, renderSectionIcon, createSectionIcon }) {
4
4
  const paths = {
5
5
  open: 'M13 4h7v7m0-7-9 9m-1-8H4v15h15v-6',
6
6
  duplicate: 'M8 8V4h12v12h-4M4 8h12v12H4z',
@@ -107,13 +107,17 @@ export function createContextMenuIcons({ enabled, addonMessages, styles }) {
107
107
  const id = Object.keys(actions).find(key => matchesMessage(text, messages[key], placeholder));
108
108
  return actions[id];
109
109
  };
110
- const renderMenuIcon = action => paths[action] ? React.createElement('svg', {
110
+ const renderMenuIcon = action => (action === 'functions' || action === 'calls') && renderSectionIcon ?
111
+ renderSectionIcon(action, styles.icon) : paths[action] ? React.createElement('svg', {
111
112
  className: styles.icon, 'aria-hidden': 'true', focusable: 'false', viewBox: '0 0 24 24'
112
113
  }, React.createElement('path', { d: paths[action] })) : null;
113
114
  const renderContextMenuIcon = action => enabled ? renderMenuIcon(action) : null;
114
115
  const svgNamespace = 'http://www.w3.org/2000/svg';
115
116
  const installed = new WeakSet();
116
117
  function createContextMenuIcon(document, action) {
118
+ if ((action === 'functions' || action === 'calls') && createSectionIcon) {
119
+ return createSectionIcon(document, action, styles.icon);
120
+ }
117
121
  if (!Object.hasOwn(paths, action))
118
122
  return null;
119
123
  const icon = document.createElementNS(svgNamespace, 'svg');
@@ -1,9 +1,29 @@
1
1
  import { isFoldedDefinition } from "./procedure-edits.js";
2
2
  import { readScriptRelations } from "./script-relations.js";
3
+ function roundedRoute(points, radius) {
4
+ let path = `M ${points[0].x} ${points[0].y}`;
5
+ for (let index = 1; index < points.length - 1; index++) {
6
+ const before = points[index - 1], corner = points[index], after = points[index + 1];
7
+ const entering = Math.hypot(corner.x - before.x, corner.y - before.y);
8
+ const leaving = Math.hypot(after.x - corner.x, after.y - corner.y);
9
+ const size = Math.min(radius, entering / 2, leaving / 2);
10
+ if (!size) {
11
+ path += ` L ${corner.x} ${corner.y}`;
12
+ continue;
13
+ }
14
+ const first = { x: corner.x + (before.x - corner.x) * size / entering,
15
+ y: corner.y + (before.y - corner.y) * size / entering };
16
+ const last = { x: corner.x + (after.x - corner.x) * size / leaving,
17
+ y: corner.y + (after.y - corner.y) * size / leaving };
18
+ path += ` L ${first.x} ${first.y} Q ${corner.x} ${corner.y} ${last.x} ${last.y}`;
19
+ }
20
+ const end = points.at(-1);
21
+ return `${path} L ${end.x} ${end.y}`;
22
+ }
3
23
  const ns = 'http://www.w3.org/2000/svg';
4
24
  // Keep the same sixteen-unit hourglass as the call graph's relation badge.
5
25
  const relationWaitGlyph = 'M1 1h14M1 15h14M2 1v3l12 8v3M14 1v3l-12 8v3M2 4h12M2 12h12';
6
- /** Keep the badge beside the receiving end of the cubic curve, leaving its stroke visible. */
26
+ /** Keep the badge beside the receiving end of the path, leaving its stroke visible. */
7
27
  function waitBadgePoint(path, offset) {
8
28
  const values = path.match(/-?(?:\d*\.?\d+)(?:e[+-]?\d+)?/gi).map(Number);
9
29
  const [sx, sy] = values;
@@ -116,6 +136,8 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
116
136
  let geometryChanged = true;
117
137
  let lastMatrix;
118
138
  let edgeDrawings = [];
139
+ let viewportDrawings = [];
140
+ let measuredAnchors = new Map();
119
141
  const renderedGroups = new WeakMap();
120
142
  const syncTransform = (matrix) => {
121
143
  // Workspace dragging lends the two native canvases to a separate SVG which must keep exactly two children.
@@ -186,16 +208,30 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
186
208
  return;
187
209
  const top = blockRoot(endpoint.scriptId, roots);
188
210
  // A script hidden by the one-script view is not the same as its folded body.
189
- if (!top || !top.getClientRects().length || top.closest('[data-tw-plus-hidden]') ||
190
- view.getComputedStyle(top).display === 'none')
211
+ if (!top || top.closest('[data-tw-plus-hidden]'))
212
+ return;
213
+ // Native viewport culling hides the whole stack, but its real endpoints still exist.
214
+ const culled = !projection && top.style.display === 'none';
215
+ if (!culled && !top.getClientRects().length)
191
216
  return;
192
217
  const folded = isFoldedDefinition(target.blocks._blocks[endpoint.scriptId]);
193
218
  let id = folded ? endpoint.scriptId : endpoint.blockId;
194
219
  let root = blockRoot(id, roots);
195
220
  // Native Blockly collapsing can also hide a caller inside a control block.
196
221
  const visited = new Set();
197
- while (root && (!root.getClientRects().length || root.closest('[data-tw-plus-hidden]') ||
198
- view.getComputedStyle(root).display === 'none') && !visited.has(id)) {
222
+ const hidden = (node) => {
223
+ if (node.closest('[data-tw-plus-hidden]'))
224
+ return true;
225
+ if (!culled)
226
+ return !node.getClientRects().length || view.getComputedStyle(node).display === 'none';
227
+ // A collapsed parent below the culled stack still needs its visible proxy anchor.
228
+ for (let ancestor = node; ancestor && ancestor !== top; ancestor = ancestor.parentElement) {
229
+ if (view.getComputedStyle(ancestor).display === 'none')
230
+ return true;
231
+ }
232
+ return false;
233
+ };
234
+ while (root && hidden(root) && !visited.has(id)) {
199
235
  visited.add(id);
200
236
  id = target.blocks._blocks[id]?.parent ?? '';
201
237
  root = blockRoot(id, roots);
@@ -225,7 +261,7 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
225
261
  return points.get(key);
226
262
  } };
227
263
  }
228
- function arrowGeometry({ relation, source, destination, count }, matrix, inverse, area, highlighted) {
264
+ function arrowGeometry({ relation, source, destination, count, serialRoute }, matrix, inverse, area, highlighted) {
229
265
  // Anchor an external link to the viewport edge; the list itself remains keyboard accessible.
230
266
  const local = source ?? destination;
231
267
  const edgeX = source ? area.right - 12 : area.left + 12;
@@ -249,6 +285,14 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
249
285
  ` C ${left} ${top}, ${left} ${end.y}, ${end.x} ${end.y}`;
250
286
  badgePoint = { x: middle, y: top - 6 };
251
287
  }
288
+ if (serialRoute && source && destination) {
289
+ const { right, top, clearance } = serialRoute;
290
+ // Leave room beside every script before turning vertically, then return through the gap above the hat.
291
+ const approach = end.x - clearance;
292
+ path = roundedRoute([start, { x: right, y: start.y }, { x: right, y: top },
293
+ { x: approach, y: top }, { x: approach, y: end.y }, end], clearance);
294
+ badgePoint = { x: right, y: (start.y + top) / 2 };
295
+ }
252
296
  const head = `M ${end.x - 9} ${end.y - 5} L ${end.x} ${end.y} L ${end.x - 9} ${end.y + 5}`;
253
297
  let waitTransform;
254
298
  if (relation.kind === 'message' && relation.wait) {
@@ -299,6 +343,16 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
299
343
  }
300
344
  return group;
301
345
  }
346
+ function inViewport({ source, destination }, matrix, area) {
347
+ return [source, destination].some(anchor => {
348
+ if (!anchor)
349
+ return false;
350
+ const first = transform(matrix, anchor.box);
351
+ const last = transform(matrix, { x: anchor.box.x + anchor.box.width, y: anchor.box.y + anchor.box.height });
352
+ return Math.max(first.x, last.x) > area.left && Math.min(first.x, last.x) < area.right &&
353
+ Math.max(first.y, last.y) > area.top && Math.min(first.y, last.y) < area.bottom;
354
+ });
355
+ }
302
356
  function render() {
303
357
  frame = undefined;
304
358
  if (disposed)
@@ -336,7 +390,9 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
336
390
  const area = (projection ?? workspace.getParentSvg()).getBoundingClientRect();
337
391
  const sameScale = lastMatrix && matrix.a === lastMatrix.a && matrix.b === lastMatrix.b &&
338
392
  matrix.c === lastMatrix.c && matrix.d === lastMatrix.d;
339
- if (!geometryChanged && !projection && sameScale) {
393
+ const reuseAnchors = !geometryChanged && !projection && sameScale;
394
+ if (reuseAnchors &&
395
+ viewportDrawings.every(item => item.visible === inViewport(item.drawing, matrix, area))) {
340
396
  const geometry = edgeDrawings.map(item => ({ ...item,
341
397
  shape: arrowGeometry(item.drawing, matrix, inverse, area, item.highlighted) }));
342
398
  syncTransform(matrix);
@@ -359,6 +415,9 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
359
415
  geometryChanged = false;
360
416
  lastMatrix = matrix;
361
417
  edgeDrawings = [];
418
+ viewportDrawings = [];
419
+ if (!reuseAnchors)
420
+ measuredAnchors = new Map();
362
421
  const paint = [];
363
422
  const guides = document.createDocumentFragment();
364
423
  const previousGroups = renderedGroups.get(drawingLayer);
@@ -384,12 +443,11 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
384
443
  const inDrag = (endpoint) => Boolean(endpoint && endpoint.targetId === target.id && draggedIds.has(endpoint.blockId));
385
444
  const incident = (relation) => inDrag(relation.source) || inDrag(relation.destination);
386
445
  const drawings = new Map();
387
- const anchors = new Map();
388
446
  const measuredAnchor = (endpoint) => {
389
447
  const key = `${endpoint.targetId}\0${endpoint.scriptId}\0${endpoint.blockId}`;
390
- if (!anchors.has(key))
391
- anchors.set(key, anchor(endpoint, target, roots, inverse));
392
- return anchors.get(key);
448
+ if (!measuredAnchors.has(key))
449
+ measuredAnchors.set(key, anchor(endpoint, target, roots, inverse));
450
+ return measuredAnchors.get(key);
393
451
  };
394
452
  for (const relation of graph) {
395
453
  if (!visibility[relation.kind])
@@ -408,6 +466,36 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
408
466
  else
409
467
  drawings.set(key, { relation, source, destination, count: 1 });
410
468
  }
469
+ if (projection) {
470
+ const unit = 1 / (Math.hypot(matrix.a, matrix.b) || 1);
471
+ const scripts = new Map();
472
+ for (const root of projection.querySelectorAll('[data-script-view-block]')) {
473
+ const rect = root.getBoundingClientRect();
474
+ const first = transform(inverse, { x: rect.left, y: rect.top });
475
+ const last = transform(inverse, { x: rect.right, y: rect.bottom });
476
+ scripts.set(root.getAttribute('data-script-view-block'), { x: first.x, y: first.y, width: last.x - first.x, height: last.y - first.y });
477
+ }
478
+ const rightEdge = [...scripts.values()].reduce((edge, box) => Math.max(edge, box.x + box.width), 0);
479
+ let lane = 0;
480
+ for (const drawing of drawings.values()) {
481
+ if (!drawing.source || !drawing.destination)
482
+ continue;
483
+ const destination = scripts.get(drawing.relation.destination.scriptId);
484
+ if (!destination)
485
+ continue;
486
+ drawing.serialRoute = { right: rightEdge + (96 + lane * 16) * unit,
487
+ top: destination.y - (14 + lane % 4 * 6) * unit, clearance: 8 * unit };
488
+ lane++;
489
+ }
490
+ // Reserve actual scrollable SVG width for the right-hand routes while preserving the block scale.
491
+ const box = projection.viewBox.baseVal;
492
+ const width = Math.ceil(rightEdge + (112 + Math.max(0, lane - 1) * 16) * unit);
493
+ if (lane && width > box.width) {
494
+ const scale = Math.hypot(matrix.a, matrix.b);
495
+ projection.setAttribute('viewBox', `${box.x} ${box.y} ${width} ${box.height}`);
496
+ projection.setAttribute('width', String(width * scale));
497
+ }
498
+ }
411
499
  const related = new Set();
412
500
  for (const relation of graph)
413
501
  if (visibility[relation.kind] && dragging && incident(relation)) {
@@ -426,7 +514,7 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
426
514
  if (root && root.getClientRects().length && !root.closest('[data-tw-plus-hidden]'))
427
515
  marked.set(root, 'related');
428
516
  }
429
- // Frame the whole stack, including its body; the original block paint and runtime glow stay intact.
517
+ // Shade the whole stack, including its body; the original block paint and runtime glow stay intact.
430
518
  for (const [root, role] of marked) {
431
519
  const bounds = root.getBoundingClientRect();
432
520
  const first = transform(inverse, { x: bounds.left, y: bounds.top });
@@ -436,6 +524,10 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
436
524
  rx: '10', class: 'tw-script-relation-script-highlight', 'data-emphasis': role }));
437
525
  }
438
526
  for (const [key, drawing] of drawings) {
527
+ const visible = inViewport(drawing, matrix, area);
528
+ viewportDrawings.push({ drawing, visible });
529
+ if (!visible)
530
+ continue;
439
531
  const { relation, source, destination, count } = drawing;
440
532
  const highlighted = dragging ? incident(relation) :
441
533
  emphasized && (emphasized === relation.source.scriptId || emphasized === relation.destination?.scriptId);
@@ -496,6 +588,8 @@ export function attachScriptArrows({ workspace, vm, getTarget, getRelations, get
496
588
  destinations.replaceChildren();
497
589
  destinations.hidden = true;
498
590
  edgeDrawings = [];
591
+ viewportDrawings = [];
592
+ measuredAnchors.clear();
499
593
  lastMatrix = undefined;
500
594
  renderedGroups.delete(layer);
501
595
  if (projectedLayer)
@@ -4,6 +4,9 @@ import { openRearrangement } from "./script-layout-dialog.js";
4
4
  import { attachScriptViewMenu } from "./script-view-menu.js";
5
5
  import { attachScriptArrows } from "./script-arrows.js";
6
6
  import { attachCodeZoomRange } from "./code-zoom.js";
7
+ import { setScriptProjection } from "./script-projection.js";
8
+ import { openSerialScriptEditor } from "./serial-script-editor.js";
9
+ import { isFoldedDefinition, setFoldedDefinition } from "./procedure-edits.js";
7
10
  const choices = [
8
11
  { view: 'free', label: 'Normal layout view', jaLabel: '通常配置の見え方' },
9
12
  { view: 'z', label: 'Z layout view', jaLabel: 'Z配置の見え方' },
@@ -19,10 +22,15 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
19
22
  surface.className = 'tw-script-view-surface';
20
23
  surface.dataset.codeViewControl = '';
21
24
  surface.tabIndex = 0;
22
- surface.toggleAttribute('data-can-show-block', Boolean(canShowBlock));
25
+ surface.toggleAttribute('data-can-show-block', Boolean(canShowBlock || relationContext?.vm));
23
26
  const contents = document.createElement('div');
24
27
  surface.append(contents);
28
+ const gutter = document.createElement('div');
29
+ gutter.className = 'tw-script-fold-gutter';
30
+ gutter.dataset.codeViewControl = '';
31
+ const foldButtons = new Map();
25
32
  let view = initialView;
33
+ let editor;
26
34
  let frame;
27
35
  const svg = workspace.getParentSvg();
28
36
  const observer = new window.MutationObserver(records => {
@@ -31,6 +39,73 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
31
39
  });
32
40
  const relations = relationContext && attachScriptArrows({ workspace, getLocale, ...relationContext });
33
41
  const japanese = () => /^ja(?:-|$)/i.test(getLocale());
42
+ function setFold(ids, value) {
43
+ const target = relationContext?.getTarget();
44
+ const runtime = relationContext?.vm?.runtime;
45
+ if (!target || !runtime?.emitProjectChanged || (canShowBlock && !canShowBlock()))
46
+ return;
47
+ for (const id of ids) {
48
+ const block = target.blocks._blocks[id];
49
+ if (block)
50
+ setFoldedDefinition(block, value ?? !isFoldedDefinition(block));
51
+ }
52
+ runtime.emitProjectChanged();
53
+ update();
54
+ }
55
+ function positionFoldButtons() {
56
+ gutter.style.left = `${surface.offsetLeft}px`;
57
+ gutter.style.top = `${surface.offsetTop}px`;
58
+ gutter.style.height = `${surface.clientHeight}px`;
59
+ for (const { button, top } of foldButtons.values())
60
+ button.style.top = `${top - surface.scrollTop}px`;
61
+ }
62
+ function paintFoldButtons(placements, scale) {
63
+ const target = relationContext?.getTarget();
64
+ const ids = new Set(placements.map(({ script }) => script.id));
65
+ for (const [id, { button }] of foldButtons)
66
+ if (!ids.has(id)) {
67
+ button.remove();
68
+ foldButtons.delete(id);
69
+ }
70
+ for (const { script, y } of placements) {
71
+ let entry = foldButtons.get(script.id);
72
+ if (!entry) {
73
+ const button = document.createElement('button');
74
+ button.type = 'button';
75
+ button.dataset.scriptFoldToggle = script.id;
76
+ button.addEventListener('click', event => { event.stopPropagation(); setFold([script.id]); });
77
+ button.addEventListener('pointerdown', event => event.stopPropagation());
78
+ entry = { button, top: 0 };
79
+ foldButtons.set(script.id, entry);
80
+ gutter.append(button);
81
+ }
82
+ const block = target?.blocks._blocks[script.id];
83
+ const folded = isFoldedDefinition(block);
84
+ const label = japanese() ? (folded ? '折りたたみを解除' : '折りたたむ') : (folded ? 'Unfold script' : 'Fold script');
85
+ entry.top = y * scale;
86
+ entry.button.textContent = folded ? '▶' : '▼';
87
+ entry.button.disabled = !block || Boolean(canShowBlock && !canShowBlock());
88
+ entry.button.setAttribute('aria-label', label);
89
+ entry.button.setAttribute('aria-expanded', String(!folded));
90
+ entry.button.title = label;
91
+ }
92
+ positionFoldButtons();
93
+ }
94
+ function foldOptions() {
95
+ const target = relationContext?.getTarget();
96
+ const runtime = relationContext?.vm?.runtime;
97
+ if (view === 'free' || !target || !runtime?.emitProjectChanged || (canShowBlock && !canShowBlock()))
98
+ return [];
99
+ const roots = readScripts(workspace).map(script => target.blocks._blocks[script.id]).filter(Boolean);
100
+ const options = [
101
+ { value: true, text: japanese() ? 'すべて折りたたむ' : 'Fold all' },
102
+ { value: false, text: japanese() ? '折りたたみをすべて解除' : 'Unfold all' }
103
+ ];
104
+ return options.map(({ value, text }) => ({ text,
105
+ enabled: roots.some(block => isFoldedDefinition(block) !== value),
106
+ callback() { setFold(readScripts(workspace).map(script => script.id), value); }
107
+ }));
108
+ }
34
109
  function labels() {
35
110
  const choice = choices.find(choice => choice.view === view);
36
111
  surface.setAttribute('aria-label', japanese() ? choice.jaLabel : choice.label);
@@ -40,6 +115,7 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
40
115
  const ja = japanese();
41
116
  return {
42
117
  label: ja ? 'コードの並びの見え方を変更する' : 'Change code layout view',
118
+ options: foldOptions(),
43
119
  choices: choices.map(choice => ({
44
120
  text: ja ? choice.jaLabel : choice.label,
45
121
  enabled: true,
@@ -62,8 +138,20 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
62
138
  surface.style.setProperty('--tw-script-view-left', !horizontal && bounds.left <= left + 2 ? `${bounds.width}px` : '0px');
63
139
  surface.style.setProperty('--tw-script-view-right', !horizontal && bounds.right >= right - 2 ? `${bounds.width}px` : '0px');
64
140
  }
65
- paintScripts(contents, arrangeScripts(readScripts(workspace), view, 'vertical'), workspace.scale || 1);
66
- relations?.setProjection(contents.querySelector('svg'));
141
+ const scale = workspace.scale || 1;
142
+ const scripts = readScripts(workspace).map(script => {
143
+ // Include raised hats and labels, and exclude folded bodies, when measuring the visible gap.
144
+ const box = script.root.getBBox();
145
+ return { ...script, x: script.origin.x + box.x, y: script.origin.y + box.y,
146
+ width: box.width, height: box.height };
147
+ });
148
+ const placements = arrangeScripts(scripts, view, 'vertical', Math.max(64, 48 / scale))
149
+ .map(placement => ({ ...placement, x: Math.max(placement.x, 32 / scale) }));
150
+ paintScripts(contents, placements, scale);
151
+ paintFoldButtons(placements, scale);
152
+ const projection = contents.querySelector('svg');
153
+ relations?.setProjection(projection);
154
+ setScriptProjection(workspace, { surface, svg: projection });
67
155
  }
68
156
  function update() {
69
157
  if (view === 'free' || frame !== undefined)
@@ -72,14 +160,20 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
72
160
  }
73
161
  function setView(next) {
74
162
  menu.close();
163
+ editor?.dispose();
164
+ editor = undefined;
75
165
  observer.disconnect();
76
166
  view = next;
77
167
  surface.hidden = view === 'free';
168
+ gutter.hidden = view === 'free';
78
169
  svg.toggleAttribute('data-script-serial', view !== 'free');
79
170
  labels();
80
171
  if (view === 'free') {
172
+ setScriptProjection(workspace);
81
173
  relations?.setProjection(null);
82
174
  contents.replaceChildren();
175
+ gutter.replaceChildren();
176
+ foldButtons.clear();
83
177
  }
84
178
  else {
85
179
  observer.observe(workspace.getCanvas(), { attributes: true, childList: true, subtree: true });
@@ -94,21 +188,39 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
94
188
  surface.addEventListener('click', event => {
95
189
  event.stopPropagation();
96
190
  const id = event.target.closest('[data-script-view-block]')?.getAttribute('data-script-view-block');
97
- if (!id || !canShowBlock?.())
191
+ if (!id || (canShowBlock && !canShowBlock()))
192
+ return;
193
+ if (relationContext?.vm) {
194
+ editor?.dispose();
195
+ editor = openSerialScriptEditor(relationContext.vm, relationContext.getTarget(), id, document, getLocale());
196
+ if (editor)
197
+ return;
198
+ }
199
+ if (!canShowBlock?.())
98
200
  return;
99
201
  chooseView('free');
100
202
  workspace.centerOnBlock(id);
101
203
  });
102
204
  const resize = new window.ResizeObserver(update);
103
205
  resize.observe(host);
104
- const language = new window.MutationObserver(labels);
206
+ const language = new window.MutationObserver(() => { labels(); update(); });
105
207
  language.observe(document.documentElement, { attributes: true, attributeFilter: ['lang'] });
106
208
  // The Blockly keyboard listener is document-wide.
107
209
  surface.addEventListener('keydown', event => {
108
210
  if (event.key !== 'Tab')
109
211
  event.stopPropagation();
110
212
  });
111
- host.append(surface);
213
+ gutter.addEventListener('keydown', event => {
214
+ if (event.key !== 'Tab')
215
+ event.stopPropagation();
216
+ });
217
+ host.append(surface, gutter);
218
+ surface.addEventListener('scroll', () => {
219
+ positionFoldButtons();
220
+ const projection = contents.querySelector('svg');
221
+ if (view !== 'free' && projection)
222
+ setScriptProjection(workspace, { surface, svg: projection });
223
+ }, { passive: true });
112
224
  setView(initialView);
113
225
  return {
114
226
  update,
@@ -117,6 +229,8 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
117
229
  get view() { return view; },
118
230
  setView,
119
231
  dispose() {
232
+ editor?.dispose();
233
+ setScriptProjection(workspace);
120
234
  restoreZoomRange();
121
235
  resize.disconnect();
122
236
  observer.disconnect();
@@ -126,6 +240,8 @@ export function attachScriptView({ workspace, ScratchBlocks, getLocale, mount, i
126
240
  menu.dispose();
127
241
  relations?.dispose();
128
242
  surface.remove();
243
+ gutter.remove();
244
+ foldButtons.clear();
129
245
  svg.removeAttribute('data-script-serial');
130
246
  }
131
247
  };
@@ -1,10 +1,15 @@
1
1
  export function readScripts(workspace) {
2
2
  return workspace.getTopBlocks(false).flatMap(block => {
3
3
  const root = block.getSvgRoot();
4
- if (!root || !workspace.getCanvas().contains(root))
4
+ if (!root || !workspace.getCanvas().contains(root) || root.hasAttribute('data-tw-plus-hidden'))
5
5
  return [];
6
6
  const origin = block.getRelativeToSurfaceXY();
7
- const { topLeft, bottomRight } = block.getBoundingRectangle();
7
+ let { topLeft, bottomRight } = block.getBoundingRectangle();
8
+ if (root.querySelector(':scope > [data-tw-plus-folded-mark]')) {
9
+ const box = root.getBBox();
10
+ topLeft = { x: origin.x + box.x, y: origin.y + box.y };
11
+ bottomRight = { x: topLeft.x + box.width, y: topLeft.y + box.height };
12
+ }
8
13
  return [{
9
14
  id: block.id, block, root, origin, ...topLeft,
10
15
  width: bottomRight.x - topLeft.x, height: bottomRight.y - topLeft.y
@@ -9,7 +9,7 @@ export interface ScriptBounds extends Point {
9
9
  }
10
10
  export type ScriptOrder = 'z' | 'n';
11
11
  export type LayoutDirection = 'vertical' | 'horizontal';
12
- export declare function arrangeScripts<T extends ScriptBounds>(scripts: readonly T[], order: ScriptOrder, direction: LayoutDirection): {
12
+ export declare function arrangeScripts<T extends ScriptBounds>(scripts: readonly T[], order: ScriptOrder, direction: LayoutDirection, gap?: number): {
13
13
  script: T;
14
14
  x: number;
15
15
  y: number;