@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,192 @@
1
+ import { fieldUpdate } from '../../field-address.js';
2
+ import { valuesEqual } from '../../field-address.js';
3
+ import { readValue } from '../../field-value.js';
4
+ import { changesFieldStructure } from '../../observation.js';
5
+ import { Authors } from './author.js';
6
+ import { FieldWrites } from './writes.js';
7
+ export function fields(options = {}) {
8
+ return {
9
+ name: 'fields',
10
+ init(context) {
11
+ const { addresses, collections, form } = context;
12
+ const controller = new AbortController();
13
+ const authors = options.authors === false ? undefined : new Authors();
14
+ const applied = new WeakMap();
15
+ const original = new WeakMap();
16
+ const observed = new Map();
17
+ const writes = new FieldWrites(address => addresses.key(address));
18
+ const document = form.ownerDocument;
19
+ let targetsChanged = true;
20
+ let revision = collections.revision;
21
+ let self = context.user();
22
+ function valueOf(address, control) {
23
+ if ((control instanceof HTMLInputElement) && (control.type === 'radio')) {
24
+ return addresses.controls(address).map(readValue).find(value => value !== null) ?? null;
25
+ }
26
+ return addresses.read(control);
27
+ }
28
+ function observe(control, change) {
29
+ const address = addresses.address(control);
30
+ if (!address)
31
+ return;
32
+ const key = addresses.key(address);
33
+ const value = valueOf(address, control);
34
+ if (!original.has(control)) {
35
+ original.set(control, addresses.read(control));
36
+ }
37
+ if (observed.has(key) && (!change || valuesEqual(observed.get(key), value)))
38
+ return;
39
+ observed.set(key, value);
40
+ if (!change)
41
+ return;
42
+ const update = { address, value };
43
+ const transaction = context.publish('field', update, key);
44
+ const write = writes.add(update, transaction);
45
+ for (const target of addresses.controls(address)) {
46
+ if (writes.winner(key) === write && (write.transaction === transaction)) {
47
+ applied.set(target, write);
48
+ }
49
+ else {
50
+ applied.delete(target);
51
+ }
52
+ }
53
+ context.changed();
54
+ }
55
+ function input(event) {
56
+ if (context.muted())
57
+ return;
58
+ const control = addresses.control(event.target);
59
+ if (control) {
60
+ observe(control, true);
61
+ }
62
+ }
63
+ function refreshControls(restore) {
64
+ const available = new Set();
65
+ for (const control of addresses.formControls()) {
66
+ const address = addresses.address(control);
67
+ if (!address)
68
+ continue;
69
+ const key = addresses.key(address);
70
+ available.add(key);
71
+ if (restore && address.collection && applied.has(control) && !writes.winner(key)) {
72
+ const value = original.get(control);
73
+ if (value !== undefined) {
74
+ addresses.write(control, value);
75
+ observed.set(key, valueOf(address, control));
76
+ }
77
+ applied.delete(control);
78
+ }
79
+ observe(control, false);
80
+ }
81
+ for (const key of observed.keys()) {
82
+ if (!available.has(key)) {
83
+ observed.delete(key);
84
+ }
85
+ }
86
+ authors?.prune(element => applied.has(element) && addresses.owns(element));
87
+ }
88
+ document.addEventListener('input', input, { signal: controller.signal });
89
+ document.addEventListener('change', input, { signal: controller.signal });
90
+ form.addEventListener('reset', event => setTimeout(() => {
91
+ if (controller.signal.aborted || event.defaultPrevented)
92
+ return;
93
+ for (const control of addresses.formControls()) {
94
+ observe(control, true);
95
+ }
96
+ }), { signal: controller.signal });
97
+ refreshControls(false);
98
+ return {
99
+ destroy() {
100
+ controller.abort();
101
+ authors?.prune(() => false);
102
+ },
103
+ flush() {
104
+ const user = context.user();
105
+ const rebound = revision !== collections.revision;
106
+ const refresh = targetsChanged || rebound;
107
+ const changed = writes.refresh(collections.revision, refresh || (self !== user));
108
+ targetsChanged = false;
109
+ revision = collections.revision;
110
+ self = user;
111
+ if (!changed.length && !refresh)
112
+ return;
113
+ context.mute(() => {
114
+ if (refresh) {
115
+ refreshControls(rebound);
116
+ }
117
+ for (const key of changed) {
118
+ const write = writes.winner(key);
119
+ if (!write)
120
+ continue;
121
+ for (const control of addresses.controls(write.address)) {
122
+ if (applied.get(control) !== write) {
123
+ addresses.write(control, write.value);
124
+ applied.set(control, write);
125
+ observed.set(key, write.value);
126
+ }
127
+ const author = write.transaction.user ?? ((write.transaction.client === context.client) ? user : undefined);
128
+ if (author && !write.initial) {
129
+ authors?.paint(control, author);
130
+ }
131
+ else {
132
+ authors?.clear(control);
133
+ }
134
+ }
135
+ }
136
+ });
137
+ },
138
+ observe(records) {
139
+ targetsChanged ||= changesFieldStructure(records);
140
+ for (const record of records) {
141
+ const control = addresses.control((record.target instanceof Element)
142
+ ? record.target
143
+ : record.target.parentElement);
144
+ if (!control)
145
+ continue;
146
+ const editable = control.hasAttribute('contenteditable');
147
+ const selection = control instanceof HTMLSelectElement;
148
+ const attribute = (record.type === 'attributes') && ['checked', 'value'].includes(record.attributeName ?? '');
149
+ if (editable || selection || attribute) {
150
+ observe(control, true);
151
+ }
152
+ }
153
+ },
154
+ prepare(transaction) {
155
+ if (transaction.type !== 'field')
156
+ return;
157
+ const update = fieldUpdate(transaction.data);
158
+ if (!update)
159
+ return;
160
+ const key = addresses.key(update.address);
161
+ const write = writes.winner(key);
162
+ if (write?.transaction !== transaction)
163
+ return;
164
+ const control = addresses.controls(update.address)[0];
165
+ if (control) {
166
+ update.value = write.value = valueOf(update.address, control);
167
+ observed.set(key, write.value);
168
+ }
169
+ },
170
+ receive(transaction) {
171
+ if (transaction.type === 'field') {
172
+ const update = fieldUpdate(transaction.data);
173
+ if (update) {
174
+ writes.add(update, transaction);
175
+ }
176
+ }
177
+ if (transaction.type !== 'add-row')
178
+ return;
179
+ const { collection, row, values } = (transaction.data ?? {});
180
+ if (typeof collection !== 'string' || typeof row !== 'string' || !values)
181
+ return;
182
+ for (const [field, value] of Object.entries(values)) {
183
+ const update = fieldUpdate({ address: { collection, row, field }, value });
184
+ if (update) {
185
+ writes.add(update, transaction, true);
186
+ }
187
+ }
188
+ }
189
+ };
190
+ }
191
+ };
192
+ }
@@ -0,0 +1,19 @@
1
+ import type { Transaction } from '../../../shared/protocol.js';
2
+ import type { FieldAddress } from '../../field-address.js';
3
+ import type { FieldUpdate } from '../../field-address.js';
4
+ export type Write = FieldUpdate & {
5
+ transaction: Transaction;
6
+ initial: boolean;
7
+ };
8
+ export declare class FieldWrites {
9
+ private key;
10
+ private entries;
11
+ private winners;
12
+ private dirty;
13
+ private version;
14
+ constructor(key: (address: FieldAddress) => string);
15
+ add(update: FieldUpdate, transaction: Transaction, initial?: boolean): Write;
16
+ refresh(version: number, redraw: boolean): string[];
17
+ winner(key: string): Write | undefined;
18
+ private consider;
19
+ }
@@ -0,0 +1,51 @@
1
+ import { compareTransactions } from '../../../shared/protocol.js';
2
+ import { addressKey } from '../../field-address.js';
3
+ export class FieldWrites {
4
+ key;
5
+ entries = new Map();
6
+ winners = new Map();
7
+ dirty = new Set();
8
+ version = -1;
9
+ constructor(key) {
10
+ this.key = key;
11
+ }
12
+ add(update, transaction, initial = false) {
13
+ const address = addressKey(update.address);
14
+ const logical = this.key(update.address);
15
+ const old = this.entries.get(address);
16
+ const write = { ...update, transaction, initial };
17
+ this.dirty.add(logical);
18
+ if (old && !wins(write, old))
19
+ return old;
20
+ this.entries.set(address, write);
21
+ this.consider(logical, write);
22
+ return write;
23
+ }
24
+ refresh(version, redraw) {
25
+ if (this.version !== version) {
26
+ this.version = version;
27
+ this.winners.clear();
28
+ for (const write of this.entries.values()) {
29
+ this.consider(this.key(write.address), write);
30
+ }
31
+ redraw = true;
32
+ }
33
+ const changed = [...(redraw ? this.winners.keys() : this.dirty)];
34
+ this.dirty.clear();
35
+ return changed;
36
+ }
37
+ winner(key) {
38
+ return this.winners.get(key);
39
+ }
40
+ consider(key, write) {
41
+ const old = this.winners.get(key);
42
+ if (!old || wins(write, old)) {
43
+ this.winners.set(key, write);
44
+ }
45
+ }
46
+ }
47
+ function wins(write, old) {
48
+ return (write.initial === old.initial)
49
+ ? compareTransactions(write.transaction, old.transaction) > 0
50
+ : !write.initial;
51
+ }
@@ -0,0 +1,9 @@
1
+ import type { Participant } from '../../../shared/protocol.js';
2
+ import type { Plugin } from '../../plugin.js';
3
+ export interface FocusOptions {
4
+ badge?: boolean;
5
+ border?: boolean;
6
+ caret?: boolean;
7
+ onPresence?(participants: readonly Participant[], form: HTMLFormElement): void;
8
+ }
9
+ export declare function focus({ badge, border, caret, onPresence }?: FocusOptions): Plugin;
@@ -0,0 +1,92 @@
1
+ import { addressKey } from '../../field-address.js';
2
+ import { parseAddress } from '../../field-address.js';
3
+ import { targetControl } from '../../field-address.js';
4
+ import { Indicators } from './indicators.js';
5
+ export function focus({ badge = true, border = true, caret, onPresence } = {}) {
6
+ return {
7
+ name: 'focus',
8
+ init(context) {
9
+ const { addresses, collections, display, form } = context;
10
+ const abort = new AbortController();
11
+ const document = form.ownerDocument;
12
+ const indicators = (badge || border) ? new Indicators(document, badge, border) : undefined;
13
+ let participants = [];
14
+ let self;
15
+ let windowBlurred = false;
16
+ if (display && (caret !== undefined)) {
17
+ display.caret = caret;
18
+ }
19
+ function report(target = document.activeElement) {
20
+ if (windowBlurred || !document.hasFocus()) {
21
+ context.focus(null);
22
+ return;
23
+ }
24
+ const control = targetControl(target);
25
+ const address = control && addresses.address(control);
26
+ context.focus(address ? addressKey(address) : null);
27
+ }
28
+ function render() {
29
+ if (!indicators)
30
+ return;
31
+ const fields = new Map();
32
+ for (const participant of participants) {
33
+ if ((participant.client === self) || !participant.field)
34
+ continue;
35
+ const address = parseAddress(participant.field);
36
+ if (!address)
37
+ continue;
38
+ for (const control of addresses.controls(address)) {
39
+ if (control.checkVisibility?.({ visibilityProperty: true }) === false)
40
+ continue;
41
+ const target = indicators.target(control, form, collections.locate(control)?.element);
42
+ const users = fields.get(target) ?? [];
43
+ if (!users.some(user => user.id === participant.user.id)) {
44
+ users.push(participant.user);
45
+ }
46
+ fields.set(target, users);
47
+ }
48
+ }
49
+ for (const users of fields.values()) {
50
+ users.sort((a, b) => (a.id < b.id) ? -1 : Number(a.id > b.id));
51
+ }
52
+ indicators.render(fields);
53
+ }
54
+ document.addEventListener('focusin', event => {
55
+ if (!context.muted()) {
56
+ report(event.target);
57
+ }
58
+ }, { signal: abort.signal });
59
+ document.addEventListener('focusout', event => {
60
+ if (!context.muted()) {
61
+ report(event.relatedTarget);
62
+ }
63
+ }, { signal: abort.signal });
64
+ document.defaultView?.addEventListener('blur', () => {
65
+ windowBlurred = true;
66
+ report(null);
67
+ }, { signal: abort.signal });
68
+ document.defaultView?.addEventListener('focus', () => {
69
+ windowBlurred = false;
70
+ report();
71
+ }, { signal: abort.signal });
72
+ report();
73
+ return {
74
+ destroy() {
75
+ abort.abort();
76
+ context.focus(null);
77
+ indicators?.destroy();
78
+ },
79
+ flush() {
80
+ report();
81
+ render();
82
+ },
83
+ presence(values, connection) {
84
+ self = connection;
85
+ participants = values;
86
+ onPresence?.(values, form);
87
+ render();
88
+ }
89
+ };
90
+ }
91
+ };
92
+ }
@@ -0,0 +1,19 @@
1
+ import type { User } from '../../../shared/protocol.js';
2
+ export declare class Indicators {
3
+ private document;
4
+ private showBadges;
5
+ private showBorder;
6
+ private abort;
7
+ private frames;
8
+ private pending;
9
+ private resize;
10
+ private window;
11
+ constructor(document: Document, showBadges: boolean, showBorder: boolean);
12
+ destroy(): void;
13
+ target(control: HTMLElement, form: HTMLFormElement, item?: Element): HTMLElement;
14
+ render(fields: ReadonlyMap<HTMLElement, User[]>): void;
15
+ private badge;
16
+ private border;
17
+ private create;
18
+ private schedule;
19
+ }
@@ -0,0 +1,163 @@
1
+ import { initials } from '../../user-colour.js';
2
+ import { userColour } from '../../user-colour.js';
3
+ export class Indicators {
4
+ document;
5
+ showBadges;
6
+ showBorder;
7
+ abort = new AbortController();
8
+ frames = new Map();
9
+ pending = 0;
10
+ resize = new ResizeObserver(() => this.schedule());
11
+ window;
12
+ constructor(document, showBadges, showBorder) {
13
+ this.document = document;
14
+ this.showBadges = showBadges;
15
+ this.showBorder = showBorder;
16
+ this.window = document.defaultView;
17
+ const options = { capture: true, passive: true, signal: this.abort.signal };
18
+ this.window.addEventListener('scroll', () => this.schedule(), options);
19
+ this.window.addEventListener('resize', () => this.schedule(), options);
20
+ }
21
+ destroy() {
22
+ this.abort.abort();
23
+ this.resize.disconnect();
24
+ this.window.cancelAnimationFrame(this.pending);
25
+ for (const indicator of this.frames.values()) {
26
+ indicator.frame.remove();
27
+ }
28
+ this.frames.clear();
29
+ }
30
+ target(control, form, item) {
31
+ for (let element = control; element && (element !== form) && (element !== this.document.body); element = element.parentElement) {
32
+ if ((element === item) || element.matches('td, th, li'))
33
+ return element;
34
+ if (hasBorder(this.window.getComputedStyle(element)))
35
+ return element;
36
+ }
37
+ return control;
38
+ }
39
+ render(fields) {
40
+ for (const [control, indicator] of this.frames) {
41
+ if (fields.has(control))
42
+ continue;
43
+ this.resize.unobserve(control);
44
+ indicator.frame.remove();
45
+ this.frames.delete(control);
46
+ }
47
+ for (const [control, users] of fields) {
48
+ let indicator = this.frames.get(control);
49
+ if (!indicator) {
50
+ indicator = this.create();
51
+ this.frames.set(control, indicator);
52
+ this.resize.observe(control);
53
+ }
54
+ const key = JSON.stringify(users.map(user => [user.id, user.name]));
55
+ if (indicator.key === key)
56
+ continue;
57
+ indicator.key = key;
58
+ if (this.showBadges) {
59
+ indicator.badges.replaceChildren(...users.map(user => this.badge(user)));
60
+ }
61
+ if (this.showBorder) {
62
+ this.border(indicator.frame, users.map(userColour));
63
+ }
64
+ }
65
+ if (this.frames.size) {
66
+ this.schedule();
67
+ }
68
+ }
69
+ badge(user) {
70
+ const badge = this.document.createElement('span');
71
+ badge.className = 'itrocks-sync-badge';
72
+ badge.textContent = initials(user);
73
+ badge.title = user.name;
74
+ badge.setAttribute('aria-label', user.name);
75
+ Object.assign(badge.style, {
76
+ background: userColour(user),
77
+ borderRadius: '3px',
78
+ color: 'white',
79
+ font: '600 11px/18px system-ui, sans-serif',
80
+ minWidth: '22px',
81
+ padding: '0 3px',
82
+ pointerEvents: 'auto',
83
+ textAlign: 'center'
84
+ });
85
+ return badge;
86
+ }
87
+ border(frame, colours) {
88
+ if (colours.length === 1) {
89
+ frame.style.background = '';
90
+ frame.style.border = '2px solid ' + colours[0];
91
+ return;
92
+ }
93
+ const horizontal = stripes(colours, 'right');
94
+ const vertical = stripes(colours, 'bottom');
95
+ frame.style.border = 'none';
96
+ frame.style.background = [
97
+ horizontal + ' top / 100% 2px no-repeat',
98
+ horizontal + ' bottom / 100% 2px no-repeat',
99
+ vertical + ' left / 2px 100% no-repeat',
100
+ vertical + ' right / 2px 100% no-repeat'
101
+ ].join(',');
102
+ }
103
+ create() {
104
+ const frame = this.document.createElement('span');
105
+ const badges = this.document.createElement('span');
106
+ frame.className = 'itrocks-sync-focus';
107
+ Object.assign(frame.style, {
108
+ boxSizing: 'border-box',
109
+ pointerEvents: 'none',
110
+ position: 'fixed',
111
+ zIndex: '2147483000'
112
+ });
113
+ Object.assign(badges.style, {
114
+ bottom: '100%',
115
+ display: 'flex',
116
+ gap: '1px',
117
+ position: 'absolute',
118
+ right: '-2px'
119
+ });
120
+ frame.append(badges);
121
+ this.document.body.append(frame);
122
+ return { badges, frame, key: '', rect: '' };
123
+ }
124
+ schedule() {
125
+ if (this.pending || !this.frames.size)
126
+ return;
127
+ this.pending = this.window.requestAnimationFrame(() => {
128
+ this.pending = 0;
129
+ const geometry = [...this.frames].map(([control, indicator]) => ({
130
+ indicator,
131
+ rect: control.getBoundingClientRect(),
132
+ visible: control.checkVisibility?.({ visibilityProperty: true }) ?? true
133
+ }));
134
+ for (const { indicator, rect, visible } of geometry) {
135
+ const { frame } = indicator;
136
+ const key = JSON.stringify([visible, rect.left, rect.top, rect.width, rect.height]);
137
+ if (indicator.rect === key)
138
+ continue;
139
+ indicator.rect = key;
140
+ frame.hidden = !visible || !rect.width || !rect.height;
141
+ Object.assign(frame.style, {
142
+ left: rect.left + 'px',
143
+ top: rect.top + 'px',
144
+ width: rect.width + 'px',
145
+ height: rect.height + 'px'
146
+ });
147
+ }
148
+ });
149
+ }
150
+ }
151
+ function hasBorder(style) {
152
+ return ['top', 'right', 'bottom', 'left'].some(side => {
153
+ const border = 'border-' + side + '-';
154
+ const type = style.getPropertyValue(border + 'style');
155
+ const color = style.getPropertyValue(border + 'color');
156
+ return (type !== 'none') && (type !== 'hidden') && (parseFloat(style.getPropertyValue(border + 'width')) > 0)
157
+ && (color !== 'transparent') && !/^rgba\([^)]*,\s*0\)$/.test(color);
158
+ });
159
+ }
160
+ function stripes(colours, direction) {
161
+ const stops = colours.map((colour, index) => colour + ' ' + (index * 12) + 'px ' + ((index + 1) * 12) + 'px');
162
+ return 'repeating-linear-gradient(to ' + direction + ', ' + stops.join(', ') + ')';
163
+ }
@@ -0,0 +1,7 @@
1
+ export type FindNamingIndex = (names: readonly string[], siblings: readonly (readonly string[])[]) => NamingIndex | undefined;
2
+ export interface NamingIndex {
3
+ index: string;
4
+ prefix: string;
5
+ previous: string;
6
+ }
7
+ export declare function findNamingIndex(names: readonly string[], siblings: readonly (readonly string[])[]): NamingIndex | undefined;
@@ -0,0 +1,65 @@
1
+ export function findNamingIndex(names, siblings) {
2
+ const patterns = rowPatterns(names);
3
+ const peers = siblings.map(rowPatterns);
4
+ let match;
5
+ for (const [prefix, { fields, previous }] of patterns) {
6
+ const values = new Set([previous]);
7
+ let size = 0;
8
+ let max = BigInt(previous);
9
+ for (const row of peers) {
10
+ const evidence = row.get(prefix);
11
+ if (!evidence || ![...evidence.fields].some(field => fields.has(field)))
12
+ continue;
13
+ values.add(evidence.previous);
14
+ const number = BigInt(evidence.previous);
15
+ if (number > max) {
16
+ max = number;
17
+ }
18
+ size++;
19
+ }
20
+ const varies = values.size > 1;
21
+ if (!varies && (fields.size < 2) && !size)
22
+ continue;
23
+ // Varying outer indices cover their nested fields. Without variation, preserve fixed outer indices.
24
+ const score = [Number(varies), fields.size, size, varies ? -prefix.length : prefix.length];
25
+ const index = (max + 1n).toString().padStart(previous.length, '0');
26
+ const candidate = { index: { index, prefix, previous }, score };
27
+ if (!match || isBetter(candidate, match)) {
28
+ match = candidate;
29
+ }
30
+ }
31
+ return match?.index;
32
+ }
33
+ function isBetter(first, second) {
34
+ const difference = first.score.findIndex((value, index) => value !== second.score[index]);
35
+ return (difference >= 0)
36
+ ? (first.score[difference] > second.score[difference])
37
+ : (first.index.prefix < second.index.prefix);
38
+ }
39
+ function rowPatterns(names) {
40
+ const patterns = new Map();
41
+ const invalid = new Set();
42
+ for (const name of names) {
43
+ const tokens = name.matchAll(/\[(\d+)(?=\])|\.(\d+)(?=\.|\[|$)/g);
44
+ for (const token of tokens) {
45
+ const previous = token[1] ?? token[2];
46
+ const offset = token.index + 1;
47
+ const prefix = name.slice(0, offset);
48
+ const field = name.slice(offset + previous.length).replace(/\[\d+\]|\.\d+(?=\.|\[|$)/g, '#');
49
+ const evidence = patterns.get(prefix);
50
+ if (!evidence) {
51
+ patterns.set(prefix, { fields: new Set([field]), previous });
52
+ }
53
+ else if (evidence.previous === previous) {
54
+ evidence.fields.add(field);
55
+ }
56
+ else {
57
+ invalid.add(prefix);
58
+ }
59
+ }
60
+ }
61
+ for (const prefix of invalid) {
62
+ patterns.delete(prefix);
63
+ }
64
+ return patterns;
65
+ }
@@ -0,0 +1,16 @@
1
+ import type { NamingIndex } from './algorithm.js';
2
+ export interface ElementNames {
3
+ attributes: Record<string, string>;
4
+ index: number;
5
+ key: string;
6
+ occurrence: number;
7
+ tag: string;
8
+ }
9
+ export declare function applyNames(row: Element, names: readonly ElementNames[]): void;
10
+ export declare function controlNames(row: Element): string[];
11
+ export declare function indexOverlaps(row: Element, names: ReadonlySet<string>, naming: NamingIndex): boolean;
12
+ export declare function namesOverlap(row: Element, names: ReadonlySet<string>, ids: ReadonlySet<string>): boolean;
13
+ export declare function parseNames(value: unknown): ElementNames[] | undefined;
14
+ export declare function readNames(row: Element): ElementNames[];
15
+ export declare function rememberNames(row: Element, names: Set<string>, ids: Set<string>): void;
16
+ export declare function renameRow(row: Element, naming: NamingIndex | undefined, collisions: ReadonlySet<string>, id: string): void;