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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { A as projectFile, C as isObject, D as planExtensionSave, E as parseProject, F as _asyncIterator, I as _objectWithoutProperties, L as _objectSpread2, M as readProjectFolder, N as sameBytes, O as projectAssets, P as unsupported, S as fileVersion, T as paletteFile, _ as collapsePalette, a as projectFolderOverwriteWarning, b as expandPalette, c as parseExplorerState, d as subscribeExplorerState, f as writeExplorerState, g as assetTypeFor, h as assetKey, i as isProjectFolderEmpty, j as readFolderUpdate, k as projectChanges, l as readExplorerState, m as assertFolderUnchanged, n as registerFolder, o as editorDirectory, p as FolderError, r as createProjectFolder, t as followProjectFolder, u as screenStateFile, v as encodePalette, w as manifestFile, x as extensionsFile, y as equal } from "./shared-h5VGx9Jp.js";
1
+ import { A as projectChanges, C as isObject, D as parseProject, E as paletteFile, F as unsupported, I as _asyncIterator, L as _objectWithoutProperties, M as readFolder, N as readFolderUpdate, O as planExtensionSave, P as sameBytes, R as _objectSpread2, S as fileVersion, T as manifestFile, _ as collapsePalette, a as projectFolderOverwriteWarning, b as expandPalette, c as parseExplorerState, d as subscribeExplorerState, f as writeExplorerState, g as assetTypeFor, h as assetKey, i as isProjectFolderEmpty, j as projectFile, k as projectAssets, l as readExplorerState, m as assertFolderUnchanged, n as registerFolder, o as editorDirectory, p as FolderError, r as createProjectFolder, t as followProjectFolder, u as screenStateFile, v as encodePalette, w as isProjectFolder, x as extensionsFile, y as equal } from "./shared-CLo1e5zK.js";
2
2
  // src/block-reload.ts
3
3
  var _excluded$3 = ["targets"];
4
4
  var _excluded2$1 = ["targets"];
@@ -513,7 +513,8 @@ function createFolderSession(vm, host) {
513
513
  vm.off("PROJECT_CHANGED", changed);
514
514
  unregisterTree === null || unregisterTree === void 0 || unregisterTree();
515
515
  };
516
- const openFrom = async (getDirectory, confirmReplace, prepare = (directory) => readProjectFolder(directory, vm.runtime.storage), stillCurrent = () => true) => {
516
+ const readProject = async (directory) => await isProjectFolder(directory) ? readFolder(directory, vm.runtime.storage) : "not-project";
517
+ const openFrom = async (getDirectory, confirmReplace, prepare = readProject, stillCurrent = () => true) => {
517
518
  if (disposed || busy) return "cancelled";
518
519
  busy = true;
519
520
  const priorStage = vm.runtime.getTargetForStage();
@@ -523,6 +524,7 @@ function createFolderSession(vm, host) {
523
524
  if (!chosen || disposed) return "cancelled";
524
525
  const storage = vm.runtime.storage;
525
526
  const source = await prepare(chosen.directory);
527
+ if (source === "not-project") return disposed ? "cancelled" : "not-project";
526
528
  if (!source || disposed || !stillCurrent() || vm.runtime.getTargetForStage() !== priorStage) return "cancelled";
527
529
  if (host.isProjectDirty() && !confirmReplace()) return "cancelled";
528
530
  host.beforeLoad();
@@ -705,7 +707,7 @@ function createFolderSession(vm, host) {
705
707
  var _current$source$direc;
706
708
  return (_current$source$direc = current === null || current === void 0 ? void 0 : current.source.directory) !== null && _current$source$direc !== void 0 ? _current$source$direc : null;
707
709
  },
708
- /** The folder the user chose: `directory` itself, or the repository whose `project` folder it is. */
710
+ /** The folder the user chose: `directory` itself, unless a host gave another one to `openDirectory`. */
709
711
  get root() {
710
712
  var _current$root;
711
713
  return (_current$root = current === null || current === void 0 ? void 0 : current.root) !== null && _current$root !== void 0 ? _current$root : null;
@@ -810,9 +812,12 @@ function createFolderSession(vm, host) {
810
812
  return openFrom(() => Promise.resolve(current === session ? {
811
813
  directory: session.source.directory,
812
814
  root: session.root
813
- } : null), confirmReplace);
815
+ } : null), confirmReplace, (directory) => readFolder(directory, vm.runtime.storage));
814
816
  },
815
- /** `pick` gives the folder to open and, when it differs, the folder the user chose as `root`. */
817
+ /**
818
+ * `pick` gives the folder to open and, when a host located the project in another folder the user chose, that
819
+ * folder as `root`. Resolves with `not-project` when the folder is not a project folder.
820
+ */
816
821
  open(pick, confirmReplace) {
817
822
  return openFrom(async () => {
818
823
  try {
@@ -827,8 +832,9 @@ function createFolderSession(vm, host) {
827
832
  }, confirmReplace);
828
833
  },
829
834
  /**
830
- * Opens `directory`, or its `project` folder when it has no project of its own. `root` is the folder the user
831
- * chose, for a host that located the project itself; it defaults to `directory`.
835
+ * Opens the project at the root of `directory`, or resolves with `not-project` and changes nothing when the
836
+ * folder is not a project folder. `root` is the folder the user chose, for a host that located the project in
837
+ * it; it defaults to `directory`.
832
838
  */
833
839
  openDirectory(directory, confirmReplace, root) {
834
840
  return openFrom(() => Promise.resolve({
@@ -1315,7 +1321,7 @@ async function zipDirectory(directory, { exclude = () => false } = {}) {
1315
1321
  ], { type: "application/zip" });
1316
1322
  }
1317
1323
  // src/browser-project-dialog.ts
1318
- var messages$1 = {
1324
+ var messages$2 = {
1319
1325
  en: {
1320
1326
  openTitle: "Project Folders in This Browser",
1321
1327
  createTitle: "New Project Folder in This Browser",
@@ -1390,11 +1396,11 @@ async function exportBrowserProject(document, projects, project) {
1390
1396
  }
1391
1397
  /**
1392
1398
  * Shows the project folders kept in this browser. With `purpose: 'open'` the user picks one; with `'create'` the user
1393
- * names a new empty one. Resolves with the chosen folder, or `null` when the dialog closes without one.
1399
+ * names a new empty one. Resolves with the chosen stored folder, or `null` when the dialog closes without one.
1394
1400
  */
1395
1401
  function chooseBrowserProject({ document, projects, locale = "en", purpose, title = "" }) {
1396
1402
  var _ref, _ref2, _dialog$querySelector;
1397
- const message = locale.startsWith("ja") ? messages$1.ja : messages$1.en;
1403
+ const message = locale.startsWith("ja") ? messages$2.ja : messages$2.en;
1398
1404
  const view = document.defaultView;
1399
1405
  const dialog = document.createElement("dialog");
1400
1406
  dialog.dataset.browserProjects = purpose;
@@ -1607,7 +1613,7 @@ function chooseBrowserProject({ document, projects, locale = "en", purpose, titl
1607
1613
  return element;
1608
1614
  };
1609
1615
  item.append(text, button(message.open, async () => {
1610
- const directory = await projects.directory(project.id);
1616
+ const directory = await projects.root(project.id);
1611
1617
  if (!directory) return render();
1612
1618
  finish({
1613
1619
  project,
@@ -1640,6 +1646,105 @@ function chooseBrowserProject({ document, projects, locale = "en", purpose, titl
1640
1646
  (_ref = (_ref2 = (_dialog$querySelector = dialog.querySelector("input")) !== null && _dialog$querySelector !== void 0 ? _dialog$querySelector : dialog.querySelector("[data-browser-projects-list] button")) !== null && _ref2 !== void 0 ? _ref2 : close) === null || _ref === void 0 || _ref.focus();
1641
1647
  return result;
1642
1648
  }
1649
+ // src/not-project-dialog.ts
1650
+ var messages$1 = {
1651
+ en: {
1652
+ title: "Cannot Open Folder",
1653
+ notProject: "This folder is not a project folder.",
1654
+ notEmptyTitle: "Cannot Use This Folder",
1655
+ notEmpty: "Choose an empty folder.",
1656
+ ok: "OK"
1657
+ },
1658
+ ja: {
1659
+ title: "フォルダを開けません",
1660
+ notProject: "このフォルダはプロジェクトフォルダではありません。",
1661
+ notEmptyTitle: "このフォルダは使えません",
1662
+ notEmpty: "空のフォルダを選んでください。",
1663
+ ok: "OK"
1664
+ }
1665
+ };
1666
+ var dialogs = 0;
1667
+ /** The message the dialog shows, for a host that tells the user in its own way. */
1668
+ var notProjectFolderMessage = (locale = "en") => (locale.startsWith("ja") ? messages$1.ja : messages$1.en).notProject;
1669
+ /**
1670
+ * Tells the user, in a modal dialog, that the folder they tried to open is not a project folder. Resolves when the
1671
+ * dialog closes, after the focus went back to where it was.
1672
+ */
1673
+ function showNotProjectFolderDialog({ document, locale = "en" }) {
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) {
1688
+ const returnFocus = document.activeElement;
1689
+ const id = `tw-plus-project-folder-error-${++dialogs}`;
1690
+ const dialog = document.createElement("dialog");
1691
+ dialog.dataset.projectFolderError = kind;
1692
+ dialog.setAttribute("role", "alertdialog");
1693
+ dialog.setAttribute("aria-labelledby", `${id}-title`);
1694
+ dialog.setAttribute("aria-describedby", `${id}-message`);
1695
+ Object.assign(dialog.style, {
1696
+ width: "min(26rem, calc(100vw - 2rem))",
1697
+ padding: "1rem 1.25rem",
1698
+ background: "Canvas",
1699
+ color: "CanvasText",
1700
+ border: "1px solid GrayText",
1701
+ borderRadius: "0.5rem",
1702
+ fontFamily: "inherit",
1703
+ fontSize: "0.875rem",
1704
+ boxSizing: "border-box"
1705
+ });
1706
+ const heading = document.createElement("h2");
1707
+ heading.id = `${id}-title`;
1708
+ heading.textContent = title;
1709
+ Object.assign(heading.style, {
1710
+ margin: "0 0 0.5rem",
1711
+ fontSize: "1rem"
1712
+ });
1713
+ const text = document.createElement("p");
1714
+ text.id = `${id}-message`;
1715
+ text.textContent = body;
1716
+ Object.assign(text.style, { margin: "0 0 1rem" });
1717
+ const footer = document.createElement("div");
1718
+ Object.assign(footer.style, {
1719
+ display: "flex",
1720
+ justifyContent: "flex-end"
1721
+ });
1722
+ const ok = document.createElement("button");
1723
+ ok.type = "button";
1724
+ ok.textContent = okLabel;
1725
+ footer.append(ok);
1726
+ dialog.append(heading, text, footer);
1727
+ await new Promise((resolve) => {
1728
+ let settled = false;
1729
+ const finish = () => {
1730
+ if (settled) return;
1731
+ settled = true;
1732
+ if (dialog.open) dialog.close();
1733
+ dialog.remove();
1734
+ if ((returnFocus === null || returnFocus === void 0 ? void 0 : returnFocus.isConnected) && typeof returnFocus.focus === "function") returnFocus.focus();
1735
+ resolve();
1736
+ };
1737
+ ok.addEventListener("click", finish);
1738
+ dialog.addEventListener("cancel", (event) => {
1739
+ event.preventDefault();
1740
+ finish();
1741
+ });
1742
+ dialog.addEventListener("close", finish);
1743
+ document.body.append(dialog);
1744
+ dialog.showModal();
1745
+ ok.focus();
1746
+ });
1747
+ }
1643
1748
  // src/index.ts
1644
1749
  var messages = {
1645
1750
  en: {
@@ -1714,6 +1819,7 @@ var messages = {
1714
1819
  }
1715
1820
  };
1716
1821
  var menus = /* @__PURE__ */ new WeakMap();
1822
+ var folderPickerId = "turbowarp-plus-project-folder";
1717
1823
  var abort = () => new DOMException("The user closed the dialog", "AbortError");
1718
1824
  /**
1719
1825
  * `autoReload` (default true) applies value and position changes without a click when the Editor has no unsaved
@@ -1737,12 +1843,9 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1737
1843
  return choice;
1738
1844
  };
1739
1845
  const chooseBrowserFolder = async () => {
1740
- var _await$browserProject;
1741
- const { project, directory } = await chooseBrowser("open");
1742
- return {
1743
- directory,
1744
- root: (_await$browserProject = await browserProjects.root(project.id).catch(() => null)) !== null && _await$browserProject !== void 0 ? _await$browserProject : directory
1745
- };
1846
+ const { directory } = await chooseBrowser("open");
1847
+ browserRoots.add(directory);
1848
+ return { directory };
1746
1849
  };
1747
1850
  const pickDirectory = devicePicker ? async (options) => ({ directory: await devicePicker.call(view, options) }) : chooseBrowserFolder;
1748
1851
  const locations = [];
@@ -1762,6 +1865,28 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1762
1865
  return result;
1763
1866
  });
1764
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?";
1765
1890
  const session = createFolderSession(vm, host);
1766
1891
  const status = document.createElement("output");
1767
1892
  status.dataset.projectFolderStatus = "";
@@ -1796,6 +1921,10 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1796
1921
  const detail = error instanceof FolderError && error.message !== error.code ? ` (${error.message})` : "";
1797
1922
  report((error instanceof FolderError ? message[error.code] : message.failed) + detail);
1798
1923
  };
1924
+ const notProject = (locale) => showNotProjectFolderDialog({
1925
+ document,
1926
+ locale
1927
+ }).catch(() => report(notProjectFolderMessage(locale)));
1799
1928
  let stopWatching;
1800
1929
  let renderReload = () => {};
1801
1930
  if (host.blockReload) {
@@ -1937,21 +2066,21 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1937
2066
  notice.remove();
1938
2067
  };
1939
2068
  }
2069
+ const opened = (locale, result) => {
2070
+ if (result === "opened") report(messageFor(locale).opened);
2071
+ else if (result === "not-project") notProject(locale);
2072
+ };
1940
2073
  const menu = {
1941
2074
  deviceFolders: typeof devicePicker === "function",
1942
2075
  session,
1943
2076
  open(locale) {
1944
2077
  const message = messageFor(locale);
1945
- session.open((options) => pickDirectory(options), () => view.confirm(message.replace)).then((result) => {
1946
- if (result === "opened") report(message.opened);
1947
- }, (error) => fail(locale, error)).finally(renderReload);
2078
+ session.open((options) => pickDirectory(options), () => view.confirm(message.replace)).then((result) => opened(locale, result), (error) => fail(locale, error)).finally(renderReload);
1948
2079
  renderReload();
1949
2080
  },
1950
2081
  openBrowser: browserProjects ? (locale) => {
1951
2082
  const message = messageFor(locale);
1952
- session.open(chooseBrowserFolder, () => view.confirm(message.replace)).then((result) => {
1953
- if (result === "opened") report(message.opened);
1954
- }, (error) => fail(locale, error)).finally(renderReload);
2083
+ session.open(chooseBrowserFolder, () => view.confirm(message.replace)).then((result) => opened(locale, result), (error) => fail(locale, error)).finally(renderReload);
1955
2084
  renderReload();
1956
2085
  } : void 0,
1957
2086
  save(locale) {
@@ -1987,7 +2116,17 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1987
2116
  mutate: (directory, operation) => session.mutate(directory, operation).finally(renderReload)
1988
2117
  });
1989
2118
  return {
1990
- openDirectory: (...args) => session.openDirectory(...args).finally(renderReload),
2119
+ /**
2120
+ * Opens the project at the root of `directory`, as the user's Open would, and resolves with the result. A folder
2121
+ * that is not a project folder changes nothing, shows the error dialog unless `options.notProjectDialog` is
2122
+ * false, and resolves with `not-project`. `root` is the folder the user chose, for a host that located the
2123
+ * project in it; it defaults to `directory`.
2124
+ */
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) => {
2126
+ var _options$locale;
2127
+ if (result === "not-project" && options.notProjectDialog !== false) notProject((_options$locale = options.locale) !== null && _options$locale !== void 0 ? _options$locale : locale);
2128
+ return result;
2129
+ }).finally(renderReload),
1991
2130
  unsavedPaths: () => session.unsavedPaths(),
1992
2131
  readUnsavedFile: (path) => session.readUnsavedFile(path),
1993
2132
  subscribeEdits: (listener) => session.subscribeEdits(listener),
@@ -1995,20 +2134,24 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1995
2134
  /** The folders kept in this browser, when they are offered, for a host that lists or exports them. */
1996
2135
  browserProjects,
1997
2136
  /**
1998
- * Creates a project folder from a snapshot. `title` names a folder made in the browser, where the user names a
1999
- * 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.
2000
2143
  */
2001
- createFromSnapshot({ prepareFiles, collectEdits, directory, current = () => true, title, location }) {
2002
- const message = locale.startsWith("ja") ? "指定されたフォルダは空ではありません。フォルダに保存されている内容が上書きされる場合があります。よろしいですか?" : "The selected folder is not empty. Contents in the folder may be overwritten. Continue?";
2003
- return session.createFromSnapshot(async () => {
2144
+ createFromSnapshot({ prepareFiles, collectEdits, directory, current = () => true, title, location, destination }) {
2145
+ const create = (picked) => session.createFromSnapshot(async () => {
2004
2146
  try {
2005
- const selected = directory !== null && directory !== void 0 ? directory : await pickNewDirectory({
2006
- id: "turbowarp-plus-project-folder",
2147
+ const selected = picked !== null && picked !== void 0 ? picked : await pickNewDirectory({
2148
+ id: folderPickerId,
2007
2149
  mode: "readwrite"
2008
2150
  }, title, location);
2009
2151
  if (!current()) return null;
2152
+ await classify(selected);
2010
2153
  const overwrite = !await isProjectFolderEmpty(selected);
2011
- if (!current() || overwrite && !view.confirm(message)) return null;
2154
+ if (!current() || overwrite && !view.confirm(overwriteMessage())) return null;
2012
2155
  await (collectEdits === null || collectEdits === void 0 ? void 0 : collectEdits());
2013
2156
  return current() ? {
2014
2157
  directory: selected,
@@ -2019,8 +2162,91 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
2019
2162
  throw error;
2020
2163
  }
2021
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);
2022
2167
  },
2023
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
+ /**
2024
2250
  * The folder the loaded project came from, or `null` once another project loaded or the folder was
2025
2251
  * detached. A host can tell projects apart by it, for example to keep the layout of each one.
2026
2252
  */
@@ -2028,8 +2254,8 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
2028
2254
  return session.directory;
2029
2255
  },
2030
2256
  /**
2031
- * The folder the user chose for the loaded project, or `null` like `directory`. It is `directory` itself, or
2032
- * the repository whose `project` folder holds the project, or the stored folder of a folder kept in the browser.
2257
+ * The folder the user chose for the loaded project, or `null` like `directory`. It is `directory` itself, the
2258
+ * project folder, unless the host gave another folder to `openDirectory`.
2033
2259
  */
2034
2260
  get root() {
2035
2261
  return session.root;
@@ -2091,4 +2317,4 @@ function renderProjectFolderMenu(createElement, { vm, locale = "en", MenuItem, M
2091
2317
  };
2092
2318
  return createElement(MenuSection, null, item("open"), entry.openBrowser ? item("openBrowser") : null, entry.session.canSave ? item("save") : null);
2093
2319
  }
2094
- export { chooseBrowserProject, createProjectFolder, exportBrowserProject, followProjectFolder, mountProjectFolder, openBrowserProjects, parseExplorerState, projectFolderActions, projectFolderOverwriteWarning, readExplorerState, renderProjectFolderMenu, subscribeExplorerState, writeExplorerState, zipDirectory, zipFileName };
2320
+ export { chooseBrowserProject, createProjectFolder, exportBrowserProject, followProjectFolder, mountProjectFolder, notProjectFolderMessage, openBrowserProjects, parseExplorerState, projectFolderActions, projectFolderOverwriteWarning, readExplorerState, renderProjectFolderMenu, showNotProjectFolderDialog, subscribeExplorerState, writeExplorerState, zipDirectory, zipFileName };
@@ -0,0 +1,20 @@
1
+ /** The message the dialog shows, for a host that tells the user in its own way. */
2
+ export declare const notProjectFolderMessage: (locale?: string) => string;
3
+ /**
4
+ * Tells the user, in a modal dialog, that the folder they tried to open is not a project folder. Resolves when the
5
+ * dialog closes, after the focus went back to where it was.
6
+ */
7
+ export declare function showNotProjectFolderDialog({ document, locale }: {
8
+ document: Document;
9
+ locale?: string;
10
+ }): Promise<void>;
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/dist/session.d.ts CHANGED
@@ -103,7 +103,12 @@ export type Chosen = {
103
103
  export type ReloadState = 'ready' | 'full' | 'waiting' | 'dirty' | 'running' | 'busy' | null;
104
104
  /** What the reload command does for the pending change, regardless of whether it may run now. */
105
105
  export type ReloadKind = 'partial' | 'full' | null;
106
- export type OpenResult = 'opened' | 'cancelled';
106
+ /**
107
+ * `opened`: the folder's project is loaded. `cancelled`: nothing was opened, as when the user closed the picker or kept
108
+ * unsaved edits. `not-project`: the folder's root lacks `project.source.json`, `sb3-source.json` or
109
+ * `embedded-extensions.json`, so it is not a project folder and nothing was opened either.
110
+ */
111
+ export type OpenResult = 'opened' | 'cancelled' | 'not-project';
107
112
  type SaveResult = {
108
113
  status: 'saved' | 'unchanged';
109
114
  sourceRemoved: string[];
@@ -128,7 +133,7 @@ export declare function createFolderSession(vm: FolderVM, host: FolderHost): {
128
133
  /** Identifies the pending project file version, so a host can attempt an automatic apply only once. */
129
134
  readonly pendingVersion: string | null;
130
135
  readonly directory: FileSystemDirectoryHandle | null;
131
- /** The folder the user chose: `directory` itself, or the repository whose `project` folder it is. */
136
+ /** The folder the user chose: `directory` itself, unless a host gave another one to `openDirectory`. */
132
137
  readonly root: FileSystemDirectoryHandle | null;
133
138
  mutate(directory: FileSystemDirectoryHandle, operation: (guard: () => void) => Promise<void>): Promise<void>;
134
139
  /**
@@ -143,14 +148,18 @@ export declare function createFolderSession(vm: FolderVM, host: FolderHost): {
143
148
  * edits are discarded only when `confirmReplace` agrees. The VM is left untouched while a project runs.
144
149
  */
145
150
  reloadAll(confirmReplace: () => boolean): Promise<OpenResult>;
146
- /** `pick` gives the folder to open and, when it differs, the folder the user chose as `root`. */
151
+ /**
152
+ * `pick` gives the folder to open and, when a host located the project in another folder the user chose, that
153
+ * folder as `root`. Resolves with `not-project` when the folder is not a project folder.
154
+ */
147
155
  open(pick: (options: {
148
156
  id: string;
149
157
  mode: "readwrite";
150
158
  }) => Promise<Chosen>, confirmReplace: () => boolean): Promise<OpenResult>;
151
159
  /**
152
- * Opens `directory`, or its `project` folder when it has no project of its own. `root` is the folder the user
153
- * chose, for a host that located the project itself; it defaults to `directory`.
160
+ * Opens the project at the root of `directory`, or resolves with `not-project` and changes nothing when the
161
+ * folder is not a project folder. `root` is the folder the user chose, for a host that located the project in
162
+ * it; it defaults to `directory`.
154
163
  */
155
164
  openDirectory(directory: FileSystemDirectoryHandle, confirmReplace: () => boolean, root?: FileSystemDirectoryHandle): Promise<OpenResult>;
156
165
  createFromSnapshot(selectDestination: () => Promise<{
@@ -404,6 +404,12 @@ var _excluded3 = ["targets"];
404
404
  var projectFile = "project.source.json";
405
405
  var manifestFile = "sb3-source.json";
406
406
  var extensionsFile = "embedded-extensions.json";
407
+ /** The files at the root of every project folder, the ones `readFolder` reads before anything else. */
408
+ var projectFolderFiles = [
409
+ projectFile,
410
+ manifestFile,
411
+ extensionsFile
412
+ ];
407
413
  /** The ZIP entry of the Editor's screen state, which sb3-toolchain lists in `archiveEntries`. */
408
414
  var screenStateEntry = "tw-plus/workspace.json";
409
415
  /** Block palette settings of source format 2. Format 1 folders have no such file. */
@@ -671,12 +677,7 @@ async function readFolder(directory, storage) {
671
677
  versions.set(prefix + name, fileVersion(file));
672
678
  return [name, await fileBytes(file)];
673
679
  };
674
- const filenames = [
675
- projectFile,
676
- manifestFile,
677
- extensionsFile
678
- ];
679
- const files = new Map(await Promise.all(filenames.map((name) => readEntry(directory, name))));
680
+ const files = new Map(await Promise.all(projectFolderFiles.map((name) => readEntry(directory, name))));
680
681
  const decoder = new TextDecoder("utf-8", { fatal: true });
681
682
  const projectText = decoder.decode(files.get(projectFile));
682
683
  const project = parseProject(projectText);
@@ -726,40 +727,20 @@ async function readFolder(directory, storage) {
726
727
  palette: paletteDocument
727
728
  };
728
729
  }
729
- /** The project folder inside a repository, as Project Starter makes it. */
730
- var projectSubfolder = "project";
731
730
  var missingEntry = (error) => error instanceof DOMException && ["NotFoundError", "TypeMismatchError"].includes(error.name);
732
- /** Whether `directory` has an entry called `name`, a file or a folder. */
733
- async function hasEntry(directory, name) {
734
- for (const get of [() => directory.getFileHandle(name), () => directory.getDirectoryHandle(name)]) try {
735
- await get();
736
- return true;
737
- } catch (error) {
738
- if (!missingEntry(error)) throw error;
739
- }
740
- return false;
741
- }
742
731
  /**
743
- * Reads the project in `directory`, or, when the folder has no project of its own, in its `project` folder, as in a
744
- * repository whose project sits in `project/`. That folder must not be a repository itself. The error is the one
745
- * for `directory` when neither holds a project.
732
+ * Whether `directory` is a project folder: its root has every file in `projectFolderFiles`. The files are not read, so a
733
+ * project folder may still be broken or unsupported, which `readFolder` reports. Other errors, such as a withdrawn
734
+ * permission, are thrown.
746
735
  */
747
- async function readProjectFolder(directory, storage) {
748
- try {
749
- return await readFolder(directory, storage);
736
+ async function isProjectFolder(directory) {
737
+ for (const name of projectFolderFiles) try {
738
+ await directory.getFileHandle(name);
750
739
  } catch (error) {
751
- const child = await (async () => {
752
- if (await hasEntry(directory, "project.source.json") || await hasEntry(directory, "sb3-source.json")) return null;
753
- const found = await directory.getDirectoryHandle(projectSubfolder);
754
- return await hasEntry(found, ".git") ? null : found;
755
- })().catch(() => null);
756
- if (!child) throw error;
757
- try {
758
- return await readFolder(child, storage);
759
- } catch (_unused2) {
760
- throw error;
761
- }
740
+ if (missingEntry(error)) return false;
741
+ throw error;
762
742
  }
743
+ return true;
763
744
  }
764
745
  var sameBytes = (a, b) => a.length === b.length && a.every((value, index) => value === b[index]);
765
746
  async function readFolderUpdate(source, previous) {
@@ -1172,7 +1153,7 @@ function registerFolder(vm, folder) {
1172
1153
  }
1173
1154
  /**
1174
1155
  * Calls `listener` with the project folder mounted for `vm`, the directory open in it and the folder the user chose for
1175
- * it (`root`, the directory itself or the repository that holds it in `project/`), now and whenever a folder is
1156
+ * it (`root`, the directory itself unless a host gave another one), now and whenever a folder is
1176
1157
  * mounted, opened, closed or saved. `directory` and `root` are `null` while no folder is open. Returns the function
1177
1158
  * that stops it.
1178
1159
  */
@@ -1199,4 +1180,4 @@ function followProjectFolder(vm, listener) {
1199
1180
  unsubscribe();
1200
1181
  };
1201
1182
  }
1202
- export { projectFile as A, isObject as C, planExtensionSave as D, parseProject as E, _asyncIterator as F, _objectWithoutProperties as I, _objectSpread2 as L, readProjectFolder as M, sameBytes as N, projectAssets as O, unsupported as P, fileVersion as S, paletteFile as T, collapsePalette as _, projectFolderOverwriteWarning as a, expandPalette as b, parseExplorerState as c, subscribeExplorerState as d, writeExplorerState as f, assetTypeFor as g, assetKey as h, isProjectFolderEmpty as i, readFolderUpdate as j, projectChanges as k, readExplorerState as l, assertFolderUnchanged as m, registerFolder as n, editorDirectory as o, FolderError as p, createProjectFolder as r, hiddenEntry as s, followProjectFolder as t, screenStateFile as u, encodePalette as v, manifestFile as w, extensionsFile as x, equal as y };
1183
+ export { projectChanges as A, isObject as C, parseProject as D, paletteFile as E, unsupported as F, _asyncIterator as I, _objectWithoutProperties as L, readFolder as M, readFolderUpdate as N, planExtensionSave as O, sameBytes as P, _objectSpread2 as R, fileVersion as S, manifestFile as T, collapsePalette as _, projectFolderOverwriteWarning as a, expandPalette as b, parseExplorerState as c, subscribeExplorerState as d, writeExplorerState as f, assetTypeFor as g, assetKey as h, isProjectFolderEmpty as i, projectFile as j, projectAssets as k, readExplorerState as l, assertFolderUnchanged as m, registerFolder as n, editorDirectory as o, FolderError as p, createProjectFolder as r, hiddenEntry as s, followProjectFolder as t, screenStateFile as u, encodePalette as v, isProjectFolder as w, extensionsFile as x, equal as y };
@@ -1,4 +1,4 @@
1
- import { L as _objectSpread2 } from "./shared-h5VGx9Jp.js";
1
+ import { R as _objectSpread2 } from "./shared-CLo1e5zK.js";
2
2
  // node_modules/@marijn/find-cluster-break/src/index.js
3
3
  var rangeFrom = [];
4
4
  var rangeTo = [];
package/dist/source.d.ts CHANGED
@@ -15,6 +15,8 @@ type Target = JsonObject & {
15
15
  export declare const projectFile = "project.source.json";
16
16
  export declare const manifestFile = "sb3-source.json";
17
17
  export declare const extensionsFile = "embedded-extensions.json";
18
+ /** The files at the root of every project folder, the ones `readFolder` reads before anything else. */
19
+ export declare const projectFolderFiles: readonly ["project.source.json", "sb3-source.json", "embedded-extensions.json"];
18
20
  /** Block palette settings of source format 2. Format 1 folders have no such file. */
19
21
  export declare const paletteFile = "block-palette.json";
20
22
  export declare class FolderError extends Error {
@@ -100,14 +102,12 @@ export declare function planExtensionSave(source: FolderSource, project: Project
100
102
  removed: string[];
101
103
  };
102
104
  export declare function readFolder(directory: FileSystemDirectoryHandle, storage: Storage): Promise<FolderSource>;
103
- /** The project folder inside a repository, as Project Starter makes it. */
104
- export declare const projectSubfolder = "project";
105
105
  /**
106
- * Reads the project in `directory`, or, when the folder has no project of its own, in its `project` folder, as in a
107
- * repository whose project sits in `project/`. That folder must not be a repository itself. The error is the one
108
- * for `directory` when neither holds a project.
106
+ * Whether `directory` is a project folder: its root has every file in `projectFolderFiles`. The files are not read, so a
107
+ * project folder may still be broken or unsupported, which `readFolder` reports. Other errors, such as a withdrawn
108
+ * permission, are thrown.
109
109
  */
110
- export declare function readProjectFolder(directory: FileSystemDirectoryHandle, storage: Storage): Promise<FolderSource>;
110
+ export declare function isProjectFolder(directory: FileSystemDirectoryHandle): Promise<boolean>;
111
111
  export declare const sameBytes: (a: Uint8Array, b: Uint8Array) => boolean;
112
112
  export type FolderUpdate = {
113
113
  version: string;