forked from lioensky/VCPChat
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscriptorium-document-store.js
More file actions
311 lines (286 loc) · 11.1 KB
/
Copy pathscriptorium-document-store.js
File metadata and controls
311 lines (286 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
'use strict';
(() => {
const EVENTS = Object.freeze({
DOCUMENT_REPLACED: 'document-replaced',
DOCUMENT_MUTATED: 'document-mutated',
STATUS_CHANGED: 'status-changed',
SAVED: 'saved',
DISPOSED: 'disposed',
});
function createDocumentStore(options = {}) {
const core = options.core;
const containerModule = options.containerModule;
const settingsPort = options.settingsPort || {};
if (!core) throw new TypeError('Document store requires VDocCore.');
const listeners = new Map();
const state = {
document: null,
currentPath: null,
currentName: '未命名文稿.vdocx',
dirty: false,
ready: false,
saving: false,
loading: false,
revision: 0,
generation: 0,
resourceData: new Map(),
resourceObjectUrls: new Map(),
resourceResolver: null,
disposed: false,
};
function assertActive() {
if (state.disposed) throw new Error('Document store has been disposed.');
}
function emit(type, detail = {}) {
const event = Object.freeze({
type,
document: state.document,
documentId: state.document?.manifest?.id || null,
revision: state.revision,
generation: state.generation,
...detail,
});
[...(listeners.get(type) || [])].forEach((listener) => {
try {
listener(event);
} catch (error) {
console.error(`[ScriptoriumDocumentStore] ${type} listener failed:`, error);
}
});
[...(listeners.get('*') || [])].forEach((listener) => {
try {
listener(event);
} catch (error) {
console.error('[ScriptoriumDocumentStore] wildcard listener failed:', error);
}
});
return event;
}
function subscribe(type, listener) {
assertActive();
if (typeof listener !== 'function') {
throw new TypeError('Document store listener must be a function.');
}
const key = String(type || '*');
const bucket = listeners.get(key) || new Set();
bucket.add(listener);
listeners.set(key, bucket);
return () => {
bucket.delete(listener);
if (!bucket.size) listeners.delete(key);
};
}
function status() {
return Object.freeze({
documentId: state.document?.manifest?.id || null,
currentPath: state.currentPath,
currentName: state.currentName,
dirty: state.dirty,
ready: state.ready,
saving: state.saving,
loading: state.loading,
revision: state.revision,
generation: state.generation,
});
}
function documentModel() {
return state.document;
}
function resourceData() {
return state.resourceData;
}
function resourceResolver() {
return state.resourceResolver;
}
function defaultNameFor(documentModel) {
const extension = core.extensionForKind(documentModel.manifest.scene.kind);
const fallback = documentModel.manifest.scene.kind === core.PROJECT_KINDS.SLIDE_DECK
? '未命名演示'
: '未命名文稿';
const supplied = String(documentModel.manifest.title || fallback);
return supplied.toLowerCase().endsWith(extension)
? supplied
: `${supplied.replace(/\.[^.]+$/, '')}${extension}`;
}
function revokeResources() {
try {
state.resourceResolver?.revoke?.();
} catch (error) {
console.warn('[ScriptoriumDocumentStore] Resource revocation failed:', error);
}
state.resourceResolver = null;
state.resourceObjectUrls = new Map();
}
function replaceDocument(documentModel, metadata = {}) {
assertActive();
const normalized = core.normalizeDocument(documentModel);
revokeResources();
state.generation += 1;
state.document = normalized;
state.currentPath = metadata.filePath || null;
state.currentName = String(metadata.name || defaultNameFor(normalized));
const extension = core.extensionForKind(normalized.manifest.scene.kind);
if (!state.currentName.toLowerCase().endsWith(extension)) {
state.currentName = `${
state.currentName.replace(/\.[^.]+$/, '')
}${extension}`;
}
state.resourceData = metadata.resourceData instanceof Map
? metadata.resourceData
: new Map();
state.resourceResolver = containerModule?.createRuntimeResolver?.(
normalized,
state.resourceData,
state.resourceObjectUrls,
{
trustNetworkFonts: () =>
settingsPort.get?.('trustNetworkFonts') === true,
}
) || null;
state.dirty = metadata.dirty === true;
state.ready = true;
state.saving = false;
state.loading = false;
state.revision = 0;
emit(EVENTS.DOCUMENT_REPLACED, {
previousDocumentId: metadata.previousDocumentId || null,
reason: metadata.reason || 'replace',
});
emit(EVENTS.STATUS_CHANGED, { reason: 'document-replaced' });
return normalized;
}
function mutate(mutator, options = {}) {
assertActive();
if (!state.document || typeof mutator !== 'function') return false;
const beforeRevision = state.revision;
const result = mutator(state.document);
if (result === false) return false;
state.document.manifest.modifiedAt = new Date().toISOString();
state.revision += 1;
state.dirty = options.dirty !== false;
emit(EVENTS.DOCUMENT_MUTATED, {
reason: options.reason || 'mutation',
beforeRevision,
result,
});
emit(EVENTS.STATUS_CHANGED, {
reason: options.reason || 'mutation',
});
return result === undefined ? true : result;
}
function updateDerived(mutator, options = {}) {
assertActive();
if (!state.document || typeof mutator !== 'function') return false;
const result = mutator(state.document);
if (result === false) return false;
emit(EVENTS.DOCUMENT_MUTATED, {
reason: options.reason || 'derived-state',
beforeRevision: state.revision,
derived: true,
result,
});
return result === undefined ? true : result;
}
function markDirty(options = {}) {
assertActive();
if (!state.ready || state.loading || !state.document) return false;
const beforeRevision = state.revision;
if (options.incrementRevision !== false) state.revision += 1;
state.dirty = true;
emit(EVENTS.DOCUMENT_MUTATED, {
reason: options.reason || 'dirty',
beforeRevision,
metadataOnly: options.metadataOnly === true,
});
emit(EVENTS.STATUS_CHANGED, { reason: options.reason || 'dirty' });
return true;
}
function markSaved(metadata = {}) {
assertActive();
if (metadata.filePath !== undefined) state.currentPath = metadata.filePath;
if (metadata.name !== undefined) state.currentName = String(metadata.name);
const savedRevision = metadata.revision;
if (savedRevision === undefined || savedRevision === state.revision) {
state.dirty = false;
}
emit(EVENTS.SAVED, {
savedRevision: savedRevision ?? state.revision,
dirtyAfterSave: state.dirty,
});
emit(EVENTS.STATUS_CHANGED, { reason: 'saved' });
return !state.dirty;
}
function setActivity(patch = {}) {
assertActive();
if (patch.loading !== undefined) state.loading = patch.loading === true;
if (patch.saving !== undefined) state.saving = patch.saving === true;
if (patch.ready !== undefined) state.ready = patch.ready === true;
emit(EVENTS.STATUS_CHANGED, { reason: patch.reason || 'activity' });
return status();
}
function updateIdentity(metadata = {}) {
assertActive();
if (metadata.filePath !== undefined) state.currentPath = metadata.filePath;
if (metadata.name !== undefined) state.currentName = String(metadata.name);
emit(EVENTS.STATUS_CHANGED, { reason: metadata.reason || 'identity' });
return status();
}
function serialize() {
assertActive();
return state.document ? core.serialize(state.document) : '';
}
function captureContext(extra = {}) {
assertActive();
return Object.freeze({
generation: state.generation,
documentId: state.document?.manifest?.id || null,
revision: state.revision,
...extra,
});
}
function isContextCurrent(context, checks = {}) {
if (!context || state.disposed) return false;
if (context.generation !== state.generation) return false;
if (checks.document !== false
&& context.documentId !== (state.document?.manifest?.id || null)) {
return false;
}
if (checks.revision === true && context.revision !== state.revision) {
return false;
}
return true;
}
function dispose() {
if (state.disposed) return;
revokeResources();
state.disposed = true;
emit(EVENTS.DISPOSED);
listeners.clear();
state.document = null;
state.resourceData.clear();
}
return Object.freeze({
EVENTS,
subscribe,
status,
document: documentModel,
resourceData,
resourceResolver,
replaceDocument,
mutate,
updateDerived,
markDirty,
markSaved,
setActivity,
updateIdentity,
serialize,
captureContext,
isContextCurrent,
dispose,
});
}
window.ScriptoriumDocumentStore = Object.freeze({
EVENTS,
createDocumentStore,
});
})();