@univerjs-pro/collaboration-client 0.1.9

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.
Files changed (52) hide show
  1. package/README.md +18 -0
  2. package/lib/cjs/index.js +4 -0
  3. package/lib/es/index.js +3626 -0
  4. package/lib/index.css +1 -0
  5. package/lib/types/controllers/collab-cursor/__tests__/doc-collab-cursor.controller.spec.d.ts +1 -0
  6. package/lib/types/controllers/collab-cursor/__tests__/serialize-text-ranges.spec.d.ts +1 -0
  7. package/lib/types/controllers/collab-cursor/__tests__/sheet-collab-cursor.controller.spec.d.ts +1 -0
  8. package/lib/types/controllers/collab-cursor/collab-cursor.controller.d.ts +24 -0
  9. package/lib/types/controllers/collab-cursor/doc-collab-cursor-entity.d.ts +40 -0
  10. package/lib/types/controllers/collab-cursor/doc-collab-cursor-render.controller.d.ts +22 -0
  11. package/lib/types/controllers/collab-cursor/serialize-text-ranges.d.ts +4 -0
  12. package/lib/types/controllers/collab-cursor/sheet-collab-cursor-entity.d.ts +41 -0
  13. package/lib/types/controllers/collab-cursor/sheet-collab-cursor-render.controller.d.ts +23 -0
  14. package/lib/types/controllers/collab-status/collab-status.controller.d.ts +18 -0
  15. package/lib/types/controllers/collaboration/__tests__/collaboration.controller.spec.d.ts +5 -0
  16. package/lib/types/controllers/collaboration/__tests__/mock-text-selection-render-manager.service.d.ts +10 -0
  17. package/lib/types/controllers/collaboration/__tests__/mocks.d.ts +55 -0
  18. package/lib/types/controllers/collaboration/collaboration-state.d.ts +266 -0
  19. package/lib/types/controllers/collaboration/collaboration.controller.d.ts +110 -0
  20. package/lib/types/controllers/collaboration/utils/changeset-utils.d.ts +17 -0
  21. package/lib/types/controllers/data-loader/__tests__/data-loader.controller.spec.d.ts +1 -0
  22. package/lib/types/controllers/data-loader/data-loader.controller.d.ts +23 -0
  23. package/lib/types/controllers/file-name/file-name.controller.d.ts +13 -0
  24. package/lib/types/index.d.ts +11 -0
  25. package/lib/types/locale/en-US.d.ts +4 -0
  26. package/lib/types/locale/index.d.ts +2 -0
  27. package/lib/types/locale/zh-CN.d.ts +29 -0
  28. package/lib/types/models/cursor.d.ts +29 -0
  29. package/lib/types/plugin.d.ts +20 -0
  30. package/lib/types/services/auth-server/auth-server.service.d.ts +15 -0
  31. package/lib/types/services/collaboration-session/collaboration-session.service.d.ts +107 -0
  32. package/lib/types/services/color-assign/color-assign.service.d.ts +11 -0
  33. package/lib/types/services/ime-cache-transform/doc-transform-ime-cache.service.d.ts +12 -0
  34. package/lib/types/services/local-cache/local-cache.service.d.ts +43 -0
  35. package/lib/types/services/member/member.service.d.ts +33 -0
  36. package/lib/types/services/range-selection/sheet-transform-selections.service.d.ts +9 -0
  37. package/lib/types/services/single-active-unit/single-active-unit.service.d.ts +40 -0
  38. package/lib/types/services/snapshot-server/snapshot-server.service.d.ts +22 -0
  39. package/lib/types/services/socket/collaboration-socket.service.d.ts +36 -0
  40. package/lib/types/services/socket/serialize.d.ts +4 -0
  41. package/lib/types/services/sync-editing-collab-cursor/doc-sync-editing-collab-cursor.service.d.ts +14 -0
  42. package/lib/types/services/text-selection/doc-transform-selections.service.d.ts +9 -0
  43. package/lib/types/services/undoredo/collaborative-undoredo.service.d.ts +20 -0
  44. package/lib/types/services/url/url.service.d.ts +13 -0
  45. package/lib/types/services/url/web-url.service.d.ts +11 -0
  46. package/lib/types/views/components/CollabStatus.d.ts +14 -0
  47. package/lib/types/views/components/CollabStatus.stories.d.ts +9 -0
  48. package/lib/types/views/shapes/doc-collab-cursor.d.ts +27 -0
  49. package/lib/types/views/shapes/sheet-collab-cursor.shape.d.ts +27 -0
  50. package/lib/types/views/shapes/text-bubble.shape.d.ts +20 -0
  51. package/lib/umd/index.js +4 -0
  52. package/package.json +102 -0
@@ -0,0 +1,3626 @@
1
+ var ws = Object.defineProperty;
2
+ var Ms = (i, e, t) => e in i ? ws(i, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[e] = t;
3
+ var l = (i, e, t) => (Ms(i, typeof e != "symbol" ? e + "" : e, t), t);
4
+ import { Disposable as X, toDisposable as T, UniverInstanceType as M, IUniverInstanceService as k, DisposableCollection as Jt, IConfigService as z, ILogService as D, ISnapshotServerService as qt, RxDisposable as L, LocaleService as H, ILocalStorageService as Ds, Tools as P, ICommandService as O, TextX as Ns, UniverPermissionService as Ke, IUndoRedoService as J, sequenceExecute as As, OnLifecycle as ee, LifecycleStages as te, CommandType as Zt, Rectangle as Us, ThemeService as Qt, Workbook as ks, textEncoder as Mt, b64DecodeUnicode as Dt, LocalUndoRedoService as Ls, IContextService as $s, COLORS as De, ColorKit as Ps, Plugin as xs } from "@univerjs/core";
5
+ import { MessageType as be } from "@univerjs/design";
6
+ import { IBeforeCloseService as es, IMessageService as Me, INotificationService as Hs, useObservable as js, DesktopUIPart as Bs, IUIController as Vs } from "@univerjs/ui";
7
+ import { CollaborationEvent as m, parseChangesetToProtocol as Fs, RevisionService as $, isTransformMutationFailure as Le, isTransformMutationsWithChangesetSuccess as _e, ITransformService as W, mapDocumentTypeToUniverType as ts, isTransformChangesetsSuccess as St, CompressMutationService as vt, parseProtocolChangeset as Nt, SnapshotService as Ws, isTransformMutationsWithChangesetFailure as At } from "@univerjs-pro/collaboration";
8
+ import { createIdentifier as pt, Inject as _, Injector as I, Optional as Ye } from "@wendellhu/redi";
9
+ import { merge as Ct, Subject as ae, BehaviorSubject as U, distinctUntilChanged as Gs, fromEvent as ss, of as Te, takeUntil as R, debounceTime as is, filter as Ut, switchMap as ot, combineLatest as ns, shareReplay as Ks, mapTo as Ys, concatMap as Xs } from "rxjs";
10
+ import { map as ce, takeUntil as It, take as $e, filter as kt, delay as Lt, shareReplay as zs, switchMap as rs } from "rxjs/operators";
11
+ import { IMEInputManagerService as Qe, TextSelectionManagerService as os, serializeTextRange as as, DocStateChangeManagerService as Js, SetTextSelectionsOperation as qs, RichTextEditingMutation as Zs, getDocObject as Qs, DocSkeletonManagerService as ei } from "@univerjs/docs";
12
+ import { HTTPService as Re, WebSocketService as cs, IHTTPImplementation as ti, XHRHTTPImplementation as si, ThresholdInterceptorFactory as ii } from "@univerjs/network";
13
+ import { SelectionManagerService as hs, SetSelectionsOperation as at, InsertSheetMutation as ni, RefRangeService as ri, EffectRefRangId as j, handleIRemoveRow as oi, handleIRemoveCol as ai, handleMoveRange as ci, handleInsertRow as hi, handleInsertRangeMoveRight as li, handleInsertRangeMoveDown as _i, handleInsertCol as ui, handleDeleteRangeMoveUp as di, handleDeleteRangeMoveLeft as gi, runRefRangeMutations as mi, SetWorksheetActivateCommand as fi } from "@univerjs/sheets";
14
+ import { deserializeRangeWithSheet as Si, serializeRangeWithSheet as vi } from "@univerjs/engine-formula";
15
+ import Et from "lodash/debounce";
16
+ import { Shape as ls, Rect as ct, Vector2 as $t, IRenderManagerService as _s, NodePositionConvertToCursor as pi, getColor as Ne, TEXT_RANGE_LAYER_INDEX as Ae, RegularPolygon as Ci } from "@univerjs/engine-render";
17
+ import { VIEWPORT_KEY as Ii, getCoordByCell as Pt, getSheetObject as Ei, SheetSkeletonManagerService as bi } from "@univerjs/sheets-ui";
18
+ import { useDependency as Ti, connectInjector as Ri } from "@wendellhu/redi/react-bindings";
19
+ import oe, { forwardRef as bt, useRef as yi, createElement as Tt } from "react";
20
+ import Oi from "clsx";
21
+ import { IRemoteInstanceService as wi } from "@univerjs/rpc";
22
+ var x = /* @__PURE__ */ ((i) => (i[i.UNIVER_UNKNOWN = 0] = "UNIVER_UNKNOWN", i[i.UNIVER_DOC = 1] = "UNIVER_DOC", i[i.UNIVER_SHEET = 2] = "UNIVER_SHEET", i[i.UNIVER_SLIDE = 3] = "UNIVER_SLIDE", i[i.UNRECOGNIZED = -1] = "UNRECOGNIZED", i))(x || {}), C = /* @__PURE__ */ ((i) => (i[i.UNKNOWN_CMD = 0] = "UNKNOWN_CMD", i[i.HELLO = 1] = "HELLO", i[i.JOIN = 2] = "JOIN", i[i.LEAVE = 3] = "LEAVE", i[i.INGEST = 4] = "INGEST", i[i.HEARTBEAT = 5] = "HEARTBEAT", i[i.RECV = 6] = "RECV", i[i.UNRECOGNIZED = -1] = "UNRECOGNIZED", i))(C || {}), Rt = /* @__PURE__ */ ((i) => (i[i.UNKNOWN_CODE = 0] = "UNKNOWN_CODE", i[i.OK = 1] = "OK", i[i.FAIL = 2] = "FAIL", i[i.UNRECOGNIZED = -1] = "UNRECOGNIZED", i))(Rt || {}), Mi = (i, e, t, s) => {
23
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
24
+ (o = i[r]) && (n = o(n) || n);
25
+ return n;
26
+ }, Di = (i, e) => (t, s) => e(t, s, i);
27
+ let Z = class extends X {
28
+ constructor(e) {
29
+ super();
30
+ l(this, "_roomMembers", /* @__PURE__ */ new Map());
31
+ l(this, "_currentUser", null);
32
+ this._univerInstanceService = e, this.disposeWithMe(
33
+ T(
34
+ Ct(
35
+ this._univerInstanceService.getTypeOfUnitDisposed$(M.UNIVER_SHEET).pipe(ce((t) => t.getUnitId())),
36
+ this._univerInstanceService.getTypeOfUnitDisposed$(M.UNIVER_DOC).pipe(ce((t) => t.getUnitId())),
37
+ this._univerInstanceService.getTypeOfUnitDisposed$(M.UNIVER_SLIDE).pipe(ce((t) => t.getUnitId()))
38
+ ).subscribe((t) => this._removeRoom(t))
39
+ )
40
+ );
41
+ }
42
+ setCurrentUser(e) {
43
+ this._currentUser = e;
44
+ }
45
+ getCurrentUser() {
46
+ return this._currentUser;
47
+ }
48
+ updateMember(e, t) {
49
+ let s = this._roomMembers.get(e);
50
+ s || (s = new Ni(), this._roomMembers.set(e, s)), s.updateMember(t);
51
+ }
52
+ removeMember(e, t) {
53
+ const s = this._roomMembers.get(e);
54
+ s && s.removeMember(t);
55
+ }
56
+ getRoom(e) {
57
+ return this._roomMembers.get(e);
58
+ }
59
+ getMember(e, t) {
60
+ const s = this._roomMembers.get(e);
61
+ if (s)
62
+ return s.getMember(t);
63
+ }
64
+ _removeRoom(e) {
65
+ const t = this._roomMembers.get(e);
66
+ t && (t.dispose(), this._roomMembers.delete(e));
67
+ }
68
+ dispose() {
69
+ this._roomMembers.forEach((e) => e.dispose()), this._roomMembers.clear();
70
+ }
71
+ };
72
+ Z = Mi([
73
+ Di(0, k)
74
+ ], Z);
75
+ class Ni extends X {
76
+ constructor() {
77
+ super(...arguments);
78
+ l(this, "_members", /* @__PURE__ */ new Map());
79
+ }
80
+ dispose() {
81
+ this._members.clear();
82
+ }
83
+ updateMember(t) {
84
+ this._members.set(t.memberID, t);
85
+ }
86
+ removeMember(t) {
87
+ this._members.delete(t);
88
+ }
89
+ getMember(t) {
90
+ return this._members.get(t);
91
+ }
92
+ }
93
+ function Ai(i) {
94
+ var s, n, r;
95
+ const e = i.data, t = JSON.parse(e);
96
+ switch (t.cmd) {
97
+ case C.HEARTBEAT:
98
+ case C.HELLO: {
99
+ const o = t.infoRsp;
100
+ return { ...t, data: o, cmd: t.cmd };
101
+ }
102
+ case C.JOIN: {
103
+ const o = t.joinRsp;
104
+ return { ...t, data: o, cmd: t.cmd };
105
+ }
106
+ case C.RECV: {
107
+ const o = t.collaMsg;
108
+ switch (o.eventID) {
109
+ case m.CHANGESET_ACK:
110
+ return {
111
+ ...t,
112
+ data: { ...o, data: (s = o.csAckEvent) == null ? void 0 : s.cs },
113
+ cmd: t.cmd
114
+ };
115
+ case m.NEW_CHANGESETS:
116
+ return {
117
+ ...t,
118
+ data: { ...o, data: (n = o.newCsEvent) == null ? void 0 : n.cs },
119
+ cmd: t.cmd
120
+ };
121
+ case m.CHANGESET_REJ:
122
+ return {
123
+ ...t,
124
+ data: { ...o, data: (r = o.csRejEvent) == null ? void 0 : r.cs },
125
+ cmd: t.cmd
126
+ };
127
+ case m.UPDATE_CURSOR:
128
+ return {
129
+ ...t,
130
+ data: { ...o, data: o.updateCursorEvent },
131
+ cmd: t.cmd
132
+ };
133
+ case m.USERS_ENTER:
134
+ return {
135
+ ...t,
136
+ data: { ...o, data: o.joinEvent },
137
+ cmd: t.cmd
138
+ };
139
+ case m.USERS_LEAVE:
140
+ return {
141
+ ...t,
142
+ data: { ...o, data: o.leaveEvent },
143
+ cmd: t.cmd
144
+ };
145
+ case m.LIVESHARE_NEW_HOST:
146
+ return {
147
+ ...t,
148
+ data: { ...o, data: o.liveShareNewHost },
149
+ cmd: t.cmd
150
+ };
151
+ case m.LIVESHARE_FETCH_OPERATIONS:
152
+ case m.LIVESHARE_OPERATION:
153
+ return {
154
+ ...t,
155
+ data: { ...o, data: o.liveShareOperation },
156
+ cmd: t.cmd
157
+ };
158
+ case m.LIVESHARE_TERMINATE:
159
+ return {
160
+ ...t,
161
+ data: { ...o, data: o.liveShareNewHost },
162
+ cmd: t.cmd
163
+ };
164
+ case m.MSG_FOR_ERROR:
165
+ return {
166
+ ...t,
167
+ data: o,
168
+ cmd: t.cmd
169
+ };
170
+ default:
171
+ return t;
172
+ }
173
+ }
174
+ default:
175
+ return t;
176
+ }
177
+ }
178
+ function Ui(i) {
179
+ switch (i.cmd) {
180
+ case C.HEARTBEAT:
181
+ case C.HELLO:
182
+ return JSON.stringify({
183
+ cmd: i.cmd,
184
+ routeKey: i.routeKey
185
+ });
186
+ case C.INGEST: {
187
+ let e;
188
+ switch (i.data.eventID) {
189
+ case m.UPDATE_CURSOR: {
190
+ e = {
191
+ eventID: m.UPDATE_CURSOR,
192
+ updateCursorEvent: i.data.data
193
+ };
194
+ break;
195
+ }
196
+ case m.USERS_LEAVE: {
197
+ e = {
198
+ eventID: m.USERS_LEAVE,
199
+ leaveEvent: i.data.data
200
+ };
201
+ break;
202
+ }
203
+ case m.USERS_ENTER: {
204
+ e = {
205
+ eventID: m.USERS_ENTER,
206
+ joinEvent: i.data.data
207
+ };
208
+ break;
209
+ }
210
+ case m.LIVESHARE_NEW_HOST: {
211
+ e = {
212
+ eventID: m.LIVESHARE_NEW_HOST,
213
+ liveShareNewHost: i.data.data
214
+ };
215
+ break;
216
+ }
217
+ case m.LIVESHARE_OPERATION: {
218
+ e = {
219
+ eventID: m.LIVESHARE_OPERATION,
220
+ liveShareOperation: i.data.data
221
+ };
222
+ break;
223
+ }
224
+ case m.LIVESHARE_TERMINATE: {
225
+ e = {
226
+ eventID: m.LIVESHARE_TERMINATE,
227
+ liveShareTerminate: i.data.data
228
+ };
229
+ break;
230
+ }
231
+ case m.LIVESHARE_REQUEST_HOST: {
232
+ e = {
233
+ eventID: m.LIVESHARE_REQUEST_HOST,
234
+ liveShareRequestHost: i.data.data
235
+ };
236
+ break;
237
+ }
238
+ case m.LIVESHARE_FETCH_OPERATIONS: {
239
+ e = {
240
+ eventID: m.LIVESHARE_FETCH_OPERATIONS
241
+ };
242
+ break;
243
+ }
244
+ default:
245
+ e = {
246
+ eventID: i.data.eventID
247
+ };
248
+ }
249
+ return JSON.stringify({
250
+ cmd: i.cmd,
251
+ routeKey: i.routeKey,
252
+ collaMsg: e
253
+ });
254
+ }
255
+ case C.JOIN:
256
+ return JSON.stringify({
257
+ cmd: i.cmd,
258
+ routeKey: i.routeKey,
259
+ joinReq: i.data
260
+ });
261
+ case C.LEAVE:
262
+ return JSON.stringify({
263
+ cmd: i.cmd,
264
+ routeKey: i.routeKey,
265
+ leaveReq: i.data
266
+ });
267
+ default:
268
+ throw new Error("[serializeCombRequest]: should not fall into default branch!");
269
+ }
270
+ }
271
+ var ki = (i, e, t, s) => {
272
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
273
+ (o = i[r]) && (n = o(n) || n);
274
+ return n;
275
+ }, me = (i, e) => (t, s) => e(t, s, i);
276
+ const us = pt(
277
+ "univer-pro.collaboration-client-socket-service"
278
+ ), Li = "COLLAB_SUBMIT_CHANGESET_URL", $i = "/universer-api/comb";
279
+ function Pi(i, e, t) {
280
+ return `${i}/${e}/unit/${t}/new_changes`;
281
+ }
282
+ let ht = class {
283
+ constructor(i, e, t, s, n) {
284
+ this._http = i, this._ws = e, this._configService = t, this._logService = s, this._snapshotServerService = n;
285
+ }
286
+ /**
287
+ * Create a socket that would connect to the remote collaboration server. It would throw an error when the socket cannot be created.
288
+ *
289
+ * @param URL The URL of the remote server.
290
+ */
291
+ createSocket(i) {
292
+ const e = this._ws.createSocket(i);
293
+ if (!e)
294
+ throw new Error("[CollaborationSocketService]: failed to create socket!");
295
+ const t = new Jt(), s = new ae();
296
+ t.add(T(e.close$.subscribe((c) => s.next(c)))), t.add(T(() => s.complete()));
297
+ const n = new ae();
298
+ t.add(T(e.error$.subscribe((c) => n.next(c)))), t.add(T(() => n.complete()));
299
+ const r = new ae();
300
+ t.add(
301
+ T(
302
+ e.message$.subscribe((c) => {
303
+ const h = Ai(c);
304
+ r.next(h);
305
+ })
306
+ )
307
+ ), t.add(T(() => r.complete()));
308
+ const o = () => {
309
+ n.next(new Event("connection error")), s.next(new CloseEvent("connection error")), a.close();
310
+ }, a = {
311
+ memberID: "",
312
+ close$: s.asObservable(),
313
+ error$: n.asObservable(),
314
+ open$: e.open$,
315
+ message$: r.asObservable(),
316
+ send: (c) => {
317
+ if (c.cmd === C.INGEST) {
318
+ if (c.data.eventID === m.SUBMIT_CHANGESET) {
319
+ this._submitChangeset(a, c.data).catch((h) => {
320
+ this._logService.error(h), o();
321
+ });
322
+ return;
323
+ }
324
+ if (c.data.eventID === m.FETCH_MISSING) {
325
+ const h = c.data;
326
+ this._fetchMissChangesets(h).then((u) => {
327
+ r.next({
328
+ cmd: C.RECV,
329
+ code: Rt.OK,
330
+ routeKey: h.data.unitID,
331
+ routeType: "",
332
+ data: {
333
+ eventID: m.PSEUDO_FETCH_MISSING_RESULT,
334
+ data: {
335
+ changesets: u
336
+ }
337
+ }
338
+ });
339
+ }).catch((u) => {
340
+ this._logService.error(u), o();
341
+ });
342
+ return;
343
+ }
344
+ }
345
+ e.send(Ui(c));
346
+ },
347
+ close: () => {
348
+ e.close(), t.dispose();
349
+ }
350
+ };
351
+ return a;
352
+ }
353
+ async _submitChangeset(i, e) {
354
+ var a;
355
+ const { unitType: t, unitID: s, changeset: n } = e.data, r = {
356
+ unitID: s,
357
+ memberID: i.memberID,
358
+ type: t,
359
+ changeset: Fs(n)
360
+ }, o = Pi(
361
+ (a = this._configService.getConfig(Li)) != null ? a : $i,
362
+ t,
363
+ s
364
+ );
365
+ try {
366
+ await this._http.post(o, { body: r });
367
+ } catch (c) {
368
+ throw this._logService.error("[CollaborationSession]", "submit changeset error!"), c;
369
+ }
370
+ }
371
+ async _fetchMissChangesets(i) {
372
+ const { unitID: e, from: t, to: s, unitType: n } = i.data;
373
+ return (await this._snapshotServerService.fetchMissingChangesets({ metadata: void 0 }, {
374
+ unitID: e,
375
+ type: n,
376
+ from: t,
377
+ to: s
378
+ })).changesets;
379
+ }
380
+ };
381
+ ht = ki([
382
+ me(0, _(Re)),
383
+ me(1, _(cs)),
384
+ me(2, z),
385
+ me(3, D),
386
+ me(4, qt)
387
+ ], ht);
388
+ var ds = (i, e, t, s) => {
389
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
390
+ (o = i[r]) && (n = o(n) || n);
391
+ return n;
392
+ }, N = (i, e) => (t, s) => e(t, s, i), he = /* @__PURE__ */ ((i) => (i[i.IDLE = 0] = "IDLE", i[i.JOINING = 1] = "JOINING", i[i.OFFLINE = 2] = "OFFLINE", i[i.ONLINE = 3] = "ONLINE", i))(he || {});
393
+ const xi = "COLLAB_WEB_SOCKET_URL", Hi = "ws://127.0.0.1:8000/universer-api/comb/connect", ji = "HEARTBEAT_INTERVAL", Bi = 3e4, gs = "HEARTBEAT_TIMEOUT", ms = 1e4, Vi = "RETRY_CONNECTING_INTERVAL", Fi = 2e4, Wi = "RETRY_CONNECTING_MAX_COUNT", Gi = 3;
394
+ let lt = class extends L {
395
+ constructor(e, t, s, n, r, o, a, c) {
396
+ super();
397
+ l(this, "_sessionStatus$", new U(
398
+ 0
399
+ /* IDLE */
400
+ ));
401
+ l(this, "sessionStatus$", this._sessionStatus$.asObservable());
402
+ l(this, "_event$", new ae());
403
+ l(this, "event$", this._event$.asObservable());
404
+ l(this, "_socket");
405
+ l(this, "_socketMessageSubscription");
406
+ l(this, "_collaborationTimeoutTimer");
407
+ this._unitID = e, this._logService = s, this._beforeCloseService = n, this._messageService = r, this._configService = o, this._localeService = a, this._memberService = c, t.pipe(It(this.dispose$)).subscribe((h) => {
408
+ var u;
409
+ typeof h > "u" || (this._socket = h, h ? (this._joinRoom(h), this._socketMessageSubscription = this._socket.message$.subscribe((d) => {
410
+ d.routeKey === this._unitID && this._onCombEvent(d);
411
+ })) : (this._sessionStatus$.next(
412
+ 2
413
+ /* OFFLINE */
414
+ ), (u = this._socketMessageSubscription) == null || u.unsubscribe(), this._socketMessageSubscription = null));
415
+ }), this.disposeWithMe(
416
+ this._beforeCloseService.registerOnClose(() => {
417
+ var h;
418
+ (h = this._socket) == null || h.send({ cmd: C.LEAVE, data: { roomID: this._unitID } });
419
+ })
420
+ );
421
+ }
422
+ get sessionStatus() {
423
+ return this._sessionStatus$.getValue();
424
+ }
425
+ getMemberID() {
426
+ var e, t;
427
+ return (t = (e = this._socket) == null ? void 0 : e.memberID) != null ? t : null;
428
+ }
429
+ dispose() {
430
+ super.dispose(), this.dispose$.next(), this.dispose$.complete();
431
+ }
432
+ _onCombEvent(e) {
433
+ e.cmd === C.JOIN ? this._onJoinRoomEvent(e) : e.cmd === C.RECV && this._onRecvEvent(e);
434
+ }
435
+ _joinRoom(e) {
436
+ this._sessionStatus$.next(
437
+ 1
438
+ /* JOINING */
439
+ ), e.send({
440
+ cmd: C.JOIN,
441
+ routeKey: this._unitID,
442
+ routeType: "",
443
+ data: {
444
+ rooms: [
445
+ {
446
+ roomID: this._unitID
447
+ }
448
+ ]
449
+ }
450
+ });
451
+ }
452
+ _onJoinRoomEvent(e) {
453
+ var s;
454
+ if (e.code === Rt.FAIL) {
455
+ this._messageService.show({
456
+ type: be.Warning,
457
+ content: this._localeService.t("session.room-full")
458
+ }), this._sessionStatus$.next(
459
+ 2
460
+ /* OFFLINE */
461
+ );
462
+ return;
463
+ }
464
+ this._sessionStatus$.next(
465
+ 3
466
+ /* ONLINE */
467
+ );
468
+ const t = (s = e.data.roomInfos[this._unitID]) == null ? void 0 : s.members;
469
+ t && t.forEach((n) => this._memberService.updateMember(this._unitID, n));
470
+ }
471
+ _onRecvEvent(e) {
472
+ try {
473
+ const t = e.data;
474
+ switch (t.eventID) {
475
+ case m.USERS_ENTER:
476
+ this._onUserJoin(t), this._event$.next(t);
477
+ break;
478
+ case m.USERS_LEAVE:
479
+ this._onUserLeave(t), this._event$.next(t);
480
+ break;
481
+ case m.CHANGESET_ACK:
482
+ this._clearCollaborationTimeoutTimer(), this._event$.next(t);
483
+ break;
484
+ case m.MSG_FOR_ERROR:
485
+ this._logService.error(`save fail reason is ${JSON.stringify(t)}`), this._event$.next(t);
486
+ break;
487
+ default:
488
+ this._event$.next(t);
489
+ }
490
+ } catch (t) {
491
+ this._logService.error(t, e);
492
+ }
493
+ }
494
+ _onUserJoin(e) {
495
+ this._memberService.updateMember(this._unitID, e.data);
496
+ }
497
+ _onUserLeave(e) {
498
+ this._memberService.removeMember(this._unitID, e.data.memberID);
499
+ }
500
+ /**
501
+ * Send event to the collaboration server.
502
+ */
503
+ async send(e, t) {
504
+ if (this.sessionStatus !== 3 || !this._socket)
505
+ throw new Error("[CollaborationSession]: should not send message when the session is offline!");
506
+ try {
507
+ e.eventID === m.NEW_CHANGESETS && this._scheduleCollaborationTimeoutTimer(), this._socket.send({
508
+ cmd: C.INGEST,
509
+ routeKey: t,
510
+ routeType: "",
511
+ data: e
512
+ });
513
+ } catch (s) {
514
+ this._logService.error(s);
515
+ }
516
+ }
517
+ _scheduleCollaborationTimeoutTimer() {
518
+ var e;
519
+ this._collaborationTimeoutTimer = window.setTimeout(() => {
520
+ this._collaborationTimeoutTimer = null, this._messageService.show({
521
+ type: be.Error,
522
+ content: this._localeService.t("session.collaboration-timeout")
523
+ });
524
+ }, (e = this._configService.getConfig(gs)) != null ? e : ms);
525
+ }
526
+ _clearCollaborationTimeoutTimer() {
527
+ this._collaborationTimeoutTimer && (clearTimeout(this._collaborationTimeoutTimer), this._collaborationTimeoutTimer = null);
528
+ }
529
+ };
530
+ lt = ds([
531
+ N(2, D),
532
+ N(3, es),
533
+ N(4, Me),
534
+ N(5, z),
535
+ N(6, _(H)),
536
+ N(7, _(Z))
537
+ ], lt);
538
+ let ye = class extends X {
539
+ constructor(e, t, s, n, r, o) {
540
+ super();
541
+ /**
542
+ * Socket for collaboration sessions. Session are by unitID but the socket is share by collaboration sessions.
543
+ */
544
+ l(this, "_socket$", new U(void 0));
545
+ l(this, "_sessions", /* @__PURE__ */ new Map());
546
+ l(this, "_status$", new U(
547
+ 0
548
+ /* IDLE */
549
+ ));
550
+ l(this, "status$", this._status$.asObservable());
551
+ l(this, "_socketReady", !1);
552
+ l(this, "_sendHeartbeatTimer");
553
+ l(this, "_timeoutTimer");
554
+ l(this, "_retryConnectingTimer");
555
+ l(this, "_retryCount", 0);
556
+ this._injector = e, this._localeService = t, this._messageService = s, this._logService = n, this._configService = r, this._socketService = o;
557
+ }
558
+ get _socket() {
559
+ return this._socket$.getValue();
560
+ }
561
+ dispose() {
562
+ super.dispose(), this._sessions.forEach((e) => e.dispose()), this._sessions.clear(), this._status$.complete();
563
+ }
564
+ /**
565
+ * Require a collaboration session.
566
+ * @param unitID
567
+ * @returns a collaboration session.
568
+ */
569
+ async requireSession(e) {
570
+ if (this._sessions.has(e))
571
+ return this._sessions.get(e);
572
+ this._tryEnsureSocket();
573
+ const t = this._injector.createInstance(lt, e, this._socket$.asObservable());
574
+ return this._sessions.set(e, t), t;
575
+ }
576
+ _createSocket() {
577
+ var s;
578
+ const e = (s = this._configService.getConfig(xi)) != null ? s : Hi;
579
+ return this._socketService.createSocket(e);
580
+ }
581
+ /**
582
+ * Try to establish connection to the collaboration server.
583
+ *
584
+ * Will send heartbeat channel to the server to keep the connection alive.
585
+ */
586
+ _tryEnsureSocket() {
587
+ try {
588
+ const e = this._createSocket();
589
+ if (e) {
590
+ const t = e.send;
591
+ e.send = (s) => (this._rescheduleHeartbeatEvent(), t.apply(e, [s])), e.message$.subscribe((s) => this._onMessage(e, s)), e.error$.pipe($e(1)).subscribe((s) => this._logService.error("[CollaborationSessionService]: socket error", s)), e.open$.pipe($e(1)).subscribe(() => {
592
+ this._onConnectionOpen(e);
593
+ }), e.close$.pipe($e(1)).subscribe((s) => {
594
+ this._logService.debug("[CollaborationSessionService]", "socket close", s), this._onConnectionFailed();
595
+ });
596
+ }
597
+ } catch (e) {
598
+ this._logService.error(e), this._onConnectionFailed();
599
+ }
600
+ }
601
+ _onConnectionOpen(e) {
602
+ this._logService.debug("[CollaborationSessionService]", "socket open."), e.send({ cmd: C.HELLO }), this._rescheduleHeartbeatEvent();
603
+ }
604
+ _onConnectionFailed() {
605
+ var e;
606
+ this._status$.next(
607
+ 2
608
+ /* OFFLINE */
609
+ ), this._socket$.next(null), this._clearTimeoutTimer(), this._clearHeartbeatTimer(), this._socketReady = !1, this._retryCount < ((e = this._configService.getConfig(Wi)) != null ? e : Gi) ? (this._scheduleReconnection(this._retryCount), this._retryCount += 1) : this._messageService.show({
610
+ type: be.Error,
611
+ content: this._localeService.t("session.connection-failed")
612
+ });
613
+ }
614
+ _scheduleReconnection(e) {
615
+ var s;
616
+ const t = ((s = this._configService.getConfig(Vi)) != null ? s : Fi) * 2 ** e;
617
+ this._messageService.show({
618
+ type: be.Warning,
619
+ content: this._localeService.t("session.will-retry")
620
+ }), this._retryConnectingTimer = setTimeout(() => {
621
+ this._tryEnsureSocket(), clearTimeout(this._retryConnectingTimer), this._retryConnectingTimer = null;
622
+ }, t);
623
+ }
624
+ _rescheduleHeartbeatEvent() {
625
+ var e;
626
+ this._clearHeartbeatTimer(), this._sendHeartbeatTimer = setTimeout(
627
+ () => this._sendHeartbeat(),
628
+ (e = this._configService.getConfig(ji)) != null ? e : Bi
629
+ );
630
+ }
631
+ _sendHeartbeat() {
632
+ this._socket.send({ cmd: C.HEARTBEAT }), this._waitForHeartbeatResponse();
633
+ }
634
+ _waitForHeartbeatResponse() {
635
+ var e;
636
+ this._timeoutTimer = setTimeout(
637
+ () => this._onConnectionFailed(),
638
+ (e = this._configService.getConfig(gs)) != null ? e : ms
639
+ );
640
+ }
641
+ _onMessage(e, t) {
642
+ const { cmd: s } = t;
643
+ s === C.HELLO && !this._socketReady && (e.memberID = t.data.memberID, this._socket$.next(e), this._status$.next(
644
+ 3
645
+ /* ONLINE */
646
+ ), this._socketReady = !0), s === C.HEARTBEAT && this._clearTimeoutTimer(), this._rescheduleHeartbeatEvent();
647
+ }
648
+ _clearHeartbeatTimer() {
649
+ this._sendHeartbeatTimer != null && (clearTimeout(this._sendHeartbeatTimer), this._sendHeartbeatTimer = null);
650
+ }
651
+ _clearTimeoutTimer() {
652
+ this._timeoutTimer != null && (clearTimeout(this._timeoutTimer), this._timeoutTimer = null);
653
+ }
654
+ };
655
+ ye = ds([
656
+ N(0, _(I)),
657
+ N(1, _(H)),
658
+ N(2, Me),
659
+ N(3, D),
660
+ N(4, z),
661
+ N(5, us)
662
+ ], ye);
663
+ var Ki = (i, e, t, s) => {
664
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
665
+ (o = i[r]) && (n = o(n) || n);
666
+ return n;
667
+ }, fe = (i, e) => (t, s) => e(t, s, i);
668
+ const Yi = "LOCAL_CACHE_INTERVAL", Xi = 1e3;
669
+ let y = class extends X {
670
+ constructor(e, t, s, n, r) {
671
+ super();
672
+ l(this, "_cachedData", /* @__PURE__ */ new Map());
673
+ l(this, "_saveTaskMap", /* @__PURE__ */ new Map());
674
+ l(this, "_disabled", !1);
675
+ this._configService = e, this._localStorageService = t, this._beforeCloseService = s, this._localeService = n, this._revisionService = r, this._setupBeforeClosingHandler();
676
+ }
677
+ disableLocalCache() {
678
+ this._disabled = !0;
679
+ }
680
+ enableLocalCache() {
681
+ this._disabled = !1;
682
+ }
683
+ dispose() {
684
+ this._exhaustSavingTask().then(() => super.dispose());
685
+ }
686
+ async loadOfflineData(e) {
687
+ return this._disabled ? null : this._localStorageService.getItem(xt(e));
688
+ }
689
+ async saveOfflineData(e, t) {
690
+ return !!this._localStorageService.setItem(e, t);
691
+ }
692
+ updateOfflineData(e, t, s, n) {
693
+ const r = this._revisionService.getCurrentRevForDocument(e);
694
+ this._cachedData.set(e, {
695
+ unitID: e,
696
+ type: t,
697
+ awaitingChangeset: s,
698
+ mutations: n,
699
+ rev: r
700
+ }), this._saveTaskMap.has(e) || this._scheduleSaving(e);
701
+ }
702
+ _scheduleSaving(e) {
703
+ const t = this._getSaveTimeout();
704
+ t === 0 ? this._saveCache(e) : this._saveTaskMap.set(e, setTimeout(() => this._saveCache(e), t));
705
+ }
706
+ _getSaveTimeout() {
707
+ var e;
708
+ return (e = this._configService.getConfig(Yi)) != null ? e : Xi;
709
+ }
710
+ _saveCache(e) {
711
+ const t = this._saveTaskMap.get(e);
712
+ return t !== void 0 && window.clearTimeout(t), this._localStorageService.setItem(xt(e), this._cachedData.get(e)).then(() => this._saveTaskMap.delete(e));
713
+ }
714
+ async _exhaustSavingTask() {
715
+ const e = [];
716
+ this._saveTaskMap.forEach((t, s) => {
717
+ window.clearTimeout(t), e.push(
718
+ this._saveCache(s).then(() => {
719
+ this._saveTaskMap.delete(s);
720
+ })
721
+ );
722
+ }), await Promise.all(e);
723
+ }
724
+ _setupBeforeClosingHandler() {
725
+ this.disposeWithMe(
726
+ this._beforeCloseService.registerBeforeClose(() => {
727
+ if (this._saveTaskMap.size)
728
+ return this._localeService.t("collaboration-client.offline-data-not-saved");
729
+ })
730
+ );
731
+ }
732
+ };
733
+ y = Ki([
734
+ fe(0, z),
735
+ fe(1, Ds),
736
+ fe(2, es),
737
+ fe(3, _(H)),
738
+ fe(4, _($))
739
+ ], y);
740
+ function xt(i) {
741
+ return `unit-cache-${i}`;
742
+ }
743
+ const Xe = pt(
744
+ "univer-pro.collaboration-client.single-active-unit-service"
745
+ );
746
+ var fs = /* @__PURE__ */ ((i) => (i[i.NO_OTHER_CLIENTS_EDITING = 0] = "NO_OTHER_CLIENTS_EDITING", i[i.OTHER_CLIENTS_EDITING = 1] = "OTHER_CLIENTS_EDITING", i))(fs || {});
747
+ const Ht = 3e4, jt = "ACTIVE_UNIT_EVENT_CHANNEL";
748
+ class zi extends X {
749
+ constructor() {
750
+ super();
751
+ l(this, "_id", P.generateRandomId());
752
+ l(this, "_selfUnitIDs", /* @__PURE__ */ new Set());
753
+ l(this, "_unitOnClients", /* @__PURE__ */ new Map());
754
+ // unitID -> memberIDs
755
+ l(this, "_heartbeatTimer", null);
756
+ l(this, "_clearOtherTimers", /* @__PURE__ */ new Map());
757
+ l(this, "_unitStatus", /* @__PURE__ */ new Map());
758
+ this._init();
759
+ }
760
+ dispose() {
761
+ super.dispose(), this._clearOtherTimers.forEach((t, s) => this._removeClearOtherTimer(s)), this._heartbeatTimer && window.clearInterval(this._heartbeatTimer);
762
+ }
763
+ getUnitStatus$(t) {
764
+ return this._ensureSubject(t).pipe(Gs());
765
+ }
766
+ editingUnit(t) {
767
+ this._selfUnitIDs.size === 0 && this._scheduleHeartbeat(), this._selfUnitIDs.add(t), this._send({
768
+ type: 0,
769
+ memberID: this._id,
770
+ unitID: t
771
+ });
772
+ }
773
+ disposeUnit(t) {
774
+ this._selfUnitIDs.delete(t), this._selfUnitIDs.size === 0 && this._heartbeatTimer && window.clearInterval(this._heartbeatTimer);
775
+ }
776
+ _init() {
777
+ this.disposeWithMe(
778
+ T(
779
+ ss(window, "storage").subscribe((t) => {
780
+ if (t.key !== jt || !t.newValue)
781
+ return;
782
+ const s = JSON.parse(t.newValue);
783
+ this._handleEvent(s);
784
+ })
785
+ )
786
+ ), window.addEventListener(
787
+ "unload",
788
+ () => this._send({
789
+ type: 1,
790
+ memberID: this._id,
791
+ unitIDs: Array.from(this._selfUnitIDs)
792
+ })
793
+ );
794
+ }
795
+ _handleEvent(t) {
796
+ switch (t.type) {
797
+ case 0:
798
+ this._handleJoinEvent(t);
799
+ break;
800
+ case 1:
801
+ this._handleLeaveEvent(t);
802
+ break;
803
+ case 2:
804
+ this._handleHeartbeatEvent(t);
805
+ break;
806
+ }
807
+ }
808
+ _handleJoinEvent(t) {
809
+ const { unitID: s, memberID: n } = t;
810
+ if (!this._unitOnClients.has(s) || !this._unitOnClients.get(s).has(n)) {
811
+ const r = this._unitOnClients.get(s) || /* @__PURE__ */ new Set();
812
+ r.add(n), this._unitOnClients.set(s, r), this._scheduleClearOtherTimer(n), this._send({
813
+ type: 0,
814
+ memberID: this._id,
815
+ unitID: s
816
+ });
817
+ } else
818
+ this._ensureSubject(s).next(
819
+ 1
820
+ /* OTHER_CLIENTS_EDITING */
821
+ );
822
+ }
823
+ _scheduleClearOtherTimer(t) {
824
+ this._removeClearOtherTimer(t);
825
+ const s = window.setTimeout(() => {
826
+ this._unitOnClients.forEach((n) => {
827
+ n.delete(t);
828
+ });
829
+ }, Ht * 2);
830
+ this._clearOtherTimers.set(t, s);
831
+ }
832
+ _removeClearOtherTimer(t) {
833
+ if (this._clearOtherTimers.has(t)) {
834
+ const s = this._clearOtherTimers.get(t);
835
+ s && window.clearTimeout(s), this._clearOtherTimers.set(t, null);
836
+ }
837
+ }
838
+ _handleLeaveEvent(t) {
839
+ const { memberID: s, unitIDs: n } = t;
840
+ n.forEach((r) => {
841
+ var a;
842
+ const o = this._unitOnClients.get(r);
843
+ o && (o.delete(s), (a = this._ensureSubject(r)) == null || a.next(
844
+ o.size === 0 ? 0 : 1
845
+ ));
846
+ }), this._removeClearOtherTimer(s);
847
+ }
848
+ _handleHeartbeatEvent(t) {
849
+ this._scheduleClearOtherTimer(t.memberID);
850
+ }
851
+ _send(t) {
852
+ localStorage.setItem(jt, JSON.stringify(t));
853
+ }
854
+ _scheduleHeartbeat() {
855
+ this._heartbeatTimer = window.setInterval(() => {
856
+ this._send({
857
+ type: 2,
858
+ memberID: this._id
859
+ });
860
+ }, Ht);
861
+ }
862
+ _ensureSubject(t) {
863
+ return this._unitStatus.has(t) || this._unitStatus.set(t, new U(
864
+ 0
865
+ /* NO_OTHER_CLIENTS_EDITING */
866
+ )), this._unitStatus.get(t);
867
+ }
868
+ }
869
+ var Ji = (i, e, t, s) => {
870
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
871
+ (o = i[r]) && (n = o(n) || n);
872
+ return n;
873
+ }, Bt = (i, e) => (t, s) => e(t, s, i);
874
+ let Be = class {
875
+ constructor(i, e) {
876
+ this._injector = i, this._transformService = e;
877
+ }
878
+ transformIMECache(i) {
879
+ this._transformUndoRedoStack(i), this._transformPreviousActiveRange(i);
880
+ }
881
+ // Since local IME inputting, the data model layer has changed,
882
+ // so when there is a remote changeset arrives,
883
+ // you need to transform the remote changeset and then apply it to the data model.
884
+ transformRemoteChangeset(i) {
885
+ const e = this._injector.get(Qe), { redoCache: t } = e.getUndoRedoMutationParamsCache();
886
+ if (t.length === 0)
887
+ return i;
888
+ let s = P.deepClone(i.mutations[0]);
889
+ for (let n = 0; n < t.length; n++) {
890
+ const r = {
891
+ id: "doc.mutation.rich-text-editing",
892
+ params: {
893
+ ...t[n]
894
+ }
895
+ }, o = this._transformService.transformMutation(s, r, !1);
896
+ if (Le(o))
897
+ throw o.error;
898
+ s = o.m1Prime;
899
+ }
900
+ return {
901
+ ...P.deepClone(i),
902
+ mutations: [s]
903
+ };
904
+ }
905
+ _transformUndoRedoStack(i) {
906
+ const e = this._injector.get(Qe), {
907
+ undoCache: t,
908
+ redoCache: s
909
+ } = e.getUndoRedoMutationParamsCache();
910
+ if (t.length === 0 || s.length === 0)
911
+ return;
912
+ const n = [], r = [];
913
+ let o = P.deepClone(i.mutations[0]), a = P.deepClone(i.mutations[0]);
914
+ for (let c = t.length - 1; c >= 0; c--) {
915
+ const h = {
916
+ id: "doc.mutation.rich-text-editing",
917
+ params: {
918
+ ...t[c]
919
+ }
920
+ }, u = {
921
+ id: "doc.mutation.rich-text-editing",
922
+ params: {
923
+ ...s[c]
924
+ }
925
+ }, d = this._transformService.transformMutation(o, h, !1), f = this._transformService.transformMutation(a, u, !1);
926
+ if (Le(d))
927
+ throw d.error;
928
+ if (Le(f))
929
+ throw f.error;
930
+ n.unshift(d.m2Prime.params), r.unshift(f.m2Prime.params), o = d.m1Prime, a = f.m1Prime;
931
+ }
932
+ e.setUndoRedoMutationParamsCache({ undoCache: n, redoCache: r });
933
+ }
934
+ _transformPreviousActiveRange(i) {
935
+ const e = this._injector.get(Qe), t = e.getActiveRange();
936
+ if (t == null)
937
+ return;
938
+ const s = [{
939
+ id: "doc.mutation.rich-text-editing",
940
+ params: {
941
+ unitId: i.unitID,
942
+ actions: [],
943
+ textRanges: [t]
944
+ }
945
+ }], n = this._transformService.transformMutationsWithChangeset(i, s);
946
+ if (!_e(n))
947
+ throw n.error;
948
+ const r = n.m2Prime[0].params.textRanges;
949
+ Array.isArray(r) && r.length && e.setActiveRange(r[0]);
950
+ }
951
+ };
952
+ Be = Ji([
953
+ Bt(0, _(I)),
954
+ Bt(1, W)
955
+ ], Be);
956
+ var qi = (i, e, t, s) => {
957
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
958
+ (o = i[r]) && (n = o(n) || n);
959
+ return n;
960
+ }, Vt = (i, e) => (t, s) => e(t, s, i);
961
+ let Ve = class {
962
+ constructor(i, e) {
963
+ this._injector = i, this._transformService = e;
964
+ }
965
+ transformSelections(i) {
966
+ var a;
967
+ const e = this._injector.get(os), t = (a = e.getSelections()) != null ? a : [], s = t == null ? void 0 : t.map(as);
968
+ if (s.length === 0)
969
+ return;
970
+ const n = [{
971
+ id: "doc.mutation.rich-text-editing",
972
+ params: {
973
+ unitId: i.unitID,
974
+ actions: [],
975
+ textRanges: s
976
+ }
977
+ }], r = this._transformService.transformMutationsWithChangeset(i, n);
978
+ if (!_e(r))
979
+ throw r.error;
980
+ const o = r.m2Prime[0].params.textRanges;
981
+ Array.isArray(o) && o.length && e.replaceTextRanges(o, !1);
982
+ }
983
+ };
984
+ Ve = qi([
985
+ Vt(0, _(I)),
986
+ Vt(1, W)
987
+ ], Ve);
988
+ function Ss(i) {
989
+ let e = "";
990
+ for (const t of i) {
991
+ const { startOffset: s, endOffset: n, isActive: r } = t;
992
+ e.length && (e += ","), e += `${s}:${n}:${r ? "1" : "0"}`;
993
+ }
994
+ return e;
995
+ }
996
+ function Zi(i) {
997
+ const e = i.split(","), t = [];
998
+ for (const s of e) {
999
+ const [n, r, o] = s.split(":");
1000
+ t.push({
1001
+ startOffset: Number(n),
1002
+ endOffset: Number(r),
1003
+ collapsed: n === r,
1004
+ isActive: o === "1"
1005
+ /* Active */
1006
+ });
1007
+ }
1008
+ return t.some((s) => s.isActive) || (t[0].isActive = !0), t;
1009
+ }
1010
+ class yt extends L {
1011
+ constructor() {
1012
+ super(...arguments);
1013
+ l(this, "_collabCursorState$", new U(null));
1014
+ l(this, "collabCursorState$", this._collabCursorState$.asObservable());
1015
+ }
1016
+ syncEditingCollabCursor(t) {
1017
+ const { unitID: s, memberID: n, textRanges: r } = t, o = Ss(r), a = {
1018
+ unitID: s,
1019
+ memberID: n,
1020
+ selection: o
1021
+ };
1022
+ this._collabCursorState$.next(a);
1023
+ }
1024
+ }
1025
+ var Qi = (i, e, t, s) => {
1026
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
1027
+ (o = i[r]) && (n = o(n) || n);
1028
+ return n;
1029
+ }, Ft = (i, e) => (t, s) => e(t, s, i);
1030
+ let Fe = class {
1031
+ constructor(i, e) {
1032
+ this._injector = i, this._transformService = e;
1033
+ }
1034
+ transformSelections(i) {
1035
+ var h, u, d, f;
1036
+ const e = this._injector.get(hs), { pluginName: t, unitId: s, sheetId: n } = e.getCurrent() || {}, r = (h = e.getSelections()) != null ? h : [];
1037
+ if (r.length === 0 || !t || !s || !n)
1038
+ return;
1039
+ const o = [{
1040
+ id: at.id,
1041
+ params: {
1042
+ unitId: s,
1043
+ subUnitId: n,
1044
+ pluginName: t,
1045
+ selections: P.deepClone(r)
1046
+ }
1047
+ }], a = this._transformService.transformMutationsWithChangeset(i, o);
1048
+ if (!_e(a))
1049
+ throw a.error;
1050
+ const c = (f = (d = (u = a.m2Prime[0]) == null ? void 0 : u.params) == null ? void 0 : d.selections) != null ? f : r;
1051
+ Array.isArray(c) && c.length && this._injector.get(O).executeCommand(at.id, {
1052
+ unitId: s,
1053
+ subUnitId: n,
1054
+ pluginName: t,
1055
+ selections: c
1056
+ });
1057
+ }
1058
+ };
1059
+ Fe = Qi([
1060
+ Ft(0, _(I)),
1061
+ Ft(1, W)
1062
+ ], Fe);
1063
+ const en = /* @__PURE__ */ new Set([ni.id]);
1064
+ function tn(i, e, t, s, n) {
1065
+ var h, u, d, f;
1066
+ const r = [];
1067
+ for (const v of i)
1068
+ if (en.has(v.id)) {
1069
+ if (r.length > 0)
1070
+ break;
1071
+ r.push(v);
1072
+ break;
1073
+ } else
1074
+ r.push(v);
1075
+ const o = (u = (h = n.getCurrentUser()) == null ? void 0 : h.userID) != null ? u : "unknown", a = (f = (d = n.getCurrentUser()) == null ? void 0 : d.memberID) != null ? f : "unknown";
1076
+ return {
1077
+ changeset: {
1078
+ unitID: e,
1079
+ type: ts(t.getUnitType(e)),
1080
+ baseRev: s.getCurrentRevForDocument(e),
1081
+ revision: 0,
1082
+ userID: o,
1083
+ memberID: a,
1084
+ mutations: r
1085
+ },
1086
+ pendingMutations: i.slice(r.length)
1087
+ };
1088
+ }
1089
+ function sn(i, e, t, s, n) {
1090
+ var u, d, f, v;
1091
+ const o = [i.reduce((p, E) => {
1092
+ var ge;
1093
+ const { id: b } = p, { id: G, type: ue } = E, qe = (ge = p.params) != null ? ge : { actions: [] }, de = E.params;
1094
+ if (b && b !== G)
1095
+ throw new Error(`Cannot assemble a changeset from multiple mutations of different types: ${b} - ${G}.`);
1096
+ return {
1097
+ ...p,
1098
+ id: G,
1099
+ type: ue,
1100
+ params: {
1101
+ unitId: de.unitId,
1102
+ textRanges: de.textRanges,
1103
+ actions: Ns.compose(qe.actions, de.actions)
1104
+ }
1105
+ };
1106
+ }, {})], a = (d = (u = n.getCurrentUser()) == null ? void 0 : u.userID) != null ? d : "unknown", c = (v = (f = n.getCurrentUser()) == null ? void 0 : f.memberID) != null ? v : "unknown";
1107
+ return {
1108
+ changeset: {
1109
+ unitID: e,
1110
+ type: ts(t.getUnitType(e)),
1111
+ baseRev: s.getCurrentRevForDocument(e),
1112
+ revision: 0,
1113
+ userID: a,
1114
+ memberID: c,
1115
+ mutations: o
1116
+ },
1117
+ pendingMutations: []
1118
+ };
1119
+ }
1120
+ var se = (i, e, t, s) => {
1121
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
1122
+ (o = i[r]) && (n = o(n) || n);
1123
+ return n;
1124
+ }, g = (i, e) => (t, s) => e(t, s, i);
1125
+ const nn = "SEND_CHANGESET_TIMEOUT", rn = 2e3;
1126
+ var w = /* @__PURE__ */ ((i) => (i.NOT_COLLAB = "not_collab", i.SYNCED = "synced", i.PENDING = "pending", i.AWAITING = "awaiting", i.AWAITING_WITH_PENDING = "awaiting_with_pending", i.FETCH_MISS = "fetch_missing", i.CONFLICT = "conflict", i.OFFLINE = "offline", i))(w || {});
1127
+ class ie {
1128
+ // The sequence of these mutations should be: [_syncedMutations]-[_awaitingMutations]-[_pendingMutations]
1129
+ constructor(e, t, s, n, r, o, a, c, h) {
1130
+ /** Mutations that has been sent to the server but not yet acknowledged by the server. */
1131
+ l(this, "_awaitingChangeset", null);
1132
+ /** Mutations that has not been sent to the server. */
1133
+ l(this, "_pendingMutations", []);
1134
+ this.unitID = e, this.type = t, this._handler = r, this._commandService = o, this._undoRedoService = a, this._revisionService = c, this._localCacheService = h, this._awaitingChangeset = s, this._pendingMutations = n;
1135
+ }
1136
+ /**
1137
+ * Check if there are some changesets missing. If true, the state should abort this changeset and request
1138
+ * for missing changesets. Missing changesets will later be passed to `onRemoteChangeset` method.
1139
+ *
1140
+ * @param changeset The changeset sent from the remote collaboration server.
1141
+ * @returns There is some changeset missing.
1142
+ */
1143
+ _checkMissing(e) {
1144
+ const t = this._revisionService.getCurrentRevForDocument(this.unitID);
1145
+ return e.revision > t + 1 ? (this._handler.onMissingChangesets({
1146
+ from: t,
1147
+ to: e.revision - 1
1148
+ }), !0) : !1;
1149
+ }
1150
+ /** Transform undo redo mutations in the undo redo stack. */
1151
+ _transformUndoredo(e) {
1152
+ this._undoRedoService.transformUndoRedo(this.unitID, e);
1153
+ }
1154
+ /** Transform selections by calling the selection manager service. */
1155
+ _transformSelections(e) {
1156
+ var t, s;
1157
+ (s = (t = this._handler).onTransformSelections) == null || s.call(t, e);
1158
+ }
1159
+ _transformIMECache(e) {
1160
+ var t, s;
1161
+ return (s = (t = this._handler).onTransformIME) == null ? void 0 : s.call(t, e);
1162
+ }
1163
+ _transformRemoteChangesetByIMECache(e) {
1164
+ var t, s, n;
1165
+ return (n = (s = (t = this._handler).onTransformRemoteChangesetByIMECache) == null ? void 0 : s.call(t, e)) != null ? n : e;
1166
+ }
1167
+ // TODO: @jocs, doc and sheet need to be split.
1168
+ _syncEditingCollabCursor(e) {
1169
+ var t, s;
1170
+ if (this.type === x.UNIVER_DOC) {
1171
+ const { unitID: n, mutations: r, memberID: o } = e, a = r[0].params.textRanges;
1172
+ Array.isArray(a) && a.length > 0 && ((s = (t = this._handler).onSyncEditingCollabCursor) == null || s.call(t, {
1173
+ unitID: n,
1174
+ memberID: o,
1175
+ textRanges: a
1176
+ }));
1177
+ }
1178
+ }
1179
+ /** @internal */
1180
+ _updateLocalCache() {
1181
+ this._localCacheService.updateOfflineData(
1182
+ this.unitID,
1183
+ this.type,
1184
+ this._awaitingChangeset,
1185
+ this._pendingMutations
1186
+ );
1187
+ }
1188
+ _getCurrentRevision() {
1189
+ return this._revisionService.getCurrentRevForDocument(this.unitID);
1190
+ }
1191
+ _incrementRevisionNumber() {
1192
+ this._revisionService.incrementRevForDocument(this.unitID);
1193
+ }
1194
+ _executeRemoteChangeset(e) {
1195
+ var n;
1196
+ const t = this._transformRemoteChangesetByIMECache(e), s = As(t.mutations, this._commandService, {
1197
+ fromCollab: !0
1198
+ });
1199
+ if (!s.result)
1200
+ throw s.error instanceof Error ? s.error : new Error((n = s.error) != null ? n : "[CollaborationState]: apply error!");
1201
+ this._transformIMECache(t), this._transformUndoredo(e), this._transformSelections(t), this._syncEditingCollabCursor(t), this._incrementRevisionNumber();
1202
+ }
1203
+ }
1204
+ let Oe = class extends ie {
1205
+ constructor(e, t, s, n, r, o, a, c, h) {
1206
+ super(
1207
+ e,
1208
+ t,
1209
+ null,
1210
+ [],
1211
+ s,
1212
+ c,
1213
+ a,
1214
+ n,
1215
+ r
1216
+ );
1217
+ l(this, "status", "synced");
1218
+ this._injector = o, this._logService = h;
1219
+ }
1220
+ appendMutation(e) {
1221
+ const t = this._injector.createInstance(B, this.unitID, this.type, [e], this._handler);
1222
+ return t._schedule(), t._updateLocalCache(), t;
1223
+ }
1224
+ onRemoteChangeset(e) {
1225
+ if (this._checkMissing(e))
1226
+ return this._injector.createInstance(
1227
+ F,
1228
+ this.unitID,
1229
+ this.type,
1230
+ null,
1231
+ [],
1232
+ null,
1233
+ [e],
1234
+ this._handler
1235
+ );
1236
+ try {
1237
+ return this._executeRemoteChangeset(e), this;
1238
+ } catch (s) {
1239
+ return this._logService.error("[CollaborationController]: remote changeset applied error.", s), this;
1240
+ }
1241
+ }
1242
+ onRemoteAck() {
1243
+ throw new Error("[SyncedState]: received acknowledgement.");
1244
+ }
1245
+ onRemoteRej() {
1246
+ throw new Error("[SyncedState]: received rejection.");
1247
+ }
1248
+ toggleOffline() {
1249
+ return this._injector.createInstance(Y, this.unitID, this.type, null, [], this._handler);
1250
+ }
1251
+ toggleOnline() {
1252
+ return this;
1253
+ }
1254
+ resend() {
1255
+ throw new Error("[SyncedState]: invalid calling to `resend`.");
1256
+ }
1257
+ };
1258
+ Oe = se([
1259
+ g(3, _($)),
1260
+ g(4, _(y)),
1261
+ g(5, _(I)),
1262
+ g(6, J),
1263
+ g(7, O),
1264
+ g(8, D)
1265
+ ], Oe);
1266
+ let B = class extends ie {
1267
+ constructor(e, t, s, n, r, o, a, c, h, u, d, f, v, p) {
1268
+ super(
1269
+ e,
1270
+ t,
1271
+ null,
1272
+ s,
1273
+ n,
1274
+ u,
1275
+ p,
1276
+ o,
1277
+ a
1278
+ );
1279
+ l(this, "status", "pending");
1280
+ l(this, "_scheduleTimestamp", null);
1281
+ l(this, "_sendingTimer", null);
1282
+ this._injector = r, this._memberService = c, this._logService = h, this._configService = d, this._transformService = f, this._univerInstanceService = v;
1283
+ }
1284
+ appendMutation(e) {
1285
+ return this._pendingMutations.push(e), this._updateLocalCache(), this;
1286
+ }
1287
+ onRemoteChangeset(e) {
1288
+ if (this._checkMissing(e))
1289
+ return this._clearScheduledTask(), this._injector.createInstance(
1290
+ F,
1291
+ this.unitID,
1292
+ this.type,
1293
+ null,
1294
+ this._pendingMutations,
1295
+ null,
1296
+ [e],
1297
+ this._handler
1298
+ );
1299
+ try {
1300
+ const s = this._transformService.transformMutationsWithChangeset(e, this._pendingMutations);
1301
+ if (_e(s)) {
1302
+ const { c1Prime: n, m2Prime: r } = s;
1303
+ this._executeRemoteChangeset(n);
1304
+ const o = this._injector.createInstance(
1305
+ B,
1306
+ this.unitID,
1307
+ this.type,
1308
+ r,
1309
+ this._handler
1310
+ );
1311
+ return this._clearScheduledTask(), o._schedule(
1312
+ this._scheduleTimestamp ? Math.max(0, (/* @__PURE__ */ new Date()).getTime() - this._scheduleTimestamp) : this._getSendChangesetTimeout()
1313
+ ), o;
1314
+ }
1315
+ throw s.error;
1316
+ } catch (s) {
1317
+ return this._logService.error(s), this._onConflict();
1318
+ }
1319
+ }
1320
+ onRemoteAck() {
1321
+ throw new Error("[PendingState]: received acknowledgement.");
1322
+ }
1323
+ onRemoteRej() {
1324
+ throw new Error("[PendingState]: received rejection.");
1325
+ }
1326
+ toggleOffline() {
1327
+ return this._clearScheduledTask(), this._injector.createInstance(
1328
+ Y,
1329
+ this.unitID,
1330
+ this.type,
1331
+ null,
1332
+ this._pendingMutations,
1333
+ this._handler
1334
+ );
1335
+ }
1336
+ toggleOnline() {
1337
+ return this;
1338
+ }
1339
+ /**
1340
+ * Schedule a task to send changeset to the server.
1341
+ *
1342
+ * @internal
1343
+ */
1344
+ _schedule(e) {
1345
+ e = e != null ? e : this._getSendChangesetTimeout(), this._scheduleTimestamp = (/* @__PURE__ */ new Date()).getTime(), this._sendingTimer = setTimeout(() => {
1346
+ this._clearScheduledTask();
1347
+ let t = null;
1348
+ switch (this.type) {
1349
+ case x.UNIVER_SHEET: {
1350
+ t = tn(
1351
+ this._pendingMutations,
1352
+ this.unitID,
1353
+ this._univerInstanceService,
1354
+ this._revisionService,
1355
+ this._memberService
1356
+ );
1357
+ break;
1358
+ }
1359
+ case x.UNIVER_DOC: {
1360
+ t = sn(
1361
+ this._pendingMutations,
1362
+ this.unitID,
1363
+ this._univerInstanceService,
1364
+ this._revisionService,
1365
+ this._memberService
1366
+ );
1367
+ break;
1368
+ }
1369
+ default:
1370
+ throw new Error(`[PendingState]: unhandled univer type: ${this.type} in _schedule.`);
1371
+ }
1372
+ const { changeset: s, pendingMutations: n } = t;
1373
+ this._handler.onSendChangeset(s);
1374
+ const r = n.length ? this._injector.createInstance(
1375
+ V,
1376
+ this.unitID,
1377
+ this.type,
1378
+ s,
1379
+ n,
1380
+ this._handler
1381
+ ) : this._injector.createInstance(K, this.unitID, this.type, s, this._handler);
1382
+ r._updateLocalCache(), this._handler.onStateChange(this, r);
1383
+ }, e);
1384
+ }
1385
+ _getSendChangesetTimeout() {
1386
+ var e;
1387
+ return (e = this._configService.getConfig(nn)) != null ? e : rn;
1388
+ }
1389
+ resend() {
1390
+ throw new Error("[PendingState]: invalid calling to `resend`.");
1391
+ }
1392
+ _clearScheduledTask() {
1393
+ this._sendingTimer != null && (clearTimeout(this._sendingTimer), this._sendingTimer = null);
1394
+ }
1395
+ _onConflict() {
1396
+ return this._clearScheduledTask(), this._injector.createInstance(
1397
+ Q,
1398
+ this.unitID,
1399
+ this.type,
1400
+ null,
1401
+ this._pendingMutations,
1402
+ this._handler
1403
+ );
1404
+ }
1405
+ };
1406
+ B = se([
1407
+ g(4, _(I)),
1408
+ g(5, _($)),
1409
+ g(6, _(y)),
1410
+ g(7, _(Z)),
1411
+ g(8, D),
1412
+ g(9, O),
1413
+ g(10, z),
1414
+ g(11, W),
1415
+ g(12, k),
1416
+ g(13, J)
1417
+ ], B);
1418
+ let K = class extends ie {
1419
+ constructor(e, t, s, n, r, o, a, c, h, u, d) {
1420
+ super(
1421
+ e,
1422
+ t,
1423
+ s,
1424
+ [],
1425
+ n,
1426
+ c,
1427
+ d,
1428
+ o,
1429
+ a
1430
+ );
1431
+ l(this, "status", "awaiting");
1432
+ this._injector = r, this._logService = h, this._transformService = u;
1433
+ }
1434
+ appendMutation(e) {
1435
+ const t = this._injector.createInstance(
1436
+ V,
1437
+ this.unitID,
1438
+ this.type,
1439
+ this._awaitingChangeset,
1440
+ [e],
1441
+ this._handler
1442
+ );
1443
+ return t._updateLocalCache(), t;
1444
+ }
1445
+ onRemoteChangeset(e) {
1446
+ if (this._checkMissing(e))
1447
+ return this._injector.createInstance(
1448
+ F,
1449
+ this.unitID,
1450
+ this.type,
1451
+ this._awaitingChangeset,
1452
+ [],
1453
+ null,
1454
+ [e],
1455
+ this._handler
1456
+ );
1457
+ try {
1458
+ const s = this._transformService.transformChangesets(
1459
+ [e],
1460
+ [this._awaitingChangeset],
1461
+ !1
1462
+ );
1463
+ if (St(s)) {
1464
+ const { c1Prime: n, c2Prime: r } = s;
1465
+ this._executeRemoteChangeset(n[0]), r[0].baseRev = this._getCurrentRevision();
1466
+ const o = this._injector.createInstance(
1467
+ K,
1468
+ this.unitID,
1469
+ this.type,
1470
+ r[0],
1471
+ this._handler
1472
+ );
1473
+ return o._updateLocalCache(), o;
1474
+ }
1475
+ return this._onConflict();
1476
+ } catch (s) {
1477
+ return this._logService.error(s), this._onConflict();
1478
+ }
1479
+ }
1480
+ onRemoteAck(e) {
1481
+ const t = this._revisionService.getCurrentRevForDocument(this.unitID);
1482
+ if (e.revision < t - 1)
1483
+ return this;
1484
+ if (this._checkMissing(e))
1485
+ return this._injector.createInstance(
1486
+ F,
1487
+ this.unitID,
1488
+ this.type,
1489
+ null,
1490
+ // the awaiting changeset should be transform against to apply those mutations
1491
+ [],
1492
+ this._awaitingChangeset,
1493
+ [],
1494
+ // no queued remote changesets
1495
+ this._handler
1496
+ );
1497
+ this._incrementRevisionNumber();
1498
+ const n = this._injector.createInstance(Oe, this.unitID, this.type, this._handler);
1499
+ return n._updateLocalCache(), n;
1500
+ }
1501
+ onRemoteRej() {
1502
+ return this._onConflict();
1503
+ }
1504
+ toggleOffline() {
1505
+ return this._injector.createInstance(
1506
+ Y,
1507
+ this.unitID,
1508
+ this.type,
1509
+ this._awaitingChangeset,
1510
+ [],
1511
+ this._handler
1512
+ );
1513
+ }
1514
+ toggleOnline() {
1515
+ return this;
1516
+ }
1517
+ resend() {
1518
+ this._handler.onSendChangeset(this._awaitingChangeset);
1519
+ }
1520
+ _onConflict() {
1521
+ return this._injector.createInstance(
1522
+ Q,
1523
+ this.unitID,
1524
+ this.type,
1525
+ this._awaitingChangeset,
1526
+ [],
1527
+ this._handler
1528
+ );
1529
+ }
1530
+ };
1531
+ K = se([
1532
+ g(4, _(I)),
1533
+ g(5, _($)),
1534
+ g(6, _(y)),
1535
+ g(7, O),
1536
+ g(8, D),
1537
+ g(9, W),
1538
+ g(10, J)
1539
+ ], K);
1540
+ let V = class extends ie {
1541
+ constructor(e, t, s, n, r, o, a, c, h, u, d, f) {
1542
+ super(
1543
+ e,
1544
+ t,
1545
+ s,
1546
+ n,
1547
+ r,
1548
+ h,
1549
+ f,
1550
+ a,
1551
+ c
1552
+ );
1553
+ l(this, "status", "awaiting_with_pending");
1554
+ this._injector = o, this._logService = u, this._transformService = d;
1555
+ }
1556
+ appendMutation(e) {
1557
+ return this._pendingMutations.push(e), this;
1558
+ }
1559
+ onRemoteChangeset(e) {
1560
+ if (this._checkMissing(e))
1561
+ return this._injector.createInstance(
1562
+ F,
1563
+ this.unitID,
1564
+ this.type,
1565
+ this._awaitingChangeset,
1566
+ this._pendingMutations,
1567
+ null,
1568
+ [e],
1569
+ this._handler
1570
+ );
1571
+ try {
1572
+ const s = this._transformService.transformChangesets(
1573
+ [e],
1574
+ [this._awaitingChangeset],
1575
+ !1
1576
+ );
1577
+ if (St(s)) {
1578
+ const { c1Prime: n, c2Prime: r } = s, o = this._transformService.transformMutationsWithChangeset(
1579
+ n[0],
1580
+ this._pendingMutations
1581
+ );
1582
+ if (_e(o)) {
1583
+ const { c1Prime: a, m2Prime: c } = o;
1584
+ return this._executeRemoteChangeset(a), r[0].baseRev = this._getCurrentRevision(), this._injector.createInstance(
1585
+ V,
1586
+ this.unitID,
1587
+ this.type,
1588
+ r[0],
1589
+ c,
1590
+ this._handler
1591
+ );
1592
+ }
1593
+ throw o.error;
1594
+ }
1595
+ throw s.error;
1596
+ } catch (s) {
1597
+ return this._logService.error(s), this._onConflict();
1598
+ }
1599
+ }
1600
+ onRemoteAck(e) {
1601
+ if (this._checkMissing(e))
1602
+ return this._injector.createInstance(
1603
+ F,
1604
+ this.unitID,
1605
+ this.type,
1606
+ null,
1607
+ this._pendingMutations,
1608
+ this._awaitingChangeset,
1609
+ [],
1610
+ // no queued remote changesets
1611
+ this._handler
1612
+ );
1613
+ this._incrementRevisionNumber();
1614
+ const s = this._injector.createInstance(
1615
+ B,
1616
+ this.unitID,
1617
+ this.type,
1618
+ this._pendingMutations,
1619
+ this._handler
1620
+ );
1621
+ return s._schedule(), s._updateLocalCache(), s;
1622
+ }
1623
+ // override onRemoteRejection(changeset: IRejectedChangeset): CollaborationState {
1624
+ onRemoteRej() {
1625
+ return this._onConflict();
1626
+ }
1627
+ toggleOffline() {
1628
+ return this._injector.createInstance(
1629
+ Y,
1630
+ this.unitID,
1631
+ this.type,
1632
+ this._awaitingChangeset,
1633
+ this._pendingMutations,
1634
+ this._handler
1635
+ );
1636
+ }
1637
+ toggleOnline() {
1638
+ return this;
1639
+ }
1640
+ resend() {
1641
+ this._handler.onSendChangeset(this._awaitingChangeset);
1642
+ }
1643
+ _onConflict() {
1644
+ return this._injector.createInstance(
1645
+ Q,
1646
+ this.unitID,
1647
+ this.type,
1648
+ null,
1649
+ this._pendingMutations,
1650
+ this._handler
1651
+ );
1652
+ }
1653
+ };
1654
+ V = se([
1655
+ g(5, _(I)),
1656
+ g(6, _($)),
1657
+ g(7, _(y)),
1658
+ g(8, O),
1659
+ g(9, D),
1660
+ g(10, W),
1661
+ g(11, J)
1662
+ ], V);
1663
+ let Q = class extends ie {
1664
+ constructor(e, t, s, n, r, o, a, c, h, u, d, f) {
1665
+ super(
1666
+ e,
1667
+ t,
1668
+ s,
1669
+ n,
1670
+ r,
1671
+ a,
1672
+ c,
1673
+ u,
1674
+ h
1675
+ );
1676
+ l(this, "status", "conflict");
1677
+ this._univerPermissionService = o, this._localeService = d, this._notificationService = f, this._showConflictNotification(), this._clearLocalCache(), this._disableEditing();
1678
+ }
1679
+ appendMutation() {
1680
+ return this;
1681
+ }
1682
+ onRemoteChangeset() {
1683
+ return this;
1684
+ }
1685
+ onRemoteAck() {
1686
+ return this;
1687
+ }
1688
+ onRemoteRej() {
1689
+ return this;
1690
+ }
1691
+ toggleOffline() {
1692
+ return this;
1693
+ }
1694
+ toggleOnline() {
1695
+ return this;
1696
+ }
1697
+ resend() {
1698
+ throw new Error("[ConflictState]: invalid calling to `resend`.");
1699
+ }
1700
+ _clearLocalCache() {
1701
+ this._localCacheService.updateOfflineData(this.unitID, this.type, null, []);
1702
+ }
1703
+ _showConflictNotification() {
1704
+ this._notificationService.show({
1705
+ title: this._localeService.t("conflict.title"),
1706
+ content: this._localeService.t("conflict.content"),
1707
+ type: "error",
1708
+ duration: 0
1709
+ // Never close because user may lost his/her data if he/she doesn't notice this notification.
1710
+ });
1711
+ }
1712
+ _disableEditing() {
1713
+ this._univerPermissionService.setEditable(this.unitID, !1);
1714
+ }
1715
+ };
1716
+ Q = se([
1717
+ g(5, _(Ke)),
1718
+ g(6, O),
1719
+ g(7, J),
1720
+ g(8, _(y)),
1721
+ g(9, _($)),
1722
+ g(10, _(H)),
1723
+ g(11, Hs)
1724
+ ], Q);
1725
+ let Y = class extends ie {
1726
+ constructor(e, t, s, n, r, o, a, c, h, u) {
1727
+ super(
1728
+ e,
1729
+ t,
1730
+ s,
1731
+ n,
1732
+ r,
1733
+ h,
1734
+ u,
1735
+ a,
1736
+ c
1737
+ );
1738
+ l(this, "status", "offline");
1739
+ this._injector = o;
1740
+ }
1741
+ appendMutation(e) {
1742
+ return this._pendingMutations.push(e), this._updateLocalCache(), this;
1743
+ }
1744
+ onRemoteChangeset(e) {
1745
+ throw new Error("[OfflineState]: received changeset.");
1746
+ }
1747
+ onRemoteAck() {
1748
+ throw new Error("[OfflineState]: received acknowledgement.");
1749
+ }
1750
+ onRemoteRej() {
1751
+ throw new Error("[OfflineState]: received rejection.");
1752
+ }
1753
+ toggleOffline() {
1754
+ return this;
1755
+ }
1756
+ toggleOnline() {
1757
+ const { _injector: e, _pendingMutations: t, _awaitingChangeset: s, unitID: n, _handler: r, type: o } = this, a = vs(e, n, o, s, t, r);
1758
+ return a instanceof B ? a._schedule() : (a instanceof V || a instanceof K) && a.resend(), a;
1759
+ }
1760
+ resend() {
1761
+ throw new Error("[OfflineState]: invalid calling to `resend`.");
1762
+ }
1763
+ };
1764
+ Y = se([
1765
+ g(5, _(I)),
1766
+ g(6, _($)),
1767
+ g(7, _(y)),
1768
+ g(8, O),
1769
+ g(9, J)
1770
+ ], Y);
1771
+ let F = class extends ie {
1772
+ constructor(e, t, s, n, r, o, a, c, h, u, d, f, v, p) {
1773
+ super(
1774
+ e,
1775
+ t,
1776
+ s,
1777
+ n,
1778
+ a,
1779
+ f,
1780
+ v,
1781
+ h,
1782
+ u
1783
+ );
1784
+ l(this, "status", "fetch_missing");
1785
+ this._acknowledgedAwaitingChangeset = r, this._queuedRemoteChangesets = o, this._injector = c, this._logService = d, this._transformService = p;
1786
+ }
1787
+ // eslint-disable-next-line max-lines-per-function
1788
+ onMissedChangesetFetched(e) {
1789
+ try {
1790
+ const t = [...e, ...this._queuedRemoteChangesets], s = [this._awaitingChangeset || this._acknowledgedAwaitingChangeset].filter(
1791
+ (c) => !!c
1792
+ );
1793
+ let n, r;
1794
+ if (s.length) {
1795
+ const c = this._transformService.transformChangesets(
1796
+ t,
1797
+ s,
1798
+ !1
1799
+ );
1800
+ if (!St(c))
1801
+ throw c.error;
1802
+ n = c.c1Prime, r = c.c2Prime;
1803
+ } else
1804
+ n = t, r = [];
1805
+ let o = this._pendingMutations;
1806
+ n.forEach((c) => {
1807
+ let h;
1808
+ if (o.length) {
1809
+ const u = this._transformService.transformMutationsWithChangeset(
1810
+ c,
1811
+ o
1812
+ );
1813
+ if (!_e(u))
1814
+ throw u.error;
1815
+ h = u.c1Prime, o = u.m2Prime;
1816
+ } else
1817
+ h = c;
1818
+ this._executeRemoteChangeset(h);
1819
+ }), this._acknowledgedAwaitingChangeset && this._incrementRevisionNumber(), this._awaitingChangeset && r.length && (r[0].baseRev = this._getCurrentRevision());
1820
+ let a;
1821
+ if (this._awaitingChangeset && o.length !== 0)
1822
+ a = this._injector.createInstance(
1823
+ V,
1824
+ this.unitID,
1825
+ this.type,
1826
+ r[0],
1827
+ o,
1828
+ this._handler
1829
+ );
1830
+ else if (this._awaitingChangeset && o.length === 0)
1831
+ r[0].baseRev = this._getCurrentRevision(), a = this._injector.createInstance(
1832
+ K,
1833
+ this.unitID,
1834
+ this.type,
1835
+ r[0],
1836
+ this._handler
1837
+ );
1838
+ else if (o.length !== 0) {
1839
+ const c = this._injector.createInstance(
1840
+ B,
1841
+ this.unitID,
1842
+ this.type,
1843
+ o,
1844
+ this._handler
1845
+ );
1846
+ c._schedule(), a = c;
1847
+ } else
1848
+ a = this._injector.createInstance(Oe, this.unitID, this.type, this._handler);
1849
+ return a._updateLocalCache(), a;
1850
+ } catch (t) {
1851
+ return this._logService.error("[FetchMissState]", "failed to apply missed changesets!", t), this._injector.createInstance(
1852
+ Q,
1853
+ this.unitID,
1854
+ this.type,
1855
+ this._awaitingChangeset,
1856
+ this._pendingMutations,
1857
+ this._handler
1858
+ );
1859
+ }
1860
+ }
1861
+ resend() {
1862
+ throw new Error("[FetchingMissState]: invalid calling to `resend`.");
1863
+ }
1864
+ appendMutation(e) {
1865
+ return this._pendingMutations.push(e), this;
1866
+ }
1867
+ onRemoteChangeset(e) {
1868
+ return this._queuedRemoteChangesets.push(e), this;
1869
+ }
1870
+ onRemoteAck(e) {
1871
+ if (this._awaitingChangeset)
1872
+ return this._acknowledgedAwaitingChangeset = this._awaitingChangeset, this._awaitingChangeset = null, this;
1873
+ throw new Error("[FetchingMissState]: not expected to receive ack when `this._awaitingChangeset` is null!");
1874
+ }
1875
+ onRemoteRej() {
1876
+ return this._onConflict();
1877
+ }
1878
+ toggleOffline() {
1879
+ return this._injector.createInstance(
1880
+ Y,
1881
+ this.unitID,
1882
+ this.type,
1883
+ this._awaitingChangeset,
1884
+ this._pendingMutations,
1885
+ this._handler
1886
+ );
1887
+ }
1888
+ toggleOnline() {
1889
+ return this;
1890
+ }
1891
+ _onConflict() {
1892
+ return this._injector.createInstance(
1893
+ Q,
1894
+ this.unitID,
1895
+ this.type,
1896
+ this._awaitingChangeset,
1897
+ this._pendingMutations,
1898
+ this._handler
1899
+ );
1900
+ }
1901
+ };
1902
+ F = se([
1903
+ g(7, _(I)),
1904
+ g(8, _($)),
1905
+ g(9, _(y)),
1906
+ g(10, D),
1907
+ g(11, O),
1908
+ g(12, J),
1909
+ g(13, W)
1910
+ ], F);
1911
+ function vs(i, e, t, s, n, r) {
1912
+ return s && n.length ? i.createInstance(V, e, t, s, n, r) : s ? i.createInstance(K, e, t, s, r) : n.length ? i.createInstance(B, e, t, n, r) : i.createInstance(Oe, e, t, r);
1913
+ }
1914
+ var ze = (i, e, t, s) => {
1915
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
1916
+ (o = i[r]) && (n = o(n) || n);
1917
+ return n;
1918
+ }, S = (i, e) => (t, s) => e(t, s, i);
1919
+ let Ie = class extends L {
1920
+ constructor(e, t, s) {
1921
+ super();
1922
+ l(this, "_entities", /* @__PURE__ */ new Map());
1923
+ l(this, "_entityInit$", new ae());
1924
+ this._injector = e, this._collabSessionService = t, this._univerInstanceService = s, this._init();
1925
+ }
1926
+ dispose() {
1927
+ super.dispose(), this._entities.forEach((e) => e.dispose()), this._entities.clear();
1928
+ }
1929
+ getCollabEntity(e) {
1930
+ var t;
1931
+ return (t = this._entities.get(e)) != null ? t : null;
1932
+ }
1933
+ getCollabEntity$(e) {
1934
+ const t = this.getCollabEntity(e);
1935
+ return t ? Te(t) : this._entityInit$.pipe(kt((s) => s.unitID === e));
1936
+ }
1937
+ _init() {
1938
+ this._univerInstanceService.getTypeOfUnitAdded$(M.UNIVER_SHEET).pipe(R(this.dispose$), Lt(16)).subscribe(async (t) => {
1939
+ const s = t.getUnitId(), n = await this._startCollaboration(s, x.UNIVER_SHEET);
1940
+ this._entities.set(s, n);
1941
+ }), this._univerInstanceService.getTypeOfUnitAdded$(M.UNIVER_DOC).pipe(R(this.dispose$), Lt(16)).pipe(kt((t) => !t.getUnitId().startsWith("__"))).subscribe(async (t) => {
1942
+ const s = t.getUnitId(), n = await this._startCollaboration(s, x.UNIVER_DOC);
1943
+ this._entities.set(s, n);
1944
+ }), Ct(
1945
+ this._univerInstanceService.getTypeOfUnitDisposed$(M.UNIVER_SHEET),
1946
+ this._univerInstanceService.getTypeOfUnitDisposed$(M.UNIVER_DOC)
1947
+ ).pipe(R(this.dispose$)).subscribe((t) => {
1948
+ const s = t.getUnitId(), n = this._entities.get(s);
1949
+ n && (n.dispose(), this._entities.delete(s));
1950
+ });
1951
+ }
1952
+ /**
1953
+ * Start collaboration on a document.
1954
+ *
1955
+ * @param unitID ID of the document to start collaboration.
1956
+ * @returns A disposable to stop collaboration.
1957
+ */
1958
+ async _startCollaboration(e, t) {
1959
+ const s = await this._collabSessionService.requireSession(e), n = this._injector.createInstance(this._getCtorByUniverType(t), e, t, s);
1960
+ return await n.init(), this._entityInit$.next(n), n;
1961
+ }
1962
+ _getCtorByUniverType(e) {
1963
+ switch (e) {
1964
+ case x.UNIVER_DOC:
1965
+ return _t;
1966
+ case x.UNIVER_SHEET:
1967
+ return ut;
1968
+ default:
1969
+ throw new Error(`[CollaborationController]: invalid univer type: ${e}`);
1970
+ }
1971
+ }
1972
+ };
1973
+ Ie = ze([
1974
+ ee(te.Starting, Ie),
1975
+ S(0, _(I)),
1976
+ S(1, _(ye)),
1977
+ S(2, k)
1978
+ ], Ie);
1979
+ let We = class extends L {
1980
+ constructor(e, t, s, n, r, o, a, c, h, u, d, f, v) {
1981
+ super();
1982
+ l(this, "_state$", new U(null));
1983
+ l(this, "state$", this._state$.asObservable());
1984
+ l(this, "_state");
1985
+ l(this, "_collaborationPaused", !1);
1986
+ l(this, "status$", this.state$.pipe(
1987
+ ce((e) => e ? e.status : w.OFFLINE),
1988
+ zs(1)
1989
+ ));
1990
+ /**
1991
+ * Could not transit the state twice at the same time. So we put a lock here in case of implementation fault.
1992
+ */
1993
+ l(this, "_transitionLocked", !1);
1994
+ l(this, "_remoteChangesetQueue", []);
1995
+ this.unitID = e, this._type = t, this._session = s, this._injector = n, this._localCacheService = r, this._univerPermissionService = o, this._compressMutationService = a, this._localeService = c, this._revisionService = h, this._logService = u, this._commandService = d, this._messageService = f, this._singleActiveUnitService = v;
1996
+ }
1997
+ get state() {
1998
+ return this._state;
1999
+ }
2000
+ async init() {
2001
+ if (this.state)
2002
+ throw new Error(
2003
+ '[CollaborationEntity]: initial state has been created before. You should not call "init" twice.'
2004
+ );
2005
+ await this._init();
2006
+ }
2007
+ /**
2008
+ * Pause collaboration on the document. Remote changesets would be inserted to a queue and wait for resuming.
2009
+ * @returns a disposable which will resume collaboration when called.
2010
+ */
2011
+ pauseCollaboration() {
2012
+ return this._collaborationPaused = !0, T(() => {
2013
+ this._collaborationPaused = !1, this._exhaustRemoteChangesetQueue();
2014
+ });
2015
+ }
2016
+ _updateState(e) {
2017
+ this._state = e, this._state$.next(e);
2018
+ }
2019
+ async _init() {
2020
+ var e;
2021
+ return this._updateState(await this._createInitialState()), this._singleActiveUnitService && ((e = this._singleActiveUnitService) == null || e.editingUnit(this.unitID), this.disposeWithMe(
2022
+ T(
2023
+ this._singleActiveUnitService.getUnitStatus$(this.unitID).subscribe((t) => {
2024
+ this._logService.debug("[CollaborationEntity]", "editing status changed to", t), t === fs.OTHER_CLIENTS_EDITING ? (this._messageService.show({
2025
+ content: this._localeService.t("collaboration.single-unit.warning"),
2026
+ type: be.Warning
2027
+ }), this._univerPermissionService.setEditable(this.unitID, !1)) : this._univerPermissionService.setEditable(this.unitID, !0);
2028
+ })
2029
+ )
2030
+ )), this.disposeWithMe(
2031
+ T(
2032
+ this._session.sessionStatus$.subscribe((t) => {
2033
+ t === he.ONLINE ? this._toggleOnline() : t === he.OFFLINE && this._toggleOffline();
2034
+ })
2035
+ )
2036
+ ), this.disposeWithMe(
2037
+ T(
2038
+ this._session.event$.subscribe((t) => {
2039
+ try {
2040
+ const s = t.eventID;
2041
+ s === m.NEW_CHANGESETS ? this._onRemoteChangeset(Nt(t.data)) : s === m.CHANGESET_ACK ? this._onRemoteACK(t.data) : s === m.CHANGESET_REJ ? this._onRemoteRejected() : s === m.PSEUDO_FETCH_MISSING_RESULT && this._onFetchMissResult(
2042
+ t.data.changesets.map(
2043
+ (n) => Nt(n)
2044
+ )
2045
+ );
2046
+ } catch (s) {
2047
+ throw console.error("Error on receiving event", s), s;
2048
+ }
2049
+ })
2050
+ )
2051
+ ), this._state;
2052
+ }
2053
+ _unlockTransition() {
2054
+ this._transitionLocked = !1;
2055
+ }
2056
+ _lockTransition() {
2057
+ if (this._transitionLocked)
2058
+ throw new Error(
2059
+ "[CollaborationEntity]: cannot lock transition twice! This is an implementation error, meaning you transit the collaboration state again in the process of a previous transition. This should never happen."
2060
+ );
2061
+ this._transitionLocked = !0;
2062
+ }
2063
+ _onLocalMutation(e) {
2064
+ this._lockTransition(), this._updateState(this._state.appendMutation(e)), this._unlockTransition();
2065
+ }
2066
+ _onRemoteChangeset(e) {
2067
+ if (!(e.revision <= this._revisionService.getCurrentRevForDocument(this.unitID))) {
2068
+ if (this._collaborationPaused) {
2069
+ this._remoteChangesetQueue.push(e);
2070
+ return;
2071
+ }
2072
+ this._applyRemoteChangeset(e);
2073
+ }
2074
+ }
2075
+ _exhaustRemoteChangesetQueue() {
2076
+ this._remoteChangesetQueue.forEach((e) => this._applyRemoteChangeset(e)), this._remoteChangesetQueue = [];
2077
+ }
2078
+ _applyRemoteChangeset(e) {
2079
+ const t = this._compressMutationService.interceptor.fetchThroughInterceptors(
2080
+ this._compressMutationService.interceptor.getInterceptPoints().COMPRESS_MUTATION_APPLY
2081
+ )(e.mutations, null) || e.mutations, s = { ...e, mutations: t };
2082
+ this._lockTransition(), this._updateState(this._state.onRemoteChangeset(s)), this._unlockTransition();
2083
+ }
2084
+ _onRemoteACK(e) {
2085
+ this._lockTransition(), this._updateState(this._state.onRemoteAck(e)), this._unlockTransition();
2086
+ }
2087
+ _onRemoteRejected() {
2088
+ this._lockTransition(), this._updateState(this._state.onRemoteRej()), this._unlockTransition();
2089
+ }
2090
+ _onFetchMissResult(e) {
2091
+ if (!(this._state instanceof F))
2092
+ throw new TypeError("[CollaborationEntity]: cannot apply missing results on other states!");
2093
+ const t = e.map((s) => {
2094
+ const n = this._compressMutationService.interceptor.fetchThroughInterceptors(
2095
+ this._compressMutationService.interceptor.getInterceptPoints().COMPRESS_MUTATION_APPLY
2096
+ )(s.mutations, null) || s.mutations;
2097
+ return { ...s, mutations: n };
2098
+ });
2099
+ this._lockTransition(), this._updateState(this._state.onMissedChangesetFetched(t)), this._unlockTransition();
2100
+ }
2101
+ _toggleOffline() {
2102
+ this._lockTransition(), this._updateState(this._state.toggleOffline()), this._unlockTransition();
2103
+ }
2104
+ _toggleOnline() {
2105
+ this._lockTransition(), this._updateState(this._state.toggleOnline()), this._unlockTransition();
2106
+ }
2107
+ async _createInitialState() {
2108
+ return new Promise((e) => {
2109
+ this._session.sessionStatus$.pipe($e(1)).subscribe(async (t) => {
2110
+ e(await this._createInitialStateImpl(t === he.ONLINE));
2111
+ });
2112
+ });
2113
+ }
2114
+ _createHandler() {
2115
+ const e = this.unitID;
2116
+ return {
2117
+ onStateChange: (s, n) => {
2118
+ if (s !== this._state)
2119
+ throw new Error(
2120
+ `[ClientCollaborationController]: invalid state transition! State transferred from is not the current state.
2121
+ Before: ${s.status}
2122
+ After: ${n.status}
2123
+ Current: ${this._state.status}`
2124
+ );
2125
+ this._updateState(n);
2126
+ },
2127
+ onSendChangeset: (s) => {
2128
+ const n = {
2129
+ eventID: m.SUBMIT_CHANGESET,
2130
+ data: {
2131
+ unitID: s.unitID,
2132
+ unitType: this._type,
2133
+ changeset: s,
2134
+ memberID: this._session.getMemberID()
2135
+ }
2136
+ };
2137
+ this._session.send(n, this.unitID);
2138
+ },
2139
+ onMissingChangesets: ({ from: s, to: n }) => {
2140
+ this._logService.debug("[CollaborationEntity]", `fetching missing changesets from ${s} to ${n}`);
2141
+ const r = {
2142
+ eventID: m.FETCH_MISSING,
2143
+ data: {
2144
+ unitID: e,
2145
+ unitType: this._type,
2146
+ from: s,
2147
+ to: n
2148
+ }
2149
+ };
2150
+ this._session.send(r, this.unitID);
2151
+ }
2152
+ };
2153
+ }
2154
+ async _createInitialStateImpl(e) {
2155
+ var a, c;
2156
+ const t = await this._localCacheService.loadOfflineData(this.unitID), s = (a = t == null ? void 0 : t.mutations) != null ? a : [], n = (c = t == null ? void 0 : t.awaitingChangeset) != null ? c : null, r = this.unitID;
2157
+ try {
2158
+ this._replayCachedMutations(n, s);
2159
+ } catch (h) {
2160
+ this._logService.error(h);
2161
+ }
2162
+ const o = this._createHandler();
2163
+ if (e) {
2164
+ const h = vs(
2165
+ this._injector,
2166
+ r,
2167
+ this._type,
2168
+ n,
2169
+ s,
2170
+ o
2171
+ );
2172
+ return h instanceof B ? h._schedule() : (h instanceof V || h instanceof K) && h.resend(), h;
2173
+ }
2174
+ return this._injector.createInstance(Y, r, this._type, n, s, o);
2175
+ }
2176
+ _replayCachedMutations(e, t) {
2177
+ var n, r;
2178
+ const s = this._compressMutationService.interceptor.fetchThroughInterceptors(
2179
+ this._compressMutationService.interceptor.getInterceptPoints().COMPRESS_MUTATION_APPLY
2180
+ );
2181
+ (n = s((e == null ? void 0 : e.mutations) || [], null)) == null || n.forEach(
2182
+ (o) => this._commandService.executeCommand(o.id, o.params)
2183
+ ), (r = s(t || [], null)) == null || r.forEach(
2184
+ (o) => this._commandService.executeCommand(o.id, o.params)
2185
+ );
2186
+ }
2187
+ };
2188
+ We = ze([
2189
+ S(3, _(I)),
2190
+ S(4, _(y)),
2191
+ S(5, _(Ke)),
2192
+ S(6, _(vt)),
2193
+ S(7, _(H)),
2194
+ S(8, _($)),
2195
+ S(9, D),
2196
+ S(10, O),
2197
+ S(11, Me),
2198
+ S(12, Ye(Xe))
2199
+ ], We);
2200
+ let _t = class extends We {
2201
+ constructor(i, e, t, s, n, r, o, a, c, h, u, d, f, v, p, E, b) {
2202
+ super(
2203
+ i,
2204
+ e,
2205
+ t,
2206
+ s,
2207
+ n,
2208
+ r,
2209
+ o,
2210
+ a,
2211
+ c,
2212
+ v,
2213
+ p,
2214
+ E,
2215
+ b
2216
+ ), this.unitID = i, this.type = e, this.session = t, this._docStateChangeManagerService = h, this._docTransformIMECacheService = u, this._docTransformSelectionsService = d, this._docSyncEditingCollabCursorService = f;
2217
+ }
2218
+ _createHandler() {
2219
+ const i = super._createHandler();
2220
+ return i.onTransformIME = (e) => this._docTransformIMECacheService.transformIMECache(e), i.onTransformSelections = (e) => this._docTransformSelectionsService.transformSelections(e), i.onSyncEditingCollabCursor = (e) => this._docSyncEditingCollabCursorService.syncEditingCollabCursor(e), i.onTransformRemoteChangesetByIMECache = (e) => this._docTransformIMECacheService.transformRemoteChangeset(e), i;
2221
+ }
2222
+ async _init() {
2223
+ const i = await super._init();
2224
+ return this._docStateChangeManagerService.docStateChange$.pipe(R(this.dispose$)).subscribe((e) => {
2225
+ if (e == null)
2226
+ return;
2227
+ const { unitId: t, redoState: s, commandId: n } = e;
2228
+ if (t !== this.unitID)
2229
+ return;
2230
+ const r = {
2231
+ id: n,
2232
+ type: Zt.MUTATION,
2233
+ params: {
2234
+ unitId: t,
2235
+ actions: s.actions,
2236
+ textRanges: null
2237
+ }
2238
+ };
2239
+ this._onLocalMutation(r);
2240
+ }), i;
2241
+ }
2242
+ };
2243
+ _t = ze([
2244
+ S(3, _(I)),
2245
+ S(4, _(y)),
2246
+ S(5, _(Ke)),
2247
+ S(6, _(vt)),
2248
+ S(7, _(H)),
2249
+ S(8, _($)),
2250
+ S(9, _(Js)),
2251
+ S(10, _(Be)),
2252
+ S(11, _(Ve)),
2253
+ S(12, _(yt)),
2254
+ S(13, D),
2255
+ S(14, O),
2256
+ S(15, Me),
2257
+ S(16, Ye(Xe))
2258
+ ], _t);
2259
+ let ut = class extends We {
2260
+ constructor(i, e, t, s, n, r, o, a, c, h, u, d, f, v) {
2261
+ super(
2262
+ i,
2263
+ e,
2264
+ t,
2265
+ s,
2266
+ n,
2267
+ r,
2268
+ o,
2269
+ a,
2270
+ c,
2271
+ u,
2272
+ d,
2273
+ f,
2274
+ v
2275
+ ), this.unitID = i, this.type = e, this.session = t, this._sheetTransformSelectionsService = h;
2276
+ }
2277
+ _createHandler() {
2278
+ const i = super._createHandler();
2279
+ return i.onTransformSelections = (e) => this._sheetTransformSelectionsService.transformSelections(e), i;
2280
+ }
2281
+ async _init() {
2282
+ const i = await super._init();
2283
+ return this.disposeWithMe(
2284
+ this._commandService.onCommandExecuted((e, t) => {
2285
+ if (e.type !== Zt.MUTATION || t != null && t.fromCollab || t != null && t.onlyLocal)
2286
+ return;
2287
+ const s = e.params;
2288
+ if ((s == null ? void 0 : s.unitId) !== this.unitID)
2289
+ return;
2290
+ const n = e, r = this._compressMutationService.interceptor.fetchThroughInterceptors(
2291
+ this._compressMutationService.interceptor.getInterceptPoints().COMPRESS_MUTATION_SEND
2292
+ )([n], null) || [n];
2293
+ this._onLocalMutation(r[0]);
2294
+ })
2295
+ ), i;
2296
+ }
2297
+ };
2298
+ ut = ze([
2299
+ S(3, _(I)),
2300
+ S(4, _(y)),
2301
+ S(5, _(Ke)),
2302
+ S(6, _(vt)),
2303
+ S(7, _(H)),
2304
+ S(8, _($)),
2305
+ S(9, _(Fe)),
2306
+ S(10, D),
2307
+ S(11, O),
2308
+ S(12, Me),
2309
+ S(13, Ye(Xe))
2310
+ ], ut);
2311
+ const Wt = ["purple300", "jiqing500", "verdancy600", "red300", "blue400", "gold400"];
2312
+ class Ot extends X {
2313
+ constructor() {
2314
+ super(...arguments);
2315
+ l(this, "_assignedColors", /* @__PURE__ */ new Map());
2316
+ l(this, "_colorIndex", 0);
2317
+ }
2318
+ assignAColorForMemberID(t) {
2319
+ if (this._assignedColors.has(t))
2320
+ return this._assignedColors.get(t);
2321
+ const s = Wt[this._colorIndex];
2322
+ return this._colorIndex = (this._colorIndex + 1) % Wt.length, this._assignedColors.set(t, s), s;
2323
+ }
2324
+ }
2325
+ var on = (i, e, t, s) => {
2326
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
2327
+ (o = i[r]) && (n = o(n) || n);
2328
+ return n;
2329
+ }, ne = (i, e) => (t, s) => e(t, s, i);
2330
+ const an = 300, cn = 100, hn = () => {
2331
+ let i = [], e = !1;
2332
+ return (t) => {
2333
+ i.push(t), e || (e = !0, setTimeout(() => {
2334
+ i.forEach((s) => s()), i = [], e = !1;
2335
+ }));
2336
+ };
2337
+ };
2338
+ let dt = class extends L {
2339
+ constructor(e, t, s, n, r, o, a, c) {
2340
+ super();
2341
+ l(this, "_online", !1);
2342
+ l(this, "_init", !1);
2343
+ /** Cursor info of the collaboration room members. The key would be the memberID. */
2344
+ l(this, "_cursorInfo$", new U(/* @__PURE__ */ new Map()));
2345
+ l(this, "cursorInfo$", this._cursorInfo$.asObservable());
2346
+ l(this, "_roomMembers$", new U([]));
2347
+ l(this, "roomMembers$", this._roomMembers$.pipe(is(an)));
2348
+ l(this, "_updateLocalCursor", Et((e, t) => {
2349
+ const s = {
2350
+ eventID: m.UPDATE_CURSOR,
2351
+ data: {
2352
+ unitID: this.unitID,
2353
+ memberID: this._session.getMemberID(),
2354
+ selection: vi(e, t.range)
2355
+ }
2356
+ };
2357
+ this._session.send(s, this.unitID);
2358
+ }, cn));
2359
+ this.unitID = e, this._session = t, this._injector = s, this._colorAssignService = n, this._memberService = r, this._univerInstanceService = o, this._commandService = a, this._refRangeService = c;
2360
+ }
2361
+ get cursorInfo() {
2362
+ return this._cursorInfo$.getValue();
2363
+ }
2364
+ get roomMembers() {
2365
+ return this._roomMembers$.getValue();
2366
+ }
2367
+ dispose() {
2368
+ super.dispose(), this._cursorInfo$.next(/* @__PURE__ */ new Map()), this._cursorInfo$.complete(), this._roomMembers$.next([]), this._roomMembers$.complete();
2369
+ }
2370
+ init() {
2371
+ this._init || (this._init = !0, this._session.sessionStatus$.pipe(R(this.dispose$)).subscribe((e) => {
2372
+ e === he.ONLINE ? this._toggleOnline() : this._toggleOffline();
2373
+ }), this._session.event$.pipe(R(this.dispose$)).subscribe((e) => {
2374
+ const t = e.eventID;
2375
+ t === m.UPDATE_CURSOR && this._onCursorUpdate(e), t === m.USERS_LEAVE && this._onCursorDelete(e);
2376
+ }), this._onRefRangeChange(), this.disposeWithMe(
2377
+ this._commandService.onCommandExecuted((e) => {
2378
+ if (this._online && e.id === at.id && e.params.unitId === this.unitID) {
2379
+ const t = e.params;
2380
+ this._updateLocalCursor(t.subUnitId, t.selections[0]);
2381
+ }
2382
+ })
2383
+ ));
2384
+ }
2385
+ _onCursorUpdate(e) {
2386
+ var h, u;
2387
+ const { memberID: t, selection: s } = e.data, { sheetName: n, range: r } = Si(s), a = {
2388
+ name: (u = (h = this._memberService.getMember(this.unitID, t)) == null ? void 0 : h.name) != null ? u : "Unknown user",
2389
+ range: this._getMergeRange(n, r),
2390
+ sheetID: n,
2391
+ color: this._colorAssignService.assignAColorForMemberID(t),
2392
+ selection: s
2393
+ }, c = this.cursorInfo;
2394
+ c.set(t, a), this._cursorInfo$.next(c);
2395
+ }
2396
+ _onCursorDelete(e) {
2397
+ const { memberID: t } = e.data, s = this.cursorInfo;
2398
+ s.delete(t), this._cursorInfo$.next(s);
2399
+ }
2400
+ _getMergeRange(e, t) {
2401
+ var n, r;
2402
+ const s = (r = (n = this._univerInstanceService.getUniverSheetInstance(this.unitID)) == null ? void 0 : n.getSheetBySheetId(e)) == null ? void 0 : r.getMergeData();
2403
+ return (s == null ? void 0 : s.find((o) => Us.contains(o, t))) || t;
2404
+ }
2405
+ _onRefRangeChange() {
2406
+ const e = new Jt(), t = hn(), s = () => {
2407
+ e.dispose();
2408
+ const n = (r, o, a, c) => {
2409
+ let h = [];
2410
+ switch (r.id) {
2411
+ case j.DeleteRangeMoveLeftCommandId: {
2412
+ h = gi(r, c);
2413
+ break;
2414
+ }
2415
+ case j.DeleteRangeMoveUpCommandId: {
2416
+ h = di(r, c);
2417
+ break;
2418
+ }
2419
+ case j.InsertColCommandId: {
2420
+ h = ui(r, c);
2421
+ break;
2422
+ }
2423
+ case j.InsertRangeMoveDownCommandId: {
2424
+ h = _i(r, c);
2425
+ break;
2426
+ }
2427
+ case j.InsertRangeMoveRightCommandId: {
2428
+ h = li(r, c);
2429
+ break;
2430
+ }
2431
+ case j.InsertRowCommandId: {
2432
+ h = hi(r, c);
2433
+ break;
2434
+ }
2435
+ case j.MoveRangeCommandId: {
2436
+ h = ci(r, c);
2437
+ break;
2438
+ }
2439
+ case j.RemoveColCommandId: {
2440
+ h = ai(r, c);
2441
+ break;
2442
+ }
2443
+ case j.RemoveRowCommandId: {
2444
+ h = oi(r, c);
2445
+ break;
2446
+ }
2447
+ }
2448
+ const u = mi(h, c), d = this.cursorInfo.get(o);
2449
+ if (d && u) {
2450
+ const f = {
2451
+ ...d,
2452
+ range: u
2453
+ };
2454
+ this.cursorInfo.set(o, f), t(() => {
2455
+ const v = this._refRangeService.registerRefRange(u, (p) => (v.dispose(), n(p, o, a, u)));
2456
+ e.add(v);
2457
+ });
2458
+ }
2459
+ return {
2460
+ redos: [],
2461
+ undos: []
2462
+ };
2463
+ };
2464
+ this.cursorInfo.forEach((r, o) => {
2465
+ const { range: a, sheetID: c } = r, h = this._refRangeService.registerRefRange(a, (u) => (h.dispose(), n(u, o, c, a)));
2466
+ e.add(h);
2467
+ });
2468
+ };
2469
+ this.disposeWithMe(
2470
+ T(
2471
+ this._cursorInfo$.subscribe(() => {
2472
+ s();
2473
+ })
2474
+ )
2475
+ );
2476
+ }
2477
+ _toggleOnline() {
2478
+ var s, n;
2479
+ if (this._online = !0, ((s = this._univerInstanceService.getFocusedUnit()) == null ? void 0 : s.getUnitId()) !== this.unitID)
2480
+ return;
2481
+ const t = (n = this._injector.get(hs).getSelections()) == null ? void 0 : n[0];
2482
+ t && this._updateLocalCursor(
2483
+ this._univerInstanceService.getCurrentUnitForType(M.UNIVER_SHEET).getActiveSheet().getSheetId(),
2484
+ t
2485
+ );
2486
+ }
2487
+ _toggleOffline() {
2488
+ this._online = !1;
2489
+ }
2490
+ };
2491
+ dt = on([
2492
+ ne(2, _(I)),
2493
+ ne(3, _(Ot)),
2494
+ ne(4, _(Z)),
2495
+ ne(5, k),
2496
+ ne(6, O),
2497
+ ne(7, _(ri))
2498
+ ], dt);
2499
+ var ln = (i, e, t, s) => {
2500
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
2501
+ (o = i[r]) && (n = o(n) || n);
2502
+ return n;
2503
+ }, q = (i, e) => (t, s) => e(t, s, i);
2504
+ const _n = 300, un = 100;
2505
+ let gt = class extends L {
2506
+ constructor(e, t, s, n, r, o, a, c, h) {
2507
+ super();
2508
+ l(this, "_online", !1);
2509
+ l(this, "_init", !1);
2510
+ /** Cursor info of the collaboration room members. The key would be the memberID. */
2511
+ l(this, "_cursorInfo$", new U(/* @__PURE__ */ new Map()));
2512
+ l(this, "cursorInfo$", this._cursorInfo$.asObservable());
2513
+ l(this, "_roomMembers$", new U([]));
2514
+ l(this, "roomMembers$", this._roomMembers$.pipe(is(_n)));
2515
+ l(this, "_updateLocalCursor", Et((e) => {
2516
+ const t = {
2517
+ eventID: m.UPDATE_CURSOR,
2518
+ data: {
2519
+ unitID: this.unitID,
2520
+ memberID: this._session.getMemberID(),
2521
+ selection: Ss(e)
2522
+ }
2523
+ };
2524
+ this._session.send(t, this.unitID);
2525
+ }, un));
2526
+ this.unitID = e, this._session = t, this._injector = s, this._colorAssignService = n, this._memberService = r, this._syncEditingCollabCursorService = o, this._transformService = a, this._univerInstanceService = c, this._commandService = h;
2527
+ }
2528
+ get cursorInfo() {
2529
+ return this._cursorInfo$.getValue();
2530
+ }
2531
+ get roomMembers() {
2532
+ return this._roomMembers$.getValue();
2533
+ }
2534
+ dispose() {
2535
+ super.dispose(), this._cursorInfo$.next(/* @__PURE__ */ new Map()), this._cursorInfo$.complete(), this._roomMembers$.next([]), this._roomMembers$.complete();
2536
+ }
2537
+ init() {
2538
+ this._init || (this._init = !0, this._session.sessionStatus$.pipe(R(this.dispose$)).subscribe((e) => {
2539
+ e === he.ONLINE ? this._toggleOnline() : this._toggleOffline();
2540
+ }), this._session.event$.pipe(R(this.dispose$)).subscribe((e) => {
2541
+ const t = e.eventID;
2542
+ t === m.UPDATE_CURSOR && this._onCursorUpdate(e), t === m.USERS_LEAVE && this._onCursorDelete(e);
2543
+ }), this.disposeWithMe(
2544
+ this._commandService.onCommandExecuted((e) => {
2545
+ const t = e.params;
2546
+ t != null && this._online && e.id === qs.id && t.unitId === this.unitID && t.isEditing === !1 && this._updateLocalCursor(t.ranges);
2547
+ })
2548
+ ), this._syncEditingCollabCursorService.collabCursorState$.pipe(R(this.dispose$)).subscribe((e) => {
2549
+ if ((e == null ? void 0 : e.unitID) !== this.unitID)
2550
+ return;
2551
+ const t = {
2552
+ eventID: m.UPDATE_CURSOR,
2553
+ data: e
2554
+ };
2555
+ this._onCursorUpdate(t);
2556
+ }), this.disposeWithMe(
2557
+ this._commandService.onCommandExecuted((e) => {
2558
+ if (e.params == null)
2559
+ return;
2560
+ const t = e.params;
2561
+ if (e.id !== Zs.id || t.unitId !== this.unitID)
2562
+ return;
2563
+ const s = {
2564
+ id: "doc.mutation.rich-text-editing",
2565
+ params: t
2566
+ }, n = this.cursorInfo;
2567
+ for (const [r, o] of n) {
2568
+ const a = {
2569
+ id: "doc.mutation.rich-text-editing",
2570
+ params: {
2571
+ unitId: this.unitID,
2572
+ actions: [],
2573
+ textRanges: o.ranges
2574
+ }
2575
+ }, c = this._transformService.transformMutation(s, a, !1);
2576
+ if (Le(c))
2577
+ throw c.error;
2578
+ n.set(r, {
2579
+ ...o,
2580
+ ranges: c.m2Prime.params.textRanges
2581
+ });
2582
+ }
2583
+ queueMicrotask(() => {
2584
+ this._cursorInfo$.next(n);
2585
+ });
2586
+ })
2587
+ ));
2588
+ }
2589
+ _onCursorUpdate(e) {
2590
+ var c, h;
2591
+ const { memberID: t, selection: s } = e.data, n = Zi(s), r = (h = (c = this._memberService.getMember(this.unitID, t)) == null ? void 0 : c.name) != null ? h : "Unknown user", o = {
2592
+ color: this._colorAssignService.assignAColorForMemberID(t),
2593
+ name: r,
2594
+ ranges: n
2595
+ }, a = this.cursorInfo;
2596
+ a.set(t, o), this._cursorInfo$.next(a);
2597
+ }
2598
+ _onCursorDelete(e) {
2599
+ const { memberID: t } = e.data, s = this.cursorInfo;
2600
+ s.delete(t), this._cursorInfo$.next(s);
2601
+ }
2602
+ _toggleOnline() {
2603
+ var n;
2604
+ if (this._online = !0, ((n = this._univerInstanceService.getFocusedUnit()) == null ? void 0 : n.getUnitId()) !== this.unitID)
2605
+ return;
2606
+ const t = this._injector.get(os).getSelections(), s = t == null ? void 0 : t.map(as);
2607
+ Array.isArray(s) && s.length > 0 && this._updateLocalCursor(s);
2608
+ }
2609
+ _toggleOffline() {
2610
+ this._online = !1;
2611
+ }
2612
+ };
2613
+ gt = ln([
2614
+ q(2, _(I)),
2615
+ q(3, _(Ot)),
2616
+ q(4, _(Z)),
2617
+ q(5, _(yt)),
2618
+ q(6, W),
2619
+ q(7, k),
2620
+ q(8, O)
2621
+ ], gt);
2622
+ var dn = (i, e, t, s) => {
2623
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
2624
+ (o = i[r]) && (n = o(n) || n);
2625
+ return n;
2626
+ }, et = (i, e) => (t, s) => e(t, s, i);
2627
+ let le = class extends L {
2628
+ constructor(e, t, s) {
2629
+ super();
2630
+ // The the kay would be the memberID.
2631
+ l(this, "_entities", /* @__PURE__ */ new Map());
2632
+ l(this, "_entityInit$", new ae());
2633
+ this._univerInstanceService = e, this._injector = t, this._collabSessionService = s, this._init();
2634
+ }
2635
+ dispose() {
2636
+ super.dispose(), this._entityInit$.complete(), this._entities.forEach((e) => e.dispose());
2637
+ }
2638
+ getCollabCursors$(e) {
2639
+ return this._entities.has(e) ? this._entities.get(e).cursorInfo$ : this._entityInit$.pipe(
2640
+ Ut((t) => t.unitID === e),
2641
+ ot((t) => t.cursorInfo$)
2642
+ );
2643
+ }
2644
+ _init() {
2645
+ this._univerInstanceService.getTypeOfUnitAdded$(M.UNIVER_SHEET).pipe(R(this.dispose$)).subscribe(async (e) => {
2646
+ const t = e.getUnitId(), s = await this._startSheetCollabCursor(t);
2647
+ this._entityInit$.next(s), this._entities.set(t, s);
2648
+ }), this._univerInstanceService.getTypeOfUnitAdded$(M.UNIVER_DOC).pipe(R(this.dispose$)).pipe(Ut((e) => !e.getUnitId().startsWith("__"))).subscribe(async (e) => {
2649
+ const t = e.getUnitId(), s = await this._startDocCollabCursor(t);
2650
+ this._entityInit$.next(s), this._entities.set(t, s);
2651
+ }), Ct(
2652
+ this._univerInstanceService.getTypeOfUnitDisposed$(M.UNIVER_DOC),
2653
+ this._univerInstanceService.getTypeOfUnitDisposed$(M.UNIVER_SHEET)
2654
+ ).pipe(R(this.dispose$)).subscribe((e) => {
2655
+ const t = e.getUnitId(), s = this._entities.get(t);
2656
+ s && (s.dispose(), this._entities.delete(t));
2657
+ });
2658
+ }
2659
+ async _startSheetCollabCursor(e) {
2660
+ const t = await this._collabSessionService.requireSession(e), s = this._injector.createInstance(dt, e, t);
2661
+ return s.init(), s;
2662
+ }
2663
+ async _startDocCollabCursor(e) {
2664
+ const t = await this._collabSessionService.requireSession(e), s = this._injector.createInstance(gt, e, t);
2665
+ return s.init(), s;
2666
+ }
2667
+ };
2668
+ le = dn([
2669
+ ee(te.Starting, le),
2670
+ et(0, k),
2671
+ et(1, _(I)),
2672
+ et(2, _(ye))
2673
+ ], le);
2674
+ const we = 20, Gt = 200, tt = 4, gn = 5;
2675
+ function mn(i, e) {
2676
+ let { radius: t, width: s, height: n } = e;
2677
+ t = t != null ? t : 0, s = s != null ? s : 30, n = n != null ? n : 30;
2678
+ let r = 0, o = 0, a = 0;
2679
+ r = o = a = Math.min(t, s / 2, n / 2), i.beginPath(), i.moveTo(r, 0), i.lineTo(s - o, 0), i.arc(s - o, o, o, Math.PI * 3 / 2, 0, !1), i.lineTo(s, n - a), i.arc(s - a, n - a, a, 0, Math.PI / 2, !1), i.lineTo(0, n), i.lineTo(0, r), i.arc(r, r, r, Math.PI, Math.PI * 3 / 2, !1), i.closePath(), e.fill && (i.save(), i.fillStyle = e.fill, e.fillRule === "evenodd" ? i.fill("evenodd") : i.fill(), i.restore());
2680
+ }
2681
+ class Je extends ls {
2682
+ constructor(t, s) {
2683
+ super(t, s);
2684
+ l(this, "color");
2685
+ l(this, "text");
2686
+ this.color = s == null ? void 0 : s.color, this.text = s == null ? void 0 : s.text;
2687
+ }
2688
+ static drawWith(t, s) {
2689
+ const { text: n, color: r } = s;
2690
+ t.save(), t.font = "bold 13px Source Han Sans CN";
2691
+ const o = t.measureText(n).width, a = Math.min(
2692
+ o + 2 * tt,
2693
+ Gt
2694
+ );
2695
+ mn(t, {
2696
+ height: we,
2697
+ radius: 4,
2698
+ width: a,
2699
+ fill: r,
2700
+ evented: !1
2701
+ }), t.fillStyle = "#FFF";
2702
+ const c = tt, h = we - gn, u = Gt - 2 * tt;
2703
+ if (o > u) {
2704
+ let d = "", f = 0;
2705
+ for (const v of n) {
2706
+ const p = t.measureText(v).width;
2707
+ if (f + p <= u - t.measureText("...").width)
2708
+ d += v, f += p;
2709
+ else {
2710
+ d += "...";
2711
+ break;
2712
+ }
2713
+ }
2714
+ t.fillText(d, c, h);
2715
+ } else
2716
+ t.fillText(n, c, h);
2717
+ t.restore();
2718
+ }
2719
+ _draw(t) {
2720
+ Je.drawWith(t, this);
2721
+ }
2722
+ }
2723
+ const fn = 1, Sn = 1.5;
2724
+ class vn extends ls {
2725
+ constructor(t, s) {
2726
+ super(t, s);
2727
+ l(this, "_color");
2728
+ l(this, "_hovered", !1);
2729
+ l(this, "_range");
2730
+ l(this, "_name", "");
2731
+ l(this, "_labelPosition", "top");
2732
+ s && this.setShapeProps(s), this.onPointerEnterObserver.add(() => this.setShapeProps({ hovered: !0 })), this.onPointerLeaveObserver.add(() => this.setShapeProps({ hovered: !1 }));
2733
+ }
2734
+ setShapeProps(t) {
2735
+ var s, n, r, o, a;
2736
+ this._color = (s = t.color) != null ? s : this._color, this._hovered = (n = t.hovered) != null ? n : this._hovered, this._range = (r = t.range) != null ? r : this._range, this._name = (o = t.name) != null ? o : this._name, this._labelPosition = (a = t.labelPosition) != null ? a : this._labelPosition, this.transformByState({
2737
+ width: t.width,
2738
+ height: t.height
2739
+ });
2740
+ }
2741
+ onMouseMove(t) {
2742
+ const { row: s, column: n } = t;
2743
+ if (s >= this._range.startRow && s <= this._range.endRow && n >= this._range.startColumn && n <= this._range.endColumn) {
2744
+ this.setShapeProps({ hovered: !0 });
2745
+ return;
2746
+ }
2747
+ this.setShapeProps({ hovered: !1 });
2748
+ }
2749
+ triggerDblclick(t) {
2750
+ return !1;
2751
+ }
2752
+ _draw(t) {
2753
+ ct.drawWith(t, {
2754
+ width: this.width,
2755
+ height: this.height,
2756
+ strokeWidth: Sn,
2757
+ stroke: this._color,
2758
+ evented: !1
2759
+ }), this._hovered && (t.save(), t.transform(
2760
+ 1,
2761
+ 0,
2762
+ 0,
2763
+ 1,
2764
+ this.width,
2765
+ this._labelPosition === "bottom" ? 0 : -we
2766
+ ), Je.drawWith(t, {
2767
+ text: this._name,
2768
+ color: this._color
2769
+ }), t.restore());
2770
+ }
2771
+ }
2772
+ var pn = (i, e, t, s) => {
2773
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
2774
+ (o = i[r]) && (n = o(n) || n);
2775
+ return n;
2776
+ }, Se = (i, e) => (t, s) => e(t, s, i);
2777
+ let Pe = class extends L {
2778
+ constructor(e, t, s, n, r) {
2779
+ super();
2780
+ /** Cursors stored for different Workbooks. */
2781
+ l(this, "_cursors", /* @__PURE__ */ new Set());
2782
+ l(this, "_lastPointer", null);
2783
+ this._collabCursorController = e, this._univerInstanceService = t, this._renderManagerService = s, this._sheetSkeletonManagerService = n, this._themeService = r, this._init();
2784
+ }
2785
+ _init() {
2786
+ this._sheetSkeletonManagerService.currentSkeleton$.pipe(
2787
+ It(this.dispose$),
2788
+ rs((e) => {
2789
+ if (e) {
2790
+ const t = e.sheetId;
2791
+ return ns(
2792
+ this._collabCursorController.getCollabCursors$(e.unitId),
2793
+ this._themeService.currentTheme$
2794
+ ).pipe(
2795
+ ce(([s, n]) => {
2796
+ const r = /* @__PURE__ */ new Map();
2797
+ return s.forEach((o, a) => {
2798
+ if (o.sheetID === t) {
2799
+ const c = { ...o };
2800
+ c.color = n[o.color], r.set(a, c);
2801
+ }
2802
+ }), {
2803
+ skeleton: e,
2804
+ cursors: r
2805
+ };
2806
+ })
2807
+ );
2808
+ }
2809
+ return Te({
2810
+ skeleton: null,
2811
+ cursors: /* @__PURE__ */ new Map()
2812
+ });
2813
+ })
2814
+ ).subscribe(({ skeleton: e, cursors: t }) => {
2815
+ this._removeCollabCursors(), e && this._updateCollabCursors(e, t);
2816
+ }), this._sheetSkeletonManagerService.currentSkeleton$.subscribe((e) => {
2817
+ if (e == null)
2818
+ return;
2819
+ const { unitId: t, skeleton: s } = e, n = this._renderManagerService.getRenderById(t);
2820
+ if (n == null)
2821
+ return;
2822
+ const { scene: r } = n;
2823
+ r.onPointerMoveObserver.add(
2824
+ Et((o) => {
2825
+ var b, G;
2826
+ const { offsetX: a, offsetY: c } = o, { x: h, y: u } = r.getRelativeCoord(
2827
+ $t.FromArray([a, c])
2828
+ ), { scaleX: d, scaleY: f } = r.getAncestorScale(), v = r.getViewport(Ii.VIEW_MAIN), p = r.getScrollXYByRelativeCoords(
2829
+ $t.FromArray([h, u]),
2830
+ v
2831
+ ), E = s.getCellPositionByOffset(
2832
+ a,
2833
+ c,
2834
+ d,
2835
+ f,
2836
+ p
2837
+ );
2838
+ ((b = this._lastPointer) == null ? void 0 : b.column) === E.column && ((G = this._lastPointer) == null ? void 0 : G.row) === E.row || this._cursors.forEach((ue) => {
2839
+ ue.onMouseMove(E);
2840
+ });
2841
+ }, 100)
2842
+ );
2843
+ });
2844
+ }
2845
+ _updateCollabCursors(e, t) {
2846
+ var a;
2847
+ const s = (a = this._sheetSkeletonManagerService.getCurrent()) == null ? void 0 : a.skeleton;
2848
+ if (!s)
2849
+ return;
2850
+ const n = this._getSheetObject();
2851
+ if (!n)
2852
+ return;
2853
+ this._cursors.forEach((c) => {
2854
+ c.makeDirty();
2855
+ });
2856
+ const { scene: r } = n, o = Cn(Array.from(t.values())).map((c) => {
2857
+ const { color: h, range: u, name: d, selection: f, sheetID: v } = c, { startColumn: p, startRow: E, endColumn: b, endRow: G } = u, ue = Pt(E, p, r, s), qe = Pt(G, b, r, s), { columnHeaderHeightAndMarginTop: de } = s, { startX: ge, startY: Ze } = ue, { endX: bs, endY: Ts } = qe, Rs = bs - ge, ys = Ts - Ze, Os = {
2858
+ labelPosition: Ze - de >= we ? "top" : "bottom",
2859
+ sheetID: v,
2860
+ range: u,
2861
+ color: h,
2862
+ name: d,
2863
+ selection: f,
2864
+ left: ge,
2865
+ top: Ze,
2866
+ width: Rs,
2867
+ height: ys,
2868
+ evented: !1
2869
+ };
2870
+ return new vn(d, Os);
2871
+ });
2872
+ r.addObjects(o, fn), this._cursors = new Set(o);
2873
+ }
2874
+ _removeCollabCursors() {
2875
+ var e;
2876
+ (e = this._cursors) == null || e.forEach((t) => t.dispose());
2877
+ }
2878
+ _getSheetObject() {
2879
+ return Ei(this._univerInstanceService, this._renderManagerService);
2880
+ }
2881
+ };
2882
+ Pe = pn([
2883
+ ee(te.Steady, Pe),
2884
+ Se(0, _(le)),
2885
+ Se(1, k),
2886
+ Se(2, _s),
2887
+ Se(3, _(bi)),
2888
+ Se(4, _(Qt))
2889
+ ], Pe);
2890
+ function Cn(i) {
2891
+ const e = /* @__PURE__ */ new Map();
2892
+ return i.forEach((t) => {
2893
+ if (e.has(t.selection)) {
2894
+ const s = e.get(t.selection);
2895
+ s.name += `, ${t.name}`;
2896
+ } else
2897
+ e.set(t.selection, t);
2898
+ }), Array.from(e.values());
2899
+ }
2900
+ var A = function() {
2901
+ return A = Object.assign || function(i) {
2902
+ for (var e, t = 1, s = arguments.length; t < s; t++) {
2903
+ e = arguments[t];
2904
+ for (var n in e)
2905
+ Object.prototype.hasOwnProperty.call(e, n) && (i[n] = e[n]);
2906
+ }
2907
+ return i;
2908
+ }, A.apply(this, arguments);
2909
+ }, In = function(i, e) {
2910
+ var t = {};
2911
+ for (var s in i)
2912
+ Object.prototype.hasOwnProperty.call(i, s) && e.indexOf(s) < 0 && (t[s] = i[s]);
2913
+ if (i != null && typeof Object.getOwnPropertySymbols == "function")
2914
+ for (var n = 0, s = Object.getOwnPropertySymbols(i); n < s.length; n++)
2915
+ e.indexOf(s[n]) < 0 && Object.prototype.propertyIsEnumerable.call(i, s[n]) && (t[s[n]] = i[s[n]]);
2916
+ return t;
2917
+ }, wt = bt(function(i, e) {
2918
+ var t = i.icon, s = i.id, n = i.className, r = i.extend, o = In(i, ["icon", "id", "className", "extend"]), a = "univerjs-icon univerjs-icon-".concat(s, " ").concat(n || "").trim(), c = yi("_".concat(Tn()));
2919
+ return ps(t, "".concat(s), { defIds: t.defIds, idSuffix: c.current }, A({ ref: e, className: a }, o), r);
2920
+ });
2921
+ function ps(i, e, t, s, n) {
2922
+ return Tt(i.tag, A(A({ key: e }, En(i, t, n)), s), (bn(i, t).children || []).map(function(r, o) {
2923
+ return ps(r, "".concat(e, "-").concat(i.tag, "-").concat(o), t, void 0, n);
2924
+ }));
2925
+ }
2926
+ function En(i, e, t) {
2927
+ var s = A({}, i.attrs);
2928
+ t != null && t.colorChannel1 && s.fill === "colorChannel1" && (s.fill = t.colorChannel1);
2929
+ var n = e.defIds;
2930
+ return !n || n.length === 0 || (i.tag === "use" && s["xlink:href"] && (s["xlink:href"] = s["xlink:href"] + e.idSuffix), Object.entries(s).forEach(function(r) {
2931
+ var o = r[0], a = r[1];
2932
+ typeof a == "string" && (s[o] = a.replace(/url\(#(.*)\)/, "url(#$1".concat(e.idSuffix, ")")));
2933
+ })), s;
2934
+ }
2935
+ function bn(i, e) {
2936
+ var t, s = e.defIds;
2937
+ return !s || s.length === 0 ? i : i.tag === "defs" && (!((t = i.children) === null || t === void 0) && t.length) ? A(A({}, i), { children: i.children.map(function(n) {
2938
+ return typeof n.attrs.id == "string" && s && s.indexOf(n.attrs.id) > -1 ? A(A({}, n), { attrs: A(A({}, n.attrs), { id: n.attrs.id + e.idSuffix }) }) : n;
2939
+ }) }) : i;
2940
+ }
2941
+ function Tn() {
2942
+ return Math.random().toString(36).substring(2, 8);
2943
+ }
2944
+ wt.displayName = "UniverIcon";
2945
+ var Rn = { tag: "svg", attrs: { fill: "none", viewBox: "0 0 16 16", width: "1em", height: "1em" }, children: [{ tag: "mask", attrs: { id: "mask0_102_585", style: { maskType: "alpha" }, width: 16, height: 16, x: 0, y: 0, maskUnits: "userSpaceOnUse" }, children: [{ tag: "path", attrs: { fill: "#D9D9D9", d: "M0 0H16V16H0z" } }] }, { tag: "g", attrs: { fill: "currentColor", mask: "url(#mask0_102_585)" }, children: [{ tag: "path", attrs: { d: "M8.00011 11.7216C7.64665 11.7216 7.36011 11.435 7.36011 11.0816V2.76158C7.36011 2.40812 7.64665 2.12158 8.00011 2.12158 8.35357 2.12158 8.64011 2.40812 8.64011 2.76158V11.0816C8.64011 11.435 8.35357 11.7216 8.00011 11.7216zM8.00008 13.8783C8.46032 13.8783 8.83342 13.5052 8.83342 13.045 8.83342 12.5847 8.46032 12.2116 8.00008 12.2116 7.53985 12.2116 7.16675 12.5847 7.16675 13.045 7.16675 13.5052 7.53985 13.8783 8.00008 13.8783zM9.43991 3.3083V4.6566C11.1747 4.93531 12.8439 5.72115 14.2082 7.01405 14.4754 7.26731 14.8974 7.25598 15.1506 6.98873 15.4039 6.72149 15.3926 6.29953 15.1253 6.04626 13.5035 4.50928 11.5069 3.59665 9.43991 3.3083zM2.3565 6.52137C3.60481 5.51948 5.05771 4.89789 6.55991 4.65657V3.30842C4.7603 3.55961 3.014 4.284 1.52191 5.48155 1.3003 5.65943 1.08439 5.84768.874838 6.04627.607592 6.29953.59626 6.72149.849526 6.98873 1.10279 7.25598 1.52475 7.26731 1.79199 7.01405 1.97498 6.84063 2.16333 6.67643 2.3565 6.52137zM2.86201 8.33667C3.91262 7.28606 5.2049 6.62442 6.55991 6.35175V7.71826C5.55037 7.96981 4.59408 8.49022 3.80482 9.27947 3.54447 9.53982 3.12236 9.53982 2.86201 9.27947 2.60166 9.01912 2.60166 8.59701 2.86201 8.33667zM9.43991 7.71818V6.35169C10.795 6.62431 12.0875 7.28597 13.1382 8.33667 13.3985 8.59701 13.3985 9.01912 13.1382 9.27947 12.8778 9.53982 12.4557 9.53982 12.1953 9.27947 11.406 8.49013 10.4496 7.9697 9.43991 7.71818zM4.86201 10.5082C5.35689 10.0134 5.93957 9.65979 6.55991 9.44753V10.8951C6.28821 11.0374 6.03315 11.2227 5.80482 11.451 5.54447 11.7114 5.12236 11.7114 4.86201 11.451 4.60166 11.1907 4.60166 10.7686 4.86201 10.5082zM9.43991 10.8949V9.44741C10.0604 9.65966 10.6432 10.0133 11.1382 10.5082 11.3985 10.7686 11.3985 11.1907 11.1382 11.451 10.8778 11.7114 10.4557 11.7114 10.1953 11.451 9.96691 11.2226 9.71174 11.0372 9.43991 10.8949z" } }] }] }, Cs = bt(function(i, e) {
2946
+ return Tt(wt, Object.assign({}, i, {
2947
+ id: "off-line-single",
2948
+ ref: e,
2949
+ icon: Rn
2950
+ }));
2951
+ });
2952
+ Cs.displayName = "OffLineSingle";
2953
+ var yn = { tag: "svg", attrs: { fill: "none", viewBox: "0 0 16 16", width: "1em", height: "1em" }, children: [{ tag: "mask", attrs: { id: "mask0_102_580", style: { maskType: "alpha" }, width: 16, height: 16, x: 0, y: 0, maskUnits: "userSpaceOnUse" }, children: [{ tag: "path", attrs: { fill: "#D9D9D9", d: "M0 0H16V16H0z" } }] }, { tag: "g", attrs: { fill: "currentColor", mask: "url(#mask0_102_580)", fillRule: "evenodd", clipRule: "evenodd" }, children: [{ tag: "path", attrs: { d: "M5.82613 4.56746C5.40036 5.04236 5.18674 5.65314 5.02643 6.21425C4.94606 6.49553 4.68897 6.68945 4.39644 6.68945C4.17409 6.68945 3.56092 6.78651 3.0238 7.12221C2.52284 7.43531 2.10324 7.93892 2.10324 8.81885C2.10324 9.60442 2.39454 10.0131 2.72844 10.2503C3.09823 10.5131 3.60322 10.6206 4.06884 10.6206C4.43069 10.6206 4.72404 10.914 4.72404 11.2758C4.72404 11.6377 4.43069 11.931 4.06884 11.931C3.44246 11.931 2.63705 11.7929 1.96945 11.3185C1.26595 10.8187 0.792847 9.99887 0.792847 8.81885C0.792847 7.40558 1.51984 6.5169 2.32929 6.011C2.8676 5.67455 3.44845 5.50028 3.89776 5.42544C4.07573 4.89085 4.35413 4.2463 4.85044 3.69271C5.51609 2.95026 6.5174 2.43066 8.00003 2.43066C9.27898 2.43066 10.2502 2.7993 10.9548 3.3781C11.5184 3.84106 11.881 4.41324 12.1008 4.9709C12.1429 4.98097 12.1875 4.99222 12.2342 5.00477C12.549 5.08928 12.9754 5.23648 13.408 5.48878C14.2932 6.00515 15.2072 6.97409 15.2072 8.65505C15.2072 9.79541 14.8194 10.6501 14.1525 11.2059C13.5065 11.7442 12.6838 11.931 11.9312 11.931C11.5694 11.931 11.276 11.6377 11.276 11.2758C11.276 10.914 11.5694 10.6206 11.9312 10.6206C12.4891 10.6206 12.9767 10.4799 13.3136 10.1992C13.6294 9.93602 13.8968 9.48028 13.8968 8.65505C13.8968 7.55142 13.3367 6.96426 12.7477 6.62068C12.4431 6.443 12.1325 6.33426 11.8944 6.27034C11.7766 6.23871 11.6799 6.21893 11.6151 6.20737C11.5828 6.2016 11.5587 6.19792 11.5442 6.19585L11.53 6.19391L11.5302 6.19393L11.5307 6.19398C11.2667 6.16442 11.0466 5.97834 10.9736 5.72285C10.8382 5.24885 10.5726 4.75996 10.123 4.39067C9.68107 4.02762 9.01427 3.74106 8.00003 3.74106C6.86186 3.74106 6.22518 4.12236 5.82613 4.56746ZM11.53 6.19391L11.5294 6.19384L11.5286 6.19374C11.5284 6.19372 11.5288 6.19377 11.53 6.19391Z" } }, { tag: "path", attrs: { d: "M11.0302 9.12626C11.3127 9.35231 11.3585 9.76463 11.1325 10.0472L8.51171 13.3232C8.40173 13.4606 8.24107 13.5481 8.06592 13.5658C7.89077 13.5835 7.71587 13.5299 7.58063 13.4172L5.61504 11.7792C5.33705 11.5476 5.2995 11.1344 5.53115 10.8564C5.7628 10.5785 6.17595 10.5409 6.45393 10.7725L7.90602 11.9826L10.1093 9.22859C10.3353 8.94603 10.7476 8.90021 11.0302 9.12626Z" } }] }] }, Is = bt(function(i, e) {
2954
+ return Tt(wt, Object.assign({}, i, {
2955
+ id: "on-line-single",
2956
+ ref: e,
2957
+ icon: yn
2958
+ }));
2959
+ });
2960
+ Is.displayName = "OnLineSingle";
2961
+ const On = "univer-online-status-icon", wn = "univer-online-status-title", Mn = "univer-online-status", Dn = "univer-online", Nn = "univer-offline", ve = {
2962
+ onlineStatusIcon: On,
2963
+ onlineStatusTitle: wn,
2964
+ onlineStatus: Mn,
2965
+ online: Dn,
2966
+ offline: Nn
2967
+ };
2968
+ function An(i) {
2969
+ switch (i) {
2970
+ case w.OFFLINE:
2971
+ return "collabStatus.offline";
2972
+ case w.CONFLICT:
2973
+ return "collabStatus.conflict";
2974
+ case w.FETCH_MISS:
2975
+ return "collabStatus.fetchMiss";
2976
+ case w.NOT_COLLAB:
2977
+ return "collabStatus.notCollab";
2978
+ case w.PENDING:
2979
+ case w.AWAITING:
2980
+ case w.AWAITING_WITH_PENDING:
2981
+ return "collabStatus.syncing";
2982
+ case w.SYNCED:
2983
+ return "collabStatus.synced";
2984
+ }
2985
+ }
2986
+ function Un(i) {
2987
+ const e = js(i.status$, w.NOT_COLLAB), t = Ti(H), s = e !== w.OFFLINE, n = t.t(An(e)), r = Oi(ve.onlineStatus, {
2988
+ [ve.online]: s,
2989
+ [ve.offline]: !s
2990
+ }), o = s ? /* @__PURE__ */ oe.createElement(Is, null) : /* @__PURE__ */ oe.createElement(Cs, null);
2991
+ return /* @__PURE__ */ oe.createElement("div", { className: r }, /* @__PURE__ */ oe.createElement("div", { className: ve.onlineStatusIcon }, o), /* @__PURE__ */ oe.createElement("div", { className: ve.onlineStatusTitle }, n));
2992
+ }
2993
+ var kn = (i, e, t, s) => {
2994
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
2995
+ (o = i[r]) && (n = o(n) || n);
2996
+ return n;
2997
+ }, Ue = (i, e) => (t, s) => e(t, s, i);
2998
+ let xe = class extends X {
2999
+ constructor(e, t, s, n) {
3000
+ super();
3001
+ l(this, "_status$", new U(w.NOT_COLLAB));
3002
+ this._uiController = e, this._univerInstanceService = t, this._injector = s, this._collaborationController = n, this._mountOnlineHint(), this._initStatusListener();
3003
+ }
3004
+ _mountOnlineHint() {
3005
+ this.disposeWithMe(
3006
+ this._uiController.registerComponent(
3007
+ Bs.HEADER_MENU,
3008
+ () => Ri(Ln({ status$: this._status$.asObservable() }), this._injector)
3009
+ )
3010
+ );
3011
+ }
3012
+ _initStatusListener() {
3013
+ this.disposeWithMe(
3014
+ T(
3015
+ this._univerInstanceService.focused$.pipe(
3016
+ ot(() => {
3017
+ const e = this._univerInstanceService.getFocusedUnit();
3018
+ return e ? this._collaborationController.getCollabEntity$(e.getUnitId()) : Te(null);
3019
+ }),
3020
+ ot((e) => e ? e.status$ : Te(w.NOT_COLLAB))
3021
+ ).subscribe((e) => {
3022
+ this._status$.next(e);
3023
+ })
3024
+ )
3025
+ );
3026
+ }
3027
+ };
3028
+ xe = kn([
3029
+ ee(te.Starting, xe),
3030
+ Ue(0, Vs),
3031
+ Ue(1, k),
3032
+ Ue(2, _(I)),
3033
+ Ue(3, _(Ie))
3034
+ ], xe);
3035
+ function Ln(i) {
3036
+ const { status$: e } = i;
3037
+ return function() {
3038
+ return /* @__PURE__ */ oe.createElement(Un, { status$: e });
3039
+ };
3040
+ }
3041
+ const Es = pt("uni.network.url-service");
3042
+ var $n = (i, e, t, s) => {
3043
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
3044
+ (o = i[r]) && (n = o(n) || n);
3045
+ return n;
3046
+ }, re = (i, e) => (t, s) => e(t, s, i);
3047
+ let Ee = class extends L {
3048
+ constructor(i, e, t, s, n, r) {
3049
+ super(), this._urlService = i, this._logService = e, this._commandService = t, this._localCacheService = s, this._snapshotService = n, r ? r == null || r.whenReady().then(() => this._init()) : (this._logService.debug(
3050
+ "[DataLoaderController]",
3051
+ "No remote instance service injected. May not syncing edits to the web worker."
3052
+ ), this._init());
3053
+ }
3054
+ async _init() {
3055
+ const i = this._urlService.getParam("unit"), e = this._urlService.getParam("type");
3056
+ if (!i || !e) {
3057
+ this._logService.debug(
3058
+ "[DataLoaderController]",
3059
+ "No unitID or type in URL. Will not load files from remote address."
3060
+ );
3061
+ return;
3062
+ }
3063
+ switch (Number(e)) {
3064
+ case x.UNIVER_SHEET: {
3065
+ const t = await this._loadSheet(i);
3066
+ this._setupSubUnitSync(t);
3067
+ break;
3068
+ }
3069
+ case x.UNIVER_DOC: {
3070
+ await this._loadDoc(i);
3071
+ break;
3072
+ }
3073
+ default: {
3074
+ this._logService.error(
3075
+ "[DataLoaderController]",
3076
+ "Unknown type in URL. Will not load files from remote address."
3077
+ );
3078
+ break;
3079
+ }
3080
+ }
3081
+ }
3082
+ async _setupSubUnitSync(i) {
3083
+ await this._updateSubUnitFromURLParams(i), i.activeSheet$.pipe(R(this.dispose$)).subscribe((e) => {
3084
+ e && this._updateURLWithCurrentState(e);
3085
+ }), this._urlService.urlChange$.pipe(R(this.dispose$)).subscribe(() => this._updateSubUnitFromURLParams(i));
3086
+ }
3087
+ _updateURLWithCurrentState(i, e = !1) {
3088
+ const t = this._urlService.getParam("subunit");
3089
+ i.getSheetId() !== t && this._urlService.setParam("subunit", i.getSheetId(), e);
3090
+ }
3091
+ async _updateSubUnitFromURLParams(i) {
3092
+ const e = this._urlService.getParam("subunit");
3093
+ if (!e || !i.getSheetBySheetId(e)) {
3094
+ this._updateURLWithCurrentState(i.getActiveSheet(), !0);
3095
+ return;
3096
+ }
3097
+ i.getActiveSheet().getSheetId() !== e && await this._commandService.executeCommand(fi.id, {
3098
+ unitId: i.getUnitId(),
3099
+ subUnitId: e
3100
+ });
3101
+ }
3102
+ async _loadSheet(i) {
3103
+ let e = 0;
3104
+ const t = await this._localCacheService.loadOfflineData(i);
3105
+ return t && (t.awaitingChangeset || t.mutations.length !== 0) && (e = t.rev), e === 0 && this._logService.debug("[DataLoaderController]", "fetching the latest document from the server."), this._snapshotService.loadSheet(i, e);
3106
+ }
3107
+ async _loadDoc(i) {
3108
+ let e = 0;
3109
+ const t = await this._localCacheService.loadOfflineData(i);
3110
+ return t && (t.awaitingChangeset || t.mutations.length !== 0) && (e = t.rev), e === 0 && this._logService.debug("[DataLoaderController]", "fetching the latest document from the server."), this._snapshotService.loadDoc(i, e);
3111
+ }
3112
+ };
3113
+ Ee = $n([
3114
+ ee(te.Starting, Ee),
3115
+ re(0, Es),
3116
+ re(1, D),
3117
+ re(2, O),
3118
+ re(3, _(y)),
3119
+ re(4, _(Ws)),
3120
+ re(5, Ye(wi))
3121
+ ], Ee);
3122
+ var Pn = (i, e, t, s) => {
3123
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
3124
+ (o = i[r]) && (n = o(n) || n);
3125
+ return n;
3126
+ }, Kt = (i, e) => (t, s) => e(t, s, i);
3127
+ const xn = "DEFAULT_FILE_NAME", Hn = "Univer";
3128
+ let He = class extends X {
3129
+ constructor(i, e) {
3130
+ super(), this._univerInstanceService = i, this._configService = e, this._init();
3131
+ }
3132
+ _init() {
3133
+ this.disposeWithMe(
3134
+ T(
3135
+ this._univerInstanceService.focused$.subscribe(() => {
3136
+ var t;
3137
+ const i = this._univerInstanceService.getFocusedUnit();
3138
+ let e = (t = this._configService.getConfig(xn)) != null ? t : Hn;
3139
+ i instanceof ks && (e = i.name), document.title = e;
3140
+ })
3141
+ )
3142
+ );
3143
+ }
3144
+ };
3145
+ He = Pn([
3146
+ ee(te.Ready, He),
3147
+ Kt(0, k),
3148
+ Kt(1, z)
3149
+ ], He);
3150
+ const jn = {
3151
+ collabStatus: {
3152
+ fetchMiss: "正在同步服务端数据...",
3153
+ conflict: "编辑冲突",
3154
+ notCollab: "本地文件",
3155
+ synced: "已保存",
3156
+ syncing: "保存中...",
3157
+ offline: "编辑将在本地保存"
3158
+ },
3159
+ session: {
3160
+ "connection-failed": "连接失败,请检查你的网络",
3161
+ "will-retry": "连接失败,将在一会儿之后重试",
3162
+ "room-full": "协同房间已满,你的编辑将在本地保存",
3163
+ "collaboration-timeout": "服务器未响应你的协同请求,你的编辑将在本地保存"
3164
+ },
3165
+ conflict: {
3166
+ title: "协同冲突",
3167
+ content: "你的本地文档和服务器的文档存在冲突。请在别处保存你的本地编辑,本地编辑将在刷新页面后丢弃。"
3168
+ },
3169
+ collaboration: {
3170
+ "single-unit": {
3171
+ warning: "你在另一个标签页打开了同一个文件。为了避免数据丢失,这个标签页的编辑行为将会被限制。"
3172
+ }
3173
+ },
3174
+ auth: {
3175
+ needGotoLoginAlert: "你的登录已过期,点击确认重新登陆,点击取消去保存你的本地编辑。"
3176
+ }
3177
+ }, Bn = jn;
3178
+ var Vn = (i, e, t, s) => {
3179
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
3180
+ (o = i[r]) && (n = o(n) || n);
3181
+ return n;
3182
+ }, Yt = (i, e) => (t, s) => e(t, s, i);
3183
+ const Fn = "SNAPSHOT_SERVER_URL_KEY", Wn = "/universer-api/snapshot";
3184
+ let mt = class {
3185
+ constructor(i, e) {
3186
+ this._configService = i, this._httpService = e;
3187
+ }
3188
+ async getUnitOnRev(i, e) {
3189
+ var u;
3190
+ const { unitID: t, type: s, revision: n = 0 } = e, o = `${this._getAPIPrefixPath()}/${s}/unit/${t}/rev/${n === 1 ? 0 : n}`, c = (await this._httpService.get(o)).body, h = (u = c.snapshot) == null ? void 0 : u.workbook;
3191
+ if (h) {
3192
+ const d = h == null ? void 0 : h.originalMeta, f = Mt.encode(Dt(d));
3193
+ h.originalMeta = f, Object.entries(h.sheets).forEach(([, v]) => {
3194
+ const p = v.originalMeta, E = Mt.encode(Dt(p));
3195
+ v.originalMeta = E;
3196
+ });
3197
+ }
3198
+ return c;
3199
+ }
3200
+ async getSheetBlock(i, e) {
3201
+ const { unitID: t, type: s, blockID: n } = e, o = `${this._getAPIPrefixPath()}/${s}/unit/${t}/block/${n}`;
3202
+ return (await this._httpService.get(o)).body;
3203
+ }
3204
+ async fetchMissingChangesets(i, e) {
3205
+ const { unitID: t, type: s, from: n, to: r } = e, a = `${this._getAPIPrefixPath()}/${s}/unit/${t}/fetchmissing?from=${n}&to=${r}`;
3206
+ return (await this._httpService.get(a)).body;
3207
+ }
3208
+ _getAPIPrefixPath() {
3209
+ var i;
3210
+ return (i = this._configService.getConfig(Fn)) != null ? i : Wn;
3211
+ }
3212
+ // #region - server only methods
3213
+ async getResourcesRequest(i, e) {
3214
+ const t = `/universer-api/snapshot/${e.type}/unit/${e.unitID}/resources`;
3215
+ return (await this._httpService.get(t, {
3216
+ params: { resourceId: JSON.stringify(e.resourceIDs) }
3217
+ })).body;
3218
+ }
3219
+ saveSnapshot() {
3220
+ throw new Error("This method should not be called on the client side!");
3221
+ }
3222
+ saveSheetBlock() {
3223
+ throw new Error("This method should not be called on the client side!");
3224
+ }
3225
+ saveChangeset() {
3226
+ throw new Error("This method should not be called on the client side!");
3227
+ }
3228
+ // #endregion - server only methods
3229
+ };
3230
+ mt = Vn([
3231
+ Yt(0, z),
3232
+ Yt(1, _(Re))
3233
+ ], mt);
3234
+ var Gn = (i, e, t, s) => {
3235
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
3236
+ (o = i[r]) && (n = o(n) || n);
3237
+ return n;
3238
+ }, pe = (i, e) => (t, s) => e(t, s, i);
3239
+ let ft = class extends Ls {
3240
+ constructor(i, e, t, s, n) {
3241
+ super(i, e, t), this._transformService = s, this._logService = n;
3242
+ }
3243
+ transformUndoRedo(i, e) {
3244
+ const t = this._getUndoStack(i);
3245
+ if (t)
3246
+ try {
3247
+ const n = this._transformStack(t, e);
3248
+ this._substituteUndoStack(i, n);
3249
+ } catch (n) {
3250
+ this._logService.error("[CollaborationUndoRedoService]", n), this._clearUndo(i);
3251
+ }
3252
+ const s = this._getRedoStack(i);
3253
+ if (s)
3254
+ try {
3255
+ const n = this._transformStack(s, e);
3256
+ this._substituteRedoStack(i, n);
3257
+ } catch (n) {
3258
+ this._logService.error(n), this._clearRedo(i);
3259
+ }
3260
+ }
3261
+ _clearUndo(i) {
3262
+ const e = this._getUndoStack(i);
3263
+ e && (e.length = 0, this._updateStatus());
3264
+ }
3265
+ _clearRedo(i) {
3266
+ const e = this._getRedoStack(i);
3267
+ e && (e.length = 0, this._updateStatus());
3268
+ }
3269
+ _substituteUndoStack(i, e) {
3270
+ this._undoStacks.set(i, e), this._updateStatus();
3271
+ }
3272
+ _substituteRedoStack(i, e) {
3273
+ this._redoStacks.set(i, e), this._updateStatus();
3274
+ }
3275
+ _transformStack(i, e) {
3276
+ const t = [];
3277
+ let s = e, n = e;
3278
+ for (let r = i.length - 1; r >= 0; r--) {
3279
+ const { unitID: o, undoMutations: a, redoMutations: c } = i[r], h = this._transformService.transformMutationsWithChangeset(s, a), u = this._transformService.transformMutationsWithChangeset(n, c);
3280
+ if (At(h) || At(u)) {
3281
+ this._logService.error("[CollaborationUndoRedoService]", "transformStack failed!", h, u);
3282
+ break;
3283
+ }
3284
+ s = h.c1Prime, n = u.c1Prime, t.push({
3285
+ unitID: o,
3286
+ undoMutations: h.m2Prime,
3287
+ redoMutations: u.m2Prime
3288
+ });
3289
+ }
3290
+ return t.reverse();
3291
+ }
3292
+ };
3293
+ ft = Gn([
3294
+ pe(0, k),
3295
+ pe(1, O),
3296
+ pe(2, $s),
3297
+ pe(3, W),
3298
+ pe(4, D)
3299
+ ], ft);
3300
+ class Kn extends L {
3301
+ constructor() {
3302
+ super();
3303
+ l(this, "urlChange$");
3304
+ this.urlChange$ = ss(window, "popstate").pipe(
3305
+ R(this.dispose$),
3306
+ Ks(1),
3307
+ Ys(void 0)
3308
+ );
3309
+ }
3310
+ setParam(t, s, n = !1) {
3311
+ const r = new URL(window.location.href);
3312
+ r.searchParams.set(t, s), n ? window.history.replaceState("", "", r.toString()) : window.history.pushState("", "", r.toString());
3313
+ }
3314
+ removeParam(t, s = !1) {
3315
+ const n = new URL(window.location.href);
3316
+ n.searchParams.delete(t), s ? window.history.replaceState("", "", n.toString()) : window.history.pushState("", "", n.toString());
3317
+ }
3318
+ getParam(t) {
3319
+ var n;
3320
+ return (n = new URL(window.location.href).searchParams.get(t)) != null ? n : void 0;
3321
+ }
3322
+ }
3323
+ const st = "collab-text-anchor-", Yn = "collab-text-range-", ke = 6, Xn = 1.5, it = 4, zn = 1.5, Jn = "rgba(255, 255, 255, 0.01)";
3324
+ class qn {
3325
+ constructor(e, t, s, n) {
3326
+ l(this, "_shapes", []);
3327
+ l(this, "_anchor", null);
3328
+ l(this, "_textBubble", null);
3329
+ l(this, "_anchorDot", null);
3330
+ l(this, "_hideTimer", null);
3331
+ l(this, "_eventUnsubscribe", null);
3332
+ this._cursor = e, this._scene = t, this._docSkeleton = s, this._document = n, this._render();
3333
+ }
3334
+ // eslint-disable-next-line accessor-pairs
3335
+ set _hover(e) {
3336
+ e ? (this._anchorDot && this._anchorDot.hide(), this._textBubble && this._textBubble.show()) : (this._anchorDot && this._anchorDot.show(), this._textBubble && this._textBubble.hide());
3337
+ }
3338
+ dispose() {
3339
+ for (const e of this._shapes)
3340
+ e.dispose();
3341
+ this._textBubble && this._textBubble.dispose(), this._anchorDot && this._anchorDot.dispose(), this._anchor && this._anchor.dispose(), this._eventUnsubscribe && this._eventUnsubscribe();
3342
+ }
3343
+ _render() {
3344
+ const { _docSkeleton: e, _document: t } = this, { color: s, name: n, ranges: r } = this._cursor, o = t.getOffsetConfig(), { docsLeft: a, docsTop: c } = o, h = new pi(o, e);
3345
+ for (const { startOffset: u, endOffset: d, collapsed: f, isActive: v } of r) {
3346
+ const p = e.findNodePositionByCharIndex(u), E = e.findNodePositionByCharIndex(d);
3347
+ if (v) {
3348
+ const { contentBoxPointGroup: b } = h.getRangePointData(E, E);
3349
+ if (b.length === 0)
3350
+ continue;
3351
+ this._drawAnchor(s, b, a, c, n), this._eventUnsubscribe = this._handleHover();
3352
+ }
3353
+ if (!f) {
3354
+ const { contentBoxPointGroup: b } = h.getRangePointData(p, E);
3355
+ if (b.length === 0)
3356
+ continue;
3357
+ this._drawRange(s, b, a, c);
3358
+ }
3359
+ }
3360
+ }
3361
+ _drawAnchor(e, t, s, n, r) {
3362
+ const o = this._getAnchorBounding(t), { left: a, top: c, height: h } = o, u = this._getScale(), d = zn / u, f = new ct(st + P.generateRandomId(ke), {
3363
+ left: a + s - d,
3364
+ top: c + n,
3365
+ height: h,
3366
+ width: Xn,
3367
+ fill: e || Ne(De.black, 0),
3368
+ strokeWidth: d,
3369
+ stroke: Jn,
3370
+ evented: !0
3371
+ });
3372
+ this._anchor = f, this._scene.addObject(f, Ae);
3373
+ const v = new ct(st + P.generateRandomId(ke), {
3374
+ left: a + s - d,
3375
+ top: c + n - it / 2,
3376
+ height: it,
3377
+ width: it,
3378
+ fill: e || Ne(De.black, 0),
3379
+ strokeWidth: 0,
3380
+ stroke: e || Ne(De.black, 0),
3381
+ evented: !1
3382
+ });
3383
+ this._anchorDot = v, this._scene.addObject(v, Ae);
3384
+ const p = new Je(st + P.generateRandomId(ke), {
3385
+ left: a + s - d,
3386
+ top: c + n - we,
3387
+ text: r,
3388
+ color: e
3389
+ });
3390
+ this._textBubble = p, this._scene.addObject(p, Ae), this._hover = !1;
3391
+ }
3392
+ _handleHover() {
3393
+ const e = this._anchor.onPointerEnterObserver.add(() => {
3394
+ this._hover = !0;
3395
+ }), t = this._anchor.onPointerLeaveObserver.add(() => {
3396
+ this._hideTimer && clearTimeout(this._hideTimer), this._hideTimer = setTimeout(() => {
3397
+ this._hover = !1;
3398
+ }, 2e3);
3399
+ });
3400
+ return () => {
3401
+ var s, n;
3402
+ (s = this._anchor) == null || s.onPointerEnterObserver.remove(e), (n = this._anchor) == null || n.onPointerLeaveObserver.remove(t);
3403
+ };
3404
+ }
3405
+ _drawRange(e, t, s, n) {
3406
+ const o = new Ps(e).setAlpha(0.2).toRgbString(), a = new Ci(Yn + P.generateRandomId(ke), {
3407
+ pointsGroup: t,
3408
+ fill: o || Ne(De.black, 0.2),
3409
+ left: s,
3410
+ top: n,
3411
+ evented: !1,
3412
+ debounceParentDirty: !1
3413
+ });
3414
+ this._shapes.push(a), this._scene.addObject(a, Ae);
3415
+ }
3416
+ _getAnchorBounding(e) {
3417
+ const t = e[0], s = t[0], n = t[2], { x: r, y: o } = s, { x: a, y: c } = n;
3418
+ return {
3419
+ left: r,
3420
+ top: o,
3421
+ width: a - r,
3422
+ height: c - o
3423
+ };
3424
+ }
3425
+ _getScale() {
3426
+ const { scaleX: e, scaleY: t } = this._scene.getAncestorScale();
3427
+ return Math.max(e, t);
3428
+ }
3429
+ }
3430
+ var Zn = (i, e, t, s) => {
3431
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
3432
+ (o = i[r]) && (n = o(n) || n);
3433
+ return n;
3434
+ }, Ce = (i, e) => (t, s) => e(t, s, i);
3435
+ let je = class extends L {
3436
+ constructor(e, t, s, n, r) {
3437
+ super();
3438
+ /** Cursors stored for different Workbooks. */
3439
+ l(this, "_cursors", []);
3440
+ this._collabCursorController = e, this._univerInstanceService = t, this._renderManagerService = s, this._docSkeletonManagerService = n, this._themeService = r, this._init();
3441
+ }
3442
+ _init() {
3443
+ this._docSkeletonManagerService.currentSkeleton$.pipe(
3444
+ It(this.dispose$),
3445
+ rs((e) => {
3446
+ if (e) {
3447
+ const { unitId: t } = e;
3448
+ return ns(
3449
+ this._collabCursorController.getCollabCursors$(t),
3450
+ this._themeService.currentTheme$
3451
+ ).pipe(
3452
+ ce(([s, n]) => ({
3453
+ skeleton: e,
3454
+ cursors: [...s.values()].flatMap((r) => ({ ...r, color: n[r.color] }))
3455
+ }))
3456
+ );
3457
+ }
3458
+ return Te({
3459
+ skeleton: null,
3460
+ cursors: []
3461
+ });
3462
+ })
3463
+ ).subscribe(({ skeleton: e, cursors: t }) => {
3464
+ this._removeCollabCursors(), e && this._updateCollabCursors(e.skeleton, t);
3465
+ });
3466
+ }
3467
+ _updateCollabCursors(e, t) {
3468
+ const s = this._getDocObject();
3469
+ if (s == null)
3470
+ return;
3471
+ const { scene: n, document: r } = s, o = t.map((a) => new qn(a, n, e, r));
3472
+ this._cursors = o;
3473
+ }
3474
+ _removeCollabCursors() {
3475
+ this._cursors.forEach((e) => e.dispose()), this._cursors = [];
3476
+ }
3477
+ _getDocObject() {
3478
+ return Qs(this._univerInstanceService, this._renderManagerService);
3479
+ }
3480
+ };
3481
+ je = Zn([
3482
+ ee(te.Steady, je),
3483
+ Ce(0, _(le)),
3484
+ Ce(1, k),
3485
+ Ce(2, _s),
3486
+ Ce(3, _(ei)),
3487
+ Ce(4, _(Qt))
3488
+ ], je);
3489
+ var Qn = (i, e, t, s) => {
3490
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
3491
+ (o = i[r]) && (n = o(n) || n);
3492
+ return n;
3493
+ }, nt = (i, e) => (t, s) => e(t, s, i);
3494
+ const er = "LOGIN_URL_KEY", tr = "/universer-api/oidc/authpage";
3495
+ let Ge = class {
3496
+ constructor(i, e, t) {
3497
+ this._configService = i, this._httpService = e, this.localeService = t, this.init();
3498
+ }
3499
+ init() {
3500
+ this._httpService.registerHTTPInterceptor({
3501
+ priority: 1,
3502
+ interceptor: (i, e) => e(i).pipe(
3503
+ Xs(async (t) => {
3504
+ if (t.status === 401 && window.confirm(
3505
+ this.localeService.t("auth.needGotoLoginAlert")
3506
+ )) {
3507
+ const n = window.encodeURIComponent(window.location.href);
3508
+ window.location.href = `${this._getLoginPath()}?url=${n}`;
3509
+ }
3510
+ return t;
3511
+ })
3512
+ )
3513
+ });
3514
+ }
3515
+ _getLoginPath() {
3516
+ var i;
3517
+ return (i = this._configService.getConfig(er)) != null ? i : tr;
3518
+ }
3519
+ };
3520
+ Ge = Qn([
3521
+ nt(0, z),
3522
+ nt(1, _(Re)),
3523
+ nt(2, _(H))
3524
+ ], Ge);
3525
+ var sr = (i, e, t, s) => {
3526
+ for (var n = e, r = i.length - 1, o; r >= 0; r--)
3527
+ (o = i[r]) && (n = o(n) || n);
3528
+ return n;
3529
+ }, Xt = (i, e) => (t, s) => e(t, s, i);
3530
+ const ir = "collaboration-client";
3531
+ var rt;
3532
+ let zt = (rt = class extends xs {
3533
+ constructor(i, e, t) {
3534
+ super(), this._config = i, this._injector = e, this._localeService = t, this._localeService.load({ zhCN: Bn });
3535
+ }
3536
+ onStarting(i) {
3537
+ var s, n, r, o;
3538
+ i.replace([J, { useClass: ft }]);
3539
+ const e = [
3540
+ // services
3541
+ [ye],
3542
+ [Ot],
3543
+ [Re],
3544
+ [Es, { useClass: Kn }],
3545
+ [Z],
3546
+ [y],
3547
+ [cs],
3548
+ [Fe],
3549
+ [Ve],
3550
+ [Be],
3551
+ [yt],
3552
+ [Ge],
3553
+ // abstract services
3554
+ [us, { useClass: (n = (s = this._config) == null ? void 0 : s.socketService) != null ? n : ht }],
3555
+ [ti, { useClass: si }],
3556
+ [qt, { useClass: mt }],
3557
+ // controllers
3558
+ [Ie],
3559
+ [Ee],
3560
+ [xe],
3561
+ [He],
3562
+ [le]
3563
+ ];
3564
+ (r = this._config) != null && r.enableSingleActiveInstanceLock && e.push([Xe, { useClass: zi }]), ((o = this._config) == null ? void 0 : o.collaborationUniverTypes) == null || this._config.collaborationUniverTypes.includes(M.UNIVER_SHEET) ? e.push([Pe]) : this._config.collaborationUniverTypes.includes(M.UNIVER_DOC) && e.push([je]), e.forEach((a) => i.add(a)), i.get(Re).registerHTTPInterceptor({
3565
+ priority: 20,
3566
+ interceptor: i.invoke(ii, { maxParallel: 6 })
3567
+ }), this._initModules();
3568
+ }
3569
+ _initModules() {
3570
+ var i, e;
3571
+ this._injector.get(Ee), (i = this._config) != null && i.enableOfflineEditing || this._injector.get(y).disableLocalCache(), (e = this._config) != null && e.enableAuthServer && this._injector.get(Ge);
3572
+ }
3573
+ }, l(rt, "pluginName", ir), rt);
3574
+ zt = sr([
3575
+ Xt(1, _(I)),
3576
+ Xt(2, _(H))
3577
+ ], zt);
3578
+ const nr = {
3579
+ collabStatus: {
3580
+ fetchMiss: "Syncing server data...",
3581
+ conflict: "Edit conflicts",
3582
+ notCollab: "Local file",
3583
+ synced: "Synced",
3584
+ syncing: "Syncing...",
3585
+ offline: "Offline, edits would be save on local"
3586
+ },
3587
+ session: {
3588
+ "connection-failed": "Connection failed, please check your network.",
3589
+ "will-retry": "Connection failed, we retry in a while.",
3590
+ "room-full": "Collaboration room is full. You edits would be saved locally.",
3591
+ "collaboration-timeout": "The server is not responding to your collaboration request. Your edits would be saved locally."
3592
+ },
3593
+ conflict: {
3594
+ title: "Collaboration Conflict",
3595
+ content: "There is a conflict between your local copy and the copy on the server. Please save your local edits, because they will be lost when you reload the page."
3596
+ },
3597
+ collaboration: {
3598
+ "single-unit": {
3599
+ warning: "You opened the same file in another tab. In case of data missing, you cannot edit on this tab."
3600
+ }
3601
+ },
3602
+ auth: {
3603
+ needGotoLoginAlert: "Your login has expired, click OK to re-login, click Cancel to save your local edits."
3604
+ }
3605
+ }, Tr = nr;
3606
+ export {
3607
+ Li as COLLAB_SUBMIT_CHANGESET_URL_KEY,
3608
+ xi as COLLAB_WEB_SOCKET_URL_KEY,
3609
+ zt as CollaborationClientPlugin,
3610
+ Ie as CollaborationController,
3611
+ lt as CollaborationSession,
3612
+ ye as CollaborationSessionService,
3613
+ ht as CollaborationSocketService,
3614
+ ji as HEARTBEAT_INTERVAL_KEY,
3615
+ gs as HEARTBEAT_TIMEOUT_KEY,
3616
+ us as ICollaborationSocketService,
3617
+ Yi as LOCAL_CACHE_INTERVAL_KEY,
3618
+ er as LOGIN_URL_KEY,
3619
+ nn as SEND_CHANGESET_TIMEOUT_KEY,
3620
+ Fn as SNAPSHOT_SERVER_URL_KEY,
3621
+ he as SessionStatus,
3622
+ Ai as deserializeToCombResponse,
3623
+ Tr as enUS,
3624
+ Ui as serializeCombRequest,
3625
+ Bn as zhCN
3626
+ };