@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,92 @@
1
+ import { ChevronLeft } from "lucide-react";
2
+
3
+ import { Link } from "../internal/next-link.js";
4
+ import type { GuideFigures } from "../markdown/figures.js";
5
+ import { extractHeadings, GuideMarkdown, type GuideClassNames } from "../markdown/guide.js";
6
+ import { GuideFigure } from "./guide-figure.js";
7
+ import type { GuideZoomClassNames } from "./guide-figure-zoom.js";
8
+ import { GuideToc } from "./guide-toc.js";
9
+ import { GUIDES_LABELS, type GuidesLabels } from "./library.js";
10
+
11
+ export interface GuideArticleProps {
12
+ /** The guide as `parseGuideFrontmatter` splits it. */
13
+ guide: { title: string; lede?: string; body: string };
14
+ /** Where "All guides" goes, and where relative links (`settings.md`) resolve. */
15
+ guidesPath: string;
16
+ /** The file name (without `.md`) of the guide index, which links to `guidesPath` itself. */
17
+ indexSlug?: string;
18
+ /** The category, shown above the title. */
19
+ category?: string;
20
+ labels?: Partial<GuidesLabels>;
21
+ classNames?: Partial<GuideClassNames>;
22
+ /**
23
+ * The pictures this app's guides may show (`![alt](/guide-images/x.webp "Caption")` and
24
+ * `![alt](diagram:name)` on a line of their own). Unregistered ones are left out.
25
+ */
26
+ figures?: GuideFigures;
27
+ /** Open a picture full-size on a click, Enter or Space. Default: on. */
28
+ zoom?: boolean;
29
+ zoomClassNames?: Partial<GuideZoomClassNames>;
30
+ }
31
+
32
+ /**
33
+ * One guide, laid out for reading inside `GuidesShell`: a way back to all guides, the category,
34
+ * the title and lede, the article drawn by `GuideMarkdown`, and "On this page" — a rail that
35
+ * follows the reader on wide screens, a collapsible list above the article on narrow ones. The
36
+ * contents use the same heading ids the renderer gives, so `#<heading id>` links land.
37
+ * Registered pictures are drawn where the guide names them, each opening full-size.
38
+ * Server-safe; the contents and the zoom are the only client parts.
39
+ */
40
+ export function GuideArticle({
41
+ guide,
42
+ guidesPath,
43
+ indexSlug,
44
+ category,
45
+ labels,
46
+ classNames,
47
+ figures,
48
+ zoom,
49
+ zoomClassNames,
50
+ }: GuideArticleProps) {
51
+ const text = { ...GUIDES_LABELS, ...labels };
52
+ const headings = extractHeadings(guide.body);
53
+
54
+ return (
55
+ <div className="xl:grid xl:grid-cols-[minmax(0,1fr)_13rem] xl:gap-12">
56
+ <article className="max-w-3xl min-w-0">
57
+ <Link
58
+ href={guidesPath}
59
+ className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
60
+ >
61
+ <ChevronLeft className="size-4" aria-hidden /> {text.allGuides}
62
+ </Link>
63
+ {category ? (
64
+ <p className="mt-5 text-xs font-bold tracking-[0.14em] text-primary uppercase">{category}</p>
65
+ ) : null}
66
+ <h1 className="mt-2 text-3xl font-bold tracking-tight text-foreground sm:text-4xl">{guide.title}</h1>
67
+ {guide.lede ? <p className="mt-3 text-lg text-muted-foreground">{guide.lede}</p> : null}
68
+ <div className="mt-8">
69
+ <GuideToc headings={headings} variant="inline" labels={labels} />
70
+ </div>
71
+ <GuideMarkdown
72
+ content={guide.body}
73
+ guidesPath={guidesPath}
74
+ indexSlug={indexSlug}
75
+ classNames={classNames}
76
+ figures={figures}
77
+ renderFigure={(figure) => (
78
+ <GuideFigure
79
+ figure={figure}
80
+ figures={figures}
81
+ zoom={zoom}
82
+ labels={labels}
83
+ classNames={classNames?.figure}
84
+ zoomClassNames={zoomClassNames}
85
+ />
86
+ )}
87
+ />
88
+ </article>
89
+ <GuideToc headings={headings} variant="rail" labels={labels} />
90
+ </div>
91
+ );
92
+ }
@@ -0,0 +1,533 @@
1
+ "use client";
2
+
3
+ import * as DialogPrimitive from "@radix-ui/react-dialog";
4
+ import { Maximize2, X, ZoomIn, ZoomOut } from "lucide-react";
5
+ import {
6
+ useCallback,
7
+ useEffect,
8
+ useRef,
9
+ useState,
10
+ type KeyboardEvent as ReactKeyboardEvent,
11
+ type PointerEvent as ReactPointerEvent,
12
+ type ReactNode,
13
+ } from "react";
14
+
15
+ import { cx } from "../internal/cx.js";
16
+ import { GUIDES_LABELS, type GuidesLabels } from "./library.js";
17
+
18
+ /**
19
+ * Every element the zoom draws. Each value replaces the default for that element. A part added after
20
+ * 0.18.0 is optional, so an app that writes out a whole `GuideZoomClassNames` keeps typechecking.
21
+ */
22
+ export interface GuideZoomClassNames {
23
+ /** The button around the picture in the article. */
24
+ trigger: string;
25
+ /**
26
+ * The row under the picture with "Click to enlarge" (or "Tap to enlarge"): under it rather than over
27
+ * its corner, so it never covers part of a small diagram on a phone.
28
+ */
29
+ hint: string;
30
+ /** The words shown where the pointer is a mouse or a trackpad. Optional: a later addition. */
31
+ hintPointer?: string;
32
+ /** The words shown on a touch screen (`@media (pointer: coarse)`). Optional: a later addition. */
33
+ hintTouch?: string;
34
+ overlay: string;
35
+ /** The dialog: the whole screen on a phone, inset on wider ones. */
36
+ content: string;
37
+ toolbar: string;
38
+ instructions: string;
39
+ button: string;
40
+ /** The zoom level, a button that switches between fit and full size. */
41
+ level: string;
42
+ /** The area the picture is zoomed and dragged in. */
43
+ stage: string;
44
+ /** Under the picture: the caption and the alt text. */
45
+ footer: string;
46
+ caption: string;
47
+ alt: string;
48
+ /**
49
+ * Added to `alt` while the description is folded away: hidden on a phone, shown on wider screens. Still
50
+ * the dialog's description for a screen reader either way. Optional: a later addition.
51
+ */
52
+ altFolded?: string;
53
+ /**
54
+ * Added to `caption` while folded when there is no caption and the alt text stands in as the title:
55
+ * two lines on a phone. Optional: a later addition.
56
+ */
57
+ titleFolded?: string;
58
+ /** The "Show description" button, on a phone only. Optional: a later addition. */
59
+ more?: string;
60
+ }
61
+
62
+ export const GUIDE_ZOOM_CLASS_NAMES: Required<GuideZoomClassNames> = {
63
+ trigger:
64
+ "group relative block w-full cursor-zoom-in rounded-xl text-left focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:ring-offset-2 focus-visible:ring-offset-background focus-visible:outline-none",
65
+ // In the flow under the picture, not over it: at 375px a pill in the corner covered a box of a small diagram.
66
+ hint: "mt-1.5 flex items-center justify-end gap-1 text-xs leading-4 font-medium text-muted-foreground transition-colors group-hover:text-foreground group-focus-visible:text-foreground motion-reduce:transition-none",
67
+ // Both are drawn and CSS shows one, so the server's HTML is right for the reader's screen with no script.
68
+ hintPointer: "pointer-coarse:hidden",
69
+ hintTouch: "hidden pointer-coarse:inline",
70
+ overlay: "fixed inset-0 z-50 bg-black/70 backdrop-blur-sm",
71
+ content:
72
+ "fixed inset-0 z-50 flex flex-col overflow-hidden bg-background text-foreground shadow-2xl outline-none sm:inset-4 sm:rounded-xl sm:border sm:border-border",
73
+ toolbar: "flex shrink-0 items-center gap-1 border-b border-border px-2 py-1.5 sm:px-3",
74
+ instructions: "mr-auto hidden min-w-0 truncate pl-1 text-xs text-muted-foreground sm:block",
75
+ button:
76
+ "inline-flex size-10 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-40",
77
+ level:
78
+ "h-10 min-w-16 rounded-lg px-2 text-sm font-medium text-foreground tabular-nums hover:bg-accent focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:outline-none",
79
+ stage: "relative min-h-0 flex-1 touch-none overflow-hidden bg-muted/40 select-none",
80
+ // Folded, the footer on a phone is a line or two; opened, it may take more of the screen than on a wider one.
81
+ footer: "max-h-[45%] shrink-0 overflow-y-auto border-t border-border px-4 py-3 text-sm sm:max-h-[30%]",
82
+ caption: "font-medium text-foreground",
83
+ alt: "mt-1 text-muted-foreground",
84
+ altFolded: "hidden sm:block",
85
+ titleFolded: "line-clamp-2 sm:line-clamp-none",
86
+ more: "mt-1 -ml-1 inline-flex min-h-10 items-center rounded px-1 text-sm font-medium text-primary hover:underline focus-visible:ring-2 focus-visible:ring-primary/40 focus-visible:outline-none sm:hidden",
87
+ };
88
+
89
+ /**
90
+ * Alt text longer than this, standing in as the title, is folded to two lines on a phone. A short one is
91
+ * shown whole, with no button.
92
+ */
93
+ const FOLDED_TITLE_CHARS = 90;
94
+
95
+ export interface GuideFigureZoomProps {
96
+ /** The picture as the article draws it: the button's content. */
97
+ children: ReactNode;
98
+ /** What the dialog shows, laid out at the natural size and scaled. Default: `children` again. */
99
+ full?: ReactNode;
100
+ /**
101
+ * The picture's natural size in CSS pixels — a screenshot's registered size, so "full size"
102
+ * is one image pixel to one CSS pixel. Left out (a diagram), it is measured from the article's
103
+ * picture when the dialog opens, and full size is twice the fit.
104
+ */
105
+ width?: number;
106
+ height?: number;
107
+ alt: string;
108
+ caption?: string;
109
+ labels?: Partial<GuidesLabels>;
110
+ classNames?: Partial<GuideZoomClassNames>;
111
+ }
112
+
113
+ interface Size {
114
+ w: number;
115
+ h: number;
116
+ }
117
+ interface Point {
118
+ x: number;
119
+ y: number;
120
+ }
121
+
122
+ /** Each button press or key multiplies or divides the zoom by this. */
123
+ export const ZOOM_STEP = 1.25;
124
+ /** The margin kept around a fitted picture, in CSS pixels, each side. */
125
+ const FIT_MARGIN = 16;
126
+ /** Used when nothing can be measured (a page not laid out yet, or a test's DOM). */
127
+ const FALLBACK_SIZE: Size = { w: 800, h: 600 };
128
+
129
+ const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value));
130
+ const near = (a: number, b: number) => Math.abs(a - b) < 0.005;
131
+
132
+ /** The scale that fits `natural` inside `stage`, never past full size for a picture with a natural size. */
133
+ export function fitScale(natural: Size, stage: Size, capAtFull: boolean): number {
134
+ const w = stage.w - 2 * FIT_MARGIN;
135
+ const h = stage.h - 2 * FIT_MARGIN;
136
+ if (w <= 0 || h <= 0 || natural.w <= 0 || natural.h <= 0) return 1;
137
+ const fit = Math.min(w / natural.w, h / natural.h);
138
+ return capAtFull ? Math.min(fit, 1) : fit;
139
+ }
140
+
141
+ /**
142
+ * A guide's picture, opened full-size: a button around the article's picture (with a "Click to
143
+ * enlarge" hint under it, "Tap to enlarge" on a touch screen) that opens a dialog fitting it to
144
+ * the screen. In there it zooms with the buttons, `+` and `−`, ⌘/Ctrl + scroll (a trackpad
145
+ * pinch) and a touch pinch; drags to pan when it is bigger than the screen (and scrolls, and
146
+ * moves with the arrow keys); a double-click or double-tap switches between fit and full size,
147
+ * and `0` fits again. Escape closes it and focus goes back to the picture. The caption and alt
148
+ * text are shown under it; on a phone the alt text (or a long one standing in as the title) waits
149
+ * behind "Show description", so the picture keeps the screen, and is still read out as the
150
+ * dialog's description.
151
+ *
152
+ * Zooming eases unless the reader prefers reduced motion; dragging and pinching never do.
153
+ */
154
+ export function GuideFigureZoom({
155
+ children,
156
+ full,
157
+ width,
158
+ height,
159
+ alt,
160
+ caption,
161
+ labels,
162
+ classNames,
163
+ }: GuideFigureZoomProps) {
164
+ const text = { ...GUIDES_LABELS, ...labels };
165
+ // An app that changed `zoomHint` (another language, say) and not `zoomHintTouch` keeps its own word on a phone.
166
+ const hintTouch = labels?.zoomHintTouch ?? labels?.zoomHint ?? GUIDES_LABELS.zoomHintTouch;
167
+ const c = { ...GUIDE_ZOOM_CLASS_NAMES, ...classNames };
168
+ const known = width !== undefined && height !== undefined && width > 0 && height > 0;
169
+
170
+ const [open, setOpen] = useState(false);
171
+ const [natural, setNatural] = useState<Size>(known ? { w: width, h: height } : FALLBACK_SIZE);
172
+ const [stage, setStage] = useState<Size>({ w: 0, h: 0 });
173
+ const [stageEl, setStageEl] = useState<HTMLDivElement | null>(null);
174
+ /** null: fitted, and staying fitted as the window changes size. */
175
+ const [zoom, setZoom] = useState<number | null>(null);
176
+ const [offset, setOffset] = useState<Point>({ x: 0, y: 0 });
177
+ const [gesture, setGesture] = useState<"drag" | "pinch" | null>(null);
178
+ /** Whether a phone shows the description. It starts folded each time the picture opens. */
179
+ const [described, setDescribed] = useState(false);
180
+ const thumb = useRef<HTMLSpanElement>(null);
181
+
182
+ const fit = fitScale(natural, stage, known);
183
+ const min = fit;
184
+ const max = Math.max(fit, 1) * 4;
185
+ const scale = clamp(zoom ?? fit, min, max);
186
+ /** Where a double-click goes from fit: full size, or twice the fit when that is already full size. */
187
+ const detail = clamp(known && fit < 1 ? 1 : fit * 2, min, max);
188
+
189
+ /** An offset that keeps the picture over the stage: centred on an axis where it fits, edge to edge where not. */
190
+ const bound = useCallback(
191
+ (point: Point, s: number): Point => {
192
+ const limitX = Math.max(0, (natural.w * s - stage.w) / 2);
193
+ const limitY = Math.max(0, (natural.h * s - stage.h) / 2);
194
+ return { x: clamp(point.x, -limitX, limitX), y: clamp(point.y, -limitY, limitY) };
195
+ },
196
+ [natural, stage],
197
+ );
198
+
199
+ // The latest view, for the listeners and gestures that outlive a render.
200
+ const view = useRef({ scale, offset, fit, min, max, detail, bound });
201
+ view.current = { scale, offset, fit, min, max, detail, bound };
202
+
203
+ /** Zoom to `next`, keeping the point `origin` (from the stage's centre) where it is. */
204
+ const zoomTo = useCallback((next: number, origin: Point = { x: 0, y: 0 }) => {
205
+ const v = view.current;
206
+ const s = clamp(next, v.min, v.max);
207
+ const ratio = s / v.scale;
208
+ const moved = {
209
+ x: origin.x - (origin.x - v.offset.x) * ratio,
210
+ y: origin.y - (origin.y - v.offset.y) * ratio,
211
+ };
212
+ setZoom(near(s, v.fit) ? null : s);
213
+ setOffset(near(s, v.fit) ? { x: 0, y: 0 } : v.bound(moved, s));
214
+ }, []);
215
+
216
+ const panBy = useCallback((dx: number, dy: number) => {
217
+ const v = view.current;
218
+ setOffset(v.bound({ x: v.offset.x + dx, y: v.offset.y + dy }, v.scale));
219
+ }, []);
220
+
221
+ const toggle = useCallback(
222
+ (origin?: Point) => {
223
+ const v = view.current;
224
+ zoomTo(near(v.scale, v.fit) ? v.detail : v.fit, origin);
225
+ },
226
+ [zoomTo],
227
+ );
228
+
229
+ /** A point on the screen, measured from the stage's centre. */
230
+ const fromCentre = useCallback(
231
+ (clientX: number, clientY: number): Point => {
232
+ if (!stageEl) return { x: 0, y: 0 };
233
+ const rect = stageEl.getBoundingClientRect();
234
+ return { x: clientX - rect.left - rect.width / 2, y: clientY - rect.top - rect.height / 2 };
235
+ },
236
+ [stageEl],
237
+ );
238
+
239
+ // The stage's size, kept as the window changes.
240
+ useEffect(() => {
241
+ if (!stageEl) return;
242
+ const measure = () => {
243
+ const rect = stageEl.getBoundingClientRect();
244
+ setStage({ w: rect.width, h: rect.height });
245
+ };
246
+ measure();
247
+ window.addEventListener("resize", measure);
248
+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);
249
+ observer?.observe(stageEl);
250
+ return () => {
251
+ window.removeEventListener("resize", measure);
252
+ observer?.disconnect();
253
+ };
254
+ }, [stageEl]);
255
+
256
+ // ⌘/Ctrl + wheel (and a trackpad pinch, which arrives as one) zooms at the pointer; a plain wheel pans a zoomed
257
+ // picture. Not React's onWheel: that listener is passive, so it can't stop the page zooming instead.
258
+ useEffect(() => {
259
+ if (!stageEl) return;
260
+ const onWheel = (event: WheelEvent) => {
261
+ const v = view.current;
262
+ if (event.ctrlKey || event.metaKey) {
263
+ event.preventDefault();
264
+ const rect = stageEl.getBoundingClientRect();
265
+ const origin = { x: event.clientX - rect.left - rect.width / 2, y: event.clientY - rect.top - rect.height / 2 };
266
+ zoomTo(v.scale * Math.exp(-clamp(event.deltaY, -50, 50) / 100), origin);
267
+ } else if (!near(v.scale, v.fit)) {
268
+ event.preventDefault();
269
+ panBy(-event.deltaX, -event.deltaY);
270
+ }
271
+ };
272
+ stageEl.addEventListener("wheel", onWheel, { passive: false });
273
+ return () => stageEl.removeEventListener("wheel", onWheel);
274
+ }, [stageEl, zoomTo, panBy]);
275
+
276
+ // Pointers on the stage: one drags, two pinch. A quick second tap (touch or pen) switches fit and full size.
277
+ const pointers = useRef(new Map<number, Point>());
278
+ const start = useRef<{
279
+ scale: number;
280
+ offset: Point;
281
+ point: Point;
282
+ distance: number;
283
+ at: number;
284
+ moved: boolean;
285
+ } | null>(null);
286
+ const lastTap = useRef<{ at: number; point: Point } | null>(null);
287
+
288
+ const beginGesture = () => {
289
+ const points = [...pointers.current.values()];
290
+ const [a, b] = points;
291
+ if (!a) return;
292
+ const point = b ? { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 } : a;
293
+ const distance = b ? Math.hypot(a.x - b.x, a.y - b.y) : 0;
294
+ start.current = {
295
+ scale: view.current.scale,
296
+ offset: view.current.offset,
297
+ point,
298
+ distance,
299
+ at: Date.now(),
300
+ moved: false,
301
+ };
302
+ setGesture(b ? "pinch" : "drag");
303
+ };
304
+
305
+ const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
306
+ if (event.pointerType === "mouse" && event.button !== 0) return;
307
+ event.currentTarget.setPointerCapture?.(event.pointerId);
308
+ pointers.current.set(event.pointerId, fromCentre(event.clientX, event.clientY));
309
+ if (pointers.current.size <= 2) beginGesture();
310
+ };
311
+
312
+ const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
313
+ if (!pointers.current.has(event.pointerId) || !start.current) return;
314
+ pointers.current.set(event.pointerId, fromCentre(event.clientX, event.clientY));
315
+ const s = start.current;
316
+ const [a, b] = [...pointers.current.values()];
317
+ if (!a) return;
318
+ if (b && s.distance > 0) {
319
+ s.moved = true;
320
+ const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
321
+ const v = view.current;
322
+ const next = clamp((s.scale * Math.hypot(a.x - b.x, a.y - b.y)) / s.distance, v.min, v.max);
323
+ const ratio = next / s.scale;
324
+ setZoom(near(next, v.fit) ? null : next);
325
+ setOffset(
326
+ v.bound({ x: mid.x - (s.point.x - s.offset.x) * ratio, y: mid.y - (s.point.y - s.offset.y) * ratio }, next),
327
+ );
328
+ } else if (!b) {
329
+ const dx = a.x - s.point.x;
330
+ const dy = a.y - s.point.y;
331
+ if (Math.hypot(dx, dy) > 4) s.moved = true;
332
+ setOffset(view.current.bound({ x: s.offset.x + dx, y: s.offset.y + dy }, view.current.scale));
333
+ }
334
+ };
335
+
336
+ const onPointerUp = (event: ReactPointerEvent<HTMLDivElement>) => {
337
+ if (!pointers.current.has(event.pointerId)) return;
338
+ const point = pointers.current.get(event.pointerId)!;
339
+ const wasTap =
340
+ pointers.current.size === 1 && start.current && !start.current.moved && Date.now() - start.current.at < 300;
341
+ pointers.current.delete(event.pointerId);
342
+ if (pointers.current.size > 0) {
343
+ beginGesture(); // the finger left on the screen carries on as a drag
344
+ return;
345
+ }
346
+ start.current = null;
347
+ setGesture(null);
348
+ if (!wasTap || event.pointerType === "mouse") return; // a mouse has onDoubleClick
349
+ const previous = lastTap.current;
350
+ if (
351
+ previous &&
352
+ Date.now() - previous.at < 350 &&
353
+ Math.hypot(point.x - previous.point.x, point.y - previous.point.y) < 30
354
+ ) {
355
+ lastTap.current = null;
356
+ toggle(point);
357
+ } else {
358
+ lastTap.current = { at: Date.now(), point };
359
+ }
360
+ };
361
+
362
+ const onKeyDown = (event: ReactKeyboardEvent) => {
363
+ if (event.metaKey || event.ctrlKey || event.altKey) return; // ⌘/Ctrl + and − stay the browser's page zoom
364
+ const v = view.current;
365
+ const step = 48;
366
+ const keys: Record<string, () => void> = {
367
+ "+": () => zoomTo(v.scale * ZOOM_STEP),
368
+ "=": () => zoomTo(v.scale * ZOOM_STEP),
369
+ "-": () => zoomTo(v.scale / ZOOM_STEP),
370
+ _: () => zoomTo(v.scale / ZOOM_STEP),
371
+ "−": () => zoomTo(v.scale / ZOOM_STEP),
372
+ "0": () => zoomTo(v.fit),
373
+ ArrowLeft: () => panBy(step, 0),
374
+ ArrowRight: () => panBy(-step, 0),
375
+ ArrowUp: () => panBy(0, step),
376
+ ArrowDown: () => panBy(0, -step),
377
+ };
378
+ const action = keys[event.key];
379
+ // Arrow keys move only a zoomed picture, so they still move between the buttons' focus otherwise.
380
+ if (!action || (event.key.startsWith("Arrow") && near(v.scale, v.fit))) return;
381
+ event.preventDefault();
382
+ action();
383
+ };
384
+
385
+ const change = (next: boolean) => {
386
+ if (next && !known) {
387
+ const rect = thumb.current?.getBoundingClientRect();
388
+ setNatural(rect && rect.width > 0 && rect.height > 0 ? { w: rect.width, h: rect.height } : FALLBACK_SIZE);
389
+ }
390
+ if (!next) {
391
+ setZoom(null);
392
+ setOffset({ x: 0, y: 0 });
393
+ setGesture(null);
394
+ pointers.current.clear();
395
+ start.current = null;
396
+ setDescribed(false);
397
+ }
398
+ setOpen(next);
399
+ };
400
+
401
+ const zoomed = !near(scale, fit);
402
+ const percent = Math.round(scale * 100);
403
+ const title = caption || alt;
404
+ // The alt text says everything the picture shows, so it is long. Under the picture on a phone it took a third
405
+ // of the screen from the picture itself; there it waits behind "Show description" (wider screens show it).
406
+ const foldsTitle = !caption && alt.length > FOLDED_TITLE_CHARS;
407
+ const folds = Boolean(caption) || foldsTitle;
408
+
409
+ return (
410
+ <DialogPrimitive.Root open={open} onOpenChange={change}>
411
+ <DialogPrimitive.Trigger asChild>
412
+ <button type="button" className={c.trigger} aria-label={text.zoomOpen.replace("{alt}", alt)}>
413
+ <span ref={thumb} className="block">
414
+ {children}
415
+ </span>
416
+ <span className={c.hint} aria-hidden>
417
+ <Maximize2 className="size-3 shrink-0" />
418
+ <span className={c.hintPointer}>{text.zoomHint}</span>
419
+ <span className={c.hintTouch}>{hintTouch}</span>
420
+ </span>
421
+ </button>
422
+ </DialogPrimitive.Trigger>
423
+ <DialogPrimitive.Portal>
424
+ <DialogPrimitive.Overlay className={c.overlay} />
425
+ <DialogPrimitive.Content
426
+ className={c.content}
427
+ onKeyDown={onKeyDown}
428
+ // With a caption, the alt text is the description; without one, the alt text is the title and there is none.
429
+ {...(caption ? {} : { "aria-describedby": undefined })}
430
+ onOpenAutoFocus={(event) => {
431
+ // The close button, not the first zoom button: Enter on open shouldn't zoom.
432
+ event.preventDefault();
433
+ (event.currentTarget as HTMLElement | null)?.querySelector<HTMLElement>("[data-house-zoom-close]")?.focus();
434
+ }}
435
+ >
436
+ <div className={c.toolbar}>
437
+ <p className={c.instructions}>{text.zoomInstructions}</p>
438
+ <button
439
+ type="button"
440
+ className={cx(c.button, "ml-auto sm:ml-0")}
441
+ onClick={() => zoomTo(scale / ZOOM_STEP)}
442
+ disabled={scale <= min + 0.001}
443
+ aria-label={text.zoomOut}
444
+ title={text.zoomOut}
445
+ >
446
+ <ZoomOut className="size-5" aria-hidden />
447
+ </button>
448
+ <button
449
+ type="button"
450
+ className={c.level}
451
+ onClick={() => toggle()}
452
+ aria-label={text.zoomToggle}
453
+ title={text.zoomToggle}
454
+ >
455
+ {percent}%
456
+ </button>
457
+ <button
458
+ type="button"
459
+ className={c.button}
460
+ onClick={() => zoomTo(scale * ZOOM_STEP)}
461
+ disabled={scale >= max - 0.001}
462
+ aria-label={text.zoomIn}
463
+ title={text.zoomIn}
464
+ >
465
+ <ZoomIn className="size-5" aria-hidden />
466
+ </button>
467
+ <DialogPrimitive.Close
468
+ className={c.button}
469
+ aria-label={text.zoomClose}
470
+ title={text.zoomClose}
471
+ data-house-zoom-close=""
472
+ >
473
+ <X className="size-5" aria-hidden />
474
+ </DialogPrimitive.Close>
475
+ <span className="sr-only" aria-live="polite">
476
+ {text.zoomLevel.replace("{percent}", String(percent))}
477
+ </span>
478
+ </div>
479
+ <div
480
+ ref={setStageEl}
481
+ data-house-zoom-stage=""
482
+ className={cx(
483
+ c.stage,
484
+ zoomed ? (gesture === "drag" ? "cursor-grabbing" : "cursor-grab") : "cursor-zoom-in",
485
+ )}
486
+ onPointerDown={onPointerDown}
487
+ onPointerMove={onPointerMove}
488
+ onPointerUp={onPointerUp}
489
+ onPointerCancel={onPointerUp}
490
+ onDoubleClick={(event) => toggle(fromCentre(event.clientX, event.clientY))}
491
+ >
492
+ <div
493
+ data-house-zoom-picture=""
494
+ data-scale={scale.toFixed(3)}
495
+ className={cx(
496
+ "absolute top-1/2 left-1/2 origin-center",
497
+ gesture ? "" : "motion-safe:transition-transform motion-safe:duration-150 motion-safe:ease-out",
498
+ )}
499
+ style={{
500
+ width: natural.w,
501
+ height: natural.h,
502
+ transform: `translate(-50%, -50%) translate(${offset.x}px, ${offset.y}px) scale(${scale})`,
503
+ }}
504
+ >
505
+ {full ?? children}
506
+ </div>
507
+ </div>
508
+ <div className={c.footer}>
509
+ <DialogPrimitive.Title className={cx(c.caption, foldsTitle && !described && c.titleFolded)}>
510
+ {title}
511
+ </DialogPrimitive.Title>
512
+ {caption ? (
513
+ <DialogPrimitive.Description className={cx(c.alt, !described && c.altFolded)}>
514
+ {alt}
515
+ </DialogPrimitive.Description>
516
+ ) : null}
517
+ {folds ? (
518
+ <button
519
+ type="button"
520
+ className={c.more}
521
+ aria-expanded={described}
522
+ data-house-zoom-more=""
523
+ onClick={() => setDescribed((shown) => !shown)}
524
+ >
525
+ {described ? text.zoomHideDescription : text.zoomShowDescription}
526
+ </button>
527
+ ) : null}
528
+ </div>
529
+ </DialogPrimitive.Content>
530
+ </DialogPrimitive.Portal>
531
+ </DialogPrimitive.Root>
532
+ );
533
+ }
@@ -0,0 +1,68 @@
1
+ import type { ReactNode } from "react";
2
+
3
+ import { GuideFigureMedia, GuideFigureView, type GuideFigureClassNames } from "../markdown/figure.js";
4
+ import type { GuideFigureBlock, GuideFigures } from "../markdown/figures.js";
5
+ import { GuideFigureZoom, type GuideZoomClassNames } from "./guide-figure-zoom.js";
6
+ import type { GuidesLabels } from "./library.js";
7
+
8
+ export interface GuideFigureProps {
9
+ figure: GuideFigureBlock;
10
+ figures?: GuideFigures;
11
+ /** Open full-size on a click, Enter or Space. Default: on. */
12
+ zoom?: boolean;
13
+ /** How wide the app's layout draws the picture, for its narrower copies. Default `GUIDE_FIGURE_SIZES`. */
14
+ sizes?: string;
15
+ labels?: Partial<GuidesLabels>;
16
+ classNames?: Partial<GuideFigureClassNames>;
17
+ zoomClassNames?: Partial<GuideZoomClassNames>;
18
+ }
19
+
20
+ /**
21
+ * A guide's picture with its caption, as `GuideArticle` draws it: the picture is a button that
22
+ * opens it full-size (`GuideFigureZoom`). Server-safe — a diagram registered as a component is
23
+ * drawn here, on the server, and only the drawn element crosses into the zoom dialog.
24
+ */
25
+ export function GuideFigure({
26
+ figure,
27
+ figures,
28
+ zoom = true,
29
+ sizes,
30
+ labels,
31
+ classNames,
32
+ zoomClassNames,
33
+ }: GuideFigureProps): ReactNode {
34
+ if (!zoom) return <GuideFigureView figure={figure} figures={figures} classNames={classNames} sizes={sizes} />;
35
+ const thumbnail = <GuideFigureMedia figure={figure} figures={figures} classNames={classNames} sizes={sizes} />;
36
+ // In the dialog a screenshot fills the box laid out at its natural size, loaded straight away and always the
37
+ // original (it is there to be zoomed into); a diagram is drawn again as it is in the article, at the size it was
38
+ // measured at, and scaled.
39
+ const full =
40
+ figure.kind === "screenshot" ? (
41
+ <GuideFigureMedia
42
+ figure={figure}
43
+ classNames={{ ...classNames, image: "size-full rounded-md bg-card align-top", imageWithoutDark: "" }}
44
+ eager
45
+ sizes={false}
46
+ />
47
+ ) : undefined;
48
+ const size = figure.kind === "screenshot" ? { width: figure.width, height: figure.height } : {};
49
+ return (
50
+ <GuideFigureView
51
+ figure={figure}
52
+ figures={figures}
53
+ classNames={classNames}
54
+ media={
55
+ <GuideFigureZoom
56
+ full={full}
57
+ {...size}
58
+ alt={figure.alt}
59
+ {...(figure.caption ? { caption: figure.caption } : {})}
60
+ labels={labels}
61
+ classNames={zoomClassNames}
62
+ >
63
+ {thumbnail}
64
+ </GuideFigureZoom>
65
+ }
66
+ />
67
+ );
68
+ }