@registrucentras/rc-ses-react-components 2.0.0-rc.2 → 2.0.0-rc.4

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 (81) hide show
  1. package/dist/assets/icons/ArrowRightIcon.d.ts +1 -1
  2. package/dist/components/common/CardShell/CardFooter/index.d.ts +3 -0
  3. package/dist/components/common/CardShell/CardFooter/types.d.ts +21 -0
  4. package/dist/components/common/CardShell/index.d.ts +5 -0
  5. package/dist/components/common/CardShell/types.d.ts +26 -0
  6. package/dist/components/common/IconWithSquareBackground/index.d.ts +12 -0
  7. package/dist/components/common/ServiceLinks/ServiceLinkItem/index.d.ts +15 -0
  8. package/dist/components/common/ServiceLinks/index.d.ts +3 -0
  9. package/dist/components/common/ServiceLinks/types.d.ts +34 -0
  10. package/dist/components/common/SideNav/SideNav.types.d.ts +20 -0
  11. package/dist/components/common/SideNav/SideNavLayout.d.ts +4 -0
  12. package/dist/components/common/SideNav/components/SideNavPill.d.ts +9 -0
  13. package/dist/components/common/SideNav/components/SideNavPillList.d.ts +9 -0
  14. package/dist/components/common/SideNav/components/SideNavRow.d.ts +9 -0
  15. package/dist/components/common/SideNav/hooks/useSideNavScrollSpy.d.ts +12 -0
  16. package/dist/components/common/SideNav/index.d.ts +4 -0
  17. package/dist/components/common/TitleBlock/index.d.ts +3 -0
  18. package/dist/components/common/TitleBlock/types.d.ts +73 -0
  19. package/dist/components/utils/normalizeSx.d.ts +4 -0
  20. package/dist/library/index.d.ts +10 -1
  21. package/dist/library/types.d.ts +8 -1
  22. package/dist/registrucentras-rc-ses-react-components.cjs +1 -1
  23. package/dist/registrucentras-rc-ses-react-components.js +3535 -2563
  24. package/dist/stories/components/display/CardShell.stories.d.ts +17 -0
  25. package/dist/stories/components/display/SelectableCardList.stories.d.ts +1 -0
  26. package/dist/stories/components/display/ServiceLinks.stories.d.ts +28 -0
  27. package/dist/stories/components/display/TitleBlock.stories.d.ts +20 -0
  28. package/dist/stories/components/form/FormControlWrapper.stories.d.ts +1 -0
  29. package/dist/stories/components/icons/IconWithSquareBackground.stories.d.ts +7 -0
  30. package/dist/stories/components/inputs/DatePicker.stories.d.ts +107 -0
  31. package/dist/stories/components/navigation/SideNav.stories.d.ts +7 -0
  32. package/dist/theme/cards.d.ts +114 -0
  33. package/dist/theme/light/MuiPickersOutlinedInput.d.ts +8 -0
  34. package/package.json +1 -1
  35. package/src/assets/icons/ArrowRightIcon.tsx +2 -1
  36. package/src/components/common/AdvancedList/components/AdvancedListItem/index.tsx +8 -6
  37. package/src/components/common/Card/index.tsx +1 -23
  38. package/src/components/common/CardShell/CardFooter/index.test.tsx +52 -0
  39. package/src/components/common/CardShell/CardFooter/index.tsx +38 -0
  40. package/src/components/common/CardShell/CardFooter/types.ts +24 -0
  41. package/src/components/common/CardShell/index.test.tsx +137 -0
  42. package/src/components/common/CardShell/index.tsx +78 -0
  43. package/src/components/common/CardShell/types.ts +30 -0
  44. package/src/components/common/IconWithSquareBackground/index.test.tsx +55 -0
  45. package/src/components/common/IconWithSquareBackground/index.tsx +83 -0
  46. package/src/components/common/ServiceLinks/ServiceLinkItem/index.tsx +177 -0
  47. package/src/components/common/ServiceLinks/index.test.tsx +166 -0
  48. package/src/components/common/ServiceLinks/index.tsx +66 -0
  49. package/src/components/common/ServiceLinks/types.ts +37 -0
  50. package/src/components/common/SideNav/SideNav.types.ts +24 -0
  51. package/src/components/common/SideNav/SideNavLayout.test.tsx +113 -0
  52. package/src/components/common/SideNav/SideNavLayout.tsx +67 -0
  53. package/src/components/common/SideNav/components/SideNavPill.tsx +62 -0
  54. package/src/components/common/SideNav/components/SideNavPillList.tsx +190 -0
  55. package/src/components/common/SideNav/components/SideNavRow.tsx +72 -0
  56. package/src/components/common/SideNav/hooks/useSideNavScrollSpy.test.ts +457 -0
  57. package/src/components/common/SideNav/hooks/useSideNavScrollSpy.ts +154 -0
  58. package/src/components/common/SideNav/index.test.tsx +99 -0
  59. package/src/components/common/SideNav/index.tsx +83 -0
  60. package/src/components/common/TitleBlock/index.test.tsx +366 -0
  61. package/src/components/common/TitleBlock/index.tsx +144 -0
  62. package/src/components/common/TitleBlock/types.ts +82 -0
  63. package/src/components/form/inputs/Datepicker/index.test.tsx +117 -0
  64. package/src/components/utils/normalizeSx.ts +24 -0
  65. package/src/i18n/namespaces/common/en.json +4 -0
  66. package/src/i18n/namespaces/common/lt.json +4 -0
  67. package/src/library/index.ts +12 -0
  68. package/src/library/types.ts +38 -0
  69. package/src/stories/components/display/CardShell.stories.tsx +263 -0
  70. package/src/stories/components/display/SelectableCardList.stories.tsx +33 -1
  71. package/src/stories/components/display/ServiceLinks.stories.tsx +154 -0
  72. package/src/stories/components/display/TitleBlock.stories.tsx +506 -0
  73. package/src/stories/components/form/FormControlWrapper.stories.tsx +23 -0
  74. package/src/stories/components/icons/IconWithSquareBackground.stories.tsx +60 -0
  75. package/src/stories/components/inputs/DatePicker.stories.tsx +105 -9
  76. package/src/stories/components/navigation/SideNav.stories.tsx +110 -0
  77. package/src/theme/cards.ts +60 -0
  78. package/src/theme/light/MuiButton.tsx +6 -0
  79. package/src/theme/light/MuiPickersLayout.ts +10 -1
  80. package/src/theme/light/MuiPickersOutlinedInput.ts +88 -0
  81. package/src/theme/light/index.tsx +2 -0
@@ -0,0 +1,457 @@
1
+ import { act, renderHook } from '@testing-library/react'
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3
+
4
+ import useSideNavScrollSpy from './useSideNavScrollSpy'
5
+
6
+ type Viewport = { scrollY: number; innerHeight: number; scrollHeight: number }
7
+ type SectionTop = { id: string; top: number }
8
+
9
+ const setViewport = ({ scrollY, innerHeight, scrollHeight }: Viewport) => {
10
+ Object.defineProperty(window, 'scrollY', { value: scrollY, configurable: true })
11
+ Object.defineProperty(window, 'innerHeight', { value: innerHeight, configurable: true })
12
+ Object.defineProperty(document.documentElement, 'scrollHeight', {
13
+ value: scrollHeight,
14
+ configurable: true,
15
+ })
16
+ }
17
+
18
+ const setSectionTops = (tops: SectionTop[]) => {
19
+ tops.forEach(({ id, top }) => {
20
+ const el = document.getElementById(id) as HTMLElement
21
+ el.getBoundingClientRect = () => ({ top }) as DOMRect
22
+ })
23
+ }
24
+
25
+ // requestAnimationFrame is inherently async in real browsers: scheduling
26
+ // (rafRef.current = requestAnimationFrame(cb)) always completes before cb runs.
27
+ // A mock that runs cb synchronously inverts that order - cb's own
28
+ // `rafRef.current = undefined` reset would run *before* the outer assignment,
29
+ // which then immediately clobbers it back to a truthy value and permanently
30
+ // blocks the in-flight guard from ever scheduling another update. Deferring
31
+ // via a microtask preserves the real ordering.
32
+ const fireScroll = async () => {
33
+ await act(async () => {
34
+ window.dispatchEvent(new Event('scroll'))
35
+ await Promise.resolve()
36
+ })
37
+ }
38
+
39
+ let rafId = 0
40
+ let cancelledRafIds: Set<number>
41
+
42
+ beforeEach(() => {
43
+ rafId = 0
44
+ cancelledRafIds = new Set()
45
+ // Mirrors real cancellation semantics (unlike a no-op stub) so tests can verify
46
+ // behaviour after a frame is scheduled and then cancelled mid-flight.
47
+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
48
+ rafId += 1
49
+ const id = rafId
50
+ Promise.resolve().then(() => {
51
+ if (!cancelledRafIds.has(id)) cb(0)
52
+ })
53
+ return id
54
+ })
55
+ vi.stubGlobal('cancelAnimationFrame', (id: number) => {
56
+ cancelledRafIds.add(id)
57
+ })
58
+
59
+ document.body.innerHTML =
60
+ '<div id="family"></div><div id="documents"></div><div id="signature"></div><div id="residence"></div>'
61
+
62
+ setViewport({ scrollY: 0, innerHeight: 800, scrollHeight: 3000 })
63
+ setSectionTops([
64
+ { id: 'family', top: 0 },
65
+ { id: 'documents', top: 300 },
66
+ { id: 'signature', top: 450 },
67
+ { id: 'residence', top: 550 },
68
+ ])
69
+ })
70
+
71
+ afterEach(() => {
72
+ document.body.innerHTML = ''
73
+ vi.unstubAllGlobals()
74
+ // Covers vi.spyOn mocks (e.g. Date.now) regardless of whether the test that
75
+ // created them failed before reaching its own manual restore.
76
+ vi.restoreAllMocks()
77
+ })
78
+
79
+ describe('useSideNavScrollSpy', () => {
80
+ it('keeps the first item active on a page that does not scroll at all', () => {
81
+ // maxScrollY is 0 here, so no section's own trigger is reachable - the first
82
+ // one on screen should stay active rather than the compression math treating
83
+ // "ran out of sections to check" the same as "found a reachable trigger" and
84
+ // collapsing everything onto the last item.
85
+ setViewport({ scrollY: 0, innerHeight: 800, scrollHeight: 800 })
86
+ setSectionTops([
87
+ { id: 'family', top: 200 },
88
+ { id: 'documents', top: 500 },
89
+ { id: 'signature', top: 650 },
90
+ { id: 'residence', top: 750 },
91
+ ])
92
+
93
+ const { result } = renderHook(() =>
94
+ useSideNavScrollSpy({ itemIds: ['family', 'documents', 'signature', 'residence'] }),
95
+ )
96
+
97
+ expect(result.current.activeItemId).toBe('family')
98
+ })
99
+
100
+ it('defaults the active item to the first id before any scroll', () => {
101
+ const { result } = renderHook(() =>
102
+ useSideNavScrollSpy({ itemIds: ['family', 'documents', 'signature', 'residence'] }),
103
+ )
104
+
105
+ expect(result.current.activeItemId).toBe('family')
106
+ })
107
+
108
+ it('activates a section once its top scrolls past the activation line, even when it is short', async () => {
109
+ const { result } = renderHook(() =>
110
+ useSideNavScrollSpy({ itemIds: ['family', 'documents', 'signature', 'residence'] }),
111
+ )
112
+
113
+ // Scrolled so that "documents" and "signature" (both short) have already
114
+ // passed the top, but "residence" has not yet - "documents" must win here,
115
+ // not get skipped in favor of whichever section shows the most pixels.
116
+ setSectionTops([
117
+ { id: 'family', top: -300 },
118
+ { id: 'documents', top: -50 },
119
+ { id: 'signature', top: 100 },
120
+ { id: 'residence', top: 250 },
121
+ ])
122
+ await fireScroll()
123
+
124
+ expect(result.current.activeItemId).toBe('documents')
125
+ })
126
+
127
+ it('advances to the next section once its top crosses the activation line', async () => {
128
+ const { result } = renderHook(() =>
129
+ useSideNavScrollSpy({ itemIds: ['family', 'documents', 'signature', 'residence'] }),
130
+ )
131
+
132
+ setSectionTops([
133
+ { id: 'family', top: -400 },
134
+ { id: 'documents', top: -100 },
135
+ { id: 'signature', top: -10 },
136
+ { id: 'residence', top: 40 },
137
+ ])
138
+ await fireScroll()
139
+
140
+ expect(result.current.activeItemId).toBe('signature')
141
+ })
142
+
143
+ it('respects a non-zero offset (e.g. a sticky header) as the activation line', async () => {
144
+ const { result } = renderHook(() =>
145
+ useSideNavScrollSpy({
146
+ itemIds: ['family', 'documents', 'signature', 'residence'],
147
+ offset: 100,
148
+ }),
149
+ )
150
+
151
+ setSectionTops([
152
+ { id: 'family', top: -400 },
153
+ { id: 'documents', top: -50 },
154
+ { id: 'signature', top: 90 },
155
+ { id: 'residence', top: 300 },
156
+ ])
157
+ await fireScroll()
158
+
159
+ expect(result.current.activeItemId).toBe('signature')
160
+ })
161
+
162
+ it('gives every trailing section its own ordered window even when the page runs out of room for their tops to reach the activation line', async () => {
163
+ // Document-absolute tops: family=0, documents=100, signature=300, residence=380.
164
+ // innerHeight=400, scrollHeight=650 -> maxScrollY=250, so "residence"'s natural
165
+ // trigger (380) is unreachable, and "signature"'s (300) barely is. Naively
166
+ // clamping both to maxScrollY would collapse them onto the same point and skip
167
+ // straight from "documents" to "residence" - exactly the bug this covers.
168
+ const { result } = renderHook(() =>
169
+ useSideNavScrollSpy({ itemIds: ['family', 'documents', 'signature', 'residence'] }),
170
+ )
171
+
172
+ setViewport({ scrollY: 150, innerHeight: 400, scrollHeight: 650 })
173
+ setSectionTops([
174
+ { id: 'family', top: -150 },
175
+ { id: 'documents', top: -50 },
176
+ { id: 'signature', top: 150 },
177
+ { id: 'residence', top: 230 },
178
+ ])
179
+ await fireScroll()
180
+ expect(result.current.activeItemId).toBe('documents')
181
+
182
+ setViewport({ scrollY: 220, innerHeight: 400, scrollHeight: 650 })
183
+ setSectionTops([
184
+ { id: 'family', top: -220 },
185
+ { id: 'documents', top: -120 },
186
+ { id: 'signature', top: 80 },
187
+ { id: 'residence', top: 160 },
188
+ ])
189
+ await fireScroll()
190
+ expect(result.current.activeItemId).toBe('signature')
191
+
192
+ setViewport({ scrollY: 250, innerHeight: 400, scrollHeight: 650 })
193
+ setSectionTops([
194
+ { id: 'family', top: -250 },
195
+ { id: 'documents', top: -150 },
196
+ { id: 'signature', top: 50 },
197
+ { id: 'residence', top: 130 },
198
+ ])
199
+ await fireScroll()
200
+ expect(result.current.activeItemId).toBe('residence')
201
+ })
202
+
203
+ it('does not drift the active id when some ids have no matching element on the page', async () => {
204
+ // Only "documents" and "signature" exist on the page; "family" and "residence"
205
+ // never render. activeIndex is computed against the filtered (DOM-resolved)
206
+ // list, so reading the result back out of the original itemIds by that same
207
+ // index would return the wrong id as soon as the two arrays' lengths diverge.
208
+ document.body.innerHTML = '<div id="documents"></div><div id="signature"></div>'
209
+ setSectionTops([
210
+ { id: 'documents', top: -400 },
211
+ { id: 'signature', top: -100 },
212
+ ])
213
+
214
+ const { result } = renderHook(() =>
215
+ useSideNavScrollSpy({ itemIds: ['family', 'documents', 'signature', 'residence'] }),
216
+ )
217
+
218
+ expect(result.current.activeItemId).toBe('signature')
219
+ })
220
+
221
+ it('does not permanently freeze scroll-spy when itemIds/offset change while a scroll frame is pending', async () => {
222
+ const { result, rerender } = renderHook(
223
+ ({ offset }: { offset: number }) =>
224
+ useSideNavScrollSpy({
225
+ itemIds: ['family', 'documents', 'signature', 'residence'],
226
+ offset,
227
+ }),
228
+ { initialProps: { offset: 0 } },
229
+ )
230
+
231
+ // Schedule a frame via a scroll event, then re-render with a different offset
232
+ // before that frame's callback has fired - this tears down and re-runs the
233
+ // effect (cancelling the pending frame) while rafRef.current is still set.
234
+ act(() => {
235
+ window.dispatchEvent(new Event('scroll'))
236
+ })
237
+ rerender({ offset: 5 })
238
+
239
+ // Let the now-cancelled frame's leftover microtask resolve.
240
+ await act(async () => {
241
+ await Promise.resolve()
242
+ })
243
+
244
+ // A fresh scroll after that should still be able to update the active item -
245
+ // if cleanup left rafRef.current stuck non-undefined, this would be a no-op
246
+ // and activeItemId would stay pinned on "family" forever.
247
+ setSectionTops([
248
+ { id: 'family', top: -400 },
249
+ { id: 'documents', top: -100 },
250
+ { id: 'signature', top: -10 },
251
+ { id: 'residence', top: 40 },
252
+ ])
253
+ await fireScroll()
254
+
255
+ expect(result.current.activeItemId).toBe('signature')
256
+ })
257
+
258
+ it('scrollToItem scrolls to the element and marks it active immediately', () => {
259
+ const scrollToMock = vi.fn()
260
+ vi.stubGlobal('scrollTo', scrollToMock)
261
+ vi.stubGlobal(
262
+ 'matchMedia',
263
+ vi.fn(() => ({ matches: false })),
264
+ )
265
+
266
+ const { result } = renderHook(() =>
267
+ useSideNavScrollSpy({ itemIds: ['family', 'documents', 'signature', 'residence'] }),
268
+ )
269
+
270
+ act(() => {
271
+ result.current.scrollToItem('signature')
272
+ })
273
+
274
+ expect(scrollToMock).toHaveBeenCalledTimes(1)
275
+ expect(scrollToMock).toHaveBeenCalledWith(
276
+ expect.objectContaining({ behavior: 'smooth' }),
277
+ )
278
+ expect(result.current.activeItemId).toBe('signature')
279
+ })
280
+
281
+ it('does not let scroll events fired by its own smooth-scroll animation flicker activeItemId away from the clicked item', async () => {
282
+ // scrollToItem's window.scrollTo is a no-op in jsdom, so the scroll events it
283
+ // "fires" here are standing in for the real animation's intermediate frames -
284
+ // section positions still reflecting the pre-click layout is exactly what a
285
+ // scroll event mid-animation would see, and it must be ignored. Date.now is
286
+ // controlled directly (rather than via fake timers, which would also hijack
287
+ // this file's own requestAnimationFrame stub) to move past the suppression
288
+ // window deterministically.
289
+ vi.stubGlobal('scrollTo', vi.fn())
290
+ vi.stubGlobal(
291
+ 'matchMedia',
292
+ vi.fn(() => ({ matches: false })),
293
+ )
294
+ const start = Date.now()
295
+ const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(start)
296
+
297
+ const { result } = renderHook(() =>
298
+ useSideNavScrollSpy({ itemIds: ['family', 'documents', 'signature', 'residence'] }),
299
+ )
300
+
301
+ act(() => {
302
+ result.current.scrollToItem('residence')
303
+ })
304
+ expect(result.current.activeItemId).toBe('residence')
305
+
306
+ nowSpy.mockReturnValue(start + 300)
307
+ await fireScroll()
308
+ expect(result.current.activeItemId).toBe('residence')
309
+
310
+ nowSpy.mockReturnValue(start + 700)
311
+ await fireScroll()
312
+ expect(result.current.activeItemId).toBe('family')
313
+ })
314
+
315
+ it('scrolls instantly when the user prefers reduced motion', () => {
316
+ const scrollToMock = vi.fn()
317
+ vi.stubGlobal('scrollTo', scrollToMock)
318
+ vi.stubGlobal(
319
+ 'matchMedia',
320
+ vi.fn(() => ({ matches: true })),
321
+ )
322
+
323
+ const { result } = renderHook(() =>
324
+ useSideNavScrollSpy({ itemIds: ['family', 'documents', 'signature', 'residence'] }),
325
+ )
326
+
327
+ act(() => {
328
+ result.current.scrollToItem('signature')
329
+ })
330
+
331
+ expect(scrollToMock).toHaveBeenCalledWith(
332
+ expect.objectContaining({ behavior: 'auto' }),
333
+ )
334
+ })
335
+
336
+ it('does not suppress scroll-driven updates when the jump is instant (reduced motion)', async () => {
337
+ vi.stubGlobal('scrollTo', vi.fn())
338
+ vi.stubGlobal(
339
+ 'matchMedia',
340
+ vi.fn(() => ({ matches: true })),
341
+ )
342
+
343
+ const { result } = renderHook(() =>
344
+ useSideNavScrollSpy({ itemIds: ['family', 'documents', 'signature', 'residence'] }),
345
+ )
346
+
347
+ act(() => {
348
+ result.current.scrollToItem('residence')
349
+ })
350
+ expect(result.current.activeItemId).toBe('residence')
351
+
352
+ await fireScroll()
353
+ expect(result.current.activeItemId).toBe('family')
354
+ })
355
+
356
+ it('does nothing when scrolling to an id with no matching element', () => {
357
+ const scrollToMock = vi.fn()
358
+ vi.stubGlobal('scrollTo', scrollToMock)
359
+
360
+ const { result } = renderHook(() =>
361
+ useSideNavScrollSpy({ itemIds: ['family', 'documents', 'signature', 'residence'] }),
362
+ )
363
+
364
+ act(() => {
365
+ result.current.scrollToItem('missing')
366
+ })
367
+
368
+ expect(scrollToMock).not.toHaveBeenCalled()
369
+ })
370
+
371
+ it('stops reacting to scroll after unmount', async () => {
372
+ const { result, unmount } = renderHook(() =>
373
+ useSideNavScrollSpy({ itemIds: ['family', 'documents', 'signature', 'residence'] }),
374
+ )
375
+
376
+ unmount()
377
+
378
+ setSectionTops([
379
+ { id: 'family', top: -400 },
380
+ { id: 'documents', top: -100 },
381
+ { id: 'signature', top: -10 },
382
+ { id: 'residence', top: 40 },
383
+ ])
384
+ await fireScroll()
385
+
386
+ expect(result.current.activeItemId).toBe('family')
387
+ })
388
+
389
+ it('does not attach scroll/resize listeners when itemIds is empty', () => {
390
+ const addEventListenerSpy = vi.spyOn(window, 'addEventListener')
391
+
392
+ renderHook(() => useSideNavScrollSpy({ itemIds: [] }))
393
+
394
+ expect(addEventListenerSpy).not.toHaveBeenCalledWith('scroll', expect.anything())
395
+ expect(addEventListenerSpy).not.toHaveBeenCalledWith('resize', expect.anything())
396
+
397
+ addEventListenerSpy.mockRestore()
398
+ })
399
+
400
+ it('resolves ids only within the given scope, ignoring a same-id collision outside it', () => {
401
+ // A "documents" element outside the scope has already scrolled past the
402
+ // activation line - if resolution weren't bounded to `scope`, it (not the real
403
+ // one inside it) would win and wrongly mark "documents" active over "family".
404
+ document.body.innerHTML = ''
405
+
406
+ const outsideDocuments = document.createElement('div')
407
+ outsideDocuments.id = 'documents'
408
+ outsideDocuments.getBoundingClientRect = () => ({ top: -500 }) as DOMRect
409
+ document.body.appendChild(outsideDocuments)
410
+
411
+ const scopeEl = document.createElement('div')
412
+ const family = document.createElement('div')
413
+ family.id = 'family'
414
+ family.getBoundingClientRect = () => ({ top: 0 }) as DOMRect
415
+ const insideDocuments = document.createElement('div')
416
+ insideDocuments.id = 'documents'
417
+ insideDocuments.getBoundingClientRect = () => ({ top: 300 }) as DOMRect
418
+ scopeEl.appendChild(family)
419
+ scopeEl.appendChild(insideDocuments)
420
+ document.body.appendChild(scopeEl)
421
+
422
+ const scope = { current: scopeEl }
423
+ const { result } = renderHook(() =>
424
+ useSideNavScrollSpy({ itemIds: ['family', 'documents'], scope }),
425
+ )
426
+
427
+ expect(result.current.activeItemId).toBe('family')
428
+ })
429
+
430
+ it('picks up a lazily-added section immediately via the mutation observer, without waiting for a scroll or resize event', async () => {
431
+ document.body.innerHTML = '<div id="scope"><div id="family"></div></div>'
432
+ setViewport({ scrollY: 500, innerHeight: 800, scrollHeight: 3000 })
433
+ const scopeEl = document.getElementById('scope') as HTMLElement
434
+ const family = scopeEl.querySelector('#family') as HTMLElement
435
+ family.getBoundingClientRect = () => ({ top: -400 }) as DOMRect
436
+
437
+ const scope = { current: scopeEl }
438
+ const { result } = renderHook(() =>
439
+ useSideNavScrollSpy({ itemIds: ['family', 'documents'], scope }),
440
+ )
441
+
442
+ expect(result.current.activeItemId).toBe('family')
443
+
444
+ const documents = document.createElement('div')
445
+ documents.id = 'documents'
446
+ documents.getBoundingClientRect = () => ({ top: -100 }) as DOMRect
447
+
448
+ await act(async () => {
449
+ scopeEl.appendChild(documents)
450
+ await Promise.resolve()
451
+ await Promise.resolve()
452
+ await Promise.resolve()
453
+ })
454
+
455
+ expect(result.current.activeItemId).toBe('documents')
456
+ })
457
+ })
@@ -0,0 +1,154 @@
1
+ import { RefObject, useCallback, useEffect, useRef, useState } from 'react'
2
+
3
+ const ACTIVATION_LINE_EPSILON = 1
4
+ // Long enough to cover a native smooth-scroll to any in-page section for this
5
+ // component's use case (a single service page's sidebar nav, not an arbitrarily
6
+ // long document).
7
+ const PROGRAMMATIC_SCROLL_SETTLE_MS = 600
8
+
9
+ type UseSideNavScrollSpyOptions = {
10
+ itemIds: string[]
11
+ offset?: number
12
+ // Bounds id resolution to this subtree so an id collision elsewhere on the page
13
+ // can't win or lose the activation check. Defaults to the whole document.
14
+ scope?: RefObject<HTMLElement>
15
+ }
16
+
17
+ function findScopedElement(root: Document | HTMLElement, id: string): HTMLElement | null {
18
+ if (root instanceof Document) return root.getElementById(id)
19
+ // Attribute selector, so an id that is not a valid CSS selector cannot throw.
20
+ return root.querySelector<HTMLElement>(`[id="${id.replace(/"/g, '\\"')}"]`)
21
+ }
22
+
23
+ function useSideNavScrollSpy({ itemIds, offset = 0, scope }: UseSideNavScrollSpyOptions) {
24
+ const [activeItemId, setActiveItemId] = useState<string | undefined>(itemIds[0])
25
+ const rafRef = useRef<number>()
26
+ const suppressUntilRef = useRef(0)
27
+ const itemIdsKey = itemIds.join('|')
28
+
29
+ useEffect(() => {
30
+ if (itemIds.length === 0) return undefined
31
+
32
+ const root: Document | HTMLElement = scope?.current ?? document
33
+
34
+ // Resolved fresh on every call (not cached once at mount) so sections added to
35
+ // the DOM after mount - e.g. lazily-loaded content - still get picked up
36
+ // immediately via the MutationObserver below, or on the next scroll/resize.
37
+ const updateActiveItem = () => {
38
+ // A click-driven scrollToItem() already set the correct activeItemId - the
39
+ // scroll events fired by its own smooth-scroll animation would otherwise
40
+ // recompute (and flicker) it through every section the animation passes over
41
+ // before landing on the clicked one.
42
+ if (Date.now() < suppressUntilRef.current) return
43
+
44
+ const resolved = itemIds
45
+ .map((id) => ({ id, element: findScopedElement(root, id) }))
46
+ .filter(
47
+ (entry): entry is { id: string; element: HTMLElement } =>
48
+ entry.element !== null,
49
+ )
50
+
51
+ if (resolved.length === 0) return
52
+
53
+ const { scrollY } = window
54
+ const maxScrollY = Math.max(
55
+ 0,
56
+ document.documentElement.scrollHeight - window.innerHeight,
57
+ )
58
+ const tops = resolved.map(
59
+ ({ element }) => element.getBoundingClientRect().top + scrollY,
60
+ )
61
+ const triggers = tops.map((top) => top - offset)
62
+ let lastReachable = triggers.length - 1
63
+ while (lastReachable > 0 && triggers[lastReachable] > maxScrollY) {
64
+ lastReachable -= 1
65
+ }
66
+
67
+ const adjustedTriggers = [...triggers]
68
+ const startTrigger = triggers[lastReachable]
69
+ // The while loop above can land on index 0 for two different reasons: because
70
+ // that section is genuinely reachable (its own trigger <= maxScrollY), or
71
+ // simply because it ran out of sections to check - e.g. the whole page fits in
72
+ // one viewport, so nothing is reachable at all. Only the first case should
73
+ // trigger compression; otherwise (maxScrollY - startTrigger) is <= 0, which
74
+ // collapses every trigger onto the same point or runs them backwards, and the
75
+ // last section ends up wrongly marked active on a page that never scrolls.
76
+ if (lastReachable < triggers.length - 1 && startTrigger < maxScrollY) {
77
+ const startTop = tops[lastReachable]
78
+ const span = tops[tops.length - 1] - startTop
79
+ for (let index = lastReachable + 1; index < triggers.length; index += 1) {
80
+ const ratio = span > 0 ? (tops[index] - startTop) / span : 1
81
+ adjustedTriggers[index] = startTrigger + ratio * (maxScrollY - startTrigger)
82
+ }
83
+ }
84
+
85
+ let activeIndex = 0
86
+ adjustedTriggers.forEach((trigger, index) => {
87
+ if (trigger <= scrollY + ACTIVATION_LINE_EPSILON) activeIndex = index
88
+ })
89
+ // Read the id back out of `resolved`, not `itemIds` - activeIndex is an index
90
+ // into the filtered (DOM-resolved) list, and the two arrays drift apart as
91
+ // soon as any id has no matching element on the page.
92
+ setActiveItemId(resolved[activeIndex].id)
93
+ }
94
+
95
+ const scheduleUpdate = () => {
96
+ if (rafRef.current !== undefined) return
97
+ rafRef.current = requestAnimationFrame(() => {
98
+ rafRef.current = undefined
99
+ updateActiveItem()
100
+ })
101
+ }
102
+
103
+ updateActiveItem()
104
+ window.addEventListener('scroll', scheduleUpdate, { passive: true })
105
+ window.addEventListener('resize', scheduleUpdate)
106
+
107
+ // Sections added to the DOM after mount - e.g. lazily-loaded content - should
108
+ // register immediately rather than waiting for the next scroll/resize event.
109
+ // Skipped when unscoped, where it would observe the whole document.
110
+ const mutationObserver =
111
+ root instanceof Document ? undefined : new MutationObserver(scheduleUpdate)
112
+ mutationObserver?.observe(root, { childList: true, subtree: true })
113
+
114
+ return () => {
115
+ window.removeEventListener('scroll', scheduleUpdate)
116
+ window.removeEventListener('resize', scheduleUpdate)
117
+ mutationObserver?.disconnect()
118
+ // Also reset the ref, not just cancel the frame - otherwise the next effect
119
+ // instance's scheduleUpdate sees a stale non-undefined handle on its in-flight
120
+ // guard and silently refuses to ever schedule another update.
121
+ if (rafRef.current !== undefined) cancelAnimationFrame(rafRef.current)
122
+ rafRef.current = undefined
123
+ }
124
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- itemIdsKey stands in for itemIds; scope is a ref, its identity is stable
125
+ }, [itemIdsKey, offset])
126
+
127
+ const scrollToItem = useCallback(
128
+ (id: string) => {
129
+ const element = findScopedElement(scope?.current ?? document, id)
130
+ if (!element) return
131
+
132
+ const prefersReducedMotion = window.matchMedia(
133
+ '(prefers-reduced-motion: reduce)',
134
+ ).matches
135
+ const top = element.getBoundingClientRect().top + window.scrollY - offset
136
+
137
+ // Always (re)assign rather than only when animating, so an instant
138
+ // (reduced-motion) click can't leave a still-running suppression window
139
+ // from an earlier animated click blocking its own follow-up scroll updates.
140
+ suppressUntilRef.current = prefersReducedMotion
141
+ ? 0
142
+ : Date.now() + PROGRAMMATIC_SCROLL_SETTLE_MS
143
+ window.scrollTo({ top, behavior: prefersReducedMotion ? 'auto' : 'smooth' })
144
+ setActiveItemId(id)
145
+ },
146
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- scope is a ref, its identity is stable
147
+ [offset],
148
+ )
149
+
150
+ return { activeItemId, scrollToItem }
151
+ }
152
+
153
+ export default useSideNavScrollSpy
154
+ export type { UseSideNavScrollSpyOptions }