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