@kubohiroya/turbowarp-plus-editor-workbench 0.29.1 → 0.30.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.
package/README.ja.md CHANGED
@@ -311,5 +311,23 @@ Web 版の Plus 標準配置で `twPlusDockview=1` を付けて起動すると
311
311
 
312
312
  ## Editor の実装との責務分担
313
313
 
314
+ `./project-open-tabs` は、別の作品を新しいタブへ開く接続を提供します。元のタブの作品を
315
+ 保存・再読み込み・停止せず、未保存の編集、Undo履歴、実行状態をそのまま残します。
316
+ ファイルを開く場合、ユーザーが選んだ新しいファイルと、その選択で許可されたファイルハンドルだけを
317
+ 同一オリジンの一時的なBroadcastChannelで渡します。元の作品のスナップショットは作りません。
318
+ 新しいタブから元のタブを操作できないように、`opener` を切り離します。
319
+ ポップアップが止められた場合は、明示的な再試行またはキャンセルを提示します。
320
+ 新しいタブで機能拡張の実行を拒否すると、そのタブを閉じます。
321
+
322
+ URLを直接開いた場合は、開始画面を履歴へ追加しません。読み込みの拒否・失敗は
323
+ メイン画面に表示し、戻り先がなければ「前の画面に戻る」を無効化します。
324
+ 「確認画面に戻る」は同じ作品の機能拡張を再確認します。URLを直接開いた場合は
325
+ 作品指定を保持して開き直します。別タブへ渡したファイルは、その選択済みファイルを
326
+ 再使用し、転送元のタブや転送終了済みのチャンネルには依存しません。
327
+ 再確認だけでは実行を許可しません。`onReview`でホスト固有の再確認操作も渡せます。
328
+
329
+ 表示・受け渡しの状態はこのパッケージが持ち、GUIは選択済みファイルと保存先の接続コールバックを渡します。
330
+ 切り戻しはEditorの接続とパッケージの固定を直前の組み合わせへ戻します。作品データの移行はありません。
331
+
314
332
  Editor 独自実装の移管元とライセンス確認は [EDITOR-MIGRATION.md](EDITOR-MIGRATION.md) に記録しています。
315
333
  追加した公開 API は GUI モジュールを import せず、ホストから必要な値・データ・コールバックを受け取ります。
@@ -0,0 +1,18 @@
1
+ interface FailureOptions {
2
+ cancelled: boolean;
3
+ locale?: string;
4
+ onDetails?(): void;
5
+ onReview?(): void;
6
+ }
7
+ /** A fresh tab may include about:blank in history without having a usable previous page. */
8
+ export declare function canReturnToPreviousPage(document: Document): boolean;
9
+ /** Drop all opening instructions while preserving display preferences such as the language. */
10
+ export declare function projectStartURL(view: Window): URL;
11
+ /** A terminal opening result replaces the busy screen, including when navigation cannot leave it. */
12
+ export declare function showProjectLoadFailure(document: Document, options: FailureOptions): () => void;
13
+ export declare const closeProjectLoadFailure: (document: Document) => void;
14
+ /** Preserve routing identity while ending the load; no default-project fetch follows a refusal. */
15
+ export declare function stoppedProjectLoadState(initial: any, states: {
16
+ NOT_LOADED: string;
17
+ }, current?: any): any;
18
+ export {};
@@ -0,0 +1,108 @@
1
+ const screens = new WeakMap();
2
+ let sequence = 0;
3
+ /** A fresh tab may include about:blank in history without having a usable previous page. */
4
+ export function canReturnToPreviousPage(document) {
5
+ const view = document.defaultView;
6
+ const navigation = view.navigation;
7
+ return view.history.length > 1 && !(navigation?.canGoBack === false && !document.referrer);
8
+ }
9
+ /** Drop all opening instructions while preserving display preferences such as the language. */
10
+ export function projectStartURL(view) {
11
+ const url = new URL('editor.html', view.location.href);
12
+ url.search = view.location.search;
13
+ for (const key of ['project_url', 'token', 'extension', 'twPlusOpenTab'])
14
+ url.searchParams.delete(key);
15
+ url.hash = '';
16
+ return url;
17
+ }
18
+ /** A terminal opening result replaces the busy screen, including when navigation cannot leave it. */
19
+ export function showProjectLoadFailure(document, options) {
20
+ const existing = screens.get(document);
21
+ if (existing) {
22
+ existing.update(options);
23
+ return existing.close;
24
+ }
25
+ const view = document.defaultView;
26
+ const dialog = document.createElement('dialog');
27
+ dialog.setAttribute('role', 'alertdialog');
28
+ dialog.setAttribute('data-project-tools', '');
29
+ dialog.setAttribute('data-testid', 'project-load-failure');
30
+ const id = `project-load-failure-${++sequence}`;
31
+ dialog.setAttribute('aria-labelledby', `${id}-title`);
32
+ dialog.setAttribute('aria-describedby', `${id}-reason`);
33
+ Object.assign(dialog.style, { position: 'fixed', inset: '0', margin: '0', width: '100vw', height: '100dvh',
34
+ maxWidth: 'none', maxHeight: 'none', boxSizing: 'border-box', border: 'none', overflow: 'auto',
35
+ padding: 'clamp(24px, 6vw, 80px)', background: 'var(--ui-modal-background, Canvas)',
36
+ color: 'var(--ui-modal-foreground, CanvasText)', font: 'inherit' });
37
+ const main = document.createElement('main');
38
+ Object.assign(main.style, { maxWidth: '680px', minHeight: '100%', margin: '0 auto',
39
+ display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: '20px' });
40
+ const title = document.createElement('h1');
41
+ title.id = `${id}-title`;
42
+ title.tabIndex = -1;
43
+ Object.assign(title.style, { fontSize: 'clamp(24px, 4vw, 36px)', margin: '0', lineHeight: '1.3' });
44
+ const reason = document.createElement('p');
45
+ reason.id = `${id}-reason`;
46
+ Object.assign(reason.style, { margin: '0', fontSize: '18px', lineHeight: '1.7' });
47
+ const actions = document.createElement('div');
48
+ Object.assign(actions.style, { display: 'flex', flexWrap: 'wrap', gap: '12px' });
49
+ const button = (action) => {
50
+ const element = document.createElement('button');
51
+ element.type = 'button';
52
+ Object.assign(element.style, { font: 'inherit', padding: '12px 18px', minHeight: '44px', cursor: 'pointer',
53
+ border: '1px solid currentColor', borderRadius: '6px', background: 'transparent', color: 'inherit' });
54
+ element.addEventListener('click', action);
55
+ actions.append(element);
56
+ return element;
57
+ };
58
+ const back = button(() => view.history.back());
59
+ // Reopen the same requested project so the person can reconsider extension permissions.
60
+ // Reload keeps its URL, including its project source, instead of opening a default project.
61
+ let review = options.onReview ?? (() => view.location.reload());
62
+ const confirm = button(() => review());
63
+ Object.assign(confirm.style, { background: 'var(--looks-secondary, #1d4ed8)', color: '#fff', borderColor: 'transparent' });
64
+ const closeTab = button(() => view.close());
65
+ let details;
66
+ const log = button(() => details?.());
67
+ main.append(title, reason, actions);
68
+ dialog.append(main);
69
+ // Escape must not expose the stale loading screen underneath the terminal result.
70
+ dialog.addEventListener('cancel', event => event.preventDefault());
71
+ let locale = options.locale ?? new URL(view.location.href).searchParams.get('lang') ?? document.documentElement.lang ?? 'en';
72
+ const screen = {
73
+ update(value) {
74
+ locale = value.locale ?? locale;
75
+ details = value.onDetails ?? details;
76
+ review = value.onReview ?? review;
77
+ const ja = locale.startsWith('ja');
78
+ dialog.dataset.outcome = value.cancelled ? 'cancelled' : 'failed';
79
+ title.textContent = ja ? '作品を開けませんでした' : 'The project could not be opened';
80
+ reason.textContent = value.cancelled ?
81
+ (ja ? '機能拡張を実行しないことを選んだため、作品の読み込みを中止しました。' :
82
+ 'You chose not to run the extensions, so loading the project has stopped.') :
83
+ (ja ? '読み込み中に問題が起きたため、作品の読み込みを中止しました。詳細ログを確認できます。' :
84
+ 'Loading stopped because a problem occurred. You can view the detailed log.');
85
+ back.textContent = ja ? '前の画面に戻る' : 'Go back';
86
+ back.disabled = !canReturnToPreviousPage(document);
87
+ Object.assign(back.style, { opacity: back.disabled ? '0.45' : '1',
88
+ cursor: back.disabled ? 'default' : 'pointer' });
89
+ confirm.textContent = ja ? '確認画面に戻る' : 'Return to confirmation';
90
+ closeTab.textContent = ja ? 'このタブを閉じる' : 'Close this tab';
91
+ closeTab.hidden = !new URL(view.location.href).searchParams.has('twPlusOpenTab');
92
+ log.textContent = ja ? '詳細ログを表示' : 'View detailed log';
93
+ log.hidden = !details;
94
+ },
95
+ close() { dialog.remove(); screens.delete(document); }
96
+ };
97
+ screens.set(document, screen);
98
+ screen.update(options);
99
+ document.body.append(dialog);
100
+ dialog.showModal();
101
+ title.focus();
102
+ return screen.close;
103
+ }
104
+ export const closeProjectLoadFailure = (document) => screens.get(document)?.close();
105
+ /** Preserve routing identity while ending the load; no default-project fetch follows a refusal. */
106
+ export function stoppedProjectLoadState(initial, states, current = initial) {
107
+ return { ...current, loadingState: states.NOT_LOADED, projectData: null, error: null };
108
+ }
@@ -0,0 +1,32 @@
1
+ import type { ProjectFileStorage } from './project-file-dialogs.js';
2
+ export type ProjectTabCommand = 'folder' | 'browser-folder' | 'remote' | 'catalog';
3
+ export type ProjectTabRequest = {
4
+ kind: 'file';
5
+ file: File;
6
+ handle?: FileSystemFileHandle;
7
+ } | {
8
+ kind: 'command';
9
+ command: ProjectTabCommand;
10
+ } | {
11
+ kind: 'folder';
12
+ directory: FileSystemDirectoryHandle;
13
+ root?: FileSystemDirectoryHandle;
14
+ };
15
+ interface TabActions {
16
+ storage: ProjectFileStorage;
17
+ commands: Partial<Record<ProjectTabCommand, () => unknown>>;
18
+ openDirectory?: (directory: FileSystemDirectoryHandle, root?: FileSystemDirectoryHandle) => Promise<unknown>;
19
+ fileOpened?(file: File): void;
20
+ }
21
+ interface TabPorts {
22
+ document: Document;
23
+ locale(): string;
24
+ ready(): boolean;
25
+ subscribe(listener: () => void): () => void;
26
+ isCancelled(error: unknown): boolean;
27
+ }
28
+ export declare function installProjectOpenTabs(vm: object, ports: TabPorts): () => void;
29
+ export declare const bindProjectOpenTabActions: (vm: object, actions: Partial<TabActions>) => void;
30
+ export declare const openProjectInNewTab: (vm: object, request: ProjectTabRequest) => boolean;
31
+ export declare const cancelProjectTabOpening: (document: Document) => boolean;
32
+ export {};
@@ -0,0 +1,227 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ import { showNotice } from './project-notice.js';
3
+ import { canReturnToPreviousPage, closeProjectLoadFailure, projectStartURL as startURL, showProjectLoadFailure } from './project-load-failure.js';
4
+ const parameter = 'twPlusOpenTab';
5
+ const services = new WeakMap();
6
+ const documents = new WeakMap();
7
+ const bindings = new WeakMap();
8
+ function createService(host, ports) {
9
+ const vm = host;
10
+ const view = ports.document.defaultView;
11
+ const token = new URL(view.location.href).searchParams.get(parameter);
12
+ let incoming = Boolean(token);
13
+ let actions;
14
+ let received = false;
15
+ let alive = true;
16
+ let channel;
17
+ let readyTimer;
18
+ let prompt;
19
+ let reviewRequest;
20
+ const returnToReview = () => {
21
+ if (!reviewRequest)
22
+ return;
23
+ closeProjectLoadFailure(ports.document);
24
+ void run(reviewRequest);
25
+ };
26
+ const pending = new Set();
27
+ const startup = new URL(view.location.href).searchParams.has('project_url');
28
+ const report = (error) => showNotice(ports.document, ports.locale().startsWith('ja') ? `別のタブで作品を開けませんでした。${String(error)}` :
29
+ `Could not open the project in another tab. ${String(error)}`, { locale: ports.locale() });
30
+ const cancel = () => {
31
+ showProjectLoadFailure(ports.document, { locale: ports.locale(), cancelled: true,
32
+ onReview: reviewRequest ? returnToReview : undefined });
33
+ if (incoming) {
34
+ view.close();
35
+ return true;
36
+ }
37
+ if (!startup)
38
+ return false;
39
+ // A directly opened URL has no previous screen. Keep the stopped result visible and
40
+ // let the person explicitly reopen confirmation rather than inventing history.
41
+ if (canReturnToPreviousPage(ports.document))
42
+ view.history.back();
43
+ return true;
44
+ };
45
+ const completed = () => {
46
+ if (!incoming || !received)
47
+ return;
48
+ incoming = false;
49
+ view.history.replaceState(view.history.state, '', startURL(view).href);
50
+ };
51
+ vm.runtime.on('PROJECT_LOADED', completed);
52
+ const run = async (request) => {
53
+ if (!actions)
54
+ return;
55
+ // Keep only the explicitly selected incoming request for reconsideration, never the
56
+ // original tab's project. A transferred File cannot be recovered by reloading its URL.
57
+ reviewRequest = request.kind === 'command' ? undefined : request;
58
+ try {
59
+ if (request.kind === 'file') {
60
+ // Only the explicitly selected incoming file crosses tabs; the original VM is untouched.
61
+ await vm.loadProject(await request.file.arrayBuffer());
62
+ const handle = /\.sb3$/i.test(request.file.name) ? request.handle ?? null : null;
63
+ actions.storage.finish(handle, request.file.name.replace(/\.sb[23]?$/i, '').substring(0, 100), true);
64
+ actions.fileOpened?.(request.file);
65
+ reviewRequest = undefined;
66
+ }
67
+ else if (request.kind === 'folder') {
68
+ if (!actions.openDirectory)
69
+ throw new Error('Folder opening is unavailable');
70
+ await actions.openDirectory(request.directory, request.root);
71
+ }
72
+ else {
73
+ const command = actions.commands[request.command];
74
+ if (!command)
75
+ throw new Error('The requested opening command is unavailable');
76
+ if (request.command === 'catalog' || request.command === 'remote') {
77
+ await command();
78
+ return;
79
+ }
80
+ const ja = ports.locale().startsWith('ja');
81
+ const names = {
82
+ folder: ['フォルダを選ぶ', 'Choose a folder'],
83
+ 'browser-folder': ['ブラウザーに保存したフォルダを選ぶ', 'Choose a browser folder'],
84
+ remote: ['Git のリモートリポジトリを選ぶ', 'Choose a Git remote repository'],
85
+ catalog: ['プロジェクト一覧を開く', 'Show projects']
86
+ };
87
+ prompt = ports.document.createElement('dialog');
88
+ prompt.setAttribute('data-project-tools', '');
89
+ const text = ports.document.createElement('p');
90
+ text.textContent = ja ? '元のタブを残して、このタブで別の作品を開きます。' :
91
+ 'Your original tab stays open. Open another project in this tab.';
92
+ const button = ports.document.createElement('button');
93
+ button.type = 'button';
94
+ button.textContent = names[request.command][ja ? 0 : 1];
95
+ button.addEventListener('click', () => {
96
+ prompt?.remove();
97
+ prompt = undefined;
98
+ try {
99
+ Promise.resolve(command()).catch(report);
100
+ }
101
+ catch (error) {
102
+ report(error);
103
+ }
104
+ });
105
+ prompt.append(text, button);
106
+ ports.document.body.append(prompt);
107
+ prompt.showModal();
108
+ }
109
+ }
110
+ catch (error) {
111
+ if (ports.isCancelled(error))
112
+ cancel();
113
+ else
114
+ showProjectLoadFailure(ports.document, { locale: ports.locale(), cancelled: false,
115
+ onReview: reviewRequest ? returnToReview : undefined });
116
+ }
117
+ };
118
+ const ready = () => {
119
+ if (alive && incoming && !received && actions?.storage && ports.ready())
120
+ channel?.postMessage({ type: 'ready' });
121
+ };
122
+ if (token) {
123
+ channel = new view.BroadcastChannel(`tw-plus-project-open-${token}`);
124
+ channel.onmessage = event => {
125
+ if (!alive || received || !actions || !ports.ready() || event.data?.type !== 'open')
126
+ return;
127
+ received = true;
128
+ channel.postMessage({ type: 'received' });
129
+ view.clearInterval(readyTimer);
130
+ channel.close();
131
+ channel = undefined;
132
+ void run(event.data.request);
133
+ };
134
+ readyTimer = view.setInterval(ready, 500);
135
+ }
136
+ const unsubscribe = ports.subscribe(ready);
137
+ const launch = (request) => {
138
+ const id = view.crypto.randomUUID();
139
+ const url = startURL(view);
140
+ url.searchParams.set(parameter, id);
141
+ const outgoing = new view.BroadcastChannel(`tw-plus-project-open-${id}`);
142
+ let child;
143
+ let sent = false;
144
+ const cleanup = () => { view.clearInterval(timer); outgoing.close(); pending.delete(cleanup); };
145
+ outgoing.onmessage = event => {
146
+ if (event.data?.type === 'ready' && !sent) {
147
+ try {
148
+ outgoing.postMessage({ type: 'open', request });
149
+ sent = true;
150
+ }
151
+ catch (error) {
152
+ cleanup();
153
+ report(error);
154
+ }
155
+ }
156
+ else if (event.data?.type === 'received')
157
+ cleanup();
158
+ };
159
+ child = view.open(url.href, '_blank');
160
+ if (child)
161
+ child.opener = null;
162
+ const timer = view.setInterval(() => { if (child?.closed)
163
+ cleanup(); }, 1000);
164
+ pending.add(cleanup);
165
+ if (!child) {
166
+ cleanup();
167
+ const ja = ports.locale().startsWith('ja');
168
+ const retry = ports.document.createElement('dialog');
169
+ retry.setAttribute('data-project-tools', '');
170
+ const text = ports.document.createElement('p');
171
+ text.textContent = ja ? '新しいタブを開くには、下のボタンを押してください。元の作品はそのまま残ります。' :
172
+ 'Use the button below to open a new tab. Your original project stays open.';
173
+ const button = ports.document.createElement('button');
174
+ button.type = 'button';
175
+ button.textContent = ja ? '新しいタブで開く' : 'Open in a new tab';
176
+ button.addEventListener('click', () => { retry.remove(); launch(request); });
177
+ const close = ports.document.createElement('button');
178
+ close.type = 'button';
179
+ close.textContent = ja ? 'キャンセル' : 'Cancel';
180
+ close.addEventListener('click', () => retry.remove());
181
+ retry.append(text, button, close);
182
+ ports.document.body.append(retry);
183
+ retry.showModal();
184
+ }
185
+ };
186
+ return {
187
+ open(request) {
188
+ if (incoming)
189
+ return false;
190
+ try {
191
+ launch(request);
192
+ }
193
+ catch (error) {
194
+ report(error);
195
+ }
196
+ return true;
197
+ },
198
+ bind(value) { actions = { ...actions, ...value }; ready(); },
199
+ cancel,
200
+ dispose() {
201
+ alive = false;
202
+ unsubscribe();
203
+ view.clearInterval(readyTimer);
204
+ channel?.close();
205
+ prompt?.remove();
206
+ reviewRequest = undefined;
207
+ for (const close of pending)
208
+ close();
209
+ vm.runtime.off('PROJECT_LOADED', completed);
210
+ }
211
+ };
212
+ }
213
+ export function installProjectOpenTabs(vm, ports) {
214
+ const service = createService(vm, ports);
215
+ services.set(vm, service);
216
+ documents.set(ports.document, service);
217
+ if (bindings.has(vm))
218
+ service.bind(bindings.get(vm));
219
+ return () => { service.dispose(); services.delete(vm); documents.delete(ports.document); };
220
+ }
221
+ export const bindProjectOpenTabActions = (vm, actions) => {
222
+ const value = { ...bindings.get(vm), ...actions };
223
+ bindings.set(vm, value);
224
+ services.get(vm)?.bind(value);
225
+ };
226
+ export const openProjectInNewTab = (vm, request) => services.get(vm)?.open(request) ?? false;
227
+ export const cancelProjectTabOpening = (document) => documents.get(document)?.cancel() ?? false;
@@ -1,7 +1,8 @@
1
1
  /** Presentation is supplied by the host's CSS Modules build. */
2
- export declare function createProjectDialogService({ styles, snackbarStyles }: {
2
+ export declare function createProjectDialogService({ styles, snackbarStyles, isCancelled }: {
3
3
  styles: Record<string, string>;
4
4
  snackbarStyles: Record<string, string>;
5
+ isCancelled?: (error: unknown) => boolean;
5
6
  }): {
6
7
  createProjectDialogs: (document: any, properties: any, history: any, diagnostics: any, { locale: hostLocale, getLocale }?: {
7
8
  locale?: string;
@@ -4,8 +4,9 @@ import { contactLink, descriptionParts } from './links.js';
4
4
  import { diagnosticText } from './diagnostics.js';
5
5
  import { renderBundleAssetForm, renderPayloadForm } from '../project-payload-forms.js';
6
6
  import { isValidSaveName } from '../project-file-dialogs.js';
7
+ import { closeProjectLoadFailure, showProjectLoadFailure } from '../project-load-failure.js';
7
8
  /** Presentation is supplied by the host's CSS Modules build. */
8
- export function createProjectDialogService({ styles, snackbarStyles }) {
9
+ export function createProjectDialogService({ styles, snackbarStyles, isCancelled = () => false }) {
9
10
  const element = (document, tag, text, attributes = {}) => {
10
11
  const node = document.createElement(tag);
11
12
  if (text !== undefined)
@@ -47,8 +48,10 @@ export function createProjectDialogService({ styles, snackbarStyles }) {
47
48
  };
48
49
  const unsubscribe = properties.subscribe(() => {
49
50
  // A form must never apply an old project's draft to the newly opened project.
50
- if (properties.loadState().phase === 'loading')
51
+ if (properties.loadState().phase === 'loading') {
51
52
  close();
53
+ closeProjectLoadFailure(document);
54
+ }
52
55
  });
53
56
  const stopNotice = diagnostics?.subscribe(() => {
54
57
  const sessions = diagnostics.snapshot();
@@ -62,6 +65,12 @@ export function createProjectDialogService({ styles, snackbarStyles }) {
62
65
  notice?.remove();
63
66
  const locale = getLocale?.() || hostLocale || document.documentElement.lang || 'en';
64
67
  const ja = locale.startsWith('ja');
68
+ if (error.type === 'project-error') {
69
+ notice = null;
70
+ showProjectLoadFailure(document, { locale, cancelled: isCancelled(error),
71
+ onDetails: () => api.showDiagnostics(locale, sessions[0].id) });
72
+ return;
73
+ }
65
74
  notice = element(document, 'aside', undefined, { class: snackbarStyles.snackbar, 'data-project-tools': '',
66
75
  'data-testid': 'project-diagnostics-snackbar' });
67
76
  const message = error.type === 'project-error' ?
@@ -355,7 +364,7 @@ export function createProjectDialogService({ styles, snackbarStyles }) {
355
364
  done.focus();
356
365
  },
357
366
  ownsKeyEvent: event => Boolean(event.target?.closest?.('[data-project-tools]')),
358
- dispose() { unsubscribe(); stopNotice?.(); notice?.remove(); close(); }
367
+ dispose() { unsubscribe(); stopNotice?.(); notice?.remove(); close(); closeProjectLoadFailure(document); }
359
368
  };
360
369
  return api;
361
370
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-workbench",
3
- "version": "0.29.1",
3
+ "version": "0.30.0",
4
4
  "description": "The TurboWarp Plus Editor workbench: layout, dockable sprite tabs, stage, debugger tab and file menu",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -154,6 +154,14 @@
154
154
  "types": "./dist/project-tools/integration.d.ts",
155
155
  "default": "./dist/project-tools/integration.js"
156
156
  },
157
+ "./project-open-tabs": {
158
+ "types": "./dist/project-open-tabs.d.ts",
159
+ "default": "./dist/project-open-tabs.js"
160
+ },
161
+ "./project-load-failure": {
162
+ "types": "./dist/project-load-failure.d.ts",
163
+ "default": "./dist/project-load-failure.js"
164
+ },
157
165
  "./project-folder-workflows": {
158
166
  "types": "./dist/project-folder-workflows.d.ts",
159
167
  "default": "./dist/project-folder-workflows.js"
@@ -0,0 +1,105 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ interface FailureOptions {
3
+ cancelled: boolean;
4
+ locale?: string;
5
+ onDetails?(): void;
6
+ onReview?(): void;
7
+ }
8
+ const screens = new WeakMap<Document, {update(options: FailureOptions): void; close(): void}>();
9
+ let sequence = 0;
10
+
11
+ /** A fresh tab may include about:blank in history without having a usable previous page. */
12
+ export function canReturnToPreviousPage(document: Document) {
13
+ const view = document.defaultView!;
14
+ const navigation = (view as Window & {navigation?: {canGoBack: boolean}}).navigation;
15
+ return view.history.length > 1 && !(navigation?.canGoBack === false && !document.referrer);
16
+ }
17
+
18
+ /** Drop all opening instructions while preserving display preferences such as the language. */
19
+ export function projectStartURL(view: Window) {
20
+ const url = new URL('editor.html', view.location.href);
21
+ url.search = view.location.search;
22
+ for (const key of ['project_url', 'token', 'extension', 'twPlusOpenTab']) url.searchParams.delete(key);
23
+ url.hash = '';
24
+ return url;
25
+ }
26
+
27
+ /** A terminal opening result replaces the busy screen, including when navigation cannot leave it. */
28
+ export function showProjectLoadFailure(document: Document, options: FailureOptions) {
29
+ const existing = screens.get(document);
30
+ if (existing) {existing.update(options); return existing.close;}
31
+ const view = document.defaultView!;
32
+ const dialog = document.createElement('dialog');
33
+ dialog.setAttribute('role', 'alertdialog');
34
+ dialog.setAttribute('data-project-tools', '');
35
+ dialog.setAttribute('data-testid', 'project-load-failure');
36
+ const id = `project-load-failure-${++sequence}`;
37
+ dialog.setAttribute('aria-labelledby', `${id}-title`);
38
+ dialog.setAttribute('aria-describedby', `${id}-reason`);
39
+ Object.assign(dialog.style, {position: 'fixed', inset: '0', margin: '0', width: '100vw', height: '100dvh',
40
+ maxWidth: 'none', maxHeight: 'none', boxSizing: 'border-box', border: 'none', overflow: 'auto',
41
+ padding: 'clamp(24px, 6vw, 80px)', background: 'var(--ui-modal-background, Canvas)',
42
+ color: 'var(--ui-modal-foreground, CanvasText)', font: 'inherit'});
43
+ const main = document.createElement('main');
44
+ Object.assign(main.style, {maxWidth: '680px', minHeight: '100%', margin: '0 auto',
45
+ display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: '20px'});
46
+ const title = document.createElement('h1'); title.id = `${id}-title`; title.tabIndex = -1;
47
+ Object.assign(title.style, {fontSize: 'clamp(24px, 4vw, 36px)', margin: '0', lineHeight: '1.3'});
48
+ const reason = document.createElement('p'); reason.id = `${id}-reason`;
49
+ Object.assign(reason.style, {margin: '0', fontSize: '18px', lineHeight: '1.7'});
50
+ const actions = document.createElement('div');
51
+ Object.assign(actions.style, {display: 'flex', flexWrap: 'wrap', gap: '12px'});
52
+ const button = (action: () => void) => {
53
+ const element = document.createElement('button'); element.type = 'button';
54
+ Object.assign(element.style, {font: 'inherit', padding: '12px 18px', minHeight: '44px', cursor: 'pointer',
55
+ border: '1px solid currentColor', borderRadius: '6px', background: 'transparent', color: 'inherit'});
56
+ element.addEventListener('click', action); actions.append(element); return element;
57
+ };
58
+ const back = button(() => view.history.back());
59
+ // Reopen the same requested project so the person can reconsider extension permissions.
60
+ // Reload keeps its URL, including its project source, instead of opening a default project.
61
+ let review = options.onReview ?? (() => view.location.reload());
62
+ const confirm = button(() => review());
63
+ Object.assign(confirm.style, {background: 'var(--looks-secondary, #1d4ed8)', color: '#fff', borderColor: 'transparent'});
64
+ const closeTab = button(() => view.close());
65
+ let details: (() => void) | undefined;
66
+ const log = button(() => details?.());
67
+ main.append(title, reason, actions); dialog.append(main);
68
+ // Escape must not expose the stale loading screen underneath the terminal result.
69
+ dialog.addEventListener('cancel', event => event.preventDefault());
70
+ let locale = options.locale ?? new URL(view.location.href).searchParams.get('lang') ?? document.documentElement.lang ?? 'en';
71
+ const screen = {
72
+ update(value: FailureOptions) {
73
+ locale = value.locale ?? locale;
74
+ details = value.onDetails ?? details;
75
+ review = value.onReview ?? review;
76
+ const ja = locale.startsWith('ja');
77
+ dialog.dataset.outcome = value.cancelled ? 'cancelled' : 'failed';
78
+ title.textContent = ja ? '作品を開けませんでした' : 'The project could not be opened';
79
+ reason.textContent = value.cancelled ?
80
+ (ja ? '機能拡張を実行しないことを選んだため、作品の読み込みを中止しました。' :
81
+ 'You chose not to run the extensions, so loading the project has stopped.') :
82
+ (ja ? '読み込み中に問題が起きたため、作品の読み込みを中止しました。詳細ログを確認できます。' :
83
+ 'Loading stopped because a problem occurred. You can view the detailed log.');
84
+ back.textContent = ja ? '前の画面に戻る' : 'Go back';
85
+ back.disabled = !canReturnToPreviousPage(document);
86
+ Object.assign(back.style, {opacity: back.disabled ? '0.45' : '1',
87
+ cursor: back.disabled ? 'default' : 'pointer'});
88
+ confirm.textContent = ja ? '確認画面に戻る' : 'Return to confirmation';
89
+ closeTab.textContent = ja ? 'このタブを閉じる' : 'Close this tab';
90
+ closeTab.hidden = !new URL(view.location.href).searchParams.has('twPlusOpenTab');
91
+ log.textContent = ja ? '詳細ログを表示' : 'View detailed log'; log.hidden = !details;
92
+ },
93
+ close() {dialog.remove(); screens.delete(document);}
94
+ };
95
+ screens.set(document, screen); screen.update(options);
96
+ document.body.append(dialog); dialog.showModal(); title.focus();
97
+ return screen.close;
98
+ }
99
+
100
+ export const closeProjectLoadFailure = (document: Document) => screens.get(document)?.close();
101
+
102
+ /** Preserve routing identity while ending the load; no default-project fetch follows a refusal. */
103
+ export function stoppedProjectLoadState(initial: any, states: {NOT_LOADED: string}, current = initial) {
104
+ return {...current, loadingState: states.NOT_LOADED, projectData: null, error: null};
105
+ }
@@ -0,0 +1,201 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ import {showNotice} from './project-notice.js';
3
+ import type {ProjectFileStorage} from './project-file-dialogs.js';
4
+ import {canReturnToPreviousPage, closeProjectLoadFailure, projectStartURL as startURL,
5
+ showProjectLoadFailure} from './project-load-failure.js';
6
+
7
+ export type ProjectTabCommand = 'folder' | 'browser-folder' | 'remote' | 'catalog';
8
+ export type ProjectTabRequest = {kind: 'file'; file: File; handle?: FileSystemFileHandle} |
9
+ {kind: 'command'; command: ProjectTabCommand} |
10
+ {kind: 'folder'; directory: FileSystemDirectoryHandle; root?: FileSystemDirectoryHandle};
11
+ interface TabActions {
12
+ storage: ProjectFileStorage;
13
+ commands: Partial<Record<ProjectTabCommand, () => unknown>>;
14
+ openDirectory?: (directory: FileSystemDirectoryHandle, root?: FileSystemDirectoryHandle) => Promise<unknown>;
15
+ fileOpened?(file: File): void;
16
+ }
17
+ interface TabPorts {
18
+ document: Document;
19
+ locale(): string;
20
+ ready(): boolean;
21
+ subscribe(listener: () => void): () => void;
22
+ isCancelled(error: unknown): boolean;
23
+ }
24
+ interface TabVM {
25
+ loadProject(input: unknown): Promise<unknown>;
26
+ runtime: {on(name: string, listener: () => void): void; off(name: string, listener: () => void): void};
27
+ }
28
+ const parameter = 'twPlusOpenTab';
29
+ const services = new WeakMap<object, ReturnType<typeof createService>>();
30
+ const documents = new WeakMap<Document, ReturnType<typeof createService>>();
31
+ const bindings = new WeakMap<object, Partial<TabActions>>();
32
+
33
+ function createService(host: object, ports: TabPorts) {
34
+ const vm = host as TabVM;
35
+ const view = ports.document.defaultView!;
36
+ const token = new URL(view.location.href).searchParams.get(parameter);
37
+ let incoming = Boolean(token);
38
+ let actions: TabActions | undefined;
39
+ let received = false;
40
+ let alive = true;
41
+ let channel: BroadcastChannel | undefined;
42
+ let readyTimer: number | undefined;
43
+ let prompt: HTMLDialogElement | undefined;
44
+ let reviewRequest: ProjectTabRequest | undefined;
45
+ const returnToReview = () => {
46
+ if (!reviewRequest) return;
47
+ closeProjectLoadFailure(ports.document);
48
+ void run(reviewRequest);
49
+ };
50
+ const pending = new Set<() => void>();
51
+ const startup = new URL(view.location.href).searchParams.has('project_url');
52
+ const report = (error: unknown) => showNotice(ports.document,
53
+ ports.locale().startsWith('ja') ? `別のタブで作品を開けませんでした。${String(error)}` :
54
+ `Could not open the project in another tab. ${String(error)}`, {locale: ports.locale()});
55
+ const cancel = () => {
56
+ showProjectLoadFailure(ports.document, {locale: ports.locale(), cancelled: true,
57
+ onReview: reviewRequest ? returnToReview : undefined});
58
+ if (incoming) {
59
+ view.close();
60
+ return true;
61
+ }
62
+ if (!startup) return false;
63
+ // A directly opened URL has no previous screen. Keep the stopped result visible and
64
+ // let the person explicitly reopen confirmation rather than inventing history.
65
+ if (canReturnToPreviousPage(ports.document)) view.history.back();
66
+ return true;
67
+ };
68
+ const completed = () => {
69
+ if (!incoming || !received) return;
70
+ incoming = false;
71
+ view.history.replaceState(view.history.state, '', startURL(view).href);
72
+ };
73
+ vm.runtime.on('PROJECT_LOADED', completed);
74
+
75
+ const run = async (request: ProjectTabRequest) => {
76
+ if (!actions) return;
77
+ // Keep only the explicitly selected incoming request for reconsideration, never the
78
+ // original tab's project. A transferred File cannot be recovered by reloading its URL.
79
+ reviewRequest = request.kind === 'command' ? undefined : request;
80
+ try {
81
+ if (request.kind === 'file') {
82
+ // Only the explicitly selected incoming file crosses tabs; the original VM is untouched.
83
+ await vm.loadProject(await request.file.arrayBuffer());
84
+ const handle = /\.sb3$/i.test(request.file.name) ? request.handle ?? null : null;
85
+ actions.storage.finish(handle, request.file.name.replace(/\.sb[23]?$/i, '').substring(0, 100), true);
86
+ actions.fileOpened?.(request.file);
87
+ reviewRequest = undefined;
88
+ } else if (request.kind === 'folder') {
89
+ if (!actions.openDirectory) throw new Error('Folder opening is unavailable');
90
+ await actions.openDirectory(request.directory, request.root);
91
+ } else {
92
+ const command = actions.commands[request.command];
93
+ if (!command) throw new Error('The requested opening command is unavailable');
94
+ if (request.command === 'catalog' || request.command === 'remote') {
95
+ await command();
96
+ return;
97
+ }
98
+ const ja = ports.locale().startsWith('ja');
99
+ const names: Record<ProjectTabCommand, [string, string]> = {
100
+ folder: ['フォルダを選ぶ', 'Choose a folder'],
101
+ 'browser-folder': ['ブラウザーに保存したフォルダを選ぶ', 'Choose a browser folder'],
102
+ remote: ['Git のリモートリポジトリを選ぶ', 'Choose a Git remote repository'],
103
+ catalog: ['プロジェクト一覧を開く', 'Show projects']
104
+ };
105
+ prompt = ports.document.createElement('dialog');
106
+ prompt.setAttribute('data-project-tools', '');
107
+ const text = ports.document.createElement('p');
108
+ text.textContent = ja ? '元のタブを残して、このタブで別の作品を開きます。' :
109
+ 'Your original tab stays open. Open another project in this tab.';
110
+ const button = ports.document.createElement('button'); button.type = 'button';
111
+ button.textContent = names[request.command][ja ? 0 : 1];
112
+ button.addEventListener('click', () => {
113
+ prompt?.remove(); prompt = undefined;
114
+ try {Promise.resolve(command()).catch(report);} catch (error) {report(error);}
115
+ });
116
+ prompt.append(text, button); ports.document.body.append(prompt); prompt.showModal();
117
+ }
118
+ } catch (error) {
119
+ if (ports.isCancelled(error)) cancel();
120
+ else showProjectLoadFailure(ports.document, {locale: ports.locale(), cancelled: false,
121
+ onReview: reviewRequest ? returnToReview : undefined});
122
+ }
123
+ };
124
+ const ready = () => {
125
+ if (alive && incoming && !received && actions?.storage && ports.ready()) channel?.postMessage({type: 'ready'});
126
+ };
127
+ if (token) {
128
+ channel = new view.BroadcastChannel(`tw-plus-project-open-${token}`);
129
+ channel.onmessage = event => {
130
+ if (!alive || received || !actions || !ports.ready() || event.data?.type !== 'open') return;
131
+ received = true;
132
+ channel!.postMessage({type: 'received'});
133
+ view.clearInterval(readyTimer);
134
+ channel!.close(); channel = undefined;
135
+ void run(event.data.request);
136
+ };
137
+ readyTimer = view.setInterval(ready, 500);
138
+ }
139
+ const unsubscribe = ports.subscribe(ready);
140
+
141
+ const launch = (request: ProjectTabRequest) => {
142
+ const id = view.crypto.randomUUID();
143
+ const url = startURL(view); url.searchParams.set(parameter, id);
144
+ const outgoing = new view.BroadcastChannel(`tw-plus-project-open-${id}`);
145
+ let child: Window | null;
146
+ let sent = false;
147
+ const cleanup = () => {view.clearInterval(timer); outgoing.close(); pending.delete(cleanup);};
148
+ outgoing.onmessage = event => {
149
+ if (event.data?.type === 'ready' && !sent) {
150
+ try {outgoing.postMessage({type: 'open', request}); sent = true;}
151
+ catch (error) {cleanup(); report(error);}
152
+ } else if (event.data?.type === 'received') cleanup();
153
+ };
154
+ child = view.open(url.href, '_blank');
155
+ if (child) child.opener = null;
156
+ const timer = view.setInterval(() => {if (child?.closed) cleanup();}, 1000);
157
+ pending.add(cleanup);
158
+ if (!child) {
159
+ cleanup();
160
+ const ja = ports.locale().startsWith('ja');
161
+ const retry = ports.document.createElement('dialog');
162
+ retry.setAttribute('data-project-tools', '');
163
+ const text = ports.document.createElement('p');
164
+ text.textContent = ja ? '新しいタブを開くには、下のボタンを押してください。元の作品はそのまま残ります。' :
165
+ 'Use the button below to open a new tab. Your original project stays open.';
166
+ const button = ports.document.createElement('button'); button.type = 'button';
167
+ button.textContent = ja ? '新しいタブで開く' : 'Open in a new tab';
168
+ button.addEventListener('click', () => {retry.remove(); launch(request);});
169
+ const close = ports.document.createElement('button'); close.type = 'button';
170
+ close.textContent = ja ? 'キャンセル' : 'Cancel'; close.addEventListener('click', () => retry.remove());
171
+ retry.append(text, button, close); ports.document.body.append(retry); retry.showModal();
172
+ }
173
+ };
174
+ return {
175
+ open(request: ProjectTabRequest) {
176
+ if (incoming) return false;
177
+ try {launch(request);} catch (error) {report(error);}
178
+ return true;
179
+ },
180
+ bind(value: Partial<TabActions>) {actions = {...actions, ...value} as TabActions; ready();},
181
+ cancel,
182
+ dispose() {
183
+ alive = false; unsubscribe(); view.clearInterval(readyTimer); channel?.close(); prompt?.remove();
184
+ reviewRequest = undefined;
185
+ for (const close of pending) close();
186
+ vm.runtime.off('PROJECT_LOADED', completed);
187
+ }
188
+ };
189
+ }
190
+
191
+ export function installProjectOpenTabs(vm: object, ports: TabPorts) {
192
+ const service = createService(vm, ports);
193
+ services.set(vm, service); documents.set(ports.document, service);
194
+ if (bindings.has(vm)) service.bind(bindings.get(vm)!);
195
+ return () => {service.dispose(); services.delete(vm); documents.delete(ports.document);};
196
+ }
197
+ export const bindProjectOpenTabActions = (vm: object, actions: Partial<TabActions>) => {
198
+ const value = {...bindings.get(vm), ...actions}; bindings.set(vm, value); services.get(vm)?.bind(value);
199
+ };
200
+ export const openProjectInNewTab = (vm: object, request: ProjectTabRequest) => services.get(vm)?.open(request) ?? false;
201
+ export const cancelProjectTabOpening = (document: Document) => documents.get(document)?.cancel() ?? false;
@@ -4,10 +4,12 @@ import {contactLink, descriptionParts} from './links.js';
4
4
  import {diagnosticText} from './diagnostics.js';
5
5
  import {renderBundleAssetForm, renderPayloadForm} from '../project-payload-forms.js';
6
6
  import {isValidSaveName} from '../project-file-dialogs.js';
7
+ import {closeProjectLoadFailure, showProjectLoadFailure} from '../project-load-failure.js';
7
8
 
8
9
  /** Presentation is supplied by the host's CSS Modules build. */
9
- export function createProjectDialogService({styles, snackbarStyles}: {
10
+ export function createProjectDialogService({styles, snackbarStyles, isCancelled = () => false}: {
10
11
  styles: Record<string, string>; snackbarStyles: Record<string, string>;
12
+ isCancelled?: (error: unknown) => boolean;
11
13
  }) {
12
14
  const element = <Tag extends keyof HTMLElementTagNameMap>(document: Document, tag: Tag, text?: string, attributes: Record<string, string> = {}) => {
13
15
  const node = document.createElement(tag);
@@ -47,7 +49,7 @@ export function createProjectDialogService({styles, snackbarStyles}: {
47
49
  };
48
50
  const unsubscribe = properties.subscribe(() => {
49
51
  // A form must never apply an old project's draft to the newly opened project.
50
- if (properties.loadState().phase === 'loading') close();
52
+ if (properties.loadState().phase === 'loading') {close(); closeProjectLoadFailure(document);}
51
53
  });
52
54
  const stopNotice = diagnostics?.subscribe(() => {
53
55
  const sessions = diagnostics.snapshot();
@@ -59,6 +61,12 @@ export function createProjectDialogService({styles, snackbarStyles}: {
59
61
  notice?.remove();
60
62
  const locale = getLocale?.() || hostLocale || document.documentElement.lang || 'en';
61
63
  const ja = locale.startsWith('ja');
64
+ if (error.type === 'project-error') {
65
+ notice = null;
66
+ showProjectLoadFailure(document, {locale, cancelled: isCancelled(error),
67
+ onDetails: () => api.showDiagnostics(locale, sessions[0].id)});
68
+ return;
69
+ }
62
70
  notice = element(document, 'aside', undefined, {class: snackbarStyles.snackbar, 'data-project-tools': '',
63
71
  'data-testid': 'project-diagnostics-snackbar'});
64
72
  const message = error.type === 'project-error' ?
@@ -332,7 +340,7 @@ export function createProjectDialogService({styles, snackbarStyles}: {
332
340
  render(); dialog.showModal(); done.focus();
333
341
  },
334
342
  ownsKeyEvent: event => Boolean(event.target?.closest?.('[data-project-tools]')),
335
- dispose () { unsubscribe(); stopNotice?.(); notice?.remove(); close(); }
343
+ dispose () { unsubscribe(); stopNotice?.(); notice?.remove(); close(); closeProjectLoadFailure(document); }
336
344
  };
337
345
  return api;
338
346
  };