@kubohiroya/turbowarp-plus-editor-project-folder 0.15.1 → 0.17.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 readFolderUpdate, 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 readFolder, 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-cwwWtggC.js";
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";
2
2
  // src/block-reload.ts
3
3
  var _excluded$3 = ["targets"];
4
4
  var _excluded2$1 = ["targets"];
@@ -513,16 +513,16 @@ 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) => readFolder(directory, vm.runtime.storage), stillCurrent = () => true) => {
516
+ const openFrom = async (getDirectory, confirmReplace, prepare = (directory) => readProjectFolder(directory, vm.runtime.storage), stillCurrent = () => true) => {
517
517
  if (disposed || busy) return "cancelled";
518
518
  busy = true;
519
519
  const priorStage = vm.runtime.getTargetForStage();
520
520
  try {
521
- var _vm$renderer;
522
- const directory = await getDirectory();
523
- if (!directory || disposed) return "cancelled";
521
+ var _chosen$root, _vm$renderer;
522
+ const chosen = await getDirectory();
523
+ if (!chosen || disposed) return "cancelled";
524
524
  const storage = vm.runtime.storage;
525
- const source = await prepare(directory);
525
+ const source = await prepare(chosen.directory);
526
526
  if (!source || disposed || !stillCurrent() || vm.runtime.getTargetForStage() !== priorStage) return "cancelled";
527
527
  if (host.isProjectDirty() && !confirmReplace()) return "cancelled";
528
528
  host.beforeLoad();
@@ -531,6 +531,7 @@ function createFolderSession(vm, host) {
531
531
  const assets = source.storageAssets;
532
532
  reader.assets = assets;
533
533
  let stage;
534
+ const directory = source.directory;
534
535
  pendingTree = void 0;
535
536
  expectingTree = true;
536
537
  try {
@@ -542,10 +543,11 @@ function createFolderSession(vm, host) {
542
543
  if (reader.assets === assets) reader.assets = null;
543
544
  }
544
545
  if (disposed || !stage || vm.runtime.getTargetForStage() !== stage) return "cancelled";
545
- host.onOpened(directory.name);
546
+ host.onOpened(chosen.directory.name);
546
547
  const baseline = snapshot();
547
548
  setCurrent({
548
549
  source,
550
+ root: (_chosen$root = chosen.root) !== null && _chosen$root !== void 0 ? _chosen$root : chosen.directory,
549
551
  stage,
550
552
  baseline,
551
553
  ids: identify(baseline),
@@ -703,6 +705,11 @@ function createFolderSession(vm, host) {
703
705
  var _current$source$direc;
704
706
  return (_current$source$direc = current === null || current === void 0 ? void 0 : current.source.directory) !== null && _current$source$direc !== void 0 ? _current$source$direc : null;
705
707
  },
708
+ /** The folder the user chose: `directory` itself, or the repository whose `project` folder it is. */
709
+ get root() {
710
+ var _current$root;
711
+ return (_current$root = current === null || current === void 0 ? void 0 : current.root) !== null && _current$root !== void 0 ? _current$root : null;
712
+ },
706
713
  async mutate(directory, operation) {
707
714
  const session = current;
708
715
  if (!session || busy || session.source.directory !== directory) throw new FolderError("conflict");
@@ -800,8 +807,12 @@ function createFolderSession(vm, host) {
800
807
  var _host$blockReload4;
801
808
  const session = current;
802
809
  if (!session || !session.pending || session.pending === "waiting" || ((_host$blockReload4 = host.blockReload) === null || _host$blockReload4 === void 0 ? void 0 : _host$blockReload4.isRunning())) return Promise.resolve("cancelled");
803
- return openFrom(() => Promise.resolve(current === session ? session.source.directory : null), confirmReplace);
810
+ return openFrom(() => Promise.resolve(current === session ? {
811
+ directory: session.source.directory,
812
+ root: session.root
813
+ } : null), confirmReplace);
804
814
  },
815
+ /** `pick` gives the folder to open and, when it differs, the folder the user chose as `root`. */
805
816
  open(pick, confirmReplace) {
806
817
  return openFrom(async () => {
807
818
  try {
@@ -815,8 +826,15 @@ function createFolderSession(vm, host) {
815
826
  }
816
827
  }, confirmReplace);
817
828
  },
818
- openDirectory(directory, confirmReplace) {
819
- return openFrom(() => Promise.resolve(directory), confirmReplace);
829
+ /**
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`.
832
+ */
833
+ openDirectory(directory, confirmReplace, root) {
834
+ return openFrom(() => Promise.resolve({
835
+ directory,
836
+ root
837
+ }), confirmReplace);
820
838
  },
821
839
  createFromSnapshot(selectDestination, prepareFiles, isCurrent) {
822
840
  const stage = vm.runtime.getTargetForStage();
@@ -824,10 +842,10 @@ function createFolderSession(vm, host) {
824
842
  const currentProject = () => !disposed && vm.runtime.getTargetForStage() === stage && (savedRevision === void 0 || revision === savedRevision) && isCurrent();
825
843
  let overwrite = false;
826
844
  return openFrom(async () => {
827
- var _destination$overwrit, _destination$director;
845
+ var _destination$overwrit;
828
846
  const destination = await selectDestination();
829
847
  overwrite = (_destination$overwrit = destination === null || destination === void 0 ? void 0 : destination.overwrite) !== null && _destination$overwrit !== void 0 ? _destination$overwrit : false;
830
- return (_destination$director = destination === null || destination === void 0 ? void 0 : destination.directory) !== null && _destination$director !== void 0 ? _destination$director : null;
848
+ return destination ? { directory: destination.directory } : null;
831
849
  }, currentProject, async (directory) => {
832
850
  if (!currentProject()) return null;
833
851
  savedRevision = revision;
@@ -1625,9 +1643,10 @@ function chooseBrowserProject({ document, projects, locale = "en", purpose, titl
1625
1643
  // src/index.ts
1626
1644
  var messages = {
1627
1645
  en: {
1628
- open: "Open Project Folder…",
1646
+ open: "Open Folder…",
1629
1647
  save: "Save to Project Folder",
1630
- openBrowser: "Open Project Folder in This Browser…",
1648
+ openBrowser: "Open Folder Saved in This Browser…",
1649
+ deviceUnavailable: "This browser cannot open folders on your device. Use Chrome or Edge, or open a folder saved in this browser.",
1631
1650
  replace: "Replace the open project and discard its unsaved changes?",
1632
1651
  opened: "Project folder opened.",
1633
1652
  saved: "Project folder saved.",
@@ -1659,9 +1678,10 @@ var messages = {
1659
1678
  full: "These changes need the whole project to be reloaded."
1660
1679
  },
1661
1680
  ja: {
1662
- open: "プロジェクトフォルダを開く…",
1681
+ open: "フォルダを開く…",
1663
1682
  save: "プロジェクトフォルダに保存",
1664
- openBrowser: "ブラウザー内のプロジェクトフォルダを開く…",
1683
+ openBrowser: "ブラウザーに保存したフォルダを開く…",
1684
+ deviceUnavailable: "このブラウザーでは端末のフォルダを開けません。Chrome か Edge を使うか、ブラウザーに保存したフォルダを開いてください。",
1665
1685
  replace: "未保存の変更を破棄して、別の作品を開きますか?",
1666
1686
  opened: "プロジェクトフォルダを開きました。",
1667
1687
  saved: "プロジェクトフォルダに保存しました。",
@@ -1714,10 +1734,24 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1714
1734
  title
1715
1735
  });
1716
1736
  if (!choice) throw abort();
1717
- return choice.directory;
1737
+ return choice;
1738
+ };
1739
+ const chooseBrowserFolder = async () => {
1740
+ var _await$browserProject;
1741
+ const { project, directory } = await chooseBrowser("open");
1742
+ return {
1743
+ directory,
1744
+ root: (_await$browserProject = await browserProjects.root(project.id).catch(() => null)) !== null && _await$browserProject !== void 0 ? _await$browserProject : directory
1745
+ };
1746
+ };
1747
+ const pickDirectory = devicePicker ? async (options) => ({ directory: await devicePicker.call(view, options) }) : chooseBrowserFolder;
1748
+ const locations = [];
1749
+ if (devicePicker) locations.push("device");
1750
+ if (browserProjects) locations.push("browser");
1751
+ const pickNewDirectory = async (options, title, location = devicePicker ? "device" : "browser") => {
1752
+ if (!locations.includes(location)) throw new FolderError("unsupported");
1753
+ return location === "device" ? devicePicker.call(view, options) : (await chooseBrowser("create", title)).directory;
1718
1754
  };
1719
- const pickDirectory = devicePicker ? (options) => devicePicker.call(view, options) : () => chooseBrowser("open");
1720
- const pickNewDirectory = (options, title) => devicePicker ? devicePicker.call(view, options) : chooseBrowser("create", title);
1721
1755
  /** Runs `run` with the browser folder of `directory` locked against other tabs, and marks it as updated. */
1722
1756
  const withBrowserProject = async (directory, run) => {
1723
1757
  const project = directory && browserProjects ? await browserProjects.find(directory).catch(() => null) : null;
@@ -1904,6 +1938,7 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1904
1938
  };
1905
1939
  }
1906
1940
  const menu = {
1941
+ deviceFolders: typeof devicePicker === "function",
1907
1942
  session,
1908
1943
  open(locale) {
1909
1944
  const message = messageFor(locale);
@@ -1912,9 +1947,9 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1912
1947
  }, (error) => fail(locale, error)).finally(renderReload);
1913
1948
  renderReload();
1914
1949
  },
1915
- openBrowser: devicePicker && browserProjects ? (locale) => {
1950
+ openBrowser: browserProjects ? (locale) => {
1916
1951
  const message = messageFor(locale);
1917
- session.open(() => chooseBrowser("open"), () => view.confirm(message.replace)).then((result) => {
1952
+ session.open(chooseBrowserFolder, () => view.confirm(message.replace)).then((result) => {
1918
1953
  if (result === "opened") report(message.opened);
1919
1954
  }, (error) => fail(locale, error)).finally(renderReload);
1920
1955
  renderReload();
@@ -1941,6 +1976,10 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1941
1976
  get directory() {
1942
1977
  return session.directory;
1943
1978
  },
1979
+ get root() {
1980
+ return session.root;
1981
+ },
1982
+ locations,
1944
1983
  subscribe: (listener) => session.subscribe(listener),
1945
1984
  subscribeEdits: (listener) => session.subscribeEdits(listener),
1946
1985
  unsavedPaths: () => session.unsavedPaths(),
@@ -1959,14 +1998,14 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1959
1998
  * Creates a project folder from a snapshot. `title` names a folder made in the browser, where the user names a
1960
1999
  * new folder instead of picking one on the device.
1961
2000
  */
1962
- createFromSnapshot({ prepareFiles, collectEdits, directory, current = () => true, title }) {
2001
+ createFromSnapshot({ prepareFiles, collectEdits, directory, current = () => true, title, location }) {
1963
2002
  const message = locale.startsWith("ja") ? "指定されたフォルダは空ではありません。フォルダに保存されている内容が上書きされる場合があります。よろしいですか?" : "The selected folder is not empty. Contents in the folder may be overwritten. Continue?";
1964
2003
  return session.createFromSnapshot(async () => {
1965
2004
  try {
1966
2005
  const selected = directory !== null && directory !== void 0 ? directory : await pickNewDirectory({
1967
2006
  id: "turbowarp-plus-project-folder",
1968
2007
  mode: "readwrite"
1969
- }, title);
2008
+ }, title, location);
1970
2009
  if (!current()) return null;
1971
2010
  const overwrite = !await isProjectFolderEmpty(selected);
1972
2011
  if (!current() || overwrite && !view.confirm(message)) return null;
@@ -1988,6 +2027,13 @@ function mountProjectFolder({ vm, document, host, locale = "en", autoReload = tr
1988
2027
  get directory() {
1989
2028
  return session.directory;
1990
2029
  },
2030
+ /**
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.
2033
+ */
2034
+ get root() {
2035
+ return session.root;
2036
+ },
1991
2037
  dispose() {
1992
2038
  menus.delete(vm);
1993
2039
  unregister();
@@ -2004,6 +2050,8 @@ function projectFolderActions(vm, locale = "en") {
2004
2050
  return {
2005
2051
  open: () => entry.open(locale),
2006
2052
  openBrowser: entry.openBrowser ? () => entry.openBrowser(locale) : void 0,
2053
+ /** Whether Open can pick a folder on the device. Safari and Firefox cannot, so hosts show Open as unavailable. */
2054
+ deviceFolders: entry.deviceFolders,
2007
2055
  save: entry.session.canSave ? () => entry.save(locale) : void 0,
2008
2056
  detach: () => entry.session.detach()
2009
2057
  };
@@ -2013,6 +2061,16 @@ function renderProjectFolderMenu(createElement, { vm, locale = "en", MenuItem, M
2013
2061
  if (!entry) return null;
2014
2062
  const labels = locale.startsWith("ja") ? messages.ja : messages.en;
2015
2063
  const item = (action) => {
2064
+ if (action === "open" && !entry.deviceFolders) return createElement(MenuItem, { command: `project-folder-${action}` }, createElement("span", {
2065
+ role: "button",
2066
+ tabIndex: -1,
2067
+ "aria-disabled": true,
2068
+ title: labels.deviceUnavailable,
2069
+ style: {
2070
+ opacity: .5,
2071
+ cursor: "default"
2072
+ }
2073
+ }, labels[action]));
2016
2074
  const run = () => {
2017
2075
  onRequestClose();
2018
2076
  entry[action](locale);
package/dist/session.d.ts CHANGED
@@ -91,6 +91,11 @@ export type Comparison = {
91
91
  editor: string | null;
92
92
  disk: string | null;
93
93
  };
94
+ /** The folder to open, and the folder the user chose for it, which defaults to `directory`. */
95
+ export type Chosen = {
96
+ directory: FileSystemDirectoryHandle;
97
+ root?: FileSystemDirectoryHandle;
98
+ };
94
99
  /**
95
100
  * `ready`: the change can be applied in place: values and positions, or with `deserializeBlocks`, whole scripts. `full`: the change needs the whole project reloaded.
96
101
  * `waiting`: an external write looks incomplete and is checked again. `dirty`, `running` and `busy` hold the change.
@@ -123,6 +128,8 @@ export declare function createFolderSession(vm: FolderVM, host: FolderHost): {
123
128
  /** Identifies the pending project file version, so a host can attempt an automatic apply only once. */
124
129
  readonly pendingVersion: string | null;
125
130
  readonly directory: FileSystemDirectoryHandle | null;
131
+ /** The folder the user chose: `directory` itself, or the repository whose `project` folder it is. */
132
+ readonly root: FileSystemDirectoryHandle | null;
126
133
  mutate(directory: FileSystemDirectoryHandle, operation: (guard: () => void) => Promise<void>): Promise<void>;
127
134
  /**
128
135
  * Reads what to compare before unsaved edits are replaced. `editor` is `null` when the edits cannot be
@@ -136,8 +143,16 @@ export declare function createFolderSession(vm: FolderVM, host: FolderHost): {
136
143
  * edits are discarded only when `confirmReplace` agrees. The VM is left untouched while a project runs.
137
144
  */
138
145
  reloadAll(confirmReplace: () => boolean): Promise<OpenResult>;
139
- open(pick: FileSystemPicker, confirmReplace: () => boolean): Promise<OpenResult>;
140
- openDirectory(directory: FileSystemDirectoryHandle, confirmReplace: () => boolean): Promise<OpenResult>;
146
+ /** `pick` gives the folder to open and, when it differs, the folder the user chose as `root`. */
147
+ open(pick: (options: {
148
+ id: string;
149
+ mode: "readwrite";
150
+ }) => Promise<Chosen>, confirmReplace: () => boolean): Promise<OpenResult>;
151
+ /**
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`.
154
+ */
155
+ openDirectory(directory: FileSystemDirectoryHandle, confirmReplace: () => boolean, root?: FileSystemDirectoryHandle): Promise<OpenResult>;
141
156
  createFromSnapshot(selectDestination: () => Promise<{
142
157
  directory: FileSystemDirectoryHandle;
143
158
  overwrite: boolean;
@@ -1,4 +1,4 @@
1
- import { L as _objectSpread2 } from "./shared-cwwWtggC.js";
1
+ import { L as _objectSpread2 } from "./shared-h5VGx9Jp.js";
2
2
  // node_modules/@marijn/find-cluster-break/src/index.js
3
3
  var rangeFrom = [];
4
4
  var rangeTo = [];
@@ -726,6 +726,41 @@ async function readFolder(directory, storage) {
726
726
  palette: paletteDocument
727
727
  };
728
728
  }
729
+ /** The project folder inside a repository, as Project Starter makes it. */
730
+ var projectSubfolder = "project";
731
+ 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
+ /**
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.
746
+ */
747
+ async function readProjectFolder(directory, storage) {
748
+ try {
749
+ return await readFolder(directory, storage);
750
+ } 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
+ }
762
+ }
763
+ }
729
764
  var sameBytes = (a, b) => a.length === b.length && a.every((value, index) => value === b[index]);
730
765
  async function readFolderUpdate(source, previous) {
731
766
  const { directory, versions } = source;
@@ -1136,21 +1171,26 @@ function registerFolder(vm, folder) {
1136
1171
  };
1137
1172
  }
1138
1173
  /**
1139
- * Calls `listener` with the project folder mounted for `vm` and the directory open in it, now and whenever a folder is
1140
- * mounted, opened, closed or saved. Returns the function that stops it.
1174
+ * 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
1176
+ * mounted, opened, closed or saved. `directory` and `root` are `null` while no folder is open. Returns the function
1177
+ * that stops it.
1141
1178
  */
1142
1179
  function followProjectFolder(vm, listener) {
1143
1180
  let unsubscribe = () => {};
1144
1181
  let followed;
1145
1182
  const update = () => {
1146
- var _folder$directory;
1183
+ var _folder$directory, _folder$root2;
1147
1184
  const folder = folders.get(vm);
1148
1185
  if (folder !== followed) {
1149
1186
  unsubscribe();
1150
1187
  followed = folder;
1151
- unsubscribe = folder ? folder.subscribe(() => listener(folder, folder.directory)) : () => {};
1188
+ unsubscribe = folder ? folder.subscribe(() => {
1189
+ var _folder$root;
1190
+ return listener(folder, folder.directory, (_folder$root = folder.root) !== null && _folder$root !== void 0 ? _folder$root : null);
1191
+ }) : () => {};
1152
1192
  }
1153
- listener(folder, (_folder$directory = folder === null || folder === void 0 ? void 0 : folder.directory) !== null && _folder$directory !== void 0 ? _folder$directory : null);
1193
+ listener(folder, (_folder$directory = folder === null || folder === void 0 ? void 0 : folder.directory) !== null && _folder$directory !== void 0 ? _folder$directory : null, (_folder$root2 = folder === null || folder === void 0 ? void 0 : folder.root) !== null && _folder$root2 !== void 0 ? _folder$root2 : null);
1154
1194
  };
1155
1195
  registrations.add(update);
1156
1196
  update();
@@ -1159,4 +1199,4 @@ function followProjectFolder(vm, listener) {
1159
1199
  unsubscribe();
1160
1200
  };
1161
1201
  }
1162
- export { projectFile as A, isObject as C, planExtensionSave as D, parseProject as E, _asyncIterator as F, _objectWithoutProperties as I, _objectSpread2 as L, readFolderUpdate 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, readFolder 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 };
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 };
package/dist/source.d.ts CHANGED
@@ -100,6 +100,14 @@ export declare function planExtensionSave(source: FolderSource, project: Project
100
100
  removed: string[];
101
101
  };
102
102
  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
+ /**
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.
109
+ */
110
+ export declare function readProjectFolder(directory: FileSystemDirectoryHandle, storage: Storage): Promise<FolderSource>;
103
111
  export declare const sameBytes: (a: Uint8Array, b: Uint8Array) => boolean;
104
112
  export type FolderUpdate = {
105
113
  version: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-project-folder",
3
- "version": "0.15.1",
3
+ "version": "0.17.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/explorer.tsx CHANGED
@@ -7,7 +7,7 @@ import {projectFolderOverwriteWarning} from './create-folder.js';
7
7
  import {followProjectFolder} from './folder-registry.js';
8
8
  import {hiddenEntry, readExplorerState, subscribeExplorerState, writeExplorerState} from './explorer-state.js';
9
9
  import type {ExplorerTreeState} from './explorer-state.js';
10
- import type {ExplorerMutation, FollowedFolder} from './folder-registry.js';
10
+ import type {ExplorerMutation, FollowedFolder, ProjectFolderLocation} from './folder-registry.js';
11
11
  import type {Json, Project} from './source.js';
12
12
  import {canMoveExplorerEntry, copyExplorerDirectory, copyExplorerFile, createExplorerDirectory, deleteExplorerEntry, ExplorerFileError,
13
13
  explorerNameAvailable, moveExplorerEntry, parentPath, renameExplorerEntry, resolveExplorerDirectory} from './explorer-files.js';
@@ -57,8 +57,18 @@ const messages = {
57
57
  en: {
58
58
  label: 'Project folder', loading: 'Loading…', empty: 'This folder is empty.', noMatches: 'No matching files.',
59
59
  results: 'Matching files',
60
- noFolder: 'Open a project folder to show its files here.', open: 'Open Project Folder…',
61
- create: 'Create Project Folder', creating: 'Creating project folder…',
60
+ noFolder: 'Open a folder to show its files here.', open: 'Open Folder…',
61
+ creating: 'Creating project folder…',
62
+ storageIntro: 'Save the current project as a folder containing its project data, costumes, sounds and other files.',
63
+ deviceTitle: 'Save to a folder on this device',
64
+ deviceDescription: 'Choose a folder on your computer. You can view its files in Finder or File Explorer and work with them in VS Code or other apps.',
65
+ deviceNext: 'The button opens a folder picker. Choose an empty folder or create a new one there.',
66
+ deviceCreate: 'Choose a Folder and Save…',
67
+ browserTitle: 'Save in this browser',
68
+ browserDescription: 'Enter a name to create a project folder in this site’s storage, without choosing a folder on your computer. Its files are not directly visible in Finder, File Explorer or other apps.',
69
+ browserRetention: 'The project stays in this browser profile on this device. Clearing site data or automatic browser cleanup may delete it. Keep a copy by exporting an SB3 or ZIP, or saving it to GitHub.',
70
+ browserReopen: 'To continue later, use Open Folder Saved in This Browser… in the File menu.',
71
+ browserCreate: 'Name and Save in This Browser…',
62
72
  createFailed: 'Could not create the project folder.',
63
73
  unavailable: 'File tabs are unavailable in this editor layout.',
64
74
  failed: 'This folder could not be read.', denied: 'Permission to read this folder was not granted.',
@@ -77,8 +87,18 @@ const messages = {
77
87
  ja: {
78
88
  label: '作品フォルダ', loading: '読み込んでいます…', empty: 'このフォルダは空です。', noMatches: '該当するファイルはありません。',
79
89
  results: '検索結果',
80
- noFolder: 'プロジェクトフォルダを開くと、ここにファイルを表示します。', open: 'プロジェクトフォルダを開く…',
81
- create: 'プロジェクトフォルダを作成', creating: 'プロジェクトフォルダを作成しています…',
90
+ noFolder: 'フォルダを開くと、ここにファイルを表示します。', open: 'フォルダを開く…',
91
+ creating: 'プロジェクトフォルダを作成しています…',
92
+ storageIntro: '編集中の作品を、作品データ・コスチューム・音などのファイルをまとめたプロジェクトフォルダとして保存します。',
93
+ deviceTitle: '端末のフォルダに保存',
94
+ deviceDescription: 'パソコン上のフォルダを選んで保存します。Finder やエクスプローラーでファイルを確認でき、VS Code などの外部アプリでも扱えます。',
95
+ deviceNext: 'ボタンを押すとフォルダ選択画面が開きます。空のフォルダを選ぶか、その画面で新しいフォルダを作成してください。',
96
+ deviceCreate: 'フォルダを選んで保存…',
97
+ browserTitle: 'このブラウザー内に保存',
98
+ browserDescription: '名前を入力すると、このサイト専用の保存領域にプロジェクトフォルダを作成します。パソコン上のフォルダを選ぶ必要はありません。Finder やエクスプローラー、外部アプリからファイルを直接見ることはできません。',
99
+ browserRetention: '保存した作品は、この端末のこのブラウザーのプロファイル内に残ります。サイトデータの削除やブラウザーの自動整理で消える場合があります。SB3・ZIP の書き出しや GitHub への保存で、別の場所にも作品を残してください。',
100
+ browserReopen: '次回は「ファイル」メニューの「ブラウザーに保存したフォルダを開く…」から開けます。',
101
+ browserCreate: '名前を付けてブラウザー内に保存…',
82
102
  createFailed: 'プロジェクトフォルダを作成できませんでした。',
83
103
  unavailable: 'このエディターのレイアウトではファイルをタブで開けません。',
84
104
  failed: 'このフォルダを読み込めません。', denied: 'このフォルダを読む許可がありません。',
@@ -191,9 +211,18 @@ background:repeating-conic-gradient(rgba(128,128,128,.22) 0 25%,transparent 0 50
191
211
  color:inherit;color:color-mix(in srgb,currentColor 78%,transparent);font-size:.75em;line-height:1.4;
192
212
  white-space:normal;overflow-wrap:anywhere}
193
213
  .${prefix}-status{opacity:.7;font-style:italic;padding-block:.15em}
194
- .${prefix}-empty{padding:.5em}
214
+ .${prefix}-empty{padding:.75em;line-height:1.6;overflow-wrap:anywhere}
195
215
  .${prefix}-empty p{margin:0 0 .6em}
196
- .${prefix}-empty button{color:inherit;background:transparent;border:1px solid currentColor;border-radius:4px;padding:.2em .6em;font:inherit;cursor:pointer}`;
216
+ .${prefix}-storage{padding-block:.8em;border-block-start:1px solid color-mix(in srgb,currentColor 25%,transparent)}
217
+ .${prefix}-storage h3{margin:0 0 .5em;font-size:1em}
218
+ .${prefix}-empty button{color:inherit;background:transparent;border:1px solid currentColor;border-radius:4px;padding:.4em .7em;font:inherit;cursor:pointer;white-space:normal;max-width:100%}
219
+ .${prefix}-storage button{display:inline-flex;align-items:center;gap:.45em;text-align:start;
220
+ border-radius:.65rem;padding:.55em .9em;background:var(--looks-secondary,#855cd6);
221
+ border-color:var(--looks-secondary,#855cd6);color:#fff;font-weight:600;line-height:1.4}
222
+ .${prefix}-storage button:hover:not(:disabled){background:color-mix(in srgb,var(--looks-secondary,#855cd6) 88%,#000)}
223
+ .${prefix}-storage button:focus-visible{outline:2px solid var(--looks-secondary,#855cd6);outline-offset:3px}
224
+ .${prefix}-storage button svg{flex:none}
225
+ .${prefix}-empty button:disabled{opacity:.6;cursor:wait}`;
197
226
 
198
227
  const indent = (level: number) => ({paddingInlineStart: `${0.25 + level * 1.1}em`});
199
228
 
@@ -213,6 +242,11 @@ const icons: Record<IconKind, string[]> = {
213
242
  'text': [page, corner, 'M5.5 7.5h5M5.5 9.5h5M5.5 11.5h3'],
214
243
  'file': [page, corner]
215
244
  };
245
+ const storageIcons: Record<ProjectFolderLocation, string[]> = {
246
+ device: icons.folder,
247
+ browser: ['M2.5 2.5h11a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1v-9a1 1 0 0 1 1-1z',
248
+ 'M1.5 5.5h13', 'M3.5 4h.1M5.5 4h.1']
249
+ };
216
250
  const extensionIcons: Record<string, IconKind> = {
217
251
  json: 'json', svg: 'image', png: 'image', jpg: 'image', jpeg: 'image', gif: 'image', bmp: 'image', webp: 'image',
218
252
  wav: 'sound', mp3: 'sound', ogg: 'sound', js: 'code', mjs: 'code', ts: 'code', md: 'text', txt: 'text'
@@ -844,8 +878,8 @@ export type FollowFileStatuses = (directory: FileSystemDirectoryHandle,
844
878
  type FolderViewProps = {
845
879
  vm: object;
846
880
  locale?: string;
847
- /** Saves the current project to a local folder. */
848
- createFolder?(): Promise<unknown>;
881
+ /** Saves the current project to the selected storage location. */
882
+ createFolder?(location?: ProjectFolderLocation): Promise<unknown>;
849
883
  marks?: FollowMarks;
850
884
  fileStatuses?: FollowFileStatuses;
851
885
  /** Reports unsaved text edits in open file tabs for the given folder. */
@@ -867,12 +901,12 @@ function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: follow
867
901
  const message = messagesFor(locale);
868
902
  const [creating, setCreating] = React.useState(false);
869
903
  const [createError, setCreateError] = React.useState('');
870
- const create = async () => {
904
+ const create = async (location: ProjectFolderLocation) => {
871
905
  if (!createFolder || creating) return;
872
906
  setCreating(true);
873
907
  setCreateError('');
874
908
  try {
875
- await createFolder();
909
+ await createFolder(location);
876
910
  } catch {
877
911
  setCreateError(message.createFailed);
878
912
  } finally {
@@ -938,8 +972,27 @@ function FolderView({vm, locale = 'en', marks: followMarks, fileStatuses: follow
938
972
  return <div className={`${prefix}-empty`}>
939
973
  <style>{css}</style>
940
974
  {createFolder ? <>
941
- <p>{projectFolderOverwriteWarning(locale)}</p>
942
- <button type="button" disabled={creating} onClick={() => void create()}>{message.create}</button>
975
+ <p>{message.storageIntro}</p>
976
+ {(folder.locations ?? ['device']).map(location => <section key={location}
977
+ className={`${prefix}-storage`} data-project-folder-location={location}>
978
+ <h3>{location === 'device' ? message.deviceTitle : message.browserTitle}</h3>
979
+ {location === 'device' ? <>
980
+ <p>{message.deviceDescription}</p>
981
+ <p>{message.deviceNext}</p>
982
+ <p>{projectFolderOverwriteWarning(locale)}</p>
983
+ </> : <>
984
+ <p>{message.browserDescription}</p>
985
+ <p>{message.browserRetention}</p>
986
+ <p>{message.browserReopen}</p>
987
+ </>}
988
+ <button type="button" disabled={creating} onClick={() => void create(location)}>
989
+ <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor"
990
+ strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" focusable="false">
991
+ {storageIcons[location].map((d, index) => <path key={index} d={d} />)}
992
+ </svg>
993
+ <span>{location === 'device' ? message.deviceCreate : message.browserCreate}</span>
994
+ </button>
995
+ </section>)}
943
996
  {creating && <p role="status">{message.creating}</p>}
944
997
  {createError && <p role="alert">{createError}</p>}
945
998
  </> : <>
@@ -1,12 +1,17 @@
1
1
  /** The project folder mounted for a VM, as a view of the folder follows it. */
2
2
  export type ExplorerMutation = (guard: () => void) => Promise<void>;
3
+ export type ProjectFolderLocation = 'device' | 'browser';
3
4
 
4
5
  export interface FollowedFolder {
5
6
  readonly directory: FileSystemDirectoryHandle | null;
7
+ /** The folder the user chose for `directory`: itself, or the repository whose `project` folder it is. */
8
+ readonly root?: FileSystemDirectoryHandle | null;
9
+ /** Storage choices available when creating a project folder. */
10
+ readonly locations?: readonly ProjectFolderLocation[];
6
11
  subscribe(listener: () => void): () => void;
7
12
  subscribeEdits(listener: () => void): () => void;
8
13
  unsavedPaths(): ReadonlySet<string> | null;
9
- /** Asks for a folder and opens it, as the File menu's Open Project Folder… does. */
14
+ /** Asks for a folder and opens it, as the File menu's Open Folder… does. */
10
15
  open(locale: string): void;
11
16
  mutate(directory: FileSystemDirectoryHandle, operation: ExplorerMutation): Promise<void>;
12
17
  }
@@ -25,11 +30,13 @@ export function registerFolder(vm: object, folder: FollowedFolder) {
25
30
  }
26
31
 
27
32
  /**
28
- * Calls `listener` with the project folder mounted for `vm` and the directory open in it, now and whenever a folder is
29
- * mounted, opened, closed or saved. Returns the function that stops it.
33
+ * Calls `listener` with the project folder mounted for `vm`, the directory open in it and the folder the user chose for
34
+ * it (`root`, the directory itself or the repository that holds it in `project/`), now and whenever a folder is
35
+ * mounted, opened, closed or saved. `directory` and `root` are `null` while no folder is open. Returns the function
36
+ * that stops it.
30
37
  */
31
- export function followProjectFolder(vm: object,
32
- listener: (folder: FollowedFolder | undefined, directory: FileSystemDirectoryHandle | null) => void) {
38
+ export function followProjectFolder(vm: object, listener: (folder: FollowedFolder | undefined,
39
+ directory: FileSystemDirectoryHandle | null, root: FileSystemDirectoryHandle | null) => void) {
33
40
  let unsubscribe = () => {};
34
41
  let followed: FollowedFolder | undefined;
35
42
  const update = () => {
@@ -37,9 +44,9 @@ export function followProjectFolder(vm: object,
37
44
  if (folder !== followed) {
38
45
  unsubscribe();
39
46
  followed = folder;
40
- unsubscribe = folder ? folder.subscribe(() => listener(folder, folder.directory)) : () => {};
47
+ unsubscribe = folder ? folder.subscribe(() => listener(folder, folder.directory, folder.root ?? null)) : () => {};
41
48
  }
42
- listener(folder, folder?.directory ?? null);
49
+ listener(folder, folder?.directory ?? null, folder?.root ?? null);
43
50
  };
44
51
  registrations.add(update);
45
52
  update();