Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions frontend/common/hooks/__tests__/useBreakpoint.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import {
BREAKPOINT_QUERIES,
matchesBreakpoint,
} from 'common/hooks/useBreakpoint'

// jest runs in node, so stand in for window.matchMedia.
const setMatchMedia = (
matchMedia?: (query: string) => { matches: boolean },
) => {
;(global as any).window = matchMedia ? { matchMedia } : {}
}

afterEach(() => {
delete (global as any).window
})

describe('matchesBreakpoint', () => {
it('returns true when the breakpoint query matches', () => {
// Given
setMatchMedia((query) => ({
matches: query === BREAKPOINT_QUERIES.isPhone,
}))

// When
const result = matchesBreakpoint('isPhone')

// Then
expect(result).toBe(true)
})

it('returns false when the breakpoint query does not match', () => {
// Given
setMatchMedia(() => ({ matches: false }))

// When
const result = matchesBreakpoint('isPhone')

// Then
expect(result).toBe(false)
})

it('returns false when matchMedia is unavailable', () => {
// Given
setMatchMedia()

// When
const result = matchesBreakpoint('isPhone')

// Then
expect(result).toBe(false)
})

it('returns false without a window', () => {
// Given no window

// When
const result = matchesBreakpoint('isPhone')

// Then
expect(result).toBe(false)
})
})
28 changes: 28 additions & 0 deletions frontend/common/hooks/useBreakpoint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { useEffect, useState } from 'react'

// Bootstrap breakpoints, so components agree with the media queries in SCSS.
// Add a size when a component needs it.
export const BREAKPOINT_QUERIES = {
isPhone: '(max-width: 767.98px)', // below md
}

export type Breakpoint = keyof typeof BREAKPOINT_QUERIES

export const matchesBreakpoint = (breakpoint: Breakpoint): boolean =>
typeof window !== 'undefined' &&
!!window.matchMedia?.(BREAKPOINT_QUERIES[breakpoint]).matches

export const useBreakpoint = (breakpoint: Breakpoint): boolean => {
const [isMatch, setIsMatch] = useState(() => matchesBreakpoint(breakpoint))

useEffect(() => {
const list = window.matchMedia?.(BREAKPOINT_QUERIES[breakpoint])
if (!list) return
const onChange = () => setIsMatch(list.matches)
onChange()
list.addEventListener('change', onChange)
return () => list.removeEventListener('change', onChange)
}, [breakpoint])

return isMatch
}
18 changes: 16 additions & 2 deletions frontend/documentation/components/Popover.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const renderPopover = () => (
)

export const Default: Story = {
render: renderPopover,
render: () => renderPopover(),
}

export const Open: Story = {
Expand All @@ -52,5 +52,19 @@ export const Open: Story = {
await userEvent.click(canvas.getByRole('button', { name: 'Sort by' }))
await screen.findByRole('dialog', { name: 'Sort' })
},
render: renderPopover,
render: () => renderPopover(),
}

// On phones the content opens as a bottom sheet
export const MobileSheet: Story = {
globals: { viewport: { isRotated: false, value: 'mobile1' } },
parameters: {
docs: { story: { height: '420px', inline: false } },
},
play: async ({ canvasElement }: { canvasElement: HTMLElement }) => {
const canvas = within(canvasElement)
await userEvent.click(canvas.getByRole('button', { name: 'Sort by' }))
await screen.findByRole('dialog', { name: 'Sort' })
},
render: () => renderPopover(),
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
.ds-bottom-sheet__overlay {
// Same layer as .ds-popover: above every modal, so it works inside one.
z-index: 200000000001;
display: flex;
align-items: flex-end;
background: oklch(from var(--slate-1000) l c h / 0.5);
animation: ds-bottom-sheet-fade var(--duration-normal) var(--easing-entrance);
}

.ds-bottom-sheet {
width: 100%;
max-height: 80vh;
max-height: 80dvh;
overflow-y: auto;
padding: 8px 12px calc(16px + env(safe-area-inset-bottom));
background: var(--color-surface-default);
border-radius: var(--radius-2xl) var(--radius-2xl) 0 0;
box-shadow: var(--shadow-lg);
animation: ds-bottom-sheet-in var(--duration-slow) var(--easing-entrance);

&__handle {
width: 40px;
height: 4px;
margin: 0 auto 12px;
border-radius: var(--radius-full);
background: var(--color-border-strong);
}

&__title {
padding: 0 12px 8px;
font-size: 13px;
font-weight: 700;
color: var(--color-text-tertiary);
}

@media (prefers-reduced-motion: reduce) {
animation: none;
}
}

@media (prefers-reduced-motion: reduce) {
.ds-bottom-sheet__overlay {
animation: none;
}
}

@keyframes ds-bottom-sheet-in {
from {
transform: translateY(100%);
}
}

@keyframes ds-bottom-sheet-fade {
from {
opacity: 0;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { AnimationEvent, FC, ReactNode, useEffect, useRef } from 'react'
import classNames from 'classnames'
import {
FloatingFocusManager,
FloatingOverlay,
FloatingPortal,
useDismiss,
useFloating,
useInteractions,
useRole,
} from '@floating-ui/react'
import './BottomSheet.scss'

type BottomSheetProps = {
open: boolean
onOpenChange: (open: boolean) => void
title: string
children: ReactNode
className?: string
// Index of the focusable item to focus on open (defaults to the first)
initialFocus?: number
}

const FOCUSABLE =
'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'

const BottomSheet: FC<BottomSheetProps> = ({
children,
className,
initialFocus = 0,
onOpenChange,
open,
title,
}) => {
const { context, refs } = useFloating({ onOpenChange, open })
const { getFloatingProps } = useInteractions([
useDismiss(context, { outsidePressEvent: 'mousedown' }),
useRole(context, { role: 'dialog' }),
])
const sheetRef = useRef<HTMLDivElement | null>(null)

const focusInitialItem = () => {
const items = sheetRef.current?.querySelectorAll<HTMLElement>(FOCUSABLE)
const target = items?.[initialFocus] ?? sheetRef.current
target?.focus({ preventScroll: true })
}

// Focusing during the slide-in makes the browser scroll to the item, which
// cuts the animation short (Safari also jumps). Focus once it has finished.
const onAnimationEnd = (e: AnimationEvent<HTMLDivElement>) => {
if (e.target === e.currentTarget) focusInitialItem()
}

// No animation runs with reduced motion, so focus straight away.
useEffect(() => {
if (!open) return
if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) {
focusInitialItem()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open])

if (!open) return null

return (
<FloatingPortal>
<FloatingOverlay className='ds-bottom-sheet__overlay' lockScroll>
<FloatingFocusManager context={context} initialFocus={-1}>
<div
ref={(node) => {
sheetRef.current = node
refs.setFloating(node)
}}
tabIndex={-1}
className={classNames('ds-bottom-sheet', className)}
aria-label={title}
onAnimationEnd={onAnimationEnd}
{...getFloatingProps()}
>
<div className='ds-bottom-sheet__handle' aria-hidden />
<div className='ds-bottom-sheet__title'>{title}</div>
<div className='ds-bottom-sheet__body'>{children}</div>
</div>
</FloatingFocusManager>
</FloatingOverlay>
</FloatingPortal>
)
}

export default BottomSheet
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './BottomSheet'
56 changes: 37 additions & 19 deletions frontend/web/components/base/Popover/Popover.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import {
useInteractions,
useRole,
} from '@floating-ui/react'
import { useBreakpoint } from 'common/hooks/useBreakpoint'
import BottomSheet from './BottomSheet'
import './Popover.scss'

export type PopoverTriggerProps = Record<string, unknown> & {
Expand Down Expand Up @@ -47,6 +49,7 @@ const Popover: FC<PopoverProps> = ({
}) => {
const [isOpen, setIsOpen] = useState(false)
const close = () => setIsOpen(false)
const asSheet = useBreakpoint('isPhone')

const { context, floatingStyles, refs } = useFloating({
middleware: [
Expand All @@ -73,32 +76,47 @@ const Popover: FC<PopoverProps> = ({
})
const { getFloatingProps, getReferenceProps } = useInteractions([
useClick(context),
useDismiss(context),
useRole(context),
// The sheet handles its own dismiss and role
useDismiss(context, { enabled: !asSheet }),
useRole(context, { enabled: !asSheet }),
])

return (
<>
{renderTrigger(
{ ref: refs.setReference, ...getReferenceProps() },
{
ref: refs.setReference,
...getReferenceProps(),
// useRole is off for the sheet, so state the popup here
...(asSheet && {
'aria-expanded': isOpen,
'aria-haspopup': 'dialog',
}),
},
isOpen,
)}
{isOpen && (
<FloatingPortal>
<FloatingFocusManager context={context} modal={false}>
<div
ref={refs.setFloating}
// Runtime position from Floating UI.
style={floatingStyles}
className={classNames('ds-popover', className)}
data-placement={context.placement}
aria-label={ariaLabel}
{...getFloatingProps()}
>
{typeof children === 'function' ? children(close) : children}
</div>
</FloatingFocusManager>
</FloatingPortal>
{asSheet ? (
<BottomSheet open={isOpen} onOpenChange={setIsOpen} title={ariaLabel}>
{typeof children === 'function' ? children(close) : children}
</BottomSheet>
) : (
isOpen && (
<FloatingPortal>
<FloatingFocusManager context={context} modal={false}>
<div
ref={refs.setFloating}
// Runtime position from Floating UI.
style={floatingStyles}
className={classNames('ds-popover', className)}
data-placement={context.placement}
aria-label={ariaLabel}
{...getFloatingProps()}
>
{typeof children === 'function' ? children(close) : children}
</div>
</FloatingFocusManager>
</FloatingPortal>
)
)}
</>
)
Expand Down
Loading