@kubohiroya/turbowarp-plus-editor-code-views 0.0.0-stage → 0.2.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.
Files changed (108) hide show
  1. package/LICENSE +373 -0
  2. package/README.ja.md +42 -0
  3. package/README.md +41 -2
  4. package/dist/asset-edit-session.d.ts +24 -0
  5. package/dist/asset-edit-session.js +58 -0
  6. package/dist/block-argument-text.d.ts +39 -0
  7. package/dist/block-argument-text.js +170 -0
  8. package/dist/block-drag.d.ts +17 -0
  9. package/dist/block-drag.js +184 -0
  10. package/dist/code-extensions.d.ts +38 -0
  11. package/dist/code-extensions.js +418 -0
  12. package/dist/code-pane.d.ts +80 -0
  13. package/dist/code-pane.js +398 -0
  14. package/dist/custom-extension-fields.d.ts +45 -0
  15. package/dist/custom-extension-fields.js +144 -0
  16. package/dist/detached-block-palette-view.d.ts +10 -0
  17. package/dist/detached-block-palette-view.js +62 -0
  18. package/dist/detached-block-palette.d.ts +41 -0
  19. package/dist/detached-block-palette.js +197 -0
  20. package/dist/dockview-unsaved.d.ts +45 -0
  21. package/dist/dockview-unsaved.js +123 -0
  22. package/dist/history.d.ts +57 -0
  23. package/dist/history.js +85 -0
  24. package/dist/index.d.ts +28 -0
  25. package/dist/index.js +729 -0
  26. package/dist/native-extension-field.d.ts +26 -0
  27. package/dist/native-extension-field.js +204 -0
  28. package/dist/native-field-svg.d.ts +20 -0
  29. package/dist/native-field-svg.js +156 -0
  30. package/dist/palette-category-reorder.d.ts +4 -0
  31. package/dist/palette-category-reorder.js +167 -0
  32. package/dist/palette-category-search.d.ts +26 -0
  33. package/dist/palette-category-search.js +74 -0
  34. package/dist/palette-dropdown-resize.d.ts +19 -0
  35. package/dist/palette-dropdown-resize.js +135 -0
  36. package/dist/parent-field-layout.d.ts +2 -0
  37. package/dist/parent-field-layout.js +90 -0
  38. package/dist/parent-field-mirror.d.ts +3 -0
  39. package/dist/parent-field-mirror.js +290 -0
  40. package/dist/parent-field-resources.d.ts +9 -0
  41. package/dist/parent-field-resources.js +199 -0
  42. package/dist/preview-chrome.d.ts +9 -0
  43. package/dist/preview-chrome.js +78 -0
  44. package/dist/procedure-editor.d.ts +9 -0
  45. package/dist/procedure-editor.js +122 -0
  46. package/dist/procedure-edits.d.ts +16 -0
  47. package/dist/procedure-edits.js +47 -0
  48. package/dist/programmatic-extension-field.d.ts +20 -0
  49. package/dist/programmatic-extension-field.js +69 -0
  50. package/dist/protocol.d.ts +15 -0
  51. package/dist/protocol.js +36 -0
  52. package/dist/script-layout-dialog.d.ts +10 -0
  53. package/dist/script-layout-dialog.js +93 -0
  54. package/dist/script-layout-view.d.ts +68 -0
  55. package/dist/script-layout-view.js +164 -0
  56. package/dist/script-layout-workspace.d.ts +45 -0
  57. package/dist/script-layout-workspace.js +55 -0
  58. package/dist/script-layout.d.ts +17 -0
  59. package/dist/script-layout.js +25 -0
  60. package/dist/script-view-menu.d.ts +46 -0
  61. package/dist/script-view-menu.js +161 -0
  62. package/dist/sprite-code-windows.d.ts +32 -0
  63. package/dist/sprite-code-windows.js +180 -0
  64. package/dist/stage-code-prewarm.d.ts +52 -0
  65. package/dist/stage-code-prewarm.js +216 -0
  66. package/dist/target-combobox.d.ts +10 -0
  67. package/dist/target-combobox.js +92 -0
  68. package/dist/variable-references.d.ts +1 -0
  69. package/dist/variable-references.js +87 -0
  70. package/dist/workspace.d.ts +104 -0
  71. package/dist/workspace.js +1102 -0
  72. package/package.json +100 -4
  73. package/src/asset-edit-session.ts +72 -0
  74. package/src/block-argument-text.ts +172 -0
  75. package/src/block-drag.ts +190 -0
  76. package/src/code-extensions.ts +394 -0
  77. package/src/code-pane.ts +393 -0
  78. package/src/custom-extension-fields.ts +154 -0
  79. package/src/detached-block-palette-view.tsx +97 -0
  80. package/src/detached-block-palette.ts +218 -0
  81. package/src/dockview-unsaved.ts +134 -0
  82. package/src/history.ts +114 -0
  83. package/src/index.ts +680 -0
  84. package/src/native-extension-field.ts +201 -0
  85. package/src/native-field-svg.ts +140 -0
  86. package/src/palette-category-reorder.ts +155 -0
  87. package/src/palette-category-search.ts +82 -0
  88. package/src/palette-dropdown-resize.ts +132 -0
  89. package/src/parent-field-layout.ts +88 -0
  90. package/src/parent-field-mirror.ts +260 -0
  91. package/src/parent-field-resources.ts +179 -0
  92. package/src/preview-chrome.ts +82 -0
  93. package/src/procedure-editor.ts +123 -0
  94. package/src/procedure-edits.ts +46 -0
  95. package/src/programmatic-extension-field.ts +76 -0
  96. package/src/protocol.ts +47 -0
  97. package/src/script-layout-dialog.ts +104 -0
  98. package/src/script-layout-view.ts +198 -0
  99. package/src/script-layout-workspace.ts +95 -0
  100. package/src/script-layout.ts +40 -0
  101. package/src/script-view-menu.ts +213 -0
  102. package/src/sprite-code-windows.tsx +183 -0
  103. package/src/stage-code-prewarm.ts +242 -0
  104. package/src/styles.css +595 -0
  105. package/src/target-combobox.tsx +106 -0
  106. package/src/variable-references.ts +85 -0
  107. package/src/workspace.ts +1125 -0
  108. package/tsconfig.json +23 -0
@@ -0,0 +1,32 @@
1
+ import React from 'react';
2
+ import type { createCodePaneAdapter } from './code-pane.ts';
3
+ export { attachCodeWorkspace } from './workspace.ts';
4
+ export { attachFunctionCallMenu, createCodePaneAdapter, createFunction, mountProcedureEditor, readHatScripts, readSavedCodePane } from './code-pane.ts';
5
+ export type { SavedCodePane } from './code-pane.ts';
6
+ export declare function CodePaneCostumeThumbnail({ adapter }: {
7
+ adapter: ReturnType<typeof createCodePaneAdapter>;
8
+ }): React.JSX.Element;
9
+ export declare const SpriteCodeProvider: React.Provider<any>;
10
+ export declare const useSpriteCodeWindows: () => any;
11
+ export declare function useCodeWindows({ vm, host, locale, enabled }: {
12
+ vm: any;
13
+ host: any;
14
+ locale: any;
15
+ enabled: any;
16
+ }): {
17
+ front: any;
18
+ windows: any[];
19
+ context: {
20
+ selectedId: any;
21
+ openLabel: string;
22
+ select: (id: any, separate?: boolean) => void;
23
+ open: (id: any) => void;
24
+ };
25
+ openCurrent: () => void;
26
+ };
27
+ export declare function BackCodeWindows({ vm, windows, front, attachBackpackDrop }: {
28
+ vm: any;
29
+ windows: any;
30
+ front: any;
31
+ attachBackpackDrop: any;
32
+ }): any;
@@ -0,0 +1,180 @@
1
+ import React from 'react';
2
+ import { createPortal } from 'react-dom';
3
+ import { getCodeSession } from "./workspace.js";
4
+ export { attachCodeWorkspace } from "./workspace.js";
5
+ export { attachFunctionCallMenu, createCodePaneAdapter, createFunction, mountProcedureEditor, readHatScripts, readSavedCodePane } from "./code-pane.js";
6
+ export function CodePaneCostumeThumbnail({ adapter }) {
7
+ const image = React.useRef(null);
8
+ React.useLayoutEffect(() => adapter.watchEditingCostume(image.current), [adapter]);
9
+ return React.createElement("div", { "data-dockview-costume-thumbnail": "", "aria-hidden": "true" },
10
+ React.createElement("img", { ref: image, alt: "" }));
11
+ }
12
+ const SpriteCodeContext = React.createContext(null);
13
+ export const SpriteCodeProvider = SpriteCodeContext.Provider;
14
+ export const useSpriteCodeWindows = () => React.useContext(SpriteCodeContext);
15
+ export function useCodeWindows({ vm, host, locale, enabled }) {
16
+ const [state, setState] = React.useState({ windows: [], front: null });
17
+ const current = React.useRef(state);
18
+ const serial = React.useRef(0);
19
+ const mounted = React.useRef(false);
20
+ const japanese = /^ja(?:-|$)/i.test(locale);
21
+ const session = getCodeSession(vm);
22
+ const title = target => japanese ? `${target.getName()}のコード` : `Code · ${target.getName()}`;
23
+ function publish(windows, front) {
24
+ current.current = { windows, front };
25
+ session.frontView = front;
26
+ if (mounted.current)
27
+ setState(current.current);
28
+ }
29
+ function activated(view) {
30
+ const { windows, front } = current.current;
31
+ if (!windows.includes(view) || front === view && !view.minimized)
32
+ return;
33
+ if (!session.bridge?.select(view))
34
+ return;
35
+ view.minimized = false;
36
+ publish([...windows.filter(item => item !== view), view], view);
37
+ }
38
+ function remaining(view, remove) {
39
+ const { windows, front } = current.current;
40
+ const next = remove ? windows.filter(item => item !== view) : windows;
41
+ if (front !== view) {
42
+ publish(next, front);
43
+ return;
44
+ }
45
+ const fallback = next.findLast(item => !item.minimized);
46
+ publish(next, null);
47
+ fallback?.connection.activate();
48
+ }
49
+ function show(id, separate = false) {
50
+ const target = vm.runtime.getTargetById(id);
51
+ if (!target?.isOriginal || target.isStage || !session.bridge)
52
+ return;
53
+ const windows = current.current.windows;
54
+ const existing = !separate && windows.findLast(item => item.target === target);
55
+ if (existing) {
56
+ existing.connection.activate();
57
+ return;
58
+ }
59
+ const view = { target, id: `sprite-code-${++serial.current}`, mount: null, minimized: false, connection: null };
60
+ const connection = host.open({
61
+ id: view.id, title: title(target), closeLabel: japanese ? 'コード画面を閉じる' : 'Close code window',
62
+ onActivate: () => activated(view),
63
+ onDuplicate: () => show(view.target.id, true),
64
+ onMinimize() {
65
+ view.minimized = true;
66
+ remaining(view, false);
67
+ }
68
+ });
69
+ if (!connection)
70
+ return;
71
+ view.connection = connection;
72
+ connection.disconnected.addEventListener('abort', () => {
73
+ remaining(view, true);
74
+ connection.close();
75
+ }, { once: true });
76
+ publish([...windows, view], current.current.front);
77
+ activated(view);
78
+ void connection.ready.then(({ mount }) => {
79
+ if (!mounted.current || connection.disconnected.aborted)
80
+ return;
81
+ view.mount = mount;
82
+ publish(current.current.windows, current.current.front);
83
+ }, () => { });
84
+ }
85
+ React.useLayoutEffect(() => {
86
+ if (!enabled)
87
+ return;
88
+ mounted.current = true;
89
+ let queued = false;
90
+ const updateTargets = () => {
91
+ if (queued)
92
+ return;
93
+ queued = true;
94
+ queueMicrotask(() => {
95
+ queued = false;
96
+ if (!mounted.current)
97
+ return;
98
+ for (const view of current.current.windows) {
99
+ if (vm.runtime.getTargetById(view.target.id) !== view.target)
100
+ view.connection.close();
101
+ else
102
+ view.connection.setTitle(title(view.target));
103
+ }
104
+ const { windows, front } = current.current;
105
+ // Native stage and asset selection may give the docked editor control.
106
+ if (front && vm.editingTarget !== front.target)
107
+ publish(windows, null);
108
+ });
109
+ };
110
+ vm.on('targetsUpdate', updateTargets);
111
+ return () => {
112
+ mounted.current = false;
113
+ vm.removeListener('targetsUpdate', updateTargets);
114
+ const { windows } = current.current;
115
+ current.current = { windows: [], front: null };
116
+ session.frontView = null;
117
+ for (const view of windows)
118
+ view.connection.close();
119
+ };
120
+ }, [enabled, vm, host]);
121
+ return enabled ? {
122
+ front: state.front,
123
+ windows: state.windows,
124
+ context: {
125
+ selectedId: state.front?.target.id ?? '',
126
+ openLabel: japanese ? '開く' : 'Open',
127
+ select: show,
128
+ open: id => show(id, true)
129
+ },
130
+ openCurrent: () => show(vm.editingTarget?.id)
131
+ } : null;
132
+ }
133
+ function Preview({ vm, view, attachBackpackDrop }) {
134
+ const { target } = view;
135
+ const drop = React.useRef(null);
136
+ const ref = React.useRef(null);
137
+ const chrome = React.useRef(null);
138
+ React.useLayoutEffect(() => {
139
+ const session = getCodeSession(vm);
140
+ let bridge;
141
+ let preview;
142
+ let dropBinding;
143
+ const update = () => {
144
+ if (bridge !== session.bridge) {
145
+ dropBinding?.dispose();
146
+ preview?.dispose();
147
+ bridge = session.bridge;
148
+ preview = bridge?.preview(ref.current, chrome.current, { ...view, dropElement: drop.current });
149
+ if (preview) {
150
+ const boundBridge = bridge;
151
+ const canCommit = () => session.bridge === boundBridge && !view.connection.disconnected.aborted;
152
+ let record;
153
+ dropBinding = attachBackpackDrop({
154
+ vm, workspace: preview.workspace, dropElement: drop.current,
155
+ canUse: canCommit, onError: bridge.onError,
156
+ destination: {
157
+ target, canCommit,
158
+ beforeCommit: () => { record = boundBridge.prepareImport(target); },
159
+ onCommitted: receipt => record(receipt)
160
+ }
161
+ });
162
+ }
163
+ }
164
+ preview?.update();
165
+ };
166
+ const unsubscribe = session.subscribe(update);
167
+ update();
168
+ return () => {
169
+ unsubscribe();
170
+ dropBinding?.dispose();
171
+ preview?.dispose();
172
+ };
173
+ }, [vm, view, target, attachBackpackDrop]);
174
+ return React.createElement("div", { ref: drop, "data-code-preview": "", "data-code-hover-surface": "" },
175
+ React.createElement("div", { ref: ref, inert: '' }),
176
+ React.createElement("div", { ref: chrome, className: "tw-code-preview-chrome", inert: '' }));
177
+ }
178
+ export function BackCodeWindows({ vm, windows, front, attachBackpackDrop }) {
179
+ return windows.filter(view => view !== front && !view.minimized && view.mount).map(view => createPortal(React.createElement(Preview, { vm: vm, view: view, attachBackpackDrop: attachBackpackDrop }), view.mount, view.id));
180
+ }
@@ -0,0 +1,52 @@
1
+ import { type CodeTarget } from './history.ts';
2
+ interface Events {
3
+ on(event: string, listener: () => void): void;
4
+ removeListener(event: string, listener: () => void): void;
5
+ }
6
+ interface Workspace {
7
+ options: {
8
+ RTL: boolean;
9
+ colours: object;
10
+ pathToMedia: string;
11
+ };
12
+ scale: number;
13
+ isDragging(): boolean;
14
+ setResizesEnabled(enabled: boolean): void;
15
+ dispose(): void;
16
+ }
17
+ interface ScratchBlocks {
18
+ mainWorkspace: Workspace;
19
+ getMainWorkspace(): Workspace;
20
+ inject(container: HTMLElement, options: object): Workspace;
21
+ Events: {
22
+ disable(): void;
23
+ enable(): void;
24
+ };
25
+ Field: {
26
+ stopCache(): void;
27
+ };
28
+ Xml: {
29
+ textToDom(xml: string): Element;
30
+ domToWorkspace(xml: Element, workspace: Workspace): void;
31
+ domToBlock(xml: Element, workspace: Workspace): {
32
+ dispose(healStack: boolean, animate: boolean): void;
33
+ };
34
+ };
35
+ }
36
+ interface Context {
37
+ vm: Events & {
38
+ runtime: Events & {
39
+ getTargetForStage(): CodeTarget | null;
40
+ };
41
+ editingTarget: CodeTarget | null;
42
+ };
43
+ ScratchBlocks: ScratchBlocks;
44
+ workspace: Workspace;
45
+ document: Document;
46
+ canUse(): boolean;
47
+ onError(error: unknown): void;
48
+ }
49
+ export declare function attachStageCodePrewarm(context: Context): {
50
+ dispose(): void;
51
+ };
52
+ export {};
@@ -0,0 +1,216 @@
1
+ import { workspaceXML } from "./history.js";
2
+ const quietPeriod = 250;
3
+ const sliceBudget = 5;
4
+ const longSlice = 50;
5
+ const minimumBlocks = 100;
6
+ const maximumXmlLength = 1_000_000;
7
+ const inputEvents = ['pointerdown', 'pointerup', 'pointermove', 'pointercancel', 'wheel', 'keydown', 'input'];
8
+ function* drawStage({ vm, ScratchBlocks: blocks, workspace, document }, stage) {
9
+ const xml = workspaceXML(vm, stage);
10
+ if (xml.length > maximumXmlLength)
11
+ return;
12
+ const dom = blocks.Xml.textToDom(xml);
13
+ const elements = dom.querySelectorAll('block, shadow');
14
+ if (elements.length < minimumBlocks)
15
+ return;
16
+ yield;
17
+ const container = document.createElement('div');
18
+ container.dataset.twPlusStageCodePrewarm = '';
19
+ container.setAttribute('aria-hidden', 'true');
20
+ container.inert = true;
21
+ container.style.cssText = 'position:fixed;left:-20000px;top:0;width:1000px;height:700px;visibility:hidden;pointer-events:none';
22
+ document.body.append(container);
23
+ let preview;
24
+ try {
25
+ try {
26
+ preview = blocks.inject(container, {
27
+ readOnly: true, scrollbars: false, sounds: false, media: workspace.options.pathToMedia,
28
+ rtl: workspace.options.RTL, colours: workspace.options.colours, zoom: { startScale: workspace.scale }
29
+ });
30
+ }
31
+ finally {
32
+ // Injection changes Blockly's main workspace. Restore it without moving browser focus.
33
+ blocks.mainWorkspace = workspace;
34
+ }
35
+ // The live workspace already holds a reference to Blockly's field width cache.
36
+ blocks.Field.stopCache();
37
+ const variables = dom.querySelector('variables');
38
+ if (variables) {
39
+ const declarations = dom.cloneNode(false);
40
+ declarations.append(variables.cloneNode(true));
41
+ blocks.Xml.domToWorkspace(declarations, preview);
42
+ }
43
+ preview.setResizesEnabled(false);
44
+ yield;
45
+ const drawn = new Set();
46
+ for (const element of elements) {
47
+ // Document pickers can enumerate and validate provider metadata during field setup.
48
+ // Let the foreground editor initialize them when the user opens the stage.
49
+ if (Array.from(element.children).some(child => child.localName === 'field' && child.getAttribute('name') === 'DOCUMENT')) {
50
+ yield;
51
+ continue;
52
+ }
53
+ // A whole connected script can exceed the slice budget. Draw one block's fields and
54
+ // mutation without its children so the renderer can reuse its normal field resources.
55
+ const block = element.cloneNode(false);
56
+ block.removeAttribute('id');
57
+ block.removeAttribute('x');
58
+ block.removeAttribute('y');
59
+ for (const child of element.children) {
60
+ if (child.localName === 'field' || child.localName === 'mutation')
61
+ block.append(child.cloneNode(true));
62
+ }
63
+ const shape = block.outerHTML;
64
+ if (!drawn.has(shape)) {
65
+ blocks.Xml.domToBlock(block, preview).dispose(false, false);
66
+ drawn.add(shape);
67
+ }
68
+ yield;
69
+ }
70
+ }
71
+ finally {
72
+ try {
73
+ preview?.dispose();
74
+ }
75
+ finally {
76
+ container.remove();
77
+ }
78
+ }
79
+ }
80
+ export function attachStageCodePrewarm(context) {
81
+ const { vm, ScratchBlocks: blocks, workspace, document, canUse, onError } = context;
82
+ const host = document.defaultView;
83
+ let job;
84
+ let cancelScheduled;
85
+ let running = false;
86
+ let lastInput = 0;
87
+ const withoutEvents = (action) => {
88
+ blocks.Events.disable();
89
+ try {
90
+ action();
91
+ }
92
+ finally {
93
+ blocks.Events.enable();
94
+ }
95
+ };
96
+ const unschedule = () => {
97
+ cancelScheduled?.();
98
+ cancelScheduled = undefined;
99
+ };
100
+ const close = (drawing) => {
101
+ try {
102
+ withoutEvents(() => drawing.return(undefined));
103
+ }
104
+ catch (error) {
105
+ onError(error);
106
+ }
107
+ };
108
+ const cancel = () => {
109
+ unschedule();
110
+ const previous = job;
111
+ job = undefined;
112
+ if (previous && !running)
113
+ close(previous.drawing);
114
+ };
115
+ const usable = () => !document.hidden && canUse() && !workspace.isDragging() &&
116
+ blocks.getMainWorkspace() === workspace;
117
+ const quietRemaining = () => quietPeriod - (host.performance.now() - lastInput);
118
+ function schedule() {
119
+ if (!job || cancelScheduled)
120
+ return;
121
+ const remainingQuiet = quietRemaining();
122
+ if (remainingQuiet > 0 || !usable()) {
123
+ const timer = host.setTimeout(() => {
124
+ cancelScheduled = undefined;
125
+ schedule();
126
+ }, remainingQuiet > 0 ? Math.ceil(remainingQuiet) : quietPeriod);
127
+ cancelScheduled = () => host.clearTimeout(timer);
128
+ return;
129
+ }
130
+ const draw = (deadline) => {
131
+ cancelScheduled = undefined;
132
+ const current = job;
133
+ if (!current || vm.runtime.getTargetForStage() !== current.stage || vm.editingTarget === current.stage) {
134
+ cancel();
135
+ return;
136
+ }
137
+ if (quietRemaining() > 0 || !usable()) {
138
+ schedule();
139
+ return;
140
+ }
141
+ const started = host.performance.now();
142
+ const stopAt = started + sliceBudget;
143
+ running = true;
144
+ try {
145
+ withoutEvents(() => {
146
+ while (job === current && host.performance.now() < stopAt && (!deadline || deadline.timeRemaining() > 1)) {
147
+ if (!current.drawing.next().done)
148
+ continue;
149
+ if (job === current)
150
+ job = undefined;
151
+ break;
152
+ }
153
+ });
154
+ // A single synchronous block constructor can overrun the budget. Avoid repeating it.
155
+ if (job === current && host.performance.now() - started >= longSlice)
156
+ cancel();
157
+ }
158
+ catch (error) {
159
+ if (job === current)
160
+ cancel();
161
+ onError(error);
162
+ }
163
+ finally {
164
+ running = false;
165
+ if (job !== current)
166
+ close(current.drawing);
167
+ }
168
+ schedule();
169
+ };
170
+ if (host.requestIdleCallback) {
171
+ const idle = host.requestIdleCallback(draw);
172
+ cancelScheduled = () => host.cancelIdleCallback(idle);
173
+ }
174
+ else {
175
+ const timer = host.setTimeout(draw, 16);
176
+ cancelScheduled = () => host.clearTimeout(timer);
177
+ }
178
+ }
179
+ const input = () => {
180
+ if (!job)
181
+ return;
182
+ lastInput = host.performance.now();
183
+ schedule();
184
+ };
185
+ const loaded = () => {
186
+ cancel();
187
+ const stage = vm.runtime.getTargetForStage();
188
+ if (!stage || vm.editingTarget === stage)
189
+ return;
190
+ lastInput = host.performance.now();
191
+ job = { stage, drawing: drawStage(context, stage) };
192
+ schedule();
193
+ };
194
+ const targetsUpdated = () => {
195
+ if (job && vm.editingTarget === job.stage)
196
+ cancel();
197
+ };
198
+ vm.runtime.on('PROJECT_LOADED', loaded);
199
+ vm.runtime.on('RUNTIME_DISPOSED', cancel);
200
+ vm.on('PROJECT_CHANGED', cancel);
201
+ vm.on('PROJECT_RUN_START', cancel);
202
+ vm.on('targetsUpdate', targetsUpdated);
203
+ for (const event of inputEvents)
204
+ document.addEventListener(event, input, { capture: true, passive: true });
205
+ loaded();
206
+ return { dispose() {
207
+ cancel();
208
+ vm.runtime.removeListener('PROJECT_LOADED', loaded);
209
+ vm.runtime.removeListener('RUNTIME_DISPOSED', cancel);
210
+ vm.removeListener('PROJECT_CHANGED', cancel);
211
+ vm.removeListener('PROJECT_RUN_START', cancel);
212
+ vm.removeListener('targetsUpdate', targetsUpdated);
213
+ for (const event of inputEvents)
214
+ document.removeEventListener(event, input, true);
215
+ } };
216
+ }
@@ -0,0 +1,10 @@
1
+ import React from 'react';
2
+ export declare function TargetCombobox({ id, targets, value, onSelect, onRename, disabled, locale }: {
3
+ id: any;
4
+ targets: any;
5
+ value: any;
6
+ onSelect: any;
7
+ onRename: any;
8
+ disabled: any;
9
+ locale: any;
10
+ }): React.JSX.Element;
@@ -0,0 +1,92 @@
1
+ import React, { useEffect, useRef, useState } from 'react';
2
+ function Thumbnail({ target }) {
3
+ return target?.thumbnailUrl ?
4
+ React.createElement("img", { className: "tw-target-combobox__thumbnail", src: target.thumbnailUrl, alt: "" }) :
5
+ React.createElement("span", { className: "tw-target-combobox__thumbnail", "aria-hidden": "true" });
6
+ }
7
+ export function TargetCombobox({ id, targets, value, onSelect, onRename, disabled, locale }) {
8
+ const japanese = /^ja(?:-|$)/i.test(locale);
9
+ const label = japanese ? '編集対象' : 'Editing target';
10
+ const optionsLabel = japanese ? '編集対象の候補' : 'Editing target options';
11
+ const selected = targets.find(target => target.id === value);
12
+ const [popup, setPopup] = useState(null);
13
+ const [draft, setDraft] = useState(null);
14
+ const input = useRef(null);
15
+ const canRename = selected && !selected.isStage;
16
+ const open = !disabled && popup !== null && popup.value === value && targets.length > 0;
17
+ const listId = `${id}-options`;
18
+ const optionId = index => `${listId}-${index}`;
19
+ const highlight = open ? targets.findIndex(target => target.id === popup.highlighted) : -1;
20
+ const show = () => setPopup({ value, highlighted: selected?.id ?? targets[0]?.id });
21
+ useEffect(() => {
22
+ if (disabled) {
23
+ setPopup(null);
24
+ setDraft(null);
25
+ }
26
+ }, [disabled]);
27
+ function choose(target) {
28
+ setPopup(null);
29
+ setDraft(null);
30
+ onSelect(target.id);
31
+ }
32
+ function commitName() {
33
+ const name = draft?.id === value ? draft.name.trim() : '';
34
+ setDraft(null);
35
+ if (!disabled && canRename && name && name !== selected.name)
36
+ onRename(name);
37
+ }
38
+ function keyDown(event) {
39
+ if (event.nativeEvent.isComposing)
40
+ return;
41
+ const { key } = event;
42
+ if (key === 'Escape' && (open || draft)) {
43
+ event.preventDefault();
44
+ if (open)
45
+ setPopup(null);
46
+ else
47
+ setDraft(null);
48
+ }
49
+ else if (key === 'Enter') {
50
+ event.preventDefault();
51
+ if (open && highlight >= 0)
52
+ choose(targets[highlight]);
53
+ else
54
+ commitName();
55
+ }
56
+ else if (key === 'ArrowDown' || key === 'ArrowUp') {
57
+ event.preventDefault();
58
+ if (!open) {
59
+ show();
60
+ return;
61
+ }
62
+ const next = Math.min(targets.length - 1, Math.max(0, highlight + (key === 'ArrowDown' ? 1 : -1)));
63
+ setPopup({ value, highlighted: targets[next].id });
64
+ event.currentTarget.ownerDocument.getElementById(optionId(next))?.scrollIntoView({ block: 'nearest' });
65
+ }
66
+ }
67
+ return (React.createElement("div", { className: "tw-target-combobox", onBlur: event => {
68
+ if (event.currentTarget.contains(event.relatedTarget))
69
+ return;
70
+ setPopup(null);
71
+ if (event.currentTarget.ownerDocument.hasFocus())
72
+ commitName();
73
+ } },
74
+ React.createElement("div", { className: "tw-target-combobox__field" },
75
+ React.createElement(Thumbnail, { target: selected }),
76
+ React.createElement("input", { "aria-activedescendant": open && highlight >= 0 ? optionId(highlight) : undefined, "aria-controls": open ? listId : undefined, "aria-expanded": open, "aria-label": label, "aria-autocomplete": "none", autoComplete: "off", id: id, disabled: disabled || !targets.length, onChange: event => {
77
+ setPopup(null);
78
+ setDraft({ id: value, name: event.currentTarget.value });
79
+ }, onKeyDown: keyDown, readOnly: !canRename, ref: input, role: "combobox", type: "text", value: draft?.id === value ? draft.name : selected?.name ?? '' }),
80
+ React.createElement("button", { "aria-label": optionsLabel, "aria-expanded": open, disabled: disabled || !targets.length, onPointerDown: event => event.preventDefault(), onClick: () => {
81
+ if (open)
82
+ setPopup(null);
83
+ else
84
+ show();
85
+ input.current?.focus();
86
+ }, tabIndex: -1, type: "button" },
87
+ React.createElement("svg", { "aria-hidden": "true", width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round" },
88
+ React.createElement("path", { d: "m4 6 4 4 4-4" })))),
89
+ open && React.createElement("ul", { "aria-label": label, className: "tw-target-combobox__options", id: listId, role: "listbox" }, targets.map((target, index) => (React.createElement("li", { "aria-selected": target.id === value, className: index === highlight ? 'tw-target-combobox__highlight' : undefined, id: optionId(index), key: target.id, onClick: () => choose(target), onPointerDown: event => event.preventDefault(), role: "option" },
90
+ React.createElement(Thumbnail, { target: target }),
91
+ React.createElement("span", null, target.name)))))));
92
+ }
@@ -0,0 +1 @@
1
+ export declare function installScopedVariableReferences(blocks: any, workspace: any, getLocale: () => string): void;
@@ -0,0 +1,87 @@
1
+ // ScratchBlocks normally coalesces variables by name and type. The VM's
2
+ // projection can contain two variables or lists with the same name and different scopes.
3
+ export function installScopedVariableReferences(blocks, workspace, getLocale) {
4
+ const scopedType = type => type === '' || type === blocks.LIST_VARIABLE_TYPE;
5
+ const map = workspace.getVariableMap();
6
+ const createVariable = map.createVariable;
7
+ const getVariable = map.getVariable;
8
+ map.createVariable = function (name, type, id, isLocal, isCloud) {
9
+ const existing = id && scopedType(type) && typeof isLocal === 'boolean' && getVariable.call(this, name, type);
10
+ if (!existing)
11
+ return createVariable.call(this, name, type, id, isLocal, isCloud);
12
+ const byId = this.getVariableById(id);
13
+ if (byId)
14
+ return byId;
15
+ // Preserve the normal model creation and events, but match the name
16
+ // only within the incoming scope for this synchronous insertion.
17
+ const sameScope = this.getVariablesOfType(type)
18
+ .find(variable => variable.name === name && variable.isLocal === isLocal);
19
+ this.getVariable = () => sameScope;
20
+ try {
21
+ return createVariable.call(this, name, type, id, isLocal, isCloud);
22
+ }
23
+ finally {
24
+ this.getVariable = getVariable;
25
+ }
26
+ };
27
+ const scopedLabel = (variable, variables) => {
28
+ if (!variables.some(other => other.name === variable.name && other.isLocal !== variable.isLocal)) {
29
+ return variable.name;
30
+ }
31
+ const ja = /^ja(?:-|$)/i.test(getLocale());
32
+ const scope = variable.isLocal ? (ja ? 'このスプライト' : 'Local') : (ja ? '全体' : 'Global');
33
+ return `${scope}: ${variable.name}`;
34
+ };
35
+ const inWorkspace = field => field.sourceBlock_?.workspace === workspace;
36
+ for (const field of [blocks.FieldVariable.prototype, blocks.FieldVariableGetter.prototype]) {
37
+ const setText = field.setText;
38
+ field.setText = function (text) {
39
+ const variable = this.getVariable();
40
+ const label = inWorkspace(this) && variable && scopedType(variable.type) && text === variable.name ?
41
+ scopedLabel(variable, workspace.getVariablesOfType(variable.type)) : text;
42
+ return setText.call(this, label);
43
+ };
44
+ }
45
+ const getOptions = blocks.FieldVariable.prototype.getOptions;
46
+ blocks.FieldVariable.prototype.getOptions = function () {
47
+ const options = getOptions.call(this);
48
+ const type = this.getVariable()?.type;
49
+ if (!inWorkspace(this) || !scopedType(type))
50
+ return options;
51
+ const variables = workspace.getVariablesOfType(type);
52
+ const byId = new Map(variables.map(variable => [variable.getId(), variable]));
53
+ return options.map(option => {
54
+ const variable = byId.get(option[1]);
55
+ return variable ? [scopedLabel(variable, variables), option[1]] : option;
56
+ });
57
+ };
58
+ for (const [opcode, fieldName, type] of [
59
+ ['data_variable', 'VARIABLE', ''],
60
+ ['data_listcontents', 'LIST', blocks.LIST_VARIABLE_TYPE]
61
+ ]) {
62
+ const reporter = blocks.Blocks[opcode];
63
+ const init = reporter.init;
64
+ reporter.init = function () {
65
+ init.call(this);
66
+ if (this.workspace !== workspace || this.isInFlyout)
67
+ return;
68
+ this.customContextMenu = options => {
69
+ if (this.isCollapsed())
70
+ return;
71
+ const field = this.getField(fieldName);
72
+ const variables = workspace.getVariablesOfType(type);
73
+ for (const variable of variables.sort((a, b) => a.name.localeCompare(b.name))) {
74
+ const id = variable.getId();
75
+ if (id !== field.getValue()) {
76
+ options.push({
77
+ text: scopedLabel(variable, variables),
78
+ twPlusMenuIcon: 'switch',
79
+ enabled: true,
80
+ callback: () => field.setValue(id)
81
+ });
82
+ }
83
+ }
84
+ };
85
+ };
86
+ }
87
+ }