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
@@ -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 };
}