@blueshed/joined 0.3.0 → 0.3.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.
Files changed (109) hide show
  1. package/.claude/skills/joined/reference.md +57 -18
  2. package/docs/design.md +93 -38
  3. package/docs/introduction.md +9 -9
  4. package/docs/light-and-shadow.svg +1 -0
  5. package/docs/links-and-trust.svg +1 -0
  6. package/docs/stories-to-code.svg +2 -1
  7. package/docs/wire-op.svg +1 -0
  8. package/examples/app.css +9 -0
  9. package/examples/cafe/cafe.css +87 -69
  10. package/examples/cafe/generated/staff.elements.ts +7 -2
  11. package/examples/cafe/generated/staff.rules.ts +3 -0
  12. package/examples/cafe/generated/supplies.rules.ts +5 -0
  13. package/examples/cafe/kitchen.css +11 -19
  14. package/examples/cafe/kitchen.ts +6 -2
  15. package/examples/cafe/migrations/002-guard-supplies.ts +15 -0
  16. package/examples/cafe/order.html +2 -1
  17. package/examples/cafe/order.ts +1 -1
  18. package/examples/cafe/staff.json +5 -0
  19. package/examples/cafe/stories.jsonl +4 -2
  20. package/examples/cafe/supplies.html +1 -0
  21. package/examples/cafe/supplies.ts +45 -28
  22. package/examples/cafe/till.ts +14 -10
  23. package/examples/cafe/views.ts +7 -5
  24. package/examples/chart/arches.ts +5 -3
  25. package/examples/chart/chart.css +7 -2
  26. package/examples/desk/desk.css +6 -10
  27. package/examples/desk/generated/elements.ts +1 -1
  28. package/examples/desk/index.html +1 -1
  29. package/examples/desk/lanes.css +21 -19
  30. package/examples/desk/stories.jsonl +1 -1
  31. package/examples/desk/tally.css +1 -1
  32. package/examples/docs.ts +7 -4
  33. package/examples/index.html +16 -7
  34. package/examples/notes/generated/queries.ts +8 -2
  35. package/examples/notes/index.html +1 -1
  36. package/examples/notes/stories.jsonl +3 -0
  37. package/examples/page.ts +9 -2
  38. package/examples/people/links.ts +7 -9
  39. package/examples/people/people.css +1 -1
  40. package/examples/people/view.ts +1 -1
  41. package/examples/trip/generated/elements.ts +1 -1
  42. package/examples/trip/stays.css +1 -1
  43. package/examples/trip/stays.ts +1 -1
  44. package/examples/trips/generated/elements.ts +1 -1
  45. package/examples/trips/trips.css +24 -23
  46. package/examples/welcome.css +41 -33
  47. package/package.json +1 -1
  48. package/src/attachment.ts +17 -2
  49. package/src/board.css +2 -1
  50. package/src/board.ts +4 -4
  51. package/src/cli.ts +14 -2
  52. package/src/compile.ts +255 -77
  53. package/src/definitions.ts +62 -14
  54. package/src/demo.css +2 -5
  55. package/src/draft.ts +10 -4
  56. package/src/drawer.ts +30 -4
  57. package/src/engine.ts +14 -5
  58. package/src/fields.ts +88 -15
  59. package/src/file-value.ts +12 -2
  60. package/src/files.ts +113 -35
  61. package/src/icon-names.ts +4 -0
  62. package/src/keep.ts +16 -3
  63. package/src/map.css +23 -16
  64. package/src/map.ts +3 -3
  65. package/src/mcp.ts +24 -3
  66. package/src/members/group.ts +41 -17
  67. package/src/members/keys.ts +3 -3
  68. package/src/members/panel.css +17 -18
  69. package/src/members/panel.ts +9 -2
  70. package/src/migrate.ts +58 -21
  71. package/src/migrations/005-change-kept.ts +7 -0
  72. package/src/month.css +6 -2
  73. package/src/month.ts +5 -5
  74. package/src/ops.ts +40 -1
  75. package/src/page.css +3 -2
  76. package/src/page.ts +64 -16
  77. package/src/parts.css +178 -86
  78. package/src/parts.ts +60 -20
  79. package/src/plane.css +9 -4
  80. package/src/plane.ts +4 -2
  81. package/src/reading.css +1 -5
  82. package/src/rows.css +2 -21
  83. package/src/rows.ts +123 -39
  84. package/src/server.ts +157 -30
  85. package/src/sheet.ts +4 -2
  86. package/src/slots.css +0 -4
  87. package/src/specs.ts +1 -1
  88. package/src/starter.ts +15 -1
  89. package/src/store.ts +40 -18
  90. package/src/surface.ts +7 -2
  91. package/src/time.ts +2 -0
  92. package/src/timeline.ts +14 -5
  93. package/src/together.ts +15 -17
  94. package/src/tokens.css +12 -3
  95. package/src/tokens.json +38 -7
  96. package/src/tool.ts +6 -7
  97. package/src/upkeep.ts +31 -4
  98. package/src/views.css +8 -9
  99. package/src/views.ts +23 -6
  100. package/src/week.css +1 -2
  101. package/src/week.ts +11 -7
  102. package/src/write.ts +130 -15
  103. package/starter/CHANGELOG.md +8 -0
  104. package/starter/CLAUDE.md +7 -1
  105. package/starter/bunfig +2 -1
  106. package/starter/githooks/pre-commit +13 -0
  107. package/starter/prettierignore +1 -0
  108. package/starter/tests/records.test.ts +40 -0
  109. package/starter/todo.jsonl +0 -0
@@ -9,12 +9,6 @@
9
9
  font: var(--font-row);
10
10
  color: var(--ink);
11
11
  }
12
- :host([hidden]) {
13
- display: none;
14
- }
15
- [hidden] {
16
- display: none !important;
17
- }
18
12
  .bar {
19
13
  display: flex;
20
14
  gap: var(--space-8);
@@ -64,7 +58,7 @@
64
58
  width: max-content;
65
59
  max-width: min(var(--size-said), calc(100% - 2 * var(--space-16)));
66
60
  padding: var(--space-4) var(--space-4) var(--space-4) var(--space-16);
67
- border-radius: 4px;
61
+ border-radius: var(--radius);
68
62
  background: var(--ink);
69
63
  color: var(--card);
70
64
  font: var(--font-small);
@@ -106,6 +100,11 @@
106
100
  min-height: 0;
107
101
  gap: var(--space-10);
108
102
  }
103
+ /* a tab's panel takes no room of its own over and under what it holds (Web Awesome's is a big space each way):
104
+ the group's own gap is all there is between the tabs, the invite and the way out */
105
+ wa-tab-panel {
106
+ --padding: var(--space-8) 0 0;
107
+ }
109
108
  wa-tab-group.alone::part(nav) {
110
109
  display: none;
111
110
  }
@@ -134,7 +133,7 @@
134
133
  position: relative;
135
134
  display: flex;
136
135
  align-items: center;
137
- gap: 8px;
136
+ gap: var(--space-8);
138
137
  min-height: 36px;
139
138
  }
140
139
  /* a line for each step in, to who invited them */
@@ -151,17 +150,17 @@
151
150
  li input {
152
151
  flex: 1;
153
152
  min-width: 0;
154
- margin-left: 8px;
153
+ margin-left: var(--space-8);
155
154
  overflow: hidden;
156
155
  text-overflow: ellipsis;
157
156
  white-space: nowrap;
158
157
  }
159
158
  /* your own name, changed where it is: a field, 16px (src/parts.css), its edge shown only when touched */
160
159
  li input {
161
- padding: 2px 6px;
160
+ padding: 2px var(--space-6);
162
161
  margin-left: 2px;
163
162
  border: 1px solid transparent;
164
- border-radius: 4px;
163
+ border-radius: var(--radius);
165
164
  background: none;
166
165
  color: inherit;
167
166
  }
@@ -170,7 +169,7 @@
170
169
  border-color: var(--control-edge);
171
170
  }
172
171
  .agents li svg.icon {
173
- margin-left: 8px;
172
+ margin-left: var(--space-8);
174
173
  color: var(--muted);
175
174
  }
176
175
  .tag {
@@ -178,18 +177,18 @@
178
177
  line-height: 16px;
179
178
  color: var(--muted);
180
179
  border: 1px solid var(--edge);
181
- border-radius: 999px;
182
- padding: 0 6px;
180
+ border-radius: var(--radius-pill);
181
+ padding: 0 var(--space-6);
183
182
  }
184
183
  form {
185
184
  display: flex;
186
- gap: 8px;
185
+ gap: var(--space-8);
187
186
  margin: 0;
188
187
  }
189
188
  .people form,
190
189
  .agents form {
191
- padding-top: 10px;
192
- margin-top: 6px;
190
+ padding-top: var(--space-10);
191
+ margin-top: var(--space-6);
193
192
  border-top: 1px solid var(--line);
194
193
  }
195
194
  form wa-input {
@@ -213,7 +212,7 @@
213
212
  min-width: 12rem;
214
213
  padding: var(--space-4);
215
214
  border: 1px solid var(--edge);
216
- border-radius: 4px;
215
+ border-radius: var(--radius);
217
216
  }
218
217
  svg.icon {
219
218
  flex: none;
@@ -266,8 +266,15 @@ class MembersPanel extends HTMLElement {
266
266
  : this.#act.kind === "read-only"
267
267
  ? `Make ${them.name} read-only`
268
268
  : `Give ${them.name} back what they could do`;
269
- asked.querySelector("h2")!.textContent = `${does}?`;
270
- asked.querySelector("p")!.textContent = consequences(this.#act.kind, them, members);
269
+ // its title what will happen, its line what follows from it (a modal states: its buttons ask)
270
+ const will =
271
+ this.#act.kind === "removed"
272
+ ? `${them.name} will be removed.`
273
+ : this.#act.kind === "read-only"
274
+ ? `${them.name} will be made read-only.`
275
+ : `${them.name} gets back what they could do.`;
276
+ asked.querySelector("h2")!.textContent = will;
277
+ asked.querySelector("p")!.textContent = consequences(this.#act.kind, them, members).replace(`${will} `, "");
271
278
  why.hidden = this.#act.kind === "restored";
272
279
  yes.replaceChildren(icon(MARKS[this.#act.kind]), does);
273
280
  yes.className = this.#act.kind === "restored" ? "act ink" : "act danger";
package/src/migrate.ts CHANGED
@@ -129,8 +129,12 @@ export function applyChange(state: State, c: Change): State {
129
129
  };
130
130
  if (c.change === "createTable") (free(c.key), (next[c.key] = structuredClone(c.table)));
131
131
  else if (c.change === "dropTable") (there(c.key), delete next[c.key]);
132
- else if (c.change === "renameTable") (free(c.to), (next[c.to] = there(c.key)), delete next[c.key]);
133
- else if (c.change === "guardTable") (there(c.key), (next[c.key] = structuredClone(c.table)));
132
+ else if (c.change === "renameTable") {
133
+ (free(c.to), (next[c.to] = there(c.key)), delete next[c.key]);
134
+ // what links to it links to it by its new name
135
+ for (const t of Object.values(next))
136
+ for (const d of Object.values(t.columns)) if (d.to?.table === c.key) d.to.table = c.to;
137
+ } else if (c.change === "guardTable") (there(c.key), (next[c.key] = structuredClone(c.table)));
134
138
  else {
135
139
  const t = there(c.key);
136
140
  if ((c.change === "addColumn") === c.column in t.columns)
@@ -138,11 +142,27 @@ export function applyChange(state: State, c: Change): State {
138
142
  `${c.change}: ${c.key}.${c.column} ${c.change === "addColumn" ? "is there already" : "isn't there"}`,
139
143
  );
140
144
  if (c.change === "addColumn") t.columns[c.column] = { ...c.def };
141
- else if (c.change === "dropColumn") delete t.columns[c.column];
142
- else {
145
+ else if (c.change === "dropColumn") {
146
+ delete t.columns[c.column];
147
+ // a unique set it's in goes with it, as its index does (and the first's words, `once`, with that); an add
148
+ // needs it no longer
149
+ if (t.unique?.[0]?.includes(c.column)) delete t.once;
150
+ const unique = t.unique?.filter((u) => !u.includes(c.column));
151
+ if (unique?.length) t.unique = unique;
152
+ else delete t.unique;
153
+ const needs = t.needs?.columns.filter((x) => x !== c.column);
154
+ if (needs?.length) t.needs = { ...t.needs!, columns: needs };
155
+ else delete t.needs;
156
+ } else {
143
157
  if (c.to in t.columns) throw new Error(`renameColumn: ${c.key}.${c.to} is there already`);
144
- t.columns = Object.fromEntries(Object.entries(t.columns).map(([k, d]) => [k === c.column ? c.to : k, d]));
145
- if (t.unique) t.unique = t.unique.map((u) => u.map((x) => (x === c.column ? c.to : x)));
158
+ const renamed = (x: string) => (x === c.column ? c.to : x);
159
+ // and the words that name its value written, `{column}`
160
+ const said = (s: string) => s.replaceAll(`{${c.column}}`, `{${c.to}}`);
161
+ t.columns = Object.fromEntries(Object.entries(t.columns).map(([k, d]) => [renamed(k), d]));
162
+ for (const d of Object.values(t.columns)) if (d.to) d.to.said = said(d.to.said);
163
+ if (t.unique) t.unique = t.unique.map((u) => u.map(renamed));
164
+ if (t.needs) t.needs = { columns: t.needs.columns.map(renamed), said: said(t.needs.said) };
165
+ if (t.once) t.once = said(t.once);
146
166
  }
147
167
  }
148
168
  return next;
@@ -214,7 +234,13 @@ export function diff(state: State, want: State): { changes: Change[]; byHand: st
214
234
  if (!same(was.unique ?? [], t.unique ?? []))
215
235
  byHand.push(`${key}: unique ${JSON.stringify(t.unique ?? [])}, was ${JSON.stringify(was.unique ?? [])}`);
216
236
  }
217
- for (const key of Object.keys(state)) if (!(key in want)) changes.push({ change: "dropTable", key });
237
+ const gone = Object.keys(state).filter((key) => !(key in want)),
238
+ made = Object.keys(want).filter((key) => !(key in state));
239
+ for (const key of gone) changes.push({ change: "dropTable", key });
240
+ if (gone.length && made.length)
241
+ byHand.push(
242
+ `${gone.join(", ")} gone and ${made.join(", ")} new: if one is the other renamed, make it renameTable (a drop loses its rows)`,
243
+ );
218
244
  return { changes, byHand };
219
245
  }
220
246
 
@@ -368,6 +394,9 @@ export const dropTriggers = async (db: Engine, like: string) => {
368
394
  for (const { name, tbl } of found)
369
395
  await db.run(`DROP TRIGGER ${q(name)}${db.dialect === "postgres" ? ` ON ${q(tbl)}` : ""}`);
370
396
  };
397
+ /** Whether a row being inserted is an add, the one its table's sequence has just given out: a document brought in (a
398
+ * seed) has its own, and an item an undo puts back the one it had. */
399
+ export const isAdd = (table: string) => `NEW.id = (SELECT last FROM ${SEQUENCES} WHERE collection = '${table}')`;
371
400
  /** A table's guards that a CHECK can't say, as its triggers: an add without what it needs (an add: the row its
372
401
  * sequence has just given out); a link to a row that
373
402
  * isn't there; a unique set written again. Each refused in its words, the first that says so. */
@@ -380,9 +409,8 @@ async function guardWith(db: Engine, key: string, t: Table | undefined) {
380
409
  ? [[`NEW.${q(c)} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM ${q(d.to.table)} WHERE id = NEW.${q(c)})`, d.to.said]]
381
410
  : [],
382
411
  );
383
- // an add is the row given the table's next id: a document brought in (a seed) has its own, and an item an undo
384
- // puts back the one it had; those are held to their links by the foreign keys, at commit
385
- const add = `NEW.id = (SELECT last FROM ${SEQUENCES} WHERE collection = '${key}')`;
412
+ // (what isn't an add is held to its links by the foreign keys, at commit)
413
+ const add = isAdd(key);
386
414
  const insert: [string, string][] = [];
387
415
  if (t.needs)
388
416
  insert.push([`${add} AND (${t.needs.columns.map((c) => `NEW.${q(c)} IS NULL`).join(" OR ")})`, t.needs.said]);
@@ -448,16 +476,18 @@ export async function guardHeld(db: Engine, key: string, t: Table | undefined) {
448
476
  }
449
477
 
450
478
  /** What a table's CHECKs and foreign keys say: whether it's strict, what each column's value is, whether it may be
451
- * empty, and the table it links to. */
479
+ * empty, and the table it links to; its columns in no order, as neither the CHECKs nor the keys have one. */
452
480
  const checks = (t: Table) => [
453
481
  !!t.strict,
454
- Object.entries(t.columns).map(([c, d]) => [
455
- c,
456
- d.is ?? null,
457
- !!d.nullable,
458
- d.to?.table ?? null,
459
- d.to?.onDelete ?? null,
460
- ]),
482
+ Object.entries(t.columns)
483
+ .map(([c, d]) => [
484
+ c,
485
+ d.is ? [d.is.type, d.is.form ?? null, d.is.said] : null,
486
+ !!d.nullable,
487
+ d.to?.table ?? null,
488
+ d.to?.onDelete ?? null,
489
+ ])
490
+ .sort(([a], [b]) => (String(a) < String(b) ? -1 : 1)),
461
491
  ];
462
492
 
463
493
  /** One change made on the database, the tables before it and after: its table's triggers made again from what it
@@ -503,6 +533,9 @@ async function make(db: Engine, c: Change, before: State, after: State) {
503
533
  } else if (c.change === "renameTable") {
504
534
  await db.run(`ALTER TABLE ${q(c.key)} RENAME TO ${q(c.to)}`);
505
535
  await guardWith(db, c.to, after[c.to]);
536
+ // the guards of what links to it made again, naming it by its new name (Postgres's triggers named it as it was)
537
+ for (const [key, t] of Object.entries(after))
538
+ if (key !== c.to && Object.values(t.columns).some((d) => d.to?.table === c.to)) await guardWith(db, key, t);
506
539
  for (const u of await uniquesOf(db, c.to))
507
540
  (await db.run(`DROP INDEX ${q(u.name)}`), await makeUnique(db, c.to, u.columns));
508
541
  await db.run(`UPDATE ${SEQUENCES} SET collection = ? WHERE collection = ?`, [c.to, c.key]);
@@ -526,8 +559,8 @@ async function make(db: Engine, c: Change, before: State, after: State) {
526
559
  }
527
560
 
528
561
  /** An app's migrations not yet run here, run in order, each with its `up` and its record in one transaction; the
529
- * ids it ran. A database from before 0.8 has delta's names for joined's two tables: they're renamed,
530
- * and what they hold is kept. */
562
+ * ids it ran. Another process migrating the store at once waits for it, and finds what it ran done. A database
563
+ * from before 0.8 has delta's names for joined's two tables: they're renamed, and what they hold is kept. */
531
564
  export async function migrate(db: Engine, app: string, list: Migration[]): Promise<string[]> {
532
565
  await db.transaction(async () => {
533
566
  for (const [was, now] of [
@@ -554,8 +587,11 @@ export async function migrate(db: Engine, app: string, list: Migration[]): Promi
554
587
  // transaction), and checked whole before it commits
555
588
  const rebuilds = db.dialect === "sqlite" && m.changes.some((c) => c.change === "guardTable");
556
589
  if (rebuilds) await db.run("PRAGMA foreign_keys = OFF");
590
+ let made = false;
557
591
  try {
558
592
  await db.transaction(async () => {
593
+ // another process may have run it since this one looked (one transaction at a time, whoever's: src/engine.ts)
594
+ if (await db.query(`SELECT 1 FROM ${RAN} WHERE app = ? AND id = ?`).get(app, m.id)) return;
559
595
  // a table made again beside itself is put in its place by commit, its links whole again by then
560
596
  await db.defer();
561
597
  let s = before;
@@ -582,13 +618,14 @@ export async function migrate(db: Engine, app: string, list: Migration[]): Promi
582
618
  if (loose) throw new Error(`${loose.table} links to no row of ${loose.parent}`);
583
619
  }
584
620
  await db.run(`INSERT INTO ${RAN} (app, id, ran_at) VALUES (?, ?, ?)`, [app, m.id, new Date().toISOString()]);
621
+ made = true;
585
622
  });
586
623
  } catch (e) {
587
624
  throw new Error(`${app}'s migration ${m.id} failed, and was rolled back: ${(e as Error).message}`);
588
625
  } finally {
589
626
  if (rebuilds) await db.run("PRAGMA foreign_keys = ON");
590
627
  }
591
- ran.push(m.id);
628
+ if (made) ran.push(m.id);
592
629
  }
593
630
  return ran;
594
631
  }
@@ -0,0 +1,7 @@
1
+ // A change row's kept write: the id a page gave a write it kept while away (src/outbox.ts), on the row of the change
2
+ // it made, so the same write sent again (its answer lost, or two tabs sending what one device kept) is answered done
3
+ // and not made twice. A row from before has none. Written by hand, as joined's code is; never changed once it has run
4
+ // anywhere.
5
+ import { addColumn } from "../migrate.ts";
6
+
7
+ export const changes = [addColumn("changes", "kept", "text?")];
package/src/month.css CHANGED
@@ -31,11 +31,12 @@
31
31
  border-left: 0;
32
32
  }
33
33
  .day[away] > .n {
34
- color: var(--edge);
34
+ color: var(--muted);
35
35
  }
36
36
  .day[over] {
37
37
  background: var(--card-hover);
38
- box-shadow: inset 0 0 0 1px var(--accent);
38
+ outline: 1px solid var(--accent);
39
+ outline-offset: -1px;
39
40
  }
40
41
  /* a day's number: a tap marks the day. Today's is ringed; the marked day's filled */
41
42
  .n {
@@ -109,8 +110,11 @@
109
110
  align-items: center;
110
111
  padding: var(--space-4) 0;
111
112
  }
113
+ /* the day's number is what's tapped: a finger, as tall as the day */
112
114
  .n {
113
115
  align-self: center;
116
+ min-width: var(--size-finger);
117
+ height: var(--size-finger);
114
118
  }
115
119
  .day > .item {
116
120
  display: none;
package/src/month.ts CHANGED
@@ -23,7 +23,7 @@ export class JMonth extends Reading {
23
23
  #grid = el("div", { className: "days", role: "grid" });
24
24
  #under = el("section", { className: "that-day" });
25
25
  #heading = el("h4");
26
- #adding = el("button", { type: "button", className: "act small adding" });
26
+ #adding = el("button", { type: "button", className: "act small adding", part: "add" });
27
27
  #list = el("ul");
28
28
  #days = new Map<string, { shows: string; el: HTMLElement }>();
29
29
  #rows = new Map<string, { shows: string; el: HTMLElement }>();
@@ -54,7 +54,7 @@ export class JMonth extends Reading {
54
54
  to.setUTCDate(Math.min(d.getUTCDate(), last));
55
55
  this.day = to.getTime() / DAY;
56
56
  };
57
- const today = el("button", { type: "button", className: "act small today" }, "Today");
57
+ const today = el("button", { type: "button", className: "act small today", part: "today" }, "Today");
58
58
  today.addEventListener("click", () => (this.day = dayOf(now())));
59
59
  this.#adding.addEventListener("click", () => {
60
60
  const f = this.when;
@@ -64,7 +64,7 @@ export class JMonth extends Reading {
64
64
  this.root.append(
65
65
  el(
66
66
  "header",
67
- { className: "head" },
67
+ { className: "head", part: "head" },
68
68
  this.#name,
69
69
  today,
70
70
  iconButton("back", "The month before", step(-1)),
@@ -108,7 +108,7 @@ export class JMonth extends Reading {
108
108
  its.map((it) => [it.key, this.named(it), it.data[f.name], this.opened(it), moves(it)]),
109
109
  ]),
110
110
  make: () => {
111
- const cell = el("div", { className: "day", role: "gridcell" });
111
+ const cell = el("div", { className: "day", part: "day", role: "gridcell" });
112
112
  cell.dataset.day = String(d);
113
113
  cell.toggleAttribute("away", away);
114
114
  const n = el("button", {
@@ -151,7 +151,7 @@ export class JMonth extends Reading {
151
151
  at = w.slice(11, 16),
152
152
  b = el(
153
153
  "button",
154
- { type: "button", className: "item", title: this.named(it) },
154
+ { type: "button", className: "item", part: "item", title: this.named(it) },
155
155
  ...(at && at !== "00:00" ? [el("span", { className: "at" }, at), " "] : []),
156
156
  this.named(it),
157
157
  );
package/src/ops.ts CHANGED
@@ -3,6 +3,13 @@
3
3
  // /events/3/people/2 is the link to 2 (and /events/3/people/- one added).
4
4
 
5
5
  export type Op = { op: "add" | "replace" | "remove"; path: string; value?: any };
6
+ /** Whether what's sent is an op: an add, a replace or a remove, at a path (its value is the write's to refuse). */
7
+ export const isOp = (o: any): o is Op =>
8
+ typeof o === "object" && o !== null && ["add", "replace", "remove"].includes(o.op) && typeof o.path === "string";
9
+ /** What's said of ops that aren't. */
10
+ export const OPS = "ops are each an add, a replace or a remove, at a path";
11
+ /** The most a message may be, in bytes: a page's, over its socket, or an agent's, at the MCP door. */
12
+ export const MESSAGE = 1 << 20;
6
13
 
7
14
  /** A field's type, read off what the stories give it: a string, or one read off its form (a date-time, a time
8
15
  * zone, an instant, a duration, a place); a boolean; a number, an integer or a decimal; or a list of ids. */
@@ -30,7 +37,7 @@ export const attribute = (type: Type | undefined, value: unknown): string | null
30
37
  ? value === true
31
38
  ? ""
32
39
  : null
33
- : value === undefined || value === null
40
+ : value === undefined || value === null || (Array.isArray(value) && !value.length)
34
41
  ? null
35
42
  : Array.isArray(value)
36
43
  ? value.join(" ")
@@ -59,6 +66,38 @@ export const NTH = /^\$([1-9]\d*)$/;
59
66
  /** Whether a part's document is named by an add before it in its write (`board:$1`): no page holds it yet. */
60
67
  export const madeBy = (doc: string) => NTH.test(docParts(doc).key ?? "");
61
68
 
69
+ /** A document's collections as a write's "$n" reads them: each one's links (a field, what it's to), and whether it's
70
+ * the document's own fields (hello's). */
71
+ export type Linked = Record<string, { links: Record<string, unknown>; own?: boolean }>;
72
+ /** An op's value with each "$n" where a link is made what `nth` says (the id the write's nth add was given): in an
73
+ * add's item, a link's value; a link replaced, or an id added to a list, its value. Anywhere else "$n" is words, and
74
+ * kept as it's given. */
75
+ export function linksNamed(o: Op, collections: Linked | undefined, nth: (n: number, v: string) => unknown): Op {
76
+ if (!("value" in o)) return o;
77
+ // (a document's own field, /greeting, is its own collection's one item's)
78
+ const own = Object.entries(collections ?? {}).find(([, c]) => c.own)?.[0];
79
+ const { coll, key, field, link } = parts(own && /^\/[a-z][a-z0-9-]*$/.test(o.path) ? `/${own}/1${o.path}` : o.path);
80
+ const links = collections?.[coll]?.links ?? {};
81
+ const read = (v: unknown): unknown => {
82
+ const n = typeof v === "string" ? NTH.exec(v)?.[1] : undefined;
83
+ return n ? nth(Number(n), v as string) : Array.isArray(v) ? v.map(read) : v;
84
+ };
85
+ const isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
86
+ // an object's fields are each named for both (terms.days)
87
+ const fields = (v: Record<string, unknown>, at = ""): Record<string, unknown> =>
88
+ Object.fromEntries(
89
+ Object.entries(v).map(([f, x]) => [
90
+ f,
91
+ `${at}${f}` in links ? read(x) : !at && isObject(x) ? fields(x, `${f}.`) : x,
92
+ ]),
93
+ );
94
+ // an add's item, each of its fields; else a field, or an id added to its list
95
+ if (field === undefined) return key === "-" && isObject(o.value) ? { ...o, value: fields(o.value) } : o;
96
+ const named = link !== undefined && /^[a-z]/.test(link) ? `${field}.${link}` : field;
97
+ if (named in links) return { ...o, value: read(o.value) };
98
+ return isObject(o.value) && link === undefined ? { ...o, value: fields(o.value, `${field}.`) } : o;
99
+ }
100
+
62
101
  /** An op's path, in its parts; `link` is an id in a list of ids, and `more` anything past it, which no op may have. */
63
102
  export function parts(path: string) {
64
103
  const [, coll = "", key = "", field, link, ...more] = path.split("/");
package/src/page.css CHANGED
@@ -12,7 +12,8 @@
12
12
  font: var(--font-body);
13
13
  max-width: 72rem;
14
14
  margin: 0 auto;
15
- padding: 0 var(--gutter) var(--space-48);
15
+ /* room at its top, whatever it opens with: the brand, a band, or nothing of joined's */
16
+ padding: var(--space-20) var(--gutter) var(--space-48);
16
17
  color: var(--ink);
17
18
  background: var(--paper);
18
19
  }
@@ -25,7 +26,7 @@
25
26
  display: inline-flex;
26
27
  align-items: center;
27
28
  gap: var(--space-8);
28
- margin: var(--space-20) 0 var(--space-24);
29
+ margin: 0 0 var(--space-24);
29
30
  color: var(--ink);
30
31
  font: var(--font-name);
31
32
  text-decoration: none;
package/src/page.ts CHANGED
@@ -175,10 +175,11 @@ document.addEventListener("ops", (e) => {
175
175
  if (writes && (!writes.length || off)) return answer?.(off ? `${off.doc} isn't on this page` : "a write of nothing");
176
176
  if (!isOpen() && (writes ?? [{ ops }]).every((p) => adds(p.ops)) && (writes || docs.has(doc)))
177
177
  return (keep(writes ? { writes } : { doc, ops, why }), answer?.());
178
- // landed, its sender is told the version it made, from the write's own answer (a page's undo keeps it: `undo`)
178
+ // landed, its sender is told the version it made, from the write's own answer (a page's undo keeps it: `undo`); a
179
+ // sender a removal has taken off the page by then, the document
179
180
  const told: Answered = (why, version) => {
180
181
  if (why === undefined && version !== undefined)
181
- e.target!.dispatchEvent(
182
+ ((e.target as Node).isConnected ? e.target! : document).dispatchEvent(
182
183
  new CustomEvent("landed", { bubbles: true, composed: true, detail: { doc: doc ?? writes![0]!.doc, version } }),
183
184
  );
184
185
  answer?.(why);
@@ -221,15 +222,21 @@ function send(doc: string | undefined, m: object, answer: Answered = () => {}) {
221
222
  // a document subscribed to again (the page back from away) says the version it has, to be sent only what's since;
222
223
  // answered, it's held on this socket, and what was kept for it is sent
223
224
  const subscribe = (s: WebSocket, doc: string) => {
224
- const had = document.body.dataset[versionKey(doc)];
225
225
  socket.sent.set(++socket.id, {
226
226
  answer: (why) => why === undefined && s === socket.ws && (socket.ready.add(doc), flush()),
227
227
  });
228
- s.send(JSON.stringify({ subscribe: doc, id: socket.id, ...(had ? { since: Number(had) } : {}) }));
228
+ s.send(JSON.stringify({ subscribe: doc, id: socket.id, ...since(doc) }));
229
+ };
230
+ /** The version the page has of a document, as a subscribe says it: none, and it's sent whole. */
231
+ const since = (doc: string) => {
232
+ const had = document.body.dataset[versionKey(doc)];
233
+ return had ? { since: Number(had) } : {};
229
234
  };
230
235
 
231
236
  /** What was kept while the page was away, sent now it's back: oldest first, each once its documents are held again;
232
- * the signal gone again, the rest wait. One refused is let go, and said. */
237
+ * the signal gone again, the rest wait. One refused is let go, and said. Each is sent with its own id (`kept`), so one
238
+ * the server made already (its answer lost as the signal went, or sent by another tab from the same storage) is
239
+ * answered done, not made twice. */
233
240
  async function flush() {
234
241
  // (a document the write makes, board:$1, is held by no page until it's made)
235
242
  const ready = (k: Kept) => (k.writes?.map((p) => p.doc) ?? [k.doc!]).every((d) => socket.ready.has(d) || madeBy(d));
@@ -238,7 +245,9 @@ async function flush() {
238
245
  try {
239
246
  for (let k = waiting().find(ready); k && isOpen(); k = waiting().find(ready)) {
240
247
  const { id, doc, ops, why, writes } = k;
241
- const refused = await new Promise<Answer>((answer) => send(doc, writes ? { writes } : { ops, why }, answer));
248
+ const refused = await new Promise<Answer>((answer) =>
249
+ send(doc, { ...(writes ? { writes } : { ops, why }), kept: id }, answer),
250
+ );
242
251
  if (refused && !isOpen()) break;
243
252
  sent(id);
244
253
  if (refused) toast(`A change made without signal wasn't kept: ${refused}`, { hold: true });
@@ -371,7 +380,8 @@ async function gone(code: number) {
371
380
  }
372
381
 
373
382
  /** A socket the browser calls open, asked whether it is: a subscribe to a document it holds, with id 0, which the
374
- * server answers done. Unanswered in time, it's let go. */
383
+ * server answers done; with the version the page has, as a page back from away asks, so it's sent only what it
384
+ * missed while asleep (nothing, mostly), never the document whole. Unanswered in time, it's let go. */
375
385
  function stillThere(s: WebSocket) {
376
386
  const [doc] = docs.keys();
377
387
  if (socket.asked || !doc) return;
@@ -379,9 +389,7 @@ function stillThere(s: WebSocket) {
379
389
  ((s.onclose = s.onmessage = null), s.close());
380
390
  gone(1006);
381
391
  }, answerIn());
382
- // (with the version it has: sent only what it missed, and told afresh what it may do, which answers it)
383
- const had = document.body.dataset[versionKey(doc)];
384
- s.send(JSON.stringify({ subscribe: doc, id: 0, ...(had ? { since: Number(had) } : {}) }));
392
+ s.send(JSON.stringify({ subscribe: doc, id: 0, ...since(doc) }));
385
393
  }
386
394
 
387
395
  /** The socket again, now: when it's time, or as soon as the phone wakes or the network comes back; one that
@@ -432,9 +440,7 @@ function apply(held: Map<string, Held>, o: Op): Element | undefined {
432
440
  * or, with no order, last. */
433
441
  function placed(h: Held, el: Element) {
434
442
  if (!h.order) return void (el.parentNode !== h.el && h.el.append(el));
435
- // without one, an item ranks by its key
436
- const at = (e: Element) =>
437
- [Number(e.getAttribute(h.order!) ?? e.getAttribute("key")), Number(e.getAttribute("key"))] as const;
443
+ const at = (e: Element) => rankOf(h, e);
438
444
  const [rank, key] = at(el);
439
445
  const after = [...h.items.values()].find((e) => {
440
446
  if (e === el || e.parentNode !== h.el) return false;
@@ -446,20 +452,62 @@ function placed(h: Held, el: Element) {
446
452
  h.el.insertBefore(el, after ?? null);
447
453
  }
448
454
 
455
+ /** Where an item ranks in its collection's order: by the field (without one, by its key), then by its key. */
456
+ const rankOf = (h: Held, el: Element) =>
457
+ [Number(el.getAttribute(h.order!) ?? el.getAttribute("key")), Number(el.getAttribute("key"))] as const;
458
+
459
+ /** A collection's items all put in its order, each one's rank read once: the longest run of them in order already
460
+ * stays where it is, and only the rest are moved, each before the next that stays. */
461
+ function inOrder(h: Held) {
462
+ const want = [...h.items.values()]
463
+ .map((el) => ({ el, at: rankOf(h, el) }))
464
+ .sort((a, b) => a.at[0] - b.at[0] || a.at[1] - b.at[1])
465
+ .map(({ el }) => el);
466
+ const now = new Map([...h.el.children].map((el, i) => [el, i]));
467
+ // the longest run: for each length, the item one so long ends with (the earliest on the page), and for each item the
468
+ // one before it in its run
469
+ const ends: Element[] = [],
470
+ before = new Map<Element, Element | undefined>();
471
+ for (const el of want) {
472
+ const here = now.get(el);
473
+ if (here === undefined) continue;
474
+ let from = 0,
475
+ to = ends.length;
476
+ while (from < to) {
477
+ const mid = (from + to) >> 1;
478
+ if (now.get(ends[mid]!)! < here) from = mid + 1;
479
+ else to = mid;
480
+ }
481
+ before.set(el, ends[from - 1]);
482
+ ends[from] = el;
483
+ }
484
+ const stays = new Set<Element>();
485
+ for (let el = ends.at(-1); el; el = before.get(el)) stays.add(el);
486
+ let moved: Element[] = [];
487
+ for (const el of want)
488
+ if (!stays.has(el)) moved.push(el);
489
+ else {
490
+ for (const m of moved) h.el.insertBefore(m, el);
491
+ moved = [];
492
+ }
493
+ for (const m of moved) h.el.append(m);
494
+ }
495
+
449
496
  /** A collection, whole, as the document has it: each item kept by key and changed only where it
450
497
  * differs, those gone taken away, and those new added. */
451
498
  function whole(h: Held, items: Record<string, unknown>[]) {
452
499
  const gone = new Set(h.items.keys());
453
500
  for (const item of items) {
454
501
  const el = h.items.get(String(item.id));
455
- if (!el) placed(h, element(h, item));
502
+ if (el) for (const [field, type] of Object.entries(h.fields)) set(el, type, field, valueAt(item, field));
456
503
  else {
457
- for (const [field, type] of Object.entries(h.fields)) set(el, type, field, valueAt(item, field));
458
- if (h.order) placed(h, el);
504
+ const made = element(h, item);
505
+ if (!h.order) placed(h, made);
459
506
  }
460
507
  gone.delete(String(item.id));
461
508
  }
462
509
  for (const key of gone) (h.items.get(key)!.remove(), h.items.delete(key));
510
+ if (h.order) inOrder(h);
463
511
  }
464
512
 
465
513
  function element({ tag, fields, items, may }: Held, item: Record<string, unknown>) {