The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
fix(tours): keep editor dropdowns inside the sidebar
Luffy20c8457f18e1
diff --git a/client/e2e/tour-type-popover.spec.ts b/client/e2e/tour-type-popover.spec.tsnew file mode 100644index 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<number> {+ 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<void>()+ 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.tsxindex 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(<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} />)diff --git a/client/src/components/Tours/planner/TourPlannerPanels.tsx b/client/src/components/Tours/planner/TourPlannerPanels.tsxindex 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<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} />diff --git a/client/src/components/Tours/planner/TourTypeFields.tsx b/client/src/components/Tours/planner/TourTypeFields.tsxindex 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')}</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">diff --git a/client/src/components/Tours/planner/TourTypeSelect.tsx b/client/src/components/Tours/planner/TourTypeSelect.tsxindex 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<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) => {diff --git a/client/src/components/Tours/ski/SkiRouteOptions.tsx b/client/src/components/Tours/ski/SkiRouteOptions.tsxindex 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<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<CustomSelectid="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 })}diff --git a/client/src/components/Tours/toursI18n.test.tsx b/client/src/components/Tours/toursI18n.test.tsxindex 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(<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()})-})\ 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.tsxindex 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.tsxindex 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<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) returnif (!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) returnconst buttons = dropRef.current?.querySelectorAll<HTMLButtonElement>('button')const direction = keyboardDirection.currentkeyboardDirection.current = nullif (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({: optionsconst 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 openedbeside 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 looksdiff --git a/client/src/components/shared/dialogParts.tsx b/client/src/components/shared/dialogParts.tsxindex 39c0ccda4..7920c70d2 100644--- a/client/src/components/shared/dialogParts.tsx+++ b/client/src/components/shared/dialogParts.tsx@@ -161,12 +161,15 @@ export function PopoverListPanel({ list, label, className = '', children }: {className?: stringchildren: ReactNode}) {- const { open, box, menuRef, listId, onListKey } = list+ const { open, box, bounded, menuRef, listId, onListKey } = listif (!open || !box) return nullreturn 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,diff --git a/client/src/components/shared/useAnchoredPopover.ts b/client/src/components/shared/useAnchoredPopover.tsnew file mode 100644index 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<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 };+}diff --git a/client/src/components/shared/usePopoverList.ts b/client/src/components/shared/usePopoverList.tsindex 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<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 };}diff --git a/client/src/hooks/useAnchoredPosition.ts b/client/src/hooks/useAnchoredPosition.tsindex 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<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 = 120export 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?.onAnchorHiddenconst measure = useCallback(() => {const el = anchorRef.currentif (!el) return- const { estimatedHeight: wanted, offset: gap, padding: pad, matchWidth: match } = optsRef.currentconst 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 : 0const 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) : nullif (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.tsindex 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