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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 リポジトリには一つの作品を、そのルートに置きます。
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/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>;
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.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",
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 => {