@kubohiroya/turbowarp-plus-editor-project-folder 0.17.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/README.ja.md CHANGED
@@ -8,10 +8,10 @@ TurboWarp Plus Editor で sb3-toolchain の作品フォルダ(展開ソース
8
8
 
9
9
  - `mountProjectFolder({vm, document, host})` でワークスペースに接続します。ワークスペースの切り替え時には `dispose()` を呼びます。
10
10
  - `renderProjectFolderMenu(createElement, props)` は既存の開く・保存コマンドをホストのファイルメニューに渡します。
11
- - 選んだフォルダの直下に作品がなく、その中の `project` フォルダが作品フォルダのときは、`project` を作品フォルダとして開きます(Project Starter が作るリポジトリの形)。`project` フォルダの中に `.git` があるときは開きません。どちらも作品でないときは、選んだフォルダのエラーをそのまま出します。
12
- - 接続後の `openDirectory(handle, confirmReplace, root?)` には、ホストが選択済みのディレクトリハンドルを渡せます。ファイルメニューと同じ作品検証・`project` フォルダへの切り替え・未保存編集の確認を経て開き、保存先にはその作品フォルダを使います。`root` には、ホストが自分で作品の場所を見つけたときに、ユーザーが選んだフォルダを渡します。省略すると `handle` です。
11
+ - 一つのフォルダには一つの作品を、フォルダのルートに置きます。ルートに `project.source.json`・`sb3-source.json`・`embedded-extensions.json` があるフォルダがプロジェクトフォルダです。ユーザーが開こうとしたフォルダ(**フォルダを開く…**、**ブラウザーに保存したフォルダを開く…**、ホストの `openDirectory`)がプロジェクトフォルダでないときは、エラーのダイアログに「このフォルダはプロジェクトフォルダではありません。」(英語では “This folder is not a project folder.”)と、その操作の言語で出し、何も開きません。開いている作品はそのまま残り、未保存の編集の確認も出さず、`followProjectFolder` の listener も呼びません。ダイアログはモーダルの `<dialog>`(`role="alertdialog"`、`data-project-folder-error="not-project"`)で、タイトルと **OK** ボタンがあり、OK で閉じるとフォーカスを元の場所に戻します。ファイルが壊れている、または対応していない形式のプロジェクトフォルダは、これまでどおり状態表示にエラーを出します。`createFromSnapshot` で新しいプロジェクトフォルダに保存する操作は変わりません。
12
+ - 接続後の `openDirectory(handle, confirmReplace, root?, options?)` には、ホストが選択済みのディレクトリハンドルを渡せます。ファイルメニューと同じ作品検証・未保存編集の確認を経て開き、`'opened'`・`'cancelled'`・`'not-project'`(`OpenResult`)のどれかで終わります。`'not-project'` のときは何も変わっていません。エラーのダイアログを出しますが、ホストが自分の方法で知らせるときは `options.notProjectDialog` に `false` を渡すと出しません。`options.locale` はダイアログの言語で、省略すると `mountProjectFolder` の `locale` です。保存先にはその作品フォルダを使います。`root` には、ホストが作品を見つけたフォルダとして、ユーザーが選んだフォルダを渡します。省略すると `handle` です(`options` だけを渡すときは `undefined` を渡します)。ダイアログを出さなかったホスト向けに、ダイアログを出す `showNotProjectFolderDialog({document, locale})` と、その文言を返す `notProjectFolderMessage(locale)` もあります。
13
13
  - 接続後の `directory` は、読み込んだ作品のフォルダーのハンドルです。別の作品を読み込むか、フォルダーとの接続を外すと `null` になります。ホストは作品を見分けるのに使えます。
14
- - 接続後の `root` は、その作品のためにユーザーが選んだフォルダーです。`directory` そのもの、`directory` を `project` フォルダに持つリポジトリ、またはブラウザーに保存したフォルダでは保存したフォルダー全体を指します。`directory` が `null` のときは `null` です。ブラウザーではフォルダーの親を読めないので、ホストは Git のリポジトリを `root` に結び付けます。
14
+ - 接続後の `root` は、その作品のためにユーザーが選んだフォルダーです。ホストが `openDirectory` に別のフォルダを渡したとき以外は `directory` そのものです。`directory` が `null` のときは `null` です。ブラウザーではフォルダーの親を読めないので、ホストは Git のリポジトリを `root` に結び付けます。
15
15
  - `host.screenState` を渡すと、Editor の画面状態をフォルダーに保存します。渡すものは workbench の `installProjectScreenState` が返すものです。作品フォルダーは SB3 ではないので、状態は `.tw-plus/workspace.json` に入れます。フォルダーを開くと、作品を読み込む前にこれを読み、`prepareLoad(text)` で渡します。保存時は、作品が変わっていなくても `serialize()` の結果を書きます。保存時刻だけが違うときは書きません。読み書きに失敗しても、開く操作と保存は失敗にしません。セッションは `projectFolder` スライス(ツリーで開いたフォルダーと選択中の項目)も登録します。SB3 から作品フォルダを作るとき、sb3-toolchain(0.26.0 以降)が展開したスナップショットに `.tw-plus/workspace.json` があれば、そのままフォルダーに書くので、作ったフォルダーは同じ画面で開きます。スナップショットにないときは、上書きするフォルダーの古い `workspace.json` を消します。`.tw-plus` のほかのファイルは残します。
16
16
 
17
17
  ホストは VM、メニューコンポーネント、作品状態を扱うコールバックを渡します。メニューからフォルダを開くには、ブラウザーが File System Access のフォルダ選択に対応しているか、[ブラウザー内の作品フォルダ](#ブラウザー内の作品フォルダ)を使える必要があります。ブロック、変数・リスト、スプライトの位置や大きさなどの項目、モニター、組み込みの拡張機能の編集を作品データ(`project.source.json`)に保存し、作品の実行で変わった状態も含みます。スプライトの追加・削除・名前の変更と、コスチューム・音の追加・削除も保存します。新しいアセットのファイルを先に書き、`sb3-source.json` と作品データを書いてから、参照されなくなったアセットのファイルを消します。 [Editor #305](https://github.com/kubohiroya/turbowarp-plus-editor/issues/305) · [Editor #308](https://github.com/kubohiroya/turbowarp-plus-editor/issues/308)
@@ -29,7 +29,7 @@ Safari と Firefox にはフォルダ選択(`showDirectoryPicker`)があり
29
29
  - 作品フォルダをまだ開いていないパネルには、利用できる保存方式の説明と作成ボタンを出します。`always` でフォルダ選択と OPFS の両方が使える場合は2方式、Safari・Firefox ではブラウザー内保存の説明を出します。説明には、ボタンを押した後の操作、外部アプリからの見え方、ブラウザー内の作品を残すための書き出し方法を含めます。
30
30
  - `renderProjectFolderExplorer` の `createFolder(location)` には、選んだ保存先(`device` または `browser`)が渡ります。ホストはこれを `createFromSnapshot({location, ...})` に渡します。`location` を省略した場合は従来どおりフォルダ選択を優先し、利用できない保存先を明示した場合は別の保存先に切り替えずエラーにします。
31
31
  - 一覧のダイアログでは、作品フォルダを開く、ZIP で書き出す、削除することができます。保存領域の使用量と、ブラウザーが消さずに残すか(`persisted`)も表示します。閉じるボタンは X のアイコンで、名前は表示の言語に合わせます。
32
- - 作品フォルダは `turbowarp-plus/projects/<id>/` に置き、表示名と時刻は `turbowarp-plus/project-info/<id>.json` に置きます。作品フォルダの外に置くので、Git の管理対象には入りません。`projectPath` を指定すると、リポジトリのルートの下の作品フォルダ(例:`project`)を開けます。
32
+ - 作品フォルダは `turbowarp-plus/projects/<id>/` に置き、表示名と時刻は `turbowarp-plus/project-info/<id>.json` に置きます。作品フォルダの外に置くので、Git の管理対象には入りません。フォルダを開くときは、保存したフォルダのルートの作品を読みます。`create(title, {projectPath})` と `directory(id)` は互換のために `projectPath` を受け付けて解決しますが、Editor はその下のフォルダを開きません。
33
33
  - 同じ作品フォルダへの保存は、`navigator.locks` で作品ごとに排他します。WebKit は `createWritable({mode: 'exclusive'})` を重ねても拒否しないので、タブ間の排他はロックで行います。保存すると一覧の更新時刻が変わります。
34
34
  - `openBrowserProjects(window)` は一覧・作成・削除・保存領域の状態を扱う口です。`chooseBrowserProject` は一覧のダイアログを、`exportBrowserProject` と `zipDirectory` は ZIP の書き出しを、ホストが直接使うためのものです。ZIP は圧縮せず、名前を UTF-8 で書きます。
35
35
 
@@ -37,6 +37,15 @@ Safari と Firefox にはフォルダ選択(`showDirectoryPicker`)があり
37
37
 
38
38
  保存先選択の導入は、このパッケージを先に公開し、Editor の依存をその版へ固定してからホストの結線を反映します。切り戻すときは Editor の結線と依存の固定を一緒に戻します。OPFS に作成済みの作品は削除せず、ブラウザー内の一覧から開く・ZIP で書き出す経路を維持します。
39
39
 
40
+ ## 0.17.0 の後の互換性のない変更: 作品はフォルダのルートに置く
41
+
42
+ 0.16.0 では、選んだフォルダの直下に作品がないとき、その中の `project` フォルダの作品を開きました(Project Starter が作るリポジトリの形)。この切り替えはなくしました。一つの Git リポジトリには一つの作品を、そのルートに置きます。
43
+
44
+ - 作品を `project/` に置いたリポジトリは、プロジェクトフォルダではなくなります。開くとエラーのダイアログを出します。作品のファイルをリポジトリのルートに移すか、`project` フォルダそのものを開いてください。
45
+ - 古い形でブラウザーに保存したフォルダ(`projectPath: 'project'` の項目)も、ほかと同じく保存したフォルダのルートを開くので、エラーのダイアログを出します。このパッケージは移し替えをしません。ZIP で書き出して残し、その `project` フォルダを端末のフォルダとして開くか、sb3-toolchain で SB3 にしてから、ブラウザーの新しいフォルダに保存し直してください。
46
+ - `root` は、ホストが `openDirectory` に `root` を渡したとき以外は、作品フォルダそのものです。
47
+ - `OpenResult` に `'not-project'` が加わりました。結果を `'opened'` と `'cancelled'` だけで見分けていたホストは、これも扱ってください。
48
+
40
49
  ## ブロックパレットの設定
41
50
 
42
51
  TurboWarp Plus Editor は、ブロックパレットの設定を画面状態(`.tw-plus/workspace.json`)に保存するようになりました。この節の形式 2 の読み書きは、それ以前に作られた作品フォルダのために残しています。
package/README.md CHANGED
@@ -8,10 +8,10 @@ This package opens and saves sb3-toolchain project folders (source formats 1 and
8
8
 
9
9
  - `mountProjectFolder({vm, document, host})` attaches the folder session to a workspace. Call `dispose()` when the workspace is replaced.
10
10
  - `renderProjectFolderMenu(createElement, props)` supplies the existing open and save commands to the host's file menu.
11
- - A chosen folder with no project of its own opens its `project` folder instead, as in a repository made by Project Starter, when that folder is a valid project folder and has no `.git` of its own. Otherwise the error for the chosen folder stays.
12
- - The mounted session's `openDirectory(handle, confirmReplace, root?)` accepts a directory handle already selected by the host. It uses the same project validation, `project` fallback and unsaved-edit confirmation as the file menu. Save still targets the opened project folder. `root` names the folder the user chose, for a host that located the project itself; it defaults to `handle`.
11
+ - One folder holds one project, at its root. A folder is a project folder when its root has `project.source.json`, `sb3-source.json` and `embedded-extensions.json`. When the folder the user opens (with **Open Folder…**, **Open Folder Saved in This Browser…** or a host's `openDirectory`) is not a project folder, an error dialog says “This folder is not a project folder.” (Japanese: 「このフォルダはプロジェクトフォルダではありません。」) in the locale of the command, and nothing opens: the open project stays, unsaved edits are not asked about, and `followProjectFolder` listeners are not called. The dialog is a modal `<dialog>` (`role="alertdialog"`, `data-project-folder-error="not-project"`) with a title and an **OK** button that closes it and returns the focus. A project folder whose files are broken or of an unsupported format reports its error in the status line as before. Saving a new project folder with `createFromSnapshot` is not affected.
12
+ - The mounted session's `openDirectory(handle, confirmReplace, root?, options?)` accepts a directory handle already selected by the host. It uses the same project validation and unsaved-edit confirmation as the file menu, and resolves with `'opened'`, `'cancelled'` or `'not-project'` (`OpenResult`). With `'not-project'` nothing changed, and the error dialog is shown unless `options.notProjectDialog` is `false`, for a host that tells the user in its own way; `options.locale` sets the dialog's locale, which defaults to the `locale` of `mountProjectFolder`. Save still targets the opened project folder. `root` names the folder the user chose, for a host that located the project in it; it defaults to `handle` (pass `undefined` to give only `options`). `showNotProjectFolderDialog({document, locale})` shows the dialog, and `notProjectFolderMessage(locale)` gives its message, for hosts that opted out.
13
13
  - The mounted session's `directory` is the folder the loaded project came from. It becomes `null` once another project loads or the folder is detached, so a host can tell projects apart by it.
14
- - The mounted session's `root` is the folder the user chose for that project: `directory` itself, the repository whose `project` folder is `directory`, or, for a folder kept in the browser, its stored folder. It is `null` whenever `directory` is. The browser cannot read a folder's parent, so a host binds a Git repository to `root`.
14
+ - The mounted session's `root` is the folder the user chose for that project: `directory` itself, unless a host gave another folder to `openDirectory`. It is `null` whenever `directory` is. The browser cannot read a folder's parent, so a host binds a Git repository to `root`.
15
15
  - `host.screenState` keeps the Editor's screen state in the folder, as the workbench's `installProjectScreenState` provides it. A project folder is not an SB3, so the state goes into `.tw-plus/workspace.json`. Opening the folder reads it and passes it with `prepareLoad(text)` before the project loads. Saving writes `serialize()`, even when the project itself is unchanged, and skips the write when only the save time differs. A failure to read or write it never fails the open or the save. The session also registers the `projectFolder` slice: the expanded folders and the selected entry of the explorer. When a folder is created from an SB3, a `.tw-plus/workspace.json` in the snapshot sb3-toolchain (0.26.0 or later) unpacked is written into the folder as it is, so the new folder opens with the same screen. A snapshot without one removes the old `workspace.json` of the folder it overwrites, and keeps the other files in `.tw-plus`.
16
16
 
17
17
  The host supplies the VM, menu components, and project state callbacks. The built-in open command needs the File System Access folder picker or [project folders in the browser](#project-folders-in-the-browser). Save writes block, variable, list, sprite property, monitor and built-in extension edits to the project file, including state that changes while the project runs. Sprites can be added, removed and renamed, and costumes and sounds added or removed: new asset files are written first, then `sb3-source.json` and the project file, and asset files nothing refers to are deleted last. See [Editor issue #305](https://github.com/kubohiroya/turbowarp-plus-editor/issues/305) and [issue #308](https://github.com/kubohiroya/turbowarp-plus-editor/issues/308).
@@ -31,12 +31,21 @@ Safari and Firefox have no folder picker (`showDirectoryPicker`). In these brows
31
31
  - Before a folder is open, the explorer explains each available destination and offers its creation button. With `always`, browsers supporting both the picker and OPFS show both choices; Safari and Firefox explain browser storage. The text describes the next step, access from other apps, and how to keep an exported copy.
32
32
  - The explorer calls its host's `createFolder(location)` with `device` or `browser`. Forward this to `createFromSnapshot({location, ...})`. Omitting `location` preserves the existing picker-first behavior. An explicitly unavailable destination fails instead of silently switching storage.
33
33
  - The dialog opens, exports as a ZIP, and deletes the folders. It shows how much storage is used and whether the browser keeps it (`persisted`). Its close button is an X icon named in the display language.
34
- - A folder lives at `turbowarp-plus/projects/<id>/`, and its name and times at `turbowarp-plus/project-info/<id>.json`, outside the folder, so Git never tracks them. With `projectPath`, the project folder can sit below the repository root, such as `project`.
34
+ - A folder lives at `turbowarp-plus/projects/<id>/`, and its name and times at `turbowarp-plus/project-info/<id>.json`, outside the folder, so Git never tracks them. Opening a folder reads the project at the root of that stored folder. `create(title, {projectPath})` and `directory(id)` still accept and resolve `projectPath` for compatibility, but the Editor does not open the folder below it.
35
35
  - Saves to the same folder are serialized per folder with `navigator.locks`. WebKit does not refuse a second `createWritable({mode: 'exclusive'})`, so the lock is what keeps tabs apart. A save updates the folder's time in the list.
36
36
  - `openBrowserProjects(window)` lists, creates and deletes the folders and reports the storage. `chooseBrowserProject` shows the dialog, and `exportBrowserProject` and `zipDirectory` write the ZIP, for hosts that use them directly. The ZIP is stored without compression and names entries in UTF-8.
37
37
 
38
38
  The browser may delete these folders when site data is cleared or the site is not used for a while (seven days in Safari). Creating the first folder asks for `navigator.storage.persist()`, which is not a guarantee. The dialog tells the user to export a ZIP or push to GitHub with Git to keep a copy.
39
39
 
40
+ ## Breaking change after 0.17.0: the project is at the folder's root
41
+
42
+ 0.16.0 opened the `project` folder of a chosen folder that had no project of its own, as in a repository made by Project Starter. That fallback is removed: one Git repository holds one project, at its root.
43
+
44
+ - A repository with its project in `project/` is not a project folder any more. Opening it shows the error dialog. Move the project files to the repository root, or open the `project` folder itself.
45
+ - A folder kept in the browser with the old layout (its entry has `projectPath: 'project'`) is opened at its stored folder like any other, so it shows the error dialog too. The package has no migration: export it as a ZIP to keep it, and open its `project` folder as a folder on the device, or build it into an SB3 with sb3-toolchain and save that as a new folder in the browser.
46
+ - `root` is the project folder itself unless a host passes `root` to `openDirectory`.
47
+ - `OpenResult` has the new value `'not-project'`. A host that compared the result with `'opened'` and `'cancelled'` only should handle it.
48
+
40
49
  ## Block palette settings
41
50
 
42
51
  TurboWarp Plus Editor now saves block palette settings in its screen state (`.tw-plus/workspace.json`). Reading and writing format 2, described here, stays for project folders made before that.
@@ -9,7 +9,7 @@ export type BrowserProjectChoice = {
9
9
  };
10
10
  /**
11
11
  * Shows the project folders kept in this browser. With `purpose: 'open'` the user picks one; with `'create'` the user
12
- * names a new empty one. Resolves with the chosen folder, or `null` when the dialog closes without one.
12
+ * names a new empty one. Resolves with the chosen stored folder, or `null` when the dialog closes without one.
13
13
  */
14
14
  export declare function chooseBrowserProject({ document, projects, locale, purpose, title }: {
15
15
  document: Document;
@@ -4,13 +4,16 @@
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
  export interface BrowserProject {
11
11
  id: string;
12
12
  title: string;
13
- /** The project folder inside the stored folder, such as `project` in a repository, or `''` for the folder itself. */
13
+ /**
14
+ * A folder inside the stored folder, `''` for the stored folder itself. Only for compatibility: the Editor opens the
15
+ * project at the root of the stored folder, so an entry with another path is not a project folder there.
16
+ */
14
17
  projectPath: string;
15
18
  createdAt: number;
16
19
  updatedAt: number;
@@ -30,7 +33,7 @@ export interface BrowserProjects {
30
33
  }>;
31
34
  /** The stored folder, or `null` when it was deleted. */
32
35
  root(id: string): Promise<FileSystemDirectoryHandle | null>;
33
- /** The project folder of the entry, `projectPath` inside its stored folder. */
36
+ /** The folder `projectPath` inside the entry's stored folder. Opening uses `root` instead. */
34
37
  directory(id: string): Promise<FileSystemDirectoryHandle | null>;
35
38
  /** The entry that holds `handle`, or `null` when it is not in the browser's storage. */
36
39
  find(handle: FileSystemHandle): Promise<BrowserProject | null>;
package/dist/explorer.js CHANGED
@@ -1,4 +1,4 @@
1
- import { A as projectFile, C as isObject, F as _asyncIterator, L as _objectSpread2, a as projectFolderOverwriteWarning, d as subscribeExplorerState, f as writeExplorerState, l as readExplorerState, p as FolderError, s as hiddenEntry, t as followProjectFolder, w as manifestFile } from "./shared-h5VGx9Jp.js";
1
+ import { C as isObject, I as _asyncIterator, R as _objectSpread2, T as manifestFile, a as projectFolderOverwriteWarning, d as subscribeExplorerState, f as writeExplorerState, j as projectFile, l as readExplorerState, p as FolderError, s as hiddenEntry, t as followProjectFolder } from "./shared-CLo1e5zK.js";
2
2
  import * as React from "react";
3
3
  import { useEffect, useState } from "react";
4
4
  import { createPortal } from "react-dom";
@@ -1463,7 +1463,7 @@ function createFilePreview(directory, documentId, { name, path }, locale, readBa
1463
1463
  status.textContent = message.large;
1464
1464
  return;
1465
1465
  }
1466
- const [bytes, { decodeText, mountTextFile }] = await Promise.all([file.arrayBuffer(), import("./shared-CwQoV7xd.js")]);
1466
+ const [bytes, { decodeText, mountTextFile }] = await Promise.all([file.arrayBuffer(), import("./shared-DkIVN2xk.js")]);
1467
1467
  if (disposed) return;
1468
1468
  const content = decodeText(bytes);
1469
1469
  if (content === null) {
@@ -3,7 +3,7 @@ export type ExplorerMutation = (guard: () => void) => Promise<void>;
3
3
  export type ProjectFolderLocation = 'device' | 'browser';
4
4
  export interface FollowedFolder {
5
5
  readonly directory: FileSystemDirectoryHandle | null;
6
- /** The folder the user chose for `directory`: itself, or the repository whose `project` folder it is. */
6
+ /** The folder the user chose for `directory`: itself, unless a host gave another one to `openDirectory`. */
7
7
  readonly root?: FileSystemDirectoryHandle | null;
8
8
  /** Storage choices available when creating a project folder. */
9
9
  readonly locations?: readonly ProjectFolderLocation[];
@@ -17,7 +17,7 @@ export interface FollowedFolder {
17
17
  export declare function registerFolder(vm: object, folder: FollowedFolder): () => void;
18
18
  /**
19
19
  * Calls `listener` with the project folder mounted for `vm`, the directory open in it and the folder the user chose for
20
- * it (`root`, the directory itself or the repository that holds it in `project/`), now and whenever a folder is
20
+ * it (`root`, the directory itself unless a host gave another one), now and whenever a folder is
21
21
  * mounted, opened, closed or saved. `directory` and `root` are `null` while no folder is open. Returns the function
22
22
  * that stops it.
23
23
  */
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ProjectFolderLocation } from './folder-registry.js';
2
2
  import type { BrowserProjects } from './browser-projects.js';
3
- import type { FolderHost, FolderVM } from './session.js';
3
+ import type { FolderHost, FolderVM, OpenResult } from './session.js';
4
4
  export type { Comparison, ComparisonRequest, ComparisonSection, FolderHost, FolderScreenState, FolderVM, OpenResult } from './session.js';
5
5
  export type { ReloadTarget } from './block-reload.js';
6
6
  export { followProjectFolder } from './folder-registry.js';
@@ -11,6 +11,7 @@ export { openBrowserProjects } from './browser-projects.js';
11
11
  export type { BrowserProject, BrowserProjects, BrowserStorageState } from './browser-projects.js';
12
12
  export { chooseBrowserProject, exportBrowserProject, zipFileName } from './browser-project-dialog.js';
13
13
  export type { BrowserProjectChoice } from './browser-project-dialog.js';
14
+ export { notProjectFolderMessage, showNotProjectFolderDialog } from './not-project-dialog.js';
14
15
  export { zipDirectory } from './zip.js';
15
16
  type MenuElement = (component: any, props: any, ...children: any[]) => any;
16
17
  interface MenuProps {
@@ -28,6 +29,16 @@ interface MenuProps {
28
29
  * - `off`: only folders on the device.
29
30
  */
30
31
  export type BrowserStorageMode = 'fallback' | 'always' | 'off';
32
+ /** Options of `openDirectory`. */
33
+ export interface OpenDirectoryOptions {
34
+ /**
35
+ * Whether a folder that is not a project folder is told to the user in the error dialog (default true). A host
36
+ * that tells the user in its own way passes false and acts on the `not-project` result.
37
+ */
38
+ notProjectDialog?: boolean;
39
+ /** The locale of the dialog; defaults to the `locale` given to `mountProjectFolder`. */
40
+ locale?: string;
41
+ }
31
42
  /**
32
43
  * `autoReload` (default true) applies value and position changes without a click when the Editor has no unsaved
33
44
  * edits and the project is stopped. Other changes always wait for the reload command.
@@ -40,7 +51,13 @@ export declare function mountProjectFolder({ vm, document, host, locale, autoRel
40
51
  autoReload?: boolean;
41
52
  browserStorage?: BrowserStorageMode;
42
53
  }): {
43
- openDirectory: (directory: FileSystemDirectoryHandle, confirmReplace: () => boolean, root?: FileSystemDirectoryHandle | undefined) => Promise<import("./session.js").OpenResult>;
54
+ /**
55
+ * Opens the project at the root of `directory`, as the user's Open would, and resolves with the result. A folder
56
+ * that is not a project folder changes nothing, shows the error dialog unless `options.notProjectDialog` is
57
+ * false, and resolves with `not-project`. `root` is the folder the user chose, for a host that located the
58
+ * project in it; it defaults to `directory`.
59
+ */
60
+ openDirectory: (directory: FileSystemDirectoryHandle, confirmReplace: () => boolean, root?: FileSystemDirectoryHandle | null, options?: OpenDirectoryOptions) => Promise<OpenResult>;
44
61
  unsavedPaths: () => ReadonlySet<string> | null;
45
62
  readUnsavedFile: (path: string) => Uint8Array<ArrayBufferLike> | null | undefined;
46
63
  subscribeEdits: (listener: () => void) => () => void;
@@ -62,15 +79,15 @@ export declare function mountProjectFolder({ vm, document, host, locale, autoRel
62
79
  title?: string;
63
80
  /** Explicit destination; omitted uses the device picker when available. */
64
81
  location?: ProjectFolderLocation;
65
- }): Promise<import("./session.js").OpenResult>;
82
+ }): Promise<OpenResult>;
66
83
  /**
67
84
  * The folder the loaded project came from, or `null` once another project loaded or the folder was
68
85
  * detached. A host can tell projects apart by it, for example to keep the layout of each one.
69
86
  */
70
87
  readonly directory: FileSystemDirectoryHandle | null;
71
88
  /**
72
- * The folder the user chose for the loaded project, or `null` like `directory`. It is `directory` itself, or
73
- * the repository whose `project` folder holds the project, or the stored folder of a folder kept in the browser.
89
+ * The folder the user chose for the loaded project, or `null` like `directory`. It is `directory` itself, the
90
+ * project folder, unless the host gave another folder to `openDirectory`.
74
91
  */
75
92
  readonly root: FileSystemDirectoryHandle | null;
76
93
  dispose(): void;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { A as projectFile, C as isObject, D as planExtensionSave, E as parseProject, F as _asyncIterator, I as _objectWithoutProperties, L as _objectSpread2, M as readProjectFolder, N as sameBytes, O as projectAssets, P as unsupported, S as fileVersion, T as paletteFile, _ as collapsePalette, a as projectFolderOverwriteWarning, b as expandPalette, c as parseExplorerState, d as subscribeExplorerState, f as writeExplorerState, g as assetTypeFor, h as assetKey, i as isProjectFolderEmpty, j as readFolderUpdate, k as projectChanges, l as readExplorerState, m as assertFolderUnchanged, n as registerFolder, o as editorDirectory, p as FolderError, r as createProjectFolder, t as followProjectFolder, u as screenStateFile, v as encodePalette, w as manifestFile, x as extensionsFile, y as equal } from "./shared-h5VGx9Jp.js";
1
+ import { A as projectChanges, C as isObject, D as parseProject, E as paletteFile, F as unsupported, I as _asyncIterator, L as _objectWithoutProperties, M as readFolder, N as readFolderUpdate, O as planExtensionSave, P as sameBytes, R as _objectSpread2, S as fileVersion, T as manifestFile, _ as collapsePalette, a as projectFolderOverwriteWarning, b as expandPalette, c as parseExplorerState, d as subscribeExplorerState, f as writeExplorerState, g as assetTypeFor, h as assetKey, i as isProjectFolderEmpty, j as projectFile, k as projectAssets, l as readExplorerState, m as assertFolderUnchanged, n as registerFolder, o as editorDirectory, p as FolderError, r as createProjectFolder, t as followProjectFolder, u as screenStateFile, v as encodePalette, w as isProjectFolder, x as extensionsFile, y as equal } from "./shared-CLo1e5zK.js";
2
2
  // src/block-reload.ts
3
3
  var _excluded$3 = ["targets"];
4
4
  var _excluded2$1 = ["targets"];
@@ -513,7 +513,8 @@ function createFolderSession(vm, host) {
513
513
  vm.off("PROJECT_CHANGED", changed);
514
514
  unregisterTree === null || unregisterTree === void 0 || unregisterTree();
515
515
  };
516
- const openFrom = async (getDirectory, confirmReplace, prepare = (directory) => readProjectFolder(directory, vm.runtime.storage), stillCurrent = () => true) => {
516
+ const readProject = async (directory) => await isProjectFolder(directory) ? readFolder(directory, vm.runtime.storage) : "not-project";
517
+ const openFrom = async (getDirectory, confirmReplace, prepare = readProject, stillCurrent = () => true) => {
517
518
  if (disposed || busy) return "cancelled";
518
519
  busy = true;
519
520
  const priorStage = vm.runtime.getTargetForStage();
@@ -523,6 +524,7 @@ function createFolderSession(vm, host) {
523
524
  if (!chosen || disposed) return "cancelled";
524
525
  const storage = vm.runtime.storage;
525
526
  const source = await prepare(chosen.directory);
527
+ if (source === "not-project") return disposed ? "cancelled" : "not-project";
526
528
  if (!source || disposed || !stillCurrent() || vm.runtime.getTargetForStage() !== priorStage) return "cancelled";
527
529
  if (host.isProjectDirty() && !confirmReplace()) return "cancelled";
528
530
  host.beforeLoad();
@@ -705,7 +707,7 @@ function createFolderSession(vm, host) {
705
707
  var _current$source$direc;
706
708
  return (_current$source$direc = current === null || current === void 0 ? void 0 : current.source.directory) !== null && _current$source$direc !== void 0 ? _current$source$direc : null;
707
709
  },
708
- /** The folder the user chose: `directory` itself, or the repository whose `project` folder it is. */
710
+ /** The folder the user chose: `directory` itself, unless a host gave another one to `openDirectory`. */
709
711
  get root() {
710
712
  var _current$root;
711
713
  return (_current$root = current === null || current === void 0 ? void 0 : current.root) !== null && _current$root !== void 0 ? _current$root : null;
@@ -810,9 +812,12 @@ function createFolderSession(vm, host) {
810
812
  return openFrom(() => Promise.resolve(current === session ? {
811
813
  directory: session.source.directory,
812
814
  root: session.root
813
- } : null), confirmReplace);
815
+ } : null), confirmReplace, (directory) => readFolder(directory, vm.runtime.storage));
814
816
  },
815
- /** `pick` gives the folder to open and, when it differs, the folder the user chose as `root`. */
817
+ /**
818
+ * `pick` gives the folder to open and, when a host located the project in another folder the user chose, that
819
+ * folder as `root`. Resolves with `not-project` when the folder is not a project folder.
820
+ */
816
821
  open(pick, confirmReplace) {
817
822
  return openFrom(async () => {
818
823
  try {
@@ -827,8 +832,9 @@ function createFolderSession(vm, host) {
827
832
  }, confirmReplace);
828
833
  },
829
834
  /**
830
- * Opens `directory`, or its `project` folder when it has no project of its own. `root` is the folder the user
831
- * chose, for a host that located the project itself; it defaults to `directory`.
835
+ * Opens the project at the root of `directory`, or resolves with `not-project` and changes nothing when the
836
+ * folder is not a project folder. `root` is the folder the user chose, for a host that located the project in
837
+ * it; it defaults to `directory`.
832
838
  */
833
839
  openDirectory(directory, confirmReplace, root) {
834
840
  return openFrom(() => Promise.resolve({
@@ -1315,7 +1321,7 @@ async function zipDirectory(directory, { exclude = () => false } = {}) {
1315
1321
  ], { type: "application/zip" });
1316
1322
  }
1317
1323
  // src/browser-project-dialog.ts
1318
- var messages$1 = {
1324
+ var messages$2 = {
1319
1325
  en: {
1320
1326
  openTitle: "Project Folders in This Browser",
1321
1327
  createTitle: "New Project Folder in This Browser",
@@ -1390,11 +1396,11 @@ async function exportBrowserProject(document, projects, project) {
1390
1396
  }
1391
1397
  /**
1392
1398
  * Shows the project folders kept in this browser. With `purpose: 'open'` the user picks one; with `'create'` the user
1393
- * names a new empty one. Resolves with the chosen folder, or `null` when the dialog closes without one.
1399
+ * names a new empty one. Resolves with the chosen stored folder, or `null` when the dialog closes without one.
1394
1400
  */
1395
1401
  function chooseBrowserProject({ document, projects, locale = "en", purpose, title = "" }) {
1396
1402
  var _ref, _ref2, _dialog$querySelector;
1397
- const message = locale.startsWith("ja") ? messages$1.ja : messages$1.en;
1403
+ const message = locale.startsWith("ja") ? messages$2.ja : messages$2.en;
1398
1404
  const view = document.defaultView;
1399
1405
  const dialog = document.createElement("dialog");
1400
1406
  dialog.dataset.browserProjects = purpose;
@@ -1607,7 +1613,7 @@ function chooseBrowserProject({ document, projects, locale = "en", purpose, titl
1607
1613
  return element;
1608
1614
  };
1609
1615
  item.append(text, button(message.open, async () => {
1610
- const directory = await projects.directory(project.id);
1616
+ const directory = await projects.root(project.id);
1611
1617
  if (!directory) return render();
1612
1618
  finish({
1613
1619
  project,
@@ -1640,6 +1646,88 @@ function chooseBrowserProject({ document, projects, locale = "en", purpose, titl
1640
1646
  (_ref = (_ref2 = (_dialog$querySelector = dialog.querySelector("input")) !== null && _dialog$querySelector !== void 0 ? _dialog$querySelector : dialog.querySelector("[data-browser-projects-list] button")) !== null && _ref2 !== void 0 ? _ref2 : close) === null || _ref === void 0 || _ref.focus();
1641
1647
  return result;
1642
1648
  }
1649
+ // src/not-project-dialog.ts
1650
+ var messages$1 = {
1651
+ en: {
1652
+ title: "Cannot Open Folder",
1653
+ notProject: "This folder is not a project folder.",
1654
+ ok: "OK"
1655
+ },
1656
+ ja: {
1657
+ title: "フォルダを開けません",
1658
+ notProject: "このフォルダはプロジェクトフォルダではありません。",
1659
+ ok: "OK"
1660
+ }
1661
+ };
1662
+ var dialogs = 0;
1663
+ /** The message the dialog shows, for a host that tells the user in its own way. */
1664
+ var notProjectFolderMessage = (locale = "en") => (locale.startsWith("ja") ? messages$1.ja : messages$1.en).notProject;
1665
+ /**
1666
+ * Tells the user, in a modal dialog, that the folder they tried to open is not a project folder. Resolves when the
1667
+ * dialog closes, after the focus went back to where it was.
1668
+ */
1669
+ async function showNotProjectFolderDialog({ document, locale = "en" }) {
1670
+ const message = locale.startsWith("ja") ? messages$1.ja : messages$1.en;
1671
+ const returnFocus = document.activeElement;
1672
+ const id = `tw-plus-project-folder-error-${++dialogs}`;
1673
+ const dialog = document.createElement("dialog");
1674
+ dialog.dataset.projectFolderError = "not-project";
1675
+ dialog.setAttribute("role", "alertdialog");
1676
+ dialog.setAttribute("aria-labelledby", `${id}-title`);
1677
+ dialog.setAttribute("aria-describedby", `${id}-message`);
1678
+ Object.assign(dialog.style, {
1679
+ width: "min(26rem, calc(100vw - 2rem))",
1680
+ padding: "1rem 1.25rem",
1681
+ background: "Canvas",
1682
+ color: "CanvasText",
1683
+ border: "1px solid GrayText",
1684
+ borderRadius: "0.5rem",
1685
+ fontFamily: "inherit",
1686
+ fontSize: "0.875rem",
1687
+ boxSizing: "border-box"
1688
+ });
1689
+ const heading = document.createElement("h2");
1690
+ heading.id = `${id}-title`;
1691
+ heading.textContent = message.title;
1692
+ Object.assign(heading.style, {
1693
+ margin: "0 0 0.5rem",
1694
+ fontSize: "1rem"
1695
+ });
1696
+ const text = document.createElement("p");
1697
+ text.id = `${id}-message`;
1698
+ text.textContent = message.notProject;
1699
+ Object.assign(text.style, { margin: "0 0 1rem" });
1700
+ const footer = document.createElement("div");
1701
+ Object.assign(footer.style, {
1702
+ display: "flex",
1703
+ justifyContent: "flex-end"
1704
+ });
1705
+ const ok = document.createElement("button");
1706
+ ok.type = "button";
1707
+ ok.textContent = message.ok;
1708
+ footer.append(ok);
1709
+ dialog.append(heading, text, footer);
1710
+ await new Promise((resolve) => {
1711
+ let settled = false;
1712
+ const finish = () => {
1713
+ if (settled) return;
1714
+ settled = true;
1715
+ if (dialog.open) dialog.close();
1716
+ dialog.remove();
1717
+ if ((returnFocus === null || returnFocus === void 0 ? void 0 : returnFocus.isConnected) && typeof returnFocus.focus === "function") returnFocus.focus();
1718
+ resolve();
1719
+ };
1720
+ ok.addEventListener("click", finish);
1721
+ dialog.addEventListener("cancel", (event) => {
1722
+ event.preventDefault();
1723
+ finish();
1724
+ });
1725
+ dialog.addEventListener("close", finish);
1726
+ document.body.append(dialog);
1727
+ dialog.showModal();
1728
+ ok.focus();
1729
+ });
1730
+ }
1643
1731
  // src/index.ts
1644
1732
  var messages = {
1645
1733
  en: {
@@ -1736,14 +1824,7 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1736
1824
  if (!choice) throw abort();
1737
1825
  return choice;
1738
1826
  };
1739
- const chooseBrowserFolder = async () => {
1740
- var _await$browserProject;
1741
- const { project, directory } = await chooseBrowser("open");
1742
- return {
1743
- directory,
1744
- root: (_await$browserProject = await browserProjects.root(project.id).catch(() => null)) !== null && _await$browserProject !== void 0 ? _await$browserProject : directory
1745
- };
1746
- };
1827
+ const chooseBrowserFolder = async () => ({ directory: (await chooseBrowser("open")).directory });
1747
1828
  const pickDirectory = devicePicker ? async (options) => ({ directory: await devicePicker.call(view, options) }) : chooseBrowserFolder;
1748
1829
  const locations = [];
1749
1830
  if (devicePicker) locations.push("device");
@@ -1796,6 +1877,10 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1796
1877
  const detail = error instanceof FolderError && error.message !== error.code ? ` (${error.message})` : "";
1797
1878
  report((error instanceof FolderError ? message[error.code] : message.failed) + detail);
1798
1879
  };
1880
+ const notProject = (locale) => showNotProjectFolderDialog({
1881
+ document,
1882
+ locale
1883
+ }).catch(() => report(notProjectFolderMessage(locale)));
1799
1884
  let stopWatching;
1800
1885
  let renderReload = () => {};
1801
1886
  if (host.blockReload) {
@@ -1937,21 +2022,21 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1937
2022
  notice.remove();
1938
2023
  };
1939
2024
  }
2025
+ const opened = (locale, result) => {
2026
+ if (result === "opened") report(messageFor(locale).opened);
2027
+ else if (result === "not-project") notProject(locale);
2028
+ };
1940
2029
  const menu = {
1941
2030
  deviceFolders: typeof devicePicker === "function",
1942
2031
  session,
1943
2032
  open(locale) {
1944
2033
  const message = messageFor(locale);
1945
- session.open((options) => pickDirectory(options), () => view.confirm(message.replace)).then((result) => {
1946
- if (result === "opened") report(message.opened);
1947
- }, (error) => fail(locale, error)).finally(renderReload);
2034
+ session.open((options) => pickDirectory(options), () => view.confirm(message.replace)).then((result) => opened(locale, result), (error) => fail(locale, error)).finally(renderReload);
1948
2035
  renderReload();
1949
2036
  },
1950
2037
  openBrowser: browserProjects ? (locale) => {
1951
2038
  const message = messageFor(locale);
1952
- session.open(chooseBrowserFolder, () => view.confirm(message.replace)).then((result) => {
1953
- if (result === "opened") report(message.opened);
1954
- }, (error) => fail(locale, error)).finally(renderReload);
2039
+ session.open(chooseBrowserFolder, () => view.confirm(message.replace)).then((result) => opened(locale, result), (error) => fail(locale, error)).finally(renderReload);
1955
2040
  renderReload();
1956
2041
  } : void 0,
1957
2042
  save(locale) {
@@ -1987,7 +2072,17 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1987
2072
  mutate: (directory, operation) => session.mutate(directory, operation).finally(renderReload)
1988
2073
  });
1989
2074
  return {
1990
- openDirectory: (...args) => session.openDirectory(...args).finally(renderReload),
2075
+ /**
2076
+ * Opens the project at the root of `directory`, as the user's Open would, and resolves with the result. A folder
2077
+ * that is not a project folder changes nothing, shows the error dialog unless `options.notProjectDialog` is
2078
+ * false, and resolves with `not-project`. `root` is the folder the user chose, for a host that located the
2079
+ * project in it; it defaults to `directory`.
2080
+ */
2081
+ openDirectory: (directory, confirmReplace, root, options = {}) => session.openDirectory(directory, confirmReplace, root !== null && root !== void 0 ? root : void 0).then((result) => {
2082
+ var _options$locale;
2083
+ if (result === "not-project" && options.notProjectDialog !== false) notProject((_options$locale = options.locale) !== null && _options$locale !== void 0 ? _options$locale : locale);
2084
+ return result;
2085
+ }).finally(renderReload),
1991
2086
  unsavedPaths: () => session.unsavedPaths(),
1992
2087
  readUnsavedFile: (path) => session.readUnsavedFile(path),
1993
2088
  subscribeEdits: (listener) => session.subscribeEdits(listener),
@@ -2028,8 +2123,8 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
2028
2123
  return session.directory;
2029
2124
  },
2030
2125
  /**
2031
- * The folder the user chose for the loaded project, or `null` like `directory`. It is `directory` itself, or
2032
- * the repository whose `project` folder holds the project, or the stored folder of a folder kept in the browser.
2126
+ * The folder the user chose for the loaded project, or `null` like `directory`. It is `directory` itself, the
2127
+ * project folder, unless the host gave another folder to `openDirectory`.
2033
2128
  */
2034
2129
  get root() {
2035
2130
  return session.root;
@@ -2091,4 +2186,4 @@ function renderProjectFolderMenu(createElement, { vm, locale = "en", MenuItem, M
2091
2186
  };
2092
2187
  return createElement(MenuSection, null, item("open"), entry.openBrowser ? item("openBrowser") : null, entry.session.canSave ? item("save") : null);
2093
2188
  }
2094
- export { chooseBrowserProject, createProjectFolder, exportBrowserProject, followProjectFolder, mountProjectFolder, openBrowserProjects, parseExplorerState, projectFolderActions, projectFolderOverwriteWarning, readExplorerState, renderProjectFolderMenu, subscribeExplorerState, writeExplorerState, zipDirectory, zipFileName };
2189
+ export { chooseBrowserProject, createProjectFolder, exportBrowserProject, followProjectFolder, mountProjectFolder, notProjectFolderMessage, openBrowserProjects, parseExplorerState, projectFolderActions, projectFolderOverwriteWarning, readExplorerState, renderProjectFolderMenu, showNotProjectFolderDialog, subscribeExplorerState, writeExplorerState, zipDirectory, zipFileName };
@@ -0,0 +1,10 @@
1
+ /** The message the dialog shows, for a host that tells the user in its own way. */
2
+ export declare const notProjectFolderMessage: (locale?: string) => string;
3
+ /**
4
+ * Tells the user, in a modal dialog, that the folder they tried to open is not a project folder. Resolves when the
5
+ * dialog closes, after the focus went back to where it was.
6
+ */
7
+ export declare function showNotProjectFolderDialog({ document, locale }: {
8
+ document: Document;
9
+ locale?: string;
10
+ }): Promise<void>;
package/dist/session.d.ts CHANGED
@@ -103,7 +103,12 @@ export type Chosen = {
103
103
  export type ReloadState = 'ready' | 'full' | 'waiting' | 'dirty' | 'running' | 'busy' | null;
104
104
  /** What the reload command does for the pending change, regardless of whether it may run now. */
105
105
  export type ReloadKind = 'partial' | 'full' | null;
106
- export type OpenResult = 'opened' | 'cancelled';
106
+ /**
107
+ * `opened`: the folder's project is loaded. `cancelled`: nothing was opened, as when the user closed the picker or kept
108
+ * unsaved edits. `not-project`: the folder's root lacks `project.source.json`, `sb3-source.json` or
109
+ * `embedded-extensions.json`, so it is not a project folder and nothing was opened either.
110
+ */
111
+ export type OpenResult = 'opened' | 'cancelled' | 'not-project';
107
112
  type SaveResult = {
108
113
  status: 'saved' | 'unchanged';
109
114
  sourceRemoved: string[];
@@ -128,7 +133,7 @@ export declare function createFolderSession(vm: FolderVM, host: FolderHost): {
128
133
  /** Identifies the pending project file version, so a host can attempt an automatic apply only once. */
129
134
  readonly pendingVersion: string | null;
130
135
  readonly directory: FileSystemDirectoryHandle | null;
131
- /** The folder the user chose: `directory` itself, or the repository whose `project` folder it is. */
136
+ /** The folder the user chose: `directory` itself, unless a host gave another one to `openDirectory`. */
132
137
  readonly root: FileSystemDirectoryHandle | null;
133
138
  mutate(directory: FileSystemDirectoryHandle, operation: (guard: () => void) => Promise<void>): Promise<void>;
134
139
  /**
@@ -143,14 +148,18 @@ export declare function createFolderSession(vm: FolderVM, host: FolderHost): {
143
148
  * edits are discarded only when `confirmReplace` agrees. The VM is left untouched while a project runs.
144
149
  */
145
150
  reloadAll(confirmReplace: () => boolean): Promise<OpenResult>;
146
- /** `pick` gives the folder to open and, when it differs, the folder the user chose as `root`. */
151
+ /**
152
+ * `pick` gives the folder to open and, when a host located the project in another folder the user chose, that
153
+ * folder as `root`. Resolves with `not-project` when the folder is not a project folder.
154
+ */
147
155
  open(pick: (options: {
148
156
  id: string;
149
157
  mode: "readwrite";
150
158
  }) => Promise<Chosen>, confirmReplace: () => boolean): Promise<OpenResult>;
151
159
  /**
152
- * Opens `directory`, or its `project` folder when it has no project of its own. `root` is the folder the user
153
- * chose, for a host that located the project itself; it defaults to `directory`.
160
+ * Opens the project at the root of `directory`, or resolves with `not-project` and changes nothing when the
161
+ * folder is not a project folder. `root` is the folder the user chose, for a host that located the project in
162
+ * it; it defaults to `directory`.
154
163
  */
155
164
  openDirectory(directory: FileSystemDirectoryHandle, confirmReplace: () => boolean, root?: FileSystemDirectoryHandle): Promise<OpenResult>;
156
165
  createFromSnapshot(selectDestination: () => Promise<{
@@ -404,6 +404,12 @@ var _excluded3 = ["targets"];
404
404
  var projectFile = "project.source.json";
405
405
  var manifestFile = "sb3-source.json";
406
406
  var extensionsFile = "embedded-extensions.json";
407
+ /** The files at the root of every project folder, the ones `readFolder` reads before anything else. */
408
+ var projectFolderFiles = [
409
+ projectFile,
410
+ manifestFile,
411
+ extensionsFile
412
+ ];
407
413
  /** The ZIP entry of the Editor's screen state, which sb3-toolchain lists in `archiveEntries`. */
408
414
  var screenStateEntry = "tw-plus/workspace.json";
409
415
  /** Block palette settings of source format 2. Format 1 folders have no such file. */
@@ -671,12 +677,7 @@ async function readFolder(directory, storage) {
671
677
  versions.set(prefix + name, fileVersion(file));
672
678
  return [name, await fileBytes(file)];
673
679
  };
674
- const filenames = [
675
- projectFile,
676
- manifestFile,
677
- extensionsFile
678
- ];
679
- const files = new Map(await Promise.all(filenames.map((name) => readEntry(directory, name))));
680
+ const files = new Map(await Promise.all(projectFolderFiles.map((name) => readEntry(directory, name))));
680
681
  const decoder = new TextDecoder("utf-8", { fatal: true });
681
682
  const projectText = decoder.decode(files.get(projectFile));
682
683
  const project = parseProject(projectText);
@@ -726,40 +727,20 @@ async function readFolder(directory, storage) {
726
727
  palette: paletteDocument
727
728
  };
728
729
  }
729
- /** The project folder inside a repository, as Project Starter makes it. */
730
- var projectSubfolder = "project";
731
730
  var missingEntry = (error) => error instanceof DOMException && ["NotFoundError", "TypeMismatchError"].includes(error.name);
732
- /** Whether `directory` has an entry called `name`, a file or a folder. */
733
- async function hasEntry(directory, name) {
734
- for (const get of [() => directory.getFileHandle(name), () => directory.getDirectoryHandle(name)]) try {
735
- await get();
736
- return true;
737
- } catch (error) {
738
- if (!missingEntry(error)) throw error;
739
- }
740
- return false;
741
- }
742
731
  /**
743
- * Reads the project in `directory`, or, when the folder has no project of its own, in its `project` folder, as in a
744
- * repository whose project sits in `project/`. That folder must not be a repository itself. The error is the one
745
- * for `directory` when neither holds a project.
732
+ * Whether `directory` is a project folder: its root has every file in `projectFolderFiles`. The files are not read, so a
733
+ * project folder may still be broken or unsupported, which `readFolder` reports. Other errors, such as a withdrawn
734
+ * permission, are thrown.
746
735
  */
747
- async function readProjectFolder(directory, storage) {
748
- try {
749
- return await readFolder(directory, storage);
736
+ async function isProjectFolder(directory) {
737
+ for (const name of projectFolderFiles) try {
738
+ await directory.getFileHandle(name);
750
739
  } catch (error) {
751
- const child = await (async () => {
752
- if (await hasEntry(directory, "project.source.json") || await hasEntry(directory, "sb3-source.json")) return null;
753
- const found = await directory.getDirectoryHandle(projectSubfolder);
754
- return await hasEntry(found, ".git") ? null : found;
755
- })().catch(() => null);
756
- if (!child) throw error;
757
- try {
758
- return await readFolder(child, storage);
759
- } catch (_unused2) {
760
- throw error;
761
- }
740
+ if (missingEntry(error)) return false;
741
+ throw error;
762
742
  }
743
+ return true;
763
744
  }
764
745
  var sameBytes = (a, b) => a.length === b.length && a.every((value, index) => value === b[index]);
765
746
  async function readFolderUpdate(source, previous) {
@@ -1172,7 +1153,7 @@ function registerFolder(vm, folder) {
1172
1153
  }
1173
1154
  /**
1174
1155
  * Calls `listener` with the project folder mounted for `vm`, the directory open in it and the folder the user chose for
1175
- * it (`root`, the directory itself or the repository that holds it in `project/`), now and whenever a folder is
1156
+ * it (`root`, the directory itself unless a host gave another one), now and whenever a folder is
1176
1157
  * mounted, opened, closed or saved. `directory` and `root` are `null` while no folder is open. Returns the function
1177
1158
  * that stops it.
1178
1159
  */
@@ -1199,4 +1180,4 @@ function followProjectFolder(vm, listener) {
1199
1180
  unsubscribe();
1200
1181
  };
1201
1182
  }
1202
- export { projectFile as A, isObject as C, planExtensionSave as D, parseProject as E, _asyncIterator as F, _objectWithoutProperties as I, _objectSpread2 as L, readProjectFolder as M, sameBytes as N, projectAssets as O, unsupported as P, fileVersion as S, paletteFile as T, collapsePalette as _, projectFolderOverwriteWarning as a, expandPalette as b, parseExplorerState as c, subscribeExplorerState as d, writeExplorerState as f, assetTypeFor as g, assetKey as h, isProjectFolderEmpty as i, readFolderUpdate as j, projectChanges as k, readExplorerState as l, assertFolderUnchanged as m, registerFolder as n, editorDirectory as o, FolderError as p, createProjectFolder as r, hiddenEntry as s, followProjectFolder as t, screenStateFile as u, encodePalette as v, manifestFile as w, extensionsFile as x, equal as y };
1183
+ export { projectChanges as A, isObject as C, parseProject as D, paletteFile as E, unsupported as F, _asyncIterator as I, _objectWithoutProperties as L, readFolder as M, readFolderUpdate as N, planExtensionSave as O, sameBytes as P, _objectSpread2 as R, fileVersion as S, manifestFile as T, collapsePalette as _, projectFolderOverwriteWarning as a, expandPalette as b, parseExplorerState as c, subscribeExplorerState as d, writeExplorerState as f, assetTypeFor as g, assetKey as h, isProjectFolderEmpty as i, projectFile as j, projectAssets as k, readExplorerState as l, assertFolderUnchanged as m, registerFolder as n, editorDirectory as o, FolderError as p, createProjectFolder as r, hiddenEntry as s, followProjectFolder as t, screenStateFile as u, encodePalette as v, isProjectFolder as w, extensionsFile as x, equal as y };
@@ -1,4 +1,4 @@
1
- import { L as _objectSpread2 } from "./shared-h5VGx9Jp.js";
1
+ import { R as _objectSpread2 } from "./shared-CLo1e5zK.js";
2
2
  // node_modules/@marijn/find-cluster-break/src/index.js
3
3
  var rangeFrom = [];
4
4
  var rangeTo = [];
package/dist/source.d.ts CHANGED
@@ -15,6 +15,8 @@ type Target = JsonObject & {
15
15
  export declare const projectFile = "project.source.json";
16
16
  export declare const manifestFile = "sb3-source.json";
17
17
  export declare const extensionsFile = "embedded-extensions.json";
18
+ /** The files at the root of every project folder, the ones `readFolder` reads before anything else. */
19
+ export declare const projectFolderFiles: readonly ["project.source.json", "sb3-source.json", "embedded-extensions.json"];
18
20
  /** Block palette settings of source format 2. Format 1 folders have no such file. */
19
21
  export declare const paletteFile = "block-palette.json";
20
22
  export declare class FolderError extends Error {
@@ -100,14 +102,12 @@ export declare function planExtensionSave(source: FolderSource, project: Project
100
102
  removed: string[];
101
103
  };
102
104
  export declare function readFolder(directory: FileSystemDirectoryHandle, storage: Storage): Promise<FolderSource>;
103
- /** The project folder inside a repository, as Project Starter makes it. */
104
- export declare const projectSubfolder = "project";
105
105
  /**
106
- * Reads the project in `directory`, or, when the folder has no project of its own, in its `project` folder, as in a
107
- * repository whose project sits in `project/`. That folder must not be a repository itself. The error is the one
108
- * for `directory` when neither holds a project.
106
+ * Whether `directory` is a project folder: its root has every file in `projectFolderFiles`. The files are not read, so a
107
+ * project folder may still be broken or unsupported, which `readFolder` reports. Other errors, such as a withdrawn
108
+ * permission, are thrown.
109
109
  */
110
- export declare function readProjectFolder(directory: FileSystemDirectoryHandle, storage: Storage): Promise<FolderSource>;
110
+ export declare function isProjectFolder(directory: FileSystemDirectoryHandle): Promise<boolean>;
111
111
  export declare const sameBytes: (a: Uint8Array, b: Uint8Array) => boolean;
112
112
  export type FolderUpdate = {
113
113
  version: string;
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.18.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
@@ -6,7 +6,8 @@ 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 {notProjectFolderMessage, 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,17 @@ 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
+
99
112
  const abort = () => new DOMException('The user closed the dialog', 'AbortError');
100
113
 
101
114
  /**
@@ -116,11 +129,8 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
116
129
  if (!choice) throw abort();
117
130
  return choice;
118
131
  };
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.
120
- const chooseBrowserFolder = async (): Promise<Chosen> => {
121
- const {project, directory} = await chooseBrowser('open');
122
- return {directory, root: await browserProjects!.root(project.id).catch(() => null) ?? directory};
123
- };
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});
124
134
  const pickDirectory = devicePicker ?
125
135
  async (options: {id: string; mode: 'readwrite'}): Promise<Chosen> => ({directory: await devicePicker.call(view, options)}) :
126
136
  chooseBrowserFolder;
@@ -167,6 +177,9 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
167
177
  const detail = error instanceof FolderError && error.message !== error.code ? ` (${error.message})` : '';
168
178
  report((error instanceof FolderError ? message[error.code] : message.failed) + detail);
169
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)));
170
183
  let stopWatching: (() => void) | undefined;
171
184
  let renderReload = () => {};
172
185
  if (host.blockReload) {
@@ -286,19 +299,23 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
286
299
  notice.remove();
287
300
  };
288
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
+ };
289
306
  const menu: MenuEntry = {
290
307
  deviceFolders: typeof devicePicker === 'function',
291
308
  session,
292
309
  open(locale) {
293
310
  const message = messageFor(locale);
294
311
  session.open(options => pickDirectory(options), () => view.confirm(message.replace))
295
- .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);
296
313
  renderReload();
297
314
  },
298
315
  openBrowser: browserProjects ? locale => {
299
316
  const message = messageFor(locale);
300
317
  session.open(chooseBrowserFolder, () => view.confirm(message.replace))
301
- .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);
302
319
  renderReload();
303
320
  } : undefined,
304
321
  save(locale) {
@@ -329,8 +346,18 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
329
346
  mutate: (directory, operation) => session.mutate(directory, operation).finally(renderReload)
330
347
  });
331
348
  return {
332
- openDirectory: (...args: Parameters<typeof session.openDirectory>) =>
333
- 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),
334
361
  unsavedPaths: () => session.unsavedPaths(),
335
362
  readUnsavedFile: (path: string) => session.readUnsavedFile(path),
336
363
  subscribeEdits: (listener: () => void) => session.subscribeEdits(listener),
@@ -373,8 +400,8 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
373
400
  */
374
401
  get directory() {return session.directory;},
375
402
  /**
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.
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`.
378
405
  */
379
406
  get root() {return session.root;},
380
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]);