@kubohiroya/turbowarp-plus-editor-workbench 0.14.0 → 0.16.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 (53) hide show
  1. package/NOTICE +26 -0
  2. package/README.ja.md +22 -0
  3. package/README.md +22 -0
  4. package/dist/backpack-script.d.ts +2 -0
  5. package/dist/backpack-script.js +23 -0
  6. package/dist/backpack.d.ts +60 -0
  7. package/dist/backpack.js +226 -0
  8. package/dist/browser-tab-title.d.ts +2 -0
  9. package/dist/browser-tab-title.js +5 -0
  10. package/dist/busy-cursor.d.ts +22 -0
  11. package/dist/busy-cursor.js +107 -0
  12. package/dist/edit-menu.d.ts +57 -0
  13. package/dist/edit-menu.js +99 -0
  14. package/dist/info-menu.d.ts +39 -0
  15. package/dist/info-menu.js +157 -0
  16. package/dist/project-file-dialogs.d.ts +70 -0
  17. package/dist/project-file-dialogs.js +625 -0
  18. package/dist/project-file-menu.d.ts +43 -0
  19. package/dist/project-file-menu.js +90 -0
  20. package/dist/project-load-progress-view.d.ts +6 -0
  21. package/dist/project-load-progress-view.js +66 -0
  22. package/dist/project-load-progress.d.ts +26 -0
  23. package/dist/project-load-progress.js +104 -0
  24. package/dist/project-search-box.d.ts +43 -0
  25. package/dist/project-search-box.js +437 -0
  26. package/dist/project-size-approval.d.ts +10 -0
  27. package/dist/project-size-approval.js +64 -0
  28. package/dist/stage-controls-view.d.ts +45 -0
  29. package/dist/stage-controls-view.js +127 -0
  30. package/dist/stage-controls.d.ts +98 -0
  31. package/dist/stage-controls.js +110 -0
  32. package/package.json +97 -28
  33. package/src/backpack-script.ts +21 -0
  34. package/src/backpack.tsx +260 -0
  35. package/src/browser-tab-title.ts +6 -0
  36. package/src/busy-cursor.ts +108 -0
  37. package/src/edit-menu.css +42 -0
  38. package/src/edit-menu.tsx +139 -0
  39. package/src/info-menu.css +172 -0
  40. package/src/info-menu.tsx +221 -0
  41. package/src/project-file-dialogs.ts +654 -0
  42. package/src/project-file-menu.css +94 -0
  43. package/src/project-file-menu.tsx +137 -0
  44. package/src/project-load-progress-view.tsx +75 -0
  45. package/src/project-load-progress.css +57 -0
  46. package/src/project-load-progress.ts +118 -0
  47. package/src/project-search-box.tsx +469 -0
  48. package/src/project-search.css +116 -0
  49. package/src/project-size-approval.ts +74 -0
  50. package/src/sprite-layout-menu.css +2 -1
  51. package/src/stage-controls-view.tsx +178 -0
  52. package/src/stage-controls.css +192 -0
  53. package/src/stage-controls.ts +124 -0
@@ -0,0 +1,260 @@
1
+ import React from 'react';
2
+ import {createPortal} from 'react-dom';
3
+ import {createSurface, pendingSurfaceEdits, recordSurface} from '@kubohiroya/turbowarp-plus-editor-windows/surfaces';
4
+ import type {SurfaceRecovery, SurfaceState} from '@kubohiroya/turbowarp-plus-editor-windows/surfaces';
5
+ import {createTransferSession, transferMime} from '@kubohiroya/turbowarp-plus-editor-windows/transfer';
6
+ import {jsonDataUrl, readBackpackScript} from './backpack-script.js';
7
+
8
+ const kind = 'backpack-script';
9
+ interface BackpackTarget {
10
+ mount: HTMLElement;
11
+ presentation?: 'internal' | 'external';
12
+ }
13
+ interface BackpackRequest {
14
+ presentation: 'internal';
15
+ id: string;
16
+ title: string;
17
+ rememberPlacement: boolean;
18
+ layer: string;
19
+ openExternal?: () => void;
20
+ }
21
+
22
+ const docked: Extract<SurfaceState<BackpackTarget>, {kind: 'docked'}> = {kind: 'docked'};
23
+ const messages = {
24
+ en: {
25
+ undock: 'Open Backpack in a browser window',
26
+ detach: 'Undock Backpack',
27
+ reopen: 'Reopen Backpack in another window',
28
+ title: 'Backpack',
29
+ restore: 'Return here',
30
+ internal: 'Move into the editor',
31
+ dock: 'Dock Backpack',
32
+ drag: 'Drag script to code',
33
+ blocked: 'Could not open Backpack window',
34
+ copyFailed: 'Could not copy Backpack script'
35
+ },
36
+ ja: {
37
+ undock: 'バックパックをブラウザーの別ウィンドウで開く',
38
+ detach: 'バックパックを別画面で開く',
39
+ reopen: 'バックパックを別画面で開き直す',
40
+ title: 'バックパック',
41
+ restore: 'ここに戻す',
42
+ internal: 'アプリ内に戻す',
43
+ dock: 'バックパックを元の位置に戻す',
44
+ drag: 'スクリプトをコードへドラッグ',
45
+ blocked: 'バックパックのウィンドウを開けませんでした',
46
+ copyFailed: 'バックパックのスクリプトをコピーできませんでした'
47
+ }
48
+ };
49
+
50
+ // The GUI uses React 16, which has no hook for external stores (added in React 18).
51
+ function useLostWindow(recovery: SurfaceRecovery | null | undefined, id: string) {
52
+ const [lost, setLost] = React.useState(() => Boolean(recovery?.isLost(id)));
53
+ React.useEffect(() => {
54
+ if (!recovery) return;
55
+ const update = () => setLost(recovery.isLost(id));
56
+ update();
57
+ return recovery.subscribe(update);
58
+ }, [recovery, id]);
59
+ return Boolean(recovery) && lost;
60
+ }
61
+
62
+ export function createBackpackIntegration({host, importScript, importScriptWithReceipt, decorateSurface, readScript = readBackpackScript,
63
+ recovery = undefined as SurfaceRecovery | undefined, pendingEdits = pendingSurfaceEdits}) {
64
+ const sessions = new WeakMap();
65
+
66
+ function BackpackSurface({vm, children, showUndock, locale, internalHost, openLabel, renderLaunchButton, launchClassName, onDetachedChange, renderPopupTools, internalLayer}) {
67
+ const labels = /^ja(?:-|$)/i.test(locale) ? messages.ja : messages.en;
68
+ const copyFailed = React.useRef(labels.copyFailed);
69
+ copyFailed.current = labels.copyFailed;
70
+ const [display, setDisplay] = React.useState<{vm: object; state: SurfaceState<BackpackTarget>}>({vm, state: docked});
71
+ const state = display.vm === vm ? display.state : docked;
72
+ const detached = state.kind === 'external';
73
+ React.useLayoutEffect(() => {onDetachedChange?.(detached);}, [onDetachedChange, detached]);
74
+ const scope = React.useRef(null);
75
+ const mounted = React.useRef(true);
76
+ const launchButton = React.useRef(null);
77
+ const fallback = React.useRef<BackpackRequest | null>(null);
78
+ const surface = React.useMemo(() => createSurface<BackpackRequest | undefined, BackpackTarget>({
79
+ open: request => request?.presentation === 'internal' ? internalHost?.open(request) : host?.open()
80
+ }, next => {
81
+ if (host) recordSurface(recovery, 'backpack', next, target => target.presentation !== 'internal');
82
+ if (next.kind === 'external') {
83
+ fallback.current = null;
84
+ const id = crypto.randomUUID();
85
+ const cleanup = next.target.presentation === 'internal' ? () => {} :
86
+ decorateSurface(next.target.mount.ownerDocument);
87
+ const transfer = createTransferSession(id);
88
+ scope.current = {id, transfer, cleanup, copyFailed,
89
+ unregister: pendingEdits.register(() => transfer.settled())};
90
+ sessions.set(vm, scope.current);
91
+ } else if (next.kind === 'docked' && scope.current) {
92
+ const active = scope.current;
93
+ scope.current = null;
94
+ if (sessions.get(vm) === active) sessions.delete(vm);
95
+ // Scripts already dropped from the closing window still reach the code area.
96
+ void active.transfer.retire().finally(active.unregister);
97
+ active.cleanup();
98
+ }
99
+ if (next.kind === 'docked' && fallback.current) {
100
+ const retry = fallback.current;
101
+ fallback.current = null;
102
+ if (next.reason === 'blocked' || next.reason === 'failed') {
103
+ surface.undock(retry);
104
+ return;
105
+ }
106
+ }
107
+ if (mounted.current) setDisplay({vm, state: next});
108
+ }), [vm, internalHost]);
109
+ const lost = useLostWindow(host ? recovery : null, 'backpack');
110
+ React.useLayoutEffect(() => {
111
+ mounted.current = true;
112
+ return () => {
113
+ mounted.current = false;
114
+ fallback.current = null;
115
+ surface.dock();
116
+ };
117
+ }, [surface]);
118
+ React.useLayoutEffect(() => {
119
+ if (!internalHost || !showUndock || state.kind !== 'docked' || !state.reason) return;
120
+ const frame = requestAnimationFrame(() => launchButton.current?.querySelector('button')?.focus({preventScroll: true}));
121
+ return () => cancelAnimationFrame(frame);
122
+ }, [internalHost, showUndock, state]);
123
+
124
+ function internalRequest() {
125
+ const request: BackpackRequest = {
126
+ presentation: 'internal', id: 'backpack', title: labels.title, rememberPlacement: true, layer: internalLayer
127
+ };
128
+ if (host) request.openExternal = () => {
129
+ surface.dock();
130
+ fallback.current = request;
131
+ surface.undock(undefined);
132
+ };
133
+ return request;
134
+ }
135
+
136
+ function moveInternal() {
137
+ surface.dock();
138
+ surface.undock(internalRequest());
139
+ }
140
+
141
+ const handle = item => typeof item.bodyUrl === 'string' && item.bodyUrl.startsWith(jsonDataUrl) ? (
142
+ <button type="button" draggable data-testid="backpack-script-drag"
143
+ style={{cursor: 'grab', flexShrink: 0}}
144
+ onDragStart={event => {
145
+ const active = scope.current;
146
+ if (!active || !event.dataTransfer) return;
147
+ const reference = active.transfer.offer(kind, signal => readScript(item.bodyUrl, signal));
148
+ event.dataTransfer.effectAllowed = 'copy';
149
+ event.dataTransfer.setData(transferMime, JSON.stringify(reference));
150
+ }}>
151
+ {labels.drag}
152
+ </button>
153
+ ) : null;
154
+ const dock = (
155
+ <button type="button" onClick={() => surface.dock()}>{labels.dock}</button>
156
+ );
157
+ if (state.kind === 'external') {
158
+ const internal = state.target.presentation === 'internal';
159
+ return (
160
+ <>
161
+ {internalHost ? (
162
+ <div style={{display: 'grid', placeItems: 'center', minHeight: 44}}>
163
+ <button type="button" onClick={() => surface.dock()}>{labels.restore}</button>
164
+ </div>
165
+ ) : dock}
166
+ {createPortal(<>
167
+ {!internal && (renderPopupTools ? renderPopupTools({mount: state.target.mount, onDock: surface.dock}) :
168
+ <>{dock}{internalHost && <button type="button" onClick={moveInternal}>
169
+ {labels.internal}
170
+ </button>}</>)}
171
+ {React.cloneElement(children, {renderScriptDragHandle: handle})}
172
+ </>,
173
+ state.target.mount)}
174
+ </>
175
+ );
176
+ }
177
+ // A backpack that was external when the editor closed reopens there on the next click.
178
+ const launch = {
179
+ disabled: state.kind === 'opening',
180
+ label: lost ? labels.reopen : internalHost ? labels.detach : (openLabel ?? labels.undock),
181
+ onOpen: () => surface.undock(internalHost && !lost ? internalRequest() : undefined)
182
+ };
183
+ return (
184
+ <>
185
+ {showUndock && (
186
+ <div className={launchClassName}>
187
+ <span ref={launchButton}>{renderLaunchButton ? renderLaunchButton(launch) :
188
+ <button type="button" disabled={launch.disabled} onClick={launch.onOpen}>{launch.label}</button>}
189
+ </span>
190
+ </div>
191
+ )}
192
+ {children}
193
+ {showUndock && state.kind === 'docked' && (state.reason === 'blocked' || state.reason === 'failed') &&
194
+ <span role="status">{labels.blocked}</span>}
195
+ </>
196
+ );
197
+ }
198
+
199
+ async function receiveBackpackDrop({vm, target, raw, position, canUse, onError, receipt,
200
+ commit = apply => apply(), accept = (_script: Awaited<ReturnType<typeof readBackpackScript>>) => true}) {
201
+ const active = sessions.get(vm);
202
+ if (!active) return;
203
+ // The drop is claimed while its window is open. It may finish after the window closes,
204
+ // but not after the destination view or target is gone.
205
+ const canCommit = () => canUse() && vm.runtime.getTargetById(target.id) === target;
206
+ const result = await active.transfer.receive(raw, {session: active.id, id: target.id}, async (_, script) => {
207
+ if (!accept(script)) throw new Error('Unsupported script for this workspace');
208
+ return commit(async () => {
209
+ if (!canCommit()) return false;
210
+ if (receipt) {
211
+ const imported = await importScriptWithReceipt(vm, target, script, {
212
+ position, canCommit, beforeCommit: receipt.beforeCommit, onCommitted: receipt.onCommitted
213
+ });
214
+ return imported !== null;
215
+ }
216
+ await importScript(vm, target, script, {position});
217
+ return true;
218
+ });
219
+ });
220
+ if (result === 'failed' && canUse()) onError?.(new Error(active.copyFailed.current));
221
+ }
222
+
223
+ function attachBackpackDrop({vm, workspace, canUse, onError, dropElement, destination}) {
224
+ const svg = workspace.getParentSvg();
225
+ const node = dropElement ?? svg;
226
+ let disposed = false;
227
+ const allowed = event => sessions.has(vm) && canUse() &&
228
+ Array.from(event.dataTransfer?.types ?? []).includes(transferMime);
229
+ function over(event) {
230
+ if (!allowed(event)) return;
231
+ event.preventDefault();
232
+ event.dataTransfer.dropEffect = 'copy';
233
+ }
234
+ function drop(event) {
235
+ if (!allowed(event)) return;
236
+ event.preventDefault();
237
+ const target = destination?.target ?? vm.editingTarget;
238
+ const raw = event.dataTransfer.getData(transferMime);
239
+ const matrix = workspace.getCanvas().getScreenCTM();
240
+ if (!target || !matrix) return;
241
+ const point = svg.createSVGPoint();
242
+ point.x = event.clientX;
243
+ point.y = event.clientY;
244
+ const {x, y} = point.matrixTransform(matrix.inverse());
245
+ void receiveBackpackDrop({
246
+ vm, target, raw, position: {x, y}, onError, receipt: destination,
247
+ canUse: destination ? destination.canCommit : () => !disposed
248
+ });
249
+ }
250
+ node.addEventListener('dragover', over);
251
+ node.addEventListener('drop', drop);
252
+ return {dispose() {
253
+ disposed = true;
254
+ node.removeEventListener('dragover', over);
255
+ node.removeEventListener('drop', drop);
256
+ }};
257
+ }
258
+
259
+ return {BackpackSurface, attachBackpackDrop, receiveBackpackDrop};
260
+ }
@@ -0,0 +1,6 @@
1
+ export const EDITOR_TAB_NAME = 'TurboWarp Plus Editor';
2
+
3
+ export function updateBrowserTabTitle(title?: string) {
4
+ const name = title?.trim();
5
+ document.title = name ? `${name} - ${EDITOR_TAB_NAME}` : EDITOR_TAB_NAME;
6
+ }
@@ -0,0 +1,108 @@
1
+ const active = new WeakMap<Document, {users: number; style: HTMLStyleElement}>();
2
+ const inputWaits = new WeakMap<Document, number>();
3
+
4
+ function holdCursor(document: Document) {
5
+ let state = active.get(document);
6
+ if (!state) {
7
+ const style = document.createElement('style');
8
+ style.dataset.twPlusWaitCursor = '';
9
+ style.textContent = ':root, :root body, :root body * { cursor: wait !important; }';
10
+ if (inputWaits.has(document)) style.media = 'not all';
11
+ document.head.append(style);
12
+ state = {users: 0, style};
13
+ active.set(document, state);
14
+ }
15
+ state.users++;
16
+ return () => {
17
+ if (--state.users) return;
18
+ state.style.remove();
19
+ active.delete(document);
20
+ };
21
+ }
22
+
23
+ function afterPaint(document: Document) {
24
+ const view = document.defaultView;
25
+ if (!view?.requestAnimationFrame || document.hidden) return Promise.resolve();
26
+ // The first callback still runs before the cursor change can be painted.
27
+ return new Promise<void>(resolve => {
28
+ let frame = view.requestAnimationFrame(() => {
29
+ frame = view.requestAnimationFrame(finish);
30
+ });
31
+ const timeout = view.setTimeout(finish, 100);
32
+ function finish() {
33
+ view.cancelAnimationFrame(frame);
34
+ view.clearTimeout(timeout);
35
+ resolve();
36
+ }
37
+ });
38
+ }
39
+
40
+ /** Give the browser a frame before starting work that may block its main thread. */
41
+ export async function withWaitCursor<T>(documents: Iterable<Document>, run: () => T): Promise<Awaited<T>> {
42
+ const visible = [...new Set(documents)].filter(document => document?.head && document.defaultView && !document.defaultView.closed);
43
+ const release = visible.map(holdCursor);
44
+ try {
45
+ await Promise.all(visible.map(afterPaint));
46
+ return await run();
47
+ } finally {
48
+ release.forEach(done => done());
49
+ }
50
+ }
51
+
52
+ /** Temporarily restore the normal cursor while an operation needs an answer. */
53
+ export async function withoutWaitCursor<T>(document: Document | undefined, ask: () => T): Promise<Awaited<T>> {
54
+ if (!document) return await ask();
55
+ inputWaits.set(document, (inputWaits.get(document) ?? 0) + 1);
56
+ const waiting = active.get(document);
57
+ if (waiting) waiting.style.media = 'not all';
58
+ try {
59
+ return await ask();
60
+ } finally {
61
+ const remaining = inputWaits.get(document) - 1;
62
+ if (remaining) inputWaits.set(document, remaining);
63
+ else {
64
+ inputWaits.delete(document);
65
+ const resumed = active.get(document);
66
+ if (resumed) {
67
+ resumed.style.media = '';
68
+ await afterPaint(document);
69
+ }
70
+ }
71
+ }
72
+ }
73
+
74
+ interface Target {
75
+ id: string;
76
+ blocks?: {_blocks?: Record<string, unknown>};
77
+ }
78
+ interface TargetSwitchVM {
79
+ editingTarget?: Target;
80
+ runtime: {getTargetById(id: string): Target | undefined; getTargetForStage(): Target | undefined};
81
+ }
82
+
83
+ // VM target changes rebuild the Blockly workspace synchronously. Large workspaces
84
+ // need a paint before that rebuild. Smaller switches stay in the input event.
85
+ const largeWorkspace = (target: Target | undefined) => Object.keys(target?.blocks?._blocks ?? {}).length >= 200;
86
+
87
+ export function createTargetSwitchFeedback(vm: TargetSwitchVM, document: Document) {
88
+ let request = 0;
89
+ let running: Target | undefined;
90
+ return {
91
+ cancel() { request++; },
92
+ select(id: string | undefined, run: () => void, source = document) {
93
+ const token = ++request;
94
+ const previous = vm.editingTarget;
95
+ const target = id === undefined ? vm.runtime.getTargetForStage() : vm.runtime.getTargetById(id);
96
+ if (!target || target === previous || target === running || !largeWorkspace(target)) {
97
+ run();
98
+ return;
99
+ }
100
+ void withWaitCursor([source, document], async () => {
101
+ if (request !== token || vm.editingTarget !== previous || vm.runtime.getTargetById(target.id) !== target) return;
102
+ running = target;
103
+ try { run(); } finally { running = undefined; }
104
+ await afterPaint(document);
105
+ }).catch(error => globalThis.reportError(error));
106
+ }
107
+ };
108
+ }
@@ -0,0 +1,42 @@
1
+ ul:has(> li > .tw-edit-menu__command) {
2
+ background-color: var(--popover-background, var(--ui-white, #fff));
3
+ color: var(--text-primary);
4
+ }
5
+
6
+ .tw-edit-menu__command,
7
+ .tw-edit-menu__restore {
8
+ display: flex;
9
+ align-items: center;
10
+ gap: 0.5rem;
11
+ }
12
+
13
+ .tw-edit-menu__command {
14
+ width: calc(100% + 20px);
15
+ margin-inline: -10px;
16
+ padding: 0 10px;
17
+ border: 0;
18
+ background: transparent;
19
+ color: inherit;
20
+ font: inherit;
21
+ line-height: inherit;
22
+ text-align: start;
23
+ cursor: inherit;
24
+ }
25
+
26
+ .tw-edit-menu__command > svg,
27
+ .tw-edit-menu__restore > svg {
28
+ flex: none;
29
+ margin-inline-end: 0;
30
+ }
31
+
32
+ .tw-edit-menu__shortcut {
33
+ margin-inline-start: auto;
34
+ padding-inline-start: 1rem;
35
+ font: inherit;
36
+ font-weight: normal;
37
+ }
38
+
39
+ .tw-edit-menu__command:disabled {
40
+ opacity: 0.5;
41
+ cursor: default;
42
+ }
@@ -0,0 +1,139 @@
1
+ import React from 'react';
2
+ import {isMacPlatform, projectReplaceOpener, projectReplaceShortcut} from '@kubohiroya/turbowarp-plus-editor-project-model/project-search-connections';
3
+ import type {SearchProject} from '@kubohiroya/turbowarp-plus-editor-project-model/project-search';
4
+
5
+ interface Workspace {
6
+ options: {readOnly: boolean};
7
+ getParentSvg(): SVGElement;
8
+ hasUndoStack(): boolean;
9
+ hasRedoStack(): boolean;
10
+ isDragging(): boolean;
11
+ isVisible(): boolean;
12
+ targetWorkspace?: Workspace;
13
+ isFlyout: boolean;
14
+ }
15
+
16
+ interface WorkspaceContext {
17
+ vm: object;
18
+ workspace: Workspace;
19
+ canUse(): boolean;
20
+ ScratchBlocks: {
21
+ getMainWorkspace(): Workspace;
22
+ selected?: {workspace: Workspace; isDeletable(): boolean; isMovable(): boolean};
23
+ clipboardXml_?: unknown;
24
+ clipboardSource_?: Workspace;
25
+ onKeyDown_(event: Pick<KeyboardEvent, 'target' | 'keyCode' | 'ctrlKey' | 'shiftKey' | 'preventDefault'>): void;
26
+ };
27
+ }
28
+
29
+ interface MenuProps {
30
+ vm: {runtime?: SearchProject};
31
+ locale: string;
32
+ MenuItem: React.ComponentType<{className?: string; children: React.ReactNode}>;
33
+ MenuSection: React.ComponentType<{children: React.ReactNode}>;
34
+ renderIcon(command: Command | 'restoreDeletion'): React.ReactNode;
35
+ getRearrangement?(): {canArrange(): boolean; open(locale: string): void} | undefined;
36
+ onRequestClose(): void;
37
+ }
38
+
39
+ const workspaces = new WeakMap<object, WorkspaceContext>();
40
+
41
+ export function attachEditMenuWorkspace(context: WorkspaceContext) {
42
+ workspaces.set(context.vm, context);
43
+ return {dispose() {
44
+ if (workspaces.get(context.vm) === context) workspaces.delete(context.vm);
45
+ }};
46
+ }
47
+
48
+ const groups = [
49
+ [['undo', 'Undo', '元に戻す'], ['redo', 'Redo', '繰り返し']],
50
+ [['cut', 'Cut', '切り取り'], ['copy', 'Copy', 'コピー'], ['paste', 'Paste', '貼り付け']],
51
+ [['findAndReplace', 'Find and Replace', '検索と置換'],
52
+ ['cleanup', 'Rearrange Code Blocks', 'コードブロックの再配置']]
53
+ ] as const;
54
+
55
+ type Command = (typeof groups)[number][number][0];
56
+ const shortcutKeys = {undo: 'Z', redo: 'Y', cut: 'X', copy: 'C', paste: 'V'};
57
+
58
+ function shortcutFor(command: Command, mac: boolean) {
59
+ if (command === 'cleanup') return;
60
+ if (command === 'findAndReplace') {
61
+ const {label, macLabel, keys, macKeys} = projectReplaceShortcut;
62
+ return {label: mac ? macLabel : label, keys: mac ? macKeys : keys};
63
+ }
64
+ if (mac && command === 'redo') return {label: '⇧⌘Z', keys: 'Meta+Shift+Z'};
65
+ const key = shortcutKeys[command];
66
+ return mac ? {label: `⌘${key}`, keys: `Meta+${key}`} : {label: `Ctrl+${key}`, keys: `Control+${key}`};
67
+ }
68
+
69
+ function canRun(context: WorkspaceContext | undefined, command: Exclude<Command, 'findAndReplace' | 'cleanup'>): boolean {
70
+ if (!context?.canUse()) return false;
71
+ const {workspace, ScratchBlocks} = context;
72
+ if (ScratchBlocks.getMainWorkspace() !== workspace || workspace.options.readOnly ||
73
+ !workspace.isVisible() || workspace.isDragging() || workspace.getParentSvg().closest('[inert]')) return false;
74
+
75
+ if (command === 'undo') return workspace.hasUndoStack();
76
+ if (command === 'redo') return workspace.hasRedoStack();
77
+ if (command === 'paste') {
78
+ const source = ScratchBlocks.clipboardSource_;
79
+ return Boolean(ScratchBlocks.clipboardXml_) && (source?.isFlyout ? source.targetWorkspace : source) === workspace;
80
+ }
81
+
82
+ const block = ScratchBlocks.selected;
83
+ return Boolean(block?.isDeletable() && block.isMovable() && (block.workspace === workspace ||
84
+ (command === 'copy' && block.workspace.isFlyout && block.workspace.targetWorkspace === workspace)));
85
+ }
86
+
87
+ export function renderEditMenu(props: MenuProps) {
88
+ return <EditMenu {...props} />;
89
+ }
90
+
91
+ export function renderEditMenuRestore(label: React.ReactNode, renderIcon: MenuProps['renderIcon']) {
92
+ return <span className="tw-edit-menu__restore">{renderIcon('restoreDeletion')}{label}</span>;
93
+ }
94
+
95
+ function EditMenu({vm, locale, MenuItem, MenuSection, renderIcon, onRequestClose, getRearrangement}: MenuProps) {
96
+ const japanese = /^ja(?:-|$)/i.test(locale);
97
+ const mac = isMacPlatform();
98
+ const context = workspaces.get(vm);
99
+ const openReplace = projectReplaceOpener(vm.runtime);
100
+ const rearrangement = getRearrangement?.();
101
+ return <>{groups.map(group => <MenuSection key={group[0][0]}>
102
+ {group.map(([command, english, translated]) => {
103
+ if (command === 'cleanup' && !getRearrangement) return null;
104
+ const shortcut = shortcutFor(command, mac);
105
+ const enabled = command === 'cleanup' ? rearrangement?.canArrange() :
106
+ command === 'findAndReplace' ? Boolean(openReplace) : canRun(context, command);
107
+ return <MenuItem key={command}>
108
+ <button className="tw-edit-menu__command" type="button"
109
+ disabled={!enabled}
110
+ aria-keyshortcuts={shortcut?.keys} onClick={event => {
111
+ if (command === 'cleanup') {
112
+ const current = getRearrangement?.();
113
+ if (!current?.canArrange()) return;
114
+ onRequestClose();
115
+ current.open(locale);
116
+ return;
117
+ }
118
+ if (command === 'findAndReplace') {
119
+ if (!openReplace) return;
120
+ onRequestClose();
121
+ openReplace();
122
+ return;
123
+ }
124
+ const current = workspaces.get(vm);
125
+ if (!canRun(current, command)) return;
126
+ // Keep cut, copy and paste on the same ScratchBlocks clipboard.
127
+ current.ScratchBlocks.onKeyDown_({target: event.currentTarget,
128
+ keyCode: shortcutKeys[command].charCodeAt(0), ctrlKey: true, shiftKey: false,
129
+ preventDefault: () => event.preventDefault()});
130
+ onRequestClose();
131
+ }}>
132
+ {renderIcon(command)}
133
+ <span>{japanese ? translated : english}</span>
134
+ {shortcut && <kbd className="tw-edit-menu__shortcut" aria-hidden="true">{shortcut.label}</kbd>}
135
+ </button>
136
+ </MenuItem>;
137
+ })}
138
+ </MenuSection>)}</>;
139
+ }