@univerjs/docs 1.3.1 → 1.5.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.
@@ -0,0 +1,955 @@
1
+ let _univerjs_core = require("@univerjs/core");
2
+ let _univerjs_engine_render = require("@univerjs/engine-render");
3
+ let rxjs = require("rxjs");
4
+
5
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/typeof.js
6
+ function _typeof(o) {
7
+ "@babel/helpers - typeof";
8
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
9
+ return typeof o;
10
+ } : function(o) {
11
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
12
+ }, _typeof(o);
13
+ }
14
+
15
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/toPrimitive.js
16
+ function toPrimitive(t, e) {
17
+ if ("object" != _typeof(t) || !t) return t;
18
+ var r;
19
+ if ("undefined" != typeof Symbol && void 0 !== (r = t[Symbol.toPrimitive])) {
20
+ var i = r.call(t, e || "default");
21
+ if ("object" != _typeof(i)) return i;
22
+ throw new TypeError("@@toPrimitive must return a primitive value.");
23
+ }
24
+ return ("string" === e ? String : Number)(t);
25
+ }
26
+
27
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/toPropertyKey.js
28
+ function toPropertyKey(t) {
29
+ var i = toPrimitive(t, "string");
30
+ return "symbol" == _typeof(i) ? i : i + "";
31
+ }
32
+
33
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/defineProperty.js
34
+ function _defineProperty(e, r, t) {
35
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
36
+ value: t,
37
+ enumerable: !0,
38
+ configurable: !0,
39
+ writable: !0
40
+ }) : e[r] = t, e;
41
+ }
42
+
43
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/decorateParam.js
44
+ function __decorateParam(paramIndex, decorator) {
45
+ return function(target, key) {
46
+ decorator(target, key, paramIndex);
47
+ };
48
+ }
49
+
50
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/decorate.js
51
+ function __decorate(decorators, target, key, desc) {
52
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
53
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
54
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
55
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
56
+ }
57
+
58
+ // src/commands/mutations/core-editing.mutation-id.ts
59
+ /**
60
+ * Copyright 2023-present DreamNum Co., Ltd.
61
+ *
62
+ * Licensed under the Apache License, Version 2.0 (the "License");
63
+ * you may not use this file except in compliance with the License.
64
+ * You may obtain a copy of the License at
65
+ *
66
+ * http://www.apache.org/licenses/LICENSE-2.0
67
+ *
68
+ * Unless required by applicable law or agreed to in writing, software
69
+ * distributed under the License is distributed on an "AS IS" BASIS,
70
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
71
+ * See the License for the specific language governing permissions and
72
+ * limitations under the License.
73
+ */
74
+ const RICH_TEXT_EDITING_MUTATION_ID = "doc.mutation.rich-text-editing";
75
+
76
+ // src/services/document-layout-snapshot.ts
77
+ function projectCustomBlock(block) {
78
+ const { docxRawXml: _docxRawXml, docxExportTs: _docxExportTs, ...layoutBlock } = block;
79
+ return layoutBlock;
80
+ }
81
+ function projectDocumentBody(body) {
82
+ const { docxRawCustomBlocks: _docxRawCustomBlocks, docxRawBlocks: _docxRawBlocks, docxExportExcludedRanges: _docxExportExcludedRanges, payloads: _payloads, customBlocks, ...layoutBody } = body;
83
+ return {
84
+ ...layoutBody,
85
+ ...customBlocks == null ? {} : { customBlocks: customBlocks.map(projectCustomBlock) }
86
+ };
87
+ }
88
+ function projectHeader(header) {
89
+ return {
90
+ ...header,
91
+ body: projectDocumentBody(header.body)
92
+ };
93
+ }
94
+ function projectFooter(footer) {
95
+ return {
96
+ ...footer,
97
+ body: projectDocumentBody(footer.body)
98
+ };
99
+ }
100
+ /**
101
+ * Builds the model snapshot owned by the layout Worker. Exchange-only payloads
102
+ * remain in the authoritative Main model and are deliberately excluded from
103
+ * the structured-clone boundary because they do not affect document geometry.
104
+ */
105
+ function createDocumentLayoutSnapshot(snapshot) {
106
+ const { resources: _resources, body, headers, footers, footnotes, endnotes, ...layoutSnapshot } = snapshot;
107
+ return {
108
+ ...layoutSnapshot,
109
+ ...footnotes == null ? {} : { footnotes: Object.fromEntries(Object.entries(footnotes).map(([id, note]) => [id, {
110
+ ...note,
111
+ body: projectDocumentBody(note.body)
112
+ }])) },
113
+ ...endnotes == null ? {} : { endnotes: Object.fromEntries(Object.entries(endnotes).map(([id, note]) => [id, {
114
+ ...note,
115
+ body: projectDocumentBody(note.body)
116
+ }])) },
117
+ ...body == null ? {} : { body: projectDocumentBody(body) },
118
+ ...headers == null ? {} : { headers: Object.fromEntries(Object.entries(headers).map(([headerId, header]) => [headerId, projectHeader(header)])) },
119
+ ...footers == null ? {} : { footers: Object.fromEntries(Object.entries(footers).map(([footerId, footer]) => [footerId, projectFooter(footer)])) }
120
+ };
121
+ }
122
+
123
+ // src/services/doc-layout-executor.service.ts
124
+ var _DocLayoutExecutorService;
125
+ let DocLayoutExecutorType = /* @__PURE__ */ function(DocLayoutExecutorType) {
126
+ DocLayoutExecutorType["MAIN_THREAD"] = "main-thread";
127
+ DocLayoutExecutorType["WORKER"] = "worker";
128
+ return DocLayoutExecutorType;
129
+ }({});
130
+ let DocLayoutSessionStatus = /* @__PURE__ */ function(DocLayoutSessionStatus) {
131
+ DocLayoutSessionStatus["ACCEPTED"] = "accepted";
132
+ DocLayoutSessionStatus["NOT_FOUND"] = "not-found";
133
+ DocLayoutSessionStatus["RESNAPSHOT_REQUIRED"] = "resnapshot-required";
134
+ DocLayoutSessionStatus["SUPERSEDED"] = "superseded";
135
+ return DocLayoutSessionStatus;
136
+ }({});
137
+ let DocLayoutExecutorState = /* @__PURE__ */ function(DocLayoutExecutorState) {
138
+ DocLayoutExecutorState["UNREGISTERED"] = "unregistered";
139
+ DocLayoutExecutorState["INITIALIZING"] = "initializing";
140
+ DocLayoutExecutorState["ACTIVE"] = "active";
141
+ DocLayoutExecutorState["RECOVERING"] = "recovering";
142
+ DocLayoutExecutorState["FAILED"] = "failed";
143
+ return DocLayoutExecutorState;
144
+ }({});
145
+ function areShallowRecordsEqual(left, right) {
146
+ const leftRecord = left;
147
+ const rightRecord = right;
148
+ const leftKeys = Object.keys(leftRecord);
149
+ const rightKeys = Object.keys(rightRecord);
150
+ return leftKeys.length === rightKeys.length && leftKeys.every((key) => leftRecord[key] === rightRecord[key]);
151
+ }
152
+ function createRecordPatch(previous, current) {
153
+ const upserts = {};
154
+ const removals = [];
155
+ for (const [key, value] of Object.entries(current)) if (previous[key] == null || !areShallowRecordsEqual(previous[key], value)) upserts[key] = value;
156
+ for (const key of Object.keys(previous)) if (current[key] == null) removals.push(key);
157
+ return {
158
+ removals,
159
+ upserts
160
+ };
161
+ }
162
+ function getCustomRangePresentationKey(entry) {
163
+ return JSON.stringify([entry.segmentId, entry.rangeId]);
164
+ }
165
+ function toCustomRangePresentationMap(entries) {
166
+ return new Map(entries.map((entry) => [getCustomRangePresentationKey(entry), entry]));
167
+ }
168
+ function createCustomRangePresentationPatch(previous, current) {
169
+ const upserts = [];
170
+ const removals = [];
171
+ for (const [key, entry] of current) {
172
+ const previousEntry = previous.get(key);
173
+ if (previousEntry == null || !areShallowRecordsEqual(previousEntry.presentation, entry.presentation)) upserts.push(entry);
174
+ }
175
+ for (const [key, entry] of previous) if (!current.has(key)) removals.push({
176
+ segmentId: entry.segmentId,
177
+ rangeId: entry.rangeId
178
+ });
179
+ return {
180
+ removals,
181
+ upserts
182
+ };
183
+ }
184
+ function isRichTextEditingMutationParams(value) {
185
+ return typeof value === "object" && value != null && "unitId" in value && typeof value.unitId === "string" && "actions" in value;
186
+ }
187
+ function collectCustomBlockViewports(dataModel, options) {
188
+ var _documentStyle$pageSi, _documentStyle$pageSi2;
189
+ const snapshot = dataModel.getSnapshot();
190
+ const documentStyle = snapshot.documentStyle;
191
+ const isModern = documentStyle.documentFlavor === _univerjs_core.DocumentFlavor.MODERN;
192
+ const modernMargin = options.modernHorizontalMargin ?? _univerjs_core.MODERN_DOCUMENT_DEFAULT_MARGIN;
193
+ const pageMarginLeft = isModern ? modernMargin : documentStyle.marginLeft;
194
+ const pageMarginRight = isModern ? modernMargin : documentStyle.marginRight;
195
+ const pageWidth = isModern ? options.modernPageWidth ?? ((_documentStyle$pageSi = documentStyle.pageSize) === null || _documentStyle$pageSi === void 0 ? void 0 : _documentStyle$pageSi.width) ?? _univerjs_core.MODERN_DOCUMENT_WIDTH[_univerjs_core.ModernDocumentWidthMode.MEDIUM] : (_documentStyle$pageSi2 = documentStyle.pageSize) === null || _documentStyle$pageSi2 === void 0 ? void 0 : _documentStyle$pageSi2.width;
196
+ const viewports = {};
197
+ const bodies = [
198
+ snapshot.body,
199
+ ...Object.values(snapshot.headers ?? {}).map((header) => header.body),
200
+ ...Object.values(snapshot.footers ?? {}).map((footer) => footer.body)
201
+ ];
202
+ for (const customBlock of bodies.flatMap((body) => (body === null || body === void 0 ? void 0 : body.customBlocks) ?? [])) {
203
+ var _snapshot$drawings;
204
+ const drawing = (_snapshot$drawings = snapshot.drawings) === null || _snapshot$drawings === void 0 ? void 0 : _snapshot$drawings[customBlock.blockId];
205
+ if (drawing == null) continue;
206
+ const viewport = (0, _univerjs_engine_render.getDocsCustomBlockRenderViewport)(dataModel.getUnitId(), customBlock.blockId, {
207
+ fallbackHeight: drawing.docTransform.size.height ?? 0,
208
+ fallbackWidth: drawing.docTransform.size.width ?? 0,
209
+ pageMarginLeft,
210
+ pageMarginRight,
211
+ pageWidth
212
+ });
213
+ if (viewport != null) viewports[customBlock.blockId] = { ...viewport };
214
+ }
215
+ return viewports;
216
+ }
217
+ let DocLayoutExecutorService = _DocLayoutExecutorService = class DocLayoutExecutorService extends _univerjs_core.Disposable {
218
+ constructor(_univerInstanceService, _commandService, _localeService, _logService) {
219
+ super();
220
+ this._univerInstanceService = _univerInstanceService;
221
+ this._commandService = _commandService;
222
+ this._localeService = _localeService;
223
+ this._logService = _logService;
224
+ _defineProperty(this, "_executor", null);
225
+ _defineProperty(this, "_executorReady", null);
226
+ _defineProperty(this, "_recoveryFailure", null);
227
+ _defineProperty(this, "_sessionEpoch", 0);
228
+ _defineProperty(this, "_sessions", /* @__PURE__ */ new Map());
229
+ _defineProperty(this, "_hydrationSamples", /* @__PURE__ */ new Map());
230
+ _defineProperty(this, "_customRangePresentationProviders", /* @__PURE__ */ new Set());
231
+ _defineProperty(this, "_executorStatus$", new rxjs.BehaviorSubject({
232
+ state: "unregistered",
233
+ executor: null,
234
+ diagnostic: null,
235
+ recoveryUnitId: null
236
+ }));
237
+ _defineProperty(this, "executorStatus$", this._executorStatus$.asObservable());
238
+ this.disposeWithMe(this._univerInstanceService.getTypeOfUnitAdded$(_univerjs_core.UniverInstanceType.UNIVER_DOC).subscribe(({ unit }) => this._createSessionIfEligible(unit)));
239
+ this.disposeWithMe(this._univerInstanceService.getTypeOfUnitDisposed$(_univerjs_core.UniverInstanceType.UNIVER_DOC).subscribe((unit) => this._disposeSession(unit.getUnitId())));
240
+ this.disposeWithMe(this._commandService.onCommandExecuted((command) => {
241
+ if (command.id !== "doc.mutation.rich-text-editing") return;
242
+ const params = command.params;
243
+ if (!isRichTextEditingMutationParams(params)) {
244
+ this._logService.warn("[DocLayoutExecutorService]: ignored malformed document mutation parameters.");
245
+ return;
246
+ }
247
+ this._enqueueCommittedMutation(params);
248
+ }));
249
+ this.disposeWithMe(this._localeService.localeChanged$.subscribe(() => {
250
+ for (const unitId of this._sessions.keys()) {
251
+ const dataModel = this._getEligibleModel(unitId);
252
+ if (dataModel != null) this._replaceSession(dataModel).catch((error) => {
253
+ this._logService.error("[DocLayoutExecutorService]: failed to refresh Worker locale.", error);
254
+ });
255
+ }
256
+ }));
257
+ }
258
+ register(executor) {
259
+ if (this._executor != null) throw new Error("A document layout executor is already registered.");
260
+ this._executor = executor;
261
+ this._recoveryFailure = null;
262
+ this._executorStatus$.next({
263
+ state: "initializing",
264
+ executor: executor.type,
265
+ diagnostic: null,
266
+ recoveryUnitId: null
267
+ });
268
+ const executorReady = executor.initialize();
269
+ this._executorReady = executorReady;
270
+ executorReady.then(() => {
271
+ if (this._executor === executor) this._executorStatus$.next({
272
+ state: "active",
273
+ executor: executor.type,
274
+ diagnostic: null,
275
+ recoveryUnitId: null
276
+ });
277
+ }).catch((error) => {
278
+ if (this._executor !== executor) return;
279
+ this._executor = null;
280
+ this._executorReady = null;
281
+ this._disposeManagedSessions();
282
+ this._sessions.clear();
283
+ const diagnostic = error instanceof Error ? error.message : String(error);
284
+ this._executorStatus$.next({
285
+ state: "failed",
286
+ executor: executor.type,
287
+ diagnostic,
288
+ recoveryUnitId: null
289
+ });
290
+ this._logService.error("[DocLayoutExecutorService]: document layout executor initialization failed.", error);
291
+ });
292
+ for (const unit of this._univerInstanceService.getAllUnitsForType(_univerjs_core.UniverInstanceType.UNIVER_DOC)) this._createSessionIfEligible(unit);
293
+ return (0, _univerjs_core.toDisposable)(() => {
294
+ if (this._executor === executor) {
295
+ this._executor = null;
296
+ this._executorReady = null;
297
+ this._disposeManagedSessions();
298
+ this._sessions.clear();
299
+ this._executorStatus$.next({
300
+ state: "unregistered",
301
+ executor: null,
302
+ diagnostic: null,
303
+ recoveryUnitId: null
304
+ });
305
+ }
306
+ });
307
+ }
308
+ getExecutor() {
309
+ return this._executor;
310
+ }
311
+ getExecutorStatus() {
312
+ return this._executorStatus$.value;
313
+ }
314
+ registerCustomRangePresentationProvider(provider) {
315
+ this._customRangePresentationProviders.add(provider);
316
+ return (0, _univerjs_core.toDisposable)(() => this._customRangePresentationProviders.delete(provider));
317
+ }
318
+ async getPerformanceMetrics(unitId) {
319
+ var _this$_executor;
320
+ const executorMetrics = await ((_this$_executor = this._executor) === null || _this$_executor === void 0 ? void 0 : _this$_executor.getPerformanceMetrics(unitId));
321
+ return {
322
+ hydrationMs: [...this._hydrationSamples.get(unitId) ?? []],
323
+ mutationTransferMs: [...(executorMetrics === null || executorMetrics === void 0 ? void 0 : executorMetrics.mutationTransferMs) ?? []],
324
+ patchTransferMs: [...(executorMetrics === null || executorMetrics === void 0 ? void 0 : executorMetrics.patchTransferMs) ?? []],
325
+ snapshotTransferMs: [...(executorMetrics === null || executorMetrics === void 0 ? void 0 : executorMetrics.snapshotTransferMs) ?? []]
326
+ };
327
+ }
328
+ async resetPerformanceMetrics(unitId) {
329
+ var _this$_executor2;
330
+ this._hydrationSamples.delete(unitId);
331
+ await ((_this$_executor2 = this._executor) === null || _this$_executor2 === void 0 ? void 0 : _this$_executor2.resetPerformanceMetrics(unitId));
332
+ }
333
+ recordHydrationDuration(unitId, durationMs) {
334
+ this._appendPerformanceSample(this._hydrationSamples, unitId, durationMs);
335
+ }
336
+ async recoverExecutor(unitId, diagnostic) {
337
+ const executor = this._requireExecutor();
338
+ this._executorStatus$.next({
339
+ state: "recovering",
340
+ executor: executor.type,
341
+ diagnostic,
342
+ recoveryUnitId: unitId
343
+ });
344
+ for (const session of this._sessions.values()) this._markSessionDisposed(session);
345
+ this._sessions.clear();
346
+ this._hydrationSamples.clear();
347
+ try {
348
+ const executorReady = executor.recover();
349
+ this._executorReady = executorReady;
350
+ await executorReady;
351
+ } catch (error) {
352
+ if (this._executor === executor) {
353
+ const recoveryDiagnostic = error instanceof Error ? error.message : String(error);
354
+ this._executor = null;
355
+ this._executorReady = null;
356
+ this._recoveryFailure = {
357
+ diagnostic: recoveryDiagnostic,
358
+ unitId
359
+ };
360
+ this._executorStatus$.next({
361
+ state: "recovering",
362
+ executor: executor.type,
363
+ diagnostic: recoveryDiagnostic,
364
+ recoveryUnitId: unitId
365
+ });
366
+ }
367
+ throw error;
368
+ }
369
+ }
370
+ completeRecovery(unitId) {
371
+ var _this$_recoveryFailur;
372
+ const status = this._executorStatus$.value;
373
+ if (status.state !== "recovering" || status.recoveryUnitId !== unitId) return;
374
+ const recoveryFailure = ((_this$_recoveryFailur = this._recoveryFailure) === null || _this$_recoveryFailur === void 0 ? void 0 : _this$_recoveryFailur.unitId) === unitId ? this._recoveryFailure : null;
375
+ this._recoveryFailure = null;
376
+ this._executorStatus$.next({
377
+ state: recoveryFailure == null ? "active" : "failed",
378
+ executor: status.executor,
379
+ diagnostic: (recoveryFailure === null || recoveryFailure === void 0 ? void 0 : recoveryFailure.diagnostic) ?? null,
380
+ recoveryUnitId: null
381
+ });
382
+ }
383
+ async startLayout(identity, options, budgetMs) {
384
+ const { unitId } = identity;
385
+ const executor = this._executor;
386
+ const dataModel = this._getEligibleModel(unitId);
387
+ if (executor == null || dataModel == null) return null;
388
+ let session = this._sessions.get(unitId);
389
+ if (session != null && session.sourceMutationRevision !== dataModel.getMutationRevision()) session.needsResnapshot = true;
390
+ if (session == null || session.needsResnapshot) session = await this._replaceSession(dataModel);
391
+ if (session.disposed || this._executor !== executor || this._getEligibleModel(unitId) !== dataModel) return null;
392
+ let result = await this._startSynchronizedLayout(executor, session, identity, options, budgetMs);
393
+ if (session.disposed || this._executor !== executor || this._getEligibleModel(unitId) !== dataModel) return null;
394
+ if (result.status === "not-found" || result.status === "resnapshot-required") {
395
+ session = await this._replaceSession(dataModel);
396
+ result = await this._startSynchronizedLayout(executor, session, identity, options, budgetMs);
397
+ }
398
+ return result;
399
+ }
400
+ stepLayout(request) {
401
+ return this._requireExecutor().stepLayout(request);
402
+ }
403
+ publishBacklog(request) {
404
+ return this._requireExecutor().publishBacklog(request);
405
+ }
406
+ getLayoutPage(request) {
407
+ return this._requireExecutor().getLayoutPage(request);
408
+ }
409
+ cancelLayout(request) {
410
+ const executor = this._executor;
411
+ return executor == null ? Promise.resolve() : executor.cancelLayout(request);
412
+ }
413
+ disposeLayoutMount(request) {
414
+ const executor = this._executor;
415
+ const session = this._sessions.get(request.unitId);
416
+ const latestStart = session === null || session === void 0 ? void 0 : session.latestStarts.get(request.mountId);
417
+ if ((latestStart === null || latestStart === void 0 ? void 0 : latestStart.mountEpoch) === request.mountEpoch && latestStart.viewportEpoch === request.viewportEpoch) {
418
+ session === null || session === void 0 || session.latestStarts.delete(request.mountId);
419
+ session === null || session === void 0 || session.customBlockViewportsByMount.delete(request.mountId);
420
+ }
421
+ return executor == null ? Promise.resolve() : executor.disposeLayoutMount(request);
422
+ }
423
+ dispose() {
424
+ const executor = this._executor;
425
+ if (executor != null) for (const [unitId, session] of this._sessions) {
426
+ this._markSessionDisposed(session);
427
+ executor.disposeSession({
428
+ unitId,
429
+ sessionEpoch: session.sessionEpoch
430
+ }).catch((error) => {
431
+ if (this._executor === executor) this._logService.error("[DocLayoutExecutorService]: failed to dispose a Worker session.", error);
432
+ });
433
+ }
434
+ this._sessions.clear();
435
+ this._executor = null;
436
+ this._executorReady = null;
437
+ this._recoveryFailure = null;
438
+ this._executorStatus$.complete();
439
+ this._customRangePresentationProviders.clear();
440
+ super.dispose();
441
+ }
442
+ _createSessionIfEligible(dataModel) {
443
+ if (this._executor == null || !this._isEligible(dataModel) || this._sessions.has(dataModel.getUnitId())) return;
444
+ this._replaceSession(dataModel).catch((error) => {
445
+ this._logService.error("[DocLayoutExecutorService]: failed to create a Worker session.", error);
446
+ });
447
+ }
448
+ _enqueueCommittedMutation(params) {
449
+ var _params$actions;
450
+ const executor = this._executor;
451
+ const dataModel = this._getEligibleModel(params.unitId);
452
+ if (executor == null || dataModel == null) return;
453
+ if (_univerjs_core.JSONX.isNoop(params.actions) || ((_params$actions = params.actions) === null || _params$actions === void 0 ? void 0 : _params$actions.length) === 0) return;
454
+ const session = this._sessions.get(params.unitId);
455
+ if (session == null) {
456
+ this._replaceSession(dataModel).catch((error) => {
457
+ this._logService.error("[DocLayoutExecutorService]: failed to snapshot a document mutation.", error);
458
+ });
459
+ return;
460
+ }
461
+ const sourceMutationRevision = dataModel.getMutationRevision();
462
+ if (sourceMutationRevision !== session.sourceMutationRevision + 1) {
463
+ session.needsResnapshot = true;
464
+ return;
465
+ }
466
+ const baseRevision = session.modelRevision;
467
+ const modelRevision = baseRevision + 1;
468
+ session.modelRevision = modelRevision;
469
+ session.sourceMutationRevision = sourceMutationRevision;
470
+ session.pendingMutations.push({
471
+ baseRevision,
472
+ modelRevision,
473
+ actions: params.actions
474
+ });
475
+ }
476
+ async _startSynchronizedLayout(executor, session, identity, options, budgetMs) {
477
+ var _session$latestStarts;
478
+ const { unitId, mountId } = identity;
479
+ const startId = (((_session$latestStarts = session.latestStarts.get(mountId)) === null || _session$latestStarts === void 0 ? void 0 : _session$latestStarts.startId) ?? 0) + 1;
480
+ const startIdentity = {
481
+ startId,
482
+ mountEpoch: identity.mountEpoch,
483
+ viewportEpoch: identity.viewportEpoch
484
+ };
485
+ session.latestStarts.set(mountId, startIdentity);
486
+ const startTask = session.queue.then(async () => {
487
+ if (session.disposed || this._executor !== executor) return { status: "not-found" };
488
+ const currentModel = this._getEligibleModel(unitId);
489
+ if (currentModel == null || currentModel.getMutationRevision() !== session.sourceMutationRevision) {
490
+ session.needsResnapshot = true;
491
+ return {
492
+ status: "resnapshot-required",
493
+ modelRevision: session.workerRevision
494
+ };
495
+ }
496
+ if (session.latestStarts.get(mountId) !== startIdentity) return { status: "superseded" };
497
+ const mutations = session.pendingMutations.slice();
498
+ const projections = this._createLayoutProjectionPayload(session, identity, this._getRequiredModel(unitId), options);
499
+ const request = {
500
+ ...identity,
501
+ metricsRevision: startId,
502
+ baseRevision: session.workerRevision,
503
+ modelRevision: session.modelRevision,
504
+ mutations,
505
+ ...projections.request,
506
+ budgetMs,
507
+ ...options
508
+ };
509
+ const result = await executor.startLayout(request);
510
+ if (result.status === "accepted") {
511
+ session.workerRevision = request.modelRevision;
512
+ session.pendingMutations.splice(0, mutations.length);
513
+ session.customBlockViewportsByMount.set(mountId, {
514
+ mountEpoch: identity.mountEpoch,
515
+ value: projections.customBlockViewports
516
+ });
517
+ session.customRangePresentations = projections.customRangePresentations;
518
+ } else session.needsResnapshot = true;
519
+ return result;
520
+ });
521
+ session.queue = startTask.then(() => void 0, (error) => {
522
+ if (session.disposed || this._executor !== executor) return;
523
+ session.needsResnapshot = true;
524
+ this._logService.error("[DocLayoutExecutorService]: synchronized layout start failed.", error);
525
+ });
526
+ return startTask;
527
+ }
528
+ _createLayoutProjectionPayload(session, identity, dataModel, options) {
529
+ const customBlockViewports = collectCustomBlockViewports(dataModel, options);
530
+ const previousCustomBlockViewports = session.customBlockViewportsByMount.get(identity.mountId);
531
+ const customRangePresentations = this._collectCustomRangePresentations(dataModel);
532
+ const customRangePresentationMap = toCustomRangePresentationMap(customRangePresentations);
533
+ const request = {};
534
+ if (previousCustomBlockViewports == null || previousCustomBlockViewports.mountEpoch !== identity.mountEpoch) request.customBlockViewports = customBlockViewports;
535
+ else {
536
+ const patch = createRecordPatch(previousCustomBlockViewports.value, customBlockViewports);
537
+ if (patch.removals.length > 0 || Object.keys(patch.upserts).length > 0) request.customBlockViewportPatch = patch;
538
+ }
539
+ if (session.customRangePresentations == null) request.customRangePresentations = customRangePresentations;
540
+ else {
541
+ const patch = createCustomRangePresentationPatch(session.customRangePresentations, customRangePresentationMap);
542
+ if (patch.removals.length > 0 || patch.upserts.length > 0) request.customRangePresentationPatch = patch;
543
+ }
544
+ return {
545
+ request,
546
+ customBlockViewports,
547
+ customRangePresentations: customRangePresentationMap
548
+ };
549
+ }
550
+ async _replaceSession(dataModel) {
551
+ const executor = this._requireExecutor();
552
+ const unitId = dataModel.getUnitId();
553
+ const previous = this._sessions.get(unitId);
554
+ if (previous != null) this._markSessionDisposed(previous);
555
+ const modelRevision = (previous === null || previous === void 0 ? void 0 : previous.modelRevision) ?? 0;
556
+ const session = {
557
+ sessionEpoch: ++this._sessionEpoch,
558
+ modelRevision,
559
+ sourceMutationRevision: dataModel.getMutationRevision(),
560
+ workerRevision: modelRevision,
561
+ pendingMutations: [],
562
+ latestStarts: /* @__PURE__ */ new Map(),
563
+ customBlockViewportsByMount: /* @__PURE__ */ new Map(),
564
+ customRangePresentations: null,
565
+ queue: Promise.resolve(),
566
+ needsResnapshot: false,
567
+ disposed: false,
568
+ cancelPendingCreateTask: null
569
+ };
570
+ const createTask = this._createSessionOnNextMacroTask(executor, session, dataModel);
571
+ session.queue = createTask;
572
+ this._sessions.set(unitId, session);
573
+ try {
574
+ await createTask;
575
+ } catch (error) {
576
+ if (!session.disposed && this._executor === executor) {
577
+ session.needsResnapshot = true;
578
+ throw error;
579
+ }
580
+ }
581
+ return session;
582
+ }
583
+ _disposeSession(unitId) {
584
+ const session = this._sessions.get(unitId);
585
+ if (session == null) return;
586
+ this._markSessionDisposed(session);
587
+ this._sessions.delete(unitId);
588
+ this._hydrationSamples.delete(unitId);
589
+ const executor = this._executor;
590
+ executor === null || executor === void 0 || executor.disposeSession({
591
+ unitId,
592
+ sessionEpoch: session.sessionEpoch
593
+ }).catch((error) => {
594
+ if (this._executor === executor) this._logService.error("[DocLayoutExecutorService]: failed to dispose a Worker session.", error);
595
+ });
596
+ }
597
+ _getEligibleModel(unitId) {
598
+ const dataModel = this._univerInstanceService.getUnit(unitId, _univerjs_core.UniverInstanceType.UNIVER_DOC);
599
+ return dataModel != null && this._isEligible(dataModel) ? dataModel : null;
600
+ }
601
+ _getRequiredModel(unitId) {
602
+ const dataModel = this._getEligibleModel(unitId);
603
+ if (dataModel == null) throw new Error(`Eligible document model not found for Worker layout: "${unitId}".`);
604
+ return dataModel;
605
+ }
606
+ _collectCustomRangePresentations(dataModel) {
607
+ const presentations = [];
608
+ const providers = Array.from(this._customRangePresentationProviders).reverse();
609
+ if (providers.length === 0) return presentations;
610
+ const collectSegment = (segmentId, body) => {
611
+ if (body == null) return;
612
+ const seenRangeIds = /* @__PURE__ */ new Set();
613
+ for (const range of body.customRanges ?? []) {
614
+ if (seenRangeIds.has(range.rangeId)) continue;
615
+ seenRangeIds.add(range.rangeId);
616
+ for (const provider of providers) {
617
+ const presentation = provider(dataModel.getUnitId(), range, {
618
+ segmentId,
619
+ body
620
+ });
621
+ if (presentation != null) {
622
+ presentations.push({
623
+ segmentId,
624
+ rangeId: range.rangeId,
625
+ presentation: { ...presentation }
626
+ });
627
+ break;
628
+ }
629
+ }
630
+ }
631
+ };
632
+ collectSegment("", dataModel.getBody());
633
+ for (const [segmentId, headerModel] of dataModel.headerModelMap) collectSegment(segmentId, headerModel.getBody());
634
+ for (const [segmentId, footerModel] of dataModel.footerModelMap) collectSegment(segmentId, footerModel.getBody());
635
+ return presentations;
636
+ }
637
+ _isEligible(dataModel) {
638
+ if ((0, _univerjs_core.isInternalEditorID)(dataModel.getUnitId())) return false;
639
+ const flavor = dataModel.getSnapshot().documentStyle.documentFlavor;
640
+ return flavor === _univerjs_core.DocumentFlavor.TRADITIONAL || flavor === _univerjs_core.DocumentFlavor.MODERN;
641
+ }
642
+ _requireExecutor() {
643
+ if (this._executor == null) throw new Error("No document layout executor is registered.");
644
+ return this._executor;
645
+ }
646
+ _appendPerformanceSample(target, unitId, durationMs) {
647
+ const samples = target.get(unitId) ?? [];
648
+ samples.push(durationMs);
649
+ if (samples.length > _DocLayoutExecutorService._performanceSampleLimit) samples.splice(0, samples.length - _DocLayoutExecutorService._performanceSampleLimit);
650
+ target.set(unitId, samples);
651
+ }
652
+ _createSessionOnNextMacroTask(executor, session, dataModel) {
653
+ return new Promise((resolve, reject) => {
654
+ const cancelTask = (0, _univerjs_core.requestImmediateMacroTask)(() => {
655
+ session.cancelPendingCreateTask = null;
656
+ const unitId = dataModel.getUnitId();
657
+ if (session.disposed || this._executor !== executor || this._sessions.get(unitId) !== session) {
658
+ resolve();
659
+ return;
660
+ }
661
+ const executorReady = this._executorReady;
662
+ if (executorReady == null) {
663
+ resolve();
664
+ return;
665
+ }
666
+ executorReady.then(() => {
667
+ if (session.disposed || this._executor !== executor || this._sessions.get(unitId) !== session || this._getEligibleModel(unitId) !== dataModel) {
668
+ resolve();
669
+ return;
670
+ }
671
+ session.sourceMutationRevision = dataModel.getMutationRevision();
672
+ session.workerRevision = session.modelRevision;
673
+ session.pendingMutations.length = 0;
674
+ const request = {
675
+ unitId,
676
+ sessionEpoch: session.sessionEpoch,
677
+ snapshot: createDocumentLayoutSnapshot(dataModel.getSnapshot()),
678
+ modelRevision: session.modelRevision,
679
+ locale: this._localeService.getCurrentLocale(),
680
+ localeData: this._localeService.getLocales(),
681
+ direction: this._localeService.getDirection()
682
+ };
683
+ executor.createSession(request).then(resolve, reject);
684
+ }, reject);
685
+ });
686
+ session.cancelPendingCreateTask = () => {
687
+ cancelTask();
688
+ session.cancelPendingCreateTask = null;
689
+ resolve();
690
+ };
691
+ });
692
+ }
693
+ _markSessionDisposed(session) {
694
+ var _session$cancelPendin;
695
+ session.disposed = true;
696
+ (_session$cancelPendin = session.cancelPendingCreateTask) === null || _session$cancelPendin === void 0 || _session$cancelPendin.call(session);
697
+ session.cancelPendingCreateTask = null;
698
+ }
699
+ _disposeManagedSessions() {
700
+ for (const session of this._sessions.values()) this._markSessionDisposed(session);
701
+ }
702
+ };
703
+ _defineProperty(DocLayoutExecutorService, "_performanceSampleLimit", 2048);
704
+ DocLayoutExecutorService = _DocLayoutExecutorService = __decorate([
705
+ __decorateParam(0, _univerjs_core.IUniverInstanceService),
706
+ __decorateParam(1, _univerjs_core.ICommandService),
707
+ __decorateParam(2, (0, _univerjs_core.Inject)(_univerjs_core.LocaleService)),
708
+ __decorateParam(3, _univerjs_core.ILogService)
709
+ ], DocLayoutExecutorService);
710
+
711
+ // package.json
712
+ var name = "@univerjs/docs";
713
+ var version = "1.5.0";
714
+
715
+ // src/config/config.ts
716
+ /**
717
+ * Copyright 2023-present DreamNum Co., Ltd.
718
+ *
719
+ * Licensed under the Apache License, Version 2.0 (the "License");
720
+ * you may not use this file except in compliance with the License.
721
+ * You may obtain a copy of the License at
722
+ *
723
+ * http://www.apache.org/licenses/LICENSE-2.0
724
+ *
725
+ * Unless required by applicable law or agreed to in writing, software
726
+ * distributed under the License is distributed on an "AS IS" BASIS,
727
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
728
+ * See the License for the specific language governing permissions and
729
+ * limitations under the License.
730
+ */
731
+ const DOCS_PLUGIN_CONFIG_KEY = "docs.config";
732
+ const configSymbol = Symbol(DOCS_PLUGIN_CONFIG_KEY);
733
+ const defaultPluginConfig = {};
734
+ const DOCS_WORKER_PLUGIN_CONFIG_KEY = "docs.worker.config";
735
+ const defaultPluginWorkerConfig = {};
736
+
737
+ // src/layout-worker/font-loader.ts
738
+ /** Owns the same explicitly supplied font faces in the rendering and layout realms. */
739
+ var DocsLayoutFontLoader = class extends _univerjs_core.Disposable {
740
+ constructor(..._args) {
741
+ super(..._args);
742
+ _defineProperty(this, "_loading", null);
743
+ _defineProperty(this, "_fontSet", void 0);
744
+ _defineProperty(this, "_faces", []);
745
+ }
746
+ load(fonts) {
747
+ this._loading ??= this._load(fonts);
748
+ return this._loading;
749
+ }
750
+ dispose() {
751
+ for (const face of this._faces) {
752
+ var _this$_fontSet;
753
+ (_this$_fontSet = this._fontSet) === null || _this$_fontSet === void 0 || _this$_fontSet.delete(face);
754
+ }
755
+ if (this._faces.length > 0) _univerjs_engine_render.FontCache.invalidateMetrics(() => true);
756
+ this._faces = [];
757
+ this._fontSet = void 0;
758
+ super.dispose();
759
+ }
760
+ async _load(fonts) {
761
+ this.ensureNotDisposed();
762
+ if (fonts.length === 0) return;
763
+ const fontSet = typeof document === "undefined" ? globalThis.fonts : document.fonts;
764
+ if (typeof FontFace === "undefined" || fontSet == null) throw new Error("Document layout requires FontFace support to load the configured fonts.");
765
+ try {
766
+ const faces = fonts.map(({ family, source, descriptors }) => {
767
+ if (!family.trim() || (typeof source === "string" ? !source.trim() : source.byteLength === 0)) throw new TypeError("Document layout font family and source must not be empty.");
768
+ return new FontFace(family, source, descriptors);
769
+ });
770
+ await Promise.all(faces.map((face) => face.load()));
771
+ this.ensureNotDisposed();
772
+ this._fontSet = fontSet;
773
+ this._faces = faces;
774
+ for (const face of faces) fontSet.add(face);
775
+ _univerjs_engine_render.FontCache.invalidateMetrics(() => true);
776
+ } catch (error) {
777
+ this.dispose();
778
+ throw error;
779
+ }
780
+ }
781
+ };
782
+
783
+ // src/layout-worker/performance-tracker.ts
784
+ const PERFORMANCE_SAMPLE_LIMIT = 2048;
785
+ function isRecord(value) {
786
+ return typeof value === "object" && value != null;
787
+ }
788
+ function getRequest(message) {
789
+ if (!isRecord(message) || typeof message.method !== "string" || !Array.isArray(message.args)) return null;
790
+ const request = message.args[0];
791
+ return isRecord(request) ? {
792
+ method: message.method,
793
+ request
794
+ } : null;
795
+ }
796
+ function getPublicationResult(message) {
797
+ if (!isRecord(message) || !isRecord(message.data)) return null;
798
+ const result = message.data;
799
+ if (isRecord(result.step)) return result.step;
800
+ return result;
801
+ }
802
+ function createTransferMetrics() {
803
+ return {
804
+ mutationTransferMs: [],
805
+ patchTransferMs: [],
806
+ snapshotTransferMs: []
807
+ };
808
+ }
809
+ var DocsLayoutWorkerPerformanceTracker = class {
810
+ constructor() {
811
+ _defineProperty(this, "_metrics", /* @__PURE__ */ new Map());
812
+ }
813
+ recordRequest(message, durationMs) {
814
+ const requestInfo = getRequest(message);
815
+ const unitId = requestInfo === null || requestInfo === void 0 ? void 0 : requestInfo.request.unitId;
816
+ if (requestInfo == null || typeof unitId !== "string") return;
817
+ if (requestInfo.method === "createSession") {
818
+ this._append(unitId, "snapshotTransferMs", durationMs);
819
+ return;
820
+ }
821
+ if (requestInfo.method === "startLayout" && Array.isArray(requestInfo.request.mutations) && requestInfo.request.mutations.length > 0) this._append(unitId, "mutationTransferMs", durationMs);
822
+ }
823
+ recordResponse(message, durationMs) {
824
+ const result = getPublicationResult(message);
825
+ if (result == null || typeof result.unitId !== "string" || result.publication == null) return;
826
+ this._append(result.unitId, "patchTransferMs", durationMs);
827
+ }
828
+ getMetrics(unitId) {
829
+ const metrics = this._metrics.get(unitId) ?? createTransferMetrics();
830
+ return {
831
+ mutationTransferMs: [...metrics.mutationTransferMs],
832
+ patchTransferMs: [...metrics.patchTransferMs],
833
+ snapshotTransferMs: [...metrics.snapshotTransferMs]
834
+ };
835
+ }
836
+ reset(unitId) {
837
+ this._metrics.delete(unitId);
838
+ }
839
+ resetAll() {
840
+ this._metrics.clear();
841
+ }
842
+ _append(unitId, metric, durationMs) {
843
+ const metrics = this._metrics.get(unitId) ?? createTransferMetrics();
844
+ const samples = metrics[metric];
845
+ samples.push(durationMs);
846
+ if (samples.length > PERFORMANCE_SAMPLE_LIMIT) samples.splice(0, samples.length - PERFORMANCE_SAMPLE_LIMIT);
847
+ this._metrics.set(unitId, metrics);
848
+ }
849
+ };
850
+
851
+ // src/layout-worker/protocol.ts
852
+ const DOCS_LAYOUT_WORKER_CHANNEL = "univer.docs-layout-worker";
853
+
854
+ Object.defineProperty(exports, "DOCS_LAYOUT_WORKER_CHANNEL", {
855
+ enumerable: true,
856
+ get: function () {
857
+ return DOCS_LAYOUT_WORKER_CHANNEL;
858
+ }
859
+ });
860
+ Object.defineProperty(exports, "DOCS_PLUGIN_CONFIG_KEY", {
861
+ enumerable: true,
862
+ get: function () {
863
+ return DOCS_PLUGIN_CONFIG_KEY;
864
+ }
865
+ });
866
+ Object.defineProperty(exports, "DOCS_WORKER_PLUGIN_CONFIG_KEY", {
867
+ enumerable: true,
868
+ get: function () {
869
+ return DOCS_WORKER_PLUGIN_CONFIG_KEY;
870
+ }
871
+ });
872
+ Object.defineProperty(exports, "DocLayoutExecutorService", {
873
+ enumerable: true,
874
+ get: function () {
875
+ return DocLayoutExecutorService;
876
+ }
877
+ });
878
+ Object.defineProperty(exports, "DocLayoutExecutorState", {
879
+ enumerable: true,
880
+ get: function () {
881
+ return DocLayoutExecutorState;
882
+ }
883
+ });
884
+ Object.defineProperty(exports, "DocLayoutExecutorType", {
885
+ enumerable: true,
886
+ get: function () {
887
+ return DocLayoutExecutorType;
888
+ }
889
+ });
890
+ Object.defineProperty(exports, "DocLayoutSessionStatus", {
891
+ enumerable: true,
892
+ get: function () {
893
+ return DocLayoutSessionStatus;
894
+ }
895
+ });
896
+ Object.defineProperty(exports, "DocsLayoutFontLoader", {
897
+ enumerable: true,
898
+ get: function () {
899
+ return DocsLayoutFontLoader;
900
+ }
901
+ });
902
+ Object.defineProperty(exports, "DocsLayoutWorkerPerformanceTracker", {
903
+ enumerable: true,
904
+ get: function () {
905
+ return DocsLayoutWorkerPerformanceTracker;
906
+ }
907
+ });
908
+ Object.defineProperty(exports, "RICH_TEXT_EDITING_MUTATION_ID", {
909
+ enumerable: true,
910
+ get: function () {
911
+ return RICH_TEXT_EDITING_MUTATION_ID;
912
+ }
913
+ });
914
+ Object.defineProperty(exports, "__decorate", {
915
+ enumerable: true,
916
+ get: function () {
917
+ return __decorate;
918
+ }
919
+ });
920
+ Object.defineProperty(exports, "__decorateParam", {
921
+ enumerable: true,
922
+ get: function () {
923
+ return __decorateParam;
924
+ }
925
+ });
926
+ Object.defineProperty(exports, "_defineProperty", {
927
+ enumerable: true,
928
+ get: function () {
929
+ return _defineProperty;
930
+ }
931
+ });
932
+ Object.defineProperty(exports, "defaultPluginConfig", {
933
+ enumerable: true,
934
+ get: function () {
935
+ return defaultPluginConfig;
936
+ }
937
+ });
938
+ Object.defineProperty(exports, "defaultPluginWorkerConfig", {
939
+ enumerable: true,
940
+ get: function () {
941
+ return defaultPluginWorkerConfig;
942
+ }
943
+ });
944
+ Object.defineProperty(exports, "name", {
945
+ enumerable: true,
946
+ get: function () {
947
+ return name;
948
+ }
949
+ });
950
+ Object.defineProperty(exports, "version", {
951
+ enumerable: true,
952
+ get: function () {
953
+ return version;
954
+ }
955
+ });