@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,268 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ import JSZip from '@turbowarp/jszip';
3
+ import { beginProjectLoad } from '../project-load-progress.js';
4
+ import { isValidSaveName } from '../project-file-dialogs.js';
5
+ export const PROJECT_INFO_KEY = 'turboWarpPlusProject';
6
+ // `saveName` names the project's folder or repository where the title cannot (#679); empty means none yet.
7
+ const fields = ['title', 'description', 'author', 'contact', 'saveName'];
8
+ const empty = () => ({ schemaVersion: 1, title: '', description: '', author: '', contact: '', saveName: '',
9
+ createdAt: null, updatedAt: null });
10
+ const clone = value => JSON.parse(JSON.stringify(value));
11
+ const validDate = value => typeof value === 'string' && Number.isFinite(Date.parse(value)) ? value : null;
12
+ const maxInfoBytes = 32 * 1024 * 1024;
13
+ const projectInfo = project => {
14
+ const value = project?.[PROJECT_INFO_KEY];
15
+ return value && typeof value === 'object' && !Array.isArray(value) ? clone(value) : null;
16
+ };
17
+ const archiveInfo = (archive) => archive && archive.projectBytes <= maxInfoBytes ? projectInfo(archive.project) : null;
18
+ const normalize = value => ({ ...empty(), ...value,
19
+ ...Object.fromEntries(fields.map(key => [key, typeof value?.[key] === 'string' ? value[key] : ''])),
20
+ createdAt: validDate(value?.createdAt), updatedAt: validDate(value?.updatedAt) });
21
+ /** Keep a new repository's chosen title in the saved project, including projects from ordinary SB3s. */
22
+ export function withProjectFolderTitle(files, title) {
23
+ const path = 'project.source.json';
24
+ const project = JSON.parse(new TextDecoder().decode(files.get(path)));
25
+ const existing = projectInfo(project);
26
+ if (existing && existing.schemaVersion !== 1)
27
+ return files;
28
+ if (existing?.title === title)
29
+ return files;
30
+ project[PROJECT_INFO_KEY] = { ...normalize(existing), title };
31
+ return new Map(files).set(path, new TextEncoder().encode(JSON.stringify(project, null, 2) + '\n'));
32
+ }
33
+ /** Read only this host's metadata. Project validation and extension manifests remain with the VM/Loader. */
34
+ async function readInfo(input) {
35
+ try {
36
+ let project;
37
+ if (typeof input === 'string')
38
+ project = JSON.parse(input);
39
+ else if (input && typeof input === 'object' && !ArrayBuffer.isView(input) &&
40
+ !(input instanceof ArrayBuffer) && !(typeof Blob !== 'undefined' && input instanceof Blob))
41
+ project = input;
42
+ else {
43
+ const bytes = typeof Blob !== 'undefined' && input instanceof Blob ? await input.arrayBuffer() : input;
44
+ const array = bytes instanceof ArrayBuffer ? new Uint8Array(bytes) :
45
+ new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength);
46
+ const prefix = new TextDecoder().decode(array.subarray(0, 64)).trimStart();
47
+ if (prefix.startsWith('{'))
48
+ return readInfo(JSON.parse(new TextDecoder().decode(array)));
49
+ // Old .sb/.sb2 inputs are left entirely to the VM.
50
+ const zip = await JSZip.loadAsync(bytes);
51
+ const file = zip.file('project.json');
52
+ if (!file || file._data?.uncompressedSize > maxInfoBytes)
53
+ return null;
54
+ project = JSON.parse(await file.async('string'));
55
+ }
56
+ return projectInfo(project);
57
+ }
58
+ catch (error) {
59
+ return null;
60
+ }
61
+ }
62
+ export function createProjectProperties({ beginProjectArchiveRead, projectSerializationOptions }) {
63
+ return function installProjectProperties(vm, { projectState = {}, now = () => new Date().toISOString(), metadataEnabled = true, runProjectLoad, shareArchives = false } = {}) {
64
+ // Diagnostics observes loads even when metadata editing and serialization are disabled.
65
+ const names = ['loadProject', ...(metadataEnabled ?
66
+ ['toJSON', 'saveProjectSb3', 'saveProjectSb3Stream', 'saveProjectSb3DontZip'] : [])];
67
+ const originals = Object.fromEntries(names.filter(name => typeof vm[name] === 'function').map(name => [name, vm[name]]));
68
+ const descriptors = Object.fromEntries(Object.keys(originals).map(name => [name, Object.getOwnPropertyDescriptor(vm, name)]));
69
+ let info = null;
70
+ let baseline = null;
71
+ let loading = 0;
72
+ let generation = 0;
73
+ let transaction = null;
74
+ let saveSerial = 0;
75
+ let lastCommittedSave = 0;
76
+ let disposed = false;
77
+ let loadQueue = Promise.resolve();
78
+ let loadState = { phase: 'idle', sequence: 0 };
79
+ const listeners = new Set();
80
+ const notify = () => {
81
+ // Presentation subscribers cannot change the result of loading or saving a project.
82
+ for (const listener of listeners) {
83
+ try {
84
+ listener();
85
+ }
86
+ catch (error) { /* Keep the project lifecycle intact. */ }
87
+ }
88
+ };
89
+ const current = () => {
90
+ const value = normalize(info);
91
+ value.title = projectSerializationOptions(vm)?.title ?? projectState.getTitle?.() ?? value.title;
92
+ return value;
93
+ };
94
+ const fingerprint = () => {
95
+ const json = JSON.parse(originals.toJSON.call(vm));
96
+ delete json[PROJECT_INFO_KEY];
97
+ delete json.meta;
98
+ const value = current();
99
+ return JSON.stringify([json, fields.map(key => value[key])]);
100
+ };
101
+ const commit = receipt => {
102
+ if (disposed || receipt.generation !== generation || receipt.serial < lastCommittedSave)
103
+ return;
104
+ lastCommittedSave = receipt.serial;
105
+ // Applying properties or editing blocks during compression must remain unsaved.
106
+ if (JSON.stringify(info) === receipt.previous || receipt.fingerprint === fingerprint())
107
+ info = receipt.info;
108
+ baseline = receipt.fingerprint;
109
+ notify();
110
+ };
111
+ const save = (original, args, stream = false) => {
112
+ if (loading)
113
+ throw new Error('Wait for project loading to finish before saving');
114
+ const options = projectSerializationOptions(vm);
115
+ if (options?.preview)
116
+ return original.apply(vm, args);
117
+ const print = fingerprint();
118
+ const value = info?.schemaVersion === 1 ? current() : info;
119
+ const receipt = { generation, serial: ++saveSerial, fingerprint: print, previous: JSON.stringify(info),
120
+ info: value ? { ...value } : null };
121
+ if (receipt.info?.schemaVersion === 1 && print !== baseline)
122
+ receipt.info.updatedAt = now();
123
+ transaction = receipt;
124
+ let result;
125
+ try {
126
+ result = original.apply(vm, args);
127
+ }
128
+ finally {
129
+ transaction = null;
130
+ }
131
+ if (options?.deferCommit) {
132
+ options.deferCommit(() => commit(receipt));
133
+ }
134
+ else if (stream) {
135
+ result.on('end', () => commit(receipt));
136
+ }
137
+ else if (result && typeof result.then === 'function') {
138
+ return result.then(output => { commit(receipt); return output; });
139
+ }
140
+ else
141
+ commit(receipt);
142
+ return result;
143
+ };
144
+ const wrappers = {
145
+ loadProject(input, ...args) {
146
+ if (disposed)
147
+ return Promise.reject(new Error('Project properties were disposed'));
148
+ loading++;
149
+ const progress = beginProjectLoad(vm, input);
150
+ const archive = shareArchives ? beginProjectArchiveRead(vm, input) : undefined;
151
+ const isNew = projectState.isNew?.() === true;
152
+ // The authoring controller identifies its own load in the synchronous start callback.
153
+ // Metadata reading must not defer that callback beyond the caller's ownership scope.
154
+ let nativeLoad;
155
+ const load = () => originals.loadProject.call(vm, input, ...args);
156
+ const invoke = () => archive ? archive.invoke(load) : load();
157
+ try {
158
+ nativeLoad = progress ? progress.invoke(invoke) : invoke();
159
+ }
160
+ catch (error) {
161
+ nativeLoad = Promise.reject(error);
162
+ }
163
+ const settled = Promise.resolve(nativeLoad).then(value => ({ value }), error => ({ error, failed: true }));
164
+ const run = async () => {
165
+ if (disposed)
166
+ throw new Error('Project properties were disposed');
167
+ const sequence = ++generation;
168
+ loadState = { phase: 'loading', sequence };
169
+ notify();
170
+ let loaded = metadataEnabled && !archive ? await readInfo(input) : null;
171
+ try {
172
+ if (disposed)
173
+ throw new Error('Project properties were disposed');
174
+ const outcome = await settled;
175
+ if (metadataEnabled && archive) {
176
+ if (archive.read.original)
177
+ loaded = archiveInfo(archive.read.original);
178
+ else if (!('failed' in outcome))
179
+ loaded = await readInfo(input);
180
+ }
181
+ if ('failed' in outcome)
182
+ throw outcome.error;
183
+ const result = outcome.value;
184
+ if (disposed)
185
+ return result;
186
+ if (metadataEnabled) {
187
+ info = loaded || (isNew ? { ...empty(), createdAt: now() } : null);
188
+ if (info?.schemaVersion === 1 && info.title)
189
+ projectState.setTitle?.(info.title);
190
+ baseline = fingerprint();
191
+ }
192
+ loadState = { phase: 'loaded', sequence };
193
+ notify();
194
+ return result;
195
+ }
196
+ catch (error) {
197
+ loadState = { phase: 'failed', sequence, title: loaded?.title,
198
+ code: error.code, message: error.message || String(error) };
199
+ notify();
200
+ throw error;
201
+ }
202
+ };
203
+ const result = loadQueue.then(() => runProjectLoad ? runProjectLoad(run) : run());
204
+ loadQueue = result.catch(() => { });
205
+ return result.finally(() => {
206
+ loading--;
207
+ progress?.finish();
208
+ });
209
+ },
210
+ toJSON(...args) {
211
+ const raw = originals.toJSON.apply(vm, args);
212
+ if (args[0])
213
+ return raw;
214
+ const value = transaction ? transaction.info : info?.schemaVersion === 1 ? current() : info;
215
+ if (!value)
216
+ return raw;
217
+ return JSON.stringify({ ...JSON.parse(raw), [PROJECT_INFO_KEY]: value });
218
+ },
219
+ saveProjectSb3(...args) { return save(originals.saveProjectSb3, args); },
220
+ saveProjectSb3Stream(...args) { return save(originals.saveProjectSb3Stream, args, true); },
221
+ saveProjectSb3DontZip(...args) { return save(originals.saveProjectSb3DontZip, args); }
222
+ };
223
+ for (const name of Object.keys(originals))
224
+ vm[name] = wrappers[name];
225
+ return {
226
+ snapshot: () => ({ ...current(), readOnly: Boolean(info && info.schemaVersion !== 1), loading: loading > 0 }),
227
+ loadState: () => ({ ...loadState }),
228
+ subscribe(listener) { listeners.add(listener); return () => listeners.delete(listener); },
229
+ loadedTitle: () => info?.schemaVersion === 1 && typeof info.title === 'string' && info.title ? info.title : undefined,
230
+ restoreTitle() { const title = this.loadedTitle(); if (title !== undefined)
231
+ projectState.setTitle?.(title); },
232
+ apply(draft) {
233
+ if (!metadataEnabled || disposed || loading || (info && info.schemaVersion !== 1)) {
234
+ throw new Error('Project properties are not editable');
235
+ }
236
+ const previous = current();
237
+ const next = { ...previous, ...Object.fromEntries(fields.map(key => [key, String(draft[key] ?? previous[key])])) };
238
+ next.title = next.title.slice(0, 100);
239
+ next.author = next.author.trim();
240
+ next.contact = next.contact.trim();
241
+ next.saveName = next.saveName.trim();
242
+ if (next.saveName && !isValidSaveName(next.saveName)) {
243
+ throw Object.assign(new Error('The save name is not valid'), { code: 'INVALID_SAVE_NAME' });
244
+ }
245
+ if (fields.every(key => next[key] === previous[key]))
246
+ return false;
247
+ info = next;
248
+ projectState.setTitle?.(next.title);
249
+ vm.runtime?.emitProjectChanged?.();
250
+ notify();
251
+ return true;
252
+ },
253
+ dispose() {
254
+ disposed = true;
255
+ generation++;
256
+ listeners.clear();
257
+ for (const [name, original] of Object.entries(originals)) {
258
+ if (vm[name] !== wrappers[name])
259
+ continue;
260
+ if (descriptors[name])
261
+ Object.defineProperty(vm, name, { ...descriptors[name], value: original });
262
+ else
263
+ delete vm[name];
264
+ }
265
+ }
266
+ };
267
+ };
268
+ }
@@ -234,6 +234,7 @@ type SpriteTabsProps<Snapshot> = Omit<TabOptions<Snapshot>, 'activateSection' |
234
234
  selectedScript?: {
235
235
  targetId: string;
236
236
  id: string;
237
+ focusRequest?: number;
237
238
  };
238
239
  /**
239
240
  * Make a new function of this name in the target: a standard custom block, whose block text is the name,
@@ -1709,6 +1709,7 @@ function SpriteTabs(props) {
1709
1709
  ((hat, options) => props.openScript(targetId, hat, options)),
1710
1710
  onOpenRelationScript: props.openRelationScript,
1711
1711
  selectedId: props.selectedScript?.targetId === targetId ? props.selectedScript.id : undefined,
1712
+ focusRequest: props.selectedScript?.targetId === targetId ? props.selectedScript.focusRequest : undefined,
1712
1713
  onCreate: props.createFunction && (async (functionKind, name) => {
1713
1714
  const created = await props.createFunction(targetId, functionKind, name);
1714
1715
  // Show the new function now rather than at the next project change.
@@ -0,0 +1,21 @@
1
+ import React from 'react';
2
+ export declare function createStageDisplayMenu({ WindowLayoutContext, StageDisplayMenuContext, layoutFlags, styles, workbenchStyles, fullscreenIcon, exitFullscreenIcon, connectFullscreen, fullscreenMount }: {
3
+ WindowLayoutContext: React.Context<any>;
4
+ StageDisplayMenuContext: React.Context<any>;
5
+ layoutFlags: {
6
+ stageDisplayMenu: boolean;
7
+ };
8
+ styles: Record<string, string>;
9
+ workbenchStyles: Record<string, string>;
10
+ fullscreenIcon: string;
11
+ exitFullscreenIcon: string;
12
+ connectFullscreen(component: React.ComponentType<any>): React.ComponentType<any>;
13
+ fullscreenMount(header: HTMLElement): HTMLElement | null;
14
+ }): {
15
+ EditorStageFullscreenMenu: React.ComponentType<any>;
16
+ StageDisplayMenu: ({ locale, presets, fullscreen }: {
17
+ locale: any;
18
+ presets: any;
19
+ fullscreen: any;
20
+ }) => React.JSX.Element;
21
+ };
@@ -0,0 +1,156 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ import React from 'react';
3
+ import { createPortal } from 'react-dom';
4
+ import { IconMenuButton } from '@kubohiroya/turbowarp-plus-editor-windows';
5
+ import { panelLayoutIconPath } from "./index.js";
6
+ import { stageDockActionLabel, stageDrawerPinItem, stagePresentationItems, useStageDocumentFullscreen } from "./stage-surface.js";
7
+ export function createStageDisplayMenu({ WindowLayoutContext, StageDisplayMenuContext, layoutFlags, styles, workbenchStyles, fullscreenIcon, exitFullscreenIcon, connectFullscreen, fullscreenMount }) {
8
+ const stageLayoutIcon = (React.createElement("svg", { viewBox: "-4 -4 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.4", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true" },
9
+ React.createElement("path", { d: panelLayoutIconPath })));
10
+ function PresetIcon({ icon }) {
11
+ return React.createElement("img", { className: styles.directional, src: typeof icon === 'function' ? icon() : icon, alt: "", draggable: false });
12
+ }
13
+ const isJapanese = locale => /^ja(?:-|$)/i.test(locale);
14
+ const menuLabel = locale => isJapanese(locale) ? 'ステージの表示' : 'Stage display';
15
+ function fullscreenItem(locale, active, onSelect, disabled = false) {
16
+ const label = active ? (isJapanese(locale) ? '全画面表示を終了' : 'Exit full screen mode') :
17
+ (isJapanese(locale) ? '全画面表示にする' : 'Enter full screen mode');
18
+ return { id: 'fullscreen', label, icon: React.createElement(PresetIcon, { icon: active ? exitFullscreenIcon : fullscreenIcon }),
19
+ onSelect, disabled };
20
+ }
21
+ function dockIcon(returning) {
22
+ return React.createElement("svg", { className: styles.directional, viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true" },
23
+ React.createElement("path", { d: "M6 4H3v9h9v-3" }),
24
+ React.createElement("path", { d: returning ? 'M12.5 3.5 7 9m0-4v4h4' : 'M8 3h5v5m0-5L7 9' }));
25
+ }
26
+ function StageLayoutMenu({ locale, items, className = '' }) {
27
+ return React.createElement(IconMenuButton, { label: menuLabel(locale), icon: stageLayoutIcon, items: items, className: `${styles.stageDisplayMenu} ${workbenchStyles.stagePresentationMenu} ${className}` });
28
+ }
29
+ const EditorStageFullscreenMenu = connectFullscreen(function EditorStageFullscreenMenu({ header, locale, onExit }) {
30
+ // Use the GUI's existing fullscreen controls row, including its alignment and stacking.
31
+ const mount = fullscreenMount(header);
32
+ return mount ? createPortal(React.createElement(StageLayoutMenu, { locale: locale, className: styles.fullscreenLayoutMenu, items: [fullscreenItem(locale, true, onExit)] }), mount) : null;
33
+ });
34
+ function DisplayMenu({ locale, presets, fullscreen }) {
35
+ const { dockAction, stage, launcher, openDrawer, closeDrawer } = React.useContext(StageDisplayMenuContext) ?? {};
36
+ const { plusLayout, stageDrawer, stageDrawerPinned, setStageDrawerPinned, stageHidden, setStageVisible } = React.useContext(WindowLayoutContext);
37
+ const japanese = isJapanese(locale);
38
+ const canToggleVisibility = plusLayout && (!dockAction || dockAction.kind === 'docked');
39
+ const visibilityLabel = stageHidden ? (japanese ? 'ステージを表示' : 'Show stage') :
40
+ (japanese ? 'ステージを隠す' : 'Hide stage');
41
+ const detached = dockAction?.kind === 'external';
42
+ const popupDocument = detached ? dockAction.mount?.ownerDocument : undefined;
43
+ const popupFullscreen = useStageDocumentFullscreen(popupDocument);
44
+ if (popupDocument) {
45
+ const toggleFullscreen = () => {
46
+ const operation = popupFullscreen ? popupDocument.exitFullscreen() :
47
+ popupDocument.documentElement.requestFullscreen();
48
+ void operation.catch(() => { });
49
+ };
50
+ return React.createElement(StageLayoutMenu, { locale: locale, items: [
51
+ fullscreenItem(locale, popupFullscreen, toggleFullscreen, !popupFullscreen && !popupDocument.fullscreenEnabled),
52
+ { id: 'dock', label: japanese ? 'エディターに戻る' : 'Return to the editor',
53
+ icon: dockIcon(true), separatorBefore: true, onSelect: dockAction.dock }
54
+ ] });
55
+ }
56
+ const dockLabel = stageDockActionLabel(locale, { drawer: stageDrawer, detached, external: dockAction?.external });
57
+ const selectDisplay = action => {
58
+ if (stageHidden)
59
+ setStageVisible(true);
60
+ if (detached)
61
+ dockAction.dock();
62
+ action();
63
+ };
64
+ // Scratch GUI passes small first and full last, with an optional fixed-width preset between them.
65
+ const items = presets.slice(1, -1).map(({ title, isSelected, handleClick, icon }) => ({
66
+ id: title,
67
+ label: title,
68
+ checked: isSelected,
69
+ icon: React.createElement(PresetIcon, { icon: icon }),
70
+ onSelect: () => selectDisplay(handleClick)
71
+ }));
72
+ const enterFullscreen = fullscreenItem(locale, false, () => {
73
+ // Dockview flushes the drawer state when the fullscreen view unmounts it.
74
+ stage?.resetDrawerPresentation();
75
+ selectDisplay(fullscreen.handleClick);
76
+ });
77
+ const openWindow = () => {
78
+ if (stageHidden)
79
+ setStageVisible(true);
80
+ if (stage?.docked)
81
+ stage.commands.close();
82
+ dockAction.undock();
83
+ };
84
+ const drawerPin = stageDrawer && !detached && !stage?.docked ?
85
+ stageDrawerPinItem(locale, stageDrawerPinned, setStageDrawerPinned) : undefined;
86
+ if (launcher && stageDrawer && !detached) {
87
+ const inTab = Boolean(stage?.docked);
88
+ const placement = stagePresentationItems(locale, inTab ? 'tab' : null, {
89
+ window: dockAction?.external && dockAction.kind === 'docked' ? openWindow : undefined,
90
+ tab: !inTab && stage?.commands ? stage.commands.open : undefined,
91
+ drawer: inTab ? () => {
92
+ stage.commands.close();
93
+ // The drawer becomes available after the stage tab has been removed.
94
+ requestAnimationFrame(() => openDrawer?.current?.());
95
+ } : undefined
96
+ }).map(item => drawerPin && item.id === 'drawer' ? drawerPin : item);
97
+ const close = {
98
+ id: 'close-placement',
99
+ label: inTab ? (japanese ? 'タブを閉じる' : 'Close the tab') :
100
+ (japanese ? '引出しを閉じる' : 'Close the drawer'),
101
+ icon: React.createElement("svg", { viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", strokeWidth: "1.4", strokeLinecap: "round", "aria-hidden": "true" },
102
+ React.createElement("path", { d: "m4.5 4.5 7 7m0-7-7 7" })),
103
+ onSelect: inTab ? stage.commands.close : () => closeDrawer?.current?.()
104
+ };
105
+ return React.createElement(StageLayoutMenu, { locale: locale, items: [
106
+ ...placement, { ...enterFullscreen, separatorBefore: true }, ...items, close
107
+ ] });
108
+ }
109
+ if (drawerPin)
110
+ items.push(drawerPin);
111
+ items.push(japanese ? enterFullscreen : { ...enterFullscreen, label: fullscreen.title });
112
+ if (canToggleVisibility)
113
+ items.push({
114
+ id: 'visibility',
115
+ label: visibilityLabel,
116
+ onSelect: () => {
117
+ if (!stageHidden && !stage?.docked && closeDrawer?.current) {
118
+ closeDrawer.current();
119
+ return;
120
+ }
121
+ if (stage?.docked)
122
+ stage.commands.close();
123
+ setStageVisible(stageHidden);
124
+ }
125
+ });
126
+ if (stage?.commands && dockAction?.kind === 'docked')
127
+ items.push({
128
+ id: 'workspace',
129
+ label: stage.docked ? stage.closeLabel : stage.openLabel,
130
+ onSelect: () => {
131
+ if (stage.docked)
132
+ stage.commands.close();
133
+ else {
134
+ if (stageHidden)
135
+ setStageVisible(true);
136
+ stage.commands.open();
137
+ }
138
+ }
139
+ });
140
+ items.push({
141
+ id: 'dock',
142
+ label: dockLabel,
143
+ disabled: !dockAction || dockAction.kind === 'opening',
144
+ separatorBefore: true,
145
+ icon: dockIcon(detached),
146
+ onSelect: detached ? () => {
147
+ if (stageHidden)
148
+ setStageVisible(true);
149
+ dockAction.dock();
150
+ } : openWindow
151
+ });
152
+ return React.createElement(StageLayoutMenu, { locale: locale, items: items, className: stageHidden ? styles.visibleWhenStageHidden : undefined });
153
+ }
154
+ const StageDisplayMenu = layoutFlags.stageDisplayMenu ? DisplayMenu : undefined;
155
+ return { EditorStageFullscreenMenu, StageDisplayMenu };
156
+ }
@@ -0,0 +1,29 @@
1
+ import React from 'react';
2
+ import { createStageSurface } from './stage-surface.ts';
3
+ export declare function createStagePanel({ WindowLayoutContext, StageDisplayMenuContext, BasicPanel, EdgeDrawer, EditorStageFullscreenMenu, externalHost, decorateSurface, layoutFlags, stageCanUndock, styles }: {
4
+ WindowLayoutContext: React.Context<any>;
5
+ StageDisplayMenuContext: React.Context<any>;
6
+ BasicPanel: Parameters<typeof createStageSurface>[1]['Panel'];
7
+ EdgeDrawer: Parameters<typeof createStageSurface>[1]['EdgeDrawer'];
8
+ EditorStageFullscreenMenu: React.ComponentType<{
9
+ header: HTMLElement;
10
+ locale: string;
11
+ }>;
12
+ externalHost: Parameters<ReturnType<typeof createStageSurface>>[0]['externalHost'];
13
+ decorateSurface(document: Document): () => void;
14
+ layoutFlags: {
15
+ standardLayout: boolean;
16
+ stageDisplayMenu: boolean;
17
+ };
18
+ stageCanUndock: boolean;
19
+ styles: Record<string, string>;
20
+ }): {
21
+ StagePanel: ({ aspect, width, defaultWidth, render, renderHeader, isFullScreen }: {
22
+ aspect: any;
23
+ width: any;
24
+ defaultWidth: any;
25
+ render: any;
26
+ renderHeader: any;
27
+ isFullScreen: any;
28
+ }) => React.JSX.Element;
29
+ };
@@ -0,0 +1,105 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ import React from 'react';
3
+ import { createStageSurface, StageResizeHandle } from "./stage-surface.js";
4
+ export function createStagePanel({ WindowLayoutContext, StageDisplayMenuContext, BasicPanel, EdgeDrawer, EditorStageFullscreenMenu, externalHost, decorateSurface, layoutFlags, stageCanUndock, styles }) {
5
+ const StageSurface = createStageSurface(React, {
6
+ context: WindowLayoutContext, EdgeDrawer: EdgeDrawer, Panel: BasicPanel
7
+ });
8
+ function StageViewport({ aspect, width, defaultWidth, floating, workspace, useNativeKeyboard, render, renderHeader, isFullScreen, inputDocument }) {
9
+ const { stageDrawer, stageHidden, stageResize, locale } = React.useContext(WindowLayoutContext);
10
+ const fit = floating || workspace;
11
+ const resizable = !fit && !isFullScreen && stageResize;
12
+ const resizeLabel = /^ja(?:-|$)/i.test(locale) ? 'ステージのサイズを変更' : 'Resize stage';
13
+ const viewport = React.useRef(null);
14
+ const header = React.useRef(null);
15
+ const [fullscreenHeader, setFullscreenHeader] = React.useState();
16
+ const [floatingWidth, setFloatingWidth] = React.useState(null);
17
+ const [externalBounds, setExternalBounds] = React.useState(Boolean(inputDocument));
18
+ React.useLayoutEffect(() => {
19
+ setFullscreenHeader(isFullScreen && layoutFlags.stageDisplayMenu ? header.current ?? undefined : undefined);
20
+ }, [isFullScreen]);
21
+ React.useLayoutEffect(() => {
22
+ if (inputDocument) {
23
+ setExternalBounds(true);
24
+ return;
25
+ }
26
+ if (!externalBounds)
27
+ return;
28
+ // Recalculate Stage bounds after the docking portal has moved back into the editor.
29
+ const frame = requestAnimationFrame(() => setExternalBounds(false));
30
+ return () => cancelAnimationFrame(frame);
31
+ }, [inputDocument, externalBounds]);
32
+ React.useLayoutEffect(() => {
33
+ if (!fit)
34
+ return;
35
+ const node = viewport.current;
36
+ const measure = () => {
37
+ const height = node.clientHeight - (header.current?.offsetHeight ?? 0) - 8;
38
+ if (node.clientWidth < 12 || height < 1)
39
+ return;
40
+ // A tab or separate window is the stage's own space, so the stage grows and shrinks with it.
41
+ setFloatingWidth(Math.max(1, Math.floor(Math.min(node.clientWidth - 12, height * aspect))));
42
+ };
43
+ const observer = new (inputDocument?.defaultView.ResizeObserver ?? ResizeObserver)(measure);
44
+ measure();
45
+ observer.observe(node);
46
+ if (header.current)
47
+ observer.observe(header.current);
48
+ return () => observer.disconnect();
49
+ }, [aspect, fit, inputDocument]);
50
+ const displayWidth = fit ? floatingWidth ?? Math.min(240, width ?? defaultWidth) : width;
51
+ const canvas = render(displayWidth, Boolean(stageDrawer || fit || externalBounds || resizable), inputDocument);
52
+ const resizeHandles = resizable && (stageDrawer ? ['left', 'right', 'top', 'bottom'] : ['left', 'bottom', 'corner'])
53
+ .map(edge => React.createElement(StageResizeHandle, { key: edge, edge, aspect, width, limits: stageResize, label: resizeLabel, className: styles.stageResizeHandle, drawer: Boolean(stageDrawer) }));
54
+ return React.createElement("div", { className: styles.stageViewport, "data-floating": fit, "data-stage-hidden": stageHidden || undefined, "data-resizable": resizable ? true : undefined, "data-focusable": stageCanUndock || undefined, ref: viewport, tabIndex: stageCanUndock ? -1 : undefined, onClick: event => {
55
+ const node = event.currentTarget;
56
+ const target = event.target;
57
+ if (target.closest('[role="menu"]'))
58
+ return;
59
+ if (useNativeKeyboard && !inputDocument && target.matches('canvas')) {
60
+ // The GUI routes project key presses from the document body.
61
+ node.ownerDocument.activeElement?.blur();
62
+ return;
63
+ }
64
+ if (stageCanUndock && !node.contains(node.ownerDocument.activeElement))
65
+ node.focus({ preventScroll: true });
66
+ } }, renderHeader ? React.createElement("div", { className: styles.stageFrame, "data-fullscreen": isFullScreen || undefined, "data-plus-stage-frame": "" },
67
+ React.createElement("div", { className: styles.stageHeader, "data-stage-drawer-handle": "", ref: header },
68
+ renderHeader(displayWidth),
69
+ isFullScreen && fullscreenHeader && React.createElement(EditorStageFullscreenMenu, { header: fullscreenHeader, locale: locale })),
70
+ React.createElement("div", { className: styles.stageCanvas },
71
+ canvas,
72
+ !stageDrawer && resizeHandles),
73
+ stageDrawer && resizeHandles) : React.createElement("div", { className: styles.stageCanvas },
74
+ canvas,
75
+ resizeHandles));
76
+ }
77
+ function AppStagePanel({ aspect, width, defaultWidth, render, renderHeader, isFullScreen }) {
78
+ const { stageActionMount } = React.useContext(WindowLayoutContext);
79
+ const menu = React.useContext(StageDisplayMenuContext);
80
+ const stage = menu?.stage;
81
+ const suspend = stage?.suspend;
82
+ const surface = stage?.surface;
83
+ const resizeStage = menu?.resizeStage;
84
+ React.useLayoutEffect(() => {
85
+ suspend?.(Boolean(isFullScreen));
86
+ }, [suspend, isFullScreen]);
87
+ React.useLayoutEffect(() => {
88
+ if (!surface)
89
+ return;
90
+ // The native update can run while the drawer anchor is still hidden.
91
+ const resize = () => resizeStage(surface);
92
+ const observer = new ResizeObserver(resize);
93
+ observer.observe(surface);
94
+ const frame = requestAnimationFrame(resize);
95
+ return () => {
96
+ observer.disconnect();
97
+ cancelAnimationFrame(frame);
98
+ };
99
+ }, [surface, resizeStage, stage?.docked, isFullScreen]);
100
+ return React.createElement(StageSurface, { placement: stage, externalHost: externalHost, decorate: decorateSurface, launcher: menu?.launcher, dockAction: menu?.dockAction, editorFullscreen: isFullScreen, openDrawerRef: menu?.openDrawer, closeDrawerRef: menu?.closeDrawer, actionMount: stageActionMount ?? null, onDockActionChange: layoutFlags.stageDisplayMenu ? menu?.setDockAction : undefined, dockHeight: Math.round((width ?? defaultWidth) / aspect) + (renderHeader ? 44 : 0), render: (floating, mount) => React.createElement(StageViewport, { aspect, width, defaultWidth, floating, render, renderHeader, isFullScreen, workspace: Boolean(stage?.docked && !isFullScreen), useNativeKeyboard: Boolean(stage), inputDocument: mount?.ownerDocument }) });
101
+ }
102
+ const StagePanel = stageCanUndock ? AppStagePanel :
103
+ (layoutFlags.standardLayout ? StageViewport : undefined);
104
+ return { StagePanel };
105
+ }