diff --git a/client/e2e/tour-type-popover.spec.ts b/client/e2e/tour-type-popover.spec.ts new file mode 100644 index 000000000..901c3cdcd --- /dev/null +++ b/client/e2e/tour-type-popover.spec.ts @@ -0,0 +1,194 @@ +import { devices, expect, test, type Locator, type Page } from '@playwright/test' +import { encodePolyline6 } from '@trek/shared' + +async function createTourTrip(page: Page): Promise { + const trip = await page.request.post('/api/trips', { + data: { title: 'Tour type picker', start_date: '2099-06-01', end_date: '2099-06-05' }, + }) + await expect(trip).toBeOK() + const { trip: { id } } = await trip.json() + await expect(await page.request.put(`/api/trips/${id}/addons/tours`, { data: { enabled: true } })).toBeOK() + return id +} + +async function expectInside(element: Locator, boundary: Locator) { + await expect.poll(async () => { + const target = await element.boundingBox() + const rail = await boundary.boundingBox() + return !!target && !!rail && target.x >= rail.x - 1 && target.y >= rail.y - 1 && + target.x + target.width <= rail.x + rail.width + 1 && target.y + target.height <= rail.y + rail.height + 1 + }).toBe(true) +} + +function editorFields(page: Page) { + const trigger = page.getByTestId('tour-type-select') + const scrollArea = page.getByTestId('tour-planner-editor-scroll') + return { trigger, scrollArea, menu: page.getByRole('group', { name: 'Tour type', exact: true }) } +} + +test('Tour type follows and fits inside the narrow editor rail', async ({ page }) => { + await page.setViewportSize({ width: 1024, height: 480 }) + const tripId = await createTourTrip(page) + await page.goto(`/trips/${tripId}?tab=tour-planner`) + await page.getByRole('button', { name: 'Plan new tour' }).click() + await expect(page.getByTestId('tour-planner-empty-state')).toBeAttached() + + const grip = page.locator('[data-resize="left"]') + for (let step = 0; step < 8; step++) await grip.press('ArrowLeft') + const { trigger, scrollArea, menu } = editorFields(page) + await trigger.scrollIntoViewIfNeeded() + await expectInside(trigger, scrollArea) + await trigger.click() + await expectInside(menu, scrollArea) + await expect.poll(() => menu.evaluate(el => el.scrollHeight > el.clientHeight)).toBe(true) + + async function anchorGap() { + return menu.evaluate((el) => { + const anchor = document.querySelector('[data-testid="tour-type-select"]')!.getBoundingClientRect() + const panel = el.getBoundingClientRect() + return Math.round(Math.max(panel.top - anchor.bottom, anchor.top - panel.bottom)) + }) + } + await expect.poll(anchorGap).toBe(4) + const start = await scrollArea.evaluate(el => el.scrollTop) + await scrollArea.evaluate(el => el.scrollBy(0, 20)) + await expect.poll(() => scrollArea.evaluate(el => el.scrollTop)).toBeGreaterThan(start) + await expect.poll(anchorGap).toBe(4) + await expectInside(menu, scrollArea) + await scrollArea.evaluate((el, top) => { el.scrollTop = top }, start) + await expect.poll(anchorGap).toBe(4) + + await page.keyboard.press('Escape') + await expect(trigger).toBeFocused() + await expect(menu).toHaveCount(0) + + await trigger.click() + await scrollArea.evaluate(el => el.scrollBy(0, 180)) + await expect(trigger).toHaveAttribute('aria-expanded', 'false') + await expect(menu).toHaveCount(0) + await scrollArea.evaluate(el => { el.scrollTop = 0 }) + await expect(menu).toHaveCount(0) + + await trigger.click() + const ski = menu.getByTestId('tour-type-option-ski') + await page.keyboard.press('End') + await expect(ski).toBeInViewport() + await expect(ski).toBeFocused() + await page.keyboard.press('Enter') + await expect(trigger).toContainText('Ski & winter') + await expect(menu).toHaveCount(0) + await page.getByRole('button', { name: 'Alpine', exact: true }).click() + const hardest = page.getByRole('button', { name: 'Hardest runs', exact: true }) + const hardestMenu = page.getByRole('group', { name: 'Hardest runs', exact: true }) + await hardest.click() + await expectInside(hardestMenu, scrollArea) + await hardestMenu.getByRole('button', { name: 'Easy', exact: true }).click() + await expect(hardest).toContainText('Easy') + await expect(hardestMenu).toHaveCount(0) +}) + +test('the saved hike difficulty dropdown fits above the field and keeps alpine confirmation', async ({ page }) => { + await page.setViewportSize({ width: 1024, height: 520 }) + const tripId = await createTourTrip(page) + const saved = await page.request.post(`/api/trips/${tripId}/tours`, { + data: { + name: 'Saved ridge walk', tour_type: 'hike', max_hiking_difficulty: 2, + route_geometry: [[48.1, 11.1, 500], [48.11, 11.11, 550]], + waypoints: [ + { lat: 48.1, lng: 11.1, role: 'start', sequence: 0 }, + { lat: 48.11, lng: 11.11, role: 'end', sequence: 1 }, + ], + }, + }) + await expect(saved).toBeOK() + const { tour: { place_id } } = await saved.json() + const detailUrl = `**/api/trips/${tripId}/tours/${place_id}` + const detailGate = Promise.withResolvers() + await page.route(detailUrl, async route => { await detailGate.promise; await route.continue() }, { times: 1 }) + const shape = encodePolyline6([{ lat: 48.1, lon: 11.1 }, { lat: 48.11, lon: 11.11 }]) + await page.route('**/api/routing/valhalla/route', route => route.fulfill({ + json: { trip: { legs: [{ shape, summary: { length: 1.4, time: 1200 } }] } }, + })) + await page.goto(`/trips/${tripId}?tab=tour-planner`) + const detailRequested = page.waitForRequest(detailUrl) + await page.getByRole('option', { name: /Saved ridge walk/ }).click() + await detailRequested + + const { trigger, menu, scrollArea } = editorFields(page) + try { + await expect(trigger).toHaveCount(0) + await expect(menu).toHaveCount(0) + } finally { + detailGate.resolve() + } + await expect(page.getByLabel('Tour name')).toHaveValue('Saved ridge walk') + await trigger.click() + await expectInside(menu, scrollArea) + await page.keyboard.press('Escape') + + const difficulty = page.getByRole('button', { name: 'Maximum trail difficulty', exact: true }) + const difficultyMenu = page.getByRole('group', { name: 'Maximum trail difficulty', exact: true }) + await difficulty.scrollIntoViewIfNeeded() + await difficulty.click() + await expectInside(difficultyMenu, scrollArea) + await expect(difficultyMenu).toHaveCSS('transform-origin', /px [1-9][0-9.]*px$/) + await page.keyboard.press('Escape') + await expect(difficulty).toBeFocused() + await expect(difficultyMenu).toHaveCount(0) + await difficulty.click() + await scrollArea.evaluate(el => { el.scrollTop = 0 }) + await expect(difficulty).toHaveAttribute('aria-expanded', 'false') + await expect(difficultyMenu).toHaveCount(0) + + await difficulty.click() + await difficultyMenu.getByRole('button', { name: 'T3: Demanding mountain hiking' }).click() + await expect(difficulty).toContainText('T3:') + await difficulty.click() + await difficultyMenu.getByRole('button', { name: 'T4: Alpine hiking' }).click() + await expect(page.getByRole('heading', { name: 'Enable alpine routing?' })).toBeVisible() + await page.getByRole('button', { name: 'Cancel' }).click() + await expect(difficulty).toContainText('T3:') + + const categories = page.getByTestId('tour-poi-categories') + await categories.click() + await expectInside(page.getByRole('group', { name: 'What to look for', exact: true }), scrollArea) +}) + +test('the tour editor dropdowns fit in the native tablet layout', async ({ playwright, baseURL, storageState }) => { + const browser = await playwright.webkit.launch() + try { + const page = await browser.newPage({ ...devices['iPad Pro 11'], viewport: { width: 680, height: 620 }, baseURL, storageState }) + page.setDefaultTimeout(10_000) + // The browser supplies the WebKit viewport and touch input. This flag selects the app shell. + await page.addInitScript(() => Object.assign(window, { CapacitorCustomPlatform: { name: 'ios' } })) + const tripId = await createTourTrip(page) + await page.goto(`/trips/${tripId}?tab=tour-planner`) + await page.getByRole('tab', { name: 'Plan a tour', exact: true }).tap() + await page.getByRole('button', { name: 'Plan new tour' }).tap() + const { trigger, menu, scrollArea } = editorFields(page) + await trigger.tap() + await expectInside(menu, scrollArea) + await scrollArea.evaluate(el => el.scrollBy(0, 160)) + await expect(trigger).toHaveAttribute('aria-expanded', 'false') + + const difficulty = page.getByRole('button', { name: 'Maximum trail difficulty', exact: true }) + const difficultyMenu = page.getByRole('group', { name: 'Maximum trail difficulty', exact: true }) + await difficulty.tap() + await expectInside(difficultyMenu, scrollArea) + await difficultyMenu.getByRole('button', { name: 'T1: Hiking' }).tap() + await expect(difficulty).toContainText('T1:') + await expect(difficultyMenu).toHaveCount(0) + + await trigger.tap() + await menu.getByTestId('tour-type-option-ski').tap() + await page.getByRole('button', { name: 'Alpine', exact: true }).tap() + const hardest = page.getByRole('button', { name: 'Hardest runs', exact: true }) + const hardestMenu = page.getByRole('group', { name: 'Hardest runs', exact: true }) + await hardest.tap() + await expectInside(hardestMenu, scrollArea) + await hardestMenu.getByRole('button', { name: 'Easy', exact: true }).tap() + await expect(hardest).toContainText('Easy') + } finally { + await browser.close() + } +}) diff --git a/client/src/components/Tours/planner/TourPlannerPanels.test.tsx b/client/src/components/Tours/planner/TourPlannerPanels.test.tsx index 14e8a4525..61e371dad 100644 --- a/client/src/components/Tours/planner/TourPlannerPanels.test.tsx +++ b/client/src/components/Tours/planner/TourPlannerPanels.test.tsx @@ -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() 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() - 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() - 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() - 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() - 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() + const trigger = screen.getByTestId('tour-type-select') + mockTourEditorLayout(trigger) + fireEvent.click(trigger) + expect(screen.getByRole('group', { name: 'Tour type' })).toBeInTheDocument() + + rerender() + expect(trigger).toBeDisabled() + expect(trigger).toHaveAttribute('aria-expanded', 'false') + expect(screen.queryByTestId('tour-type-option-hike')).not.toBeInTheDocument() + rerender() + 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() diff --git a/client/src/components/Tours/planner/TourPlannerPanels.tsx b/client/src/components/Tours/planner/TourPlannerPanels.tsx index b2a33b0e4..931794a6a 100644 --- a/client/src/components/Tours/planner/TourPlannerPanels.tsx +++ b/client/src/components/Tours/planner/TourPlannerPanels.tsx @@ -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(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, -
- - - - +
+ + + + + - + - + - {recordedTrack?.available && } + {recordedTrack?.available && } - - + + - - + + - + - + - + - + - + - {planner.tourType === 'hike' && ( - - )} + {planner.tourType === 'hike' && ( + + )} - + - + - + +
diff --git a/client/src/components/Tours/planner/TourTypeFields.tsx b/client/src/components/Tours/planner/TourTypeFields.tsx index c6e530d7c..affc7fadc 100644 --- a/client/src/components/Tours/planner/TourTypeFields.tsx +++ b/client/src/components/Tours/planner/TourTypeFields.tsx @@ -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')} {choice.discipline !== null && ( - + )}
); @@ -157,7 +157,7 @@ export function TourTypeFields({ planner, locked }: TourTypeFieldsProps) { {planner.isRun && } - {planner.isSki && } + {planner.isSki && } {planner.isPaddle && (
diff --git a/client/src/components/Tours/planner/TourTypeSelect.tsx b/client/src/components/Tours/planner/TourTypeSelect.tsx index f4add21c7..3df3542a4 100644 --- a/client/src/components/Tours/planner/TourTypeSelect.tsx +++ b/client/src/components/Tours/planner/TourTypeSelect.tsx @@ -47,7 +47,10 @@ export function TourTypeSelect 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) => { diff --git a/client/src/components/Tours/ski/SkiRouteOptions.tsx b/client/src/components/Tours/ski/SkiRouteOptions.tsx index 9230e130e..4a53944da 100644 --- a/client/src/components/Tours/ski/SkiRouteOptions.tsx +++ b/client/src/components/Tours/ski/SkiRouteOptions.tsx @@ -47,6 +47,7 @@ interface SkiRouteOptionsProps { discipline: SkiDiscipline; options: SkiRouteOptionsInput | null | undefined; onChange: (patch: Partial) => 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 onChange({ max_difficulty: value as SkiDifficulty })} diff --git a/client/src/components/Tours/toursI18n.test.tsx b/client/src/components/Tours/toursI18n.test.tsx index ad341481b..711732fa5 100644 --- a/client/src/components/Tours/toursI18n.test.tsx +++ b/client/src/components/Tours/toursI18n.test.tsx @@ -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() 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() }) -}) \ No newline at end of file +}) diff --git a/client/src/components/shared/CustomSelect.consumers.test.tsx b/client/src/components/shared/CustomSelect.consumers.test.tsx index d1b7d924e..b6ec523c8 100644 --- a/client/src/components/shared/CustomSelect.consumers.test.tsx +++ b/client/src/components/shared/CustomSelect.consumers.test.tsx @@ -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') }) -}) \ No newline at end of file +}) diff --git a/client/src/components/shared/CustomSelect.tsx b/client/src/components/shared/CustomSelect.tsx index 704ca44f5..d6ad806ff 100644 --- a/client/src/components/shared/CustomSelect.tsx +++ b/client/src/components/shared/CustomSelect.tsx @@ -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(null) const triggerRef = useRef(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('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({ {/* Dropdown */} - {open && createPortal( + {menuOpen && createPortal(
@@ -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). */}
+ 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}
, document.body, diff --git a/client/src/components/shared/useAnchoredPopover.ts b/client/src/components/shared/useAnchoredPopover.ts new file mode 100644 index 000000000..7e9ff7c08 --- /dev/null +++ b/client/src/components/shared/useAnchoredPopover.ts @@ -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 | null>(null); + +export function useAnchoredPopover(anchorRef: RefObject, { + 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 }; +} diff --git a/client/src/components/shared/usePopoverList.ts b/client/src/components/shared/usePopoverList.ts index 5609ad275..b9dbfc9b0 100644 --- a/client/src/components/shared/usePopoverList.ts +++ b/client/src/components/shared/usePopoverList.ts @@ -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(null); const menuRef = useRef(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 }; } diff --git a/client/src/hooks/useAnchoredPosition.ts b/client/src/hooks/useAnchoredPosition.ts index 20fcb4720..e711f3d8b 100644 --- a/client/src/hooks/useAnchoredPosition.ts +++ b/client/src/hooks/useAnchoredPosition.ts @@ -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 + 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) { + 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, 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(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 } diff --git a/client/tests/helpers/tourPlannerStub.ts b/client/tests/helpers/tourPlannerStub.ts index 8e4278232..36bb2e57a 100644 --- a/client/tests/helpers/tourPlannerStub.ts +++ b/client/tests/helpers/tourPlannerStub.ts @@ -1,5 +1,13 @@ import { vi } from 'vitest'; +/** Supply the editor geometry that jsdom cannot measure. */ +export function mockTourEditorLayout(anchor: HTMLElement) { + const scrollArea = anchor.closest('[data-testid="tour-planner-editor-scroll"]'); + if (!scrollArea) throw new Error('Expected a dropdown anchor inside the tour editor'); + vi.spyOn(scrollArea, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 20, 300, 400)); + vi.spyOn(anchor, 'getBoundingClientRect').mockReturnValue(new DOMRect(12, 100, 276, 40)); +} + /** * What a stubbed tour planner needs beyond the fields a test sets: a hike, no * boat, no loop and the route tools as spies. Spread first, so a test's own