@connextar/house 0.23.1 → 0.24.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 (186) hide show
  1. package/README.md +55 -13
  2. package/dist/analytics/browser.d.ts +1 -0
  3. package/dist/analytics/browser.d.ts.map +1 -1
  4. package/dist/analytics/browser.js +22 -5
  5. package/dist/analytics/browser.js.map +1 -1
  6. package/dist/analytics/config.d.ts +5 -0
  7. package/dist/analytics/config.d.ts.map +1 -1
  8. package/dist/analytics/config.js +4 -1
  9. package/dist/analytics/config.js.map +1 -1
  10. package/dist/analytics/posthog-extensions.d.ts +19 -0
  11. package/dist/analytics/posthog-extensions.d.ts.map +1 -0
  12. package/dist/analytics/posthog-extensions.js +19 -0
  13. package/dist/analytics/posthog-extensions.js.map +1 -0
  14. package/dist/analytics/react.d.ts.map +1 -1
  15. package/dist/analytics/react.js +4 -2
  16. package/dist/analytics/react.js.map +1 -1
  17. package/dist/analytics/redact.d.ts.map +1 -1
  18. package/dist/analytics/redact.js +6 -1
  19. package/dist/analytics/redact.js.map +1 -1
  20. package/dist/house.css +19 -0
  21. package/package.json +17 -3
  22. package/src/account/data-contract.ts +112 -0
  23. package/src/account/index.ts +11 -0
  24. package/src/admin/access.ts +267 -0
  25. package/src/admin/audit.ts +238 -0
  26. package/src/admin/bootstrap.ts +220 -0
  27. package/src/admin/client-index.ts +19 -0
  28. package/src/admin/client.tsx +187 -0
  29. package/src/admin/index.ts +91 -0
  30. package/src/admin/proof.ts +155 -0
  31. package/src/admin/second-factor-index.ts +16 -0
  32. package/src/admin/second-factor.ts +403 -0
  33. package/src/admin/testing-index.ts +13 -0
  34. package/src/admin/testing.ts +299 -0
  35. package/src/admin/view-as.ts +511 -0
  36. package/src/ai/config-index.ts +40 -0
  37. package/src/ai/config.ts +176 -0
  38. package/src/ai/images.ts +18 -0
  39. package/src/ai/index.ts +21 -0
  40. package/src/ai/pricing.ts +107 -0
  41. package/src/ai/provider.ts +403 -0
  42. package/src/analytics/browser.ts +400 -0
  43. package/src/analytics/client-index.ts +12 -0
  44. package/src/analytics/config.ts +89 -0
  45. package/src/analytics/index.ts +17 -0
  46. package/src/analytics/ingest.ts +81 -0
  47. package/src/analytics/posthog-extensions.ts +19 -0
  48. package/src/analytics/react-index.ts +16 -0
  49. package/src/analytics/react.tsx +241 -0
  50. package/src/analytics/redact.ts +146 -0
  51. package/src/analytics/server-index.ts +17 -0
  52. package/src/analytics/server.ts +277 -0
  53. package/src/auth/index.ts +30 -0
  54. package/src/auth/second-factor-index.ts +16 -0
  55. package/src/auth/second-factor-next.ts +136 -0
  56. package/src/auth/second-factor-routes.ts +40 -0
  57. package/src/auth/second-factor.ts +226 -0
  58. package/src/auth/step-up-client-index.ts +13 -0
  59. package/src/auth/step-up-client.ts +23 -0
  60. package/src/auth/step-up-index.ts +19 -0
  61. package/src/auth/step-up-routes.ts +99 -0
  62. package/src/auth/step-up.ts +432 -0
  63. package/src/auth/two-factor-policy.ts +112 -0
  64. package/src/changelog/changelog.tsx +367 -0
  65. package/src/changelog/index.ts +12 -0
  66. package/src/editor/block-handle.tsx +312 -0
  67. package/src/editor/blocks.ts +169 -0
  68. package/src/editor/bubble-toolbar.tsx +208 -0
  69. package/src/editor/collapsible.ts +159 -0
  70. package/src/editor/content-index.ts +1 -0
  71. package/src/editor/content.tsx +343 -0
  72. package/src/editor/editor.tsx +333 -0
  73. package/src/editor/emoji-index.ts +1 -0
  74. package/src/editor/emoji-picker.tsx +114 -0
  75. package/src/editor/emoji.ts +436 -0
  76. package/src/editor/index.ts +6 -0
  77. package/src/editor/sections.ts +83 -0
  78. package/src/editor/suggestion-popup.tsx +136 -0
  79. package/src/editor/suggestions.ts +309 -0
  80. package/src/editor/ui.tsx +171 -0
  81. package/src/errors/error-shell.tsx +72 -0
  82. package/src/errors/global-error-shell.tsx +116 -0
  83. package/src/errors/index.ts +2 -0
  84. package/src/grid/columns.ts +48 -0
  85. package/src/grid/compare.ts +35 -0
  86. package/src/grid/hidden-columns.ts +95 -0
  87. package/src/grid/index.ts +27 -0
  88. package/src/grid/use-grid.ts +282 -0
  89. package/src/grid/views.ts +70 -0
  90. package/src/guides/guide-article.tsx +92 -0
  91. package/src/guides/guide-figure-zoom.tsx +533 -0
  92. package/src/guides/guide-figure.tsx +68 -0
  93. package/src/guides/guide-toc.tsx +133 -0
  94. package/src/guides/guides-landing.tsx +57 -0
  95. package/src/guides/guides-search.tsx +160 -0
  96. package/src/guides/guides-shell.tsx +60 -0
  97. package/src/guides/guides-sidebar.tsx +93 -0
  98. package/src/guides/index.ts +28 -0
  99. package/src/guides/library.ts +165 -0
  100. package/src/health/health.ts +115 -0
  101. package/src/health/index.ts +11 -0
  102. package/src/internal/cx.ts +4 -0
  103. package/src/internal/next-link.ts +23 -0
  104. package/src/jobs/counts.ts +151 -0
  105. package/src/jobs/cron-auth.ts +60 -0
  106. package/src/jobs/health.ts +315 -0
  107. package/src/jobs/idle.ts +86 -0
  108. package/src/jobs/index.ts +120 -0
  109. package/src/jobs/job-health-list.tsx +316 -0
  110. package/src/jobs/next-index.ts +4 -0
  111. package/src/jobs/next.ts +65 -0
  112. package/src/jobs/prisma-index.ts +12 -0
  113. package/src/jobs/prisma.ts +170 -0
  114. package/src/jobs/prune.ts +79 -0
  115. package/src/jobs/react-index.ts +35 -0
  116. package/src/jobs/registry.ts +189 -0
  117. package/src/jobs/scheduler.ts +437 -0
  118. package/src/jobs/store.ts +212 -0
  119. package/src/jobs/windows.ts +157 -0
  120. package/src/maintenance/core.ts +270 -0
  121. package/src/maintenance/gate.ts +171 -0
  122. package/src/maintenance/index.ts +40 -0
  123. package/src/maintenance/page.ts +76 -0
  124. package/src/maintenance/proxy.ts +88 -0
  125. package/src/maintenance/react-index.ts +7 -0
  126. package/src/maintenance/react.tsx +190 -0
  127. package/src/maintenance/route.ts +82 -0
  128. package/src/maintenance/unavailable.ts +61 -0
  129. package/src/markdown/figure.tsx +132 -0
  130. package/src/markdown/figures.ts +237 -0
  131. package/src/markdown/guide.tsx +536 -0
  132. package/src/markdown/index.ts +53 -0
  133. package/src/markdown/table-view.tsx +74 -0
  134. package/src/markdown/table.ts +90 -0
  135. package/src/password/common.ts +58 -0
  136. package/src/password/estimate-index.ts +18 -0
  137. package/src/password/estimate.ts +715 -0
  138. package/src/password/index.ts +40 -0
  139. package/src/password/password-input.tsx +116 -0
  140. package/src/password/password-strength.tsx +157 -0
  141. package/src/password/reveal.ts +151 -0
  142. package/src/rate-limit/better-auth.ts +94 -0
  143. package/src/rate-limit/index.ts +32 -0
  144. package/src/rate-limit/keys.ts +110 -0
  145. package/src/rate-limit/limiter.ts +276 -0
  146. package/src/rate-limit/prisma-index.ts +12 -0
  147. package/src/rate-limit/prisma.ts +157 -0
  148. package/src/rate-limit/store.ts +47 -0
  149. package/src/release/changelog.ts +364 -0
  150. package/src/release/index.ts +32 -0
  151. package/src/release/version.ts +64 -0
  152. package/src/setup-guide/bits.tsx +420 -0
  153. package/src/setup-guide/card.tsx +358 -0
  154. package/src/setup-guide/class-names.ts +144 -0
  155. package/src/setup-guide/context.tsx +239 -0
  156. package/src/setup-guide/guide.ts +271 -0
  157. package/src/setup-guide/index.ts +76 -0
  158. package/src/setup-guide/launcher.tsx +207 -0
  159. package/src/setup-guide/strip.tsx +127 -0
  160. package/src/styles/house.css +403 -0
  161. package/src/trail/index.ts +12 -0
  162. package/src/trail/rules.ts +84 -0
  163. package/src/trail/trail.tsx +367 -0
  164. package/src/ux/errors.ts +32 -0
  165. package/src/ux/feedback.tsx +41 -0
  166. package/src/ux/index.ts +44 -0
  167. package/src/ux/navigation-index.ts +16 -0
  168. package/src/ux/navigation-progress.tsx +270 -0
  169. package/src/ux/optimistic.ts +415 -0
  170. package/src/ux/use-action.ts +155 -0
  171. package/src/ux/use-optimistic-list.ts +227 -0
  172. package/src/ux/use-optimistic-value.ts +136 -0
  173. package/src/web-search/index.ts +13 -0
  174. package/src/web-search/providers.ts +177 -0
  175. package/src/web-search/types.ts +98 -0
  176. package/src/whats-new/body.tsx +190 -0
  177. package/src/whats-new/index.ts +43 -0
  178. package/src/whats-new/seen.ts +40 -0
  179. package/src/whats-new/select.ts +230 -0
  180. package/src/whats-new/use-whats-new.ts +109 -0
  181. package/src/wizard/index.ts +61 -0
  182. package/src/wizard/invalid.ts +152 -0
  183. package/src/wizard/react-hook-form-index.ts +11 -0
  184. package/src/wizard/rhf-adapter.ts +67 -0
  185. package/src/wizard/rules.ts +137 -0
  186. package/src/wizard/wizard.tsx +442 -0
@@ -0,0 +1,270 @@
1
+ "use client";
2
+
3
+ import { usePathname, useRouter, useSearchParams } from "next/navigation.js";
4
+ import * as React from "react";
5
+
6
+ /**
7
+ * Feedback for the other half of "nothing answers my click": moving between
8
+ * screens.
9
+ *
10
+ * Two signals, because they answer two different questions:
11
+ *
12
+ * - **A bar across the top of the page** — "something is happening". It waits
13
+ * a moment before appearing so a fast navigation does not flash it.
14
+ * - **A spinner on the thing that was clicked** — "*that* is what is
15
+ * happening". Without it, a slow route on a page full of links gives no clue
16
+ * which one took, which is when people click a second one.
17
+ *
18
+ * The second is set on the DOM node directly rather than through React state.
19
+ * The click can land on any link anywhere in the tree, including ones rendered
20
+ * by pages this component knows nothing about, and an attribute is the only
21
+ * thing they all have in common. `data-busy` is the same attribute the button
22
+ * primitive sets for an action, so one rule in the stylesheet covers both.
23
+ */
24
+
25
+ /** Delay before the bar appears, so fast navigations do not flash it. */
26
+ const START_DELAY_MS = 140;
27
+ /** Cadence of the trickle that creeps the bar towards 90%. */
28
+ const TRICKLE_MS = 220;
29
+ /** Safety net: never leave the bar running forever if a navigation never commits. */
30
+ const MAX_PENDING_MS = 20_000;
31
+ /** How long the completed bar stays at 100% before fading out. */
32
+ const COMPLETE_MS = 260;
33
+
34
+ const START_EVENT = "cx:navigation-start";
35
+
36
+ /** The attribute every busy control carries, action or navigation alike. */
37
+ export const BUSY_ATTRIBUTE = "data-busy";
38
+
39
+ /** The control currently marked as the reason for a navigation. */
40
+ let marked: Element | null = null;
41
+
42
+ function unmark() {
43
+ if (!marked) return;
44
+ marked.removeAttribute(BUSY_ATTRIBUTE);
45
+ marked.removeAttribute("aria-busy");
46
+ marked = null;
47
+ }
48
+
49
+ function mark(element: Element | null) {
50
+ if (marked === element) return;
51
+ unmark();
52
+ if (!element) return;
53
+ marked = element;
54
+ element.setAttribute(BUSY_ATTRIBUTE, "true");
55
+ element.setAttribute("aria-busy", "true");
56
+ }
57
+
58
+ /**
59
+ * Show the navigation feedback for something this module cannot see on its
60
+ * own — a programmatic `router.push`. Pass the control that caused it and it
61
+ * gets the spinner too.
62
+ */
63
+ export function startNavigation(element?: Element | null): void {
64
+ if (typeof window === "undefined") return;
65
+ mark(element ?? null);
66
+ window.dispatchEvent(new Event(START_EVENT));
67
+ }
68
+
69
+ /** Backwards-compatible alias for the original name. */
70
+ export const startRouteProgress = startNavigation;
71
+
72
+ /**
73
+ * `useRouter`, with the navigation feedback attached to `push` and `replace`.
74
+ *
75
+ * A click that runs `router.push(href)` is invisible to the watcher above —
76
+ * there is no anchor and no popstate — so those navigations were the ones with
77
+ * no feedback at all. The worst case is the one right after a save: the
78
+ * button's own spinner stops when the write lands, and then nothing happens
79
+ * for as long as the next screen takes to render.
80
+ *
81
+ * Swapping the import is the whole change; no call site moves. `refresh`,
82
+ * `back`, `forward` and `prefetch` pass straight through — a refresh re-renders
83
+ * the screen you are already on, which needs no bar.
84
+ */
85
+ export function useAppRouter() {
86
+ const router = useRouter();
87
+ return React.useMemo(
88
+ () => ({
89
+ ...router,
90
+ // Forwarded by spread, not by naming the options: passing an explicit
91
+ // `undefined` is a different call from passing nothing.
92
+ push: (...args: Parameters<typeof router.push>) => {
93
+ startNavigation();
94
+ router.push(...args);
95
+ },
96
+ replace: (...args: Parameters<typeof router.replace>) => {
97
+ startNavigation();
98
+ router.replace(...args);
99
+ },
100
+ }),
101
+ [router],
102
+ );
103
+ }
104
+
105
+ /**
106
+ * `router.push` with the feedback attached, and the control that caused it
107
+ * marked as busy. For a button that navigates rather than saves.
108
+ */
109
+ export function useNavigate() {
110
+ const router = useRouter();
111
+ return React.useCallback(
112
+ (href: string, options?: { replace?: boolean; element?: Element | null }) => {
113
+ startNavigation(options?.element ?? null);
114
+ if (options?.replace) router.replace(href);
115
+ else router.push(href);
116
+ },
117
+ [router],
118
+ );
119
+ }
120
+
121
+ /**
122
+ * A click that means "take me there", rather than one the browser will handle
123
+ * itself — a new tab, a download, a context menu.
124
+ *
125
+ * Deliberately *not* a `defaultPrevented` check. This runs in the capture
126
+ * phase, and the reason is the whole point of this listener: Next's `Link`
127
+ * calls `preventDefault()` on its way to a client-side navigation, so by the
128
+ * time a bubble-phase listener sees the click, every in-app link looks
129
+ * cancelled. Guarding on `defaultPrevented` there means the bar fires for
130
+ * exactly the navigations that do not need it and stays silent for all the
131
+ * ones that do — which is what was happening here until this was measured in
132
+ * the browser.
133
+ */
134
+ function isPlainLeftClick(event: MouseEvent) {
135
+ return event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey;
136
+ }
137
+
138
+ function navigatesElsewhere(url: URL) {
139
+ if (url.origin !== window.location.origin) return false;
140
+ // API routes are downloads/exports, not page navigations.
141
+ if (url.pathname.startsWith("/api/")) return false;
142
+ return url.pathname !== window.location.pathname || url.search !== window.location.search;
143
+ }
144
+
145
+ function NavigationProgressBar({ className }: { className?: string }) {
146
+ const pathname = usePathname();
147
+ const search = useSearchParams().toString();
148
+ const [progress, setProgress] = React.useState<number | null>(null);
149
+ const timers = React.useRef<number[]>([]);
150
+ const active = React.useRef(false);
151
+
152
+ const clearTimers = React.useCallback(() => {
153
+ timers.current.forEach((id) => window.clearTimeout(id));
154
+ timers.current = [];
155
+ }, []);
156
+
157
+ const stop = React.useCallback(() => {
158
+ clearTimers();
159
+ active.current = false;
160
+ delete document.body.dataset.routePending;
161
+ unmark();
162
+ setProgress((value) => (value === null ? null : 100));
163
+ window.setTimeout(() => {
164
+ // A new navigation may have started in the meantime; leave its bar alone.
165
+ if (!active.current) setProgress(null);
166
+ }, COMPLETE_MS);
167
+ }, [clearTimers]);
168
+
169
+ const start = React.useCallback(() => {
170
+ if (active.current) return;
171
+ active.current = true;
172
+ document.body.dataset.routePending = "true";
173
+
174
+ const trickle = () => {
175
+ setProgress((value) => (value === null ? value : Math.min(value + Math.max(1, (90 - value) * 0.16), 90)));
176
+ timers.current.push(window.setTimeout(trickle, TRICKLE_MS));
177
+ };
178
+
179
+ timers.current.push(
180
+ window.setTimeout(() => {
181
+ setProgress(8);
182
+ trickle();
183
+ }, START_DELAY_MS),
184
+ );
185
+ timers.current.push(window.setTimeout(stop, MAX_PENDING_MS));
186
+ }, [stop]);
187
+
188
+ // The navigation committed once the URL the router reports has changed.
189
+ const initialRender = React.useRef(true);
190
+ React.useEffect(() => {
191
+ if (initialRender.current) {
192
+ initialRender.current = false;
193
+ return;
194
+ }
195
+ stop();
196
+ }, [pathname, search, stop]);
197
+
198
+ React.useEffect(() => {
199
+ const onClick = (event: MouseEvent) => {
200
+ if (!isPlainLeftClick(event)) return;
201
+ const target = event.target;
202
+ if (!(target instanceof Element)) return;
203
+ const anchor = target.closest("a");
204
+ if (!anchor?.href || anchor.hasAttribute("download")) return;
205
+ if (anchor.target && anchor.target !== "_self") return;
206
+ if (!navigatesElsewhere(new URL(anchor.href))) return;
207
+ // Mark before `start`, which returns early when a navigation is already
208
+ // running: a second click during a slow load should still move the
209
+ // spinner to the link that was actually clicked.
210
+ mark(anchor);
211
+ start();
212
+ };
213
+
214
+ const onSubmit = (event: SubmitEvent) => {
215
+ if (event.defaultPrevented) return;
216
+ const form = event.target;
217
+ if (!(form instanceof HTMLFormElement)) return;
218
+ if (form.method.toLowerCase() !== "get" || !form.action) return;
219
+ if (new URL(form.action).origin !== window.location.origin) return;
220
+ if (event.submitter) mark(event.submitter);
221
+ start();
222
+ };
223
+
224
+ // Capture, so this runs before `Link` cancels the click (see above). The
225
+ // submit listener stays in the bubble phase on purpose: a form with an
226
+ // `onSubmit` that saves rather than navigates is the common case here, and
227
+ // `defaultPrevented` is exactly how to tell those apart.
228
+ document.addEventListener("click", onClick, true);
229
+ document.addEventListener("submit", onSubmit);
230
+ window.addEventListener("popstate", start);
231
+ window.addEventListener(START_EVENT, start);
232
+ return () => {
233
+ document.removeEventListener("click", onClick, true);
234
+ document.removeEventListener("submit", onSubmit);
235
+ window.removeEventListener("popstate", start);
236
+ window.removeEventListener(START_EVENT, start);
237
+ clearTimers();
238
+ unmark();
239
+ delete document.body.dataset.routePending;
240
+ };
241
+ }, [clearTimers, start]);
242
+
243
+ if (progress === null) return null;
244
+
245
+ return (
246
+ <div
247
+ className="pointer-events-none fixed inset-x-0 top-0 z-[100] h-0.5"
248
+ role="progressbar"
249
+ aria-label="Loading page"
250
+ aria-busy="true"
251
+ >
252
+ <div className={className} style={{ width: `${progress}%`, opacity: progress === 100 ? 0 : 1 }} />
253
+ </div>
254
+ );
255
+ }
256
+
257
+ /**
258
+ * Mount once, above everything else — including anything that suspends, or the
259
+ * bar disappears for exactly the navigations it is there for.
260
+ *
261
+ * `className` styles the filled part of the bar, so the host app picks its own
262
+ * colour without this module knowing any of its tokens.
263
+ */
264
+ export function NavigationProgress({ className }: { className?: string }) {
265
+ return (
266
+ <React.Suspense fallback={null}>
267
+ <NavigationProgressBar className={className} />
268
+ </React.Suspense>
269
+ );
270
+ }
@@ -0,0 +1,415 @@
1
+ /**
2
+ * The patch queue behind the optimistic hooks — no React, no transport, no
3
+ * framework. All of the thinking is here so it can be tested as a function.
4
+ *
5
+ * ## The shape of the problem
6
+ *
7
+ * A screen shows rows the server sent. Someone ticks one. Three things then
8
+ * have to be true at once:
9
+ *
10
+ * 1. The tick shows **now**, before any request goes out.
11
+ * 2. If the write fails, the tick goes away again and the person is told.
12
+ * 3. When the server's own rows arrive, they win — including when they say
13
+ * something different from what was guessed.
14
+ *
15
+ * React's `useOptimistic` solves (1) and (2) for a server action, because the
16
+ * action *is* the transition and React knows when it ends. It does not solve
17
+ * (3) for an app that writes over `fetch` and then calls `router.refresh()`:
18
+ * `router.refresh()` is not awaitable, so the transition ends before the new
19
+ * rows land and the optimistic value snaps back to the stale one — a visible
20
+ * flash of the old answer on every single write. That is the reason this
21
+ * module exists rather than a wrapper around `useOptimistic`.
22
+ *
23
+ * ## How it works
24
+ *
25
+ * The server's rows are the *base*. Every optimistic change is a *patch* held
26
+ * beside the base, never merged into it. What the screen renders is the base
27
+ * with the patches applied, recomputed on each render.
28
+ *
29
+ * A patch is `pending` while its write is in flight, then either:
30
+ *
31
+ * - **dropped** — the write failed, so the base alone is the truth again; or
32
+ * - **settled** — the write landed. It keeps being applied, because the base
33
+ * is still the *old* rows until a refresh arrives, and taking the patch away
34
+ * at this point is precisely the flash we are avoiding.
35
+ *
36
+ * A settled patch is dropped when fresh rows arrive that account for it. That
37
+ * is the whole reconciliation rule, and it is deliberately evidence-based
38
+ * rather than timed: see `shouldDropSettled`.
39
+ *
40
+ * The same rules apply to a single value — a switch, a status, a settings
41
+ * record — under the `…Value` names at the foot of this file. A queue there
42
+ * too, and for the sharper of the two reasons: see `ValuePatch`.
43
+ */
44
+
45
+ /** How a row is identified. Ids are strings here; numbers stringify fine. */
46
+ export type RowKey = string;
47
+
48
+ export type PatchKind = "insert" | "update" | "remove" | "move";
49
+
50
+ export interface Patch<T> {
51
+ readonly id: string;
52
+ readonly kind: PatchKind;
53
+ /**
54
+ * The row this patch concerns. For an insert this starts as a made-up key
55
+ * and becomes the server's own key once the write lands.
56
+ */
57
+ readonly key: RowKey;
58
+ /** `insert`: the row to show. */
59
+ readonly row?: T;
60
+ /** `update`: the fields to lay over the row. */
61
+ readonly fields?: Partial<T>;
62
+ /** `insert`: which end of the list to show it at. */
63
+ readonly at?: "start" | "end";
64
+ /** `move`: the key this row now sits before; `null` means last. */
65
+ readonly before?: RowKey | null;
66
+ readonly settled: boolean;
67
+ /**
68
+ * What the base said about `key` at the moment the write landed. Fresh rows
69
+ * are recognised by disagreeing with it — see `shouldDropSettled`.
70
+ */
71
+ readonly witness?: T | null;
72
+ }
73
+
74
+ let counter = 0;
75
+
76
+ /** A patch id. Unique within a session; never stored or sent anywhere. */
77
+ export function nextPatchId(): string {
78
+ counter += 1;
79
+ return `p${counter}`;
80
+ }
81
+
82
+ function find<T>(rows: readonly T[], key: RowKey, keyOf: (row: T) => RowKey): T | null {
83
+ for (const row of rows) if (keyOf(row) === key) return row;
84
+ return null;
85
+ }
86
+
87
+ /**
88
+ * The rows to render: the server's, with every patch laid over them in the
89
+ * order they were made, so a later change to the same row wins.
90
+ */
91
+ export function applyPatches<T>(
92
+ base: readonly T[],
93
+ patches: readonly Patch<T>[],
94
+ keyOf: (row: T) => RowKey,
95
+ ): readonly T[] {
96
+ if (patches.length === 0) return base;
97
+
98
+ let rows = [...base];
99
+ for (const patch of patches) {
100
+ switch (patch.kind) {
101
+ case "insert": {
102
+ // The server's own copy has arrived under this key: show that one
103
+ // rather than two of the same thing.
104
+ if (patch.row === undefined || find(rows, patch.key, keyOf) !== null) break;
105
+ if (patch.at === "start") rows.unshift(patch.row);
106
+ else rows.push(patch.row);
107
+ break;
108
+ }
109
+ case "update": {
110
+ rows = rows.map((row) => (keyOf(row) === patch.key ? { ...row, ...patch.fields } : row));
111
+ break;
112
+ }
113
+ case "remove": {
114
+ rows = rows.filter((row) => keyOf(row) !== patch.key);
115
+ break;
116
+ }
117
+ case "move": {
118
+ const from = rows.findIndex((row) => keyOf(row) === patch.key);
119
+ if (from < 0) break;
120
+ const moved = rows.splice(from, 1);
121
+ // `splice` above removed exactly one row at a known index, so this is
122
+ // never empty; the check is for the type, not for the case.
123
+ if (moved.length === 0) break;
124
+ const to = patch.before == null ? -1 : rows.findIndex((other) => keyOf(other) === patch.before);
125
+ rows.splice(to < 0 ? rows.length : to, 0, ...moved);
126
+ break;
127
+ }
128
+ }
129
+ }
130
+ return rows;
131
+ }
132
+
133
+ /** The key that follows `key` in `rows`; `null` at the end. */
134
+ function neighbourAfter<T>(rows: readonly T[], key: RowKey, keyOf: (row: T) => RowKey): RowKey | null {
135
+ const index = rows.findIndex((row) => keyOf(row) === key);
136
+ if (index < 0) return null;
137
+ const next = rows[index + 1];
138
+ return next === undefined ? null : keyOf(next);
139
+ }
140
+
141
+ /** Shallow, own-keys equality. Enough to tell "the same row" from "new data". */
142
+ export function sameRow<T>(a: T | null | undefined, b: T | null | undefined): boolean {
143
+ if (a === b) return true;
144
+ if (a == null || b == null) return false;
145
+ if (typeof a !== "object" || typeof b !== "object") return Object.is(a, b);
146
+ const left = a as Record<string, unknown>;
147
+ const right = b as Record<string, unknown>;
148
+ const keys = Object.keys(left);
149
+ if (keys.length !== Object.keys(right).length) return false;
150
+ return keys.every((key) => Object.is(left[key], right[key]));
151
+ }
152
+
153
+ /**
154
+ * Does the base already say what this patch says? A redundant patch has
155
+ * nothing left to show and can go.
156
+ */
157
+ export function isRedundant<T>(patch: Patch<T>, base: readonly T[], keyOf: (row: T) => RowKey): boolean {
158
+ const current = find(base, patch.key, keyOf);
159
+ switch (patch.kind) {
160
+ case "insert":
161
+ return current !== null;
162
+ case "remove":
163
+ return current === null;
164
+ case "update": {
165
+ // A row that is no longer there cannot be waiting for an edit.
166
+ if (current === null) return true;
167
+ const fields = (patch.fields ?? {}) as Record<string, unknown>;
168
+ const row = current as Record<string, unknown>;
169
+ return Object.keys(fields).every((key) => Object.is(row[key], fields[key]));
170
+ }
171
+ case "move":
172
+ return find(base, patch.key, keyOf) !== null && neighbourAfter(base, patch.key, keyOf) === patch.before;
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Whether a settled patch has been overtaken by fresh server rows.
178
+ *
179
+ * Two ways it can have been, and they cover the two endings the person cares
180
+ * about:
181
+ *
182
+ * - **The base agrees** — the refresh carried the change through. Dropping the
183
+ * patch changes nothing on screen, which is exactly the point.
184
+ * - **The base disagrees with what it said when the write landed** — new data
185
+ * for this row has arrived. It wins, whatever it says. This is the case
186
+ * where the server did something other than what was guessed (clamped a
187
+ * value, renamed on save, reordered), and the screen corrects itself.
188
+ *
189
+ * A base that has not changed at all leaves the patch applied, however long it
190
+ * has been there. There is no timeout on purpose: a screen that never refetches
191
+ * has no truth to fall back to, and snapping to stale rows after N seconds
192
+ * would be a bug that only shows up on slow connections.
193
+ *
194
+ * Only ever called when the base is a *different array* from the one the patch
195
+ * settled against, so a parent that rebuilds its rows on every render cannot
196
+ * shake patches loose.
197
+ */
198
+ export function shouldDropSettled<T>(patch: Patch<T>, base: readonly T[], keyOf: (row: T) => RowKey): boolean {
199
+ if (isRedundant(patch, base, keyOf)) return true;
200
+ return !sameRow(find(base, patch.key, keyOf), patch.witness ?? null);
201
+ }
202
+
203
+ /**
204
+ * The queue after fresh rows arrived: pending writes are left alone, settled
205
+ * ones are dropped once the rows account for them.
206
+ */
207
+ export function reconcile<T>(
208
+ patches: readonly Patch<T>[],
209
+ base: readonly T[],
210
+ keyOf: (row: T) => RowKey,
211
+ ): readonly Patch<T>[] {
212
+ if (patches.length === 0) return patches;
213
+ const kept = patches.filter((patch) => !patch.settled || !shouldDropSettled(patch, base, keyOf));
214
+ return kept.length === patches.length ? patches : kept;
215
+ }
216
+
217
+ /**
218
+ * Mark a landed write as settled, taking the server's own answer over the
219
+ * guess where it sent one — the correction in "confirm or correct" — and
220
+ * noting what the base said, so the next refresh can be recognised.
221
+ *
222
+ * What it takes from that answer is deliberately narrow. A write endpoint
223
+ * often returns a *thinner* record than the list endpoint does — no joined
224
+ * learner, no counts — because the caller did not need them. Laying that over
225
+ * the row wholesale would blank the columns beside the one that was edited,
226
+ * which looks exactly like data loss and is the reason this is a `pick` and a
227
+ * merge rather than an assignment.
228
+ */
229
+ export function settlePatch<T>(
230
+ patch: Patch<T>,
231
+ serverRow: T | undefined,
232
+ base: readonly T[],
233
+ keyOf: (row: T) => RowKey,
234
+ ): Patch<T> {
235
+ const settled = { ...patch, settled: true, witness: find(base, patch.key, keyOf) };
236
+ if (serverRow === null || serverRow === undefined || typeof serverRow !== "object") return settled;
237
+
238
+ if (patch.kind === "insert" && patch.row !== undefined) {
239
+ // The guess fills in whatever the create did not answer with; the key
240
+ // comes from the server, because that is the one thing only it knows.
241
+ const row = { ...patch.row, ...serverRow };
242
+ const key = keyOf(row);
243
+ return { ...settled, key, row, witness: find(base, key, keyOf) };
244
+ }
245
+
246
+ if (patch.kind === "update" && patch.fields) {
247
+ // Only the fields this write set, and only those the answer carried: a
248
+ // price rounded on save, a title trimmed, a status the server chose.
249
+ const answer = serverRow as Record<string, unknown>;
250
+ const corrected: Record<string, unknown> = { ...(patch.fields as Record<string, unknown>) };
251
+ for (const field of Object.keys(corrected)) {
252
+ if (field in answer) corrected[field] = answer[field];
253
+ }
254
+ return { ...settled, fields: corrected as Partial<T> };
255
+ }
256
+
257
+ return settled;
258
+ }
259
+
260
+ /**
261
+ * Drop what a write that has just landed supersedes: earlier *settled* changes
262
+ * to the same rows. Writes still in flight stay — each has a request that can
263
+ * still come back refused and needs rolling back on its own.
264
+ *
265
+ * This happens on landing, never on queueing. A change that succeeded is still
266
+ * true while a later one is being attempted, and clearing it early means a
267
+ * failed second write rolls the first one back with it.
268
+ */
269
+ export function supersede<T>(patches: readonly Patch<T>[], keys: ReadonlySet<RowKey>): readonly Patch<T>[] {
270
+ return patches.filter((patch) => !(patch.settled && keys.has(patch.key)));
271
+ }
272
+
273
+ /**
274
+ * A stand-in key for a row that does not exist server-side yet. Distinctive on
275
+ * purpose: if one of these ever reaches a request body or a URL, the resulting
276
+ * 404 should say why at a glance.
277
+ */
278
+ export function tempKey(prefix = "tmp"): string {
279
+ counter += 1;
280
+ return `${prefix}:${counter}:${Date.now().toString(36)}`;
281
+ }
282
+
283
+ /** Whether a key came from `tempKey` — a row that is still being created. */
284
+ export function isTempKey(key: RowKey): boolean {
285
+ return key.startsWith("tmp:");
286
+ }
287
+
288
+ /* ------------------------------------------------------------------------- *
289
+ * One value rather than a list
290
+ * ------------------------------------------------------------------------- */
291
+
292
+ /**
293
+ * A change to a single value — a switch, a status, a settings record.
294
+ *
295
+ * The same queue as above, for the case where the base is one thing instead of
296
+ * an array of them. It is a queue and not one held value for the reason a list
297
+ * is: two writes can be in flight at once, and each has to be able to land or
298
+ * roll back **on its own**. A single slot makes whichever request answers last
299
+ * the winner, so a slow first write landing after a second one quietly puts the
300
+ * first answer back on screen — a change the person watched save, undone by
301
+ * nothing they did.
302
+ */
303
+ export interface ValuePatch<T> {
304
+ readonly id: string;
305
+ /** `set` replaces the value; `merge` lays fields over whatever is beneath it. */
306
+ readonly kind: "set" | "merge";
307
+ /** `set`: the value to show. */
308
+ readonly value?: T;
309
+ /** `merge`: the fields to lay over it. */
310
+ readonly fields?: Partial<T>;
311
+ readonly settled: boolean;
312
+ /** What the base was when the write landed — see `shouldDropSettledValue`. */
313
+ readonly witness?: T;
314
+ }
315
+
316
+ /** The value to render: the server's, with every change laid over it in order. */
317
+ export function applyValuePatches<T>(base: T, patches: readonly ValuePatch<T>[]): T {
318
+ if (patches.length === 0) return base;
319
+
320
+ let value = base;
321
+ for (const patch of patches) {
322
+ if (patch.kind === "set") {
323
+ value = patch.value as T;
324
+ continue;
325
+ }
326
+ // Fields need something to go over. A merge against a value that is not an
327
+ // object has nothing to lay them on and is dropped rather than turned into
328
+ // an object that was never that shape.
329
+ if (typeof value === "object" && value !== null) {
330
+ value = { ...(value as object), ...(patch.fields as object) } as T;
331
+ }
332
+ }
333
+ return value;
334
+ }
335
+
336
+ /** Does the base already say what this change says? */
337
+ export function isRedundantValue<T>(patch: ValuePatch<T>, base: T): boolean {
338
+ if (patch.kind === "set") return sameRow(base, patch.value);
339
+ if (typeof base !== "object" || base === null) return true;
340
+ const fields = (patch.fields ?? {}) as Record<string, unknown>;
341
+ const current = base as Record<string, unknown>;
342
+ return Object.keys(fields).every((key) => Object.is(current[key], fields[key]));
343
+ }
344
+
345
+ /**
346
+ * Whether a settled change has been overtaken by a fresh value — the same two
347
+ * endings as `shouldDropSettled`: the base agrees, so the change has nothing
348
+ * left to show, or the base has moved since the write landed, in which case it
349
+ * wins whatever it says.
350
+ */
351
+ export function shouldDropSettledValue<T>(patch: ValuePatch<T>, base: T): boolean {
352
+ return isRedundantValue(patch, base) || !sameRow(base, patch.witness);
353
+ }
354
+
355
+ /**
356
+ * The queue after a fresh value arrived.
357
+ *
358
+ * Writes in flight are left alone. Settled ones go **together**, judged by the
359
+ * last of them: unlike a list, every change here is about the same one thing,
360
+ * so once fresh data has overtaken the newest of them the older ones have
361
+ * nothing to say either — and keeping some while dropping others is how a
362
+ * half-applied value would get on screen.
363
+ */
364
+ export function reconcileValue<T>(patches: readonly ValuePatch<T>[], base: T): readonly ValuePatch<T>[] {
365
+ if (patches.length === 0) return patches;
366
+
367
+ let newest: ValuePatch<T> | null = null;
368
+ for (const patch of patches) if (patch.settled) newest = patch;
369
+ if (newest === null || !shouldDropSettledValue(newest, base)) return patches;
370
+
371
+ return patches.filter((patch) => !patch.settled);
372
+ }
373
+
374
+ /**
375
+ * Mark a landed write as settled, taking the server's own answer where it sent
376
+ * one and noting what the base said, so the next refresh can be recognised.
377
+ *
378
+ * A `set` takes the answer whole, because the caller declared the value's own
379
+ * shape by passing it. A `merge` takes only the fields it wrote, for the reason
380
+ * `settlePatch` does: a write route often answers with a thinner record than
381
+ * the read did, and laying that over the value blanks everything the write said
382
+ * nothing about.
383
+ */
384
+ export function settleValuePatch<T>(patch: ValuePatch<T>, answer: T | undefined, base: T): ValuePatch<T> {
385
+ const settled = { ...patch, settled: true, witness: base };
386
+ if (answer === null || answer === undefined) return settled;
387
+
388
+ if (patch.kind === "set") return { ...settled, value: answer };
389
+
390
+ if (typeof answer !== "object") return settled;
391
+ const sent = answer as Record<string, unknown>;
392
+ const corrected: Record<string, unknown> = { ...((patch.fields ?? {}) as Record<string, unknown>) };
393
+ for (const field of Object.keys(corrected)) {
394
+ if (field in sent) corrected[field] = sent[field];
395
+ }
396
+ return { ...settled, fields: corrected as Partial<T> };
397
+ }
398
+
399
+ /**
400
+ * Drop what a write that has just landed supersedes: settled changes queued
401
+ * *before* a landed `set`, which replaced the whole value and so answered for
402
+ * them. Writes still in flight stay — each has a request that can still come
403
+ * back refused — and a landed `merge` supersedes nothing, because the changes
404
+ * under it may carry fields it says nothing about.
405
+ *
406
+ * Pruning only, never order: a landed change keeps its place in the queue, or a
407
+ * slow first write would jump ahead of the second one on landing and win.
408
+ */
409
+ export function supersedeValue<T>(patches: readonly ValuePatch<T>[], landed: ValuePatch<T>): readonly ValuePatch<T>[] {
410
+ if (landed.kind !== "set") return patches;
411
+ const at = patches.findIndex((patch) => patch.id === landed.id);
412
+ if (at <= 0) return patches;
413
+ const kept = patches.filter((patch, index) => index >= at || !patch.settled);
414
+ return kept.length === patches.length ? patches : kept;
415
+ }