fix(tours): keep editor dropdowns inside the sidebar

This commit is contained in:
Luffy
2026-11-27 17:02:21 +08:00
committed by Maurice
parent eaef3c014e
commit 20c8457f18
14 changed files with 393 additions and 89 deletions
@@ -12,7 +12,7 @@ import type { Day } from '../../../types'
import { toggleTourPlacing } from '../../../store/tourPlaceToolStore'
import { publishTourFerrataCrossings } from '../../../store/tourFerrataCrossingStore'
import { TourPlannerRail, TourPlannerToursRail } from './TourPlannerPanels'
import { hikePlannerDefaults } from '../../../../tests/helpers/tourPlannerStub'
import { hikePlannerDefaults, mockTourEditorLayout } from '../../../../tests/helpers/tourPlannerStub'
import { tourRepo } from '../../../repo/tourRepo'
import { useTripStore } from '../../../store/tripStore'
import type { TourStage } from '../stages/tourStages'
@@ -132,6 +132,12 @@ beforeEach(() => {
seedStore(useSettingsStore, { settings: { distance_unit: 'metric' } })
})
function openDifficulty() {
const trigger = screen.getByRole('button', { name: 'Maximum trail difficulty' })
mockTourEditorLayout(trigger.parentElement ?? trigger)
fireEvent.click(trigger)
}
describe('TourPlannerToursRail', () => {
it('MDT-02: a multi-day tour unfolds its stages in the list, a day tour has nothing to unfold', async () => {
vi.spyOn(tourRepo, 'detail').mockResolvedValue({ tour, waypoints: [] })
@@ -702,6 +708,7 @@ describe('TourPlannerRail', () => {
render(<TourPlannerRail planner={controller} />)
expect(screen.getByLabelText('Tour name')).toBeDisabled()
expect(screen.getByTestId('tour-type-select')).toBeDisabled()
expect(screen.getByRole('button', { name: 'Maximum trail difficulty' })).toBeDisabled()
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
expect(screen.getByRole('button', { name: 'Back to Tours' })).toBeDisabled()
@@ -765,7 +772,7 @@ describe('TourPlannerRail', () => {
const controller = planner({ mode: { type: 'new-draft' }, setMaxHikingDifficulty: setDifficulty, acknowledgeAlpine: acknowledge })
const { unmount } = render(<TourPlannerRail planner={controller} />)
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
openDifficulty()
fireEvent.click(screen.getByRole('button', { name: /T4: Alpine hiking/ }))
expect(screen.getByRole('heading', { name: 'Enable alpine routing?' })).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Enable alpine routing' }))
@@ -775,7 +782,7 @@ describe('TourPlannerRail', () => {
// The planner remembers the answer, so a rail that mounts anew does not ask again.
render(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, setMaxHikingDifficulty: setDifficulty, alpineAcknowledged: true })} />)
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
openDifficulty()
fireEvent.click(screen.getByRole('button', { name: /T5: Demanding alpine hiking/ }))
expect(screen.queryByRole('heading', { name: 'Enable alpine routing?' })).not.toBeInTheDocument()
expect(setDifficulty).toHaveBeenLastCalledWith(5)
@@ -785,7 +792,7 @@ describe('TourPlannerRail', () => {
const setDifficulty = vi.fn()
render(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, setMaxHikingDifficulty: setDifficulty })} />)
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
openDifficulty()
fireEvent.click(screen.getByRole('button', { name: /T4: Alpine hiking/ }))
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
expect(setDifficulty).not.toHaveBeenCalled()
@@ -802,7 +809,7 @@ describe('TourPlannerRail', () => {
})} />
}
render(<StatefulDifficultyRail />)
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
openDifficulty()
for (const label of [
'T1: Hiking',
@@ -818,6 +825,22 @@ describe('TourPlannerRail', () => {
expect(screen.getAllByRole('status').some(el => /T3 routes may include exposed/.test(el.textContent ?? ''))).toBe(true)
})
it('dismisses an open tour type list when saving locks the editor', () => {
const controller = planner({ mode: { type: 'new-draft' } })
const { rerender } = render(<TourPlannerRail planner={controller} />)
const trigger = screen.getByTestId('tour-type-select')
mockTourEditorLayout(trigger)
fireEvent.click(trigger)
expect(screen.getByRole('group', { name: 'Tour type' })).toBeInTheDocument()
rerender(<TourPlannerRail planner={{ ...controller, isSaving: true }} />)
expect(trigger).toBeDisabled()
expect(trigger).toHaveAttribute('aria-expanded', 'false')
expect(screen.queryByTestId('tour-type-option-hike')).not.toBeInTheDocument()
rerender(<TourPlannerRail planner={controller} />)
expect(trigger).toHaveAttribute('aria-expanded', 'false')
})
it('TOUR-PLANNER-RAIL-009: neutral shows only the Plan new entry and new-draft guidance hides after the first waypoint', () => {
const controller = planner({ mode: { type: 'neutral' } })
const { rerender } = render(<TourPlannerRail planner={controller} />)
@@ -12,6 +12,7 @@ import { useRailHeadProps } from './railHead'
import EmptyState from '../../shared/EmptyState'
import { useToast } from '../../shared/Toast'
import { Tooltip } from '../../shared/Tooltip'
import { PopoverBoundary } from '../../shared/useAnchoredPopover'
import { BOX } from '../../Planner/bookings/bookingParts'
import { BarButton, SoftPill } from '../../Planner/planParts'
import TourListRow from '../TourListRow'
@@ -335,6 +336,7 @@ export function TourPlannerRail({ planner,
const { t } = useTranslation()
const [confirmDiscard, setConfirmDiscard] = useState(false)
const [pendingDifficulty, setPendingDifficulty] = useState<1 | 2 | 3 | 4 | 5 | 6 | null>(null)
const editorScrollRef = useRef<HTMLDivElement>(null)
const isSaving = planner.isSaving
// Nothing in the editor changes while the viewer may not edit or a save is in flight.
const locked = !canEdit || isSaving
@@ -389,44 +391,46 @@ export function TourPlannerRail({ planner,
</BarButton>
</div>
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-3 py-3.5">
<TourRemoteChangeNotice planner={planner} />
<WalkImportDraftNotice planner={planner} />
<WalkRoutePendingNotice planner={planner} />
<TourNameField planner={planner} locked={locked} />
<div ref={editorScrollRef} data-testid="tour-planner-editor-scroll" className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-3 py-3.5">
<PopoverBoundary value={editorScrollRef}>
<TourRemoteChangeNotice planner={planner} />
<WalkImportDraftNotice planner={planner} />
<WalkRoutePendingNotice planner={planner} />
<TourNameField planner={planner} locked={locked} />
<TourTypeFields planner={planner} locked={locked} />
<TourTypeFields planner={planner} locked={locked} />
<TourStageModeField planner={planner} locked={locked} />
<TourStageModeField planner={planner} locked={locked} />
{recordedTrack?.available && <RecordedTrackCard recordedTrack={recordedTrack} disabled={isSaving} />}
{recordedTrack?.available && <RecordedTrackCard recordedTrack={recordedTrack} disabled={isSaving} />}
<UnreachableNotice planner={planner} />
<WalkFerryNotice planner={planner} />
<UnreachableNotice planner={planner} />
<WalkFerryNotice planner={planner} />
<TourStageLossNotice planner={planner} />
<TourStageDayNotice planner={planner} />
<TourStageLossNotice planner={planner} />
<TourStageDayNotice planner={planner} />
<TourWaypointList planner={planner} canEdit={canEdit} isSaving={isSaving} tourPlaceIds={tourPlaceIds} />
<TourWaypointList planner={planner} canEdit={canEdit} isSaving={isSaving} tourPlaceIds={tourPlaceIds} />
<BikeWaysCard planner={planner} />
<BikeWaysCard planner={planner} />
<RunWaysCard planner={planner} />
<RunWaysCard planner={planner} />
<HorseRoutesCard planner={planner} />
<HorseRoutesCard planner={planner} />
<SkiPlannerSummary planner={planner} />
<SkiPlannerSummary planner={planner} />
{planner.tourType === 'hike' && (
<HikeWaysCard tripId={planner.tripId} route={planner.route} routeCurrent={planner.routeCurrent}
routingLimit={planner.maxHikingDifficulty} />
)}
{planner.tourType === 'hike' && (
<HikeWaysCard tripId={planner.tripId} route={planner.route} routeCurrent={planner.routeCurrent}
routingLimit={planner.maxHikingDifficulty} />
)}
<TourPoiSearchCard planner={planner} />
<TourPoiSearchCard planner={planner} />
<PaddleEditorCards planner={planner} locked={locked} checklist={paddleChecklist} />
<PaddleEditorCards planner={planner} locked={locked} checklist={paddleChecklist} />
<TourDetailsSection planner={planner} locked={locked} onDifficultyChange={changeDifficulty} />
<TourDetailsSection planner={planner} locked={locked} onDifficultyChange={changeDifficulty} />
</PopoverBoundary>
</div>
<TourEditorRailFooter planner={planner} canEdit={canEdit} locked={locked} isSavedEdit={isSavedEdit} onDiscard={requestClose} />
@@ -111,7 +111,7 @@ function BikeProfileField({ planner }: { planner: TourPlannerController }) {
* discipline and, for cross-country, the technique, then what the piste router
* is asked for. A short line says how its legs are laid.
*/
function SkiFields({ planner }: { planner: TourPlannerController }) {
function SkiFields({ planner, locked }: TourTypeFieldsProps) {
const { t } = useTranslation();
const { choice } = planner.ski;
return (
@@ -121,7 +121,7 @@ function SkiFields({ planner }: { planner: TourPlannerController }) {
{t('tours.ski.plannedHint')}
</span>
{choice.discipline !== null && (
<SkiRouteOptions discipline={choice.discipline} options={choice.options} onChange={planner.ski.setOption} />
<SkiRouteOptions discipline={choice.discipline} options={choice.options} onChange={planner.ski.setOption} locked={locked} />
)}
</div>
);
@@ -157,7 +157,7 @@ export function TourTypeFields({ planner, locked }: TourTypeFieldsProps) {
{planner.isRun && <RunFields planner={planner} locked={locked} />}
{planner.isSki && <SkiFields planner={planner} />}
{planner.isSki && <SkiFields planner={planner} locked={locked} />}
{planner.isPaddle && (
<div data-testid="tour-planner-paddle-fields" className="flex min-w-0 flex-col gap-3">
@@ -47,7 +47,10 @@ export function TourTypeSelect<T extends ImportableTourType = PlannableTourType>
const { t } = useTranslation();
const valueId = useId();
const offered: readonly ImportableTourType[] = types ?? PLANNER_TOUR_TYPES;
const list = usePopoverList(offered.indexOf(value), { estimatedHeight: 50 * offered.length + 20 });
const list = usePopoverList(offered.indexOf(value), {
estimatedHeight: 50 * offered.length + 20,
disabled,
});
const { open, toggle, triggerRef, listId } = list;
const label = t('tours.planner.tourType');
const pick = (type: T) => {
@@ -47,6 +47,7 @@ interface SkiRouteOptionsProps {
discipline: SkiDiscipline;
options: SkiRouteOptionsInput | null | undefined;
onChange: (patch: Partial<SkiRouteOptionsInput>) => void;
locked?: boolean;
}
/** One switch of the piste router on its own row, its label beside it. */
@@ -102,7 +103,7 @@ function LiftClasses({ avoided, onChange }: { avoided: SkiLiftClass[]; onChange:
* weigh most for a downhill skier, groomed and lit trails for cross-country,
* the lifts for anyone who rides them. Every change plans the tour again.
*/
export function SkiRouteOptions({ discipline, options, onChange }: SkiRouteOptionsProps) {
export function SkiRouteOptions({ discipline, options, onChange, locked }: SkiRouteOptionsProps) {
const { t } = useTranslation();
const read = new Set(skiOptionsReadBy(discipline));
const current: Options = { ...DEFAULT_SKI_ROUTE_OPTIONS, ...options };
@@ -119,6 +120,7 @@ export function SkiRouteOptions({ discipline, options, onChange }: SkiRouteOptio
<CustomSelect
id="tour-planner-ski-difficulty"
ariaLabel={t('tours.ski.options.maxDifficulty')}
disabled={locked}
size="sm"
value={current.max_difficulty}
onChange={(value) => onChange({ max_difficulty: value as SkiDifficulty })}
@@ -11,7 +11,7 @@ import { analyzeRouteGeometry } from '../../utils/routeGeometry'
import TourListRow from './TourListRow'
import { TourPlannerRail, TourPlannerToursRail } from './planner/TourPlannerPanels'
import type { TourPlannerController } from './planner/useTourPlanner'
import { hikePlannerDefaults } from '../../../tests/helpers/tourPlannerStub'
import { hikePlannerDefaults, mockTourEditorLayout } from '../../../tests/helpers/tourPlannerStub'
vi.mock('../../../../server/src/config', () => { throw new Error('Config initialization is forbidden in client tests') })
vi.mock('../../../../server/src/db/database', () => { throw new Error('Legacy database imports are forbidden in client tests') })
@@ -151,7 +151,9 @@ describe('Tours English and German copy', () => {
}
rerender(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, status: 'ready', error: 'save' })} />)
expect(screen.getByLabelText(toursText(de, 'tours.planner.status.saveFailed'))).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: toursText(de, 'tours.planner.maxDifficulty') }))
const difficulty = screen.getByRole('button', { name: toursText(de, 'tours.planner.maxDifficulty') })
mockTourEditorLayout(difficulty.parentElement ?? difficulty)
fireEvent.click(difficulty)
fireEvent.click(screen.getByRole('button', { name: toursText(de, 'tours.planner.difficulty.t4') }))
expect(screen.getByRole('heading', { name: toursText(de, 'tours.planner.difficulty.alpineTitle') })).toBeInTheDocument()
expect(screen.getByText(toursText(de, 'tours.planner.difficulty.alpineBody'))).toBeInTheDocument()
@@ -187,4 +189,4 @@ describe('Tours English and German copy', () => {
expect(await screen.findByText(toursText(fr, 'tours.planner.neutralTitle'))).toBeInTheDocument()
assertNoRawToursKeys()
})
})
})
@@ -8,7 +8,7 @@ import type { TourPlannerController } from '../Tours/planner/useTourPlanner'
import ToursSidebar from '../Tours/ToursSidebar'
import type { Day } from '../../types'
import CustomSelect from './CustomSelect'
import { hikePlannerDefaults } from '../../../tests/helpers/tourPlannerStub'
import { hikePlannerDefaults, mockTourEditorLayout } from '../../../tests/helpers/tourPlannerStub'
vi.mock('../../repo/tourRepo', () => ({ tourRepo: {} }))
vi.mock('../../store/settingsStore', () => ({
@@ -57,6 +57,7 @@ describe('CustomSelect consumer contracts', () => {
expect(screen.getByLabelText('Maximum trail difficulty')).toBe(trigger)
expect(trigger).toHaveAttribute('id', 'tour-planner-difficulty')
expect(document.querySelectorAll('[id="tour-planner-difficulty"]')).toHaveLength(1)
mockTourEditorLayout(trigger.parentElement ?? trigger)
await user.click(trigger)
const menu = within(document.getElementById(trigger.getAttribute('aria-controls')!)!)
for (const difficulty of [1, 2, 3, 4, 5, 6]) {
@@ -132,4 +133,4 @@ describe('CustomSelect consumer contracts', () => {
await user.click(screen.getByRole('button', { name: /^Planned\s*1$/ }))
expect(setFilter).toHaveBeenLastCalledWith('planned')
})
})
})
+15 -11
View File
@@ -1,9 +1,10 @@
import React, { useState, useRef, useEffect, useId } from 'react'
import { createPortal } from 'react-dom'
import { ChevronDown, Check } from 'lucide-react'
import { useAnchoredPosition, scrollAnchorIntoView } from '../../hooks/useAnchoredPosition'
import { scrollAnchorIntoView } from '../../hooks/useAnchoredPosition'
import { useTranslation } from '../../i18n'
import { selectionHaptic } from '../../native/haptics'
import { useAnchoredPopover } from './useAnchoredPopover'
interface SelectOption {
// Callers use both string keys and numeric ids (e.g. day/place ids) as values, and
@@ -85,7 +86,6 @@ export default function CustomSelect({
menuFit = 'anchor',
id,
}: CustomSelectProps) {
const [open, setOpen] = useState(false)
const [search, setSearch] = useState('')
const ref = useRef<HTMLDivElement>(null)
const triggerRef = useRef<HTMLButtonElement>(null)
@@ -97,23 +97,24 @@ export default function CustomSelect({
// Follows the trigger while the sheet scrolls and while the on-screen keyboard
// resizes the viewport, instead of freezing at the rect measured on open (#1999).
const anchored = useAnchoredPosition(ref, open)
const { open, bounded, box: anchored, setOpen } = useAnchoredPopover(ref, { disabled })
const menuOpen = open && (!bounded || !!anchored)
useEffect(() => {
if (!open || !searchable || !searchRef.current) return
if (!menuOpen || !searchable || !searchRef.current) return
if (!keyboardDirection.current) searchRef.current.focus()
// Focusing raises the keyboard on a phone; scroll the trigger up so the list
// it just opened is not left underneath it (#2000).
scrollAnchorIntoView(ref.current)
}, [open, searchable])
}, [menuOpen, searchable])
useEffect(() => {
if (!open || !keyboardDirection.current) return
if (!menuOpen || !keyboardDirection.current) return
const buttons = dropRef.current?.querySelectorAll<HTMLButtonElement>('button')
const direction = keyboardDirection.current
keyboardDirection.current = null
if (buttons?.length) buttons[direction === 'last' ? buttons.length - 1 : 0].focus()
}, [open])
}, [menuOpen])
useEffect(() => {
const handleClick = (e: MouseEvent) => {
@@ -123,7 +124,7 @@ export default function CustomSelect({
}
if (open) document.addEventListener('mousedown', handleClick)
return () => document.removeEventListener('mousedown', handleClick)
}, [open])
}, [open, setOpen])
const selected = options.find(o => sameValue(value, o.value))
const filtered = searchable && search
@@ -152,6 +153,8 @@ export default function CustomSelect({
: options
const sm = size === 'sm'
const availableOptionsHeight = (anchored?.maxHeight ?? 220) - (searchable ? 38 : 0)
const optionsHeight = bounded ? Math.max(0, availableOptionsHeight - 2) : Math.max(96, availableOptionsHeight)
const closeMenu = () => {
setOpen(false)
@@ -223,7 +226,7 @@ export default function CustomSelect({
</button>
{/* Dropdown */}
{open && createPortal(
{menuOpen && createPortal(
<div ref={dropRef} id={menuId} role="group" aria-label={ariaLabel || selected?.label || placeholder || undefined} onKeyDown={handleKeyDown} style={{
position: 'fixed',
...(anchored
@@ -233,7 +236,7 @@ export default function CustomSelect({
// Never narrower than the trigger, and never past the right-hand edge of
// the window. The cap is read at render time rather than measured, and
// that is enough: every reason the anchor moved already re-renders this.
...(menuFit === 'content'
...(!bounded && menuFit === 'content'
? {
minWidth: anchored.width,
width: 'max-content',
@@ -251,6 +254,7 @@ export default function CustomSelect({
boxShadow: '0 8px 32px rgba(0,0,0,0.12)',
overflow: 'hidden',
animation: 'trek-menu-enter 200ms cubic-bezier(0.23, 1, 0.32, 1)',
overflowWrap: bounded ? 'anywhere' : undefined,
transformOrigin: anchored?.flipped ? 'bottom center' : 'top center',
willChange: 'transform, opacity',
}}>
@@ -277,7 +281,7 @@ export default function CustomSelect({
{/* Options — capped at whatever the viewport still shows, so a list opened
beside an on-screen keyboard shrinks instead of hiding under it (#2000). */}
<div style={{
maxHeight: Math.min(220, Math.max(96, (anchored?.maxHeight ?? 220) - (searchable ? 38 : 0))),
maxHeight: Math.min(220, optionsHeight),
overflowY: 'auto',
// The panel is portaled to document.body and positioned fixed, so its
// scroll chain runs to the viewport rather than to the sheet it looks
+6 -3
View File
@@ -161,12 +161,15 @@ export function PopoverListPanel({ list, label, className = '', children }: {
className?: string
children: ReactNode
}) {
const { open, box, menuRef, listId, onListKey } = list
const { open, box, bounded, menuRef, listId, onListKey } = list
if (!open || !box) return null
return createPortal(
<div ref={menuRef} id={listId} role="group" aria-label={label} onKeyDown={onListKey}
className={`fixed z-[var(--z-toast)] overflow-y-auto ${className}`}
style={{ ...POPOVER, top: box.top, bottom: box.bottom, left: box.left, maxHeight: box.maxHeight }}>
className={`fixed z-[var(--z-toast)] overflow-y-auto ${bounded ? 'overflow-x-hidden overscroll-contain [overflow-wrap:anywhere] [&>button]:shrink-0' : ''} ${className}`}
style={{
...POPOVER, top: box.top, bottom: box.bottom, left: box.left, width: box.width || undefined, maxHeight: box.maxHeight,
minWidth: bounded ? 0 : undefined,
}}>
{children}
</div>,
document.body,
@@ -0,0 +1,27 @@
import { createContext, use, useCallback, useState, type RefObject } from 'react';
import { useAnchoredPosition } from '../../hooks/useAnchoredPosition';
/** The scrolling content that contains a panel's dropdown triggers. */
export const PopoverBoundary = createContext<RefObject<HTMLElement | null> | null>(null);
export function useAnchoredPopover(anchorRef: RefObject<HTMLElement | null>, {
disabled = false, estimatedHeight, matchWidth = true,
}: {
disabled?: boolean;
estimatedHeight?: number;
matchWidth?: boolean;
}) {
const boundaryRef = use(PopoverBoundary);
const bounded = !!boundaryRef;
const unavailable = bounded && disabled;
const [expanded, setOpen] = useState(false);
if (unavailable && expanded) setOpen(false);
const open = expanded && !unavailable;
const hide = useCallback(() => setOpen(false), []);
const box = useAnchoredPosition(anchorRef, open, {
matchWidth: bounded || matchWidth,
estimatedHeight,
boundary: boundaryRef ? { ref: boundaryRef, onAnchorHidden: hide } : undefined,
});
return { open, box, bounded, setOpen };
}
+16 -13
View File
@@ -1,5 +1,5 @@
import { useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { useAnchoredPosition } from '../../hooks/useAnchoredPosition';
import { useEffect, useId, useLayoutEffect, useRef, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { useAnchoredPopover } from './useAnchoredPopover';
const itemsOf = (list: HTMLElement | null) => Array.from(list?.querySelectorAll('button') ?? []);
@@ -13,38 +13,41 @@ const EDGE = 8;
* it and goes on from the button; a click beside it closes it. The caller draws
* the button and the list and hands `currentIndex`, the choice held now.
*/
export function usePopoverList(currentIndex: number, options: { estimatedHeight?: number } = {}) {
const [open, setOpen] = useState(false);
export function usePopoverList(currentIndex: number, { estimatedHeight = 320, disabled }: {
estimatedHeight?: number;
disabled?: boolean;
} = {}) {
const triggerRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
const startAt = useRef(0);
const listId = useId();
const box = useAnchoredPosition(triggerRef, open, {
const { open, box, bounded, setOpen } = useAnchoredPopover(triggerRef, {
matchWidth: false,
estimatedHeight: options.estimatedHeight ?? 320,
estimatedHeight,
disabled,
});
const listShown = open && !!box;
const toggle = () => {
if (!open) startAt.current = Math.max(0, currentIndex);
setOpen((o) => !o);
setOpen((value) => !value);
};
useEffect(() => {
if (listShown) itemsOf(menuRef.current)[startAt.current]?.focus({ preventScroll: true });
}, [listShown]);
if (listShown) itemsOf(menuRef.current)[startAt.current]?.focus({ preventScroll: !bounded });
}, [listShown, bounded]);
// The list opens from its button's start; one wider than the room beside a button near the
// window's side moves back inside, as far as it must, before it is painted.
useLayoutEffect(() => {
const menu = menuRef.current;
if (!listShown || !menu) return;
if (!listShown || !menu || bounded) return;
menu.style.translate = '';
const rect = menu.getBoundingClientRect();
let shift = Math.min(0, window.innerWidth - EDGE - rect.right);
if (rect.left + shift < EDGE) shift = EDGE - rect.left;
if (shift) menu.style.translate = `${Math.round(shift)}px 0`;
}, [listShown, box]);
}, [listShown, box, bounded]);
useEffect(() => {
if (!open) return;
@@ -66,7 +69,7 @@ export function usePopoverList(currentIndex: number, options: { estimatedHeight?
document.removeEventListener('mousedown', onDown);
document.removeEventListener('keydown', onKey, true);
};
}, [open]);
}, [open, setOpen]);
/** Closes the list after a choice and hands the focus back to the button. */
const close = () => {
@@ -94,5 +97,5 @@ export function usePopoverList(currentIndex: number, options: { estimatedHeight?
items[next]?.focus();
};
return { open, box, toggle, close, onListKey, triggerRef, menuRef, listId };
return { open, box, bounded, toggle, close, onListKey, triggerRef, menuRef, listId };
}
+53 -23
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { useCallback, useEffect, useLayoutEffect, useState } from 'react'
export interface AnchoredBox {
/** Distance from the viewport top, when the panel hangs below the trigger. */
@@ -22,8 +22,38 @@ interface AnchoredOptions {
padding?: number
/** Adopt the trigger's width (selects) instead of measuring only its position. */
matchWidth?: boolean
/** Keep the panel inside a scroll area and dismiss it when the anchor leaves. */
boundary?: {
ref: React.RefObject<HTMLElement | null>
onAnchorHidden: () => void
}
}
function viewportBounds() {
// visualViewport excludes the area covered by an on-screen keyboard.
const viewport = window.visualViewport
const top = viewport?.offsetTop ?? 0
const left = viewport?.offsetLeft ?? 0
return { top, left, bottom: top + (viewport?.height ?? window.innerHeight), right: left + (viewport?.width ?? window.innerWidth) }
}
function anchorLimits(anchor: DOMRect, boundaryRef?: React.RefObject<HTMLElement | null>) {
const viewport = viewportBounds()
const rect = boundaryRef?.current?.getBoundingClientRect()
if (!rect) return { top: viewport.top, bottom: viewport.bottom, left: anchor.left, width: anchor.width, bounded: false }
const left = Math.max(anchor.left, rect.left, viewport.left)
return {
top: Math.max(viewport.top, rect.top),
bottom: Math.min(viewport.bottom, rect.bottom),
left,
width: Math.min(anchor.right, rect.right, viewport.right) - left,
bounded: true,
}
}
/** Below this much room, the list would barely display its own border and padding. */
const MIN_BOUNDED_HEIGHT = 24
/** How much the viewport must shrink before we treat it as an on-screen keyboard. */
const KEYBOARD_THRESHOLD = 120
@@ -47,37 +77,35 @@ const KEYBOARD_THRESHOLD = 120
export function useAnchoredPosition(
anchorRef: React.RefObject<HTMLElement | null>,
open: boolean,
{ estimatedHeight = 220, offset = 4, padding = 8, matchWidth = true }: AnchoredOptions = {},
{ estimatedHeight = 220, offset = 4, padding = 8, matchWidth = true, boundary }: AnchoredOptions = {},
): AnchoredBox | null {
const [box, setBox] = useState<AnchoredBox | null>(null)
// Read in the measure callback so it stays stable across renders.
const optsRef = useRef({ estimatedHeight, offset, padding, matchWidth })
optsRef.current = { estimatedHeight, offset, padding, matchWidth }
const boundaryRef = boundary?.ref
const onAnchorHidden = boundary?.onAnchorHidden
const measure = useCallback(() => {
const el = anchorRef.current
if (!el) return
const { estimatedHeight: wanted, offset: gap, padding: pad, matchWidth: match } = optsRef.current
const r = el.getBoundingClientRect()
// visualViewport is the part still visible next to an open keyboard; its
// offsetTop is how far the browser scrolled the layout viewport up to keep
// the focused field in sight, which shifts where "the bottom" really is.
const vv = typeof window !== 'undefined' ? window.visualViewport : null
const viewTop = typeof vv?.offsetTop === 'number' ? vv.offsetTop : 0
const viewHeight = typeof vv?.height === 'number' ? vv.height : window.innerHeight
const viewBottom = viewTop + viewHeight
const spaceBelow = viewBottom - r.bottom - gap - pad
const spaceAbove = r.top - viewTop - gap - pad
const limits = anchorLimits(r, boundaryRef)
const spaceBelow = limits.bottom - r.bottom - offset - padding
const spaceAbove = r.top - limits.top - offset - padding
// Only flip when below genuinely cannot hold the panel and above is roomier,
// which keeps the familiar downward direction in the ordinary case.
const flipped = spaceBelow < Math.min(wanted, 160) && spaceAbove > spaceBelow
const maxHeight = Math.max(96, Math.floor(flipped ? spaceAbove : spaceBelow))
const flipped = spaceBelow < Math.min(estimatedHeight, 160) && spaceAbove > spaceBelow
const availableHeight = Math.floor(flipped ? spaceAbove : spaceBelow)
if (limits.bounded && (r.bottom <= limits.top || r.top >= limits.bottom || limits.width <= 0 || availableHeight < MIN_BOUNDED_HEIGHT)) {
setBox(null)
onAnchorHidden?.()
return
}
const maxHeight = limits.bounded ? availableHeight : Math.max(96, availableHeight)
const { left } = limits
const width = matchWidth ? limits.width : 0
const next: AnchoredBox = flipped
? { bottom: Math.round(window.innerHeight - r.top + gap), left: r.left, width: r.width, maxHeight, flipped }
: { top: Math.round(r.bottom + gap), left: r.left, width: r.width, maxHeight, flipped }
if (!match) next.width = 0
? { bottom: Math.round(window.innerHeight - r.top + offset), left, width, maxHeight, flipped }
: { top: Math.round(r.bottom + offset), left, width, maxHeight, flipped }
setBox(prev =>
prev
@@ -87,7 +115,7 @@ export function useAnchoredPosition(
? prev
: next,
)
}, [anchorRef])
}, [anchorRef, boundaryRef, estimatedHeight, matchWidth, offset, onAnchorHidden, padding])
// Measure before paint so the panel never shows up at a stale spot first.
useLayoutEffect(() => {
@@ -110,6 +138,8 @@ export function useAnchoredPosition(
// The trigger can change size on its own (a select whose label grows).
const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null
if (el && ro) ro.observe(el)
const boundaryEl = boundaryRef?.current
if (boundaryEl && ro) ro.observe(boundaryEl)
return () => {
window.removeEventListener('scroll', measure, true)
window.removeEventListener('resize', measure)
@@ -117,7 +147,7 @@ export function useAnchoredPosition(
vv?.removeEventListener('scroll', measure)
ro?.disconnect()
}
}, [open, measure, anchorRef])
}, [open, measure, anchorRef, boundaryRef])
return box
}