@connextar/house 0.23.0 → 0.23.3

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 (187) hide show
  1. package/README.md +27 -3
  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 +20 -3
  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/react.d.ts.map +1 -1
  11. package/dist/analytics/react.js +4 -2
  12. package/dist/analytics/react.js.map +1 -1
  13. package/dist/analytics/redact.d.ts.map +1 -1
  14. package/dist/analytics/redact.js +6 -1
  15. package/dist/analytics/redact.js.map +1 -1
  16. package/dist/rate-limit/prisma-index.d.ts +1 -1
  17. package/dist/rate-limit/prisma-index.d.ts.map +1 -1
  18. package/dist/rate-limit/prisma-index.js.map +1 -1
  19. package/dist/rate-limit/prisma.d.ts +10 -1
  20. package/dist/rate-limit/prisma.d.ts.map +1 -1
  21. package/dist/rate-limit/prisma.js +2 -1
  22. package/dist/rate-limit/prisma.js.map +1 -1
  23. package/package.json +5 -2
  24. package/src/account/data-contract.ts +112 -0
  25. package/src/account/index.ts +11 -0
  26. package/src/admin/access.ts +267 -0
  27. package/src/admin/audit.ts +238 -0
  28. package/src/admin/bootstrap.ts +220 -0
  29. package/src/admin/client-index.ts +19 -0
  30. package/src/admin/client.tsx +187 -0
  31. package/src/admin/index.ts +91 -0
  32. package/src/admin/proof.ts +155 -0
  33. package/src/admin/second-factor-index.ts +16 -0
  34. package/src/admin/second-factor.ts +403 -0
  35. package/src/admin/testing-index.ts +13 -0
  36. package/src/admin/testing.ts +299 -0
  37. package/src/admin/view-as.ts +511 -0
  38. package/src/ai/config-index.ts +40 -0
  39. package/src/ai/config.ts +176 -0
  40. package/src/ai/images.ts +18 -0
  41. package/src/ai/index.ts +21 -0
  42. package/src/ai/pricing.ts +107 -0
  43. package/src/ai/provider.ts +403 -0
  44. package/src/analytics/browser.ts +400 -0
  45. package/src/analytics/client-index.ts +12 -0
  46. package/src/analytics/config.ts +89 -0
  47. package/src/analytics/index.ts +17 -0
  48. package/src/analytics/ingest.ts +81 -0
  49. package/src/analytics/react-index.ts +16 -0
  50. package/src/analytics/react.tsx +241 -0
  51. package/src/analytics/redact.ts +146 -0
  52. package/src/analytics/server-index.ts +17 -0
  53. package/src/analytics/server.ts +277 -0
  54. package/src/auth/index.ts +30 -0
  55. package/src/auth/second-factor-index.ts +16 -0
  56. package/src/auth/second-factor-next.ts +136 -0
  57. package/src/auth/second-factor-routes.ts +40 -0
  58. package/src/auth/second-factor.ts +226 -0
  59. package/src/auth/step-up-client-index.ts +13 -0
  60. package/src/auth/step-up-client.ts +23 -0
  61. package/src/auth/step-up-index.ts +19 -0
  62. package/src/auth/step-up-routes.ts +99 -0
  63. package/src/auth/step-up.ts +432 -0
  64. package/src/auth/two-factor-policy.ts +112 -0
  65. package/src/changelog/changelog.tsx +367 -0
  66. package/src/changelog/index.ts +12 -0
  67. package/src/editor/block-handle.tsx +312 -0
  68. package/src/editor/blocks.ts +169 -0
  69. package/src/editor/bubble-toolbar.tsx +208 -0
  70. package/src/editor/collapsible.ts +159 -0
  71. package/src/editor/content-index.ts +1 -0
  72. package/src/editor/content.tsx +343 -0
  73. package/src/editor/editor.tsx +333 -0
  74. package/src/editor/emoji-index.ts +1 -0
  75. package/src/editor/emoji-picker.tsx +114 -0
  76. package/src/editor/emoji.ts +436 -0
  77. package/src/editor/index.ts +6 -0
  78. package/src/editor/sections.ts +83 -0
  79. package/src/editor/suggestion-popup.tsx +136 -0
  80. package/src/editor/suggestions.ts +309 -0
  81. package/src/editor/ui.tsx +171 -0
  82. package/src/errors/error-shell.tsx +72 -0
  83. package/src/errors/global-error-shell.tsx +116 -0
  84. package/src/errors/index.ts +2 -0
  85. package/src/grid/columns.ts +48 -0
  86. package/src/grid/compare.ts +35 -0
  87. package/src/grid/hidden-columns.ts +95 -0
  88. package/src/grid/index.ts +27 -0
  89. package/src/grid/use-grid.ts +282 -0
  90. package/src/grid/views.ts +70 -0
  91. package/src/guides/guide-article.tsx +92 -0
  92. package/src/guides/guide-figure-zoom.tsx +533 -0
  93. package/src/guides/guide-figure.tsx +68 -0
  94. package/src/guides/guide-toc.tsx +133 -0
  95. package/src/guides/guides-landing.tsx +57 -0
  96. package/src/guides/guides-search.tsx +160 -0
  97. package/src/guides/guides-shell.tsx +60 -0
  98. package/src/guides/guides-sidebar.tsx +93 -0
  99. package/src/guides/index.ts +28 -0
  100. package/src/guides/library.ts +165 -0
  101. package/src/health/health.ts +115 -0
  102. package/src/health/index.ts +11 -0
  103. package/src/internal/cx.ts +4 -0
  104. package/src/internal/next-link.ts +23 -0
  105. package/src/jobs/counts.ts +151 -0
  106. package/src/jobs/cron-auth.ts +60 -0
  107. package/src/jobs/health.ts +315 -0
  108. package/src/jobs/idle.ts +86 -0
  109. package/src/jobs/index.ts +120 -0
  110. package/src/jobs/job-health-list.tsx +316 -0
  111. package/src/jobs/next-index.ts +4 -0
  112. package/src/jobs/next.ts +65 -0
  113. package/src/jobs/prisma-index.ts +12 -0
  114. package/src/jobs/prisma.ts +170 -0
  115. package/src/jobs/prune.ts +79 -0
  116. package/src/jobs/react-index.ts +35 -0
  117. package/src/jobs/registry.ts +189 -0
  118. package/src/jobs/scheduler.ts +437 -0
  119. package/src/jobs/store.ts +212 -0
  120. package/src/jobs/windows.ts +157 -0
  121. package/src/maintenance/core.ts +270 -0
  122. package/src/maintenance/gate.ts +171 -0
  123. package/src/maintenance/index.ts +40 -0
  124. package/src/maintenance/page.ts +76 -0
  125. package/src/maintenance/proxy.ts +88 -0
  126. package/src/maintenance/react-index.ts +7 -0
  127. package/src/maintenance/react.tsx +190 -0
  128. package/src/maintenance/route.ts +82 -0
  129. package/src/maintenance/unavailable.ts +61 -0
  130. package/src/markdown/figure.tsx +132 -0
  131. package/src/markdown/figures.ts +237 -0
  132. package/src/markdown/guide.tsx +536 -0
  133. package/src/markdown/index.ts +53 -0
  134. package/src/markdown/table-view.tsx +74 -0
  135. package/src/markdown/table.ts +90 -0
  136. package/src/password/common.ts +58 -0
  137. package/src/password/estimate-index.ts +18 -0
  138. package/src/password/estimate.ts +715 -0
  139. package/src/password/index.ts +40 -0
  140. package/src/password/password-input.tsx +116 -0
  141. package/src/password/password-strength.tsx +157 -0
  142. package/src/password/reveal.ts +151 -0
  143. package/src/rate-limit/better-auth.ts +94 -0
  144. package/src/rate-limit/index.ts +32 -0
  145. package/src/rate-limit/keys.ts +110 -0
  146. package/src/rate-limit/limiter.ts +276 -0
  147. package/src/rate-limit/prisma-index.ts +12 -0
  148. package/src/rate-limit/prisma.ts +157 -0
  149. package/src/rate-limit/store.ts +47 -0
  150. package/src/release/changelog.ts +364 -0
  151. package/src/release/index.ts +32 -0
  152. package/src/release/version.ts +64 -0
  153. package/src/setup-guide/bits.tsx +420 -0
  154. package/src/setup-guide/card.tsx +358 -0
  155. package/src/setup-guide/class-names.ts +144 -0
  156. package/src/setup-guide/context.tsx +239 -0
  157. package/src/setup-guide/guide.ts +271 -0
  158. package/src/setup-guide/index.ts +76 -0
  159. package/src/setup-guide/launcher.tsx +207 -0
  160. package/src/setup-guide/strip.tsx +127 -0
  161. package/src/styles/house.css +384 -0
  162. package/src/trail/index.ts +12 -0
  163. package/src/trail/rules.ts +84 -0
  164. package/src/trail/trail.tsx +367 -0
  165. package/src/ux/errors.ts +32 -0
  166. package/src/ux/feedback.tsx +41 -0
  167. package/src/ux/index.ts +44 -0
  168. package/src/ux/navigation-index.ts +16 -0
  169. package/src/ux/navigation-progress.tsx +270 -0
  170. package/src/ux/optimistic.ts +415 -0
  171. package/src/ux/use-action.ts +155 -0
  172. package/src/ux/use-optimistic-list.ts +227 -0
  173. package/src/ux/use-optimistic-value.ts +136 -0
  174. package/src/web-search/index.ts +13 -0
  175. package/src/web-search/providers.ts +177 -0
  176. package/src/web-search/types.ts +98 -0
  177. package/src/whats-new/body.tsx +190 -0
  178. package/src/whats-new/index.ts +43 -0
  179. package/src/whats-new/seen.ts +40 -0
  180. package/src/whats-new/select.ts +230 -0
  181. package/src/whats-new/use-whats-new.ts +109 -0
  182. package/src/wizard/index.ts +61 -0
  183. package/src/wizard/invalid.ts +152 -0
  184. package/src/wizard/react-hook-form-index.ts +11 -0
  185. package/src/wizard/rhf-adapter.ts +67 -0
  186. package/src/wizard/rules.ts +137 -0
  187. package/src/wizard/wizard.tsx +442 -0
@@ -0,0 +1,230 @@
1
+ import {
2
+ isInternalChange,
3
+ publicHeading,
4
+ publicWording,
5
+ releaseAnchor,
6
+ type ChangeType,
7
+ type ChangelogRelease,
8
+ } from "../release/changelog.js";
9
+ import { compareVersions, isReleaseVersion } from "../release/version.js";
10
+
11
+ /**
12
+ * What a signed-in person is told about the releases since they last looked —
13
+ * worked out on the server, from the app's `CHANGELOG` and the one version it
14
+ * stores against them.
15
+ *
16
+ * Pure: no React, no clock unless one is passed, nothing read or written. The
17
+ * signed-in layout calls `whatsNew` and hands the answer to the client, which
18
+ * is why the answer holds the public wording and nothing else: a change marked
19
+ * `internal`, a release not yet reviewed, and the team's wording of anything
20
+ * the review reworded never leave the server.
21
+ */
22
+
23
+ /** One change the dialog leads with, in the public's words. */
24
+ export interface WhatsNewHighlight {
25
+ version: string;
26
+ /** ISO date of its release. */
27
+ date: string;
28
+ /** Its release's public headline. */
29
+ releaseTitle: string;
30
+ /** Its section's public heading ("Invoices"). */
31
+ heading: string;
32
+ type: ChangeType;
33
+ title: string;
34
+ text: string;
35
+ /** Its release's fragment id on the changelog page, `v1-4-0`. */
36
+ anchor: string;
37
+ }
38
+
39
+ export interface WhatsNewData {
40
+ /** The newest release in the changelog: what dismissing stores. */
41
+ latestVersion: string;
42
+ /** The version stored against the person, as read — null when there was none worth reading. */
43
+ since: string | null;
44
+ /** How many reviewed releases have come out since `since`. */
45
+ releaseCount: number;
46
+ /** The changes the dialog leads with, `changed` first, at most `maxItems`. */
47
+ highlights: WhatsNewHighlight[];
48
+ /** How many more would have qualified as highlights. */
49
+ moreCount: number;
50
+ /** The fragment id of the newest unseen public release, for "See everything in the changelog". */
51
+ anchor: string | null;
52
+ /** Open the dialog: something new or changed since they last looked, and long enough since they last did. */
53
+ shouldShow: boolean;
54
+ /** Nothing was stored (a new account, or a value that isn't a version): store `latestVersion` without a word. */
55
+ stampSilently: boolean;
56
+ }
57
+
58
+ export interface WhatsNewOptions {
59
+ /** The most highlights to return. Defaults to 5; the rest are counted in `moreCount`. */
60
+ maxItems?: number;
61
+ /**
62
+ * The types that can be highlights, in the order they are shown. Defaults to
63
+ * `changed` (someone may need to act), `new`, `improved` — a fix is the
64
+ * changelog's business, not a reason to interrupt someone.
65
+ */
66
+ highlightTypes?: readonly ChangeType[];
67
+ /** The types that open the dialog. Defaults to `new` and `changed`: improvements alone wait for the next one. */
68
+ showFor?: readonly ChangeType[];
69
+ /** Sections whose changes are never highlights, matched case-insensitively. Defaults to `DEFAULT_SKIP_HEADINGS`. */
70
+ skipHeadings?: readonly string[];
71
+ /**
72
+ * Days to wait after the stored version's release date before showing again.
73
+ * Defaults to 0. An app releasing several times a day sets 7: the date of the
74
+ * version someone last stored stands in for when they last saw the dialog, so
75
+ * no second column is needed — they stored the newest release there was.
76
+ */
77
+ minDaysBetween?: number;
78
+ /** The time to measure `minDaysBetween` against. Defaults to now. */
79
+ now?: Date | number;
80
+ /** The person's role, matched against `roles` on changes and sections. Without one, only changes for everyone. */
81
+ role?: string;
82
+ }
83
+
84
+ export const DEFAULT_SKIP_HEADINGS: readonly string[] = ["Fixes", "Bug fixes", "Behind the scenes"];
85
+ export const DEFAULT_HIGHLIGHT_TYPES: readonly ChangeType[] = ["changed", "new", "improved"];
86
+ export const DEFAULT_SHOW_FOR: readonly ChangeType[] = ["new", "changed"];
87
+ export const WHATS_NEW_MAX_ITEMS = 5;
88
+
89
+ const DAY_MS = 24 * 60 * 60 * 1000;
90
+
91
+ interface Candidate {
92
+ highlight: WhatsNewHighlight;
93
+ forced: boolean;
94
+ rank: number;
95
+ release: number;
96
+ section: number;
97
+ part: number;
98
+ change: number;
99
+ }
100
+
101
+ const forRole = (roles: readonly string[] | undefined, role: string | undefined) =>
102
+ roles === undefined || (role !== undefined && roles.includes(role));
103
+
104
+ /**
105
+ * What's new for someone who last stored `lastSeen`, or null when the
106
+ * changelog has no release to speak of.
107
+ *
108
+ * - Unseen means every release newer than `lastSeen` by version, so a stored
109
+ * version the changelog no longer holds still works, and one newer than the
110
+ * changelog (a rollback) has nothing unseen and stores nothing.
111
+ * - Only reviewed releases count, through the same public wording as
112
+ * `publicRelease`, and without the generic "Behind the scenes" line — there is
113
+ * no cap of five, as `publicChangelog` has, because a week of AltEd is twenty-five.
114
+ * - `lastSeen` missing or not a version: nothing shown, `stampSilently`, so a
115
+ * new account isn't greeted by a hundred releases.
116
+ */
117
+ export function whatsNew(
118
+ changelog: readonly ChangelogRelease[],
119
+ lastSeen: string | null | undefined,
120
+ {
121
+ maxItems = WHATS_NEW_MAX_ITEMS,
122
+ highlightTypes = DEFAULT_HIGHLIGHT_TYPES,
123
+ showFor = DEFAULT_SHOW_FOR,
124
+ skipHeadings = DEFAULT_SKIP_HEADINGS,
125
+ minDaysBetween = 0,
126
+ now,
127
+ role,
128
+ }: WhatsNewOptions = {},
129
+ ): WhatsNewData | null {
130
+ const releases = changelog
131
+ .filter((release) => isReleaseVersion(release.version))
132
+ .sort((a, b) => compareVersions(b.version, a.version));
133
+ const newest = releases[0];
134
+ if (!newest) return null;
135
+
136
+ const stored = typeof lastSeen === "string" ? lastSeen.trim() : "";
137
+ const nothing: WhatsNewData = {
138
+ latestVersion: newest.version,
139
+ since: null,
140
+ releaseCount: 0,
141
+ highlights: [],
142
+ moreCount: 0,
143
+ anchor: null,
144
+ shouldShow: false,
145
+ stampSilently: false,
146
+ };
147
+ if (!isReleaseVersion(stored)) return { ...nothing, stampSilently: true };
148
+
149
+ const unseen = releases.filter((release) => release.public && compareVersions(release.version, stored) > 0);
150
+ const skipped = new Set(skipHeadings.map((heading) => heading.trim().toLowerCase()));
151
+ const candidates: Candidate[] = [];
152
+
153
+ unseen.forEach((release, releaseIndex) => {
154
+ const releaseTitle = release.public?.title ?? release.title;
155
+ // Sections sharing a public heading are one section on the public page, placed where the first one was.
156
+ const headings = release.sections.map(publicHeading);
157
+ release.sections.forEach((section, part) => {
158
+ const heading = publicHeading(section);
159
+ section.changes.forEach((change, changeIndex) => {
160
+ if (isInternalChange(change, section)) return;
161
+ if (!forRole(section.roles, role) || !forRole(change.roles, role)) return;
162
+ if (change.highlight === false) return;
163
+ const forced = change.highlight === true;
164
+ if (!forced && (!highlightTypes.includes(change.type) || skipped.has(heading.trim().toLowerCase()))) return;
165
+ const rank = highlightTypes.indexOf(change.type);
166
+ candidates.push({
167
+ highlight: {
168
+ version: release.version,
169
+ date: release.date,
170
+ releaseTitle,
171
+ heading,
172
+ type: change.type,
173
+ ...publicWording(change),
174
+ anchor: releaseAnchor(release.version),
175
+ },
176
+ forced,
177
+ rank: rank === -1 ? highlightTypes.length : rank,
178
+ release: releaseIndex,
179
+ section: headings.indexOf(heading),
180
+ part,
181
+ change: changeIndex,
182
+ });
183
+ });
184
+ });
185
+ });
186
+
187
+ const shown = (a: Candidate, b: Candidate) =>
188
+ a.rank - b.rank || a.release - b.release || a.section - b.section || a.part - b.part || a.change - b.change;
189
+ // A forced highlight is guaranteed a place; the rest are taken in the order they are shown.
190
+ const kept = new Set(
191
+ [...candidates]
192
+ .sort((a, b) => Number(b.forced) - Number(a.forced) || shown(a, b))
193
+ .slice(0, Math.max(0, Math.floor(maxItems))),
194
+ );
195
+ const highlights = candidates
196
+ .filter((candidate) => kept.has(candidate))
197
+ .sort(shown)
198
+ .map((candidate) => candidate.highlight);
199
+
200
+ const worthShowing = candidates.some((candidate) => candidate.forced || showFor.includes(candidate.highlight.type));
201
+
202
+ return {
203
+ ...nothing,
204
+ since: stored,
205
+ releaseCount: unseen.length,
206
+ highlights,
207
+ moreCount: candidates.length - highlights.length,
208
+ anchor: unseen[0] ? releaseAnchor(unseen[0].version) : null,
209
+ shouldShow: worthShowing && longEnoughSince(releases, stored, minDaysBetween, now),
210
+ };
211
+ }
212
+
213
+ /**
214
+ * Whether `minDaysBetween` days have passed since the stored version's release
215
+ * date. A version the changelog doesn't hold, or a date that won't parse, has
216
+ * nothing to wait for.
217
+ */
218
+ function longEnoughSince(
219
+ releases: readonly ChangelogRelease[],
220
+ stored: string,
221
+ minDaysBetween: number,
222
+ now: Date | number | undefined,
223
+ ): boolean {
224
+ if (!(minDaysBetween > 0)) return true;
225
+ const seen = releases.find((release) => release.version === stored);
226
+ const released = seen ? Date.parse(`${seen.date}T00:00:00Z`) : Number.NaN;
227
+ if (Number.isNaN(released)) return true;
228
+ const at = now === undefined ? Date.now() : typeof now === "number" ? now : now.getTime();
229
+ return at - released >= minDaysBetween * DAY_MS;
230
+ }
@@ -0,0 +1,109 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+
5
+ import { useActionReporter } from "../ux/feedback.js";
6
+ import type { WhatsNewData } from "./select.js";
7
+
8
+ export interface UseWhatsNewOptions {
9
+ /** `whatsNew(...)` from the signed-in layout, or null for nobody (signed out, or not in the audience). */
10
+ initial: WhatsNewData | null;
11
+ /**
12
+ * Store the version the person has now seen — the app's `POST /api/whats-new/seen`.
13
+ * `false` or a throw means it did not take. Use `keepalive` on the request:
14
+ * following the changelog link may unload the page while it is in flight.
15
+ */
16
+ markSeen: (version: string) => Promise<boolean>;
17
+ /** Somebody viewing as this person: never opens, never stores. */
18
+ readOnly?: boolean;
19
+ }
20
+
21
+ export interface WhatsNew {
22
+ open: boolean;
23
+ /** For the dialog's `onOpenChange`. Closing it any way — Escape, a click outside — counts as seen. */
24
+ setOpen: (open: boolean) => void;
25
+ data: WhatsNewData | null;
26
+ /** Close at once and store `latestVersion`. */
27
+ dismiss: () => void;
28
+ /** For the changelog link: following it counts as seen. */
29
+ onChangelogClick: () => void;
30
+ }
31
+
32
+ /**
33
+ * When the "what's new" dialog opens, and what closing it stores.
34
+ *
35
+ * It opens once, on mount, when the server said `shouldShow` — never while
36
+ * someone is viewing as the person. A new account (`stampSilently`) stores the
37
+ * newest version without opening, so its first visit after the next release
38
+ * says only what came out since it arrived. Closing, however it's done, closes
39
+ * at once and stores the newest version; if that fails the person is told
40
+ * through the app's `ActionFeedbackProvider`, and the dialog stays closed for
41
+ * this visit rather than coming back to ask again.
42
+ */
43
+ export function useWhatsNew({ initial, markSeen, readOnly = false }: UseWhatsNewOptions): WhatsNew {
44
+ const report = useActionReporter();
45
+ const [open, setOpenState] = React.useState(false);
46
+ const isOpen = React.useRef(false);
47
+ const started = React.useRef(false);
48
+ const stored = React.useRef(false);
49
+
50
+ // Read through a ref so the callbacks below keep one identity across renders.
51
+ const latest = React.useRef({ initial, markSeen, readOnly, report });
52
+ React.useEffect(() => {
53
+ latest.current = { initial, markSeen, readOnly, report };
54
+ });
55
+
56
+ const store = React.useCallback(async (quietly: boolean) => {
57
+ const { initial: data, markSeen: save, readOnly: viewingAs, report: tell } = latest.current;
58
+ if (!data || viewingAs || stored.current) return;
59
+ stored.current = true;
60
+ let saved = false;
61
+ try {
62
+ saved = await save(data.latestVersion);
63
+ } catch {
64
+ saved = false;
65
+ }
66
+ if (saved) return;
67
+ // Not stored: the next visit may ask again, which is the honest outcome of a failed save.
68
+ stored.current = false;
69
+ if (quietly) return;
70
+ tell({
71
+ tone: "error",
72
+ title: "Couldn't save that you've seen what's new",
73
+ description: "It may show again next time you visit.",
74
+ });
75
+ }, []);
76
+
77
+ const show = React.useCallback((next: boolean) => {
78
+ isOpen.current = next;
79
+ setOpenState(next);
80
+ }, []);
81
+
82
+ // Once, the first time there is an answer: a later render with fresh data must not reopen what was just closed.
83
+ React.useEffect(() => {
84
+ if (started.current || !initial) return;
85
+ started.current = true;
86
+ if (readOnly) return;
87
+ if (initial.stampSilently) {
88
+ void store(true);
89
+ return;
90
+ }
91
+ if (initial.shouldShow) show(true);
92
+ }, [initial, readOnly, store, show]);
93
+
94
+ const dismiss = React.useCallback(() => {
95
+ show(false);
96
+ void store(false);
97
+ }, [store, show]);
98
+
99
+ const setOpen = React.useCallback(
100
+ (next: boolean) => {
101
+ if (next) show(true);
102
+ // Closing what is open is a dismissal; "closing" what never opened stores nothing.
103
+ else if (isOpen.current) dismiss();
104
+ },
105
+ [dismiss, show],
106
+ );
107
+
108
+ return { open, setOpen, data: initial, dismiss, onChangelogClick: dismiss };
109
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * `@connextar/house/wizard` — one long form, split into steps that check
3
+ * themselves.
4
+ *
5
+ * Five apps wrote this and four of them shipped a defect in it: a booking
6
+ * created from step two because two buttons shared a slot and React switched the
7
+ * type mid-click; three forms that refused to save with nothing on screen saying
8
+ * why; a stepper that checked no step at all on submit and sent a record whose
9
+ * first step had been cleared. None of those are mistakes about wizards. They are
10
+ * mistakes about what a form must do before it agrees to send, and there is one
11
+ * right answer to that, which is why this is here rather than in five places.
12
+ *
13
+ * Form-library-agnostic on purpose: the host supplies the check
14
+ * (`onValidateStep`, or a `validate` on the step), so react-hook-form, plain
15
+ * state and a form held in `useState` can all host it. The react-hook-form
16
+ * adapter is `@connextar/house/wizard/react-hook-form`, kept apart so that
17
+ * `react-hook-form` stays the optional peer dependency it is declared to be.
18
+ *
19
+ * What reaches the person, when a refusal has nowhere to show itself, goes
20
+ * through the `ActionFeedbackProvider` from `@connextar/house/ux` — so this
21
+ * module imports no toast library and no design system.
22
+ */
23
+ export {
24
+ ERROR_ATTRIBUTE,
25
+ fieldProblems,
26
+ INVALID_MESSAGES,
27
+ isOnScreen,
28
+ REPORT_DELAY,
29
+ reportInvalid,
30
+ shownErrorFields,
31
+ unseenProblems,
32
+ useInvalidReporter,
33
+ type FieldProblem,
34
+ type InvalidMessages,
35
+ type InvalidReporter,
36
+ } from "./invalid.js";
37
+ export {
38
+ checkStep,
39
+ firstFailure,
40
+ isReachable,
41
+ markerState,
42
+ nextIndex,
43
+ percentComplete,
44
+ previousIndex,
45
+ stepResult,
46
+ type MarkerState,
47
+ type StepCheck,
48
+ type StepCheckable,
49
+ type StepFailure,
50
+ type StepOutcome,
51
+ type StepResult,
52
+ } from "./rules.js";
53
+ export {
54
+ FieldError,
55
+ FormWizard,
56
+ ReviewRow,
57
+ WIZARD_CLASS_NAMES,
58
+ type FormWizardProps,
59
+ type WizardClassNames,
60
+ type WizardStep,
61
+ } from "./wizard.js";
@@ -0,0 +1,152 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+
5
+ import { useActionReporter, type ActionReporter } from "../ux/feedback.js";
6
+
7
+ /**
8
+ * Saying why a form refused, when the reason is somewhere nobody can look.
9
+ *
10
+ * A wizard keeps fields on steps that are mounted but hidden, and a form library
11
+ * will not call a submit handler while any field is invalid. An error shown
12
+ * beside its field speaks for itself. One on a field nobody can see — another
13
+ * step, a field the form hides because it does not apply, a rule that belongs to
14
+ * no field at all — makes the button look broken, and that one has to be said
15
+ * out loud. This is the half of the wizard that has to read the DOM, so it is
16
+ * kept apart from the rules.
17
+ *
18
+ * Where it is said is the app's decision, not this package's: the message goes to
19
+ * the `ActionFeedbackProvider` that `@connextar/house/ux` already defines, so an
20
+ * app wires one reporter to whatever it uses to tell people things and this
21
+ * module imports no toast library.
22
+ */
23
+
24
+ /**
25
+ * The attribute a field's error message carries, so a visible one can be told
26
+ * from a hidden one. `FieldError` sets it; an app's own message component sets
27
+ * it too (`<p data-error-for="title">`), which is the whole integration.
28
+ */
29
+ export const ERROR_ATTRIBUTE = "data-error-for";
30
+
31
+ /** How long to wait before looking. */
32
+ export const REPORT_DELAY = 50;
33
+
34
+ export interface InvalidMessages {
35
+ /** The heading. */
36
+ title: string;
37
+ /** Used when no problem carried a message of its own. */
38
+ fallback: string;
39
+ }
40
+
41
+ export const INVALID_MESSAGES: InvalidMessages = {
42
+ title: "That can't be saved yet",
43
+ fallback: "Something on the form needs changing — check the highlighted fields.",
44
+ };
45
+
46
+ export interface FieldProblem {
47
+ name: string;
48
+ message: string | null;
49
+ }
50
+
51
+ /**
52
+ * The problems in an error object, whatever shape the form library gave them.
53
+ * Only the entries that are objects count: a form library's error map holds one
54
+ * per field, and anything else in there is not a field error.
55
+ */
56
+ export function fieldProblems(errors: object): FieldProblem[] {
57
+ return Object.entries(errors).flatMap(([name, value]) => {
58
+ if (typeof value !== "object" || value === null) return [];
59
+ const message = (value as { message?: unknown }).message;
60
+ return [{ name, message: typeof message === "string" && message !== "" ? message : null }];
61
+ });
62
+ }
63
+
64
+ /**
65
+ * Rendered, outside a hidden step, and — where the page has layout at all —
66
+ * taking up space.
67
+ *
68
+ * A DOM without layout, like a test's, has no boxes to measure, so `hidden`
69
+ * decides there on its own. Measuring alone was AltEd's version, and under jsdom
70
+ * it called every message invisible and said everything twice.
71
+ */
72
+ export function isOnScreen(element: HTMLElement): boolean {
73
+ if (element.closest("[hidden]")) return false;
74
+ const hasLayout = element.ownerDocument.documentElement.getClientRects().length > 0;
75
+ return !hasLayout || element.getClientRects().length > 0;
76
+ }
77
+
78
+ /** The field names whose message is on screen right now. */
79
+ export function shownErrorFields(root: ParentNode): string[] {
80
+ return [...root.querySelectorAll<HTMLElement>(`[${ERROR_ATTRIBUTE}]`)]
81
+ .filter(isOnScreen)
82
+ .map((element) => element.getAttribute(ERROR_ATTRIBUTE) ?? "");
83
+ }
84
+
85
+ /**
86
+ * The problems with nothing on screen to show them.
87
+ *
88
+ * A name matches a shown message exactly, or as its prefix: an error on
89
+ * `times` is answered by a message on `times.0.start`, because that is where a
90
+ * form library puts the message for an array field's row.
91
+ */
92
+ export function unseenProblems(problems: readonly FieldProblem[], shown: readonly string[]): FieldProblem[] {
93
+ return problems.filter(({ name }) => !shown.some((on) => on === name || on.startsWith(`${name}.`)));
94
+ }
95
+
96
+ export type InvalidReporter = (errors: object) => void;
97
+
98
+ /**
99
+ * Report the errors an invalid form refused on, if any of them has nowhere to
100
+ * show itself.
101
+ *
102
+ * Deferred, because it has to run after the form has re-rendered with its errors
103
+ * and after a wizard has moved to the failing step — before that, every message
104
+ * is still hidden and it would say everything twice. Returns a way to cancel,
105
+ * for a component that unmounts in between.
106
+ *
107
+ * Two silences and one noise:
108
+ *
109
+ * - Problems, all of them showing → quiet. The fields say it better.
110
+ * - Problems, at least one unseen → the first unseen message, or the fallback.
111
+ * - **No problems at all → the fallback**, not quiet. A form that refuses with
112
+ * an empty error map is the worst of the cases, not the mildest: something
113
+ * said no and named nothing, and the person is left pressing a dead button.
114
+ */
115
+ export function reportInvalid(
116
+ errors: object,
117
+ report: ActionReporter,
118
+ options: { delay?: number; root?: ParentNode; messages?: Partial<InvalidMessages> } = {},
119
+ ): () => void {
120
+ const { delay = REPORT_DELAY, messages } = options;
121
+ const words = { ...INVALID_MESSAGES, ...messages };
122
+ const problems = fieldProblems(errors);
123
+
124
+ const timer = setTimeout(() => {
125
+ const root = options.root ?? globalThis.document;
126
+ const unseen = unseenProblems(problems, shownErrorFields(root));
127
+ if (problems.length > 0 && unseen.length === 0) return;
128
+ const message = unseen.map((problem) => problem.message).find((text): text is string => text !== null);
129
+ report({ tone: "error", title: words.title, description: message ?? words.fallback });
130
+ }, delay);
131
+
132
+ return () => clearTimeout(timer);
133
+ }
134
+
135
+ /**
136
+ * `reportInvalid` bound to the app's reporter — pass it straight to a form
137
+ * library's invalid handler (`handleSubmit(onSubmit, report)`), or let
138
+ * `stepValidator` from `@connextar/house/wizard/react-hook-form` call it.
139
+ */
140
+ export function useInvalidReporter(messages?: Partial<InvalidMessages>): InvalidReporter {
141
+ const report = useActionReporter();
142
+ const title = messages?.title;
143
+ const fallback = messages?.fallback;
144
+ return React.useCallback(
145
+ (errors: object) => {
146
+ reportInvalid(errors, report, {
147
+ messages: { ...(title === undefined ? {} : { title }), ...(fallback === undefined ? {} : { fallback }) },
148
+ });
149
+ },
150
+ [report, title, fallback],
151
+ );
152
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `@connextar/house/wizard/react-hook-form` — the step check for a
3
+ * react-hook-form wizard.
4
+ *
5
+ * Its own entry point so that `react-hook-form` stays an optional peer
6
+ * dependency: every import of it in here is `import type`, which erases, but a
7
+ * declaration file that names a package an app has not installed still fails
8
+ * that app's typecheck. An app on plain state imports `@connextar/house/wizard`
9
+ * and never comes near this.
10
+ */
11
+ export { stepValidator, useStepValidator } from "./rhf-adapter.js";
@@ -0,0 +1,67 @@
1
+ "use client";
2
+
3
+ import * as React from "react";
4
+ import type { FieldPath, FieldValues, UseFormReturn } from "react-hook-form";
5
+
6
+ import { useInvalidReporter, type InvalidReporter } from "./invalid.js";
7
+ import type { StepCheck } from "./rules.js";
8
+
9
+ /**
10
+ * `@connextar/house/wizard/react-hook-form` — the step check most of the cohort
11
+ * wants, for the library most of the cohort uses.
12
+ *
13
+ * Its own entry point, and the reason is types rather than code: every import
14
+ * from `react-hook-form` here is `import type`, so the emitted JavaScript
15
+ * mentions it nowhere and an app without it can still run every part of
16
+ * `@connextar/house/wizard`. What an app without it *cannot* do is typecheck a
17
+ * declaration file that names the package — so the names live behind a subpath
18
+ * nobody has to reach for. MAS has no `react-hook-form` and never will;
19
+ * `entry-points.test.ts` keeps this split honest.
20
+ */
21
+
22
+ /**
23
+ * The usual step check for a react-hook-form wizard: validate just this step's
24
+ * fields, and when one fails, say why if its message is not on screen.
25
+ *
26
+ * Returns `false` rather than a sentence, because a form library puts its
27
+ * messages beside the fields they belong to and a second copy in a banner above
28
+ * them is noise. The exception is the message with nowhere to go, which is what
29
+ * the reporter is for.
30
+ */
31
+ export function stepValidator<T extends FieldValues>(form: UseFormReturn<T>, report: InvalidReporter): StepCheck {
32
+ return async (fields) => {
33
+ if (fields.length === 0) return true;
34
+ const names = fields as FieldPath<T>[];
35
+ const ok = await form.trigger(names);
36
+ if (ok) return true;
37
+ report(
38
+ Object.fromEntries(
39
+ names.flatMap((name) => {
40
+ const error = form.getFieldState(name).error;
41
+ return error ? [[name, error] as const] : [];
42
+ }),
43
+ ),
44
+ );
45
+ return false;
46
+ };
47
+ }
48
+
49
+ /**
50
+ * `stepValidator` wired to the app's `ActionFeedbackProvider`, with an identity
51
+ * that does not change between renders — a check that is a new function on every
52
+ * render makes the wizard re-render every step's content for nothing.
53
+ */
54
+ export function useStepValidator<T extends FieldValues>(form: UseFormReturn<T>): StepCheck {
55
+ const report = useInvalidReporter();
56
+ // Written after the render, so the check always reads the current form and
57
+ // reporter without itself having to change.
58
+ const latest = React.useRef({ form, report });
59
+ React.useEffect(() => {
60
+ latest.current = { form, report };
61
+ });
62
+
63
+ return React.useCallback<StepCheck>((fields, step) => {
64
+ const { form: current, report: tell } = latest.current;
65
+ return stepValidator(current, tell)(fields, step);
66
+ }, []);
67
+ }