@daasboard/doc 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,515 @@
1
+ import { Cursor, EphemeralStore, LoroText } from "loro-crdt";
2
+ export const MAX_PRESENCE_BYTES = 16 * 1024;
3
+ export const MAX_PRESENCE_SELECTION = 128;
4
+ export const MAX_PRESENCE_DRAG_OBJECTS = 32;
5
+ export const PRESENCE_TIMEOUT_MS = 30_000;
6
+ const MAX_PEERS = 256;
7
+ const CURSOR_INTERVAL_MS = 40;
8
+ const DRAG_INTERVAL_MS = 1000 / 60;
9
+ const FRAMES_PER_SECOND = 90;
10
+ const FRAME_BURST = 16;
11
+ const BYTES_PER_SECOND = 224 * 1024;
12
+ const BYTE_BURST = 16 * 1024;
13
+ const DECODE_TIMEOUT_MS = 2 ** 31 - 1;
14
+ const KEYS = ["user", "cursor", "selection", "drag", "caret"];
15
+ const DEFAULT_USER = { name: "Guest", color: "#3978d4" };
16
+ const EMPTY_SELECTION = { ids: [], truncated: false };
17
+ const record = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && !(v instanceof Uint8Array);
18
+ const finite = (v) => typeof v === "number" && Number.isFinite(v) && Math.abs(v) <= 1e9;
19
+ const id = (v) => typeof v === "string" && v.length > 0 && v.length <= 64 && /^[\x21-\x7e]+$/.test(v);
20
+ function user(v) {
21
+ if (!record(v) || typeof v.name !== "string" || typeof v.color !== "string" || !/^#[0-9a-fA-F]{6}$/.test(v.color))
22
+ return null;
23
+ return { name: Array.from(v.name.replace(/[\u0000-\u001f\u007f]/g, "")).slice(0, 80).join(""), color: v.color };
24
+ }
25
+ function point(v) { return record(v) && finite(v.x) && finite(v.y) ? { x: v.x, y: v.y } : null; }
26
+ function drag(v) {
27
+ if (!record(v) || !Array.isArray(v.objects) || v.objects.length > MAX_PRESENCE_DRAG_OBJECTS)
28
+ return null;
29
+ const objects = [];
30
+ for (const o of v.objects) {
31
+ if (!record(o) || !id(o.id) || !finite(o.x) || !finite(o.y) || !finite(o.w) || !finite(o.h) || o.w < 0 || o.h < 0 || !finite(o.rot))
32
+ return null;
33
+ objects.push({ id: o.id, x: o.x, y: o.y, w: o.w, h: o.h, rot: o.rot });
34
+ }
35
+ return { objects };
36
+ }
37
+ function selection(v) {
38
+ if (!record(v) || !Array.isArray(v.ids) || v.ids.length > MAX_PRESENCE_SELECTION || !v.ids.every(id))
39
+ return null;
40
+ return { ids: [...new Set(v.ids)], truncated: v.truncated === true };
41
+ }
42
+ function caret(v) {
43
+ if (!record(v) || !id(v.objectId) || !(v.anchor instanceof Uint8Array) || !(v.head instanceof Uint8Array) || v.anchor.length > 256 || v.head.length > 256)
44
+ return null;
45
+ return { objectId: v.objectId, anchor: v.anchor, head: v.head };
46
+ }
47
+ function normalize(key, value) {
48
+ if (value === null)
49
+ return null;
50
+ const result = key === "user" ? user(value) : key === "cursor" ? point(value) : key === "selection" ? selection(value) : key === "drag" ? drag(value) : caret(value);
51
+ return result === null ? undefined : result;
52
+ }
53
+ function sameValue(a, b) {
54
+ if (a === b)
55
+ return true;
56
+ if (a instanceof Uint8Array && b instanceof Uint8Array)
57
+ return a.length === b.length && a.every((v, i) => v === b[i]);
58
+ if (Array.isArray(a) && Array.isArray(b))
59
+ return a.length === b.length && a.every((v, i) => sameValue(v, b[i]));
60
+ if (record(a) && record(b)) {
61
+ const keys = Object.keys(a);
62
+ return keys.length === Object.keys(b).length && keys.every((key) => sameValue(a[key], b[key]));
63
+ }
64
+ return false;
65
+ }
66
+ function release(store) {
67
+ store.destroy();
68
+ queueMicrotask(() => store.inner.free());
69
+ }
70
+ export class RoomPresence {
71
+ page;
72
+ send;
73
+ local;
74
+ state;
75
+ remote = new Map();
76
+ listeners = new Set();
77
+ changedIds = new Set();
78
+ peerViews = [];
79
+ membershipChanged = false;
80
+ notificationFrame;
81
+ notificationIsRaf = false;
82
+ documentVersion = 0;
83
+ unsubscribeDocument;
84
+ dirty = new Set();
85
+ timeout;
86
+ heartbeatMs;
87
+ heartbeat;
88
+ flushTimer;
89
+ cursorTimer;
90
+ dragTimer;
91
+ discoveryTimer;
92
+ lastDrag = -Infinity;
93
+ fullAnnouncement = false;
94
+ dragClearRepeats = 0;
95
+ frameTokens = FRAME_BURST;
96
+ byteTokens = BYTE_BURST;
97
+ budgetAt = Date.now();
98
+ lastCursor = -Infinity;
99
+ lastDiscovery = -Infinity;
100
+ connected = false;
101
+ active = true;
102
+ enabled;
103
+ disposed = false;
104
+ constructor(page, send, options) {
105
+ this.page = page;
106
+ this.send = send;
107
+ this.timeout = Math.max(50, Math.min(options?.timeoutMs ?? PRESENCE_TIMEOUT_MS, PRESENCE_TIMEOUT_MS));
108
+ this.heartbeatMs = Math.max(20, Math.min(options?.heartbeatMs ?? 10_000, this.timeout / 3));
109
+ this.local = new EphemeralStore(this.timeout);
110
+ this.state = { user: (user(options?.user) ?? DEFAULT_USER), cursor: null, selection: { ids: [], truncated: false }, drag: null, caret: null };
111
+ this.enabled = options !== undefined;
112
+ this.unsubscribeDocument = page.subscribe(() => { this.documentVersion++; });
113
+ }
114
+ subscribe(listener) {
115
+ this.listeners.add(listener);
116
+ return () => { this.listeners.delete(listener); };
117
+ }
118
+ get size() { return this.remote.size; }
119
+ changed(connectionId) {
120
+ if (!this.changedIds.has("0")) {
121
+ if (this.changedIds.size >= MAX_PEERS && !this.changedIds.has(connectionId)) {
122
+ this.changedIds.clear();
123
+ this.changedIds.add("0");
124
+ }
125
+ else
126
+ this.changedIds.add(connectionId);
127
+ }
128
+ if (this.notificationFrame !== undefined || this.disposed)
129
+ return;
130
+ const notify = () => {
131
+ this.notificationFrame = undefined;
132
+ const changed = new Set(this.changedIds);
133
+ this.changedIds.clear();
134
+ for (const listener of this.listeners)
135
+ listener(changed);
136
+ };
137
+ this.notificationIsRaf = typeof requestAnimationFrame === "function";
138
+ this.notificationFrame = this.notificationIsRaf ? requestAnimationFrame(notify) : setTimeout(notify, 16);
139
+ }
140
+ setConnected(connected) {
141
+ if (this.disposed)
142
+ return;
143
+ this.connected = connected;
144
+ this.stopSending();
145
+ if (!connected)
146
+ this.clearPeers();
147
+ else
148
+ this.startSending();
149
+ }
150
+ setActive(active) {
151
+ if (this.disposed || active === this.active)
152
+ return;
153
+ this.active = active;
154
+ this.stopSending();
155
+ if (active)
156
+ this.startSending();
157
+ }
158
+ setUser(value) { this.set("user", (user(value) ?? DEFAULT_USER)); }
159
+ setCursor(value) {
160
+ this.enable();
161
+ this.state.cursor = point(value);
162
+ if (this.state.drag !== null)
163
+ return;
164
+ const delay = Math.max(0, CURSOR_INTERVAL_MS - (Date.now() - this.lastCursor));
165
+ if (this.cursorTimer !== undefined)
166
+ return;
167
+ if (!delay)
168
+ this.publishCursor();
169
+ else
170
+ this.cursorTimer = setTimeout(() => { this.cursorTimer = undefined; this.publishCursor(); }, delay);
171
+ }
172
+ publishCursor() {
173
+ if (this.state.drag !== null)
174
+ return;
175
+ this.lastCursor = Date.now();
176
+ this.publish("cursor");
177
+ }
178
+ setSelection(ids) {
179
+ const selected = [];
180
+ let truncated = false;
181
+ for (const value of ids) {
182
+ if (selected.length === MAX_PRESENCE_SELECTION) {
183
+ truncated = true;
184
+ break;
185
+ }
186
+ if (id(value))
187
+ selected.push(value);
188
+ }
189
+ this.set("selection", { ids: selected, truncated });
190
+ }
191
+ setDrag(value) {
192
+ this.enable();
193
+ const wasDragging = this.state.drag !== null;
194
+ this.state.drag = (value ? drag({ objects: value.objects.slice(0, MAX_PRESENCE_DRAG_OBJECTS) }) : null);
195
+ if (this.state.drag !== null) {
196
+ this.dragClearRepeats = 0;
197
+ clearTimeout(this.cursorTimer);
198
+ this.cursorTimer = undefined;
199
+ this.dirty.delete("cursor");
200
+ }
201
+ else if (wasDragging) {
202
+ this.dragClearRepeats = 2;
203
+ }
204
+ if (this.dragTimer !== undefined)
205
+ return;
206
+ const delay = Number.isFinite(this.lastDrag) ? Math.max(0, Math.ceil(DRAG_INTERVAL_MS - (Date.now() - this.lastDrag))) : 16;
207
+ this.dragTimer = setTimeout(() => {
208
+ this.dragTimer = undefined;
209
+ this.lastDrag = Date.now();
210
+ this.publish("drag");
211
+ }, delay);
212
+ }
213
+ setCaret(value) {
214
+ let encoded = null;
215
+ if (value && id(value.objectId)) {
216
+ const text = this.text(value.objectId);
217
+ if (text) {
218
+ const length = text.length;
219
+ const a = Number.isSafeInteger(value.anchor) && value.anchor >= 0 && value.anchor <= length ? text.getCursor(value.anchor, 0) : undefined;
220
+ const h = Number.isSafeInteger(value.head) && value.head >= 0 && value.head <= length ? text.getCursor(value.head, 0) : undefined;
221
+ try {
222
+ if (a && h)
223
+ encoded = { objectId: value.objectId, anchor: a.encode(), head: h.encode() };
224
+ }
225
+ finally {
226
+ a?.free();
227
+ h?.free();
228
+ }
229
+ }
230
+ }
231
+ this.set("caret", encoded);
232
+ }
233
+ text(objectId) {
234
+ if (!this.page.get(objectId))
235
+ return null;
236
+ const node = this.page.tree.getNodeByID(objectId);
237
+ if (!node || node.isDeleted())
238
+ return null;
239
+ const text = node.data.get("text");
240
+ return text instanceof LoroText ? text : null;
241
+ }
242
+ caretObjectId(connectionId) {
243
+ return this.remote.get(connectionId)?.values.caret?.objectId ?? null;
244
+ }
245
+ resolveCaret(connectionId) {
246
+ const peer = this.remote.get(connectionId);
247
+ if (!peer)
248
+ return null;
249
+ if (peer.caretVersion === this.documentVersion)
250
+ return peer.resolvedCaret;
251
+ peer.caretVersion = this.documentVersion;
252
+ peer.resolvedCaret = null;
253
+ const encoded = peer.values.caret;
254
+ if (!encoded)
255
+ return null;
256
+ const text = this.text(encoded.objectId);
257
+ if (!text)
258
+ return null;
259
+ let anchor, head;
260
+ try {
261
+ anchor = Cursor.decode(encoded.anchor);
262
+ head = Cursor.decode(encoded.head);
263
+ if (anchor.containerId() !== text.id || head.containerId() !== text.id)
264
+ return null;
265
+ const a = this.page.doc.getCursorPos(anchor), h = this.page.doc.getCursorPos(head);
266
+ try {
267
+ peer.resolvedCaret = a && h ? { objectId: encoded.objectId, anchor: a.offset, head: h.offset } : null;
268
+ }
269
+ finally {
270
+ a?.update?.free();
271
+ h?.update?.free();
272
+ }
273
+ return peer.resolvedCaret;
274
+ }
275
+ catch {
276
+ return null;
277
+ }
278
+ finally {
279
+ anchor?.free();
280
+ head?.free();
281
+ }
282
+ }
283
+ peers() {
284
+ if (this.membershipChanged) {
285
+ this.peerViews = Array.from(this.remote.values(), (peer) => peer.view);
286
+ this.membershipChanged = false;
287
+ }
288
+ return this.peerViews;
289
+ }
290
+ updateView(connectionId, peer, key, value) {
291
+ const previous = peer.values[key];
292
+ if (sameValue(previous, value))
293
+ return false;
294
+ if (value === undefined)
295
+ delete peer.values[key];
296
+ else
297
+ peer.values[key] = value;
298
+ const empty = key === "user" ? DEFAULT_USER : key === "selection" ? EMPTY_SELECTION : null;
299
+ if (sameValue(previous ?? empty, value ?? empty))
300
+ return false;
301
+ const view = peer.view;
302
+ if (key === "user")
303
+ view.user = value ?? DEFAULT_USER;
304
+ else if (key === "cursor")
305
+ view.cursor = value ?? null;
306
+ else if (key === "selection") {
307
+ const selected = value;
308
+ view.selection = selected?.ids ?? [];
309
+ view.selectionTruncated = selected?.truncated ?? false;
310
+ }
311
+ else if (key === "drag")
312
+ view.drag = value ?? null;
313
+ else
314
+ peer.caretVersion = -1;
315
+ this.changed(connectionId);
316
+ return true;
317
+ }
318
+ receive(connectionId, subject, bytes) {
319
+ if (this.disposed || !/^[1-9][0-9]{0,19}$/.test(connectionId) || bytes.length === 0 || bytes.length > MAX_PRESENCE_BYTES)
320
+ return;
321
+ const decoded = new EphemeralStore(DECODE_TIMEOUT_MS);
322
+ const values = [];
323
+ try {
324
+ decoded.apply(bytes);
325
+ const incoming = decoded.getAllStates();
326
+ for (const key of KEYS) {
327
+ if (!(key in incoming))
328
+ continue;
329
+ const value = normalize(key, incoming[key]);
330
+ if (value === undefined)
331
+ return;
332
+ values.push([key, value]);
333
+ }
334
+ }
335
+ catch {
336
+ return;
337
+ }
338
+ finally {
339
+ release(decoded);
340
+ }
341
+ if (!values.length)
342
+ return;
343
+ let peer = this.remote.get(connectionId);
344
+ if (peer && peer.subject !== subject)
345
+ return;
346
+ const isNew = !peer;
347
+ if (!peer) {
348
+ if (this.remote.size >= MAX_PEERS)
349
+ return;
350
+ const store = new EphemeralStore(this.timeout);
351
+ const source = this;
352
+ peer = {
353
+ subject, store, unsubscribe: () => { }, values: {}, caretVersion: -1, resolvedCaret: null,
354
+ view: { connectionId, subject, user: DEFAULT_USER, cursor: null, selection: [],
355
+ selectionTruncated: false, drag: null, get caret() { return source.resolveCaret(connectionId); } },
356
+ };
357
+ this.remote.set(connectionId, peer);
358
+ this.membershipChanged = true;
359
+ this.changed(connectionId);
360
+ peer.unsubscribe = store.subscribe((event) => {
361
+ if (event.by === "timeout") {
362
+ const remaining = store.getAllStates();
363
+ if (!Object.keys(remaining).length)
364
+ this.leave(connectionId);
365
+ else {
366
+ const current = this.remote.get(connectionId);
367
+ if (current)
368
+ for (const key of KEYS)
369
+ if (key !== "user" && !(key in remaining))
370
+ this.updateView(connectionId, current, key, undefined);
371
+ }
372
+ }
373
+ });
374
+ }
375
+ for (const [key, value] of values) {
376
+ peer.store.set(key, value);
377
+ this.updateView(connectionId, peer, key, value);
378
+ }
379
+ if (isNew && Date.now() - this.lastDiscovery >= 1000) {
380
+ this.lastDiscovery = Date.now();
381
+ this.discoveryTimer = setTimeout(() => { this.discoveryTimer = undefined; this.reannounce(); }, 100 + Math.floor(Math.random() * 200));
382
+ }
383
+ }
384
+ leave(connectionId) {
385
+ if (connectionId === "0") {
386
+ this.clearPeers();
387
+ return;
388
+ }
389
+ const peer = this.remote.get(connectionId);
390
+ if (!peer)
391
+ return;
392
+ this.remote.delete(connectionId);
393
+ this.membershipChanged = true;
394
+ peer.unsubscribe();
395
+ release(peer.store);
396
+ this.changed(connectionId);
397
+ }
398
+ clearPeers() {
399
+ if (!this.remote.size)
400
+ return;
401
+ for (const [connectionId, peer] of this.remote) {
402
+ peer.unsubscribe();
403
+ release(peer.store);
404
+ this.changed(connectionId);
405
+ }
406
+ this.remote.clear();
407
+ this.peerViews = [];
408
+ this.membershipChanged = false;
409
+ }
410
+ enable() { if (!this.enabled) {
411
+ this.enabled = true;
412
+ this.startSending();
413
+ } }
414
+ set(key, value) { this.state[key] = value; this.enable(); this.publish(key); }
415
+ publish(key) {
416
+ if (this.disposed || !this.active || !this.connected || !this.enabled)
417
+ return;
418
+ this.local.set(key, this.state[key]);
419
+ this.dirty.add(key);
420
+ this.flush();
421
+ }
422
+ reannounce() {
423
+ if (!this.active || !this.connected || !this.enabled || this.disposed)
424
+ return;
425
+ for (const key of KEYS)
426
+ this.local.set(key, this.state[key]);
427
+ this.fullAnnouncement = true;
428
+ this.flush();
429
+ }
430
+ flush() {
431
+ if (!this.active || !this.connected || this.disposed)
432
+ return;
433
+ const now = Date.now(), elapsed = Math.max(0, now - this.budgetAt) / 1000;
434
+ this.budgetAt = now;
435
+ this.frameTokens = Math.min(FRAME_BURST, this.frameTokens + elapsed * FRAMES_PER_SECOND);
436
+ this.byteTokens = Math.min(BYTE_BURST, this.byteTokens + elapsed * BYTES_PER_SECOND);
437
+ const keys = this.fullAnnouncement ? [null] : [...this.dirty];
438
+ for (const key of keys) {
439
+ const bytes = key === null ? this.local.encodeAll() : this.local.encode(key);
440
+ if (bytes.length > MAX_PRESENCE_BYTES) {
441
+ if (key === null)
442
+ this.fullAnnouncement = false;
443
+ else
444
+ this.dirty.delete(key);
445
+ continue;
446
+ }
447
+ if (this.frameTokens < 1 || this.byteTokens < bytes.length || !this.send(bytes))
448
+ break;
449
+ this.frameTokens--;
450
+ this.byteTokens -= bytes.length;
451
+ if (key === null) {
452
+ this.fullAnnouncement = false;
453
+ this.dirty.clear();
454
+ if (this.state.drag === null && this.dragClearRepeats > 0) {
455
+ this.local.set("drag", null);
456
+ this.dirty.add("drag");
457
+ }
458
+ }
459
+ else
460
+ this.dirty.delete(key);
461
+ if (key === "drag" && this.state.drag === null && this.dragClearRepeats > 0) {
462
+ if (this.dragClearRepeats === 2) {
463
+ this.local.set("cursor", this.state.cursor);
464
+ this.dirty.add("cursor");
465
+ this.lastCursor = now;
466
+ }
467
+ this.dragClearRepeats--;
468
+ if (this.dragClearRepeats)
469
+ this.dirty.add("drag");
470
+ }
471
+ }
472
+ if ((this.fullAnnouncement || this.dirty.size) && this.flushTimer === undefined) {
473
+ this.flushTimer = setTimeout(() => { this.flushTimer = undefined; this.flush(); }, 16);
474
+ }
475
+ }
476
+ startSending() {
477
+ if (!this.connected || !this.active || !this.enabled || this.disposed)
478
+ return;
479
+ this.reannounce();
480
+ this.heartbeat = setInterval(() => this.reannounce(), this.heartbeatMs);
481
+ }
482
+ stopSending() {
483
+ clearInterval(this.heartbeat);
484
+ this.heartbeat = undefined;
485
+ clearTimeout(this.flushTimer);
486
+ this.flushTimer = undefined;
487
+ clearTimeout(this.cursorTimer);
488
+ this.cursorTimer = undefined;
489
+ clearTimeout(this.dragTimer);
490
+ this.dragTimer = undefined;
491
+ clearTimeout(this.discoveryTimer);
492
+ this.discoveryTimer = undefined;
493
+ this.dirty.clear();
494
+ this.fullAnnouncement = false;
495
+ this.dragClearRepeats = 0;
496
+ }
497
+ dispose() {
498
+ if (this.disposed)
499
+ return;
500
+ this.disposed = true;
501
+ this.stopSending();
502
+ this.clearPeers();
503
+ this.listeners.clear();
504
+ release(this.local);
505
+ this.unsubscribeDocument();
506
+ this.changedIds.clear();
507
+ if (this.notificationFrame !== undefined) {
508
+ if (this.notificationIsRaf)
509
+ cancelAnimationFrame(this.notificationFrame);
510
+ else
511
+ clearTimeout(this.notificationFrame);
512
+ this.notificationFrame = undefined;
513
+ }
514
+ }
515
+ }