@procedures/collections 0.12.1 → 0.12.2

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,271 @@
1
+ /**
2
+ * The keys of an ordered list (Graph's split, wave 2, W1): fractional indexing with base-62 keys. A
3
+ * key is a string. Each item of the list keeps one, and the list sorts by it. An item that moves
4
+ * between two others gets a key between theirs, so a move writes one item and no other.
5
+ *
6
+ * - A key has an integer part and a fraction part. The first character of the integer part gives its
7
+ * length. An insertion at an end changes the integer part, so the keys stay short. An insertion
8
+ * between two keys uses the fraction part, which can grow without a limit: the keys never run out,
9
+ * and the list needs no rebalance.
10
+ * - Compare two keys by the code units of the strings (`a < b`), never with `localeCompare`.
11
+ * - Two writers that move items into the same gap at the same time can get the same key. Sort by the
12
+ * key, then by the id of the item, so each reader sees one order.
13
+ *
14
+ * The algorithm is the one of the `fractional-indexing` package of Rocicorp (CC0), after the article
15
+ * "Implementing Fractional Indexing" of David Greenspan.
16
+ */
17
+
18
+ /** The digits of a key, in ascending order of their code units. */
19
+ export const KEY_DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
20
+
21
+ const ZERO = KEY_DIGITS[0]!;
22
+ const LAST = KEY_DIGITS[KEY_DIGITS.length - 1]!;
23
+ /** The smallest integer part. No key comes before it. */
24
+ const SMALLEST_INTEGER = `A${ZERO.repeat(26)}`;
25
+
26
+ function invalid(message: string): RangeError {
27
+ return new RangeError(message);
28
+ }
29
+
30
+ /** The length of the integer part that starts with a head character: a to z give 2 to 27, Z to A give 2 to 27. */
31
+ function integerLength(head: string): number {
32
+ if (head >= "a" && head <= "z") return head.charCodeAt(0) - "a".charCodeAt(0) + 2;
33
+ if (head >= "A" && head <= "Z") return "Z".charCodeAt(0) - head.charCodeAt(0) + 2;
34
+ throw invalid(`A key cannot start with "${head}"`);
35
+ }
36
+
37
+ function integerPart(key: string): string {
38
+ const length = integerLength(key[0] ?? "");
39
+ if (length > key.length) throw invalid(`The key "${key}" is too short for its integer part`);
40
+ return key.slice(0, length);
41
+ }
42
+
43
+ function validateKey(key: string): void {
44
+ if (typeof key !== "string" || key === "") throw invalid("A key is a string that is not empty");
45
+ for (const c of key) if (!KEY_DIGITS.includes(c)) throw invalid(`The key "${key}" has a character that is no digit of a key`);
46
+ if (key === SMALLEST_INTEGER) throw invalid(`The key "${key}" is reserved`);
47
+ const fraction = key.slice(integerPart(key).length);
48
+ if (fraction.endsWith(ZERO)) throw invalid(`The fraction part of the key "${key}" ends with ${ZERO}`);
49
+ }
50
+
51
+ /** A fraction strictly between two fractions. `b` null is the end. Neither one ends with the zero digit. */
52
+ function midpoint(a: string, b: string | null): string {
53
+ if (b !== null) {
54
+ let n = 0;
55
+ while ((a[n] ?? ZERO) === b[n]) n++;
56
+ if (n > 0) return b.slice(0, n) + midpoint(a.slice(n), b.slice(n));
57
+ }
58
+ const digitA = a ? KEY_DIGITS.indexOf(a[0]!) : 0;
59
+ const digitB = b !== null ? KEY_DIGITS.indexOf(b[0]!) : KEY_DIGITS.length;
60
+ if (digitB - digitA > 1) return KEY_DIGITS[Math.round((digitA + digitB) / 2)]!;
61
+ // The first digits are next to each other
62
+ if (b !== null && b.length > 1) return b.slice(0, 1);
63
+ return KEY_DIGITS[digitA]! + midpoint(a.slice(1), null);
64
+ }
65
+
66
+ function incrementInteger(x: string): string | null {
67
+ const [head, ...digits] = x.split("") as [string, ...string[]];
68
+ let carry = true;
69
+ for (let i = digits.length - 1; carry && i >= 0; i--) {
70
+ const d = KEY_DIGITS.indexOf(digits[i]!) + 1;
71
+ if (d === KEY_DIGITS.length) digits[i] = ZERO;
72
+ else {
73
+ digits[i] = KEY_DIGITS[d]!;
74
+ carry = false;
75
+ }
76
+ }
77
+ if (!carry) return head + digits.join("");
78
+ if (head === "Z") return `a${ZERO}`;
79
+ if (head === "z") return null;
80
+ const next = String.fromCharCode(head.charCodeAt(0) + 1);
81
+ if (next > "a") digits.push(ZERO);
82
+ else digits.pop();
83
+ return next + digits.join("");
84
+ }
85
+
86
+ function decrementInteger(x: string): string | null {
87
+ const [head, ...digits] = x.split("") as [string, ...string[]];
88
+ let borrow = true;
89
+ for (let i = digits.length - 1; borrow && i >= 0; i--) {
90
+ const d = KEY_DIGITS.indexOf(digits[i]!) - 1;
91
+ if (d === -1) digits[i] = LAST;
92
+ else {
93
+ digits[i] = KEY_DIGITS[d]!;
94
+ borrow = false;
95
+ }
96
+ }
97
+ if (!borrow) return head + digits.join("");
98
+ if (head === "a") return `Z${LAST}`;
99
+ if (head === "A") return null;
100
+ const next = String.fromCharCode(head.charCodeAt(0) - 1);
101
+ if (next < "Z") digits.push(LAST);
102
+ else digits.pop();
103
+ return next + digits.join("");
104
+ }
105
+
106
+ /**
107
+ * This function gives a key strictly between two keys. Without `prev`, the key comes before `next`.
108
+ * Without `next`, it comes after `prev`. Without both, it gives the first key of a list ("a0").
109
+ *
110
+ * @throws RangeError when a key is not valid, or when `prev` is not before `next`
111
+ *
112
+ * @example
113
+ * ```ts
114
+ * keyBetween(undefined, undefined); // "a0"
115
+ * keyBetween("a0", undefined); // "a1", after a0
116
+ * keyBetween("a0", "a1"); // "a0V"
117
+ * ```
118
+ */
119
+ export function keyBetween(prev: string | null | undefined, next: string | null | undefined): string {
120
+ const a = prev ?? null;
121
+ const b = next ?? null;
122
+ if (a !== null) validateKey(a);
123
+ if (b !== null) validateKey(b);
124
+ if (a !== null && b !== null && a >= b) throw invalid(`The key "${a}" is not before the key "${b}"`);
125
+ if (a === null) {
126
+ if (b === null) return `a${ZERO}`;
127
+ const ib = integerPart(b);
128
+ const fb = b.slice(ib.length);
129
+ if (ib === SMALLEST_INTEGER) return ib + midpoint("", fb);
130
+ if (ib < b) return ib;
131
+ const decremented = decrementInteger(ib);
132
+ if (decremented === null) throw invalid("No key comes before this one");
133
+ return decremented;
134
+ }
135
+ const ia = integerPart(a);
136
+ const fa = a.slice(ia.length);
137
+ if (b === null) {
138
+ const incremented = incrementInteger(ia);
139
+ return incremented === null ? ia + midpoint(fa, null) : incremented;
140
+ }
141
+ const ib = integerPart(b);
142
+ const fb = b.slice(ib.length);
143
+ if (ia === ib) return ia + midpoint(fa, fb);
144
+ const incremented = incrementInteger(ia);
145
+ if (incremented === null) throw invalid("No key comes after this one");
146
+ if (incremented < b) return incremented;
147
+ return ia + midpoint(fa, null);
148
+ }
149
+
150
+ /**
151
+ * This function gives `count` keys in ascending order, strictly between two keys, for example to put
152
+ * several items at one place, or to give keys to the items of a list for the first time.
153
+ *
154
+ * @throws RangeError as `keyBetween`, or when `count` is not an integer of 0 or more
155
+ */
156
+ export function keysBetween(prev: string | null | undefined, next: string | null | undefined, count: number): string[] {
157
+ if (!Number.isInteger(count) || count < 0) throw invalid(`A count of keys is an integer of 0 or more, not ${count}`);
158
+ const a = prev ?? null;
159
+ const b = next ?? null;
160
+ if (count === 0) return [];
161
+ if (count === 1) return [keyBetween(a, b)];
162
+ if (b === null) {
163
+ const keys = [keyBetween(a, null)];
164
+ for (let i = 1; i < count; i++) keys.push(keyBetween(keys[i - 1]!, null));
165
+ return keys;
166
+ }
167
+ if (a === null) {
168
+ const keys = [keyBetween(null, b)];
169
+ for (let i = 1; i < count; i++) keys.push(keyBetween(null, keys[i - 1]!));
170
+ return keys.reverse();
171
+ }
172
+ const half = Math.floor(count / 2);
173
+ const middle = keyBetween(a, b);
174
+ return [...keysBetween(a, middle, half), middle, ...keysBetween(middle, b, count - half - 1)];
175
+ }
176
+
177
+ /** The options of `isValidKey`. */
178
+ export interface KeyCheckOptions {
179
+ /** The longest key that the check accepts. The default is 1024 characters. */
180
+ readonly maxLength?: number;
181
+ }
182
+
183
+ /**
184
+ * This function tells if a value is a valid key, for example a key that a client writes. A key that
185
+ * is longer than `maxLength` is not valid.
186
+ */
187
+ export function isValidKey(key: unknown, options: KeyCheckOptions = {}): key is string {
188
+ if (typeof key !== "string" || key.length > (options.maxLength ?? 1024)) return false;
189
+ try {
190
+ validateKey(key);
191
+ return true;
192
+ } catch {
193
+ return false;
194
+ }
195
+ }
196
+
197
+ /** An item of an ordered list: its id and its key. */
198
+ export interface KeyedItem {
199
+ readonly id: string;
200
+ readonly key: string;
201
+ }
202
+
203
+ /**
204
+ * This function gives the writes of a move: the new key of the item that moves, and new keys for the
205
+ * neighbors that need them. Give the other items of the list in order (by key, then by id), without
206
+ * the item that moves, and the index of the drop from 0 to their number (`dropIndex`).
207
+ *
208
+ * Two writers can give two items one key. A drop between two such items has no key between them, so
209
+ * the helper first gives new keys to the items after the drop that have the key of the item before
210
+ * it. Each write is `{ id, key }`. The writes of the neighbors come first, and the write of the item
211
+ * that moves comes last.
212
+ *
213
+ * @throws RangeError when the index is outside the list, when the list holds the item that moves, or
214
+ * when a key is not valid
215
+ *
216
+ * @example
217
+ * ```ts
218
+ * const index = dropIndex(pointer, others.map(centerOf));
219
+ * for (const { id, key } of keysForDrop(others, index, dragged.id)) await save(id, { rank: key });
220
+ * ```
221
+ */
222
+ export function keysForDrop(items: readonly KeyedItem[], index: number, movingId: string): Array<{ id: string; key: string }> {
223
+ if (!Number.isInteger(index) || index < 0 || index > items.length) throw invalid(`The index ${index} is outside the list of ${items.length} items`);
224
+ if (items.some((item) => item.id === movingId)) throw invalid(`The list holds the item that moves (${movingId})`);
225
+ const prev = items[index - 1]?.key ?? null;
226
+ // The items from the index on that do not come after the item before the drop need new keys
227
+ let end = index;
228
+ while (end < items.length && prev !== null && items[end]!.key <= prev) end++;
229
+ const writes: Array<{ id: string; key: string }> = [];
230
+ if (end > index) {
231
+ const keys = keysBetween(prev, items[end]?.key ?? null, end - index);
232
+ for (let i = index; i < end; i++) writes.push({ id: items[i]!.id, key: keys[i - index]! });
233
+ }
234
+ const next = writes.length > 0 ? writes[0]!.key : (items[index]?.key ?? null);
235
+ writes.push({ id: movingId, key: keyBetween(prev, next) });
236
+ return writes;
237
+ }
238
+
239
+ /** The order of two keys: the code units of the strings, as the keys need (never `localeCompare`). */
240
+ export function compareKeys(a: string, b: string): number {
241
+ return a < b ? -1 : a > b ? 1 : 0;
242
+ }
243
+
244
+ /** A point, for example the center of an item on the screen. */
245
+ export interface Point {
246
+ readonly x: number;
247
+ readonly y: number;
248
+ }
249
+
250
+ /**
251
+ * This function gives the index at which a point goes among the items of a list on the screen, in
252
+ * reading order: the rows from top to bottom, and each row from left to right. It is the index of the
253
+ * first item whose center comes after the point, from 0 to the number of items. A center within
254
+ * `rowTolerance` of the point on the vertical axis is in the row of the point.
255
+ *
256
+ * Give the centers in reading order, the same order as the keys, and without the item that moves.
257
+ *
258
+ * @example
259
+ * ```ts
260
+ * const index = dropIndex(pointer, others.map(centerOf));
261
+ * const key = keyBetween(keys[index - 1], keys[index]);
262
+ * ```
263
+ */
264
+ export function dropIndex(point: Point, centers: readonly Point[], rowTolerance = 24): number {
265
+ for (let i = 0; i < centers.length; i++) {
266
+ const c = centers[i]!;
267
+ if (point.y < c.y - rowTolerance) return i;
268
+ if (Math.abs(point.y - c.y) <= rowTolerance && point.x < c.x) return i;
269
+ }
270
+ return centers.length;
271
+ }