Skip to content

armgit / TREK

Public Imported from GitHub
0

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.

21.8 KB
Raw Blame
import { useState } from 'react'
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { TourListItem } from '@trek/shared'
import { buildAssignment, buildDay, buildPlace } from '../../../tests/helpers/factories'
import { paddleBench } from '../../../tests/helpers/paddleCheck'
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
import { useSettingsStore } from '../../store/settingsStore'
import { useTourActivityCompareStore } from '../../store/tourActivityCompareStore'
import TourDetailDialog from './TourDetailDialog'
import { useTripStore } from '../../store/tripStore'
import { tourRepo } from '../../repo/tourRepo'

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') })
vi.mock('better-sqlite3', () => { throw new Error('SQLite imports are forbidden in client tests') })
vi.mock('./bike/BikeWaysCard', () => ({
  BikeWaysView: (props: { route: unknown[] | null; bikeProfile: string | null | undefined; active: boolean }) => (
    <div data-testid="bike-ways-view" data-profile={String(props.bikeProfile)} data-points={props.route?.length ?? 0} data-active={String(props.active)} />
  ),
}))

const place = buildPlace({
  id: 42,
  name: 'Ridge walk',
  lat: 48,
  lng: 11,
  notes: 'Bring water',
  route_geometry: JSON.stringify([
    [48, 11, 500],
    [48, 11.01, 550],
    [48, 11.03, 520],
  ]),
})

const tour: TourListItem = {
  place_id: 42,
  name: 'Ridge walk',
  tour_type: 'hike',
  distance: 999,
  elevation_gain: 999,
  elevation_loss: 999,
  duration: null,
  difficulty: null,
  wanderer_ref: null,
  match_confidence: null,
  max_hiking_difficulty: 2,
  planned: false,
  caution: false,
}

const defaultProps = {
  canEdit: true,
  canAssign: true,
  tour,
  place,
  onClose: vi.fn(),
  onUpdatePlace: vi.fn().mockResolvedValue(undefined),
  onAssignToDay: vi.fn(),
  onRemoveAssignment: vi.fn(),
  onDelete: vi.fn(),
}

beforeEach(() => {
  resetAllStores()
  vi.clearAllMocks()
  seedStore(useSettingsStore, { settings: { distance_unit: 'metric' } })
})

// A repository answer one test stubs never reaches the tests after it.
afterEach(() => {
  vi.restoreAllMocks()
  useTourActivityCompareStore.setState({ comparison: null, mapAvailable: false })
})

describe('TourDetailDialog', () => {
  it('keeps desktop detail non-modal and returns focus to its Tour row on Escape', async () => {
    const opener = document.createElement('button')
    opener.textContent = 'Open Tour'
    document.body.appendChild(opener)
    const onClose = vi.fn()
    function DesktopDetail() {
      const [open, setOpen] = useState(true)
      return open ? <TourDetailDialog {...defaultProps} desktopNonModal desktopFocusReturnTarget={opener}
        onClose={() => { onClose(); setOpen(false) }} /> : null
    }

    const view = render(<DesktopDetail />)
    const close = screen.getByRole('button', { name: 'Close' })
    expect(close).toHaveClass('focus-visible:outline')
    expect(document.querySelector('[aria-modal="true"]')).toBeNull()
    expect(document.querySelector('.trek-modal-backdrop')).toBeNull()
    expect(document.body.style.overflow).toBe('')
    const tab = new KeyboardEvent('keydown', { key: 'Tab', bubbles: true, cancelable: true })
    close.dispatchEvent(tab)
    expect(tab.defaultPrevented).toBe(false)

    fireEvent.keyDown(document, { key: 'Escape' })
    await waitFor(() => expect(screen.queryByText('Ridge walk')).not.toBeInTheDocument())
    expect(onClose).toHaveBeenCalledTimes(1)
    expect(document.activeElement).toBe(opener)
    view.unmount()
    document.body.removeChild(opener)
  })

  it('shows only curated tour content and uses live geometry instead of cached tour metrics', () => {
    render(<TourDetailDialog {...defaultProps} />)

    expect(screen.getByText('Ridge walk')).toBeInTheDocument()
    expect(screen.getByText('Minimum altitude')).toBeInTheDocument()
    expect(screen.getByText('Maximum altitude')).toBeInTheDocument()
    expect(screen.getByText('Ascent')).toBeInTheDocument()
    expect(screen.getByText('Descent')).toBeInTheDocument()
    // The head's pills and the fields below both measure the line as it is now.
    expect(screen.getAllByText('50 m').length).toBeGreaterThan(0)
    expect(screen.getAllByText('30 m').length).toBeGreaterThan(0)
    expect(screen.queryByText('999 m')).not.toBeInTheDocument()
    expect(screen.queryByText('999 km')).not.toBeInTheDocument()
    expect(screen.getByText('Bring water')).toBeInTheDocument()
    expect(screen.queryByText('Opening Hours')).not.toBeInTheDocument()
    expect(screen.queryByText('Participants')).not.toBeInTheDocument()
  })

  it('a bike tour carries its surfaces and ways on the Plan tab, a hike does not', () => {
    const { unmount } = render(<TourDetailDialog {...defaultProps} />)
    expect(screen.queryByTestId('bike-ways-view')).not.toBeInTheDocument()
    unmount()
    render(<TourDetailDialog {...defaultProps} tour={{ ...tour, tour_type: 'bike', bike_profile: 'road' }} />)
    const card = screen.getByTestId('bike-ways-view')
    expect(card).toHaveAttribute('data-profile', 'road')
    expect(card).toHaveAttribute('data-points', '3')
    expect(card).toHaveAttribute('data-active', 'true')
  })

  it('RS-01: shows Tour description and opens the classified HTTPS information link without fetching it', () => {
    const fetchSpy = vi.spyOn(globalThis, 'fetch')
    const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null)
    render(
      <TourDetailDialog
        {...defaultProps}
        tour={{ ...tour, description: 'Ridge above the lake', website: 'https://www.komoot.com/tour/42' }}
        place={{ ...place, description: 'Ridge above the lake', website: 'https://www.komoot.com/tour/42' }}
      />
    )

    expect(screen.getByText('Ridge above the lake')).toBeInTheDocument()
    // The footer names the provider; the domain rides along in the tooltip.
    const website = screen.getByRole('button', { name: 'Website: Komoot' })
    expect(website).toHaveTextContent('Komoot')
    fireEvent.click(website)
    expect(openSpy).toHaveBeenCalledWith('https://www.komoot.com/tour/42', '_blank', 'noopener,noreferrer')
    expect(fetchSpy).not.toHaveBeenCalled()
    fetchSpy.mockRestore()
    openSpy.mockRestore()
  })

  it('RS-02: labels calculated walking time and planned total as separate values', () => {
    render(<TourDetailDialog {...defaultProps} tour={{ ...tour, duration: 60, break_additional_minutes: 35, planned_duration_minutes: 125 }} />)

    // One time in the head, its parts named in full behind it; the fields below keep them apart.
    expect(screen.getByLabelText('Walk: 1 h, Breaks: 35 min, Planned (Manual override): 2 h 5 min')).toHaveTextContent(
      '2 h 5 min'
    )
    expect(screen.getByText('Walk')).toBeInTheDocument()
    expect(screen.getByText('Breaks')).toBeInTheDocument()
    expect(screen.getByText('Planned (Manual override)')).toBeInTheDocument()
  })

  it('CW-02: shows a city walk its walking time, its stays and their total, and no breaks left from another type', async () => {
    const walk = {
      ...tour, tour_type: 'walk' as const, max_hiking_difficulty: null, duration: 45, break_additional_minutes: 15,
      station_count: 3, station_stay_minutes: 120, station_stays_unknown: 0,
    }
    vi.spyOn(tourRepo, 'detail').mockResolvedValue({ tour: walk, waypoints: [] })
    const view = render(<TourDetailDialog {...defaultProps} tour={walk} />)

    // 45 min of walking, a museum of 90 min and a cafe of 30 min, as the day row says it too.
    expect(screen.getByLabelText('Walking: 45 min, Stays: 2 h, Planned: 2 h 45 min')).toHaveTextContent('2 h 45 min')
    expect(screen.getByText('Stays')).toBeInTheDocument()
    expect(screen.queryByText('Breaks')).not.toBeInTheDocument()

    view.rerender(<TourDetailDialog {...defaultProps} tour={{ ...walk, station_stay_minutes: 90, station_stays_unknown: 1 }} />)
    expect(screen.getByLabelText('Walking: 45 min, Stays: at least 1 h 30 min, Planned: at least 2 h 15 min'))
      .toHaveTextContent('≥ 2 h 15 min')
    // On a phone's three narrow columns the longer values wrap rather than being cut.
    const stays = screen.getByText('Stays').closest('dt')?.nextElementSibling
    expect(stays).toHaveTextContent('at least 1 h 30 min')
    expect(stays).toHaveClass('break-words')
    expect(stays).not.toHaveClass('truncate')

    view.rerender(<TourDetailDialog {...defaultProps}
      tour={{ ...walk, station_stay_minutes: 90, station_stays_unknown: 1, planned_duration_minutes: 240 }} />)
    expect(screen.getByLabelText(
      'Walking: 45 min, Stays: at least 1 h 30 min, Planned (Manual override): 4 h, Computed: at least 2 h 15 min'
    )).toHaveTextContent('4 h')
    expect(screen.getByText('Computed')).toBeInTheDocument()
    expect(await screen.findByTestId('walk-stations')).toBeInTheDocument()
  })

  it('CW-04: a walk opened from a day it is on keeps that day for its times; opened otherwise, a day can be picked', async () => {
    const walk = { ...tour, tour_type: 'walk' as const, max_hiking_difficulty: null, duration: 20, station_count: 1 }
    vi.spyOn(tourRepo, 'detail').mockResolvedValue({ tour: walk, waypoints: [
      { lat: 48, lng: 11, role: 'start', sequence: 0, key: 'stop-01', name: 'Museum', stay_minutes: 30, opening_hours: 'Mo-Fr 10:00-18:00' },
    ] })
    // 2026-10-19 is a Monday: the museum opens at 10:00.
    const days = [buildDay({ id: 7, date: '2026-10-19' }), buildDay({ id: 8, date: '2026-10-20' })]
    const assignments = {
      '7': [buildAssignment({ id: 9, day_id: 7, place_id: 42, assignment_time: '09:00', place })],
      '8': [buildAssignment({ id: 10, day_id: 8, place_id: 42, assignment_time: '11:00', place })],
    }
    const view = render(<TourDetailDialog {...defaultProps} tour={walk} days={days} assignments={assignments} selectedDayId={7} />)

    expect(screen.getByTestId('walk-day')).toHaveTextContent(/^Day 1, Mon, Oct 19(, 2026)?, start 09:00$/)
    expect(screen.queryByTestId('walk-day-picker')).not.toBeInTheDocument()
    expect(await screen.findByText('Arrival about 09:00, stay until 09:30')).toBeInTheDocument()
    expect(screen.getByTestId('walk-station-conflict'))
      .toHaveTextContent('Museum is closed at 09:00, the stay would last until 09:30; open 10:00 to 18:00')
    expect(screen.getByText('Mark visited')).toBeInTheDocument()

    view.rerender(<TourDetailDialog {...defaultProps} tour={walk} days={days} assignments={assignments} />)
    expect(screen.getByTestId('walk-day-picker')).toHaveTextContent(/^Day 1, Mon, Oct 19(, 2026)?, start 09:00$/)
    expect(screen.queryByText('Mark visited')).not.toBeInTheDocument()
    fireEvent.click(screen.getByTestId('walk-day-picker'))
    fireEvent.click(screen.getByRole('button', { name: /^Day 2, .*start 11:00$/ }))
    expect(await screen.findByText('Arrival about 11:00, stay until 11:30')).toBeInTheDocument()
    expect(screen.queryByTestId('walk-station-conflict')).not.toBeInTheDocument()
    expect(screen.getByText(/Open 10:00 to 18:00/)).toBeInTheDocument()
  })

  it('CW-11: a walk saved with its stops only says once that its way is planned in the planner, and shows no measures yet', async () => {
    const pending = {
      ...tour, tour_type: 'walk' as const, max_hiking_difficulty: null, distance: null, elevation_gain: null, elevation_loss: null,
      station_count: 2, route_pending: true,
    }
    vi.spyOn(tourRepo, 'detail').mockResolvedValue({ tour: pending, waypoints: [] })
    const view = render(<TourDetailDialog {...defaultProps} tour={pending} place={{ ...place, route_geometry: null }} />)

    expect(screen.getByText(
      'Saved with its stops only. The way between them is planned when the walk is opened in the planner and saved.'
    )).toBeInTheDocument()
    expect(screen.queryByText('Distance')).not.toBeInTheDocument()
    expect(await screen.findByTestId('walk-stations')).toBeInTheDocument()

    view.rerender(<TourDetailDialog {...defaultProps} tour={{ ...pending, route_pending: false }} />)
    expect(screen.queryByText(/Saved with its stops only/)).not.toBeInTheDocument()
  })

  it('PAD-01: a paddle tour without heights shows distance, paddling and total side by side in one row', () => {
    render(<TourDetailDialog {...defaultProps} tour={{ ...tour, tour_type: 'kayak', has_waypoints: true, duration: 50 }} />)

    const row = screen.getByText('Distance').closest('dl')
    expect(row).toHaveClass('grid-cols-3')
    expect(row).toContainElement(screen.getByText('Paddling'))
    expect(row).toContainElement(screen.getByText('Planned'))
    expect(screen.queryByText('Ascent')).not.toBeInTheDocument()
  })

  it('RS-01: rejects an unsafe legacy Tour website for rendering', () => {
    render(
      <TourDetailDialog
        {...defaultProps}
        tour={{ ...tour, website: 'javascript:alert(1)' }}
        place={{ ...place, website: 'javascript:alert(1)' }}
      />
    )
    expect(screen.queryByRole('link')).not.toBeInTheDocument()
  })

  it('uses existing assignment callbacks for add and remove actions', () => {
    const { rerender } = render(<TourDetailDialog {...defaultProps} days={[{ id: 7 } as never]} selectedDayId={7} />)
    fireEvent.click(screen.getByRole('button', { name: /Add to Day/i }))
    expect(defaultProps.onAssignToDay).toHaveBeenCalledWith(42, 7)

    rerender(<TourDetailDialog {...defaultProps} days={[{ id: 7 } as never]} selectedDayId={7} assignments={{ '7': [{ id: 9, place }] as never }} />)
    fireEvent.click(screen.getByRole('button', { name: /Remove from Day/i }))
    expect(defaultProps.onRemoveAssignment).toHaveBeenCalledWith(7, 9)
  })

  it('requires place-edit permission for deletion while retaining day-edit assignment removal', () => {
    render(<TourDetailDialog
      {...defaultProps}
      canEdit={false}
      canAssign={true}
      days={[{ id: 7 } as never]}
      selectedDayId={7}
      assignments={{ '7': [{ id: 9, place }] as never }}
    />)

    expect(screen.queryByRole('button', { name: 'Delete' })).not.toBeInTheDocument()
    fireEvent.click(screen.getByRole('button', { name: /Remove from Day/i }))
    expect(defaultProps.onRemoveAssignment).toHaveBeenCalledWith(7, 9)
    expect(defaultProps.onDelete).not.toHaveBeenCalled()
  })

  it('renames through the supplied place update path', async () => {
    render(<TourDetailDialog {...defaultProps} />)
    fireEvent.click(screen.getByRole('button', { name: 'Edit' }))
    const input = screen.getByDisplayValue('Ridge walk')
    fireEvent.change(input, { target: { value: 'New route name' } })
    fireEvent.click(screen.getByRole('button', { name: 'Save' }))
    expect(defaultProps.onUpdatePlace).toHaveBeenCalledWith(42, { name: 'New route name' })
  })

  it('TIME-01-FE-005: an import shows its estimated time apart from a planned one, and an import without heights says it is unknown', () => {
    const imported = { ...tour, has_waypoints: false, origin: 'gpx' as const, distance: 12, elevation_gain: 300, elevation_loss: 500 }
    const view = render(<TourDetailDialog {...defaultProps} tour={imported} />)
    expect(screen.getByLabelText('Estimated time: ≈ 4 h')).toHaveTextContent('≈ 4 h')
    expect(screen.getByText('Estimated time')).toBeInTheDocument()
    view.unmount()
    render(<TourDetailDialog {...defaultProps} tour={{ ...imported, elevation_gain: null, elevation_loss: null }} />)
    expect(screen.getByText('Unknown')).toBeInTheDocument()
  })

  it('RC-03: names a GPX import as such, without a read-only notice in the plan', () => {
    render(<TourDetailDialog {...defaultProps} tour={{ ...tour, has_waypoints: false }} />)

    expect(screen.getByText('GPX import')).toBeInTheDocument()
    expect(screen.queryByText(/view-only/)).not.toBeInTheDocument()
  })

  it('PR1-05B: names the import a tour was planned from while it is still in the trip', () => {
    seedStore(useTripStore, { places: [buildPlace({ id: 7, name: 'Recorded ridge' }), place] })
    render(<TourDetailDialog {...defaultProps} tour={{ ...tour, derived_from_place_id: 7 }} />)

    expect(screen.getByText('Based on Recorded ridge')).toBeInTheDocument()
  })

  it('PR1-05B: says nothing of an origin that is gone from the trip', () => {
    seedStore(useTripStore, { places: [place] })
    render(<TourDetailDialog {...defaultProps} tour={{ ...tour, derived_from_place_id: 7 }} />)

    expect(screen.queryByText(/Based on/)).not.toBeInTheDocument()
  })

  it('SKI-02: names a snowshoe tour by its discipline in its head and on its tile, and a hike by none', () => {
    const { unmount } = render(<TourDetailDialog {...defaultProps} />)
    expect(screen.queryByTestId('tour-detail-ski')).not.toBeInTheDocument()
    expect(screen.queryByTestId('tour-ski-mark')).not.toBeInTheDocument()
    unmount()

    const snowshoe = { ...tour, tour_type: 'ski' as const, max_hiking_difficulty: null, ski_discipline: 'snowshoe' as const }
    render(<TourDetailDialog {...defaultProps} tour={snowshoe} />)
    expect(screen.getByTestId('tour-detail-ski')).toHaveTextContent('Snowshoeing')
    expect(screen.getByRole('img', { name: 'Snowshoeing' })).toBeInTheDocument()
  })

  it('ACT-01: a recording that is the actual track of a tour names that tour in its head', () => {
    seedStore(useTripStore, { places: [buildPlace({ id: 7, name: 'Lake loop' }), place] })
    render(<TourDetailDialog {...defaultProps} tour={{ ...tour, has_waypoints: false, origin: 'gpx', activity_of: 7 }} />)

    expect(screen.getByTestId('tour-detail-track-of')).toHaveTextContent('Actual track of Lake loop')
    expect(screen.getByTestId('tour-detail-track-of').querySelector('svg.lucide-check-check')).not.toBeNull()
  })

  it('ACT-02: an actual track stands beside the plan the head shows, and only the map detail offers to compare it there', async () => {
    const activity = {
      id: 4,
      assignment_id: null,
      day_id: null,
      assigned_at: null,
      track: { place_id: 20, name: 'Watch export', origin: 'gpx' as const, file_name: 'morning.gpx', imported_at: null },
      metrics: {
        distance_km: 3,
        elevation_gain_m: null,
        elevation_loss_m: null,
        started_at: null,
        ended_at: null,
        elapsed_minutes: null,
        point_count: 2,
      },
      geometry: [
        [48, 11],
        [48, 11.03],
      ] as [number, number][],
    }
    vi.spyOn(tourRepo, 'detail').mockResolvedValue({ tour, waypoints: [], activities: [activity] })
    // The planner map is on screen, so the map detail may offer the switch.
    useTourActivityCompareStore.setState({ comparison: null, mapAvailable: true })
    const { unmount } = render(<TourDetailDialog {...defaultProps} desktopNonModal />)

    const distance = await screen.findByTestId('tour-activity-compare-distance')
    // The plan as the head measures it from the line, not the list's stale 999 km.
    expect(distance).toHaveTextContent('2.2 km')
    expect(distance).toHaveTextContent('3 km')
    expect(screen.getByRole('button', { name: /Compare on map/ })).toBeInTheDocument()
    unmount()

    render(<TourDetailDialog {...defaultProps} />)
    await screen.findByTestId('tour-activity-compare-distance')
    expect(screen.queryByRole('button', { name: /Compare on map/ })).not.toBeInTheDocument()
  })

  it('shows the grade on the tile and no second difficulty scale', () => {
    render(<TourDetailDialog {...defaultProps} tour={{ ...tour, difficulty: 'easy', max_hiking_difficulty: 1 }} />)

    expect(screen.getAllByText('T1').length).toBeGreaterThan(0)
    expect(screen.queryByText(/easy/i)).not.toBeInTheDocument()
  })

  it('PCT-001: a paddle tour shows its checklist and the safety row before the wind, a hike neither', () => {
    const { unmount } = render(<TourDetailDialog {...defaultProps} tour={{ ...tour, tour_type: 'kayak', paddle_check: paddleBench() }} />)

    expect(screen.getByText('Checklist')).toBeInTheDocument()
    expect(screen.getByTestId('paddle-check-summary')).toBeInTheDocument()
    const safety = screen.getByRole('button', { name: /Paddling has risks/ })
    expect(safety.compareDocumentPosition(screen.getByTestId('paddle-wind-card'))).toBe(Node.DOCUMENT_POSITION_FOLLOWING)
    unmount()

    render(<TourDetailDialog {...defaultProps} tour={{ ...tour, paddle_check: paddleBench() }} />)
    expect(screen.queryByText('Checklist')).not.toBeInTheDocument()
    expect(screen.queryByTestId('paddle-check-summary')).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: /Paddling has risks/ })).not.toBeInTheDocument()
  })

  it("#2812: offers the whole route in the map apps that follow one, in the tour's own mode", () => {
    const open = vi.spyOn(window, 'open').mockImplementation(() => null)
    render(<TourDetailDialog {...defaultProps} tour={{ ...tour, tour_type: 'bike' }} />)

    fireEvent.click(screen.getByRole('button', { name: 'Open the route in a map app' }))
    const menu = screen.getByRole('menu')
    // Only the apps that follow a whole route: Waze and geo: lead to the start, which Navigation
    // already does, and CoMaps would get the stops between as unrouted pins.
    const names = Array.from(menu.querySelectorAll('[role="menuitem"]')).map(item => item.textContent)
    expect(names).toContain('Google Maps')
    expect(names).not.toContain('CoMaps')
    expect(names).not.toContain('Waze')

    fireEvent.click(screen.getByRole('menuitem', { name: 'Google Maps' }))
    // The ride goes by bike, with the stops along the line between its ends.
    expect(open).toHaveBeenCalledWith(expect.stringContaining('&travelmode=bicycling'), '_blank', 'noopener,noreferrer')
  })

  it('#2812: a paddle tour is not handed to a map app, which would route it by road', () => {
    render(<TourDetailDialog {...defaultProps} tour={{ ...tour, tour_type: 'kayak', paddle_check: paddleBench() }} />)
    expect(screen.queryByRole('button', { name: 'Open the route in a map app' })).not.toBeInTheDocument()
  })
})