@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.
@@ -0,0 +1,179 @@
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, {block?: string | null; shadow?: string | null}>;
8
+ fields?: Record<string, {value?: unknown; id?: string}>;
9
+ mutation?: Record<string, unknown>;
10
+ topLevel?: boolean;
11
+ shadow?: boolean;
12
+ x?: number;
13
+ y?: number;
14
+ }
15
+
16
+ export interface RelationTarget {
17
+ id: string;
18
+ isOriginal?: boolean;
19
+ isStage?: boolean;
20
+ getName?(): string;
21
+ blocks: {_blocks: Record<string, RelationBlock>};
22
+ }
23
+
24
+ export interface ScriptEndpoint {
25
+ targetId: string;
26
+ blockId: string;
27
+ scriptId: string;
28
+ }
29
+
30
+ export interface ScriptRelation {
31
+ kind: 'function' | 'message';
32
+ source: ScriptEndpoint;
33
+ destination?: ScriptEndpoint;
34
+ label: string;
35
+ wait: boolean;
36
+ unresolved?: 'dynamic' | 'missing' | 'ambiguous';
37
+ }
38
+
39
+ const namedPrefix = 'kubohiroyanamedfunctions_';
40
+
41
+ type Program = {target: RelationTarget; blocks: Record<string, RelationBlock>; endpoint(id: string): ScriptEndpoint | undefined};
42
+ type Definition = {endpoint: ScriptEndpoint; scope: 'global' | 'sprite'};
43
+
44
+ function program(target: RelationTarget): Program {
45
+ const blocks = target.blocks._blocks;
46
+ const roots = new Map<string, string | undefined>();
47
+ function endpoint(id: string): ScriptEndpoint | undefined {
48
+ const path = new Set<string>();
49
+ let current = id;
50
+ let root: string | undefined;
51
+ while (true) {
52
+ if (roots.has(current)) {
53
+ root = roots.get(current);
54
+ break;
55
+ }
56
+ if (path.has(current) || !blocks[current]) break;
57
+ path.add(current);
58
+ const parent = blocks[current].parent;
59
+ if (!parent) {
60
+ root = current;
61
+ break;
62
+ }
63
+ current = parent;
64
+ }
65
+ for (const member of path) roots.set(member, root);
66
+ return root ? {targetId: target.id, blockId: id, scriptId: root} : undefined;
67
+ }
68
+ return {target, blocks, endpoint};
69
+ }
70
+
71
+ /** Read the active literal only; an obscured menu/text shadow is never a possible destination. */
72
+ function inputLiteral(block: RelationBlock, blocks: Program['blocks'], name: string): string | undefined {
73
+ const input = block.inputs?.[name];
74
+ const value = input?.block ? blocks[input.block] : undefined;
75
+ if (!value) return undefined;
76
+ const field = value.opcode === 'text' ? value.fields?.TEXT :
77
+ value.opcode === 'event_broadcast_menu' ? value.fields?.BROADCAST_OPTION : undefined;
78
+ return field?.value === undefined || field.value === null ? undefined : String(field.value);
79
+ }
80
+
81
+ function append<K, V>(map: Map<K, V[]>, key: K, value: V) {
82
+ const entries = map.get(key);
83
+ if (entries) entries.push(value);
84
+ else map.set(key, [value]);
85
+ }
86
+
87
+ /**
88
+ * Extract possible static calls without executing the project or modifying its blocks.
89
+ * Broadcasts fan out; conflicting function definitions and computed names stay unresolved.
90
+ */
91
+ export function readScriptRelations(targets: readonly RelationTarget[]): ScriptRelation[] {
92
+ const seenTargets = new Set<string>();
93
+ const programs = targets.filter(target => {
94
+ if (target.isOriginal === false || seenTargets.has(target.id)) return false;
95
+ seenTargets.add(target.id);
96
+ return true;
97
+ }).map(program);
98
+ const procedures = new Map<string, Map<string, ScriptEndpoint[]>>();
99
+ const functions = new Map<string, Definition[]>();
100
+ const receivers = new Map<string, ScriptEndpoint[]>();
101
+
102
+ for (const {target, blocks, endpoint} of programs) {
103
+ const own = new Map<string, ScriptEndpoint[]>();
104
+ procedures.set(target.id, own);
105
+ for (const block of Object.values(blocks)) {
106
+ if (block.parent || block.topLevel === false || block.shadow) continue;
107
+ const destination = endpoint(block.id);
108
+ if (!destination) continue;
109
+ if (block.opcode === 'procedures_definition') {
110
+ const prototype = blocks[block.inputs?.custom_block?.block ?? ''];
111
+ const code = prototype?.opcode === 'procedures_prototype' ? prototype.mutation?.proccode : undefined;
112
+ if (typeof code === 'string') append(own, code, destination);
113
+ } else if (block.opcode === `${namedPrefix}defineFunction`) {
114
+ // A named definition's NAME is required to be literal, including its shadow connection.
115
+ const input = block.inputs?.NAME;
116
+ if (input?.block && input.block !== input.shadow) continue;
117
+ const name = inputLiteral(block, blocks, 'NAME')?.trim();
118
+ const scope = block.fields?.SCOPE?.value;
119
+ if (name && (scope === undefined || scope === null || scope === 'global' || scope === 'sprite')) {
120
+ append(functions, name, {endpoint: destination, scope: scope === 'sprite' ? 'sprite' : 'global'});
121
+ }
122
+ } else if (block.opcode === 'event_whenbroadcastreceived') {
123
+ const name = block.fields?.BROADCAST_OPTION?.value;
124
+ if (name !== undefined && name !== null) append(receivers, String(name).toUpperCase(), destination);
125
+ }
126
+ }
127
+ }
128
+
129
+ const relations: ScriptRelation[] = [];
130
+ for (const {target, blocks, endpoint} of programs) {
131
+ for (const block of Object.values(blocks)) {
132
+ let kind: ScriptRelation['kind'];
133
+ let name: string | undefined;
134
+ let wait = true;
135
+ let destinations: ScriptEndpoint[] = [];
136
+ let hasInput = true;
137
+ if (block.opcode === 'procedures_call') {
138
+ kind = 'function';
139
+ name = typeof block.mutation?.proccode === 'string' ? block.mutation.proccode : undefined;
140
+ destinations = procedures.get(target.id)?.get(name) ?? [];
141
+ hasInput = name !== undefined;
142
+ } else if (block.opcode === 'event_broadcast' || block.opcode === 'event_broadcastandwait') {
143
+ kind = 'message';
144
+ wait = block.opcode === 'event_broadcastandwait';
145
+ name = inputLiteral(block, blocks, 'BROADCAST_INPUT');
146
+ destinations = name === undefined ? [] : receivers.get(name.toUpperCase()) ?? [];
147
+ hasInput = Boolean(block.inputs?.BROADCAST_INPUT?.block);
148
+ } else if (block.opcode === `${namedPrefix}callFunction` || block.opcode === `${namedPrefix}startFunction` ||
149
+ block.opcode === `${namedPrefix}callFunctionFromMenu`) {
150
+ kind = 'function';
151
+ wait = block.opcode !== `${namedPrefix}startFunction`;
152
+ if (block.opcode === `${namedPrefix}callFunctionFromMenu`) {
153
+ const field = block.fields?.FUNCTION?.value;
154
+ name = field === undefined || field === null ? undefined : String(field);
155
+ hasInput = name !== undefined;
156
+ } else {
157
+ name = inputLiteral(block, blocks, 'NAME');
158
+ hasInput = Boolean(block.inputs?.NAME?.block);
159
+ }
160
+ name = name?.trim();
161
+ destinations = (functions.get(name) ?? []).filter(definition => definition.scope === 'global' ||
162
+ definition.endpoint.targetId === target.id).map(definition => definition.endpoint);
163
+ } else continue;
164
+ const source = endpoint(block.id);
165
+ if (!source || block.shadow) continue;
166
+ const relation = {kind, source, label: name ?? '', wait};
167
+ if (name === undefined) {
168
+ relations.push({...relation, unresolved: hasInput ? 'dynamic' : 'missing'});
169
+ } else if (!destinations.length) {
170
+ relations.push({...relation, unresolved: 'missing'});
171
+ } else if (kind === 'function' && destinations.length > 1) {
172
+ relations.push({...relation, unresolved: 'ambiguous'});
173
+ } else {
174
+ for (const destination of destinations) relations.push({...relation, destination});
175
+ }
176
+ }
177
+ }
178
+ return relations;
179
+ }
@@ -4,7 +4,7 @@ import type {createCodePaneAdapter} from './code-pane.ts';
4
4
  import {getCodeSession} from './workspace.ts';
5
5
 
6
6
  export {attachCodeWorkspace} from './workspace.ts';
7
- export {attachFunctionCallMenu, createCodePaneAdapter, createFunction, mountProcedureEditor, readHatScripts, readSavedCodePane} from './code-pane.ts';
7
+ export {attachFunctionCallMenu, createCodePaneAdapter, createFunction, mountProcedureEditor, readHatScripts, readSavedCodePane, readScriptRelationGraph} from './code-pane.ts';
8
8
  export type {SavedCodePane} from './code-pane.ts';
9
9
 
10
10
  export function CodePaneCostumeThumbnail({adapter}: {adapter: ReturnType<typeof createCodePaneAdapter>}) {
package/src/styles.css CHANGED
@@ -520,6 +520,151 @@
520
520
  pointer-events: none;
521
521
  }
522
522
 
523
+ :root {
524
+ --tw-script-function-stroke: light-dark(#7051c7, #c9abff);
525
+ --tw-script-message-stroke: light-dark(#a85a00, #ffbd66);
526
+ }
527
+
528
+ [data-script-relation="function"] {
529
+ --tw-script-relation-stroke: var(--tw-script-function-stroke);
530
+ --tw-script-relation-dash: none;
531
+ }
532
+
533
+ [data-script-relation="message"] {
534
+ --tw-script-relation-stroke: var(--tw-script-message-stroke);
535
+ --tw-script-relation-dash: 7 5;
536
+ }
537
+
538
+ [data-script-relation-layer] {
539
+ pointer-events: none;
540
+ }
541
+
542
+ .tw-script-relation-line, .tw-script-relation-head {
543
+ fill: none;
544
+ stroke: var(--tw-script-relation-stroke);
545
+ stroke-width: 1.8;
546
+ stroke-opacity: 0.75;
547
+ vector-effect: non-scaling-stroke;
548
+ pointer-events: none;
549
+ }
550
+
551
+ .tw-script-relation-line {
552
+ stroke-dasharray: var(--tw-script-relation-dash);
553
+ }
554
+
555
+ [data-script-relation][data-highlighted] :is(.tw-script-relation-line, .tw-script-relation-head) {
556
+ stroke-width: 3;
557
+ stroke-opacity: 1;
558
+ }
559
+
560
+ [data-script-dragging] > [data-script-relation]:not([data-highlighted]) :is(.tw-script-relation-line, .tw-script-relation-head) {
561
+ stroke-opacity: 0.2;
562
+ }
563
+
564
+ .tw-script-relation-script-highlight {
565
+ fill: light-dark(#3373cc, #93c5fd);
566
+ fill-opacity: 0.1;
567
+ stroke: light-dark(#2563a8, #93c5fd);
568
+ stroke-width: 2;
569
+ vector-effect: non-scaling-stroke;
570
+ pointer-events: none;
571
+ }
572
+
573
+ .tw-script-relation-script-highlight[data-emphasis="source"] {
574
+ stroke-width: 3;
575
+ fill-opacity: 0.15;
576
+ }
577
+
578
+ .tw-script-relation-destinations button[data-highlighted] {
579
+ font-weight: bold;
580
+ box-shadow: inset 3px 0 var(--tw-script-relation-stroke);
581
+ padding-inline-start: 6px;
582
+ }
583
+
584
+ .tw-script-relation-badge {
585
+ fill: var(--tw-script-relation-stroke);
586
+ stroke: var(--ui-primary, Canvas);
587
+ stroke-width: 3px;
588
+ paint-order: stroke;
589
+ font: 12px sans-serif;
590
+ pointer-events: none;
591
+ }
592
+
593
+ .tw-script-relation-wait {
594
+ pointer-events: visiblePainted;
595
+ }
596
+
597
+ .tw-script-relation-wait rect {
598
+ fill: var(--ui-primary, Canvas);
599
+ stroke: var(--tw-script-relation-stroke);
600
+ stroke-width: 1;
601
+ }
602
+
603
+ .tw-script-relation-wait .tw-script-relation-wait-glyph {
604
+ fill: none;
605
+ stroke: var(--tw-script-relation-stroke);
606
+ stroke-width: 1.4;
607
+ stroke-linecap: round;
608
+ stroke-linejoin: round;
609
+ }
610
+
611
+ .tw-script-relation-guide {
612
+ position: absolute;
613
+ z-index: 5;
614
+ inset-inline-end: 10px;
615
+ inset-block-start: 10px;
616
+ max-inline-size: min(240px, 45%);
617
+ padding: 2px 6px;
618
+ border: 1px solid var(--ui-black-transparent, #80808070);
619
+ border-radius: 6px;
620
+ background: var(--ui-primary, Canvas);
621
+ color: var(--text-primary, CanvasText);
622
+ font: 12px sans-serif;
623
+ pointer-events: none;
624
+ }
625
+
626
+ .tw-script-relation-guide[hidden] { display: none; }
627
+
628
+ .tw-script-relation-destinations [data-script-relation]::before {
629
+ content: "";
630
+ display: inline-block;
631
+ inline-size: 20px;
632
+ margin-inline-end: 5px;
633
+ vertical-align: middle;
634
+ border-block-start: 2px solid var(--tw-script-relation-stroke);
635
+ }
636
+
637
+ .tw-script-relation-destinations [data-script-relation="message"]::before {
638
+ border-block-start-style: dashed;
639
+ }
640
+
641
+ .tw-script-relation-destinations {
642
+ max-block-size: 9rem;
643
+ overflow: auto;
644
+ }
645
+
646
+ .tw-script-relation-destinations button {
647
+ display: block;
648
+ inline-size: 100%;
649
+ padding: 4px 0;
650
+ border: 0;
651
+ text-align: start;
652
+ background: transparent;
653
+ color: inherit;
654
+ cursor: pointer;
655
+ overflow-wrap: anywhere;
656
+ pointer-events: auto;
657
+ }
658
+
659
+ .tw-script-relation-destinations button:disabled { cursor: default; }
660
+
661
+ @media (forced-colors: active) {
662
+ :root {
663
+ --tw-script-function-stroke: CanvasText;
664
+ --tw-script-message-stroke: CanvasText;
665
+ }
666
+ }
667
+
523
668
  .tw-script-view-menu-arrow {
524
669
  display: inline-block;
525
670
  inline-size: 0.4em;
package/src/workspace.ts CHANGED
@@ -6,6 +6,8 @@ import {decodeEdit, encodeEdit, isCommentEdit} from './protocol.ts';
6
6
  import {captureCodePreviewChrome} from './preview-chrome.ts';
7
7
  import type {PresentationElements} from './preview-chrome.ts';
8
8
  import {attachScriptView, getDockedScriptLayout, type ScriptView} from './script-layout-view.ts';
9
+ import {attachScriptArrows, registerScriptRelationNavigation} from './script-arrows.ts';
10
+ import type {RelationBlock, ScriptEndpoint} from './script-relations.ts';
9
11
 
10
12
  export type AttachPreviewMinimap = (workspace, ScratchBlocks, watermark: HTMLElement) => {dispose(): void};
11
13
  /** Adds the code area's zoom buttons and minimap to another workspace. */
@@ -25,8 +27,8 @@ export interface Presentation {
25
27
  interface CodeSession {
26
28
  frontView: {target: object; mount: HTMLElement; presentation?: Presentation} | null;
27
29
  bridge: ReturnType<typeof attachCodeWorkspace> | null;
28
- subscribe(listener: () => void): () => void;
29
- changed(): void;
30
+ subscribe(listener: (navigation?: ScriptEndpoint) => void): () => void;
31
+ changed(navigation?: ScriptEndpoint): void;
30
32
  }
31
33
 
32
34
  const sessions = new WeakMap<object, CodeSession>();
@@ -34,7 +36,7 @@ const sessions = new WeakMap<object, CodeSession>();
34
36
  export function getCodeSession(vm: object) {
35
37
  let session = sessions.get(vm);
36
38
  if (!session) {
37
- const listeners = new Set<() => void>();
39
+ const listeners = new Set<(navigation?: ScriptEndpoint) => void>();
38
40
  session = {
39
41
  bridge: null,
40
42
  frontView: null,
@@ -42,8 +44,8 @@ export function getCodeSession(vm: object) {
42
44
  listeners.add(listener);
43
45
  return () => listeners.delete(listener);
44
46
  },
45
- changed() {
46
- for (const listener of listeners) listener();
47
+ changed(navigation) {
48
+ for (const listener of listeners) listener(navigation);
47
49
  }
48
50
  };
49
51
  sessions.set(vm, session);
@@ -595,6 +597,7 @@ export function attachCodeWorkspace({vm, ScratchBlocks: blocks, workspace, optio
595
597
  const minimap = attachMinimap?.(preview, blocks, watermark);
596
598
  const scriptView = attachScriptView({workspace: preview, ScratchBlocks: blocks, mount: chrome.parentElement,
597
599
  getLocale: () => locale ?? workspace.getInjectionDiv().ownerDocument.documentElement.lang,
600
+ relations: {vm, getTarget: () => target},
598
601
  initialView: view.scriptView ?? presentation?.scriptView,
599
602
  onChange: next => {
600
603
  if (presentation) presentation.scriptView = next;
@@ -680,6 +683,7 @@ export function attachCodeWorkspace({vm, ScratchBlocks: blocks, workspace, optio
680
683
  },
681
684
  dispose() {
682
685
  blockDrag.dispose();
686
+ unregisterRelationNavigation();
683
687
  unregisterCodeWorkspace();
684
688
  shown?.disconnect();
685
689
  visibility.dispose();
@@ -707,6 +711,19 @@ export function attachCodeWorkspace({vm, ScratchBlocks: blocks, workspace, optio
707
711
 
708
712
  const blockDrag = attachBlockDrag({vm, workspace, ScratchBlocks: blocks, onError, prepareImport: bridge.prepareImport});
709
713
  const visibility = attachScriptVisibility({vm, blocks, workspace, homeDocument, onError});
714
+ const unregisterRelationNavigation = registerScriptRelationNavigation(vm, endpoint => {
715
+ if (vm.runtime.getTargetById(endpoint.targetId)?.blocks._blocks[endpoint.blockId] === undefined) return;
716
+ if (vm.editingTarget?.id !== endpoint.targetId) vm.setEditingTarget(endpoint.targetId);
717
+ view.requestAnimationFrame(() => {
718
+ if (session.bridge !== bridge) return;
719
+ // Let a target switch restore that pane's mode first. Normal views keep showing all scripts.
720
+ if (visibility.focusedScript) {
721
+ visibility.focus(endpoint.scriptId);
722
+ session.changed(endpoint);
723
+ }
724
+ workspace.centerOnBlock(endpoint.scriptId);
725
+ });
726
+ });
710
727
  visibility.paint();
711
728
  session.bridge = bridge;
712
729
  vm.runtime.on('PROJECT_CHANGED', changed);
@@ -717,7 +734,7 @@ export function attachCodeWorkspace({vm, ScratchBlocks: blocks, workspace, optio
717
734
  type ProcedureTarget = CodeTarget & {
718
735
  id: string;
719
736
  blocks: CodeTarget['blocks'] & {
720
- _blocks: Record<string, {topLevel?: boolean; mutation?: Record<string, unknown>}>;
737
+ _blocks: Record<string, RelationBlock>;
721
738
  blockToXML(id: string, comments: CodeTarget['comments']): string;
722
739
  blocklyListen(event: object): void;
723
740
  };
@@ -994,6 +1011,8 @@ function attachProcedureEditor({vm, blocks, workspace, options, onError, homeDoc
994
1011
  };
995
1012
  document.addEventListener('pointerdown', releaseFocus, true);
996
1013
  vm.runtime.on('PROJECT_CHANGED', scheduleLoad);
1014
+ const relations = attachScriptArrows({workspace: editor, vm, getTarget: () => target,
1015
+ getLocale: () => locale});
997
1016
  load();
998
1017
 
999
1018
  // In a modal dialog the rest of the page is inert, including the text and dropdown editors
@@ -1011,6 +1030,7 @@ function attachProcedureEditor({vm, blocks, workspace, options, onError, homeDoc
1011
1030
  },
1012
1031
  dispose() {
1013
1032
  toolboxListeners.delete(refreshPalette);
1033
+ relations.dispose();
1014
1034
  navigation?.dispose();
1015
1035
  element.removeAttribute('data-code-hover-surface');
1016
1036
  element.removeAttribute('data-hover-palette');