@kubohiroya/turbowarp-plus-editor-project-folder 0.7.0 → 0.8.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 +5 -1
- package/README.md +4 -0
- package/dist/explorer.d.ts +15 -0
- package/dist/explorer.js +255 -204
- package/dist/folder-registry.d.ts +13 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +348 -325
- package/dist/session.d.ts +4 -1
- package/dist/{shared-DLcytVOx.js → shared-DlmcdO1_.js} +58 -45
- package/dist/source.d.ts +4 -2
- package/package.json +1 -1
- package/src/explorer.tsx +62 -1
- package/src/folder-registry.ts +45 -0
- package/src/index.ts +16 -1
- package/src/session.ts +28 -8
- package/src/source.ts +26 -30
package/dist/session.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Storage } from './source.js';
|
|
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
4
|
export interface FolderVM {
|
|
@@ -18,6 +18,7 @@ export interface FolderVM {
|
|
|
18
18
|
toJSON(target?: string, options?: {
|
|
19
19
|
allowOptimization: boolean;
|
|
20
20
|
}): string;
|
|
21
|
+
assets?: readonly (Asset | null | undefined)[];
|
|
21
22
|
renderer?: {
|
|
22
23
|
draw(): void;
|
|
23
24
|
};
|
|
@@ -87,6 +88,8 @@ type SaveResult = {
|
|
|
87
88
|
};
|
|
88
89
|
export declare function createFolderSession(vm: FolderVM, host: FolderHost): {
|
|
89
90
|
detach(): void;
|
|
91
|
+
/** Calls `listener` when a folder opens or closes, and after a save. Returns the function that stops it. */
|
|
92
|
+
subscribe(listener: () => void): () => void;
|
|
90
93
|
readonly canSave: boolean;
|
|
91
94
|
readonly busy: boolean;
|
|
92
95
|
readonly reloadState: ReloadState;
|
|
@@ -162,7 +162,10 @@ var C = async (e, t) => (await e.getFileHandle(t)).getFile(), w = (e) => `${e.si
|
|
|
162
162
|
}, O = (e, t) => {
|
|
163
163
|
let n = new Set(t);
|
|
164
164
|
return e.size === n.size && [...e].every((e) => n.has(e));
|
|
165
|
-
}, k = (e, t, n) =>
|
|
165
|
+
}, k = (e, t, n) => {
|
|
166
|
+
var r;
|
|
167
|
+
return t === "fonts" ? (r = e.AssetType.Font) == null ? v("The editor does not support font assets") : r : t === "sounds" ? e.AssetType.Sound : n === "svg" ? e.AssetType.ImageVector : e.AssetType.ImageBitmap;
|
|
168
|
+
}, A = (e, t, n) => `${e.name}/${t}.${n}`, j = (e) => /^[A-Za-z0-9._-]+$/u.test(e) ? `extensions/${e}.js` : v(`Embedded extension ID cannot be used as a filename: ${e}`), M = (e) => typeof e == "string" && e.length > 0 && !/[;,\r\n]/u.test(e), N = (e) => {
|
|
166
169
|
let t = e.extensionURLs === void 0 ? {} : e.extensionURLs;
|
|
167
170
|
return !y(t) || Object.values(t).some((e) => typeof e != "string") ? v("Invalid extensionURLs") : t;
|
|
168
171
|
}, P = (e) => {
|
|
@@ -295,43 +298,27 @@ async function V(e, t) {
|
|
|
295
298
|
h
|
|
296
299
|
], a = new Map(await Promise.all(i.map((t) => r(e, t)))), o = new TextDecoder("utf-8", { fatal: !0 }), c = o.decode(a.get(p)), l = S(c), u = b(o.decode(a.get(m))), d = b(o.decode(a.get(h)));
|
|
297
300
|
if (u.formatVersion !== 1 || u.project !== "project.source.json" || u.embeddedExtensions !== "embedded-extensions.json" || u.assetsDirectory !== "assets" || !Array.isArray(u.archiveEntries)) return v("Expected an sb3-toolchain v1 folder");
|
|
298
|
-
if (
|
|
299
|
-
let f = I(l, d), g = /* @__PURE__ */ new Set(["project.json"
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
id: r,
|
|
310
|
-
format: i,
|
|
311
|
-
type: o,
|
|
312
|
-
name: a
|
|
313
|
-
});
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
if (u.archiveEntries.length !== g.size || !O(new Set(u.archiveEntries), g)) return v("Asset references and archiveEntries do not match");
|
|
317
|
-
g.delete("project.json");
|
|
318
|
-
let [E, k] = await Promise.all([e.getDirectoryHandle("assets"), e.getDirectoryHandle("extensions")]), j = F(f.extensions);
|
|
319
|
-
if (!O(await D(E), g) || !O(await D(k), j)) return v("Unexpected or missing source files");
|
|
320
|
-
let M = new Map(await Promise.all([...g].map((e) => r(E, e, "assets/")))), P = new Map(await Promise.all(j.map((e) => r(k, e, "extensions/")))), R = f.extensions.length ? JSON.stringify(s(s({}, l), {}, { extensionURLs: s(s({}, N(l)), Object.fromEntries(f.extensions.map((e) => [e.id, L(e, P.get(`${e.id}.js`))]))) })) : c, z = /* @__PURE__ */ new Map();
|
|
321
|
-
for (let [e, { id: n, format: r, type: i, name: a }] of _) {
|
|
322
|
-
let o = t.createAsset(i, r, M.get(a).slice(), null, !0);
|
|
323
|
-
if (o.assetId !== n) return v(`Asset hash mismatch: ${a}`);
|
|
324
|
-
z.set(e, o);
|
|
301
|
+
if (l.turboWarpPlus !== void 0) return v("Plus extension manifests are not supported in project folders");
|
|
302
|
+
let f = I(l, d), g = J(l), _ = /* @__PURE__ */ new Set(["project.json", ...g.keys()]);
|
|
303
|
+
if (u.archiveEntries.length !== _.size || !O(new Set(u.archiveEntries), _)) return v("Asset references and archiveEntries do not match");
|
|
304
|
+
_.delete("project.json");
|
|
305
|
+
let [y, x] = await Promise.all([e.getDirectoryHandle("assets"), e.getDirectoryHandle("extensions")]), E = F(f.extensions);
|
|
306
|
+
if (!O(await D(y), _) || !O(await D(x), E)) return v("Unexpected or missing source files");
|
|
307
|
+
let j = new Map(await Promise.all([..._].map((e) => r(y, e, "assets/")))), M = new Map(await Promise.all(E.map((e) => r(x, e, "extensions/")))), P = f.extensions.length ? JSON.stringify(s(s({}, l), {}, { extensionURLs: s(s({}, N(l)), Object.fromEntries(f.extensions.map((e) => [e.id, L(e, M.get(`${e.id}.js`))]))) })) : c, R = /* @__PURE__ */ new Map();
|
|
308
|
+
for (let [e, n] of g) {
|
|
309
|
+
let [r, i] = e.split("."), a = k(t, n, i), o = t.createAsset(a, i, j.get(e).slice(), null, !0);
|
|
310
|
+
if (o.assetId !== r) return v(`Asset hash mismatch: ${e}`);
|
|
311
|
+
R.set(A(a, r, i), o);
|
|
325
312
|
}
|
|
326
313
|
return {
|
|
327
314
|
versions: n,
|
|
328
315
|
files: a,
|
|
329
316
|
directory: e,
|
|
330
|
-
bytes:
|
|
331
|
-
extensionBytes:
|
|
317
|
+
bytes: j,
|
|
318
|
+
extensionBytes: M,
|
|
332
319
|
project: l,
|
|
333
|
-
loadText:
|
|
334
|
-
storageAssets:
|
|
320
|
+
loadText: P,
|
|
321
|
+
storageAssets: R,
|
|
335
322
|
embedded: f
|
|
336
323
|
};
|
|
337
324
|
}
|
|
@@ -397,24 +384,31 @@ var G = (e, t) => {
|
|
|
397
384
|
for (let e of Object.keys(n)) Object.hasOwn(t, e) || (r[e] = n[e]);
|
|
398
385
|
return r;
|
|
399
386
|
}, J = (e) => {
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
387
|
+
var t;
|
|
388
|
+
let n = /* @__PURE__ */ new Map();
|
|
389
|
+
for (let t of e.targets) for (let e of ["costumes", "sounds"]) {
|
|
390
|
+
var r;
|
|
391
|
+
let i = (r = t[e]) == null ? [] : r;
|
|
404
392
|
if (!Array.isArray(i)) return v("Invalid asset list");
|
|
405
|
-
for (let
|
|
406
|
-
if (!y(
|
|
407
|
-
if (!(e === "sounds" ? /^(wav|mp3)$/u.test(
|
|
408
|
-
|
|
393
|
+
for (let t of i) {
|
|
394
|
+
if (!y(t) || typeof t.assetId != "string" || !/^[a-f0-9]{32}$/u.test(t.assetId) || typeof t.dataFormat != "string" || t.md5ext !== `${t.assetId}.${t.dataFormat}`) return v("Invalid asset reference");
|
|
395
|
+
if (!(e === "sounds" ? /^(wav|mp3)$/u.test(t.dataFormat) : /^(svg|png|bmp|jpg|jpeg|gif)$/u.test(t.dataFormat))) return v(`Unsupported asset reference: ${t.md5ext}`);
|
|
396
|
+
n.set(t.md5ext, e);
|
|
409
397
|
}
|
|
410
398
|
}
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
399
|
+
let i = (t = e.customFonts) == null ? [] : t;
|
|
400
|
+
if (!Array.isArray(i)) return v("Invalid customFonts list");
|
|
401
|
+
for (let e of i) if (y(e) && e.system === !1 && e.md5ext !== void 0) {
|
|
402
|
+
if (typeof e.md5ext != "string" || !/^[a-f0-9]{32}\.(ttf|otf|woff2?)$/u.test(e.md5ext)) return v("Invalid font asset reference");
|
|
403
|
+
n.set(e.md5ext, "fonts");
|
|
404
|
+
}
|
|
405
|
+
return n;
|
|
406
|
+
};
|
|
407
|
+
function Y(e, t, n, r) {
|
|
414
408
|
var i, a;
|
|
415
409
|
let o = (i = r == null ? void 0 : r.before) == null ? t.targets.map(x) : i, s = (a = r == null ? void 0 : r.after) == null ? n.targets.map(x) : a;
|
|
416
410
|
if (o.length !== t.targets.length || s.length !== n.targets.length) return v("The targets could not be identified");
|
|
417
|
-
if (J(n),
|
|
411
|
+
if (J(n), n.turboWarpPlus !== void 0) return v("Plus extension manifests are not saved to a project folder");
|
|
418
412
|
if (G(t, n) && G([...o], [...s])) return null;
|
|
419
413
|
let { targets: c } = e, p = l(e, u), { targets: m } = t, h = l(t, d), { targets: g } = n, _ = l(n, f), y = new Map(c.map((e) => [x(e), e])), b = new Map(m.map((e, t) => [o[t], e])), S = g.map((e, t) => {
|
|
420
414
|
let n = b.get(s[t]);
|
|
@@ -442,4 +436,23 @@ function X(e, t, n, r) {
|
|
|
442
436
|
for (let e of Object.keys(w)) Object.hasOwn(T, e) || (T[e] = w[e]);
|
|
443
437
|
return T;
|
|
444
438
|
}
|
|
445
|
-
|
|
439
|
+
// src/folder-registry.ts
|
|
440
|
+
var X = /* @__PURE__ */ new WeakMap(), Z = /* @__PURE__ */ new Set(), Q = () => {
|
|
441
|
+
for (let e of [...Z]) e();
|
|
442
|
+
};
|
|
443
|
+
function $(e, t) {
|
|
444
|
+
return X.set(e, t), Q(), () => {
|
|
445
|
+
X.get(e) === t && X.delete(e), Q();
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
function ee(e, t) {
|
|
449
|
+
let n = () => {}, r, i = () => {
|
|
450
|
+
var i;
|
|
451
|
+
let a = X.get(e);
|
|
452
|
+
a !== r && (n(), r = a, n = a ? a.subscribe(() => t(a, a.directory)) : () => {}), t(a, (i = a == null ? void 0 : a.directory) == null ? null : i);
|
|
453
|
+
};
|
|
454
|
+
return Z.add(i), i(), () => {
|
|
455
|
+
Z.delete(i), n();
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
export { e as C, s as S, V as _, A as a, v as b, h as c, m as d, S as f, p as g, Y as h, W as i, w as l, J as m, $ as n, k as o, B as p, _ as r, G as s, ee as t, y as u, U as v, l as x, H as y };
|
package/dist/source.d.ts
CHANGED
|
@@ -34,6 +34,7 @@ export interface Storage {
|
|
|
34
34
|
Sound: AssetType;
|
|
35
35
|
ImageVector: AssetType;
|
|
36
36
|
ImageBitmap: AssetType;
|
|
37
|
+
Font?: AssetType;
|
|
37
38
|
};
|
|
38
39
|
createAsset(type: AssetType, format: string, data: Uint8Array, id: null, generateId: true): Asset;
|
|
39
40
|
addHelper(helper: {
|
|
@@ -54,7 +55,8 @@ export type FolderSource = FolderFiles & {
|
|
|
54
55
|
embedded: ExtensionManifest;
|
|
55
56
|
};
|
|
56
57
|
export declare const fileVersion: (file: File) => string;
|
|
57
|
-
export
|
|
58
|
+
export type AssetKind = 'costumes' | 'sounds' | 'fonts';
|
|
59
|
+
export declare const assetTypeFor: (storage: Storage, kind: AssetKind, format: string) => AssetType;
|
|
58
60
|
export declare const assetKey: (type: AssetType, id: string, format: string) => string;
|
|
59
61
|
type DataUrlMetadata = {
|
|
60
62
|
mediaType: string;
|
|
@@ -93,7 +95,7 @@ export declare function readFolderUpdate(source: FolderSource, previous: FolderU
|
|
|
93
95
|
export declare function assertFolderUnchanged(source: FolderSource): Promise<void>;
|
|
94
96
|
export declare const equal: (left: Json | undefined, right: Json | undefined) => boolean;
|
|
95
97
|
/** The asset files a project refers to, by file name, with the kind of list that refers to each. */
|
|
96
|
-
export declare const projectAssets: (project: Project) => Map<string,
|
|
98
|
+
export declare const projectAssets: (project: Project) => Map<string, AssetKind>;
|
|
97
99
|
/** Runtime ids of the targets, in the order of the project's `targets`, so a renamed sprite stays the same sprite. */
|
|
98
100
|
export type TargetIdentity = {
|
|
99
101
|
before: readonly string[];
|
package/package.json
CHANGED
package/src/explorer.tsx
CHANGED
|
@@ -3,6 +3,8 @@ import {asyncDataLoaderFeature, hotkeysCoreFeature, selectionFeature} from '@hea
|
|
|
3
3
|
import type {ItemInstance} from '@headless-tree/core';
|
|
4
4
|
import {useTree} from '@headless-tree/react/react17';
|
|
5
5
|
import {isObject, manifestFile, projectFile} from './source.js';
|
|
6
|
+
import {followProjectFolder} from './folder-registry.js';
|
|
7
|
+
import type {FollowedFolder} from './folder-registry.js';
|
|
6
8
|
import type {Json, Project} from './source.js';
|
|
7
9
|
|
|
8
10
|
export type ExplorerMark = 'added' | 'modified' | 'deleted' | 'untracked';
|
|
@@ -25,6 +27,7 @@ export type ProjectFolderExplorerProps = {
|
|
|
25
27
|
const messages = {
|
|
26
28
|
en: {
|
|
27
29
|
label: 'Project folder', loading: 'Loading…', empty: 'This folder is empty.',
|
|
30
|
+
noFolder: 'Open a project folder to show its files here.', open: 'Open Project Folder…',
|
|
28
31
|
failed: 'This folder could not be read.', denied: 'Permission to read this folder was not granted.',
|
|
29
32
|
separator: ', ',
|
|
30
33
|
marks: {added: 'Added', modified: 'Modified', deleted: 'Deleted', untracked: 'Untracked'},
|
|
@@ -37,6 +40,7 @@ const messages = {
|
|
|
37
40
|
},
|
|
38
41
|
ja: {
|
|
39
42
|
label: '作品フォルダ', loading: '読み込んでいます…', empty: 'このフォルダは空です。',
|
|
43
|
+
noFolder: 'プロジェクトフォルダを開くと、ここにファイルを表示します。', open: 'プロジェクトフォルダを開く…',
|
|
40
44
|
failed: 'このフォルダを読み込めません。', denied: 'このフォルダを読む許可がありません。',
|
|
41
45
|
separator: '、',
|
|
42
46
|
marks: {added: '追加', modified: '変更', deleted: '削除', untracked: '未追跡'},
|
|
@@ -124,7 +128,10 @@ background:repeating-conic-gradient(rgba(128,128,128,.22) 0 25%,transparent 0 50
|
|
|
124
128
|
.${prefix}-name{overflow:hidden;text-overflow:ellipsis}
|
|
125
129
|
.${prefix}-mark{flex:none;font-size:.85em;padding:0 .3em;border:1px solid currentColor;border-radius:3px;opacity:.85}
|
|
126
130
|
.${prefix}-description{overflow:hidden;text-overflow:ellipsis;opacity:.7;font-size:.9em}
|
|
127
|
-
.${prefix}-status{opacity:.7;font-style:italic;padding-block:.15em}
|
|
131
|
+
.${prefix}-status{opacity:.7;font-style:italic;padding-block:.15em}
|
|
132
|
+
.${prefix}-empty{padding:.5em}
|
|
133
|
+
.${prefix}-empty p{margin:0 0 .6em}
|
|
134
|
+
.${prefix}-empty button{color:inherit;background:transparent;border:1px solid currentColor;border-radius:4px;padding:.2em .6em;font:inherit;cursor:pointer}`;
|
|
128
135
|
|
|
129
136
|
const indent = (level: number) => ({paddingInlineStart: `${0.25 + level * 1.1}em`});
|
|
130
137
|
|
|
@@ -347,3 +354,57 @@ export function ProjectFolderExplorer(props: ProjectFolderExplorerProps) {
|
|
|
347
354
|
// A new directory starts a new tree, so cached entries and expanded folders never leak between folders.
|
|
348
355
|
return <Explorer key={keyFor(props.directory)} {...props} />;
|
|
349
356
|
}
|
|
357
|
+
|
|
358
|
+
/** Follows marks for the files under `directory`, by path relative to it. Returns the function that stops it. */
|
|
359
|
+
export type FollowMarks = (directory: FileSystemDirectoryHandle,
|
|
360
|
+
update: (marks: ReadonlyMap<string, ExplorerMark>) => void) => () => void;
|
|
361
|
+
type FolderViewProps = {vm: object; locale?: string; marks?: FollowMarks};
|
|
362
|
+
|
|
363
|
+
const readJson = async (directory: FileSystemDirectoryHandle, name: string): Promise<Json> =>
|
|
364
|
+
JSON.parse(await (await (await directory.getFileHandle(name)).getFile()).text());
|
|
365
|
+
|
|
366
|
+
function FolderView({vm, locale, marks: followMarks}: FolderViewProps) {
|
|
367
|
+
const message = messagesFor(locale);
|
|
368
|
+
const [{folder, directory, version}, setFollowed] = React.useState<{
|
|
369
|
+
folder?: FollowedFolder; directory: FileSystemDirectoryHandle | null; version: number;
|
|
370
|
+
}>({directory: null, version: 0});
|
|
371
|
+
React.useEffect(() => followProjectFolder(vm, (folder, directory) =>
|
|
372
|
+
setFollowed(previous => ({folder, directory, version: previous.version + 1}))), [vm]);
|
|
373
|
+
// The descriptions come from the folder's project file as last saved, read again after each save.
|
|
374
|
+
const [descriptions, setDescriptions] = React.useState<ReadonlyMap<string, string>>();
|
|
375
|
+
React.useEffect(() => {
|
|
376
|
+
let current = true;
|
|
377
|
+
setDescriptions(undefined);
|
|
378
|
+
if (!directory) return;
|
|
379
|
+
Promise.all([readJson(directory, projectFile), readJson(directory, manifestFile).catch(() => undefined)]).then(([project, manifest]) => {
|
|
380
|
+
if (current && isObject(project)) setDescriptions(describeProjectFolder(project as Project, locale, {manifest}));
|
|
381
|
+
}, () => {});
|
|
382
|
+
return () => {current = false;};
|
|
383
|
+
}, [directory, version, locale]);
|
|
384
|
+
const [marks, setMarks] = React.useState<ReadonlyMap<string, ExplorerMark>>();
|
|
385
|
+
React.useEffect(() => {
|
|
386
|
+
setMarks(undefined);
|
|
387
|
+
if (!directory || !followMarks) return;
|
|
388
|
+
return followMarks(directory, setMarks);
|
|
389
|
+
}, [directory, followMarks]);
|
|
390
|
+
if (!folder) return null;
|
|
391
|
+
if (!directory) {
|
|
392
|
+
return <div className={`${prefix}-empty`}>
|
|
393
|
+
<style>{css}</style>
|
|
394
|
+
<p>{message.noFolder}</p>
|
|
395
|
+
<button type="button" onClick={() => folder.open(locale ?? 'en')}>{message.open}</button>
|
|
396
|
+
</div>;
|
|
397
|
+
}
|
|
398
|
+
return <ProjectFolderExplorer directory={directory} locale={locale} descriptions={descriptions} marks={marks}/>;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Renders the explorer of the project folder open for `vm`, for a side panel of the host: its files with what each is
|
|
403
|
+
* for, and `marks` (such as the Git status) when given. It follows the folder as it opens, closes and saves; with no
|
|
404
|
+
* folder open it offers Open Project Folder…, and it renders nothing while no project folder is mounted for `vm`.
|
|
405
|
+
* Pass the same `marks` function across renders, or the marks are followed again.
|
|
406
|
+
*/
|
|
407
|
+
export function renderProjectFolderExplorer(createElement: (component: any, props: any, ...children: any[]) => any,
|
|
408
|
+
{vm, locale = 'en', marks}: FolderViewProps) {
|
|
409
|
+
return createElement(FolderView, {vm, locale, marks});
|
|
410
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/** The project folder mounted for a VM, as a view of the folder follows it. */
|
|
2
|
+
export interface FollowedFolder {
|
|
3
|
+
readonly directory: FileSystemDirectoryHandle | null;
|
|
4
|
+
subscribe(listener: () => void): () => void;
|
|
5
|
+
/** Asks for a folder and opens it, as the File menu's Open Project Folder… does. */
|
|
6
|
+
open(locale: string): void;
|
|
7
|
+
}
|
|
8
|
+
const folders = new WeakMap<object, FollowedFolder>();
|
|
9
|
+
// Views rendered before the folder is mounted, or after it is disposed, wait for the VM's folder here.
|
|
10
|
+
const registrations = new Set<() => void>();
|
|
11
|
+
const announce = () => {for (const listener of [...registrations]) listener();};
|
|
12
|
+
|
|
13
|
+
export function registerFolder(vm: object, folder: FollowedFolder) {
|
|
14
|
+
folders.set(vm, folder);
|
|
15
|
+
announce();
|
|
16
|
+
return () => {
|
|
17
|
+
if (folders.get(vm) === folder) folders.delete(vm);
|
|
18
|
+
announce();
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Calls `listener` with the project folder mounted for `vm` and the directory open in it, now and whenever a folder is
|
|
24
|
+
* mounted, opened, closed or saved. Returns the function that stops it.
|
|
25
|
+
*/
|
|
26
|
+
export function followProjectFolder(vm: object,
|
|
27
|
+
listener: (folder: FollowedFolder | undefined, directory: FileSystemDirectoryHandle | null) => void) {
|
|
28
|
+
let unsubscribe = () => {};
|
|
29
|
+
let followed: FollowedFolder | undefined;
|
|
30
|
+
const update = () => {
|
|
31
|
+
const folder = folders.get(vm);
|
|
32
|
+
if (folder !== followed) {
|
|
33
|
+
unsubscribe();
|
|
34
|
+
followed = folder;
|
|
35
|
+
unsubscribe = folder ? folder.subscribe(() => listener(folder, folder.directory)) : () => {};
|
|
36
|
+
}
|
|
37
|
+
listener(folder, folder?.directory ?? null);
|
|
38
|
+
};
|
|
39
|
+
registrations.add(update);
|
|
40
|
+
update();
|
|
41
|
+
return () => {
|
|
42
|
+
registrations.delete(update);
|
|
43
|
+
unsubscribe();
|
|
44
|
+
};
|
|
45
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import {FolderError} from './source.js';
|
|
2
2
|
import {createFolderSession} from './session.js';
|
|
3
|
+
import {registerFolder} from './folder-registry.js';
|
|
3
4
|
import type {FolderHost, FolderVM, PickerWindow} from './session.js';
|
|
4
5
|
|
|
5
6
|
export type {Comparison, ComparisonRequest, ComparisonSection, FolderHost, FolderVM, OpenResult} from './session.js';
|
|
6
7
|
export type {ReloadTarget} from './block-reload.js';
|
|
8
|
+
export {followProjectFolder} from './folder-registry.js';
|
|
9
|
+
export type {FollowedFolder} from './folder-registry.js';
|
|
7
10
|
export type {DeserializeBlocks} from './script-reload.js';
|
|
8
11
|
|
|
9
12
|
const messages = {
|
|
@@ -221,7 +224,7 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
|
|
|
221
224
|
notice.remove();
|
|
222
225
|
};
|
|
223
226
|
}
|
|
224
|
-
|
|
227
|
+
const menu: MenuEntry = {
|
|
225
228
|
session,
|
|
226
229
|
open(locale) {
|
|
227
230
|
const message = messageFor(locale);
|
|
@@ -239,12 +242,24 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
|
|
|
239
242
|
renderReload();
|
|
240
243
|
}
|
|
241
244
|
}
|
|
245
|
+
};
|
|
246
|
+
menus.set(vm, menu);
|
|
247
|
+
const unregister = registerFolder(vm, {
|
|
248
|
+
get directory() {return session.directory;},
|
|
249
|
+
subscribe: listener => session.subscribe(listener),
|
|
250
|
+
open: locale => menu.open(locale)
|
|
242
251
|
});
|
|
243
252
|
return {
|
|
244
253
|
openDirectory: (...args: Parameters<typeof session.openDirectory>) =>
|
|
245
254
|
session.openDirectory(...args).finally(renderReload),
|
|
255
|
+
/**
|
|
256
|
+
* The folder the loaded project came from, or `null` once another project loaded or the folder was
|
|
257
|
+
* detached. A host can tell projects apart by it, for example to keep the layout of each one.
|
|
258
|
+
*/
|
|
259
|
+
get directory() {return session.directory;},
|
|
246
260
|
dispose() {
|
|
247
261
|
menus.delete(vm);
|
|
262
|
+
unregister();
|
|
248
263
|
session.dispose();
|
|
249
264
|
stopWatching?.();
|
|
250
265
|
view.clearTimeout(timer);
|
package/src/session.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {assetKey, assetTypeFor, assertFolderUnchanged, extensionsFile, fileVersion, FolderError, manifestFile, parseProject,
|
|
2
2
|
planExtensionSave, projectAssets, projectChanges, projectFile, readFolder, readFolderUpdate, sameBytes, unsupported} from './source.js';
|
|
3
|
-
import type {Asset, FolderSource, FolderUpdate, JsonObject, Project, Storage} from './source.js';
|
|
3
|
+
import type {Asset, AssetKind, FolderSource, FolderUpdate, JsonObject, Project, Storage} from './source.js';
|
|
4
4
|
import {applyBlockReload, planBlockReload} from './block-reload.js';
|
|
5
5
|
import type {ReloadTarget} from './block-reload.js';
|
|
6
6
|
import {applyScriptReload, planScriptReload} from './script-reload.js';
|
|
@@ -19,6 +19,7 @@ export interface FolderVM {
|
|
|
19
19
|
quit(): void;
|
|
20
20
|
loadProject(project: string, options?: {replaceLegacyExtensions: boolean}): Promise<unknown>;
|
|
21
21
|
toJSON(target?: string, options?: {allowOptimization: boolean}): string;
|
|
22
|
+
assets?: readonly (Asset | null | undefined)[];
|
|
22
23
|
renderer?: {draw(): void};
|
|
23
24
|
}
|
|
24
25
|
|
|
@@ -90,6 +91,14 @@ type VMAsset = {assetId: string; dataFormat: string; data?: Uint8Array};
|
|
|
90
91
|
|
|
91
92
|
export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
92
93
|
let current: Session | null = null;
|
|
94
|
+
// Told when a folder opens or closes, and after a save, so a view of the folder can read it again.
|
|
95
|
+
const listeners = new Set<() => void>();
|
|
96
|
+
const notify = () => {for (const listener of [...listeners]) listener();};
|
|
97
|
+
const setCurrent = (session: Session | null) => {
|
|
98
|
+
if (current === session) return;
|
|
99
|
+
current = session;
|
|
100
|
+
notify();
|
|
101
|
+
};
|
|
93
102
|
let busy = false;
|
|
94
103
|
let disposed = false;
|
|
95
104
|
let revision = 0;
|
|
@@ -128,7 +137,10 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
|
128
137
|
}
|
|
129
138
|
};
|
|
130
139
|
// The bytes of an asset the Editor holds, such as a costume added since the folder was opened.
|
|
131
|
-
const assetData = (name: string) => {
|
|
140
|
+
const assetData = (name: string, kind: AssetKind) => {
|
|
141
|
+
if (kind === 'fonts') {
|
|
142
|
+
return vm.assets?.find(asset => asset && `${asset.assetId}.${asset.dataFormat}` === name)?.data;
|
|
143
|
+
}
|
|
132
144
|
for (const target of runtimeTargets()) {
|
|
133
145
|
for (const entry of [...target.sprite?.costumes ?? [], ...target.sprite?.sounds ?? []]) {
|
|
134
146
|
const asset = entry.asset;
|
|
@@ -138,7 +150,7 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
|
138
150
|
return null;
|
|
139
151
|
};
|
|
140
152
|
const changed = () => {revision++;};
|
|
141
|
-
const loaded = () =>
|
|
153
|
+
const loaded = () => setCurrent(null);
|
|
142
154
|
vm.runtime.on('PROJECT_LOADED', loaded);
|
|
143
155
|
vm.on('PROJECT_CHANGED', changed);
|
|
144
156
|
const active = (session: Session) => {
|
|
@@ -148,7 +160,8 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
|
148
160
|
};
|
|
149
161
|
const dispose = () => {
|
|
150
162
|
disposed = true;
|
|
151
|
-
|
|
163
|
+
setCurrent(null);
|
|
164
|
+
listeners.clear();
|
|
152
165
|
vm.runtime.off('PROJECT_LOADED', loaded);
|
|
153
166
|
vm.off('PROJECT_CHANGED', changed);
|
|
154
167
|
};
|
|
@@ -167,7 +180,7 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
|
167
180
|
if (disposed || vm.runtime.getTargetForStage() !== priorStage) return 'cancelled';
|
|
168
181
|
if (host.isProjectDirty() && !confirmReplace()) return 'cancelled';
|
|
169
182
|
host.beforeLoad();
|
|
170
|
-
|
|
183
|
+
setCurrent(null);
|
|
171
184
|
const reader = readerFor(storage);
|
|
172
185
|
const assets = source.storageAssets;
|
|
173
186
|
reader.assets = assets;
|
|
@@ -182,7 +195,7 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
|
182
195
|
if (disposed || !stage || vm.runtime.getTargetForStage() !== stage) return 'cancelled';
|
|
183
196
|
host.onOpened(directory.name);
|
|
184
197
|
const baseline = snapshot();
|
|
185
|
-
|
|
198
|
+
setCurrent({source, stage, baseline, ids: identify(baseline), pending: null});
|
|
186
199
|
vm.renderer?.draw();
|
|
187
200
|
return 'opened';
|
|
188
201
|
} finally {
|
|
@@ -227,7 +240,12 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
|
227
240
|
};
|
|
228
241
|
const canApply = () => !host.isProjectDirty() && !host.blockReload?.isRunning();
|
|
229
242
|
return {
|
|
230
|
-
detach() {
|
|
243
|
+
detach() {setCurrent(null);},
|
|
244
|
+
/** Calls `listener` when a folder opens or closes, and after a save. Returns the function that stops it. */
|
|
245
|
+
subscribe(listener: () => void) {
|
|
246
|
+
listeners.add(listener);
|
|
247
|
+
return () => {listeners.delete(listener);};
|
|
248
|
+
},
|
|
231
249
|
get canSave() {return current !== null;},
|
|
232
250
|
get busy() {return busy;},
|
|
233
251
|
get reloadState() {return reloadState();},
|
|
@@ -363,7 +381,7 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
|
363
381
|
const added = new Map<string, Uint8Array>();
|
|
364
382
|
for (const [name, kind] of needed) {
|
|
365
383
|
if (source.bytes.has(name)) continue;
|
|
366
|
-
const data = assetData(name);
|
|
384
|
+
const data = assetData(name, kind);
|
|
367
385
|
if (!data) return unsupported(`The data of ${name} is not in the Editor`);
|
|
368
386
|
const [id, format] = name.split('.');
|
|
369
387
|
const asset = vm.runtime.storage.createAsset(assetTypeFor(vm.runtime.storage, kind, format), format, data.slice(), null, true);
|
|
@@ -373,6 +391,7 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
|
373
391
|
const removed = [...source.bytes.keys()].filter(name => !needed.has(name));
|
|
374
392
|
if (!result && !removed.length && !extensionSave.removed.length) {
|
|
375
393
|
if (revision === saveRevision) host.onSaved();
|
|
394
|
+
notify();
|
|
376
395
|
return {status: 'unchanged', sourceRemoved: []};
|
|
377
396
|
}
|
|
378
397
|
const encoder = new TextEncoder();
|
|
@@ -466,6 +485,7 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
|
|
|
466
485
|
session.ids = ids;
|
|
467
486
|
session.pending = null;
|
|
468
487
|
if (current === session && revision === saveRevision) host.onSaved();
|
|
488
|
+
notify();
|
|
469
489
|
return {status: 'saved', sourceRemoved: extensionSave.sourceRemoved};
|
|
470
490
|
} finally {
|
|
471
491
|
busy = false;
|
package/src/source.ts
CHANGED
|
@@ -48,7 +48,7 @@ export function parseProject(text: string): Project {
|
|
|
48
48
|
export interface AssetType {name: string}
|
|
49
49
|
export interface Asset {assetId: string; dataFormat: string; data: Uint8Array}
|
|
50
50
|
export interface Storage {
|
|
51
|
-
AssetType: {Sound: AssetType; ImageVector: AssetType; ImageBitmap: AssetType};
|
|
51
|
+
AssetType: {Sound: AssetType; ImageVector: AssetType; ImageBitmap: AssetType; Font?: AssetType};
|
|
52
52
|
createAsset(type: AssetType, format: string, data: Uint8Array, id: null, generateId: true): Asset;
|
|
53
53
|
addHelper(helper: {load(type: AssetType, id: string, format: string): Promise<Asset> | null}, priority: number): void;
|
|
54
54
|
}
|
|
@@ -85,8 +85,13 @@ const sameNames = (actual: Set<string>, expected: Iterable<string>) => {
|
|
|
85
85
|
return actual.size === expectedNames.size && [...actual].every(name => expectedNames.has(name));
|
|
86
86
|
};
|
|
87
87
|
|
|
88
|
-
export
|
|
89
|
-
|
|
88
|
+
export type AssetKind = 'costumes' | 'sounds' | 'fonts';
|
|
89
|
+
|
|
90
|
+
export const assetTypeFor = (storage: Storage, kind: AssetKind, format: string): AssetType => {
|
|
91
|
+
if (kind === 'fonts') return storage.AssetType.Font ?? unsupported('The editor does not support font assets');
|
|
92
|
+
if (kind === 'sounds') return storage.AssetType.Sound;
|
|
93
|
+
return format === 'svg' ? storage.AssetType.ImageVector : storage.AssetType.ImageBitmap;
|
|
94
|
+
};
|
|
90
95
|
export const assetKey = (type: AssetType, id: string, format: string) => `${type.name}/${id}.${format}`;
|
|
91
96
|
|
|
92
97
|
type DataUrlMetadata = {mediaType: string; parameters: string[]; encoding: 'base64' | 'percent'};
|
|
@@ -278,29 +283,10 @@ export async function readFolder(directory: FileSystemDirectoryHandle, storage:
|
|
|
278
283
|
manifest.assetsDirectory !== 'assets' || !Array.isArray(manifest.archiveEntries)) {
|
|
279
284
|
return unsupported('Expected an sb3-toolchain v1 folder');
|
|
280
285
|
}
|
|
281
|
-
if (
|
|
286
|
+
if (project.turboWarpPlus !== undefined) return unsupported('Plus extension manifests are not supported in project folders');
|
|
282
287
|
const extensionManifest = validateExtensions(project, embedded);
|
|
283
|
-
const
|
|
284
|
-
const
|
|
285
|
-
for (const target of project.targets) {
|
|
286
|
-
for (const kind of ['costumes', 'sounds'] as const) {
|
|
287
|
-
const entries = target[kind] ?? [];
|
|
288
|
-
if (!Array.isArray(entries)) return unsupported('Invalid asset list');
|
|
289
|
-
for (const entry of entries) {
|
|
290
|
-
if (!isObject(entry) || typeof entry.assetId !== 'string' || !/^[a-f0-9]{32}$/u.test(entry.assetId) ||
|
|
291
|
-
typeof entry.dataFormat !== 'string') return unsupported('Invalid asset reference');
|
|
292
|
-
const {assetId: id, dataFormat: format} = entry;
|
|
293
|
-
const name = `${id}.${format}`;
|
|
294
|
-
const type = kind === 'sounds' ?
|
|
295
|
-
(/^(wav|mp3)$/u.test(format) ? storage.AssetType.Sound : null) :
|
|
296
|
-
(format === 'svg' ? storage.AssetType.ImageVector :
|
|
297
|
-
(/^(png|bmp|jpg|jpeg|gif)$/u.test(format) ? storage.AssetType.ImageBitmap : null));
|
|
298
|
-
if (!type || entry.md5ext !== name) return unsupported(`Unsupported asset reference: ${name}`);
|
|
299
|
-
expected.add(name);
|
|
300
|
-
references.set(assetKey(type, id, format), {id, format, type, name});
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
}
|
|
288
|
+
const references = projectAssets(project);
|
|
289
|
+
const expected = new Set(['project.json', ...references.keys()]);
|
|
304
290
|
if (manifest.archiveEntries.length !== expected.size || !sameNames(new Set(manifest.archiveEntries as string[]), expected)) {
|
|
305
291
|
return unsupported('Asset references and archiveEntries do not match');
|
|
306
292
|
}
|
|
@@ -318,10 +304,12 @@ export async function readFolder(directory: FileSystemDirectoryHandle, storage:
|
|
|
318
304
|
[entry.id, encodeDataUrl(entry, extensionBytes.get(`${entry.id}.js`)!)]))
|
|
319
305
|
}}) : projectText;
|
|
320
306
|
const storageAssets = new Map<string, Asset>();
|
|
321
|
-
for (const [
|
|
307
|
+
for (const [name, kind] of references) {
|
|
308
|
+
const [id, format] = name.split('.');
|
|
309
|
+
const type = assetTypeFor(storage, kind, format);
|
|
322
310
|
const asset = storage.createAsset(type, format, bytes.get(name)!.slice(), null, true);
|
|
323
311
|
if (asset.assetId !== id) return unsupported(`Asset hash mismatch: ${name}`);
|
|
324
|
-
storageAssets.set(
|
|
312
|
+
storageAssets.set(assetKey(type, id, format), asset);
|
|
325
313
|
}
|
|
326
314
|
return {versions, files, directory, bytes, extensionBytes, project, loadText, storageAssets, embedded: extensionManifest};
|
|
327
315
|
}
|
|
@@ -423,7 +411,7 @@ const applyChanges = (source: Json | undefined, before: Json, after: Json): Json
|
|
|
423
411
|
|
|
424
412
|
/** The asset files a project refers to, by file name, with the kind of list that refers to each. */
|
|
425
413
|
export const projectAssets = (project: Project) => {
|
|
426
|
-
const names = new Map<string,
|
|
414
|
+
const names = new Map<string, AssetKind>();
|
|
427
415
|
for (const target of project.targets) {
|
|
428
416
|
for (const kind of ['costumes', 'sounds'] as const) {
|
|
429
417
|
const entries = target[kind] ?? [];
|
|
@@ -440,9 +428,17 @@ export const projectAssets = (project: Project) => {
|
|
|
440
428
|
}
|
|
441
429
|
}
|
|
442
430
|
}
|
|
431
|
+
const fonts = project.customFonts ?? [];
|
|
432
|
+
if (!Array.isArray(fonts)) return unsupported('Invalid customFonts list');
|
|
433
|
+
for (const font of fonts) {
|
|
434
|
+
if (!isObject(font) || font.system !== false || font.md5ext === undefined) continue;
|
|
435
|
+
if (typeof font.md5ext !== 'string' || !/^[a-f0-9]{32}\.(ttf|otf|woff2?)$/u.test(font.md5ext)) {
|
|
436
|
+
return unsupported('Invalid font asset reference');
|
|
437
|
+
}
|
|
438
|
+
names.set(font.md5ext, 'fonts');
|
|
439
|
+
}
|
|
443
440
|
return names;
|
|
444
441
|
};
|
|
445
|
-
const customContent = (project: Project) => project.turboWarpPlus !== undefined || project.customFonts !== undefined;
|
|
446
442
|
|
|
447
443
|
/** Runtime ids of the targets, in the order of the project's `targets`, so a renamed sprite stays the same sprite. */
|
|
448
444
|
export type TargetIdentity = {before: readonly string[]; after: readonly string[]};
|
|
@@ -460,7 +456,7 @@ export function projectChanges(source: Project, before: Project, after: Project,
|
|
|
460
456
|
return unsupported('The targets could not be identified');
|
|
461
457
|
}
|
|
462
458
|
projectAssets(after);
|
|
463
|
-
if (
|
|
459
|
+
if (after.turboWarpPlus !== undefined) return unsupported('Plus extension manifests are not saved to a project folder');
|
|
464
460
|
if (equal(before, after) && equal([...beforeIds], [...afterIds])) return null;
|
|
465
461
|
const {targets: sourceTargets, ...sourceOther} = source;
|
|
466
462
|
const {targets: beforeTargets, ...beforeOther} = before;
|