@itrocks/sync 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.
Files changed (156) hide show
  1. package/LICENSE +165 -0
  2. package/README.md +249 -2
  3. package/config.yaml +2 -0
  4. package/demo/src/demo.css +458 -0
  5. package/dist/client/author-background.d.ts +2 -0
  6. package/dist/client/author-background.js +28 -0
  7. package/dist/client/clock.d.ts +10 -0
  8. package/dist/client/clock.js +30 -0
  9. package/dist/client/collections/order.d.ts +10 -0
  10. package/dist/client/collections/order.js +77 -0
  11. package/dist/client/collections/reorder-nodes.d.ts +2 -0
  12. package/dist/client/collections/reorder-nodes.js +67 -0
  13. package/dist/client/collections/row-changes.d.ts +12 -0
  14. package/dist/client/collections/row-changes.js +26 -0
  15. package/dist/client/collections/row-history.d.ts +16 -0
  16. package/dist/client/collections/row-history.js +61 -0
  17. package/dist/client/collections/table-columns.d.ts +19 -0
  18. package/dist/client/collections/table-columns.js +200 -0
  19. package/dist/client/collections.d.ts +54 -0
  20. package/dist/client/collections.js +262 -0
  21. package/dist/client/discovery.d.ts +1 -0
  22. package/dist/client/discovery.js +57 -0
  23. package/dist/client/field-address.d.ts +38 -0
  24. package/dist/client/field-address.js +225 -0
  25. package/dist/client/field-value.d.ts +7 -0
  26. package/dist/client/field-value.js +105 -0
  27. package/dist/client/form-identity.d.ts +1 -0
  28. package/dist/client/form-identity.js +43 -0
  29. package/dist/client/form-session.d.ts +53 -0
  30. package/dist/client/form-session.js +218 -0
  31. package/dist/client/identity.d.ts +3 -0
  32. package/dist/client/identity.js +27 -0
  33. package/dist/client/index.d.ts +43 -0
  34. package/dist/client/index.js +109 -0
  35. package/dist/client/journal.d.ts +13 -0
  36. package/dist/client/journal.js +59 -0
  37. package/dist/client/lifecycle.d.ts +26 -0
  38. package/dist/client/lifecycle.js +112 -0
  39. package/dist/client/observation.d.ts +11 -0
  40. package/dist/client/observation.js +46 -0
  41. package/dist/client/outbox.d.ts +15 -0
  42. package/dist/client/outbox.js +71 -0
  43. package/dist/client/plugin.d.ts +42 -0
  44. package/dist/client/plugin.js +1 -0
  45. package/dist/client/plugins/column-order/apply.d.ts +2 -0
  46. package/dist/client/plugins/column-order/apply.js +30 -0
  47. package/dist/client/plugins/column-order/colgroups.d.ts +2 -0
  48. package/dist/client/plugins/column-order/colgroups.js +78 -0
  49. package/dist/client/plugins/column-order/index.d.ts +2 -0
  50. package/dist/client/plugins/column-order/index.js +98 -0
  51. package/dist/client/plugins/cursor/editable.d.ts +16 -0
  52. package/dist/client/plugins/cursor/editable.js +67 -0
  53. package/dist/client/plugins/cursor/geometry.d.ts +16 -0
  54. package/dist/client/plugins/cursor/geometry.js +122 -0
  55. package/dist/client/plugins/cursor/index.d.ts +4 -0
  56. package/dist/client/plugins/cursor/index.js +13 -0
  57. package/dist/client/plugins/cursor/indicators.d.ts +31 -0
  58. package/dist/client/plugins/cursor/indicators.js +144 -0
  59. package/dist/client/plugins/cursor/local-selection.d.ts +19 -0
  60. package/dist/client/plugins/cursor/local-selection.js +234 -0
  61. package/dist/client/plugins/cursor/selection.d.ts +9 -0
  62. package/dist/client/plugins/cursor/selection.js +49 -0
  63. package/dist/client/plugins/cursor/text-presence.d.ts +15 -0
  64. package/dist/client/plugins/cursor/text-presence.js +95 -0
  65. package/dist/client/plugins/fields/author.d.ts +7 -0
  66. package/dist/client/plugins/fields/author.js +22 -0
  67. package/dist/client/plugins/fields/index.d.ts +4 -0
  68. package/dist/client/plugins/fields/index.js +192 -0
  69. package/dist/client/plugins/fields/writes.d.ts +19 -0
  70. package/dist/client/plugins/fields/writes.js +51 -0
  71. package/dist/client/plugins/focus/index.d.ts +9 -0
  72. package/dist/client/plugins/focus/index.js +92 -0
  73. package/dist/client/plugins/focus/indicators.d.ts +19 -0
  74. package/dist/client/plugins/focus/indicators.js +163 -0
  75. package/dist/client/plugins/naming/algorithm.d.ts +7 -0
  76. package/dist/client/plugins/naming/algorithm.js +65 -0
  77. package/dist/client/plugins/naming/attributes.d.ts +16 -0
  78. package/dist/client/plugins/naming/attributes.js +195 -0
  79. package/dist/client/plugins/naming/index.d.ts +5 -0
  80. package/dist/client/plugins/naming/index.js +185 -0
  81. package/dist/client/plugins/range/index.d.ts +4 -0
  82. package/dist/client/plugins/range/index.js +15 -0
  83. package/dist/client/plugins/reconciliation/index.d.ts +6 -0
  84. package/dist/client/plugins/reconciliation/index.js +282 -0
  85. package/dist/client/plugins/reconciliation/matching.d.ts +12 -0
  86. package/dist/client/plugins/reconciliation/matching.js +37 -0
  87. package/dist/client/plugins/reconciliation/proposals.d.ts +11 -0
  88. package/dist/client/plugins/reconciliation/proposals.js +32 -0
  89. package/dist/client/plugins/row-order/index.d.ts +2 -0
  90. package/dist/client/plugins/row-order/index.js +99 -0
  91. package/dist/client/plugins/rows/clone.d.ts +2 -0
  92. package/dist/client/plugins/rows/clone.js +123 -0
  93. package/dist/client/plugins/rows/index.d.ts +2 -0
  94. package/dist/client/plugins/rows/index.js +191 -0
  95. package/dist/client/plugins/rows/materialize.d.ts +4 -0
  96. package/dist/client/plugins/rows/materialize.js +43 -0
  97. package/dist/client/plugins/rows/remove.d.ts +1 -0
  98. package/dist/client/plugins/rows/remove.js +13 -0
  99. package/dist/client/plugins/rows/template.d.ts +2 -0
  100. package/dist/client/plugins/rows/template.js +21 -0
  101. package/dist/client/transport.d.ts +23 -0
  102. package/dist/client/transport.js +128 -0
  103. package/dist/client/user-colour.d.ts +3 -0
  104. package/dist/client/user-colour.js +11 -0
  105. package/dist/server/acknowledgments.d.ts +3 -0
  106. package/dist/server/acknowledgments.js +8 -0
  107. package/dist/server/broadcast.d.ts +3 -0
  108. package/dist/server/broadcast.js +7 -0
  109. package/dist/server/cli.d.ts +2 -0
  110. package/dist/server/cli.js +44 -0
  111. package/dist/server/clock.d.ts +2 -0
  112. package/dist/server/clock.js +3 -0
  113. package/dist/server/configuration.d.ts +3 -0
  114. package/dist/server/configuration.js +7 -0
  115. package/dist/server/connection.d.ts +13 -0
  116. package/dist/server/connection.js +1 -0
  117. package/dist/server/express.d.ts +2 -0
  118. package/dist/server/express.js +1 -0
  119. package/dist/server/fastify.d.ts +10 -0
  120. package/dist/server/fastify.js +15 -0
  121. package/dist/server/index.d.ts +7 -0
  122. package/dist/server/index.js +1 -0
  123. package/dist/server/journal.d.ts +7 -0
  124. package/dist/server/journal.js +16 -0
  125. package/dist/server/messages.d.ts +4 -0
  126. package/dist/server/messages.js +106 -0
  127. package/dist/server/participants.d.ts +9 -0
  128. package/dist/server/participants.js +7 -0
  129. package/dist/server/receipts.d.ts +13 -0
  130. package/dist/server/receipts.js +28 -0
  131. package/dist/server/recovery.d.ts +3 -0
  132. package/dist/server/recovery.js +9 -0
  133. package/dist/server/server.d.ts +34 -0
  134. package/dist/server/server.js +189 -0
  135. package/dist/server/sessions.d.ts +16 -0
  136. package/dist/server/sessions.js +37 -0
  137. package/dist/server/standalone.d.ts +9 -0
  138. package/dist/server/standalone.js +12 -0
  139. package/dist/server/transactions.d.ts +15 -0
  140. package/dist/server/transactions.js +50 -0
  141. package/dist/server/websocket-connection.d.ts +3 -0
  142. package/dist/server/websocket-connection.js +38 -0
  143. package/dist/server/websocket.d.ts +11 -0
  144. package/dist/server/websocket.js +26 -0
  145. package/dist/shared/field-update.d.ts +12 -0
  146. package/dist/shared/field-update.js +18 -0
  147. package/dist/shared/journal-entries.d.ts +9 -0
  148. package/dist/shared/journal-entries.js +33 -0
  149. package/dist/shared/protocol.d.ts +105 -0
  150. package/dist/shared/protocol.js +15 -0
  151. package/docs/dependencies.md +130 -0
  152. package/docs/spec-addendum-dependencies.md +10 -0
  153. package/docs/spec-addendum.md +717 -0
  154. package/docs/spec.md +1165 -0
  155. package/docs/testing.md +39 -0
  156. package/package.json +96 -5
@@ -0,0 +1,144 @@
1
+ import { userColour } from '../../user-colour.js';
2
+ import { clipOf } from './geometry.js';
3
+ import { editableGeometry } from './geometry.js';
4
+ import { intersect } from './geometry.js';
5
+ import { TextControlMirror } from './geometry.js';
6
+ export class CursorIndicators {
7
+ kind;
8
+ targets;
9
+ document;
10
+ window;
11
+ abort = new AbortController();
12
+ markers = new Map();
13
+ resize;
14
+ controls = new Set();
15
+ mirror;
16
+ pending = 0;
17
+ constructor(document, kind, targets) {
18
+ this.kind = kind;
19
+ this.targets = targets;
20
+ this.document = document;
21
+ this.window = document.defaultView;
22
+ this.resize = new ResizeObserver(() => this.schedule());
23
+ const options = { capture: true, passive: true, signal: this.abort.signal };
24
+ this.window.addEventListener('scroll', () => this.schedule(), options);
25
+ this.window.addEventListener('resize', () => this.schedule(), options);
26
+ }
27
+ destroy() {
28
+ this.abort.abort();
29
+ this.resize.disconnect();
30
+ this.window.cancelAnimationFrame(this.pending);
31
+ this.mirror?.destroy();
32
+ for (const { container } of this.markers.values()) {
33
+ container.remove();
34
+ }
35
+ this.markers.clear();
36
+ }
37
+ schedule() {
38
+ if (this.pending)
39
+ return;
40
+ this.pending = this.window.requestAnimationFrame(() => {
41
+ this.pending = 0;
42
+ this.render();
43
+ });
44
+ }
45
+ render() {
46
+ const targets = this.targets();
47
+ const clients = new Set(targets.map(({ client }) => client));
48
+ const controls = new Set(targets.map(({ control }) => control));
49
+ for (const control of this.controls) {
50
+ if (!controls.has(control)) {
51
+ this.resize.unobserve(control);
52
+ }
53
+ }
54
+ for (const control of controls) {
55
+ if (!this.controls.has(control)) {
56
+ this.resize.observe(control);
57
+ }
58
+ }
59
+ this.controls = controls;
60
+ for (const [client, marker] of this.markers) {
61
+ if (clients.has(client))
62
+ continue;
63
+ marker.container.remove();
64
+ this.markers.delete(client);
65
+ }
66
+ for (const target of targets) {
67
+ this.draw(target);
68
+ }
69
+ }
70
+ draw(target) {
71
+ const { client, control, user } = target;
72
+ let marker = this.markers.get(client);
73
+ if (!marker) {
74
+ marker = this.create(user);
75
+ this.markers.set(client, marker);
76
+ }
77
+ const { container, selection } = marker;
78
+ container.hidden = !control.isConnected || (control.checkVisibility?.({ visibilityProperty: true }) === false);
79
+ if (container.hidden)
80
+ return;
81
+ const clip = clipOf(control, this.window);
82
+ const offsets = ('offset' in target)
83
+ ? { anchor: target.offset, focus: target.offset }
84
+ : { anchor: 0, focus: 0, ranges: target.ranges };
85
+ const geometry = ((control instanceof HTMLInputElement) || (control instanceof HTMLTextAreaElement))
86
+ ? (this.mirror ??= new TextControlMirror(this.document)).measure(control, offsets)
87
+ : editableGeometry(control, offsets);
88
+ if ('offset' in target) {
89
+ const caret = marker.caret ??= this.createCaret(container);
90
+ const start = Math.min(geometry.caret.left, clip.right - 2);
91
+ const rect = new DOMRect(start, geometry.caret.top, 2, geometry.caret.height);
92
+ caret.hidden = (geometry.caret.left > clip.right + 1) || (geometry.caret.left < clip.left - 1);
93
+ place(caret, intersect(rect, clip));
94
+ return;
95
+ }
96
+ const rectangles = geometry.selection.map(rect => intersect(rect, clip)).filter(rect => rect.width && rect.height);
97
+ for (const [index, rect] of rectangles.entries()) {
98
+ let block = selection[index];
99
+ if (!block) {
100
+ block = this.createBlock('itrocks-sync-cursor-selection');
101
+ Object.assign(block.style, { background: 'currentColor', opacity: '0.25' });
102
+ container.append(block);
103
+ selection.push(block);
104
+ }
105
+ place(block, rect);
106
+ }
107
+ for (const block of selection.splice(rectangles.length)) {
108
+ block.remove();
109
+ }
110
+ }
111
+ create(user) {
112
+ const container = this.document.createElement('span');
113
+ container.className = 'itrocks-sync-' + this.kind;
114
+ container.setAttribute('aria-hidden', 'true');
115
+ Object.assign(container.style, {
116
+ color: userColour(user), position: 'fixed', pointerEvents: 'none', inset: '0',
117
+ zIndex: (this.kind === 'cursor') ? '2147482999' : '2147482998'
118
+ });
119
+ this.document.body.append(container);
120
+ return { container, selection: [] };
121
+ }
122
+ createBlock(className) {
123
+ const element = this.document.createElement('span');
124
+ element.className = className;
125
+ element.style.position = 'absolute';
126
+ return element;
127
+ }
128
+ createCaret(container) {
129
+ const caret = this.createBlock('itrocks-sync-cursor-caret');
130
+ caret.style.background = 'currentColor';
131
+ container.append(caret);
132
+ if (!this.window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
133
+ caret.animate([{ opacity: 1 }, { opacity: 0 }], {
134
+ duration: 1100, easing: 'steps(2, jump-none)', iterations: Infinity
135
+ });
136
+ }
137
+ return caret;
138
+ }
139
+ }
140
+ function place(element, rect) {
141
+ Object.assign(element.style, {
142
+ left: rect.left + 'px', top: rect.top + 'px', width: rect.width + 'px', height: rect.height + 'px'
143
+ });
144
+ }
@@ -0,0 +1,19 @@
1
+ import type { Offsets } from './selection.js';
2
+ interface Options {
3
+ className?: string;
4
+ multiple?: boolean;
5
+ rememberOnBlur?: boolean;
6
+ signal?: AbortSignal;
7
+ }
8
+ export interface SelectionSource {
9
+ read(): {
10
+ control: HTMLElement;
11
+ focused: boolean;
12
+ offsets: Offsets;
13
+ } | undefined;
14
+ subscribe(listener: () => void, signal: AbortSignal): void;
15
+ }
16
+ export declare function trackTextSelection(form: HTMLFormElement, options?: Options): SelectionSource & {
17
+ show(active: boolean): void;
18
+ };
19
+ export {};
@@ -0,0 +1,234 @@
1
+ import { targetControl } from '../../field-address.js';
2
+ import { clipOf } from './geometry.js';
3
+ import { editableGeometry } from './geometry.js';
4
+ import { TextControlMirror } from './geometry.js';
5
+ import { isCursorControl } from './selection.js';
6
+ import { rangesOf } from './selection.js';
7
+ import { selectionOf } from './selection.js';
8
+ const navigationKeys = new Set([
9
+ 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'End', 'Escape', 'Home', 'PageDown', 'PageUp', 'Tab'
10
+ ]);
11
+ function mergeRanges(first, second) {
12
+ const sorted = [...first, ...second].sort((left, right) => left.start - right.start);
13
+ const merged = [];
14
+ for (const range of sorted) {
15
+ const last = merged.at(-1);
16
+ if (last && (range.start <= last.end)) {
17
+ last.end = Math.max(last.end, range.end);
18
+ }
19
+ else {
20
+ merged.push({ ...range });
21
+ }
22
+ }
23
+ return merged;
24
+ }
25
+ function subtractRanges(ranges, covered) {
26
+ let remaining = ranges;
27
+ for (const { start, end } of covered) {
28
+ remaining = remaining.flatMap(range => {
29
+ if ((range.end <= start) || (range.start >= end))
30
+ return [range];
31
+ const portions = [];
32
+ if (range.start < start) {
33
+ portions.push({ start: range.start, end: start });
34
+ }
35
+ if (range.end > end) {
36
+ portions.push({ start: end, end: range.end });
37
+ }
38
+ return portions;
39
+ });
40
+ }
41
+ return remaining;
42
+ }
43
+ export function trackTextSelection(form, options = {}) {
44
+ const { className, multiple = true, rememberOnBlur, signal } = options;
45
+ const document = form.ownerDocument;
46
+ const view = document.defaultView;
47
+ const events = new EventTarget();
48
+ let control;
49
+ let layer;
50
+ let mirror;
51
+ let native;
52
+ let retained = [];
53
+ let scheduled = false;
54
+ let selection;
55
+ let visible = true;
56
+ let windowBlurred = false;
57
+ signal?.addEventListener('abort', () => {
58
+ layer?.remove();
59
+ mirror?.destroy();
60
+ }, { once: true });
61
+ function begin(event) {
62
+ if (!multiple || !event.isPrimary || (event.button !== 0))
63
+ return;
64
+ const target = targetControl(event.target);
65
+ if (!target || !form.contains(target))
66
+ return;
67
+ retained = ((target === control) && isCursorControl(target) && (event.ctrlKey || event.metaKey))
68
+ ? rangesOf(selection ?? selectionOf(target))
69
+ : [];
70
+ }
71
+ function capture(event) {
72
+ const inactive = windowBlurred || !document.hasFocus();
73
+ const focused = inactive ? undefined : targetControl(document.activeElement);
74
+ const active = (focused && isCursorControl(focused)) ? focused : (controlWithNativeRanges() ?? focused);
75
+ if (!active || !form.contains(active)) {
76
+ if (!inactive && !rememberOnBlur && !hasMultipleRanges()) {
77
+ forget();
78
+ }
79
+ notify();
80
+ schedule();
81
+ return;
82
+ }
83
+ if (active !== control) {
84
+ forget(active);
85
+ }
86
+ if ((event?.type === 'input') || ((event instanceof KeyboardEvent) && navigationKeys.has(event.key))) {
87
+ retained = [];
88
+ }
89
+ native = selectionOf(active, multiple);
90
+ if (native) {
91
+ selection = retained.length ? { ...native, ranges: mergeRanges(retained, rangesOf(native)) } : native;
92
+ }
93
+ else if (!rememberOnBlur && !retained.length) {
94
+ selection = undefined;
95
+ }
96
+ notify();
97
+ schedule();
98
+ }
99
+ function controlWithNativeRanges() {
100
+ if (!multiple)
101
+ return;
102
+ const selection = document.getSelection();
103
+ if (!selection || (selection.rangeCount < 2))
104
+ return;
105
+ const node = selection.focusNode;
106
+ const target = targetControl((node instanceof Element) ? node : (node?.parentElement ?? null));
107
+ if (target?.isContentEditable && form.contains(target))
108
+ return target;
109
+ }
110
+ function forget(next) {
111
+ control = next;
112
+ native = undefined;
113
+ retained = [];
114
+ selection = undefined;
115
+ }
116
+ function blur() {
117
+ windowBlurred = true;
118
+ if (hasMultipleRanges()) {
119
+ retained = rangesOf(selection);
120
+ }
121
+ notify();
122
+ schedule();
123
+ }
124
+ function focus() {
125
+ windowBlurred = false;
126
+ capture();
127
+ }
128
+ function geometry(control, offsets) {
129
+ if ((control instanceof HTMLInputElement) || (control instanceof HTMLTextAreaElement)) {
130
+ mirror ??= new TextControlMirror(document);
131
+ return mirror.measure(control, offsets);
132
+ }
133
+ return editableGeometry(control, offsets);
134
+ }
135
+ function hasMultipleRanges() {
136
+ return multiple && ((selection?.ranges?.length ?? 0) > 1);
137
+ }
138
+ function isFocused() {
139
+ return !!control && !windowBlurred && document.hasFocus() && (targetControl(document.activeElement) === control);
140
+ }
141
+ function notify() {
142
+ events.dispatchEvent(new Event('change'));
143
+ }
144
+ function schedule() {
145
+ if (scheduled || signal?.aborted || (!layer && !rememberOnBlur && !retained.length))
146
+ return;
147
+ scheduled = true;
148
+ queueMicrotask(() => {
149
+ scheduled = false;
150
+ if (!signal?.aborted) {
151
+ update();
152
+ }
153
+ });
154
+ }
155
+ function update() {
156
+ const focused = isFocused();
157
+ if (!visible || !selection || !control?.isConnected
158
+ || (!focused && !rememberOnBlur && !hasMultipleRanges())
159
+ || (control.checkVisibility?.({ visibilityProperty: true }) === false)) {
160
+ if (layer)
161
+ layer.hidden = true;
162
+ return;
163
+ }
164
+ // The browser already paints its native ranges while the field is focused.
165
+ const offsets = focused
166
+ ? { ...selection, ranges: subtractRanges(selection.ranges ?? [], rangesOf(native)) }
167
+ : selection;
168
+ const bounds = clipOf(control, view);
169
+ if (!bounds.width || !bounds.height || (focused && !offsets.ranges?.length)) {
170
+ if (layer)
171
+ layer.hidden = true;
172
+ return;
173
+ }
174
+ const { caret, selection: rectangles } = geometry(control, offsets);
175
+ const blocks = (rectangles.length || focused) ? rectangles : [caret];
176
+ if (!layer) {
177
+ layer = document.createElement('div');
178
+ layer.className = className ?? 'itrocks-sync-local-selection';
179
+ layer.setAttribute('aria-hidden', 'true');
180
+ if (!className) {
181
+ Object.assign(layer.style, {
182
+ overflow: 'hidden', pointerEvents: 'none', position: 'fixed', zIndex: '2147482998'
183
+ });
184
+ }
185
+ document.body.append(layer);
186
+ }
187
+ layer.replaceChildren(...blocks.map(rect => {
188
+ const block = document.createElement('span');
189
+ block.className = rectangles.length ? 'range' : 'caret';
190
+ if (!className) {
191
+ Object.assign(block.style, { position: 'absolute', background: 'Highlight', opacity: '0.35' });
192
+ }
193
+ Object.assign(block.style, {
194
+ height: rect.height + 'px',
195
+ left: (rect.left - bounds.x) + 'px',
196
+ top: (rect.top - bounds.y) + 'px',
197
+ width: (rectangles.length ? rect.width : 1) + 'px'
198
+ });
199
+ return block;
200
+ }));
201
+ Object.assign(layer.style, {
202
+ height: bounds.height + 'px', left: bounds.x + 'px', top: bounds.y + 'px', width: bounds.width + 'px'
203
+ });
204
+ layer.hidden = false;
205
+ }
206
+ const captured = { capture: true, signal };
207
+ document.addEventListener('pointerdown', begin, captured);
208
+ for (const event of ['focusin', 'focusout', 'input', 'keyup', 'pointerup', 'select', 'selectionchange']) {
209
+ document.addEventListener(event, capture, captured);
210
+ }
211
+ view.addEventListener('blur', blur, { signal });
212
+ view.addEventListener('focus', focus, { signal });
213
+ for (const event of ['resize', 'scroll']) {
214
+ view.addEventListener(event, schedule, captured);
215
+ }
216
+ capture();
217
+ return {
218
+ read() {
219
+ const focused = !!rememberOnBlur || isFocused();
220
+ if (!focused && !hasMultipleRanges())
221
+ return;
222
+ if (control && selection && form.contains(control)) {
223
+ return { control, focused, offsets: selection };
224
+ }
225
+ },
226
+ show(active) {
227
+ visible = active;
228
+ schedule();
229
+ },
230
+ subscribe(listener, signal) {
231
+ events.addEventListener('change', listener, { signal });
232
+ }
233
+ };
234
+ }
@@ -0,0 +1,9 @@
1
+ import type { CursorRange } from '../../../shared/protocol.js';
2
+ export interface Offsets {
3
+ anchor: number;
4
+ focus: number;
5
+ ranges?: readonly CursorRange[];
6
+ }
7
+ export declare function rangesOf(selection: Offsets | undefined): readonly CursorRange[];
8
+ export declare function isCursorControl(control: HTMLElement): boolean;
9
+ export declare function selectionOf(control: HTMLElement, multiple?: boolean): Offsets | undefined;
@@ -0,0 +1,49 @@
1
+ import { EditableText } from './editable.js';
2
+ export function rangesOf(selection) {
3
+ if (!selection)
4
+ return [];
5
+ const { anchor, focus, ranges } = selection;
6
+ if (ranges)
7
+ return ranges;
8
+ return (anchor === focus) ? [] : [{ start: Math.min(anchor, focus), end: Math.max(anchor, focus) }];
9
+ }
10
+ export function isCursorControl(control) {
11
+ if (control instanceof HTMLTextAreaElement)
12
+ return true;
13
+ if (control instanceof HTMLInputElement) {
14
+ return (control.type !== 'password') && (control.selectionStart !== null);
15
+ }
16
+ return control.isContentEditable && control.hasAttribute('contenteditable');
17
+ }
18
+ export function selectionOf(control, multiple = true) {
19
+ if (!isCursorControl(control))
20
+ return;
21
+ if ((control instanceof HTMLInputElement) || (control instanceof HTMLTextAreaElement)) {
22
+ const { selectionStart: start, selectionEnd: end, selectionDirection: direction } = control;
23
+ if ((start !== null) && (end !== null)) {
24
+ return (direction === 'backward') ? { anchor: end, focus: start } : { anchor: start, focus: end };
25
+ }
26
+ return;
27
+ }
28
+ const selection = control.ownerDocument.getSelection();
29
+ if (!selection?.anchorNode || !selection.focusNode || !control.contains(selection.focusNode)
30
+ || !control.contains(selection.anchorNode))
31
+ return;
32
+ const text = new EditableText(control);
33
+ const anchor = text.offset(selection.anchorNode, selection.anchorOffset);
34
+ const focus = text.offset(selection.focusNode, selection.focusOffset);
35
+ if ((anchor === undefined) || (focus === undefined))
36
+ return;
37
+ if (!multiple || (selection.rangeCount <= 1))
38
+ return { anchor, focus };
39
+ const ranges = [];
40
+ for (let index = 0; index < selection.rangeCount; index++) {
41
+ const range = selection.getRangeAt(index);
42
+ const start = text.offset(range.startContainer, range.startOffset);
43
+ const end = text.offset(range.endContainer, range.endOffset);
44
+ if ((start !== undefined) && (end !== undefined) && (start < end)) {
45
+ ranges.push({ start, end });
46
+ }
47
+ }
48
+ return { anchor, focus, ranges };
49
+ }
@@ -0,0 +1,15 @@
1
+ import type { CursorPosition } from '../../../shared/protocol.js';
2
+ import type { Participant } from '../../../shared/protocol.js';
3
+ import type { RangeSelection } from '../../../shared/protocol.js';
4
+ import type { Plugin } from '../../plugin.js';
5
+ import type { PluginContext } from '../../plugin.js';
6
+ import type { SelectionSource } from './local-selection.js';
7
+ type Snapshot = NonNullable<ReturnType<SelectionSource['read']>>;
8
+ type TextPresence = CursorPosition | RangeSelection;
9
+ interface Options<T extends TextPresence> {
10
+ local(field: string, snapshot: Snapshot): T | null;
11
+ remote(participant: Participant): T | undefined;
12
+ send(context: PluginContext, value: T | null): void;
13
+ }
14
+ export declare function textPresence<T extends TextPresence>(name: 'cursor' | 'range', options: Options<T>, source?: SelectionSource): Plugin;
15
+ export {};
@@ -0,0 +1,95 @@
1
+ import { addressKey } from '../../field-address.js';
2
+ import { parseAddress } from '../../field-address.js';
3
+ import { CursorIndicators } from './indicators.js';
4
+ import { trackTextSelection } from './local-selection.js';
5
+ import { isCursorControl } from './selection.js';
6
+ const sources = new WeakMap();
7
+ export function textPresence(name, options, source) {
8
+ return {
9
+ name,
10
+ init(context) {
11
+ const { addresses, display, form } = context;
12
+ const abort = new AbortController();
13
+ const document = form.ownerDocument;
14
+ const window = document.defaultView;
15
+ const selection = source ?? sources.get(addresses) ?? trackTextSelection(form, {
16
+ multiple: name === 'range', signal: abort.signal
17
+ });
18
+ const peers = new Map();
19
+ const indicators = new CursorIndicators(document, name, targets);
20
+ let frame = 0;
21
+ if (!source) {
22
+ sources.set(addresses, selection);
23
+ }
24
+ function targets() {
25
+ const result = [];
26
+ for (const [client, { user, value }] of peers) {
27
+ if (!value || (('offset' in value) && (display?.caret === false)))
28
+ continue;
29
+ const address = parseAddress(value.field);
30
+ if (!address)
31
+ continue;
32
+ const control = addresses.controls(address).find(isCursorControl);
33
+ if (control) {
34
+ result.push({ ...value, client, control, user });
35
+ }
36
+ }
37
+ return result;
38
+ }
39
+ function publish(snapshot) {
40
+ const control = snapshot?.control;
41
+ const address = control && !control.closest('[hidden]') && addresses.address(control);
42
+ options.send(context, (address && snapshot) ? options.local(addressKey(address), snapshot) : null);
43
+ }
44
+ function schedule() {
45
+ if (context.muted())
46
+ return;
47
+ const snapshot = selection.read();
48
+ if (source || !snapshot?.focused) {
49
+ window.cancelAnimationFrame(frame);
50
+ frame = 0;
51
+ publish(snapshot);
52
+ return;
53
+ }
54
+ if (frame)
55
+ return;
56
+ frame = window.requestAnimationFrame(() => {
57
+ frame = 0;
58
+ publish(selection.read());
59
+ });
60
+ }
61
+ selection.subscribe(schedule, abort.signal);
62
+ schedule();
63
+ return {
64
+ [name](client, value) {
65
+ const peer = peers.get(client);
66
+ if (!peer)
67
+ return;
68
+ peer.value = value ?? undefined;
69
+ indicators.schedule();
70
+ },
71
+ destroy() {
72
+ abort.abort();
73
+ window.cancelAnimationFrame(frame);
74
+ indicators.destroy();
75
+ options.send(context, null);
76
+ },
77
+ flush() {
78
+ if (peers.size) {
79
+ indicators.schedule();
80
+ }
81
+ schedule();
82
+ },
83
+ presence(participants, self) {
84
+ peers.clear();
85
+ for (const participant of participants) {
86
+ if (participant.client === self)
87
+ continue;
88
+ peers.set(participant.client, { user: participant.user, value: options.remote(participant) });
89
+ }
90
+ indicators.schedule();
91
+ }
92
+ };
93
+ }
94
+ };
95
+ }
@@ -0,0 +1,7 @@
1
+ import type { User } from '../../../shared/protocol.js';
2
+ export declare class Authors {
3
+ private elements;
4
+ clear(element: HTMLElement): void;
5
+ paint(element: HTMLElement, user: User): void;
6
+ prune(keep: (element: HTMLElement) => boolean): void;
7
+ }
@@ -0,0 +1,22 @@
1
+ import { paintAuthorBackground } from '../../author-background.js';
2
+ import { restoreAuthorBackground } from '../../author-background.js';
3
+ import { userColour } from '../../user-colour.js';
4
+ export class Authors {
5
+ elements = new Set();
6
+ clear(element) {
7
+ if (this.elements.delete(element)) {
8
+ restoreAuthorBackground(element, element);
9
+ }
10
+ }
11
+ paint(element, user) {
12
+ paintAuthorBackground(element, userColour(user));
13
+ this.elements.add(element);
14
+ }
15
+ prune(keep) {
16
+ for (const element of this.elements) {
17
+ if (keep(element))
18
+ continue;
19
+ this.clear(element);
20
+ }
21
+ }
22
+ }
@@ -0,0 +1,4 @@
1
+ import type { Plugin } from '../../plugin.js';
2
+ export declare function fields(options?: {
3
+ authors?: boolean;
4
+ }): Plugin;