@kubohiroya/turbowarp-plus-editor-project-folder 0.18.0 → 0.19.1

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
@@ -37,6 +37,36 @@ Safari と Firefox にはフォルダ選択(`showDirectoryPicker`)があり
37
37
 
38
38
  保存先選択の導入は、このパッケージを先に公開し、Editor の依存をその版へ固定してからホストの結線を反映します。切り戻すときは Editor の結線と依存の固定を一緒に戻します。OPFS に作成済みの作品は削除せず、ブラウザー内の一覧から開く・ZIP で書き出す経路を維持します。
39
39
 
40
+ ## フォルダの作成・写し・改名
41
+
42
+ 新しい作品を作る、写しを保存する、作品名を変えるホストは、自前の補助関数の代わりに、マウントしたセッションの次のメンバーを使います。[Editor の issue #679](https://github.com/kubohiroya/turbowarp-plus-editor/issues/679) を参照してください。
43
+
44
+ ```ts
45
+ type ProjectFolderDestination = 'browser' | FileSystemDirectoryHandle;
46
+ createFromSnapshot({prepareFiles, collectEdits?, current?, title?, destination?, directory?, location?}): Promise<OpenResult>;
47
+ copyToFolder({destination, prepareFiles, collectEdits?, current?, title?}): Promise<FileSystemDirectoryHandle | null>;
48
+ pickEmptyFolder({locale?, id?}?): Promise<FileSystemDirectoryHandle | null>;
49
+ renameCurrentBrowserFolder(title: string): Promise<boolean>;
50
+ readonly location: 'browser' | 'device' | null;
51
+ readonly locations: readonly ('device' | 'browser')[];
52
+ ```
53
+
54
+ - `createFromSnapshot({destination})` は、新しいプロジェクトフォルダを作成先に書き、`destination` がないときと同じく開きます。`'browser'` はブラウザーの保存領域に `browserProjects.create(title, {projectPath: ''})` で新しいフォルダを作り(`title` の既定は `Project`)、そこから作品が開かなかったとき、つまりユーザーが断ったとき、`current()` が偽になったとき、準備や書き込みに失敗したときには、そのフォルダを消します。ディレクトリのハンドルは、ホストが端末で選んだフォルダです。フォルダ選択は開きません。空でないフォルダは、これまでどおりユーザーが確かめたときだけ上書きします。ブラウザー内のフォルダが使えないときの `'browser'` は、`prepareFiles` を呼ぶ前に `unsupported` で失敗します。`destination` がなければ、`directory` と `location` はこれまでどおりです。
55
+ - `copyToFolder({destination, title, prepareFiles})` は、プロジェクトフォルダを書くだけで開きません(プロジェクトのコピーを保存)。開いている作品、`directory`・`root`・`location` は変わらず、`followProjectFolder` の listener も呼びません。`collectEdits`、`prepareFiles` の順に呼び、`createProjectFolder` で書いて、書いたフォルダを返します。`'browser'` は `title` という名前の新しいフォルダを作り、何も書かなかったときは消します。端末の空でないフォルダは、ユーザーが確かめたときだけ上書きします。ユーザーが断ったときや `current()` が偽になったときは、何も書かずに `null` を返します。開いているプロジェクトフォルダそのものとその `root`(`isSameEntry` で比べます)は、何も尋ねず何も書かずに `conflict` で断ります。そこへ書くのは保存です。
56
+ - `pickEmptyFolder({locale, id})` は端末のフォルダ選択(`showDirectoryPicker({id, mode: 'readwrite'})`、`id` の既定は `turbowarp-plus-project-folder`)を開き、空のフォルダならそれを返します。ユーザーが取り消したときと、空でないフォルダを選んだときは `null` を返し、後者ではモーダルのダイアログに「このフォルダは使えません」「空のフォルダを選んでください。」(英語では “Cannot Use This Folder”、“Choose an empty folder.”)を `locale` の言語で出します。ダイアログはプロジェクトフォルダでないときと同じ `<dialog>` で、`data-project-folder-error="not-empty"` を持ち、閉じてから `null` を返します。ブラウザーはクリックの処理中にしかフォルダ選択を開かないので、クリックを処理している間に呼びます。端末のフォルダを選べないブラウザーでは `unsupported` で失敗します。
57
+ - `renameCurrentBrowserFolder(title)` は、開いているフォルダの、このブラウザーのフォルダ一覧での名前を `title` にし(`browserProjects.find` と `rename`)、`true` を返します。フォルダが開いていないときや、開いているのが端末のフォルダのとき(ブラウザーからは名前を変えられません)は、何も変えずに `false` を返します。
58
+ - `location` は開いているフォルダの場所です。このブラウザー内なら `browser`、それ以外は `device`、開いていなければ `null` です。`locations` は新しいフォルダを作れる場所の一覧で、`followProjectFolder` が伝えるものと同じです。
59
+
60
+ 自前の補助関数を持つホストは、次のように置き換えます。
61
+
62
+ | ホストの補助関数 | 置き換え先 |
63
+ | --- | --- |
64
+ | ホストが新しいブラウザー内のフォルダを作って消す `createFolder(…, destination)` | `createFromSnapshot({destination, title, prepareFiles, collectEdits, current})` |
65
+ | 選んだフォルダや新しいブラウザー内のフォルダに `createProjectFolder` で書くコピーの保存 | `copyToFolder({destination, title, prepareFiles, collectEdits, current})` |
66
+ | 空でないフォルダを断るフォルダ選択 | `pickEmptyFolder({locale})` |
67
+ | ホストが自分で調べた `{browser, device}` | `locations.includes('browser')`、`locations.includes('device')` |
68
+ | 作品名の変更後の `browserProjects.find(root)` と `rename` | `renameCurrentBrowserFolder(title)`。`false` ならフォルダ名は変わりません |
69
+
40
70
  ## 0.17.0 の後の互換性のない変更: 作品はフォルダのルートに置く
41
71
 
42
72
  0.16.0 では、選んだフォルダの直下に作品がないとき、その中の `project` フォルダの作品を開きました(Project Starter が作るリポジトリの形)。この切り替えはなくしました。一つの Git リポジトリには一つの作品を、そのルートに置きます。
@@ -83,6 +113,8 @@ TurboWarp Plus Editor は、ブロックパレットの設定を画面状態(`
83
113
 
84
114
  この OPFS 対応は、ローカル連携の URL から開いた Editor の保存領域が対象です。通常の配信サイトとローカル連携では OPFS の保存領域が異なるため、配信サイトで既に作業している OPFS を直接共有しません。通常の配信サイトを開いたまま外部編集するための別オリジン接続は、この実装には含みません。
85
115
 
116
+ 通常表示で内容の高さが表示領域より小さいときは、スクロール領域の上に操作ボタンの高さに合わせた空欄を設け、先頭行がボタンに隠れないようにします。内容の編集、画面サイズの変更、タブの再表示に応じて再計算します。差分表示にも、操作ボタンが差分や表示範囲の切り替えに重ならない空欄を設けています。
117
+
86
118
  編集画面の右下には、ファイル全体と現在の表示範囲を示すミニマップを表示します。クリック・ドラッグで移動でき、ミニマップにフォーカスすると矢印・Page Up/Page Down・Home/End キーでもスクロールできます。編集、スクロール、パネルのサイズ変更、タブの再表示に追従します。差分表示では編集用のミニマップを隠します。
87
119
 
88
120
  切り戻す場合はこの UI 変更を revert し、パッケージと Editor を再ビルドします。ファイル形式の変更やデータ移行はありません。対象のヘッドレス検証は `node --test test/text-file.browser.js` で実行します。
package/README.md CHANGED
@@ -37,6 +37,36 @@ Safari and Firefox have no folder picker (`showDirectoryPicker`). In these brows
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
+ ## Creating, copying and renaming folders
41
+
42
+ A host that makes new projects, saves copies or renames projects uses these members of the mounted session instead of its own helpers. See [Editor issue #679](https://github.com/kubohiroya/turbowarp-plus-editor/issues/679).
43
+
44
+ ```ts
45
+ type ProjectFolderDestination = 'browser' | FileSystemDirectoryHandle;
46
+ createFromSnapshot({prepareFiles, collectEdits?, current?, title?, destination?, directory?, location?}): Promise<OpenResult>;
47
+ copyToFolder({destination, prepareFiles, collectEdits?, current?, title?}): Promise<FileSystemDirectoryHandle | null>;
48
+ pickEmptyFolder({locale?, id?}?): Promise<FileSystemDirectoryHandle | null>;
49
+ renameCurrentBrowserFolder(title: string): Promise<boolean>;
50
+ readonly location: 'browser' | 'device' | null;
51
+ readonly locations: readonly ('device' | 'browser')[];
52
+ ```
53
+
54
+ - `createFromSnapshot({destination})` writes the new project folder to the destination and opens it, as without `destination`. `'browser'` makes a new folder in the browser's storage with `browserProjects.create(title, {projectPath: ''})` (`title` defaults to `Project`) and removes it again unless the project opens from it: when the user declines, `current()` turns false, or preparing or writing fails. A directory handle is a folder the host picked on the device; no picker opens. A folder that is not empty is overwritten only when the user confirms it, as before. `'browser'` without the browser's folders rejects with `unsupported` before `prepareFiles` runs. Without `destination`, `directory` and `location` work as before.
55
+ - `copyToFolder({destination, title, prepareFiles})` writes a project folder and does not open it (Save a Copy): the open project, `directory`, `root` and `location` stay, and `followProjectFolder` listeners are not called. It calls `collectEdits` and then `prepareFiles`, writes with `createProjectFolder`, and resolves with the folder written. `'browser'` makes a new folder named `title`, removed again when nothing is written. A folder on the device that is not empty is overwritten only when the user confirms it; when the user declines or `current()` turns false, it resolves with `null` and writes nothing. The open project folder itself and its `root` (compared with `isSameEntry`) are refused with `conflict` before anything is asked or written; Save writes there.
56
+ - `pickEmptyFolder({locale, id})` opens the device's folder picker (`showDirectoryPicker({id, mode: 'readwrite'})`, `id` defaults to `turbowarp-plus-project-folder`) and resolves with the folder when it is empty. It resolves with `null` when the user cancelled, and when the folder is not empty, which a modal dialog tells in `locale`: “Cannot Use This Folder” with “Choose an empty folder.” (Japanese: 「このフォルダは使えません」, 「空のフォルダを選んでください。」). The dialog is the same `<dialog>` as the not-project one, with `data-project-folder-error="not-empty"`, and the call resolves once it closes. Call it while handling the user's click, because the browser opens the picker only then. Where the browser cannot pick folders on the device it rejects with `unsupported`.
57
+ - `renameCurrentBrowserFolder(title)` gives the open folder the title in the list of folders kept in this browser (`browserProjects.find` and `rename`) and resolves with `true`. It resolves with `false` and changes nothing when no folder is open or the open folder is on the device, whose name the browser cannot change.
58
+ - `location` is where the open folder is: `browser` for a folder kept in this browser, `device` for another, and `null` while none is open. `locations` lists where new folders can be made, as `followProjectFolder` reports it.
59
+
60
+ A host that had its own helpers replaces them like this:
61
+
62
+ | Host helper | Replacement |
63
+ | --- | --- |
64
+ | `createFolder(…, destination)` with a new browser folder made and removed by the host | `createFromSnapshot({destination, title, prepareFiles, collectEdits, current})` |
65
+ | Save a Copy writing with `createProjectFolder` into a picked or new browser folder | `copyToFolder({destination, title, prepareFiles, collectEdits, current})` |
66
+ | A picker that refuses a folder that is not empty | `pickEmptyFolder({locale})` |
67
+ | `{browser, device}` from the host's own checks | `locations.includes('browser')`, `locations.includes('device')` |
68
+ | `browserProjects.find(root)` and `rename` after the title changes | `renameCurrentBrowserFolder(title)`; `false` means the folder keeps its name |
69
+
40
70
  ## Breaking change after 0.17.0: the project is at the folder's root
41
71
 
42
72
  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.
package/dist/explorer.js CHANGED
@@ -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-DkIVN2xk.js")]);
1466
+ const [bytes, { decodeText, mountTextFile }] = await Promise.all([file.arrayBuffer(), import("./shared-CeJrx6Ve.js")]);
1467
1467
  if (disposed) return;
1468
1468
  const content = decodeText(bytes);
1469
1469
  if (content === null) {
package/dist/index.d.ts CHANGED
@@ -39,6 +39,11 @@ export interface OpenDirectoryOptions {
39
39
  /** The locale of the dialog; defaults to the `locale` given to `mountProjectFolder`. */
40
40
  locale?: string;
41
41
  }
42
+ /**
43
+ * Where `createFromSnapshot` and `copyToFolder` write: `browser` for a new folder in the browser's own storage, or a
44
+ * folder on the device that the host already picked, for example with `pickEmptyFolder`.
45
+ */
46
+ export type ProjectFolderDestination = 'browser' | FileSystemDirectoryHandle;
42
47
  /**
43
48
  * `autoReload` (default true) applies value and position changes without a click when the Editor has no unsaved
44
49
  * edits and the project is stopped. Other changes always wait for the reload command.
@@ -68,10 +73,14 @@ export declare function mountProjectFolder({ vm, document, host, locale, autoRel
68
73
  /** The folders kept in this browser, when they are offered, for a host that lists or exports them. */
69
74
  browserProjects: BrowserProjects | null;
70
75
  /**
71
- * Creates a project folder from a snapshot. `title` names a folder made in the browser, where the user names a
72
- * new folder instead of picking one on the device.
76
+ * Creates a project folder from a snapshot and opens it. `destination` writes to a new folder in the browser's
77
+ * storage (`browser`, named by `title`; it is removed again unless the project opens from it) or to a folder the
78
+ * host picked on the device (see `pickEmptyFolder`). Without it, `directory` is the folder the host picked, and
79
+ * otherwise `location` (or the device picker where there is one) asks the user: `title` then names a folder
80
+ * made in the browser, where the user names a new folder instead of picking one. A folder that is not empty is
81
+ * overwritten only when the user confirms it.
73
82
  */
74
- createFromSnapshot({ prepareFiles, collectEdits, directory, current, title, location }: {
83
+ createFromSnapshot({ prepareFiles, collectEdits, directory, current, title, location, destination }: {
75
84
  prepareFiles: () => Promise<ReadonlyMap<string, Uint8Array>>;
76
85
  collectEdits?: () => Promise<void>;
77
86
  directory?: FileSystemDirectoryHandle;
@@ -79,7 +88,44 @@ export declare function mountProjectFolder({ vm, document, host, locale, autoRel
79
88
  title?: string;
80
89
  /** Explicit destination; omitted uses the device picker when available. */
81
90
  location?: ProjectFolderLocation;
91
+ destination?: ProjectFolderDestination;
82
92
  }): Promise<OpenResult>;
93
+ /**
94
+ * Writes a project folder from a snapshot to `destination` and leaves the open project as it is: nothing is
95
+ * opened or attached, `directory` and `root` stay, and `followProjectFolder` listeners are not called (Save a
96
+ * Copy). `browser` makes a new folder in the browser's storage named by `title`, removed again when nothing is
97
+ * written; a folder on the device that is not empty is overwritten only when the user confirms it. Resolves
98
+ * with the folder written, or `null` when the user declined or `current()` turned false. The open project
99
+ * folder and its `root` are refused with `conflict` before anything is asked or written.
100
+ */
101
+ copyToFolder({ destination, prepareFiles, collectEdits, current, title }: {
102
+ destination: ProjectFolderDestination;
103
+ prepareFiles: () => Promise<ReadonlyMap<string, Uint8Array>>;
104
+ collectEdits?: () => Promise<void>;
105
+ current?: () => boolean;
106
+ title?: string;
107
+ }): Promise<FileSystemDirectoryHandle | null>;
108
+ /**
109
+ * Asks the user for an empty folder on the device, for a new project. Call it while handling the user's click,
110
+ * as the browser lets the folder picker open only then. Resolves with `null` when the user cancelled, or chose
111
+ * a folder that is not empty, which a modal dialog then tells (“Choose an empty folder.”); it resolves once the
112
+ * dialog closes. Rejects with
113
+ * `unsupported` where the browser cannot pick folders on the device.
114
+ */
115
+ pickEmptyFolder({ locale: language, id }?: {
116
+ locale?: string;
117
+ id?: string;
118
+ }): Promise<FileSystemDirectoryHandle | null>;
119
+ /**
120
+ * Gives the open folder the title `title` in the list of folders kept in this browser. Resolves with `false`,
121
+ * changing nothing, when no folder is open or the open folder is not kept in this browser: a folder on the
122
+ * device keeps its name, as the browser cannot rename it.
123
+ */
124
+ renameCurrentBrowserFolder(title: string): Promise<boolean>;
125
+ /** Where the open folder is: `browser` for a folder kept in this browser, `device`, or `null` with none open. */
126
+ readonly location: ProjectFolderLocation | null;
127
+ /** Where new project folders can be made: `device` with the folder picker, and `browser` with the browser's folders. */
128
+ locations: readonly ProjectFolderLocation[];
83
129
  /**
84
130
  * The folder the loaded project came from, or `null` once another project loaded or the folder was
85
131
  * detached. A host can tell projects apart by it, for example to keep the layout of each one.
package/dist/index.js CHANGED
@@ -1651,11 +1651,15 @@ var messages$1 = {
1651
1651
  en: {
1652
1652
  title: "Cannot Open Folder",
1653
1653
  notProject: "This folder is not a project folder.",
1654
+ notEmptyTitle: "Cannot Use This Folder",
1655
+ notEmpty: "Choose an empty folder.",
1654
1656
  ok: "OK"
1655
1657
  },
1656
1658
  ja: {
1657
1659
  title: "フォルダを開けません",
1658
1660
  notProject: "このフォルダはプロジェクトフォルダではありません。",
1661
+ notEmptyTitle: "このフォルダは使えません",
1662
+ notEmpty: "空のフォルダを選んでください。",
1659
1663
  ok: "OK"
1660
1664
  }
1661
1665
  };
@@ -1666,12 +1670,25 @@ var notProjectFolderMessage = (locale = "en") => (locale.startsWith("ja") ? mess
1666
1670
  * Tells the user, in a modal dialog, that the folder they tried to open is not a project folder. Resolves when the
1667
1671
  * dialog closes, after the focus went back to where it was.
1668
1672
  */
1669
- async function showNotProjectFolderDialog({ document, locale = "en" }) {
1673
+ function showNotProjectFolderDialog({ document, locale = "en" }) {
1670
1674
  const message = locale.startsWith("ja") ? messages$1.ja : messages$1.en;
1675
+ return showFolderErrorDialog(document, "not-project", message.title, message.notProject, message.ok);
1676
+ }
1677
+ /** The message of the dialog for a folder that is not empty. */
1678
+ var folderNotEmptyMessage = (locale = "en") => (locale.startsWith("ja") ? messages$1.ja : messages$1.en).notEmpty;
1679
+ /**
1680
+ * Tells the user, in the same modal dialog, that the folder they chose for a new project is not empty. Resolves when
1681
+ * the dialog closes.
1682
+ */
1683
+ function showFolderNotEmptyDialog({ document, locale = "en" }) {
1684
+ const message = locale.startsWith("ja") ? messages$1.ja : messages$1.en;
1685
+ return showFolderErrorDialog(document, "not-empty", message.notEmptyTitle, message.notEmpty, message.ok);
1686
+ }
1687
+ async function showFolderErrorDialog(document, kind, title, body, okLabel) {
1671
1688
  const returnFocus = document.activeElement;
1672
1689
  const id = `tw-plus-project-folder-error-${++dialogs}`;
1673
1690
  const dialog = document.createElement("dialog");
1674
- dialog.dataset.projectFolderError = "not-project";
1691
+ dialog.dataset.projectFolderError = kind;
1675
1692
  dialog.setAttribute("role", "alertdialog");
1676
1693
  dialog.setAttribute("aria-labelledby", `${id}-title`);
1677
1694
  dialog.setAttribute("aria-describedby", `${id}-message`);
@@ -1688,14 +1705,14 @@ async function showNotProjectFolderDialog({ document, locale = "en" }) {
1688
1705
  });
1689
1706
  const heading = document.createElement("h2");
1690
1707
  heading.id = `${id}-title`;
1691
- heading.textContent = message.title;
1708
+ heading.textContent = title;
1692
1709
  Object.assign(heading.style, {
1693
1710
  margin: "0 0 0.5rem",
1694
1711
  fontSize: "1rem"
1695
1712
  });
1696
1713
  const text = document.createElement("p");
1697
1714
  text.id = `${id}-message`;
1698
- text.textContent = message.notProject;
1715
+ text.textContent = body;
1699
1716
  Object.assign(text.style, { margin: "0 0 1rem" });
1700
1717
  const footer = document.createElement("div");
1701
1718
  Object.assign(footer.style, {
@@ -1704,7 +1721,7 @@ async function showNotProjectFolderDialog({ document, locale = "en" }) {
1704
1721
  });
1705
1722
  const ok = document.createElement("button");
1706
1723
  ok.type = "button";
1707
- ok.textContent = message.ok;
1724
+ ok.textContent = okLabel;
1708
1725
  footer.append(ok);
1709
1726
  dialog.append(heading, text, footer);
1710
1727
  await new Promise((resolve) => {
@@ -1802,6 +1819,7 @@ var messages = {
1802
1819
  }
1803
1820
  };
1804
1821
  var menus = /* @__PURE__ */ new WeakMap();
1822
+ var folderPickerId = "turbowarp-plus-project-folder";
1805
1823
  var abort = () => new DOMException("The user closed the dialog", "AbortError");
1806
1824
  /**
1807
1825
  * `autoReload` (default true) applies value and position changes without a click when the Editor has no unsaved
@@ -1824,7 +1842,11 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1824
1842
  if (!choice) throw abort();
1825
1843
  return choice;
1826
1844
  };
1827
- const chooseBrowserFolder = async () => ({ directory: (await chooseBrowser("open")).directory });
1845
+ const chooseBrowserFolder = async () => {
1846
+ const { directory } = await chooseBrowser("open");
1847
+ browserRoots.add(directory);
1848
+ return { directory };
1849
+ };
1828
1850
  const pickDirectory = devicePicker ? async (options) => ({ directory: await devicePicker.call(view, options) }) : chooseBrowserFolder;
1829
1851
  const locations = [];
1830
1852
  if (devicePicker) locations.push("device");
@@ -1843,6 +1865,28 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1843
1865
  return result;
1844
1866
  });
1845
1867
  };
1868
+ const browserRoots = /* @__PURE__ */ new WeakSet();
1869
+ const classify = async (handle) => {
1870
+ if (browserProjects && await browserProjects.find(handle).catch(() => null)) browserRoots.add(handle);
1871
+ };
1872
+ /**
1873
+ * Runs `run` on a new folder in the browser's storage named `title`, and removes the folder again unless `keep`
1874
+ * says the result is worth keeping, also when `run` throws.
1875
+ */
1876
+ const withNewBrowserFolder = async (title, run, keep) => {
1877
+ if (!browserProjects) throw new FolderError("unsupported");
1878
+ const project = await browserProjects.create(title || "Project", { projectPath: "" });
1879
+ browserRoots.add(project.root);
1880
+ let kept = false;
1881
+ try {
1882
+ const result = await run(project.root);
1883
+ kept = keep(result);
1884
+ return result;
1885
+ } finally {
1886
+ if (!kept) await browserProjects.remove(project.id).catch(() => {});
1887
+ }
1888
+ };
1889
+ const overwriteMessage = () => locale.startsWith("ja") ? "指定されたフォルダは空ではありません。フォルダに保存されている内容が上書きされる場合があります。よろしいですか?" : "The selected folder is not empty. Contents in the folder may be overwritten. Continue?";
1846
1890
  const session = createFolderSession(vm, host);
1847
1891
  const status = document.createElement("output");
1848
1892
  status.dataset.projectFolderStatus = "";
@@ -2078,7 +2122,7 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
2078
2122
  * false, and resolves with `not-project`. `root` is the folder the user chose, for a host that located the
2079
2123
  * project in it; it defaults to `directory`.
2080
2124
  */
2081
- openDirectory: (directory, confirmReplace, root, options = {}) => session.openDirectory(directory, confirmReplace, root !== null && root !== void 0 ? root : void 0).then((result) => {
2125
+ openDirectory: (directory, confirmReplace, root, options = {}) => classify(root !== null && root !== void 0 ? root : directory).then(() => session.openDirectory(directory, confirmReplace, root !== null && root !== void 0 ? root : void 0)).then((result) => {
2082
2126
  var _options$locale;
2083
2127
  if (result === "not-project" && options.notProjectDialog !== false) notProject((_options$locale = options.locale) !== null && _options$locale !== void 0 ? _options$locale : locale);
2084
2128
  return result;
@@ -2090,20 +2134,24 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
2090
2134
  /** The folders kept in this browser, when they are offered, for a host that lists or exports them. */
2091
2135
  browserProjects,
2092
2136
  /**
2093
- * Creates a project folder from a snapshot. `title` names a folder made in the browser, where the user names a
2094
- * new folder instead of picking one on the device.
2137
+ * Creates a project folder from a snapshot and opens it. `destination` writes to a new folder in the browser's
2138
+ * storage (`browser`, named by `title`; it is removed again unless the project opens from it) or to a folder the
2139
+ * host picked on the device (see `pickEmptyFolder`). Without it, `directory` is the folder the host picked, and
2140
+ * otherwise `location` (or the device picker where there is one) asks the user: `title` then names a folder
2141
+ * made in the browser, where the user names a new folder instead of picking one. A folder that is not empty is
2142
+ * overwritten only when the user confirms it.
2095
2143
  */
2096
- createFromSnapshot({ prepareFiles, collectEdits, directory, current = () => true, title, location }) {
2097
- const message = locale.startsWith("ja") ? "指定されたフォルダは空ではありません。フォルダに保存されている内容が上書きされる場合があります。よろしいですか?" : "The selected folder is not empty. Contents in the folder may be overwritten. Continue?";
2098
- return session.createFromSnapshot(async () => {
2144
+ createFromSnapshot({ prepareFiles, collectEdits, directory, current = () => true, title, location, destination }) {
2145
+ const create = (picked) => session.createFromSnapshot(async () => {
2099
2146
  try {
2100
- const selected = directory !== null && directory !== void 0 ? directory : await pickNewDirectory({
2101
- id: "turbowarp-plus-project-folder",
2147
+ const selected = picked !== null && picked !== void 0 ? picked : await pickNewDirectory({
2148
+ id: folderPickerId,
2102
2149
  mode: "readwrite"
2103
2150
  }, title, location);
2104
2151
  if (!current()) return null;
2152
+ await classify(selected);
2105
2153
  const overwrite = !await isProjectFolderEmpty(selected);
2106
- if (!current() || overwrite && !view.confirm(message)) return null;
2154
+ if (!current() || overwrite && !view.confirm(overwriteMessage())) return null;
2107
2155
  await (collectEdits === null || collectEdits === void 0 ? void 0 : collectEdits());
2108
2156
  return current() ? {
2109
2157
  directory: selected,
@@ -2114,8 +2162,91 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
2114
2162
  throw error;
2115
2163
  }
2116
2164
  }, prepareFiles, current).finally(renderReload);
2165
+ if (destination === "browser") return withNewBrowserFolder(title, create, (result) => result === "opened");
2166
+ return create(destination !== null && destination !== void 0 ? destination : directory);
2117
2167
  },
2118
2168
  /**
2169
+ * Writes a project folder from a snapshot to `destination` and leaves the open project as it is: nothing is
2170
+ * opened or attached, `directory` and `root` stay, and `followProjectFolder` listeners are not called (Save a
2171
+ * Copy). `browser` makes a new folder in the browser's storage named by `title`, removed again when nothing is
2172
+ * written; a folder on the device that is not empty is overwritten only when the user confirms it. Resolves
2173
+ * with the folder written, or `null` when the user declined or `current()` turned false. The open project
2174
+ * folder and its `root` are refused with `conflict` before anything is asked or written.
2175
+ */
2176
+ async copyToFolder({ destination, prepareFiles, collectEdits, current = () => true, title }) {
2177
+ if (destination !== "browser") {
2178
+ for (const open of [session.directory, session.root]) if (open && (open === destination || await open.isSameEntry(destination).catch(() => false))) throw new FolderError("conflict", "The copy cannot go to the open project folder");
2179
+ }
2180
+ const write = async (target, isNew) => {
2181
+ try {
2182
+ const overwrite = !isNew && !await isProjectFolderEmpty(target);
2183
+ if (!current() || overwrite && !view.confirm(overwriteMessage())) return null;
2184
+ await (collectEdits === null || collectEdits === void 0 ? void 0 : collectEdits());
2185
+ if (!current()) return null;
2186
+ const files = await prepareFiles();
2187
+ if (!current()) return null;
2188
+ await createProjectFolder({
2189
+ directory: target,
2190
+ files,
2191
+ storage: vm.runtime.storage,
2192
+ overwrite,
2193
+ current
2194
+ });
2195
+ return target;
2196
+ } catch (error) {
2197
+ if (error instanceof DOMException && error.name === "AbortError") return null;
2198
+ throw error;
2199
+ }
2200
+ };
2201
+ if (destination === "browser") return withNewBrowserFolder(title, (root) => write(root, true), (result) => result !== null);
2202
+ return write(destination, false);
2203
+ },
2204
+ /**
2205
+ * Asks the user for an empty folder on the device, for a new project. Call it while handling the user's click,
2206
+ * as the browser lets the folder picker open only then. Resolves with `null` when the user cancelled, or chose
2207
+ * a folder that is not empty, which a modal dialog then tells (“Choose an empty folder.”); it resolves once the
2208
+ * dialog closes. Rejects with
2209
+ * `unsupported` where the browser cannot pick folders on the device.
2210
+ */
2211
+ async pickEmptyFolder({ locale: language = locale, id = folderPickerId } = {}) {
2212
+ if (!devicePicker) throw new FolderError("unsupported");
2213
+ let picked;
2214
+ try {
2215
+ picked = await devicePicker.call(view, {
2216
+ id,
2217
+ mode: "readwrite"
2218
+ });
2219
+ } catch (error) {
2220
+ if (error instanceof DOMException && error.name === "AbortError") return null;
2221
+ throw error;
2222
+ }
2223
+ if (await isProjectFolderEmpty(picked)) return picked;
2224
+ await showFolderNotEmptyDialog({
2225
+ document,
2226
+ locale: language
2227
+ }).catch(() => report(folderNotEmptyMessage(language)));
2228
+ return null;
2229
+ },
2230
+ /**
2231
+ * Gives the open folder the title `title` in the list of folders kept in this browser. Resolves with `false`,
2232
+ * changing nothing, when no folder is open or the open folder is not kept in this browser: a folder on the
2233
+ * device keeps its name, as the browser cannot rename it.
2234
+ */
2235
+ async renameCurrentBrowserFolder(title) {
2236
+ const root = session.root;
2237
+ const entry = root && browserProjects ? await browserProjects.find(root).catch(() => null) : null;
2238
+ if (!entry || session.root !== root) return false;
2239
+ await browserProjects.rename(entry.id, title);
2240
+ return true;
2241
+ },
2242
+ /** Where the open folder is: `browser` for a folder kept in this browser, `device`, or `null` with none open. */
2243
+ get location() {
2244
+ const root = session.root;
2245
+ return root ? browserRoots.has(root) ? "browser" : "device" : null;
2246
+ },
2247
+ /** Where new project folders can be made: `device` with the folder picker, and `browser` with the browser's folders. */
2248
+ locations,
2249
+ /**
2119
2250
  * The folder the loaded project came from, or `null` once another project loaded or the folder was
2120
2251
  * detached. A host can tell projects apart by it, for example to keep the layout of each one.
2121
2252
  */
@@ -8,3 +8,13 @@ export declare function showNotProjectFolderDialog({ document, locale }: {
8
8
  document: Document;
9
9
  locale?: string;
10
10
  }): Promise<void>;
11
+ /** The message of the dialog for a folder that is not empty. */
12
+ export declare const folderNotEmptyMessage: (locale?: string) => string;
13
+ /**
14
+ * Tells the user, in the same modal dialog, that the folder they chose for a new project is not empty. Resolves when
15
+ * the dialog closes.
16
+ */
17
+ export declare function showFolderNotEmptyDialog({ document, locale }: {
18
+ document: Document;
19
+ locale?: string;
20
+ }): Promise<void>;
@@ -30016,6 +30016,7 @@ max-height:40%;overflow:auto;border-radius:.3rem;background:var(--ui-primary,#ff
30016
30016
  box-sizing:border-box;max-width:calc(100% - 2rem);margin:0;padding:.65rem 1rem;border-radius:.35rem;
30017
30017
  background:#323232;color:#fff;font-size:.9em;box-shadow:0 2px 8px rgba(0,0,0,.3);pointer-events:none}
30018
30018
  .twpf-file-edit,.twpf-file-diff{flex:1;min-height:0}
30019
+ .twpf-file-edit.twpf-file-short{padding-top:var(--twpf-toolbar-height,3.25rem)}
30019
30020
  .twpf-file-diff{padding-top:var(--twpf-toolbar-height,3.25rem)}
30020
30021
  .twpf-file-edit>.cm-editor{height:100%}
30021
30022
  .twpf-text-file .cm-scroller{overflow:auto}
@@ -30292,8 +30293,10 @@ function mountTextFile(parent, options) {
30292
30293
  parent.append(shell);
30293
30294
  const toolbarObserver = browser && new browser.ResizeObserver(() => {
30294
30295
  panel.style.setProperty("--twpf-toolbar-height", `calc(${toolbar.getBoundingClientRect().height}px + 1rem)`);
30296
+ measureToolbarSpace();
30295
30297
  });
30296
30298
  toolbarObserver === null || toolbarObserver === void 0 || toolbarObserver.observe(toolbar);
30299
+ toolbarObserver === null || toolbarObserver === void 0 || toolbarObserver.observe(editPane);
30297
30300
  const editing = new Compartment();
30298
30301
  const view = new EditorView({
30299
30302
  parent: editPane,
@@ -30311,9 +30314,23 @@ function mountTextFile(parent, options) {
30311
30314
  keymap.of([...defaultKeymap, ...historyKeymap]),
30312
30315
  EditorView.updateListener.of((update) => {
30313
30316
  if (update.docChanged) updateSaveState(void 0, true);
30317
+ if (update.docChanged || update.geometryChanged) measureToolbarSpace();
30314
30318
  })
30315
30319
  ]
30316
30320
  });
30321
+ function measureToolbarSpace() {
30322
+ if (disposed || comparison) return;
30323
+ view.requestMeasure({
30324
+ key: editPane,
30325
+ read: (view) => {
30326
+ const available = editPane.clientHeight;
30327
+ return available ? view.contentHeight < available : null;
30328
+ },
30329
+ write: (short) => {
30330
+ if (!disposed && !comparison && short !== null) editPane.classList.toggle("twpf-file-short", short);
30331
+ }
30332
+ });
30333
+ }
30317
30334
  const dirty = () => !view.state.doc.eq(savedDoc);
30318
30335
  const serialize = () => bom + (newline === "\n" ? view.state.doc.toString() : view.state.doc.toString().replace(/\n/gu, newline));
30319
30336
  let wasDirty = false;
@@ -30491,6 +30508,7 @@ function mountTextFile(parent, options) {
30491
30508
  ++readVersion;
30492
30509
  baselineLoading = false;
30493
30510
  destroyDiff();
30511
+ measureToolbarSpace();
30494
30512
  }
30495
30513
  }
30496
30514
  async function loadBaseline() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-project-folder",
3
- "version": "0.18.0",
3
+ "version": "0.19.1",
4
4
  "description": "Read and save expanded Scratch project folders in TurboWarp Plus Editor",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
package/src/index.ts CHANGED
@@ -1,12 +1,12 @@
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 {notProjectFolderMessage, showNotProjectFolderDialog} from './not-project-dialog.js';
9
+ import {folderNotEmptyMessage, notProjectFolderMessage, showFolderNotEmptyDialog, showNotProjectFolderDialog} from './not-project-dialog.js';
10
10
  import type {Chosen, FolderHost, FolderVM, OpenResult, PickerWindow} from './session.js';
11
11
 
12
12
  export type {Comparison, ComparisonRequest, ComparisonSection, FolderHost, FolderScreenState, FolderVM, OpenResult} from './session.js';
@@ -109,6 +109,13 @@ export interface OpenDirectoryOptions {
109
109
  locale?: string;
110
110
  }
111
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';
112
119
  const abort = () => new DOMException('The user closed the dialog', 'AbortError');
113
120
 
114
121
  /**
@@ -130,7 +137,11 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
130
137
  return choice;
131
138
  };
132
139
  // 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});
140
+ const chooseBrowserFolder = async (): Promise<Chosen> => {
141
+ const {directory} = await chooseBrowser('open');
142
+ browserRoots.add(directory);
143
+ return {directory};
144
+ };
134
145
  const pickDirectory = devicePicker ?
135
146
  async (options: {id: string; mode: 'readwrite'}): Promise<Chosen> => ({directory: await devicePicker.call(view, options)}) :
136
147
  chooseBrowserFolder;
@@ -152,6 +163,32 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
152
163
  return result;
153
164
  });
154
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?';
155
192
  const session = createFolderSession(vm, host);
156
193
  const status = document.createElement('output');
157
194
  status.dataset.projectFolderStatus = '';
@@ -354,7 +391,7 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
354
391
  */
355
392
  openDirectory: (directory: FileSystemDirectoryHandle, confirmReplace: () => boolean,
356
393
  root?: FileSystemDirectoryHandle | null, options: OpenDirectoryOptions = {}): Promise<OpenResult> =>
357
- session.openDirectory(directory, confirmReplace, root ?? undefined).then(result => {
394
+ classify(root ?? directory).then(() => session.openDirectory(directory, confirmReplace, root ?? undefined)).then(result => {
358
395
  if (result === 'not-project' && options.notProjectDialog !== false) void notProject(options.locale ?? locale);
359
396
  return result;
360
397
  }).finally(renderReload),
@@ -365,10 +402,14 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
365
402
  /** The folders kept in this browser, when they are offered, for a host that lists or exports them. */
366
403
  browserProjects,
367
404
  /**
368
- * Creates a project folder from a snapshot. `title` names a folder made in the browser, where the user names a
369
- * 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.
370
411
  */
371
- createFromSnapshot({prepareFiles, collectEdits, directory, current = () => true, title, location}: {
412
+ createFromSnapshot({prepareFiles, collectEdits, directory, current = () => true, title, location, destination}: {
372
413
  prepareFiles: () => Promise<ReadonlyMap<string, Uint8Array>>;
373
414
  collectEdits?: () => Promise<void>;
374
415
  directory?: FileSystemDirectoryHandle;
@@ -376,16 +417,15 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
376
417
  title?: string;
377
418
  /** Explicit destination; omitted uses the device picker when available. */
378
419
  location?: ProjectFolderLocation;
379
- }) {
380
- const message = locale.startsWith('ja') ?
381
- '指定されたフォルダは空ではありません。フォルダに保存されている内容が上書きされる場合があります。よろしいですか?' :
382
- 'The selected folder is not empty. Contents in the folder may be overwritten. Continue?';
383
- return session.createFromSnapshot(async () => {
420
+ destination?: ProjectFolderDestination;
421
+ }): Promise<OpenResult> {
422
+ const create = (picked?: FileSystemDirectoryHandle) => session.createFromSnapshot(async () => {
384
423
  try {
385
- 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);
386
425
  if (!current()) return null;
426
+ await classify(selected);
387
427
  const overwrite = !await isProjectFolderEmpty(selected);
388
- if (!current() || (overwrite && !view.confirm(message))) return null;
428
+ if (!current() || (overwrite && !view.confirm(overwriteMessage()))) return null;
389
429
  await collectEdits?.();
390
430
  return current() ? {directory: selected, overwrite} : null;
391
431
  } catch (error) {
@@ -393,7 +433,90 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
393
433
  throw error;
394
434
  }
395
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;
396
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[],
397
520
  /**
398
521
  * The folder the loaded project came from, or `null` once another project loaded or the folder was
399
522
  * detached. A host can tell projects apart by it, for example to keep the layout of each one.
@@ -1,6 +1,8 @@
1
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'}
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'}
4
6
  };
5
7
 
6
8
  let dialogs = 0;
@@ -12,12 +14,28 @@ export const notProjectFolderMessage = (locale = 'en') => (locale.startsWith('ja
12
14
  * Tells the user, in a modal dialog, that the folder they tried to open is not a project folder. Resolves when the
13
15
  * dialog closes, after the focus went back to where it was.
14
16
  */
15
- export async function showNotProjectFolderDialog({document, locale = 'en'}: {document: Document; locale?: string}): Promise<void> {
17
+ export function showNotProjectFolderDialog({document, locale = 'en'}: {document: Document; locale?: string}): Promise<void> {
16
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) {
17
35
  const returnFocus = document.activeElement as HTMLElement | null;
18
36
  const id = `tw-plus-project-folder-error-${++dialogs}`;
19
37
  const dialog = document.createElement('dialog');
20
- dialog.dataset.projectFolderError = 'not-project';
38
+ dialog.dataset.projectFolderError = kind;
21
39
  dialog.setAttribute('role', 'alertdialog');
22
40
  dialog.setAttribute('aria-labelledby', `${id}-title`);
23
41
  dialog.setAttribute('aria-describedby', `${id}-message`);
@@ -27,17 +45,17 @@ export async function showNotProjectFolderDialog({document, locale = 'en'}: {doc
27
45
  });
28
46
  const heading = document.createElement('h2');
29
47
  heading.id = `${id}-title`;
30
- heading.textContent = message.title;
48
+ heading.textContent = title;
31
49
  Object.assign(heading.style, {margin: '0 0 0.5rem', fontSize: '1rem'});
32
50
  const text = document.createElement('p');
33
51
  text.id = `${id}-message`;
34
- text.textContent = message.notProject;
52
+ text.textContent = body;
35
53
  Object.assign(text.style, {margin: '0 0 1rem'});
36
54
  const footer = document.createElement('div');
37
55
  Object.assign(footer.style, {display: 'flex', justifyContent: 'flex-end'});
38
56
  const ok = document.createElement('button');
39
57
  ok.type = 'button';
40
- ok.textContent = message.ok;
58
+ ok.textContent = okLabel;
41
59
  footer.append(ok);
42
60
  dialog.append(heading, text, footer);
43
61
  await new Promise<void>(resolve => {
@@ -95,6 +95,7 @@ max-height:40%;overflow:auto;border-radius:.3rem;background:var(--ui-primary,#ff
95
95
  box-sizing:border-box;max-width:calc(100% - 2rem);margin:0;padding:.65rem 1rem;border-radius:.35rem;
96
96
  background:#323232;color:#fff;font-size:.9em;box-shadow:0 2px 8px rgba(0,0,0,.3);pointer-events:none}
97
97
  .twpf-file-edit,.twpf-file-diff{flex:1;min-height:0}
98
+ .twpf-file-edit.twpf-file-short{padding-top:var(--twpf-toolbar-height,3.25rem)}
98
99
  .twpf-file-diff{padding-top:var(--twpf-toolbar-height,3.25rem)}
99
100
  .twpf-file-edit>.cm-editor{height:100%}
100
101
  .twpf-text-file .cm-scroller{overflow:auto}
@@ -328,8 +329,10 @@ export function mountTextFile(parent: HTMLElement, options: TextFileOptions) {
328
329
  parent.append(shell);
329
330
  const toolbarObserver = browser && new browser.ResizeObserver(() => {
330
331
  panel.style.setProperty('--twpf-toolbar-height', `calc(${toolbar.getBoundingClientRect().height}px + 1rem)`);
332
+ measureToolbarSpace();
331
333
  });
332
334
  toolbarObserver?.observe(toolbar);
335
+ toolbarObserver?.observe(editPane);
333
336
 
334
337
  const editing = new Compartment();
335
338
  const view = new EditorView({
@@ -339,9 +342,26 @@ export function mountTextFile(parent: HTMLElement, options: TextFileOptions) {
339
342
  highlightActiveLine(), textMinimap(message.minimap),
340
343
  EditorView.contentAttributes.of({'aria-label': options.path}),
341
344
  keymap.of([...defaultKeymap, ...historyKeymap]),
342
- EditorView.updateListener.of(update => {if (update.docChanged) updateSaveState(undefined, true);})
345
+ EditorView.updateListener.of(update => {
346
+ if (update.docChanged) updateSaveState(undefined, true);
347
+ if (update.docChanged || update.geometryChanged) measureToolbarSpace();
348
+ })
343
349
  ]
344
350
  });
351
+ function measureToolbarSpace() {
352
+ if (disposed || comparison) return;
353
+ view.requestMeasure({
354
+ key: editPane,
355
+ read: view => {
356
+ // Include the reserved space when comparing, so adding it cannot flip the decision back.
357
+ const available = editPane.clientHeight;
358
+ return available ? view.contentHeight < available : null;
359
+ },
360
+ write: short => {
361
+ if (!disposed && !comparison && short !== null) editPane.classList.toggle('twpf-file-short', short);
362
+ }
363
+ });
364
+ }
345
365
  const dirty = () => !view.state.doc.eq(savedDoc);
346
366
  const serialize = () => bom + (newline === '\n' ? view.state.doc.toString() : view.state.doc.toString().replace(/\n/gu, newline));
347
367
 
@@ -524,6 +544,7 @@ export function mountTextFile(parent: HTMLElement, options: TextFileOptions) {
524
544
  ++readVersion;
525
545
  baselineLoading = false;
526
546
  destroyDiff();
547
+ measureToolbarSpace();
527
548
  }
528
549
  }
529
550