@kubohiroya/turbowarp-plus-editor-project-folder 0.17.0 → 0.19.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-project-folder",
3
- "version": "0.17.0",
3
+ "version": "0.19.0",
4
4
  "description": "Read and save expanded Scratch project folders in TurboWarp Plus Editor",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -69,7 +69,7 @@ export type BrowserProjectChoice = {project: BrowserProject; directory: FileSyst
69
69
 
70
70
  /**
71
71
  * Shows the project folders kept in this browser. With `purpose: 'open'` the user picks one; with `'create'` the user
72
- * names a new empty one. Resolves with the chosen folder, or `null` when the dialog closes without one.
72
+ * names a new empty one. Resolves with the chosen stored folder, or `null` when the dialog closes without one.
73
73
  */
74
74
  export function chooseBrowserProject({document, projects, locale = 'en', purpose, title = ''}: {
75
75
  document: Document; projects: BrowserProjects; locale?: string; purpose: 'open' | 'create'; title?: string;
@@ -222,8 +222,9 @@ export function chooseBrowserProject({document, projects, locale = 'en', purpose
222
222
  return element;
223
223
  };
224
224
  item.append(text,
225
+ // The project is at the root of the stored folder, as on the device.
225
226
  button(message.open, async () => {
226
- const directory = await projects.directory(project.id);
227
+ const directory = await projects.root(project.id);
227
228
  if (!directory) return render();
228
229
  finish({project, directory});
229
230
  }),
@@ -4,14 +4,17 @@
4
4
  * browser may delete them; a user keeps a copy by exporting a ZIP or pushing to GitHub.
5
5
  *
6
6
  * Layout under the OPFS root:
7
- * turbowarp-plus/projects/<id>/ the folder (a project folder, or a repository with the project inside)
7
+ * turbowarp-plus/projects/<id>/ the folder, a project folder with the project at its root
8
8
  * turbowarp-plus/project-info/<id>.json its title and times, kept outside the folder so Git never sees them
9
9
  */
10
10
 
11
11
  export interface BrowserProject {
12
12
  id: string;
13
13
  title: string;
14
- /** The project folder inside the stored folder, such as `project` in a repository, or `''` for the folder itself. */
14
+ /**
15
+ * A folder inside the stored folder, `''` for the stored folder itself. Only for compatibility: the Editor opens the
16
+ * project at the root of the stored folder, so an entry with another path is not a project folder there.
17
+ */
15
18
  projectPath: string;
16
19
  createdAt: number;
17
20
  updatedAt: number;
@@ -29,7 +32,7 @@ export interface BrowserProjects {
29
32
  directory: FileSystemDirectoryHandle}>;
30
33
  /** The stored folder, or `null` when it was deleted. */
31
34
  root(id: string): Promise<FileSystemDirectoryHandle | null>;
32
- /** The project folder of the entry, `projectPath` inside its stored folder. */
35
+ /** The folder `projectPath` inside the entry's stored folder. Opening uses `root` instead. */
33
36
  directory(id: string): Promise<FileSystemDirectoryHandle | null>;
34
37
  /** The entry that holds `handle`, or `null` when it is not in the browser's storage. */
35
38
  find(handle: FileSystemHandle): Promise<BrowserProject | null>;
@@ -4,7 +4,7 @@ export type ProjectFolderLocation = 'device' | 'browser';
4
4
 
5
5
  export interface FollowedFolder {
6
6
  readonly directory: FileSystemDirectoryHandle | null;
7
- /** 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`. */
8
8
  readonly root?: FileSystemDirectoryHandle | null;
9
9
  /** Storage choices available when creating a project folder. */
10
10
  readonly locations?: readonly ProjectFolderLocation[];
@@ -31,7 +31,7 @@ export function registerFolder(vm: object, folder: FollowedFolder) {
31
31
 
32
32
  /**
33
33
  * Calls `listener` with the project folder mounted for `vm`, the directory open in it and the folder the user chose for
34
- * 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
35
35
  * mounted, opened, closed or saved. `directory` and `root` are `null` while no folder is open. Returns the function
36
36
  * that stops it.
37
37
  */
package/src/index.ts CHANGED
@@ -1,12 +1,13 @@
1
1
  import {FolderError} from './source.js';
2
2
  import {createFolderSession} from './session.js';
3
- import {isProjectFolderEmpty} from './create-folder.js';
3
+ import {createProjectFolder, isProjectFolderEmpty} from './create-folder.js';
4
4
  import {registerFolder} from './folder-registry.js';
5
5
  import type {ProjectFolderLocation} from './folder-registry.js';
6
6
  import {openBrowserProjects} from './browser-projects.js';
7
7
  import type {BrowserProjects} from './browser-projects.js';
8
8
  import {chooseBrowserProject} from './browser-project-dialog.js';
9
- import type {Chosen, FolderHost, FolderVM, PickerWindow} from './session.js';
9
+ import {folderNotEmptyMessage, notProjectFolderMessage, showFolderNotEmptyDialog, showNotProjectFolderDialog} from './not-project-dialog.js';
10
+ import type {Chosen, FolderHost, FolderVM, OpenResult, PickerWindow} from './session.js';
10
11
 
11
12
  export type {Comparison, ComparisonRequest, ComparisonSection, FolderHost, FolderScreenState, FolderVM, OpenResult} from './session.js';
12
13
  export type {ReloadTarget} from './block-reload.js';
@@ -18,6 +19,7 @@ export {openBrowserProjects} from './browser-projects.js';
18
19
  export type {BrowserProject, BrowserProjects, BrowserStorageState} from './browser-projects.js';
19
20
  export {chooseBrowserProject, exportBrowserProject, zipFileName} from './browser-project-dialog.js';
20
21
  export type {BrowserProjectChoice} from './browser-project-dialog.js';
22
+ export {notProjectFolderMessage, showNotProjectFolderDialog} from './not-project-dialog.js';
21
23
  export {zipDirectory} from './zip.js';
22
24
 
23
25
  const messages = {
@@ -96,6 +98,24 @@ type ObserverWindow = PickerWindow & {FileSystemObserver?: new (callback: () =>
96
98
  */
97
99
  export type BrowserStorageMode = 'fallback' | 'always' | 'off';
98
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
+
112
+ /**
113
+ * Where `createFromSnapshot` and `copyToFolder` write: `browser` for a new folder in the browser's own storage, or a
114
+ * folder on the device that the host already picked, for example with `pickEmptyFolder`.
115
+ */
116
+ export type ProjectFolderDestination = 'browser' | FileSystemDirectoryHandle;
117
+
118
+ const folderPickerId = 'turbowarp-plus-project-folder';
99
119
  const abort = () => new DOMException('The user closed the dialog', 'AbortError');
100
120
 
101
121
  /**
@@ -116,10 +136,11 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
116
136
  if (!choice) throw abort();
117
137
  return choice;
118
138
  };
119
- // A folder kept in the browser was chosen as a whole, so its stored folder is the root even when the project is inside.
139
+ // The stored folder is opened as a whole, so it is its own root, as a folder on the device is.
120
140
  const chooseBrowserFolder = async (): Promise<Chosen> => {
121
- const {project, directory} = await chooseBrowser('open');
122
- return {directory, root: await browserProjects!.root(project.id).catch(() => null) ?? directory};
141
+ const {directory} = await chooseBrowser('open');
142
+ browserRoots.add(directory);
143
+ return {directory};
123
144
  };
124
145
  const pickDirectory = devicePicker ?
125
146
  async (options: {id: string; mode: 'readwrite'}): Promise<Chosen> => ({directory: await devicePicker.call(view, options)}) :
@@ -142,6 +163,32 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
142
163
  return result;
143
164
  });
144
165
  };
166
+ // The stored folders of the browser that were opened or created here, so `location` can answer without waiting.
167
+ const browserRoots = new WeakSet<FileSystemDirectoryHandle>();
168
+ const classify = async (handle: FileSystemDirectoryHandle) => {
169
+ if (browserProjects && await browserProjects.find(handle).catch(() => null)) browserRoots.add(handle);
170
+ };
171
+ /**
172
+ * Runs `run` on a new folder in the browser's storage named `title`, and removes the folder again unless `keep`
173
+ * says the result is worth keeping, also when `run` throws.
174
+ */
175
+ const withNewBrowserFolder = async <T>(title: string | undefined, run: (root: FileSystemDirectoryHandle) => Promise<T>,
176
+ keep: (result: T) => boolean) => {
177
+ if (!browserProjects) throw new FolderError('unsupported');
178
+ const project = await browserProjects.create(title || 'Project', {projectPath: ''});
179
+ browserRoots.add(project.root);
180
+ let kept = false;
181
+ try {
182
+ const result = await run(project.root);
183
+ kept = keep(result);
184
+ return result;
185
+ } finally {
186
+ if (!kept) await browserProjects.remove(project.id).catch(() => {});
187
+ }
188
+ };
189
+ const overwriteMessage = () => locale.startsWith('ja') ?
190
+ '指定されたフォルダは空ではありません。フォルダに保存されている内容が上書きされる場合があります。よろしいですか?' :
191
+ 'The selected folder is not empty. Contents in the folder may be overwritten. Continue?';
145
192
  const session = createFolderSession(vm, host);
146
193
  const status = document.createElement('output');
147
194
  status.dataset.projectFolderStatus = '';
@@ -167,6 +214,9 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
167
214
  const detail = error instanceof FolderError && error.message !== error.code ? ` (${error.message})` : '';
168
215
  report((error instanceof FolderError ? message[error.code] : message.failed) + detail);
169
216
  };
217
+ // The open project stays; the dialog tells why nothing opened, or the status line where no dialog can be shown.
218
+ const notProject = (locale: string) => showNotProjectFolderDialog({document, locale})
219
+ .catch(() => report(notProjectFolderMessage(locale)));
170
220
  let stopWatching: (() => void) | undefined;
171
221
  let renderReload = () => {};
172
222
  if (host.blockReload) {
@@ -286,19 +336,23 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
286
336
  notice.remove();
287
337
  };
288
338
  }
339
+ const opened = (locale: string, result: OpenResult) => {
340
+ if (result === 'opened') report(messageFor(locale).opened);
341
+ else if (result === 'not-project') void notProject(locale);
342
+ };
289
343
  const menu: MenuEntry = {
290
344
  deviceFolders: typeof devicePicker === 'function',
291
345
  session,
292
346
  open(locale) {
293
347
  const message = messageFor(locale);
294
348
  session.open(options => pickDirectory(options), () => view.confirm(message.replace))
295
- .then(result => {if (result === 'opened') report(message.opened);}, error => fail(locale, error)).finally(renderReload);
349
+ .then(result => opened(locale, result), error => fail(locale, error)).finally(renderReload);
296
350
  renderReload();
297
351
  },
298
352
  openBrowser: browserProjects ? locale => {
299
353
  const message = messageFor(locale);
300
354
  session.open(chooseBrowserFolder, () => view.confirm(message.replace))
301
- .then(result => {if (result === 'opened') report(message.opened);}, error => fail(locale, error)).finally(renderReload);
355
+ .then(result => opened(locale, result), error => fail(locale, error)).finally(renderReload);
302
356
  renderReload();
303
357
  } : undefined,
304
358
  save(locale) {
@@ -329,8 +383,18 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
329
383
  mutate: (directory, operation) => session.mutate(directory, operation).finally(renderReload)
330
384
  });
331
385
  return {
332
- openDirectory: (...args: Parameters<typeof session.openDirectory>) =>
333
- session.openDirectory(...args).finally(renderReload),
386
+ /**
387
+ * Opens the project at the root of `directory`, as the user's Open would, and resolves with the result. A folder
388
+ * that is not a project folder changes nothing, shows the error dialog unless `options.notProjectDialog` is
389
+ * false, and resolves with `not-project`. `root` is the folder the user chose, for a host that located the
390
+ * project in it; it defaults to `directory`.
391
+ */
392
+ openDirectory: (directory: FileSystemDirectoryHandle, confirmReplace: () => boolean,
393
+ root?: FileSystemDirectoryHandle | null, options: OpenDirectoryOptions = {}): Promise<OpenResult> =>
394
+ classify(root ?? directory).then(() => session.openDirectory(directory, confirmReplace, root ?? undefined)).then(result => {
395
+ if (result === 'not-project' && options.notProjectDialog !== false) void notProject(options.locale ?? locale);
396
+ return result;
397
+ }).finally(renderReload),
334
398
  unsavedPaths: () => session.unsavedPaths(),
335
399
  readUnsavedFile: (path: string) => session.readUnsavedFile(path),
336
400
  subscribeEdits: (listener: () => void) => session.subscribeEdits(listener),
@@ -338,10 +402,14 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
338
402
  /** The folders kept in this browser, when they are offered, for a host that lists or exports them. */
339
403
  browserProjects,
340
404
  /**
341
- * Creates a project folder from a snapshot. `title` names a folder made in the browser, where the user names a
342
- * new folder instead of picking one on the device.
405
+ * Creates a project folder from a snapshot and opens it. `destination` writes to a new folder in the browser's
406
+ * storage (`browser`, named by `title`; it is removed again unless the project opens from it) or to a folder the
407
+ * host picked on the device (see `pickEmptyFolder`). Without it, `directory` is the folder the host picked, and
408
+ * otherwise `location` (or the device picker where there is one) asks the user: `title` then names a folder
409
+ * made in the browser, where the user names a new folder instead of picking one. A folder that is not empty is
410
+ * overwritten only when the user confirms it.
343
411
  */
344
- createFromSnapshot({prepareFiles, collectEdits, directory, current = () => true, title, location}: {
412
+ createFromSnapshot({prepareFiles, collectEdits, directory, current = () => true, title, location, destination}: {
345
413
  prepareFiles: () => Promise<ReadonlyMap<string, Uint8Array>>;
346
414
  collectEdits?: () => Promise<void>;
347
415
  directory?: FileSystemDirectoryHandle;
@@ -349,16 +417,15 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
349
417
  title?: string;
350
418
  /** Explicit destination; omitted uses the device picker when available. */
351
419
  location?: ProjectFolderLocation;
352
- }) {
353
- const message = locale.startsWith('ja') ?
354
- '指定されたフォルダは空ではありません。フォルダに保存されている内容が上書きされる場合があります。よろしいですか?' :
355
- 'The selected folder is not empty. Contents in the folder may be overwritten. Continue?';
356
- return session.createFromSnapshot(async () => {
420
+ destination?: ProjectFolderDestination;
421
+ }): Promise<OpenResult> {
422
+ const create = (picked?: FileSystemDirectoryHandle) => session.createFromSnapshot(async () => {
357
423
  try {
358
- const selected = directory ?? await pickNewDirectory({id: 'turbowarp-plus-project-folder', mode: 'readwrite'}, title, location);
424
+ const selected = picked ?? await pickNewDirectory({id: folderPickerId, mode: 'readwrite'}, title, location);
359
425
  if (!current()) return null;
426
+ await classify(selected);
360
427
  const overwrite = !await isProjectFolderEmpty(selected);
361
- if (!current() || (overwrite && !view.confirm(message))) return null;
428
+ if (!current() || (overwrite && !view.confirm(overwriteMessage()))) return null;
362
429
  await collectEdits?.();
363
430
  return current() ? {directory: selected, overwrite} : null;
364
431
  } catch (error) {
@@ -366,15 +433,98 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
366
433
  throw error;
367
434
  }
368
435
  }, prepareFiles, current).finally(renderReload);
436
+ if (destination === 'browser') return withNewBrowserFolder(title, create, result => result === 'opened');
437
+ return create(destination ?? directory);
438
+ },
439
+ /**
440
+ * Writes a project folder from a snapshot to `destination` and leaves the open project as it is: nothing is
441
+ * opened or attached, `directory` and `root` stay, and `followProjectFolder` listeners are not called (Save a
442
+ * Copy). `browser` makes a new folder in the browser's storage named by `title`, removed again when nothing is
443
+ * written; a folder on the device that is not empty is overwritten only when the user confirms it. Resolves
444
+ * with the folder written, or `null` when the user declined or `current()` turned false. The open project
445
+ * folder and its `root` are refused with `conflict` before anything is asked or written.
446
+ */
447
+ async copyToFolder({destination, prepareFiles, collectEdits, current = () => true, title}: {
448
+ destination: ProjectFolderDestination;
449
+ prepareFiles: () => Promise<ReadonlyMap<string, Uint8Array>>;
450
+ collectEdits?: () => Promise<void>;
451
+ current?: () => boolean;
452
+ title?: string;
453
+ }): Promise<FileSystemDirectoryHandle | null> {
454
+ // Writing over the open folder would replace the project under the session; Save is for that.
455
+ if (destination !== 'browser') {
456
+ for (const open of [session.directory, session.root]) {
457
+ if (open && (open === destination || await open.isSameEntry(destination).catch(() => false))) {
458
+ throw new FolderError('conflict', 'The copy cannot go to the open project folder');
459
+ }
460
+ }
461
+ }
462
+ const write = async (target: FileSystemDirectoryHandle, isNew: boolean) => {
463
+ try {
464
+ const overwrite = !isNew && !await isProjectFolderEmpty(target);
465
+ if (!current() || (overwrite && !view.confirm(overwriteMessage()))) return null;
466
+ await collectEdits?.();
467
+ if (!current()) return null;
468
+ const files = await prepareFiles();
469
+ if (!current()) return null;
470
+ await createProjectFolder({directory: target, files, storage: vm.runtime.storage, overwrite, current});
471
+ return target;
472
+ } catch (error) {
473
+ if (error instanceof DOMException && error.name === 'AbortError') return null;
474
+ throw error;
475
+ }
476
+ };
477
+ if (destination === 'browser') return withNewBrowserFolder(title, root => write(root, true), result => result !== null);
478
+ return write(destination, false);
479
+ },
480
+ /**
481
+ * Asks the user for an empty folder on the device, for a new project. Call it while handling the user's click,
482
+ * as the browser lets the folder picker open only then. Resolves with `null` when the user cancelled, or chose
483
+ * a folder that is not empty, which a modal dialog then tells (“Choose an empty folder.”); it resolves once the
484
+ * dialog closes. Rejects with
485
+ * `unsupported` where the browser cannot pick folders on the device.
486
+ */
487
+ async pickEmptyFolder({locale: language = locale, id = folderPickerId}: {locale?: string; id?: string} = {}) {
488
+ if (!devicePicker) throw new FolderError('unsupported');
489
+ let picked: FileSystemDirectoryHandle;
490
+ try {
491
+ picked = await devicePicker.call(view, {id, mode: 'readwrite'});
492
+ } catch (error) {
493
+ if (error instanceof DOMException && error.name === 'AbortError') return null;
494
+ throw error;
495
+ }
496
+ if (await isProjectFolderEmpty(picked)) return picked;
497
+ // Where no dialog can be shown, the status line tells it instead.
498
+ await showFolderNotEmptyDialog({document, locale: language}).catch(() => report(folderNotEmptyMessage(language)));
499
+ return null;
500
+ },
501
+ /**
502
+ * Gives the open folder the title `title` in the list of folders kept in this browser. Resolves with `false`,
503
+ * changing nothing, when no folder is open or the open folder is not kept in this browser: a folder on the
504
+ * device keeps its name, as the browser cannot rename it.
505
+ */
506
+ async renameCurrentBrowserFolder(title: string) {
507
+ const root = session.root;
508
+ const entry = root && browserProjects ? await browserProjects.find(root).catch(() => null) : null;
509
+ if (!entry || session.root !== root) return false;
510
+ await browserProjects!.rename(entry.id, title);
511
+ return true;
512
+ },
513
+ /** Where the open folder is: `browser` for a folder kept in this browser, `device`, or `null` with none open. */
514
+ get location(): ProjectFolderLocation | null {
515
+ const root = session.root;
516
+ return root ? (browserRoots.has(root) ? 'browser' : 'device') : null;
369
517
  },
518
+ /** Where new project folders can be made: `device` with the folder picker, and `browser` with the browser's folders. */
519
+ locations: locations as readonly ProjectFolderLocation[],
370
520
  /**
371
521
  * The folder the loaded project came from, or `null` once another project loaded or the folder was
372
522
  * detached. A host can tell projects apart by it, for example to keep the layout of each one.
373
523
  */
374
524
  get directory() {return session.directory;},
375
525
  /**
376
- * The folder the user chose for the loaded project, or `null` like `directory`. It is `directory` itself, or
377
- * the repository whose `project` folder holds the project, or the stored folder of a folder kept in the browser.
526
+ * The folder the user chose for the loaded project, or `null` like `directory`. It is `directory` itself, the
527
+ * project folder, unless the host gave another folder to `openDirectory`.
378
528
  */
379
529
  get root() {return session.root;},
380
530
  dispose() {
@@ -0,0 +1,81 @@
1
+ const messages = {
2
+ en: {title: 'Cannot Open Folder', notProject: 'This folder is not a project folder.',
3
+ notEmptyTitle: 'Cannot Use This Folder', notEmpty: 'Choose an empty folder.', ok: 'OK'},
4
+ ja: {title: 'フォルダを開けません', notProject: 'このフォルダはプロジェクトフォルダではありません。',
5
+ notEmptyTitle: 'このフォルダは使えません', notEmpty: '空のフォルダを選んでください。', ok: 'OK'}
6
+ };
7
+
8
+ let dialogs = 0;
9
+
10
+ /** The message the dialog shows, for a host that tells the user in its own way. */
11
+ export const notProjectFolderMessage = (locale = 'en') => (locale.startsWith('ja') ? messages.ja : messages.en).notProject;
12
+
13
+ /**
14
+ * Tells the user, in a modal dialog, that the folder they tried to open is not a project folder. Resolves when the
15
+ * dialog closes, after the focus went back to where it was.
16
+ */
17
+ export function showNotProjectFolderDialog({document, locale = 'en'}: {document: Document; locale?: string}): Promise<void> {
18
+ const message = locale.startsWith('ja') ? messages.ja : messages.en;
19
+ return showFolderErrorDialog(document, 'not-project', message.title, message.notProject, message.ok);
20
+ }
21
+
22
+ /** The message of the dialog for a folder that is not empty. */
23
+ export const folderNotEmptyMessage = (locale = 'en') => (locale.startsWith('ja') ? messages.ja : messages.en).notEmpty;
24
+
25
+ /**
26
+ * Tells the user, in the same modal dialog, that the folder they chose for a new project is not empty. Resolves when
27
+ * the dialog closes.
28
+ */
29
+ export function showFolderNotEmptyDialog({document, locale = 'en'}: {document: Document; locale?: string}): Promise<void> {
30
+ const message = locale.startsWith('ja') ? messages.ja : messages.en;
31
+ return showFolderErrorDialog(document, 'not-empty', message.notEmptyTitle, message.notEmpty, message.ok);
32
+ }
33
+
34
+ async function showFolderErrorDialog(document: Document, kind: string, title: string, body: string, okLabel: string) {
35
+ const returnFocus = document.activeElement as HTMLElement | null;
36
+ const id = `tw-plus-project-folder-error-${++dialogs}`;
37
+ const dialog = document.createElement('dialog');
38
+ dialog.dataset.projectFolderError = kind;
39
+ dialog.setAttribute('role', 'alertdialog');
40
+ dialog.setAttribute('aria-labelledby', `${id}-title`);
41
+ dialog.setAttribute('aria-describedby', `${id}-message`);
42
+ Object.assign(dialog.style, {
43
+ width: 'min(26rem, calc(100vw - 2rem))', padding: '1rem 1.25rem', background: 'Canvas', color: 'CanvasText',
44
+ border: '1px solid GrayText', borderRadius: '0.5rem', fontFamily: 'inherit', fontSize: '0.875rem', boxSizing: 'border-box'
45
+ });
46
+ const heading = document.createElement('h2');
47
+ heading.id = `${id}-title`;
48
+ heading.textContent = title;
49
+ Object.assign(heading.style, {margin: '0 0 0.5rem', fontSize: '1rem'});
50
+ const text = document.createElement('p');
51
+ text.id = `${id}-message`;
52
+ text.textContent = body;
53
+ Object.assign(text.style, {margin: '0 0 1rem'});
54
+ const footer = document.createElement('div');
55
+ Object.assign(footer.style, {display: 'flex', justifyContent: 'flex-end'});
56
+ const ok = document.createElement('button');
57
+ ok.type = 'button';
58
+ ok.textContent = okLabel;
59
+ footer.append(ok);
60
+ dialog.append(heading, text, footer);
61
+ await new Promise<void>(resolve => {
62
+ let settled = false;
63
+ const finish = () => {
64
+ if (settled) return;
65
+ settled = true;
66
+ if (dialog.open) dialog.close();
67
+ dialog.remove();
68
+ if (returnFocus?.isConnected && typeof returnFocus.focus === 'function') returnFocus.focus();
69
+ resolve();
70
+ };
71
+ ok.addEventListener('click', finish);
72
+ dialog.addEventListener('cancel', event => {
73
+ event.preventDefault();
74
+ finish();
75
+ });
76
+ dialog.addEventListener('close', finish);
77
+ document.body.append(dialog);
78
+ dialog.showModal();
79
+ ok.focus();
80
+ });
81
+ }
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]);