@kubohiroya/turbowarp-plus-editor-project-folder 0.9.3 → 0.10.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 +2 -1
- package/README.md +2 -1
- package/dist/explorer-state.d.ts +22 -0
- package/dist/explorer.js +26 -8
- package/dist/index.d.ts +3 -1
- package/dist/index.js +64 -3
- package/dist/session.d.ts +16 -0
- package/dist/{shared-BqC3-Bzi.js → shared-teFlHQ2X.js} +1 -1
- package/dist/{shared-Dz9dzxQF.js → shared-zlHgCKDG.js} +33 -1
- package/package.json +1 -1
- package/src/explorer-files.ts +2 -1
- package/src/explorer-state.ts +50 -0
- package/src/explorer.tsx +23 -3
- package/src/index.ts +3 -1
- package/src/session.ts +79 -0
package/README.ja.md
CHANGED
|
@@ -10,6 +10,7 @@ TurboWarp Plus Editor で既存の sb3-toolchain v1 の作品フォルダを開
|
|
|
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
14
|
|
|
14
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)
|
|
15
16
|
|
|
@@ -27,7 +28,7 @@ TurboWarp Plus Editor で既存の sb3-toolchain v1 の作品フォルダを開
|
|
|
27
28
|
|
|
28
29
|
`./explorer`(`@kubohiroya/turbowarp-plus-editor-project-folder/explorer`)は、エディターのサイドパネルに置くフォルダのツリーです。[Headless Tree](https://headless-tree.lukasbach.com/) を同梱しています。描画にはホストの React 16.14〜18 を使います(省略可能な peer dependency)。メインの入口は React を使いません。
|
|
29
30
|
|
|
30
|
-
- `ProjectFolderExplorer` は `directory`(作品フォルダまたはリポジトリのルート)を表示します。フォルダは開いたときに読み込み、ファイルより先に並べます。`.git`
|
|
31
|
+
- `ProjectFolderExplorer` は `directory`(作品フォルダまたはリポジトリのルート)を表示します。フォルダは開いたときに読み込み、ファイルより先に並べます。`.git` と `.tw-plus` は表示しません。フォルダーごとの開いたフォルダーと選択中の項目はページの中で保持するので、横のパネルを開き直すと、前と同じツリーに戻ります。矢印キー・Home・End で移動と開閉をします。ファイルで Enter・Space を押すかクリックすると `onOpen({path, name, kind})` を呼びます。props は `directory`、`locale`(`ja…` で日本語、それ以外は英語)、`descriptions` と `marks`(Git の状態: `added`・`modified`・`deleted`・`untracked`、どちらも `directory` からの相対パスがキー)、`onOpen`、`label`(ツリーのアクセシブルな名前)です。読み込めないフォルダは、ツリーの中にメッセージを表示します。
|
|
31
32
|
- `renderProjectFolderExplorer(createElement, {vm, locale, marks})` は、`vm` で開いているプロジェクトフォルダのツリーを Editor の横のパネル向けに描きます。説明はフォルダの `project.source.json` と `sb3-source.json` から作り、保存のたびに読み直します。`marks(directory, update)` はそのフォルダの印を追い、止める関数を返します(Git パッケージの `followChangeMarks` など)。フォルダを開いていないときは **プロジェクトフォルダを開く…** を出し、`vm` にプロジェクトフォルダを組み込んでいないときは何も描きません。`followProjectFolder(vm, listener)` は、組み込んだフォルダと開いているディレクトリの変化を知らせます。
|
|
32
33
|
- 各行には文字色で描いたアイコンが付きます。開いた・閉じたフォルダ、作品データ(`project.source.json`・`sb3-source.json`)、JSON、画像、音、コード(`.js`・`.mjs`・`.ts`)、テキスト(`.md`・`.txt`)、その他のファイルです。画像(`.svg`・`.png`・`.jpg`・`.jpeg`・`.gif`・`.bmp`・`.webp`)は、行が画面に入るとサムネイルを表示します。2 MiB を超えるファイルと読み込めない画像はアイコンのままです。サムネイルは装飾用の `<img>` で、オブジェクト URL は行がなくなると解放します。
|
|
33
34
|
- `describeProjectFolder(project, locale, {manifest, folder})` は `descriptions` を作ります。`project.source.json`・`sb3-source.json`・`embedded-extensions.json` の説明と、各アセットのファイルを使うコスチューム・背景・音を返します。`manifest` から `assetsDirectory` を読みます。`folder` はツリーのルートから見た作品フォルダのパスです。
|
package/README.md
CHANGED
|
@@ -10,6 +10,7 @@ This package opens and saves existing sb3-toolchain v1 project folders in TurboW
|
|
|
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
14
|
|
|
14
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).
|
|
15
16
|
|
|
@@ -21,7 +22,7 @@ Folders can contain embedded extension scripts and custom extension URLs. Openin
|
|
|
21
22
|
|
|
22
23
|
The `./explorer` entry (`@kubohiroya/turbowarp-plus-editor-project-folder/explorer`) is a tree of a folder for the Editor's side panel, built on [Headless Tree](https://headless-tree.lukasbach.com/), which is bundled. It renders with the host's React 16.14–18 (an optional peer dependency); the main entry does not use React.
|
|
23
24
|
|
|
24
|
-
- `ProjectFolderExplorer` shows `directory` (a project folder or a repository root). Folders load when expanded and sort before files, and `.git`
|
|
25
|
+
- `ProjectFolderExplorer` shows `directory` (a project folder or a repository root). Folders load when expanded and sort before files, and `.git` and `.tw-plus` are hidden. The expanded folders and the selected entry of each folder are kept for the page, so the tree comes back as it was when the side panel shows it again. Arrow keys, Home and End move and expand; Enter, Space or a click on a file calls `onOpen({path, name, kind})`. Props: `directory`, `locale` (`ja…` for Japanese, otherwise English), `descriptions` and `marks` (Git status: `added`, `modified`, `deleted` or `untracked`), both keyed by the path relative to `directory`, `onOpen` and `label` (the tree's accessible name). A folder that cannot be read shows a message in the tree.
|
|
25
26
|
- `renderProjectFolderExplorer(createElement, {vm, locale, marks})` renders that explorer on the project folder open for `vm`, for the Editor's side panel, with descriptions from the folder's `project.source.json` and `sb3-source.json` (read again after each save). `marks(directory, update)` follows marks for the directory and returns the function that stops it, such as the Git package's `followChangeMarks`. With no folder open it offers **Open Project Folder…**; it renders nothing while no project folder is mounted for `vm`. `followProjectFolder(vm, listener)` reports the mounted folder and its open directory as they change.
|
|
26
27
|
- Each row has an icon drawn in the text color: an open or closed folder, project data (`project.source.json`, `sb3-source.json`), JSON, image, sound, code (`.js`, `.mjs`, `.ts`), text (`.md`, `.txt`) or another file. Images (`.svg`, `.png`, `.jpg`, `.jpeg`, `.gif`, `.bmp`, `.webp`) show a thumbnail once their row is on screen; files over 2 MiB, and images that cannot be read, keep the icon. Thumbnails are decorative `<img>` elements from object URLs, which are revoked when the row goes away.
|
|
27
28
|
- `describeProjectFolder(project, locale, {manifest, folder})` builds `descriptions`: what `project.source.json`, `sb3-source.json` and `embedded-extensions.json` are, and which costumes, backdrops and sounds use each asset file. `manifest` supplies `assetsDirectory`; `folder` is the project folder's path under the tree's root.
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The expanded folders and the selected entry of each project folder's explorer, for this page. It outlives the
|
|
3
|
+
* explorer, which unmounts whenever the side panel shows another view, so the tree comes back as it was left, and
|
|
4
|
+
* the Editor's screen state reads it from here when a project is saved.
|
|
5
|
+
*/
|
|
6
|
+
export interface ExplorerTreeState {
|
|
7
|
+
/** Folder paths relative to the project folder, such as `assets`. */
|
|
8
|
+
expanded: readonly string[];
|
|
9
|
+
/** The selected entry, a path relative to the project folder. */
|
|
10
|
+
selected?: string;
|
|
11
|
+
}
|
|
12
|
+
/** The folder the Editor keeps its own files in. The explorer and its search leave it out, like `.git`. */
|
|
13
|
+
export declare const editorDirectory = ".tw-plus";
|
|
14
|
+
/** The screen state of the Editor, inside `editorDirectory`. */
|
|
15
|
+
export declare const screenStateFile = "workspace.json";
|
|
16
|
+
export declare const hiddenEntry: (name: string) => boolean;
|
|
17
|
+
/** Read a tree state saved in a file, keeping only well-formed paths. */
|
|
18
|
+
export declare function parseExplorerState(value: unknown): ExplorerTreeState | undefined;
|
|
19
|
+
export declare const readExplorerState: (directory: FileSystemDirectoryHandle) => ExplorerTreeState | undefined;
|
|
20
|
+
/** Remember the tree of `directory`. With `notify`, a mounted explorer of that folder shows it too. */
|
|
21
|
+
export declare function writeExplorerState(directory: FileSystemDirectoryHandle, state: ExplorerTreeState, notify?: boolean): void;
|
|
22
|
+
export declare function subscribeExplorerState(directory: FileSystemDirectoryHandle, listener: (state: ExplorerTreeState) => void): () => void;
|
package/dist/explorer.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { E as
|
|
1
|
+
import { E as projectFile, M as _objectSpread2, N as _asyncIterator, b as isObject, c as subscribeExplorerState, f as projectFolderOverwriteWarning, i as hiddenEntry, l as writeExplorerState, o as readExplorerState, p as FolderError, t as followProjectFolder, x as manifestFile } from "./shared-zlHgCKDG.js";
|
|
2
2
|
import * as React from "react";
|
|
3
3
|
import { useEffect, useState } from "react";
|
|
4
4
|
import { createPortal } from "react-dom";
|
|
@@ -923,7 +923,7 @@ function parentPath(path) {
|
|
|
923
923
|
return path.slice(0, Math.max(0, path.lastIndexOf("/")));
|
|
924
924
|
}
|
|
925
925
|
function validateName(name) {
|
|
926
|
-
if (!name.trim() || name === "." || name === ".." || name
|
|
926
|
+
if (!name.trim() || name === "." || name === ".." || hiddenEntry(name) || /[\\/\u0000]/u.test(name)) throw new ExplorerFileError("invalidName");
|
|
927
927
|
}
|
|
928
928
|
async function resolveExplorerDirectory(root, path) {
|
|
929
929
|
var _await$root$resolve;
|
|
@@ -1420,7 +1420,7 @@ function createFilePreview(directory, documentId, { name, path }, locale, readBa
|
|
|
1420
1420
|
status.textContent = message.large;
|
|
1421
1421
|
return;
|
|
1422
1422
|
}
|
|
1423
|
-
const [bytes, { decodeText, mountTextFile }] = await Promise.all([file.arrayBuffer(), import("./shared-
|
|
1423
|
+
const [bytes, { decodeText, mountTextFile }] = await Promise.all([file.arrayBuffer(), import("./shared-teFlHQ2X.js")]);
|
|
1424
1424
|
if (disposed) return;
|
|
1425
1425
|
const content = decodeText(bytes);
|
|
1426
1426
|
if (content === null) {
|
|
@@ -1822,7 +1822,7 @@ function FileSearch({ directory, query, locale, refreshKey, marks, fileStatuses,
|
|
|
1822
1822
|
const entry = _step.value;
|
|
1823
1823
|
{
|
|
1824
1824
|
if (!current) return;
|
|
1825
|
-
if (entry.name
|
|
1825
|
+
if (hiddenEntry(entry.name)) continue;
|
|
1826
1826
|
const path = base + entry.name;
|
|
1827
1827
|
if (entry.kind === "directory") await walk(entry, path + "/");
|
|
1828
1828
|
else files.push({
|
|
@@ -1895,6 +1895,7 @@ function FileSearch({ directory, query, locale, refreshKey, marks, fileStatuses,
|
|
|
1895
1895
|
}), !index ? /* @__PURE__ */ React.createElement("p", { role: "status" }, message.loading) : index.failed ? /* @__PURE__ */ React.createElement("p", { role: "status" }, message.failed) : !(matches === null || matches === void 0 ? void 0 : matches.length) && /* @__PURE__ */ React.createElement("p", { role: "status" }, message.noMatches));
|
|
1896
1896
|
}
|
|
1897
1897
|
function Explorer({ directory, locale, descriptions, marks, fileStatuses, unsavedPaths, refreshKey, onOpen, label, mutate, git, isCurrent }) {
|
|
1898
|
+
var _remembered$expanded, _remembered$selected;
|
|
1898
1899
|
const message = messagesFor(locale);
|
|
1899
1900
|
const actions = actionMessages(locale);
|
|
1900
1901
|
const [handles] = React.useState(() => /* @__PURE__ */ new Map([[rootId, directory]]));
|
|
@@ -1937,14 +1938,24 @@ function Explorer({ directory, locale, descriptions, marks, fileStatuses, unsave
|
|
|
1937
1938
|
return handle.getFile();
|
|
1938
1939
|
};
|
|
1939
1940
|
const deleted = React.useMemo(() => deletedChildren(deletedPaths(fileStatuses, marks)), [fileStatuses, marks]);
|
|
1941
|
+
const [remembered] = React.useState(() => readExplorerState(directory));
|
|
1942
|
+
const remember = (change) => {
|
|
1943
|
+
var _readExplorerState;
|
|
1944
|
+
const previous = (_readExplorerState = readExplorerState(directory)) !== null && _readExplorerState !== void 0 ? _readExplorerState : { expanded: [] };
|
|
1945
|
+
const next = _objectSpread2(_objectSpread2({}, previous), change);
|
|
1946
|
+
if (!next.selected) delete next.selected;
|
|
1947
|
+
writeExplorerState(directory, next);
|
|
1948
|
+
};
|
|
1940
1949
|
const compareNodes = (a, b) => (a.kind === "directory" ? 0 : 1) - (b.kind === "directory" ? 0 : 1) || collator.compare(a.name, b.name) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
1941
1950
|
const tree = useTree({
|
|
1942
1951
|
rootItemId: rootId,
|
|
1943
1952
|
initialState: {
|
|
1944
|
-
expandedItems: [],
|
|
1945
|
-
selectedItems: [],
|
|
1946
|
-
focusedItem: null
|
|
1953
|
+
expandedItems: [...(_remembered$expanded = remembered === null || remembered === void 0 ? void 0 : remembered.expanded) !== null && _remembered$expanded !== void 0 ? _remembered$expanded : []],
|
|
1954
|
+
selectedItems: (remembered === null || remembered === void 0 ? void 0 : remembered.selected) ? [remembered.selected] : [],
|
|
1955
|
+
focusedItem: (_remembered$selected = remembered === null || remembered === void 0 ? void 0 : remembered.selected) !== null && _remembered$selected !== void 0 ? _remembered$selected : null
|
|
1947
1956
|
},
|
|
1957
|
+
setExpandedItems: (expanded) => remember({ expanded }),
|
|
1958
|
+
setSelectedItems: (selected) => remember({ selected: selected[0] }),
|
|
1948
1959
|
getItemName: (item) => {
|
|
1949
1960
|
var _item$getItemData$nam, _item$getItemData;
|
|
1950
1961
|
return (_item$getItemData$nam = (_item$getItemData = item.getItemData()) === null || _item$getItemData === void 0 ? void 0 : _item$getItemData.name) !== null && _item$getItemData$nam !== void 0 ? _item$getItemData$nam : "";
|
|
@@ -2009,7 +2020,7 @@ function Explorer({ directory, locale, descriptions, marks, fileStatuses, unsave
|
|
|
2009
2020
|
for (var _iterator2 = _asyncIterator(handle.values()), _step2; _iteratorAbruptCompletion2 = !(_step2 = await _iterator2.next()).done; _iteratorAbruptCompletion2 = false) {
|
|
2010
2021
|
const entry = _step2.value;
|
|
2011
2022
|
{
|
|
2012
|
-
if (entry.name
|
|
2023
|
+
if (hiddenEntry(entry.name)) continue;
|
|
2013
2024
|
const path = base + entry.name;
|
|
2014
2025
|
if (entry.kind === "directory") handles.set(path, entry);
|
|
2015
2026
|
else files.set(path, entry);
|
|
@@ -2057,6 +2068,13 @@ function Explorer({ directory, locale, descriptions, marks, fileStatuses, unsave
|
|
|
2057
2068
|
tree.setMounted(true);
|
|
2058
2069
|
return () => tree.setMounted(false);
|
|
2059
2070
|
}, [tree]);
|
|
2071
|
+
React.useEffect(() => subscribeExplorerState(directory, (state) => {
|
|
2072
|
+
var _state$selected;
|
|
2073
|
+
tree.applySubStateUpdate("expandedItems", [...state.expanded]);
|
|
2074
|
+
tree.applySubStateUpdate("selectedItems", state.selected ? [state.selected] : []);
|
|
2075
|
+
tree.applySubStateUpdate("focusedItem", (_state$selected = state.selected) !== null && _state$selected !== void 0 ? _state$selected : null);
|
|
2076
|
+
tree.rebuildTree();
|
|
2077
|
+
}), [tree, directory]);
|
|
2060
2078
|
const lastRefresh = React.useRef({
|
|
2061
2079
|
refreshKey,
|
|
2062
2080
|
deleted
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { FolderHost, FolderVM } from './session.js';
|
|
2
|
-
export type { Comparison, ComparisonRequest, ComparisonSection, FolderHost, FolderVM, OpenResult } from './session.js';
|
|
2
|
+
export type { Comparison, ComparisonRequest, ComparisonSection, FolderHost, FolderScreenState, FolderVM, OpenResult } from './session.js';
|
|
3
3
|
export type { ReloadTarget } from './block-reload.js';
|
|
4
4
|
export { followProjectFolder } from './folder-registry.js';
|
|
5
5
|
export type { FollowedFolder } from './folder-registry.js';
|
|
@@ -51,3 +51,5 @@ export declare function projectFolderActions(vm: FolderVM, locale?: string): {
|
|
|
51
51
|
detach: () => void;
|
|
52
52
|
} | undefined;
|
|
53
53
|
export declare function renderProjectFolderMenu(createElement: MenuElement, { vm, locale, MenuItem, MenuSection, onRequestClose }: MenuProps): any;
|
|
54
|
+
export { parseExplorerState, readExplorerState, subscribeExplorerState, writeExplorerState } from './explorer-state.js';
|
|
55
|
+
export type { ExplorerTreeState } from './explorer-state.js';
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { A as unsupported, C as planExtensionSave, D as readFolder, E as projectFile, M as _objectSpread2, O as readFolderUpdate, S as parseProject, T as projectChanges, _ as equal, a as parseExplorerState, b as isObject, c as subscribeExplorerState, d as isProjectFolderEmpty, f as projectFolderOverwriteWarning, g as assetTypeFor, h as assetKey, j as _objectWithoutProperties, k as sameBytes, 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 extensionsFile, w as projectAssets, x as manifestFile, y as fileVersion } from "./shared-zlHgCKDG.js";
|
|
2
2
|
// src/block-reload.ts
|
|
3
3
|
var _excluded$1 = ["targets"];
|
|
4
4
|
var _excluded2$1 = ["targets"];
|
|
@@ -330,6 +330,41 @@ function applyScriptReload(targets, edits, deserialize) {
|
|
|
330
330
|
return prepared.map(({ target }) => target);
|
|
331
331
|
}
|
|
332
332
|
// src/session.ts
|
|
333
|
+
var screenStateMaxBytes = 524288;
|
|
334
|
+
var notFound = (error) => error instanceof DOMException && ["NotFoundError", "TypeMismatchError"].includes(error.name);
|
|
335
|
+
/** The screen state the folder was saved with, or nothing. */
|
|
336
|
+
async function readScreenStateText(directory) {
|
|
337
|
+
try {
|
|
338
|
+
const file = await (await (await directory.getDirectoryHandle(editorDirectory)).getFileHandle(screenStateFile)).getFile();
|
|
339
|
+
return file.size > screenStateMaxBytes ? void 0 : await file.text();
|
|
340
|
+
} catch (error) {
|
|
341
|
+
if (!notFound(error)) console.warn("The screen state of the project folder could not be read", error);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
/** The slices of a screen state, to tell whether only the time of the save changed. */
|
|
345
|
+
var slicesOf = (text) => {
|
|
346
|
+
try {
|
|
347
|
+
return JSON.stringify(JSON.parse(text).slices);
|
|
348
|
+
} catch (_unused) {
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
};
|
|
352
|
+
/** Write the screen state next to the project. Failing to write it never fails the save. */
|
|
353
|
+
async function writeScreenStateText(directory, text) {
|
|
354
|
+
try {
|
|
355
|
+
if (slicesOf(await readScreenStateText(directory)) === slicesOf(text)) return;
|
|
356
|
+
const writable = await (await (await directory.getDirectoryHandle(editorDirectory, { create: true })).getFileHandle(screenStateFile, { create: true })).createWritable();
|
|
357
|
+
try {
|
|
358
|
+
await writable.write(new TextEncoder().encode(text));
|
|
359
|
+
await writable.close();
|
|
360
|
+
} catch (error) {
|
|
361
|
+
await writable.abort().catch(() => {});
|
|
362
|
+
throw error;
|
|
363
|
+
}
|
|
364
|
+
} catch (error) {
|
|
365
|
+
console.warn("The screen state of the project folder could not be saved", error);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
333
368
|
var storageReaders = /* @__PURE__ */ new WeakMap();
|
|
334
369
|
var readerFor = (storage) => {
|
|
335
370
|
const existing = storageReaders.get(storage);
|
|
@@ -350,6 +385,7 @@ function saveManifest(source, added, removed) {
|
|
|
350
385
|
return encodeJson(_objectSpread2(_objectSpread2({}, value), {}, { archiveEntries: [...entries, ...added] }));
|
|
351
386
|
}
|
|
352
387
|
function createFolderSession(vm, host) {
|
|
388
|
+
var _host$screenState, _host$screenState$reg;
|
|
353
389
|
let current = null;
|
|
354
390
|
const listeners = /* @__PURE__ */ new Set();
|
|
355
391
|
const notify = () => {
|
|
@@ -429,6 +465,22 @@ function createFolderSession(vm, host) {
|
|
|
429
465
|
removed: [...source.bytes.keys()].filter((name) => !needed.has(name))
|
|
430
466
|
};
|
|
431
467
|
};
|
|
468
|
+
let expectingTree = false;
|
|
469
|
+
let pendingTree;
|
|
470
|
+
const unregisterTree = (_host$screenState = host.screenState) === null || _host$screenState === void 0 || (_host$screenState$reg = _host$screenState.register) === null || _host$screenState$reg === void 0 ? void 0 : _host$screenState$reg.call(_host$screenState, "projectFolder", {
|
|
471
|
+
capture: () => current ? readExplorerState(current.source.directory) : void 0,
|
|
472
|
+
apply(value) {
|
|
473
|
+
const tree = parseExplorerState(value);
|
|
474
|
+
if (!tree) return;
|
|
475
|
+
if (current) writeExplorerState(current.source.directory, tree, true);
|
|
476
|
+
else if (expectingTree) pendingTree = tree;
|
|
477
|
+
}
|
|
478
|
+
});
|
|
479
|
+
const saveScreenState = async (directory) => {
|
|
480
|
+
var _host$screenState2;
|
|
481
|
+
const text = (_host$screenState2 = host.screenState) === null || _host$screenState2 === void 0 ? void 0 : _host$screenState2.serialize();
|
|
482
|
+
if (text !== void 0) await writeScreenStateText(directory, text);
|
|
483
|
+
};
|
|
432
484
|
const loaded = () => setCurrent(null);
|
|
433
485
|
vm.runtime.on("PROJECT_LOADED", loaded);
|
|
434
486
|
vm.on("PROJECT_CHANGED", changed);
|
|
@@ -442,6 +494,7 @@ function createFolderSession(vm, host) {
|
|
|
442
494
|
editListeners.clear();
|
|
443
495
|
vm.runtime.off("PROJECT_LOADED", loaded);
|
|
444
496
|
vm.off("PROJECT_CHANGED", changed);
|
|
497
|
+
unregisterTree === null || unregisterTree === void 0 || unregisterTree();
|
|
445
498
|
};
|
|
446
499
|
const openFrom = async (getDirectory, confirmReplace, prepare = (directory) => readFolder(directory, vm.runtime.storage), stillCurrent = () => true) => {
|
|
447
500
|
if (disposed || busy) return "cancelled";
|
|
@@ -461,7 +514,10 @@ function createFolderSession(vm, host) {
|
|
|
461
514
|
const assets = source.storageAssets;
|
|
462
515
|
reader.assets = assets;
|
|
463
516
|
let stage;
|
|
517
|
+
pendingTree = void 0;
|
|
518
|
+
expectingTree = true;
|
|
464
519
|
try {
|
|
520
|
+
if (host.screenState) host.screenState.prepareLoad(await readScreenStateText(directory));
|
|
465
521
|
vm.quit();
|
|
466
522
|
await vm.loadProject(source.loadText, { replaceLegacyExtensions: true });
|
|
467
523
|
stage = vm.runtime.getTargetForStage();
|
|
@@ -478,6 +534,9 @@ function createFolderSession(vm, host) {
|
|
|
478
534
|
ids: identify(baseline),
|
|
479
535
|
pending: null
|
|
480
536
|
});
|
|
537
|
+
expectingTree = false;
|
|
538
|
+
if (pendingTree) writeExplorerState(directory, pendingTree, true);
|
|
539
|
+
pendingTree = void 0;
|
|
481
540
|
(_vm$renderer = vm.renderer) === null || _vm$renderer === void 0 || _vm$renderer.draw();
|
|
482
541
|
return "opened";
|
|
483
542
|
} finally {
|
|
@@ -660,7 +719,7 @@ function createFolderSession(vm, host) {
|
|
|
660
719
|
try {
|
|
661
720
|
const file = await (await session.source.directory.getFileHandle(projectFile)).getFile();
|
|
662
721
|
disk = decoder.decode(new Uint8Array(await file.arrayBuffer()));
|
|
663
|
-
} catch (
|
|
722
|
+
} catch (_unused2) {
|
|
664
723
|
disk = null;
|
|
665
724
|
}
|
|
666
725
|
return current === session ? {
|
|
@@ -787,6 +846,7 @@ function createFolderSession(vm, host) {
|
|
|
787
846
|
added.set(name, data);
|
|
788
847
|
}
|
|
789
848
|
if (!result && !removed.length && !extensionSave.removed.length) {
|
|
849
|
+
await saveScreenState(source.directory);
|
|
790
850
|
if (revision === saveRevision) host.onSaved();
|
|
791
851
|
notify();
|
|
792
852
|
return {
|
|
@@ -878,6 +938,7 @@ function createFolderSession(vm, host) {
|
|
|
878
938
|
session.baseline = edited;
|
|
879
939
|
session.ids = ids;
|
|
880
940
|
session.pending = null;
|
|
941
|
+
await saveScreenState(source.directory);
|
|
881
942
|
if (current === session && revision === saveRevision) host.onSaved();
|
|
882
943
|
notify();
|
|
883
944
|
return {
|
|
@@ -1262,4 +1323,4 @@ function renderProjectFolderMenu(createElement, { vm, locale = "en", MenuItem, M
|
|
|
1262
1323
|
};
|
|
1263
1324
|
return createElement(MenuSection, null, item("open"), entry.session.canSave ? item("save") : null);
|
|
1264
1325
|
}
|
|
1265
|
-
export { createProjectFolder, followProjectFolder, mountProjectFolder, projectFolderActions, projectFolderOverwriteWarning, renderProjectFolderMenu };
|
|
1326
|
+
export { createProjectFolder, followProjectFolder, mountProjectFolder, parseExplorerState, projectFolderActions, projectFolderOverwriteWarning, readExplorerState, renderProjectFolderMenu, subscribeExplorerState, writeExplorerState };
|
package/dist/session.d.ts
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
1
|
import type { Asset, Storage } from './source.js';
|
|
2
2
|
import type { ReloadTarget } from './block-reload.js';
|
|
3
3
|
import type { DeserializeBlocks } from './script-reload.js';
|
|
4
|
+
/**
|
|
5
|
+
* The Editor's screen state, such as `installProjectScreenState` of the workbench gives it. A project folder is not
|
|
6
|
+
* an SB3, so the folder keeps the state as `.tw-plus/workspace.json` and gives it back when it opens.
|
|
7
|
+
*/
|
|
8
|
+
export interface FolderScreenState {
|
|
9
|
+
/** The text to write, or nothing to leave the file as it is. */
|
|
10
|
+
serialize(): string | undefined;
|
|
11
|
+
/** Use this text for the next project load. */
|
|
12
|
+
prepareLoad(text: string | undefined): void;
|
|
13
|
+
/** Add a slice, here the explorer's tree. Returns a function that removes it. */
|
|
14
|
+
register?(key: string, slice: {
|
|
15
|
+
capture(): unknown;
|
|
16
|
+
apply?(value: unknown): void;
|
|
17
|
+
}): () => void;
|
|
18
|
+
}
|
|
4
19
|
export interface FolderVM {
|
|
5
20
|
runtime: {
|
|
6
21
|
storage: Storage;
|
|
@@ -51,6 +66,7 @@ export interface FolderHost {
|
|
|
51
66
|
*/
|
|
52
67
|
compareChanges?(request: ComparisonRequest): Promise<string | null>;
|
|
53
68
|
};
|
|
69
|
+
screenState?: FolderScreenState;
|
|
54
70
|
}
|
|
55
71
|
/** A titled comparison of two project.source.json texts; `null` stands for a version that cannot be shown. */
|
|
56
72
|
export type ComparisonSection = {
|
|
@@ -732,6 +732,38 @@ async function createProjectFolder({ directory, files, storage, overwrite = fals
|
|
|
732
732
|
throw error;
|
|
733
733
|
}
|
|
734
734
|
}
|
|
735
|
+
// src/explorer-state.ts
|
|
736
|
+
/** The folder the Editor keeps its own files in. The explorer and its search leave it out, like `.git`. */
|
|
737
|
+
var editorDirectory = ".tw-plus";
|
|
738
|
+
/** The screen state of the Editor, inside `editorDirectory`. */
|
|
739
|
+
var screenStateFile = "workspace.json";
|
|
740
|
+
var hiddenEntry = (name) => [".git", editorDirectory].includes(name.toLowerCase());
|
|
741
|
+
var limit = 1e3;
|
|
742
|
+
var states = /* @__PURE__ */ new WeakMap();
|
|
743
|
+
var listeners = /* @__PURE__ */ new WeakMap();
|
|
744
|
+
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));
|
|
745
|
+
/** Read a tree state saved in a file, keeping only well-formed paths. */
|
|
746
|
+
function parseExplorerState(value) {
|
|
747
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return;
|
|
748
|
+
const { expanded, selected } = value;
|
|
749
|
+
if (!Array.isArray(expanded)) return;
|
|
750
|
+
return _objectSpread2({ expanded: [...new Set(expanded.filter(validPath))].slice(0, limit) }, validPath(selected) && { selected });
|
|
751
|
+
}
|
|
752
|
+
var readExplorerState = (directory) => states.get(directory);
|
|
753
|
+
/** Remember the tree of `directory`. With `notify`, a mounted explorer of that folder shows it too. */
|
|
754
|
+
function writeExplorerState(directory, state, notify = false) {
|
|
755
|
+
var _listeners$get;
|
|
756
|
+
states.set(directory, state);
|
|
757
|
+
if (notify) for (const listener of [...(_listeners$get = listeners.get(directory)) !== null && _listeners$get !== void 0 ? _listeners$get : []]) listener(state);
|
|
758
|
+
}
|
|
759
|
+
function subscribeExplorerState(directory, listener) {
|
|
760
|
+
let set = listeners.get(directory);
|
|
761
|
+
if (!set) listeners.set(directory, set = /* @__PURE__ */ new Set());
|
|
762
|
+
set.add(listener);
|
|
763
|
+
return () => {
|
|
764
|
+
set.delete(listener);
|
|
765
|
+
};
|
|
766
|
+
}
|
|
735
767
|
// src/folder-registry.ts
|
|
736
768
|
var folders = /* @__PURE__ */ new WeakMap();
|
|
737
769
|
var registrations = /* @__PURE__ */ new Set();
|
|
@@ -770,4 +802,4 @@ function followProjectFolder(vm, listener) {
|
|
|
770
802
|
unsubscribe();
|
|
771
803
|
};
|
|
772
804
|
}
|
|
773
|
-
export { unsupported as C,
|
|
805
|
+
export { unsupported as A, planExtensionSave as C, readFolder as D, projectFile as E, _objectSpread2 as M, _asyncIterator as N, readFolderUpdate as O, parseProject as S, projectChanges as T, equal as _, parseExplorerState as a, isObject as b, subscribeExplorerState as c, isProjectFolderEmpty as d, projectFolderOverwriteWarning as f, assetTypeFor as g, assetKey as h, hiddenEntry as i, _objectWithoutProperties as j, sameBytes 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, extensionsFile as v, projectAssets as w, manifestFile as x, fileVersion as y };
|
package/package.json
CHANGED
package/src/explorer-files.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {hiddenEntry} from './explorer-state.js';
|
|
1
2
|
type DirectoryEntries = FileSystemDirectoryHandle & {values(): AsyncIterable<FileSystemHandle>};
|
|
2
3
|
|
|
3
4
|
export class ExplorerFileError extends Error {
|
|
@@ -11,7 +12,7 @@ export function parentPath(path: string) {
|
|
|
11
12
|
}
|
|
12
13
|
|
|
13
14
|
function validateName(name: string) {
|
|
14
|
-
if (!name.trim() || name === '.' || name === '..' || name
|
|
15
|
+
if (!name.trim() || name === '.' || name === '..' || hiddenEntry(name) || /[\\/\u0000]/u.test(name)) {
|
|
15
16
|
throw new ExplorerFileError('invalidName');
|
|
16
17
|
}
|
|
17
18
|
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The expanded folders and the selected entry of each project folder's explorer, for this page. It outlives the
|
|
3
|
+
* explorer, which unmounts whenever the side panel shows another view, so the tree comes back as it was left, and
|
|
4
|
+
* the Editor's screen state reads it from here when a project is saved.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export interface ExplorerTreeState {
|
|
8
|
+
/** Folder paths relative to the project folder, such as `assets`. */
|
|
9
|
+
expanded: readonly string[];
|
|
10
|
+
/** The selected entry, a path relative to the project folder. */
|
|
11
|
+
selected?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** The folder the Editor keeps its own files in. The explorer and its search leave it out, like `.git`. */
|
|
15
|
+
export const editorDirectory = '.tw-plus';
|
|
16
|
+
/** The screen state of the Editor, inside `editorDirectory`. */
|
|
17
|
+
export const screenStateFile = 'workspace.json';
|
|
18
|
+
export const hiddenEntry = (name: string) => ['.git', editorDirectory].includes(name.toLowerCase());
|
|
19
|
+
|
|
20
|
+
const limit = 1000;
|
|
21
|
+
const states = new WeakMap<FileSystemDirectoryHandle, ExplorerTreeState>();
|
|
22
|
+
const listeners = new WeakMap<FileSystemDirectoryHandle, Set<(state: ExplorerTreeState) => void>>();
|
|
23
|
+
|
|
24
|
+
const validPath = (value: unknown): value is string => typeof value === 'string' && value.length > 0 &&
|
|
25
|
+
value.length <= 1024 && value.split('/').every(part => part && part !== '.' && part !== '..' && !hiddenEntry(part) &&
|
|
26
|
+
!/[\\\u0000]/u.test(part));
|
|
27
|
+
|
|
28
|
+
/** Read a tree state saved in a file, keeping only well-formed paths. */
|
|
29
|
+
export function parseExplorerState(value: unknown): ExplorerTreeState | undefined {
|
|
30
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return;
|
|
31
|
+
const {expanded, selected} = value as Record<string, unknown>;
|
|
32
|
+
if (!Array.isArray(expanded)) return;
|
|
33
|
+
return {expanded: [...new Set(expanded.filter(validPath))].slice(0, limit),
|
|
34
|
+
...(validPath(selected) && {selected})};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const readExplorerState = (directory: FileSystemDirectoryHandle) => states.get(directory);
|
|
38
|
+
|
|
39
|
+
/** Remember the tree of `directory`. With `notify`, a mounted explorer of that folder shows it too. */
|
|
40
|
+
export function writeExplorerState(directory: FileSystemDirectoryHandle, state: ExplorerTreeState, notify = false) {
|
|
41
|
+
states.set(directory, state);
|
|
42
|
+
if (notify) for (const listener of [...listeners.get(directory) ?? []]) listener(state);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function subscribeExplorerState(directory: FileSystemDirectoryHandle, listener: (state: ExplorerTreeState) => void) {
|
|
46
|
+
let set = listeners.get(directory);
|
|
47
|
+
if (!set) listeners.set(directory, set = new Set());
|
|
48
|
+
set.add(listener);
|
|
49
|
+
return () => {set.delete(listener);};
|
|
50
|
+
}
|
package/src/explorer.tsx
CHANGED
|
@@ -5,6 +5,8 @@ import {useTree} from '@headless-tree/react/react17';
|
|
|
5
5
|
import {FolderError, isObject, manifestFile, projectFile} from './source.js';
|
|
6
6
|
import {projectFolderOverwriteWarning} from './create-folder.js';
|
|
7
7
|
import {followProjectFolder} from './folder-registry.js';
|
|
8
|
+
import {hiddenEntry, readExplorerState, subscribeExplorerState, writeExplorerState} from './explorer-state.js';
|
|
9
|
+
import type {ExplorerTreeState} from './explorer-state.js';
|
|
8
10
|
import type {ExplorerMutation, FollowedFolder} from './folder-registry.js';
|
|
9
11
|
import type {Json, Project} from './source.js';
|
|
10
12
|
import {canMoveExplorerEntry, copyExplorerFile, createExplorerDirectory, deleteExplorerEntry, ExplorerFileError,
|
|
@@ -327,7 +329,7 @@ function FileSearch({directory, query, locale, refreshKey, marks, fileStatuses,
|
|
|
327
329
|
try {
|
|
328
330
|
for await (const entry of (folder as IterableDirectory).values()) {
|
|
329
331
|
if (!current) return;
|
|
330
|
-
if (entry.name
|
|
332
|
+
if (hiddenEntry(entry.name)) continue;
|
|
331
333
|
const path = base + entry.name;
|
|
332
334
|
if (entry.kind === 'directory') await walk(entry as FileSystemDirectoryHandle, path + '/');
|
|
333
335
|
else files.push({path, name: entry.name, kind: 'file'});
|
|
@@ -408,12 +410,23 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
|
|
|
408
410
|
return handle.getFile();
|
|
409
411
|
};
|
|
410
412
|
const deleted = React.useMemo(() => deletedChildren(deletedPaths(fileStatuses, marks)), [fileStatuses, marks]);
|
|
413
|
+
const [remembered] = React.useState(() => readExplorerState(directory));
|
|
414
|
+
const remember = (change: Partial<ExplorerTreeState>) => {
|
|
415
|
+
const previous = readExplorerState(directory) ?? {expanded: []};
|
|
416
|
+
const next = {...previous, ...change};
|
|
417
|
+
if (!next.selected) delete next.selected;
|
|
418
|
+
writeExplorerState(directory, next);
|
|
419
|
+
};
|
|
411
420
|
const compareNodes = (a: ExplorerNode, b: ExplorerNode) =>
|
|
412
421
|
(a.kind === 'directory' ? 0 : 1) - (b.kind === 'directory' ? 0 : 1) ||
|
|
413
422
|
collator.compare(a.name, b.name) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
414
423
|
const tree = useTree<ExplorerNode>({
|
|
415
424
|
rootItemId: rootId,
|
|
416
|
-
|
|
425
|
+
// The tree comes back as it was left, or as the folder's screen state saved it.
|
|
426
|
+
initialState: {expandedItems: [...remembered?.expanded ?? []],
|
|
427
|
+
selectedItems: remembered?.selected ? [remembered.selected] : [], focusedItem: remembered?.selected ?? null},
|
|
428
|
+
setExpandedItems: expanded => remember({expanded: expanded as string[]}),
|
|
429
|
+
setSelectedItems: selected => remember({selected: (selected as string[])[0]}),
|
|
417
430
|
getItemName: item => item.getItemData()?.name ?? '',
|
|
418
431
|
isItemFolder: item => item.getItemData()?.kind === 'directory',
|
|
419
432
|
createLoadingItemData: () => ({name: '', path: '', kind: 'file'}),
|
|
@@ -443,7 +456,7 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
|
|
|
443
456
|
try {
|
|
444
457
|
const handle = await directoryAt(id);
|
|
445
458
|
for await (const entry of (handle as IterableDirectory).values()) {
|
|
446
|
-
if (entry.name
|
|
459
|
+
if (hiddenEntry(entry.name)) continue;
|
|
447
460
|
const path = base + entry.name;
|
|
448
461
|
if (entry.kind === 'directory') handles.set(path, entry as FileSystemDirectoryHandle);
|
|
449
462
|
else files.set(path, entry as FileSystemFileHandle);
|
|
@@ -466,6 +479,13 @@ function Explorer({directory, locale, descriptions, marks, fileStatuses, unsaved
|
|
|
466
479
|
tree.setMounted(true);
|
|
467
480
|
return () => tree.setMounted(false);
|
|
468
481
|
}, [tree]);
|
|
482
|
+
// A project opened again with this folder shows the tree its screen state saved.
|
|
483
|
+
React.useEffect(() => subscribeExplorerState(directory, state => {
|
|
484
|
+
tree.applySubStateUpdate('expandedItems', [...state.expanded]);
|
|
485
|
+
tree.applySubStateUpdate('selectedItems', state.selected ? [state.selected] : []);
|
|
486
|
+
tree.applySubStateUpdate('focusedItem', state.selected ?? null);
|
|
487
|
+
tree.rebuildTree();
|
|
488
|
+
}), [tree, directory]);
|
|
469
489
|
const lastRefresh = React.useRef({refreshKey, deleted});
|
|
470
490
|
React.useEffect(() => {
|
|
471
491
|
const previous = lastRefresh.current;
|
package/src/index.ts
CHANGED
|
@@ -4,7 +4,7 @@ import {isProjectFolderEmpty} from './create-folder.js';
|
|
|
4
4
|
import {registerFolder} from './folder-registry.js';
|
|
5
5
|
import type {FolderHost, FolderVM, PickerWindow} from './session.js';
|
|
6
6
|
|
|
7
|
-
export type {Comparison, ComparisonRequest, ComparisonSection, FolderHost, FolderVM, OpenResult} from './session.js';
|
|
7
|
+
export type {Comparison, ComparisonRequest, ComparisonSection, FolderHost, FolderScreenState, FolderVM, OpenResult} from './session.js';
|
|
8
8
|
export type {ReloadTarget} from './block-reload.js';
|
|
9
9
|
export {followProjectFolder} from './folder-registry.js';
|
|
10
10
|
export type {FollowedFolder} from './folder-registry.js';
|
|
@@ -333,3 +333,5 @@ export function renderProjectFolderMenu(createElement: MenuElement, {
|
|
|
333
333
|
};
|
|
334
334
|
return createElement(MenuSection, null, item('open'), entry.session.canSave ? item('save') : null);
|
|
335
335
|
}
|
|
336
|
+
export {parseExplorerState, readExplorerState, subscribeExplorerState, writeExplorerState} from './explorer-state.js';
|
|
337
|
+
export type {ExplorerTreeState} from './explorer-state.js';
|
package/src/session.ts
CHANGED
|
@@ -6,6 +6,58 @@ import type {ReloadTarget} from './block-reload.js';
|
|
|
6
6
|
import {applyScriptReload, planScriptReload} from './script-reload.js';
|
|
7
7
|
import type {DeserializeBlocks, ScriptReloadTarget} from './script-reload.js';
|
|
8
8
|
import {createProjectFolder} from './create-folder.js';
|
|
9
|
+
import {editorDirectory, parseExplorerState, readExplorerState, screenStateFile, writeExplorerState} from './explorer-state.js';
|
|
10
|
+
import type {ExplorerTreeState} from './explorer-state.js';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The Editor's screen state, such as `installProjectScreenState` of the workbench gives it. A project folder is not
|
|
14
|
+
* an SB3, so the folder keeps the state as `.tw-plus/workspace.json` and gives it back when it opens.
|
|
15
|
+
*/
|
|
16
|
+
export interface FolderScreenState {
|
|
17
|
+
/** The text to write, or nothing to leave the file as it is. */
|
|
18
|
+
serialize(): string | undefined;
|
|
19
|
+
/** Use this text for the next project load. */
|
|
20
|
+
prepareLoad(text: string | undefined): void;
|
|
21
|
+
/** Add a slice, here the explorer's tree. Returns a function that removes it. */
|
|
22
|
+
register?(key: string, slice: {capture(): unknown; apply?(value: unknown): void}): () => void;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const screenStateMaxBytes = 512 * 1024;
|
|
26
|
+
const notFound = (error: unknown) => error instanceof DOMException && ['NotFoundError', 'TypeMismatchError'].includes(error.name);
|
|
27
|
+
|
|
28
|
+
/** The screen state the folder was saved with, or nothing. */
|
|
29
|
+
async function readScreenStateText(directory: FileSystemDirectoryHandle) {
|
|
30
|
+
try {
|
|
31
|
+
const file = await (await (await directory.getDirectoryHandle(editorDirectory)).getFileHandle(screenStateFile)).getFile();
|
|
32
|
+
return file.size > screenStateMaxBytes ? undefined : await file.text();
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (!notFound(error)) console.warn('The screen state of the project folder could not be read', error);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The slices of a screen state, to tell whether only the time of the save changed. */
|
|
39
|
+
const slicesOf = (text: string | undefined) => {
|
|
40
|
+
try { return JSON.stringify(JSON.parse(text!).slices); } catch { return undefined; }
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/** Write the screen state next to the project. Failing to write it never fails the save. */
|
|
44
|
+
async function writeScreenStateText(directory: FileSystemDirectoryHandle, text: string) {
|
|
45
|
+
try {
|
|
46
|
+
if (slicesOf(await readScreenStateText(directory)) === slicesOf(text)) return;
|
|
47
|
+
const handle = await (await directory.getDirectoryHandle(editorDirectory, {create: true}))
|
|
48
|
+
.getFileHandle(screenStateFile, {create: true});
|
|
49
|
+
const writable = await handle.createWritable();
|
|
50
|
+
try {
|
|
51
|
+
await writable.write(new TextEncoder().encode(text));
|
|
52
|
+
await writable.close();
|
|
53
|
+
} catch (error) {
|
|
54
|
+
await writable.abort().catch(() => {});
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
} catch (error) {
|
|
58
|
+
console.warn('The screen state of the project folder could not be saved', error);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
9
61
|
|
|
10
62
|
export interface FolderVM {
|
|
11
63
|
runtime: {
|
|
@@ -61,6 +113,7 @@ export interface FolderHost {
|
|
|
61
113
|
*/
|
|
62
114
|
compareChanges?(request: ComparisonRequest): Promise<string | null>;
|
|
63
115
|
};
|
|
116
|
+
screenState?: FolderScreenState;
|
|
64
117
|
}
|
|
65
118
|
|
|
66
119
|
/** A titled comparison of two project.source.json texts; `null` stands for a version that cannot be shown. */
|
|
@@ -170,6 +223,22 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
|
170
223
|
const removed = [...source.bytes.keys()].filter(name => !needed.has(name));
|
|
171
224
|
return {result, extensionSave, added, removed};
|
|
172
225
|
};
|
|
226
|
+
// The explorer's tree from the folder's screen state. It can arrive before or after the folder is current.
|
|
227
|
+
let expectingTree = false;
|
|
228
|
+
let pendingTree: ExplorerTreeState | undefined;
|
|
229
|
+
const unregisterTree = host.screenState?.register?.('projectFolder', {
|
|
230
|
+
capture: () => current ? readExplorerState(current.source.directory) : undefined,
|
|
231
|
+
apply(value) {
|
|
232
|
+
const tree = parseExplorerState(value);
|
|
233
|
+
if (!tree) return;
|
|
234
|
+
if (current) writeExplorerState(current.source.directory, tree, true);
|
|
235
|
+
else if (expectingTree) pendingTree = tree;
|
|
236
|
+
}
|
|
237
|
+
});
|
|
238
|
+
const saveScreenState = async (directory: FileSystemDirectoryHandle) => {
|
|
239
|
+
const text = host.screenState?.serialize();
|
|
240
|
+
if (text !== undefined) await writeScreenStateText(directory, text);
|
|
241
|
+
};
|
|
173
242
|
const loaded = () => setCurrent(null);
|
|
174
243
|
vm.runtime.on('PROJECT_LOADED', loaded);
|
|
175
244
|
vm.on('PROJECT_CHANGED', changed);
|
|
@@ -185,6 +254,7 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
|
185
254
|
editListeners.clear();
|
|
186
255
|
vm.runtime.off('PROJECT_LOADED', loaded);
|
|
187
256
|
vm.off('PROJECT_CHANGED', changed);
|
|
257
|
+
unregisterTree?.();
|
|
188
258
|
};
|
|
189
259
|
const openFrom = async (
|
|
190
260
|
getDirectory: () => Promise<FileSystemDirectoryHandle | null>,
|
|
@@ -209,7 +279,10 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
|
209
279
|
const assets = source.storageAssets;
|
|
210
280
|
reader.assets = assets;
|
|
211
281
|
let stage: object | null;
|
|
282
|
+
pendingTree = undefined;
|
|
283
|
+
expectingTree = true;
|
|
212
284
|
try {
|
|
285
|
+
if (host.screenState) host.screenState.prepareLoad(await readScreenStateText(directory));
|
|
213
286
|
vm.quit();
|
|
214
287
|
await vm.loadProject(source.loadText, {replaceLegacyExtensions: true});
|
|
215
288
|
stage = vm.runtime.getTargetForStage();
|
|
@@ -220,6 +293,10 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
|
220
293
|
host.onOpened(directory.name);
|
|
221
294
|
const baseline = snapshot();
|
|
222
295
|
setCurrent({source, stage, baseline, ids: identify(baseline), pending: null});
|
|
296
|
+
// The tree may come with the load or right after it; once the folder is current, it is written there.
|
|
297
|
+
expectingTree = false;
|
|
298
|
+
if (pendingTree) writeExplorerState(directory, pendingTree, true);
|
|
299
|
+
pendingTree = undefined;
|
|
223
300
|
vm.renderer?.draw();
|
|
224
301
|
return 'opened';
|
|
225
302
|
} finally {
|
|
@@ -489,6 +566,7 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
|
489
566
|
added.set(name, data);
|
|
490
567
|
}
|
|
491
568
|
if (!result && !removed.length && !extensionSave.removed.length) {
|
|
569
|
+
await saveScreenState(source.directory);
|
|
492
570
|
if (revision === saveRevision) host.onSaved();
|
|
493
571
|
notify();
|
|
494
572
|
return {status: 'unchanged', sourceRemoved: []};
|
|
@@ -576,6 +654,7 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
|
576
654
|
session.baseline = edited;
|
|
577
655
|
session.ids = ids;
|
|
578
656
|
session.pending = null;
|
|
657
|
+
await saveScreenState(source.directory);
|
|
579
658
|
if (current === session && revision === saveRevision) host.onSaved();
|
|
580
659
|
notify();
|
|
581
660
|
return {status: 'saved', sourceRemoved: extensionSave.sourceRemoved};
|