Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
65 changes: 65 additions & 0 deletions frontend/common/hooks/__tests__/useBreakpoint.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
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 },
) => {
Object.defineProperty(globalThis, 'window', {
configurable: true,
value: matchMedia ? { matchMedia } : {},
})
}

afterEach(() => {
Reflect.deleteProperty(globalThis, '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' } },
Comment thread
talissoncosta marked this conversation as resolved.
Resolved
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(),
}
8 changes: 8 additions & 0 deletions frontend/global.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,3 +99,11 @@ declare global {
}
}
}

// Lets a style object set CSS custom properties, the one inline style the lint
// rule allows (runtime values feeding a SCSS class).
declare module 'react' {
interface CSSProperties {
[key: `--${string}`]: string | number | undefined
}
}
1 change: 0 additions & 1 deletion frontend/web/components/PanelSearch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,6 @@ const PanelSearch = <T,>(props: PanelSearchProps<T>): ReactElement => {
<Row className='mr-3 position-relative'>
<Popover
aria-label='Sort'
className='inline-modal--sm'
renderTrigger={(triggerProps, isActive) => (
<BareButton
{...triggerProps}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
@import '../../../../styles/variables';

.scope-card {
// As wide as the scope switch; the steps below wrap to it.
width: max-content;
Expand Down Expand Up @@ -32,6 +34,25 @@
background: var(--color-surface-hover);
}

// Phones open this in a bottom sheet (useBreakpoint isPhone): fill it,
// and let the sheet scroll instead of the list.
@include media-breakpoint-down(md) {
width: 100%;

&__projects {
max-height: none;
overflow-y: visible;
}

&__project {
min-height: $touch-target-size;
}

.scope-mode-switch__option {
min-height: $touch-target-size;
}
}

@media (prefers-reduced-motion: reduce) {
&__section {
transition: none;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import { RefObject, useLayoutEffect } from 'react'

// The list scrolls in the popover, but in the phone sheet the sheet scrolls.
const getScroller = (el: HTMLElement): HTMLElement | null => {
for (let node: HTMLElement | null = el; node; node = node.parentElement) {
const { overflowY } = getComputedStyle(node)
const canScroll = overflowY === 'auto' || overflowY === 'scroll'
if (canScroll && node.scrollHeight > node.clientHeight) return node
}
return null
}

// rowCount re-runs it once the rows have loaded.
export default function useScrollSelectedIntoView(
listRef: RefObject<HTMLElement | null>,
Expand All @@ -10,7 +20,11 @@ export default function useScrollSelectedIntoView(
const row = list
?.querySelector('input:checked')
?.closest<HTMLElement>('label')
if (!list || !row) return
list.scrollTop = row.offsetTop - (list.clientHeight - row.offsetHeight) / 2
const scroller = list && getScroller(list)
if (!row || !scroller) return
const offset =
row.getBoundingClientRect().top - scroller.getBoundingClientRect().top
scroller.scrollTop +=
offset - (scroller.clientHeight - row.offsetHeight) / 2
}, [listRef, rowCount])
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
.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);

&__header {
padding: 0 0 8px 12px;
}

@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;
}
}
100 changes: 100 additions & 0 deletions frontend/web/components/base/Popover/BottomSheet/BottomSheet.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { AnimationEvent, FC, ReactNode, useId, useRef } from 'react'
import { HeadingText } from 'components/base/typography'
import IconButton from 'components/base/IconButton'
import Icon from 'components/icons/Icon'
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
// 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,
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 titleId = useId()

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()
}

if (!open) return null

// No animation runs with reduced motion, so the focus manager focuses on open
const prefersReducedMotion = !!window.matchMedia?.(
'(prefers-reduced-motion: reduce)',
).matches

return (
<FloatingPortal>
<FloatingOverlay className='ds-bottom-sheet__overlay' lockScroll>
<FloatingFocusManager
context={context}
initialFocus={prefersReducedMotion ? initialFocus : -1}
>
<div
ref={(node) => {
sheetRef.current = node
refs.setFloating(node)
}}
tabIndex={-1}
className='ds-bottom-sheet'
aria-labelledby={titleId}
onAnimationEnd={onAnimationEnd}
{...getFloatingProps()}
>
<div className='ds-bottom-sheet__header d-flex align-items-center justify-content-between gap-2'>
<HeadingText id={titleId} level={2} size='sm'>
{title}
</HeadingText>
<IconButton
aria-label='Close'
variant='ghost'
onClick={() => onOpenChange(false)}
>
<Icon name='close' width={20} />
</IconButton>
</div>
{children}
</div>
</FloatingFocusManager>
</FloatingOverlay>
</FloatingPortal>
)
}

export default BottomSheet
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from './BottomSheet'
4 changes: 4 additions & 0 deletions frontend/web/components/base/Popover/Popover.scss
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
// The entry animation grows from the side nearest the trigger.
.ds-popover {
position: absolute;
top: var(--ds-popover-y, 0);
left: var(--ds-popover-x, 0);
// Same layer as portaled react-select menus (styles.scss): above every modal.
z-index: 200000000001;
min-width: 200px;
max-width: calc(100vw - 16px);
max-height: var(--ds-popover-max-height, none);
overflow-y: auto;
Expand Down
Loading
Loading