mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 16:10:07 +00:00
test(dawarich): the integration that shipped without a suite
Dawarich landed on dev untested, which is why release PR #2273 reads 79.0% on SonarCloud's 80% new-code gate: 1352 of the release's 4610 uncovered units are Dawarich's own. 946 cases across 30 files take the surface to 100% in shared, 99.7 in server and 99.6 in client, and the gate to roughly 85%. What stays uncovered is thirteen type-narrowing guards and defensive fallbacks the only caller cannot reach, each argued in the file beside it rather than forced with a cast. No source, config or coverage threshold is touched.
This commit is contained in:
@@ -0,0 +1,527 @@
|
||||
// FE-DAWARICH-ACCEPT-001 to FE-DAWARICH-ACCEPT-024
|
||||
/**
|
||||
* The review step between a detector's guess and a row in somebody's trip.
|
||||
*
|
||||
* This dialog is the only thing standing between Dawarich's visit detector and
|
||||
* real data, and almost all of its behaviour is invisible until it is wrong:
|
||||
* which fields are prefilled, which of them are sent back, and which are left
|
||||
* out because the user did not actually change them. The server takes the body
|
||||
* at face value (an accidental `name` or `date` in it silently overrides the
|
||||
* recording), so "only what was corrected travels" is the contract worth
|
||||
* pinning, and it is the one a refactor breaks first.
|
||||
*
|
||||
* The rest is the shape of the three targets. `place` needs a trip and offers a
|
||||
* day, `journal` needs a journey and asks for a story, `bucket_list` needs a
|
||||
* matched wish and hides the clock entirely because ticking a wish off uses the
|
||||
* recorded timestamp and nothing else. Each of the three can be in a state
|
||||
* where there is nothing to write to (no trips, no journeys, no matched wish),
|
||||
* and in each of those the confirm button has to be inert rather than sending a
|
||||
* body the server will reject with a 400.
|
||||
*
|
||||
* The seeding is keyed on the stay, not on the target, and one live instance
|
||||
* serves all three rails. That makes two things true at once that are easy to
|
||||
* get wrong together: what the user typed survives a switch from the place rail
|
||||
* to the journal rail, and the trip and day they chose under the place rail
|
||||
* must not travel in the journal body they then confirm.
|
||||
*
|
||||
* Both shells are covered: the phone gets an MSheet with its own footer, the
|
||||
* desktop a Modal, and the fields in between are the same element tree. A
|
||||
* regression that dropped one shell would otherwise only show up on a device.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { fireEvent } from '@testing-library/react'
|
||||
import type { DawarichSuggestion } from '@trek/shared'
|
||||
import { render, screen } from '../../../tests/helpers/render'
|
||||
import DawarichAcceptDialog, { type AcceptTargetOption } from './DawarichAcceptDialog'
|
||||
|
||||
// The one thing the dialog reads about the device. A hoisted flag rather than a
|
||||
// resize: useIsPhone is matchMedia-driven and the global stub always answers false.
|
||||
const phone = vi.hoisted(() => ({ value: false }))
|
||||
vi.mock('../../mobile/useIsPhone', () => ({ useIsPhone: () => phone.value }))
|
||||
|
||||
/**
|
||||
* A stay as the suggestions endpoint hands it over. The offsets are real ones:
|
||||
* `clockOf` slices the local wall clock straight out of the string rather than
|
||||
* converting it, so a fixture in UTC would quietly test a different code path
|
||||
* than the one production sees.
|
||||
*/
|
||||
function stay(over: Partial<DawarichSuggestion> = {}): DawarichSuggestion {
|
||||
return {
|
||||
id: 1,
|
||||
sourceVisitId: '1',
|
||||
tripId: null,
|
||||
tripTitle: null,
|
||||
name: 'Cafe Reichard',
|
||||
lat: 50.94,
|
||||
lng: 6.96,
|
||||
startedAt: '2026-09-10T10:15:00+02:00',
|
||||
endedAt: '2026-09-10T12:40:00+02:00',
|
||||
durationMinutes: 145,
|
||||
localDate: '2026-09-10',
|
||||
sourceStatus: 'suggested',
|
||||
confidence: null,
|
||||
confidenceBand: null,
|
||||
state: 'new',
|
||||
target: null,
|
||||
acceptedPlaceId: null,
|
||||
acceptedJournalEntryId: null,
|
||||
acceptedBucketListItemId: null,
|
||||
sourceChanged: false,
|
||||
sourceMissing: false,
|
||||
matchedBucketListItemId: null,
|
||||
matchedBucketListName: null,
|
||||
countryCode: null,
|
||||
firstSeenAt: '2026-09-10T06:00:00Z',
|
||||
lastSeenAt: '2026-09-10T06:00:00Z',
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
const TRIPS: AcceptTargetOption[] = [
|
||||
{ id: 31, label: 'Rhineland' },
|
||||
{ id: 32, label: 'Alps' },
|
||||
]
|
||||
|
||||
// Distinct labels per trip so "the day list followed the trip" is observable
|
||||
// without reading ids out of the DOM.
|
||||
const DAYS: Record<number, AcceptTargetOption[]> = {
|
||||
31: [
|
||||
{ id: 401, label: 'Day 1', badge: '10 Sept' },
|
||||
{ id: 402, label: 'Day 2', badge: '11 Sept' },
|
||||
],
|
||||
32: [{ id: 501, label: 'Alpine day', badge: '01 Oct' }],
|
||||
}
|
||||
const daysForTrip = (tripId: number): AcceptTargetOption[] => DAYS[tripId] ?? []
|
||||
|
||||
const JOURNALS: AcceptTargetOption[] = [
|
||||
{ id: 71, label: 'Rhine notebook' },
|
||||
{ id: 72, label: 'Alpine notebook' },
|
||||
]
|
||||
|
||||
type Props = React.ComponentProps<typeof DawarichAcceptDialog>
|
||||
|
||||
function open(props: Partial<Props> = {}) {
|
||||
const onConfirm = vi.fn()
|
||||
const onCancel = vi.fn()
|
||||
const all: Props = { suggestion: stay(), target: 'place', ...props, onConfirm, onCancel }
|
||||
const view = render(<DawarichAcceptDialog {...all} />)
|
||||
return {
|
||||
...view,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
/** Re-render with the same props bar the ones named: the parent's own update path. */
|
||||
update: (next: Partial<Props>) => view.rerender(<DawarichAcceptDialog {...all} {...next} />),
|
||||
}
|
||||
}
|
||||
|
||||
/** Open a CustomSelect by its trigger, then pick the option with this label. */
|
||||
function pick(triggerName: string | RegExp, optionLabel: string): void {
|
||||
fireEvent.click(screen.getByRole('button', { name: triggerName }))
|
||||
fireEvent.click(screen.getByText(optionLabel))
|
||||
}
|
||||
|
||||
/** Type into the date field's keyboard entry, which takes ISO as-is. */
|
||||
function typeDate(iso: string): void {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Enter date manually' }))
|
||||
const input = screen.getByLabelText('Enter date manually')
|
||||
fireEvent.change(input, { target: { value: iso } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
phone.value = false
|
||||
})
|
||||
|
||||
describe('DawarichAcceptDialog', () => {
|
||||
it('FE-DAWARICH-ACCEPT-001: nothing is on screen while no stay is pending', () => {
|
||||
open({ suggestion: null, trips: TRIPS })
|
||||
// The panel portals to document.body, so "empty container" proves nothing:
|
||||
// the absence of the title and the confirm button does.
|
||||
expect(screen.queryByText('Add this stay as a place')).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: 'Add place' })).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-002: every field opens prefilled from the recording', () => {
|
||||
open({ trips: TRIPS, daysForTrip })
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'Add this stay as a place' })).toBeInTheDocument()
|
||||
expect(screen.getByLabelText('Name')).toHaveValue('Cafe Reichard')
|
||||
// The wall clock out of the offset the recording carries, not UTC.
|
||||
expect(screen.getByLabelText('Arrived')).toHaveValue('10:15')
|
||||
expect(screen.getByLabelText('Left')).toHaveValue('12:40')
|
||||
expect(screen.getByLabelText('Notes')).toHaveValue('')
|
||||
expect(screen.getByText(/^Recorded /)).toBeInTheDocument()
|
||||
expect(screen.getByText('145 min')).toBeInTheDocument()
|
||||
// No trip of its own, so the first trip the user may write to.
|
||||
expect(screen.getByRole('button', { name: 'Rhineland' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Not on a day yet' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-003: an untouched stay sends only the target, its trip and the recorded clock', () => {
|
||||
const { onConfirm } = open({ suggestion: stay({ tripId: 32 }), trips: TRIPS, daysForTrip })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add place' }))
|
||||
|
||||
// No name, no notes, no date: the server falls back to the recording for
|
||||
// each of those, and repeating them would turn every accept into an edit.
|
||||
expect(onConfirm).toHaveBeenCalledWith({ target: 'place', tripId: 32, time: '10:15', endTime: '12:40' })
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-004: every correction travels, the day included', () => {
|
||||
const { onConfirm } = open({ trips: TRIPS, daysForTrip })
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Café Reichard am Dom' } })
|
||||
fireEvent.change(screen.getByLabelText('Notes'), { target: { value: 'Two hours and a lot of cake.' } })
|
||||
typeDate('2026-09-12')
|
||||
fireEvent.change(screen.getByLabelText('Arrived'), { target: { value: '09:00' } })
|
||||
fireEvent.change(screen.getByLabelText('Left'), { target: { value: '11:45' } })
|
||||
pick('Not on a day yet', 'Day 1')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add place' }))
|
||||
|
||||
expect(onConfirm).toHaveBeenCalledWith({
|
||||
target: 'place',
|
||||
tripId: 31,
|
||||
dayId: 401,
|
||||
name: 'Café Reichard am Dom',
|
||||
notes: 'Two hours and a lot of cake.',
|
||||
date: '2026-09-12',
|
||||
time: '09:00',
|
||||
endTime: '11:45',
|
||||
})
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-005: a name or note that says nothing new is left out of the body', () => {
|
||||
const { onConfirm } = open({ trips: TRIPS, daysForTrip })
|
||||
const untouched = { target: 'place', tripId: 31, time: '10:15', endTime: '12:40' }
|
||||
|
||||
// Emptied entirely: the recording's own name is what should survive.
|
||||
fireEvent.change(screen.getByLabelText('Name'), { target: { value: ' ' } })
|
||||
fireEvent.change(screen.getByLabelText('Notes'), { target: { value: ' ' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add place' }))
|
||||
expect(onConfirm).toHaveBeenLastCalledWith(untouched)
|
||||
|
||||
// Retyped with padding around it: after trimming this is the same name, and
|
||||
// sending it would write a "correction" nobody made.
|
||||
fireEvent.change(screen.getByLabelText('Name'), { target: { value: ' Cafe Reichard ' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add place' }))
|
||||
expect(onConfirm).toHaveBeenLastCalledWith(untouched)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-006: unplanned is an answer, not a missing one', () => {
|
||||
const { onConfirm } = open({ trips: TRIPS, daysForTrip })
|
||||
|
||||
pick('Not on a day yet', 'Day 1')
|
||||
// The date rides along as the trigger's badge rather than inside its label.
|
||||
expect(screen.getByRole('button', { name: /Day 1/ })).toHaveTextContent('10 Sept')
|
||||
|
||||
// Back to "not on a day yet": the sentinel option has to clear the choice
|
||||
// rather than be stored as a day id of its own.
|
||||
pick(/Day 1/, 'Not on a day yet')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add place' }))
|
||||
expect(onConfirm).toHaveBeenCalledWith({ target: 'place', tripId: 31, time: '10:15', endTime: '12:40' })
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-007: changing the trip drops the day that belonged to the old one', () => {
|
||||
const { onConfirm } = open({ trips: TRIPS, daysForTrip })
|
||||
|
||||
pick('Not on a day yet', 'Day 2')
|
||||
pick('Rhineland', 'Alps')
|
||||
|
||||
// Day 2 is a day of the Rhineland trip; keeping it would attach the place to
|
||||
// somebody else's day, which the server refuses with a 400.
|
||||
expect(screen.getByRole('button', { name: 'Not on a day yet' })).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Not on a day yet' }))
|
||||
expect(screen.getByText('Alpine day')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Day 2')).toBeNull()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add place' }))
|
||||
expect(onConfirm).toHaveBeenCalledWith({ target: 'place', tripId: 32, time: '10:15', endTime: '12:40' })
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-008: the trip falls back from the stay to the first writable one to nothing', () => {
|
||||
// The stay's own trip wins: it is the one whose dates the recording fell into.
|
||||
const own = open({ suggestion: stay({ tripId: 32 }), trips: TRIPS, daysForTrip })
|
||||
expect(screen.getByRole('button', { name: 'Alps' })).toBeInTheDocument()
|
||||
own.unmount()
|
||||
|
||||
const first = open({ trips: TRIPS, daysForTrip })
|
||||
expect(screen.getByRole('button', { name: 'Rhineland' })).toBeInTheDocument()
|
||||
first.unmount()
|
||||
|
||||
// No trip at all: the picker admits it and the confirm is inert, because a
|
||||
// place with no trip is a 400 rather than a partial success.
|
||||
open({ trips: [], daysForTrip })
|
||||
expect(screen.getByRole('button', { name: 'Choose a trip' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Add place' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-009: with no day resolver the day picker offers only "not on a day yet"', () => {
|
||||
// The trip rail passes a resolver; an Atlas-side or MCP-shaped caller need
|
||||
// not, and the picker has to survive that rather than throw.
|
||||
open({ trips: TRIPS })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Not on a day yet' }))
|
||||
expect(screen.getAllByText('Not on a day yet')).toHaveLength(2)
|
||||
expect(screen.queryByText('Day 1')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-010: the journal target asks for a story and sends the chosen journey', () => {
|
||||
const { onConfirm } = open({ target: 'journal', journals: JOURNALS })
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'Write a journal entry' })).toBeInTheDocument()
|
||||
// A story gets room to be one; notes on a place do not need five rows.
|
||||
expect(screen.getByLabelText('Your story')).toHaveAttribute('rows', '5')
|
||||
expect(screen.getByText('Add photos to the entry after it is created.')).toBeInTheDocument()
|
||||
// No trip or day rail here: the entry belongs to a journey, not to a day.
|
||||
expect(screen.queryByText('Day')).toBeNull()
|
||||
expect(screen.queryByText('Trip')).toBeNull()
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Your story'), { target: { value: 'Cake, then the cathedral.' } })
|
||||
pick('Rhine notebook', 'Alpine notebook')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add entry' }))
|
||||
|
||||
expect(onConfirm).toHaveBeenCalledWith({
|
||||
target: 'journal',
|
||||
journalId: 72,
|
||||
notes: 'Cake, then the cathedral.',
|
||||
time: '10:15',
|
||||
endTime: '12:40',
|
||||
})
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-011: with no journey to write to, the journal confirm is inert', () => {
|
||||
open({ target: 'journal' })
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Choose a journal' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Add entry' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-012: ticking a wish off states the rule and sends the matched wish', () => {
|
||||
const { onConfirm } = open({
|
||||
target: 'bucket_list',
|
||||
suggestion: stay({ matchedBucketListItemId: 88, matchedBucketListName: 'Museum Ludwig' }),
|
||||
})
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'Tick off a wish' })).toBeInTheDocument()
|
||||
// Why a stay at a café is being offered against a museum: the rule, spelled out.
|
||||
expect(screen.getByText(/On your wishlist: Museum Ludwig/)).toHaveTextContent('within 250 m and after 20 minutes')
|
||||
// Nothing here is editable but the wish it ticks off: the visit's own
|
||||
// timestamp is what gets stored, so a clock or a note would be theatre.
|
||||
expect(screen.queryByLabelText('Arrived')).toBeNull()
|
||||
expect(screen.queryByLabelText('Left')).toBeNull()
|
||||
expect(screen.queryByLabelText('Notes')).toBeNull()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Tick it off' }))
|
||||
expect(onConfirm).toHaveBeenCalledWith({
|
||||
target: 'bucket_list',
|
||||
bucketListItemId: 88,
|
||||
time: '10:15',
|
||||
endTime: '12:40',
|
||||
})
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-013: a stay that matched no wish cannot be ticked off', () => {
|
||||
open({ target: 'bucket_list', suggestion: stay() })
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Tick it off' })).toBeDisabled()
|
||||
expect(screen.queryByText(/On your wishlist/)).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-014: a write already in flight blocks a second one', () => {
|
||||
// Everything is answered, so only `busy` can be holding the button, which is
|
||||
// the point: double-accepting a stay creates two places out of one recording.
|
||||
open({ trips: TRIPS, daysForTrip, busy: true })
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Add place' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-015: backing out writes nothing, by button or by Escape', () => {
|
||||
const { onCancel, onConfirm } = open({ trips: TRIPS, daysForTrip })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
|
||||
expect(onCancel).toHaveBeenCalledTimes(2)
|
||||
expect(onConfirm).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("FE-DAWARICH-ACCEPT-016: the source's own verdict is shown only while it is unconfirmed", () => {
|
||||
const unconfirmed = open({ trips: TRIPS, suggestion: stay({ sourceStatus: 'suggested' }) })
|
||||
expect(screen.getByText('Detected, unconfirmed')).toBeInTheDocument()
|
||||
unconfirmed.unmount()
|
||||
|
||||
// Confirmed in Dawarich: saying so would be noise, the badge is simply gone.
|
||||
open({ trips: TRIPS, suggestion: stay({ sourceStatus: 'confirmed' }) })
|
||||
expect(screen.queryByText('Detected, unconfirmed')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-017: only the bands Dawarich actually emits are shown, and only "low" warns', () => {
|
||||
const low = open({ trips: TRIPS, suggestion: stay({ confidenceBand: 'low', confidence: 20 }) })
|
||||
expect(screen.getByText('Uncertain detection').parentElement?.className).toContain('text-warning')
|
||||
low.unmount()
|
||||
|
||||
const high = open({ trips: TRIPS, suggestion: stay({ confidenceBand: 'high', confidence: 90 }) })
|
||||
// A confident detection is a fact, not a warning. Same badge, neutral tone.
|
||||
expect(screen.getByText('Confident detection').parentElement?.className).toContain('text-content-secondary')
|
||||
high.unmount()
|
||||
|
||||
const none = open({ trips: TRIPS, suggestion: stay({ confidenceBand: null }) })
|
||||
expect(screen.queryByText(/detection$/)).toBeNull()
|
||||
none.unmount()
|
||||
|
||||
// A band a later Dawarich invents: nothing at all, rather than a raw key.
|
||||
open({ trips: TRIPS, suggestion: stay({ confidenceBand: 'certain', confidence: 100 }) })
|
||||
expect(screen.queryByText(/dawarich\.confidence/)).toBeNull()
|
||||
expect(screen.queryByText(/detection$/)).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-018: a recording with no readable clock or date sends neither', () => {
|
||||
// Dawarich has shipped date-only and non-ISO timestamps; the clock parser
|
||||
// answers with an empty string rather than a guess, and an empty string must
|
||||
// not reach the body as `time: ""`.
|
||||
const { onConfirm } = open({
|
||||
trips: TRIPS,
|
||||
daysForTrip,
|
||||
suggestion: stay({ startedAt: '2026-09-10', endedAt: '2026-09-10', localDate: '' }),
|
||||
})
|
||||
|
||||
expect(screen.getByLabelText('Arrived')).toHaveValue('')
|
||||
expect(screen.getByLabelText('Left')).toHaveValue('')
|
||||
expect(screen.getByRole('button', { name: 'Date' })).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add place' }))
|
||||
expect(onConfirm).toHaveBeenCalledWith({ target: 'place', tripId: 31 })
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-019: the fields follow the stay, and survive a re-render of the same one', () => {
|
||||
const { update } = open({ trips: TRIPS, daysForTrip })
|
||||
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Edited by hand' } })
|
||||
|
||||
// A fresh object for the same row: a parent re-render, not a new decision.
|
||||
// Re-seeding here would eat what the user typed mid-sentence.
|
||||
update({ suggestion: stay() })
|
||||
expect(screen.getByLabelText('Name')).toHaveValue('Edited by hand')
|
||||
|
||||
update({
|
||||
suggestion: stay({
|
||||
id: 2,
|
||||
name: 'Kölner Dom',
|
||||
tripId: 32,
|
||||
localDate: '2026-09-11',
|
||||
startedAt: '2026-09-11T08:00:00+02:00',
|
||||
endedAt: '2026-09-11T09:30:00+02:00',
|
||||
}),
|
||||
})
|
||||
expect(screen.getByLabelText('Name')).toHaveValue('Kölner Dom')
|
||||
expect(screen.getByLabelText('Arrived')).toHaveValue('08:00')
|
||||
expect(screen.getByRole('button', { name: 'Alps' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-020: on a phone it is a sheet, and its footer confirms', () => {
|
||||
phone.value = true
|
||||
const { onConfirm } = open({ trips: TRIPS, daysForTrip })
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Add this stay as a place' })).toBeInTheDocument()
|
||||
// The desktop modal's own heading is the tell that the wrong shell rendered.
|
||||
expect(screen.queryByRole('heading', { name: 'Add this stay as a place' })).toBeNull()
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Reichard' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add place' }))
|
||||
|
||||
expect(onConfirm).toHaveBeenCalledWith({
|
||||
target: 'place',
|
||||
tripId: 31,
|
||||
name: 'Reichard',
|
||||
time: '10:15',
|
||||
endTime: '12:40',
|
||||
})
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-021: the phone sheet backs out from its header and its footer, and blocks an impossible write', () => {
|
||||
phone.value = true
|
||||
const { onCancel, onConfirm } = open({ target: 'journal' })
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Add entry' })).toBeDisabled()
|
||||
|
||||
// Two ways out of the sheet, both the same door: the header's close circle
|
||||
// and the footer's cancel pill.
|
||||
const exits = screen.getAllByRole('button', { name: 'Cancel' })
|
||||
expect(exits).toHaveLength(2)
|
||||
exits.forEach(button => fireEvent.click(button))
|
||||
|
||||
expect(onCancel).toHaveBeenCalledTimes(2)
|
||||
expect(onConfirm).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-022: the name stays editable on the wishlist rail, and a correction travels', () => {
|
||||
// The clock, the date and the notes are all hidden for a wish, which is
|
||||
// exactly why the one field that survives is worth naming: the detector's
|
||||
// guess at a place name is what a tick-off is filed under, and "hide
|
||||
// everything that is not the wish" is the tidy-up that would take it away.
|
||||
const { onConfirm } = open({
|
||||
target: 'bucket_list',
|
||||
suggestion: stay({ matchedBucketListItemId: 88, matchedBucketListName: 'Museum Ludwig' }),
|
||||
})
|
||||
|
||||
expect(screen.getByLabelText('Name')).toHaveValue('Cafe Reichard')
|
||||
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Museum Ludwig' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Tick it off' }))
|
||||
|
||||
expect(onConfirm).toHaveBeenCalledWith({
|
||||
target: 'bucket_list',
|
||||
bucketListItemId: 88,
|
||||
name: 'Museum Ludwig',
|
||||
time: '10:15',
|
||||
endTime: '12:40',
|
||||
})
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-023: a new stay arrives with no day chosen, whatever the last one had', () => {
|
||||
const { onConfirm, update } = open({ trips: TRIPS, daysForTrip })
|
||||
|
||||
pick('Not on a day yet', 'Day 2')
|
||||
|
||||
// Same trip, so the day list does not change and a stale `dayId` would stay
|
||||
// a legal value, which is the dangerous version of this bug: the second
|
||||
// stay is filed silently on the day somebody picked for the first.
|
||||
update({ suggestion: stay({ id: 3, name: 'Kölner Dom', tripId: 31 }) })
|
||||
expect(screen.getByRole('button', { name: 'Not on a day yet' })).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add place' }))
|
||||
expect(onConfirm).toHaveBeenCalledWith({ target: 'place', tripId: 31, time: '10:15', endTime: '12:40' })
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ACCEPT-024: switching rails keeps what was typed and leaks no trip into the journal body', () => {
|
||||
const { onConfirm, update } = open({ trips: TRIPS, daysForTrip })
|
||||
|
||||
fireEvent.change(screen.getByLabelText('Notes'), { target: { value: 'Cake, then the cathedral.' } })
|
||||
pick('Not on a day yet', 'Day 1')
|
||||
|
||||
// Backing out of "add as a place" and choosing "write a journal entry" on
|
||||
// the same row is one instance and one stay, so nothing is re-seeded.
|
||||
update({ target: 'journal', journals: JOURNALS })
|
||||
expect(screen.getByLabelText('Your story')).toHaveValue('Cake, then the cathedral.')
|
||||
|
||||
// The journal was never chosen, because the seeding runs off the stay and
|
||||
// the stay has not changed. Offering a confirm here would send a body with
|
||||
// no journalId in it.
|
||||
expect(screen.getByRole('button', { name: 'Choose a journal' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Add entry' })).toBeDisabled()
|
||||
|
||||
pick('Choose a journal', 'Rhine notebook')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add entry' }))
|
||||
|
||||
// Trip 31 and day 401 are still held in state. A journal entry belongs to a
|
||||
// journey, and the server reads the body at face value.
|
||||
expect(onConfirm).toHaveBeenCalledWith({
|
||||
target: 'journal',
|
||||
journalId: 71,
|
||||
notes: 'Cake, then the cathedral.',
|
||||
time: '10:15',
|
||||
endTime: '12:40',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,35 @@
|
||||
// FE-DAWARICH-ATLASDLG-001 to FE-DAWARICH-ATLASDLG-009
|
||||
// FE-DAWARICH-ATLASDLG-001 to FE-DAWARICH-ATLASDLG-029
|
||||
/**
|
||||
* The room where Dawarich's two Atlas questions get answered.
|
||||
*
|
||||
* Nothing in here runs on its own, and that is the whole design: the Atlas is a
|
||||
* curated list that carries tombstones precisely so a country somebody removed
|
||||
* stays removed, so every read and every write starts with a person pressing a
|
||||
* button. What is worth pinning is therefore not "does it fetch" but everything
|
||||
* arranged around the fetch.
|
||||
*
|
||||
* - **What is written, and dated when.** A wish is ticked off on the day it was
|
||||
* reached, not on today, and wishes reached on the same day travel in one
|
||||
* request. A regression here either back-dates somebody's list wrongly or
|
||||
* turns one confirmation into twenty requests.
|
||||
* - **The five states each half can be in.** Unasked, in flight, answered,
|
||||
* answered with nothing, answered with caveats. The confirm button is
|
||||
* rendered or absent rather than merely greyed out, so each state has to
|
||||
* decide whether that control exists at all, and the caveats under the list
|
||||
* are only said when there is something to say.
|
||||
* - **Refusing to write blind.** Offline is not a server error: nothing was
|
||||
* sent, and "something went wrong talking to Dawarich" for a train tunnel
|
||||
* sends people hunting for a bug in their own instance.
|
||||
* - **Both shells.** The phone gets an MSheet with its own footer, the desktop
|
||||
* a Modal; the body between them is the same tree, so a regression that
|
||||
* dropped one shell would otherwise only surface on a device.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render'
|
||||
import { fireEvent } from '@testing-library/react'
|
||||
import { act, fireEvent } from '@testing-library/react'
|
||||
import { setForcedOffline } from '../../sync/networkMode'
|
||||
import { DawarichOfflineError } from '../../repo/dawarichRepo'
|
||||
import DawarichAtlasDialog from './DawarichAtlasDialog'
|
||||
|
||||
const toast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }
|
||||
@@ -31,6 +58,11 @@ vi.mock('../../api/dawarich', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
// The one thing the dialog reads about the device. A hoisted flag rather than a
|
||||
// resize: useIsPhone is matchMedia-driven and the global stub always answers false.
|
||||
const phone = vi.hoisted(() => ({ value: false }))
|
||||
vi.mock('../../mobile/useIsPhone', () => ({ useIsPhone: () => phone.value }))
|
||||
|
||||
const SCAN = {
|
||||
matches: [
|
||||
{
|
||||
@@ -61,11 +93,77 @@ const COUNTRIES = {
|
||||
fetchedAt: '2026-09-12T10:00:00Z',
|
||||
}
|
||||
|
||||
/**
|
||||
* Three wishes reached on two days. The pair sharing a timestamp is the whole
|
||||
* point of the fixture: the dialog groups by the date it is about to write, and
|
||||
* a regression that lost the grouping would send one request per wish. The
|
||||
* third one sits far enough away to be reported in kilometres rather than
|
||||
* metres, which is the other half of the row's arithmetic.
|
||||
*/
|
||||
const SAME_DAY = {
|
||||
matches: [
|
||||
{
|
||||
itemId: 21,
|
||||
name: 'Van Gogh Museum',
|
||||
match: { at: '2026-08-02T11:00:00Z', minutes: 95, distanceMeters: 30, points: 40 },
|
||||
alreadyVisited: false,
|
||||
},
|
||||
{
|
||||
itemId: 22,
|
||||
name: 'Rijksmuseum',
|
||||
match: { at: '2026-08-02T11:00:00Z', minutes: 120, distanceMeters: 55, points: 51 },
|
||||
alreadyVisited: false,
|
||||
},
|
||||
{
|
||||
itemId: 23,
|
||||
name: 'Kinderdijk',
|
||||
match: { at: '2026-07-30T09:00:00Z', minutes: 70, distanceMeters: 1400, points: 22 },
|
||||
alreadyVisited: false,
|
||||
},
|
||||
],
|
||||
skippedWithoutCoordinates: 0,
|
||||
truncated: false,
|
||||
fetchedAt: '2026-09-12T10:00:00Z',
|
||||
}
|
||||
|
||||
/**
|
||||
* A reading with nothing to apologise for: no unmatched names, one country with
|
||||
* more cities than fit beside a flag and one with none at all.
|
||||
*/
|
||||
const MORE_COUNTRIES = {
|
||||
countries: [
|
||||
{
|
||||
countryCode: 'FR',
|
||||
sourceName: 'France',
|
||||
cities: ['Paris', 'Lyon', 'Nice', 'Nantes'].map(name => ({
|
||||
name,
|
||||
minutes: 120,
|
||||
lastSeenAt: '2026-08-02T10:00:00Z',
|
||||
})),
|
||||
alreadyVisited: false,
|
||||
},
|
||||
{ countryCode: 'BE', sourceName: 'Belgium', cities: [], alreadyVisited: false },
|
||||
],
|
||||
unresolved: [],
|
||||
fetchedAt: '2026-09-12T10:00:00Z',
|
||||
}
|
||||
|
||||
/** A promise this test settles by hand, to pin down what is on screen mid-flight. */
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
const promise = new Promise<T>(res => {
|
||||
resolve = res
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
function open(props: Partial<React.ComponentProps<typeof DawarichAtlasDialog>> = {}) {
|
||||
return render(<DawarichAtlasDialog isOpen onClose={vi.fn()} {...props} />)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
phone.value = false
|
||||
setForcedOffline(false)
|
||||
toast.success.mockReset()
|
||||
toast.error.mockReset()
|
||||
repo.bucketScan.mockReset().mockResolvedValue(SCAN)
|
||||
@@ -74,6 +172,10 @@ beforeEach(() => {
|
||||
api.acceptAtlasCountries.mockReset().mockResolvedValue({ marked: 1 })
|
||||
})
|
||||
|
||||
// Force-offline is module state, not component state: left on, it would leak
|
||||
// into the next file's writes.
|
||||
afterEach(() => setForcedOffline(false))
|
||||
|
||||
describe('DawarichAtlasDialog', () => {
|
||||
it('FE-DAWARICH-ATLASDLG-001: asks nothing on its own — the scan runs when the reader says so', () => {
|
||||
open()
|
||||
@@ -168,4 +270,368 @@ describe('DawarichAtlasDialog', () => {
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Dawarich rejected the API key.'))
|
||||
expect(screen.getByRole('button', { name: 'Check wishlist' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-010: while the recordings are being read there are placeholders and nothing to press', async () => {
|
||||
const scan = deferred<typeof SCAN>()
|
||||
repo.bucketScan.mockReturnValueOnce(scan.promise)
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
expect(screen.getByText('Checking…')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('checkbox')).toBeNull()
|
||||
// Neither control exists yet: there is nothing to confirm, and "check again"
|
||||
// before the first answer is a second request for the same thing.
|
||||
expect(screen.queryByRole('button', { name: /Tick off/ })).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: 'Check again' })).toBeNull()
|
||||
|
||||
await act(async () => {
|
||||
scan.resolve(SCAN)
|
||||
})
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-011: a scan that found nothing says so in a sentence and offers no confirmation', async () => {
|
||||
repo.bucketScan.mockResolvedValue({ ...SCAN, matches: [], skippedWithoutCoordinates: 0 })
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Nothing on your wishlist turned up in your recordings.')).toBeInTheDocument(),
|
||||
)
|
||||
// Absent, not greyed out: a dead "Tick off 0" under an empty state only asks
|
||||
// to be understood.
|
||||
expect(screen.queryByRole('button', { name: /Tick off/ })).toBeNull()
|
||||
// The rule stays on screen, because it is the answer to "why did nothing
|
||||
// turn up": driving past a wish does not count as reaching it.
|
||||
expect(screen.getByText(/A wish counts as reached within 250 m and after 20 minutes/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-012: the caveats under a scan are only said when there are any', async () => {
|
||||
repo.bucketScan.mockResolvedValue({ ...SCAN, skippedWithoutCoordinates: 0, truncated: true })
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Only the first entries were checked. Run it again for the rest.')).toBeInTheDocument(),
|
||||
)
|
||||
// Nothing was skipped this time, so nothing is said about skipping: a
|
||||
// "0 entries have no coordinates" line is noise dressed as information.
|
||||
expect(screen.queryByText(/have no coordinates/)).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-013: a country shows the first of its cities, one without any shows none', async () => {
|
||||
repo.atlasSuggestions.mockResolvedValue(MORE_COUNTRIES)
|
||||
open({ initialTab: 'countries' })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'France' })).toBeInTheDocument())
|
||||
const france = screen.getByRole('checkbox', { name: 'France' })
|
||||
// The badge counts all four; the line beside it names three, which is what
|
||||
// fits beside a flag at the width a phone gives this dialog.
|
||||
expect(france.textContent).toContain('4 cities')
|
||||
expect(france.textContent).toContain('Paris, Lyon, Nice')
|
||||
expect(france.textContent).not.toContain('Nantes')
|
||||
expect(screen.getByRole('checkbox', { name: 'Belgium' }).textContent).not.toContain('cities')
|
||||
// Everything matched, so the dialog does not mention matching at all.
|
||||
expect(screen.queryByText(/could not match these to a country/)).toBeNull()
|
||||
expect(screen.getByText('The last 12 months were looked at.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-014: a reading with nothing new in it says so rather than showing an empty list', async () => {
|
||||
// Germany alone, and the Atlas already has it.
|
||||
repo.atlasSuggestions.mockResolvedValue({ ...COUNTRIES, countries: [COUNTRIES.countries[0]] })
|
||||
open({ initialTab: 'countries' })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Your recordings show no countries TREK does not already have.')).toBeInTheDocument(),
|
||||
)
|
||||
expect(screen.queryByRole('button', { name: /Add \d+ countries/ })).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-015: wishes reached on one day travel in one request, another day in its own', async () => {
|
||||
repo.bucketScan.mockResolvedValue(SAME_DAY)
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Rijksmuseum' })).toBeInTheDocument())
|
||||
// Over a kilometre out is said in kilometres: "1400 m away" is a
|
||||
// measurement, "1.4 km away" is how far it was.
|
||||
expect(screen.getByRole('checkbox', { name: 'Kinderdijk' }).textContent).toContain('1.4 km away')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 3/ }))
|
||||
|
||||
await waitFor(() => expect(api.confirmBucketVisits).toHaveBeenCalledTimes(2))
|
||||
// Grouped by date, not ordered by it: the row order inside a day is the
|
||||
// sort's business and nothing here depends on it.
|
||||
const calls = api.confirmBucketVisits.mock.calls as Array<[number[], string]>
|
||||
const byDate = new Map(calls.map(([ids, at]) => [at, [...ids].sort((a, b) => a - b)]))
|
||||
expect(byDate.get('2026-08-02T11:00:00Z')).toEqual([21, 22])
|
||||
expect(byDate.get('2026-07-30T09:00:00Z')).toEqual([23])
|
||||
// Both answers counted, not just the last one to come back.
|
||||
expect(toast.success).toHaveBeenCalledWith('2 wishes ticked off')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-016: an unticked wish is left out of the write entirely', async () => {
|
||||
repo.bucketScan.mockResolvedValue(SAME_DAY)
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Kinderdijk' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Kinderdijk' }))
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Rijksmuseum' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
|
||||
|
||||
// One request, for one day, carrying one id. The day whose other wish was
|
||||
// dropped does not travel half-empty, and the other day does not travel at all.
|
||||
await waitFor(() => expect(api.confirmBucketVisits).toHaveBeenCalledTimes(1))
|
||||
expect(api.confirmBucketVisits).toHaveBeenCalledWith([21], '2026-08-02T11:00:00Z')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-017: a row that was unticked can be put back', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Museum Ludwig' }))
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toHaveAttribute('aria-checked', 'false')
|
||||
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Museum Ludwig' }))
|
||||
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toHaveAttribute('aria-checked', 'true')
|
||||
expect(screen.getByRole('button', { name: /Tick off 1/ })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-018: offline, a wish confirmation is refused before anything is sent', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
setForcedOffline(true)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('TREK is offline right now'))
|
||||
// Not attempted at all: a confirmation fired into a dead connection hangs to
|
||||
// a timeout and then reports a server error for something no server saw.
|
||||
expect(api.confirmBucketVisits).not.toHaveBeenCalled()
|
||||
// And the selection survives, so pressing it again once there is signal is enough.
|
||||
expect(screen.getByRole('button', { name: /Tick off 1/ })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-019: offline, a country confirmation is refused before anything is sent', async () => {
|
||||
open({ initialTab: 'countries' })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
|
||||
setForcedOffline(true)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add 1 countries/ }))
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('TREK is offline right now'))
|
||||
expect(api.acceptAtlasCountries).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-020: a write that failed leaves every row exactly as it was', async () => {
|
||||
// A rejection with no `{ error }` envelope at all: a socket that died
|
||||
// mid-request rather than a server that answered.
|
||||
api.confirmBucketVisits.mockRejectedValue(new Error('socket hang up'))
|
||||
const onChanged = vi.fn()
|
||||
open({ onChanged })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Something went wrong talking to Dawarich.'))
|
||||
// Nothing was marked off locally, so a second attempt still has something to
|
||||
// send, and the Atlas is not asked to re-read for a write that never landed.
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toHaveAttribute('aria-checked', 'true')
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeEnabled()
|
||||
expect(onChanged).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-021: a refusal carrying no readable reason still gets a sentence', async () => {
|
||||
// An `{ error }` that is not a string is not a message: falling through to
|
||||
// the generic sentence beats printing "[object Object]" at somebody.
|
||||
api.acceptAtlasCountries.mockRejectedValue({ response: { data: { error: { code: 502 } } } })
|
||||
open({ initialTab: 'countries' })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add 1 countries/ }))
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Something went wrong talking to Dawarich.'))
|
||||
expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toHaveAttribute('aria-checked', 'true')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-022: a read that never left the device reads as a connection, not a failure', async () => {
|
||||
// The repo refuses offline reads itself, and its refusal has to survive the
|
||||
// trip through failureText as the connection message rather than as
|
||||
// "something went wrong talking to Dawarich", which points at the instance.
|
||||
repo.atlasSuggestions.mockRejectedValue(new DawarichOfflineError())
|
||||
open({ initialTab: 'countries' })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('TREK is offline right now')),
|
||||
)
|
||||
// Still unasked, so the button that asks is the one on screen.
|
||||
expect(screen.getByRole('button', { name: 'Look for countries' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-023: the other tab asks the other question, and each keeps its own answer', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Countries/ }))
|
||||
|
||||
// Switching tabs asks nothing on its own: a country reading costs an
|
||||
// upstream request, and nobody asked for it by moving their eyes.
|
||||
expect(repo.atlasSuggestions).not.toHaveBeenCalled()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Wishlist/ }))
|
||||
|
||||
// The scan is still there, and was not repeated for the return trip.
|
||||
expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument()
|
||||
expect(repo.bucketScan).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-024: "Check again" re-runs the scan and is inert while it runs', async () => {
|
||||
open()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
const second = deferred<typeof SCAN>()
|
||||
repo.bucketScan.mockReturnValueOnce(second.promise)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check again' }))
|
||||
|
||||
// A second press while the first is in flight would run the whole scan twice:
|
||||
// one upstream request per wish, for the same answer.
|
||||
expect(screen.getByRole('button', { name: 'Check again' })).toBeDisabled()
|
||||
|
||||
await act(async () => {
|
||||
second.resolve(SCAN)
|
||||
})
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Check again' })).toBeEnabled())
|
||||
expect(repo.bucketScan).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-025: "Check again" on the countries tab re-reads the countries, not the wishes', async () => {
|
||||
open({ initialTab: 'countries' })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check again' }))
|
||||
|
||||
await waitFor(() => expect(repo.atlasSuggestions).toHaveBeenCalledTimes(2))
|
||||
expect(repo.bucketScan).not.toHaveBeenCalled()
|
||||
// A year back from the moment it was asked, both times: the window is the
|
||||
// same question asked again, not a widening one.
|
||||
const calls = repo.atlasSuggestions.mock.calls as Array<[string, string]>
|
||||
for (const [from, to] of calls) {
|
||||
expect(Date.parse(to) - Date.parse(from)).toBe(365 * 24 * 60 * 60 * 1000)
|
||||
}
|
||||
expect(Date.parse(calls[1][0])).toBeGreaterThanOrEqual(Date.parse(calls[0][0]))
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-026: on a phone it is a sheet, and the count and the confirm live in its own footer', async () => {
|
||||
phone.value = true
|
||||
const onClose = vi.fn()
|
||||
open({ onClose })
|
||||
|
||||
expect(screen.getByRole('dialog', { name: 'Dawarich' })).toBeInTheDocument()
|
||||
// The desktop modal puts the title in a heading: its absence is the tell
|
||||
// that the right shell rendered.
|
||||
expect(screen.queryByRole('heading', { name: /Dawarich/ })).toBeNull()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Museum Ludwig' })).toBeInTheDocument())
|
||||
|
||||
expect(screen.getByText('1 selected')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: /Tick off 1/ }))
|
||||
await waitFor(() => expect(api.confirmBucketVisits).toHaveBeenCalledWith([11], '2026-09-10T14:00:00Z'))
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-027: a country that was just added stops being offered, and the Atlas is told', async () => {
|
||||
const onChanged = vi.fn()
|
||||
open({ initialTab: 'countries', onChanged })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Netherlands' })).toBeInTheDocument())
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add 1 countries/ }))
|
||||
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('1 countries added'))
|
||||
// Marked in place rather than re-read: the reading costs an upstream request
|
||||
// and the only thing that changed is what the reader just pressed. The row
|
||||
// leaving the list is what says the write landed.
|
||||
await waitFor(() =>
|
||||
expect(screen.getByText('Your recordings show no countries TREK does not already have.')).toBeInTheDocument(),
|
||||
)
|
||||
expect(screen.queryByRole('checkbox', { name: 'Netherlands' })).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: /Add \d+ countries/ })).toBeNull()
|
||||
expect(repo.atlasSuggestions).toHaveBeenCalledTimes(1)
|
||||
// The Atlas keeps its own map and its own counts; without this the country
|
||||
// it was just told about only appears there after a reload.
|
||||
expect(onChanged).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-028: a request that died without a reason at all still gets a sentence', async () => {
|
||||
// An aborted request rejects with nothing: not an Error, not a response.
|
||||
// Reaching into `.response.data` on that must not be the thing that takes
|
||||
// the dialog down, because a crash here loses the scan the reader is
|
||||
// looking at as well as the message they needed.
|
||||
repo.bucketScan.mockRejectedValue(undefined)
|
||||
open()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check wishlist' }))
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Something went wrong talking to Dawarich.'))
|
||||
expect(screen.getByRole('button', { name: 'Check wishlist' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASDLG-029: a country can be unticked and put back, and only the ticked ones are written', async () => {
|
||||
// Both offers start ticked, which is the useful default but not the answer
|
||||
// every time: a border crossed on the way to somewhere else is a country
|
||||
// Dawarich saw and the reader does not want in their Atlas. Taking one out
|
||||
// has to actually take it out of the write, and changing one's mind has to
|
||||
// put it back, because the Atlas carries tombstones and an unwanted country
|
||||
// added here is removed by hand afterwards.
|
||||
repo.atlasSuggestions.mockResolvedValue(MORE_COUNTRIES)
|
||||
open({ initialTab: 'countries' })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Look for countries' }))
|
||||
await waitFor(() => expect(screen.getByRole('checkbox', { name: 'Belgium' })).toBeInTheDocument())
|
||||
expect(screen.getByRole('button', { name: /Add 2 countries/ })).toBeEnabled()
|
||||
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'Belgium' }))
|
||||
expect(screen.getByRole('checkbox', { name: 'Belgium' })).toHaveAttribute('aria-checked', 'false')
|
||||
|
||||
// Out and back in again: the tick is a toggle, not a one-way door.
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'France' }))
|
||||
expect(screen.getByRole('button', { name: /Add 0 countries/ })).toBeDisabled()
|
||||
fireEvent.click(screen.getByRole('checkbox', { name: 'France' }))
|
||||
expect(screen.getByRole('checkbox', { name: 'France' })).toHaveAttribute('aria-checked', 'true')
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add 1 countries/ }))
|
||||
|
||||
// Belgium was never sent, so nothing has to be undone in the Atlas after.
|
||||
await waitFor(() => expect(api.acceptAtlasCountries).toHaveBeenCalledWith(['FR']))
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('1 countries added'))
|
||||
// And it is still on offer, still unticked, for the trip it does belong to.
|
||||
expect(screen.getByRole('checkbox', { name: 'Belgium' })).toHaveAttribute('aria-checked', 'false')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
// FE-DAWARICH-ATLASPANEL-001 to FE-DAWARICH-ATLASPANEL-007
|
||||
/**
|
||||
* Dawarich's own panel on the Atlas, beside the stats.
|
||||
*
|
||||
* The panel itself holds almost no logic, and the little it does hold is the
|
||||
* kind that is invisible until it is wrong:
|
||||
*
|
||||
* - **It has to disappear completely when the addon is off.** Not empty, not a
|
||||
* blank pane of glass in the row beside the stats: absent, so an Atlas
|
||||
* without Dawarich looks exactly as it did before the integration landed.
|
||||
* - **It has to ask the question that was pressed.** Two tiles, one dialog, one
|
||||
* `initialTab` between them. Wiring both tiles to the same tab is a bug that
|
||||
* looks like a working panel.
|
||||
* - **It mounts the dialog on open and throws it away on close**, deliberately,
|
||||
* so a second visit starts from a fresh question rather than from a scan
|
||||
* somebody ran an hour ago.
|
||||
* - **It is made of the same glass as the Atlas panel next to it.** The tint
|
||||
* and the cursor glare are hand-written rgba rather than tokens (a solid
|
||||
* surface token would punch an opaque hole in a panel floating over a blurred
|
||||
* map), so nothing but a test stops the two panels drifting apart in the
|
||||
* dark theme.
|
||||
*
|
||||
* The dialog is pinned by its own file and stands in for itself here, so the
|
||||
* panel's decisions are observable without a scan and without mocking Dawarich.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { fireEvent } from '@testing-library/react'
|
||||
import { render, screen } from '../../../tests/helpers/render'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import DawarichAtlasSidePanel from './DawarichAtlasSidePanel'
|
||||
|
||||
vi.mock('./DawarichAtlasDialog', () => ({
|
||||
default: ({
|
||||
initialTab,
|
||||
onClose,
|
||||
onChanged,
|
||||
}: {
|
||||
initialTab: string
|
||||
onClose: () => void
|
||||
onChanged?: () => void
|
||||
}) => (
|
||||
<div data-testid="atlas-dialog">
|
||||
<span>asked: {initialTab}</span>
|
||||
<button type="button" onClick={onClose}>
|
||||
dismiss
|
||||
</button>
|
||||
<button type="button" onClick={() => onChanged?.()}>
|
||||
wrote something
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
|
||||
const ADDON = { id: 'dawarich', name: 'Dawarich', type: 'integration', icon: 'route', enabled: true }
|
||||
|
||||
/** The glass the Atlas hands down, reduced to the one property jsdom can answer for. */
|
||||
const GLASS: React.CSSProperties = { borderRadius: 20 }
|
||||
|
||||
/** Inline rgba comes back from jsdom respaced; nothing here cares about the spaces. */
|
||||
const rgba = (el: HTMLElement): string => el.style.background.replace(/\s/g, '')
|
||||
|
||||
function mount(props: Partial<React.ComponentProps<typeof DawarichAtlasSidePanel>> = {}) {
|
||||
return render(<DawarichAtlasSidePanel style={GLASS} dark {...props} />)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useAddonStore.setState({ addons: [ADDON], loaded: true })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
useAddonStore.setState({ addons: [], loaded: false })
|
||||
})
|
||||
|
||||
describe('DawarichAtlasSidePanel', () => {
|
||||
it('FE-DAWARICH-ATLASPANEL-001: an Atlas without the addon gets no panel at all', () => {
|
||||
useAddonStore.setState({ addons: [{ ...ADDON, enabled: false }] })
|
||||
|
||||
const { container } = mount()
|
||||
|
||||
// Nothing rendered, rather than an empty pane of glass in the row: the
|
||||
// panel is stretched to the height of the stats beside it, so an empty one
|
||||
// would be a visible hole.
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
expect(screen.queryByRole('button', { name: 'Wishlist' })).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-002: with the addon on it offers two questions and asks neither', () => {
|
||||
const { container } = mount()
|
||||
|
||||
expect(screen.getByText('Dawarich')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Wishlist' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Countries' })).toBeInTheDocument()
|
||||
// A scan costs one upstream request per wish. Nothing is asked until asked.
|
||||
expect(screen.queryByTestId('atlas-dialog')).toBeNull()
|
||||
// And it wears the glass it was handed rather than one of its own.
|
||||
expect(container.firstElementChild).toHaveStyle({ borderRadius: '20px' })
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-003: the wishlist tile opens the dialog on the wishlist, and closing puts it away', () => {
|
||||
mount()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Wishlist' }))
|
||||
|
||||
expect(screen.getByText('asked: wishes')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'dismiss' }))
|
||||
|
||||
// Unmounted, not hidden: the next visit starts from a clean question rather
|
||||
// than from an answer that is an hour old.
|
||||
expect(screen.queryByTestId('atlas-dialog')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-004: the countries tile opens the same dialog on the other question', () => {
|
||||
mount()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Countries' }))
|
||||
|
||||
expect(screen.getByText('asked: countries')).toBeInTheDocument()
|
||||
expect(screen.queryByText('asked: wishes')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-005: what the dialog wrote is reported up to the Atlas', () => {
|
||||
// The Atlas keeps its own counts and its own map. Without this the confirmed
|
||||
// countries only appear after a reload.
|
||||
const onChanged = vi.fn()
|
||||
mount({ onChanged })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Countries' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'wrote something' }))
|
||||
|
||||
expect(onChanged).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-006: the tiles are a tint of the light the panel is made of, per theme', () => {
|
||||
const { rerender } = render(<DawarichAtlasSidePanel style={GLASS} dark={false} />)
|
||||
const wishes = screen.getByRole('button', { name: 'Wishlist' })
|
||||
|
||||
expect(rgba(wishes)).toBe('rgba(0,0,0,0.05)')
|
||||
fireEvent.mouseEnter(wishes)
|
||||
expect(rgba(wishes)).toBe('rgba(0,0,0,0.09)')
|
||||
fireEvent.mouseLeave(wishes)
|
||||
expect(rgba(wishes)).toBe('rgba(0,0,0,0.05)')
|
||||
|
||||
rerender(<DawarichAtlasSidePanel style={GLASS} dark />)
|
||||
|
||||
// Inverted on the dark map, not merely darkened: the tile is light added to
|
||||
// the glass, and a black tint on a dark blurred map is an invisible button.
|
||||
expect(rgba(screen.getByRole('button', { name: 'Wishlist' }))).toBe('rgba(255,255,255,0.07)')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASPANEL-007: the glass glare follows the cursor and goes out behind it', () => {
|
||||
const { container } = mount()
|
||||
const panel = container.firstElementChild as HTMLElement
|
||||
const [glare, borderGlare] = Array.from(panel.children) as HTMLElement[]
|
||||
|
||||
expect(glare.style.opacity).toBe('0')
|
||||
|
||||
fireEvent.mouseMove(panel, { clientX: 140, clientY: 60 })
|
||||
|
||||
// The pool of light has to sit under the pointer, not merely exist: the
|
||||
// panel's box measures as the origin here, so the cursor's own coordinates
|
||||
// are what should end up in the gradient. An effect that lit up in a fixed
|
||||
// spot would pass an opacity-only assertion and look broken on screen.
|
||||
expect(glare.style.background).toContain('at 140px 60px')
|
||||
expect(glare.style.opacity).toBe('1')
|
||||
expect(borderGlare.style.opacity).toBe('1')
|
||||
|
||||
fireEvent.mouseLeave(panel)
|
||||
|
||||
expect(glare.style.opacity).toBe('0')
|
||||
expect(borderGlare.style.opacity).toBe('0')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,172 @@
|
||||
// FE-DAWARICH-BADGE-001 to FE-DAWARICH-BADGE-007
|
||||
/**
|
||||
* The one pill the whole Dawarich surface is drawn from, pinned prop by prop.
|
||||
*
|
||||
* It is nine lines of JSX, which is exactly why it is worth a test: the review
|
||||
* list, the accept dialog and the Atlas dialog all render it, so a change here
|
||||
* lands in three places at once and none of their tests would name it as the
|
||||
* culprit.
|
||||
*
|
||||
* What is worth holding still, roughly in the order of what breaks worst:
|
||||
*
|
||||
* - **Icon-only means named.** `children === undefined` is the switch that
|
||||
* turns a badge into a round dot of colour, and it is the same switch that
|
||||
* adds `role="img"` and the accessible name. Lose the pairing and the low
|
||||
* confidence flag, the "source gone" flag and the "source changed" flag all
|
||||
* become unlabelled squares that a screen reader reads as nothing at all.
|
||||
* - **`children === undefined`, not `!children`.** The day header counts its
|
||||
* stays with the array length, so a falsy check would turn a legitimate
|
||||
* count of zero into an unlabelled dot.
|
||||
* - **The tone is the meaning.** Five tones, each a pair of theme tokens; a
|
||||
* warning that quietly maps to the neutral pair still reads as a fact worth
|
||||
* ignoring, which is the opposite of what it is there to say.
|
||||
* - **The type scales with the reader's setting.** Both sizes go through
|
||||
* `--fs-scale-caption`; a raw `fontSize: 11` would look identical in review
|
||||
* and ignore the text-size preference entirely.
|
||||
* - **A badge with something to add gets TREK's tooltip, one without gets
|
||||
* none.** `title` wins over `label` as the hover text, so a pointer user can
|
||||
* be told more than the accessible name says.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { render, screen, act } from '../../../tests/helpers/render'
|
||||
import { fireEvent } from '@testing-library/react'
|
||||
import DawarichBadge from './DawarichBadge'
|
||||
|
||||
type BadgeProps = React.ComponentProps<typeof DawarichBadge>
|
||||
|
||||
// The clock goes in before anything renders, the way Tooltip's own suite does
|
||||
// it: swapping timers out from under a mounted tree leaves whatever it already
|
||||
// scheduled on the real clock. `shouldAdvanceTime` keeps real time moving, so
|
||||
// the locale promise the render helper's provider starts still settles.
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
/**
|
||||
* Stands in for a lucide icon. All the badge does with one is hand it a
|
||||
* className, so that string is the only thing worth asserting about it.
|
||||
*/
|
||||
function StubIcon({ className }: { className?: string }) {
|
||||
return <svg data-testid="badge-icon" className={className} />
|
||||
}
|
||||
|
||||
function badge(props: BadgeProps) {
|
||||
const view = render(<DawarichBadge {...props} />)
|
||||
return { ...view, el: view.container.firstElementChild as HTMLElement }
|
||||
}
|
||||
|
||||
/**
|
||||
* What the badge says on hover, or null when it has nothing to add and is
|
||||
* therefore not wrapped in a tooltip at all. The tooltip opens on a 250 ms
|
||||
* timer, so the clock has to be moved on by hand for either answer to be true
|
||||
* rather than merely early.
|
||||
*/
|
||||
function hoverText(el: HTMLElement): string | null {
|
||||
fireEvent.mouseEnter(el)
|
||||
// One window covers both steps: the 250 ms open timer, and the effect that
|
||||
// measures the trigger afterwards. Until that effect lands the portal is
|
||||
// `visibility: hidden`, which is invisible to a role query as well as to a
|
||||
// reader, so a half-flushed tooltip would read as no tooltip at all.
|
||||
act(() => { vi.advanceTimersByTime(300) })
|
||||
return screen.queryByRole('tooltip')?.textContent ?? null
|
||||
}
|
||||
|
||||
describe('DawarichBadge', () => {
|
||||
it('FE-DAWARICH-BADGE-001: the default pill is neutral, xs, and says nothing on hover', () => {
|
||||
const { el } = badge({ children: '3 stays' })
|
||||
|
||||
expect(el).toHaveTextContent('3 stays')
|
||||
expect(el).toHaveClass('h-[18px]', 'px-1.5', 'bg-surface-secondary', 'text-content-secondary')
|
||||
// A pill that already reads "3 stays" needs no image role and no name of
|
||||
// its own: both would make a screen reader announce the same thing twice.
|
||||
expect(el).not.toHaveAttribute('role')
|
||||
expect(el).not.toHaveAttribute('aria-label')
|
||||
expect(el.style.fontSize).toBe('calc(10px * var(--fs-scale-caption, 1))')
|
||||
expect(el.querySelector('[data-testid="badge-icon"]')).toBeNull()
|
||||
// No title and no label, so there is nothing a tooltip could add.
|
||||
expect(hoverText(el)).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-BADGE-002: sm raises the box, the icon and the type together', () => {
|
||||
const { el } = badge({ icon: StubIcon, size: 'sm', children: '2 h 25 min' })
|
||||
|
||||
expect(el).toHaveClass('h-[20px]', 'px-1.5')
|
||||
expect(el.style.fontSize).toBe('calc(11px * var(--fs-scale-caption, 1))')
|
||||
expect(screen.getByTestId('badge-icon').getAttribute('class')).toBe('w-3 h-3 flex-shrink-0')
|
||||
// The text truncates and the glyph does not: a long name must run out of
|
||||
// room before it squeezes the icon out of shape.
|
||||
expect(el.querySelector('.truncate')).toHaveTextContent('2 h 25 min')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-BADGE-003: an icon-only pill is square, named, and offers its name on hover', () => {
|
||||
const { el } = badge({ icon: StubIcon, tone: 'warning', label: 'Low confidence' })
|
||||
|
||||
expect(el).toHaveAttribute('role', 'img')
|
||||
expect(el).toHaveAttribute('aria-label', 'Low confidence')
|
||||
expect(el).toHaveClass('w-[18px]', 'justify-center', 'bg-warning-soft', 'text-warning')
|
||||
// Side padding would make the circle an oval, and there is no text to pad
|
||||
// away from in the first place.
|
||||
expect(el).not.toHaveClass('px-1.5')
|
||||
expect(el.querySelector('.truncate')).toBeNull()
|
||||
expect(screen.getByTestId('badge-icon').getAttribute('class')).toBe('w-2.5 h-2.5 flex-shrink-0')
|
||||
// No title, so the accessible name doubles as the hover text and a pointer
|
||||
// user is told exactly what a screen reader is told.
|
||||
expect(hoverText(el)).toBe('Low confidence')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-BADGE-004: the square grows with the size, so the dot stays a circle', () => {
|
||||
const { el } = badge({ icon: StubIcon, size: 'sm', label: 'Source gone' })
|
||||
|
||||
expect(el).toHaveClass('h-[20px]', 'w-[20px]', 'justify-center')
|
||||
expect(el).not.toHaveClass('w-[18px]')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-BADGE-005: title is the hover text, label stays the name', () => {
|
||||
const { el } = badge({
|
||||
icon: StubIcon,
|
||||
tone: 'warning',
|
||||
label: 'Low confidence',
|
||||
title: 'Dawarich is not sure this stay happened',
|
||||
})
|
||||
|
||||
// The two are not interchangeable: the name is what the badge is, the title
|
||||
// is what it has to add, and a screen reader would drown in the long one.
|
||||
expect(el).toHaveAttribute('aria-label', 'Low confidence')
|
||||
expect(hoverText(el)).toBe('Dawarich is not sure this stay happened')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-BADGE-006: every tone keeps its own pair of theme tokens', () => {
|
||||
const tones: Array<[NonNullable<BadgeProps['tone']>, string[]]> = [
|
||||
['neutral', ['bg-surface-secondary', 'text-content-secondary']],
|
||||
['quiet', ['bg-surface-secondary', 'text-content-faint']],
|
||||
['accent', ['bg-accent-subtle', 'text-accent-on']],
|
||||
['success', ['bg-success-soft', 'text-success']],
|
||||
['warning', ['bg-warning-soft', 'text-warning']],
|
||||
]
|
||||
|
||||
for (const [tone, classes] of tones) {
|
||||
const { el, unmount } = badge({ tone, children: tone })
|
||||
// Tokens rather than colour literals, or the badge stops following the
|
||||
// user's scheme the moment they pick one.
|
||||
expect(el).toHaveClass(...classes)
|
||||
unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-BADGE-007: a zero is a child, not an absent one', () => {
|
||||
// The day header counts its stays with the array length. Icon-only is
|
||||
// `children === undefined` and not a falsy check for exactly this reason: a
|
||||
// count of 0 that turned into an unlabelled dot would be a day that lost
|
||||
// its number.
|
||||
const { el } = badge({ tone: 'quiet', children: 0 })
|
||||
|
||||
expect(el).toHaveTextContent('0')
|
||||
expect(el).not.toHaveAttribute('role')
|
||||
expect(el).toHaveClass('px-1.5')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,640 @@
|
||||
// FE-DAWARICH-PANEL-001 to FE-DAWARICH-PANEL-033
|
||||
/**
|
||||
* The review panel both shells share, pinned end to end.
|
||||
*
|
||||
* `useDawarichSuggestions` is mocked rather than the network: the hook is
|
||||
* already covered on its own, and driving the panel through six `status`
|
||||
* values, a busy row and a refused accept via MSW would mean six round trips to
|
||||
* assert one branch each. What is NOT mocked is anything the panel renders
|
||||
* itself, `DawarichAcceptDialog` included, because the wiring between a row's
|
||||
* button and that dialog's confirm is exactly the part that would rot silently.
|
||||
*
|
||||
* What is worth pinning here, roughly in the order of what breaks worst:
|
||||
*
|
||||
* - **The panel renders nothing when there is nothing to review.** A connected,
|
||||
* quiet integration is meant to be invisible; the moment that early return
|
||||
* goes, every trip in the app grows a permanent empty card explaining that
|
||||
* Dawarich found nothing.
|
||||
* - **`accept` is the only path that writes.** The dialog closes and the host
|
||||
* is notified only when the hook says the write landed, so a refused accept
|
||||
* has to leave the dialog standing with the user's corrections still in it.
|
||||
* - **The two accept buttons are conditional on there being somewhere to put
|
||||
* the stay.** The planner has no journey list and the journal has no trip
|
||||
* list; offering the missing one opens an empty picker.
|
||||
* - **A shrinking place count means somebody deleted what an acceptance
|
||||
* created**, which puts the stay back into review on the server. If that
|
||||
* effect stops firing, the row stays hidden until a full reload.
|
||||
* - **The phone shell paints from `--m-*`.** Both shells run this one
|
||||
* component, so every palette fork inside it is real behaviour that no
|
||||
* mobile-screen test covers.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { render, screen, act, within } from '../../../tests/helpers/render'
|
||||
import { fireEvent } from '@testing-library/react'
|
||||
import type { DawarichSuggestion } from '@trek/shared'
|
||||
import type { Place } from '../../types'
|
||||
import type { DawarichSuggestionsState } from '../../hooks/useDawarichSuggestions'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import DawarichSuggestionsPanel from './DawarichSuggestionsPanel'
|
||||
|
||||
// The hook is the panel's whole world: status, rows, the busy row and the three
|
||||
// mutations. Held in a `let` the factory reads lazily, so each test hands the
|
||||
// panel a different world without re-importing the component.
|
||||
let S: DawarichSuggestionsState
|
||||
const seenFilter = vi.fn()
|
||||
vi.mock('../../hooks/useDawarichSuggestions', () => ({
|
||||
useDawarichSuggestions: (filter?: { tripId?: number }) => {
|
||||
seenFilter(filter)
|
||||
return S
|
||||
},
|
||||
}))
|
||||
|
||||
// Both the panel and the accept dialog read this module, and the relative
|
||||
// specifier resolves to the same file from either, so one mock flips the whole
|
||||
// tree between the desktop tokens and the phone's own palette.
|
||||
let phone = false
|
||||
vi.mock('../../mobile/useIsPhone', () => ({ useIsPhone: () => phone }))
|
||||
|
||||
function stay(over: Partial<DawarichSuggestion> & { id: number; localDate: string }): DawarichSuggestion {
|
||||
return {
|
||||
id: over.id,
|
||||
sourceVisitId: String(over.id),
|
||||
tripId: over.tripId ?? null,
|
||||
tripTitle: over.tripTitle ?? null,
|
||||
name: over.name ?? 'Cafe Reichard',
|
||||
lat: over.lat ?? 50.94,
|
||||
lng: over.lng ?? 6.96,
|
||||
startedAt: over.startedAt ?? `${over.localDate}T10:15:00+02:00`,
|
||||
endedAt: over.endedAt ?? `${over.localDate}T12:40:00+02:00`,
|
||||
durationMinutes: over.durationMinutes ?? 145,
|
||||
localDate: over.localDate,
|
||||
sourceStatus: over.sourceStatus ?? 'suggested',
|
||||
confidence: over.confidence ?? null,
|
||||
confidenceBand: over.confidenceBand ?? null,
|
||||
state: over.state ?? 'new',
|
||||
target: over.target ?? null,
|
||||
acceptedPlaceId: over.acceptedPlaceId ?? null,
|
||||
acceptedJournalEntryId: over.acceptedJournalEntryId ?? null,
|
||||
acceptedBucketListItemId: over.acceptedBucketListItemId ?? null,
|
||||
sourceChanged: over.sourceChanged ?? false,
|
||||
sourceMissing: over.sourceMissing ?? false,
|
||||
matchedBucketListItemId: over.matchedBucketListItemId ?? null,
|
||||
matchedBucketListName: over.matchedBucketListName ?? null,
|
||||
countryCode: over.countryCode ?? null,
|
||||
firstSeenAt: over.firstSeenAt ?? '2026-09-10T06:00:00Z',
|
||||
lastSeenAt: over.lastSeenAt ?? '2026-09-10T06:00:00Z',
|
||||
}
|
||||
}
|
||||
|
||||
const accept = vi.fn<(id: number, body: unknown) => Promise<boolean>>()
|
||||
const dismiss = vi.fn<(id: number) => Promise<void>>()
|
||||
const restore = vi.fn<(id: number) => Promise<void>>()
|
||||
const reload = vi.fn()
|
||||
|
||||
function hookState(over: Partial<DawarichSuggestionsState> = {}): DawarichSuggestionsState {
|
||||
return {
|
||||
suggestions: [],
|
||||
status: 'ready',
|
||||
lastSyncAt: null,
|
||||
lastSyncState: 'ok',
|
||||
lastSyncError: null,
|
||||
busyId: null,
|
||||
reload,
|
||||
accept,
|
||||
dismiss,
|
||||
restore,
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
/** Only the one field the panel's place-count effect reads. */
|
||||
function places(count: number): Place[] {
|
||||
return Array.from({ length: count }, (_, i) => ({ id: i + 1 })) as unknown as Place[]
|
||||
}
|
||||
|
||||
const TRIPS = [{ id: 5, label: 'Cologne' }]
|
||||
const JOURNALS = [{ id: 9, label: 'Rhine notes' }]
|
||||
|
||||
function panel(props: Partial<React.ComponentProps<typeof DawarichSuggestionsPanel>> = {}) {
|
||||
return render(<DawarichSuggestionsPanel {...props} />)
|
||||
}
|
||||
|
||||
/** The collapsible header, which is also the only element carrying aria-expanded. */
|
||||
function header(): HTMLElement {
|
||||
return screen.getByRole('button', { name: /From Dawarich/ })
|
||||
}
|
||||
|
||||
/** The row card holding a given stay name, for scoping a query to one row. */
|
||||
function rowOf(container: HTMLElement, name: string): HTMLElement {
|
||||
const row = within(container).getByText(name).closest('.items-stretch')
|
||||
if (!row) throw new Error(`no row found for ${name}`)
|
||||
return row as HTMLElement
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
phone = false
|
||||
S = hookState()
|
||||
seenFilter.mockReset()
|
||||
accept.mockReset().mockResolvedValue(true)
|
||||
dismiss.mockReset().mockResolvedValue(undefined)
|
||||
restore.mockReset().mockResolvedValue(undefined)
|
||||
reload.mockReset()
|
||||
useTripStore.setState({ places: [] })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
useTripStore.setState({ places: [] })
|
||||
})
|
||||
|
||||
describe('DawarichSuggestionsPanel: whether it shows up at all', () => {
|
||||
it('FE-DAWARICH-PANEL-001: an addon nobody switched on renders nothing', () => {
|
||||
S = hookState({ status: 'idle' })
|
||||
const { container } = panel()
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-002: connected and quiet is invisible, not an empty card', () => {
|
||||
// Read successfully, nothing pending and nothing in the history: the panel
|
||||
// stays out of the rail rather than explaining that it found nothing.
|
||||
S = hookState({ status: 'ready', suggestions: [] })
|
||||
const { container } = panel()
|
||||
expect(container).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-003: it does show up while it is still reading, before it knows', () => {
|
||||
S = hookState({ status: 'loading', suggestions: [] })
|
||||
panel()
|
||||
// Twice: once under the title, once in the opened body.
|
||||
expect(screen.getAllByText('Reading Dawarich…')).toHaveLength(2)
|
||||
expect(header()).toHaveAttribute('aria-expanded', 'true')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-004: a failed read is said in the danger colour, without the stale error under it', () => {
|
||||
S = hookState({ status: 'unavailable', lastSyncError: 'Dawarich rejected the API key.' })
|
||||
const { container } = panel()
|
||||
|
||||
const line = container.querySelector('p.text-danger')
|
||||
expect(line).not.toBeNull()
|
||||
expect(line).toHaveTextContent('Dawarich could not be read.')
|
||||
// The sync error belongs above a list that did load. Beside "could not be
|
||||
// read" it is the same news twice in two different wordings.
|
||||
expect(screen.queryByText('Dawarich rejected the API key.')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-005: not-connected and offline each get their own sentence', () => {
|
||||
S = hookState({ status: 'disconnected' })
|
||||
const { unmount } = panel()
|
||||
expect(screen.getAllByText('Connect Dawarich in Settings to see your stays here.')).toHaveLength(2)
|
||||
unmount()
|
||||
|
||||
S = hookState({ status: 'offline' })
|
||||
panel()
|
||||
expect(screen.getAllByText('The recorded route needs a connection')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-006: freshness reads as a relative time, and says so when there is none', () => {
|
||||
S = hookState({
|
||||
suggestions: [stay({ id: 1, localDate: '2026-09-10' })],
|
||||
lastSyncAt: new Date(Date.now() - 120_000).toISOString(),
|
||||
})
|
||||
const { unmount } = panel()
|
||||
// "checked 2 minutes ago" answers the question; a stamp makes the reader
|
||||
// do the subtraction.
|
||||
expect(header()).toHaveTextContent(/checked 2 minutes ago/)
|
||||
unmount()
|
||||
|
||||
S = hookState({ suggestions: [stay({ id: 1, localDate: '2026-09-10' })], lastSyncAt: null })
|
||||
panel()
|
||||
expect(header()).toHaveTextContent('Not checked yet')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-007: the trip filter is handed to the hook', () => {
|
||||
S = hookState({ suggestions: [stay({ id: 1, localDate: '2026-09-10' })] })
|
||||
panel({ tripId: 5 })
|
||||
expect(seenFilter).toHaveBeenCalledWith({ tripId: 5 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('DawarichSuggestionsPanel: the list', () => {
|
||||
it('FE-DAWARICH-PANEL-008: stays are grouped by day, newest day first, each day counted', () => {
|
||||
S = hookState({
|
||||
suggestions: [
|
||||
stay({ id: 1, localDate: '2026-09-10', name: 'Museum Ludwig', startedAt: '2026-09-10T18:00:00+02:00' }),
|
||||
stay({ id: 2, localDate: '2026-09-10', name: 'Cafe Reichard' }),
|
||||
stay({ id: 3, localDate: '2026-09-11', name: 'Koelner Dom' }),
|
||||
],
|
||||
})
|
||||
const { container } = panel({ trips: TRIPS })
|
||||
|
||||
const headings = Array.from(container.querySelectorAll('.uppercase')).map(node => node.textContent)
|
||||
expect(headings).toEqual(['Fri, Sep 11', 'Thu, Sep 10'])
|
||||
// The badge in the header repeats what the open list adds up to.
|
||||
expect(header()).toHaveTextContent('3')
|
||||
// The times, which are the only thing telling two stays on one day apart.
|
||||
const row = rowOf(container, 'Cafe Reichard')
|
||||
expect(row).toHaveTextContent('10:15')
|
||||
expect(row).toHaveTextContent('12:40')
|
||||
expect(row).toHaveTextContent('2 h 25 min')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-009: collapsed to start, and the header is the way back in', () => {
|
||||
S = hookState({ suggestions: [stay({ id: 1, localDate: '2026-09-10', name: 'Museum Ludwig' })] })
|
||||
panel({ initiallyCollapsed: true, trips: TRIPS })
|
||||
|
||||
expect(header()).toHaveAttribute('aria-expanded', 'false')
|
||||
expect(screen.queryByText('Museum Ludwig')).toBeNull()
|
||||
|
||||
fireEvent.click(header())
|
||||
|
||||
expect(header()).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(screen.getByText('Museum Ludwig')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-010: bare drops the card and its header, and cannot be collapsed shut', () => {
|
||||
S = hookState({
|
||||
suggestions: [stay({ id: 1, localDate: '2026-09-10', name: 'Museum Ludwig' })],
|
||||
lastSyncAt: null,
|
||||
})
|
||||
// The phone journey opens this list inside a sheet that already carries a
|
||||
// title, and `initiallyCollapsed` must not fold it away in there.
|
||||
const { container } = panel({ bare: true, initiallyCollapsed: true, trips: TRIPS })
|
||||
|
||||
expect(screen.queryByRole('button', { name: /From Dawarich/ })).toBeNull()
|
||||
expect(screen.getByText('Museum Ludwig')).toBeInTheDocument()
|
||||
// Read the property rather than the attribute: what matters is that the
|
||||
// card is gone, not how React chooses to serialise an empty className.
|
||||
expect(container.querySelector('section')?.className).toBe('')
|
||||
// The freshness line survives the missing header, as a plain paragraph.
|
||||
expect(screen.getByText('Not checked yet')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-011: a sync error rides above a list that did load', () => {
|
||||
S = hookState({
|
||||
status: 'ready',
|
||||
suggestions: [stay({ id: 1, localDate: '2026-09-10' })],
|
||||
lastSyncError: 'Dawarich asked TREK to slow down. Try again shortly.',
|
||||
})
|
||||
panel({ trips: TRIPS })
|
||||
expect(screen.getByText('Dawarich asked TREK to slow down. Try again shortly.')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-012: a row carries the flags worth interrupting for, and gone beats changed', () => {
|
||||
S = hookState({
|
||||
suggestions: [
|
||||
stay({
|
||||
id: 1,
|
||||
localDate: '2026-09-10',
|
||||
name: 'Museum Ludwig',
|
||||
confidenceBand: 'low',
|
||||
// Both set on purpose: a stay that vanished upstream may well have
|
||||
// changed before it went, and saying both is two warnings about one
|
||||
// row where only the fatal one matters.
|
||||
sourceChanged: true,
|
||||
sourceMissing: true,
|
||||
}),
|
||||
],
|
||||
})
|
||||
panel({ trips: TRIPS })
|
||||
|
||||
expect(screen.getByRole('img', { name: 'Unsure' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('img', { name: 'Gone from Dawarich' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('img', { name: 'Changed in Dawarich' })).toBeNull()
|
||||
expect(screen.getByText(/no longer exists in Dawarich/)).toBeInTheDocument()
|
||||
expect(screen.queryByText(/has changed in Dawarich/)).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-013: a stay that only changed says exactly that, in full', () => {
|
||||
S = hookState({ suggestions: [stay({ id: 1, localDate: '2026-09-10', sourceChanged: true })] })
|
||||
panel({ trips: TRIPS })
|
||||
|
||||
expect(screen.getByRole('img', { name: 'Changed in Dawarich' })).toBeInTheDocument()
|
||||
expect(screen.getByText(/has changed in Dawarich since you used it/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-014: the trip name shows only where rows can come from more than one trip', () => {
|
||||
const rows = [stay({ id: 1, localDate: '2026-09-10', tripId: 5, tripTitle: 'Cologne' })]
|
||||
S = hookState({ suggestions: rows })
|
||||
const { unmount } = panel({ trips: TRIPS })
|
||||
expect(screen.getByText('Cologne')).toBeInTheDocument()
|
||||
unmount()
|
||||
|
||||
// Inside one trip's rail every row is from that trip, so the name is noise.
|
||||
S = hookState({ suggestions: rows })
|
||||
panel({ tripId: 5, trips: TRIPS })
|
||||
expect(screen.queryByText('Cologne')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-015: a stay with no trip behind it gets no empty badge', () => {
|
||||
S = hookState({ suggestions: [stay({ id: 1, localDate: '2026-09-10', tripId: null, tripTitle: null })] })
|
||||
const { container } = panel({ trips: TRIPS })
|
||||
// Two badges on the row, the clock and the duration, and nothing else.
|
||||
expect(rowOf(container, 'Cafe Reichard').querySelectorAll('.rounded-full.font-semibold')).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('DawarichSuggestionsPanel: acting on a stay', () => {
|
||||
it('FE-DAWARICH-PANEL-016: an action is offered only where there is somewhere to put the stay', () => {
|
||||
S = hookState({ suggestions: [stay({ id: 1, localDate: '2026-09-10' })] })
|
||||
const { unmount } = panel({ trips: [], journals: [] })
|
||||
|
||||
// No trips and no journeys: only "not a place I visited" is still an answer.
|
||||
expect(screen.queryByRole('button', { name: 'Add as a place' })).toBeNull()
|
||||
expect(screen.queryByRole('button', { name: 'Write a journal entry' })).toBeNull()
|
||||
expect(screen.getByRole('button', { name: 'Not a place I visited' })).toBeInTheDocument()
|
||||
unmount()
|
||||
|
||||
S = hookState({ suggestions: [stay({ id: 1, localDate: '2026-09-10' })] })
|
||||
panel({ trips: TRIPS, journals: JOURNALS })
|
||||
expect(screen.getByRole('button', { name: 'Add as a place' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Write a journal entry' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-017: dismissing hands the row id straight to the hook', () => {
|
||||
S = hookState({ suggestions: [stay({ id: 42, localDate: '2026-09-10' })] })
|
||||
panel({ trips: TRIPS })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Not a place I visited' }))
|
||||
|
||||
expect(dismiss).toHaveBeenCalledWith(42)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-018: the row being written is the row that goes dead, and only that one', () => {
|
||||
S = hookState({
|
||||
suggestions: [
|
||||
stay({ id: 42, localDate: '2026-09-10', name: 'Museum Ludwig' }),
|
||||
stay({ id: 43, localDate: '2026-09-11', name: 'Koelner Dom' }),
|
||||
],
|
||||
busyId: 42,
|
||||
})
|
||||
const { container } = panel({ trips: TRIPS })
|
||||
|
||||
expect(within(rowOf(container, 'Museum Ludwig')).getByRole('button', { name: 'Add as a place' })).toBeDisabled()
|
||||
expect(within(rowOf(container, 'Koelner Dom')).getByRole('button', { name: 'Add as a place' })).toBeEnabled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-019: accepting opens the review step and reports a write that landed', async () => {
|
||||
const onAccepted = vi.fn()
|
||||
const daysForTrip = vi.fn((tripId: number) => [{ id: 70 + tripId, label: 'Day 1', badge: 'Thu, Sep 10' }])
|
||||
S = hookState({ suggestions: [stay({ id: 42, localDate: '2026-09-10', name: 'Museum Ludwig' })] })
|
||||
panel({ trips: TRIPS, journals: JOURNALS, daysForTrip, onAccepted })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add as a place' }))
|
||||
|
||||
// The dialog opens on the row that was pressed, for the target that was pressed.
|
||||
expect(screen.getByRole('heading', { name: 'Add this stay as a place' })).toBeInTheDocument()
|
||||
expect(daysForTrip).toHaveBeenCalledWith(5)
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add place' }))
|
||||
})
|
||||
|
||||
expect(accept).toHaveBeenCalledWith(42, expect.objectContaining({ target: 'place', tripId: 5 }))
|
||||
// Only now: the host refreshes its own list off the back of a write that landed.
|
||||
expect(onAccepted).toHaveBeenCalledWith(expect.objectContaining({ id: 42 }))
|
||||
expect(screen.queryByRole('heading', { name: 'Add this stay as a place' })).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-020: a refused write leaves the dialog standing, with the correction still in it', async () => {
|
||||
const onAccepted = vi.fn()
|
||||
accept.mockResolvedValue(false)
|
||||
S = hookState({ suggestions: [stay({ id: 42, localDate: '2026-09-10' })] })
|
||||
panel({ trips: TRIPS, journals: JOURNALS, onAccepted })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Write a journal entry' }))
|
||||
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Corrected name' } })
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add entry' }))
|
||||
})
|
||||
|
||||
expect(accept).toHaveBeenCalledWith(
|
||||
42,
|
||||
expect.objectContaining({ target: 'journal', journalId: 9, name: 'Corrected name' }),
|
||||
)
|
||||
// Closing here would throw away what the user typed and leave them nothing
|
||||
// to retry with.
|
||||
expect(screen.getByRole('heading', { name: 'Write a journal entry' })).toBeInTheDocument()
|
||||
expect(screen.getByLabelText('Name')).toHaveValue('Corrected name')
|
||||
expect(onAccepted).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-021: a host that wants no callback still gets its dialog closed', async () => {
|
||||
S = hookState({ suggestions: [stay({ id: 42, localDate: '2026-09-10' })] })
|
||||
panel({ trips: TRIPS, journals: JOURNALS })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Write a journal entry' }))
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add entry' }))
|
||||
})
|
||||
|
||||
expect(accept).toHaveBeenCalledTimes(1)
|
||||
expect(screen.queryByRole('heading', { name: 'Write a journal entry' })).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-022: cancelling writes nothing', () => {
|
||||
S = hookState({ suggestions: [stay({ id: 42, localDate: '2026-09-10' })] })
|
||||
panel({ trips: TRIPS, journals: JOURNALS })
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add as a place' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
|
||||
expect(screen.queryByRole('heading', { name: 'Add this stay as a place' })).toBeNull()
|
||||
expect(accept).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DawarichSuggestionsPanel: what was already dealt with', () => {
|
||||
const handledRows = [
|
||||
stay({ id: 1, localDate: '2026-09-10', name: 'Museum Ludwig', state: 'accepted', target: 'place' }),
|
||||
stay({ id: 2, localDate: '2026-09-09', name: 'Koelner Dom', state: 'dismissed' }),
|
||||
// Accepted before `target` was recorded: the wording falls back rather than
|
||||
// printing a missing translation key at somebody.
|
||||
stay({ id: 3, localDate: '2026-09-08', name: 'Rheinpark', state: 'accepted', target: null }),
|
||||
]
|
||||
|
||||
it('FE-DAWARICH-PANEL-023: the history stays folded away until it is asked for', () => {
|
||||
S = hookState({ suggestions: handledRows })
|
||||
panel({ trips: TRIPS })
|
||||
|
||||
expect(screen.queryByText('Museum Ludwig')).toBeNull()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Show 3 already dealt with' }))
|
||||
|
||||
expect(screen.getByText('Museum Ludwig')).toBeInTheDocument()
|
||||
expect(screen.getByText('Added as a place')).toBeInTheDocument()
|
||||
expect(screen.getByText('Dismissed')).toBeInTheDocument()
|
||||
expect(screen.getByText('In the journal')).toBeInTheDocument()
|
||||
// A history row carries its own date, which the open list keeps in the day
|
||||
// heading it no longer sits under.
|
||||
expect(screen.getByText('Thu, Sep 10')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Hide the ones already dealt with' }))
|
||||
expect(screen.queryByText('Museum Ludwig')).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-024: only a dismissal can be put back, and it goes through the hook', () => {
|
||||
S = hookState({ suggestions: handledRows })
|
||||
const { container } = panel({ trips: TRIPS })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Show 3 already dealt with' }))
|
||||
|
||||
// An accepted stay already produced a place or an entry; "put back" there
|
||||
// would mean silently unpicking something the user wrote.
|
||||
expect(within(rowOf(container, 'Museum Ludwig')).queryByRole('button', { name: 'Put back' })).toBeNull()
|
||||
// And no history row offers the accept buttons a second time.
|
||||
expect(within(rowOf(container, 'Koelner Dom')).queryByRole('button', { name: 'Add as a place' })).toBeNull()
|
||||
|
||||
fireEvent.click(within(rowOf(container, 'Koelner Dom')).getByRole('button', { name: 'Put back' }))
|
||||
|
||||
expect(restore).toHaveBeenCalledWith(2)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-025: a restore in flight disables the button that started it', () => {
|
||||
S = hookState({ suggestions: handledRows, busyId: 2 })
|
||||
const { container } = panel({ trips: TRIPS })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Show 3 already dealt with' }))
|
||||
|
||||
expect(within(rowOf(container, 'Koelner Dom')).getByRole('button', { name: 'Put back' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-026: nothing left open says so instead of showing an empty day', () => {
|
||||
S = hookState({ suggestions: [handledRows[0]] })
|
||||
const { container } = panel({ trips: TRIPS })
|
||||
|
||||
expect(screen.getByText('Everything recorded here has been dealt with.')).toBeInTheDocument()
|
||||
// And the count badge goes with the last open row rather than showing a zero.
|
||||
expect(container.querySelector('.text-accent-text')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DawarichSuggestionsPanel: the deleted-place hint', () => {
|
||||
it('FE-DAWARICH-PANEL-027: a shrinking place count reloads, a growing one does not', () => {
|
||||
useTripStore.setState({ places: places(3) })
|
||||
S = hookState({ suggestions: [stay({ id: 1, localDate: '2026-09-10' })] })
|
||||
panel({ tripId: 5, trips: TRIPS })
|
||||
|
||||
// Mounting is not a shrink.
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
|
||||
// Deleting the place an acceptance created is how somebody says "not that
|
||||
// one" after the fact, and the server puts the stay back into review.
|
||||
act(() => { useTripStore.setState({ places: places(2) }) })
|
||||
expect(reload).toHaveBeenCalledTimes(1)
|
||||
|
||||
// A place appearing is usually this panel's own doing.
|
||||
act(() => { useTripStore.setState({ places: places(6) }) })
|
||||
expect(reload).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-028: outside a trip the place count is not this panel\'s business', () => {
|
||||
useTripStore.setState({ places: places(3) })
|
||||
S = hookState({ suggestions: [stay({ id: 1, localDate: '2026-09-10' })] })
|
||||
// The journal shell mounts this without a trip, and whatever trip happens to
|
||||
// be loaded has nothing to do with the rows it shows.
|
||||
panel({ trips: TRIPS })
|
||||
|
||||
act(() => { useTripStore.setState({ places: places(1) }) })
|
||||
|
||||
expect(reload).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DawarichSuggestionsPanel: the phone shell', () => {
|
||||
it('FE-DAWARICH-PANEL-029: the phone paints from its own palette, header to action pill', () => {
|
||||
phone = true
|
||||
S = hookState({
|
||||
suggestions: [
|
||||
stay({ id: 1, localDate: '2026-09-10', name: 'Museum Ludwig', sourceChanged: true }),
|
||||
stay({ id: 2, localDate: '2026-09-09', name: 'Koelner Dom', state: 'dismissed' }),
|
||||
],
|
||||
lastSyncAt: new Date(Date.now() - 60_000).toISOString(),
|
||||
})
|
||||
const { container } = panel({ trips: TRIPS, journals: JOURNALS })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Show 1 already dealt with' }))
|
||||
|
||||
// A card in the desktop surface tokens glares inside the mobile shell, and
|
||||
// neither token set exists outside its own shell, so every surface here has
|
||||
// to come from the `--m-*` palette.
|
||||
expect(container.querySelector('section')?.className).toContain('var(--m-ic)')
|
||||
expect(header().className).toContain('var(--m-inner)')
|
||||
expect(container.querySelector('.bg-m-card')).not.toBeNull()
|
||||
expect(container.querySelector('.bg-m-act')).not.toBeNull()
|
||||
expect(container.querySelector('.text-m-ink')).not.toBeNull()
|
||||
expect(container.querySelectorAll('.text-m-muted').length).toBeGreaterThan(0)
|
||||
expect(container.querySelector('.text-m-faint')).not.toBeNull()
|
||||
// The actions keep their accessible names, which is what makes dropping the
|
||||
// hover-only tooltip on a touch device cost nothing.
|
||||
expect(screen.getByRole('button', { name: 'Add as a place' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-030: bare on a phone, with nothing left open', () => {
|
||||
phone = true
|
||||
S = hookState({
|
||||
suggestions: [stay({ id: 1, localDate: '2026-09-10', state: 'accepted', target: 'journal' })],
|
||||
lastSyncAt: null,
|
||||
})
|
||||
const { container } = panel({ bare: true, trips: TRIPS })
|
||||
|
||||
expect(screen.queryByRole('button', { name: /From Dawarich/ })).toBeNull()
|
||||
expect(screen.getByText('Everything recorded here has been dealt with.').className).toContain('text-m-muted')
|
||||
expect(screen.getByText('Not checked yet').className).toContain('text-m-muted')
|
||||
expect(container.querySelector('section')?.className).toBe('')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-PANEL-033: folded shut on a phone, the arrow that says so comes from the phone palette', () => {
|
||||
phone = true
|
||||
S = hookState({ suggestions: [stay({ id: 1, localDate: '2026-09-10', name: 'Museum Ludwig' })] })
|
||||
// The planner mounts this one collapsed, so on a phone the right-pointing
|
||||
// arrow is the header's ordinary state and not an edge case. It is also the
|
||||
// only part of the header an expanded phone never paints, which is exactly
|
||||
// how a desktop token would survive in there unnoticed.
|
||||
const { container } = panel({ initiallyCollapsed: true, trips: TRIPS })
|
||||
|
||||
expect(header()).toHaveAttribute('aria-expanded', 'false')
|
||||
expect(screen.queryByText('Museum Ludwig')).toBeNull()
|
||||
expect(container.querySelector('.lucide-chevron-right.text-m-faint')).not.toBeNull()
|
||||
expect(container.querySelector('.lucide-chevron-down')).toBeNull()
|
||||
expect(container.querySelector('.text-content-faint')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DawarichSuggestionsPanel: the desktop tooltip', () => {
|
||||
it('FE-DAWARICH-PANEL-031: a row action explains itself on focus, where there is a pointer to do it with', () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
try {
|
||||
S = hookState({ suggestions: [stay({ id: 1, localDate: '2026-09-10' })] })
|
||||
panel({ trips: TRIPS })
|
||||
|
||||
fireEvent.focus(screen.getByRole('button', { name: 'Not a place I visited' }))
|
||||
act(() => { vi.advanceTimersByTime(300) })
|
||||
|
||||
// The icon is the whole button, so without this a square is a mystery to
|
||||
// anybody who has not pressed one before. Reaching it by keyboard is the
|
||||
// one route where there is no hover to discover it with.
|
||||
expect(screen.getByRole('tooltip')).toHaveTextContent('Not a place I visited')
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('DawarichSuggestionsPanel: open and handled in the same list', () => {
|
||||
it('FE-DAWARICH-PANEL-032: the two halves are counted separately and only the open half gets days', () => {
|
||||
S = hookState({
|
||||
suggestions: [
|
||||
stay({ id: 1, localDate: '2026-09-10', name: 'Museum Ludwig' }),
|
||||
stay({ id: 2, localDate: '2026-09-09', name: 'Koelner Dom', state: 'accepted', target: 'place' }),
|
||||
stay({ id: 3, localDate: '2026-09-08', name: 'Rheinpark', state: 'dismissed' }),
|
||||
],
|
||||
})
|
||||
const { container } = panel({ trips: TRIPS })
|
||||
|
||||
// Counting all three would send somebody looking for work that is done.
|
||||
expect(container.querySelector('.bg-accent')).toHaveTextContent('1')
|
||||
expect(screen.getByRole('button', { name: 'Show 2 already dealt with' })).toBeInTheDocument()
|
||||
// And the day rail is built from the open half alone: a heading for a day
|
||||
// whose only stay was dismissed is an empty day with a coloured dot on it.
|
||||
expect(container.querySelectorAll('.uppercase')).toHaveLength(1)
|
||||
expect(screen.getByText('Thu, Sep 10')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,22 @@
|
||||
// FE-DAWARICH-ATLASMODEL-001 to FE-DAWARICH-ATLASMODEL-010
|
||||
// FE-DAWARICH-ATLASMODEL-001 to FE-DAWARICH-ATLASMODEL-014
|
||||
/**
|
||||
* The Atlas dialog's arithmetic, with no React around it.
|
||||
*
|
||||
* Everything here is small enough to look correct and wrong enough to matter if
|
||||
* it is not. Three of the five carry a real trap:
|
||||
*
|
||||
* 1. `orderedMatches` sorts on two keys with a hand-written comparator that
|
||||
* never returns 0. That is fine for ordering and a hazard for anything else,
|
||||
* so the cases below check that the order is the same whichever way round
|
||||
* the input arrives and that two wishes reached at the same moment both
|
||||
* survive the sort rather than one of them being swapped away.
|
||||
* 2. `countryLabel` runs on whatever `Intl` the device shipped. A WebView
|
||||
* without `Intl.DisplayNames` throws, one with a partial region table
|
||||
* answers `undefined`, and both have to end up as Dawarich's own spelling
|
||||
* rather than as a crash or an empty label beside a flag.
|
||||
* 3. `formatDistance` switches units at exactly a kilometre, which is the one
|
||||
* input a refactor gets wrong.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import type { DawarichAtlasCountry, DawarichBucketMatch } from '@trek/shared'
|
||||
import {
|
||||
@@ -67,6 +85,32 @@ describe('orderedMatches', () => {
|
||||
orderedMatches(input)
|
||||
expect(input.map(m => m.itemId)).toEqual([1, 2])
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASMODEL-011: the order they arrive in does not change the order they are shown in', () => {
|
||||
// Both arms of both comparisons. A comparator that answers consistently one
|
||||
// way round and not the other sorts whatever the scan happened to return,
|
||||
// which is a list that reshuffles itself between two identical scans.
|
||||
const ticked = match({ itemId: 1, alreadyVisited: true })
|
||||
const openWish = match({ itemId: 2 })
|
||||
expect(orderedMatches([ticked, openWish]).map(m => m.itemId)).toEqual([2, 1])
|
||||
expect(orderedMatches([openWish, ticked]).map(m => m.itemId)).toEqual([2, 1])
|
||||
|
||||
const older = match({ itemId: 3, match: { at: '2026-01-02T10:00:00Z', minutes: 30, distanceMeters: 10, points: 3 } })
|
||||
const newer = match({ itemId: 4, match: { at: '2026-06-02T10:00:00Z', minutes: 30, distanceMeters: 10, points: 3 } })
|
||||
expect(orderedMatches([older, newer]).map(m => m.itemId)).toEqual([4, 3])
|
||||
expect(orderedMatches([newer, older]).map(m => m.itemId)).toEqual([4, 3])
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASMODEL-012: two wishes reached in the same moment both survive the sort', () => {
|
||||
// The comparator never answers 0, so equal timestamps are reported as "swap"
|
||||
// in both directions. Ordering them either way is fine; losing one is not.
|
||||
const at = '2026-08-02T11:00:00Z'
|
||||
const ordered = orderedMatches([
|
||||
match({ itemId: 1, match: { at, minutes: 95, distanceMeters: 30, points: 40 } }),
|
||||
match({ itemId: 2, match: { at, minutes: 120, distanceMeters: 55, points: 51 } }),
|
||||
])
|
||||
expect(ordered.map(m => m.itemId).sort((a, b) => a - b)).toEqual([1, 2])
|
||||
})
|
||||
})
|
||||
|
||||
describe('newCountries', () => {
|
||||
@@ -89,6 +133,28 @@ describe('countryLabel', () => {
|
||||
// name a reader would recognise.
|
||||
expect(countryLabel('ZZZZ', 'Freedonia', 'en')).toBe('Freedonia')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASMODEL-013: a runtime whose Intl names nothing still labels the row', () => {
|
||||
// The other half of the fallback, and the one no desktop browser reproduces:
|
||||
// a WebView that ships Intl.DisplayNames with a partial region table answers
|
||||
// `undefined` instead of throwing, and an empty string beside a flag is a
|
||||
// row nobody can identify.
|
||||
const real = Intl.DisplayNames
|
||||
Object.defineProperty(Intl, 'DisplayNames', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: class {
|
||||
of(): string | undefined {
|
||||
return undefined
|
||||
}
|
||||
},
|
||||
})
|
||||
try {
|
||||
expect(countryLabel('NL', 'Netherlands', 'en')).toBe('Netherlands')
|
||||
} finally {
|
||||
Object.defineProperty(Intl, 'DisplayNames', { configurable: true, writable: true, value: real })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('cityLine', () => {
|
||||
@@ -110,4 +176,13 @@ describe('formatDistance', () => {
|
||||
expect(formatDistance(999, t)).toBe('dawarich.bucket.metersAway:{"meters":999}')
|
||||
expect(formatDistance(1400, t)).toBe('dawarich.bucket.kilometersAway:{"km":"1.4"}')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-ATLASMODEL-014: exactly a kilometre is already a kilometre', () => {
|
||||
// The switch is `< 1000`, so 1000 belongs to the other unit. Off by one here
|
||||
// reads as "1000 m away", which is the phrasing the rule exists to avoid.
|
||||
expect(formatDistance(1000, t)).toBe('dawarich.bucket.kilometersAway:{"km":"1.0"}')
|
||||
// One decimal, rounded, not truncated: 1049 and 1051 are not the same walk.
|
||||
expect(formatDistance(1049, t)).toBe('dawarich.bucket.kilometersAway:{"km":"1.0"}')
|
||||
expect(formatDistance(1051, t)).toBe('dawarich.bucket.kilometersAway:{"km":"1.1"}')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-DAWARICH-SUGMODEL-001 to FE-DAWARICH-SUGMODEL-012
|
||||
// FE-DAWARICH-SUGMODEL-001 to FE-DAWARICH-SUGMODEL-014
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import type { DawarichSuggestion } from '@trek/shared'
|
||||
import {
|
||||
@@ -74,6 +74,24 @@ describe('groupByDay', () => {
|
||||
it('FE-DAWARICH-SUGMODEL-003: nothing in, nothing out', () => {
|
||||
expect(groupByDay([])).toEqual([])
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGMODEL-013: a day that already reads in order is left in it', () => {
|
||||
// Three stays rather than two: with two, a comparator that answered the
|
||||
// same thing both ways would still look right half the time.
|
||||
const input = [
|
||||
stay({ id: 1, localDate: '2026-09-10', startedAt: '2026-09-10T09:00:00+02:00' }),
|
||||
stay({ id: 2, localDate: '2026-09-10', startedAt: '2026-09-10T18:00:00+02:00' }),
|
||||
stay({ id: 3, localDate: '2026-09-10', startedAt: '2026-09-10T13:30:00+02:00' }),
|
||||
]
|
||||
|
||||
const days = groupByDay(input)
|
||||
|
||||
expect(days).toHaveLength(1)
|
||||
expect(days[0].stays.map(s => s.id)).toEqual([1, 3, 2])
|
||||
// The list handed in belongs to the store. Sorting it in place would
|
||||
// reorder what the panel is rendering from underneath it.
|
||||
expect(input.map(s => s.id)).toEqual([1, 2, 3])
|
||||
})
|
||||
})
|
||||
|
||||
describe('clockOf / timeRange', () => {
|
||||
@@ -115,6 +133,16 @@ describe('formatDayHeading', () => {
|
||||
it('FE-DAWARICH-SUGMODEL-010: an unparseable date is shown as it came', () => {
|
||||
expect(formatDayHeading('not-a-date', 'en-GB')).toBe('not-a-date')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGMODEL-014: a date missing its month or its day is shown as it came too', () => {
|
||||
// Each guard on its own, because `Date` would rather guess than refuse:
|
||||
// month 0 rolls the heading back into December of the previous year, and a
|
||||
// missing day silently becomes the first of the month. Either one reads as
|
||||
// a real date, which is worse than showing the string that arrived.
|
||||
expect(formatDayHeading('2026-00-10', 'en-GB')).toBe('2026-00-10')
|
||||
expect(formatDayHeading('2026-09-00', 'en-GB')).toBe('2026-09-00')
|
||||
expect(formatDayHeading('2026-09', 'en-GB')).toBe('2026-09')
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatDayOption', () => {
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* FE-DAWARICH-API-030 to FE-DAWARICH-API-032
|
||||
*
|
||||
* Two lines of code, and both of them are the kind that rot without a sound.
|
||||
*
|
||||
* Accepting a recorded stay into a trip is written entirely server-side, so the
|
||||
* planner learns nothing about the place it produced until something pulls the
|
||||
* trip back in. This is that something, and both trip shells (the desktop
|
||||
* `PlacesSidebar` and the phone `MPlacesBrowser`) call it as a one-liner
|
||||
* precisely so the two copies cannot drift apart. What the tests hold is:
|
||||
*
|
||||
* - **Both refreshes are started, not one.** A stay accepted onto a day creates
|
||||
* an assignment as well as a place, so refreshing only the places leaves the
|
||||
* day rail one entry short until a reload. That is a plausible "simplification"
|
||||
* for someone reading the call site, and nothing else in the app would notice.
|
||||
* - **They run together, not in sequence.** `Promise.all` fires both before
|
||||
* awaiting either; rewritten as two awaits it still works, just twice as
|
||||
* slowly, and the button keeps spinning for both round trips. The order check
|
||||
* below is synchronous, so it distinguishes the two shapes without timing.
|
||||
* - **The id goes through verbatim.** The phone shell hands over a route param,
|
||||
* which is a string; the desktop one hands over a number. Coercing either
|
||||
* direction here would break the other caller.
|
||||
*/
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { refreshTripAfterAccept } from './dawarichTripRefresh'
|
||||
|
||||
const original = {
|
||||
refreshPlaces: useTripStore.getState().refreshPlaces,
|
||||
refreshDays: useTripStore.getState().refreshDays,
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
useTripStore.setState(original)
|
||||
})
|
||||
|
||||
describe('refreshTripAfterAccept', () => {
|
||||
it('FE-DAWARICH-API-030: starts the day refresh without waiting for the place refresh', async () => {
|
||||
const order: string[] = []
|
||||
let releasePlaces!: () => void
|
||||
// A gate rather than a timer: with Promise.all both calls are made before
|
||||
// anything is awaited, so the day refresh has already run by the time control
|
||||
// returns. Rewritten as `await a; await b` it would still be waiting here.
|
||||
const placesGate = new Promise<void>(resolve => {
|
||||
releasePlaces = resolve
|
||||
})
|
||||
|
||||
useTripStore.setState({
|
||||
refreshPlaces: vi.fn(async (_tripId: number | string) => {
|
||||
order.push('places:called')
|
||||
await placesGate
|
||||
order.push('places:settled')
|
||||
}),
|
||||
refreshDays: vi.fn(async (_tripId: number | string) => {
|
||||
order.push('days:called')
|
||||
}),
|
||||
})
|
||||
|
||||
const pending = refreshTripAfterAccept(7)
|
||||
expect(order).toEqual(['places:called', 'days:called'])
|
||||
|
||||
releasePlaces()
|
||||
await pending
|
||||
expect(order).toEqual(['places:called', 'days:called', 'places:settled'])
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-API-031: resolves only once both refreshes have finished', async () => {
|
||||
let releaseDays!: () => void
|
||||
const daysGate = new Promise<void>(resolve => {
|
||||
releaseDays = resolve
|
||||
})
|
||||
let settled = false
|
||||
|
||||
useTripStore.setState({
|
||||
refreshPlaces: vi.fn(async (_tripId: number | string) => {}),
|
||||
refreshDays: vi.fn(async (_tripId: number | string) => {
|
||||
await daysGate
|
||||
}),
|
||||
})
|
||||
|
||||
const pending = refreshTripAfterAccept(7).then(() => {
|
||||
settled = true
|
||||
})
|
||||
|
||||
// Drain the microtask queue: the places half is already done, so anything
|
||||
// that only awaited that one would be finished by now.
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
expect(settled).toBe(false)
|
||||
|
||||
releaseDays()
|
||||
await pending
|
||||
expect(settled).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-API-032: hands both refreshes the id exactly as the caller gave it', async () => {
|
||||
const refreshPlaces = vi.fn(async (_tripId: number | string) => {})
|
||||
const refreshDays = vi.fn(async (_tripId: number | string) => {})
|
||||
useTripStore.setState({ refreshPlaces, refreshDays })
|
||||
|
||||
// The phone shell reads the trip id off the route, so it is a string there
|
||||
// and a number on the desktop. Both repos accept either; a cast added here
|
||||
// would only break whichever caller was not the one being looked at.
|
||||
await refreshTripAfterAccept('42')
|
||||
expect(refreshPlaces).toHaveBeenCalledWith('42')
|
||||
expect(refreshDays).toHaveBeenCalledWith('42')
|
||||
|
||||
await refreshTripAfterAccept(42)
|
||||
expect(refreshPlaces).toHaveBeenLastCalledWith(42)
|
||||
expect(refreshDays).toHaveBeenLastCalledWith(42)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* FE-DAWARICH-TRAILUI-010 to FE-DAWARICH-TRAILUI-015: the recorded-route
|
||||
* overlay on the Leaflet renderer.
|
||||
*
|
||||
* Everything this component decides is a decision about legibility on top of
|
||||
* somebody else's map, and every one of them is the kind that quietly rots:
|
||||
*
|
||||
* - **two lines per segment, casing first.** The white casing is what keeps
|
||||
* the route visible over a satellite tile. It only works while it is drawn
|
||||
* *under* the coloured line, so the order of the two `map()` blocks is
|
||||
* load-bearing and not cosmetic.
|
||||
* - **`interactive: false` on both.** A Leaflet path without it grows an
|
||||
* invisible hit area that lies over the places and the planned route and
|
||||
* eats the clicks meant for them. Losing this flag breaks selection on a
|
||||
* surface that has nothing to do with Dawarich, which is why it is pinned
|
||||
* here rather than left to a reviewer's eye.
|
||||
* - **colour through `pathOptions`**, because react-leaflet only calls
|
||||
* `setStyle` when that object's identity changes; a bare `color` prop sticks
|
||||
* at its mount-time value and a day recolour never arrives.
|
||||
* - **the day filter keeps the day's colour.** The colour index comes from the
|
||||
* day's place in the whole track, so scrubbing to a single day dims the rest
|
||||
* of the trip instead of repainting the day the user is looking at.
|
||||
*
|
||||
* The empty case matters too: returning `null` rather than an empty fragment is
|
||||
* what stops Leaflet from being handed zero-length polylines on every trip that
|
||||
* has no recording.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import type { DawarichTrack, DawarichTrackDay } from '@trek/shared'
|
||||
import { DAWARICH_DAY_COLORS, DAWARICH_TRAIL_CASING } from './dawarichTrail'
|
||||
|
||||
// Leaflet itself is irrelevant here. What is under test is which polylines are
|
||||
// asked for and with what options, so the mock reflects the props back as data
|
||||
// attributes and the assertions read them in render order.
|
||||
vi.mock('react-leaflet', () => ({
|
||||
Polyline: ({
|
||||
positions,
|
||||
pathOptions,
|
||||
pane,
|
||||
interactive,
|
||||
}: {
|
||||
positions: Array<[number, number]>
|
||||
pathOptions?: Record<string, unknown>
|
||||
pane?: string
|
||||
interactive?: boolean
|
||||
}) => (
|
||||
<div
|
||||
data-testid="polyline"
|
||||
data-points={JSON.stringify(positions)}
|
||||
data-color={String(pathOptions?.color ?? '')}
|
||||
data-weight={String(pathOptions?.weight ?? '')}
|
||||
data-opacity={String(pathOptions?.opacity ?? '')}
|
||||
data-dash={String(pathOptions?.dashArray ?? '')}
|
||||
data-pane={pane ?? ''}
|
||||
data-interactive={String(interactive)}
|
||||
/>
|
||||
),
|
||||
}))
|
||||
|
||||
import DawarichTrailLayer from './DawarichTrailLayer'
|
||||
|
||||
function day(date: string, ...segments: Array<Array<[number, number]>>): DawarichTrackDay {
|
||||
return {
|
||||
date,
|
||||
segments: segments.map((points, i) => ({
|
||||
points,
|
||||
mode: 'walking',
|
||||
startedAt: date + 'T08:0' + i + ':00.000Z',
|
||||
endedAt: date + 'T09:0' + i + ':00.000Z',
|
||||
distanceMeters: 1200,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
function track(days: DawarichTrackDay[]): DawarichTrack {
|
||||
return {
|
||||
days,
|
||||
source: 'tracks',
|
||||
fetchedAt: '2026-05-03T10:00:00.000Z',
|
||||
pointCount: days.reduce((sum, d) => sum + d.segments.reduce((n, s) => n + s.points.length, 0), 0),
|
||||
truncated: false,
|
||||
}
|
||||
}
|
||||
|
||||
const DAY_ONE = day('2026-05-01', [[48.2, 16.37], [48.21, 16.38]])
|
||||
const DAY_TWO = day('2026-05-02', [[45.46, 9.18], [45.47, 9.19]], [[45.5, 9.2], [45.51, 9.21]])
|
||||
|
||||
const lines = () => screen.queryAllByTestId('polyline')
|
||||
|
||||
describe('DawarichTrailLayer', () => {
|
||||
it('FE-DAWARICH-TRAILUI-010: draws nothing at all when there is no recording', () => {
|
||||
const { container } = render(<DawarichTrailLayer track={null} />)
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-011: ignores a segment that is a single fix rather than a line', () => {
|
||||
// Dawarich reports a lone point for a day someone only opened the app on.
|
||||
// Leaflet would accept the one-point polyline and draw nothing visible, but
|
||||
// it would still be a layer, and every such day would add two of them.
|
||||
const { container } = render(<DawarichTrailLayer track={track([day('2026-05-01', [[48.2, 16.37]])])} />)
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-012: draws every casing first, then every coloured line on top', () => {
|
||||
render(<DawarichTrailLayer track={track([DAY_ONE, DAY_TWO])} casingPane="trek-track-casing" />)
|
||||
|
||||
const drawn = lines()
|
||||
expect(drawn).toHaveLength(6) // three segments, casing + line each
|
||||
|
||||
// The first half is the casing pass. Reversing these two blocks would put
|
||||
// the white line over the coloured one and the overlay would go white.
|
||||
const casings = drawn.slice(0, 3)
|
||||
const coloured = drawn.slice(3)
|
||||
expect(casings.every(el => el.getAttribute('data-color') === DAWARICH_TRAIL_CASING)).toBe(true)
|
||||
expect(coloured.some(el => el.getAttribute('data-color') === DAWARICH_TRAIL_CASING)).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-013: gives the casing the pane and the weight that make it a casing, and nothing catches clicks', () => {
|
||||
render(<DawarichTrailLayer track={track([DAY_ONE])} casingPane="trek-track-casing" />)
|
||||
|
||||
const [casing, line] = lines()
|
||||
expect(casing.getAttribute('data-pane')).toBe('trek-track-casing')
|
||||
expect(casing.getAttribute('data-weight')).toBe('6')
|
||||
expect(casing.getAttribute('data-opacity')).toBe('0.55')
|
||||
|
||||
// Only the casing takes the pane; the coloured line is left in Leaflet's
|
||||
// default overlay pane. Pinned as the fact it is rather than as a rule:
|
||||
// that pane also holds the planned route, and the trail is mounted after
|
||||
// it, so the recorded line currently draws over the plan while the GL twin
|
||||
// puts both of its layers under it.
|
||||
expect(line.getAttribute('data-pane')).toBe('')
|
||||
expect(line.getAttribute('data-weight')).toBe('3')
|
||||
expect(line.getAttribute('data-dash')).toBe('6 5')
|
||||
expect(line.getAttribute('data-points')).toBe(JSON.stringify([[48.2, 16.37], [48.21, 16.38]]))
|
||||
|
||||
expect(lines().every(el => el.getAttribute('data-interactive') === 'false')).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-014: works without a casing pane on a renderer that has none', () => {
|
||||
render(<DawarichTrailLayer track={track([DAY_ONE])} />)
|
||||
|
||||
// An older Leaflet build, or the GL renderer's Leaflet fallback, has no
|
||||
// pane API and MapView passes undefined. Everything then lands in the
|
||||
// default overlay pane in insertion order, which still keeps the casing
|
||||
// under its own line, the one piece of the stacking that has to hold.
|
||||
expect(lines().every(el => el.getAttribute('data-pane') === '')).toBe(true)
|
||||
expect(lines()).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-015: scrubbing to one day keeps that day its own colour', () => {
|
||||
const { rerender } = render(<DawarichTrailLayer track={track([DAY_ONE, DAY_TWO])} selectedDate="2026-05-02" />)
|
||||
|
||||
// Two segments on the second day, so two casings and two lines, and the hue
|
||||
// is the SECOND of the palette even though it is now the only day drawn.
|
||||
expect(lines()).toHaveLength(4)
|
||||
expect(lines().slice(2).map(el => el.getAttribute('data-color')))
|
||||
.toEqual([DAWARICH_DAY_COLORS[1], DAWARICH_DAY_COLORS[1]])
|
||||
|
||||
rerender(<DawarichTrailLayer track={track([DAY_ONE, DAY_TWO])} selectedDate="2026-05-01" />)
|
||||
expect(lines().slice(1).map(el => el.getAttribute('data-color'))).toEqual([DAWARICH_DAY_COLORS[0]])
|
||||
|
||||
// A day nobody recorded on falls back to the empty case rather than to the
|
||||
// whole trip, which would be the worst possible answer to "show me Sunday".
|
||||
rerender(<DawarichTrailLayer track={track([DAY_ONE, DAY_TWO])} selectedDate="2026-05-09" />)
|
||||
expect(lines()).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* FE-DAWARICH-TRAILUI-001 to FE-DAWARICH-TRAILUI-007: the recorded-route
|
||||
* toggle that sits with the compass and the layer switcher on the trip map.
|
||||
*
|
||||
* The pill is small but it carries the only explanation the user ever gets for
|
||||
* an empty overlay. Turning the layer on and seeing no line has four different
|
||||
* causes (it is still loading, nothing was recorded on these dates, the
|
||||
* Dawarich instance did not answer, the device is offline), and all four are
|
||||
* answered by the label on this one control. If the label chain collapses to
|
||||
* "hide recorded route" the map silently lies: the user sees a pressed button,
|
||||
* no line, and no reason.
|
||||
*
|
||||
* So what is pinned here is the mapping from `status` to the label, and the
|
||||
* second, wordless channel next to it: a problem state drains the mark to 0.35
|
||||
* so it is visible without hovering, while loading (which is not a problem)
|
||||
* stays at full strength. The off state has to win over all of it, because a
|
||||
* dimmed logo on a switched-off control would read as broken rather than as
|
||||
* off.
|
||||
*/
|
||||
import React from 'react'
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest'
|
||||
import { render, screen, fireEvent, act } from '../../../tests/helpers/render'
|
||||
import { DawarichTrailPill } from './DawarichTrailPill'
|
||||
import type { DawarichTrailStatus } from './useDawarichTrail'
|
||||
|
||||
function pill(props: Partial<React.ComponentProps<typeof DawarichTrailPill>> = {}) {
|
||||
return render(
|
||||
<DawarichTrailPill active={false} status="idle" onToggle={vi.fn()} {...props} />,
|
||||
)
|
||||
}
|
||||
|
||||
const button = () => screen.getByTestId('dawarich-trail-pill')
|
||||
const label = () => button().getAttribute('aria-label')
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('DawarichTrailPill', () => {
|
||||
it('FE-DAWARICH-TRAILUI-001: offers to show the route while the layer is off, whatever the last status was', () => {
|
||||
const { rerender } = pill()
|
||||
|
||||
expect(label()).toBe('Show recorded route')
|
||||
expect(button()).toHaveAttribute('aria-pressed', 'false')
|
||||
expect(button().style.opacity).toBe('0.6')
|
||||
|
||||
// A stale failure from the last time the layer was on must not dim a
|
||||
// switched-off control: off already has its own resting opacity, and a
|
||||
// second, dimmer step would read as "this button is broken".
|
||||
rerender(<DawarichTrailPill active={false} status="unavailable" onToggle={vi.fn()} />)
|
||||
expect(label()).toBe('Show recorded route')
|
||||
expect(button().style.opacity).toBe('0.6')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-002: offers to hide the route once a line is on the map', () => {
|
||||
const { rerender } = pill({ active: true, status: 'ready' })
|
||||
|
||||
expect(label()).toBe('Hide recorded route')
|
||||
expect(button()).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(button().style.opacity).toBe('1')
|
||||
|
||||
// `idle` is the state between the toggle flipping and the first fetch
|
||||
// starting. It falls through the same arm as `ready` on purpose: the button
|
||||
// has just been pressed and "hide" is the only honest thing it can offer.
|
||||
rerender(<DawarichTrailPill active status="idle" onToggle={vi.fn()} />)
|
||||
expect(label()).toBe('Hide recorded route')
|
||||
expect(button().style.opacity).toBe('1')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-003: says it is loading without dimming the mark', () => {
|
||||
pill({ active: true, status: 'loading' })
|
||||
|
||||
expect(label()).toMatch(/^Loading the recorded route/)
|
||||
// Loading is not a problem, so the wordless "something is wrong" channel
|
||||
// stays off. Otherwise every refresh would blink the control.
|
||||
expect(button().style.opacity).toBe('1')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-004: names each reason there is no line and dims the mark for it', () => {
|
||||
const reasons: Array<[DawarichTrailStatus, string]> = [
|
||||
['empty', 'Nothing was recorded on these dates'],
|
||||
['offline', 'The recorded route needs a connection'],
|
||||
['unavailable', 'The recorded route could not be loaded'],
|
||||
]
|
||||
|
||||
for (const [status, expected] of reasons) {
|
||||
const { unmount } = pill({ active: true, status })
|
||||
expect(label()).toBe(expected)
|
||||
expect(button().style.opacity).toBe('0.35')
|
||||
// The pressed state survives the problem: the layer really is on, and
|
||||
// un-pressing it here would make the toggle disagree with the map.
|
||||
expect(button()).toHaveAttribute('aria-pressed', 'true')
|
||||
unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-005: reports a press once', () => {
|
||||
const onToggle = vi.fn()
|
||||
pill({ onToggle })
|
||||
|
||||
fireEvent.click(button())
|
||||
expect(onToggle).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-006: lifts the mark under the pointer and puts it back', () => {
|
||||
pill({ active: true, status: 'ready' })
|
||||
|
||||
fireEvent.mouseEnter(button())
|
||||
expect(button().style.transform).toBe('scale(1.06)')
|
||||
|
||||
fireEvent.mouseLeave(button())
|
||||
expect(button().style.transform).toBe('none')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-007: repeats the status in a readable tooltip rather than the native one', () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
pill({ active: true, status: 'empty' })
|
||||
|
||||
fireEvent.mouseEnter(button())
|
||||
act(() => { vi.advanceTimersByTime(300) })
|
||||
|
||||
// The whole reason this control carries TREK's own tooltip: the native one
|
||||
// never appears on a touch device, which is exactly where someone taps the
|
||||
// button to find out why the map is empty.
|
||||
expect(screen.getByRole('tooltip')).toHaveTextContent('Nothing was recorded on these dates')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,229 @@
|
||||
/**
|
||||
* dawarichTrail unit tests: FE-DAWARICH-TRAIL-001 to FE-DAWARICH-TRAIL-008.
|
||||
*
|
||||
* This module is the whole of what the two map renderers agree on about the
|
||||
* recorded route: Leaflet turns `trailSegments` into `<Polyline>` elements, the
|
||||
* GL map turns `trailGeoJson` into one source, and the pill reports
|
||||
* `trailDistanceKm`. Nothing here touches a map, so every decision it makes can
|
||||
* be pinned directly, and every one of them breaks silently, because a wrong
|
||||
* line still looks exactly like a line.
|
||||
*
|
||||
* Four claims are worth holding:
|
||||
*
|
||||
* - **the day colour comes from the day's place in the whole track, never in
|
||||
* the filtered list.** Picking a day on the timeline has to dim the rest of
|
||||
* the trip while leaving the picked day the colour it already had; an index
|
||||
* read off the filtered array would repaint every selection blue, and the
|
||||
* map would quietly stop meaning "we were here on Tuesday".
|
||||
* - **a segment that cannot be drawn is dropped, not drawn badly.** The pairs
|
||||
* are narrowed at runtime rather than cast, so a ragged answer from someone
|
||||
* else's Dawarich instance costs a point instead of putting a vertex at NaN
|
||||
* and taking the rest of the overlay down with it.
|
||||
* - **`[lat, lng]` becomes `[lng, lat]` exactly once.** This is the only
|
||||
* coordinate flip in the overlay. A second flip, or none, drops the whole
|
||||
* recording in the Gulf of Guinea, and nothing else in the repo watches
|
||||
* that boundary.
|
||||
* - **an unknown distance is not zero.** `null` means "Dawarich did not say",
|
||||
* which the panel has to render as nothing rather than as "0 km travelled".
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import type { DawarichTrack, DawarichTrackDay, DawarichTrackSegment } from '@trek/shared'
|
||||
import {
|
||||
DAWARICH_DAY_COLORS,
|
||||
DAWARICH_TRAIL_CASING,
|
||||
DAWARICH_TRAIL_COLOR,
|
||||
dayColor,
|
||||
trailDistanceKm,
|
||||
trailGeoJson,
|
||||
trailSegments,
|
||||
type DawarichTrailSegment,
|
||||
} from './dawarichTrail'
|
||||
|
||||
const seg = (over: Partial<DawarichTrackSegment> = {}): DawarichTrackSegment => ({
|
||||
points: over.points ?? [
|
||||
[52.52, 13.405],
|
||||
[52.51, 13.41],
|
||||
],
|
||||
mode: over.mode === undefined ? 'walking' : over.mode,
|
||||
startedAt: over.startedAt ?? '2026-05-01T08:00:00Z',
|
||||
endedAt: over.endedAt ?? '2026-05-01T09:00:00Z',
|
||||
distanceMeters: over.distanceMeters === undefined ? 1200 : over.distanceMeters,
|
||||
})
|
||||
|
||||
const track = (days: DawarichTrackDay[]): DawarichTrack => ({
|
||||
days,
|
||||
source: 'tracks',
|
||||
fetchedAt: '2026-05-03T10:00:00Z',
|
||||
pointCount: 42,
|
||||
truncated: false,
|
||||
})
|
||||
|
||||
/** Three calendar days, so "the second day" has a colour that is not the first day's. */
|
||||
const THREE_DAYS = track([
|
||||
{ date: '2026-05-01', segments: [seg(), seg({ mode: 'car', distanceMeters: 40_000 })] },
|
||||
{ date: '2026-05-02', segments: [seg({ mode: null, distanceMeters: null })] },
|
||||
{ date: '2026-05-03', segments: [seg()] },
|
||||
])
|
||||
|
||||
/**
|
||||
* The wire shapes a Dawarich instance can actually produce but the Zod tuple
|
||||
* type cannot express: a pair that lost its longitude, and a pair whose
|
||||
* latitude came back as text. The casts reproduce the bad answer rather than
|
||||
* pretending the schema makes it impossible, which is exactly the assumption
|
||||
* the runtime narrowing in `trailSegments` refuses to make.
|
||||
*/
|
||||
const RAGGED = [
|
||||
[52.52, 13.405],
|
||||
[52.51],
|
||||
[52.5, 13.4],
|
||||
] as unknown as Array<[number, number]>
|
||||
|
||||
const UNDRAWABLE = [
|
||||
['north', 13.405],
|
||||
[52.51, 13.41],
|
||||
] as unknown as Array<[number, number]>
|
||||
|
||||
describe('dayColor', () => {
|
||||
it('FE-DAWARICH-TRAIL-001: cycles the six day hues and wraps instead of running off the end', () => {
|
||||
expect(DAWARICH_DAY_COLORS).toHaveLength(6)
|
||||
expect(dayColor(0)).toBe(DAWARICH_DAY_COLORS[0])
|
||||
expect(dayColor(5)).toBe(DAWARICH_DAY_COLORS[5])
|
||||
// A fortnight-long trip must not hand back undefined on day seven.
|
||||
expect(dayColor(6)).toBe(DAWARICH_DAY_COLORS[0])
|
||||
expect(dayColor(13)).toBe(DAWARICH_DAY_COLORS[1])
|
||||
// These two are what the Leaflet path options and the GL paint expressions
|
||||
// both read. Changing either is a review decision, not a drive-by diff.
|
||||
expect(DAWARICH_TRAIL_COLOR).toBe('#2563EB')
|
||||
expect(DAWARICH_TRAIL_CASING).toBe('#FFFFFF')
|
||||
})
|
||||
})
|
||||
|
||||
describe('trailSegments', () => {
|
||||
it('FE-DAWARICH-TRAIL-002: has nothing to draw before a track has been fetched', () => {
|
||||
expect(trailSegments(null)).toEqual([])
|
||||
// The timeline passes its selected day even while the first fetch is out.
|
||||
expect(trailSegments(null, '2026-05-01')).toEqual([])
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAIL-003: flattens every day into keyed segments carrying the day colour', () => {
|
||||
const out = trailSegments(THREE_DAYS)
|
||||
|
||||
expect(out.map(s => s.id)).toEqual([
|
||||
'2026-05-01-0',
|
||||
'2026-05-01-1',
|
||||
'2026-05-02-0',
|
||||
'2026-05-03-0',
|
||||
])
|
||||
expect(out.map(s => s.color)).toEqual([
|
||||
DAWARICH_DAY_COLORS[0],
|
||||
DAWARICH_DAY_COLORS[0],
|
||||
DAWARICH_DAY_COLORS[1],
|
||||
DAWARICH_DAY_COLORS[2],
|
||||
])
|
||||
expect(out[1].mode).toBe('car')
|
||||
expect(out[1].distanceMeters).toBe(40_000)
|
||||
// An instance too old to classify the movement reports null, and null is
|
||||
// what reaches the renderer: no invented transport mode.
|
||||
expect(out[2].mode).toBeNull()
|
||||
expect(out[2].distanceMeters).toBeNull()
|
||||
expect(out[0].startedAt).toBe('2026-05-01T08:00:00Z')
|
||||
expect(out[0].endedAt).toBe('2026-05-01T09:00:00Z')
|
||||
expect(out[0].points).toEqual([
|
||||
[52.52, 13.405],
|
||||
[52.51, 13.41],
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAIL-004: filtering to one day keeps that day its own colour', () => {
|
||||
const only = trailSegments(THREE_DAYS, '2026-05-03')
|
||||
|
||||
expect(only.map(s => s.id)).toEqual(['2026-05-03-0'])
|
||||
// The regression this test exists for: an index taken from the filtered
|
||||
// array would be 0 here and repaint the third day in the first day's blue.
|
||||
expect(only[0].color).toBe(DAWARICH_DAY_COLORS[2])
|
||||
// An explicit null is the "no day picked" case the scrubber sends on reset.
|
||||
expect(trailSegments(THREE_DAYS, null)).toHaveLength(4)
|
||||
// A day with no recording is an empty overlay, not the whole trip.
|
||||
expect(trailSegments(THREE_DAYS, '2026-04-30')).toEqual([])
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAIL-005: drops what cannot be drawn and keeps the rest of the day numbered', () => {
|
||||
const out = trailSegments(
|
||||
track([
|
||||
{
|
||||
date: '2026-05-01',
|
||||
segments: [
|
||||
// A single recorded fix is a dot, not a line: Leaflet would draw
|
||||
// nothing and the GL source would reject the LineString.
|
||||
seg({ points: [[52.52, 13.405]] }),
|
||||
// Two pairs, one of them without a usable latitude, so only one
|
||||
// point survives the narrowing and this segment goes with it.
|
||||
seg({ points: UNDRAWABLE }),
|
||||
seg({ points: RAGGED }),
|
||||
],
|
||||
},
|
||||
]),
|
||||
)
|
||||
|
||||
expect(out).toHaveLength(1)
|
||||
// The id keeps the segment's index inside the day rather than its index in
|
||||
// the output: a renderer keys on it, and renumbering would remount every
|
||||
// surviving line as soon as an earlier segment went missing.
|
||||
expect(out[0].id).toBe('2026-05-01-2')
|
||||
expect(out[0].points).toEqual([
|
||||
[52.52, 13.405],
|
||||
[52.5, 13.4],
|
||||
])
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAIL-006: a day that recorded nothing contributes nothing', () => {
|
||||
expect(trailSegments(track([{ date: '2026-05-01', segments: [] }]))).toEqual([])
|
||||
expect(trailSegments(track([]))).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('trailGeoJson', () => {
|
||||
it('FE-DAWARICH-TRAIL-007: flips lat/lng once and carries the paint properties across', () => {
|
||||
const collection = trailGeoJson(trailSegments(THREE_DAYS, '2026-05-02'))
|
||||
|
||||
expect(collection.type).toBe('FeatureCollection')
|
||||
expect(collection.features).toHaveLength(1)
|
||||
const [feature] = collection.features
|
||||
expect(feature.type).toBe('Feature')
|
||||
expect(feature.properties).toEqual({
|
||||
id: '2026-05-02-0',
|
||||
color: DAWARICH_DAY_COLORS[1],
|
||||
date: '2026-05-02',
|
||||
mode: null,
|
||||
})
|
||||
expect(feature.geometry.type).toBe('LineString')
|
||||
// TREK stores [lat, lng]; GeoJSON wants [lng, lat]. Berlin sits at 52 N
|
||||
// 13 E, so a missed flip lands the recording off the coast of Ghana.
|
||||
expect(feature.geometry.coordinates).toEqual([
|
||||
[13.405, 52.52],
|
||||
[13.41, 52.51],
|
||||
])
|
||||
|
||||
// Nothing recorded is an empty collection, which a GeoJSON source accepts,
|
||||
// not the null it would choke on.
|
||||
expect(trailGeoJson([])).toEqual({ type: 'FeatureCollection', features: [] })
|
||||
})
|
||||
})
|
||||
|
||||
describe('trailDistanceKm', () => {
|
||||
it('FE-DAWARICH-TRAIL-008: sums the known metres into kilometres and says nothing when none are known', () => {
|
||||
const withDistances: DawarichTrailSegment[] = trailSegments(THREE_DAYS)
|
||||
|
||||
// 1200 + 40000 + 1200 metres; the day Dawarich gave no distance for is
|
||||
// skipped rather than counted as a zero-kilometre leg.
|
||||
expect(trailDistanceKm(withDistances)).toBeCloseTo(42.4, 6)
|
||||
|
||||
const unknownOnly = trailSegments(
|
||||
track([{ date: '2026-05-02', segments: [seg({ distanceMeters: null })] }]),
|
||||
)
|
||||
// null, not 0: "Dawarich did not say" and "you went nowhere" are different
|
||||
// sentences and the pill is allowed to render only one of them.
|
||||
expect(trailDistanceKm(unknownOnly)).toBeNull()
|
||||
expect(trailDistanceKm([])).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,430 @@
|
||||
/**
|
||||
* useDawarichTrail unit tests: FE-DAWARICH-TRAIL-009 to FE-DAWARICH-TRAIL-024
|
||||
* (the numbering continues the one in `dawarichTrail.test.ts`, so a grep for
|
||||
* FE-DAWARICH-TRAIL finds the whole overlay in one list).
|
||||
*
|
||||
* This hook is the only fetcher for the recorded route. It is called once in
|
||||
* `MapViewAuto` and the answer is handed to both renderers as a prop, so a bug
|
||||
* here is not a rendering glitch. It is either a request storm against a
|
||||
* server the user pays for and runs themselves, or a line on the map that is
|
||||
* telling them about a different moment than the one they are looking at.
|
||||
*
|
||||
* What is pinned, and why each one matters:
|
||||
*
|
||||
* - **the gate.** `enabled && tripId && the addon is on`: three separate ways
|
||||
* to be switched off, and the hook must reach the network for none of them.
|
||||
* The addon check is the one a reviewer forgets, and forgetting it means an
|
||||
* instance with Dawarich turned off still hammers `/api/dawarich/...` every
|
||||
* two minutes.
|
||||
* - **the offline contract.** `isEffectivelyOffline()` and not
|
||||
* `navigator.onLine`, so the manual switch someone flipped before a flight
|
||||
* is honoured; a request fired anyway blocks on a timeout instead of
|
||||
* failing, and that is the case the user cannot see.
|
||||
* - **staleness is said, never faked.** A refresh keeps the previous line on
|
||||
* screen and only moves the status, because blanking the map makes a routine
|
||||
* two-minute poll look like the recording was deleted. A failure keeps the
|
||||
* line too, and says `unavailable`.
|
||||
* - **nothing that arrives late is allowed to paint.** Three ways a response
|
||||
* can be obsolete by the time it lands (the layer was switched off, the
|
||||
* device went offline, a newer request superseded it), and all three have to
|
||||
* end in the answer being dropped rather than drawn over a newer truth.
|
||||
* - **the timer is torn down with the hook.** An interval that outlives the
|
||||
* map is an unattributable request every two minutes, for the rest of the
|
||||
* session.
|
||||
*/
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import type { DawarichTrack } from '@trek/shared'
|
||||
|
||||
const { tripTrack } = vi.hoisted(() => ({ tripTrack: vi.fn() }))
|
||||
vi.mock('../../repo/dawarichRepo', () => ({ dawarichRepo: { tripTrack } }))
|
||||
|
||||
import { seedStore } from '../../../tests/helpers/store'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { _resetNetworkMode, setForcedOffline } from '../../sync/networkMode'
|
||||
import { useDawarichTrail } from './useDawarichTrail'
|
||||
|
||||
const REFRESH_MS = 120_000
|
||||
|
||||
const trackWith = (dates: string[], fetchedAt = '2026-05-03T10:00:00Z'): DawarichTrack => ({
|
||||
days: dates.map(date => ({
|
||||
date,
|
||||
segments: [
|
||||
{
|
||||
points: [
|
||||
[52.52, 13.405],
|
||||
[52.51, 13.41],
|
||||
],
|
||||
mode: 'walking',
|
||||
startedAt: `${date}T08:00:00Z`,
|
||||
endedAt: `${date}T09:00:00Z`,
|
||||
distanceMeters: 1200,
|
||||
},
|
||||
],
|
||||
})),
|
||||
source: 'tracks',
|
||||
fetchedAt,
|
||||
pointCount: 2 * dates.length,
|
||||
truncated: false,
|
||||
})
|
||||
|
||||
const TRACK = trackWith(['2026-05-01'])
|
||||
const NEWER = trackWith(['2026-05-01', '2026-05-02'], '2026-05-03T10:02:00Z')
|
||||
const EMPTY: DawarichTrack = { ...trackWith([]), pointCount: 0 }
|
||||
|
||||
const addon = (enabled: boolean) => [
|
||||
{ id: 'dawarich', name: 'Dawarich', description: '', type: 'integration', icon: 'map', enabled },
|
||||
]
|
||||
|
||||
/**
|
||||
* A promise the test settles by hand. "In flight" is a state this hook has
|
||||
* opinions about (it keeps the old line, it aborts on the next load), and none
|
||||
* of them are observable against a promise that has already resolved.
|
||||
*/
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
let reject!: (reason: unknown) => void
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res
|
||||
reject = rej
|
||||
})
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
/** Let the repo promise and the state updates it schedules settle inside act. */
|
||||
const flush = () =>
|
||||
act(async () => {
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
})
|
||||
|
||||
/** jsdom's onLine is a prototype getter; an own property shadows it for one test. */
|
||||
const setBrowserOnline = (value: boolean) =>
|
||||
Object.defineProperty(navigator, 'onLine', { value, writable: true, configurable: true })
|
||||
|
||||
const signalOf = (call: number): AbortSignal => tripTrack.mock.calls[call][2] as AbortSignal
|
||||
|
||||
beforeEach(() => {
|
||||
tripTrack.mockReset()
|
||||
tripTrack.mockResolvedValue(TRACK)
|
||||
// The `isEnabled` selector is a stable function reference, so a store change
|
||||
// after mount does not re-render the hook. Every test seeds before it renders.
|
||||
seedStore(useAddonStore, { addons: addon(true), loaded: true })
|
||||
_resetNetworkMode()
|
||||
setBrowserOnline(true)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
_resetNetworkMode()
|
||||
setBrowserOnline(true)
|
||||
})
|
||||
|
||||
describe('useDawarichTrail: the gate', () => {
|
||||
it('FE-DAWARICH-TRAIL-009: stays idle and reaches for nothing while the layer is off', () => {
|
||||
const { result } = renderHook(() => useDawarichTrail(7, false))
|
||||
|
||||
expect(result.current.status).toBe('idle')
|
||||
expect(result.current.track).toBeNull()
|
||||
expect(result.current.fetchedAt).toBeNull()
|
||||
expect(tripTrack).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAIL-010: a trip that has not loaded its id yet is not a trip to fetch for', () => {
|
||||
const { result } = renderHook(() => useDawarichTrail(undefined, true))
|
||||
|
||||
expect(result.current.status).toBe('idle')
|
||||
expect(tripTrack).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAIL-011: an instance with the addon switched off never calls the integration', () => {
|
||||
seedStore(useAddonStore, { addons: addon(false), loaded: true })
|
||||
|
||||
const { result } = renderHook(() => useDawarichTrail(7, true))
|
||||
|
||||
expect(result.current.status).toBe('idle')
|
||||
expect(tripTrack).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDawarichTrail: fetching', () => {
|
||||
it('FE-DAWARICH-TRAIL-012: fetches the trip window with an abort signal and reports it ready', async () => {
|
||||
const { result } = renderHook(() =>
|
||||
useDawarichTrail(7, true, { from: '2026-05-01', to: '2026-05-03' }),
|
||||
)
|
||||
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
expect(result.current.track).toEqual(TRACK)
|
||||
// fetchedAt comes off the answer, not off the clock: it is the server's
|
||||
// statement about how fresh the recording is, and the pill quotes it.
|
||||
expect(result.current.fetchedAt).toBe('2026-05-03T10:00:00Z')
|
||||
expect(tripTrack).toHaveBeenCalledTimes(1)
|
||||
expect(tripTrack.mock.calls[0][0]).toBe(7)
|
||||
expect(tripTrack.mock.calls[0][1]).toEqual({ from: '2026-05-01', to: '2026-05-03' })
|
||||
expect(signalOf(0)).toBeInstanceOf(AbortSignal)
|
||||
expect(signalOf(0).aborted).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAIL-013: a window with no recording is empty, which is not the same as ready', async () => {
|
||||
tripTrack.mockResolvedValue(EMPTY)
|
||||
|
||||
const { result } = renderHook(() => useDawarichTrail(7, true))
|
||||
|
||||
await waitFor(() => expect(result.current.status).toBe('empty'))
|
||||
expect(result.current.track).toEqual(EMPTY)
|
||||
expect(result.current.fetchedAt).toBe(EMPTY.fetchedAt)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAIL-014: a failed refresh keeps the line that is already drawn', async () => {
|
||||
tripTrack.mockResolvedValueOnce(TRACK).mockRejectedValueOnce(new Error('502 from Dawarich'))
|
||||
|
||||
const { result } = renderHook(() => useDawarichTrail(7, true))
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
act(() => {
|
||||
result.current.reload()
|
||||
})
|
||||
|
||||
await waitFor(() => expect(result.current.status).toBe('unavailable'))
|
||||
// A line from two minutes ago beats an empty map; the status is the part
|
||||
// that admits it may be stale.
|
||||
expect(result.current.track).toEqual(TRACK)
|
||||
expect(result.current.fetchedAt).toBe(TRACK.fetchedAt)
|
||||
expect(tripTrack).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAIL-015: a refresh does not blank the map while the next answer is in flight', async () => {
|
||||
const second = deferred<DawarichTrack>()
|
||||
tripTrack.mockResolvedValueOnce(TRACK).mockReturnValueOnce(second.promise)
|
||||
|
||||
const { result } = renderHook(() => useDawarichTrail(7, true))
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
act(() => {
|
||||
result.current.reload()
|
||||
})
|
||||
|
||||
// Not 'loading': flipping back to the spinner every two minutes would make
|
||||
// a routine poll look like the recording had gone away.
|
||||
expect(result.current.status).toBe('ready')
|
||||
expect(result.current.track).toEqual(TRACK)
|
||||
expect(tripTrack).toHaveBeenCalledTimes(2)
|
||||
|
||||
await act(async () => {
|
||||
second.resolve(NEWER)
|
||||
await Promise.resolve()
|
||||
})
|
||||
await waitFor(() => expect(result.current.track).toEqual(NEWER))
|
||||
expect(result.current.fetchedAt).toBe(NEWER.fetchedAt)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAIL-016: changing the window refetches, re-rendering with the same window does not', async () => {
|
||||
type Range = { from?: string; to?: string }
|
||||
const { result, rerender } = renderHook(
|
||||
({ range }: { range: Range }) => useDawarichTrail(7, true, range),
|
||||
{ initialProps: { range: { from: '2026-05-01' } as Range } },
|
||||
)
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
expect(tripTrack).toHaveBeenCalledTimes(1)
|
||||
|
||||
// A fresh object literal with the same window: the parent produces one on
|
||||
// every render, and re-fetching on each of them is the bug the range key
|
||||
// exists to prevent.
|
||||
rerender({ range: { from: '2026-05-01' } })
|
||||
await flush()
|
||||
expect(tripTrack).toHaveBeenCalledTimes(1)
|
||||
|
||||
rerender({ range: { from: '2026-05-01', to: '2026-05-04' } })
|
||||
await waitFor(() => expect(tripTrack).toHaveBeenCalledTimes(2))
|
||||
expect(tripTrack.mock.calls[1][1]).toEqual({ from: '2026-05-01', to: '2026-05-04' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDawarichTrail: offline', () => {
|
||||
it('FE-DAWARICH-TRAIL-017: a device that is offline by choice is never asked to reach the network', () => {
|
||||
setForcedOffline(true)
|
||||
|
||||
const { result } = renderHook(() => useDawarichTrail(7, true))
|
||||
|
||||
expect(result.current.status).toBe('offline')
|
||||
expect(tripTrack).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAIL-018: going offline mid-flight aborts the request and drops the answer', async () => {
|
||||
const first = deferred<DawarichTrack>()
|
||||
tripTrack.mockReturnValueOnce(first.promise)
|
||||
|
||||
const { result } = renderHook(() => useDawarichTrail(7, true))
|
||||
expect(result.current.status).toBe('loading')
|
||||
|
||||
act(() => {
|
||||
setForcedOffline(true)
|
||||
})
|
||||
|
||||
// The hook subscribes to network-mode changes, so the switch re-enters the
|
||||
// load immediately rather than waiting out the two-minute timer.
|
||||
expect(signalOf(0).aborted).toBe(true)
|
||||
expect(result.current.status).toBe('offline')
|
||||
expect(tripTrack).toHaveBeenCalledTimes(1)
|
||||
|
||||
await act(async () => {
|
||||
first.resolve(TRACK)
|
||||
await Promise.resolve()
|
||||
})
|
||||
// The answer belonged to a request the hook has already given up on.
|
||||
// Painting it now would contradict the status the user is reading.
|
||||
expect(result.current.status).toBe('offline')
|
||||
expect(result.current.track).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAIL-019: a request that fails after the connection dropped says offline, not unavailable', async () => {
|
||||
tripTrack.mockImplementationOnce(async () => {
|
||||
// The browser drops the connection after the request left: the pre-flight
|
||||
// check passed, and only the failure knows the device is gone.
|
||||
setBrowserOnline(false)
|
||||
throw new Error('network error')
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => useDawarichTrail(7, true))
|
||||
|
||||
await waitFor(() => expect(result.current.status).toBe('offline'))
|
||||
expect(result.current.track).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDawarichTrail: lifecycle', () => {
|
||||
it('FE-DAWARICH-TRAIL-020: switching the layer off mid-flight discards the answer instead of drawing it', async () => {
|
||||
const first = deferred<DawarichTrack>()
|
||||
tripTrack.mockReturnValueOnce(first.promise)
|
||||
|
||||
const { result, rerender } = renderHook(({ on }: { on: boolean }) => useDawarichTrail(7, on), {
|
||||
initialProps: { on: true },
|
||||
})
|
||||
expect(result.current.status).toBe('loading')
|
||||
|
||||
rerender({ on: false })
|
||||
expect(result.current.status).toBe('idle')
|
||||
expect(signalOf(0).aborted).toBe(true)
|
||||
|
||||
await act(async () => {
|
||||
first.resolve(TRACK)
|
||||
await Promise.resolve()
|
||||
})
|
||||
// Nobody asked for this line any more; drawing it would put the overlay
|
||||
// back on a map the user just cleared.
|
||||
expect(result.current.status).toBe('idle')
|
||||
expect(result.current.track).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAIL-021: a failure that lands after the layer was switched off stays quiet', async () => {
|
||||
const first = deferred<DawarichTrack>()
|
||||
tripTrack.mockReturnValueOnce(first.promise)
|
||||
|
||||
const { result, rerender } = renderHook(({ on }: { on: boolean }) => useDawarichTrail(7, on), {
|
||||
initialProps: { on: true },
|
||||
})
|
||||
rerender({ on: false })
|
||||
|
||||
await act(async () => {
|
||||
first.reject(new Error('too late'))
|
||||
await Promise.resolve()
|
||||
})
|
||||
// 'unavailable' here would light up a warning pill about a layer that is
|
||||
// not on screen.
|
||||
expect(result.current.status).toBe('idle')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAIL-022: switching off clears the drawn track and switching back on refetches', async () => {
|
||||
const { result, rerender } = renderHook(({ on }: { on: boolean }) => useDawarichTrail(7, on), {
|
||||
initialProps: { on: true },
|
||||
})
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
expect(result.current.track).toEqual(TRACK)
|
||||
|
||||
rerender({ on: false })
|
||||
expect(result.current.track).toBeNull()
|
||||
expect(result.current.status).toBe('idle')
|
||||
// fetchedAt is deliberately not cleared: it describes the last answer the
|
||||
// hook actually received, and the pill reads it again on the way back.
|
||||
expect(result.current.fetchedAt).toBe(TRACK.fetchedAt)
|
||||
|
||||
rerender({ on: true })
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
expect(tripTrack).toHaveBeenCalledTimes(2)
|
||||
expect(result.current.track).toEqual(TRACK)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAIL-023: refreshes on the two-minute timer and stops the timer with the hook', async () => {
|
||||
vi.useFakeTimers({ shouldAdvanceTime: true })
|
||||
|
||||
const { result, unmount } = renderHook(() => useDawarichTrail(7, true))
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
})
|
||||
expect(result.current.status).toBe('ready')
|
||||
expect(tripTrack).toHaveBeenCalledTimes(1)
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(REFRESH_MS)
|
||||
})
|
||||
expect(tripTrack).toHaveBeenCalledTimes(2)
|
||||
// Each poll supersedes the one before it, so a slow answer can never land
|
||||
// on top of a newer one.
|
||||
expect(signalOf(0).aborted).toBe(true)
|
||||
|
||||
unmount()
|
||||
expect(signalOf(1).aborted).toBe(true)
|
||||
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(REFRESH_MS * 3)
|
||||
})
|
||||
// An interval that outlived the map would be a request every two minutes
|
||||
// for the rest of the session, against somebody's own hardware.
|
||||
expect(tripTrack).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAIL-024: a superseded request that fails afterwards leaves the newer one alone', async () => {
|
||||
const superseded = deferred<DawarichTrack>()
|
||||
const current = deferred<DawarichTrack>()
|
||||
tripTrack.mockReturnValueOnce(superseded.promise).mockReturnValueOnce(current.promise)
|
||||
|
||||
const { result } = renderHook(() => useDawarichTrail(7, true))
|
||||
expect(result.current.status).toBe('loading')
|
||||
|
||||
// Offline and straight back: two network-mode notifications inside the same
|
||||
// effect, so the first request is abandoned without the hook being torn down
|
||||
// or reloaded. That is the only way to get an aborted request whose failure
|
||||
// still arrives at a live listener, which is what the abort check in the
|
||||
// failure path is for. A timer tick does the same thing two minutes later.
|
||||
act(() => {
|
||||
setForcedOffline(true)
|
||||
})
|
||||
expect(result.current.status).toBe('offline')
|
||||
act(() => {
|
||||
setForcedOffline(false)
|
||||
})
|
||||
|
||||
expect(tripTrack).toHaveBeenCalledTimes(2)
|
||||
expect(signalOf(0).aborted).toBe(true)
|
||||
expect(signalOf(1).aborted).toBe(false)
|
||||
expect(result.current.status).toBe('loading')
|
||||
|
||||
await act(async () => {
|
||||
superseded.reject(new Error('aborted while the next request was already out'))
|
||||
// The failure travels through the then() before it reaches the catch(),
|
||||
// so one tick is not enough to see it land.
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
})
|
||||
// 'unavailable' here would put a warning on the map about a request the hook
|
||||
// threw away itself, while the request it is actually waiting for is fine.
|
||||
expect(result.current.status).toBe('loading')
|
||||
|
||||
await act(async () => {
|
||||
current.resolve(TRACK)
|
||||
await Promise.resolve()
|
||||
})
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
expect(result.current.track).toEqual(TRACK)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,317 @@
|
||||
/**
|
||||
* FE-DAWARICH-TRAILUI-020 to FE-DAWARICH-TRAILUI-029: the recorded-route
|
||||
* overlay on the GL renderer, the imperative twin of `DawarichTrailLayer`.
|
||||
*
|
||||
* A declarative overlay that gets its ordering wrong looks wrong. An imperative
|
||||
* one that gets its lifecycle wrong leaks: sources and layers survive the React
|
||||
* tree that created them, and a GL map carrying a layer nobody owns any more
|
||||
* throws on the next style change instead of at the point of the mistake. So
|
||||
* the things pinned here are the ones whose failure is invisible at the call
|
||||
* site:
|
||||
*
|
||||
* - **the guard.** `mapRef.current` is null on the first render and the style
|
||||
* is not loaded for several frames after that. Adding a layer in either
|
||||
* window throws inside an effect, which React reports as a render error on a
|
||||
* component that has nothing to do with Dawarich.
|
||||
* - **the anchor.** `beforeId` is only usable once that layer actually exists
|
||||
* on the current style; passing an unknown id to `addLayer` is a throw, not
|
||||
* a no-op, and the layer it names belongs to a different overlay that may
|
||||
* not have mounted yet.
|
||||
* - **the `trek-` prefix on every id**, which is what `applySatellite` looks
|
||||
* for when it decides where to slot the satellite tile. A layer called
|
||||
* `dawarich-trail` would end up underneath the satellite image and simply
|
||||
* not be there for the people most likely to want it.
|
||||
* - **`setData` over remove-and-add** when the source is still there, because
|
||||
* a rebuilt source flickers. The two-minute refresh does not reach that arm:
|
||||
* a fresh track object re-runs the effect and the teardown takes the source
|
||||
* with it, so what setData actually covers is a style change that kept its
|
||||
* sources. Both paths are pinned, because which one a refresh takes is the
|
||||
* difference between a line that blinks every two minutes and one that does
|
||||
* not.
|
||||
* - **one `style.load` subscription at a time.** The effect re-runs on every
|
||||
* refresh, and a cleanup that forgot to unsubscribe would add one silent
|
||||
* redraw per refresh for the life of the map.
|
||||
* - **the teardown**, which has to take both layers and the source away, and
|
||||
* has to survive a style rebuild that already took them.
|
||||
*/
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import type { Map as MapboxMap } from 'mapbox-gl'
|
||||
import type { DawarichTrack, DawarichTrackDay } from '@trek/shared'
|
||||
import { DAWARICH_DAY_COLORS, DAWARICH_TRAIL_CASING } from './dawarichTrail'
|
||||
import { useDawarichTrailGL } from './useDawarichTrailGL'
|
||||
|
||||
const SOURCE = 'trek-dawarich-trail'
|
||||
const CASING_LAYER = 'trek-dawarich-trail-casing'
|
||||
const LINE_LAYER = 'trek-dawarich-trail-line'
|
||||
|
||||
interface FakeSource {
|
||||
data: unknown
|
||||
setData: ReturnType<typeof vi.fn>
|
||||
}
|
||||
|
||||
/**
|
||||
* A GL map double that keeps real registries rather than returning fixed
|
||||
* values: the hook asks "is this already there?" before every decision it
|
||||
* makes, so a double that always answers the same way cannot exercise the
|
||||
* decisions at all.
|
||||
*/
|
||||
function fakeGlMap({ styleLoaded = true, styleLayers = [] as string[] } = {}) {
|
||||
const sources = new Map<string, FakeSource>()
|
||||
const layers = new Map<string, { spec: { id: string; paint?: Record<string, unknown> }; before: string | undefined }>()
|
||||
for (const id of styleLayers) layers.set(id, { spec: { id }, before: undefined })
|
||||
const listeners = new Map<string, Set<() => void>>()
|
||||
|
||||
const state = { styleLoaded }
|
||||
const map = {
|
||||
isStyleLoaded: vi.fn(() => state.styleLoaded),
|
||||
getSource: vi.fn((id: string) => sources.get(id)),
|
||||
addSource: vi.fn((id: string, spec: { type: string; data: unknown }) => {
|
||||
const entry: FakeSource = {
|
||||
data: spec.data,
|
||||
setData: vi.fn((next: unknown) => { entry.data = next }),
|
||||
}
|
||||
sources.set(id, entry)
|
||||
}),
|
||||
removeSource: vi.fn((id: string) => { sources.delete(id) }),
|
||||
getLayer: vi.fn((id: string) => layers.get(id)),
|
||||
addLayer: vi.fn((spec: { id: string; paint?: Record<string, unknown> }, before?: string) => {
|
||||
layers.set(spec.id, { spec, before })
|
||||
}),
|
||||
removeLayer: vi.fn((id: string) => { layers.delete(id) }),
|
||||
on: vi.fn((type: string, fn: () => void) => {
|
||||
const set = listeners.get(type) ?? new Set<() => void>()
|
||||
set.add(fn)
|
||||
listeners.set(type, set)
|
||||
}),
|
||||
off: vi.fn((type: string, fn: () => void) => { listeners.get(type)?.delete(fn) }),
|
||||
}
|
||||
|
||||
return {
|
||||
map: map as unknown as MapboxMap,
|
||||
spies: map,
|
||||
sources,
|
||||
layers,
|
||||
state,
|
||||
styleLoadListeners: () => listeners.get('style.load')?.size ?? 0,
|
||||
emitStyleLoad: () => { listeners.get('style.load')?.forEach(fn => fn()) },
|
||||
/** What a style rebuild does to the map before `style.load` fires. */
|
||||
dropStyle: () => { sources.clear(); layers.clear() },
|
||||
drawn: () => sources.get(SOURCE)?.data as
|
||||
| { features: Array<{ properties: { color: string; date: string }; geometry: { coordinates: Array<[number, number]> } }> }
|
||||
| undefined,
|
||||
}
|
||||
}
|
||||
|
||||
interface Props {
|
||||
map: MapboxMap | null
|
||||
ready: boolean
|
||||
track?: DawarichTrack | null
|
||||
date?: string | null
|
||||
before?: string
|
||||
}
|
||||
|
||||
const mount = (props: Props) =>
|
||||
renderHook((p: Props) => useDawarichTrailGL(p.map, p.ready, p.track, p.date, p.before), {
|
||||
initialProps: props,
|
||||
})
|
||||
|
||||
function day(date: string, ...segments: Array<Array<[number, number]>>): DawarichTrackDay {
|
||||
return {
|
||||
date,
|
||||
segments: segments.map(points => ({
|
||||
points,
|
||||
mode: 'driving',
|
||||
startedAt: date + 'T08:00:00.000Z',
|
||||
endedAt: date + 'T09:00:00.000Z',
|
||||
distanceMeters: 4200,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
function track(days: DawarichTrackDay[]): DawarichTrack {
|
||||
return { days, source: 'tracks', fetchedAt: '2026-05-03T10:00:00.000Z', pointCount: 4, truncated: false }
|
||||
}
|
||||
|
||||
const DAY_ONE = day('2026-05-01', [[48.2, 16.37], [48.21, 16.38]])
|
||||
const DAY_TWO = day('2026-05-02', [[45.46, 9.18], [45.47, 9.19]])
|
||||
|
||||
describe('useDawarichTrailGL', () => {
|
||||
it('FE-DAWARICH-TRAILUI-020: touches nothing before there is a map and a ready style', () => {
|
||||
const gl = fakeGlMap()
|
||||
const view = mount({ map: null, ready: true, track: track([DAY_ONE]) })
|
||||
expect(gl.spies.addSource).not.toHaveBeenCalled()
|
||||
|
||||
// A map that exists but is not ready is the more dangerous half: the object
|
||||
// answers every call and throws from inside GL rather than from here.
|
||||
view.rerender({ map: gl.map, ready: false, track: track([DAY_ONE]) })
|
||||
expect(gl.spies.addSource).not.toHaveBeenCalled()
|
||||
expect(gl.styleLoadListeners()).toBe(0)
|
||||
|
||||
view.rerender({ map: gl.map, ready: true, track: track([DAY_ONE]) })
|
||||
expect(gl.spies.addSource).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-021: builds the source and both layers under TREK-prefixed ids, anchored below the planned route', () => {
|
||||
const gl = fakeGlMap({ styleLayers: ['trip-route-casing'] })
|
||||
mount({ map: gl.map, ready: true, track: track([DAY_ONE]), before: 'trip-route-casing' })
|
||||
|
||||
expect(gl.spies.addSource).toHaveBeenCalledWith(SOURCE, expect.objectContaining({ type: 'geojson' }))
|
||||
|
||||
const [casingCall, lineCall] = gl.spies.addLayer.mock.calls
|
||||
expect(casingCall[0].id).toBe(CASING_LAYER)
|
||||
expect(casingCall[0].paint['line-color']).toBe(DAWARICH_TRAIL_CASING)
|
||||
expect(casingCall[0].paint['line-width']).toBe(6)
|
||||
expect(lineCall[0].id).toBe(LINE_LAYER)
|
||||
// Per-feature colour, with the casing white as the fallback a feature
|
||||
// without one falls back to. The GPX layer uses the same shape.
|
||||
expect(lineCall[0].paint['line-color']).toEqual(['coalesce', ['get', 'color'], DAWARICH_TRAIL_CASING])
|
||||
// Dashed, so the recording is distinguishable from the planned route for
|
||||
// someone who cannot tell the two hues apart.
|
||||
expect(lineCall[0].paint['line-dasharray']).toEqual([2, 1.6])
|
||||
|
||||
// Both go beneath the planned route's casing. The line is inserted second
|
||||
// and therefore ends up above its own casing and still below the plan.
|
||||
expect(casingCall[1]).toBe('trip-route-casing')
|
||||
expect(lineCall[1]).toBe('trip-route-casing')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-022: appends on top when the anchor layer is not on the style', () => {
|
||||
// The trip-route overlay may not have mounted yet, or may be switched off
|
||||
// entirely. Passing its id to addLayer then throws, so the hook has to look
|
||||
// before it leaps and simply append instead.
|
||||
const absent = fakeGlMap()
|
||||
mount({ map: absent.map, ready: true, track: track([DAY_ONE]), before: 'trip-route-casing' })
|
||||
expect(absent.spies.addLayer.mock.calls.map(call => call[1])).toEqual([undefined, undefined])
|
||||
|
||||
const none = fakeGlMap()
|
||||
mount({ map: none.map, ready: true, track: track([DAY_ONE]) })
|
||||
expect(none.spies.addLayer.mock.calls.map(call => call[1])).toEqual([undefined, undefined])
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-023: waits for style.load instead of drawing into a half-loaded style', () => {
|
||||
const gl = fakeGlMap({ styleLoaded: false })
|
||||
mount({ map: gl.map, ready: true, track: track([DAY_ONE]) })
|
||||
|
||||
expect(gl.spies.addSource).not.toHaveBeenCalled()
|
||||
expect(gl.styleLoadListeners()).toBe(1)
|
||||
|
||||
// The whole GL map is torn down and reassembled when the provider, the
|
||||
// style or the token changes; this subscription is what puts the overlay
|
||||
// back afterwards.
|
||||
gl.state.styleLoaded = true
|
||||
gl.emitStyleLoad()
|
||||
expect(gl.spies.addSource).toHaveBeenCalledTimes(1)
|
||||
expect(gl.spies.addLayer).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-024: updates a surviving source in place rather than rebuilding it', () => {
|
||||
const gl = fakeGlMap()
|
||||
mount({ map: gl.map, ready: true, track: track([DAY_ONE]) })
|
||||
expect(gl.spies.addSource).toHaveBeenCalledTimes(1)
|
||||
|
||||
// A style change that kept its sources, which is what setStyle does when it
|
||||
// can diff the two. Rebuilding the source here would flicker the line for
|
||||
// nothing, so the hook writes into the one that is already on the map.
|
||||
gl.emitStyleLoad()
|
||||
expect(gl.spies.addSource).toHaveBeenCalledTimes(1)
|
||||
expect(gl.spies.addLayer).toHaveBeenCalledTimes(2)
|
||||
expect(gl.sources.get(SOURCE)?.setData).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-025: hands GL the recording in GeoJSON order, and an empty collection when there is none', () => {
|
||||
const empty = fakeGlMap()
|
||||
mount({ map: empty.map, ready: true, track: null })
|
||||
// An empty collection rather than a skipped source: the layers still have
|
||||
// to be on the style, so a style change that keeps its sources finds
|
||||
// something to write into instead of leaving the map bare.
|
||||
expect(empty.drawn()?.features).toEqual([])
|
||||
|
||||
// The track parameter is optional, so the overlay also has to build before
|
||||
// anyone has handed the hook a track at all. Same empty collection, reached
|
||||
// through the `?? null` rather than through an explicit null.
|
||||
const unfetched = fakeGlMap()
|
||||
mount({ map: unfetched.map, ready: true })
|
||||
expect(unfetched.drawn()?.features).toEqual([])
|
||||
|
||||
const gl = fakeGlMap()
|
||||
mount({ map: gl.map, ready: true, track: track([DAY_ONE, DAY_TWO]) })
|
||||
const features = gl.drawn()?.features ?? []
|
||||
expect(features).toHaveLength(2)
|
||||
// TREK stores [lat, lng] everywhere; GeoJSON wants the other order, and the
|
||||
// overlay is the single place that flips it. Getting this backwards puts
|
||||
// Vienna in the Indian Ocean.
|
||||
expect(features[0].geometry.coordinates).toEqual([[16.37, 48.2], [16.38, 48.21]])
|
||||
expect(features[0].properties.color).toBe(DAWARICH_DAY_COLORS[0])
|
||||
expect(features[1].properties.color).toBe(DAWARICH_DAY_COLORS[1])
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-026: redraws for a picked day without repainting it', () => {
|
||||
const gl = fakeGlMap()
|
||||
const view = mount({ map: gl.map, ready: true, track: track([DAY_ONE, DAY_TWO]) })
|
||||
|
||||
view.rerender({ map: gl.map, ready: true, track: track([DAY_ONE, DAY_TWO]), date: '2026-05-02' })
|
||||
const features = gl.drawn()?.features ?? []
|
||||
expect(features).toHaveLength(1)
|
||||
expect(features[0].properties.date).toBe('2026-05-02')
|
||||
// Still the second hue, because the index comes from the day's place in the
|
||||
// whole track. Picking a day must dim the others, not recolour the one.
|
||||
expect(features[0].properties.color).toBe(DAWARICH_DAY_COLORS[1])
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-027: takes both layers and the source away with it, and stops listening', () => {
|
||||
const gl = fakeGlMap()
|
||||
const view = mount({ map: gl.map, ready: true, track: track([DAY_ONE]) })
|
||||
|
||||
view.unmount()
|
||||
|
||||
// Layers before the source, in that order: a GL map refuses to remove a
|
||||
// source that still carries a layer, so a teardown that started with the
|
||||
// source would throw and leave both layers behind.
|
||||
expect(gl.spies.removeLayer.mock.calls.map(call => call[0])).toEqual([LINE_LAYER, CASING_LAYER])
|
||||
expect(gl.spies.removeSource).toHaveBeenCalledWith(SOURCE)
|
||||
expect(gl.layers.size).toBe(0)
|
||||
expect(gl.sources.size).toBe(0)
|
||||
expect(gl.styleLoadListeners()).toBe(0)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-028: does not try to remove what a style rebuild already took', () => {
|
||||
const gl = fakeGlMap()
|
||||
const view = mount({ map: gl.map, ready: true, track: track([DAY_ONE]) })
|
||||
|
||||
// setStyle drops every source and layer the previous style carried. The
|
||||
// teardown then runs against a map that has never heard of them, and a
|
||||
// blind removeLayer there throws out of a cleanup function.
|
||||
gl.dropStyle()
|
||||
view.unmount()
|
||||
|
||||
expect(gl.spies.removeLayer).not.toHaveBeenCalled()
|
||||
expect(gl.spies.removeSource).not.toHaveBeenCalled()
|
||||
expect(gl.spies.off).toHaveBeenCalledWith('style.load', expect.any(Function))
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-TRAILUI-029: rebuilds the overlay when the refresh hands it a new track, without leaving a listener behind', () => {
|
||||
const gl = fakeGlMap()
|
||||
const view = mount({ map: gl.map, ready: true, track: track([DAY_ONE]) })
|
||||
const firstSource = gl.sources.get(SOURCE)
|
||||
expect(firstSource?.setData).toBeTypeOf('function')
|
||||
|
||||
// `useDawarichTrail` refetches every two minutes and returns a fresh object
|
||||
// every time, so the effect's dependency changes and React tears the whole
|
||||
// overlay down before rebuilding it. The setData path above belongs to a
|
||||
// style change that kept its sources, not to a refresh. Pinned as the
|
||||
// behaviour it is, so that making the refresh cheap later is a visible
|
||||
// change to this file rather than a silent one on the map.
|
||||
view.rerender({ map: gl.map, ready: true, track: track([DAY_ONE, DAY_TWO]) })
|
||||
|
||||
expect(gl.spies.removeSource).toHaveBeenCalledWith(SOURCE)
|
||||
expect(gl.spies.addSource).toHaveBeenCalledTimes(2)
|
||||
expect(firstSource?.setData).not.toHaveBeenCalled()
|
||||
expect(gl.drawn()?.features).toHaveLength(2)
|
||||
|
||||
// One subscription, not two. The cleanup unsubscribes before the next
|
||||
// effect subscribes; without that the overlay would redraw once per style
|
||||
// change per refresh, for as long as the map lives.
|
||||
expect(gl.styleLoadListeners()).toBe(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,597 @@
|
||||
/**
|
||||
* FE-DAWARICH-SETTINGS-001 to FE-DAWARICH-SETTINGS-018: the desktop
|
||||
* Settings -> Integrations -> Dawarich card.
|
||||
*
|
||||
* The card is markup over `useDawarichConnection`, so it is driven here the way
|
||||
* the AirTrail card next to it is driven: the real hook, the real axios client,
|
||||
* MSW answering the four endpoints. A test that handed the section a fake state
|
||||
* object would pin the JSX and nothing else, and the things that actually break
|
||||
* on this surface are round trips: what leaves in the PUT body, what the card
|
||||
* believes after the answer comes back.
|
||||
*
|
||||
* What is worth pinning, and what breaks if it regresses:
|
||||
*
|
||||
* - **The key is never prefilled.** The server answers with a mask, never the
|
||||
* stored key, and the field stays empty; the mask is only a placeholder. If
|
||||
* the field were ever bound to the masked value, saving would send the
|
||||
* bullets as the new key and lock the user out of their own instance.
|
||||
* - **Blank key means "keep the stored one".** A connected instance must save a
|
||||
* changed URL or a changed toggle without the user digging their key out
|
||||
* again, so `apiKey` is absent from the body, not an empty string, which the
|
||||
* server would read as "clear it".
|
||||
* - **`canSave`.** An address alone is not a connection: saving needs either an
|
||||
* existing connection or a typed key. And nothing may be saved while the card
|
||||
* is still reading the settings it is about to overwrite.
|
||||
* - **The status block**, which is the part of this card that earns its space.
|
||||
* A connection to somebody else's server fails in ways the owner can act on
|
||||
* (a rejected key, a certificate, a Dawarich too old for half the endpoints),
|
||||
* and every one of those reasons reaches the reader through this one block.
|
||||
* Each branch of it (probe message, never-synced vs. last-synced, the partial
|
||||
* suffix, the stored error, the server version, the missing-capability list)
|
||||
* is pinned, because a silent one turns "not connected" into a support ticket.
|
||||
* - **The capability list's `tracks || points` rule.** The recorded route can
|
||||
* come from either endpoint, so only an instance offering neither is missing
|
||||
* it. Reporting "recorded route" as missing on an instance that serves points
|
||||
* would tell the user to upgrade for something they already have.
|
||||
*
|
||||
* Toasts are asserted through a mocked `useToast` rather than a rendered
|
||||
* container: two of them repeat the sentence the status block already shows, and
|
||||
* a duplicated string makes every `getByText` in this file ambiguous.
|
||||
*/
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { DawarichCapabilities } from '@trek/shared';
|
||||
import { render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import { server } from '../../../tests/helpers/msw/server';
|
||||
import { resetAllStores } from '../../../tests/helpers/store';
|
||||
import DawarichConnectionSection from './DawarichConnectionSection';
|
||||
|
||||
const toast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() };
|
||||
vi.mock('../shared/Toast', () => ({
|
||||
useToast: () => toast,
|
||||
default: () => toast,
|
||||
ToastContainer: () => null,
|
||||
}));
|
||||
|
||||
const SETTINGS_URL = '/api/integrations/dawarich/settings';
|
||||
const TEST_URL = '/api/integrations/dawarich/test';
|
||||
const SYNC_URL = '/api/integrations/dawarich/sync';
|
||||
|
||||
/** The desktop card renders this exact placeholder in place of a stored key. */
|
||||
const MASK = '••••••••';
|
||||
|
||||
interface SavedBody {
|
||||
url: string;
|
||||
apiKey?: string;
|
||||
allowInsecureTls?: boolean;
|
||||
syncEnabled?: boolean;
|
||||
}
|
||||
|
||||
/** A Dawarich that answers everything TREK knows how to ask for. */
|
||||
const CAPS_ALL: DawarichCapabilities = {
|
||||
visits: true,
|
||||
tracks: true,
|
||||
points: true,
|
||||
locations: true,
|
||||
visitedCities: true,
|
||||
visitUpdatedAt: true,
|
||||
visitCountryCode: true,
|
||||
serverVersion: '1.14.4',
|
||||
probedAt: '2026-09-12T09:00:00.000Z',
|
||||
};
|
||||
|
||||
function caps(over: Partial<DawarichCapabilities> = {}): DawarichCapabilities {
|
||||
return { ...CAPS_ALL, ...over };
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored connection, as the GET answers it. Mutable because saving and
|
||||
* disconnecting re-read it: the card's post-write state comes from this second
|
||||
* read, not from the write's own answer, so the stub has to behave like a store
|
||||
* rather than a fixture.
|
||||
*/
|
||||
let stored: Record<string, unknown>;
|
||||
|
||||
const DISCONNECTED = {
|
||||
url: '',
|
||||
apiKeyMasked: '',
|
||||
allowInsecureTls: false,
|
||||
syncEnabled: true,
|
||||
connected: false,
|
||||
lastSyncAt: null,
|
||||
lastSyncState: 'never',
|
||||
lastSyncError: null,
|
||||
capabilities: null,
|
||||
};
|
||||
|
||||
const CONNECTED = {
|
||||
...DISCONNECTED,
|
||||
url: 'https://dawarich.example.com',
|
||||
apiKeyMasked: MASK,
|
||||
connected: true,
|
||||
capabilities: CAPS_ALL,
|
||||
};
|
||||
|
||||
function stubSettings(over: Record<string, unknown> = {}): void {
|
||||
stored = { ...DISCONNECTED, ...over };
|
||||
server.use(http.get(SETTINGS_URL, () => HttpResponse.json(stored)));
|
||||
}
|
||||
|
||||
/** A promise the test releases by hand, to observe an in-flight request. */
|
||||
function deferred(): { promise: Promise<void>; release: () => void } {
|
||||
let release!: () => void;
|
||||
const promise = new Promise<void>(resolve => {
|
||||
release = resolve;
|
||||
});
|
||||
return { promise, release };
|
||||
}
|
||||
|
||||
function renderSection() {
|
||||
return render(<DawarichConnectionSection />);
|
||||
}
|
||||
|
||||
/** Both switches carry their label as an aria-label, so the role query reaches them. */
|
||||
function toggle(label: string): HTMLElement {
|
||||
return screen.getByRole('button', { name: label });
|
||||
}
|
||||
|
||||
const SYNC_TOGGLE = 'Check for new stays automatically';
|
||||
const TLS_TOGGLE = 'Allow self-signed certificate';
|
||||
|
||||
function urlField(): HTMLElement {
|
||||
return screen.getByLabelText('Instance address');
|
||||
}
|
||||
|
||||
function keyField(): HTMLElement {
|
||||
return screen.getByLabelText('API key');
|
||||
}
|
||||
|
||||
function saveButton(): HTMLElement {
|
||||
return screen.getByRole('button', { name: /^Save$/ });
|
||||
}
|
||||
|
||||
function testButton(): HTMLElement {
|
||||
return screen.getByRole('button', { name: 'Test connection' });
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
vi.clearAllMocks();
|
||||
stubSettings();
|
||||
});
|
||||
|
||||
describe('DawarichConnectionSection', () => {
|
||||
it('FE-DAWARICH-SETTINGS-001: an unconfigured card is empty, disconnected, blocked and shows no status block', async () => {
|
||||
// An unconfigured card looks identical before and after its settings land,
|
||||
// so there is no rendered marker to wait on. Counting the read is what
|
||||
// makes the assertions below about a hydrated card rather than first paint.
|
||||
const read = vi.fn();
|
||||
server.use(
|
||||
http.get(SETTINGS_URL, () => {
|
||||
read();
|
||||
return HttpResponse.json(stored);
|
||||
}),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await waitFor(() => expect(read).toHaveBeenCalled());
|
||||
expect(testButton()).toBeDisabled();
|
||||
expect(saveButton()).toBeDisabled();
|
||||
expect(urlField()).toHaveValue('');
|
||||
expect(keyField()).toHaveValue('');
|
||||
// No connection means no key to hide, so the field says what it wants.
|
||||
expect(keyField()).toHaveAttribute('placeholder', 'Paste your Dawarich API key');
|
||||
expect(screen.getByText('Not connected')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Check now' })).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: 'Disconnect' })).toBeNull();
|
||||
// Nothing to report yet: the block would be an empty grey box.
|
||||
expect(screen.queryByText('Not checked yet')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-002: a stored connection hydrates the fields, the toggles, the badge and the status block', async () => {
|
||||
stubSettings({
|
||||
...CONNECTED,
|
||||
allowInsecureTls: true,
|
||||
syncEnabled: false,
|
||||
lastSyncAt: '2026-09-12T08:30:00.000Z',
|
||||
lastSyncState: 'ok',
|
||||
});
|
||||
renderSection();
|
||||
|
||||
expect(await screen.findByDisplayValue('https://dawarich.example.com')).toBeInTheDocument();
|
||||
expect(toggle(TLS_TOGGLE)).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(toggle(SYNC_TOGGLE)).toHaveAttribute('aria-pressed', 'false');
|
||||
expect(screen.getByText('Connected')).toBeInTheDocument();
|
||||
// The stored key is hidden behind the placeholder and never put in the field.
|
||||
expect(keyField()).toHaveAttribute('placeholder', MASK);
|
||||
expect(keyField()).toHaveValue('');
|
||||
expect(screen.getByRole('button', { name: 'Check now' })).toBeEnabled();
|
||||
expect(screen.getByRole('button', { name: 'Disconnect' })).toBeEnabled();
|
||||
expect(screen.getByText(/^Last checked /)).toBeInTheDocument();
|
||||
expect(screen.getByText('Dawarich 1.14.4')).toBeInTheDocument();
|
||||
// Everything answered, so there is nothing to warn about.
|
||||
expect(screen.queryByText(/does not offer/)).toBeNull();
|
||||
expect(screen.queryByText('some trips could not be read')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-003: a failed read of our own settings leaves an empty card rather than a false verdict', async () => {
|
||||
// Same as -001: a failed read changes nothing on screen, so the request
|
||||
// itself is the only proof the card got as far as failing.
|
||||
const read = vi.fn();
|
||||
server.use(
|
||||
http.get(SETTINGS_URL, () => {
|
||||
read();
|
||||
return HttpResponse.json({ error: 'boom' }, { status: 500 });
|
||||
}),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
// Losing our own settings is a TREK problem: the card must not claim the
|
||||
// user's instance is unreachable, and must not stay locked in `loading`.
|
||||
await waitFor(() => expect(read).toHaveBeenCalled());
|
||||
await waitFor(() => expect(testButton()).toBeDisabled());
|
||||
expect(screen.getByText('Not connected')).toBeInTheDocument();
|
||||
expect(urlField()).toHaveValue('');
|
||||
expect(screen.queryByText('Not checked yet')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-004: nothing can be saved while the stored settings are still being read', async () => {
|
||||
const user = userEvent.setup();
|
||||
const gate = deferred();
|
||||
server.use(
|
||||
http.get(SETTINGS_URL, async () => {
|
||||
await gate.promise;
|
||||
return HttpResponse.json({ ...CONNECTED, connected: false });
|
||||
}),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await user.type(urlField(), 'https://typed.example.com');
|
||||
await user.type(keyField(), 'typed-key');
|
||||
// URL and key are both there, so only the in-flight read is holding Save.
|
||||
expect(saveButton()).toBeDisabled();
|
||||
// And the same lock on Test. With an address typed this is the one place
|
||||
// the `loading` term of that condition is visible at all. Everywhere else
|
||||
// the empty-address term hides it.
|
||||
expect(testButton()).toBeDisabled();
|
||||
|
||||
gate.release();
|
||||
await waitFor(() => expect(saveButton()).toBeEnabled());
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-005: a stored address that never connected still needs a typed key before it can be saved', async () => {
|
||||
const user = userEvent.setup();
|
||||
// The state a failed first attempt leaves behind: the address was stored,
|
||||
// the key was not accepted, so there is no connection to fall back on.
|
||||
stubSettings({ url: 'https://dawarich.example.com', connected: false });
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://dawarich.example.com');
|
||||
// The address is enough to probe with, but not enough to store. Waited for
|
||||
// rather than read straight off the render that showed the address: the
|
||||
// hook drops the `loading` lock in a later tick than it sets the fields.
|
||||
await waitFor(() => expect(testButton()).toBeEnabled());
|
||||
expect(saveButton()).toBeDisabled();
|
||||
|
||||
await user.type(keyField(), 'key-123');
|
||||
expect(saveButton()).toBeEnabled();
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-006: a connected instance saves without retyping the key, and typing one drops the mask', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: SavedBody | undefined;
|
||||
stubSettings(CONNECTED);
|
||||
server.use(
|
||||
http.put(SETTINGS_URL, async ({ request }) => {
|
||||
body = (await request.json()) as SavedBody;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://dawarich.example.com');
|
||||
// A click on a disabled button is swallowed rather than failing, so every
|
||||
// click below waits for the `loading` lock to lift first.
|
||||
await waitFor(() => expect(saveButton()).toBeEnabled());
|
||||
await user.click(saveButton());
|
||||
|
||||
// No `apiKey` key at all: an empty string would read as "clear the key".
|
||||
await waitFor(() =>
|
||||
expect(body).toEqual({
|
||||
url: 'https://dawarich.example.com',
|
||||
allowInsecureTls: false,
|
||||
syncEnabled: true,
|
||||
}),
|
||||
);
|
||||
await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Dawarich connection saved'));
|
||||
|
||||
await user.type(keyField(), 'replacement');
|
||||
// Once there is something to send, the mask stops pretending the field is full.
|
||||
expect(keyField()).toHaveAttribute('placeholder', 'Paste your Dawarich API key');
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-007: the save sends the trimmed address, the typed key and both toggles, then clears the key field', async () => {
|
||||
const user = userEvent.setup();
|
||||
let body: SavedBody | undefined;
|
||||
// Auto-sync stored as off, so the switch flipping to on is the proof that
|
||||
// the settings read landed before anything is typed: the effect that
|
||||
// hydrates the card also rewrites the URL field.
|
||||
stubSettings({ syncEnabled: false });
|
||||
server.use(
|
||||
http.put(SETTINGS_URL, async ({ request }) => {
|
||||
body = (await request.json()) as SavedBody;
|
||||
// The card believes the re-read, not the write's own answer.
|
||||
stored = { ...stored, url: body.url, connected: true, capabilities: CAPS_ALL };
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await waitFor(() => expect(toggle(SYNC_TOGGLE)).toHaveAttribute('aria-pressed', 'false'));
|
||||
// Both fields are padded, but only the key actually pins `trim()`: jsdom
|
||||
// runs the value-sanitisation algorithm for input[type=url], which strips
|
||||
// the surrounding whitespace before the hook ever sees the address. The
|
||||
// password field has no such algorithm, so the space it keeps is real.
|
||||
await user.type(urlField(), ' https://dawarich.example.com ');
|
||||
await user.type(keyField(), ' key-123 ');
|
||||
await user.click(toggle(SYNC_TOGGLE));
|
||||
await user.click(toggle(TLS_TOGGLE));
|
||||
await user.click(saveButton());
|
||||
|
||||
// Both switches send what is on screen, not what was stored.
|
||||
await waitFor(() =>
|
||||
expect(body).toEqual({
|
||||
url: 'https://dawarich.example.com',
|
||||
allowInsecureTls: true,
|
||||
syncEnabled: true,
|
||||
apiKey: 'key-123',
|
||||
}),
|
||||
);
|
||||
expect(toggle(SYNC_TOGGLE)).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(toggle(TLS_TOGGLE)).toHaveAttribute('aria-pressed', 'true');
|
||||
await waitFor(() => expect(screen.getByText('Connected')).toBeInTheDocument());
|
||||
expect(keyField()).toHaveValue('');
|
||||
expect(keyField()).toHaveAttribute('placeholder', MASK);
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-008: an in-flight save locks both Save and Disconnect', async () => {
|
||||
const user = userEvent.setup();
|
||||
const gate = deferred();
|
||||
stubSettings(CONNECTED);
|
||||
server.use(
|
||||
http.put(SETTINGS_URL, async () => {
|
||||
await gate.promise;
|
||||
return HttpResponse.json({ success: true });
|
||||
}),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://dawarich.example.com');
|
||||
await waitFor(() => expect(saveButton()).toBeEnabled());
|
||||
await user.click(saveButton());
|
||||
|
||||
await waitFor(() => expect(saveButton()).toBeDisabled());
|
||||
// Disconnecting mid-save would race the write it is trying to undo.
|
||||
expect(screen.getByRole('button', { name: 'Disconnect' })).toBeDisabled();
|
||||
|
||||
gate.release();
|
||||
await waitFor(() => expect(saveButton()).toBeEnabled());
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-009: a rejected save reports the server reason code as a sentence, not as a code', async () => {
|
||||
const user = userEvent.setup();
|
||||
stubSettings(CONNECTED);
|
||||
server.use(
|
||||
http.put(SETTINGS_URL, () =>
|
||||
HttpResponse.json({ code: 'unauthorized', error: 'Unauthorized' }, { status: 400 }),
|
||||
),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://dawarich.example.com');
|
||||
await waitFor(() => expect(saveButton()).toBeEnabled());
|
||||
await user.click(saveButton());
|
||||
|
||||
// The code wins over the server's English prose, so a German install reads German.
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Dawarich rejected the API key.'));
|
||||
// A refused save leaves the card usable so the reader can correct the key.
|
||||
await waitFor(() => expect(saveButton()).toBeEnabled());
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-010: a probe shows a spinner while it runs, then reports the stay count and flips the badge', async () => {
|
||||
const user = userEvent.setup();
|
||||
const gate = deferred();
|
||||
let body: Partial<SavedBody> | undefined;
|
||||
stubSettings({ url: 'https://dawarich.example.com' });
|
||||
server.use(
|
||||
http.post(TEST_URL, async ({ request }) => {
|
||||
body = (await request.json()) as Partial<SavedBody>;
|
||||
await gate.promise;
|
||||
return HttpResponse.json({ connected: true, visitCount: 12, capabilities: CAPS_ALL });
|
||||
}),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://dawarich.example.com');
|
||||
await waitFor(() => expect(testButton()).toBeEnabled());
|
||||
await user.type(keyField(), 'probe-key');
|
||||
await user.click(testButton());
|
||||
|
||||
await waitFor(() => expect(testButton()).toBeDisabled());
|
||||
expect(testButton().querySelector('.animate-spin')).not.toBeNull();
|
||||
|
||||
gate.release();
|
||||
expect(await screen.findByText('Connected. 12 stays found in the last 30 days.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Connected')).toBeInTheDocument();
|
||||
// The probe uses what is on screen, not what is stored. That is the point of it.
|
||||
expect(body).toEqual({ url: 'https://dawarich.example.com', allowInsecureTls: false, apiKey: 'probe-key' });
|
||||
expect(screen.getByText('Dawarich 1.14.4')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-011: a refused probe keeps the badge off and puts the reason plus the detail in the status block', async () => {
|
||||
const user = userEvent.setup();
|
||||
stubSettings({ url: 'https://dawarich.example.com' });
|
||||
server.use(
|
||||
http.post(TEST_URL, () =>
|
||||
HttpResponse.json({
|
||||
connected: false,
|
||||
error: 'unreachable',
|
||||
errorDetail: 'self-signed certificate in chain',
|
||||
}),
|
||||
),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://dawarich.example.com');
|
||||
await waitFor(() => expect(testButton()).toBeEnabled());
|
||||
await user.click(testButton());
|
||||
|
||||
// The block gets the detail, the toast stays one line: a self-hoster needs
|
||||
// to know it was the certificate and not the host being down.
|
||||
expect(
|
||||
await screen.findByText('TREK could not reach that address. (self-signed certificate in chain)'),
|
||||
).toBeInTheDocument();
|
||||
expect(toast.error).toHaveBeenCalledWith('TREK could not reach that address.');
|
||||
expect(screen.getByText('Not connected')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-012: a probe that never reaches the server falls back to the generic sentence', async () => {
|
||||
const user = userEvent.setup();
|
||||
stubSettings({ url: 'https://dawarich.example.com' });
|
||||
server.use(http.post(TEST_URL, () => HttpResponse.json({}, { status: 500 })));
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://dawarich.example.com');
|
||||
await waitFor(() => expect(testButton()).toBeEnabled());
|
||||
await user.click(testButton());
|
||||
|
||||
// No code and no prose from the server: exactly one sentence, no empty parentheses.
|
||||
expect(await screen.findByText('Could not reach Dawarich.')).toBeInTheDocument();
|
||||
expect(toast.error).toHaveBeenCalledWith('Could not reach Dawarich.');
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-013: Check now spins while it runs and replaces "never" with a timestamp', async () => {
|
||||
const user = userEvent.setup();
|
||||
const gate = deferred();
|
||||
stubSettings(CONNECTED);
|
||||
server.use(
|
||||
http.post(SYNC_URL, async () => {
|
||||
await gate.promise;
|
||||
return HttpResponse.json({ state: 'ok', created: 3, updated: 0, missing: 0 });
|
||||
}),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
expect(await screen.findByText('Not checked yet')).toBeInTheDocument();
|
||||
const syncBtn = screen.getByRole('button', { name: 'Check now' });
|
||||
await user.click(syncBtn);
|
||||
|
||||
await waitFor(() => expect(syncBtn).toBeDisabled());
|
||||
expect(syncBtn.querySelector('.animate-spin')).not.toBeNull();
|
||||
|
||||
gate.release();
|
||||
expect(await screen.findByText(/^Last checked /)).toBeInTheDocument();
|
||||
expect(screen.queryByText('Not checked yet')).toBeNull();
|
||||
// Said as a count: a sync that found nothing and one that failed silently
|
||||
// look identical if the toast only says "done".
|
||||
expect(toast.success).toHaveBeenCalledWith('3 new stays found');
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-014: a sync that is already running reports itself and invents no result', async () => {
|
||||
const user = userEvent.setup();
|
||||
stubSettings(CONNECTED);
|
||||
server.use(
|
||||
http.post(SYNC_URL, () =>
|
||||
HttpResponse.json({ state: 'ok', created: 0, updated: 0, missing: 0, alreadyRunning: true }),
|
||||
),
|
||||
);
|
||||
renderSection();
|
||||
|
||||
await screen.findByText('Not checked yet');
|
||||
await user.click(screen.getByRole('button', { name: 'Check now' }));
|
||||
|
||||
await waitFor(() => expect(toast.info).toHaveBeenCalledWith('A check is already running'));
|
||||
// "0 new stays" would be a result, and there is no result yet.
|
||||
expect(toast.success).not.toHaveBeenCalled();
|
||||
expect(screen.getByText('Not checked yet')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-015: a failed sync falls back to the generic message and leaves the last timestamp alone', async () => {
|
||||
const user = userEvent.setup();
|
||||
stubSettings({ ...CONNECTED, lastSyncAt: '2026-09-12T08:30:00.000Z', lastSyncState: 'ok' });
|
||||
server.use(http.post(SYNC_URL, () => HttpResponse.json({}, { status: 502 })));
|
||||
renderSection();
|
||||
|
||||
await screen.findByText(/^Last checked /);
|
||||
await user.click(screen.getByRole('button', { name: 'Check now' }));
|
||||
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Could not read Dawarich'));
|
||||
// A failed attempt is not a check: the timestamp still belongs to the last real one.
|
||||
expect(screen.getByText(/^Last checked /)).toBeInTheDocument();
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Check now' })).toBeEnabled());
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-016: a partial sync on an old instance shows the suffix, the stored reason and every missing capability', async () => {
|
||||
stubSettings({
|
||||
...CONNECTED,
|
||||
lastSyncAt: '2026-09-12T08:30:00.000Z',
|
||||
lastSyncState: 'partial',
|
||||
lastSyncError: 'unauthorized',
|
||||
capabilities: caps({
|
||||
visits: false,
|
||||
tracks: false,
|
||||
points: false,
|
||||
locations: false,
|
||||
visitedCities: false,
|
||||
serverVersion: null,
|
||||
}),
|
||||
});
|
||||
renderSection();
|
||||
|
||||
expect(await screen.findByText(/some trips could not be read/)).toBeInTheDocument();
|
||||
expect(screen.getByText('Dawarich rejected the API key.')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(
|
||||
'This Dawarich version does not offer: stays, recorded route, wishlist matching, countries and cities.',
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
// An instance that does not report its version gets no version line at all,
|
||||
// rather than a line with a blank in it. (The section heading is the bare
|
||||
// word "Dawarich", so the version line is the one followed by a digit.)
|
||||
expect(screen.queryByText(/^Dawarich \d/)).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-017: an instance serving points but not tracks is not told its recorded route is missing', async () => {
|
||||
stubSettings({
|
||||
...CONNECTED,
|
||||
capabilities: caps({ tracks: false, points: true, visitedCities: false, serverVersion: '1.15.0' }),
|
||||
});
|
||||
renderSection();
|
||||
|
||||
// Either endpoint can draw the route, so only the Atlas feed is actually gone.
|
||||
expect(await screen.findByText('This Dawarich version does not offer: countries and cities.')).toBeInTheDocument();
|
||||
expect(screen.getByText('Dawarich 1.15.0')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-DAWARICH-SETTINGS-018: disconnecting empties the card back to its unconfigured state', async () => {
|
||||
const user = userEvent.setup();
|
||||
stubSettings({ ...CONNECTED, lastSyncAt: '2026-09-12T08:30:00.000Z', lastSyncState: 'ok' });
|
||||
server.use(http.delete(SETTINGS_URL, () => HttpResponse.json({ success: true })));
|
||||
renderSection();
|
||||
|
||||
await screen.findByDisplayValue('https://dawarich.example.com');
|
||||
await user.click(screen.getByRole('button', { name: 'Disconnect' }));
|
||||
|
||||
await waitFor(() => expect(screen.getByText('Not connected')).toBeInTheDocument());
|
||||
expect(toast.success).toHaveBeenCalledWith('Dawarich disconnected');
|
||||
expect(urlField()).toHaveValue('');
|
||||
expect(keyField()).toHaveAttribute('placeholder', 'Paste your Dawarich API key');
|
||||
expect(screen.queryByRole('button', { name: 'Check now' })).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: 'Disconnect' })).toBeNull();
|
||||
// Nothing left to report, so the whole status block goes with it.
|
||||
expect(screen.queryByText(/^Last checked /)).toBeNull();
|
||||
expect(screen.queryByText('Not checked yet')).toBeNull();
|
||||
expect(screen.queryByText('Dawarich 1.14.4')).toBeNull();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user