@sssb/kit 0.0.0 → 0.2.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 (214) hide show
  1. package/LICENSE +21 -0
  2. package/dist/core/webhook-hmac.d.ts +69 -0
  3. package/dist/release.json +1 -0
  4. package/dist/testing/e2e.d.ts +15 -0
  5. package/dist/testing/e2e.js +195 -0
  6. package/package.json +209 -5
  7. package/src/adapters/README.md +6 -0
  8. package/src/adapters/dev-server.ts +21 -0
  9. package/src/adapters/fake/agreements.ts +81 -0
  10. package/src/adapters/fake/analytics.ts +93 -0
  11. package/src/adapters/fake/atomic-write.ts +161 -0
  12. package/src/adapters/fake/audit.ts +58 -0
  13. package/src/adapters/fake/auth.ts +312 -0
  14. package/src/adapters/fake/clock.ts +54 -0
  15. package/src/adapters/fake/data-dir.ts +27 -0
  16. package/src/adapters/fake/db.ts +88 -0
  17. package/src/adapters/fake/email.ts +46 -0
  18. package/src/adapters/fake/jobs.ts +270 -0
  19. package/src/adapters/fake/llm.ts +230 -0
  20. package/src/adapters/fake/pglite-dialect.ts +124 -0
  21. package/src/adapters/fake/service-auth.ts +145 -0
  22. package/src/adapters/fake/simulator-admin.ts +203 -0
  23. package/src/adapters/fake/simulator.ts +94 -0
  24. package/src/adapters/fake/sms.ts +43 -0
  25. package/src/adapters/fake/storage.ts +288 -0
  26. package/src/adapters/fake/webhooks.ts +98 -0
  27. package/src/adapters/index.ts +115 -0
  28. package/src/adapters/real/accept-invite-form.tsx +77 -0
  29. package/src/adapters/real/analytics.ts +28 -0
  30. package/src/adapters/real/auth.ts +216 -0
  31. package/src/adapters/real/contract-data-api.ts +104 -0
  32. package/src/adapters/real/contract-postgres.ts +167 -0
  33. package/src/adapters/real/database-transport.ts +34 -0
  34. package/src/adapters/real/db-data-api.ts +61 -0
  35. package/src/adapters/real/db.ts +88 -0
  36. package/src/adapters/real/email.ts +22 -0
  37. package/src/adapters/real/index.ts +89 -0
  38. package/src/adapters/real/jobs.ts +32 -0
  39. package/src/adapters/real/llm.ts +108 -0
  40. package/src/adapters/real/migrate-handler.ts +66 -0
  41. package/src/adapters/real/providers.tsx +12 -0
  42. package/src/adapters/real/rds-data-codec.ts +508 -0
  43. package/src/adapters/real/rds-data-dialect.ts +470 -0
  44. package/src/adapters/real/rds-data-emulator.ts +351 -0
  45. package/src/adapters/real/s3-storage.ts +233 -0
  46. package/src/adapters/real/sign-in-form.tsx +59 -0
  47. package/src/adapters/real/storage.ts +10 -0
  48. package/src/adapters/sentry/baseline.ts +90 -0
  49. package/src/adapters/sentry/client.ts +17 -0
  50. package/src/adapters/sentry/init.ts +17 -0
  51. package/src/authz/app-exemptions.ts +226 -0
  52. package/src/authz/authorize.ts +214 -0
  53. package/src/authz/route-policy.ts +153 -0
  54. package/src/authz/route-scan.ts +1516 -0
  55. package/src/components/agreements/acceptances-section.tsx +55 -0
  56. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  57. package/src/components/agreements/agreement-body.tsx +34 -0
  58. package/src/components/agreements/agreement-gate.tsx +45 -0
  59. package/src/components/app-header.tsx +45 -0
  60. package/src/components/auth/accept-invite-screen.tsx +126 -0
  61. package/src/components/auth/auth-icons.tsx +68 -0
  62. package/src/components/auth/org-switcher.tsx +76 -0
  63. package/src/components/auth/people-picker.tsx +50 -0
  64. package/src/components/auth/preview-row.tsx +64 -0
  65. package/src/components/auth/sign-in-screen.tsx +24 -0
  66. package/src/components/auth/user-menu.tsx +64 -0
  67. package/src/components/demo-badge.tsx +20 -0
  68. package/src/components/demo-banner.tsx +14 -0
  69. package/src/components/gates/gate-interstitial.tsx +23 -0
  70. package/src/components/job-timeline.tsx +64 -0
  71. package/src/components/notifications/notification-bell.tsx +120 -0
  72. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  73. package/src/components/org-screen.tsx +197 -0
  74. package/src/components/profile-screen.tsx +100 -0
  75. package/src/components/simulator/actor-runtime.ts +180 -0
  76. package/src/components/simulator/actor-shell.tsx +275 -0
  77. package/src/components/simulator/actors-app.tsx +119 -0
  78. package/src/components/simulator/errors-app.tsx +84 -0
  79. package/src/components/simulator/events-app.tsx +210 -0
  80. package/src/components/simulator/format-when.ts +20 -0
  81. package/src/components/simulator/hooks-app.tsx +319 -0
  82. package/src/components/simulator/inbound-app.tsx +210 -0
  83. package/src/components/simulator/jobs-app.tsx +471 -0
  84. package/src/components/simulator/mail-app.tsx +290 -0
  85. package/src/components/simulator/messages-app.tsx +64 -0
  86. package/src/components/simulator/people-app.tsx +140 -0
  87. package/src/components/simulator/people-dimensions.ts +16 -0
  88. package/src/components/simulator/simulator-panel.tsx +716 -0
  89. package/src/components/simulator/snapshots-app.tsx +398 -0
  90. package/src/components/simulator/tab-mount.ts +25 -0
  91. package/src/components/simulator/tours-app.tsx +105 -0
  92. package/src/components/webhook-endpoints-card.tsx +172 -0
  93. package/src/core/abilities.ts +459 -0
  94. package/src/core/agreements.ts +139 -0
  95. package/src/core/gates.ts +157 -0
  96. package/src/core/greeting.ts +11 -0
  97. package/src/core/inbound-email.ts +129 -0
  98. package/src/core/jobs.ts +51 -0
  99. package/src/core/keyset.ts +227 -0
  100. package/src/core/llm-models.ts +10 -0
  101. package/src/core/locale.ts +3 -0
  102. package/src/core/notifications.ts +182 -0
  103. package/src/core/presets.ts +456 -0
  104. package/src/core/roles.ts +47 -0
  105. package/src/core/schedules.ts +147 -0
  106. package/src/core/standard-schema.ts +56 -0
  107. package/src/core/state-machine.ts +43 -0
  108. package/src/core/webhook-events.ts +86 -0
  109. package/src/core/webhook-hmac.ts +248 -0
  110. package/src/core/webhook-signing.ts +27 -0
  111. package/src/cutover/rows.json +101 -0
  112. package/src/db/agreements.ts +176 -0
  113. package/src/db/app-roles.ts +197 -0
  114. package/src/db/audit.ts +356 -0
  115. package/src/db/inbound-email.ts +145 -0
  116. package/src/db/jobs.ts +300 -0
  117. package/src/db/jsonb.ts +18 -0
  118. package/src/db/keyset.ts +179 -0
  119. package/src/db/migrate.ts +73 -0
  120. package/src/db/migrations/0001_tenants.ts +25 -0
  121. package/src/db/migrations/0003_organizations.ts +27 -0
  122. package/src/db/migrations/0004_jobs.ts +64 -0
  123. package/src/db/migrations/0005_service_keys.ts +33 -0
  124. package/src/db/migrations/0008_audit_events.ts +51 -0
  125. package/src/db/migrations/0009_job_schedules.ts +52 -0
  126. package/src/db/migrations/0010_webhooks.ts +100 -0
  127. package/src/db/migrations/0011_notifications.ts +98 -0
  128. package/src/db/migrations/0012_inbound_email.ts +74 -0
  129. package/src/db/migrations/0013_agreements.ts +98 -0
  130. package/src/db/migrations/0014_audit_credential.ts +29 -0
  131. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  132. package/src/db/migrations/0016_audit_detail.ts +26 -0
  133. package/src/db/migrations/index.ts +49 -0
  134. package/src/db/notifications.ts +185 -0
  135. package/src/db/org-lookup.ts +104 -0
  136. package/src/db/owner-pass.ts +252 -0
  137. package/src/db/rls-coverage.ts +259 -0
  138. package/src/db/rls-proof-runner.ts +94 -0
  139. package/src/db/rls-proofs.ts +1176 -0
  140. package/src/db/schedules.ts +187 -0
  141. package/src/db/schema.ts +235 -0
  142. package/src/db/seed.ts +176 -0
  143. package/src/db/service-keys.ts +50 -0
  144. package/src/db/tenant-lookup.ts +13 -0
  145. package/src/db/webhooks.ts +483 -0
  146. package/src/db/with-tenant.ts +26 -0
  147. package/src/demo-static/actor-drivers.ts +161 -0
  148. package/src/demo-static/assistant-replay.ts +61 -0
  149. package/src/demo-static/contracts.ts +282 -0
  150. package/src/demo-static/email-html.ts +58 -0
  151. package/src/demo-static/hash-route.ts +24 -0
  152. package/src/demo-static/rows.ts +105 -0
  153. package/src/demo-static/shell.tsx +440 -0
  154. package/src/demo-static/tour/contracts.ts +97 -0
  155. package/src/demo-static/tour/driver.ts +320 -0
  156. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  157. package/src/demo-static/tour/use-tours.tsx +394 -0
  158. package/src/demo-static/world.ts +1479 -0
  159. package/src/email/send.ts +12 -0
  160. package/src/email/templates/digest-email.tsx +61 -0
  161. package/src/email/templates/invite-email.tsx +57 -0
  162. package/src/email/templates/notification-email.tsx +39 -0
  163. package/src/guide.md +118 -0
  164. package/src/i18n/messages/en.json +373 -0
  165. package/src/i18n/messages/es.json +373 -0
  166. package/src/i18n/messages.ts +34 -0
  167. package/src/i18n/namespaces.ts +32 -0
  168. package/src/i18n/request.ts +34 -0
  169. package/src/i18n/routing.ts +7 -0
  170. package/src/inbound-email/handlers.ts +67 -0
  171. package/src/inbound-email/intake.ts +180 -0
  172. package/src/jobs/digest-email.ts +97 -0
  173. package/src/observability/scrub.ts +42 -0
  174. package/src/ports/README.md +8 -0
  175. package/src/ports/analytics.ts +8 -0
  176. package/src/ports/auth.ts +87 -0
  177. package/src/ports/db.ts +27 -0
  178. package/src/ports/email.ts +14 -0
  179. package/src/ports/errors.ts +46 -0
  180. package/src/ports/jobs.ts +48 -0
  181. package/src/ports/llm.ts +85 -0
  182. package/src/ports/storage.ts +132 -0
  183. package/src/seed/contracts.ts +129 -0
  184. package/src/server-lib/assistant.ts +45 -0
  185. package/src/server-lib/defer.ts +53 -0
  186. package/src/server-lib/demo-presets.ts +85 -0
  187. package/src/server-lib/invite.ts +92 -0
  188. package/src/server-lib/notify-deps.ts +15 -0
  189. package/src/server-lib/notify.ts +252 -0
  190. package/src/server-lib/preset-operations.ts +121 -0
  191. package/src/server-lib/scheduled-tick.ts +38 -0
  192. package/src/server-lib/sms.ts +43 -0
  193. package/src/server-lib/webhook-dispatch.ts +75 -0
  194. package/src/service-auth/mailgun.ts +70 -0
  195. package/src/service-auth/verify.ts +73 -0
  196. package/src/service-auth/webhook.ts +60 -0
  197. package/src/testing/checks.json +103 -0
  198. package/src/testing/conformance/authz.ts +46 -0
  199. package/src/testing/conformance/db.ts +258 -0
  200. package/src/testing/conformance/demo-presets.ts +295 -0
  201. package/src/testing/conformance/i18n.ts +80 -0
  202. package/src/testing/conformance/register.ts +200 -0
  203. package/src/testing/conformance/seam-map.ts +205 -0
  204. package/src/testing/conformance/suite.ts +59 -0
  205. package/src/testing/conformance/types.ts +18 -0
  206. package/src/testing/contract.ts +200 -0
  207. package/src/testing/e2e.ts +15 -0
  208. package/src/testing/index.ts +6 -0
  209. package/src/testing/seam-specifiers.json +22 -0
  210. package/src/testing/tmp-dir-marker.d.mts +4 -0
  211. package/src/testing/tmp-dir-marker.mjs +5 -0
  212. package/src/testing/tmp-dir.ts +182 -0
  213. package/src/theme.ts +28 -0
  214. package/README.md +0 -3
@@ -0,0 +1,394 @@
1
+ 'use client'
2
+
3
+ import { tours as appTours } from '@sssb/app-config/tours'
4
+ import { useTranslations } from 'next-intl'
5
+ import { useCallback, useEffect, useRef, useState } from 'react'
6
+ import type { ToursAppProps } from '../../components/simulator/tours-app'
7
+ import type { TourMiss } from './contracts'
8
+ import { cancelScript, hideCursor, isDriving, requestFastForward, runScript, setDriverSpeed } from './driver'
9
+ import { TourOverlay } from './tour-overlay'
10
+
11
+ /**
12
+ * The tour ENGINE — step state, spotlights, advance-on-Next, the derail guard, and the run report —
13
+ * plus the two things a host needs to mount it: the Simulator tab's props and the overlay node.
14
+ *
15
+ * Hosts are the two places the Simulator panel is composed (the static shell and the server glue), and
16
+ * both wire tours in two lines. The registered tours come from the SEAM (`@sssb/app-config/tours`), read
17
+ * here exactly as SnapshotsApp reads `@sssb/app-config/simulator` flags, so SSSB hosts an app's walkthroughs
18
+ * without learning a word of its vocabulary.
19
+ *
20
+ * A tour SURVIVES A RELOAD. That is not a nicety: on a server host, restoring a snapshot, switching
21
+ * person and flipping a feature flag all reload the page, and a walkthrough that died on its own second
22
+ * step would be useless there. The current tour + step is written to sessionStorage on every step and
23
+ * resumed on mount; ending the tour clears it.
24
+ */
25
+
26
+ /** How long the spotlight effect waits for its target before calling it a miss. */
27
+ const SPOTLIGHT_TIMEOUT_MS = 1_500
28
+ const SPOTLIGHT_POLL_MS = 60
29
+ /** How often the derail guard samples the location (there is no event that covers every router). */
30
+ const DERAIL_POLL_MS = 400
31
+ /** Fast: a preview crawl, and the speed the CI walkthrough runs a whole tour at. */
32
+ const FAST_SPEED = 0.02
33
+ const RESUME_KEY = 'app-simulator-tour'
34
+ const FAST_KEY = 'app-simulator-tour-fast'
35
+
36
+ function readStoredFast(): boolean {
37
+ try {
38
+ return window.localStorage.getItem(FAST_KEY) === 'true'
39
+ } catch {
40
+ return false
41
+ }
42
+ }
43
+
44
+ function readResumeMarker(): { tourId: string; idx: number } | null {
45
+ try {
46
+ const raw = window.sessionStorage.getItem(RESUME_KEY)
47
+ if (!raw) return null
48
+ const parsed = JSON.parse(raw) as { tourId?: unknown; idx?: unknown }
49
+ if (typeof parsed.tourId !== 'string' || typeof parsed.idx !== 'number') return null
50
+ return { tourId: parsed.tourId, idx: parsed.idx }
51
+ } catch {
52
+ return null
53
+ }
54
+ }
55
+
56
+ function writeResumeMarker(marker: { tourId: string; idx: number } | null) {
57
+ try {
58
+ if (marker) window.sessionStorage.setItem(RESUME_KEY, JSON.stringify(marker))
59
+ else window.sessionStorage.removeItem(RESUME_KEY)
60
+ } catch {
61
+ // A host with storage disabled loses only the resume-after-reload ability.
62
+ }
63
+ }
64
+
65
+ export interface ToursHandle {
66
+ /** Hand to `<SimulatorPanel tours={…}>`. Undefined when the app registers no tours, which is how
67
+ * the tab disappears entirely for an adopter who wants none. */
68
+ tab: ToursAppProps | undefined
69
+ /** Render once, beside the panel: cursor, vignette, narration bar, run report. */
70
+ overlay: React.ReactNode
71
+ }
72
+
73
+ export function useTours(
74
+ options: {
75
+ /**
76
+ * Put the world into the start a tour declares, before its first step — resolved by the host with
77
+ * @sssb/kit/core/presets.ts `resolveWorldStart`: `'reset'` (the seeded world) and every registered demo
78
+ * preset work on every host; a server host may also restore a saved snapshot. On a host where that
79
+ * reloads the page, the tour resumes itself afterwards. Answer `false` when this host cannot
80
+ * produce that world: the tour still runs, but its start is recorded as a miss, which fails the
81
+ * CI walkthrough rather than letting a tour quietly begin in the wrong world.
82
+ */
83
+ onSnapshot?: (snapshot: string) => void | boolean | Promise<void | boolean>
84
+ } = {},
85
+ ): ToursHandle {
86
+ const { onSnapshot } = options
87
+ const t = useTranslations()
88
+ const [activeId, setActiveId] = useState<string | null>(null)
89
+ const [idx, setIdx] = useState(-1)
90
+ const [advancing, setAdvancing] = useState(false)
91
+ const [spotlight, setSpotlight] = useState<string | null>(null)
92
+ const [spotlit, setSpotlit] = useState(false)
93
+ const [misses, setMisses] = useState<TourMiss[]>([])
94
+ const [derailed, setDerailed] = useState(false)
95
+ const [report, setReport] = useState<{ steps: number; misses: TourMiss[] } | null>(null)
96
+ const [fast, setFast] = useState(false)
97
+
98
+ // Read by the scroll listener, which is registered once and must not be re-registered per step.
99
+ // Synced in an effect rather than written during render: a ref write during render is banned
100
+ // (react-hooks/refs), and this is the same "mirror state for a listener" shape world.ts uses.
101
+ const idxRef = useRef(idx)
102
+ useEffect(() => {
103
+ idxRef.current = idx
104
+ }, [idx])
105
+ // Where the story is meant to be standing: captured when a step's entry script finishes, and the
106
+ // place "Back to the tour" returns to.
107
+ const stepLocationRef = useRef<string | null>(null)
108
+ // Bumped on every goto so a script that finishes AFTER the viewer pressed Back cannot light that
109
+ // abandoned step's spotlight on the screen they are now looking at.
110
+ const runTokenRef = useRef(0)
111
+
112
+ const tour = appTours.find((candidate) => candidate.id === activeId) ?? null
113
+ const steps = tour?.steps ?? []
114
+ const touring = idx >= 0 && tour !== null
115
+
116
+ // Mirrors the misses state for end(): next()'s closure predates any miss its own advance script
117
+ // records, so the run report must read the CURRENT list, not the render-time one — a final-step
118
+ // advance miss would otherwise vanish from the report (and from the CI gate that asserts on it).
119
+ const missesRef = useRef<TourMiss[]>([])
120
+ const addMiss = useCallback((miss: TourMiss) => {
121
+ if (missesRef.current.some((seen) => seen.action === miss.action && seen.target === miss.target)) return
122
+ missesRef.current = [...missesRef.current, miss]
123
+ setMisses(missesRef.current)
124
+ }, [])
125
+
126
+ // The controls below are deliberately PLAIN FUNCTIONS, not useCallbacks: they are event handlers,
127
+ // nothing downstream memoizes on their identity, and a useCallback closing over the tour registry
128
+ // is manual memoization the React Compiler cannot verify (it reports the module-level array as
129
+ // "may be modified later"). `addMiss` above stays memoized because an effect depends on it.
130
+
131
+ function goto(tourId: string, next: number) {
132
+ const target = appTours.find((candidate) => candidate.id === tourId)
133
+ const step = target?.steps[next]
134
+ if (!target || !step) return
135
+ cancelScript()
136
+ const token = (runTokenRef.current += 1)
137
+ setActiveId(tourId)
138
+ setIdx(next)
139
+ setDerailed(false)
140
+ setReport(null)
141
+ // The vignette lights AFTER the entry script, not before it: the script is usually what puts
142
+ // the target on screen (it navigates, or opens a panel tab), so lighting first would race it —
143
+ // and did, at presentation speed, where the wait timed out before the cursor had finished
144
+ // walking there. It also paces better: dim, then halo, once the cursor arrives.
145
+ setSpotlight(null)
146
+ writeResumeMarker({ tourId, idx: next })
147
+ stepLocationRef.current = window.location.href
148
+ void runScript(step.script, addMiss).then(() => {
149
+ if (runTokenRef.current !== token) return
150
+ // The baseline for the derail guard is where the STEP left the viewer, not where it
151
+ // started — a step whose script navigates has moved the story on purpose.
152
+ stepLocationRef.current = window.location.href
153
+ setSpotlight(step.spotlight ?? null)
154
+ })
155
+ }
156
+
157
+ function end(stepsRun: number) {
158
+ cancelScript()
159
+ hideCursor()
160
+ writeResumeMarker(null)
161
+ setReport({ steps: stepsRun, misses: missesRef.current })
162
+ setActiveId(null)
163
+ setIdx(-1)
164
+ setAdvancing(false)
165
+ setSpotlight(null)
166
+ setDerailed(false)
167
+ }
168
+
169
+ async function start(tourId: string) {
170
+ const target = appTours.find((candidate) => candidate.id === tourId)
171
+ if (!target) return
172
+ missesRef.current = []
173
+ setMisses([])
174
+ setReport(null)
175
+ // Snapshot first: a tour begins from a world it can describe, not from wherever the last person
176
+ // clicked. On a server host this reloads, and the resume marker takes over.
177
+ writeResumeMarker({ tourId, idx: 0 })
178
+ if (target.snapshot && onSnapshot) {
179
+ // A host that could not produce the world answers false; one whose request failed outright
180
+ // (a network error, a throw) is the same miss, never an unhandled rejection that leaves the
181
+ // resume marker pointing at a tour that never began.
182
+ const produced = await Promise.resolve()
183
+ .then(() => onSnapshot(target.snapshot!))
184
+ .catch(() => false as const)
185
+ if (produced === false) addMiss({ action: 'snapshot', target: target.snapshot })
186
+ }
187
+ goto(tourId, 0)
188
+ }
189
+
190
+ async function next() {
191
+ if (advancing || !tour) return
192
+ const step = tour.steps[idx]
193
+ setAdvancing(true)
194
+ // Next DURING an entry script fast-forwards it to completion rather than cancelling it: a
195
+ // cancelled script leaves a half-typed form on screen, which reads as a bug.
196
+ if (isDriving()) {
197
+ requestFastForward()
198
+ while (isDriving()) await new Promise((resolve) => setTimeout(resolve, 60))
199
+ }
200
+ // Move the resume marker BEFORE the advance script runs. Every submission lives in `advance`,
201
+ // and on a server host some of them reload the page (a feature flag, a person switch) — writing
202
+ // the marker first is the difference between coming back on the next beat and replaying the
203
+ // action that caused the reload.
204
+ writeResumeMarker(idx + 1 < tour.steps.length ? { tourId: tour.id, idx: idx + 1 } : null)
205
+ if (step?.advance) {
206
+ setSpotlight(null) // the vignette lifts before the cursor clicks through it
207
+ await runScript(step.advance, addMiss)
208
+ }
209
+ setAdvancing(false)
210
+ if (idx >= tour.steps.length - 1) end(tour.steps.length)
211
+ else goto(tour.id, idx + 1)
212
+ }
213
+
214
+ function back() {
215
+ if (idx > 0 && !advancing && tour) goto(tour.id, idx - 1)
216
+ }
217
+
218
+ function resume() {
219
+ setDerailed(false)
220
+ if (!tour) return
221
+ const home = stepLocationRef.current
222
+ // Hash routing lands back in place without a reload; a real navigation reloads, and the resume
223
+ // marker restarts the tour on the same step.
224
+ if (home && window.location.href !== home) window.location.assign(home)
225
+ goto(tour.id, idx)
226
+ }
227
+
228
+ useEffect(() => {
229
+ // Mount-only external-system reads: the persisted Fast preference, and a tour interrupted by a
230
+ // reload (a snapshot restore, a person switch, a flag flip — all of which reload a server host).
231
+ const storedFast = readStoredFast()
232
+ // eslint-disable-next-line react-hooks/set-state-in-effect
233
+ setFast(storedFast)
234
+ setDriverSpeed(storedFast ? FAST_SPEED : 1)
235
+ const marker = readResumeMarker()
236
+ const resumable = marker && appTours.some((candidate) => candidate.id === marker.tourId)
237
+ if (marker && resumable) goto(marker.tourId, marker.idx)
238
+ // Intentionally mount-only.
239
+ // eslint-disable-next-line react-hooks/exhaustive-deps
240
+ }, [])
241
+
242
+ useEffect(() => {
243
+ // The cursor is position:fixed, so the viewer's own scrolling makes its coordinates a lie —
244
+ // hide it, and let the driver's next move bring it back.
245
+ const onScroll = () => {
246
+ if (idxRef.current >= 0 && !isDriving()) hideCursor()
247
+ }
248
+ window.addEventListener('scroll', onScroll)
249
+ window.addEventListener('wheel', onScroll, { passive: true })
250
+ return () => {
251
+ window.removeEventListener('scroll', onScroll)
252
+ window.removeEventListener('wheel', onScroll)
253
+ }
254
+ }, [])
255
+
256
+ useEffect(() => {
257
+ // The DERAIL GUARD. The template this is ported from wrapped the app's one navigation
258
+ // function; this codebase has two hosts with two routers (hash and Next), so the guard watches
259
+ // the LOCATION instead: if it moves while the driver is idle, the viewer went somewhere the
260
+ // story did not, and the bar offers them the way back. Post-hoc rather than a confirmation
261
+ // dialog, which is also less rude — clicking around mid-tour is allowed, it just says so.
262
+ if (!touring) return
263
+ let last = window.location.href
264
+ const id = setInterval(() => {
265
+ if (isDriving()) {
266
+ last = window.location.href
267
+ return
268
+ }
269
+ if (window.location.href !== last) {
270
+ last = window.location.href
271
+ setDerailed(true)
272
+ }
273
+ }, DERAIL_POLL_MS)
274
+ return () => clearInterval(id)
275
+ }, [touring])
276
+
277
+ useEffect(() => {
278
+ // The vignette: dim the page, halo the target. The backdrop renders only once the target is
279
+ // actually there, so a stale selector never leaves the page dimmed with nothing lit — and it
280
+ // is recorded as a miss, because a spotlight that stopped pointing at anything is exactly the
281
+ // rot this gate exists to catch.
282
+ if (!spotlight || !touring) {
283
+ // Syncing an external system (the DOM styles this effect owns) back to "nothing lit" — the
284
+ // legitimate case the set-state-in-effect rule carves out.
285
+ // eslint-disable-next-line react-hooks/set-state-in-effect
286
+ setSpotlit(false)
287
+ return
288
+ }
289
+ let target: HTMLElement | null = null
290
+ let halo: Animation | undefined
291
+ let previous: { position: string; zIndex: string } | null = null
292
+ const deadline = Date.now() + SPOTLIGHT_TIMEOUT_MS
293
+ const poll = setInterval(() => {
294
+ const el = document.querySelector<HTMLElement>(spotlight)
295
+ if (!el) {
296
+ if (Date.now() > deadline) {
297
+ clearInterval(poll)
298
+ addMiss({ action: 'spotlight', target: spotlight })
299
+ }
300
+ return
301
+ }
302
+ clearInterval(poll)
303
+ target = el
304
+ previous = { position: el.style.position, zIndex: el.style.zIndex }
305
+ // Lift the target above the backdrop. `static` cannot take a z-index, so it becomes
306
+ // relative — the smallest change that makes stacking work on an arbitrary element.
307
+ if (getComputedStyle(el).position === 'static') el.style.position = 'relative'
308
+ el.style.zIndex = '1150'
309
+ halo = el.animate(
310
+ [
311
+ { boxShadow: '0 0 0 6px rgba(252,196,25,.75), 0 0 60px 10px rgba(252,196,25,.35)' },
312
+ { boxShadow: '0 0 0 11px rgba(252,196,25,.5), 0 0 70px 16px rgba(252,196,25,.22)' },
313
+ { boxShadow: '0 0 0 6px rgba(252,196,25,.75), 0 0 60px 10px rgba(252,196,25,.35)' },
314
+ ],
315
+ { duration: 1500, iterations: Infinity },
316
+ )
317
+ setSpotlit(true)
318
+ try {
319
+ el.scrollIntoView({ block: 'center', behavior: 'smooth' })
320
+ } catch {
321
+ // no layout engine (unit tests) — the halo is still attached
322
+ }
323
+ }, SPOTLIGHT_POLL_MS)
324
+ return () => {
325
+ clearInterval(poll)
326
+ halo?.cancel()
327
+ if (target && previous) {
328
+ target.style.position = previous.position
329
+ target.style.zIndex = previous.zIndex
330
+ }
331
+ setSpotlit(false)
332
+ }
333
+ }, [addMiss, spotlight, touring])
334
+
335
+ useEffect(() => {
336
+ // Keep the bar from covering the bottom of the page while a tour runs — the same trick the
337
+ // template used, minus a stylesheet.
338
+ if (!touring && !report) return
339
+ const previous = document.body.style.paddingBottom
340
+ document.body.style.paddingBottom = '150px'
341
+ return () => {
342
+ document.body.style.paddingBottom = previous
343
+ }
344
+ }, [touring, report])
345
+
346
+ const onFastChange = useCallback((value: boolean) => {
347
+ setFast(value)
348
+ setDriverSpeed(value ? FAST_SPEED : 1)
349
+ try {
350
+ window.localStorage.setItem(FAST_KEY, String(value))
351
+ } catch {
352
+ // preference only
353
+ }
354
+ }, [])
355
+
356
+ const tab: ToursAppProps | undefined =
357
+ appTours.length === 0
358
+ ? undefined
359
+ : {
360
+ tours: appTours.map((candidate) => ({
361
+ id: candidate.id,
362
+ title: t(candidate.titleKey),
363
+ summary: t(candidate.summaryKey),
364
+ })),
365
+ activeId,
366
+ fast,
367
+ onFastChange,
368
+ onStart: (tourId: string) => void start(tourId),
369
+ }
370
+
371
+ const step = touring ? steps[idx] : undefined
372
+
373
+ return {
374
+ tab,
375
+ overlay: (
376
+ <TourOverlay
377
+ active={touring}
378
+ stepIndex={Math.max(idx, 0)}
379
+ total={steps.length}
380
+ narration={step ? t.rich(step.textKey, { b: (chunks) => <b>{chunks}</b> }) : null}
381
+ advancing={advancing}
382
+ spotlit={spotlit}
383
+ misses={misses}
384
+ derailed={derailed}
385
+ report={report}
386
+ onNext={() => void next()}
387
+ onBack={back}
388
+ onExit={() => end(idx + 1)}
389
+ onResume={resume}
390
+ onDismissReport={() => setReport(null)}
391
+ />
392
+ ),
393
+ }
394
+ }