@kubohiroya/turbowarp-plus-editor-project-folder 0.6.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 +24 -2
- package/README.md +18 -2
- package/dist/THIRD_PARTY_NOTICES.md +5 -1
- package/dist/explorer.d.ts +52 -0
- package/dist/explorer.js +1059 -0
- package/dist/folder-registry.d.ts +13 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +390 -621
- package/dist/session.d.ts +11 -3
- package/dist/shared-DlmcdO1_.js +458 -0
- package/dist/source.d.ts +34 -3
- package/package.json +24 -1
- package/src/explorer.tsx +410 -0
- package/src/folder-registry.ts +45 -0
- package/src/index.ts +23 -2
- package/src/session.ts +115 -68
- package/src/source.ts +235 -50
- package/tsconfig.json +2 -1
- package/vite.config.ts +12 -2
package/src/explorer.tsx
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
import * as React from 'react';
|
|
2
|
+
import {asyncDataLoaderFeature, hotkeysCoreFeature, selectionFeature} from '@headless-tree/core';
|
|
3
|
+
import type {ItemInstance} from '@headless-tree/core';
|
|
4
|
+
import {useTree} from '@headless-tree/react/react17';
|
|
5
|
+
import {isObject, manifestFile, projectFile} from './source.js';
|
|
6
|
+
import {followProjectFolder} from './folder-registry.js';
|
|
7
|
+
import type {FollowedFolder} from './folder-registry.js';
|
|
8
|
+
import type {Json, Project} from './source.js';
|
|
9
|
+
|
|
10
|
+
export type ExplorerMark = 'added' | 'modified' | 'deleted' | 'untracked';
|
|
11
|
+
export type ExplorerEntry = {path: string; name: string; kind: 'file' | 'directory'};
|
|
12
|
+
export type ProjectFolderExplorerProps = {
|
|
13
|
+
/** The folder to show: a project folder or a repository root. It is only read. */
|
|
14
|
+
directory: FileSystemDirectoryHandle;
|
|
15
|
+
/** 'ja…' shows Japanese text; anything else shows English. */
|
|
16
|
+
locale?: string;
|
|
17
|
+
/** Extra text for an entry, by path relative to `directory`, such as `assets/<md5>.svg`. */
|
|
18
|
+
descriptions?: ReadonlyMap<string, string>;
|
|
19
|
+
/** Git status for an entry, by path relative to `directory`. */
|
|
20
|
+
marks?: ReadonlyMap<string, ExplorerMark>;
|
|
21
|
+
/** Called when a file is opened with Enter, Space or a click. */
|
|
22
|
+
onOpen?(entry: ExplorerEntry): void;
|
|
23
|
+
/** The tree's accessible name. Defaults to "Project folder". */
|
|
24
|
+
label?: string;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const messages = {
|
|
28
|
+
en: {
|
|
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…',
|
|
31
|
+
failed: 'This folder could not be read.', denied: 'Permission to read this folder was not granted.',
|
|
32
|
+
separator: ', ',
|
|
33
|
+
marks: {added: 'Added', modified: 'Modified', deleted: 'Deleted', untracked: 'Untracked'},
|
|
34
|
+
project: 'Project data', manifest: 'Folder manifest', extensions: 'Embedded extensions',
|
|
35
|
+
assetsDirectory: 'Costume and sound files', extensionsDirectory: 'Extension files',
|
|
36
|
+
costume: (sprite: string, name: string) => `${sprite} · costume ${name}`,
|
|
37
|
+
backdrop: (name: string) => `Stage · backdrop ${name}`,
|
|
38
|
+
sound: (sprite: string, name: string) => `${sprite} · sound ${name}`,
|
|
39
|
+
stageSound: (name: string) => `Stage · sound ${name}`
|
|
40
|
+
},
|
|
41
|
+
ja: {
|
|
42
|
+
label: '作品フォルダ', loading: '読み込んでいます…', empty: 'このフォルダは空です。',
|
|
43
|
+
noFolder: 'プロジェクトフォルダを開くと、ここにファイルを表示します。', open: 'プロジェクトフォルダを開く…',
|
|
44
|
+
failed: 'このフォルダを読み込めません。', denied: 'このフォルダを読む許可がありません。',
|
|
45
|
+
separator: '、',
|
|
46
|
+
marks: {added: '追加', modified: '変更', deleted: '削除', untracked: '未追跡'},
|
|
47
|
+
project: '作品データ', manifest: '作品フォルダの目録', extensions: '埋め込み拡張の一覧',
|
|
48
|
+
assetsDirectory: 'コスチュームと音のファイル', extensionsDirectory: '拡張のファイル',
|
|
49
|
+
costume: (sprite: string, name: string) => `${sprite} のコスチューム ${name}`,
|
|
50
|
+
backdrop: (name: string) => `ステージの背景 ${name}`,
|
|
51
|
+
sound: (sprite: string, name: string) => `${sprite} の音 ${name}`,
|
|
52
|
+
stageSound: (name: string) => `ステージの音 ${name}`
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
const messagesFor = (locale = 'en') => locale.toLowerCase().startsWith('ja') ? messages.ja : messages.en;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Describes the files of a project folder for `ProjectFolderExplorer`'s `descriptions`: the project, manifest and
|
|
59
|
+
* extension files, and each asset file with the costumes and sounds that use it. `folder` is the project folder's
|
|
60
|
+
* path inside the explorer's root ('' when the root is the project folder). Malformed entries are skipped.
|
|
61
|
+
*/
|
|
62
|
+
export function describeProjectFolder(project: Project, locale?: string, {manifest, folder = ''}: {
|
|
63
|
+
manifest?: Json; folder?: string;
|
|
64
|
+
} = {}): Map<string, string> {
|
|
65
|
+
const message = messagesFor(locale);
|
|
66
|
+
const prefix = folder.replace(/^\/+|\/+$/gu, '');
|
|
67
|
+
const at = (name: string) => prefix ? `${prefix}/${name}` : name;
|
|
68
|
+
const assetsDirectory = isObject(manifest) && typeof manifest.assetsDirectory === 'string' && manifest.assetsDirectory ?
|
|
69
|
+
manifest.assetsDirectory.replace(/^\/+|\/+$/gu, '') : 'assets';
|
|
70
|
+
const extensions = isObject(manifest) && typeof manifest.embeddedExtensions === 'string' ?
|
|
71
|
+
manifest.embeddedExtensions : 'embedded-extensions.json';
|
|
72
|
+
const descriptions = new Map<string, string>([
|
|
73
|
+
[at(projectFile), message.project],
|
|
74
|
+
[at(manifestFile), message.manifest],
|
|
75
|
+
[at(extensions), message.extensions],
|
|
76
|
+
[at(assetsDirectory), message.assetsDirectory],
|
|
77
|
+
[at('extensions'), message.extensionsDirectory]
|
|
78
|
+
]);
|
|
79
|
+
const users = new Map<string, string[]>();
|
|
80
|
+
for (const target of Array.isArray(project.targets) ? project.targets : []) {
|
|
81
|
+
if (!isObject(target)) continue;
|
|
82
|
+
const sprite = typeof target.name === 'string' ? target.name : '';
|
|
83
|
+
for (const kind of ['costumes', 'sounds'] as const) {
|
|
84
|
+
const entries = target[kind];
|
|
85
|
+
if (!Array.isArray(entries)) continue;
|
|
86
|
+
for (const entry of entries) {
|
|
87
|
+
if (!isObject(entry) || typeof entry.assetId !== 'string' || typeof entry.dataFormat !== 'string') continue;
|
|
88
|
+
const file = typeof entry.md5ext === 'string' ? entry.md5ext : `${entry.assetId}.${entry.dataFormat}`;
|
|
89
|
+
const name = typeof entry.name === 'string' ? entry.name : '';
|
|
90
|
+
const text = kind === 'costumes' ?
|
|
91
|
+
(target.isStage ? message.backdrop(name) : message.costume(sprite, name)) :
|
|
92
|
+
(target.isStage ? message.stageSound(name) : message.sound(sprite, name));
|
|
93
|
+
const path = at(`${assetsDirectory}/${file}`);
|
|
94
|
+
const list = users.get(path) ?? [];
|
|
95
|
+
if (!list.includes(text)) list.push(text);
|
|
96
|
+
users.set(path, list);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
for (const [path, list] of users) descriptions.set(path, list.join(message.separator));
|
|
101
|
+
return descriptions;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
type Node = {name: string; path: string; kind: 'file' | 'directory' | 'error'; message?: string};
|
|
105
|
+
type Message = typeof messages.en;
|
|
106
|
+
const rootId = '/';
|
|
107
|
+
// '\0' cannot appear in a file name, so the error row never collides with a real entry.
|
|
108
|
+
const errorId = (parent: string) => `${parent}\0error`;
|
|
109
|
+
type IterableDirectory = FileSystemDirectoryHandle & {values(): AsyncIterable<FileSystemHandle>};
|
|
110
|
+
|
|
111
|
+
const failure = (error: unknown, message: Message) =>
|
|
112
|
+
error instanceof DOMException && (error.name === 'NotAllowedError' || error.name === 'SecurityError') ?
|
|
113
|
+
message.denied : message.failed;
|
|
114
|
+
|
|
115
|
+
const prefix = 'twpf-explorer';
|
|
116
|
+
// Colors come from the host's text color, so the tree follows light and dark themes.
|
|
117
|
+
const css = `.${prefix}{font:inherit;color:inherit}
|
|
118
|
+
.${prefix}-item{display:flex;align-items:center;gap:.4em;width:100%;box-sizing:border-box;margin:0;border:0;border-radius:3px;
|
|
119
|
+
padding-block:.15em;padding-inline-end:.4em;background:none;color:inherit;font:inherit;text-align:start;cursor:pointer;white-space:nowrap}
|
|
120
|
+
.${prefix}-item:hover{background:rgba(128,128,128,.12)}
|
|
121
|
+
.${prefix}-item[aria-selected="true"]{background:rgba(128,128,128,.24)}
|
|
122
|
+
.${prefix}-item:focus-visible{outline:2px solid currentColor;outline-offset:-2px}
|
|
123
|
+
.${prefix}-caret{display:inline-block;width:1em;flex:none;text-align:center}
|
|
124
|
+
.${prefix}-icon{display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;flex:none}
|
|
125
|
+
.${prefix}-icon img{width:20px;height:20px;object-fit:contain;border-radius:2px;
|
|
126
|
+
background:repeating-conic-gradient(rgba(128,128,128,.22) 0 25%,transparent 0 50%) 0 0/8px 8px}
|
|
127
|
+
.${prefix}-icon img[hidden]{display:none}
|
|
128
|
+
.${prefix}-name{overflow:hidden;text-overflow:ellipsis}
|
|
129
|
+
.${prefix}-mark{flex:none;font-size:.85em;padding:0 .3em;border:1px solid currentColor;border-radius:3px;opacity:.85}
|
|
130
|
+
.${prefix}-description{overflow:hidden;text-overflow:ellipsis;opacity:.7;font-size:.9em}
|
|
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}`;
|
|
135
|
+
|
|
136
|
+
const indent = (level: number) => ({paddingInlineStart: `${0.25 + level * 1.1}em`});
|
|
137
|
+
|
|
138
|
+
type IconKind = 'folder' | 'folder-open' | 'project' | 'json' | 'image' | 'sound' | 'code' | 'text' | 'file';
|
|
139
|
+
const page = 'M3.5 1.5h6l3 3v10h-9z';
|
|
140
|
+
const corner = 'M9.5 1.5v3h3';
|
|
141
|
+
// 16px outlines drawn with currentColor, so they follow the host's text color.
|
|
142
|
+
const icons: Record<IconKind, string[]> = {
|
|
143
|
+
'folder': ['M1.5 3.5h4l1.5 1.5h7.5v8h-13z'],
|
|
144
|
+
'folder-open': ['M1.5 13V3.5h4l1.5 1.5h6v2', 'M1.5 13l2-6h11l-2 6z'],
|
|
145
|
+
'project': ['M8 1.5l6 3v7l-6 3-6-3v-7z', 'M2 4.5l6 3 6-3', 'M8 7.5v7'],
|
|
146
|
+
'json': [page, corner, 'M7 7c-1 0-1 .6-1 1.4s-.3 1.1-.8 1.1c.5 0 .8.4.8 1.1S6 12 7 12',
|
|
147
|
+
'M9 7c1 0 1 .6 1 1.4s.3 1.1.8 1.1c-.5 0-.8.4-.8 1.1S10 12 9 12'],
|
|
148
|
+
'image': ['M1.5 2.5h13v11h-13z', 'M1.5 11l4-4 3 3 2-2 4 4', 'M12.2 5.5a1.2 1.2 0 1 1-2.4 0a1.2 1.2 0 1 1 2.4 0'],
|
|
149
|
+
'sound': ['M2 6h3l3.5-3v10L5 10H2z', 'M10.5 5.5a3.5 3.5 0 0 1 0 5', 'M12.5 3.5a6.5 6.5 0 0 1 0 9'],
|
|
150
|
+
'code': ['M5.5 4.5L2 8l3.5 3.5', 'M10.5 4.5L14 8l-3.5 3.5', 'M9 3l-2 10'],
|
|
151
|
+
'text': [page, corner, 'M5.5 7.5h5M5.5 9.5h5M5.5 11.5h3'],
|
|
152
|
+
'file': [page, corner]
|
|
153
|
+
};
|
|
154
|
+
const extensionIcons: Record<string, IconKind> = {
|
|
155
|
+
json: 'json', svg: 'image', png: 'image', jpg: 'image', jpeg: 'image', gif: 'image', bmp: 'image', webp: 'image',
|
|
156
|
+
wav: 'sound', mp3: 'sound', ogg: 'sound', js: 'code', mjs: 'code', ts: 'code', md: 'text', txt: 'text'
|
|
157
|
+
};
|
|
158
|
+
const iconFor = (name: string): IconKind => name === projectFile || name === manifestFile ? 'project' :
|
|
159
|
+
extensionIcons[name.slice(name.lastIndexOf('.') + 1).toLowerCase()] ?? 'file';
|
|
160
|
+
// Larger images are left as icons: decoding them for a 20px preview costs more than it shows.
|
|
161
|
+
const thumbnailLimit = 2 * 1024 * 1024;
|
|
162
|
+
type Thumbnail = 'waiting' | 'loading' | 'loaded' | 'skipped' | 'failed';
|
|
163
|
+
|
|
164
|
+
function Icon({kind, path, readFile}: {kind: IconKind; path: string; readFile?: (path: string) => Promise<File>}) {
|
|
165
|
+
const ref = React.useRef<HTMLSpanElement>(null);
|
|
166
|
+
const [state, setState] = React.useState<Thumbnail>('waiting');
|
|
167
|
+
const [url, setUrl] = React.useState<string>();
|
|
168
|
+
// A row keeps its path for its lifetime (rows are keyed by path, and a new directory remounts the tree).
|
|
169
|
+
React.useEffect(() => {
|
|
170
|
+
if (!readFile) return undefined;
|
|
171
|
+
let live = true;
|
|
172
|
+
let created: string | undefined;
|
|
173
|
+
const load = async () => {
|
|
174
|
+
setState('loading');
|
|
175
|
+
try {
|
|
176
|
+
const file = await readFile(path);
|
|
177
|
+
if (!live) return;
|
|
178
|
+
if (file.size > thumbnailLimit) return setState('skipped');
|
|
179
|
+
created = URL.createObjectURL(file);
|
|
180
|
+
setUrl(created);
|
|
181
|
+
} catch {
|
|
182
|
+
if (live) setState('failed');
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
// Only rows that are shown read their file, so a large assets folder does not read every image at once.
|
|
186
|
+
let observer: IntersectionObserver | undefined;
|
|
187
|
+
if (typeof IntersectionObserver === 'function' && ref.current) {
|
|
188
|
+
observer = new IntersectionObserver(entries => {
|
|
189
|
+
if (!entries.some(entry => entry.isIntersecting)) return;
|
|
190
|
+
observer?.disconnect();
|
|
191
|
+
void load();
|
|
192
|
+
});
|
|
193
|
+
observer.observe(ref.current);
|
|
194
|
+
} else {
|
|
195
|
+
void load();
|
|
196
|
+
}
|
|
197
|
+
return () => {
|
|
198
|
+
live = false;
|
|
199
|
+
observer?.disconnect();
|
|
200
|
+
if (created) URL.revokeObjectURL(created);
|
|
201
|
+
};
|
|
202
|
+
}, [path]);
|
|
203
|
+
return (
|
|
204
|
+
<span ref={ref} className={`${prefix}-icon`} aria-hidden="true" data-icon={kind}
|
|
205
|
+
data-thumbnail={readFile ? state : undefined}>
|
|
206
|
+
{state === 'loaded' ? null : (
|
|
207
|
+
<svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="1.2"
|
|
208
|
+
strokeLinecap="round" strokeLinejoin="round" focusable="false">
|
|
209
|
+
{icons[kind].map(d => <path key={d} d={d} />)}
|
|
210
|
+
</svg>
|
|
211
|
+
)}
|
|
212
|
+
{/* An <img> never runs an SVG's scripts, unlike markup inserted into the page. */}
|
|
213
|
+
{url && state !== 'failed' ? (
|
|
214
|
+
<img src={url} alt="" decoding="async" hidden={state !== 'loaded'}
|
|
215
|
+
onLoad={() => setState('loaded')} onError={() => setState('failed')} />
|
|
216
|
+
) : null}
|
|
217
|
+
</span>
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function Explorer({directory, locale, descriptions, marks, onOpen, label}: ProjectFolderExplorerProps) {
|
|
222
|
+
const message = messagesFor(locale);
|
|
223
|
+
const [handles] = React.useState(() => new Map<string, FileSystemDirectoryHandle>([[rootId, directory]]));
|
|
224
|
+
const [files] = React.useState(() => new Map<string, FileSystemFileHandle>());
|
|
225
|
+
const [rootLoaded, setRootLoaded] = React.useState(false);
|
|
226
|
+
const collator = React.useMemo(() => new Intl.Collator(locale, {numeric: true, sensitivity: 'base'}), [locale]);
|
|
227
|
+
|
|
228
|
+
const directoryAt = async (id: string) => {
|
|
229
|
+
let handle = handles.get(id);
|
|
230
|
+
if (handle) return handle;
|
|
231
|
+
handle = directory;
|
|
232
|
+
for (const name of id.split('/')) handle = await handle.getDirectoryHandle(name);
|
|
233
|
+
handles.set(id, handle);
|
|
234
|
+
return handle;
|
|
235
|
+
};
|
|
236
|
+
const readFile = async (path: string) => {
|
|
237
|
+
let handle = files.get(path);
|
|
238
|
+
if (!handle) {
|
|
239
|
+
const parts = path.split('/');
|
|
240
|
+
const name = parts.pop()!;
|
|
241
|
+
handle = await (parts.length ? await directoryAt(parts.join('/')) : directory).getFileHandle(name);
|
|
242
|
+
}
|
|
243
|
+
return handle.getFile();
|
|
244
|
+
};
|
|
245
|
+
const tree = useTree<Node>({
|
|
246
|
+
rootItemId: rootId,
|
|
247
|
+
initialState: {expandedItems: [], selectedItems: [], focusedItem: null},
|
|
248
|
+
getItemName: item => item.getItemData()?.name ?? '',
|
|
249
|
+
isItemFolder: item => item.getItemData()?.kind === 'directory',
|
|
250
|
+
createLoadingItemData: () => ({name: '', path: '', kind: 'file'}),
|
|
251
|
+
onPrimaryAction: item => {
|
|
252
|
+
const data = item.getItemData();
|
|
253
|
+
if (data?.kind === 'file') onOpen?.({path: data.path, name: data.name, kind: 'file'});
|
|
254
|
+
},
|
|
255
|
+
onLoadedChildren: id => {if (id === rootId) setRootLoaded(true);},
|
|
256
|
+
dataLoader: {
|
|
257
|
+
getItem: async id => {
|
|
258
|
+
if (id === rootId) return {name: directory.name, path: '', kind: 'directory'};
|
|
259
|
+
const parts = id.split('/');
|
|
260
|
+
const name = parts.pop()!;
|
|
261
|
+
const parent = parts.length ? await directoryAt(parts.join('/')) : directory;
|
|
262
|
+
try {
|
|
263
|
+
await parent.getDirectoryHandle(name);
|
|
264
|
+
return {name, path: id, kind: 'directory'};
|
|
265
|
+
} catch {
|
|
266
|
+
await parent.getFileHandle(name);
|
|
267
|
+
return {name, path: id, kind: 'file'};
|
|
268
|
+
}
|
|
269
|
+
},
|
|
270
|
+
getChildrenWithData: async id => {
|
|
271
|
+
try {
|
|
272
|
+
const handle = await directoryAt(id);
|
|
273
|
+
const base = id === rootId ? '' : `${id}/`;
|
|
274
|
+
const nodes: Node[] = [];
|
|
275
|
+
for await (const entry of (handle as IterableDirectory).values()) {
|
|
276
|
+
if (entry.kind === 'directory' && entry.name === '.git') continue;
|
|
277
|
+
const path = base + entry.name;
|
|
278
|
+
if (entry.kind === 'directory') handles.set(path, entry as FileSystemDirectoryHandle);
|
|
279
|
+
else files.set(path, entry as FileSystemFileHandle);
|
|
280
|
+
nodes.push({name: entry.name, path, kind: entry.kind});
|
|
281
|
+
}
|
|
282
|
+
nodes.sort((a, b) => (a.kind === 'directory' ? 0 : 1) - (b.kind === 'directory' ? 0 : 1) ||
|
|
283
|
+
collator.compare(a.name, b.name) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
284
|
+
return nodes.map(data => ({id: data.path, data}));
|
|
285
|
+
} catch (error) {
|
|
286
|
+
return [{id: errorId(id), data: {name: failure(error, message), path: '', kind: 'error'}}];
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
},
|
|
290
|
+
features: [asyncDataLoaderFeature, selectionFeature, hotkeysCoreFeature]
|
|
291
|
+
});
|
|
292
|
+
// The React 17 hook of Headless Tree 1.8.0 never marks the tree as mounted, unlike its React 18 hook, so every state
|
|
293
|
+
// update and rebuild would wait forever. Marking it here also runs the rebuild that the hook queued on mount.
|
|
294
|
+
React.useEffect(() => {
|
|
295
|
+
tree.setMounted(true);
|
|
296
|
+
return () => tree.setMounted(false);
|
|
297
|
+
}, [tree]);
|
|
298
|
+
|
|
299
|
+
const renderItem = (item: ItemInstance<Node>) => {
|
|
300
|
+
const data = item.getItemData();
|
|
301
|
+
const level = item.getItemMeta().level;
|
|
302
|
+
const folder = item.isFolder();
|
|
303
|
+
const expanded = folder && item.isExpanded();
|
|
304
|
+
const mark = data && data.kind !== 'error' ? marks?.get(data.path) : undefined;
|
|
305
|
+
const markLabel = mark ? message.marks[mark] : '';
|
|
306
|
+
const description = data && data.kind !== 'error' ? descriptions?.get(data.path) : undefined;
|
|
307
|
+
const icon = !data || data.kind === 'error' ? undefined :
|
|
308
|
+
folder ? (expanded ? 'folder-open' : 'folder') : iconFor(data.name);
|
|
309
|
+
const accessibleName = [item.getItemName(), markLabel, description].filter(Boolean).join(message.separator);
|
|
310
|
+
const rows = [
|
|
311
|
+
<button {...item.getProps()} key={item.getId()} type="button" aria-label={accessibleName}
|
|
312
|
+
className={`${prefix}-item${data?.kind === 'error' ? ` ${prefix}-error` : ''}`} style={indent(level)}
|
|
313
|
+
data-path={data?.path}>
|
|
314
|
+
<span className={`${prefix}-caret`} aria-hidden="true">{folder ? (expanded ? '▾' : '▸') : ''}</span>
|
|
315
|
+
{icon ? <Icon kind={icon} path={data!.path} readFile={icon === 'image' ? readFile : undefined} /> : null}
|
|
316
|
+
<span className={`${prefix}-name`}>{item.getItemName()}</span>
|
|
317
|
+
{markLabel ? <span className={`${prefix}-mark`} aria-hidden="true">{markLabel}</span> : null}
|
|
318
|
+
{description ? <span className={`${prefix}-description`} aria-hidden="true">{description}</span> : null}
|
|
319
|
+
</button>
|
|
320
|
+
];
|
|
321
|
+
if (expanded && item.isLoading()) {
|
|
322
|
+
rows.push(<div key={`${item.getId()}\0loading`} className={`${prefix}-status`} role="status"
|
|
323
|
+
style={indent(level + 1)}>{message.loading}</div>);
|
|
324
|
+
}
|
|
325
|
+
return rows;
|
|
326
|
+
};
|
|
327
|
+
const items = tree.getItems();
|
|
328
|
+
return (
|
|
329
|
+
<div className={prefix}>
|
|
330
|
+
<style>{css}</style>
|
|
331
|
+
<div {...tree.getContainerProps(label ?? message.label)}>
|
|
332
|
+
{items.map(renderItem)}
|
|
333
|
+
</div>
|
|
334
|
+
{items.length ? null : (
|
|
335
|
+
<div className={`${prefix}-status`} role="status">{rootLoaded ? message.empty : message.loading}</div>
|
|
336
|
+
)}
|
|
337
|
+
</div>
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
let nextKey = 0;
|
|
342
|
+
const keys = new WeakMap<FileSystemDirectoryHandle, number>();
|
|
343
|
+
const keyFor = (directory: FileSystemDirectoryHandle) => {
|
|
344
|
+
if (!keys.has(directory)) keys.set(directory, nextKey++);
|
|
345
|
+
return keys.get(directory)!;
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* A read-only tree of a folder for the Editor's side panel, built on Headless Tree. Folders load when expanded, folders
|
|
350
|
+
* sort before files, and `.git` is hidden. Keyboard: arrow keys, Home and End move and expand; Enter or Space opens a
|
|
351
|
+
* file. Needs React 16.14–18 from the host.
|
|
352
|
+
*/
|
|
353
|
+
export function ProjectFolderExplorer(props: ProjectFolderExplorerProps) {
|
|
354
|
+
// A new directory starts a new tree, so cached entries and expanded folders never leak between folders.
|
|
355
|
+
return <Explorer key={keyFor(props.directory)} {...props} />;
|
|
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 = {
|
|
@@ -11,6 +14,7 @@ const messages = {
|
|
|
11
14
|
open: 'Open Project Folder…', save: 'Save to Project Folder',
|
|
12
15
|
replace: 'Replace the open project and discard its unsaved changes?',
|
|
13
16
|
opened: 'Project folder opened.', saved: 'Project folder saved.', unchanged: 'No changes to save.',
|
|
17
|
+
sourceRemoved: (ids: string[]) => `Removed source metadata for replaced extensions: ${ids.join(', ')}. Use sb3-toolchain to fetch the managed sources again if you need to keep their provenance.`,
|
|
14
18
|
conflict: 'The project folder changed outside the editor or is no longer open. Your edits are still in the editor.',
|
|
15
19
|
unsupported: 'This project or edit cannot be saved to a project folder yet.',
|
|
16
20
|
failed: 'Could not access the project folder.',
|
|
@@ -31,6 +35,7 @@ const messages = {
|
|
|
31
35
|
open: 'プロジェクトフォルダを開く…', save: 'プロジェクトフォルダに保存',
|
|
32
36
|
replace: '未保存の変更を破棄して、別の作品を開きますか?',
|
|
33
37
|
opened: 'プロジェクトフォルダを開きました。', saved: 'プロジェクトフォルダに保存しました。', unchanged: '保存する変更はありません。',
|
|
38
|
+
sourceRemoved: (ids: string[]) => `差し替えた拡張機能(${ids.join('、')})の出どころ情報を削除しました。出どころを保つには、sb3-toolchain で拡張機能を取得し直してください。`,
|
|
34
39
|
conflict: '外部でフォルダが変更されたか、作品が切り替わりました。編集中の変更はエディターに残っています。',
|
|
35
40
|
unsupported: 'この作品または編集は、まだプロジェクトフォルダに保存できません。',
|
|
36
41
|
failed: 'プロジェクトフォルダにアクセスできませんでした。',
|
|
@@ -219,7 +224,7 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
|
|
|
219
224
|
notice.remove();
|
|
220
225
|
};
|
|
221
226
|
}
|
|
222
|
-
|
|
227
|
+
const menu: MenuEntry = {
|
|
223
228
|
session,
|
|
224
229
|
open(locale) {
|
|
225
230
|
const message = messageFor(locale);
|
|
@@ -229,16 +234,32 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
|
|
|
229
234
|
},
|
|
230
235
|
save(locale) {
|
|
231
236
|
if (!session.busy) {
|
|
232
|
-
|
|
237
|
+
const message = messageFor(locale);
|
|
238
|
+
void session.save().then(({status, sourceRemoved}) => {
|
|
239
|
+
const detail = sourceRemoved.length ? ` ${message.sourceRemoved(sourceRemoved)}` : '';
|
|
240
|
+
report(message[status] + detail);
|
|
241
|
+
}, error => fail(locale, error)).finally(renderReload);
|
|
233
242
|
renderReload();
|
|
234
243
|
}
|
|
235
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)
|
|
236
251
|
});
|
|
237
252
|
return {
|
|
238
253
|
openDirectory: (...args: Parameters<typeof session.openDirectory>) =>
|
|
239
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;},
|
|
240
260
|
dispose() {
|
|
241
261
|
menus.delete(vm);
|
|
262
|
+
unregister();
|
|
242
263
|
session.dispose();
|
|
243
264
|
stopWatching?.();
|
|
244
265
|
view.clearTimeout(timer);
|