@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.
@@ -0,0 +1,47 @@
1
+ /** The serialized program is the source of relations, even when a view omits a folded body. */
2
+ export interface RelationBlock {
3
+ id: string;
4
+ opcode: string;
5
+ parent?: string | null;
6
+ next?: string | null;
7
+ inputs?: Record<string, {
8
+ block?: string | null;
9
+ shadow?: string | null;
10
+ }>;
11
+ fields?: Record<string, {
12
+ value?: unknown;
13
+ id?: string;
14
+ }>;
15
+ mutation?: Record<string, unknown>;
16
+ topLevel?: boolean;
17
+ shadow?: boolean;
18
+ x?: number;
19
+ y?: number;
20
+ }
21
+ export interface RelationTarget {
22
+ id: string;
23
+ isOriginal?: boolean;
24
+ isStage?: boolean;
25
+ getName?(): string;
26
+ blocks: {
27
+ _blocks: Record<string, RelationBlock>;
28
+ };
29
+ }
30
+ export interface ScriptEndpoint {
31
+ targetId: string;
32
+ blockId: string;
33
+ scriptId: string;
34
+ }
35
+ export interface ScriptRelation {
36
+ kind: 'function' | 'message';
37
+ source: ScriptEndpoint;
38
+ destination?: ScriptEndpoint;
39
+ label: string;
40
+ wait: boolean;
41
+ unresolved?: 'dynamic' | 'missing' | 'ambiguous';
42
+ }
43
+ /**
44
+ * Extract possible static calls without executing the project or modifying its blocks.
45
+ * Broadcasts fan out; conflicting function definitions and computed names stay unresolved.
46
+ */
47
+ export declare function readScriptRelations(targets: readonly RelationTarget[]): ScriptRelation[];
@@ -0,0 +1,155 @@
1
+ const namedPrefix = 'kubohiroyanamedfunctions_';
2
+ function program(target) {
3
+ const blocks = target.blocks._blocks;
4
+ const roots = new Map();
5
+ function endpoint(id) {
6
+ const path = new Set();
7
+ let current = id;
8
+ let root;
9
+ while (true) {
10
+ if (roots.has(current)) {
11
+ root = roots.get(current);
12
+ break;
13
+ }
14
+ if (path.has(current) || !blocks[current])
15
+ break;
16
+ path.add(current);
17
+ const parent = blocks[current].parent;
18
+ if (!parent) {
19
+ root = current;
20
+ break;
21
+ }
22
+ current = parent;
23
+ }
24
+ for (const member of path)
25
+ roots.set(member, root);
26
+ return root ? { targetId: target.id, blockId: id, scriptId: root } : undefined;
27
+ }
28
+ return { target, blocks, endpoint };
29
+ }
30
+ /** Read the active literal only; an obscured menu/text shadow is never a possible destination. */
31
+ function inputLiteral(block, blocks, name) {
32
+ const input = block.inputs?.[name];
33
+ const value = input?.block ? blocks[input.block] : undefined;
34
+ if (!value)
35
+ return undefined;
36
+ const field = value.opcode === 'text' ? value.fields?.TEXT :
37
+ value.opcode === 'event_broadcast_menu' ? value.fields?.BROADCAST_OPTION : undefined;
38
+ return field?.value === undefined || field.value === null ? undefined : String(field.value);
39
+ }
40
+ function append(map, key, value) {
41
+ const entries = map.get(key);
42
+ if (entries)
43
+ entries.push(value);
44
+ else
45
+ map.set(key, [value]);
46
+ }
47
+ /**
48
+ * Extract possible static calls without executing the project or modifying its blocks.
49
+ * Broadcasts fan out; conflicting function definitions and computed names stay unresolved.
50
+ */
51
+ export function readScriptRelations(targets) {
52
+ const seenTargets = new Set();
53
+ const programs = targets.filter(target => {
54
+ if (target.isOriginal === false || seenTargets.has(target.id))
55
+ return false;
56
+ seenTargets.add(target.id);
57
+ return true;
58
+ }).map(program);
59
+ const procedures = new Map();
60
+ const functions = new Map();
61
+ const receivers = new Map();
62
+ for (const { target, blocks, endpoint } of programs) {
63
+ const own = new Map();
64
+ procedures.set(target.id, own);
65
+ for (const block of Object.values(blocks)) {
66
+ if (block.parent || block.topLevel === false || block.shadow)
67
+ continue;
68
+ const destination = endpoint(block.id);
69
+ if (!destination)
70
+ continue;
71
+ if (block.opcode === 'procedures_definition') {
72
+ const prototype = blocks[block.inputs?.custom_block?.block ?? ''];
73
+ const code = prototype?.opcode === 'procedures_prototype' ? prototype.mutation?.proccode : undefined;
74
+ if (typeof code === 'string')
75
+ append(own, code, destination);
76
+ }
77
+ else if (block.opcode === `${namedPrefix}defineFunction`) {
78
+ // A named definition's NAME is required to be literal, including its shadow connection.
79
+ const input = block.inputs?.NAME;
80
+ if (input?.block && input.block !== input.shadow)
81
+ continue;
82
+ const name = inputLiteral(block, blocks, 'NAME')?.trim();
83
+ const scope = block.fields?.SCOPE?.value;
84
+ if (name && (scope === undefined || scope === null || scope === 'global' || scope === 'sprite')) {
85
+ append(functions, name, { endpoint: destination, scope: scope === 'sprite' ? 'sprite' : 'global' });
86
+ }
87
+ }
88
+ else if (block.opcode === 'event_whenbroadcastreceived') {
89
+ const name = block.fields?.BROADCAST_OPTION?.value;
90
+ if (name !== undefined && name !== null)
91
+ append(receivers, String(name).toUpperCase(), destination);
92
+ }
93
+ }
94
+ }
95
+ const relations = [];
96
+ for (const { target, blocks, endpoint } of programs) {
97
+ for (const block of Object.values(blocks)) {
98
+ let kind;
99
+ let name;
100
+ let wait = true;
101
+ let destinations = [];
102
+ let hasInput = true;
103
+ if (block.opcode === 'procedures_call') {
104
+ kind = 'function';
105
+ name = typeof block.mutation?.proccode === 'string' ? block.mutation.proccode : undefined;
106
+ destinations = procedures.get(target.id)?.get(name) ?? [];
107
+ hasInput = name !== undefined;
108
+ }
109
+ else if (block.opcode === 'event_broadcast' || block.opcode === 'event_broadcastandwait') {
110
+ kind = 'message';
111
+ wait = block.opcode === 'event_broadcastandwait';
112
+ name = inputLiteral(block, blocks, 'BROADCAST_INPUT');
113
+ destinations = name === undefined ? [] : receivers.get(name.toUpperCase()) ?? [];
114
+ hasInput = Boolean(block.inputs?.BROADCAST_INPUT?.block);
115
+ }
116
+ else if (block.opcode === `${namedPrefix}callFunction` || block.opcode === `${namedPrefix}startFunction` ||
117
+ block.opcode === `${namedPrefix}callFunctionFromMenu`) {
118
+ kind = 'function';
119
+ wait = block.opcode !== `${namedPrefix}startFunction`;
120
+ if (block.opcode === `${namedPrefix}callFunctionFromMenu`) {
121
+ const field = block.fields?.FUNCTION?.value;
122
+ name = field === undefined || field === null ? undefined : String(field);
123
+ hasInput = name !== undefined;
124
+ }
125
+ else {
126
+ name = inputLiteral(block, blocks, 'NAME');
127
+ hasInput = Boolean(block.inputs?.NAME?.block);
128
+ }
129
+ name = name?.trim();
130
+ destinations = (functions.get(name) ?? []).filter(definition => definition.scope === 'global' ||
131
+ definition.endpoint.targetId === target.id).map(definition => definition.endpoint);
132
+ }
133
+ else
134
+ continue;
135
+ const source = endpoint(block.id);
136
+ if (!source || block.shadow)
137
+ continue;
138
+ const relation = { kind, source, label: name ?? '', wait };
139
+ if (name === undefined) {
140
+ relations.push({ ...relation, unresolved: hasInput ? 'dynamic' : 'missing' });
141
+ }
142
+ else if (!destinations.length) {
143
+ relations.push({ ...relation, unresolved: 'missing' });
144
+ }
145
+ else if (kind === 'function' && destinations.length > 1) {
146
+ relations.push({ ...relation, unresolved: 'ambiguous' });
147
+ }
148
+ else {
149
+ for (const destination of destinations)
150
+ relations.push({ ...relation, destination });
151
+ }
152
+ }
153
+ }
154
+ return relations;
155
+ }
@@ -1,7 +1,8 @@
1
1
  import React from 'react';
2
2
  import type { createCodePaneAdapter } from './code-pane.ts';
3
3
  export { attachCodeWorkspace } from './workspace.ts';
4
- export { attachFunctionCallMenu, createCodePaneAdapter, createFunction, mountProcedureEditor, readHatScripts, readSavedCodePane } from './code-pane.ts';
4
+ export { fitScriptInWorkspace } from './script-fit.ts';
5
+ export { attachFunctionCallMenu, createCodePaneAdapter, createFunction, mountProcedureEditor, readHatScripts, readSavedCodePane, readScriptRelationGraph } from './code-pane.ts';
5
6
  export type { SavedCodePane } from './code-pane.ts';
6
7
  export declare function CodePaneCostumeThumbnail({ adapter }: {
7
8
  adapter: ReturnType<typeof createCodePaneAdapter>;
@@ -2,7 +2,8 @@ import React from 'react';
2
2
  import { createPortal } from 'react-dom';
3
3
  import { getCodeSession } from "./workspace.js";
4
4
  export { attachCodeWorkspace } from "./workspace.js";
5
- export { attachFunctionCallMenu, createCodePaneAdapter, createFunction, mountProcedureEditor, readHatScripts, readSavedCodePane } from "./code-pane.js";
5
+ export { fitScriptInWorkspace } from "./script-fit.js";
6
+ export { attachFunctionCallMenu, createCodePaneAdapter, createFunction, mountProcedureEditor, readHatScripts, readSavedCodePane, readScriptRelationGraph } from "./code-pane.js";
6
7
  export function CodePaneCostumeThumbnail({ adapter }) {
7
8
  const image = React.useRef(null);
8
9
  React.useLayoutEffect(() => adapter.watchEditingCostume(image.current), [adapter]);
@@ -2,6 +2,7 @@ import { type CodeTarget } from './history.ts';
2
2
  import { captureCodePreviewChrome } from './preview-chrome.ts';
3
3
  import type { PresentationElements } from './preview-chrome.ts';
4
4
  import { type ScriptView } from './script-layout-view.ts';
5
+ import type { ScriptEndpoint } from './script-relations.ts';
5
6
  export type AttachPreviewMinimap = (workspace: any, ScratchBlocks: any, watermark: HTMLElement) => {
6
7
  dispose(): void;
7
8
  };
@@ -25,8 +26,8 @@ interface CodeSession {
25
26
  presentation?: Presentation;
26
27
  } | null;
27
28
  bridge: ReturnType<typeof attachCodeWorkspace> | null;
28
- subscribe(listener: () => void): () => void;
29
- changed(): void;
29
+ subscribe(listener: (navigation?: ScriptEndpoint) => void): () => void;
30
+ changed(navigation?: ScriptEndpoint): void;
30
31
  }
31
32
  export declare function getCodeSession(vm: object): CodeSession;
32
33
  type MeasuredField = {
@@ -78,7 +79,7 @@ export declare function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspa
78
79
  * Show only one script in the code area, a hat or a function, or every script again without `id`.
79
80
  * `onLost` runs when that script is deleted.
80
81
  */
81
- focusScript(id?: string, onLost?: () => void): void;
82
+ focusScript(id?: string, onLost?: () => void, refit?: boolean): void;
82
83
  readonly focusedScript: string;
83
84
  createFunction(target: CodeTarget & {
84
85
  id: string;
package/dist/workspace.js CHANGED
@@ -5,6 +5,8 @@ import { isFoldedDefinition, removeObsoleteProcedureInputs, setFoldedDefinition
5
5
  import { decodeEdit, encodeEdit, isCommentEdit } from "./protocol.js";
6
6
  import { captureCodePreviewChrome } from "./preview-chrome.js";
7
7
  import { attachScriptView, getDockedScriptLayout } from "./script-layout-view.js";
8
+ import { attachScriptArrows, registerScriptRelationNavigation } from "./script-arrows.js";
9
+ import { fitScriptInWorkspace } from "./script-fit.js";
8
10
  const sessions = new WeakMap();
9
11
  export function getCodeSession(vm) {
10
12
  let session = sessions.get(vm);
@@ -17,9 +19,9 @@ export function getCodeSession(vm) {
17
19
  listeners.add(listener);
18
20
  return () => listeners.delete(listener);
19
21
  },
20
- changed() {
22
+ changed(navigation) {
21
23
  for (const listener of listeners)
22
- listener();
24
+ listener(navigation);
23
25
  }
24
26
  };
25
27
  sessions.set(vm, session);
@@ -241,28 +243,17 @@ function attachScriptVisibility({ vm, blocks, workspace, homeDocument, onError }
241
243
  safePaint();
242
244
  }
243
245
  /**
244
- * Put the shown script at the top left of the view, once the code area has its size there: the view it
245
- * moves into may only be laid out after the script was picked.
246
+ * Fit the shown script once the code area has its size: its destination view may only be laid out
247
+ * after the script was picked. Later edits and manual zooms keep their viewport.
246
248
  */
247
249
  let revealPending = false;
248
250
  function reveal() {
249
251
  if (!revealPending)
250
252
  return;
251
- const block = focus && workspace.getBlockById(focus.id);
252
- const injection = workspace.getInjectionDiv();
253
- if (!block || !injection.clientWidth || !injection.clientHeight)
254
- return;
255
- // The scroll area follows the shown scripts, which may have changed since the scrollbars were sized.
256
- workspace.resize?.();
257
- const metrics = workspace.getMetrics?.();
258
- if (!metrics?.viewWidth || !metrics.viewHeight)
259
- return;
260
- revealPending = false;
261
- const { x, y } = block.getRelativeToSurfaceXY();
262
- const padding = 16;
263
- workspace.scrollbar?.set(x * workspace.scale - metrics.contentLeft - padding, y * workspace.scale - metrics.contentTop - padding);
253
+ if (focus && fitScriptInWorkspace(workspace, focus.id, blocks))
254
+ revealPending = false;
264
255
  }
265
- function setFocus(next) {
256
+ function setFocus(next, refit = false) {
266
257
  const changedScript = next?.id !== focus?.id;
267
258
  focus = next && { id: next.id, onLost: next.onLost, extras: changedScript ? new Set() : focus?.extras ?? new Set() };
268
259
  if (focus) {
@@ -287,11 +278,13 @@ function attachScriptVisibility({ vm, blocks, workspace, homeDocument, onError }
287
278
  safePaint();
288
279
  if (workspace.rendered && workspace.isVisible?.() !== false)
289
280
  workspace.resize?.();
290
- if (focus && changedScript) {
281
+ if (focus && (changedScript || refit)) {
291
282
  revealPending = true;
292
- reveal();
283
+ // The pane can still be moving from its previous size during this activation.
293
284
  schedulePaint();
294
285
  }
286
+ else if (!focus)
287
+ revealPending = false;
295
288
  }
296
289
  // Blocks dragged in from the palette, or pulled out of the shown script, stay in view. Only the end of a
297
290
  // drag counts: a reload of the workspace also sends a create event for every block, after the load.
@@ -341,9 +334,9 @@ function attachScriptVisibility({ vm, blocks, workspace, homeDocument, onError }
341
334
  if (!disposed)
342
335
  reveal();
343
336
  },
344
- focus: (id, onLost) => {
337
+ focus: (id, onLost, refit = false) => {
345
338
  if (!disposed)
346
- setFocus(id ? { id, onLost } : undefined);
339
+ setFocus(id ? { id, onLost } : undefined, refit);
347
340
  },
348
341
  get focusedScript() { return focus?.id; },
349
342
  dispose() {
@@ -566,6 +559,7 @@ export function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspace, opti
566
559
  const minimap = attachMinimap?.(preview, blocks, watermark);
567
560
  const scriptView = attachScriptView({ workspace: preview, ScratchBlocks: blocks, mount: chrome.parentElement,
568
561
  getLocale: () => locale ?? workspace.getInjectionDiv().ownerDocument.documentElement.lang,
562
+ relations: { vm, getTarget: () => target },
569
563
  initialView: view.scriptView ?? presentation?.scriptView,
570
564
  onChange: next => {
571
565
  if (presentation)
@@ -633,8 +627,8 @@ export function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspace, opti
633
627
  * Show only one script in the code area, a hat or a function, or every script again without `id`.
634
628
  * `onLost` runs when that script is deleted.
635
629
  */
636
- focusScript(id, onLost) {
637
- visibility.focus(id, onLost);
630
+ focusScript(id, onLost, refit = false) {
631
+ visibility.focus(id, onLost, refit);
638
632
  },
639
633
  get focusedScript() { return visibility.focusedScript; },
640
634
  createFunction(target, kind, name, { loadNamedFunctions } = {}) {
@@ -647,6 +641,7 @@ export function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspace, opti
647
641
  },
648
642
  dispose() {
649
643
  blockDrag.dispose();
644
+ unregisterRelationNavigation();
650
645
  unregisterCodeWorkspace();
651
646
  shown?.disconnect();
652
647
  visibility.dispose();
@@ -676,6 +671,23 @@ export function attachCodeWorkspace({ vm, ScratchBlocks: blocks, workspace, opti
676
671
  shown?.observe(injection);
677
672
  const blockDrag = attachBlockDrag({ vm, workspace, ScratchBlocks: blocks, onError, prepareImport: bridge.prepareImport });
678
673
  const visibility = attachScriptVisibility({ vm, blocks, workspace, homeDocument, onError });
674
+ const unregisterRelationNavigation = registerScriptRelationNavigation(vm, endpoint => {
675
+ if (vm.runtime.getTargetById(endpoint.targetId)?.blocks._blocks[endpoint.blockId] === undefined)
676
+ return;
677
+ if (vm.editingTarget?.id !== endpoint.targetId)
678
+ vm.setEditingTarget(endpoint.targetId);
679
+ view.requestAnimationFrame(() => {
680
+ if (session.bridge !== bridge)
681
+ return;
682
+ // Let a target switch restore that pane's mode first. Normal views keep showing all scripts.
683
+ if (visibility.focusedScript) {
684
+ visibility.focus(endpoint.scriptId, undefined, true);
685
+ session.changed(endpoint);
686
+ }
687
+ else
688
+ workspace.centerOnBlock(endpoint.scriptId);
689
+ });
690
+ });
679
691
  visibility.paint();
680
692
  session.bridge = bridge;
681
693
  vm.runtime.on('PROJECT_CHANGED', changed);
@@ -827,15 +839,7 @@ function attachProcedureEditor({ vm, blocks, workspace, options, onError, homeDo
827
839
  let rendered;
828
840
  let positioned = false;
829
841
  function position() {
830
- const definition = editor.getBlockById(definitionId);
831
- const metrics = editor.getMetrics();
832
- if (!definition || !metrics?.viewWidth || !metrics.viewHeight)
833
- return false;
834
- // Put the hat at the top left whatever its place in the code area.
835
- const { x, y } = definition.getRelativeToSurfaceXY();
836
- const padding = 16;
837
- editor.scrollbar.set(x * editor.scale - metrics.contentLeft - padding, y * editor.scale - metrics.contentTop - padding);
838
- return true;
842
+ return fitScriptInWorkspace(editor, definitionId, blocks);
839
843
  }
840
844
  function load() {
841
845
  if (!exists() || !target.blocks._blocks[definitionId])
@@ -891,7 +895,7 @@ function attachProcedureEditor({ vm, blocks, workspace, options, onError, homeDo
891
895
  return;
892
896
  }
893
897
  pendingBlock = undefined;
894
- editor.centerOnBlock(block.id);
898
+ fitScriptInWorkspace(editor, definitionId, blocks);
895
899
  block.select();
896
900
  }
897
901
  let frame;
@@ -970,6 +974,8 @@ function attachProcedureEditor({ vm, blocks, workspace, options, onError, homeDo
970
974
  };
971
975
  document.addEventListener('pointerdown', releaseFocus, true);
972
976
  vm.runtime.on('PROJECT_CHANGED', scheduleLoad);
977
+ const relations = attachScriptArrows({ workspace: editor, vm, getTarget: () => target,
978
+ getLocale: () => locale });
973
979
  load();
974
980
  // In a modal dialog the rest of the page is inert, including the text and dropdown editors
975
981
  // ScratchBlocks keeps in the body. Lend them to the dialog, which covers the viewport so their
@@ -986,6 +992,7 @@ function attachProcedureEditor({ vm, blocks, workspace, options, onError, homeDo
986
992
  },
987
993
  dispose() {
988
994
  toolboxListeners.delete(refreshPalette);
995
+ relations.dispose();
989
996
  navigation?.dispose();
990
997
  element.removeAttribute('data-code-hover-surface');
991
998
  element.removeAttribute('data-hover-palette');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-code-views",
3
- "version": "0.18.0",
3
+ "version": "0.20.0",
4
4
  "description": "Code views for TurboWarp Plus Editor: code in tabs and windows, the detached block palette, script layout and block field editing",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
package/src/code-pane.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import {getCodeSession} from './workspace.ts';
2
2
  import type {AttachPreviewMinimap, AttachWorkspaceNavigation} from './workspace.ts';
3
3
  import {getDockedScriptLayout, type ScriptView} from './script-layout-view.ts';
4
+ import {readScriptRelations, type RelationTarget} from './script-relations.ts';
4
5
 
5
6
  type Pane = {id: string; targetId: string; section: number};
6
7
  type Bridge = NonNullable<ReturnType<typeof getCodeSession>['bridge']>;
@@ -34,14 +35,16 @@ export function createCodePaneAdapter(vm, locale: string, attachMinimap?: Attach
34
35
  const focused = new Map<string, {scriptId: string; onLost?: () => void}>();
35
36
  // The code pane the code area is in, which shows its script there.
36
37
  let current: string | undefined;
37
- const applyFocus = (paneId?: string) => {
38
+ const applyFocus = (paneId?: string, refit = false) => {
38
39
  const focus = paneId === undefined ? undefined : focused.get(paneId);
39
- session.bridge?.focusScript(focus?.scriptId, focus && (() => focus.onLost?.()));
40
+ session.bridge?.focusScript(focus?.scriptId, focus && (() => focus.onLost?.()), refit);
40
41
  };
41
42
  let pending: {frame: number; pane: Pane; presentation: Presentation} | undefined;
42
43
  // The GUI can attach the code area again, with a new bridge; the view it is in still shows its script.
43
44
  let attached = session.bridge;
44
- session.subscribe(() => {
45
+ session.subscribe(navigation => {
46
+ const focus = current === undefined ? undefined : focused.get(current);
47
+ if (navigation && focus) focus.scriptId = navigation.scriptId;
45
48
  if (session.bridge === attached) return;
46
49
  attached = session.bridge;
47
50
  if (current !== undefined) applyFocus(current);
@@ -77,7 +80,7 @@ export function createCodePaneAdapter(vm, locale: string, attachMinimap?: Attach
77
80
  focusPane(paneId: string, scriptId?: string, onLost?: () => void) {
78
81
  if (scriptId) focused.set(paneId, {scriptId, onLost});
79
82
  else focused.delete(paneId);
80
- if (current === paneId) applyFocus(paneId);
83
+ if (current === paneId) applyFocus(paneId, true);
81
84
  // Previews of other views redraw with their script.
82
85
  session.changed();
83
86
  },
@@ -136,6 +139,8 @@ export function createCodePaneAdapter(vm, locale: string, attachMinimap?: Attach
136
139
  const frame = requestAnimationFrame(() => {
137
140
  pending = undefined;
138
141
  session.bridge?.restorePane(pane.targetId, presentation);
142
+ // A picked script owns its initial viewport, including after a saved pane is restored.
143
+ if (focused.has(pane.id)) applyFocus(pane.id, true);
139
144
  });
140
145
  pending = {frame, pane, presentation};
141
146
  },
@@ -351,6 +356,34 @@ export function readHatScripts(target, ScratchBlocks, skip: ReadonlySet<string>
351
356
  }
352
357
  }
353
358
 
359
+ /** Supply the calls panel with the same relations and native hat labels as the code workspace. */
360
+ export function readScriptRelationGraph(targets: readonly RelationTarget[], ScratchBlocks) {
361
+ const scriptRelations = readScriptRelations(targets);
362
+ const used = new Map<string, Set<string>>();
363
+ for (const relation of scriptRelations) {
364
+ for (const endpoint of [relation.source, relation.destination]) {
365
+ if (!endpoint) continue;
366
+ if (!used.has(endpoint.targetId)) used.set(endpoint.targetId, new Set());
367
+ used.get(endpoint.targetId).add(endpoint.scriptId);
368
+ }
369
+ }
370
+ const scripts: {targetId: string; scriptId: string; label: string; targetName?: string; isStage?: boolean; x?: number; y?: number}[] = [];
371
+ for (const target of targets) {
372
+ if (target.isOriginal === false || !used.has(target.id)) continue;
373
+ const hats = new Map(readHatScripts(target, ScratchBlocks).map(hat => [hat.id, hat]));
374
+ for (const scriptId of used.get(target.id)) {
375
+ const block = target.blocks._blocks[scriptId];
376
+ if (!block) continue;
377
+ const prototype = target.blocks._blocks[block.inputs?.custom_block?.block ?? ''];
378
+ const label = hats.get(scriptId)?.label ?? String(prototype?.mutation?.proccode ??
379
+ block.fields?.BROADCAST_OPTION?.value ?? block.opcode);
380
+ scripts.push({targetId: target.id, scriptId, label, targetName: target.getName?.(),
381
+ isStage: Boolean(target.isStage), x: block.x ?? 0, y: block.y ?? 0});
382
+ }
383
+ }
384
+ return {scriptRelations, scripts};
385
+ }
386
+
354
387
  /**
355
388
  * Add “Show this function” at the top of the menu of every block that calls a function, in the code area and
356
389
  * in the script editors. `find` names the function a block calls, if any; `open` shows it.
package/src/index.ts CHANGED
@@ -6,11 +6,15 @@ import {readFieldActionPanel, runFieldAction, type FieldActionPanel, type Progra
6
6
  import {capture, createHistory, restore, workspaceXML} from './history.ts';
7
7
  import {removeObsoleteProcedureInputs} from './procedure-edits.ts';
8
8
  import {decodeEdit, isCodeEdit, isCommentEdit} from './protocol.ts';
9
+ import {readScriptRelations, type ScriptEndpoint} from './script-relations.ts';
9
10
 
10
11
  export {attachDockedCodeExtensions} from './code-extensions.ts';
11
12
  export type {NativeFieldEditSession} from './native-extension-field.ts';
12
13
  export type {FieldActionPanel, ProgrammaticExtensionField} from './programmatic-extension-field.ts';
13
14
  export {encodeEdit} from './protocol.ts';
15
+ export {fitScriptInWorkspace} from './script-fit.ts';
16
+ export {readScriptRelations} from './script-relations.ts';
17
+ export type {ScriptEndpoint, ScriptRelation} from './script-relations.ts';
14
18
 
15
19
  // A drop must stay within one target's block and comment history.
16
20
  const supportsSharedHistory = script => !script.variables.length && !script.extensionIDs?.length &&
@@ -63,6 +67,8 @@ export function createCodeSession({vm, workspace, ScratchBlocks, document, local
63
67
  document: Document;
64
68
  close(): void;
65
69
  duplicate?: () => void;
70
+ relationFocus?: ScriptEndpoint;
71
+ relationSignature?: string;
66
72
  closeNativeField?: () => void;
67
73
  fieldAction?: {request: number; blockId: string; name: string; value: string;
68
74
  editor: ProgrammaticExtensionField; panel: FieldActionPanel; submitted?: boolean};
@@ -80,6 +86,7 @@ export function createCodeSession({vm, workspace, ScratchBlocks, document, local
80
86
  let lease = 0;
81
87
  let projecting = false;
82
88
  let disposed = false;
89
+ let relationsPending = false;
83
90
  let canDuplicate = false;
84
91
  let flushRequest = 0;
85
92
  const flushes = new Set<{request: number; waiting: Set<CodeView>; resolve(): void}>();
@@ -95,10 +102,27 @@ export function createCodeSession({vm, workspace, ScratchBlocks, document, local
95
102
  const dynamicShapesFor = target => getCodeDynamicShapes(vm.runtime, target);
96
103
  const projection = (target, xml = workspaceXML(vm, target)) => ({
97
104
  ...histories.get(target).state, xml, dynamicShapes: dynamicShapesFor(target),
105
+ blocks: target.blocks._blocks,
106
+ scriptRelations: readScriptRelations(vm.runtime.targets.filter(selectable)),
98
107
  nativeFieldGraphics: vm.editingTarget === target ? projectNativeFieldGraphics(vm.runtime, target, workspace) : []
99
108
  });
100
109
  const extensionsFor = target => getCodeExtensions(vm.runtime, target);
101
- const send = (view, message) => view.port.postMessage(message);
110
+ const send = (view, message) => {
111
+ if (message.scriptRelations) view.relationSignature = JSON.stringify(message.scriptRelations);
112
+ view.port.postMessage(message);
113
+ };
114
+
115
+ function updateRelations() {
116
+ if (relationsPending || !views.size) return;
117
+ relationsPending = true;
118
+ queueMicrotask(() => {
119
+ relationsPending = false;
120
+ if (disposed || !views.size) return;
121
+ const scriptRelations = readScriptRelations(vm.runtime.targets.filter(selectable));
122
+ const signature = JSON.stringify(scriptRelations);
123
+ for (const view of views) if (view.relationSignature !== signature) send(view, {type: 'relations', scriptRelations});
124
+ });
125
+ }
102
126
 
103
127
  function updateCatalog() {
104
128
  const targets = vm.runtime.targets.filter(selectable).map(target => {
@@ -143,8 +167,11 @@ export function createCodeSession({vm, workspace, ScratchBlocks, document, local
143
167
  const data = projection(target, xml);
144
168
  for (const view of views) {
145
169
  if (view.target !== target) continue;
146
- send(view, view === source ? {type: 'history', ...histories.get(target).state} : {type: 'update', ...data});
170
+ // The editing source must keep its live fields and queued edits; only other views reload XML.
171
+ send(view, view === source ? {type: 'history', ...histories.get(target).state,
172
+ blocks: data.blocks, scriptRelations: data.scriptRelations} : {type: 'update', ...data});
147
173
  }
174
+ updateRelations();
148
175
  }
149
176
 
150
177
  function flushParent() {
@@ -196,6 +223,11 @@ export function createCodeSession({vm, workspace, ScratchBlocks, document, local
196
223
  view.target = target;
197
224
  if (!histories.has(target)) histories.set(target, createHistory(target, vm.runtime.getTargetForStage()));
198
225
  send(view, {type: 'target', targetId: target.id, extensions: extensionsFor(target), ...projection(target)});
226
+ if (view.relationFocus?.targetId === target.id) {
227
+ const {blockId, scriptId} = view.relationFocus;
228
+ view.relationFocus = undefined;
229
+ send(view, {type: 'relation-focus', blockId, scriptId});
230
+ }
199
231
  }
200
232
 
201
233
  function grant() {
@@ -470,6 +502,25 @@ export function createCodeSession({vm, workspace, ScratchBlocks, document, local
470
502
  accept: supportsSharedHistory, commit: apply => queueDrop(target, apply)});
471
503
  return;
472
504
  }
505
+ if (message.type === 'relation-navigate') {
506
+ if (view.draining || !viewFocused(view) || !exists(view.target)) return;
507
+ const endpoint = {targetId: message.targetId, blockId: message.blockId, scriptId: message.scriptId};
508
+ const matches = candidate => candidate && candidate.targetId === endpoint.targetId &&
509
+ candidate.blockId === endpoint.blockId && candidate.scriptId === endpoint.scriptId;
510
+ // Navigation is limited to an existing endpoint related to this window's target.
511
+ if (!readScriptRelations(vm.runtime.targets.filter(selectable)).some(relation =>
512
+ (relation.source.targetId === view.target.id || relation.destination?.targetId === view.target.id) &&
513
+ (matches(relation.source) || matches(relation.destination)))) return;
514
+ const target = vm.runtime.getTargetById(endpoint.targetId);
515
+ if (!selectable(target)) return;
516
+ if (target === view.target) send(view, {type: 'relation-focus', blockId: endpoint.blockId, scriptId: endpoint.scriptId});
517
+ else {
518
+ view.relationFocus = endpoint;
519
+ pending = view;
520
+ retarget(view, target);
521
+ }
522
+ return;
523
+ }
473
524
  if (!owns(view, message)) return;
474
525
  if (message.type === 'field-editor' || message.type === 'field-action') {
475
526
  handleFieldAction(view, message);
@@ -561,6 +612,7 @@ export function createCodeSession({vm, workspace, ScratchBlocks, document, local
561
612
  }
562
613
 
563
614
  function targetsUpdated() {
615
+ updateRelations();
564
616
  if (views.size) updateCatalog();
565
617
  for (const view of views) if (!exists(view.target)) view.close();
566
618
  for (const target of histories.keys()) if (!exists(target)) histories.delete(target);
@@ -648,6 +700,7 @@ export function createCodeSession({vm, workspace, ScratchBlocks, document, local
648
700
  vm.on('workspaceUpdate', flushWorkspaceProjection);
649
701
  vm.on('EXTENSION_ADDED', extensionsUpdated);
650
702
  vm.on('BLOCKSINFO_UPDATE', extensionsUpdated);
703
+ vm.runtime.on?.('PROJECT_CHANGED', updateRelations);
651
704
 
652
705
  return {attach, flush, setCanDuplicate(available) {
653
706
  if (available === canDuplicate) return;
@@ -670,6 +723,7 @@ export function createCodeSession({vm, workspace, ScratchBlocks, document, local
670
723
  parent.removeEventListener('focus', parentFocus);
671
724
  vm.removeListener('targetsUpdate', targetsUpdated);
672
725
  vm.removeListener('workspaceUpdate', flushWorkspaceProjection);
726
+ vm.runtime.removeListener?.('PROJECT_CHANGED', updateRelations);
673
727
  vm.removeListener('EXTERNAL_BLOCKS_RELOADED', externalBlocksReloaded);
674
728
  vm.removeListener('EXTENSION_ADDED', extensionsUpdated);
675
729
  vm.removeListener('BLOCKSINFO_UPDATE', extensionsUpdated);