@kubohiroya/turbowarp-plus-editor-project-folder 0.16.0 → 0.18.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/src/explorer.tsx CHANGED
@@ -7,7 +7,7 @@ import {projectFolderOverwriteWarning} from './create-folder.js';
7
7
  import {followProjectFolder} from './folder-registry.js';
8
8
  import {hiddenEntry, readExplorerState, subscribeExplorerState, writeExplorerState} from './explorer-state.js';
9
9
  import type {ExplorerTreeState} from './explorer-state.js';
10
- import type {ExplorerMutation, FollowedFolder} from './folder-registry.js';
10
+ import type {ExplorerMutation, FollowedFolder, ProjectFolderLocation} from './folder-registry.js';
11
11
  import type {Json, Project} from './source.js';
12
12
  import {canMoveExplorerEntry, copyExplorerDirectory, copyExplorerFile, createExplorerDirectory, deleteExplorerEntry, ExplorerFileError,
13
13
  explorerNameAvailable, moveExplorerEntry, parentPath, renameExplorerEntry, resolveExplorerDirectory} from './explorer-files.js';
@@ -58,7 +58,17 @@ const messages = {
58
58
  label: 'Project folder', loading: 'Loading…', empty: 'This folder is empty.', noMatches: 'No matching files.',
59
59
  results: 'Matching files',
60
60
  noFolder: 'Open a folder to show its files here.', open: 'Open Folder…',
61
- create: 'Create Project Folder', creating: 'Creating project folder…',
61
+ creating: 'Creating project folder…',
62
+ storageIntro: 'Save the current project as a folder containing its project data, costumes, sounds and other files.',
63
+ deviceTitle: 'Save to a folder on this device',
64
+ deviceDescription: 'Choose a folder on your computer. You can view its files in Finder or File Explorer and work with them in VS Code or other apps.',
65
+ deviceNext: 'The button opens a folder picker. Choose an empty folder or create a new one there.',
66
+ deviceCreate: 'Choose a Folder and Save…',
67
+ browserTitle: 'Save in this browser',
68
+ browserDescription: 'Enter a name to create a project folder in this site’s storage, without choosing a folder on your computer. Its files are not directly visible in Finder, File Explorer or other apps.',
69
+ browserRetention: 'The project stays in this browser profile on this device. Clearing site data or automatic browser cleanup may delete it. Keep a copy by exporting an SB3 or ZIP, or saving it to GitHub.',
70
+ browserReopen: 'To continue later, use Open Folder Saved in This Browser… in the File menu.',
71
+ browserCreate: 'Name and Save in This Browser…',
62
72
  createFailed: 'Could not create the project folder.',
63
73
  unavailable: 'File tabs are unavailable in this editor layout.',
64
74
  failed: 'This folder could not be read.', denied: 'Permission to read this folder was not granted.',
@@ -78,7 +88,17 @@ const messages = {
78
88
  label: '作品フォルダ', loading: '読み込んでいます…', empty: 'このフォルダは空です。', noMatches: '該当するファイルはありません。',
79
89
  results: '検索結果',
80
90
  noFolder: 'フォルダを開くと、ここにファイルを表示します。', open: 'フォルダを開く…',
81
- create: 'プロジェクトフォルダを作成', creating: 'プロジェクトフォルダを作成しています…',
91
+ creating: 'プロジェクトフォルダを作成しています…',
92
+ storageIntro: '編集中の作品を、作品データ・コスチューム・音などのファイルをまとめたプロジェクトフォルダとして保存します。',
93
+ deviceTitle: '端末のフォルダに保存',
94
+ deviceDescription: 'パソコン上のフォルダを選んで保存します。Finder やエクスプローラーでファイルを確認でき、VS Code などの外部アプリでも扱えます。',
95
+ deviceNext: 'ボタンを押すとフォルダ選択画面が開きます。空のフォルダを選ぶか、その画面で新しいフォルダを作成してください。',
96
+ deviceCreate: 'フォルダを選んで保存…',
97
+ browserTitle: 'このブラウザー内に保存',
98
+ browserDescription: '名前を入力すると、このサイト専用の保存領域にプロジェクトフォルダを作成します。パソコン上のフォルダを選ぶ必要はありません。Finder やエクスプローラー、外部アプリからファイルを直接見ることはできません。',
99
+ browserRetention: '保存した作品は、この端末のこのブラウザーのプロファイル内に残ります。サイトデータの削除やブラウザーの自動整理で消える場合があります。SB3・ZIP の書き出しや GitHub への保存で、別の場所にも作品を残してください。',
100
+ browserReopen: '次回は「ファイル」メニューの「ブラウザーに保存したフォルダを開く…」から開けます。',
101
+ browserCreate: '名前を付けてブラウザー内に保存…',
82
102
  createFailed: 'プロジェクトフォルダを作成できませんでした。',
83
103
  unavailable: 'このエディターのレイアウトではファイルをタブで開けません。',
84
104
  failed: 'このフォルダを読み込めません。', denied: 'このフォルダを読む許可がありません。',
@@ -191,9 +211,18 @@ background:repeating-conic-gradient(rgba(128,128,128,.22) 0 25%,transparent 0 50
191
211
  color:inherit;color:color-mix(in srgb,currentColor 78%,transparent);font-size:.75em;line-height:1.4;
192
212
  white-space:normal;overflow-wrap:anywhere}
193
213
  .${prefix}-status{opacity:.7;font-style:italic;padding-block:.15em}
194
- .${prefix}-empty{padding:.5em}
214
+ .${prefix}-empty{padding:.75em;line-height:1.6;overflow-wrap:anywhere}
195
215
  .${prefix}-empty p{margin:0 0 .6em}
196
- .${prefix}-empty button{color:inherit;background:transparent;border:1px solid currentColor;border-radius:4px;padding:.2em .6em;font:inherit;cursor:pointer}`;
216
+ .${prefix}-storage{padding-block:.8em;border-block-start:1px solid color-mix(in srgb,currentColor 25%,transparent)}
217
+ .${prefix}-storage h3{margin:0 0 .5em;font-size:1em}
218
+ .${prefix}-empty button{color:inherit;background:transparent;border:1px solid currentColor;border-radius:4px;padding:.4em .7em;font:inherit;cursor:pointer;white-space:normal;max-width:100%}
219
+ .${prefix}-storage button{display:inline-flex;align-items:center;gap:.45em;text-align:start;
220
+ border-radius:.65rem;padding:.55em .9em;background:var(--looks-secondary,#855cd6);
221
+ border-color:var(--looks-secondary,#855cd6);color:#fff;font-weight:600;line-height:1.4}
222
+ .${prefix}-storage button:hover:not(:disabled){background:color-mix(in srgb,var(--looks-secondary,#855cd6) 88%,#000)}
223
+ .${prefix}-storage button:focus-visible{outline:2px solid var(--looks-secondary,#855cd6);outline-offset:3px}
224
+ .${prefix}-storage button svg{flex:none}
225
+ .${prefix}-empty button:disabled{opacity:.6;cursor:wait}`;
197
226
 
198
227
  const indent = (level: number) => ({paddingInlineStart: `${0.25 + level * 1.1}em`});
199
228
 
@@ -213,6 +242,11 @@ const icons: Record<IconKind, string[]> = {
213
242
  'text': [page, corner, 'M5.5 7.5h5M5.5 9.5h5M5.5 11.5h3'],
214
243
  'file': [page, corner]
215
244
  };
245
+ const storageIcons: Record<ProjectFolderLocation, string[]> = {
246
+ device: icons.folder,
247
+ browser: ['M2.5 2.5h11a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1v-9a1 1 0 0 1 1-1z',
248
+ 'M1.5 5.5h13', 'M3.5 4h.1M5.5 4h.1']
249
+ };
216
250
  const extensionIcons: Record<string, IconKind> = {
217
251
  json: 'json', svg: 'image', png: 'image', jpg: 'image', jpeg: 'image', gif: 'image', bmp: 'image', webp: 'image',
218
252
  wav: 'sound', mp3: 'sound', ogg: 'sound', js: 'code', mjs: 'code', ts: 'code', md: 'text', txt: 'text'
@@ -844,8 +878,8 @@ export type FollowFileStatuses = (directory: FileSystemDirectoryHandle,
844
878
  type FolderViewProps = {
845
879
  vm: object;
846
880
  locale?: string;
847
- /** Saves the current project to a local folder. */
848
- createFolder?(): Promise<unknown>;
881
+ /** Saves the current project to the selected storage location. */
882
+ createFolder?(location?: ProjectFolderLocation): Promise<unknown>;
849
883
  marks?: FollowMarks;
850
884
  fileStatuses?: FollowFileStatuses;
851
885
  /** Reports unsaved text edits in open file tabs for the given folder. */
@@ -867,12 +901,12 @@ function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: follow
867
901
  const message = messagesFor(locale);
868
902
  const [creating, setCreating] = React.useState(false);
869
903
  const [createError, setCreateError] = React.useState('');
870
- const create = async () => {
904
+ const create = async (location: ProjectFolderLocation) => {
871
905
  if (!createFolder || creating) return;
872
906
  setCreating(true);
873
907
  setCreateError('');
874
908
  try {
875
- await createFolder();
909
+ await createFolder(location);
876
910
  } catch {
877
911
  setCreateError(message.createFailed);
878
912
  } finally {
@@ -938,8 +972,27 @@ function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: follow
938
972
  return <div className={`${prefix}-empty`}>
939
973
  <style>{css}</style>
940
974
  {createFolder ? <>
941
- <p>{projectFolderOverwriteWarning(locale)}</p>
942
- <button type="button" disabled={creating} onClick={() => void create()}>{message.create}</button>
975
+ <p>{message.storageIntro}</p>
976
+ {(folder.locations ?? ['device']).map(location => <section key={location}
977
+ className={`${prefix}-storage`} data-project-folder-location={location}>
978
+ <h3>{location === 'device' ? message.deviceTitle : message.browserTitle}</h3>
979
+ {location === 'device' ? <>
980
+ <p>{message.deviceDescription}</p>
981
+ <p>{message.deviceNext}</p>
982
+ <p>{projectFolderOverwriteWarning(locale)}</p>
983
+ </> : <>
984
+ <p>{message.browserDescription}</p>
985
+ <p>{message.browserRetention}</p>
986
+ <p>{message.browserReopen}</p>
987
+ </>}
988
+ <button type="button" disabled={creating} onClick={() => void create(location)}>
989
+ <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor"
990
+ strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" focusable="false">
991
+ {storageIcons[location].map((d, index) => <path key={index} d={d} />)}
992
+ </svg>
993
+ <span>{location === 'device' ? message.deviceCreate : message.browserCreate}</span>
994
+ </button>
995
+ </section>)}
943
996
  {creating && <p role="status">{message.creating}</p>}
944
997
  {createError && <p role="alert">{createError}</p>}
945
998
  </> : <>
@@ -1,10 +1,13 @@
1
1
  /** The project folder mounted for a VM, as a view of the folder follows it. */
2
2
  export type ExplorerMutation = (guard: () => void) => Promise<void>;
3
+ export type ProjectFolderLocation = 'device' | 'browser';
3
4
 
4
5
  export interface FollowedFolder {
5
6
  readonly directory: FileSystemDirectoryHandle | null;
6
- /** The folder the user chose for `directory`: itself, or the repository whose `project` folder it is. */
7
+ /** The folder the user chose for `directory`: itself, unless a host gave another one to `openDirectory`. */
7
8
  readonly root?: FileSystemDirectoryHandle | null;
9
+ /** Storage choices available when creating a project folder. */
10
+ readonly locations?: readonly ProjectFolderLocation[];
8
11
  subscribe(listener: () => void): () => void;
9
12
  subscribeEdits(listener: () => void): () => void;
10
13
  unsavedPaths(): ReadonlySet<string> | null;
@@ -28,7 +31,7 @@ export function registerFolder(vm: object, folder: FollowedFolder) {
28
31
 
29
32
  /**
30
33
  * Calls `listener` with the project folder mounted for `vm`, the directory open in it and the folder the user chose for
31
- * it (`root`, the directory itself or the repository that holds it in `project/`), now and whenever a folder is
34
+ * it (`root`, the directory itself unless a host gave another one), now and whenever a folder is
32
35
  * mounted, opened, closed or saved. `directory` and `root` are `null` while no folder is open. Returns the function
33
36
  * that stops it.
34
37
  */
package/src/index.ts CHANGED
@@ -2,21 +2,24 @@ import {FolderError} from './source.js';
2
2
  import {createFolderSession} from './session.js';
3
3
  import {isProjectFolderEmpty} from './create-folder.js';
4
4
  import {registerFolder} from './folder-registry.js';
5
+ import type {ProjectFolderLocation} from './folder-registry.js';
5
6
  import {openBrowserProjects} from './browser-projects.js';
6
7
  import type {BrowserProjects} from './browser-projects.js';
7
8
  import {chooseBrowserProject} from './browser-project-dialog.js';
8
- import type {Chosen, FolderHost, FolderVM, PickerWindow} from './session.js';
9
+ import {notProjectFolderMessage, showNotProjectFolderDialog} from './not-project-dialog.js';
10
+ import type {Chosen, FolderHost, FolderVM, OpenResult, PickerWindow} from './session.js';
9
11
 
10
12
  export type {Comparison, ComparisonRequest, ComparisonSection, FolderHost, FolderScreenState, FolderVM, OpenResult} from './session.js';
11
13
  export type {ReloadTarget} from './block-reload.js';
12
14
  export {followProjectFolder} from './folder-registry.js';
13
- export type {FollowedFolder} from './folder-registry.js';
15
+ export type {FollowedFolder, ProjectFolderLocation} from './folder-registry.js';
14
16
  export type {DeserializeBlocks} from './script-reload.js';
15
17
  export {createProjectFolder, projectFolderOverwriteWarning} from './create-folder.js';
16
18
  export {openBrowserProjects} from './browser-projects.js';
17
19
  export type {BrowserProject, BrowserProjects, BrowserStorageState} from './browser-projects.js';
18
20
  export {chooseBrowserProject, exportBrowserProject, zipFileName} from './browser-project-dialog.js';
19
21
  export type {BrowserProjectChoice} from './browser-project-dialog.js';
22
+ export {notProjectFolderMessage, showNotProjectFolderDialog} from './not-project-dialog.js';
20
23
  export {zipDirectory} from './zip.js';
21
24
 
22
25
  const messages = {
@@ -95,6 +98,17 @@ type ObserverWindow = PickerWindow & {FileSystemObserver?: new (callback: () =>
95
98
  */
96
99
  export type BrowserStorageMode = 'fallback' | 'always' | 'off';
97
100
 
101
+ /** Options of `openDirectory`. */
102
+ export interface OpenDirectoryOptions {
103
+ /**
104
+ * Whether a folder that is not a project folder is told to the user in the error dialog (default true). A host
105
+ * that tells the user in its own way passes false and acts on the `not-project` result.
106
+ */
107
+ notProjectDialog?: boolean;
108
+ /** The locale of the dialog; defaults to the `locale` given to `mountProjectFolder`. */
109
+ locale?: string;
110
+ }
111
+
98
112
  const abort = () => new DOMException('The user closed the dialog', 'AbortError');
99
113
 
100
114
  /**
@@ -115,16 +129,19 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
115
129
  if (!choice) throw abort();
116
130
  return choice;
117
131
  };
118
- // A folder kept in the browser was chosen as a whole, so its stored folder is the root even when the project is inside.
119
- const chooseBrowserFolder = async (): Promise<Chosen> => {
120
- const {project, directory} = await chooseBrowser('open');
121
- return {directory, root: await browserProjects!.root(project.id).catch(() => null) ?? directory};
122
- };
132
+ // The stored folder is opened as a whole, so it is its own root, as a folder on the device is.
133
+ const chooseBrowserFolder = async (): Promise<Chosen> => ({directory: (await chooseBrowser('open')).directory});
123
134
  const pickDirectory = devicePicker ?
124
135
  async (options: {id: string; mode: 'readwrite'}): Promise<Chosen> => ({directory: await devicePicker.call(view, options)}) :
125
136
  chooseBrowserFolder;
126
- const pickNewDirectory = async (options: {id: string; mode: 'readwrite'}, title?: string) =>
127
- devicePicker ? devicePicker.call(view, options) : (await chooseBrowser('create', title)).directory;
137
+ const locations: ProjectFolderLocation[] = [];
138
+ if (devicePicker) locations.push('device');
139
+ if (browserProjects) locations.push('browser');
140
+ const pickNewDirectory = async (options: {id: string; mode: 'readwrite'}, title?: string,
141
+ location: ProjectFolderLocation = devicePicker ? 'device' : 'browser') => {
142
+ if (!locations.includes(location)) throw new FolderError('unsupported');
143
+ return location === 'device' ? devicePicker!.call(view, options) : (await chooseBrowser('create', title)).directory;
144
+ };
128
145
  /** Runs `run` with the browser folder of `directory` locked against other tabs, and marks it as updated. */
129
146
  const withBrowserProject = async <T>(directory: FileSystemDirectoryHandle | null, run: () => Promise<T>) => {
130
147
  const project = directory && browserProjects ? await browserProjects.find(directory).catch(() => null) : null;
@@ -160,6 +177,9 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
160
177
  const detail = error instanceof FolderError && error.message !== error.code ? ` (${error.message})` : '';
161
178
  report((error instanceof FolderError ? message[error.code] : message.failed) + detail);
162
179
  };
180
+ // The open project stays; the dialog tells why nothing opened, or the status line where no dialog can be shown.
181
+ const notProject = (locale: string) => showNotProjectFolderDialog({document, locale})
182
+ .catch(() => report(notProjectFolderMessage(locale)));
163
183
  let stopWatching: (() => void) | undefined;
164
184
  let renderReload = () => {};
165
185
  if (host.blockReload) {
@@ -279,19 +299,23 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
279
299
  notice.remove();
280
300
  };
281
301
  }
302
+ const opened = (locale: string, result: OpenResult) => {
303
+ if (result === 'opened') report(messageFor(locale).opened);
304
+ else if (result === 'not-project') void notProject(locale);
305
+ };
282
306
  const menu: MenuEntry = {
283
307
  deviceFolders: typeof devicePicker === 'function',
284
308
  session,
285
309
  open(locale) {
286
310
  const message = messageFor(locale);
287
311
  session.open(options => pickDirectory(options), () => view.confirm(message.replace))
288
- .then(result => {if (result === 'opened') report(message.opened);}, error => fail(locale, error)).finally(renderReload);
312
+ .then(result => opened(locale, result), error => fail(locale, error)).finally(renderReload);
289
313
  renderReload();
290
314
  },
291
315
  openBrowser: browserProjects ? locale => {
292
316
  const message = messageFor(locale);
293
317
  session.open(chooseBrowserFolder, () => view.confirm(message.replace))
294
- .then(result => {if (result === 'opened') report(message.opened);}, error => fail(locale, error)).finally(renderReload);
318
+ .then(result => opened(locale, result), error => fail(locale, error)).finally(renderReload);
295
319
  renderReload();
296
320
  } : undefined,
297
321
  save(locale) {
@@ -314,6 +338,7 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
314
338
  const unregister = registerFolder(vm, {
315
339
  get directory() {return session.directory;},
316
340
  get root() {return session.root;},
341
+ locations,
317
342
  subscribe: listener => session.subscribe(listener),
318
343
  subscribeEdits: listener => session.subscribeEdits(listener),
319
344
  unsavedPaths: () => session.unsavedPaths(),
@@ -321,8 +346,18 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
321
346
  mutate: (directory, operation) => session.mutate(directory, operation).finally(renderReload)
322
347
  });
323
348
  return {
324
- openDirectory: (...args: Parameters<typeof session.openDirectory>) =>
325
- session.openDirectory(...args).finally(renderReload),
349
+ /**
350
+ * Opens the project at the root of `directory`, as the user's Open would, and resolves with the result. A folder
351
+ * that is not a project folder changes nothing, shows the error dialog unless `options.notProjectDialog` is
352
+ * false, and resolves with `not-project`. `root` is the folder the user chose, for a host that located the
353
+ * project in it; it defaults to `directory`.
354
+ */
355
+ openDirectory: (directory: FileSystemDirectoryHandle, confirmReplace: () => boolean,
356
+ root?: FileSystemDirectoryHandle | null, options: OpenDirectoryOptions = {}): Promise<OpenResult> =>
357
+ session.openDirectory(directory, confirmReplace, root ?? undefined).then(result => {
358
+ if (result === 'not-project' && options.notProjectDialog !== false) void notProject(options.locale ?? locale);
359
+ return result;
360
+ }).finally(renderReload),
326
361
  unsavedPaths: () => session.unsavedPaths(),
327
362
  readUnsavedFile: (path: string) => session.readUnsavedFile(path),
328
363
  subscribeEdits: (listener: () => void) => session.subscribeEdits(listener),
@@ -333,19 +368,21 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
333
368
  * Creates a project folder from a snapshot. `title` names a folder made in the browser, where the user names a
334
369
  * new folder instead of picking one on the device.
335
370
  */
336
- createFromSnapshot({prepareFiles, collectEdits, directory, current = () => true, title}: {
371
+ createFromSnapshot({prepareFiles, collectEdits, directory, current = () => true, title, location}: {
337
372
  prepareFiles: () => Promise<ReadonlyMap<string, Uint8Array>>;
338
373
  collectEdits?: () => Promise<void>;
339
374
  directory?: FileSystemDirectoryHandle;
340
375
  current?: () => boolean;
341
376
  title?: string;
377
+ /** Explicit destination; omitted uses the device picker when available. */
378
+ location?: ProjectFolderLocation;
342
379
  }) {
343
380
  const message = locale.startsWith('ja') ?
344
381
  '指定されたフォルダは空ではありません。フォルダに保存されている内容が上書きされる場合があります。よろしいですか?' :
345
382
  'The selected folder is not empty. Contents in the folder may be overwritten. Continue?';
346
383
  return session.createFromSnapshot(async () => {
347
384
  try {
348
- const selected = directory ?? await pickNewDirectory({id: 'turbowarp-plus-project-folder', mode: 'readwrite'}, title);
385
+ const selected = directory ?? await pickNewDirectory({id: 'turbowarp-plus-project-folder', mode: 'readwrite'}, title, location);
349
386
  if (!current()) return null;
350
387
  const overwrite = !await isProjectFolderEmpty(selected);
351
388
  if (!current() || (overwrite && !view.confirm(message))) return null;
@@ -363,8 +400,8 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
363
400
  */
364
401
  get directory() {return session.directory;},
365
402
  /**
366
- * The folder the user chose for the loaded project, or `null` like `directory`. It is `directory` itself, or
367
- * the repository whose `project` folder holds the project, or the stored folder of a folder kept in the browser.
403
+ * The folder the user chose for the loaded project, or `null` like `directory`. It is `directory` itself, the
404
+ * project folder, unless the host gave another folder to `openDirectory`.
368
405
  */
369
406
  get root() {return session.root;},
370
407
  dispose() {
@@ -0,0 +1,63 @@
1
+ const messages = {
2
+ en: {title: 'Cannot Open Folder', notProject: 'This folder is not a project folder.', ok: 'OK'},
3
+ ja: {title: 'フォルダを開けません', notProject: 'このフォルダはプロジェクトフォルダではありません。', ok: 'OK'}
4
+ };
5
+
6
+ let dialogs = 0;
7
+
8
+ /** The message the dialog shows, for a host that tells the user in its own way. */
9
+ export const notProjectFolderMessage = (locale = 'en') => (locale.startsWith('ja') ? messages.ja : messages.en).notProject;
10
+
11
+ /**
12
+ * Tells the user, in a modal dialog, that the folder they tried to open is not a project folder. Resolves when the
13
+ * dialog closes, after the focus went back to where it was.
14
+ */
15
+ export async function showNotProjectFolderDialog({document, locale = 'en'}: {document: Document; locale?: string}): Promise<void> {
16
+ const message = locale.startsWith('ja') ? messages.ja : messages.en;
17
+ const returnFocus = document.activeElement as HTMLElement | null;
18
+ const id = `tw-plus-project-folder-error-${++dialogs}`;
19
+ const dialog = document.createElement('dialog');
20
+ dialog.dataset.projectFolderError = 'not-project';
21
+ dialog.setAttribute('role', 'alertdialog');
22
+ dialog.setAttribute('aria-labelledby', `${id}-title`);
23
+ dialog.setAttribute('aria-describedby', `${id}-message`);
24
+ Object.assign(dialog.style, {
25
+ width: 'min(26rem, calc(100vw - 2rem))', padding: '1rem 1.25rem', background: 'Canvas', color: 'CanvasText',
26
+ border: '1px solid GrayText', borderRadius: '0.5rem', fontFamily: 'inherit', fontSize: '0.875rem', boxSizing: 'border-box'
27
+ });
28
+ const heading = document.createElement('h2');
29
+ heading.id = `${id}-title`;
30
+ heading.textContent = message.title;
31
+ Object.assign(heading.style, {margin: '0 0 0.5rem', fontSize: '1rem'});
32
+ const text = document.createElement('p');
33
+ text.id = `${id}-message`;
34
+ text.textContent = message.notProject;
35
+ Object.assign(text.style, {margin: '0 0 1rem'});
36
+ const footer = document.createElement('div');
37
+ Object.assign(footer.style, {display: 'flex', justifyContent: 'flex-end'});
38
+ const ok = document.createElement('button');
39
+ ok.type = 'button';
40
+ ok.textContent = message.ok;
41
+ footer.append(ok);
42
+ dialog.append(heading, text, footer);
43
+ await new Promise<void>(resolve => {
44
+ let settled = false;
45
+ const finish = () => {
46
+ if (settled) return;
47
+ settled = true;
48
+ if (dialog.open) dialog.close();
49
+ dialog.remove();
50
+ if (returnFocus?.isConnected && typeof returnFocus.focus === 'function') returnFocus.focus();
51
+ resolve();
52
+ };
53
+ ok.addEventListener('click', finish);
54
+ dialog.addEventListener('cancel', event => {
55
+ event.preventDefault();
56
+ finish();
57
+ });
58
+ dialog.addEventListener('close', finish);
59
+ document.body.append(dialog);
60
+ dialog.showModal();
61
+ ok.focus();
62
+ });
63
+ }
package/src/session.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import {assetKey, assetTypeFor, assertFolderUnchanged, collapsePalette, encodePalette, expandPalette, extensionsFile, fileVersion,
2
- equal, FolderError, manifestFile, paletteFile, parseProject, planExtensionSave, projectAssets, projectChanges, projectFile, readProjectFolder,
3
- readFolderUpdate, sameBytes, unsupported} from './source.js';
2
+ equal, FolderError, manifestFile, paletteFile, parseProject, planExtensionSave, projectAssets, projectChanges, projectFile, isProjectFolder,
3
+ readFolder, readFolderUpdate, sameBytes, unsupported} from './source.js';
4
4
  import type {Asset, AssetKind, FolderSource, FolderUpdate, JsonObject, Project, Storage} from './source.js';
5
5
  import {applyBlockReload, planBlockReload} from './block-reload.js';
6
6
  import type {ReloadTarget} from './block-reload.js';
@@ -141,7 +141,12 @@ type Session = {source: FolderSource; root: FileSystemDirectoryHandle; baseline:
141
141
  export type ReloadState = 'ready' | 'full' | 'waiting' | 'dirty' | 'running' | 'busy' | null;
142
142
  /** What the reload command does for the pending change, regardless of whether it may run now. */
143
143
  export type ReloadKind = 'partial' | 'full' | null;
144
- export type OpenResult = 'opened' | 'cancelled';
144
+ /**
145
+ * `opened`: the folder's project is loaded. `cancelled`: nothing was opened, as when the user closed the picker or kept
146
+ * unsaved edits. `not-project`: the folder's root lacks `project.source.json`, `sb3-source.json` or
147
+ * `embedded-extensions.json`, so it is not a project folder and nothing was opened either.
148
+ */
149
+ export type OpenResult = 'opened' | 'cancelled' | 'not-project';
145
150
  type SaveResult = {status: 'saved' | 'unchanged'; sourceRemoved: string[]};
146
151
  type SaveDirectory = {directory: FileSystemDirectoryHandle; files: Map<string, Uint8Array>; prefix: string};
147
152
 
@@ -275,11 +280,13 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
275
280
  vm.off('PROJECT_CHANGED', changed);
276
281
  unregisterTree?.();
277
282
  };
283
+ // A folder without the project files at its root is no project folder; one with them that cannot be read is broken.
284
+ const readProject = async (directory: FileSystemDirectoryHandle) =>
285
+ await isProjectFolder(directory) ? readFolder(directory, vm.runtime.storage) : 'not-project' as const;
278
286
  const openFrom = async (
279
287
  getDirectory: () => Promise<Chosen | null>,
280
288
  confirmReplace: () => boolean,
281
- prepare: (directory: FileSystemDirectoryHandle) => Promise<FolderSource | null> =
282
- directory => readProjectFolder(directory, vm.runtime.storage),
289
+ prepare: (directory: FileSystemDirectoryHandle) => Promise<FolderSource | 'not-project' | null> = readProject,
283
290
  stillCurrent = () => true
284
291
  ): Promise<OpenResult> => {
285
292
  if (disposed || busy) return 'cancelled';
@@ -290,6 +297,8 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
290
297
  if (!chosen || disposed) return 'cancelled';
291
298
  const storage = vm.runtime.storage;
292
299
  const source = await prepare(chosen.directory);
300
+ // The open project stays as it is, and the user is not asked about unsaved edits.
301
+ if (source === 'not-project') return disposed ? 'cancelled' : 'not-project';
293
302
  if (!source || disposed || !stillCurrent() || vm.runtime.getTargetForStage() !== priorStage) return 'cancelled';
294
303
  if (host.isProjectDirty() && !confirmReplace()) return 'cancelled';
295
304
  host.beforeLoad();
@@ -298,7 +307,6 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
298
307
  const assets = source.storageAssets;
299
308
  reader.assets = assets;
300
309
  let stage: object | null;
301
- // The project may be the `project` folder inside the chosen one.
302
310
  const directory = source.directory;
303
311
  pendingTree = undefined;
304
312
  expectingTree = true;
@@ -436,7 +444,7 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
436
444
  return typeof pending === 'object' && pending !== null ? pending.update.version : null;
437
445
  },
438
446
  get directory() {return current?.source.directory ?? null;},
439
- /** The folder the user chose: `directory` itself, or the repository whose `project` folder it is. */
447
+ /** The folder the user chose: `directory` itself, unless a host gave another one to `openDirectory`. */
440
448
  get root() {return current?.root ?? null;},
441
449
  async mutate(directory: FileSystemDirectoryHandle, operation: (guard: () => void) => Promise<void>) {
442
450
  const session = current;
@@ -534,10 +542,14 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
534
542
  if (!session || !session.pending || session.pending === 'waiting' || host.blockReload?.isRunning()) {
535
543
  return Promise.resolve('cancelled');
536
544
  }
545
+ // The open folder is a project folder already; when it no longer is one, the error tells what is missing.
537
546
  return openFrom(() => Promise.resolve(current === session ? {directory: session.source.directory, root: session.root} : null),
538
- confirmReplace);
547
+ confirmReplace, directory => readFolder(directory, vm.runtime.storage));
539
548
  },
540
- /** `pick` gives the folder to open and, when it differs, the folder the user chose as `root`. */
549
+ /**
550
+ * `pick` gives the folder to open and, when a host located the project in another folder the user chose, that
551
+ * folder as `root`. Resolves with `not-project` when the folder is not a project folder.
552
+ */
541
553
  open(pick: (options: {id: string; mode: 'readwrite'}) => Promise<Chosen>, confirmReplace: () => boolean): Promise<OpenResult> {
542
554
  return openFrom(async () => {
543
555
  try {
@@ -549,8 +561,9 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
549
561
  }, confirmReplace);
550
562
  },
551
563
  /**
552
- * Opens `directory`, or its `project` folder when it has no project of its own. `root` is the folder the user
553
- * chose, for a host that located the project itself; it defaults to `directory`.
564
+ * Opens the project at the root of `directory`, or resolves with `not-project` and changes nothing when the
565
+ * folder is not a project folder. `root` is the folder the user chose, for a host that located the project in
566
+ * it; it defaults to `directory`.
554
567
  */
555
568
  openDirectory(directory: FileSystemDirectoryHandle, confirmReplace: () => boolean,
556
569
  root?: FileSystemDirectoryHandle): Promise<OpenResult> {
package/src/source.ts CHANGED
@@ -10,6 +10,8 @@ type Target = JsonObject & {isStage: boolean; name: string};
10
10
  export const projectFile = 'project.source.json';
11
11
  export const manifestFile = 'sb3-source.json';
12
12
  export const extensionsFile = 'embedded-extensions.json';
13
+ /** The files at the root of every project folder, the ones `readFolder` reads before anything else. */
14
+ export const projectFolderFiles = [projectFile, manifestFile, extensionsFile] as const;
13
15
  /** The ZIP entry of the Editor's screen state, which sb3-toolchain lists in `archiveEntries`. */
14
16
  const screenStateEntry = 'tw-plus/workspace.json';
15
17
  /** Block palette settings of source format 2. Format 1 folders have no such file. */
@@ -317,8 +319,7 @@ export async function readFolder(directory: FileSystemDirectoryHandle, storage:
317
319
  versions.set(prefix + name, fileVersion(file));
318
320
  return [name, await fileBytes(file)] as const;
319
321
  };
320
- const filenames = [projectFile, manifestFile, extensionsFile];
321
- const files = new Map(await Promise.all(filenames.map(name => readEntry(directory, name))));
322
+ const files = new Map(await Promise.all(projectFolderFiles.map(name => readEntry(directory, name))));
322
323
  const decoder = new TextDecoder('utf-8', {fatal: true});
323
324
  const projectText = decoder.decode(files.get(projectFile));
324
325
  const project = parseProject(projectText);
@@ -374,44 +375,23 @@ export async function readFolder(directory: FileSystemDirectoryHandle, storage:
374
375
  palette: paletteDocument};
375
376
  }
376
377
 
377
- /** The project folder inside a repository, as Project Starter makes it. */
378
- export const projectSubfolder = 'project';
379
-
380
378
  const missingEntry = (error: unknown) => error instanceof DOMException && ['NotFoundError', 'TypeMismatchError'].includes(error.name);
381
- /** Whether `directory` has an entry called `name`, a file or a folder. */
382
- async function hasEntry(directory: FileSystemDirectoryHandle, name: string) {
383
- for (const get of [() => directory.getFileHandle(name), () => directory.getDirectoryHandle(name)]) {
384
- try {
385
- await get();
386
- return true;
387
- } catch (error) {
388
- if (!missingEntry(error)) throw error;
389
- }
390
- }
391
- return false;
392
- }
393
379
 
394
380
  /**
395
- * Reads the project in `directory`, or, when the folder has no project of its own, in its `project` folder, as in a
396
- * repository whose project sits in `project/`. That folder must not be a repository itself. The error is the one
397
- * for `directory` when neither holds a project.
381
+ * Whether `directory` is a project folder: its root has every file in `projectFolderFiles`. The files are not read, so a
382
+ * project folder may still be broken or unsupported, which `readFolder` reports. Other errors, such as a withdrawn
383
+ * permission, are thrown.
398
384
  */
399
- export async function readProjectFolder(directory: FileSystemDirectoryHandle, storage: Storage): Promise<FolderSource> {
400
- try {
401
- return await readFolder(directory, storage);
402
- } catch (error) {
403
- const child = await (async () => {
404
- if (await hasEntry(directory, projectFile) || await hasEntry(directory, manifestFile)) return null;
405
- const found = await directory.getDirectoryHandle(projectSubfolder);
406
- return await hasEntry(found, '.git') ? null : found;
407
- })().catch(() => null);
408
- if (!child) throw error;
385
+ export async function isProjectFolder(directory: FileSystemDirectoryHandle) {
386
+ for (const name of projectFolderFiles) {
409
387
  try {
410
- return await readFolder(child, storage);
411
- } catch {
388
+ await directory.getFileHandle(name);
389
+ } catch (error) {
390
+ if (missingEntry(error)) return false;
412
391
  throw error;
413
392
  }
414
393
  }
394
+ return true;
415
395
  }
416
396
 
417
397
  export const sameBytes = (a: Uint8Array, b: Uint8Array) => a.length === b.length && a.every((value, index) => value === b[index]);