@kubohiroya/turbowarp-plus-editor-workbench 0.26.0 → 0.27.1

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 (49) hide show
  1. package/EDITOR-MIGRATION.md +5 -0
  2. package/README.ja.md +7 -0
  3. package/dist/basic-panel.d.ts +52 -0
  4. package/dist/basic-panel.js +153 -0
  5. package/dist/editor-tabs.d.ts +37 -0
  6. package/dist/editor-tabs.js +538 -0
  7. package/dist/popup-layout.d.ts +20 -0
  8. package/dist/popup-layout.js +59 -0
  9. package/dist/project-folder-workflows.d.ts +31 -0
  10. package/dist/project-folder-workflows.js +1 -0
  11. package/dist/project-payload-forms.d.ts +8 -0
  12. package/dist/project-payload-forms.js +184 -0
  13. package/dist/project-tools/diagnostics.d.ts +13 -0
  14. package/dist/project-tools/diagnostics.js +65 -0
  15. package/dist/project-tools/dialog.d.ts +21 -0
  16. package/dist/project-tools/dialog.js +363 -0
  17. package/dist/project-tools/history.d.ts +8 -0
  18. package/dist/project-tools/history.js +22 -0
  19. package/dist/project-tools/integration.d.ts +65 -0
  20. package/dist/project-tools/integration.js +356 -0
  21. package/dist/project-tools/links.d.ts +3 -0
  22. package/dist/project-tools/links.js +36 -0
  23. package/dist/project-tools/properties.d.ts +51 -0
  24. package/dist/project-tools/properties.js +268 -0
  25. package/dist/sprite-tabs.d.ts +7 -1
  26. package/dist/sprite-tabs.js +11 -1
  27. package/dist/stage-display-menu.d.ts +21 -0
  28. package/dist/stage-display-menu.js +156 -0
  29. package/dist/stage-panel.d.ts +29 -0
  30. package/dist/stage-panel.js +105 -0
  31. package/package.json +78 -9
  32. package/src/basic-panel.tsx +207 -0
  33. package/src/editor-tabs.tsx +580 -0
  34. package/src/popup-layout.css +4 -0
  35. package/src/popup-layout.tsx +81 -0
  36. package/src/project-dialog.css +39 -0
  37. package/src/project-folder-workflows.ts +32 -0
  38. package/src/project-payload-forms.ts +179 -0
  39. package/src/project-snackbar.css +85 -0
  40. package/src/project-tools/diagnostics.ts +51 -0
  41. package/src/project-tools/dialog.ts +341 -0
  42. package/src/project-tools/history.ts +20 -0
  43. package/src/project-tools/integration.ts +366 -0
  44. package/src/project-tools/links.ts +31 -0
  45. package/src/project-tools/properties.ts +251 -0
  46. package/src/sprite-tabs.ts +17 -1
  47. package/src/stage-display-menu.css +28 -0
  48. package/src/stage-display-menu.tsx +177 -0
  49. package/src/stage-panel.tsx +127 -0
@@ -0,0 +1,580 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ import React from 'react';
3
+ import {createAssetTransferPanel, type ProjectAssetTransferPort} from '@kubohiroya/turbowarp-script-transfer';
4
+ import {createSurface} from '@kubohiroya/turbowarp-plus-editor-windows/surfaces';
5
+ import {DockablePanel, OpenWindowButton, useWindowHost} from '@kubohiroya/turbowarp-plus-editor-windows';
6
+ import {SpriteTargetTabsContext, useSpriteTabs} from './sprite-tabs.js';
7
+ import {editSpriteVariable, readSpriteVariable, showSpriteVariableOnStage, writeSpriteVariableValue} from '@kubohiroya/turbowarp-plus-editor-project-model/sprite-variable-edit';
8
+ import {SpriteEditorToolbar, spriteEditorSections} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-editor-toolbar';
9
+ import {editClonedSpriteVariable, SpriteCloneInspector, SpriteClonePagination, SpriteCloneVariables}
10
+ from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-clone-inspector';
11
+ import {centerProjectComment} from './project-search-box.js';
12
+ import {activateTargetView, connectProjectSearchNavigation, openVariableSearch,
13
+ type SearchNavigation} from '@kubohiroya/turbowarp-plus-editor-project-model/project-search-connections';
14
+ import {countVariableAccesses} from '@kubohiroya/turbowarp-plus-editor-project-model/project-search';
15
+ import {renameProjectMessage} from '@kubohiroya/turbowarp-plus-editor-project-model/project-search-replace';
16
+ import {scanTargetMessages} from '@kubohiroya/turbowarp-plus-editor-project-model/project-messages';
17
+ import type {SpriteVariable} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-asset-pane';
18
+ import {readTemporaryVariables, watchTemporaryVariables} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/temporary-variables';
19
+ import {createBlockImageRenderer} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/block-image';
20
+ import {describeScriptStart} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/script-start';
21
+ import type {MessagePaneData} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-message-pane';
22
+ import {readTargetFunctions} from '@kubohiroya/turbowarp-plus-editor-sprite-panes/sprite-function-pane';
23
+ import type {SpriteAssetKind, SpriteAssetPreviewData, SpriteAssetSelection} from './sprite-tabs.js';
24
+ import type {WorkspaceProjectIdentity} from './sprite-tabs.js';
25
+ import {parseExtensionCatalog} from '@kubohiroya/turbowarp-extension-security-dialog';
26
+ import {attachFunctionCallMenu, BackCodeWindows, CodePaneCostumeThumbnail, createCodePaneAdapter, createFunction, mountProcedureEditor, readHatScripts, readScriptRelationGraph, SpriteCodeProvider, useCodeWindows} from '@kubohiroya/turbowarp-plus-editor-code-views/sprite-code-windows';
27
+ export interface EditorTabPorts {
28
+ WindowLayoutContext: React.Context<any>; StageDisplayMenuContext: React.Context<any>; TargetSwitchContext: React.Context<any>;
29
+ desktopCodeEnabled: any;
30
+ openDesktopCode: any;
31
+ styles: any;
32
+ desktopProjectKey: any;
33
+ desktopWorkspaceLayoutStore: any;
34
+ dockviewMultiViewEnabled: any;
35
+ dockviewSpriteTabsEnabled: any;
36
+ layoutFlags: any;
37
+ isProjectLoading: any;
38
+ loadedProjectTitle: any;
39
+ projectScreenState: any;
40
+ subscribeProjectLoad: any;
41
+ projectFolderDirectory: any;
42
+ openDetachedBlockPalette: any;
43
+ categoryArtwork: any;
44
+ decorateSurface: any;
45
+ plusCatalog: any;
46
+ loadPlusExtensions: any;
47
+ beginPlusReview: any;
48
+ canLoadPlusExtension: any;
49
+ attachBackpackDrop: any;
50
+ attachCodePreviewMinimap: any;
51
+ attachCodeNavigation: any;
52
+ getScratchBlocks: any;
53
+ assetTransferPort: any;
54
+ readOpenedFile: any;
55
+ popupURL: any;
56
+ connectEditorTabs: any;
57
+ }
58
+ export function createEditorTabLayout({desktopCodeEnabled, openDesktopCode, styles, desktopProjectKey, desktopWorkspaceLayoutStore, dockviewMultiViewEnabled, dockviewSpriteTabsEnabled, layoutFlags, WindowLayoutContext, isProjectLoading, loadedProjectTitle, projectScreenState, subscribeProjectLoad, projectFolderDirectory, StageDisplayMenuContext, TargetSwitchContext, openDetachedBlockPalette, categoryArtwork, decorateSurface, plusCatalog, loadPlusExtensions, beginPlusReview, canLoadPlusExtension, attachBackpackDrop, attachCodePreviewMinimap, attachCodeNavigation, getScratchBlocks, assetTransferPort, readOpenedFile, popupURL, connectEditorTabs}: EditorTabPorts) {
59
+ const codeTab = 0;
60
+
61
+ /**
62
+ * Add named-functions from this distribution's catalog, dependencies first. A listed URL is what this
63
+ * distribution trusts, so it loads unsandboxed as it does from the extension library. The mode has to
64
+ * be given through the same review bookkeeping: the GUI's own `getSandboxMode` sandboxes any URL it
65
+ * is not told about, and named-functions refuses to run sandboxed.
66
+ */
67
+ async function loadNamedFunctions(vm) {
68
+ const {catalog} = await plusCatalog.read(AbortSignal.timeout(15000));
69
+ const entries = new Map(parseExtensionCatalog(catalog).map(entry => [entry.id, entry]));
70
+ const order = [];
71
+ const visit = id => {
72
+ const entry = entries.get(id);
73
+ if (!entry || order.includes(entry)) return;
74
+ entry.dependencies.forEach(visit);
75
+ order.push(entry);
76
+ };
77
+ visit('kubohiroyanamedfunctions');
78
+ await loadPlusExtensions(vm, order, new Map(order.map(entry => [entry.url, 'unsandboxed'])),
79
+ {beginReview: beginPlusReview, canLoad: canLoadPlusExtension});
80
+ }
81
+ const soundsTab = 2;
82
+ const categoryIcons = {
83
+ motion: categoryArtwork['icons/motion_icon.svg'],
84
+ looks: categoryArtwork['icons/looks_icon.svg'],
85
+ sound: categoryArtwork['icons/sound_icon.svg'],
86
+ events: categoryArtwork['icons/events_icon.svg'],
87
+ control: categoryArtwork['icons/control_icon.svg'],
88
+ sensing: categoryArtwork['icons/sensing_icon.svg'],
89
+ operators: categoryArtwork['icons/operators_icon.svg'],
90
+ variables: categoryArtwork['icons/variables_icon.svg'],
91
+ lists: categoryArtwork['icons/list_icon.svg'],
92
+ myBlocks: categoryArtwork['icons/block_icon.svg']
93
+ };
94
+
95
+ function AttachedCodePanel({children}: {children: React.ReactNode}) {
96
+ const [attached, setAttached] = React.useState(false);
97
+ // Blockly injects synchronously once cached. DockablePanel attaches its portal during commit.
98
+ React.useLayoutEffect(() => setAttached(true), []);
99
+ return attached ? children : null;
100
+ }
101
+
102
+ const thumbnails = new WeakMap<object, string>();
103
+ function assetImage(asset) {
104
+ if (!asset?.encodeDataURI) return undefined;
105
+ if (!thumbnails.has(asset)) thumbnails.set(asset, asset.encodeDataURI());
106
+ return thumbnails.get(asset);
107
+ }
108
+
109
+ function readSpriteAssets(vm, targetId: string, kind: SpriteAssetKind): SpriteAssetPreviewData {
110
+ const target = vm.runtime.getTargetById(targetId);
111
+ if (!target) return {items: []};
112
+ if (kind === 'costumes') {
113
+ return {
114
+ defaultAsset: target.getCurrentCostume(),
115
+ items: target.getCostumes().map(costume => ({
116
+ asset: costume, name: costume.name, imageUrl: assetImage(costume.asset)
117
+ }))
118
+ };
119
+ }
120
+ const bank = target.sprite.soundBank;
121
+ return {items: target.getSounds().map(sound => ({
122
+ asset: sound, name: sound.name,
123
+ buffer: sound.soundId ? bank?.getSoundPlayer(sound.soundId)?.buffer : undefined,
124
+ duration: sound.rate ? sound.sampleCount / sound.rate : undefined
125
+ }))};
126
+ }
127
+
128
+ function readSpriteVariables(vm, id: string): SpriteVariable[] {
129
+ const target = vm.runtime.getTargetById(id);
130
+ const variables = Object.values<Parameters<typeof readSpriteVariable>[0]>(target?.variables ?? {})
131
+ .flatMap(variable => readSpriteVariable(variable) ?? []);
132
+ if (!variables.length) return variables;
133
+ const counts = countVariableAccesses(vm.runtime, id);
134
+ const monitors = vm.runtime.getMonitorState();
135
+ return variables.map(variable => ({
136
+ ...variable,
137
+ monitor: {
138
+ visible: Boolean(monitors.get(variable.id)?.visible),
139
+ setVisible: visible => showSpriteVariableOnStage(vm.runtime, id, variable.id, visible)
140
+ },
141
+ accesses: {
142
+ ...counts.get(variable.id) ?? {read: 0, write: 0},
143
+ open: access => openVariableSearch(vm.runtime, {ownerId: id, variableId: variable.id, access})
144
+ }
145
+ }));
146
+ }
147
+ const resizeCode = () => {
148
+ const blocks = getScratchBlocks();
149
+ const workspace = blocks?.getMainWorkspace();
150
+ if (workspace?.getInjectionDiv()?.clientWidth) blocks.svgResize(workspace);
151
+ };
152
+
153
+ type TransferKind = 'costume' | 'sound';
154
+ function DesktopAssetPanel({vm, kind, locale, port, selection, child}: {
155
+ vm: Parameters<typeof createAssetTransferPanel>[0];
156
+ kind: TransferKind;
157
+ locale: string;
158
+ port: ProjectAssetTransferPort;
159
+ selection?: SpriteAssetSelection;
160
+ child: React.ReactElement<{assetSelection?: SpriteAssetSelection}>;
161
+ }) {
162
+ const container = React.useRef<HTMLDivElement>(null);
163
+ const toolbar = React.useRef<HTMLDivElement>(null);
164
+ const controller = React.useMemo(() => createAssetTransferPanel(vm, kind, locale, port), [vm, kind, locale, port]);
165
+ React.useLayoutEffect(() => controller.mount(toolbar.current, container.current), [controller]);
166
+ const bridge = React.useMemo<SpriteAssetSelection>(() => ({
167
+ ...selection,
168
+ restore: selection?.restore ?? (() => undefined),
169
+ remember(target, asset, select) {
170
+ selection?.remember(target, asset, select);
171
+ controller.remember(target, asset);
172
+ }
173
+ }), [controller, selection]);
174
+ return <div ref={container} style={{display: 'flex', flex: 1, flexDirection: 'column', minWidth: 0, minHeight: 0}}>
175
+ <div ref={toolbar} />
176
+ {React.cloneElement(child, {assetSelection: bridge})}
177
+ </div>;
178
+ }
179
+
180
+ type OpenedFile = {id?: string; name?: string; isSameEntry?: unknown};
181
+
182
+ /** Tell the loaded project apart by the folder or file it came from, so each one keeps its own Dockview layout. */
183
+ function identifyProject(vm): WorkspaceProjectIdentity {
184
+ const name = loadedProjectTitle(vm) ?? '';
185
+ const directory = projectFolderDirectory(vm);
186
+ if (directory) return {kind: 'directory', name: directory.name, handle: directory};
187
+ const file = readOpenedFile();
188
+ if (file && typeof file.isSameEntry === 'function') {
189
+ return {kind: 'file', name: file.name ?? name, handle: file as unknown as FileSystemFileHandle};
190
+ }
191
+ // The desktop app gives its own handles; it keys each SB3 by its path.
192
+ const key = file?.id && desktopProjectKey ? desktopProjectKey(file.id) : null;
193
+ if (key) return {kind: 'desktop', name: file.name ?? name, key};
194
+ return {kind: 'anonymous', name};
195
+ }
196
+
197
+ function EditorTabs({vm, activeEditorTab, onActivateEditorTab, editorTargetIsStage, showUndock, locale, layout, render,
198
+ soundRecorderVisible}) {
199
+ const host = useWindowHost();
200
+ const {plusLayout} = React.useContext(WindowLayoutContext);
201
+ const stage = React.useContext(StageDisplayMenuContext)?.stage;
202
+ const targetSwitch = React.useContext(TargetSwitchContext);
203
+ // The stage uses the native fullscreen surface while Dockview keeps its panel and layout.
204
+ const workspaceEnabled = plusLayout || Boolean(stage);
205
+ const multiView = workspaceEnabled && dockviewMultiViewEnabled && typeof onActivateEditorTab === 'function';
206
+ const workspaceLayout = React.useMemo(() => multiView ? {
207
+ store: desktopWorkspaceLayoutStore,
208
+ identify: () => identifyProject(vm),
209
+ isProjectLoading: () => isProjectLoading(vm), subscribeProject: listener => subscribeProjectLoad(vm, listener),
210
+ // Read when the tabs mount and each project opens, after the project tools installed it.
211
+ get screenState() { return projectScreenState(vm); }
212
+ } : undefined, [multiView, vm]);
213
+ // The script shown beside the sprite, which the list of hats and functions highlights.
214
+ const [selectedScript, setSelectedScript] = React.useState<{targetId: string; id: string}>();
215
+ // The code view beside the sprite that shows one script at a time: the code area itself, without the other
216
+ // scripts and without the section buttons.
217
+ const [scriptView, setScriptView] = React.useState<{viewId: string; targetId: string}>();
218
+ const scriptViewRef = React.useRef(scriptView);
219
+ scriptViewRef.current = scriptView;
220
+ // A function or hat script picked in the functions sections shows there. `block` asks to show one of its blocks.
221
+ const openScriptView = (targetId: string, id: string, block?: string) => {
222
+ const views = spriteTabs.controller.current;
223
+ if (!views) return;
224
+ let viewId = scriptViewRef.current?.targetId === targetId &&
225
+ views.views().some(view => view.id === scriptViewRef.current.viewId) ? scriptViewRef.current.viewId : undefined;
226
+ if (!viewId) {
227
+ const current = views.currentView();
228
+ let from = current?.targetId === targetId ? current.id : views.views().find(view => view.targetId === targetId)?.id;
229
+ if (!from && navigation.current) {
230
+ from = activateTargetView(navigation.current, targetId, codeTab)?.viewId;
231
+ if (current) views.activateView(current.id);
232
+ }
233
+ viewId = from && views.split('right', from);
234
+ if (!viewId) return;
235
+ const opened = {viewId, targetId};
236
+ scriptViewRef.current = opened;
237
+ setScriptView(opened);
238
+ }
239
+ const shown = viewId;
240
+ codePaneAdapter.focusPane(shown, id, () => requestAnimationFrame(() => {
241
+ // The script was deleted, so its view goes too.
242
+ codePaneAdapter.forgetPane(shown);
243
+ spriteTabs.controller.current?.closeSplit(shown);
244
+ if (scriptViewRef.current?.viewId === shown) {
245
+ scriptViewRef.current = undefined;
246
+ setScriptView(undefined);
247
+ }
248
+ setSelectedScript(current => current?.targetId === targetId && current.id === id ? undefined : current);
249
+ }));
250
+ views.setViewSection(shown, codeTab);
251
+ views.activateView(shown);
252
+ setSelectedScript(current => current?.targetId === targetId && current.id === id ? current : {targetId, id});
253
+ if (block) {
254
+ requestAnimationFrame(() => {
255
+ const workspace = getScratchBlocks()?.getMainWorkspace();
256
+ const found = workspace?.getBlockById(block);
257
+ if (!found) return;
258
+ found.select();
259
+ });
260
+ }
261
+ };
262
+ const codePaneAdapter = React.useMemo(() =>
263
+ createCodePaneAdapter(vm, locale, layoutFlags.workspaceMinimap ? attachCodePreviewMinimap : undefined), [vm, locale]);
264
+ const popouts = React.useMemo(() => ({
265
+ url: popupURL,
266
+ openPalette: () => openDetachedBlockPalette({locale, categoryIcons, decorate: decorateSurface})
267
+ }), [locale]);
268
+ const code = useCodeWindows({vm, host, locale,
269
+ enabled: !multiView && (layoutFlags.spriteCodeWindows || layoutFlags.standardLayout) && !desktopCodeEnabled});
270
+ const [states, setStates] = React.useState([]);
271
+ const action = React.useRef(null);
272
+ const previousActive = React.useRef(null);
273
+ const surfaces = React.useMemo(() => [0, 1, 2].map(index => createSurface(host, state => {
274
+ setStates(previous => {
275
+ const next = [...previous];
276
+ next[index] = state;
277
+ return next;
278
+ });
279
+ })), [host]);
280
+ React.useLayoutEffect(() => () => surfaces.forEach(surface => surface.dock()), [surfaces]);
281
+
282
+ const japanese = /^ja(?:-|$)/i.test(locale);
283
+ const openLabel = japanese ? '別画面で開く' : 'Open in another window';
284
+ const dockLabel = japanese ? 'ここに戻す' : 'Return here';
285
+ const titles = japanese ? ['コード', editorTargetIsStage ? '背景' : 'コスチューム', '音'] :
286
+ ['Code', editorTargetIsStage ? 'Backdrops' : 'Costumes', 'Sounds'];
287
+ const title = titles[activeEditorTab];
288
+ const activeState = states[activeEditorTab];
289
+ React.useLayoutEffect(() => {
290
+ const previous = previousActive.current;
291
+ previousActive.current = {index: activeEditorTab, kind: activeState?.kind};
292
+ if (showUndock && previous?.index === activeEditorTab && previous.kind === 'external' &&
293
+ activeState?.kind === 'docked') {
294
+ action.current?.querySelector('button')?.focus();
295
+ }
296
+ }, [activeEditorTab, activeState, showUndock]);
297
+ React.useLayoutEffect(() => {
298
+ const tabs = action.current?.parentElement?.parentElement;
299
+ if (!tabs) return;
300
+ const enableCodeFocus = event => {
301
+ // Blockly focuses its SVG on mouse down, so make it programmatically focusable first.
302
+ const svg = event.target.closest('.blocklySvg');
303
+ if (svg && !svg.hasAttribute('tabindex')) svg.setAttribute('tabindex', '-1');
304
+ };
305
+ const focusPanel = event => {
306
+ const panel = event.target.closest('[role="tabpanel"]');
307
+ if (!panel || panel.contains(panel.ownerDocument.activeElement)) return;
308
+ if (!panel.hasAttribute('tabindex')) panel.tabIndex = -1;
309
+ panel.focus({preventScroll: true});
310
+ };
311
+ tabs.addEventListener('pointerdown', enableCodeFocus, true);
312
+ tabs.addEventListener('click', focusPanel);
313
+ return () => {
314
+ tabs.removeEventListener('pointerdown', enableCodeFocus, true);
315
+ tabs.removeEventListener('click', focusPanel);
316
+ };
317
+ }, [showUndock, title]);
318
+ const getMount = index => {
319
+ if (index === codeTab && code?.front) return code.front.mount;
320
+ return states[index]?.kind === 'external' ? states[index].target.mount : undefined;
321
+ };
322
+
323
+ function open() {
324
+ if (activeEditorTab === codeTab && desktopCodeEnabled) {
325
+ openDesktopCode();
326
+ return;
327
+ }
328
+ if (code && activeEditorTab === codeTab && !editorTargetIsStage) {
329
+ code.openCurrent();
330
+ return;
331
+ }
332
+ surfaces[activeEditorTab].undock({id: `basic-editor-tab-${activeEditorTab}`, title, rememberPlacement: true});
333
+ }
334
+
335
+ const tabAction = showUndock && title && (!multiView || activeEditorTab !== codeTab) && (
336
+ <div className={`${styles.tabAction} ${styles.openWindowAction}`} ref={action}>
337
+ <OpenWindowButton label={openLabel} onOpen={open} disabled={Boolean(activeState && activeState.kind !== 'docked')} />
338
+ </div>
339
+ );
340
+ const renderEditorTabRow = tabs => layout.renderEditorTabRow ? layout.renderEditorTabRow(tabs, tabAction) :
341
+ <div className={styles.tabRow}>{tabs}{tabAction}</div>;
342
+ // The message section and the temporary variable tables open blocks through the same navigation
343
+ // the project search uses: the target's code, with the block centered.
344
+ const navigation = React.useRef<SearchNavigation | null>(null);
345
+ // The variable and message panes draw the hats of scripts in any target as Scratch shows them.
346
+ const blockImages = React.useMemo(() => createBlockImageRenderer(() => getScratchBlocks(), vm.runtime), [vm]);
347
+ React.useEffect(() => () => blockImages.dispose(), [blockImages]);
348
+ const openBlock = (targetId: string, blockId: string) => {
349
+ const search = navigation.current;
350
+ if (!search || !activateTargetView(search, targetId, codeTab)) return;
351
+ requestAnimationFrame(() => search.centerBlock(blockId));
352
+ };
353
+ const spriteTabs = useSpriteTabs({
354
+ available: dockviewSpriteTabsEnabled, enabled: workspaceEnabled && dockviewSpriteTabsEnabled,
355
+ vm, locale, className: styles.spriteTabs, activeSection: activeEditorTab,
356
+ activateSection: onActivateEditorTab,
357
+ ...{runTargetSwitch: targetSwitch?.select},
358
+ resize: () => requestAnimationFrame(resizeCode),
359
+ ...(multiView && {
360
+ multiView, workspaceLayout, stagePane: stage?.pane, viewAdapter: codePaneAdapter, popouts,
361
+ renderToolbar(view, actions) {
362
+ // The view that shows one script keeps to the code: no section buttons.
363
+ if (view.id === scriptView?.viewId && view.section === codeTab) return <></>;
364
+ const section = spriteEditorSections[view.section] ?? 'code';
365
+ return <SpriteEditorToolbar viewId={view.id} locale={locale} section={section} isStage={view.isStage}
366
+ activeGroup={view.groupActive} propertiesInVariables
367
+ sectionControls={actions.sectionControls}
368
+ onSectionChange={next => actions.setSection(spriteEditorSections.indexOf(next))}
369
+ actions={section === 'variables' && !view.isStage ?
370
+ <SpriteClonePagination viewId={view.id} targetId={view.targetId} locale={locale} /> :
371
+ view.active && section !== 'variables' && section !== 'messages' && section !== 'functions' ?
372
+ renderEditorTabRow(null) : undefined} />;
373
+ },
374
+ wrapVariablePane(viewId, targetId, editable, pane) {
375
+ pane = React.cloneElement(pane, {temporaryVariables: readTemporaryVariables(vm.runtime, targetId),
376
+ onOpenFunction: openBlock, getBlockImage: blockImages.render});
377
+ return vm.runtime.getTargetById(targetId)?.isStage ?
378
+ React.cloneElement(pane, {global: {canAddCloudVariable: vm.runtime.canAddCloudVariable()}}) :
379
+ <SpriteCloneVariables {...{viewId, targetId, locale, editable}}>{pane}</SpriteCloneVariables>;
380
+ },
381
+ getAssetPreview: (id, kind) => readSpriteAssets(vm, id, kind),
382
+ getVariables: id => readSpriteVariables(vm, id),
383
+ editVariable: (id, edit) => editClonedSpriteVariable(vm, id, edit, () => editSpriteVariable(vm, id, edit)),
384
+ getProperties(id) {
385
+ const target = vm.runtime.getTargetById(id);
386
+ if (!target || target.isStage) return;
387
+ const {x, y, size, direction, visible, rotationStyle} = target;
388
+ return {name: target.getName(), x, y, size, direction, visible, rotationStyle};
389
+ },
390
+ writeProperties(id, {name, ...patch}) {
391
+ const target = vm.runtime.getTargetById(id);
392
+ if (!target || target !== vm.editingTarget || target.isStage || (vm._dragTarget && vm._dragTarget !== target)) return;
393
+ if (name !== undefined) {
394
+ const trimmed = name.trim();
395
+ if (trimmed && trimmed !== target.getName()) vm.renameSprite(id, trimmed);
396
+ } else vm.postSpriteInfo(patch);
397
+ },
398
+ writeVariable(id, variableId, value) {
399
+ if (writeSpriteVariableValue(vm, id, variableId, value)) {
400
+ vm.runtime.emitProjectChanged();
401
+ }
402
+ },
403
+ getMessages: (id): MessagePaneData => ({
404
+ ...scanTargetMessages(vm.runtime, id),
405
+ getThumbnailUrl: targetId => assetImage(vm.runtime.getTargetById(targetId)?.getCurrentCostume()?.asset),
406
+ getBlockImage: blockImages.render,
407
+ describeScript: (targetId, blockId) => describeScriptStart(vm.runtime, targetId, blockId)
408
+ }),
409
+ openMessage: use => openBlock(use.targetId, use.blockId),
410
+ openMessageTarget(id) {
411
+ if (navigation.current) activateTargetView(navigation.current, id, codeTab);
412
+ },
413
+ getFunctions(id) {
414
+ const target = vm.runtime.getTargetById(id);
415
+ if (!target) return {targetId: id, isStage: false, functions: []};
416
+ const hats = new Map<string, ReturnType<typeof readHatScripts>>();
417
+ const targetHats = targetId => {
418
+ if (!hats.has(targetId)) {
419
+ const owner = vm.runtime.getTargetById(targetId);
420
+ hats.set(targetId, owner ? readHatScripts(owner, getScratchBlocks()) : []);
421
+ }
422
+ return hats.get(targetId)!;
423
+ };
424
+ const data = readTargetFunctions(target, {
425
+ others: vm.runtime.targets.filter(other => other.isOriginal),
426
+ getTargetThumbnail: targetId => assetImage(vm.runtime.getTargetById(targetId)?.getCurrentCostume()?.asset),
427
+ describeScript: (targetId, scriptId) => targetHats(targetId).find(hat => hat.id === scriptId)?.label
428
+ });
429
+ const definitions = new Set(data.functions.map(fn => fn.id));
430
+ return {...data, hats: targetHats(id).filter(hat => !definitions.has(hat.id)),
431
+ ...readScriptRelationGraph(vm.runtime.targets, getScratchBlocks())};
432
+ },
433
+ createFunction: (targetId, kind, name) =>
434
+ createFunction(vm, targetId, kind, name, {loadNamedFunctions: () => loadNamedFunctions(vm)}),
435
+ mountFunctionEditor: (element, targetId, functionId, options) =>
436
+ mountProcedureEditor(vm, locale, element, targetId, functionId, {...options, attachNavigation: attachCodeNavigation}),
437
+ openFunction: (targetId, fn, options) =>
438
+ openScriptView(fn.owner?.targetId ?? targetId, fn.owner?.functionId ?? fn.id, options?.block),
439
+ openScript: (targetId, hat, options) => openScriptView(hat.targetId ?? targetId, hat.id, options?.block),
440
+ openRelationScript: endpoint => openScriptView(endpoint.targetId, endpoint.scriptId, endpoint.blockId),
441
+ selectedScript,
442
+ renameMessage(message, name) {
443
+ const workspace = getScratchBlocks()?.getMainWorkspace();
444
+ if (!workspace || !message.id) return 'unavailable';
445
+ const outcome = renameProjectMessage(vm.runtime, workspace, message.id, name);
446
+ return outcome === 'applied' ? undefined : outcome === 'conflict' ? 'duplicateName' : 'unavailable';
447
+ }
448
+ })
449
+ });
450
+ // “Show this function” on a block that calls one opens it in the list of hats and functions beside the sprite.
451
+ const openScriptViewRef = React.useRef(openScriptView);
452
+ openScriptViewRef.current = openScriptView;
453
+ React.useEffect(() => {
454
+ if (!multiView) return undefined;
455
+ const callee = (blockId: string) => {
456
+ const target = vm.editingTarget;
457
+ return target && readTargetFunctions(target).functions.find(fn => fn.uses?.some(use => use.block === blockId));
458
+ };
459
+ let detach: (() => void) | undefined;
460
+ // ScratchBlocks loads with the code area, which says so with its first workspace update.
461
+ const attach = () => {
462
+ const blocks = getScratchBlocks();
463
+ if (detach || !blocks?.BlockSvg) return;
464
+ detach = attachFunctionCallMenu(blocks, {
465
+ label: () => (/^ja(?:-|$)/i.test(locale) ? 'この関数を表示' : 'Show this function'),
466
+ find: blockId => callee(blockId)?.id,
467
+ open(functionId) {
468
+ const target = vm.editingTarget;
469
+ const fn = target && readTargetFunctions(target).functions.find(item => item.id === functionId);
470
+ if (!fn) return;
471
+ openScriptViewRef.current(target.id, fn.id);
472
+ }
473
+ });
474
+ };
475
+ attach();
476
+ vm.on('workspaceUpdate', attach);
477
+ return () => {
478
+ vm.removeListener('workspaceUpdate', attach);
479
+ detach?.();
480
+ };
481
+ }, [vm, locale, multiView]);
482
+ React.useLayoutEffect(() => {
483
+ if (!multiView) return;
484
+ const current: SearchNavigation = {
485
+ getViews: () => spriteTabs.controller.current,
486
+ getTarget: id => vm.runtime.getTargetById(id),
487
+ getEditingTarget: () => vm.editingTarget,
488
+ centerBlock(id) {
489
+ const workspace = getScratchBlocks()?.getMainWorkspace();
490
+ if (workspace?.getBlockById(id)) workspace.centerOnBlock(id);
491
+ },
492
+ centerComment(id, blockId) {
493
+ centerProjectComment(getScratchBlocks()?.getMainWorkspace(), id, blockId);
494
+ },
495
+ replacementContext() {
496
+ const Blockly = getScratchBlocks();
497
+ const workspace = Blockly?.getMainWorkspace();
498
+ return workspace?.isVisible() ? {workspace, Blockly} : undefined;
499
+ }
500
+ };
501
+ navigation.current = current;
502
+ const disconnect = connectProjectSearchNavigation(vm.runtime, current);
503
+ let refreshFrame: number | undefined;
504
+ const refreshVariables = () => {
505
+ const views = spriteTabs.controller.current;
506
+ // Variables show values, and functions list definitions, that change with the project.
507
+ if (refreshFrame !== undefined || !views?.views().some(view =>
508
+ view.section === spriteEditorSections.indexOf('variables') ||
509
+ view.section === spriteEditorSections.indexOf('functions'))) return;
510
+ refreshFrame = requestAnimationFrame(() => {
511
+ refreshFrame = undefined;
512
+ spriteTabs.controller.current?.refreshSurfaces();
513
+ });
514
+ };
515
+ let visibleMonitors = new Set<string>();
516
+ const refreshMonitorVisibility = monitors => {
517
+ const next = new Set<string>();
518
+ for (const monitor of monitors.values()) {
519
+ if (monitor.visible && (monitor.opcode === 'data_variable' || monitor.opcode === 'data_listcontents')) next.add(monitor.id);
520
+ }
521
+ if (next.size === visibleMonitors.size && [...next].every(id => visibleMonitors.has(id))) return;
522
+ visibleMonitors = next;
523
+ refreshVariables();
524
+ };
525
+ vm.on('PROJECT_CHANGED', refreshVariables);
526
+ vm.on('MONITORS_UPDATE', refreshMonitorVisibility);
527
+ refreshMonitorVisibility(vm.runtime.getMonitorState());
528
+ const stopTemporaryVariables = watchTemporaryVariables(vm.runtime, refreshVariables);
529
+ return () => {
530
+ stopTemporaryVariables();
531
+ vm.removeListener('PROJECT_CHANGED', refreshVariables);
532
+ vm.removeListener('MONITORS_UPDATE', refreshMonitorVisibility);
533
+ if (refreshFrame !== undefined) cancelAnimationFrame(refreshFrame);
534
+ if (navigation.current === current) navigation.current = null;
535
+ disconnect();
536
+ };
537
+ }, [multiView, vm, spriteTabs.controller]);
538
+ const connectAssetSelection = (index: number, child: React.ReactNode) => {
539
+ const assetSelection = index === 1 ? spriteTabs.assetSelections?.costumes : index === 2 ? spriteTabs.assetSelections?.sounds : undefined;
540
+ if (!React.isValidElement<{assetSelection?: SpriteAssetSelection}>(child)) return child;
541
+ const kind = index === 1 ? 'costume' : index === 2 ? 'sound' : undefined;
542
+ const port = kind && assetTransferPort();
543
+ if (port) return <DesktopAssetPanel {...{vm, kind, locale, port, selection: assetSelection, child}} />;
544
+ return assetSelection ? React.cloneElement(child, {assetSelection}) : child;
545
+ };
546
+
547
+ const content = render({...layout,
548
+ renderEditorTabRow: tabs => {
549
+ const row = multiView ? tabs : renderEditorTabRow(tabs);
550
+ return spriteTabs.renderEditorTabRow ? spriteTabs.renderEditorTabRow(row) : row;
551
+ },
552
+ // The recorder is hosted by the sound panel and must survive editor tab switches.
553
+ isEditorPanelOpen: index => Boolean(getMount(index)) || (index === soundsTab && soundRecorderVisible),
554
+ renderEditorPanel: (index, children) => {
555
+ const panel = <DockablePanel
556
+ dockLabel={dockLabel}
557
+ mount={getMount(index)}
558
+ onDock={() => index === codeTab && code?.front ? code.front.connection.close() : surfaces[index].dock()}
559
+ onResize={index === codeTab ? resizeCode : undefined}
560
+ >{index === codeTab ? <AttachedCodePanel>
561
+ {children}
562
+ {multiView && <CodePaneCostumeThumbnail adapter={codePaneAdapter} />}
563
+ </AttachedCodePanel> :
564
+ connectAssetSelection(index, children)}</DockablePanel>;
565
+ return spriteTabs.renderEditorPanel ? spriteTabs.renderEditorPanel(index, panel) : panel;
566
+ }
567
+ });
568
+ const selection = spriteTabs.context;
569
+ const editorCommands = selection && code ? {...selection, open: code.context.open} : selection ?? code?.context ?? null;
570
+ return <SpriteTargetTabsContext.Provider value={spriteTabs.listTabs}><SpriteCodeProvider value={editorCommands}>
571
+ <SpriteCloneInspector vm={vm}>{content}</SpriteCloneInspector>
572
+ {code && <BackCodeWindows vm={vm} windows={code.windows} front={code.front}
573
+ attachBackpackDrop={attachBackpackDrop} />}
574
+ </SpriteCodeProvider></SpriteTargetTabsContext.Provider>;
575
+ }
576
+
577
+ const EditorTabLayout = connectEditorTabs(EditorTabs);
578
+
579
+ return {EditorTabLayout};
580
+ }
@@ -0,0 +1,4 @@
1
+ /* SPDX-License-Identifier: MPL-2.0 */
2
+ .root {
3
+ --tw-plus-icon-menu-max-width: min(17rem, 90vw);
4
+ }