@kubohiroya/turbowarp-plus-editor-workbench 0.15.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 (52) 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/stage-controls-view.tsx +178 -0
  51. package/src/stage-controls.css +192 -0
  52. package/src/stage-controls.ts +124 -0
package/NOTICE ADDED
@@ -0,0 +1,26 @@
1
+ TurboWarp Plus Editor Workbench is licensed under MPL-2.0. See LICENSE.
2
+
3
+ The Mark GitHub and Law icons in src/info-menu.tsx are from GitHub Octicons
4
+ (https://github.com/primer/octicons).
5
+
6
+ MIT License
7
+
8
+ Copyright (c) 2026 GitHub Inc.
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
package/README.ja.md CHANGED
@@ -95,6 +95,28 @@ workspaceLayout: {
95
95
  - すべてのレイアウトを消すには、ブラウザーの開発者ツールで `twPlusWorkspaceLayout` データベースを削除する(Chrome では Application の IndexedDB)。コンソールで `indexedDB.deleteDatabase('twPlusWorkspaceLayout')` を実行してもよい。
96
96
  - 以前の版は `localStorage`(`twPlusDockviewLayout` と `twPlusDockviewLayout.tabs`)に 1 件だけ保存していた。これらのキーは移さずに消す。
97
97
 
98
+ ## メニュー・作品のダイアログ・ステージの操作・バックパックの窓
99
+
100
+ turbowarp-plus-editor の `packages/editor-ui` と `packages/editor-backpack` から移したもの。
101
+
102
+ | import | 内容 |
103
+ | --- | --- |
104
+ | `./project-info-menu` | 作品と設定のメニュー。作品名の欄と、ホストが渡す GUI の表示設定を含む |
105
+ | `./edit-menu` | 編集メニューのワークスペースの操作、復元、置換のショートカット |
106
+ | `./project-file-menu`・`./project-file-dialogs` | ファイルメニュー、名前を付けて保存(現在の形式・埋め込み・フォルダ、GitHub の新しいリポジトリ)、書き出しの表示、拡張の置き場所のフォーム |
107
+ | `./project-search` | 作品全体の検索と置換のボックス(検索そのものは `@kubohiroya/turbowarp-plus-editor-project-model` にある) |
108
+ | `./project-load-progress`・`./project-load-progress-view`・`./project-size-approval` | 読み込みの進み具合と、標準の上限を超える作品を開く前の確認 |
109
+ | `./stage-controls`・`./stage-controls-view` | 拡張が登録するステージの操作と、デバッガーと録画のボタンを含むメニューバーの表示 |
110
+ | `./busy-cursor`・`./browser-tab-title` | 時間のかかる処理の待ちカーソルと、ブラウザーのタブの題名 |
111
+ | `./backpack` | 別窓のバックパック。窓をまたぐコピーは `@kubohiroya/turbowarp-plus-editor-windows` を使う |
112
+ | `./edit-menu.css`・`./info-menu.css`・`./project-file-menu.css`・`./project-load-progress.css`・`./project-search.css`・`./stage-controls.css` | 上のグローバルなスタイルシート |
113
+
114
+ これらのスタイルシートはグローバルなスタイルシートとして読み込む。ダイアログの操作ボタンに使う `@kubohiroya/turbowarp-plus-editor-windows` の `styles.css` もあわせて読み込む。
115
+
116
+ デバッガーのボタンは GUI のアドオンが作る。ホストは `setDebuggerButton` に渡すとき、アドオンのボタンに `data-tw-stage-button`、アイコンに `data-tw-stage-button-icon`、中身に `data-tw-stage-button-content` の印を付ける。スタイルシートとキーボードの扱いは、GUI のクラス名ではなくこの印を使う。
117
+
118
+ これらは同じ作者が書いたもので、移すときに GPL-3.0 から MPL-2.0 にした。由来の監査は [turbowarp-plus-packages の移行計画](https://github.com/kubohiroya/turbowarp-plus-packages/blob/main/docs/editor-migration-plan.ja.md)の「由来の監査(7b)」にある。作品のメニューの Mark GitHub と Law のアイコンは GitHub Octicons(MIT)のもの。`NOTICE` を参照。
119
+
98
120
  ## 検証
99
121
 
100
122
  `npm test` で配分・縦横比・設定の読み書きを、`npm run test:browser` で独立した試験用ホストを検証する。試験用ホストを手動で開くには、このディレクトリで `npm install` と `python3 -m http.server` を実行し、`/example/` を表示する。
package/README.md CHANGED
@@ -97,6 +97,28 @@ workspaceLayout: {
97
97
  - To forget every layout, delete the `twPlusWorkspaceLayout` database from the browser's developer tools (in Chrome: Application, then IndexedDB), or run `indexedDB.deleteDatabase('twPlusWorkspaceLayout')` in the console.
98
98
  - Earlier versions kept a single layout in `localStorage` (`twPlusDockviewLayout` and `twPlusDockviewLayout.tabs`). Those keys are removed without being moved.
99
99
 
100
+ ## Menus, project dialogs, stage controls and the backpack window
101
+
102
+ These moved here from `packages/editor-ui` and `packages/editor-backpack` in turbowarp-plus-editor.
103
+
104
+ | Import | Contents |
105
+ | --- | --- |
106
+ | `./project-info-menu` | The project and settings menu, with the project title field and the GUI's display settings the host passes in |
107
+ | `./edit-menu` | The Edit menu's workspace commands, restore and the replace shortcut |
108
+ | `./project-file-menu`, `./project-file-dialogs` | The File menu, Save As (current, embedded or folder, and a new GitHub repository), the export view and the extension storage form |
109
+ | `./project-search` | The project-wide search and replace box (the search itself is in `@kubohiroya/turbowarp-plus-editor-project-model`) |
110
+ | `./project-load-progress`, `./project-load-progress-view`, `./project-size-approval` | Loading progress, and asking before opening a project over the standard size limit |
111
+ | `./stage-controls`, `./stage-controls-view` | The stage controls that extensions register, and their view on the menu bar with the debugger and recorder buttons |
112
+ | `./busy-cursor`, `./browser-tab-title` | The wait cursor around blocking work, and the browser tab title |
113
+ | `./backpack` | The backpack in its own window, with copies between windows through `@kubohiroya/turbowarp-plus-editor-windows` |
114
+ | `./edit-menu.css`, `./info-menu.css`, `./project-file-menu.css`, `./project-load-progress.css`, `./project-search.css`, `./stage-controls.css` | Their global stylesheets |
115
+
116
+ Load those stylesheets as global stylesheets, together with the `styles.css` of `@kubohiroya/turbowarp-plus-editor-windows`, whose dialog actions the dialogs use.
117
+
118
+ The debugger button comes from a GUI add-on. When handing it to `setDebuggerButton`, the host marks the add-on's button with `data-tw-stage-button`, its icon with `data-tw-stage-button-icon` and its content with `data-tw-stage-button-content`; the stylesheet and the keyboard handling use those marks instead of the GUI's class names.
119
+
120
+ These came from the same author and changed from GPL-3.0 to MPL-2.0 in the move. The provenance audit is in the "由来の監査(7b)" section of the [migration plan in turbowarp-plus-packages](https://github.com/kubohiroya/turbowarp-plus-packages/blob/main/docs/editor-migration-plan.ja.md). The Mark GitHub and Law icons in the project menu are from GitHub Octicons (MIT); see `NOTICE`.
121
+
100
122
  ## Verification
101
123
 
102
124
  Run `npm test` to verify split sizing, aspect ratios, and settings persistence. Run `npm run test:browser` to test the standalone host. To open the test host manually, run `npm install` and `python3 -m http.server` in this directory, then open `/example/`.
@@ -0,0 +1,2 @@
1
+ export declare const jsonDataUrl = "data:application/json;base64,";
2
+ export declare function readBackpackScript(url: string, signal?: AbortSignal): Promise<import("@kubohiroya/turbowarp-script-transfer").ScriptFile>;
@@ -0,0 +1,23 @@
1
+ import { FORMAT, MAX_BYTES, validateScript } from '@kubohiroya/turbowarp-script-transfer';
2
+ const stockOpcode = /^(motion|looks|sound|event|control|sensing|operator|math|text|colour|note)_|^(text|colour_picker)$/;
3
+ export const jsonDataUrl = 'data:application/json;base64,';
4
+ export async function readBackpackScript(url, signal) {
5
+ if (!url.startsWith(jsonDataUrl))
6
+ throw new Error('Unsupported Backpack script URL');
7
+ if (url.length > MAX_BYTES * 2)
8
+ throw new Error('Backpack script too large');
9
+ const response = await fetch(url, { signal });
10
+ if (!response.ok)
11
+ throw new Error('Backpack item unavailable');
12
+ const bytes = await response.arrayBuffer();
13
+ if (bytes.byteLength > MAX_BYTES)
14
+ throw new Error('Backpack script too large');
15
+ const raw = JSON.parse(new TextDecoder().decode(bytes));
16
+ if (!Array.isArray(raw) || !raw.length)
17
+ throw new Error('Unsupported Backpack script');
18
+ const script = validateScript({ format: FORMAT, version: 1, blocks: raw, variables: [], extensionURLs: {} });
19
+ if (script.blocks.some(block => block.comment || !stockOpcode.test(block.opcode))) {
20
+ throw new Error('This Backpack script requires unsupported project dependencies');
21
+ }
22
+ return script;
23
+ }
@@ -0,0 +1,60 @@
1
+ import React from 'react';
2
+ import { readBackpackScript } from './backpack-script.js';
3
+ export declare function createBackpackIntegration({ host, importScript, importScriptWithReceipt, decorateSurface, readScript, recovery, pendingEdits }: {
4
+ host: any;
5
+ importScript: any;
6
+ importScriptWithReceipt: any;
7
+ decorateSurface: any;
8
+ readScript?: typeof readBackpackScript;
9
+ recovery?: {
10
+ lost: () => string[];
11
+ isLost: (id: string) => boolean;
12
+ version: () => number;
13
+ subscribe(listener: () => void): () => void;
14
+ opened(id: string): void;
15
+ closed(id: string, cause?: import("@kubohiroya/turbowarp-plus-editor-windows/surfaces").DisconnectCause): void;
16
+ dismiss: (id: string) => void;
17
+ };
18
+ pendingEdits?: {
19
+ register(source: import("@kubohiroya/turbowarp-plus-editor-windows/surfaces").PendingEditSource): () => void;
20
+ readonly size: number;
21
+ flush({ timeoutMs }?: {
22
+ timeoutMs?: number;
23
+ }): Promise<void>;
24
+ };
25
+ }): {
26
+ BackpackSurface: ({ vm, children, showUndock, locale, internalHost, openLabel, renderLaunchButton, launchClassName, onDetachedChange, renderPopupTools, internalLayer }: {
27
+ vm: any;
28
+ children: any;
29
+ showUndock: any;
30
+ locale: any;
31
+ internalHost: any;
32
+ openLabel: any;
33
+ renderLaunchButton: any;
34
+ launchClassName: any;
35
+ onDetachedChange: any;
36
+ renderPopupTools: any;
37
+ internalLayer: any;
38
+ }) => React.JSX.Element;
39
+ attachBackpackDrop: ({ vm, workspace, canUse, onError, dropElement, destination }: {
40
+ vm: any;
41
+ workspace: any;
42
+ canUse: any;
43
+ onError: any;
44
+ dropElement: any;
45
+ destination: any;
46
+ }) => {
47
+ dispose(): void;
48
+ };
49
+ receiveBackpackDrop: ({ vm, target, raw, position, canUse, onError, receipt, commit, accept }: {
50
+ vm: any;
51
+ target: any;
52
+ raw: any;
53
+ position: any;
54
+ canUse: any;
55
+ onError: any;
56
+ receipt: any;
57
+ commit?: (apply: any) => any;
58
+ accept?: (_script: Awaited<ReturnType<typeof readBackpackScript>>) => boolean;
59
+ }) => Promise<void>;
60
+ };
@@ -0,0 +1,226 @@
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 { createTransferSession, transferMime } from '@kubohiroya/turbowarp-plus-editor-windows/transfer';
5
+ import { jsonDataUrl, readBackpackScript } from './backpack-script.js';
6
+ const kind = 'backpack-script';
7
+ const docked = { kind: 'docked' };
8
+ const messages = {
9
+ en: {
10
+ undock: 'Open Backpack in a browser window',
11
+ detach: 'Undock Backpack',
12
+ reopen: 'Reopen Backpack in another window',
13
+ title: 'Backpack',
14
+ restore: 'Return here',
15
+ internal: 'Move into the editor',
16
+ dock: 'Dock Backpack',
17
+ drag: 'Drag script to code',
18
+ blocked: 'Could not open Backpack window',
19
+ copyFailed: 'Could not copy Backpack script'
20
+ },
21
+ ja: {
22
+ undock: 'バックパックをブラウザーの別ウィンドウで開く',
23
+ detach: 'バックパックを別画面で開く',
24
+ reopen: 'バックパックを別画面で開き直す',
25
+ title: 'バックパック',
26
+ restore: 'ここに戻す',
27
+ internal: 'アプリ内に戻す',
28
+ dock: 'バックパックを元の位置に戻す',
29
+ drag: 'スクリプトをコードへドラッグ',
30
+ blocked: 'バックパックのウィンドウを開けませんでした',
31
+ copyFailed: 'バックパックのスクリプトをコピーできませんでした'
32
+ }
33
+ };
34
+ // The GUI uses React 16, which has no hook for external stores (added in React 18).
35
+ function useLostWindow(recovery, id) {
36
+ const [lost, setLost] = React.useState(() => Boolean(recovery?.isLost(id)));
37
+ React.useEffect(() => {
38
+ if (!recovery)
39
+ return;
40
+ const update = () => setLost(recovery.isLost(id));
41
+ update();
42
+ return recovery.subscribe(update);
43
+ }, [recovery, id]);
44
+ return Boolean(recovery) && lost;
45
+ }
46
+ export function createBackpackIntegration({ host, importScript, importScriptWithReceipt, decorateSurface, readScript = readBackpackScript, recovery = undefined, pendingEdits = pendingSurfaceEdits }) {
47
+ const sessions = new WeakMap();
48
+ function BackpackSurface({ vm, children, showUndock, locale, internalHost, openLabel, renderLaunchButton, launchClassName, onDetachedChange, renderPopupTools, internalLayer }) {
49
+ const labels = /^ja(?:-|$)/i.test(locale) ? messages.ja : messages.en;
50
+ const copyFailed = React.useRef(labels.copyFailed);
51
+ copyFailed.current = labels.copyFailed;
52
+ const [display, setDisplay] = React.useState({ vm, state: docked });
53
+ const state = display.vm === vm ? display.state : docked;
54
+ const detached = state.kind === 'external';
55
+ React.useLayoutEffect(() => { onDetachedChange?.(detached); }, [onDetachedChange, detached]);
56
+ const scope = React.useRef(null);
57
+ const mounted = React.useRef(true);
58
+ const launchButton = React.useRef(null);
59
+ const fallback = React.useRef(null);
60
+ const surface = React.useMemo(() => createSurface({
61
+ open: request => request?.presentation === 'internal' ? internalHost?.open(request) : host?.open()
62
+ }, next => {
63
+ if (host)
64
+ recordSurface(recovery, 'backpack', next, target => target.presentation !== 'internal');
65
+ if (next.kind === 'external') {
66
+ fallback.current = null;
67
+ const id = crypto.randomUUID();
68
+ const cleanup = next.target.presentation === 'internal' ? () => { } :
69
+ decorateSurface(next.target.mount.ownerDocument);
70
+ const transfer = createTransferSession(id);
71
+ scope.current = { id, transfer, cleanup, copyFailed,
72
+ unregister: pendingEdits.register(() => transfer.settled()) };
73
+ sessions.set(vm, scope.current);
74
+ }
75
+ else if (next.kind === 'docked' && scope.current) {
76
+ const active = scope.current;
77
+ scope.current = null;
78
+ if (sessions.get(vm) === active)
79
+ sessions.delete(vm);
80
+ // Scripts already dropped from the closing window still reach the code area.
81
+ void active.transfer.retire().finally(active.unregister);
82
+ active.cleanup();
83
+ }
84
+ if (next.kind === 'docked' && fallback.current) {
85
+ const retry = fallback.current;
86
+ fallback.current = null;
87
+ if (next.reason === 'blocked' || next.reason === 'failed') {
88
+ surface.undock(retry);
89
+ return;
90
+ }
91
+ }
92
+ if (mounted.current)
93
+ setDisplay({ vm, state: next });
94
+ }), [vm, internalHost]);
95
+ const lost = useLostWindow(host ? recovery : null, 'backpack');
96
+ React.useLayoutEffect(() => {
97
+ mounted.current = true;
98
+ return () => {
99
+ mounted.current = false;
100
+ fallback.current = null;
101
+ surface.dock();
102
+ };
103
+ }, [surface]);
104
+ React.useLayoutEffect(() => {
105
+ if (!internalHost || !showUndock || state.kind !== 'docked' || !state.reason)
106
+ return;
107
+ const frame = requestAnimationFrame(() => launchButton.current?.querySelector('button')?.focus({ preventScroll: true }));
108
+ return () => cancelAnimationFrame(frame);
109
+ }, [internalHost, showUndock, state]);
110
+ function internalRequest() {
111
+ const request = {
112
+ presentation: 'internal', id: 'backpack', title: labels.title, rememberPlacement: true, layer: internalLayer
113
+ };
114
+ if (host)
115
+ request.openExternal = () => {
116
+ surface.dock();
117
+ fallback.current = request;
118
+ surface.undock(undefined);
119
+ };
120
+ return request;
121
+ }
122
+ function moveInternal() {
123
+ surface.dock();
124
+ surface.undock(internalRequest());
125
+ }
126
+ const handle = item => typeof item.bodyUrl === 'string' && item.bodyUrl.startsWith(jsonDataUrl) ? (React.createElement("button", { type: "button", draggable: true, "data-testid": "backpack-script-drag", style: { cursor: 'grab', flexShrink: 0 }, onDragStart: event => {
127
+ const active = scope.current;
128
+ if (!active || !event.dataTransfer)
129
+ return;
130
+ const reference = active.transfer.offer(kind, signal => readScript(item.bodyUrl, signal));
131
+ event.dataTransfer.effectAllowed = 'copy';
132
+ event.dataTransfer.setData(transferMime, JSON.stringify(reference));
133
+ } }, labels.drag)) : null;
134
+ const dock = (React.createElement("button", { type: "button", onClick: () => surface.dock() }, labels.dock));
135
+ if (state.kind === 'external') {
136
+ const internal = state.target.presentation === 'internal';
137
+ return (React.createElement(React.Fragment, null,
138
+ internalHost ? (React.createElement("div", { style: { display: 'grid', placeItems: 'center', minHeight: 44 } },
139
+ React.createElement("button", { type: "button", onClick: () => surface.dock() }, labels.restore))) : dock,
140
+ createPortal(React.createElement(React.Fragment, null,
141
+ !internal && (renderPopupTools ? renderPopupTools({ mount: state.target.mount, onDock: surface.dock }) :
142
+ React.createElement(React.Fragment, null,
143
+ dock,
144
+ internalHost && React.createElement("button", { type: "button", onClick: moveInternal }, labels.internal))),
145
+ React.cloneElement(children, { renderScriptDragHandle: handle })), state.target.mount)));
146
+ }
147
+ // A backpack that was external when the editor closed reopens there on the next click.
148
+ const launch = {
149
+ disabled: state.kind === 'opening',
150
+ label: lost ? labels.reopen : internalHost ? labels.detach : (openLabel ?? labels.undock),
151
+ onOpen: () => surface.undock(internalHost && !lost ? internalRequest() : undefined)
152
+ };
153
+ return (React.createElement(React.Fragment, null,
154
+ showUndock && (React.createElement("div", { className: launchClassName },
155
+ React.createElement("span", { ref: launchButton }, renderLaunchButton ? renderLaunchButton(launch) :
156
+ React.createElement("button", { type: "button", disabled: launch.disabled, onClick: launch.onOpen }, launch.label)))),
157
+ children,
158
+ showUndock && state.kind === 'docked' && (state.reason === 'blocked' || state.reason === 'failed') &&
159
+ React.createElement("span", { role: "status" }, labels.blocked)));
160
+ }
161
+ async function receiveBackpackDrop({ vm, target, raw, position, canUse, onError, receipt, commit = apply => apply(), accept = (_script) => true }) {
162
+ const active = sessions.get(vm);
163
+ if (!active)
164
+ return;
165
+ // The drop is claimed while its window is open. It may finish after the window closes,
166
+ // but not after the destination view or target is gone.
167
+ const canCommit = () => canUse() && vm.runtime.getTargetById(target.id) === target;
168
+ const result = await active.transfer.receive(raw, { session: active.id, id: target.id }, async (_, script) => {
169
+ if (!accept(script))
170
+ throw new Error('Unsupported script for this workspace');
171
+ return commit(async () => {
172
+ if (!canCommit())
173
+ return false;
174
+ if (receipt) {
175
+ const imported = await importScriptWithReceipt(vm, target, script, {
176
+ position, canCommit, beforeCommit: receipt.beforeCommit, onCommitted: receipt.onCommitted
177
+ });
178
+ return imported !== null;
179
+ }
180
+ await importScript(vm, target, script, { position });
181
+ return true;
182
+ });
183
+ });
184
+ if (result === 'failed' && canUse())
185
+ onError?.(new Error(active.copyFailed.current));
186
+ }
187
+ function attachBackpackDrop({ vm, workspace, canUse, onError, dropElement, destination }) {
188
+ const svg = workspace.getParentSvg();
189
+ const node = dropElement ?? svg;
190
+ let disposed = false;
191
+ const allowed = event => sessions.has(vm) && canUse() &&
192
+ Array.from(event.dataTransfer?.types ?? []).includes(transferMime);
193
+ function over(event) {
194
+ if (!allowed(event))
195
+ return;
196
+ event.preventDefault();
197
+ event.dataTransfer.dropEffect = 'copy';
198
+ }
199
+ function drop(event) {
200
+ if (!allowed(event))
201
+ return;
202
+ event.preventDefault();
203
+ const target = destination?.target ?? vm.editingTarget;
204
+ const raw = event.dataTransfer.getData(transferMime);
205
+ const matrix = workspace.getCanvas().getScreenCTM();
206
+ if (!target || !matrix)
207
+ return;
208
+ const point = svg.createSVGPoint();
209
+ point.x = event.clientX;
210
+ point.y = event.clientY;
211
+ const { x, y } = point.matrixTransform(matrix.inverse());
212
+ void receiveBackpackDrop({
213
+ vm, target, raw, position: { x, y }, onError, receipt: destination,
214
+ canUse: destination ? destination.canCommit : () => !disposed
215
+ });
216
+ }
217
+ node.addEventListener('dragover', over);
218
+ node.addEventListener('drop', drop);
219
+ return { dispose() {
220
+ disposed = true;
221
+ node.removeEventListener('dragover', over);
222
+ node.removeEventListener('drop', drop);
223
+ } };
224
+ }
225
+ return { BackpackSurface, attachBackpackDrop, receiveBackpackDrop };
226
+ }
@@ -0,0 +1,2 @@
1
+ export declare const EDITOR_TAB_NAME = "TurboWarp Plus Editor";
2
+ export declare function updateBrowserTabTitle(title?: string): void;
@@ -0,0 +1,5 @@
1
+ export const EDITOR_TAB_NAME = 'TurboWarp Plus Editor';
2
+ export function updateBrowserTabTitle(title) {
3
+ const name = title?.trim();
4
+ document.title = name ? `${name} - ${EDITOR_TAB_NAME}` : EDITOR_TAB_NAME;
5
+ }
@@ -0,0 +1,22 @@
1
+ /** Give the browser a frame before starting work that may block its main thread. */
2
+ export declare function withWaitCursor<T>(documents: Iterable<Document>, run: () => T): Promise<Awaited<T>>;
3
+ /** Temporarily restore the normal cursor while an operation needs an answer. */
4
+ export declare function withoutWaitCursor<T>(document: Document | undefined, ask: () => T): Promise<Awaited<T>>;
5
+ interface Target {
6
+ id: string;
7
+ blocks?: {
8
+ _blocks?: Record<string, unknown>;
9
+ };
10
+ }
11
+ interface TargetSwitchVM {
12
+ editingTarget?: Target;
13
+ runtime: {
14
+ getTargetById(id: string): Target | undefined;
15
+ getTargetForStage(): Target | undefined;
16
+ };
17
+ }
18
+ export declare function createTargetSwitchFeedback(vm: TargetSwitchVM, document: Document): {
19
+ cancel(): void;
20
+ select(id: string | undefined, run: () => void, source?: Document): void;
21
+ };
22
+ export {};
@@ -0,0 +1,107 @@
1
+ const active = new WeakMap();
2
+ const inputWaits = new WeakMap();
3
+ function holdCursor(document) {
4
+ let state = active.get(document);
5
+ if (!state) {
6
+ const style = document.createElement('style');
7
+ style.dataset.twPlusWaitCursor = '';
8
+ style.textContent = ':root, :root body, :root body * { cursor: wait !important; }';
9
+ if (inputWaits.has(document))
10
+ 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)
18
+ return;
19
+ state.style.remove();
20
+ active.delete(document);
21
+ };
22
+ }
23
+ function afterPaint(document) {
24
+ const view = document.defaultView;
25
+ if (!view?.requestAnimationFrame || document.hidden)
26
+ return Promise.resolve();
27
+ // The first callback still runs before the cursor change can be painted.
28
+ return new Promise(resolve => {
29
+ let frame = view.requestAnimationFrame(() => {
30
+ frame = view.requestAnimationFrame(finish);
31
+ });
32
+ const timeout = view.setTimeout(finish, 100);
33
+ function finish() {
34
+ view.cancelAnimationFrame(frame);
35
+ view.clearTimeout(timeout);
36
+ resolve();
37
+ }
38
+ });
39
+ }
40
+ /** Give the browser a frame before starting work that may block its main thread. */
41
+ export async function withWaitCursor(documents, run) {
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
+ }
48
+ finally {
49
+ release.forEach(done => done());
50
+ }
51
+ }
52
+ /** Temporarily restore the normal cursor while an operation needs an answer. */
53
+ export async function withoutWaitCursor(document, ask) {
54
+ if (!document)
55
+ return await ask();
56
+ inputWaits.set(document, (inputWaits.get(document) ?? 0) + 1);
57
+ const waiting = active.get(document);
58
+ if (waiting)
59
+ waiting.style.media = 'not all';
60
+ try {
61
+ return await ask();
62
+ }
63
+ finally {
64
+ const remaining = inputWaits.get(document) - 1;
65
+ if (remaining)
66
+ inputWaits.set(document, remaining);
67
+ else {
68
+ inputWaits.delete(document);
69
+ const resumed = active.get(document);
70
+ if (resumed) {
71
+ resumed.style.media = '';
72
+ await afterPaint(document);
73
+ }
74
+ }
75
+ }
76
+ }
77
+ // VM target changes rebuild the Blockly workspace synchronously. Large workspaces
78
+ // need a paint before that rebuild. Smaller switches stay in the input event.
79
+ const largeWorkspace = (target) => Object.keys(target?.blocks?._blocks ?? {}).length >= 200;
80
+ export function createTargetSwitchFeedback(vm, document) {
81
+ let request = 0;
82
+ let running;
83
+ return {
84
+ cancel() { request++; },
85
+ select(id, run, source = document) {
86
+ const token = ++request;
87
+ const previous = vm.editingTarget;
88
+ const target = id === undefined ? vm.runtime.getTargetForStage() : vm.runtime.getTargetById(id);
89
+ if (!target || target === previous || target === running || !largeWorkspace(target)) {
90
+ run();
91
+ return;
92
+ }
93
+ void withWaitCursor([source, document], async () => {
94
+ if (request !== token || vm.editingTarget !== previous || vm.runtime.getTargetById(target.id) !== target)
95
+ return;
96
+ running = target;
97
+ try {
98
+ run();
99
+ }
100
+ finally {
101
+ running = undefined;
102
+ }
103
+ await afterPaint(document);
104
+ }).catch(error => globalThis.reportError(error));
105
+ }
106
+ };
107
+ }
@@ -0,0 +1,57 @@
1
+ import React from 'react';
2
+ import type { SearchProject } from '@kubohiroya/turbowarp-plus-editor-project-model/project-search';
3
+ interface Workspace {
4
+ options: {
5
+ readOnly: boolean;
6
+ };
7
+ getParentSvg(): SVGElement;
8
+ hasUndoStack(): boolean;
9
+ hasRedoStack(): boolean;
10
+ isDragging(): boolean;
11
+ isVisible(): boolean;
12
+ targetWorkspace?: Workspace;
13
+ isFlyout: boolean;
14
+ }
15
+ interface WorkspaceContext {
16
+ vm: object;
17
+ workspace: Workspace;
18
+ canUse(): boolean;
19
+ ScratchBlocks: {
20
+ getMainWorkspace(): Workspace;
21
+ selected?: {
22
+ workspace: Workspace;
23
+ isDeletable(): boolean;
24
+ isMovable(): boolean;
25
+ };
26
+ clipboardXml_?: unknown;
27
+ clipboardSource_?: Workspace;
28
+ onKeyDown_(event: Pick<KeyboardEvent, 'target' | 'keyCode' | 'ctrlKey' | 'shiftKey' | 'preventDefault'>): void;
29
+ };
30
+ }
31
+ interface MenuProps {
32
+ vm: {
33
+ runtime?: SearchProject;
34
+ };
35
+ locale: string;
36
+ MenuItem: React.ComponentType<{
37
+ className?: string;
38
+ children: React.ReactNode;
39
+ }>;
40
+ MenuSection: React.ComponentType<{
41
+ children: React.ReactNode;
42
+ }>;
43
+ renderIcon(command: Command | 'restoreDeletion'): React.ReactNode;
44
+ getRearrangement?(): {
45
+ canArrange(): boolean;
46
+ open(locale: string): void;
47
+ } | undefined;
48
+ onRequestClose(): void;
49
+ }
50
+ export declare function attachEditMenuWorkspace(context: WorkspaceContext): {
51
+ dispose(): void;
52
+ };
53
+ declare const groups: readonly [readonly [readonly ["undo", "Undo", "元に戻す"], readonly ["redo", "Redo", "繰り返し"]], readonly [readonly ["cut", "Cut", "切り取り"], readonly ["copy", "Copy", "コピー"], readonly ["paste", "Paste", "貼り付け"]], readonly [readonly ["findAndReplace", "Find and Replace", "検索と置換"], readonly ["cleanup", "Rearrange Code Blocks", "コードブロックの再配置"]]];
54
+ type Command = (typeof groups)[number][number][0];
55
+ export declare function renderEditMenu(props: MenuProps): React.JSX.Element;
56
+ export declare function renderEditMenuRestore(label: React.ReactNode, renderIcon: MenuProps['renderIcon']): React.JSX.Element;
57
+ export {};