@kubohiroya/turbowarp-plus-editor-code-views 0.18.0 → 0.19.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
@@ -41,11 +41,27 @@ TurboWarp Plus Editor のコードの画面。1つの作品と1つの取り消
41
41
 
42
42
  Editor は GUI の React 16 にこれらを描画するので、React 16.14 以降に対応する。
43
43
 
44
+ ## スクリプト間の矢印
45
+
46
+ コードの背面に、関数呼び出しを紫系の実線、メッセージ送信を橙系の破線で表示する。「送って待つ」には待機の印を添える。通常配置、Z/N 配置、折り畳み、プレビュー、別窓で同じ表現を使う。関数の再帰はスクリプトの外へ回る線で示す。選択・ホバーによる強調は太さと不透明度で行い、関係種別の色・線種は変えない。
47
+
48
+ 関係は作品データから読み、折り畳みによって表示から消えた呼び出しも保持する。展開中は呼び出しブロックから、折り畳み中は見えているハットから結ぶ。同じハットと宛先へ重なる呼び出しは件数を表示する。別スプライトや一スクリプト表示の外にある接続先は、画面端の案内から辿れる。変数などで呼び出し先が変わるものは「実行時に決定」と示し、見えていない既定値を宛先とみなさない。
49
+
50
+ スクリプトをドラッグしている間は、そこへ入る・そこから出る矢印を太く濃くし、画面にある相手のスクリプト全体を枠で強調する。関係しない矢印は薄くし、画面外の相手は接続先の案内を強調する。関数とメッセージの色・線種は維持する。折り畳み中も同じように働き、ドラッグの終了・矢印の非表示・画面の破棄で一時的な枠を解除する。移動中に Blockly がブロックを別の SVG へ移しても追従する。
51
+
52
+ `attachDockedScriptLayout` と `attachCodeWorkspace` のプレビュー・関数エディタには自動で付く。VM を持たない表示では、`attachScriptView` に `relations: {getTarget, getRelations, getTargetName, navigate}` を渡す。`getRelations` は親の `createCodeSession` が渡す `scriptRelations`、`getTarget` はその対象の `blocks` を使う。`getTargetName` は既存の対象一覧から名前を返し、同じメッセージを受信する別スプライトを案内で識別できるようにする。投影の受信後は `view.relations.update()` を呼ぶ。関係だけの更新は `relations`、接続先への移動は `relation-navigate`/`relation-focus` で既存の編集回収・対象切り替えを経由する。編集中の窓には履歴の更新のために XML を再読み込みさせない。
53
+
54
+ 色は共通の CSS 変数 `--tw-script-function-stroke` と `--tw-script-message-stroke` に定義する。明暗テーマでは同じ種別のまま明度を変え、線種でも区別できる。既存の関数呼び出し図とミニマップも関数用の変数を使う。
55
+
56
+ コード画面に常設の凡例や表示スイッチは置かない。選択・ホバー・ドラッグ中の関係に必要な接続先だけを短く表示する。呼び出し関係の図へ渡す `readScriptRelationGraph(targets, ScratchBlocks)` は、同じ関係データと、接続先スクリプトのハットの文言・対象名・位置を返す。図の向きと関数・メッセージの表示は、呼び出し関係パネルの左端カラム下端で操作する。
57
+
58
+ 既定は表示する。作品の保存形式は変えない。完全に切り戻す場合は導入前のパッケージ固定と結線へ戻す。関連: [Editor #683](https://github.com/kubohiroya/turbowarp-plus-editor/issues/683)。
59
+
44
60
  ## 検証
45
61
 
46
62
  `npm test` でビルドし、単体テストを実行し、React 16.14 より新しい API を使っていないことを確かめる。
47
63
 
48
- `npm run test:browser` は、最小のエディター実行環境(`@kubohiroya/turbowarp-plus-editor-test-runtime`)で、Editor と同じ VM と Scratch Blocks を使い、パレットのグループを Chromium で操作して確かめる(子ブロックパレット、ピン、並べ替え、別窓のパレット)。`TWPE_CHROME_EXECUTABLE` を指定すると、Playwright のものの代わりにその Chromium を使う。
64
+ `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
65
 
50
66
  ## ライセンス
51
67
 
@@ -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. */
@@ -24,7 +25,10 @@ export function createCodePaneAdapter(vm, locale, attachMinimap) {
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;
@@ -355,6 +359,37 @@ export function readHatScripts(target, ScratchBlocks, skip = new Set()) {
355
359
  workspace.dispose();
356
360
  }
357
361
  }
362
+ /** Supply the calls panel with the same relations and native hat labels as the code workspace. */
363
+ export function readScriptRelationGraph(targets, ScratchBlocks) {
364
+ const scriptRelations = readScriptRelations(targets);
365
+ const used = new Map();
366
+ for (const relation of scriptRelations) {
367
+ for (const endpoint of [relation.source, relation.destination]) {
368
+ if (!endpoint)
369
+ continue;
370
+ if (!used.has(endpoint.targetId))
371
+ used.set(endpoint.targetId, new Set());
372
+ used.get(endpoint.targetId).add(endpoint.scriptId);
373
+ }
374
+ }
375
+ const scripts = [];
376
+ for (const target of targets) {
377
+ if (target.isOriginal === false || !used.has(target.id))
378
+ continue;
379
+ const hats = new Map(readHatScripts(target, ScratchBlocks).map(hat => [hat.id, hat]));
380
+ for (const scriptId of used.get(target.id)) {
381
+ const block = target.blocks._blocks[scriptId];
382
+ if (!block)
383
+ continue;
384
+ const prototype = target.blocks._blocks[block.inputs?.custom_block?.block ?? ''];
385
+ const label = hats.get(scriptId)?.label ?? String(prototype?.mutation?.proccode ??
386
+ block.fields?.BROADCAST_OPTION?.value ?? block.opcode);
387
+ scripts.push({ targetId: target.id, scriptId, label, targetName: target.getName?.(),
388
+ isStage: Boolean(target.isStage), x: block.x ?? 0, y: block.y ?? 0 });
389
+ }
390
+ }
391
+ return { scriptRelations, scripts };
392
+ }
358
393
  /**
359
394
  * Add “Show this function” at the top of the menu of every block that calls a function, in the code area and
360
395
  * 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,8 @@ 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 { readScriptRelations } from './script-relations.ts';
6
+ export type { ScriptEndpoint, ScriptRelation } from './script-relations.ts';
5
7
  export declare function refreshExternalBlockViews(vm: any, targets: any): void;
6
8
  export declare function createCodeSession({ vm, workspace, ScratchBlocks, document, locale, canUse, onError, receiveBackpackDrop }: {
7
9
  vm: any;
package/dist/index.js CHANGED
@@ -6,8 +6,10 @@ 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 { readScriptRelations } from "./script-relations.js";
11
13
  // A drop must stay within one target's block and comment history.
12
14
  const supportsSharedHistory = script => !script.variables.length && !script.extensionIDs?.length &&
13
15
  !Object.keys(script.extensionURLs).length;
@@ -61,6 +63,7 @@ export function createCodeSession({ vm, workspace, ScratchBlocks, document, loca
61
63
  let lease = 0;
62
64
  let projecting = false;
63
65
  let disposed = false;
66
+ let relationsPending = false;
64
67
  let canDuplicate = false;
65
68
  let flushRequest = 0;
66
69
  const flushes = new Set();
@@ -75,10 +78,31 @@ export function createCodeSession({ vm, workspace, ScratchBlocks, document, loca
75
78
  const dynamicShapesFor = target => getCodeDynamicShapes(vm.runtime, target);
76
79
  const projection = (target, xml = workspaceXML(vm, target)) => ({
77
80
  ...histories.get(target).state, xml, dynamicShapes: dynamicShapesFor(target),
81
+ blocks: target.blocks._blocks,
82
+ scriptRelations: readScriptRelations(vm.runtime.targets.filter(selectable)),
78
83
  nativeFieldGraphics: vm.editingTarget === target ? projectNativeFieldGraphics(vm.runtime, target, workspace) : []
79
84
  });
80
85
  const extensionsFor = target => getCodeExtensions(vm.runtime, target);
81
- const send = (view, message) => view.port.postMessage(message);
86
+ const send = (view, message) => {
87
+ if (message.scriptRelations)
88
+ view.relationSignature = JSON.stringify(message.scriptRelations);
89
+ view.port.postMessage(message);
90
+ };
91
+ function updateRelations() {
92
+ if (relationsPending || !views.size)
93
+ return;
94
+ relationsPending = true;
95
+ queueMicrotask(() => {
96
+ relationsPending = false;
97
+ if (disposed || !views.size)
98
+ return;
99
+ const scriptRelations = readScriptRelations(vm.runtime.targets.filter(selectable));
100
+ const signature = JSON.stringify(scriptRelations);
101
+ for (const view of views)
102
+ if (view.relationSignature !== signature)
103
+ send(view, { type: 'relations', scriptRelations });
104
+ });
105
+ }
82
106
  function updateCatalog() {
83
107
  const targets = vm.runtime.targets.filter(selectable).map(target => {
84
108
  const asset = target.getCostumes?.()[target.currentCostume]?.asset;
@@ -126,8 +150,11 @@ export function createCodeSession({ vm, workspace, ScratchBlocks, document, loca
126
150
  for (const view of views) {
127
151
  if (view.target !== target)
128
152
  continue;
129
- send(view, view === source ? { type: 'history', ...histories.get(target).state } : { type: 'update', ...data });
153
+ // The editing source must keep its live fields and queued edits; only other views reload XML.
154
+ send(view, view === source ? { type: 'history', ...histories.get(target).state,
155
+ blocks: data.blocks, scriptRelations: data.scriptRelations } : { type: 'update', ...data });
130
156
  }
157
+ updateRelations();
131
158
  }
132
159
  function flushParent() {
133
160
  for (const target of dirty) {
@@ -184,6 +211,11 @@ export function createCodeSession({ vm, workspace, ScratchBlocks, document, loca
184
211
  if (!histories.has(target))
185
212
  histories.set(target, createHistory(target, vm.runtime.getTargetForStage()));
186
213
  send(view, { type: 'target', targetId: target.id, extensions: extensionsFor(target), ...projection(target) });
214
+ if (view.relationFocus?.targetId === target.id) {
215
+ const { blockId, scriptId } = view.relationFocus;
216
+ view.relationFocus = undefined;
217
+ send(view, { type: 'relation-focus', blockId, scriptId });
218
+ }
187
219
  }
188
220
  function grant() {
189
221
  if (disposed || owner)
@@ -490,6 +522,28 @@ export function createCodeSession({ vm, workspace, ScratchBlocks, document, loca
490
522
  accept: supportsSharedHistory, commit: apply => queueDrop(target, apply) });
491
523
  return;
492
524
  }
525
+ if (message.type === 'relation-navigate') {
526
+ if (view.draining || !viewFocused(view) || !exists(view.target))
527
+ return;
528
+ const endpoint = { targetId: message.targetId, blockId: message.blockId, scriptId: message.scriptId };
529
+ const matches = candidate => candidate && candidate.targetId === endpoint.targetId &&
530
+ candidate.blockId === endpoint.blockId && candidate.scriptId === endpoint.scriptId;
531
+ // Navigation is limited to an existing endpoint related to this window's target.
532
+ if (!readScriptRelations(vm.runtime.targets.filter(selectable)).some(relation => (relation.source.targetId === view.target.id || relation.destination?.targetId === view.target.id) &&
533
+ (matches(relation.source) || matches(relation.destination))))
534
+ return;
535
+ const target = vm.runtime.getTargetById(endpoint.targetId);
536
+ if (!selectable(target))
537
+ return;
538
+ if (target === view.target)
539
+ send(view, { type: 'relation-focus', blockId: endpoint.blockId, scriptId: endpoint.scriptId });
540
+ else {
541
+ view.relationFocus = endpoint;
542
+ pending = view;
543
+ retarget(view, target);
544
+ }
545
+ return;
546
+ }
493
547
  if (!owns(view, message))
494
548
  return;
495
549
  if (message.type === 'field-editor' || message.type === 'field-action') {
@@ -594,6 +648,7 @@ export function createCodeSession({ vm, workspace, ScratchBlocks, document, loca
594
648
  }
595
649
  }
596
650
  function targetsUpdated() {
651
+ updateRelations();
597
652
  if (views.size)
598
653
  updateCatalog();
599
654
  for (const view of views)
@@ -694,6 +749,7 @@ export function createCodeSession({ vm, workspace, ScratchBlocks, document, loca
694
749
  vm.on('workspaceUpdate', flushWorkspaceProjection);
695
750
  vm.on('EXTENSION_ADDED', extensionsUpdated);
696
751
  vm.on('BLOCKSINFO_UPDATE', extensionsUpdated);
752
+ vm.runtime.on?.('PROJECT_CHANGED', updateRelations);
697
753
  return { attach, flush, setCanDuplicate(available) {
698
754
  if (available === canDuplicate)
699
755
  return;
@@ -720,6 +776,7 @@ export function createCodeSession({ vm, workspace, ScratchBlocks, document, loca
720
776
  parent.removeEventListener('focus', parentFocus);
721
777
  vm.removeListener('targetsUpdate', targetsUpdated);
722
778
  vm.removeListener('workspaceUpdate', flushWorkspaceProjection);
779
+ vm.runtime.removeListener?.('PROJECT_CHANGED', updateRelations);
723
780
  vm.removeListener('EXTERNAL_BLOCKS_RELOADED', externalBlocksReloaded);
724
781
  vm.removeListener('EXTENSION_ADDED', extensionsUpdated);
725
782
  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
+ };