@registrucentras/rc-ses-react-components 2.0.0-rc.8 → 2.0.0-rc.9

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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@registrucentras/rc-ses-react-components",
3
3
  "author": "VĮ REGISTRŲ CENTRAS",
4
- "version": "2.0.0-rc.8",
4
+ "version": "2.0.0-rc.9",
5
5
  "description": "RC SES React komponentų biblioteka",
6
6
  "type": "module",
7
7
  "private": false,
@@ -22,10 +22,20 @@ export interface RcSesSideNavProps {
22
22
  // Height of the sticky page header the nav sits below. Decides both where the
23
23
  // nav sticks and, with overflow='scroll', how tall it may grow.
24
24
  offset?: number
25
+ // Reports the height of the mobile bar, which is sticky and overlays the
26
+ // scrolling content - 0 on the desktop layout, where the nav overlays nothing.
27
+ // Anything that scrolls the page to a section has to clear it on top of
28
+ // `offset`; RcSesSideNavLayout does that for its own children.
29
+ onOverlayHeightChange?: (height: number) => void
25
30
  sx?: SxProps<Theme>
26
31
  }
27
32
 
28
- export type RcSesSideNavLayoutProps = Omit<RcSesSideNavProps, 'sx'> & {
33
+ // The layout measures the mobile bar for its own children, so the callback is
34
+ // not part of its surface.
35
+ export type RcSesSideNavLayoutProps = Omit<
36
+ RcSesSideNavProps,
37
+ 'sx' | 'onOverlayHeightChange'
38
+ > & {
29
39
  children: ReactNode
30
40
  sidebarWidth?: string
31
41
  sx?: SxProps<Theme>
@@ -15,6 +15,10 @@ function ResizeObserverMock() {
15
15
 
16
16
  Element.prototype.scrollIntoView = vi.fn()
17
17
 
18
+ const HEADER_OFFSET = 56
19
+ const MOBILE_BAR_HEIGHT = 62
20
+ const SECTION_TOP = 500
21
+
18
22
  const items: RcSesSideNavItem[] = [
19
23
  { id: 'family', label: 'Aš ir mano šeima', count: 4 },
20
24
  { id: 'documents', label: 'Dokumentai apie gyventoją', count: 2 },
@@ -31,6 +35,7 @@ describe('RcSesSideNavLayout', () => {
31
35
 
32
36
  afterEach(() => {
33
37
  vi.unstubAllGlobals()
38
+ vi.restoreAllMocks()
34
39
  })
35
40
 
36
41
  it('renders the nav alongside its content children', () => {
@@ -84,6 +89,53 @@ describe('RcSesSideNavLayout', () => {
84
89
  )
85
90
  })
86
91
 
92
+ // The mobile bar is sticky on top of the content: land a section at the page
93
+ // header's height alone and the bar covers its heading, so the first thing the
94
+ // reader sees is the section's first row.
95
+ it('clears the mobile bar as well as the page header when scrolling to an item', () => {
96
+ const scrollToMock = vi.fn()
97
+ vi.stubGlobal('scrollTo', scrollToMock)
98
+ vi.stubGlobal(
99
+ 'matchMedia',
100
+ vi.fn(() => ({ matches: false })),
101
+ )
102
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(
103
+ () => ({ top: SECTION_TOP, height: MOBILE_BAR_HEIGHT }) as DOMRect,
104
+ )
105
+
106
+ renderLayout(
107
+ <RcSesSideNavLayout items={items} title='Temos' offset={HEADER_OFFSET}>
108
+ <div id='family' />
109
+ <div id='documents' />
110
+ </RcSesSideNavLayout>,
111
+ )
112
+
113
+ act(() => {
114
+ screen.getAllByRole('button', { name: 'Dokumentai apie gyventoją, 2' })[0].click()
115
+ })
116
+
117
+ expect(scrollToMock).toHaveBeenCalledWith(
118
+ expect.objectContaining({ top: SECTION_TOP - HEADER_OFFSET - MOBILE_BAR_HEIGHT }),
119
+ )
120
+ })
121
+
122
+ it('publishes that same offset for the sections to scroll-margin by', () => {
123
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(
124
+ () => ({ top: SECTION_TOP, height: MOBILE_BAR_HEIGHT }) as DOMRect,
125
+ )
126
+
127
+ const { container } = renderLayout(
128
+ <RcSesSideNavLayout items={items} title='Temos' offset={HEADER_OFFSET}>
129
+ <div id='family' />
130
+ </RcSesSideNavLayout>,
131
+ )
132
+
133
+ const content = container.querySelector<HTMLElement>('[style*="scroll-offset"]')
134
+ expect(content?.style.getPropertyValue('--rc-ses-sidenav-scroll-offset')).toBe(
135
+ `${HEADER_OFFSET + MOBILE_BAR_HEIGHT}px`,
136
+ )
137
+ })
138
+
87
139
  it('does not throw when clicked with no matching section in the content', () => {
88
140
  renderLayout(
89
141
  <RcSesSideNavLayout items={items} title='Temos'>
@@ -1,5 +1,5 @@
1
1
  import { Box } from '@mui/material'
2
- import { useRef } from 'react'
2
+ import { CSSProperties, useRef, useState } from 'react'
3
3
 
4
4
  import normalizeSx from '@/components/utils/normalizeSx'
5
5
 
@@ -20,11 +20,17 @@ function RcSesSideNavLayout({
20
20
  }: RcSesSideNavLayoutProps) {
21
21
  const contentRef = useRef<HTMLDivElement>(null)
22
22
 
23
+ // The mobile bar is sticky and sits on top of the content, so a section
24
+ // scrolled to at `offset` would land underneath it - heading first. Everything
25
+ // that scrolls the page has to clear the bar as well as the page header.
26
+ const [overlayHeight, setOverlayHeight] = useState(0)
27
+ const scrollOffset = (offset ?? 0) + overlayHeight
28
+
23
29
  const isControlled = controlledActiveItemId !== undefined
24
30
  const itemIds = items.map((item) => item.id)
25
31
  const scrollSpy = useSideNavScrollSpy({
26
32
  itemIds: isControlled ? [] : itemIds,
27
- offset,
33
+ offset: scrollOffset,
28
34
  scope: contentRef,
29
35
  })
30
36
  const activeItemId = isControlled ? controlledActiveItemId : scrollSpy.activeItemId
@@ -51,6 +57,7 @@ function RcSesSideNavLayout({
51
57
  title={title}
52
58
  overflow={overflow}
53
59
  offset={offset}
60
+ onOverlayHeightChange={setOverlayHeight}
54
61
  sx={{
55
62
  position: 'sticky',
56
63
  top: `${offset ?? 0}px`,
@@ -59,7 +66,17 @@ function RcSesSideNavLayout({
59
66
  flexShrink: 0,
60
67
  }}
61
68
  />
62
- <Box ref={contentRef} sx={{ flex: 1, minWidth: 0 }}>
69
+ {/*
70
+ Sections are the consumer's, so the layout cannot set their
71
+ scroll-margin itself; it publishes the offset they need instead:
72
+ `scrollMarginTop: 'var(--rc-ses-sidenav-scroll-offset)'`. Inline rather
73
+ than in sx, so a resize rewrites one property instead of minting a class.
74
+ */}
75
+ <Box
76
+ ref={contentRef}
77
+ style={{ '--rc-ses-sidenav-scroll-offset': `${scrollOffset}px` } as CSSProperties}
78
+ sx={{ flex: 1, minWidth: 0 }}
79
+ >
63
80
  {children}
64
81
  </Box>
65
82
  </Box>
@@ -0,0 +1,135 @@
1
+ import { act, renderHook } from '@testing-library/react'
2
+ import { createRef } from 'react'
3
+ import { afterEach, describe, expect, it, vi } from 'vitest'
4
+
5
+ import useElementHeight from './useElementHeight'
6
+
7
+ type ResizeCallback = () => void
8
+
9
+ const resizeCallbacks: ResizeCallback[] = []
10
+ const disconnect = vi.fn()
11
+
12
+ // Matches the sibling SideNav suites: a plain function, so `new` hands back the
13
+ // object below rather than a class instance ESLint wants methods on.
14
+ function ResizeObserverMock(callback: ResizeCallback) {
15
+ resizeCallbacks.push(callback)
16
+ return { observe: () => {}, unobserve: () => {}, disconnect }
17
+ }
18
+
19
+ function elementOfHeight(height: number) {
20
+ const element = document.createElement('div')
21
+ vi.spyOn(element, 'getBoundingClientRect').mockImplementation(
22
+ () => ({ height }) as DOMRect,
23
+ )
24
+ return element
25
+ }
26
+
27
+ function remeasureAt(element: HTMLElement, height: number) {
28
+ vi.spyOn(element, 'getBoundingClientRect').mockImplementation(
29
+ () => ({ height }) as DOMRect,
30
+ )
31
+ }
32
+
33
+ function renderWithElement(element: HTMLElement | null) {
34
+ const ref = createRef<HTMLElement>()
35
+ Object.assign(ref, { current: element })
36
+ return renderHook(() => useElementHeight(ref))
37
+ }
38
+
39
+ describe('useElementHeight', () => {
40
+ afterEach(() => {
41
+ resizeCallbacks.length = 0
42
+ disconnect.mockClear()
43
+ vi.unstubAllGlobals()
44
+ vi.restoreAllMocks()
45
+ })
46
+
47
+ it('returns 0 when there is no element to measure', () => {
48
+ const { result } = renderWithElement(null)
49
+
50
+ expect(result.current).toBe(0)
51
+ })
52
+
53
+ it('measures the element on mount', () => {
54
+ vi.stubGlobal('ResizeObserver', ResizeObserverMock)
55
+
56
+ const { result } = renderWithElement(elementOfHeight(62))
57
+
58
+ expect(result.current).toBe(62)
59
+ })
60
+
61
+ // A hidden element has no box at all, which is what lets the caller use the
62
+ // height as a breakpoint test.
63
+ it('reports 0 for an element the media query switched off', () => {
64
+ vi.stubGlobal('ResizeObserver', ResizeObserverMock)
65
+
66
+ const { result } = renderWithElement(elementOfHeight(0))
67
+
68
+ expect(result.current).toBe(0)
69
+ })
70
+
71
+ it('rounds to whole pixels', () => {
72
+ vi.stubGlobal('ResizeObserver', ResizeObserverMock)
73
+
74
+ const { result } = renderWithElement(elementOfHeight(61.6))
75
+
76
+ expect(result.current).toBe(62)
77
+ })
78
+
79
+ it('re-measures when the element resizes in place', () => {
80
+ vi.stubGlobal('ResizeObserver', ResizeObserverMock)
81
+ const element = elementOfHeight(62)
82
+
83
+ const { result } = renderWithElement(element)
84
+ remeasureAt(element, 104)
85
+ act(() => resizeCallbacks.forEach((callback) => callback()))
86
+
87
+ expect(result.current).toBe(104)
88
+ })
89
+
90
+ // A viewport resize that changes the element's box is a resize of the element,
91
+ // so the observer already reports it and a second listener would only measure
92
+ // the same thing twice.
93
+ it('does not listen for viewport resizes alongside the observer', () => {
94
+ vi.stubGlobal('ResizeObserver', ResizeObserverMock)
95
+ const addEventListener = vi.spyOn(window, 'addEventListener')
96
+
97
+ renderWithElement(elementOfHeight(62))
98
+
99
+ expect(addEventListener).not.toHaveBeenCalledWith('resize', expect.anything())
100
+ })
101
+
102
+ it('falls back to a viewport resize listener where ResizeObserver is missing', () => {
103
+ vi.stubGlobal('ResizeObserver', undefined)
104
+ const element = elementOfHeight(62)
105
+
106
+ const { result } = renderWithElement(element)
107
+ expect(result.current).toBe(62)
108
+
109
+ remeasureAt(element, 0)
110
+ act(() => window.dispatchEvent(new Event('resize')))
111
+
112
+ expect(result.current).toBe(0)
113
+ })
114
+
115
+ it('disconnects the observer once unmounted', () => {
116
+ vi.stubGlobal('ResizeObserver', ResizeObserverMock)
117
+
118
+ const { unmount } = renderWithElement(elementOfHeight(62))
119
+ unmount()
120
+
121
+ expect(disconnect).toHaveBeenCalled()
122
+ })
123
+
124
+ it('drops the fallback listener once unmounted', () => {
125
+ vi.stubGlobal('ResizeObserver', undefined)
126
+ const element = elementOfHeight(62)
127
+
128
+ const { result, unmount } = renderWithElement(element)
129
+ unmount()
130
+ remeasureAt(element, 104)
131
+ act(() => window.dispatchEvent(new Event('resize')))
132
+
133
+ expect(result.current).toBe(62)
134
+ })
135
+ })
@@ -0,0 +1,46 @@
1
+ import { RefObject, useCallback, useLayoutEffect, useState } from 'react'
2
+
3
+ /**
4
+ * Rendered height of an element, in pixels.
5
+ *
6
+ * 0 while the element is absent or `display: none`, which is what makes this
7
+ * usable as a breakpoint test: the nav's mobile bar and desktop column are
8
+ * swapped by a media query, so measuring the one that is switched off yields 0
9
+ * without the hook having to know anything about breakpoints.
10
+ */
11
+ function useElementHeight(ref: RefObject<HTMLElement>): number {
12
+ const [height, setHeight] = useState(0)
13
+
14
+ const measure = useCallback((element: HTMLElement | null) => {
15
+ setHeight(element ? Math.round(element.getBoundingClientRect().height) : 0)
16
+ }, [])
17
+
18
+ // Before paint, not after: the height feeds the offset the page is scrolled
19
+ // by, and a consumer that scrolls on mount - honouring a #hash deep link, say
20
+ // - runs its own effect after this one and would otherwise read 0.
21
+ useLayoutEffect(() => {
22
+ const element = ref.current
23
+ measure(element)
24
+ if (!element) return undefined
25
+
26
+ // The bar changes height in place - the pills wrap, a late web font lands,
27
+ // the media query switches it off entirely - and a ResizeObserver reports
28
+ // all of it, viewport resizes included. So the window listener is the
29
+ // fallback for where ResizeObserver is missing, not a second opinion
30
+ // running alongside it.
31
+ if (typeof ResizeObserver !== 'undefined') {
32
+ const observer = new ResizeObserver(() => measure(element))
33
+ observer.observe(element)
34
+ return () => observer.disconnect()
35
+ }
36
+
37
+ const onResize = () => measure(element)
38
+ window.addEventListener('resize', onResize)
39
+ return () => window.removeEventListener('resize', onResize)
40
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- ref is a ref, its identity is stable
41
+ }, [measure])
42
+
43
+ return height
44
+ }
45
+
46
+ export default useElementHeight
@@ -1,5 +1,5 @@
1
1
  import { Box, Typography } from '@mui/material'
2
- import { useRef } from 'react'
2
+ import { useEffect, useRef } from 'react'
3
3
  import { useTranslation } from 'react-i18next'
4
4
 
5
5
  import normalizeSx from '@/components/utils/normalizeSx'
@@ -8,6 +8,7 @@ import palette, { common } from '@/theme/palette'
8
8
  import { RcSesSideNavItem, RcSesSideNavProps } from './SideNav.types'
9
9
  import SideNavPillList from './components/SideNavPillList'
10
10
  import SideNavRow from './components/SideNavRow'
11
+ import useElementHeight from './hooks/useElementHeight'
11
12
  import useKeepActiveItemInView from './hooks/useKeepActiveItemInView'
12
13
 
13
14
  const ROW_GAP = '0.25rem'
@@ -19,11 +20,13 @@ function RcSesSideNav({
19
20
  title,
20
21
  overflow = 'fit',
21
22
  offset = 0,
23
+ onOverlayHeightChange,
22
24
  sx,
23
25
  }: RcSesSideNavProps) {
24
26
  const { t } = useTranslation('common', { keyPrefix: 'components.RcSesSideNav' })
25
27
  const navTitle = title ?? t('title')
26
28
  const rowListRef = useRef<HTMLDivElement>(null)
29
+ const pillBarRef = useRef<HTMLDivElement>(null)
27
30
 
28
31
  const isScrollable = overflow === 'scroll'
29
32
  useKeepActiveItemInView({
@@ -34,6 +37,13 @@ function RcSesSideNav({
34
37
  behavior: 'smooth',
35
38
  })
36
39
 
40
+ // 0 above the mobile breakpoint, where the bar is display: none and the nav is
41
+ // a column beside the content rather than a layer on top of it.
42
+ const overlayHeight = useElementHeight(pillBarRef)
43
+ useEffect(() => {
44
+ onOverlayHeightChange?.(overlayHeight)
45
+ }, [overlayHeight, onOverlayHeightChange])
46
+
37
47
  const getItemAriaLabel = (item: RcSesSideNavItem) =>
38
48
  item.count !== undefined
39
49
  ? t('itemLabel', { label: item.label, count: item.count })
@@ -98,7 +108,7 @@ function RcSesSideNav({
98
108
  </Box>
99
109
  </Box>
100
110
 
101
- <Box sx={{ display: { xs: 'block', md: 'none' } }}>
111
+ <Box ref={pillBarRef} sx={{ display: { xs: 'block', md: 'none' } }}>
102
112
  <SideNavPillList
103
113
  items={items}
104
114
  activeItemId={activeItemId}
@@ -40,6 +40,11 @@ function Sections({ items = ITEMS }: { items?: RcSesSideNavItem[] }) {
40
40
  height: `${SECTION_HEIGHT}px`,
41
41
  borderBottom: '1px dashed #dce0e5',
42
42
  paddingTop: '1rem',
43
+ // Published by the layout: the page header offset plus the mobile
44
+ // bar, which is sticky over the content. Without it a section the
45
+ // page scrolls to by its own means - a #hash deep link, say - lands
46
+ // with its heading behind the bar.
47
+ scrollMarginTop: 'var(--rc-ses-sidenav-scroll-offset, 0px)',
43
48
  }}
44
49
  >
45
50
  <Typography variant='h3' sx={{ fontSize: '1.25rem', fontWeight: 600 }}>
@@ -62,7 +67,7 @@ const meta: Meta<typeof RcSesSideNavLayout> = {
62
67
  docs: {
63
68
  description: {
64
69
  component:
65
- 'RcSesSideNavLayout is the only supported way to use this component - it lays out the sticky nav column (a topic list on desktop, a horizontally scrollable pill bar on mobile) alongside its section children, which is what guarantees the desktop sticky behavior works. By default (no `activeItemId`) it tracks scroll position itself and scrolls the page on click - pass `activeItemId`/`onItemClick` to take full control instead. See `WithScrollSpy` for the default, self-contained behavior; `Main` demonstrates the fully-controlled mode, which is why it wires the state itself. `overflow` decides what happens when there are more topics than fit the screen - see `WithScrollOverflow`.',
70
+ 'RcSesSideNavLayout is the only supported way to use this component - it lays out the sticky nav column (a topic list on desktop, a horizontally scrollable pill bar on mobile) alongside its section children, which is what guarantees the desktop sticky behavior works. By default (no `activeItemId`) it tracks scroll position itself and scrolls the page on click - pass `activeItemId`/`onItemClick` to take full control instead. See `WithScrollSpy` for the default, self-contained behavior; `Main` demonstrates the fully-controlled mode, which is why it wires the state itself. `overflow` decides what happens when there are more topics than fit the screen - see `WithScrollOverflow`. Scrolling to a section on click already clears both the page header (`offset`) and the mobile pill bar; sections scrolled to any other way should set `scrollMarginTop` to `var(--rc-ses-sidenav-scroll-offset)`, which the layout keeps up to date on the element wrapping them.',
66
71
  },
67
72
  },
68
73
  },