@kubohiroya/turbowarp-plus-editor-project-folder 0.11.0 → 0.13.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
@@ -10,7 +10,7 @@ TurboWarp Plus Editor で sb3-toolchain の作品フォルダ(展開ソース
10
10
  - `renderProjectFolderMenu(createElement, props)` は既存の開く・保存コマンドをホストのファイルメニューに渡します。
11
11
  - 接続後の `openDirectory(handle, confirmReplace)` には、ホストが選択済みのディレクトリハンドルを渡せます。ファイルメニューと同じ作品検証・未保存編集の確認を経て開き、保存先にはその作品フォルダを使います。
12
12
  - 接続後の `directory` は、読み込んだ作品のフォルダーのハンドルです。別の作品を読み込むか、フォルダーとの接続を外すと `null` になります。ホストは作品を見分けるのに使えます。
13
- - `host.screenState` を渡すと、Editor の画面状態をフォルダーに保存します。渡すものは workbench の `installProjectScreenState` が返すものです。作品フォルダーは SB3 ではないので、状態は `.tw-plus/workspace.json` に入れます。フォルダーを開くと、作品を読み込む前にこれを読み、`prepareLoad(text)` で渡します。保存時は、作品が変わっていなくても `serialize()` の結果を書きます。保存時刻だけが違うときは書きません。読み書きに失敗しても、開く操作と保存は失敗にしません。セッションは `projectFolder` スライス(ツリーで開いたフォルダーと選択中の項目)も登録します。
13
+ - `host.screenState` を渡すと、Editor の画面状態をフォルダーに保存します。渡すものは workbench の `installProjectScreenState` が返すものです。作品フォルダーは SB3 ではないので、状態は `.tw-plus/workspace.json` に入れます。フォルダーを開くと、作品を読み込む前にこれを読み、`prepareLoad(text)` で渡します。保存時は、作品が変わっていなくても `serialize()` の結果を書きます。保存時刻だけが違うときは書きません。読み書きに失敗しても、開く操作と保存は失敗にしません。セッションは `projectFolder` スライス(ツリーで開いたフォルダーと選択中の項目)も登録します。SB3 から作品フォルダを作るとき、sb3-toolchain(0.26.0 以降)が展開したスナップショットに `.tw-plus/workspace.json` があれば、そのままフォルダーに書くので、作ったフォルダーは同じ画面で開きます。スナップショットにないときは、上書きするフォルダーの古い `workspace.json` を消します。`.tw-plus` のほかのファイルは残します。
14
14
 
15
15
  ホストは VM、メニューコンポーネント、作品状態を扱うコールバックを渡します。メニューからフォルダを開くには、ブラウザーが File System Access のフォルダ選択に対応している必要があります。ブロック、変数・リスト、スプライトの位置や大きさなどの項目、モニター、組み込みの拡張機能の編集を作品データ(`project.source.json`)に保存し、作品の実行で変わった状態も含みます。スプライトの追加・削除・名前の変更と、コスチューム・音の追加・削除も保存します。新しいアセットのファイルを先に書き、`sb3-source.json` と作品データを書いてから、参照されなくなったアセットのファイルを消します。 [Editor #305](https://github.com/kubohiroya/turbowarp-plus-editor/issues/305) · [Editor #308](https://github.com/kubohiroya/turbowarp-plus-editor/issues/308)
16
16
 
@@ -18,6 +18,8 @@ TurboWarp Plus Editor で sb3-toolchain の作品フォルダ(展開ソース
18
18
 
19
19
  ## ブロックパレットの設定
20
20
 
21
+ TurboWarp Plus Editor は、ブロックパレットの設定を画面状態(`.tw-plus/workspace.json`)に保存するようになりました。この節の形式 2 の読み書きは、それ以前に作られた作品フォルダのために残しています。
22
+
21
23
  展開ソース形式 2 の作品フォルダは、スプライト・背景ごとのブロックパレットの設定を `block-palette.json` に持ちます([sb3-toolchain の形式 v2](https://github.com/kubohiroya/sb3-toolchain/blob/main/docs/ja/source-format-v2.md))。開くときは、`project.source.json` のコメントにある参照 `block-palette:block-palette.json` を、SB3 と同じパレット設定のコメントの本文に戻して VM に読み込みます。
22
24
 
23
25
  保存時は、VM にあるパレット設定のコメントを `block-palette.json` に移し、`project.source.json` のコメントを参照に戻します。スプライトの名前を変えると、設定のキーも新しい名前になります。パレットの設定だけを変えたときは、`block-palette.json` だけを書きます。設定のある作品は形式 2、ない作品は形式 1 で保存します。形式 1 から 2 に移るときは `block-palette.json` を先に書き、2 から 1 に戻るときは `sb3-source.json` と作品データを書いてから `block-palette.json` を消します。変換には sb3-toolchain のブラウザー向けの関数を使い、toolchain の `build` と `import` が作る内容とバイト単位で同じにします。
package/README.md CHANGED
@@ -10,7 +10,7 @@ This package opens and saves sb3-toolchain project folders (source formats 1 and
10
10
  - `renderProjectFolderMenu(createElement, props)` supplies the existing open and save commands to the host's file menu.
11
11
  - The mounted session's `openDirectory(handle, confirmReplace)` accepts a directory handle already selected by the host. It uses the same project validation and unsaved-edit confirmation as the file menu. Save still targets the opened folder.
12
12
  - The mounted session's `directory` is the folder the loaded project came from. It becomes `null` once another project loads or the folder is detached, so a host can tell projects apart by it.
13
- - `host.screenState` keeps the Editor's screen state in the folder, as the workbench's `installProjectScreenState` provides it. A project folder is not an SB3, so the state goes into `.tw-plus/workspace.json`. Opening the folder reads it and passes it with `prepareLoad(text)` before the project loads. Saving writes `serialize()`, even when the project itself is unchanged, and skips the write when only the save time differs. A failure to read or write it never fails the open or the save. The session also registers the `projectFolder` slice: the expanded folders and the selected entry of the explorer.
13
+ - `host.screenState` keeps the Editor's screen state in the folder, as the workbench's `installProjectScreenState` provides it. A project folder is not an SB3, so the state goes into `.tw-plus/workspace.json`. Opening the folder reads it and passes it with `prepareLoad(text)` before the project loads. Saving writes `serialize()`, even when the project itself is unchanged, and skips the write when only the save time differs. A failure to read or write it never fails the open or the save. The session also registers the `projectFolder` slice: the expanded folders and the selected entry of the explorer. When a folder is created from an SB3, a `.tw-plus/workspace.json` in the snapshot sb3-toolchain (0.26.0 or later) unpacked is written into the folder as it is, so the new folder opens with the same screen. A snapshot without one removes the old `workspace.json` of the folder it overwrites, and keeps the other files in `.tw-plus`.
14
14
 
15
15
  The host supplies the VM, menu components, and project state callbacks. The browser must support the File System Access picker for the built-in open command. Save writes block, variable, list, sprite property, monitor and built-in extension edits to the project file, including state that changes while the project runs. Sprites can be added, removed and renamed, and costumes and sounds added or removed: new asset files are written first, then `sb3-source.json` and the project file, and asset files nothing refers to are deleted last. See [Editor issue #305](https://github.com/kubohiroya/turbowarp-plus-editor/issues/305) and [issue #308](https://github.com/kubohiroya/turbowarp-plus-editor/issues/308).
16
16
 
@@ -20,6 +20,8 @@ Folders can contain embedded extension scripts and custom extension URLs. Openin
20
20
 
21
21
  ## Block palette settings
22
22
 
23
+ TurboWarp Plus Editor now saves block palette settings in its screen state (`.tw-plus/workspace.json`). Reading and writing format 2, described here, stays for project folders made before that.
24
+
23
25
  A source format 2 folder keeps per-sprite and stage block palette settings in `block-palette.json` (see [sb3-toolchain source format v2](https://github.com/kubohiroya/sb3-toolchain/blob/main/docs/source-format-v2.md)). Opening the folder turns each `block-palette:block-palette.json` comment reference in `project.source.json` back into the palette comment text an SB3 has, and the VM loads that.
24
26
 
25
27
  Saving moves the VM's palette comments into `block-palette.json` and puts the references back in `project.source.json`. A renamed sprite keeps its settings under the new name. A change to palette settings alone writes only `block-palette.json`. A project with settings is saved as format 2, and one without as format 1: moving to format 2 writes `block-palette.json` first, and moving back deletes it after `sb3-source.json` and the project file are written. The conversion uses sb3-toolchain's browser functions, so the files match what the toolchain's `build` and `import` produce, byte for byte.
@@ -390,7 +390,7 @@ THE SOFTWARE.
390
390
 
391
391
  ## @headless-tree/react - 1.8.0 (MIT)
392
392
 
393
- ## @kubohiroya/sb3-toolchain - 0.25.1 (MPL-2.0)
393
+ ## @kubohiroya/sb3-toolchain - 0.26.0 (MPL-2.0)
394
394
 
395
395
  Mozilla Public License Version 2.0
396
396
  ==================================
@@ -7,6 +7,11 @@ export declare function resolveExplorerDirectory(root: FileSystemDirectoryHandle
7
7
  export declare function explorerNameAvailable(directory: FileSystemDirectoryHandle, name: string): Promise<boolean>;
8
8
  export declare function createExplorerDirectory(parent: FileSystemDirectoryHandle, name: string, guard: () => void): Promise<void>;
9
9
  export declare function copyExplorerFile(directory: FileSystemDirectoryHandle, file: File, guard: () => void): Promise<void>;
10
+ /**
11
+ * Copy a folder dropped from outside, such as from Finder or File Explorer, into `parent` with everything in it.
12
+ * Entries the tree hides, such as `.git`, are left out. If any part fails, the partial copy is removed.
13
+ */
14
+ export declare function copyExplorerDirectory(parent: FileSystemDirectoryHandle, source: FileSystemDirectoryHandle, guard: () => void): Promise<void>;
10
15
  export declare function renameExplorerEntry(parent: FileSystemDirectoryHandle, entry: {
11
16
  name: string;
12
17
  kind: FileSystemHandleKind;
package/dist/explorer.js CHANGED
@@ -1,4 +1,4 @@
1
- import { A as projectFile, C as isObject, F as _asyncIterator, L as _objectSpread2, c as subscribeExplorerState, f as projectFolderOverwriteWarning, i as hiddenEntry, l as writeExplorerState, o as readExplorerState, p as FolderError, t as followProjectFolder, w as manifestFile } from "./shared-tZS90T71.js";
1
+ import { A as projectFile, C as isObject, F as _asyncIterator, L as _objectSpread2, a as projectFolderOverwriteWarning, d as subscribeExplorerState, f as writeExplorerState, l as readExplorerState, p as FolderError, s as hiddenEntry, t as followProjectFolder, w as manifestFile } from "./shared-cwwWtggC.js";
2
2
  import * as React from "react";
3
3
  import { useEffect, useState } from "react";
4
4
  import { createPortal } from "react-dom";
@@ -983,6 +983,49 @@ async function copyExplorerFile(directory, file, guard) {
983
983
  validateName(file.name);
984
984
  await writeNewFile(directory, file.name, file, guard);
985
985
  }
986
+ /**
987
+ * Copy a folder dropped from outside, such as from Finder or File Explorer, into `parent` with everything in it.
988
+ * Entries the tree hides, such as `.git`, are left out. If any part fails, the partial copy is removed.
989
+ */
990
+ async function copyExplorerDirectory(parent, source, guard) {
991
+ validateName(source.name);
992
+ await assertUnused(parent, source.name);
993
+ guard();
994
+ const destination = await parent.getDirectoryHandle(source.name, { create: true });
995
+ try {
996
+ await copyDirectoryContents(source, destination, guard);
997
+ } catch (error) {
998
+ await removeIncompleteCopy(parent, source.name);
999
+ throw error;
1000
+ }
1001
+ }
1002
+ async function copyDirectoryContents(source, destination, guard) {
1003
+ var _iteratorAbruptCompletion = false;
1004
+ var _didIteratorError = false;
1005
+ var _iteratorError;
1006
+ try {
1007
+ for (var _iterator = _asyncIterator(source.values()), _step; _iteratorAbruptCompletion = !(_step = await _iterator.next()).done; _iteratorAbruptCompletion = false) {
1008
+ const handle = _step.value;
1009
+ if (hiddenEntry(handle.name)) continue;
1010
+ validateName(handle.name);
1011
+ if (handle.kind === "file") {
1012
+ await writeNewFile(destination, handle.name, await handle.getFile(), guard);
1013
+ continue;
1014
+ }
1015
+ guard();
1016
+ await copyDirectoryContents(handle, await destination.getDirectoryHandle(handle.name, { create: true }), guard);
1017
+ }
1018
+ } catch (err) {
1019
+ _didIteratorError = true;
1020
+ _iteratorError = err;
1021
+ } finally {
1022
+ try {
1023
+ if (_iteratorAbruptCompletion && _iterator.return != null) await _iterator.return();
1024
+ } finally {
1025
+ if (_didIteratorError) throw _iteratorError;
1026
+ }
1027
+ }
1028
+ }
986
1029
  async function copyEntry(sourceParent, source, parent, name, guard) {
987
1030
  validateName(source.name);
988
1031
  if (source.kind === "file") {
@@ -1007,25 +1050,25 @@ async function copyEntry(sourceParent, source, parent, name, guard) {
1007
1050
  const directory = source;
1008
1051
  const children = /* @__PURE__ */ new Map();
1009
1052
  try {
1010
- var _iteratorAbruptCompletion = false;
1011
- var _didIteratorError = false;
1012
- var _iteratorError;
1053
+ var _iteratorAbruptCompletion2 = false;
1054
+ var _didIteratorError2 = false;
1055
+ var _iteratorError2;
1013
1056
  try {
1014
- for (var _iterator = _asyncIterator(directory.values()), _step; _iteratorAbruptCompletion = !(_step = await _iterator.next()).done; _iteratorAbruptCompletion = false) {
1015
- const handle = _step.value;
1057
+ for (var _iterator2 = _asyncIterator(directory.values()), _step2; _iteratorAbruptCompletion2 = !(_step2 = await _iterator2.next()).done; _iteratorAbruptCompletion2 = false) {
1058
+ const handle = _step2.value;
1016
1059
  children.set(handle.name, {
1017
1060
  handle,
1018
1061
  copy: await copyEntry(directory, handle, destination, handle.name, guard)
1019
1062
  });
1020
1063
  }
1021
1064
  } catch (err) {
1022
- _didIteratorError = true;
1023
- _iteratorError = err;
1065
+ _didIteratorError2 = true;
1066
+ _iteratorError2 = err;
1024
1067
  } finally {
1025
1068
  try {
1026
- if (_iteratorAbruptCompletion && _iterator.return != null) await _iterator.return();
1069
+ if (_iteratorAbruptCompletion2 && _iterator2.return != null) await _iterator2.return();
1027
1070
  } finally {
1028
- if (_didIteratorError) throw _iteratorError;
1071
+ if (_didIteratorError2) throw _iteratorError2;
1029
1072
  }
1030
1073
  }
1031
1074
  } catch (error) {
@@ -1034,12 +1077,12 @@ async function copyEntry(sourceParent, source, parent, name, guard) {
1034
1077
  }
1035
1078
  const verify = async () => {
1036
1079
  let count = 0;
1037
- var _iteratorAbruptCompletion2 = false;
1038
- var _didIteratorError2 = false;
1039
- var _iteratorError2;
1080
+ var _iteratorAbruptCompletion3 = false;
1081
+ var _didIteratorError3 = false;
1082
+ var _iteratorError3;
1040
1083
  try {
1041
- for (var _iterator2 = _asyncIterator(directory.values()), _step2; _iteratorAbruptCompletion2 = !(_step2 = await _iterator2.next()).done; _iteratorAbruptCompletion2 = false) {
1042
- const handle = _step2.value;
1084
+ for (var _iterator3 = _asyncIterator(directory.values()), _step3; _iteratorAbruptCompletion3 = !(_step3 = await _iterator3.next()).done; _iteratorAbruptCompletion3 = false) {
1085
+ const handle = _step3.value;
1043
1086
  {
1044
1087
  const child = children.get(handle.name);
1045
1088
  if (!child || !await handle.isSameEntry(child.handle)) throw new ExplorerFileError("sourceChanged");
@@ -1048,13 +1091,13 @@ async function copyEntry(sourceParent, source, parent, name, guard) {
1048
1091
  }
1049
1092
  }
1050
1093
  } catch (err) {
1051
- _didIteratorError2 = true;
1052
- _iteratorError2 = err;
1094
+ _didIteratorError3 = true;
1095
+ _iteratorError3 = err;
1053
1096
  } finally {
1054
1097
  try {
1055
- if (_iteratorAbruptCompletion2 && _iterator2.return != null) await _iterator2.return();
1098
+ if (_iteratorAbruptCompletion3 && _iterator3.return != null) await _iterator3.return();
1056
1099
  } finally {
1057
- if (_didIteratorError2) throw _iteratorError2;
1100
+ if (_didIteratorError3) throw _iteratorError3;
1058
1101
  }
1059
1102
  }
1060
1103
  if (count !== children.size) throw new ExplorerFileError("sourceChanged");
@@ -1109,24 +1152,24 @@ async function deleteExplorerEntry(parent, entry, guard) {
1109
1152
  validateName(entry.name);
1110
1153
  if (entry.kind === "directory") {
1111
1154
  const check = async (directory) => {
1112
- var _iteratorAbruptCompletion3 = false;
1113
- var _didIteratorError3 = false;
1114
- var _iteratorError3;
1155
+ var _iteratorAbruptCompletion4 = false;
1156
+ var _didIteratorError4 = false;
1157
+ var _iteratorError4;
1115
1158
  try {
1116
- for (var _iterator3 = _asyncIterator(directory.values()), _step3; _iteratorAbruptCompletion3 = !(_step3 = await _iterator3.next()).done; _iteratorAbruptCompletion3 = false) {
1117
- const child = _step3.value;
1159
+ for (var _iterator4 = _asyncIterator(directory.values()), _step4; _iteratorAbruptCompletion4 = !(_step4 = await _iterator4.next()).done; _iteratorAbruptCompletion4 = false) {
1160
+ const child = _step4.value;
1118
1161
  guard();
1119
1162
  validateName(child.name);
1120
1163
  if (child.kind === "directory") await check(child);
1121
1164
  }
1122
1165
  } catch (err) {
1123
- _didIteratorError3 = true;
1124
- _iteratorError3 = err;
1166
+ _didIteratorError4 = true;
1167
+ _iteratorError4 = err;
1125
1168
  } finally {
1126
1169
  try {
1127
- if (_iteratorAbruptCompletion3 && _iterator3.return != null) await _iterator3.return();
1170
+ if (_iteratorAbruptCompletion4 && _iterator4.return != null) await _iterator4.return();
1128
1171
  } finally {
1129
- if (_didIteratorError3) throw _iteratorError3;
1172
+ if (_didIteratorError4) throw _iteratorError4;
1130
1173
  }
1131
1174
  }
1132
1175
  };
@@ -1420,7 +1463,7 @@ function createFilePreview(directory, documentId, { name, path }, locale, readBa
1420
1463
  status.textContent = message.large;
1421
1464
  return;
1422
1465
  }
1423
- const [bytes, { decodeText, mountTextFile }] = await Promise.all([file.arrayBuffer(), import("./shared-BKa_B85G.js")]);
1466
+ const [bytes, { decodeText, mountTextFile }] = await Promise.all([file.arrayBuffer(), import("./shared-BYk-uDpM.js")]);
1424
1467
  if (disposed) return;
1425
1468
  const content = decodeText(bytes);
1426
1469
  if (content === null) {
@@ -2238,22 +2281,40 @@ function Explorer({ directory, locale, descriptions, marks, fileStatuses, unsave
2238
2281
  if (item.kind !== "file") return [];
2239
2282
  const entry = (_item$webkitGetAsEntr = item.webkitGetAsEntry) === null || _item$webkitGetAsEntr === void 0 ? void 0 : _item$webkitGetAsEntr.call(item);
2240
2283
  if (entry === null || entry === void 0 ? void 0 : entry.isDirectory) {
2284
+ var _item$getAsFileSystem;
2285
+ const folder = (_item$getAsFileSystem = item.getAsFileSystemHandle) === null || _item$getAsFileSystem === void 0 ? void 0 : _item$getAsFileSystem.call(item);
2286
+ if (folder) return [{
2287
+ name: entry.name,
2288
+ folder
2289
+ }];
2241
2290
  problems.push(`${entry.name} — ${actions.filesOnly}`);
2242
2291
  return [];
2243
2292
  }
2244
2293
  const file = item.getAsFile();
2245
- return file ? [file] : [];
2246
- }) : Array.from(event.dataTransfer.files);
2294
+ return file ? [{
2295
+ name: file.name,
2296
+ file
2297
+ }] : [];
2298
+ }) : Array.from(event.dataTransfer.files, (file) => ({
2299
+ name: file.name,
2300
+ file
2301
+ }));
2247
2302
  run(async () => {
2248
2303
  if (!dropped.length) return problems.join("\n") || actions.filesOnly;
2249
2304
  try {
2250
2305
  await write(path, async (parent, guard) => {
2251
- for (const file of dropped) {
2306
+ for (const item of dropped) {
2252
2307
  guard();
2253
2308
  try {
2254
- await copyExplorerFile(parent, file, guard);
2309
+ if ("file" in item) {
2310
+ await copyExplorerFile(parent, item.file, guard);
2311
+ continue;
2312
+ }
2313
+ const folder = await item.folder;
2314
+ if ((folder === null || folder === void 0 ? void 0 : folder.kind) !== "directory") throw new DOMException("Not a folder", "NotFoundError");
2315
+ await copyExplorerDirectory(parent, folder, guard);
2255
2316
  } catch (error) {
2256
- problems.push(`${actions.copyFailed} ${file.name} — ${errorText(error)}`);
2317
+ problems.push(`${actions.copyFailed} ${item.name} — ${errorText(error)}`);
2257
2318
  }
2258
2319
  }
2259
2320
  });
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { A as projectFile, C as isObject, D as planExtensionSave, E as parseProject, 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 parseExplorerState, b as expandPalette, c as subscribeExplorerState, d as isProjectFolderEmpty, f as projectFolderOverwriteWarning, g as assetTypeFor, h as assetKey, j as readFolder, k as projectChanges, l as writeExplorerState, m as assertFolderUnchanged, n as registerFolder, o as readExplorerState, p as FolderError, r as editorDirectory, s as screenStateFile, t as followProjectFolder, u as createProjectFolder, v as encodePalette, w as manifestFile, x as extensionsFile, y as equal } from "./shared-tZS90T71.js";
1
+ import { A as projectFile, C as isObject, D as planExtensionSave, E as parseProject, 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";
2
2
  // src/block-reload.ts
3
3
  var _excluded$2 = ["targets"];
4
4
  var _excluded2$1 = ["targets"];
@@ -1,4 +1,4 @@
1
- import { L as _objectSpread2 } from "./shared-tZS90T71.js";
1
+ import { L as _objectSpread2 } from "./shared-cwwWtggC.js";
2
2
  // node_modules/@marijn/find-cluster-break/src/index.js
3
3
  var rangeFrom = [];
4
4
  var rangeTo = [];
@@ -404,6 +404,8 @@ 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 ZIP entry of the Editor's screen state, which sb3-toolchain lists in `archiveEntries`. */
408
+ var screenStateEntry = "tw-plus/workspace.json";
407
409
  /** Block palette settings of source format 2. Format 1 folders have no such file. */
408
410
  var paletteFile = blockPaletteFile;
409
411
  var embeddedReference = "embedded-extension:";
@@ -693,7 +695,8 @@ async function readFolder(directory, storage) {
693
695
  const extensionManifest = validateExtensions(project, embedded);
694
696
  const references = projectAssets(project);
695
697
  const expected = /* @__PURE__ */ new Set(["project.json", ...references.keys()]);
696
- if (manifest.archiveEntries.length !== expected.size || !sameNames(new Set(manifest.archiveEntries), expected)) return unsupported("Asset references and archiveEntries do not match");
698
+ const listed = manifest.archiveEntries.filter((name) => name !== screenStateEntry);
699
+ if (listed.length !== expected.size || !sameNames(new Set(listed), expected)) return unsupported("Asset references and archiveEntries do not match");
697
700
  expected.delete("project.json");
698
701
  const [assets, extensions] = await Promise.all([readDirectory(directory, "assets"), readDirectory(directory, "extensions")]);
699
702
  const scripts = extensionNames(extensionManifest.extensions);
@@ -872,6 +875,38 @@ function projectChanges(source, before, after, identity) {
872
875
  for (const key of Object.keys(other)) if (!Object.hasOwn(result, key)) result[key] = other[key];
873
876
  return result;
874
877
  }
878
+ // src/explorer-state.ts
879
+ /** The folder the Editor keeps its own files in. The explorer and its search leave it out, like `.git`. */
880
+ var editorDirectory = ".tw-plus";
881
+ /** The screen state of the Editor, inside `editorDirectory`. */
882
+ var screenStateFile = "workspace.json";
883
+ var hiddenEntry = (name) => [".git", editorDirectory].includes(name.toLowerCase());
884
+ var limit = 1e3;
885
+ var states = /* @__PURE__ */ new WeakMap();
886
+ var listeners = /* @__PURE__ */ new WeakMap();
887
+ var validPath = (value) => typeof value === "string" && value.length > 0 && value.length <= 1024 && value.split("/").every((part) => part && part !== "." && part !== ".." && !hiddenEntry(part) && !/[\\\u0000]/u.test(part));
888
+ /** Read a tree state saved in a file, keeping only well-formed paths. */
889
+ function parseExplorerState(value) {
890
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return;
891
+ const { expanded, selected } = value;
892
+ if (!Array.isArray(expanded)) return;
893
+ return _objectSpread2({ expanded: [...new Set(expanded.filter(validPath))].slice(0, limit) }, validPath(selected) && { selected });
894
+ }
895
+ var readExplorerState = (directory) => states.get(directory);
896
+ /** Remember the tree of `directory`. With `notify`, a mounted explorer of that folder shows it too. */
897
+ function writeExplorerState(directory, state, notify = false) {
898
+ var _listeners$get;
899
+ states.set(directory, state);
900
+ if (notify) for (const listener of [...(_listeners$get = listeners.get(directory)) !== null && _listeners$get !== void 0 ? _listeners$get : []]) listener(state);
901
+ }
902
+ function subscribeExplorerState(directory, listener) {
903
+ let set = listeners.get(directory);
904
+ if (!set) listeners.set(directory, set = /* @__PURE__ */ new Set());
905
+ set.add(listener);
906
+ return () => {
907
+ set.delete(listener);
908
+ };
909
+ }
875
910
  // src/create-folder.ts
876
911
  var manifests = /* @__PURE__ */ new Set([
877
912
  projectFile,
@@ -879,6 +914,7 @@ var manifests = /* @__PURE__ */ new Set([
879
914
  extensionsFile
880
915
  ]);
881
916
  var optionalManifests = /* @__PURE__ */ new Set([paletteFile]);
917
+ var screenStatePath = `${editorDirectory}/${screenStateFile}`;
882
918
  var sourceDirectories = ["assets", "extensions"];
883
919
  var sourcePath = /^(?:assets\/[a-f0-9]{32}\.[A-Za-z0-9]+|extensions\/[A-Za-z0-9._-]+\.(?:js|manifest\.json))$/u;
884
920
  function missing(error) {
@@ -933,7 +969,7 @@ async function directoryEntries(directory) {
933
969
  /** Create and validate a project-folder snapshot in a directory chosen by the user. */
934
970
  async function createProjectFolder({ directory, files, storage, overwrite = false, current = () => true }) {
935
971
  for (const filename of manifests) if (!files.has(filename)) return unsupported(`Missing ${filename}`);
936
- for (const [filename, bytes] of files) if (!manifests.has(filename) && !optionalManifests.has(filename) && !sourcePath.test(filename) || !(bytes instanceof Uint8Array)) return unsupported(`Invalid project folder entry: ${filename}`);
972
+ for (const [filename, bytes] of files) if (!manifests.has(filename) && !optionalManifests.has(filename) && filename !== screenStatePath && !sourcePath.test(filename) || !(bytes instanceof Uint8Array)) return unsupported(`Invalid project folder entry: ${filename}`);
937
973
  const assertCurrent = () => {
938
974
  if (!current()) throw new FolderError("conflict", "The project changed before the folder was saved");
939
975
  };
@@ -1016,6 +1052,26 @@ async function createProjectFolder({ directory, files, storage, overwrite = fals
1016
1052
  entries: children
1017
1053
  });
1018
1054
  }
1055
+ const editorEntry = existing.get(editorDirectory);
1056
+ if (files.has(screenStatePath)) {
1057
+ if ((editorEntry === null || editorEntry === void 0 ? void 0 : editorEntry.kind) === "file") await remove(directory, editorEntry);
1058
+ const previous = await getDirectory(directory, editorDirectory);
1059
+ if (previous && (editorEntry === null || editorEntry === void 0 ? void 0 : editorEntry.kind) === "directory" && !await previous.isSameEntry(editorEntry)) throw new FolderError("conflict");
1060
+ assertCurrent();
1061
+ const handle = previous !== null && previous !== void 0 ? previous : await directory.getDirectoryHandle(editorDirectory, { create: true });
1062
+ if (!previous) undo.push(async () => {
1063
+ const found = await getDirectory(directory, editorDirectory);
1064
+ if (found && await found.isSameEntry(handle)) await directory.removeEntry(editorDirectory);
1065
+ });
1066
+ directories.set(editorDirectory, {
1067
+ handle,
1068
+ entries: await directoryEntries(handle)
1069
+ });
1070
+ } else if ((editorEntry === null || editorEntry === void 0 ? void 0 : editorEntry.kind) === "directory") {
1071
+ const handle = await getDirectory(directory, editorDirectory);
1072
+ const stale = handle && (await directoryEntries(handle)).get("workspace.json");
1073
+ if (stale) await remove(handle, stale);
1074
+ }
1019
1075
  for (const name of optionalManifests) {
1020
1076
  const entry = existing.get(name);
1021
1077
  if (entry && !files.has(name)) {
@@ -1065,38 +1121,6 @@ async function createProjectFolder({ directory, files, storage, overwrite = fals
1065
1121
  throw error;
1066
1122
  }
1067
1123
  }
1068
- // src/explorer-state.ts
1069
- /** The folder the Editor keeps its own files in. The explorer and its search leave it out, like `.git`. */
1070
- var editorDirectory = ".tw-plus";
1071
- /** The screen state of the Editor, inside `editorDirectory`. */
1072
- var screenStateFile = "workspace.json";
1073
- var hiddenEntry = (name) => [".git", editorDirectory].includes(name.toLowerCase());
1074
- var limit = 1e3;
1075
- var states = /* @__PURE__ */ new WeakMap();
1076
- var listeners = /* @__PURE__ */ new WeakMap();
1077
- var validPath = (value) => typeof value === "string" && value.length > 0 && value.length <= 1024 && value.split("/").every((part) => part && part !== "." && part !== ".." && !hiddenEntry(part) && !/[\\\u0000]/u.test(part));
1078
- /** Read a tree state saved in a file, keeping only well-formed paths. */
1079
- function parseExplorerState(value) {
1080
- if (value === null || typeof value !== "object" || Array.isArray(value)) return;
1081
- const { expanded, selected } = value;
1082
- if (!Array.isArray(expanded)) return;
1083
- return _objectSpread2({ expanded: [...new Set(expanded.filter(validPath))].slice(0, limit) }, validPath(selected) && { selected });
1084
- }
1085
- var readExplorerState = (directory) => states.get(directory);
1086
- /** Remember the tree of `directory`. With `notify`, a mounted explorer of that folder shows it too. */
1087
- function writeExplorerState(directory, state, notify = false) {
1088
- var _listeners$get;
1089
- states.set(directory, state);
1090
- if (notify) for (const listener of [...(_listeners$get = listeners.get(directory)) !== null && _listeners$get !== void 0 ? _listeners$get : []]) listener(state);
1091
- }
1092
- function subscribeExplorerState(directory, listener) {
1093
- let set = listeners.get(directory);
1094
- if (!set) listeners.set(directory, set = /* @__PURE__ */ new Set());
1095
- set.add(listener);
1096
- return () => {
1097
- set.delete(listener);
1098
- };
1099
- }
1100
1124
  // src/folder-registry.ts
1101
1125
  var folders = /* @__PURE__ */ new WeakMap();
1102
1126
  var registrations = /* @__PURE__ */ new Set();
@@ -1135,4 +1159,4 @@ function followProjectFolder(vm, listener) {
1135
1159
  unsubscribe();
1136
1160
  };
1137
1161
  }
1138
- 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 _, parseExplorerState as a, expandPalette as b, subscribeExplorerState as c, isProjectFolderEmpty as d, projectFolderOverwriteWarning as f, assetTypeFor as g, assetKey as h, hiddenEntry as i, readFolder as j, projectChanges as k, writeExplorerState as l, assertFolderUnchanged as m, registerFolder as n, readExplorerState as o, FolderError as p, editorDirectory as r, screenStateFile as s, followProjectFolder as t, createProjectFolder as u, encodePalette as v, manifestFile as w, extensionsFile as x, equal as y };
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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-project-folder",
3
- "version": "0.11.0",
3
+ "version": "0.13.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",
@@ -55,7 +55,7 @@
55
55
  "@codemirror/view": "6.43.15",
56
56
  "@headless-tree/core": "1.8.0",
57
57
  "@headless-tree/react": "1.8.0",
58
- "@kubohiroya/sb3-toolchain": "0.25.1",
58
+ "@kubohiroya/sb3-toolchain": "0.26.0",
59
59
  "@kubohiroya/turbowarp-plus-editor-test-runtime": "0.1.0",
60
60
  "@lezer/highlight": "1.2.5",
61
61
  "@playwright/test": "1.64.1",
@@ -1,9 +1,12 @@
1
1
  import {extensionsFile, fileVersion, FolderError, manifestFile, paletteFile, projectFile, readFolder, sameBytes, unsupported} from './source.js';
2
2
  import type {Storage} from './source.js';
3
+ import {editorDirectory, screenStateFile} from './explorer-state.js';
3
4
 
4
5
  const manifests = new Set<string>([projectFile, manifestFile, extensionsFile]);
5
6
  // Present only in a format 2 snapshot; readFolder checks that the manifest agrees.
6
7
  const optionalManifests = new Set<string>([paletteFile]);
8
+ // The Editor's screen state, which sb3-toolchain unpacks from an SB3 that carries one. Opening the folder reads it.
9
+ const screenStatePath = `${editorDirectory}/${screenStateFile}`;
7
10
  const sourceDirectories = ['assets', 'extensions'];
8
11
  const sourcePath = /^(?:assets\/[a-f0-9]{32}\.[A-Za-z0-9]+|extensions\/[A-Za-z0-9._-]+\.(?:js|manifest\.json))$/u;
9
12
 
@@ -41,7 +44,8 @@ export async function createProjectFolder({directory, files, storage, overwrite
41
44
  if (!files.has(filename)) return unsupported(`Missing ${filename}`);
42
45
  }
43
46
  for (const [filename, bytes] of files) {
44
- if ((!manifests.has(filename) && !optionalManifests.has(filename) && !sourcePath.test(filename)) || !(bytes instanceof Uint8Array)) {
47
+ if ((!manifests.has(filename) && !optionalManifests.has(filename) && filename !== screenStatePath && !sourcePath.test(filename)) ||
48
+ !(bytes instanceof Uint8Array)) {
45
49
  return unsupported(`Invalid project folder entry: ${filename}`);
46
50
  }
47
51
  }
@@ -126,6 +130,27 @@ export async function createProjectFolder({directory, files, storage, overwrite
126
130
  }
127
131
  directories.set(name, {handle, entries: children});
128
132
  }
133
+ // The Editor's own folder keeps its other files. The snapshot's screen state replaces the old one, and a
134
+ // snapshot without one does not leave the replaced project's screen behind.
135
+ const editorEntry = existing.get(editorDirectory);
136
+ if (files.has(screenStatePath)) {
137
+ if (editorEntry?.kind === 'file') await remove(directory, editorEntry);
138
+ const previous = await getDirectory(directory, editorDirectory);
139
+ if (previous && editorEntry?.kind === 'directory' && !await previous.isSameEntry(editorEntry)) {
140
+ throw new FolderError('conflict');
141
+ }
142
+ assertCurrent();
143
+ const handle = previous ?? await directory.getDirectoryHandle(editorDirectory, {create: true});
144
+ if (!previous) undo.push(async () => {
145
+ const found = await getDirectory(directory, editorDirectory);
146
+ if (found && await found.isSameEntry(handle)) await directory.removeEntry(editorDirectory);
147
+ });
148
+ directories.set(editorDirectory, {handle, entries: await directoryEntries(handle)});
149
+ } else if (editorEntry?.kind === 'directory') {
150
+ const handle = await getDirectory(directory, editorDirectory);
151
+ const stale = handle && (await directoryEntries(handle)).get(screenStateFile);
152
+ if (stale) await remove(handle, stale);
153
+ }
129
154
  // A format 1 snapshot over a format 2 folder must not leave the old palette settings behind.
130
155
  for (const name of optionalManifests) {
131
156
  const entry = existing.get(name);
@@ -81,7 +81,39 @@ export async function copyExplorerFile(directory: FileSystemDirectoryHandle, fil
81
81
  await writeNewFile(directory, file.name, file, guard);
82
82
  }
83
83
 
84
- type CopiedEntry = {verify(): Promise<void>; removeSource(): Promise<void>};
84
+ /**
85
+ * Copy a folder dropped from outside, such as from Finder or File Explorer, into `parent` with everything in it.
86
+ * Entries the tree hides, such as `.git`, are left out. If any part fails, the partial copy is removed.
87
+ */
88
+ export async function copyExplorerDirectory(parent: FileSystemDirectoryHandle, source: FileSystemDirectoryHandle,
89
+ guard: () => void) {
90
+ validateName(source.name);
91
+ await assertUnused(parent, source.name);
92
+ guard();
93
+ const destination = await parent.getDirectoryHandle(source.name, {create: true});
94
+ try {
95
+ await copyDirectoryContents(source as DirectoryEntries, destination, guard);
96
+ } catch (error) {
97
+ await removeIncompleteCopy(parent, source.name);
98
+ throw error;
99
+ }
100
+ }
101
+
102
+ async function copyDirectoryContents(source: DirectoryEntries, destination: FileSystemDirectoryHandle, guard: () => void) {
103
+ for await (const handle of source.values()) {
104
+ if (hiddenEntry(handle.name)) continue;
105
+ validateName(handle.name);
106
+ if (handle.kind === 'file') {
107
+ await writeNewFile(destination, handle.name, await (handle as FileSystemFileHandle).getFile(), guard);
108
+ continue;
109
+ }
110
+ guard();
111
+ const directory = await destination.getDirectoryHandle(handle.name, {create: true});
112
+ await copyDirectoryContents(handle as DirectoryEntries, directory, guard);
113
+ }
114
+ }
115
+
116
+ type CopiedEntry ={verify(): Promise<void>; removeSource(): Promise<void>};
85
117
 
86
118
  async function copyEntry(sourceParent: FileSystemDirectoryHandle, source: FileSystemHandle, parent: FileSystemDirectoryHandle,
87
119
  name: string, guard: () => void): Promise<CopiedEntry> {
package/src/explorer.tsx CHANGED
@@ -9,7 +9,7 @@ import {hiddenEntry, readExplorerState, subscribeExplorerState, writeExplorerSta
9
9
  import type {ExplorerTreeState} from './explorer-state.js';
10
10
  import type {ExplorerMutation, FollowedFolder} from './folder-registry.js';
11
11
  import type {Json, Project} from './source.js';
12
- import {canMoveExplorerEntry, copyExplorerFile, createExplorerDirectory, deleteExplorerEntry, ExplorerFileError,
12
+ import {canMoveExplorerEntry, copyExplorerDirectory, copyExplorerFile, createExplorerDirectory, deleteExplorerEntry, ExplorerFileError,
13
13
  explorerNameAvailable, moveExplorerEntry, parentPath, renameExplorerEntry, resolveExplorerDirectory} from './explorer-files.js';
14
14
  import {actionCss, actionMessages, ExplorerFileDialog, ExplorerMenu} from './explorer-menu.js';
15
15
  import type {FileAction, MenuAnchor} from './explorer-menu.js';
@@ -630,24 +630,38 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
630
630
  const path = dropPath(event.target);
631
631
  const items = Array.from(event.dataTransfer.items);
632
632
  const problems: string[] = [];
633
- const dropped = items.length ? items.flatMap(item => {
634
- if (item.kind !== 'file') return [];
635
- const entry = item.webkitGetAsEntry?.();
636
- if (entry?.isDirectory) {
637
- problems.push(`${entry.name} — ${actions.filesOnly}`);
638
- return [];
639
- }
640
- const file = item.getAsFile();
641
- return file ? [file] : [];
642
- }) : Array.from(event.dataTransfer.files);
633
+ // A folder's handle has to be asked for while the drop event runs; the items are emptied after it.
634
+ type Dropped = {name: string; file: File} | {name: string; folder: Promise<FileSystemHandle | null>};
635
+ const dropped: Dropped[] =
636
+ items.length ? items.flatMap((item): Dropped[] => {
637
+ if (item.kind !== 'file') return [];
638
+ const entry = item.webkitGetAsEntry?.();
639
+ if (entry?.isDirectory) {
640
+ const folder = (item as DataTransferItem & {
641
+ getAsFileSystemHandle?(): Promise<FileSystemHandle | null>;
642
+ }).getAsFileSystemHandle?.();
643
+ if (folder) return [{name: entry.name, folder}];
644
+ problems.push(`${entry.name} — ${actions.filesOnly}`);
645
+ return [];
646
+ }
647
+ const file = item.getAsFile();
648
+ return file ? [{name: file.name, file}] : [];
649
+ }) : Array.from(event.dataTransfer.files, file => ({name: file.name, file}));
643
650
  void run(async () => {
644
651
  if (!dropped.length) return problems.join('\n') || actions.filesOnly;
645
652
  try {
646
653
  await write(path, async (parent, guard) => {
647
- for (const file of dropped) {
654
+ for (const item of dropped) {
648
655
  guard();
649
- try {await copyExplorerFile(parent, file, guard);}
650
- catch (error) {problems.push(`${actions.copyFailed} ${file.name} — ${errorText(error)}`);}
656
+ try {
657
+ if ('file' in item) {
658
+ await copyExplorerFile(parent, item.file, guard);
659
+ continue;
660
+ }
661
+ const folder = await item.folder;
662
+ if (folder?.kind !== 'directory') throw new DOMException('Not a folder', 'NotFoundError');
663
+ await copyExplorerDirectory(parent, folder as FileSystemDirectoryHandle, guard);
664
+ } catch (error) {problems.push(`${actions.copyFailed} ${item.name} — ${errorText(error)}`);}
651
665
  }
652
666
  });
653
667
  } finally {
package/src/source.ts CHANGED
@@ -10,6 +10,8 @@ type Target = JsonObject & {isStage: boolean; name: string};
10
10
  export const projectFile = 'project.source.json';
11
11
  export const manifestFile = 'sb3-source.json';
12
12
  export const extensionsFile = 'embedded-extensions.json';
13
+ /** The ZIP entry of the Editor's screen state, which sb3-toolchain lists in `archiveEntries`. */
14
+ const screenStateEntry = 'tw-plus/workspace.json';
13
15
  /** Block palette settings of source format 2. Format 1 folders have no such file. */
14
16
  export const paletteFile = blockPaletteFile;
15
17
  const embeddedReference = 'embedded-extension:';
@@ -341,7 +343,9 @@ export async function readFolder(directory: FileSystemDirectoryHandle, storage:
341
343
  const extensionManifest = validateExtensions(project, embedded);
342
344
  const references = projectAssets(project);
343
345
  const expected = new Set(['project.json', ...references.keys()]);
344
- if (manifest.archiveEntries.length !== expected.size || !sameNames(new Set(manifest.archiveEntries as string[]), expected)) {
346
+ // sb3-toolchain lists the Editor's screen state among the entries; the file itself is not an asset.
347
+ const listed = (manifest.archiveEntries as string[]).filter(name => name !== screenStateEntry);
348
+ if (listed.length !== expected.size || !sameNames(new Set(listed), expected)) {
345
349
  return unsupported('Asset references and archiveEntries do not match');
346
350
  }
347
351
  expected.delete('project.json');