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