@kubohiroya/turbowarp-plus-editor-code-views 0.18.0 → 0.20.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
@@ -4,6 +4,12 @@
4
4
 
5
5
  TurboWarp Plus Editor のコードの画面。1つの作品と1つの取り消し履歴を共有するタブと窓のコード、別窓に切り離したブロックパレット、スクリプトの整列とスクリプト表示、関数の編集、拡張が自分で描くブロックの入力欄の編集を持つ。どの関数も VM・Blockly のワークスペース・`ScratchBlocks` をホストから受け取り、GUI のモジュールを import しない。
6
6
 
7
+ ## 選択したスクリプトの表示
8
+
9
+ 関数・ハットなどを選んで開くと、そのスクリプトの描画範囲を24pxの余白付きでパネルへ収める。自動ズームは50〜125%に制限し、ワークスペース固有の制限が厳しければそちらに従う。下限倍率ではスクリプトの上端を余白の下に置き、長いスクリプトも先頭から読めるようにする。通常の編集・手動ズームでは再フィットしない。
10
+
11
+ ホストが独立したワークスペースを表示する場合は、ルートまたは `./sprite-code-windows` の `fitScriptInWorkspace(workspace, scriptId, ScratchBlocks)` を使える。表示領域やブロックがまだない場合は `false` を返すので、レイアウト後に再試行する。
12
+
7
13
  ## 入口
8
14
 
9
15
  | import | 内容 |
@@ -41,11 +47,27 @@ TurboWarp Plus Editor のコードの画面。1つの作品と1つの取り消
41
47
 
42
48
  Editor は GUI の React 16 にこれらを描画するので、React 16.14 以降に対応する。
43
49
 
50
+ ## スクリプト間の矢印
51
+
52
+ コードの背面に、関数呼び出しを紫系の実線、メッセージ送信を橙系の破線で表示する。「送って待つ」には待機の印を添える。通常配置、Z/N 配置、折り畳み、プレビュー、別窓で同じ表現を使う。関数の再帰はスクリプトの外へ回る線で示す。選択・ホバーによる強調は太さと不透明度で行い、関係種別の色・線種は変えない。
53
+
54
+ 関係は作品データから読み、折り畳みによって表示から消えた呼び出しも保持する。展開中は呼び出しブロックから、折り畳み中は見えているハットから結ぶ。同じハットと宛先へ重なる呼び出しは件数を表示する。別スプライトや一スクリプト表示の外にある接続先は、画面端の案内から辿れる。変数などで呼び出し先が変わるものは「実行時に決定」と示し、見えていない既定値を宛先とみなさない。
55
+
56
+ スクリプトをドラッグしている間は、そこへ入る・そこから出る矢印を太く濃くし、画面にある相手のスクリプト全体を枠で強調する。関係しない矢印は薄くし、画面外の相手は接続先の案内を強調する。関数とメッセージの色・線種は維持する。折り畳み中も同じように働き、ドラッグの終了・矢印の非表示・画面の破棄で一時的な枠を解除する。移動中に Blockly がブロックを別の SVG へ移しても追従する。
57
+
58
+ `attachDockedScriptLayout` と `attachCodeWorkspace` のプレビュー・関数エディタには自動で付く。VM を持たない表示では、`attachScriptView` に `relations: {getTarget, getRelations, getTargetName, navigate}` を渡す。`getRelations` は親の `createCodeSession` が渡す `scriptRelations`、`getTarget` はその対象の `blocks` を使う。`getTargetName` は既存の対象一覧から名前を返し、同じメッセージを受信する別スプライトを案内で識別できるようにする。投影の受信後は `view.relations.update()` を呼ぶ。関係だけの更新は `relations`、接続先への移動は `relation-navigate`/`relation-focus` で既存の編集回収・対象切り替えを経由する。編集中の窓には履歴の更新のために XML を再読み込みさせない。
59
+
60
+ 色は共通の CSS 変数 `--tw-script-function-stroke` と `--tw-script-message-stroke` に定義する。明暗テーマでは同じ種別のまま明度を変え、線種でも区別できる。既存の関数呼び出し図とミニマップも関数用の変数を使う。
61
+
62
+ コード画面に常設の凡例や表示スイッチは置かない。選択・ホバー・ドラッグ中の関係に必要な接続先だけを短く表示する。呼び出し関係の図へ渡す `readScriptRelationGraph(targets, ScratchBlocks)` は、同じ関係データと、接続先スクリプトのハットの文言・対象名・位置を返す。図の向きと関数・メッセージの表示は、呼び出し関係パネルの左端カラム下端で操作する。
63
+
64
+ 既定は表示する。作品の保存形式は変えない。完全に切り戻す場合は導入前のパッケージ固定と結線へ戻す。関連: [Editor #683](https://github.com/kubohiroya/turbowarp-plus-editor/issues/683)。
65
+
44
66
  ## 検証
45
67
 
46
68
  `npm test` でビルドし、単体テストを実行し、React 16.14 より新しい API を使っていないことを確かめる。
47
69
 
48
- `npm run test:browser` は、最小のエディター実行環境(`@kubohiroya/turbowarp-plus-editor-test-runtime`)で、Editor と同じ VM と Scratch Blocks を使い、パレットのグループを Chromium で操作して確かめる(子ブロックパレット、ピン、並べ替え、別窓のパレット)。`TWPE_CHROME_EXECUTABLE` を指定すると、Playwright のものの代わりにその Chromium を使う。
70
+ `npm run test:browser` は、最小のエディター実行環境(`@kubohiroya/turbowarp-plus-editor-test-runtime`)で、Editor と同じ VM と Scratch Blocks を使い、パレットのグループとスクリプト間の矢印を Chromium で操作して確かめる。矢印は `node --test test/script-arrows.browser.ts` で限定実行でき、折り畳み・実際の関数エディタ・Z/N 配置・テーマ・別スプライトへの移動・キー入力の隔離をヘッドレスで検証する。`TWPE_CHROME_EXECUTABLE` を指定すると、Playwright のものの代わりにその Chromium を使う。
49
71
 
50
72
  ## ライセンス
51
73
 
package/README.md CHANGED
@@ -4,6 +4,12 @@
4
4
 
5
5
  The code views of TurboWarp Plus Editor: code in tabs and windows that share one project and one undo history, the block palette detached into its own window, script layout and script views, the function editor, and editing of block fields that extensions draw themselves. Every function takes the VM, the Blockly workspace and `ScratchBlocks` from the host; the package imports no GUI module.
6
6
 
7
+ ## Opening a selected script
8
+
9
+ Opening a function or hat fits its rendered script into the pane with 24px of padding. Automatic zoom stays between 50% and 125%, respecting stricter workspace limits. At the lower limit, the script starts below the top padding so a long script remains readable from its beginning. Ordinary edits and manual zoom do not refit it.
10
+
11
+ Hosts with a separate workspace can call `fitScriptInWorkspace(workspace, scriptId, ScratchBlocks)` from the root or `./sprite-code-windows` export. It returns `false` if the viewport or block is not ready, so the host can retry after layout.
12
+
7
13
  ## Entry points
8
14
 
9
15
  | Import | Contents |
@@ -1,6 +1,7 @@
1
1
  import { getCodeSession } from './workspace.ts';
2
2
  import type { AttachPreviewMinimap, AttachWorkspaceNavigation } from './workspace.ts';
3
3
  import { type ScriptView } from './script-layout-view.ts';
4
+ import { type RelationTarget } from './script-relations.ts';
4
5
  type Pane = {
5
6
  id: string;
6
7
  targetId: string;
@@ -64,6 +65,19 @@ export interface HatScript {
64
65
  * to plug it into; its label is how ScratchBlocks spells that block.
65
66
  */
66
67
  export declare function readHatScripts(target: any, ScratchBlocks: any, skip?: ReadonlySet<string>): HatScript[];
68
+ /** Supply the calls panel with the same relations and native hat labels as the code workspace. */
69
+ export declare function readScriptRelationGraph(targets: readonly RelationTarget[], ScratchBlocks: any): {
70
+ scriptRelations: import("./script-relations.ts").ScriptRelation[];
71
+ scripts: {
72
+ targetId: string;
73
+ scriptId: string;
74
+ label: string;
75
+ targetName?: string;
76
+ isStage?: boolean;
77
+ x?: number;
78
+ y?: number;
79
+ }[];
80
+ };
67
81
  /**
68
82
  * Add “Show this function” at the top of the menu of every block that calls a function, in the code area and
69
83
  * in the script editors. `find` names the function a block calls, if any; `open` shows it.
package/dist/code-pane.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { getCodeSession } from "./workspace.js";
2
2
  import { getDockedScriptLayout } from "./script-layout-view.js";
3
+ import { readScriptRelations } from "./script-relations.js";
3
4
  const scriptViews = ['free', 'z', 'n'];
4
5
  const finite = (value, limit) => typeof value === 'number' && Number.isFinite(value) && Math.abs(value) <= limit;
5
6
  /** Read a saved code area back, or nothing if it does not have the shape `serialize` writes. */
@@ -17,14 +18,17 @@ export function createCodePaneAdapter(vm, locale, attachMinimap) {
17
18
  const focused = new Map();
18
19
  // The code pane the code area is in, which shows its script there.
19
20
  let current;
20
- const applyFocus = (paneId) => {
21
+ const applyFocus = (paneId, refit = false) => {
21
22
  const focus = paneId === undefined ? undefined : focused.get(paneId);
22
- session.bridge?.focusScript(focus?.scriptId, focus && (() => focus.onLost?.()));
23
+ session.bridge?.focusScript(focus?.scriptId, focus && (() => focus.onLost?.()), refit);
23
24
  };
24
25
  let pending;
25
26
  // The GUI can attach the code area again, with a new bridge; the view it is in still shows its script.
26
27
  let attached = session.bridge;
27
- session.subscribe(() => {
28
+ session.subscribe(navigation => {
29
+ const focus = current === undefined ? undefined : focused.get(current);
30
+ if (navigation && focus)
31
+ focus.scriptId = navigation.scriptId;
28
32
  if (session.bridge === attached)
29
33
  return;
30
34
  attached = session.bridge;
@@ -68,7 +72,7 @@ export function createCodePaneAdapter(vm, locale, attachMinimap) {
68
72
  else
69
73
  focused.delete(paneId);
70
74
  if (current === paneId)
71
- applyFocus(paneId);
75
+ applyFocus(paneId, true);
72
76
  // Previews of other views redraw with their script.
73
77
  session.changed();
74
78
  },
@@ -136,6 +140,9 @@ export function createCodePaneAdapter(vm, locale, attachMinimap) {
136
140
  const frame = requestAnimationFrame(() => {
137
141
  pending = undefined;
138
142
  session.bridge?.restorePane(pane.targetId, presentation);
143
+ // A picked script owns its initial viewport, including after a saved pane is restored.
144
+ if (focused.has(pane.id))
145
+ applyFocus(pane.id, true);
139
146
  });
140
147
  pending = { frame, pane, presentation };
141
148
  },
@@ -355,6 +362,37 @@ export function readHatScripts(target, ScratchBlocks, skip = new Set()) {
355
362
  workspace.dispose();
356
363
  }
357
364
  }
365
+ /** Supply the calls panel with the same relations and native hat labels as the code workspace. */
366
+ export function readScriptRelationGraph(targets, ScratchBlocks) {
367
+ const scriptRelations = readScriptRelations(targets);
368
+ const used = new Map();
369
+ for (const relation of scriptRelations) {
370
+ for (const endpoint of [relation.source, relation.destination]) {
371
+ if (!endpoint)
372
+ continue;
373
+ if (!used.has(endpoint.targetId))
374
+ used.set(endpoint.targetId, new Set());
375
+ used.get(endpoint.targetId).add(endpoint.scriptId);
376
+ }
377
+ }
378
+ const scripts = [];
379
+ for (const target of targets) {
380
+ if (target.isOriginal === false || !used.has(target.id))
381
+ continue;
382
+ const hats = new Map(readHatScripts(target, ScratchBlocks).map(hat => [hat.id, hat]));
383
+ for (const scriptId of used.get(target.id)) {
384
+ const block = target.blocks._blocks[scriptId];
385
+ if (!block)
386
+ continue;
387
+ const prototype = target.blocks._blocks[block.inputs?.custom_block?.block ?? ''];
388
+ const label = hats.get(scriptId)?.label ?? String(prototype?.mutation?.proccode ??
389
+ block.fields?.BROADCAST_OPTION?.value ?? block.opcode);
390
+ scripts.push({ targetId: target.id, scriptId, label, targetName: target.getName?.(),
391
+ isStage: Boolean(target.isStage), x: block.x ?? 0, y: block.y ?? 0 });
392
+ }
393
+ }
394
+ return { scriptRelations, scripts };
395
+ }
358
396
  /**
359
397
  * Add “Show this function” at the top of the menu of every block that calls a function, in the code area and
360
398
  * in the script editors. `find` names the function a block calls, if any; `open` shows it.
package/dist/index.d.ts CHANGED
@@ -2,6 +2,9 @@ export { attachDockedCodeExtensions } from './code-extensions.ts';
2
2
  export type { NativeFieldEditSession } from './native-extension-field.ts';
3
3
  export type { FieldActionPanel, ProgrammaticExtensionField } from './programmatic-extension-field.ts';
4
4
  export { encodeEdit } from './protocol.ts';
5
+ export { fitScriptInWorkspace } from './script-fit.ts';
6
+ export { readScriptRelations } from './script-relations.ts';
7
+ export type { ScriptEndpoint, ScriptRelation } from './script-relations.ts';
5
8
  export declare function refreshExternalBlockViews(vm: any, targets: any): void;
6
9
  export declare function createCodeSession({ vm, workspace, ScratchBlocks, document, locale, canUse, onError, receiveBackpackDrop }: {
7
10
  vm: any;
package/dist/index.js CHANGED
@@ -6,8 +6,11 @@ import { readFieldActionPanel, runFieldAction } from "./programmatic-extension-f
6
6
  import { capture, createHistory, restore, workspaceXML } from "./history.js";
7
7
  import { removeObsoleteProcedureInputs } from "./procedure-edits.js";
8
8
  import { decodeEdit, isCodeEdit, isCommentEdit } from "./protocol.js";
9
+ import { readScriptRelations } from "./script-relations.js";
9
10
  export { attachDockedCodeExtensions } from "./code-extensions.js";
10
11
  export { encodeEdit } from "./protocol.js";
12
+ export { fitScriptInWorkspace } from "./script-fit.js";
13
+ export { readScriptRelations } from "./script-relations.js";
11
14
  // A drop must stay within one target's block and comment history.
12
15
  const supportsSharedHistory = script => !script.variables.length && !script.extensionIDs?.length &&
13
16
  !Object.keys(script.extensionURLs).length;
@@ -61,6 +64,7 @@ export function createCodeSession({ vm, workspace, ScratchBlocks, document, loca
61
64
  let lease = 0;
62
65
  let projecting = false;
63
66
  let disposed = false;
67
+ let relationsPending = false;
64
68
  let canDuplicate = false;
65
69
  let flushRequest = 0;
66
70
  const flushes = new Set();
@@ -75,10 +79,31 @@ export function createCodeSession({ vm, workspace, ScratchBlocks, document, loca
75
79
  const dynamicShapesFor = target => getCodeDynamicShapes(vm.runtime, target);
76
80
  const projection = (target, xml = workspaceXML(vm, target)) => ({
77
81
  ...histories.get(target).state, xml, dynamicShapes: dynamicShapesFor(target),
82
+ blocks: target.blocks._blocks,
83
+ scriptRelations: readScriptRelations(vm.runtime.targets.filter(selectable)),
78
84
  nativeFieldGraphics: vm.editingTarget === target ? projectNativeFieldGraphics(vm.runtime, target, workspace) : []
79
85
  });
80
86
  const extensionsFor = target => getCodeExtensions(vm.runtime, target);
81
- const send = (view, message) => view.port.postMessage(message);
87
+ const send = (view, message) => {
88
+ if (message.scriptRelations)
89
+ view.relationSignature = JSON.stringify(message.scriptRelations);
90
+ view.port.postMessage(message);
91
+ };
92
+ function updateRelations() {
93
+ if (relationsPending || !views.size)
94
+ return;
95
+ relationsPending = true;
96
+ queueMicrotask(() => {
97
+ relationsPending = false;
98
+ if (disposed || !views.size)
99
+ return;
100
+ const scriptRelations = readScriptRelations(vm.runtime.targets.filter(selectable));
101
+ const signature = JSON.stringify(scriptRelations);
102
+ for (const view of views)
103
+ if (view.relationSignature !== signature)
104
+ send(view, { type: 'relations', scriptRelations });
105
+ });
106
+ }
82
107
  function updateCatalog() {
83
108
  const targets = vm.runtime.targets.filter(selectable).map(target => {
84
109
  const asset = target.getCostumes?.()[target.currentCostume]?.asset;
@@ -126,8 +151,11 @@ export function createCodeSession({ vm, workspace, ScratchBlocks, document, loca
126
151
  for (const view of views) {
127
152
  if (view.target !== target)
128
153
  continue;
129
- send(view, view === source ? { type: 'history', ...histories.get(target).state } : { type: 'update', ...data });
154
+ // The editing source must keep its live fields and queued edits; only other views reload XML.
155
+ send(view, view === source ? { type: 'history', ...histories.get(target).state,
156
+ blocks: data.blocks, scriptRelations: data.scriptRelations } : { type: 'update', ...data });
130
157
  }
158
+ updateRelations();
131
159
  }
132
160
  function flushParent() {
133
161
  for (const target of dirty) {
@@ -184,6 +212,11 @@ export function createCodeSession({ vm, workspace, ScratchBlocks, document, loca
184
212
  if (!histories.has(target))
185
213
  histories.set(target, createHistory(target, vm.runtime.getTargetForStage()));
186
214
  send(view, { type: 'target', targetId: target.id, extensions: extensionsFor(target), ...projection(target) });
215
+ if (view.relationFocus?.targetId === target.id) {
216
+ const { blockId, scriptId } = view.relationFocus;
217
+ view.relationFocus = undefined;
218
+ send(view, { type: 'relation-focus', blockId, scriptId });
219
+ }
187
220
  }
188
221
  function grant() {
189
222
  if (disposed || owner)
@@ -490,6 +523,28 @@ export function createCodeSession({ vm, workspace, ScratchBlocks, document, loca
490
523
  accept: supportsSharedHistory, commit: apply => queueDrop(target, apply) });
491
524
  return;
492
525
  }
526
+ if (message.type === 'relation-navigate') {
527
+ if (view.draining || !viewFocused(view) || !exists(view.target))
528
+ return;
529
+ const endpoint = { targetId: message.targetId, blockId: message.blockId, scriptId: message.scriptId };
530
+ const matches = candidate => candidate && candidate.targetId === endpoint.targetId &&
531
+ candidate.blockId === endpoint.blockId && candidate.scriptId === endpoint.scriptId;
532
+ // Navigation is limited to an existing endpoint related to this window's target.
533
+ if (!readScriptRelations(vm.runtime.targets.filter(selectable)).some(relation => (relation.source.targetId === view.target.id || relation.destination?.targetId === view.target.id) &&
534
+ (matches(relation.source) || matches(relation.destination))))
535
+ return;
536
+ const target = vm.runtime.getTargetById(endpoint.targetId);
537
+ if (!selectable(target))
538
+ return;
539
+ if (target === view.target)
540
+ send(view, { type: 'relation-focus', blockId: endpoint.blockId, scriptId: endpoint.scriptId });
541
+ else {
542
+ view.relationFocus = endpoint;
543
+ pending = view;
544
+ retarget(view, target);
545
+ }
546
+ return;
547
+ }
493
548
  if (!owns(view, message))
494
549
  return;
495
550
  if (message.type === 'field-editor' || message.type === 'field-action') {
@@ -594,6 +649,7 @@ export function createCodeSession({ vm, workspace, ScratchBlocks, document, loca
594
649
  }
595
650
  }
596
651
  function targetsUpdated() {
652
+ updateRelations();
597
653
  if (views.size)
598
654
  updateCatalog();
599
655
  for (const view of views)
@@ -694,6 +750,7 @@ export function createCodeSession({ vm, workspace, ScratchBlocks, document, loca
694
750
  vm.on('workspaceUpdate', flushWorkspaceProjection);
695
751
  vm.on('EXTENSION_ADDED', extensionsUpdated);
696
752
  vm.on('BLOCKSINFO_UPDATE', extensionsUpdated);
753
+ vm.runtime.on?.('PROJECT_CHANGED', updateRelations);
697
754
  return { attach, flush, setCanDuplicate(available) {
698
755
  if (available === canDuplicate)
699
756
  return;
@@ -720,6 +777,7 @@ export function createCodeSession({ vm, workspace, ScratchBlocks, document, loca
720
777
  parent.removeEventListener('focus', parentFocus);
721
778
  vm.removeListener('targetsUpdate', targetsUpdated);
722
779
  vm.removeListener('workspaceUpdate', flushWorkspaceProjection);
780
+ vm.runtime.removeListener?.('PROJECT_CHANGED', updateRelations);
723
781
  vm.removeListener('EXTERNAL_BLOCKS_RELOADED', externalBlocksReloaded);
724
782
  vm.removeListener('EXTENSION_ADDED', extensionsUpdated);
725
783
  vm.removeListener('BLOCKSINFO_UPDATE', extensionsUpdated);
@@ -0,0 +1,47 @@
1
+ import { type RelationTarget, type ScriptEndpoint, type ScriptRelation } from './script-relations.ts';
2
+ export interface ScriptRelationContext {
3
+ vm?: {
4
+ runtime?: {
5
+ targets?: readonly RelationTarget[];
6
+ on?(name: string, listener: () => void): void;
7
+ removeListener?(name: string, listener: () => void): void;
8
+ };
9
+ on?(name: string, listener: () => void): void;
10
+ removeListener?(name: string, listener: () => void): void;
11
+ setEditingTarget?(id: string): void;
12
+ };
13
+ getTarget(): RelationTarget | undefined;
14
+ /** A child window receives the parent's graph rather than interpreting a partial project. */
15
+ getRelations?(): readonly ScriptRelation[];
16
+ getLocale?(): string;
17
+ getTargetName?(id: string): string | undefined;
18
+ navigate?(endpoint: ScriptEndpoint): void;
19
+ }
20
+ export declare function registerScriptRelationNavigation(vm: object, navigate: (endpoint: ScriptEndpoint) => void): () => void;
21
+ /** One renderer and semantic stylesheet serve live code, folded scripts, previews and serial layouts. */
22
+ export declare function attachScriptArrows({ workspace, vm, getTarget, getRelations, getLocale, getTargetName, navigate }: ScriptRelationContext & {
23
+ workspace: {
24
+ getInjectionDiv(): HTMLElement;
25
+ getCanvas(): SVGElement;
26
+ getParentSvg(): SVGElement;
27
+ getBlockById?(id: string): {
28
+ width?: number;
29
+ height?: number;
30
+ getSvgRoot(): SVGElement | null;
31
+ } | null;
32
+ addChangeListener?(listener: (event: {
33
+ type?: string;
34
+ }) => void): void;
35
+ removeChangeListener?(listener: (event: {
36
+ type?: string;
37
+ }) => void): void;
38
+ centerOnBlock(id: string): void;
39
+ RTL?: boolean;
40
+ };
41
+ }): {
42
+ update: () => void;
43
+ readonly enabled: boolean;
44
+ setEnabled(value: boolean): void;
45
+ setProjection(svg: SVGSVGElement | null): void;
46
+ dispose(): void;
47
+ };