@kubohiroya/turbowarp-plus-editor-project-folder 0.0.0-stage → 0.2.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/LICENSE +373 -0
- package/README.ja.md +35 -0
- package/README.md +34 -2
- package/dist/block-reload.d.ts +70 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +783 -0
- package/dist/session.d.ts +74 -0
- package/dist/source.d.ts +64 -0
- package/package.json +33 -4
- package/src/block-reload.ts +145 -0
- package/src/index.ts +239 -0
- package/src/session.ts +277 -0
- package/src/source.ts +256 -0
- package/tsconfig.json +16 -0
- package/vite.config.ts +9 -0
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { Storage } from './source.js';
|
|
2
|
+
import type { ReloadTarget } from './block-reload.js';
|
|
3
|
+
export interface FolderVM {
|
|
4
|
+
runtime: {
|
|
5
|
+
storage: Storage;
|
|
6
|
+
targets?: readonly ReloadTarget[];
|
|
7
|
+
getTargetForStage(): object | null;
|
|
8
|
+
on(event: 'PROJECT_LOADED', listener: () => void): void;
|
|
9
|
+
off(event: 'PROJECT_LOADED', listener: () => void): void;
|
|
10
|
+
};
|
|
11
|
+
on(event: 'PROJECT_CHANGED', listener: () => void): void;
|
|
12
|
+
off(event: 'PROJECT_CHANGED', listener: () => void): void;
|
|
13
|
+
quit(): void;
|
|
14
|
+
loadProject(project: string): Promise<unknown>;
|
|
15
|
+
toJSON(target?: string, options?: {
|
|
16
|
+
allowOptimization: boolean;
|
|
17
|
+
}): string;
|
|
18
|
+
renderer?: {
|
|
19
|
+
draw(): void;
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
type FileSystemPicker = (options: {
|
|
23
|
+
id: string;
|
|
24
|
+
mode: 'readwrite';
|
|
25
|
+
}) => Promise<FileSystemDirectoryHandle>;
|
|
26
|
+
export type PickerWindow = Window & {
|
|
27
|
+
showDirectoryPicker?: FileSystemPicker;
|
|
28
|
+
};
|
|
29
|
+
export interface FolderHost {
|
|
30
|
+
isProjectDirty(): boolean;
|
|
31
|
+
beforeLoad(): void;
|
|
32
|
+
onOpened(title: string): void;
|
|
33
|
+
onSaved(): void;
|
|
34
|
+
blockReload?: {
|
|
35
|
+
isRunning(): boolean;
|
|
36
|
+
subscribe(listener: () => void): () => void;
|
|
37
|
+
onApplied(targets: readonly ReloadTarget[]): void;
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* `ready`: values and positions can be applied in place. `full`: the change needs the whole project reloaded.
|
|
42
|
+
* `waiting`: an external write looks incomplete and is checked again. `dirty`, `running` and `busy` hold the change.
|
|
43
|
+
*/
|
|
44
|
+
export type ReloadState = 'ready' | 'full' | 'waiting' | 'dirty' | 'running' | 'busy' | null;
|
|
45
|
+
/** What the reload command does for the pending change, regardless of whether it may run now. */
|
|
46
|
+
export type ReloadKind = 'partial' | 'full' | null;
|
|
47
|
+
export type OpenResult = 'opened' | 'cancelled';
|
|
48
|
+
export type SaveResult = 'saved' | 'unchanged';
|
|
49
|
+
export declare function createFolderSession(vm: FolderVM, host: FolderHost): {
|
|
50
|
+
detach(): void;
|
|
51
|
+
readonly canSave: boolean;
|
|
52
|
+
readonly busy: boolean;
|
|
53
|
+
readonly reloadState: ReloadState;
|
|
54
|
+
readonly reloadKind: ReloadKind;
|
|
55
|
+
/** A partial change that has stayed the same across two scans and may be applied without asking. */
|
|
56
|
+
readonly canAutoReload: boolean;
|
|
57
|
+
/** True while a change is new or looks incomplete, so a host can look again sooner than its interval. */
|
|
58
|
+
readonly settling: boolean;
|
|
59
|
+
/** Identifies the pending project file version, so a host can attempt an automatic apply only once. */
|
|
60
|
+
readonly pendingVersion: string | null;
|
|
61
|
+
readonly directory: FileSystemDirectoryHandle | null;
|
|
62
|
+
refresh(): Promise<void>;
|
|
63
|
+
reload(): Promise<boolean>;
|
|
64
|
+
/**
|
|
65
|
+
* Reads the open folder again and replaces the project, for changes a partial reload cannot apply. Unsaved
|
|
66
|
+
* edits are discarded only when `confirmReplace` agrees. The VM is left untouched while a project runs.
|
|
67
|
+
*/
|
|
68
|
+
reloadAll(confirmReplace: () => boolean): Promise<OpenResult>;
|
|
69
|
+
open(pick: FileSystemPicker, confirmReplace: () => boolean): Promise<OpenResult>;
|
|
70
|
+
openDirectory(directory: FileSystemDirectoryHandle, confirmReplace: () => boolean): Promise<OpenResult>;
|
|
71
|
+
save(): Promise<SaveResult>;
|
|
72
|
+
dispose: () => void;
|
|
73
|
+
};
|
|
74
|
+
export {};
|
package/dist/source.d.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export type Json = null | boolean | number | string | Json[] | {
|
|
2
|
+
[key: string]: Json;
|
|
3
|
+
};
|
|
4
|
+
export type JsonObject = {
|
|
5
|
+
[key: string]: Json;
|
|
6
|
+
};
|
|
7
|
+
export type Project = JsonObject & {
|
|
8
|
+
targets: Target[];
|
|
9
|
+
};
|
|
10
|
+
type Target = JsonObject & {
|
|
11
|
+
isStage: boolean;
|
|
12
|
+
name: string;
|
|
13
|
+
};
|
|
14
|
+
export declare const projectFile = "project.source.json";
|
|
15
|
+
export declare class FolderError extends Error {
|
|
16
|
+
code: 'conflict' | 'unsupported';
|
|
17
|
+
constructor(code: FolderError['code'], detail?: string);
|
|
18
|
+
}
|
|
19
|
+
export declare const unsupported: (detail: string) => never;
|
|
20
|
+
export declare const isObject: (value: Json | undefined) => value is JsonObject;
|
|
21
|
+
export declare function parseProject(text: string): Project;
|
|
22
|
+
export interface AssetType {
|
|
23
|
+
name: string;
|
|
24
|
+
}
|
|
25
|
+
export interface Asset {
|
|
26
|
+
assetId: string;
|
|
27
|
+
dataFormat: string;
|
|
28
|
+
data: Uint8Array;
|
|
29
|
+
}
|
|
30
|
+
export interface Storage {
|
|
31
|
+
AssetType: {
|
|
32
|
+
Sound: AssetType;
|
|
33
|
+
ImageVector: AssetType;
|
|
34
|
+
ImageBitmap: AssetType;
|
|
35
|
+
};
|
|
36
|
+
createAsset(type: AssetType, format: string, data: Uint8Array, id: null, generateId: true): Asset;
|
|
37
|
+
addHelper(helper: {
|
|
38
|
+
load(type: AssetType, id: string, format: string): Promise<Asset> | null;
|
|
39
|
+
}, priority: number): void;
|
|
40
|
+
}
|
|
41
|
+
type FolderFiles = {
|
|
42
|
+
versions: Map<string, string>;
|
|
43
|
+
files: Map<string, Uint8Array>;
|
|
44
|
+
directory: FileSystemDirectoryHandle;
|
|
45
|
+
bytes: Map<string, Uint8Array>;
|
|
46
|
+
};
|
|
47
|
+
export type FolderSource = FolderFiles & {
|
|
48
|
+
project: Project;
|
|
49
|
+
projectText: string;
|
|
50
|
+
storageAssets: Map<string, Asset>;
|
|
51
|
+
};
|
|
52
|
+
export declare const assetKey: (type: AssetType, id: string, format: string) => string;
|
|
53
|
+
export declare function readFolder(directory: FileSystemDirectoryHandle, storage: Storage): Promise<FolderSource>;
|
|
54
|
+
export type FolderUpdate = {
|
|
55
|
+
version: string;
|
|
56
|
+
bytes: Uint8Array;
|
|
57
|
+
project: Project;
|
|
58
|
+
};
|
|
59
|
+
export type DiskChange = FolderUpdate | 'structure' | 'waiting' | null;
|
|
60
|
+
export declare function readFolderUpdate(source: FolderSource, previous: FolderUpdate | null): Promise<DiskChange>;
|
|
61
|
+
export declare function assertFolderUnchanged(source: FolderSource): Promise<void>;
|
|
62
|
+
export declare const equal: (left: Json | undefined, right: Json | undefined) => boolean;
|
|
63
|
+
export declare function projectChanges(source: Project, before: Project, after: Project): Project | null;
|
|
64
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubohiroya/turbowarp-plus-editor-project-folder",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Read and save expanded Scratch project folders in TurboWarp Plus Editor",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MPL-2.0",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/kubohiroya/turbowarp-plus-editor-project-folder.git"
|
|
10
|
+
},
|
|
11
|
+
"main": "./dist/index.js",
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"default": "./dist/index.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"src",
|
|
22
|
+
"vite.config.ts",
|
|
23
|
+
"tsconfig.json",
|
|
24
|
+
"README.ja.md"
|
|
25
|
+
],
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "vite build && tsc -p tsconfig.json",
|
|
28
|
+
"test": "npm run build && node --test",
|
|
29
|
+
"prepack": "npm run build"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"typescript": "6.0.3",
|
|
33
|
+
"vite": "8.3.5"
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import {equal, isObject, unsupported} from './source.js';
|
|
2
|
+
import type {Json, Project} from './source.js';
|
|
3
|
+
|
|
4
|
+
type Value = string | number | boolean;
|
|
5
|
+
type Point = {x: number; y: number};
|
|
6
|
+
type Field = {value: Value; id?: string | null};
|
|
7
|
+
type Block = {
|
|
8
|
+
id: string; opcode: string; topLevel: boolean; shadow: boolean; isMonitored?: boolean;
|
|
9
|
+
parent?: string; x?: number; y?: number;
|
|
10
|
+
fields: Record<string, Field>;
|
|
11
|
+
inputs: Record<string, {block: string | null; shadow: string | null}>;
|
|
12
|
+
};
|
|
13
|
+
export type ReloadTarget = {
|
|
14
|
+
isStage: boolean; isOriginal: boolean; getName(): string;
|
|
15
|
+
blocks: {
|
|
16
|
+
getBlock(id: string): Block | undefined;
|
|
17
|
+
changeBlock(event: {id: string; element: 'field'; name: string; value: Value}): void;
|
|
18
|
+
moveBlock(event: {id: string; newCoordinate: Point}): void;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
type ScalarChange = {kind: 'field'; name: string; before: Value; after: Value} |
|
|
23
|
+
{kind: 'input'; name: string; connected: string | null; tag: number; before: Value; after: Value};
|
|
24
|
+
type Change = ScalarChange | {kind: 'position'; before: Point; after: Point};
|
|
25
|
+
type BlockChange = Change & {id: string; target: string; stage: boolean; opcode: string};
|
|
26
|
+
|
|
27
|
+
const isValue = (value: Json): value is Value =>
|
|
28
|
+
typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value));
|
|
29
|
+
const literals: Record<number, [string, string]> = {
|
|
30
|
+
4: ['math_number', 'NUM'], 5: ['math_positive_number', 'NUM'], 6: ['math_whole_number', 'NUM'],
|
|
31
|
+
7: ['math_integer', 'NUM'], 8: ['math_angle', 'NUM'], 9: ['colour_picker', 'COLOUR'], 10: ['text', 'TEXT']
|
|
32
|
+
};
|
|
33
|
+
const reject = (): never => unsupported('Only values and coordinates of existing blocks can be reloaded');
|
|
34
|
+
const keysMatch = (before: Record<string, unknown>, after: Record<string, unknown>) =>
|
|
35
|
+
equal(Object.keys(before), Object.keys(after));
|
|
36
|
+
const point = (x: Json, y: Json): Point => {
|
|
37
|
+
if (typeof x !== 'number' || typeof y !== 'number' || !Number.isSafeInteger(x) || !Number.isSafeInteger(y)) return reject();
|
|
38
|
+
return {x, y};
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export function planBlockReload(before: Project, after: Project): BlockChange[] {
|
|
42
|
+
const {targets: oldTargets, ...oldProject} = before;
|
|
43
|
+
const {targets: newTargets, ...newProject} = after;
|
|
44
|
+
if (oldTargets.length !== newTargets.length || !equal(oldProject, newProject)) return reject();
|
|
45
|
+
const edits: BlockChange[] = [];
|
|
46
|
+
for (const [index, oldTarget] of oldTargets.entries()) {
|
|
47
|
+
const {blocks: oldBlocks, ...oldRest} = oldTarget;
|
|
48
|
+
const {blocks: newBlocks, ...newRest} = newTargets[index];
|
|
49
|
+
if (!equal(oldRest, newRest)) return reject();
|
|
50
|
+
if (!isObject(oldBlocks) || !isObject(newBlocks)) {
|
|
51
|
+
if (equal(oldBlocks, newBlocks)) continue;
|
|
52
|
+
return reject();
|
|
53
|
+
}
|
|
54
|
+
if (!keysMatch(oldBlocks, newBlocks)) return reject();
|
|
55
|
+
for (const [id, oldBlock] of Object.entries(oldBlocks)) {
|
|
56
|
+
const newBlock = newBlocks[id];
|
|
57
|
+
if (equal(oldBlock, newBlock)) continue;
|
|
58
|
+
if (!isObject(oldBlock) || !isObject(newBlock)) return reject();
|
|
59
|
+
const {inputs: oldInputs, fields: oldFields, x: oldX, y: oldY, ...oldShape} = oldBlock;
|
|
60
|
+
const {inputs: newInputs, fields: newFields, x: newX, y: newY, ...newShape} = newBlock;
|
|
61
|
+
if (!equal(oldShape, newShape) || typeof oldShape.opcode !== 'string') return reject();
|
|
62
|
+
const common = {id, target: oldTarget.name, stage: oldTarget.isStage, opcode: oldShape.opcode};
|
|
63
|
+
if (oldX !== newX || oldY !== newY) {
|
|
64
|
+
if (oldShape.topLevel !== true) return reject();
|
|
65
|
+
edits.push({...common, kind: 'position', before: point(oldX, oldY), after: point(newX, newY)});
|
|
66
|
+
}
|
|
67
|
+
if (!equal(oldFields, newFields)) {
|
|
68
|
+
if (!isObject(oldFields) || !isObject(newFields) || !keysMatch(oldFields, newFields)) return reject();
|
|
69
|
+
for (const [name, a] of Object.entries(oldFields)) {
|
|
70
|
+
const b = newFields[name];
|
|
71
|
+
if (equal(a, b)) continue;
|
|
72
|
+
if (['VARIABLE', 'LIST', 'BROADCAST_OPTION'].includes(name) || oldShape.opcode === 'sensing_of_object_menu' ||
|
|
73
|
+
!Array.isArray(a) || !Array.isArray(b) || a.length !== 1 || b.length !== 1 ||
|
|
74
|
+
!isValue(a[0]) || !isValue(b[0])) return reject();
|
|
75
|
+
edits.push({...common, kind: 'field', name, before: a[0], after: b[0]});
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (!equal(oldInputs, newInputs)) {
|
|
79
|
+
if (!isObject(oldInputs) || !isObject(newInputs) || !keysMatch(oldInputs, newInputs)) return reject();
|
|
80
|
+
for (const [name, a] of Object.entries(oldInputs)) {
|
|
81
|
+
const b = newInputs[name];
|
|
82
|
+
if (equal(a, b)) continue;
|
|
83
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a[0] !== b[0]) return reject();
|
|
84
|
+
const slot = a[0] === 1 ? 1 : a[0] === 3 && typeof a[1] === 'string' && a[1] === b[1] ? 2 : null;
|
|
85
|
+
if (slot === null || a.length !== slot + 1 || b.length !== slot + 1) return reject();
|
|
86
|
+
const from = a[slot];
|
|
87
|
+
const to = b[slot];
|
|
88
|
+
if (!Array.isArray(from) || !Array.isArray(to) || from.length !== 2 || to.length !== 2 ||
|
|
89
|
+
typeof from[0] !== 'number' || !Object.hasOwn(literals, from[0]) || from[0] !== to[0] ||
|
|
90
|
+
!isValue(from[1]) || !isValue(to[1])) return reject();
|
|
91
|
+
const connected = slot === 2 ? a[1] as string : null;
|
|
92
|
+
edits.push({...common, kind: 'input', name, connected, tag: from[0], before: from[1], after: to[1]});
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return edits;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function applyBlockReload(targets: readonly ReloadTarget[], edits: BlockChange[]) {
|
|
101
|
+
const touched = new Set<ReloadTarget>();
|
|
102
|
+
// Resolve all edits before invoking any VM mutation.
|
|
103
|
+
const operations = edits.map(edit => {
|
|
104
|
+
const matching = targets.filter(target => target.isStage === edit.stage &&
|
|
105
|
+
(edit.stage || target.isOriginal && target.getName() === edit.target));
|
|
106
|
+
if (matching.length !== 1) return reject();
|
|
107
|
+
const target = matching[0];
|
|
108
|
+
const container = target.blocks;
|
|
109
|
+
const parent = container.getBlock(edit.id);
|
|
110
|
+
if (!parent || parent.opcode !== edit.opcode) return reject();
|
|
111
|
+
touched.add(target);
|
|
112
|
+
if (edit.kind === 'position') {
|
|
113
|
+
if (!parent.topLevel || Math.round(parent.x ?? 0) !== edit.before.x || Math.round(parent.y ?? 0) !== edit.before.y) {
|
|
114
|
+
return reject();
|
|
115
|
+
}
|
|
116
|
+
return (direction: 'before' | 'after') => container.moveBlock({id: edit.id, newCoordinate: edit[direction]});
|
|
117
|
+
}
|
|
118
|
+
let block = parent;
|
|
119
|
+
let name = edit.name;
|
|
120
|
+
if (edit.kind === 'input') {
|
|
121
|
+
const input = parent.inputs[edit.name];
|
|
122
|
+
const shadow = input?.shadow;
|
|
123
|
+
if (!shadow || input.block !== (edit.connected ?? shadow)) return reject();
|
|
124
|
+
const literal = container.getBlock(shadow);
|
|
125
|
+
const [opcode, field] = literals[edit.tag];
|
|
126
|
+
if (!literal?.shadow || literal.parent !== parent.id || literal.opcode !== opcode) return reject();
|
|
127
|
+
block = literal;
|
|
128
|
+
name = field;
|
|
129
|
+
}
|
|
130
|
+
const field = block.fields[name];
|
|
131
|
+
if (!field || field.id != null || field.value !== edit.before || block.isMonitored || parent.isMonitored) return reject();
|
|
132
|
+
return (direction: 'before' | 'after') => container.changeBlock({
|
|
133
|
+
id: block.id, element: 'field', name, value: edit[direction]
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
let index = 0;
|
|
137
|
+
try {
|
|
138
|
+
for (; index < operations.length; index++) operations[index]('after');
|
|
139
|
+
} catch (error) {
|
|
140
|
+
// VM events can fail after a mutation. Restore the attempted batch in reverse order.
|
|
141
|
+
for (; index >= 0; index--) operations[index]('before');
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
return [...touched];
|
|
145
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import {FolderError} from './source.js';
|
|
2
|
+
import {createFolderSession} from './session.js';
|
|
3
|
+
import type {FolderHost, FolderVM, PickerWindow} from './session.js';
|
|
4
|
+
|
|
5
|
+
export type {FolderHost, FolderVM, OpenResult} from './session.js';
|
|
6
|
+
export type {ReloadTarget} from './block-reload.js';
|
|
7
|
+
|
|
8
|
+
const messages = {
|
|
9
|
+
en: {
|
|
10
|
+
open: 'Open Project Folder…', save: 'Save to Project Folder',
|
|
11
|
+
replace: 'Replace the open project and discard its unsaved changes?',
|
|
12
|
+
opened: 'Project folder opened.', saved: 'Project folder saved.', unchanged: 'No changes to save.',
|
|
13
|
+
conflict: 'The project folder changed outside the editor or is no longer open. Your edits are still in the editor.',
|
|
14
|
+
unsupported: 'This project or edit is outside the folder prototype scope.',
|
|
15
|
+
failed: 'Could not access the project folder.',
|
|
16
|
+
external: 'External changes detected.', reload: 'Reload from Disk', reloaded: 'Changes loaded from disk.',
|
|
17
|
+
reloadAll: 'Reload Whole Project', discard: 'Discard Edits and Reload…',
|
|
18
|
+
discardConfirm: 'Discard your unsaved edits and load the project from the folder?',
|
|
19
|
+
dirty: 'You have unsaved edits.', running: 'Stop the project before reloading.',
|
|
20
|
+
runningAuto: 'The changes load when the project stops.', busy: 'Please wait for the current operation.',
|
|
21
|
+
waiting: 'Waiting for the external write to finish.',
|
|
22
|
+
full: 'These changes need the whole project to be reloaded.'
|
|
23
|
+
},
|
|
24
|
+
ja: {
|
|
25
|
+
open: 'プロジェクトフォルダを開く…', save: 'プロジェクトフォルダに保存',
|
|
26
|
+
replace: '未保存の変更を破棄して、別の作品を開きますか?',
|
|
27
|
+
opened: 'プロジェクトフォルダを開きました。', saved: 'プロジェクトフォルダに保存しました。', unchanged: '保存する変更はありません。',
|
|
28
|
+
conflict: '外部でフォルダが変更されたか、作品が切り替わりました。編集中の変更はエディターに残っています。',
|
|
29
|
+
unsupported: 'この作品または編集はフォルダ編集の試作対象外です。',
|
|
30
|
+
failed: 'プロジェクトフォルダにアクセスできませんでした。',
|
|
31
|
+
external: '外部変更あり', reload: 'ディスクから再読み込み', reloaded: 'ディスクの変更を読み込みました。',
|
|
32
|
+
reloadAll: '作品全体を再読み込み', discard: '編集を破棄して再読み込み…',
|
|
33
|
+
discardConfirm: '未保存の編集を破棄して、フォルダの作品を読み込みますか?',
|
|
34
|
+
dirty: '未保存の編集があります。', running: '作品を停止してから再読み込みできます。',
|
|
35
|
+
runningAuto: '作品の停止後に反映します。', busy: '処理が終わるまでお待ちください。',
|
|
36
|
+
waiting: '外部の書き込みが終わるのを待っています。',
|
|
37
|
+
full: 'この変更は作品全体の再読み込みが必要です。'
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
type MenuElement = (component: any, props: any, ...children: any[]) => any;
|
|
42
|
+
interface MenuProps {
|
|
43
|
+
vm: FolderVM;
|
|
44
|
+
locale?: string;
|
|
45
|
+
MenuItem: any;
|
|
46
|
+
MenuSection: any;
|
|
47
|
+
onRequestClose(): void;
|
|
48
|
+
}
|
|
49
|
+
type MenuEntry = {session: ReturnType<typeof createFolderSession>; open(locale: string): void; save(locale: string): void};
|
|
50
|
+
const menus = new WeakMap<FolderVM, MenuEntry>();
|
|
51
|
+
|
|
52
|
+
type ObserverWindow = PickerWindow & {FileSystemObserver?: new (callback: () => void) => {
|
|
53
|
+
observe(handle: FileSystemDirectoryHandle, options: {recursive: boolean}): Promise<void>;
|
|
54
|
+
disconnect(): void;
|
|
55
|
+
}};
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* `autoReload` (default true) applies value and position changes without a click when the Editor has no unsaved
|
|
59
|
+
* edits and the project is stopped. Other changes always wait for the reload command.
|
|
60
|
+
*/
|
|
61
|
+
export function mountProjectFolder({vm, document, host, locale = 'en', autoReload = true}: {
|
|
62
|
+
vm: FolderVM; document: Document; host: FolderHost; locale?: string; autoReload?: boolean;
|
|
63
|
+
}) {
|
|
64
|
+
const view = document.defaultView as ObserverWindow;
|
|
65
|
+
const pickDirectory = view?.showDirectoryPicker;
|
|
66
|
+
if (!pickDirectory || !vm.runtime?.storage) return null;
|
|
67
|
+
const session = createFolderSession(vm, host);
|
|
68
|
+
const status = document.createElement('output');
|
|
69
|
+
status.dataset.projectFolderStatus = '';
|
|
70
|
+
status.setAttribute('role', 'status');
|
|
71
|
+
status.hidden = true;
|
|
72
|
+
Object.assign(status.style, {
|
|
73
|
+
position: 'fixed', insetInlineEnd: '1rem', bottom: '1rem', zIndex: '1000', padding: '0.6rem 0.85rem',
|
|
74
|
+
maxWidth: 'min(28rem, calc(100vw - 2rem))', background: 'Canvas', color: 'CanvasText',
|
|
75
|
+
border: '1px solid currentColor', borderRadius: '0.4rem'
|
|
76
|
+
});
|
|
77
|
+
document.body.append(status);
|
|
78
|
+
let timer: number;
|
|
79
|
+
const report = (text: string) => {
|
|
80
|
+
if (!status.isConnected) return;
|
|
81
|
+
status.hidden = false;
|
|
82
|
+
status.textContent = text;
|
|
83
|
+
view.clearTimeout(timer);
|
|
84
|
+
timer = view.setTimeout(() => {status.hidden = true;}, 7500);
|
|
85
|
+
};
|
|
86
|
+
const messageFor = (locale: string) => locale.startsWith('ja') ? messages.ja : messages.en;
|
|
87
|
+
const fail = (locale: string, error: unknown) => {
|
|
88
|
+
const message = messageFor(locale);
|
|
89
|
+
const detail = error instanceof FolderError && error.message !== error.code ? ` (${error.message})` : '';
|
|
90
|
+
report((error instanceof FolderError ? message[error.code] : message.failed) + detail);
|
|
91
|
+
};
|
|
92
|
+
let stopWatching: (() => void) | undefined;
|
|
93
|
+
let renderReload = () => {};
|
|
94
|
+
if (host.blockReload) {
|
|
95
|
+
const message = messageFor(locale);
|
|
96
|
+
const notice = document.createElement('aside');
|
|
97
|
+
notice.dataset.projectFolderExternal = '';
|
|
98
|
+
notice.hidden = true;
|
|
99
|
+
Object.assign(notice.style, {
|
|
100
|
+
position: 'fixed', insetInlineEnd: '1rem', bottom: '4.5rem', zIndex: '1000', padding: '0.65rem 0.85rem',
|
|
101
|
+
maxWidth: 'min(27rem, calc(100vw - 2rem))', background: 'Canvas', color: 'CanvasText',
|
|
102
|
+
border: '1px solid currentColor', borderRadius: '0.4rem'
|
|
103
|
+
});
|
|
104
|
+
const text = document.createElement('div');
|
|
105
|
+
text.setAttribute('role', 'status');
|
|
106
|
+
const button = document.createElement('button');
|
|
107
|
+
button.type = 'button';
|
|
108
|
+
button.textContent = message.reload;
|
|
109
|
+
notice.append(text, button);
|
|
110
|
+
document.body.append(notice);
|
|
111
|
+
let settle: number | undefined;
|
|
112
|
+
let autoTried: string | null = null;
|
|
113
|
+
let observed: FileSystemDirectoryHandle | null = null;
|
|
114
|
+
let observer: InstanceType<NonNullable<ObserverWindow['FileSystemObserver']>> | null = null;
|
|
115
|
+
const apply = (run: () => Promise<boolean | string>) => {
|
|
116
|
+
const done = run();
|
|
117
|
+
renderReload();
|
|
118
|
+
void done.then(result => {if (result === true || result === 'opened') report(message.reloaded);}, error => fail(locale, error))
|
|
119
|
+
.finally(renderReload);
|
|
120
|
+
};
|
|
121
|
+
renderReload = () => {
|
|
122
|
+
const state = session.reloadState;
|
|
123
|
+
const kind = session.reloadKind;
|
|
124
|
+
if (autoReload && session.canAutoReload && session.pendingVersion !== autoTried) {
|
|
125
|
+
autoTried = session.pendingVersion;
|
|
126
|
+
apply(() => session.reload());
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
notice.hidden = !state;
|
|
130
|
+
button.hidden = !kind;
|
|
131
|
+
button.disabled = !['ready', 'full', 'dirty'].includes(state ?? '');
|
|
132
|
+
const action = state === 'dirty' ? message.discard : kind === 'full' ? message.reloadAll : message.reload;
|
|
133
|
+
if (button.textContent !== action) button.textContent = action;
|
|
134
|
+
const detail = !state || state === 'ready' ? '' :
|
|
135
|
+
state === 'running' && kind === 'partial' && autoReload ? message.runningAuto : message[state];
|
|
136
|
+
const label = detail ? `${message.external} ${detail}` : message.external;
|
|
137
|
+
if (text.textContent !== label) text.textContent = label;
|
|
138
|
+
const directory = session.directory;
|
|
139
|
+
if (observer && observed !== directory) {
|
|
140
|
+
observer.disconnect();
|
|
141
|
+
observed = directory;
|
|
142
|
+
if (directory) observer.observe(directory, {recursive: true}).catch(() => {});
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
const refresh = () => {
|
|
146
|
+
if (document.visibilityState !== 'visible') return;
|
|
147
|
+
void session.refresh().then(() => {
|
|
148
|
+
renderReload();
|
|
149
|
+
// Look again soon after a new or incomplete change instead of waiting for the next interval.
|
|
150
|
+
if (session.settling) schedule(500);
|
|
151
|
+
}, error => fail(locale, error));
|
|
152
|
+
};
|
|
153
|
+
const schedule = (delay: number) => {
|
|
154
|
+
view.clearTimeout(settle);
|
|
155
|
+
settle = view.setTimeout(refresh, delay);
|
|
156
|
+
};
|
|
157
|
+
if (view.FileSystemObserver) {
|
|
158
|
+
try {
|
|
159
|
+
observer = new view.FileSystemObserver(() => schedule(300));
|
|
160
|
+
} catch {
|
|
161
|
+
observer = null;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
button.addEventListener('click', () => {
|
|
165
|
+
const state = session.reloadState;
|
|
166
|
+
if (state === 'ready') apply(() => session.reload());
|
|
167
|
+
else if (state === 'full') apply(() => session.reloadAll(() => true));
|
|
168
|
+
else if (state === 'dirty') apply(() => session.reloadAll(() => view.confirm(message.discardConfirm)));
|
|
169
|
+
});
|
|
170
|
+
const unsubscribe = host.blockReload.subscribe(renderReload);
|
|
171
|
+
const interval = view.setInterval(refresh, 2000);
|
|
172
|
+
view.addEventListener('focus', refresh);
|
|
173
|
+
document.addEventListener('visibilitychange', refresh);
|
|
174
|
+
stopWatching = () => {
|
|
175
|
+
unsubscribe();
|
|
176
|
+
view.clearInterval(interval);
|
|
177
|
+
view.clearTimeout(settle);
|
|
178
|
+
observer?.disconnect();
|
|
179
|
+
view.removeEventListener('focus', refresh);
|
|
180
|
+
document.removeEventListener('visibilitychange', refresh);
|
|
181
|
+
notice.remove();
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
menus.set(vm, {
|
|
185
|
+
session,
|
|
186
|
+
open(locale) {
|
|
187
|
+
const message = messageFor(locale);
|
|
188
|
+
session.open(options => pickDirectory.call(view, options), () => view.confirm(message.replace))
|
|
189
|
+
.then(result => {if (result === 'opened') report(message.opened);}, error => fail(locale, error)).finally(renderReload);
|
|
190
|
+
renderReload();
|
|
191
|
+
},
|
|
192
|
+
save(locale) {
|
|
193
|
+
if (!session.busy) {
|
|
194
|
+
void session.save().then(result => report(messageFor(locale)[result]), error => fail(locale, error)).finally(renderReload);
|
|
195
|
+
renderReload();
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
return {
|
|
200
|
+
openDirectory: (...args: Parameters<typeof session.openDirectory>) =>
|
|
201
|
+
session.openDirectory(...args).finally(renderReload),
|
|
202
|
+
dispose() {
|
|
203
|
+
menus.delete(vm);
|
|
204
|
+
session.dispose();
|
|
205
|
+
stopWatching?.();
|
|
206
|
+
view.clearTimeout(timer);
|
|
207
|
+
status.remove();
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export function projectFolderActions(vm: FolderVM, locale = 'en') {
|
|
213
|
+
const entry = menus.get(vm);
|
|
214
|
+
if (!entry) return undefined;
|
|
215
|
+
return {
|
|
216
|
+
open: () => entry.open(locale),
|
|
217
|
+
save: entry.session.canSave ? () => entry.save(locale) : undefined,
|
|
218
|
+
detach: () => entry.session.detach()
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export function renderProjectFolderMenu(createElement: MenuElement, {
|
|
223
|
+
vm, locale = 'en', MenuItem, MenuSection, onRequestClose
|
|
224
|
+
}: MenuProps) {
|
|
225
|
+
const entry = menus.get(vm);
|
|
226
|
+
if (!entry) return null;
|
|
227
|
+
const labels = locale.startsWith('ja') ? messages.ja : messages.en;
|
|
228
|
+
const item = (action: 'open' | 'save') => {
|
|
229
|
+
const run = () => {onRequestClose(); entry[action](locale);};
|
|
230
|
+
return createElement(MenuItem, {command: `project-folder-${action}`, onClick: run},
|
|
231
|
+
createElement('span', {role: 'button', tabIndex: 0, onKeyDown(event: KeyboardEvent) {
|
|
232
|
+
if (event.key !== 'Enter' && event.key !== ' ') return;
|
|
233
|
+
event.preventDefault();
|
|
234
|
+
event.stopPropagation();
|
|
235
|
+
run();
|
|
236
|
+
}}, labels[action]));
|
|
237
|
+
};
|
|
238
|
+
return createElement(MenuSection, null, item('open'), entry.session.canSave ? item('save') : null);
|
|
239
|
+
}
|