@univerjs/docs 1.4.0 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/worker.js CHANGED
@@ -1,5 +1,338 @@
1
- import { _ as __decorateParam, c as defaultPluginWorkerConfig, g as __decorate, l as name, o as DOCS_WORKER_PLUGIN_CONFIG_KEY, t as startDocsLayoutWorker, u as version, v as _defineProperty } from "./worker-Dny9WctR.js";
2
- import { IConfigService, Inject, Injector, Plugin, merge } from "@univerjs/core";
1
+ import { _ as _defineProperty, a as DOCS_WORKER_PLUGIN_CONFIG_KEY, c as name, f as DocLayoutExecutorType, g as __decorateParam, h as __decorate, l as version, n as DocsLayoutWorkerPerformanceTracker, p as DocLayoutSessionStatus, r as DocsLayoutFontLoader, s as defaultPluginWorkerConfig, t as DOCS_LAYOUT_WORKER_CHANNEL } from "./protocol-Cwx95k-U.js";
2
+ import { DocumentDataModel, IConfigService, Inject, Injector, LocaleService, Plugin, Tools, merge, requestImmediateMacroTask } from "@univerjs/core";
3
+ import { Observable, shareReplay } from "rxjs";
4
+ import { ChannelService, fromModule } from "@univerjs/rpc";
5
+ import { DocumentLayoutSession, FontCache, setDocsCustomBlockRenderViewportProvider } from "@univerjs/engine-render/worker";
6
+
7
+ // src/layout-worker/worker.ts
8
+ const FONT_PROBE_CONTENT = "Univer 文档 Worker 0123456789";
9
+ const FONT_PROBE_STYLE = "16px Arial";
10
+ const WORKER_LAYOUT_INTERRUPT_INTERVAL = 8;
11
+ function yieldForWorkerMessage() {
12
+ return new Promise((resolve) => {
13
+ requestImmediateMacroTask(() => resolve());
14
+ });
15
+ }
16
+ function createDocsLayoutWorkerMessageProtocol(performanceTracker) {
17
+ return {
18
+ send(message) {
19
+ const startedAt = Tools.now();
20
+ postMessage(message);
21
+ performanceTracker.recordResponse(message, Tools.now() - startedAt);
22
+ },
23
+ onMessage: new Observable((subscriber) => {
24
+ const handler = (event) => subscriber.next(event.data);
25
+ addEventListener("message", handler);
26
+ return () => removeEventListener("message", handler);
27
+ }).pipe(shareReplay({
28
+ bufferSize: 1,
29
+ refCount: true
30
+ }))
31
+ };
32
+ }
33
+ function getCustomRangePresentationKey(entry) {
34
+ return JSON.stringify([entry.segmentId, entry.rangeId]);
35
+ }
36
+ function applyRecordPatch(target, patch) {
37
+ if (patch == null) return;
38
+ for (const key of patch.removals) delete target[key];
39
+ Object.assign(target, patch.upserts);
40
+ }
41
+ var DocsLayoutWorkerRuntime = class {
42
+ constructor(_performanceTracker = new DocsLayoutWorkerPerformanceTracker()) {
43
+ this._performanceTracker = _performanceTracker;
44
+ _defineProperty(this, "_sessions", /* @__PURE__ */ new Map());
45
+ _defineProperty(this, "_fontLoader", new DocsLayoutFontLoader());
46
+ _defineProperty(this, "type", "worker");
47
+ }
48
+ initialize(fontFaces = []) {
49
+ return this._fontLoader.load(fontFaces);
50
+ }
51
+ async getCapabilities() {
52
+ const metrics = FontCache.getMeasureText(FONT_PROBE_CONTENT, FONT_PROBE_STYLE);
53
+ return {
54
+ protocolVersion: 5,
55
+ executor: "worker",
56
+ offscreenCanvas: typeof OffscreenCanvas !== "undefined",
57
+ structuredClone: typeof structuredClone === "function",
58
+ fontProbe: {
59
+ content: FONT_PROBE_CONTENT,
60
+ font: FONT_PROBE_STYLE,
61
+ width: metrics.width,
62
+ actualBoundingBoxAscent: metrics.actualBoundingBoxAscent,
63
+ actualBoundingBoxDescent: metrics.actualBoundingBoxDescent
64
+ }
65
+ };
66
+ }
67
+ async recover() {
68
+ for (const session of this._sessions.values()) for (const mount of session.layoutSessions.values()) mount.layoutSession.dispose();
69
+ this._sessions.clear();
70
+ }
71
+ async createSession(request) {
72
+ if (typeof OffscreenCanvas === "undefined") throw new Error("Document layout Worker requires OffscreenCanvas text measurement support.");
73
+ const currentSession = this._sessions.get(request.unitId);
74
+ if (currentSession != null && request.sessionEpoch < currentSession.sessionEpoch) return;
75
+ this._disposeSession(request.unitId);
76
+ FontCache.setNormalLineHeightCache(request.normalFontLineHeights ?? {});
77
+ const dataModel = new DocumentDataModel(request.snapshot);
78
+ const localeService = new LocaleService();
79
+ if (request.localeData != null) localeService.load({ [request.locale]: request.localeData });
80
+ localeService.setLocale(request.locale);
81
+ localeService.setDirection(request.direction);
82
+ this._sessions.set(request.unitId, {
83
+ sessionEpoch: request.sessionEpoch,
84
+ dataModel,
85
+ layoutSessions: /* @__PURE__ */ new Map(),
86
+ localeService,
87
+ modelRevision: request.modelRevision,
88
+ customRangePresentations: /* @__PURE__ */ new Map()
89
+ });
90
+ }
91
+ async startLayout(request) {
92
+ const session = this._sessions.get(request.unitId);
93
+ if (session == null) return { status: "not-found" };
94
+ if (session.modelRevision !== request.baseRevision) return {
95
+ status: "resnapshot-required",
96
+ modelRevision: session.modelRevision
97
+ };
98
+ if (!this._applyMutations(session, request)) return {
99
+ status: "resnapshot-required",
100
+ modelRevision: session.modelRevision
101
+ };
102
+ FontCache.setNormalLineHeightCache(request.normalFontLineHeights ?? {});
103
+ this._updateCustomRangePresentations(session, request);
104
+ this._applyCustomRangePresentations(session.dataModel, Array.from(session.customRangePresentations.values()));
105
+ let mount = session.layoutSessions.get(request.mountId);
106
+ if (mount != null && (request.mountEpoch < mount.mountEpoch || request.mountEpoch === mount.mountEpoch && request.viewportEpoch < mount.viewportEpoch)) return { status: "superseded" };
107
+ if (mount != null && request.mountEpoch > mount.mountEpoch) {
108
+ mount.layoutSession.dispose();
109
+ session.layoutSessions.delete(request.mountId);
110
+ mount = void 0;
111
+ }
112
+ if (mount == null) {
113
+ const customBlockViewports = { ...request.customBlockViewports };
114
+ applyRecordPatch(customBlockViewports, request.customBlockViewportPatch);
115
+ mount = {
116
+ mountId: request.mountId,
117
+ layoutSession: new DocumentLayoutSession(session.dataModel, session.localeService),
118
+ customBlockViewports,
119
+ metricsRevision: request.metricsRevision,
120
+ mountEpoch: request.mountEpoch,
121
+ viewportEpoch: request.viewportEpoch,
122
+ activeGeneration: null,
123
+ cancelledGeneration: null
124
+ };
125
+ session.layoutSessions.set(request.mountId, mount);
126
+ } else {
127
+ if (request.customBlockViewports != null) mount.customBlockViewports = { ...request.customBlockViewports };
128
+ applyRecordPatch(mount.customBlockViewports, request.customBlockViewportPatch);
129
+ mount.metricsRevision = request.metricsRevision;
130
+ mount.viewportEpoch = request.viewportEpoch;
131
+ }
132
+ const generation = mount.layoutSession.start({
133
+ waitForHyphenationPatterns: true,
134
+ reason: request.reason,
135
+ anchor: request.anchor,
136
+ priorityAnchor: request.priorityAnchor,
137
+ invalidation: request.invalidation,
138
+ modernPageWidth: request.modernPageWidth,
139
+ modernHorizontalMargin: request.modernHorizontalMargin
140
+ });
141
+ mount.activeGeneration = generation;
142
+ mount.cancelledGeneration = null;
143
+ return {
144
+ status: "accepted",
145
+ step: await this._runLayoutStep(session, mount, generation, request.budgetMs)
146
+ };
147
+ }
148
+ _applyMutations(session, request) {
149
+ for (const mutation of request.mutations) {
150
+ if (mutation.baseRevision !== session.modelRevision || mutation.modelRevision !== mutation.baseRevision + 1) return false;
151
+ session.dataModel.apply(mutation.actions);
152
+ session.modelRevision = mutation.modelRevision;
153
+ }
154
+ if (session.modelRevision !== request.modelRevision) return false;
155
+ if (request.mutations.length > 0) for (const mount of session.layoutSessions.values()) {
156
+ mount.activeGeneration = null;
157
+ mount.cancelledGeneration = null;
158
+ mount.layoutSession.resetDataModel(session.dataModel);
159
+ }
160
+ return true;
161
+ }
162
+ _applyCustomRangePresentations(dataModel, presentations) {
163
+ const rangeMaps = /* @__PURE__ */ new Map();
164
+ const segmentModels = [
165
+ ["", dataModel],
166
+ ...dataModel.headerModelMap,
167
+ ...dataModel.footerModelMap
168
+ ];
169
+ for (const [segmentId, segmentModel] of segmentModels) {
170
+ var _segmentModel$getBody;
171
+ const rangeMap = /* @__PURE__ */ new Map();
172
+ for (const range of ((_segmentModel$getBody = segmentModel.getBody()) === null || _segmentModel$getBody === void 0 ? void 0 : _segmentModel$getBody.customRanges) ?? []) {
173
+ const workerRange = range;
174
+ delete workerRange.active;
175
+ delete workerRange.glyphAscentEm;
176
+ delete workerRange.glyphDescentEm;
177
+ delete workerRange.glyphWidthEm;
178
+ delete workerRange.show;
179
+ if (!rangeMap.has(range.rangeId)) rangeMap.set(range.rangeId, workerRange);
180
+ }
181
+ rangeMaps.set(segmentId, rangeMap);
182
+ }
183
+ for (const { segmentId, rangeId, presentation } of presentations ?? []) {
184
+ const rangeMap = rangeMaps.get(segmentId);
185
+ const range = rangeMap === null || rangeMap === void 0 ? void 0 : rangeMap.get(rangeId);
186
+ if (range != null) {
187
+ Object.assign(range, presentation);
188
+ rangeMap === null || rangeMap === void 0 || rangeMap.delete(rangeId);
189
+ }
190
+ }
191
+ }
192
+ _updateCustomRangePresentations(session, request) {
193
+ var _request$customRangeP, _request$customRangeP2;
194
+ if (request.customRangePresentations != null) {
195
+ session.customRangePresentations.clear();
196
+ for (const entry of request.customRangePresentations) {
197
+ const key = getCustomRangePresentationKey(entry);
198
+ if (!session.customRangePresentations.has(key)) session.customRangePresentations.set(key, entry);
199
+ }
200
+ }
201
+ for (const removal of ((_request$customRangeP = request.customRangePresentationPatch) === null || _request$customRangeP === void 0 ? void 0 : _request$customRangeP.removals) ?? []) session.customRangePresentations.delete(getCustomRangePresentationKey(removal));
202
+ for (const entry of ((_request$customRangeP2 = request.customRangePresentationPatch) === null || _request$customRangeP2 === void 0 ? void 0 : _request$customRangeP2.upserts) ?? []) session.customRangePresentations.set(getCustomRangePresentationKey(entry), entry);
203
+ }
204
+ async stepLayout(request) {
205
+ const session = this._getSession(request.unitId);
206
+ const mount = this._getLayoutMount(session, request);
207
+ return await this._runLayoutStep(session, mount, request.generation, request.budgetMs);
208
+ }
209
+ async publishBacklog(request) {
210
+ const session = this._getSession(request.unitId);
211
+ const mount = this._getLayoutMount(session, request);
212
+ return this._runWithCustomBlockViewports(session, mount, () => ({
213
+ ...mount.layoutSession.publishBacklog(request.generation),
214
+ unitId: request.unitId,
215
+ mountId: request.mountId,
216
+ mountEpoch: mount.mountEpoch,
217
+ viewportEpoch: mount.viewportEpoch,
218
+ modelRevision: session.modelRevision,
219
+ metricsRevision: mount.metricsRevision
220
+ }));
221
+ }
222
+ async getLayoutPage(request) {
223
+ const session = this._getSession(request.unitId);
224
+ const mount = this._getLayoutMount(session, request);
225
+ return {
226
+ ...request,
227
+ modelRevision: session.modelRevision,
228
+ metricsRevision: mount.metricsRevision,
229
+ page: mount.layoutSession.getPage(request.pageIndex)
230
+ };
231
+ }
232
+ async cancelLayout(request) {
233
+ var _this$_sessions$get;
234
+ 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);
235
+ if ((mount === null || mount === void 0 ? void 0 : mount.mountEpoch) === request.mountEpoch && mount.viewportEpoch === request.viewportEpoch) {
236
+ if (request.generation == null || request.generation === mount.activeGeneration) mount.cancelledGeneration = request.generation ?? mount.activeGeneration;
237
+ mount.layoutSession.cancel(request.generation);
238
+ }
239
+ }
240
+ async getPerformanceMetrics(unitId) {
241
+ return this._performanceTracker.getMetrics(unitId);
242
+ }
243
+ async resetPerformanceMetrics(unitId) {
244
+ this._performanceTracker.reset(unitId);
245
+ }
246
+ async disposeLayoutMount(request) {
247
+ const session = this._sessions.get(request.unitId);
248
+ const mount = session === null || session === void 0 ? void 0 : session.layoutSessions.get(request.mountId);
249
+ if (session == null || mount == null || mount.mountEpoch !== request.mountEpoch || mount.viewportEpoch !== request.viewportEpoch) return;
250
+ session.layoutSessions.delete(request.mountId);
251
+ mount.activeGeneration = null;
252
+ mount.layoutSession.dispose();
253
+ }
254
+ async disposeSession(request) {
255
+ const session = this._sessions.get(request.unitId);
256
+ if ((session === null || session === void 0 ? void 0 : session.sessionEpoch) !== request.sessionEpoch) return;
257
+ this._disposeSession(request.unitId);
258
+ this._performanceTracker.reset(request.unitId);
259
+ }
260
+ dispose() {
261
+ this._fontLoader.dispose();
262
+ for (const unitId of this._sessions.keys()) this._disposeSession(unitId);
263
+ this._performanceTracker.resetAll();
264
+ }
265
+ _getSession(unitId) {
266
+ const session = this._sessions.get(unitId);
267
+ if (session == null) throw new Error(`Document layout Worker session not found for unit "${unitId}".`);
268
+ return session;
269
+ }
270
+ _getLayoutMount(session, request) {
271
+ const mount = session.layoutSessions.get(request.mountId);
272
+ if (mount == null) throw new Error(`Document layout Worker mount not found: "${request.mountId}".`);
273
+ if (mount.mountEpoch !== request.mountEpoch || mount.viewportEpoch !== request.viewportEpoch) throw new Error(`Document layout Worker rejected a stale mount publication: "${request.mountId}".`);
274
+ return mount;
275
+ }
276
+ async _runLayoutStep(session, mount, generation, budgetMs) {
277
+ const result = this._runWithCustomBlockViewports(session, mount, () => ({
278
+ ...mount.layoutSession.step(generation, budgetMs, WORKER_LAYOUT_INTERRUPT_INTERVAL),
279
+ unitId: session.dataModel.getUnitId(),
280
+ mountId: mount.mountId,
281
+ mountEpoch: mount.mountEpoch,
282
+ viewportEpoch: mount.viewportEpoch,
283
+ modelRevision: session.modelRevision,
284
+ metricsRevision: mount.metricsRevision
285
+ }));
286
+ await yieldForWorkerMessage();
287
+ if (mount.activeGeneration === generation && mount.cancelledGeneration !== generation) return result;
288
+ return this._runWithCustomBlockViewports(session, mount, () => ({
289
+ ...mount.layoutSession.step(generation, 0, 1),
290
+ unitId: session.dataModel.getUnitId(),
291
+ mountId: mount.mountId,
292
+ mountEpoch: mount.mountEpoch,
293
+ viewportEpoch: mount.viewportEpoch,
294
+ modelRevision: session.modelRevision,
295
+ metricsRevision: mount.metricsRevision
296
+ }));
297
+ }
298
+ _runWithCustomBlockViewports(session, mount, run) {
299
+ const unregister = setDocsCustomBlockRenderViewportProvider((unitId, blockId) => unitId === session.dataModel.getUnitId() ? mount.customBlockViewports[blockId] : null);
300
+ try {
301
+ return run();
302
+ } finally {
303
+ unregister();
304
+ }
305
+ }
306
+ _disposeSession(unitId) {
307
+ const session = this._sessions.get(unitId);
308
+ if (session == null) return;
309
+ this._sessions.delete(unitId);
310
+ for (const mount of session.layoutSessions.values()) {
311
+ mount.activeGeneration = null;
312
+ mount.layoutSession.dispose();
313
+ }
314
+ session.layoutSessions.clear();
315
+ session.dataModel.dispose();
316
+ session.localeService.dispose();
317
+ }
318
+ };
319
+ var DocsLayoutWorkerChannelService = class extends ChannelService {
320
+ constructor(protocol, _runtime) {
321
+ super(protocol);
322
+ this._runtime = _runtime;
323
+ }
324
+ dispose() {
325
+ this._runtime.dispose();
326
+ super.dispose();
327
+ }
328
+ };
329
+ function startDocsLayoutWorker() {
330
+ const performanceTracker = new DocsLayoutWorkerPerformanceTracker();
331
+ const runtime = new DocsLayoutWorkerRuntime(performanceTracker);
332
+ const channelService = new DocsLayoutWorkerChannelService(createDocsLayoutWorkerMessageProtocol(performanceTracker), runtime);
333
+ channelService.registerChannel(DOCS_LAYOUT_WORKER_CHANNEL, fromModule(runtime));
334
+ return channelService;
335
+ }
3
336
 
4
337
  // src/worker.ts
5
338
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@univerjs/docs",
3
- "version": "1.4.0",
3
+ "version": "1.5.1",
4
4
  "private": false,
5
5
  "description": "Core document model and rich-text operations for Univer Docs.",
6
6
  "author": "DreamNum Co., Ltd. <developer@univer.ai>",
@@ -67,16 +67,16 @@
67
67
  "rxjs": ">=7.0.0"
68
68
  },
69
69
  "dependencies": {
70
- "@univerjs/core": "1.4.0",
71
- "@univerjs/engine-render": "1.4.0",
72
- "@univerjs/protocol": "1.4.0",
73
- "@univerjs/rpc": "1.4.0"
70
+ "@univerjs/core": "1.5.1",
71
+ "@univerjs/engine-render": "1.5.1",
72
+ "@univerjs/protocol": "1.5.1",
73
+ "@univerjs/rpc": "1.5.1"
74
74
  },
75
75
  "devDependencies": {
76
- "@univerjs-infra/shared": "1.4.0",
76
+ "@univerjs-infra/shared": "1.5.1",
77
77
  "rxjs": "7.8.2",
78
- "tsrs": "0.20.1-ts7.1.0-beta",
79
- "vitest": "^5.0.5"
78
+ "tsrs": "0.23.0-ts7.1.0-beta",
79
+ "vitest": "^5.1.0"
80
80
  },
81
81
  "scripts": {
82
82
  "test": "vitest run",