Merge branch 'dev' into feat/comaps-integration

# Conflicts:
#	client/src/components/Planner/DayPlanSidebar.tsx
This commit is contained in:
Konstantinos Thermos
2026-08-14 15:05:00 +03:00
367 changed files with 8734 additions and 1431 deletions
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { hasTicketSplit, payerSum, payersBalanced, readTicketItems, readUserNote, rebalancePayers, splitCents, writeTicketItems } from './CostsPanel.helpers'
import { calculateTicketShares, hasTicketSplit, payerSum, payersBalanced, readTicketItems, readUserNote, rebalancePayers, splitCents, writeTicketItems, type TicketItem } from './CostsPanel.helpers'
describe('splitCents', () => {
it('splits evenly when it divides cleanly', () => {
@@ -132,3 +132,47 @@ describe('readUserNote', () => {
expect(readUserNote(null)).toBe('')
})
})
// ── Receipt splits have to reconcile (#1382) ─────────────────────────────────
describe('calculateTicketShares', () => {
const line = (price: string, parts: number[]): TicketItem =>
({ id: price + parts.join(), name: 'Line', price, participants: new Set(parts) })
const shareSum = (shares: Record<number, number>) =>
Object.values(shares).reduce((a, v) => a + Math.round(v * 100), 0)
it('splits each line among the people on it', () => {
const { shares, total } = calculateTicketShares([line('10', [1, 2]), line('6', [2])])
expect(shares).toEqual({ 1: 5, 2: 11 })
expect(total).toBe(16)
})
it('spreads a line nobody was ticked for across everyone on the receipt', () => {
// The service charge used to count toward the total and toward nobody's share,
// so the expense carried a permanent difference no settle-up could clear.
const { shares, total } = calculateTicketShares([
line('10', [1, 2]),
line('5', []),
line('x', [2]),
])
expect(shares).toEqual({ 1: 7.5, 2: 7.5 })
expect(total).toBe(15)
expect(shareSum(shares)).toBe(Math.round(total * 100))
})
it('hands out the remainder cents so the shares add back up to the total', () => {
const { shares, total } = calculateTicketShares([line('10', [1, 2, 3]), line('0.01', [])])
expect(shareSum(shares)).toBe(Math.round(total * 100))
expect(total).toBe(10.01)
})
it('splits nothing when the receipt has no participants anywhere', () => {
const { shares, total } = calculateTicketShares([line('10', []), line('5', [])])
expect(shares).toEqual({})
expect(total).toBe(15)
})
it('is empty for an empty receipt', () => {
expect(calculateTicketShares([])).toEqual({ shares: {}, total: 0 })
})
})
@@ -135,24 +135,36 @@ export function readUserNote(item: { note?: string | null } | null | undefined):
return note && !note.startsWith('TICKETJSON:') ? note : ''
}
/** Per-person totals for a receipt split line by line, plus the receipt total. */
/**
* Per-person totals for a receipt split line by line, plus the receipt total.
*
* Every cent on the receipt lands on somebody: a line nobody was ticked for is
* carried by everyone who appears on the receipt, so the shares add back up to
* the total. They used to count toward the total only, which left the expense
* with member debits that could never cancel the payer's credit — a permanent
* difference the settle-up view showed as debt but had no flow to clear (#1382).
* A receipt with no participants at all splits nothing; it is not saveable
* anyway, since every line needs someone on it.
*/
export function calculateTicketShares(items: TicketItem[]): { shares: Record<number, number>; total: number } {
const shares: Record<number, number> = {}
let totalCents = 0
const everyone = [...new Set(items.flatMap(i => [...i.participants]))].sort((a, b) => a - b)
for (const item of items) {
const priceNum = parseFloat(item.price) || 0
const priceCents = Math.round(priceNum * 100)
totalCents += priceCents
const partIds = [...item.participants]
const n = partIds.length
const sortedPartIds = item.participants.size > 0
? [...item.participants].sort((a, b) => a - b)
: everyone
const n = sortedPartIds.length
if (n === 0) continue
const baseCents = Math.floor(priceCents / n)
const remainder = priceCents % n
const sortedPartIds = [...partIds].sort((a, b) => a - b)
const remainder = priceCents - baseCents * n
for (let i = 0; i < n; i++) {
const id = sortedPartIds[i]
@@ -1393,6 +1393,26 @@ describe('CostsPanel — expense modal', () => {
expect(posted).toMatchObject({ name: 'Hotel Astoria', category: 'accommodation', total_price: 240, reservation_id: 12 })
expect(onSaved).toHaveBeenCalled()
})
it('FE-W5COSTS-038b: a prefill from a place links the expense to that place (#1298)', async () => {
const user = userEvent.setup()
let posted: Record<string, unknown> | null = null
server.use(http.post('/api/trips/1/budget', async ({ request }) => {
posted = await request.json() as Record<string, unknown>
return HttpResponse.json({ item: dinner() })
}))
render(
<ExpenseModal tripId={1} base="EUR" people={tripMembers} me={1} editing={null}
prefill={{ name: 'Louvre', category: 'activities', amount: 34, placeId: 7 }}
onClose={() => {}} onSaved={vi.fn()} />
)
await user.click(screen.getByRole('button', { name: 'Add expense' }))
await waitFor(() => expect(posted).toBeTruthy());
expect(posted).toMatchObject({ name: 'Louvre', category: 'activities', total_price: 34, place_id: 7 })
expect(posted).not.toHaveProperty('reservation_id')
})
})
describe('CostsPanel — remaining paths', () => {
@@ -1742,13 +1762,15 @@ describe('CostsPanel — split maths', () => {
expect(splitEqualShares(10, [{ user_id: 1 }, { user_id: 2 }, { user_id: 3 }], 1)).toEqual({ 1: 3.33, 2: 3.34, 3: 3.33 })
})
it('FE-W5COSTS-041: ticket items nobody is assigned to still count toward the total', () => {
it('FE-W5COSTS-041: a receipt line nobody is assigned to is carried by everyone on the receipt', () => {
const items: TicketItem[] = [
{ id: 'a', name: 'Apples', price: '10', participants: new Set([1, 2]) },
{ id: 'b', name: 'Service', price: '5', participants: new Set() },
{ id: 'c', name: 'Cake', price: 'x', participants: new Set([2]) },
]
expect(calculateTicketShares(items)).toEqual({ shares: { 1: 5, 2: 5 }, total: 15 })
// The service line used to count toward the total without landing on anyone,
// so the shares stayed a permanent 5.00 short of it (#1382).
expect(calculateTicketShares(items)).toEqual({ shares: { 1: 7.5, 2: 7.5 }, total: 15 })
})
})
+11 -2
View File
@@ -1000,6 +1000,8 @@ export interface ExpensePrefill {
category?: string
amount?: number
reservationId?: number
/** Set when the expense is being created from a place (#1298). */
placeId?: number
}
export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClose, onSaved }: {
@@ -1232,7 +1234,13 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
.map(id => ({ user_id: id, amount: parseFloat(payerAmounts[id]) || 0 }))
.filter(p => p.amount > 0)
: payerId > 0 ? [{ user_id: payerId, amount: totalNum }] : []
const memberList = [...participants].map(id => ({
// A receipt line can name somebody who is not ticked as a participant. Sending
// only the ticked set would drop their share, leaving the member sum short of
// total_price and handing the settlement a difference it can never clear (#1382).
const memberIds = splitMode === 'ticket'
? [...new Set([...participants, ...Object.keys(ticketInfo.shares).map(Number)])].sort((a, b) => a - b)
: [...participants]
const memberList = memberIds.map(id => ({
user_id: id,
amount: splitMode === 'custom'
? (parseFloat(customAmounts[id]) || 0)
@@ -1246,12 +1254,13 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
currency,
payers: payerList,
members: memberList,
member_ids: [...participants],
member_ids: memberIds,
expense_date: day || null,
total_price: totalNum,
note: note.trim() || null,
ticket_json: splitMode === 'ticket' ? writeTicketItems(ticketItems) : null,
...(!editing && prefill?.reservationId ? { reservation_id: prefill.reservationId } : {}),
...(!editing && prefill?.placeId ? { place_id: prefill.placeId } : {}),
}
try {
if (editing) await updateBudgetItem(tripId, editing.id, data)
@@ -13,7 +13,10 @@ export function ChatMessages(props: any) {
<>
{/* Messages */}
{messages.length === 0 ? (
<EmptyState scene="chat" title={t('collab.chat.empty')} />
// flex-1, like the message list it stands in for: without it the empty
// state was only as tall as its own content and the composer rode up to
// sit right under the mascot, with the rest of the panel left blank.
<EmptyState scene="chat" title={t('collab.chat.empty')} className="min-h-0 flex-1" />
) : (
<div ref={scrollRef} onScroll={checkAtBottom} className="chat-scroll" style={{
flex: 1, overflowY: 'auto', overflowX: 'hidden', padding: '8px 14px 4px', WebkitOverflowScrolling: 'touch',
@@ -1,4 +1,4 @@
// FE-COMP-ADDPLACECOL-001 to FE-COMP-ADDPLACECOL-024
// FE-COMP-ADDPLACECOL-001 to FE-COMP-ADDPLACECOL-028
import React from 'react'
import type { Mock } from 'vitest'
import { http, HttpResponse } from 'msw'
@@ -163,13 +163,27 @@ describe('AddPlaceToCollectionModal', () => {
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Places API disabled', 'error', undefined))
})
it('FE-COMP-ADDPLACECOL-009: a search response without places yields no dropdown', async () => {
it('FE-COMP-ADDPLACECOL-009: a search that finds nothing says so instead of staying silent', async () => {
server.use(http.post('/api/maps/search', () => HttpResponse.json({ source: 'nominatim' })))
setup()
fireEvent.change(screen.getByPlaceholderText('Search for a place…'), { target: { value: 'kissa' } })
fireEvent.click(screen.getByRole('button', { name: /Search/ }))
await waitFor(() => expect(screen.getByRole('button', { name: /Search/ })).not.toBeDisabled())
expect(screen.queryByRole('button', { name: 'Close' })).not.toBeInTheDocument()
expect(await screen.findByText('No places found')).toBeInTheDocument()
// Typing the next query clears it again.
fireEvent.change(screen.getByPlaceholderText('Search for a place…'), { target: { value: 'kissaten' } })
expect(screen.queryByText('No places found')).not.toBeInTheDocument()
})
it('FE-COMP-ADDPLACECOL-009b: the empty search panel can be dismissed', async () => {
server.use(http.post('/api/maps/search', () => HttpResponse.json({ places: [], source: 'nominatim' })))
setup()
fireEvent.change(screen.getByPlaceholderText('Search for a place…'), { target: { value: 'kissa' } })
fireEvent.click(screen.getByRole('button', { name: /Search/ }))
await screen.findByText('No places found')
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
expect(screen.queryByText('No places found')).not.toBeInTheDocument()
})
it('FE-COMP-ADDPLACECOL-010: saving posts the manually typed place with nulls for what is empty', async () => {
@@ -360,4 +374,49 @@ describe('AddPlaceToCollectionModal', () => {
expect(props.onClose).toHaveBeenCalledTimes(1)
expect(savedBodies).toHaveLength(0)
})
it('FE-COMP-ADDPLACECOL-025: the caret goes back to the search field after an add', async () => {
setup()
const nameField = screen.getByPlaceholderText('Name')
typeName('Manual spot')
// Where the focus sits in the browser once the add button disables itself.
nameField.focus()
fireEvent.click(screen.getByRole('button', { name: /Add$/ }))
await waitFor(() => expect(nameField).toHaveValue(''))
expect(screen.getByPlaceholderText('Search for a place…')).toHaveFocus()
})
it('FE-COMP-ADDPLACECOL-026: the search still runs after a place was added', async () => {
mockSearch([mapsResult])
setup()
typeName('Manual spot')
fireEvent.click(screen.getByRole('button', { name: /Add$/ }))
await waitFor(() => expect(screen.getByPlaceholderText('Name')).toHaveValue(''))
const input = screen.getByPlaceholderText('Search for a place…')
expect(input).toHaveValue('')
fireEvent.change(input, { target: { value: 'kissa' } })
expect(screen.getByRole('button', { name: /Search/ })).not.toBeDisabled()
fireEvent.keyDown(input, { key: 'Enter' })
expect(await screen.findByText('Kissa Sakaiki')).toBeInTheDocument()
})
it('FE-COMP-ADDPLACECOL-027: the search row is pinned to the top of the scrolling body', () => {
setup()
// The dialog stays open after an add, so the row has to survive a scrolled form.
expect(screen.getByPlaceholderText('Search for a place…').closest('.sticky')).not.toBeNull()
})
it('FE-COMP-ADDPLACECOL-028: a failed save leaves the caret where the user had it', async () => {
server.use(http.post('/api/addons/collections/places', () => HttpResponse.json({ error: 'List is full' }, { status: 400 })))
setup()
const nameField = screen.getByPlaceholderText('Name')
typeName('Manual spot')
nameField.focus()
fireEvent.click(screen.getByRole('button', { name: /Add$/ }))
await waitFor(() => expect(addToast).toHaveBeenCalledWith('List is full', 'error', undefined))
expect(nameField).toHaveFocus()
})
})
@@ -42,6 +42,9 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
const [query, setQuery] = useState('')
const [results, setResults] = useState<MapsPlace[]>([])
const [searching, setSearching] = useState(false)
// A search that came back empty used to render nothing at all, which reads as
// "the dialog is dead". Say so instead (#1921).
const [noResults, setNoResults] = useState(false)
// The picked location (address/coords/ids) plus the editable fields.
const [picked, setPicked] = useState<MapsPlace | null>(null)
const [name, setName] = useState('')
@@ -56,16 +59,20 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
const [status, setStatus] = useState<CollectionStatus>('idea')
const [saving, setSaving] = useState(false)
const descRef = useRef<HTMLTextAreaElement>(null)
const searchRef = useRef<HTMLInputElement>(null)
const reset = () => { setQuery(''); setResults([]); setPicked(null); setName(''); setAddress(''); setLat(''); setLng(''); setCategoryId(null); setDescription(''); setLinks([]); setStatus('idea') }
const reset = () => { setQuery(''); setResults([]); setNoResults(false); setPicked(null); setName(''); setAddress(''); setLat(''); setLng(''); setCategoryId(null); setDescription(''); setLinks([]); setStatus('idea') }
useEffect(() => { if (!isOpen) reset() }, [isOpen])
const search = async () => {
if (!query.trim()) return
setSearching(true)
setNoResults(false)
try {
const res = await mapsApi.search(query, language)
setResults((res.places as MapsPlace[]) || [])
const places = (res.places as MapsPlace[]) || []
setResults(places)
setNoResults(places.length === 0)
} catch (err) {
toast.error(getApiErrorMessage(err, t('places.mapsSearchError')))
} finally {
@@ -73,6 +80,8 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
}
}
const dismissResults = () => { setResults([]); setNoResults(false) }
const pick = (r: MapsPlace) => {
setPicked(r)
setName(str(r.name) ?? '')
@@ -80,7 +89,7 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
const la = num(r.lat); const lo = num(r.lng)
setLat(la != null ? String(la) : '')
setLng(lo != null ? String(lo) : '')
setResults([]); setQuery(str(r.name) ?? query)
setResults([]); setNoResults(false); setQuery(str(r.name) ?? query)
}
const setLink = (i: number, patch: Partial<CollectionLink>) => setLinks(links.map((l, idx) => (idx === i ? { ...l, ...patch } : l)))
@@ -112,6 +121,11 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
if (res.duplicate) toast.info(t('collections.duplicateWarning'))
else { toast.success(t('collections.addedToList', { name: collectionName })); onAdded() }
reset()
// The dialog stays open for the next place, so hand the caret back to the
// search field. The add button the user just clicked goes disabled with the
// cleared name, which drops the focus to <body> and leaves the dialog dead
// to the keyboard (#1921).
searchRef.current?.focus()
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')))
} finally {
@@ -142,42 +156,51 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
}
>
<div className="flex flex-col gap-4">
{/* Search — picking a result fills the location below */}
<div className="relative">
<div className="flex gap-2">
<div className="relative flex-1">
<Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-content-faint" />
<input
autoFocus
value={query}
onChange={e => setQuery(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); search() } }}
placeholder={t('collections.addPlaceSearch')}
className="w-full pl-9 pr-3 py-2 rounded-lg border border-edge bg-surface-input text-content text-[14px] outline-none focus:border-accent"
/>
</div>
<button type="button" onClick={search} disabled={!query.trim() || searching} className="px-4 py-2 rounded-lg bg-accent text-accent-text text-[13px] font-semibold disabled:opacity-50 inline-flex items-center gap-2">
{searching ? <Loader2 size={15} className="animate-spin" /> : <Search size={15} />}
{t('common.search')}
</button>
</div>
{results.length > 0 && (
<div className="absolute z-20 left-0 right-0 mt-1.5 max-h-[280px] overflow-y-auto rounded-xl border border-edge bg-surface-card shadow-lg p-1.5 flex flex-col gap-1">
<div className="flex items-center justify-between px-2 py-1">
<span className="text-[11px] font-semibold uppercase tracking-wide text-content-faint">{t('common.search')}</span>
<button type="button" onClick={() => setResults([])} className="p-1 rounded-md text-content-faint hover:text-content hover:bg-surface-hover" aria-label={t('common.close')}><X size={13} /></button>
{/* Search — picking a result fills the location below. Pinned to the top of
the scrolling dialog body: the dialog stays open after an add, and the
search row used to sit above the viewport once the form was scrolled,
so it looked like the button had vanished (#1921). The negative margins
let its background cover the body padding while it is stuck. */}
<div className="sticky top-0 z-20 -mx-6 -mt-6 -mb-4 px-6 pt-6 pb-4 bg-surface-card">
<div className="relative">
<div className="flex gap-2">
<div className="relative flex-1">
<Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-content-faint" />
<input
autoFocus
ref={searchRef}
value={query}
onChange={e => { setQuery(e.target.value); setNoResults(false) }}
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); search() } }}
placeholder={t('collections.addPlaceSearch')}
className="w-full pl-9 pr-3 py-2 rounded-lg border border-edge bg-surface-input text-content text-[14px] outline-none focus:border-accent"
/>
</div>
{results.map((r, i) => (
<button key={i} type="button" onClick={() => pick(r)} className="flex items-center gap-3 px-2.5 py-2 rounded-lg text-left hover:bg-surface-hover transition-colors">
<div className="w-8 h-8 min-w-[32px] rounded-lg bg-surface-secondary flex items-center justify-center text-content-faint shrink-0"><MapPin size={15} /></div>
<div className="flex flex-col min-w-0 flex-1">
<span className="text-[13px] font-semibold text-content truncate">{str(r.name)}</span>
{str(r.address) && <span className="text-[11.5px] text-content-faint truncate">{str(r.address)}</span>}
</div>
</button>
))}
<button type="button" onClick={search} disabled={!query.trim() || searching} className="px-4 py-2 rounded-lg bg-accent text-accent-text text-[13px] font-semibold disabled:opacity-50 inline-flex items-center gap-2">
{searching ? <Loader2 size={15} className="animate-spin" /> : <Search size={15} />}
{t('common.search')}
</button>
</div>
)}
{(results.length > 0 || noResults) && (
<div className="absolute z-20 left-0 right-0 mt-1.5 max-h-[280px] overflow-y-auto rounded-xl border border-edge bg-surface-card shadow-lg p-1.5 flex flex-col gap-1">
<div className="flex items-center justify-between px-2 py-1">
<span className="text-[11px] font-semibold uppercase tracking-wide text-content-faint">{t('common.search')}</span>
<button type="button" onClick={dismissResults} className="p-1 rounded-md text-content-faint hover:text-content hover:bg-surface-hover" aria-label={t('common.close')}><X size={13} /></button>
</div>
{noResults ? (
<div className="px-2.5 py-3 text-center text-[12.5px] text-content-faint">{t('planner.noPlacesFound')}</div>
) : results.map((r, i) => (
<button key={i} type="button" onClick={() => pick(r)} className="flex items-center gap-3 px-2.5 py-2 rounded-lg text-left hover:bg-surface-hover transition-colors">
<div className="w-8 h-8 min-w-[32px] rounded-lg bg-surface-secondary flex items-center justify-center text-content-faint shrink-0"><MapPin size={15} /></div>
<div className="flex flex-col min-w-0 flex-1">
<span className="text-[13px] font-semibold text-content truncate">{str(r.name)}</span>
{str(r.address) && <span className="text-[11.5px] text-content-faint truncate">{str(r.address)}</span>}
</div>
</button>
))}
</div>
)}
</div>
</div>
{/* Name */}
@@ -1,4 +1,4 @@
// FE-COMP-COLDETAIL-001 to FE-COMP-COLDETAIL-035
// FE-COMP-COLDETAIL-001 to FE-COMP-COLDETAIL-043
import React from 'react';
import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
@@ -335,6 +335,8 @@ describe('CollectionPlaceDetail', () => {
links: [{ label: undefined, url: 'https://x.com' }],
category_id: 2,
label_ids: [1, 2],
// Untouched in this case, but the address rides along on every save (#1870).
address: 'Somewhere',
lat: 52.5,
lng: 13.4,
});
@@ -547,3 +549,56 @@ describe('CollectionPlaceDetail — open in maps', () => {
expect(screen.queryByRole('button', { name: /navigation|google maps/i })).toBeNull();
});
});
// ── Editable address (#1870) ─────────────────────────────────────────────────
describe('CollectionPlaceDetail: editable address', () => {
it('FE-COMP-COLDETAIL-040: edit mode offers an address field seeded from the place', async () => {
const user = userEvent.setup();
renderDetail({ canEdit: true });
await user.click(await screen.findByRole('button', { name: 'Edit' }));
expect(screen.getByText('Address')).toBeInTheDocument();
expect(screen.getByPlaceholderText('Street, City, Country')).toHaveValue('Somewhere');
});
it('FE-COMP-COLDETAIL-041: a corrected address is trimmed into the patch', async () => {
const user = userEvent.setup();
const props = renderDetail({ canEdit: true });
await user.click(await screen.findByRole('button', { name: 'Edit' }));
const addressInput = screen.getByPlaceholderText('Street, City, Country');
await user.clear(addressInput);
await user.type(addressInput, ' Via Nuova 1 ');
await user.click(screen.getByRole('button', { name: /Save/ }));
await waitFor(() => expect(props.onSave).toHaveBeenCalled());
expect(props.onSave).toHaveBeenCalledWith(expect.objectContaining({ address: 'Via Nuova 1' }));
});
it('FE-COMP-COLDETAIL-042: an emptied address is sent as null', async () => {
const user = userEvent.setup();
const props = renderDetail({ canEdit: true });
await user.click(await screen.findByRole('button', { name: 'Edit' }));
await user.clear(screen.getByPlaceholderText('Street, City, Country'));
await user.click(screen.getByRole('button', { name: /Save/ }));
await waitFor(() => expect(props.onSave).toHaveBeenCalled());
expect(props.onSave).toHaveBeenCalledWith(expect.objectContaining({ address: null }));
});
it('FE-COMP-COLDETAIL-043: Cancel restores the stored address', async () => {
const user = userEvent.setup();
const props = renderDetail({ canEdit: true });
await user.click(await screen.findByRole('button', { name: 'Edit' }));
await user.type(screen.getByPlaceholderText('Street, City, Country'), ' 2');
await user.click(screen.getByRole('button', { name: 'Cancel' }));
expect(props.onSave).not.toHaveBeenCalled();
expect(screen.getByText('Somewhere')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Edit' }));
expect(screen.getByPlaceholderText('Street, City, Country')).toHaveValue('Somewhere');
});
});
@@ -35,7 +35,7 @@ interface CollectionPlaceDetailProps {
anchorRect?: { left: number; width: number } | null
onClose: () => void
onSetStatus: (status: CollectionStatus) => void
onSave: (patch: { name?: string; description?: string | null; links?: CollectionLink[]; category_id?: number | null; label_ids?: number[]; image_url?: string | null; lat?: number | null; lng?: number | null }) => Promise<void>
onSave: (patch: { name?: string; description?: string | null; links?: CollectionLink[]; category_id?: number | null; label_ids?: number[]; image_url?: string | null; lat?: number | null; lng?: number | null; address?: string | null }) => Promise<void>
/** Upload a custom cover image (#1136); enables the cover change/remove controls. */
onUploadImage?: (file: File) => Promise<void>
onCopyToTrip: () => void
@@ -83,6 +83,7 @@ export default function CollectionPlaceDetail({
const [description, setDescription] = useState(place.description ?? '')
const [links, setLinks] = useState<CollectionLink[]>(place.links ?? [])
const [labelIds, setLabelIds] = useState<number[]>(place.label_ids ?? [])
const [address, setAddress] = useState(place.address ?? '')
const [lat, setLat] = useState(place.lat != null ? String(place.lat) : '')
const [lng, setLng] = useState(place.lng != null ? String(place.lng) : '')
const [saving, setSaving] = useState(false)
@@ -99,6 +100,7 @@ export default function CollectionPlaceDetail({
setDescription(place.description ?? '')
setLinks(place.links ?? [])
setLabelIds(place.label_ids ?? [])
setAddress(place.address ?? '')
setLat(place.lat != null ? String(place.lat) : '')
setLng(place.lng != null ? String(place.lng) : '')
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -147,7 +149,7 @@ export default function CollectionPlaceDetail({
const setLink = (i: number, patch: Partial<CollectionLink>) => setLinks(links.map((l, idx) => (idx === i ? { ...l, ...patch } : l)))
const toggleLabel = (id: number) => setLabelIds(labelIds.includes(id) ? labelIds.filter(x => x !== id) : [...labelIds, id])
const resetForm = () => { setEditing(false); setName(place.name); setCategoryId(place.category_id ?? null); setDescription(place.description ?? ''); setLinks(place.links ?? []); setLabelIds(place.label_ids ?? []); setLat(place.lat != null ? String(place.lat) : ''); setLng(place.lng != null ? String(place.lng) : '') }
const resetForm = () => { setEditing(false); setName(place.name); setCategoryId(place.category_id ?? null); setDescription(place.description ?? ''); setLinks(place.links ?? []); setLabelIds(place.label_ids ?? []); setAddress(place.address ?? ''); setLat(place.lat != null ? String(place.lat) : ''); setLng(place.lng != null ? String(place.lng) : '') }
const coordPaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
const text = e.clipboardData.getData('text').trim()
const match = text.match(/^(-?\d+\.?\d*)\s*[,;\s]\s*(-?\d+\.?\d*)$/)
@@ -161,7 +163,7 @@ export default function CollectionPlaceDetail({
const lngNum = lng.trim() ? Number(lng) : NaN
setSaving(true)
try {
await onSave({ name: name.trim() || place.name, description: description.trim() || null, links: cleanLinks, category_id: categoryId, label_ids: labelIds, lat: Number.isFinite(latNum) ? latNum : null, lng: Number.isFinite(lngNum) ? lngNum : null })
await onSave({ name: name.trim() || place.name, description: description.trim() || null, links: cleanLinks, category_id: categoryId, label_ids: labelIds, address: address.trim() || null, lat: Number.isFinite(latNum) ? latNum : null, lng: Number.isFinite(lngNum) ? lngNum : null })
setEditing(false)
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')))
@@ -280,6 +282,11 @@ export default function CollectionPlaceDetail({
})}
</div>
</div>
{/* Address (#1870): free text, the coordinates stay separate */}
<div className="col-detail-field">
<div className="col-detail-label"><MapPin size={12} /> {t('places.formAddress')}</div>
<input value={address} onChange={e => setAddress(e.target.value)} placeholder={t('places.formAddressPlaceholder')} className="col-detail-input" />
</div>
{/* Coordinates */}
<div className="col-detail-field">
<div className="col-detail-label"><MapPin size={12} /> {t('collections.coordinates')}</div>
@@ -115,7 +115,7 @@ describe('MSaveToCollectionSheet', () => {
it('FE-COMP-MSAVESHEET-006: lists already holding the place are marked saved', async () => {
vi.spyOn(collectionsApi, 'membership').mockResolvedValue({
saved: true,
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900 }],
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900, status: 'want', can_edit: true }],
});
openFor();
render(<MSaveToCollectionSheet />);
@@ -167,7 +167,7 @@ describe('MSaveToCollectionSheet', () => {
it('FE-COMP-MSAVESHEET-010: tapping a saved list removes that place instead', async () => {
vi.spyOn(collectionsApi, 'membership').mockResolvedValue({
saved: true,
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900 }],
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900, status: 'want', can_edit: true }],
});
const del = vi.spyOn(collectionsApi, 'deletePlace').mockResolvedValue({});
openFor();
@@ -1,6 +1,6 @@
import { useEffect, useMemo, useState, useCallback } from 'react'
import { useNavigate } from 'react-router'
import { Bookmark, BookmarkCheck, Check, Loader2, Plus, X } from 'lucide-react'
import { Bookmark, BookmarkCheck, Check, CheckCircle2, Loader2, Plus, X } from 'lucide-react'
import MSheet from '../../mobile/components/MSheet'
import MIconBtn from '../../mobile/components/MIconBtn'
import { useToast } from '../shared/Toast'
@@ -8,7 +8,8 @@ import { useTranslation } from '../../i18n'
import { collectionsApi } from '../../api/collections'
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore'
import { getApiErrorMessage } from '../../utils/apiError'
import type { Collection, CollectionMembership } from '@trek/shared'
import { STATUS_META, nextStatus } from '../../pages/collections/collectionsModel'
import type { Collection, CollectionMembership, CollectionStatus } from '@trek/shared'
/**
* Mobile counterpart of SaveToCollectionModal — the same store-driven list
@@ -71,12 +72,44 @@ export default function MSaveToCollectionSheet() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [target])
const savedByCollection = new Map<number, number>()
for (const l of membership?.lists ?? []) savedByCollection.set(l.collection_id, l.place_id)
const savedByCollection = new Map<number, CollectionMembership['lists'][number]>()
for (const l of membership?.lists ?? []) savedByCollection.set(l.collection_id, l)
/** Lists holding this place that the viewer may edit and that are not visited yet. */
const unvisited = (membership?.lists ?? []).filter(l => l.can_edit && l.status !== 'visited')
const handleStatus = async (entry: CollectionMembership['lists'][number], next: CollectionStatus) => {
if (busyId != null) return
setBusyId(entry.collection_id)
try {
await collectionsApi.setStatus(entry.place_id, next)
await refreshMembership()
bumpVersion()
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')))
} finally {
setBusyId(null)
}
}
const handleVisitedEverywhere = async () => {
if (busyId != null || unvisited.length === 0) return
setBusyId(-1)
try {
const { updated } = await collectionsApi.setStatusMany(unvisited.map(l => l.place_id), 'visited')
toast.success(t('collections.markedVisited', { count: updated }))
await refreshMembership()
bumpVersion()
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')))
} finally {
setBusyId(null)
}
}
const handleToggle = async (list: Collection) => {
if (busyId != null || !target) return
const savedPlaceId = savedByCollection.get(list.id)
const savedPlaceId = savedByCollection.get(list.id)?.place_id
setBusyId(list.id)
try {
if (savedPlaceId != null) {
@@ -156,8 +189,11 @@ export default function MSaveToCollectionSheet() {
</div>
) : (
lists.map(list => {
const saved = savedByCollection.has(list.id)
const entry = savedByCollection.get(list.id)
const saved = !!entry
const busy = busyId === list.id
const statusMeta = entry ? STATUS_META[entry.status] : null
const StatusIcon = statusMeta?.icon
return (
<button
key={list.id}
@@ -178,9 +214,27 @@ export default function MSaveToCollectionSheet() {
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-[0.8125rem] font-semibold text-m-ink">{list.name}</span>
<span className="mt-px block font-geist text-[0.65625rem] text-m-muted">
{t('collections.placeCount', { count: list.place_count ?? 0 })}
</span>
{/* Saved lists show their own status here instead of the place
count — that number matters when picking a list, the status
matters once the place is in it (#1469). */}
{entry && statusMeta && StatusIcon ? (
<span
role={entry.can_edit ? 'button' : undefined}
tabIndex={entry.can_edit ? 0 : undefined}
aria-label={t(statusMeta.labelKey)}
onClick={entry.can_edit ? e => { e.preventDefault(); e.stopPropagation(); void handleStatus(entry, nextStatus(entry.status)) } : undefined}
onKeyDown={entry.can_edit ? e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); void handleStatus(entry, nextStatus(entry.status)) } } : undefined}
className="mt-[3px] inline-flex items-center gap-1 rounded-full bg-[color:var(--m-inner)] px-2 py-[3px] font-geist text-[0.65625rem] font-semibold"
style={{ color: statusMeta.color }}
>
<StatusIcon size={11} strokeWidth={2.4} />
{t(statusMeta.labelKey)}
</span>
) : (
<span className="mt-px block font-geist text-[0.65625rem] text-m-muted">
{t('collections.placeCount', { count: list.place_count ?? 0 })}
</span>
)}
</span>
{list.is_owner === false && (
<span className="flex-none font-geist text-[0.5625rem] font-bold uppercase tracking-[.05em] text-m-faint">
@@ -200,6 +254,22 @@ export default function MSaveToCollectionSheet() {
)}
</div>
{unvisited.length > 0 && (
<div className="flex-none px-[14px] pb-1">
<button
type="button"
onClick={handleVisitedEverywhere}
disabled={busyId != null}
className="flex w-full items-center justify-center gap-1.5 rounded-[14px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] py-[10px] text-[0.78125rem] font-semibold text-m-ink disabled:opacity-60"
>
{busyId === -1
? <Loader2 size={14} className="animate-spin" />
: <CheckCircle2 size={14} strokeWidth={2.2} />}
{unvisited.length > 1 ? t('collections.markVisitedAll') : t('collections.markVisited')}
</button>
</div>
)}
{lists.length > 0 && (
<div className="flex flex-none items-center justify-between gap-2 border-t border-[color:var(--m-rowbr)] px-[18px] py-3">
<button
@@ -1,4 +1,4 @@
// FE-COMP-SAVETOCOL-001 to FE-COMP-SAVETOCOL-016
// FE-COMP-SAVETOCOL-001 to FE-COMP-SAVETOCOL-020
import React from 'react';
import { afterEach, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render';
@@ -120,7 +120,7 @@ describe('SaveToCollectionModal', () => {
it('FE-COMP-SAVETOCOL-006: lists already holding the place are marked saved', async () => {
vi.spyOn(collectionsApi, 'membership').mockResolvedValue({
saved: true,
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900 }],
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900, status: 'want', can_edit: true }],
});
openFor();
render(<SaveToCollectionModal />);
@@ -194,7 +194,7 @@ describe('SaveToCollectionModal', () => {
it('FE-COMP-SAVETOCOL-011: picking a saved list removes that place instead', async () => {
vi.spyOn(collectionsApi, 'membership').mockResolvedValue({
saved: true,
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900 }],
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900, status: 'want', can_edit: true }],
});
const del = vi.spyOn(collectionsApi, 'deletePlace').mockResolvedValue({});
const save = vi.spyOn(collectionsApi, 'savePlace');
@@ -263,6 +263,65 @@ describe('SaveToCollectionModal', () => {
expect(screen.queryByText('Favorites')).not.toBeInTheDocument();
});
// ── Per-list status + "visited everywhere" (#1469) ────────────────────────
const savedIn = (over: Partial<CollectionMembership['lists'][number]> = {}): CollectionMembership => ({
saved: true,
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900, status: 'want', can_edit: true, ...over }],
});
it('FE-COMP-SAVETOCOL-017: a saved list shows its own status and one tap cycles it', async () => {
vi.spyOn(collectionsApi, 'membership').mockResolvedValue(savedIn());
const setStatus = vi.spyOn(collectionsApi, 'setStatus').mockResolvedValue({} as never);
const del = vi.spyOn(collectionsApi, 'deletePlace').mockResolvedValue({});
openFor();
render(<SaveToCollectionModal />);
const badge = await screen.findByRole('button', { name: 'Want to go' });
fireEvent.click(badge);
// want → visited, and the row toggle must NOT have fired underneath it.
await waitFor(() => expect(setStatus).toHaveBeenCalledWith(900, 'visited'));
expect(del).not.toHaveBeenCalled();
});
it('FE-COMP-SAVETOCOL-018: the header action marks every list holding the place visited', async () => {
vi.spyOn(collectionsApi, 'membership').mockResolvedValue({
saved: true,
lists: [
{ collection_id: 1, name: 'Favorites', place_id: 900, status: 'want', can_edit: true },
{ collection_id: 2, name: 'Wishlist', place_id: 901, status: 'idea', can_edit: true },
],
});
const many = vi.spyOn(collectionsApi, 'setStatusMany').mockResolvedValue({ updated: 2 });
openFor();
render(<SaveToCollectionModal />);
fireEvent.click(await screen.findByRole('button', { name: 'Visited everywhere' }));
await waitFor(() => expect(many).toHaveBeenCalledWith([900, 901], 'visited'));
});
it('FE-COMP-SAVETOCOL-019: the action disappears once every list is visited', async () => {
vi.spyOn(collectionsApi, 'membership').mockResolvedValue(savedIn({ status: 'visited' }));
openFor();
render(<SaveToCollectionModal />);
await screen.findByText('Favorites');
expect(screen.queryByRole('button', { name: /Visited everywhere|Mark visited/ })).not.toBeInTheDocument();
});
it('FE-COMP-SAVETOCOL-020: a read-only list shows its status but does not offer to change it', async () => {
vi.spyOn(collectionsApi, 'membership').mockResolvedValue(savedIn({ can_edit: false }));
openFor();
render(<SaveToCollectionModal />);
await screen.findByText('Favorites');
expect(screen.queryByRole('button', { name: 'Want to go' })).not.toBeInTheDocument();
expect(screen.getByTitle('Want to go')).toBeInTheDocument();
// Nothing to offer: the only list holding it is one the viewer cannot edit.
expect(screen.queryByRole('button', { name: /Visited everywhere|Mark visited/ })).not.toBeInTheDocument();
});
it('FE-COMP-SAVETOCOL-014: the footer navigates to the collections page or just closes', async () => {
openFor();
const { unmount } = render(<SaveToCollectionModal />);
@@ -1,13 +1,14 @@
import React, { useEffect, useMemo, useState, useCallback } from 'react'
import { useNavigate } from 'react-router'
import { Bookmark, BookmarkCheck, Check, Loader2, Plus } from 'lucide-react'
import { Bookmark, BookmarkCheck, Check, CheckCircle2, Loader2, Plus } from 'lucide-react'
import Modal from '../shared/Modal'
import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
import { collectionsApi } from '../../api/collections'
import StatusBadge from './StatusBadge'
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore'
import { getApiErrorMessage } from '../../utils/apiError'
import type { Collection, CollectionMembership } from '@trek/shared'
import type { Collection, CollectionMembership, CollectionStatus } from '@trek/shared'
/**
* Globally-mounted list picker for the "Save to Collection" entry points
@@ -70,12 +71,44 @@ export default function SaveToCollectionModal(): React.ReactElement | null {
if (!target) return null
const savedByCollection = new Map<number, number>()
for (const l of membership?.lists ?? []) savedByCollection.set(l.collection_id, l.place_id)
const savedByCollection = new Map<number, CollectionMembership['lists'][number]>()
for (const l of membership?.lists ?? []) savedByCollection.set(l.collection_id, l)
/** Lists holding this place that the viewer may edit and that are not visited yet. */
const unvisited = (membership?.lists ?? []).filter(l => l.can_edit && l.status !== 'visited')
const handleStatus = async (entry: CollectionMembership['lists'][number], next: CollectionStatus) => {
if (busyId != null) return
setBusyId(entry.collection_id)
try {
await collectionsApi.setStatus(entry.place_id, next)
await refreshMembership()
bumpVersion()
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')))
} finally {
setBusyId(null)
}
}
const handleVisitedEverywhere = async () => {
if (busyId != null || unvisited.length === 0) return
setBusyId(-1)
try {
const { updated } = await collectionsApi.setStatusMany(unvisited.map(l => l.place_id), 'visited')
toast.success(t('collections.markedVisited', { count: updated }))
await refreshMembership()
bumpVersion()
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')))
} finally {
setBusyId(null)
}
}
const handleToggle = async (list: Collection) => {
if (busyId != null) return
const savedPlaceId = savedByCollection.get(list.id)
const savedPlaceId = savedByCollection.get(list.id)?.place_id
setBusyId(list.id)
try {
if (savedPlaceId != null) {
@@ -140,7 +173,23 @@ export default function SaveToCollectionModal(): React.ReactElement | null {
}
>
<div className="flex flex-col gap-2">
<p className="text-[13px] font-semibold text-content truncate">{target.name}</p>
<div className="flex items-center gap-2 min-w-0">
<p className="flex-1 min-w-0 text-[13px] font-semibold text-content truncate">{target.name}</p>
{/* One tap for "I have been here", however many lists hold it (#1469). */}
{unvisited.length > 0 && (
<button
type="button"
onClick={handleVisitedEverywhere}
disabled={busyId != null}
className="shrink-0 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-edge bg-surface-card text-[11px] font-semibold text-content-secondary hover:bg-surface-hover disabled:opacity-60"
>
{busyId === -1
? <Loader2 size={12} className="animate-spin" />
: <CheckCircle2 size={12} strokeWidth={2.2} />}
{unvisited.length > 1 ? t('collections.markVisitedAll') : t('collections.markVisited')}
</button>
)}
</div>
{loading ? (
<div className="flex items-center justify-center py-8 text-content-faint">
<Loader2 size={20} className="animate-spin" />
@@ -162,7 +211,8 @@ export default function SaveToCollectionModal(): React.ReactElement | null {
) : (
<div className="flex flex-col gap-1 max-h-[50vh] overflow-y-auto -mx-1 px-1">
{lists.map(list => {
const saved = savedByCollection.has(list.id)
const entry = savedByCollection.get(list.id)
const saved = !!entry
const busy = busyId === list.id
return (
<button
@@ -170,13 +220,24 @@ export default function SaveToCollectionModal(): React.ReactElement | null {
type="button"
onClick={() => handleToggle(list)}
disabled={busyId != null}
className={`flex items-center gap-3 px-3 py-2.5 rounded-xl border text-left transition-colors disabled:opacity-60 ${saved ? 'border-accent bg-accent-subtle' : 'border-edge bg-surface-card hover:bg-surface-hover'}`}
className={`flex items-center gap-2.5 px-3 py-2.5 rounded-xl border text-left transition-colors disabled:opacity-60 ${saved ? 'border-accent bg-accent-subtle' : 'border-edge bg-surface-card hover:bg-surface-hover'}`}
>
<span className="w-2.5 h-2.5 rounded-full shrink-0" style={{ background: list.color || 'var(--accent)' }} />
<span className="flex-1 min-w-0 text-[13px] font-medium text-content truncate">{list.name}</span>
{list.is_owner === false && (
<span className="text-[10px] uppercase font-semibold text-content-faint">{t('collections.shared')}</span>
)}
{/* Per-list status, so one place can be an idea in one list and
visited in another. A role=button span, safe to nest here. */}
{entry && (
<StatusBadge
status={entry.status}
showLabel={false}
size={12}
onChange={entry.can_edit ? next => { void handleStatus(entry, next) } : undefined}
t={t}
/>
)}
<span className={`w-5 h-5 rounded-md flex items-center justify-center shrink-0 ${saved ? 'bg-accent text-accent-text' : 'border border-edge text-transparent'}`}>
{busy ? <Loader2 size={13} className="animate-spin text-content-faint" /> : saved ? <BookmarkCheck size={13} /> : <Check size={13} />}
</span>
+4 -1
View File
@@ -899,7 +899,10 @@ export const MapView = memo(function MapView({
onClick={cycleTrackingMode}
bottomOffset={locationButtonBottom as unknown as number}
/>}
<div style={{ position: 'absolute', left: leftWidth + 12, bottom: switcherBottom, zIndex: 1000, pointerEvents: 'none' }}>
{/* 20px off the sidebar, not 12: the pill is round and frosted, so at the
smaller gap its shadow ran into the sidebar edge and the two read as one
surface. */}
<div style={{ position: 'absolute', left: leftWidth + 20, bottom: switcherBottom, zIndex: 1000, pointerEvents: 'none' }}>
<MapLayerSwitcher active={baseLayer} onToggle={toggleBaseLayer} />
</div>
</div>
@@ -1,10 +1,11 @@
// FE-COMP-JOURNEYPDF-001 to FE-COMP-JOURNEYPDF-006
// FE-COMP-JOURNEYPDF-001 to FE-COMP-JOURNEYPDF-012
//
// JourneyBookPDF.tsx exports an async function `downloadJourneyBookPDF(journey)`
// that renders a PDF preview in an srcdoc iframe overlay (Safari-safe pattern).
// Tests verify the overlay DOM structure and HTML content.
// JourneyBookPDF.tsx exports an async function
// `downloadJourneyBookPDF(journey, { t, locale })` that renders a PDF preview in
// an srcdoc iframe overlay (Safari-safe pattern). Tests verify the overlay DOM
// structure, the HTML content and that the book follows the app language.
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { describe, it, expect, vi, afterEach } from 'vitest';
// Mock `marked` so we don't need the real markdown parser
vi.mock('marked', () => ({
@@ -87,6 +88,18 @@ function getIframe(): HTMLIFrameElement | null {
return getOverlay()?.querySelector('iframe') ?? null;
}
// Echoes the key (plus any params) so the assertions read as "this string comes
// from i18n" instead of pinning English copy.
function t(key: string, params?: Record<string, string | number>): string {
if (!params) return key;
return `${key}(${Object.entries(params).map(([k, v]) => `${k}=${v}`).join(',')})`;
}
const longDate = (d: string, locale: string) =>
new Date(d + 'T00:00:00').toLocaleDateString(locale, {
weekday: 'long', month: 'long', day: 'numeric', year: 'numeric',
});
// ── Setup ────────────────────────────────────────────────────────────────────
afterEach(() => {
@@ -142,9 +155,10 @@ describe('downloadJourneyBookPDF', () => {
expect(getOverlay()).not.toBeNull();
const html = getIframe()!.srcdoc;
expect(html).toContain('Iceland Ring Road');
// No entry pages, but cover and closing page are still present
expect(html).toContain('Journey Book');
expect(html).toContain('The End');
// No entry pages, but cover and closing page are still present. Without a
// translator the chrome falls back to the raw keys instead of throwing.
expect(html).toContain('journey.pdf.journeyBook');
expect(html).toContain('journey.pdf.theEnd');
});
it('FE-COMP-JOURNEYPDF-007: sanitises HTML injected via an entry story and keeps the iframe script-free', async () => {
@@ -162,4 +176,72 @@ describe('downloadJourneyBookPDF', () => {
expect(html).toContain('Hello');
expect(html).toContain('world');
});
it('FE-COMP-JOURNEYPDF-008: renders cover, day header and closing page through i18n', async () => {
await downloadJourneyBookPDF(buildJourney(), { t, locale: 'de-DE' });
const html = getIframe()!.srcdoc;
expect(html).toContain('<html lang="de">');
expect(html).toContain('journey.pdf.journeyBook');
expect(html).toContain('journey.stats.days');
expect(html).toContain('journey.stats.entries');
expect(html).toContain('journey.stats.photos');
expect(html).toContain('journey.pdf.madeWith');
expect(html).toContain('journey.pdf.theEnd');
// Day header is the parameterised key plus a date in the picked locale —
// the hardcoded 'en' formatting would not produce this string.
expect(html).toContain('journey.detail.day(number=1)');
expect(html).toContain(longDate('2026-07-01', 'de-DE'));
// Pros/cons headings too.
expect(html).toContain('journey.verdict.lovedIt');
expect(html).toContain('journey.verdict.couldBeBetter');
});
it('FE-COMP-JOURNEYPDF-009: translates the preview bar above the book', async () => {
await downloadJourneyBookPDF(buildJourney(), { t, locale: 'de-DE' });
const overlay = getOverlay()!;
// cover + one entry page + closing page
expect(overlay.textContent).toContain('3 journey.pdf.pages');
expect(overlay.querySelector('#journey-pdf-save')!.textContent).toBe('journey.pdf.saveAsPdf');
expect(overlay.querySelector('#journey-pdf-close')!.textContent).toBe('common.close');
});
it('FE-COMP-JOURNEYPDF-010: prints mood and weather next to the entry', async () => {
const journey = buildJourney();
journey.entries[0].mood = 'good';
journey.entries[0].weather = 'rainy';
await downloadJourneyBookPDF(journey, { t, locale: 'en-US' });
const html = getIframe()!.srcdoc;
expect(html).toContain('journey.mood.good');
expect(html).toContain('journey.weather.rainy');
// Icons come along as inline SVG inside the chips.
expect(html).toContain('class="entry-chips"');
expect(html).toContain('<svg');
});
it('FE-COMP-JOURNEYPDF-011: skips chips for values the app does not know', async () => {
// The fixture carries mood 'excited', which is not one of the four moods.
await downloadJourneyBookPDF(buildJourney(), { t, locale: 'en-US' });
const html = getIframe()!.srcdoc;
// Scoped to the chip row: the page elsewhere is free to carry whatever the
// fixture happens to leave undefined, and that is not what this asserts.
const chips = html.match(/<div class="entry-chips">[\s\S]*?<\/div>/)?.[0] ?? '';
expect(chips).not.toBe('');
expect(chips).not.toContain('undefined');
expect(chips).not.toContain('journey.mood.');
// The known weather value still gets its chip.
expect(chips).toContain('journey.weather.sunny');
});
it('FE-COMP-JOURNEYPDF-012: leaves out the chip row when an entry has neither', async () => {
const journey = buildJourney();
journey.entries[0].mood = null;
journey.entries[0].weather = null;
await downloadJourneyBookPDF(journey, { t, locale: 'en-US' });
expect(getIframe()!.srcdoc).not.toContain('class="entry-chips"');
});
});
+92 -27
View File
@@ -1,7 +1,13 @@
// Journey Photo Book PDF — Polarsteps-inspired, magazine-density
import { createElement } from 'react'
import type { LucideIcon } from 'lucide-react'
import { marked } from 'marked'
import { sanitizeRichTextHtml } from '@trek/shared'
import type { JourneyDetail, JourneyEntry, JourneyPhoto } from '../../store/journeyStore'
import { MOOD_CONFIG, WEATHER_CONFIG } from '../../pages/journeyDetail/JourneyDetailPage.constants'
import { renderIconMarkup } from '../../utils/iconMarkup'
type Translate = (key: string, params?: Record<string, string | number>) => string
function esc(str: string | null | undefined): string {
if (!str) return ''
@@ -25,13 +31,9 @@ function pSrc(p: JourneyPhoto): string {
return abs(`/api/photos/${p.photo_id}/original`)
}
function fmtDate(d: string): string {
function fmtDate(d: string, locale: string): string {
const date = new Date(d + 'T00:00:00')
return date.toLocaleDateString('en', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' })
}
function fmtShort(d: string): string {
return new Date(d + 'T00:00:00').toLocaleDateString('en', { month: 'short', day: 'numeric' })
return date.toLocaleDateString(locale, { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' })
}
function groupByDate(entries: JourneyEntry[]): Map<string, JourneyEntry[]> {
@@ -44,7 +46,7 @@ function groupByDate(entries: JourneyEntry[]): Map<string, JourneyEntry[]> {
return groups
}
function renderProscons(entry: JourneyEntry): string {
function renderProscons(entry: JourneyEntry, tr: Translate): string {
const pc = entry.pros_cons
if (!pc) return ''
const pros = pc.pros?.filter(p => p.trim()) || []
@@ -52,11 +54,31 @@ function renderProscons(entry: JourneyEntry): string {
if (pros.length === 0 && cons.length === 0) return ''
return `<div class="verdict-wrap"><div class="verdict-row">
${pros.length > 0 ? `<div class="verdict-card pros"><div class="verdict-label">Loved it</div><ul>${pros.map(p => `<li>${esc(p)}</li>`).join('')}</ul></div>` : ''}
${cons.length > 0 ? `<div class="verdict-card cons"><div class="verdict-label">Could be better</div><ul>${cons.map(c => `<li>${esc(c)}</li>`).join('')}</ul></div>` : ''}
${pros.length > 0 ? `<div class="verdict-card pros"><div class="verdict-label">${esc(tr('journey.verdict.lovedIt'))}</div><ul>${pros.map(p => `<li>${esc(p)}</li>`).join('')}</ul></div>` : ''}
${cons.length > 0 ? `<div class="verdict-card cons"><div class="verdict-label">${esc(tr('journey.verdict.couldBeBetter'))}</div><ul>${cons.map(c => `<li>${esc(c)}</li>`).join('')}</ul></div>` : ''}
</div></div>`
}
function chip(icon: LucideIcon, label: string, bg: string, color: string): string {
const svg = renderIconMarkup(createElement(icon, { size: 12, strokeWidth: 2, color }))
return `<span class="chip" style="background:${bg};color:${color}">${svg}${esc(label)}</span>`
}
/**
* Mood and weather were on screen but never in the book (#1848). Unknown values
* (older entries, a provider-set category we don't render) drop out silently,
* the same way MoodChip/WeatherChip return null for them.
*/
function renderMoodWeather(entry: JourneyEntry, tr: Translate): string {
const chips: string[] = []
const mood = entry.mood ? MOOD_CONFIG[entry.mood] : undefined
if (mood) chips.push(chip(mood.icon, tr(mood.label), mood.bg, mood.text))
const weather = entry.weather ? WEATHER_CONFIG[entry.weather] : undefined
if (weather) chips.push(chip(weather.icon, tr(weather.label), '#f4f4f5', '#3f3f46'))
if (chips.length === 0) return ''
return `<div class="entry-chips">${chips.join('')}</div>`
}
function renderPhotoBlock(photos: JourneyPhoto[]): string {
if (photos.length === 0) return ''
if (photos.length === 1) {
@@ -75,7 +97,16 @@ function renderPhotoBlock(photos: JourneyPhoto[]): string {
</div>`
}
export async function downloadJourneyBookPDF(journey: JourneyDetail) {
/**
* `opts` stays optional so the signature is additive, but every caller passes
* the page's `t`/`locale` — without them the book falls back to raw keys (#1848).
*/
export async function downloadJourneyBookPDF(
journey: JourneyDetail,
opts: { t?: Translate; locale?: string } = {},
) {
const tr: Translate = opts.t || (key => key)
const loc = opts.locale || 'en'
const entries = (journey.entries || []).filter(e => e.type !== 'skeleton')
const allPhotos = entries.flatMap(e => e.photos || [])
const coverUrl = journey.cover_image ? abs(`/uploads/${journey.cover_image}`) : (allPhotos[0] ? pSrc(allPhotos[0]) : '')
@@ -96,14 +127,14 @@ export async function downloadJourneyBookPDF(journey: JourneyDetail) {
// Day header (inline, only on first entry of day)
const dayHeaderHtml = isFirstOfDay
? `<div class="day-header">Day ${di + 1} · ${fmtDate(date)}</div>`
? `<div class="day-header">${esc(tr('journey.detail.day', { number: di + 1 }))} · ${esc(fmtDate(date, loc))}</div>`
: ''
// Photo block
const photoHtml = renderPhotoBlock(photos)
// Pros/cons
const prosconsHtml = renderProscons(entry)
const prosconsHtml = renderProscons(entry, tr)
// Story (markdown)
const storyHtml = entry.story ? `<div class="entry-story">${md(entry.story)}</div>` : ''
@@ -114,6 +145,7 @@ export async function downloadJourneyBookPDF(journey: JourneyDetail) {
${photoHtml}
<div class="entry-content">
${meta ? `<div class="entry-meta">${esc(meta)}</div>` : ''}
${renderMoodWeather(entry, tr)}
${entry.title ? `<h2 class="entry-title">${esc(entry.title)}</h2>` : ''}
${storyHtml}
${prosconsHtml}
@@ -126,11 +158,17 @@ export async function downloadJourneyBookPDF(journey: JourneyDetail) {
const totalPages = pageNum + 1 // +1 for closing page
const html = `<!DOCTYPE html>
<html>
<html lang="${esc(loc.split('-')[0])}">
<head>
<meta charset="UTF-8">
<!-- The page is A4 landscape and laid out in pt, so it is about 1123px wide. Without
this, a phone lays the preview out at its default 980px and the document spills
out of the frame, which reads as being zoomed far in. Declaring the real width
makes the browser scale the whole page to fit instead. Printing is unaffected,
it goes by @page. -->
<meta name="viewport" content="width=1123">
<base href="${window.location.origin}/">
<title>${esc(journey.title)} — Journey Book</title>
<title>${esc(journey.title)} — ${esc(tr('journey.pdf.journeyBook'))}</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
@@ -207,6 +245,9 @@ export async function downloadJourneyBookPDF(journey: JourneyDetail) {
/* Entry content */
.entry-content { flex: 1; }
.entry-meta { font-size: 10pt; letter-spacing: 0.04em; text-transform: uppercase; color: #71717a; font-weight: 500; margin-bottom: 6pt; }
.entry-chips { display: flex; flex-wrap: wrap; gap: 5pt; margin-bottom: 8pt; }
.chip { display: inline-flex; align-items: center; gap: 3pt; padding: 2.5pt 7pt; border-radius: 999pt; font-size: 8.5pt; font-weight: 600; }
.chip svg { width: 9pt; height: 9pt; }
h2.entry-title { font-size: 28pt; font-weight: 700; letter-spacing: -0.02em; line-height: 1.1; margin: 0 0 10pt; color: #0a0a0f; }
.entry-story { font-size: 11pt; line-height: 1.65; color: #3f3f46; }
.entry-story p { margin: 0 0 8pt; }
@@ -262,16 +303,16 @@ export async function downloadJourneyBookPDF(journey: JourneyDetail) {
<div class="cover-dim"></div>
<div class="cover-mesh"></div>
<div class="cover-content">
<div class="cover-label">Journey Book</div>
<div class="cover-label">${esc(tr('journey.pdf.journeyBook'))}</div>
<h1>${esc(journey.title)}</h1>
${journey.subtitle ? `<div class="sub">${esc(journey.subtitle)}</div>` : ''}
<div class="cover-stats">
<div><div class="cover-stat-val">${dates.length}</div><div class="cover-stat-label">Days</div></div>
<div><div class="cover-stat-val">${entries.length}</div><div class="cover-stat-label">Entries</div></div>
<div><div class="cover-stat-val">${allPhotos.length}</div><div class="cover-stat-label">Photos</div></div>
<div><div class="cover-stat-val">${dates.length}</div><div class="cover-stat-label">${esc(tr('journey.stats.days'))}</div></div>
<div><div class="cover-stat-val">${entries.length}</div><div class="cover-stat-label">${esc(tr('journey.stats.entries'))}</div></div>
<div><div class="cover-stat-val">${allPhotos.length}</div><div class="cover-stat-label">${esc(tr('journey.stats.photos'))}</div></div>
</div>
</div>
<div class="cover-footer">Made with TREK</div>
<div class="cover-footer">${esc(tr('journey.pdf.madeWith'))}</div>
</div>
<!-- Entry Pages -->
@@ -280,8 +321,8 @@ export async function downloadJourneyBookPDF(journey: JourneyDetail) {
<!-- Closing Page -->
<div class="closing-page">
<div>
<div class="closing-title">The End</div>
<div class="closing-sub">Made with TREK · ${new Date().getFullYear()}</div>
<div class="closing-title">${esc(tr('journey.pdf.theEnd'))}</div>
<div class="closing-sub">${esc(tr('journey.pdf.madeWith'))} · ${new Date().getFullYear()}</div>
</div>
</div>
@@ -296,16 +337,39 @@ export async function downloadJourneyBookPDF(journey: JourneyDetail) {
overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.75);z-index:9999;display:flex;align-items:center;justify-content:center;padding:8px;'
overlay.onclick = (e) => { if (e.target === overlay) overlay.remove() }
// The chrome needs a stylesheet rather than inline styles: on a phone the title
// and the two labels do not fit on one row, and translated labels are longer
// than the English ones. Below 640px the card goes full-bleed, the decorative
// title steps aside and the two actions share the width (#1848).
const style = document.createElement('style')
style.textContent = `
#journey-pdf-overlay .jp-card { width:100%;max-width:1100px;height:95vh;background:#fff;border-radius:12px;overflow:hidden;display:flex;flex-direction:column;box-shadow:0 20px 60px rgba(0,0,0,0.35); }
#journey-pdf-overlay .jp-head { display:flex;align-items:center;justify-content:space-between;gap:8px;padding:8px 16px;border-bottom:1px solid #e4e4e7;flex-shrink:0;background:#0f172a; }
#journey-pdf-overlay .jp-title { min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;color:rgba(255,255,255,0.45);font-weight:500;letter-spacing:0.03em; }
#journey-pdf-overlay .jp-actions { display:flex;align-items:center;gap:8px;flex:none; }
#journey-pdf-overlay .jp-btn { min-height:44px;padding:10px 20px;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit;white-space:nowrap; }
#journey-pdf-overlay .jp-save { border:none;background:#fff;color:#0f172a; }
#journey-pdf-overlay .jp-close { border:1px solid rgba(255,255,255,0.15);background:rgba(255,255,255,0.1);color:rgba(255,255,255,0.7); }
@media (max-width: 640px) {
#journey-pdf-overlay { padding:0; }
#journey-pdf-overlay .jp-card { height:100dvh;max-width:none;border-radius:0; }
#journey-pdf-overlay .jp-head { padding:8px 10px; }
#journey-pdf-overlay .jp-title { display:none; }
#journey-pdf-overlay .jp-actions { flex:1; }
#journey-pdf-overlay .jp-btn { flex:1;padding:10px 12px;font-size:13px; }
}
`
const card = document.createElement('div')
card.style.cssText = 'width:100%;max-width:1100px;height:95vh;background:#fff;border-radius:12px;overflow:hidden;display:flex;flex-direction:column;box-shadow:0 20px 60px rgba(0,0,0,0.35);'
card.className = 'jp-card'
const header = document.createElement('div')
header.style.cssText = 'display:flex;align-items:center;justify-content:space-between;padding:8px 16px;border-bottom:1px solid #e4e4e7;flex-shrink:0;background:#0f172a;'
header.className = 'jp-head'
header.innerHTML = `
<span style="font-size:12px;color:rgba(255,255,255,0.45);font-weight:500;letter-spacing:0.03em">${esc(journey.title)} &middot; ${totalPages} pages</span>
<div style="display:flex;align-items:center;gap:8px">
<button id="journey-pdf-save" style="min-height:44px;padding:10px 20px;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit;border:none;background:#fff;color:#0f172a;">Save as PDF</button>
<button id="journey-pdf-close" style="min-height:44px;padding:10px 16px;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;font-family:inherit;border:1px solid rgba(255,255,255,0.15);background:rgba(255,255,255,0.1);color:rgba(255,255,255,0.7);">Close</button>
<span class="jp-title">${esc(journey.title)} &middot; ${totalPages} ${esc(tr('journey.pdf.pages'))}</span>
<div class="jp-actions">
<button id="journey-pdf-save" class="jp-btn jp-save">${esc(tr('journey.pdf.saveAsPdf'))}</button>
<button id="journey-pdf-close" class="jp-btn jp-close">${esc(tr('common.close'))}</button>
</div>
`
@@ -318,6 +382,7 @@ export async function downloadJourneyBookPDF(journey: JourneyDetail) {
card.appendChild(header)
card.appendChild(iframe)
overlay.appendChild(style)
overlay.appendChild(card)
document.body.appendChild(overlay)
@@ -7,13 +7,21 @@ import { catMeta } from '../Budget/costsCategories'
import type { BudgetItem } from '../../types'
/**
* The Costs block inside a booking modal. Replaces the old inline price + budget
* category fields: when no expense is linked yet it offers a "create expense"
* button (the modal saves the booking first, then opens the full Costs editor);
* once linked it shows the expense with edit / remove actions.
* The Costs block inside a booking modal — and, since #1298, inside the place
* form, which links its expense the same way. Replaces the old inline price +
* budget category fields: when no expense is linked yet it offers a "create
* expense" button (the modal saves its own record first, then opens the full
* Costs editor); once linked it shows the expense with edit / remove actions.
*
* Exactly one of reservationId / placeId is set — they are the two sides of the
* same link, and the block behaves identically on both.
*/
export function BookingCostsSection({ reservationId, pendingExpense, onCreate, onEdit, onRemove }: {
export function BookingCostsSection({ reservationId, placeId = null, hintKey = 'reservations.createExpenseHint', pendingExpense, onCreate, onEdit, onRemove }: {
reservationId: number | null
/** Set instead of reservationId when the block sits in the place form (#1298). */
placeId?: number | null
/** What gets saved before the editor opens — "the booking" or "the place". */
hintKey?: string
/** A cost parsed from an import that will be linked on save — previewed before the booking exists. */
pendingExpense?: { total_price: number; currency?: string | null; category: string } | null
onCreate: () => void
@@ -25,7 +33,11 @@ export function BookingCostsSection({ reservationId, pendingExpense, onCreate, o
const trip = useTripStore(s => s.trip)
const displayCurrency = useSettingsStore(s => s.settings.default_currency)
const base = (displayCurrency || trip?.currency || 'EUR').toUpperCase()
const linked = reservationId ? budgetItems.find(i => i.reservation_id === reservationId) : null
const linked = reservationId
? budgetItems.find(i => i.reservation_id === reservationId)
: placeId
? budgetItems.find(i => i.place_id === placeId)
: null
const labelCls = 'block text-[11px] font-semibold uppercase tracking-[0.08em] text-content-faint mb-[6px]'
@@ -40,7 +52,7 @@ export function BookingCostsSection({ reservationId, pendingExpense, onCreate, o
<span style={{ width: 26, height: 26, borderRadius: 7, display: 'grid', placeItems: 'center', background: meta.color + '22', color: meta.color, flexShrink: 0 }}><Icon size={14} /></span>
<div style={{ flex: 1, minWidth: 0 }}>
<div className="text-content" style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600 }}>{t(meta.labelKey)}</div>
<div className="text-content-faint" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}>{t('reservations.createExpenseHint')}</div>
<div className="text-content-faint" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}>{t(hintKey)}</div>
</div>
<span className="text-content" style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 700, flexShrink: 0 }}>{formatMoney(pendingExpense.total_price, pendingExpense.currency || base, locale)}</span>
</div>
@@ -76,7 +88,7 @@ export function BookingCostsSection({ reservationId, pendingExpense, onCreate, o
style={{ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '11px 13px', borderRadius: 10, fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>
<Plus size={15} /> {t('reservations.createExpense')}
</button>
<div className="text-content-faint" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', marginTop: 6 }}>{t('reservations.createExpenseHint')}</div>
<div className="text-content-faint" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', marginTop: 6 }}>{t(hintKey)}</div>
</div>
)
}
@@ -1,11 +1,12 @@
import type { BudgetItem } from '../../types'
/**
* A request from a booking modal to open the Costs expense editor — either to
* edit the already-linked expense, or to create a new one prefilled from the
* booking (the modal saves the booking first so `reservationId` is known).
* A request from a booking modal — or from the place form (#1298) — to open the
* Costs expense editor: either to edit the already-linked expense, or to create
* a new one prefilled from the record. The modal saves itself first, so the
* `reservationId` / `placeId` it names already exists.
*/
export interface BookingExpenseRequest {
editItem?: BudgetItem
prefill?: { reservationId?: number; name?: string; category?: string; amount?: number }
prefill?: { reservationId?: number; placeId?: number; name?: string; category?: string; amount?: number }
}
@@ -184,11 +184,17 @@ beforeEach(() => {
// otherwise leak into the ones after them.
vi.mocked(calculateRouteWithLegs).mockImplementation(waypoints => Promise.resolve({
coordinates: [], distance: 0, duration: 0,
legs: Array.from({ length: Math.max(0, (waypoints?.length ?? 0) - 1) }, () => ({
mid: [0, 0] as [number, number], from: [0, 0] as [number, number], to: [0, 0] as [number, number],
distance: 2000, duration: 600, distanceText: '2 km', durationText: '10 min',
drivingText: '10 min', walkingText: '25 min',
})),
// Each leg carries its endpoint coordinates (mirrors the real RouteCalculator), so
// connector-driven features that read seg.from/seg.to see faithful [lat, lng] pairs.
legs: Array.from({ length: Math.max(0, (waypoints?.length ?? 0) - 1) }, (_, i) => {
const a = waypoints[i], b = waypoints[i + 1]
return {
mid: [(a.lat + b.lat) / 2, (a.lng + b.lng) / 2] as [number, number],
from: [a.lat, a.lng] as [number, number], to: [b.lat, b.lng] as [number, number],
distance: 2000, duration: 600, distanceText: '2 km', durationText: '10 min',
drivingText: '10 min', walkingText: '25 min',
}
}),
}))
vi.mocked(generateGoogleMapsUrl).mockReturnValue('https://maps.google.com/...')
vi.mocked(generateCoMapsUrl).mockReturnValue('https://comaps.at/...')
@@ -606,16 +612,17 @@ describe('DayPlanSidebar', () => {
// ── PDF export ──────────────────────────────────────────────────────────
it('FE-PLANNER-DAYPLAN-025: PDF export button is present', () => {
it('FE-PLANNER-DAYPLAN-025: the export button is present', () => {
render(<DayPlanSidebar {...makeDefaultProps()} />)
expect(screen.getByText('PDF')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Export' })).toBeInTheDocument()
})
it('FE-PLANNER-DAYPLAN-026: clicking PDF button calls downloadTripPDF', async () => {
it('FE-PLANNER-DAYPLAN-026: the PDF row in the export dialog calls downloadTripPDF', async () => {
const user = userEvent.setup()
const { downloadTripPDF } = await import('../PDF/TripPDF')
render(<DayPlanSidebar {...makeDefaultProps()} />)
await user.click(screen.getByText('PDF'))
await user.click(screen.getByRole('button', { name: 'Export' }))
await user.click(await screen.findByText('PDF'))
await waitFor(() => {
expect(downloadTripPDF).toHaveBeenCalled()
})
@@ -896,11 +903,14 @@ describe('DayPlanSidebar', () => {
// Day-title renaming moved to DayDetailPanel (#1065) — covered there.
// ── ICS export button ────────────────────────────────────────────────────
// ── ICS export ───────────────────────────────────────────────────────────
it('FE-PLANNER-DAYPLAN-043: ICS export button is present', () => {
it('FE-PLANNER-DAYPLAN-043: the calendar export sits in the export dialog', async () => {
const user = userEvent.setup()
render(<DayPlanSidebar {...makeDefaultProps()} />)
expect(screen.getByText('ICS')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Export' }))
expect(await screen.findByText('Calendar')).toBeInTheDocument()
expect(screen.getByText('Download .ics')).toBeInTheDocument()
})
// ── getMergedItems: transport merged with assignments ──────────────────
@@ -1116,13 +1126,12 @@ describe('DayPlanSidebar', () => {
// ── PDF hover tooltip ─────────────────────────────────────────────────
it('FE-PLANNER-DAYPLAN-054: hovering PDF button shows tooltip', async () => {
it('FE-PLANNER-DAYPLAN-054: hovering the export button shows its tooltip', async () => {
const user = userEvent.setup()
render(<DayPlanSidebar {...makeDefaultProps()} />)
const pdfBtn = screen.getByText('PDF').closest('button')!
await user.hover(pdfBtn)
await user.hover(screen.getByRole('button', { name: 'Export' }))
await waitFor(() => {
// Tooltip text appears (from t('dayplan.pdfTooltip'))
// Tooltip text appears (from t('dayplan.exportIntro'))
const tooltips = document.querySelectorAll('[style*="pointer-events: none"]')
expect(tooltips.length).toBeGreaterThan(0)
})
@@ -1190,10 +1199,9 @@ describe('DayPlanSidebar', () => {
const createObjURL = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:mock')
const revokeObjURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})
render(<DayPlanSidebar {...makeDefaultProps()} />)
// The ICS button now opens a hover menu (Download / Subscribe) instead of
// downloading on direct click.
await user.hover(screen.getByText('ICS').closest('button')!)
await user.click(await screen.findByText('Download ICS'))
// The three export buttons collapsed into one that opens the export dialog.
await user.click(screen.getByRole('button', { name: 'Export' }))
await user.click(await screen.findByText('Download .ics'))
await waitFor(() => expect(fetchSpy).toHaveBeenCalledWith('/api/trips/1/export.ics', expect.any(Object)))
fetchSpy.mockRestore()
createObjURL.mockRestore()
@@ -1827,8 +1835,8 @@ describe('DayPlanSidebar', () => {
render(<DayPlanSidebar {...makeDefaultProps({
days: [day], places: [place], assignments: { '10': [assignment] },
})} />)
const pdfBtn = screen.getByRole('button', { name: /pdf/i })
await user.click(pdfBtn)
await user.click(screen.getByRole('button', { name: 'Export' }))
await user.click(await screen.findByText('PDF'))
await waitFor(() => expect(downloadTripPDF).toHaveBeenCalledWith(
expect.objectContaining({ dayNotes: expect.arrayContaining([expect.objectContaining({ text: 'PDF Note' })]) })
))
@@ -1912,16 +1920,17 @@ describe('DayPlanSidebar', () => {
}
})
// ── ICS hover tooltip ─────────────────────────────────────────────────────
// ── Export dialog ─────────────────────────────────────────────────────────
it('FE-PLANNER-DAYPLAN-090: hovering ICS button shows the download/subscribe menu', async () => {
it('FE-PLANNER-DAYPLAN-090: the export button opens the dialog with every format', async () => {
const user = userEvent.setup()
render(<DayPlanSidebar {...makeDefaultProps()} />)
const icsBtn = screen.getByText('ICS').closest('button')!
await user.hover(icsBtn)
await user.click(screen.getByRole('button', { name: 'Export' }))
await waitFor(() => {
expect(screen.getByText('Download ICS')).toBeInTheDocument()
expect(screen.getByText('PDF')).toBeInTheDocument()
expect(screen.getByText('Download .ics')).toBeInTheDocument()
expect(screen.getByText('Subscribe to calendar')).toBeInTheDocument()
expect(screen.getByText('Whole trip')).toBeInTheDocument()
})
})
@@ -3462,6 +3471,100 @@ describe('DayPlanSidebar', () => {
expect(vi.mocked(assignmentsApi.updateTransport)).toHaveBeenLastCalledWith(1, 11, null)
})
it('FE-PLANNER-DAYPLAN-171b: a stop-to-stop connector offers public transport pre-filled from the leg', async () => {
const user = userEvent.setup()
const onPlanTransitLeg = vi.fn()
const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' })
const assignments = {
'10': [
buildAssignment({ id: 11, day_id: 10, order_index: 0, place: buildPlace({ id: 1, name: 'Louvre', place_time: '10:30', lat: 48.86, lng: 2.34 }) }),
buildAssignment({ id: 12, day_id: 10, order_index: 1, place: buildPlace({ id: 2, name: 'Orsay', lat: 48.87, lng: 2.33 }) }),
],
}
render(<DayPlanSidebar {...makeDefaultProps({ days: [day], assignments, selectedDayId: 10, routeShown: true, onPlanTransitLeg })} />)
await user.click(await screen.findByTitle('Change travel mode'))
await user.click(contextMenu().getByRole('button', { name: 'Public transit' }))
// Origin/destination + this stop's departure time, resolved back from the leg coords.
expect(onPlanTransitLeg).toHaveBeenCalledWith({
dayId: 10,
from: { name: 'Louvre', lat: 48.86, lng: 2.34 },
to: { name: 'Orsay', lat: 48.87, lng: 2.33 },
time: '10:30',
})
})
it('FE-PLANNER-DAYPLAN-171c: the public-transport entry is absent without the onPlanTransitLeg handler', async () => {
const user = userEvent.setup()
const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' })
const assignments = {
'10': [
buildAssignment({ id: 11, day_id: 10, order_index: 0, place: buildPlace({ id: 1, name: 'A', lat: 48.85, lng: 2.35 }) }),
buildAssignment({ id: 12, day_id: 10, order_index: 1, place: buildPlace({ id: 2, name: 'B', lat: 48.86, lng: 2.36 }) }),
],
}
render(<DayPlanSidebar {...makeDefaultProps({ days: [day], assignments, selectedDayId: 10, routeShown: true })} />)
await user.click(await screen.findByTitle('Change travel mode'))
expect(contextMenu().queryByRole('button', { name: 'Public transit' })).not.toBeInTheDocument()
})
it('FE-PLANNER-DAYPLAN-171d: a hotel bookend connector offers public transport from the hotel', async () => {
const user = userEvent.setup()
const onPlanTransitLeg = vi.fn()
const days = [
buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }),
buildDay({ id: 11, date: '2025-06-02', title: 'Day 2' }),
buildDay({ id: 12, date: '2025-06-03', title: 'Day 3' }),
]
const accommodations: Accommodation[] = [{
id: 1, trip_id: 1, start_day_id: 10, end_day_id: 12,
place_lat: 48.85, place_lng: 2.35, place_name: 'Hotel Lutetia',
}]
const assignments = {
'11': [
buildAssignment({ id: 11, day_id: 11, order_index: 0, place: buildPlace({ id: 1, name: 'Louvre', lat: 48.86, lng: 2.34 }) }),
buildAssignment({ id: 12, day_id: 11, order_index: 1, place: buildPlace({ id: 2, name: 'Orsay', lat: 48.87, lng: 2.33 }) }),
],
}
render(<DayPlanSidebar {...makeDefaultProps({ days, assignments, accommodations, selectedDayId: 11, routeShown: true, onPlanTransitLeg })} />)
// The morning bookend (hotel -> first stop) is the first connector in the list.
const connectors = await screen.findAllByTitle('Change travel mode')
await user.click(connectors[0])
await user.click(contextMenu().getByRole('button', { name: 'Public transit' }))
expect(onPlanTransitLeg).toHaveBeenCalledWith(expect.objectContaining({
dayId: 11,
from: { name: 'Hotel Lutetia', lat: 48.85, lng: 2.35 },
to: { name: 'Louvre', lat: 48.86, lng: 2.34 },
// The hotel has no place_time, so the departure time falls back to null (the
// panel then uses its own 09:00 default).
time: null,
}))
})
it('FE-PLANNER-DAYPLAN-171e: a revisited stop seeds THIS day\'s departure time, not another day\'s', async () => {
const user = userEvent.setup()
const onPlanTransitLeg = vi.fn()
const days = [
buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }),
buildDay({ id: 11, date: '2025-06-02', title: 'Day 2' }),
]
// The SAME located POI (identical coords) is visited on both days at different
// times. Day 10 has it alone (no leg); day 11 pairs it with Rodin (one leg).
const assignments = {
'10': [
buildAssignment({ id: 11, day_id: 10, order_index: 0, place: buildPlace({ id: 1, name: 'Louvre', place_time: '09:00', lat: 48.86, lng: 2.34 }) }),
],
'11': [
buildAssignment({ id: 21, day_id: 11, order_index: 0, place: buildPlace({ id: 1, name: 'Louvre', place_time: '16:30', lat: 48.86, lng: 2.34 }) }),
buildAssignment({ id: 22, day_id: 11, order_index: 1, place: buildPlace({ id: 3, name: 'Rodin', lat: 48.855, lng: 2.315 }) }),
],
}
render(<DayPlanSidebar {...makeDefaultProps({ days, assignments, selectedDayId: 11, routeShown: true, onPlanTransitLeg })} />)
await user.click(await screen.findByTitle('Change travel mode'))
await user.click(contextMenu().getByRole('button', { name: 'Public transit' }))
// Day 11's own 16:30, not day 10's 09:00 (a trip-wide coord index would leak it).
expect(onPlanTransitLeg).toHaveBeenCalledWith(expect.objectContaining({ dayId: 11, time: '16:30' }))
})
it('FE-PLANNER-DAYPLAN-172: a failing per-segment save is reported and the days are refetched', async () => {
const user = userEvent.setup()
const { assignmentsApi } = await import('../../api/client')
+108 -39
View File
@@ -5,6 +5,7 @@ declare global { interface Window { __dragData: DragDataPayload | null } }
import React, { useState, useEffect, useLayoutEffect, useRef, useMemo, useCallback } from 'react'
import { avatarSrc } from '../../utils/avatarSrc'
import { ChevronDown, ChevronRight, ChevronUp, Compass, Navigation, RotateCcw, ExternalLink, Clock, Pencil, GripVertical, Ticket, Plus, FileText, Trash2, Car, Lock, Hotel, Footprints, Route as RouteIcon, Bookmark, TramFront, Zap } from 'lucide-react'
import { type PickedPlace } from './TransitSearchPanel'
import { assignmentsApi, reservationsApi, daysApi } from '../../api/client'
import { calculateRouteWithLegs, optimizeRoute, generateGoogleMapsUrl, generateCoMapsUrl, type NamedWaypoint } from '../Map/RouteCalculator'
import PlaceAvatar from '../shared/PlaceAvatar'
@@ -99,6 +100,12 @@ interface DayPlanSidebarProps {
onAddTransport?: (dayId: number) => void
/** Opens the public-transit route search for a day (#1065). */
onPlanTransit?: (dayId: number) => void
/**
* Opens the public-transit search pre-filled for a single leg (#1281 follow-up):
* the leg's origin and destination endpoints plus the origin's departure time,
* so "public transport" becomes an option on any connector, not just the day header.
*/
onPlanTransitLeg?: (leg: { dayId: number; from: PickedPlace; to: PickedPlace; time: string | null }) => void
/** Opens the journey view for a saved transit entry (#1065). */
onOpenTransit?: (reservation: Reservation) => void
onEditTransport?: (reservation: Reservation) => void
@@ -148,6 +155,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
onRouteRefresh,
onAddTransport,
onPlanTransit,
onPlanTransitLeg,
onOpenTransit,
onEditTransport,
onEditReservation,
@@ -203,7 +211,6 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
const [lockedIds, setLockedIds] = useState(new Set())
const [lockHoverId, setLockHoverId] = useState(null)
const [undoHover, setUndoHover] = useState(false)
const [icsHover, setIcsHover] = useState(false)
const [hoveredAssignmentId, setHoveredAssignmentId] = useState<number | null>(null)
// Transit rows fold their itinerary out inline (#1065).
const [expandedTransitIds, setExpandedTransitIds] = useState<Set<number>>(new Set())
@@ -977,6 +984,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
onRouteRefresh,
onAddTransport,
onPlanTransit,
onPlanTransitLeg,
onOpenTransit,
onEditTransport,
expandedTransitIds,
@@ -1025,8 +1033,6 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
setLockHoverId,
undoHover,
setUndoHover,
icsHover,
setIcsHover,
hoveredAssignmentId,
setHoveredAssignmentId,
dropTargetKey,
@@ -1151,6 +1157,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
onRouteRefresh,
onAddTransport,
onPlanTransit,
onPlanTransitLeg,
onOpenTransit,
onEditTransport,
expandedTransitIds,
@@ -1199,8 +1206,6 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
setLockHoverId,
undoHover,
setUndoHover,
icsHover,
setIcsHover,
hoveredAssignmentId,
setHoveredAssignmentId,
dropTargetKey,
@@ -1284,11 +1289,71 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
})
}
// Open the mode menu at the clicked connector: every route profile plus a
// "use day default" entry that clears the per-leg override.
const openLegModeMenu = (e: React.MouseEvent, assignmentId: number, dayId: number) => {
// A connector's endpoints carry only coordinates (RouteSegment.from/to, both
// [lat, lng]); resolve them back to the NAMES the transit search shows by indexing
// every located place, hotel and booking endpoint on the trip. Name is a property
// of a coordinate, so a trip-wide index is fine; a connector only renders when both
// ends are located, so a coordinate that misses the index is rare (nameless pick).
const transitNameIndex = useMemo(() => {
const m = new Map<string, string>()
const put = (lat?: number | null, lng?: number | null, name?: string | null) => {
if (lat == null || lng == null || !name) return
const k = `${lat},${lng}`
if (!m.has(k)) m.set(k, name)
}
for (const list of Object.values(assignments)) {
for (const a of list) put(a.place?.lat, a.place?.lng, a.place?.name)
}
for (const acc of accommodations) put(acc.place_lat, acc.place_lng, acc.place_name)
for (const r of reservations) {
for (const ep of (r.endpoints || [])) put(ep.lat, ep.lng, ep.name)
}
return m
}, [assignments, accommodations, reservations])
// The leg's departure time must be resolved WITHIN its day: the same located POI can
// be revisited on another day at a different time (a supported pattern), so a
// trip-wide coordinate index would return the wrong day's time. Scope to this day's
// assignments (and the reservations that touch it) so a revisit keeps its own time.
const originDepartureTime = (originKey: string, dayId: number): string | null => {
for (const a of assignments[String(dayId)] ?? []) {
if (a.place?.lat != null && a.place?.lng != null && `${a.place.lat},${a.place.lng}` === originKey) return a.place.place_time ?? null
}
for (const r of reservations) {
if (r.day_id !== dayId && r.end_day_id !== dayId) continue
for (const ep of (r.endpoints || [])) {
if (ep.lat != null && ep.lng != null && `${ep.lat},${ep.lng}` === originKey) return ep.local_time ?? null
}
}
return null
}
// Build the "public transport" prefill for a leg from its RouteSegment: MOTIS is
// driven off the coordinates, the names come from the index and the departure time
// from the origin's own day. Accepts 'H:mm' or 'HH:mm[:ss]', normalised to 'HH:mm'.
const buildTransitLeg = (seg: RouteSegment | undefined, dayId: number): { from: PickedPlace; to: PickedPlace; time: string | null } | null => {
if (!seg?.from || !seg?.to) return null
const pick = (c: [number, number]): PickedPlace => ({ name: transitNameIndex.get(`${c[0]},${c[1]}`) || '', lat: c[0], lng: c[1] })
const rawTime = originDepartureTime(`${seg.from[0]},${seg.from[1]}`, dayId)
const m = rawTime ? /^(\d{1,2}):(\d{2})/.exec(rawTime) : null
return { from: pick(seg.from), to: pick(seg.to), time: m ? `${m[1].padStart(2, '0')}:${m[2]}` : null }
}
// The extra connector-menu entry (#1281 follow-up): search public transit for this
// leg instead of drawing a road route. Only when a handler is wired (day has dates).
const transitLegMenuItem = (dayId: number, seg?: RouteSegment) => {
if (!onPlanTransitLeg) return []
const leg = buildTransitLeg(seg, dayId)
if (!leg) return []
return [{ label: t('transit.title'), icon: TramFront, onClick: () => onPlanTransitLeg({ dayId, from: leg.from, to: leg.to, time: leg.time }) }]
}
// Open the mode menu at the clicked connector: every route profile, the optional
// "public transport" entry, plus a "use day default" entry that clears the override.
const openLegModeMenu = (e: React.MouseEvent, assignmentId: number, dayId: number, seg?: RouteSegment) => {
ctxMenu.open(e, [
...routeProfileOptions.map(o => ({ label: o.label, icon: modeIcon(o.key), onClick: () => setLegMode(assignmentId, dayId, o.key) })),
...transitLegMenuItem(dayId, seg),
{ divider: true },
{ label: t('dayplan.transportMode.useDefault'), icon: RotateCcw, onClick: () => setLegMode(assignmentId, dayId, null) },
])
@@ -1310,9 +1375,10 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
})
}
const openIncomingLegModeMenu = (e: React.MouseEvent, assignmentId: number, dayId: number) => {
const openIncomingLegModeMenu = (e: React.MouseEvent, assignmentId: number, dayId: number, seg?: RouteSegment) => {
ctxMenu.open(e, [
...routeProfileOptions.map(o => ({ label: o.label, icon: modeIcon(o.key), onClick: () => setIncomingLegMode(assignmentId, dayId, o.key) })),
...transitLegMenuItem(dayId, seg),
{ divider: true },
{ label: t('dayplan.transportMode.useDefault'), icon: RotateCcw, onClick: () => setIncomingLegMode(assignmentId, dayId, null) },
])
@@ -1334,8 +1400,6 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
t={t}
locale={locale}
toast={toast}
icsHover={icsHover}
setIcsHover={setIcsHover}
expandedDays={expandedDays}
setExpandedDays={setExpandedDays}
onUndo={onUndo}
@@ -1664,7 +1728,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
const targetId = hotelLegs[day.id]?.top?.targetId
const connector = <HotelRouteConnector seg={hotelLegs[day.id]!.top!.seg} name={hotelLegs[day.id]!.top!.name} profile={routeProfile} placement="top" />
return canEditDays && targetId != null ? (
<div role="button" tabIndex={0} title={t('dayplan.transportMode.change')} onClick={e => openIncomingLegModeMenu(e, targetId, day.id)} style={{ cursor: 'pointer' }}>
<div role="button" tabIndex={0} title={t('dayplan.transportMode.change')} onClick={e => openIncomingLegModeMenu(e, targetId, day.id, hotelLegs[day.id]!.top!.seg)} style={{ cursor: 'pointer' }}>
{connector}
</div>
) : connector
@@ -1906,33 +1970,38 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
const confirmed = res.status === 'confirmed'
const hasEndpoints = onToggleConnection && (res.endpoints || []).length >= 2
const active = hasEndpoints ? visibleConnectionIds.includes(res.id) : false
// The status, the time and the flight/train number used to sit in one
// pill strung together on a middle dot, which read as one run-on
// sentence. They are separate chips now: same tint so they still
// belong together, own outline so the eye can take them one at a time.
const RI = RES_ICONS[res.type] || Ticket
const tint = confirmed ? 'bg-[rgba(22,163,74,0.1)] text-[#16a34a]' : 'bg-[rgba(217,119,6,0.1)] text-[#d97706]'
const chip: React.CSSProperties = {
display: 'inline-flex', alignItems: 'center', gap: 3,
padding: '1px 6px', borderRadius: 5,
fontSize: 'calc(9px * var(--fs-scale-caption, 1))', fontWeight: 600,
whiteSpace: 'nowrap',
}
const { time: st } = splitReservationDateTime(res.reservation_time)
const { time: et } = splitReservationDateTime(res.reservation_end_time)
const timeLabel = st || et
? `${st ? formatTime(st, locale, timeFormat) : ''}${et ? ` – ${formatTime(et, locale, timeFormat)}` : ''}`
: ''
let meta: any = {}
try { meta = typeof res.metadata === 'string' ? JSON.parse(res.metadata || '{}') : (res.metadata || {}) } catch { meta = {} }
const carrierLabel = meta
? (meta.airline && meta.flight_number ? `${meta.airline} ${meta.flight_number}` : meta.flight_number || meta.train_number || '')
: ''
return (
<div style={{ marginTop: 3, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
<div className={confirmed ? 'bg-[rgba(22,163,74,0.1)] text-[#16a34a]' : 'bg-[rgba(217,119,6,0.1)] text-[#d97706]'} style={{ display: 'inline-flex', alignItems: 'center', gap: 3, padding: '1px 6px', borderRadius: 5, fontSize: 'calc(9px * var(--fs-scale-caption, 1))', fontWeight: 600,
}}>
{(() => { const RI = RES_ICONS[res.type] || Ticket; return <RI size={8} /> })()}
// No wrapping: the time belongs to the status it qualifies, so the
// chips stay on one line even when the row gets narrow.
<div style={{ marginTop: 3, display: 'inline-flex', alignItems: 'center', gap: 3, flexWrap: 'nowrap' }}>
<div className={tint} style={chip}>
<RI size={8} />
<span className="hidden sm:inline">{confirmed ? t('planner.resConfirmed') : t('planner.resPending')}</span>
{(() => {
const { time: st } = splitReservationDateTime(res.reservation_time)
const { time: et } = splitReservationDateTime(res.reservation_end_time)
if (!st && !et) return null
return (
<span style={{ fontWeight: 400 }}>
{st ? formatTime(st, locale, timeFormat) : ''}
{et ? ` – ${formatTime(et, locale, timeFormat)}` : ''}
</span>
)
})()}
{(() => {
let meta: any = {}
try { meta = typeof res.metadata === 'string' ? JSON.parse(res.metadata || '{}') : (res.metadata || {}) } catch { meta = {} }
if (!meta) return null
if (meta.airline && meta.flight_number) return <span style={{ fontWeight: 400 }}>{meta.airline} {meta.flight_number}</span>
if (meta.flight_number) return <span style={{ fontWeight: 400 }}>{meta.flight_number}</span>
if (meta.train_number) return <span style={{ fontWeight: 400 }}>{meta.train_number}</span>
return null
})()}
</div>
{timeLabel && <span className={tint} style={{ ...chip, fontWeight: 500 }}>{timeLabel}</span>}
{carrierLabel && <span className={tint} style={{ ...chip, fontWeight: 500 }}>{carrierLabel}</span>}
{hasEndpoints && (
<button
type="button"
@@ -2034,7 +2103,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
</div>
{daySchedule.byAssignment[day.id]?.[assignment.id]?.map(si => <PluginDayScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)}
{routeLegs[day.id]?.[assignment.id] && (canEditDays ? (
<div role="button" tabIndex={0} title={t('dayplan.transportMode.change')} onClick={e => openLegModeMenu(e, assignment.id, day.id)} style={{ cursor: 'pointer' }}>
<div role="button" tabIndex={0} title={t('dayplan.transportMode.change')} onClick={e => openLegModeMenu(e, assignment.id, day.id, routeLegs[day.id]![assignment.id])} style={{ cursor: 'pointer' }}>
<RouteConnector seg={routeLegs[day.id]![assignment.id]} profile={routeProfile} />
</div>
) : (
@@ -2273,7 +2342,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
const nextPlaceId = merged.slice(idx + 1).find(i => i.type === 'place' && i.data.place?.lat && i.data.place?.lng)?.data.id
const connector = <RouteConnector seg={routeLegs[day.id]![res.id]} profile={routeProfile} />
return canEditDays && nextPlaceId != null ? (
<div role="button" tabIndex={0} title={t('dayplan.transportMode.change')} onClick={e => openIncomingLegModeMenu(e, Number(nextPlaceId), day.id)} style={{ cursor: 'pointer' }}>
<div role="button" tabIndex={0} title={t('dayplan.transportMode.change')} onClick={e => openIncomingLegModeMenu(e, Number(nextPlaceId), day.id, routeLegs[day.id]![res.id])} style={{ cursor: 'pointer' }}>
{connector}
</div>
) : connector
@@ -2407,7 +2476,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
const targetId = hotelLegs[day.id]?.bottom?.targetId
const connector = <HotelRouteConnector seg={hotelLegs[day.id]!.bottom!.seg} name={hotelLegs[day.id]!.bottom!.name} profile={routeProfile} placement="bottom" />
return canEditDays && targetId != null ? (
<div role="button" tabIndex={0} title={t('dayplan.transportMode.change')} onClick={e => openLegModeMenu(e, targetId, day.id)} style={{ cursor: 'pointer' }}>
<div role="button" tabIndex={0} title={t('dayplan.transportMode.change')} onClick={e => openLegModeMenu(e, targetId, day.id, hotelLegs[day.id]!.bottom!.seg)} style={{ cursor: 'pointer' }}>
{connector}
</div>
) : connector
@@ -1,15 +1,15 @@
// FE-PLANNER-DPTOOLBAR-001 to FE-PLANNER-DPTOOLBAR-022
// FE-PLANNER-DPTOOLBAR-001 to FE-PLANNER-DPTOOLBAR-023
import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render'
import userEvent from '@testing-library/user-event'
import { downloadTripPDF } from '../PDF/TripPDF'
import { buildDay, buildDayNote, buildReservation, buildTrip } from '../../../tests/helpers/factories'
import { buildDay, buildReservation, buildTrip } from '../../../tests/helpers/factories'
import { DayPlanSidebarToolbar } from './DayPlanSidebarToolbar'
import type { Reservation } from '../../types'
vi.mock('../PDF/TripPDF', () => ({ downloadTripPDF: vi.fn().mockResolvedValue(undefined) }))
// The subscribe dialog fetches its feed token on mount; it is exercised in its
// own test, here we only care that opening the menu entry mounts it.
// own test, and TripExportModal covers the entry that opens it.
vi.mock('./IcsSubscribeModal', () => ({
IcsSubscribeModal: ({ title, onClose }: { title: string; onClose: () => void }) => (
<div data-testid="ics-subscribe-modal">
@@ -46,8 +46,6 @@ function makeProps(overrides: Partial<React.ComponentProps<typeof DayPlanSidebar
t,
locale: 'en-US',
toast: makeToast(),
icsHover: false,
setIcsHover: vi.fn((_v: boolean) => {}),
expandedDays: new Set<number>(),
setExpandedDays: vi.fn((_v: Set<number>) => {}),
canUndo: false,
@@ -72,37 +70,42 @@ beforeEach(() => {
})
describe('DayPlanSidebarToolbar', () => {
// ── PDF export ────────────────────────────────────────────────────────────
// ── Export ─────────────────────────────────────────────────────
// PDF, ICS and GPX each used to be their own button with its own hover menu.
// The mechanics now live in TripExportModal and are tested there; what is left
// here is the single button that opens it.
it('FE-PLANNER-DPTOOLBAR-001: the PDF button exports the trip with the day notes flattened', async () => {
const user = userEvent.setup()
const days = [buildDay({ id: 10, title: 'Day 1' })]
const dayNotes = { '10': [buildDayNote({ id: 1, text: 'Bring cash' })] }
render(<DayPlanSidebarToolbar {...makeProps({ days, dayNotes })} />)
await user.click(screen.getByText('dayplan.pdf'))
await waitFor(() => expect(downloadTripPDF).toHaveBeenCalledTimes(1))
expect(vi.mocked(downloadTripPDF).mock.calls[0][0]).toMatchObject({
trip, days, dayNotes: [expect.objectContaining({ id: 1, text: 'Bring cash', day_id: 10 })],
})
it('FE-PLANNER-DPTOOLBAR-001: the toolbar carries one export button, not three', () => {
render(<DayPlanSidebarToolbar {...makeProps()} />)
expect(screen.getByRole('button', { name: 'dayplan.export' })).toBeInTheDocument()
expect(screen.queryByText('ICS')).not.toBeInTheDocument()
expect(screen.queryByText('GPX')).not.toBeInTheDocument()
expect(screen.queryByText('dayplan.pdf')).not.toBeInTheDocument()
})
it('FE-PLANNER-DPTOOLBAR-002: a failing PDF export surfaces the error via the toast', async () => {
const user = userEvent.setup()
vi.mocked(downloadTripPDF).mockRejectedValueOnce(new Error('font missing'))
const toast = makeToast()
render(<DayPlanSidebarToolbar {...makeProps({ toast })} />)
await user.click(screen.getByText('dayplan.pdf'))
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('dayplan.pdfError: font missing'))
})
it('FE-PLANNER-DPTOOLBAR-003: hovering the PDF button shows the export tooltip', async () => {
it('FE-PLANNER-DPTOOLBAR-002: the export button opens the dialog and closes again', async () => {
const user = userEvent.setup()
render(<DayPlanSidebarToolbar {...makeProps()} />)
expect(screen.queryByText('dayplan.pdfTooltip')).not.toBeInTheDocument()
await user.hover(screen.getByText('dayplan.pdf'))
await waitFor(() => expect(screen.getByText('dayplan.pdfTooltip')).toBeInTheDocument())
await user.unhover(screen.getByText('dayplan.pdf'))
await waitFor(() => expect(screen.queryByText('dayplan.pdfTooltip')).not.toBeInTheDocument())
const btn = screen.getByRole('button', { name: 'dayplan.export' })
expect(btn).toHaveAttribute('aria-expanded', 'false')
await user.click(btn)
expect(btn).toHaveAttribute('aria-expanded', 'true')
expect(screen.getByText('dayplan.exportDocument')).toBeInTheDocument()
expect(screen.getByText('dayplan.exportCalendar')).toBeInTheDocument()
await user.click(screen.getByText('dayplan.pdf'))
await waitFor(() => expect(downloadTripPDF).toHaveBeenCalledTimes(1))
await waitFor(() => expect(screen.queryByText('dayplan.exportDocument')).not.toBeInTheDocument())
})
it('FE-PLANNER-DPTOOLBAR-003: hovering the export button shows its tooltip', async () => {
const user = userEvent.setup()
render(<DayPlanSidebarToolbar {...makeProps()} />)
expect(screen.queryByText('dayplan.exportIntro')).not.toBeInTheDocument()
const btn = screen.getByRole('button', { name: 'dayplan.export' })
await user.hover(btn)
await waitFor(() => expect(screen.getByText('dayplan.exportIntro')).toBeInTheDocument())
await user.unhover(btn)
await waitFor(() => expect(screen.queryByText('dayplan.exportIntro')).not.toBeInTheDocument())
})
// The button sits at the right edge of the leftmost pane. Its own tooltip was
@@ -111,8 +114,8 @@ describe('DayPlanSidebarToolbar', () => {
it('FE-PLANNER-DPTOOLBAR-004: the export tooltip stays inside the window', async () => {
const user = userEvent.setup()
render(<DayPlanSidebarToolbar {...makeProps()} />)
await user.hover(screen.getByText('dayplan.pdf'))
const tip = await screen.findByText('dayplan.pdfTooltip')
await user.hover(screen.getByRole('button', { name: 'dayplan.export' }))
const tip = await screen.findByText('dayplan.exportIntro')
expect(tip.closest('[role="tooltip"]')).not.toBeNull()
expect(tip.parentElement).toBe(document.body)
expect(tip.style.position).toBe('fixed')
@@ -120,94 +123,12 @@ describe('DayPlanSidebarToolbar', () => {
await waitFor(() => expect(parseFloat(tip.style.left)).toBeGreaterThanOrEqual(0))
})
// ── ICS menu ──────────────────────────────────────────────────────────────
it('FE-PLANNER-DPTOOLBAR-005: hovering ICS opens the download/subscribe menu', async () => {
const user = userEvent.setup()
const setIcsHover = vi.fn((_v: boolean) => {})
render(<DayPlanSidebarToolbar {...makeProps({ setIcsHover })} />)
expect(screen.queryByText('Download ICS')).not.toBeInTheDocument()
await user.hover(screen.getByText('ICS'))
expect(screen.getByText('Download ICS')).toBeInTheDocument()
expect(screen.getByText('Subscribe to calendar')).toBeInTheDocument()
expect(setIcsHover).toHaveBeenCalledWith(true)
})
it('FE-PLANNER-DPTOOLBAR-005b: without share_manage the menu offers the download but not the subscription', async () => {
// The subscription mints a link that reads the trip without an account, so
// it needs share_manage; the one-off download is a file this member may
// already read. Leaving the entry visible would only produce a dialog whose
// enable button the server refuses.
it('FE-PLANNER-DPTOOLBAR-005: the dialog inherits the share permission from the toolbar', async () => {
const user = userEvent.setup()
render(<DayPlanSidebarToolbar {...makeProps({ canManageShare: false })} />)
await user.hover(screen.getByText('ICS'))
expect(screen.getByText('Download ICS')).toBeInTheDocument()
expect(screen.queryByText('Subscribe to calendar')).not.toBeInTheDocument()
})
it('FE-PLANNER-DPTOOLBAR-006: leaving the ICS area closes the menu after the grace period', async () => {
const user = userEvent.setup()
const setIcsHover = vi.fn((_v: boolean) => {})
render(<DayPlanSidebarToolbar {...makeProps({ setIcsHover })} />)
const icsButton = screen.getByText('ICS')
await user.hover(icsButton)
expect(screen.getByText('Download ICS')).toBeInTheDocument()
await user.unhover(icsButton)
await waitFor(() => expect(screen.queryByText('Download ICS')).not.toBeInTheDocument())
expect(setIcsHover).toHaveBeenLastCalledWith(false)
})
it('FE-PLANNER-DPTOOLBAR-007: re-entering the ICS area cancels the pending close', async () => {
const user = userEvent.setup()
render(<DayPlanSidebarToolbar {...makeProps()} />)
const icsButton = screen.getByText('ICS')
await user.hover(icsButton)
await user.unhover(icsButton)
await user.hover(icsButton)
// The close is scheduled 120ms out; coming back in has to cancel it.
await new Promise(r => setTimeout(r, 200))
expect(screen.getByText('Download ICS')).toBeInTheDocument()
})
it('FE-PLANNER-DPTOOLBAR-008: "Download ICS" fetches the export and hands it to a download link', async () => {
const user = userEvent.setup()
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
blob: () => Promise.resolve(new Blob(['BEGIN:VCALENDAR'], { type: 'text/calendar' })),
} as unknown as Response)
const createObjURL = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:mock')
const revokeObjURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
render(<DayPlanSidebarToolbar {...makeProps()} />)
await user.hover(screen.getByText('ICS'))
await user.click(screen.getByText('Download ICS'))
await waitFor(() => expect(fetchSpy).toHaveBeenCalledWith('/api/trips/1/export.ics', { credentials: 'include' }))
await waitFor(() => expect(clickSpy).toHaveBeenCalled())
expect(revokeObjURL).toHaveBeenCalledWith('blob:mock')
// The menu closes itself once the download starts.
expect(screen.queryByText('Download ICS')).not.toBeInTheDocument()
fetchSpy.mockRestore(); createObjURL.mockRestore(); revokeObjURL.mockRestore(); clickSpy.mockRestore()
})
it('FE-PLANNER-DPTOOLBAR-009: a rejected ICS export shows the failure toast', async () => {
const user = userEvent.setup()
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({ ok: false } as unknown as Response)
const toast = makeToast()
render(<DayPlanSidebarToolbar {...makeProps({ toast })} />)
await user.hover(screen.getByText('ICS'))
await user.click(screen.getByText('Download ICS'))
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('planner.icsExportFailed'))
fetchSpy.mockRestore()
})
it('FE-PLANNER-DPTOOLBAR-010: "Subscribe to calendar" opens the subscribe dialog and closes again', async () => {
const user = userEvent.setup()
render(<DayPlanSidebarToolbar {...makeProps()} />)
await user.hover(screen.getByText('ICS'))
await user.click(screen.getByText('Subscribe to calendar'))
expect(screen.getByTestId('ics-subscribe-modal')).toBeInTheDocument()
await user.click(screen.getByText('close-subscribe'))
expect(screen.queryByTestId('ics-subscribe-modal')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'dayplan.export' }))
expect(screen.getByText('mobileTrip.icsDownload')).toBeInTheDocument()
expect(screen.queryByText('mobileTrip.icsSubscribe')).not.toBeInTheDocument()
})
// ── Expand / collapse all ────────────────────────────────────────────────
@@ -350,105 +271,6 @@ describe('DayPlanSidebarToolbar', () => {
expect(routeBtn.style.background).toBe('var(--bg-hover)')
await user.unhover(routeBtn)
expect(routeBtn.style.background).toBe('transparent')
await user.hover(screen.getByText('ICS'))
const download = screen.getByText('Download ICS')
const subscribe = screen.getByText('Subscribe to calendar')
await user.hover(download)
expect(download.style.background).toContain('var(--bg-hover')
// Sliding down to the next entry has to clear the one we left.
await user.hover(subscribe)
expect(download.style.background).toBe('transparent')
expect(subscribe.style.background).toContain('var(--bg-hover')
await user.unhover(subscribe)
expect(subscribe.style.background).toBe('transparent')
})
it('FE-PLANNER-DPTOOLBAR-024: an aborted PDF export without an Error still reaches the toast', async () => {
const user = userEvent.setup()
vi.mocked(downloadTripPDF).mockRejectedValueOnce('boom')
const toast = makeToast()
render(<DayPlanSidebarToolbar {...makeProps({ toast })} />)
await user.click(screen.getByText('dayplan.pdf'))
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('dayplan.pdfError: boom'))
})
// ── GPX export (#1442) ────────────────────────────────────────────────────
describe('GPX menu', () => {
let clickedHref: string | null
beforeEach(() => {
clickedHref = null
// jsdom has neither of these, and an anchor click would navigate.
globalThis.URL.createObjectURL = vi.fn(() => 'blob:gpx')
globalThis.URL.revokeObjectURL = vi.fn()
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {
clickedHref = this.href
})
})
afterEach(() => vi.restoreAllMocks())
const okResponse = () => ({ ok: true, status: 200, blob: async () => new Blob(['<gpx/>']) }) as unknown as Response
it('FE-PLANNER-DPTOOLBAR-025: the menu offers the three scopes on hover', async () => {
const user = userEvent.setup()
render(<DayPlanSidebarToolbar {...makeProps()} />)
expect(screen.queryByText('dayplan.gpxAll')).not.toBeInTheDocument()
await user.hover(screen.getByText('GPX'))
expect(screen.getByText('dayplan.gpxAll')).toBeInTheDocument()
expect(screen.getByText('dayplan.gpxPlaces')).toBeInTheDocument()
expect(screen.getByText('dayplan.gpxDays')).toBeInTheDocument()
})
it('FE-PLANNER-DPTOOLBAR-026: each scope asks the server for exactly its own selection', async () => {
const user = userEvent.setup()
const fetchMock = vi.fn(async () => okResponse())
vi.stubGlobal('fetch', fetchMock)
render(<DayPlanSidebarToolbar {...makeProps()} />)
for (const [label, expected] of [
['dayplan.gpxAll', '/api/trips/1/places/export.gpx'],
['dayplan.gpxPlaces', '/api/trips/1/places/export.gpx?dayRoutes=false'],
['dayplan.gpxDays', '/api/trips/1/places/export.gpx?waypoints=false&tracks=false'],
] as const) {
await user.hover(screen.getByText('GPX'))
await user.click(screen.getByText(label))
await waitFor(() => expect(fetchMock).toHaveBeenCalledWith(expected, { credentials: 'include' }))
fetchMock.mockClear()
}
})
it('FE-PLANNER-DPTOOLBAR-027: a download names the file after the trip', async () => {
const user = userEvent.setup()
vi.stubGlobal('fetch', vi.fn(async () => okResponse()))
render(<DayPlanSidebarToolbar {...makeProps()} />)
await user.hover(screen.getByText('GPX'))
await user.click(screen.getByText('dayplan.gpxAll'))
await waitFor(() => expect(clickedHref).toBe('blob:gpx'))
expect(globalThis.URL.revokeObjectURL).toHaveBeenCalled()
})
it('FE-PLANNER-DPTOOLBAR-028: an empty trip says so instead of reporting a failure', async () => {
const user = userEvent.setup()
const toast = makeToast()
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 404 }) as unknown as Response))
render(<DayPlanSidebarToolbar {...makeProps({ toast })} />)
await user.hover(screen.getByText('GPX'))
await user.click(screen.getByText('dayplan.gpxAll'))
await waitFor(() => expect(toast.info).toHaveBeenCalledWith('dayplan.gpxEmpty'))
expect(toast.error).not.toHaveBeenCalled()
expect(clickedHref).toBeNull()
})
it('FE-PLANNER-DPTOOLBAR-029: a real failure toasts the error', async () => {
const user = userEvent.setup()
const toast = makeToast()
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 500 }) as unknown as Response))
render(<DayPlanSidebarToolbar {...makeProps({ toast })} />)
await user.hover(screen.getByText('GPX'))
await user.click(screen.getByText('dayplan.gpxAll'))
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('dayplan.gpxFailed'))
})
})
})
@@ -1,24 +1,12 @@
import React, { useState, useRef } from 'react'
import { ChevronsDownUp, ChevronsUpDown, FileDown, Undo2, ArrowUpDown, CalendarPlus, MapPin, Route as RouteIcon } from 'lucide-react'
import { useState } from 'react'
import { ChevronsDownUp, ChevronsUpDown, Download, Undo2, ArrowUpDown, Route as RouteIcon } from 'lucide-react'
import { DayReorderPopup } from './DayReorderPopup'
import Tooltip from '../shared/Tooltip'
import { useToast } from '../shared/Toast'
import { IcsSubscribeModal } from './IcsSubscribeModal'
import { TripExportModal } from './TripExportModal'
import { isRoutableReservation } from '../../utils/reservationRoutes'
import type { Trip, Day, Place, Category, AssignmentsMap, Reservation, DayNote } from '../../types'
/**
* What a GPX download can carry. Worded by what someone wants on their device
* rather than by the GPX element it maps to: "everything", "just the places" for
* an offline map, "just the days" for following a plan. An omitted flag defaults
* to true server-side, so the first entry needs no query at all.
*/
const GPX_SCOPES = [
{ key: 'all', query: '', labelKey: 'dayplan.gpxAll', icon: FileDown },
{ key: 'places', query: '?dayRoutes=false', labelKey: 'dayplan.gpxPlaces', icon: MapPin },
{ key: 'days', query: '?waypoints=false&tracks=false', labelKey: 'dayplan.gpxDays', icon: RouteIcon },
] as const
interface DayPlanSidebarToolbarProps {
tripId: number
trip: Trip
@@ -33,8 +21,6 @@ interface DayPlanSidebarToolbarProps {
t: (key: string, params?: Record<string, any>) => string
locale: string
toast: ReturnType<typeof useToast>
icsHover: boolean
setIcsHover: (v: boolean) => void
expandedDays: Set<number>
setExpandedDays: (next: Set<number>) => void
onUndo?: () => void
@@ -44,11 +30,9 @@ interface DayPlanSidebarToolbarProps {
lastActionLabel: string | null
canEditDays?: boolean
/**
* Gates "Subscribe to calendar" only. The one-off "Download ICS" below it
* stays open to every member: it is a file they already have the right to
* read, while the subscription mints a link that works without an account.
* Defaults to true so a caller that has not wired the permission through
* keeps today's menu rather than silently losing an entry.
* Gates "Subscribe to calendar" in the export dialog only. Defaults to true so
* a caller that has not wired the permission through keeps today's entries
* rather than silently losing one.
*/
canManageShare?: boolean
onReorderDays?: (orderedIds: number[]) => void
@@ -58,230 +42,53 @@ interface DayPlanSidebarToolbarProps {
export function DayPlanSidebarToolbar({
tripId, trip, days, places, categories, assignments, reservations, dayNotes,
allConnectionsShown = false, onToggleAllConnections,
t, locale, toast, setIcsHover,
t, locale, toast,
expandedDays, setExpandedDays, onUndo, canUndo, undoHover, setUndoHover, lastActionLabel,
canEditDays, canManageShare = true, onReorderDays, onAddDay,
}: DayPlanSidebarToolbarProps) {
const [reorderOpen, setReorderOpen] = useState(false)
const [subscribeOpen, setSubscribeOpen] = useState(false)
const icsMenuTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const [icsMenuVisible, setIcsMenuVisible] = useState(false)
const gpxMenuTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const [gpxMenuVisible, setGpxMenuVisible] = useState(false)
const [exportOpen, setExportOpen] = useState(false)
const showIcsMenu = () => {
if (icsMenuTimeoutRef.current) clearTimeout(icsMenuTimeoutRef.current)
setIcsMenuVisible(true)
setIcsHover(true)
}
const hideIcsMenu = () => {
icsMenuTimeoutRef.current = setTimeout(() => {
setIcsMenuVisible(false)
setIcsHover(false)
}, 120)
}
const showGpxMenu = () => {
if (gpxMenuTimeoutRef.current) clearTimeout(gpxMenuTimeoutRef.current)
setGpxMenuVisible(true)
}
const hideGpxMenu = () => {
gpxMenuTimeoutRef.current = setTimeout(() => setGpxMenuVisible(false), 120)
}
const downloadGpx = async (query: string) => {
setGpxMenuVisible(false)
try {
const res = await fetch(`/api/trips/${tripId}/places/export.gpx${query}`, { credentials: 'include' })
// 404 here means the selection is empty, which is worth its own message:
// "nothing happened" and "the download broke" look identical otherwise.
if (res.status === 404) { toast.info(t('dayplan.gpxEmpty')); return }
if (!res.ok) throw new Error()
const blob = await res.blob()
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `${trip?.title || 'trip'}.gpx`
a.click()
URL.revokeObjectURL(url)
} catch { toast.error(t('dayplan.gpxFailed')) }
}
const menuItemStyle: React.CSSProperties = {
display: 'flex', alignItems: 'center', gap: 7,
width: '100%', padding: '7px 12px', border: 'none',
background: 'transparent', cursor: 'pointer',
fontSize: 11, fontWeight: 500, fontFamily: 'inherit',
color: 'var(--text-primary)', textAlign: 'left',
transition: 'background 0.1s',
}
return (
<div className="border-b border-edge-faint" style={{ padding: '12px 16px', flexShrink: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 8 }}>
<div style={{ position: 'relative', flexShrink: 0 }}>
<Tooltip label={t('dayplan.pdfTooltip')} placement="bottom">
{/* One export button instead of three: PDF, ICS and GPX each carried
their own hover menu, and on a narrower sidebar the row ran out of
width and pushed them off the edge. The dialog holds every option. */}
<Tooltip label={t('dayplan.exportIntro')} placement="bottom">
<button
onClick={async () => {
const flatNotes = Object.entries(dayNotes).flatMap(([dayId, notes]) =>
notes.map(n => ({ ...n, day_id: Number(dayId) }))
)
try {
// Loaded on click: the PDF builder is ~226 kB and hangs off the
// days sidebar, so every trip used to pay for it whether or not
// anyone exported. A missing chunk lands in the catch below and
// shows the same error the export already had.
const { downloadTripPDF } = await import('../PDF/TripPDF')
await downloadTripPDF({ trip, days, places, assignments, categories, dayNotes: flatNotes, reservations, t, locale })
} catch (e) {
console.error('PDF error:', e)
toast.error(t('dayplan.pdfError') + ': ' + (e?.message || String(e)))
}
}}
type="button"
onClick={() => setExportOpen(true)}
aria-haspopup="dialog"
aria-expanded={exportOpen}
className="bg-accent text-accent-text"
style={{
display: 'flex', alignItems: 'center', gap: 5,
display: 'flex', alignItems: 'center', gap: 5, flexShrink: 0,
padding: '5px 10px', borderRadius: 8, border: 'none',
fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500,
cursor: 'pointer', fontFamily: 'inherit',
}}
>
<FileDown size={13} strokeWidth={2} />
{t('dayplan.pdf')}
<Download size={13} strokeWidth={2} />
{t('dayplan.export')}
</button>
</Tooltip>
</div>
<div
style={{ position: 'relative', flexShrink: 0 }}
onMouseEnter={showIcsMenu}
onMouseLeave={hideIcsMenu}
>
<button
style={{
display: 'flex', alignItems: 'center', gap: 5,
padding: '5px 10px', borderRadius: 8,
border: '1px solid var(--border-primary)', background: 'none',
color: 'var(--text-muted)', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500,
cursor: 'pointer', fontFamily: 'inherit',
}}
>
<FileDown size={13} strokeWidth={2} />
ICS
</button>
{icsMenuVisible && (
<div
onMouseEnter={showIcsMenu}
onMouseLeave={hideIcsMenu}
style={{
position: 'absolute', top: 'calc(100% + 4px)', left: '50%', transform: 'translateX(-50%)',
zIndex: 200, minWidth: 160,
background: 'var(--bg-card, white)',
borderRadius: 8, boxShadow: '0 4px 16px rgba(0,0,0,0.15)',
border: '1px solid var(--border-faint, #e5e7eb)',
overflow: 'hidden',
}}
>
<button
onClick={async () => {
setIcsMenuVisible(false)
setIcsHover(false)
try {
const res = await fetch(`/api/trips/${tripId}/export.ics`, { credentials: 'include' })
if (!res.ok) throw new Error()
const blob = await res.blob()
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `${trip?.title || 'trip'}.ics`
a.click()
URL.revokeObjectURL(url)
} catch { toast.error(t('planner.icsExportFailed')) }
}}
style={menuItemStyle}
onMouseEnter={e => { (e.currentTarget as HTMLButtonElement).style.background = 'var(--bg-hover, #f3f4f6)' }}
onMouseLeave={e => { (e.currentTarget as HTMLButtonElement).style.background = 'transparent' }}
>
<FileDown size={12} strokeWidth={2} />
Download ICS
</button>
{canManageShare && (
<button
onClick={() => {
setIcsMenuVisible(false)
setIcsHover(false)
setSubscribeOpen(true)
}}
style={menuItemStyle}
onMouseEnter={e => { (e.currentTarget as HTMLButtonElement).style.background = 'var(--bg-hover, #f3f4f6)' }}
onMouseLeave={e => { (e.currentTarget as HTMLButtonElement).style.background = 'transparent' }}
>
<CalendarPlus size={12} strokeWidth={2} />
Subscribe to calendar
</button>
)}
</div>
)}
</div>
{/* GPX — the counterpart to the GPX import in the places sidebar, sitting
with the other exports rather than with the importer. Same hover-menu
shape as ICS beside it. */}
<div
style={{ position: 'relative', flexShrink: 0 }}
onMouseEnter={showGpxMenu}
onMouseLeave={hideGpxMenu}
>
<button
aria-haspopup="menu"
aria-expanded={gpxMenuVisible}
aria-label={t('dayplan.gpxTooltip')}
style={{
display: 'flex', alignItems: 'center', gap: 5,
padding: '5px 10px', borderRadius: 8,
border: '1px solid var(--border-primary)', background: 'none',
color: 'var(--text-muted)', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500,
cursor: 'pointer', fontFamily: 'inherit',
}}
>
<FileDown size={13} strokeWidth={2} />
GPX
</button>
{gpxMenuVisible && (
<div
role="menu"
onMouseEnter={showGpxMenu}
onMouseLeave={hideGpxMenu}
style={{
position: 'absolute', top: 'calc(100% + 4px)', left: '50%', transform: 'translateX(-50%)',
zIndex: 200, minWidth: 190,
background: 'var(--bg-card, white)',
borderRadius: 8, boxShadow: '0 4px 16px rgba(0,0,0,0.15)',
border: '1px solid var(--border-faint, #e5e7eb)',
overflow: 'hidden',
}}
>
{GPX_SCOPES.map(scope => (
<button
key={scope.key}
role="menuitem"
onClick={() => downloadGpx(scope.query)}
style={menuItemStyle}
onMouseEnter={e => { (e.currentTarget as HTMLButtonElement).style.background = 'var(--bg-hover, #f3f4f6)' }}
onMouseLeave={e => { (e.currentTarget as HTMLButtonElement).style.background = 'transparent' }}
>
<scope.icon size={12} strokeWidth={2} />
{t(scope.labelKey)}
</button>
))}
</div>
)}
</div>
{subscribeOpen && canManageShare && (
<IcsSubscribeModal
endpoint={`/api/trips/${tripId}/feed`}
title="Subscribe to calendar"
description="This link stays in sync with your trip automatically. Calendar apps re-fetch it every hour."
onClose={() => setSubscribeOpen(false)}
/>
)}
</Tooltip>
<TripExportModal
isOpen={exportOpen}
onClose={() => setExportOpen(false)}
tripId={tripId}
trip={trip}
days={days}
places={places}
categories={categories}
assignments={assignments}
reservations={reservations}
dayNotes={dayNotes}
t={t}
locale={locale}
toast={toast}
canManageShare={canManageShare}
/>
{(() => {
const allExpanded = days.length > 0 && days.every(d => expandedDays.has(d.id))
const label = allExpanded ? t('dayplan.collapseAll') : t('dayplan.expandAll')
@@ -90,7 +90,7 @@ export function DayPlanSidebarTransportDetailModal({
<div className={res.status === 'confirmed' ? 'bg-[rgba(22,163,74,0.1)] text-[#16a34a]' : 'bg-[rgba(217,119,6,0.1)] text-[#d97706]'} style={{
padding: '3px 8px', borderRadius: 6, fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600,
}}>
{(res.status === 'confirmed' ? t('planner.resConfirmed') : t('planner.resPending')).replace(/\s*·\s*$/, '')}
{res.status === 'confirmed' ? t('planner.resConfirmed') : t('planner.resPending')}
</div>
</div>
@@ -1,4 +1,4 @@
// FE-COMP-PLACEFORM-001 to FE-COMP-PLACEFORM-036, FE-PLANNER-PLACEFORM-016 to FE-PLANNER-PLACEFORM-062
// FE-COMP-PLACEFORM-001 to FE-COMP-PLACEFORM-036, FE-PLANNER-PLACEFORM-016 to FE-PLANNER-PLACEFORM-067, plus FE-PLANNER-PLACEFORM-068 to -072
import { render, screen, waitFor, fireEvent, within } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
@@ -1467,4 +1467,94 @@ describe('PlaceFormModal remaining branches', () => {
expect(websiteInput().value).toBe('https://stored.example');
});
});
// ── Linked expense (#1298) — the same block bookings have ──────────────────
describe('Costs section', () => {
const withBudget = () => seedStore(useAddonStore, {
addons: [{ id: 'budget', name: 'Budget', type: 'budget', icon: '', enabled: true }],
loaded: true,
});
it('FE-PLANNER-PLACEFORM-068: the block only appears while the Budget addon is on', () => {
const { unmount } = render(<PlaceFormModal {...defaultProps} />);
expect(screen.queryByRole('button', { name: /Create expense/i })).not.toBeInTheDocument();
unmount();
withBudget();
render(<PlaceFormModal {...defaultProps} />);
expect(screen.getByRole('button', { name: /Create expense/i })).toBeInTheDocument();
});
it('FE-PLANNER-PLACEFORM-069: creating an expense saves the place first, then opens the editor', async () => {
withBudget();
const onSave = vi.fn().mockResolvedValue({ id: 42 });
const onOpenExpense = vi.fn();
render(<PlaceFormModal {...defaultProps} onSave={onSave} onOpenExpense={onOpenExpense} />);
fireEvent.change(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), { target: { value: 'Louvre' } });
fireEvent.click(screen.getByRole('button', { name: /Create expense/i }));
await waitFor(() => expect(onOpenExpense).toHaveBeenCalled());
expect(onSave).toHaveBeenCalled();
expect(onSave.mock.invocationCallOrder[0]).toBeLessThan(onOpenExpense.mock.invocationCallOrder[0]);
expect(onOpenExpense).toHaveBeenCalledWith({
prefill: { placeId: 42, name: 'Louvre', category: 'activities' },
});
});
it('FE-PLANNER-PLACEFORM-070: a save that yields no id opens no editor', async () => {
withBudget();
const onSave = vi.fn().mockResolvedValue(undefined);
const onOpenExpense = vi.fn();
render(<PlaceFormModal {...defaultProps} onSave={onSave} onOpenExpense={onOpenExpense} />);
fireEvent.change(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), { target: { value: 'Louvre' } });
fireEvent.click(screen.getByRole('button', { name: /Create expense/i }));
await waitFor(() => expect(onSave).toHaveBeenCalled());
expect(onOpenExpense).not.toHaveBeenCalled();
});
it('FE-PLANNER-PLACEFORM-070b: a nameless click drops the intent instead of arming the next save', async () => {
withBudget();
const onSave = vi.fn().mockResolvedValue({ id: 42 });
const onOpenExpense = vi.fn();
render(<PlaceFormModal {...defaultProps} onSave={onSave} onOpenExpense={onOpenExpense} />);
// No name yet — the save is refused and the intent must not survive it.
fireEvent.click(screen.getByRole('button', { name: /Create expense/i }));
await waitFor(() => expect(onSave).not.toHaveBeenCalled());
fireEvent.change(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), { target: { value: 'Louvre' } });
fireEvent.click(screen.getByRole('button', { name: /^Add$/i }));
await waitFor(() => expect(onSave).toHaveBeenCalled());
expect(onOpenExpense).not.toHaveBeenCalled();
});
it('FE-PLANNER-PLACEFORM-071: an already-linked expense is shown with its amount instead of the button', () => {
withBudget();
seedStore(useTripStore, {
trip: buildTrip({ id: 1 }),
budgetItems: [{ id: 8, trip_id: 1, name: 'Louvre tickets', total_price: 34, category: 'activities', place_id: 7 }],
});
render(<PlaceFormModal {...defaultProps} place={{ id: 7, name: 'Louvre' } as never} />);
expect(screen.getByText('Louvre tickets')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /Create expense/i })).not.toBeInTheDocument();
});
it('FE-PLANNER-PLACEFORM-072: an expense linked to another place is not claimed', () => {
withBudget();
seedStore(useTripStore, {
trip: buildTrip({ id: 1 }),
budgetItems: [{ id: 8, trip_id: 1, name: 'Orsay tickets', total_price: 16, category: 'activities', place_id: 99 }],
});
render(<PlaceFormModal {...defaultProps} place={{ id: 7, name: 'Louvre' } as never} />);
expect(screen.queryByText('Orsay tickets')).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: /Create expense/i })).toBeInTheDocument();
});
});
});
@@ -16,7 +16,9 @@ import { useTranslation } from '../../i18n'
import CustomTimePicker from '../shared/CustomTimePicker'
import { DEFAULT_FORM, isGoogleMapsUrl, mergeResult, type PlaceFormData, type ResultField } from './PlaceFormModal.helpers'
import { getApiErrorMessage } from '../../utils/apiError'
import type { Place, Category, Assignment } from '../../types'
import { BookingCostsSection } from './BookingCostsSection'
import type { BookingExpenseRequest } from './BookingCostsSection.types'
import type { Place, Category, Assignment, BudgetItem } from '../../types'
import { NumericInput } from '../shared/NumericInput'
// The submit payload mirrors the form, but lat/lng are parsed to numbers and
@@ -31,7 +33,7 @@ export interface PlaceSubmitData extends Omit<PlaceFormData, 'lat' | 'lng' | 'ca
interface PlaceFormModalProps {
isOpen: boolean
onClose: () => void
onSave: (data: PlaceSubmitData, files?: File[]) => Promise<void> | void
onSave: (data: PlaceSubmitData, files?: File[]) => Promise<{ id: number } | void> | void
place: Place | null
prefillCoords?: { lat: number; lng: number; name?: string; address?: string; website?: string; phone?: string; osm_id?: string } | null
tripId: number
@@ -43,6 +45,9 @@ interface PlaceFormModalProps {
* picker column when the Collections addon is enabled. Sourced from the trip
* planner's matchMedia('(max-width:767px)'). */
isMobile?: boolean
/** Opens the Costs editor for this place's linked expense (#1298) — the same
* seam the booking and transport modals use. */
onOpenExpense?: (req: BookingExpenseRequest) => void
}
@@ -78,6 +83,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
const {
isOpen, onClose, onSave, place, prefillCoords, tripId, categories,
onCategoryCreated, assignmentId, dayAssignments = [], isMobile = false,
onOpenExpense,
} = props
const [form, setForm] = useState(DEFAULT_FORM)
const [mapsSearch, setMapsSearch] = useState('')
@@ -108,6 +114,11 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
const tripObj = useTripStore((s) => s.trip)
const canUploadFiles = can('file_upload', tripObj)
const collectionsEnabled = useAddonStore((s) => s.isEnabled('collections'))
const isBudgetEnabled = useAddonStore((s) => s.isEnabled('budget'))
const deleteBudgetItem = useTripStore((s) => s.deleteBudgetItem)
// Set right before submit when the user clicked create/edit expense — the
// place has to exist before an expense can point at it (see ReservationModal).
const expenseIntentRef = useRef<{ editItem?: BudgetItem; create?: boolean } | null>(null)
useEffect(() => {
if (place) {
@@ -430,9 +441,12 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
const hasTimeError = place && form.place_time && form.end_time && form.place_time.length >= 5 && form.end_time.length >= 5 && form.end_time <= form.place_time
const handleSubmit = async (e) => {
e.preventDefault()
const handleSubmit = async (e?: { preventDefault?: () => void }) => {
e?.preventDefault?.()
if (!form.name.trim()) {
// Nothing was saved, so an expense intent from a previous click is stale —
// otherwise the next plain Save would open a Costs editor out of nowhere.
expenseIntentRef.current = null
toast.error(t('places.nameRequired'))
return
}
@@ -449,13 +463,23 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
}
setIsSaving(true)
try {
await onSave({
const saved = await onSave({
...form,
lat: form.lat ? parseFloat(form.lat) : null,
lng: form.lng ? parseFloat(form.lng) : null,
category_id: form.category_id || null,
_pendingFiles: pendingFiles.length > 0 ? pendingFiles : undefined,
})
// Open the Costs editor for the saved place when the user asked to
// create/edit its linked expense — gated on an id, so a create that the
// server refused never opens an editor pointing at nothing (#1298).
const intent = expenseIntentRef.current
expenseIntentRef.current = null
const savedId = (saved && 'id' in saved ? saved.id : null) ?? place?.id ?? null
if (intent && onOpenExpense && savedId) {
if (intent.editItem) onOpenExpense({ editItem: intent.editItem })
else onOpenExpense({ prefill: { placeId: savedId, name: form.name.trim(), category: 'activities' } })
}
onClose()
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : t('places.saveError'))
@@ -464,6 +488,12 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
}
}
const handleCreateExpense = () => { expenseIntentRef.current = { create: true }; void handleSubmit() }
const handleEditExpense = (item: BudgetItem) => { expenseIntentRef.current = { editItem: item }; void handleSubmit() }
const handleRemoveExpense = async (item: BudgetItem) => {
try { await deleteBudgetItem(Number(tripId), item.id) } catch { toast.error(t('common.unknownError')) }
}
return {
isOpen,
onClose,
@@ -527,6 +557,10 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
handleSubmit,
duplicateWarning,
detailsSelection,
isBudgetEnabled,
handleCreateExpense,
handleEditExpense,
handleRemoveExpense,
}
}
@@ -593,6 +627,10 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
handleSubmit,
duplicateWarning,
detailsSelection,
isBudgetEnabled,
handleCreateExpense,
handleEditExpense,
handleRemoveExpense,
} = S
// Desktop + Collections addon → the saved-place picker on the right. Mobile
// always keeps the original single-column form untouched.
@@ -917,6 +955,19 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
</div>
)}
{/* Costs — create / view the expense linked to this place (#1298).
Same block, same flow as a booking: save first, then the editor. */}
{isBudgetEnabled && (
<BookingCostsSection
placeId={place?.id ?? null}
reservationId={null}
hintKey="places.createExpenseHint"
onCreate={handleCreateExpense}
onEdit={handleEditExpense}
onRemove={handleRemoveExpense}
/>
)}
</form>
{twoColumn && (
<CollectionPicker bias={locationBias} onSelect={handleSelectMapsResult} t={t} />
@@ -1,9 +1,9 @@
import { Check, Tag, Trash2, Bookmark } from 'lucide-react'
import { Check, CheckCircle2, Loader2, Tag, Trash2, Bookmark } from 'lucide-react'
import Tooltip from '../shared/Tooltip'
import type { SidebarState } from './usePlacesSidebar'
export function PlacesSelectionBar(S: SidebarState) {
const { t, selectedIds, filtered, setSelectedIds, isMobile, setPendingDeleteIds, onBulkDeletePlaces, setCategoryPickerOpen, collectionsEnabled, setSaveToListOpen } = S
const { t, selectedIds, filtered, setSelectedIds, isMobile, setPendingDeleteIds, onBulkDeletePlaces, setCategoryPickerOpen, collectionsEnabled, setSaveToListOpen, markSelectionVisited, markVisitedBusy } = S
return (
<div style={{
margin: '6px 16px', padding: '5px 8px 5px 10px', borderRadius: 8,
@@ -68,6 +68,25 @@ export function PlacesSelectionBar(S: SidebarState) {
</button>
</Tooltip>
)}
{collectionsEnabled && (
<Tooltip label={t('collections.markVisitedSelection')} placement="bottom">
<button
onClick={() => { if (selectedIds.size === 0) return; void markSelectionVisited() }}
disabled={selectedIds.size === 0 || markVisitedBusy}
aria-label={t('collections.markVisitedSelection')}
className={selectedIds.size > 0 ? 'bg-transparent text-content-muted' : 'bg-transparent text-content-faint'}
style={{
display: 'flex', alignItems: 'center', justifyContent: 'center',
width: 24, height: 24, borderRadius: 6, border: 'none',
cursor: selectedIds.size > 0 ? 'pointer' : 'default', padding: 0,
}}
onMouseEnter={e => { if (selectedIds.size > 0) e.currentTarget.style.background = 'var(--bg-hover)' }}
onMouseLeave={e => { e.currentTarget.style.background = 'transparent' }}
>
{markVisitedBusy ? <Loader2 size={13} className="animate-spin" /> : <CheckCircle2 size={13} strokeWidth={2} />}
</button>
</Tooltip>
)}
<Tooltip label={t('places.deleteSelected')} placement="bottom">
<button
onClick={() => {
@@ -177,6 +177,20 @@ describe('TransitSearchPanel', () => {
expect(transitApiMock.plan.mock.calls[0][0]).toMatchObject({ arriveBy: true, time: '2025-06-01T08:00:00.000Z' })
})
it('FE-PLANNER-TRANSIT-008b: initialTime seeds the departure time', async () => {
const user = userEvent.setup()
transitApiMock.plan.mockResolvedValueOnce({ itineraries: [] })
render(<TransitSearchPanel {...makeProps({
initialFrom: { name: 'Fernsehturm', lat: 52.5208, lng: 13.4094 },
initialTo: { name: 'London Victoria', lat: 51.5074, lng: -0.1278 },
initialTime: '11:00',
})} />)
await user.click(screen.getByRole('button', { name: /^Search$/ }))
await waitFor(() => expect(transitApiMock.plan).toHaveBeenCalled())
// 11:00 in Berlin (UTC+2) anchors depart-by to the origin zone → 09:00Z.
expect(transitApiMock.plan.mock.calls[0][0]).toMatchObject({ time: '2025-06-01T09:00:00.000Z' })
})
it('FE-PLANNER-TRANSIT-009: arrive-by lists the latest-arriving itinerary first', async () => {
const user = userEvent.setup()
// MOTIS returns arrive-by results ascending, deadline-adjacent last (#1479).
@@ -318,9 +318,11 @@ interface TransitSearchPanelProps {
/** Pre-seed from/to — used by "change route" on an existing journey. */
initialFrom?: PickedPlace | null
initialTo?: PickedPlace | null
/** Pre-seed the departure time ('HH:mm') — used when planning a specific leg. */
initialTime?: string | null
}
export default function TransitSearchPanel({ day, days, places, accommodations = [], onAdd, initialFrom = null, initialTo = null }: TransitSearchPanelProps) {
export default function TransitSearchPanel({ day, days, places, accommodations = [], onAdd, initialFrom = null, initialTo = null, initialTime = null }: TransitSearchPanelProps) {
const { t } = useTranslation()
const toast = useToast()
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
@@ -328,7 +330,7 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
const [from, setFrom] = useState<PickedPlace | null>(initialFrom)
const [to, setTo] = useState<PickedPlace | null>(initialTo)
const [time, setTime] = useState('09:00')
const [time, setTime] = useState(initialTime || '09:00')
const [arriveBy, setArriveBy] = useState(false)
const [activeModes, setActiveModes] = useState<Set<string>>(() => new Set(MODE_GROUPS.map(m => m.key)))
const [pref, setPref] = useState<'best' | 'transfers' | 'walking'>('best')
@@ -160,8 +160,8 @@ interface TransportModalProps {
initialAutomated?: boolean
/** Transit search needs real dates to depart on, so the Automated mode is hidden on a dateless trip. */
tripHasDates?: boolean
/** Pre-seed the transit search — used by "change route" on an existing journey. */
transitPrefill?: { from?: PickedPlace | null; to?: PickedPlace | null } | null
/** Pre-seed the transit search — used by "change route" and by per-leg planning. */
transitPrefill?: { from?: PickedPlace | null; to?: PickedPlace | null; time?: string | null } | null
/** Trip members + guests, for the traveler picker (#1517). */
tripMembers?: TripMember[]
}
@@ -701,6 +701,7 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
onAdd={(payload) => onSave(payload as Record<string, any> & { title: string })}
initialFrom={transitPrefill?.from ?? null}
initialTo={transitPrefill?.to ?? null}
initialTime={transitPrefill?.time ?? null}
/>
)
})()}
@@ -0,0 +1,222 @@
// FE-PLANNER-EXPORTMODAL-001 to FE-PLANNER-EXPORTMODAL-014
import { render, screen, waitFor } from '../../../tests/helpers/render'
import userEvent from '@testing-library/user-event'
import { downloadTripPDF } from '../PDF/TripPDF'
import { buildDay, buildDayNote, buildTrip } from '../../../tests/helpers/factories'
import { TripExportModal } from './TripExportModal'
vi.mock('../PDF/TripPDF', () => ({ downloadTripPDF: vi.fn().mockResolvedValue(undefined) }))
// The subscribe dialog fetches its feed token on mount; it is exercised in its
// own test, here we only care that the entry mounts it.
vi.mock('./IcsSubscribeModal', () => ({
IcsSubscribeModal: ({ title, onClose }: { title: string; onClose: () => void }) => (
<div data-testid="ics-subscribe-modal">
{title}
<button onClick={onClose}>close-subscribe</button>
</div>
),
}))
const t = (key: string, params?: Record<string, unknown>) =>
params ? `${key}|${Object.values(params).join('|')}` : key
const trip = buildTrip({ id: 1, title: 'Roadtrip' })
function makeToast() {
return {
success: vi.fn((_m: string) => {}),
error: vi.fn((_m: string) => {}),
warning: vi.fn((_m: string) => {}),
info: vi.fn((_m: string) => {}),
}
}
function makeProps(overrides: Partial<React.ComponentProps<typeof TripExportModal>> = {}) {
return {
isOpen: true,
onClose: vi.fn(),
tripId: 1,
trip,
days: [],
places: [],
categories: [],
assignments: {},
reservations: [],
dayNotes: {},
t,
locale: 'en-US',
toast: makeToast(),
...overrides,
} as React.ComponentProps<typeof TripExportModal>
}
let clickedHref: string | null
beforeEach(() => {
vi.clearAllMocks()
clickedHref = null
// jsdom has neither of these, and an anchor click would navigate.
globalThis.URL.createObjectURL = vi.fn(() => 'blob:mock')
globalThis.URL.revokeObjectURL = vi.fn()
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {
clickedHref = this.href
})
})
afterEach(() => vi.restoreAllMocks())
const okResponse = (body = '<gpx/>') =>
({ ok: true, status: 200, blob: async () => new Blob([body]) }) as unknown as Response
describe('TripExportModal', () => {
it('FE-PLANNER-EXPORTMODAL-001: closed, it renders nothing', () => {
render(<TripExportModal {...makeProps({ isOpen: false })} />)
expect(screen.queryByText('dayplan.export')).not.toBeInTheDocument()
})
it('FE-PLANNER-EXPORTMODAL-002: open, every export sits in its own section', () => {
render(<TripExportModal {...makeProps()} />)
expect(screen.getByText('dayplan.exportDocument')).toBeInTheDocument()
expect(screen.getByText('dayplan.exportCalendar')).toBeInTheDocument()
expect(screen.getByText('dayplan.exportMaps · GPX')).toBeInTheDocument()
for (const label of ['dayplan.pdf', 'mobileTrip.icsDownload', 'mobileTrip.icsSubscribe',
'dayplan.gpxAll', 'dayplan.gpxPlaces', 'dayplan.gpxDays']) {
expect(screen.getByText(label)).toBeInTheDocument()
}
})
// ── PDF ───────────────────────────────────────────────────────────────────
it('FE-PLANNER-EXPORTMODAL-003: the PDF row exports the trip with the day notes flattened', async () => {
const user = userEvent.setup()
const days = [buildDay({ id: 10, title: 'Day 1' })]
const dayNotes = { '10': [buildDayNote({ id: 1, text: 'Bring cash' })] }
render(<TripExportModal {...makeProps({ days, dayNotes })} />)
await user.click(screen.getByText('dayplan.pdf'))
await waitFor(() => expect(downloadTripPDF).toHaveBeenCalledTimes(1))
expect(vi.mocked(downloadTripPDF).mock.calls[0][0]).toMatchObject({
trip, days, dayNotes: [expect.objectContaining({ id: 1, text: 'Bring cash', day_id: 10 })],
})
})
it('FE-PLANNER-EXPORTMODAL-004: a finished PDF export closes the dialog', async () => {
const user = userEvent.setup()
const onClose = vi.fn()
render(<TripExportModal {...makeProps({ onClose })} />)
await user.click(screen.getByText('dayplan.pdf'))
await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1))
})
it('FE-PLANNER-EXPORTMODAL-005: a failing PDF export toasts the error and keeps the dialog open', async () => {
const user = userEvent.setup()
vi.mocked(downloadTripPDF).mockRejectedValueOnce(new Error('font missing'))
const toast = makeToast()
const onClose = vi.fn()
render(<TripExportModal {...makeProps({ toast, onClose })} />)
await user.click(screen.getByText('dayplan.pdf'))
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('dayplan.pdfError: font missing'))
expect(onClose).not.toHaveBeenCalled()
})
it('FE-PLANNER-EXPORTMODAL-006: an aborted PDF export without an Error still reaches the toast', async () => {
const user = userEvent.setup()
vi.mocked(downloadTripPDF).mockRejectedValueOnce('boom')
const toast = makeToast()
render(<TripExportModal {...makeProps({ toast })} />)
await user.click(screen.getByText('dayplan.pdf'))
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('dayplan.pdfError: boom'))
})
// ── Calendar ──────────────────────────────────────────────────────────────
it('FE-PLANNER-EXPORTMODAL-007: the ICS row fetches the export and hands it to a download link', async () => {
const user = userEvent.setup()
const fetchMock = vi.fn(async () => okResponse('BEGIN:VCALENDAR'))
vi.stubGlobal('fetch', fetchMock)
render(<TripExportModal {...makeProps()} />)
await user.click(screen.getByText('mobileTrip.icsDownload'))
await waitFor(() => expect(fetchMock).toHaveBeenCalledWith('/api/trips/1/export.ics', { credentials: 'include' }))
await waitFor(() => expect(clickedHref).toBe('blob:mock'))
})
it('FE-PLANNER-EXPORTMODAL-008: a rejected ICS export shows the failure toast', async () => {
const user = userEvent.setup()
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 500 }) as unknown as Response))
const toast = makeToast()
render(<TripExportModal {...makeProps({ toast })} />)
await user.click(screen.getByText('mobileTrip.icsDownload'))
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('planner.icsExportFailed'))
expect(clickedHref).toBeNull()
})
it('FE-PLANNER-EXPORTMODAL-009: the subscribe row opens the subscribe dialog and closes again', async () => {
const user = userEvent.setup()
render(<TripExportModal {...makeProps()} />)
await user.click(screen.getByText('mobileTrip.icsSubscribe'))
expect(screen.getByTestId('ics-subscribe-modal')).toBeInTheDocument()
await user.click(screen.getByText('close-subscribe'))
expect(screen.queryByTestId('ics-subscribe-modal')).not.toBeInTheDocument()
})
// The subscription mints a link that reads the trip without an account, so it
// needs share_manage; the one-off download is a file this member may already
// read. Leaving the entry visible would only produce a dialog whose enable
// button the server refuses.
it('FE-PLANNER-EXPORTMODAL-010: without share_manage the download stays and the subscription goes', () => {
render(<TripExportModal {...makeProps({ canManageShare: false })} />)
expect(screen.getByText('mobileTrip.icsDownload')).toBeInTheDocument()
expect(screen.queryByText('mobileTrip.icsSubscribe')).not.toBeInTheDocument()
})
// ── GPX (#1442) ───────────────────────────────────────────────────────────
it('FE-PLANNER-EXPORTMODAL-011: each scope asks the server for exactly its own selection', async () => {
const user = userEvent.setup()
const fetchMock = vi.fn(async () => okResponse())
vi.stubGlobal('fetch', fetchMock)
for (const [label, expected] of [
['dayplan.gpxAll', '/api/trips/1/places/export.gpx'],
['dayplan.gpxPlaces', '/api/trips/1/places/export.gpx?dayRoutes=false'],
['dayplan.gpxDays', '/api/trips/1/places/export.gpx?waypoints=false&tracks=false'],
] as const) {
const view = render(<TripExportModal {...makeProps()} />)
await user.click(screen.getByText(label))
await waitFor(() => expect(fetchMock).toHaveBeenCalledWith(expected, { credentials: 'include' }))
fetchMock.mockClear()
view.unmount()
}
})
it('FE-PLANNER-EXPORTMODAL-012: a download names the file after the trip', async () => {
const user = userEvent.setup()
vi.stubGlobal('fetch', vi.fn(async () => okResponse()))
render(<TripExportModal {...makeProps()} />)
await user.click(screen.getByText('dayplan.gpxAll'))
await waitFor(() => expect(clickedHref).toBe('blob:mock'))
await waitFor(() => expect(globalThis.URL.revokeObjectURL).toHaveBeenCalled())
})
it('FE-PLANNER-EXPORTMODAL-013: an empty trip says so instead of reporting a failure', async () => {
const user = userEvent.setup()
const toast = makeToast()
const onClose = vi.fn()
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 404 }) as unknown as Response))
render(<TripExportModal {...makeProps({ toast, onClose })} />)
await user.click(screen.getByText('dayplan.gpxAll'))
await waitFor(() => expect(toast.info).toHaveBeenCalledWith('dayplan.gpxEmpty'))
expect(toast.error).not.toHaveBeenCalled()
expect(clickedHref).toBeNull()
// Nothing was downloaded, so the dialog stays put.
expect(onClose).not.toHaveBeenCalled()
})
it('FE-PLANNER-EXPORTMODAL-014: a real failure toasts the error', async () => {
const user = userEvent.setup()
const toast = makeToast()
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 500 }) as unknown as Response))
render(<TripExportModal {...makeProps({ toast })} />)
await user.click(screen.getByText('dayplan.gpxAll'))
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('dayplan.gpxFailed'))
})
})
@@ -0,0 +1,246 @@
import { useState, type ReactNode } from 'react'
import { CalendarDays, CalendarPlus, ChevronRight, Download, FileText, Loader2, MapPin, Route as RouteIcon } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import Modal from '../shared/Modal'
import { IcsSubscribeModal } from './IcsSubscribeModal'
import { useToast } from '../shared/Toast'
import type { Trip, Day, Place, Category, AssignmentsMap, Reservation, DayNote } from '../../types'
/**
* What a GPX download can carry. Worded by what someone wants on their device
* rather than by the GPX element it maps to: "everything", "just the places" for
* an offline map, "just the days" for following a plan. An omitted flag defaults
* to true server-side, so the first entry needs no query at all.
*/
const GPX_SCOPES = [
{ key: 'all', query: '', labelKey: 'dayplan.gpxAll', icon: Download },
{ key: 'places', query: '?dayRoutes=false', labelKey: 'dayplan.gpxPlaces', icon: MapPin },
{ key: 'days', query: '?waypoints=false&tracks=false', labelKey: 'dayplan.gpxDays', icon: RouteIcon },
] as const
interface TripExportModalProps {
isOpen: boolean
onClose: () => void
tripId: number
trip: Trip
days: Day[]
places: Place[]
categories: Category[]
assignments: AssignmentsMap
reservations: Reservation[]
dayNotes: Record<string, DayNote[]>
t: (key: string, params?: Record<string, any>) => string
locale: string
toast: ReturnType<typeof useToast>
/**
* Gates "Subscribe to calendar" only. The one-off ICS download above it stays
* open to every member: it is a file they already have the right to read,
* while the subscription mints a link that works without an account.
*/
canManageShare?: boolean
}
/**
* Every way a trip leaves TREK, in one dialog: the day plan as a PDF, the
* bookings as a calendar (a one-off .ics or a live subscription) and the map
* data as GPX in the three scopes a device actually wants.
*
* It replaces three separate toolbar buttons, two of which opened hover menus of
* their own. On a narrow sidebar that row simply ran out of width and the
* exports dropped off the edge; one button cannot.
*/
export function TripExportModal({
isOpen, onClose, tripId, trip, days, places, categories, assignments, reservations, dayNotes,
t, locale, toast, canManageShare = true,
}: TripExportModalProps) {
const [subscribeOpen, setSubscribeOpen] = useState(false)
// Which row is working, so the dialog can say so instead of looking inert
// while a 226 kB PDF builder is fetched and a document is rendered.
const [busy, setBusy] = useState<string | null>(null)
const fileBase = trip?.title || 'trip'
// Shared tail of every download: Firefox and Safari cancel the download when
// the object URL is revoked before they picked the blob up, hence the delay.
const saveBlob = (blob: Blob, filename: string) => {
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
setTimeout(() => { URL.revokeObjectURL(url); a.remove() }, 100)
}
const exportPdf = async () => {
if (busy) return
setBusy('pdf')
const flatNotes = Object.entries(dayNotes).flatMap(([dayId, notes]) =>
notes.map(n => ({ ...n, day_id: Number(dayId) })),
)
try {
// Loaded on click: the PDF builder is ~226 kB and hangs off the days
// sidebar, so every trip used to pay for it whether or not anyone
// exported. A missing chunk lands in the catch and shows the same error
// the export already had.
const { downloadTripPDF } = await import('../PDF/TripPDF')
await downloadTripPDF({ trip, days, places, assignments, categories, dayNotes: flatNotes, reservations, t, locale })
onClose()
} catch (e) {
console.error('PDF error:', e)
toast.error(`${t('dayplan.pdfError')}: ${e instanceof Error ? e.message : String(e)}`)
} finally {
setBusy(null)
}
}
const downloadIcs = async () => {
if (busy) return
setBusy('ics')
try {
const res = await fetch(`/api/trips/${tripId}/export.ics`, { credentials: 'include' })
if (!res.ok) throw new Error()
saveBlob(await res.blob(), `${fileBase}.ics`)
onClose()
} catch {
toast.error(t('planner.icsExportFailed'))
} finally {
setBusy(null)
}
}
const downloadGpx = async (key: string, query: string) => {
if (busy) return
setBusy(`gpx:${key}`)
try {
const res = await fetch(`/api/trips/${tripId}/places/export.gpx${query}`, { credentials: 'include' })
// 404 here means the selection is empty, which is worth its own message:
// "nothing happened" and "the download broke" look identical otherwise.
if (res.status === 404) { toast.info(t('dayplan.gpxEmpty')); return }
if (!res.ok) throw new Error()
saveBlob(await res.blob(), `${fileBase}.gpx`)
onClose()
} catch {
toast.error(t('dayplan.gpxFailed'))
} finally {
setBusy(null)
}
}
return (
<>
<Modal
isOpen={isOpen}
onClose={onClose}
size="lg"
title={
<span className="flex items-center gap-2.5">
<span className="flex h-8 w-8 items-center justify-center rounded-[10px] bg-accent-subtle text-accent-on">
<Download size={16} strokeWidth={2} />
</span>
{t('dayplan.export')}
</span>
}
>
<p className="-mt-1 mb-5 text-caption text-content-muted">{t('dayplan.exportIntro')}</p>
<Section label={t('dayplan.exportDocument')}>
<ExportRow
icon={FileText}
title={t('dayplan.pdf')}
sub={t('dayplan.pdfTooltip')}
busy={busy === 'pdf'}
disabled={busy != null}
onClick={exportPdf}
/>
</Section>
<Section label={t('dayplan.exportCalendar')}>
<ExportRow
icon={CalendarDays}
title={t('mobileTrip.icsDownload')}
sub={`${fileBase}.ics`}
busy={busy === 'ics'}
disabled={busy != null}
onClick={downloadIcs}
/>
{canManageShare && (
<ExportRow
icon={CalendarPlus}
title={t('mobileTrip.icsSubscribe')}
sub={t('mobileTrip.icsSubscribeSub')}
disabled={busy != null}
onClick={() => setSubscribeOpen(true)}
/>
)}
</Section>
{/* GPX — the counterpart to the GPX import in the places sidebar. The
format name carries more than a translated heading would, so it is
spelled out beside the plain-language one. */}
<Section label={`${t('dayplan.exportMaps')} · GPX`}>
{GPX_SCOPES.map(scope => (
<ExportRow
key={scope.key}
icon={scope.icon}
title={t(scope.labelKey)}
busy={busy === `gpx:${scope.key}`}
disabled={busy != null}
onClick={() => downloadGpx(scope.key, scope.query)}
/>
))}
</Section>
</Modal>
{subscribeOpen && canManageShare && (
<IcsSubscribeModal
endpoint={`/api/trips/${tripId}/feed`}
title={t('mobileTrip.icsSubscribe')}
description={t('mobileTrip.icsSubscribeSub')}
onClose={() => setSubscribeOpen(false)}
/>
)}
</>
)
}
function Section({ label, children }: { label: string; children: ReactNode }) {
return (
<section className="mb-4 last:mb-0">
<h3 className="mb-1.5 px-1 text-caption font-bold uppercase tracking-[0.07em] text-content-faint">{label}</h3>
<div className="divide-y divide-edge-faint overflow-hidden rounded-xl border border-edge-faint bg-surface">
{children}
</div>
</section>
)
}
function ExportRow({ icon: Icon, title, sub, busy = false, disabled = false, onClick }: {
icon: LucideIcon
title: string
sub?: string
busy?: boolean
disabled?: boolean
onClick: () => void
}) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
className="group flex w-full items-center gap-3 px-3 py-2.5 text-left transition-colors hover:bg-surface-hover disabled:cursor-default disabled:opacity-50"
>
<span className="flex h-9 w-9 flex-none items-center justify-center rounded-[10px] bg-surface-tertiary text-content-secondary transition-colors group-enabled:group-hover:bg-accent-subtle group-enabled:group-hover:text-accent-on">
{busy ? <Loader2 size={16} strokeWidth={2} className="animate-spin" /> : <Icon size={16} strokeWidth={1.9} />}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-body font-semibold text-content">{title}</span>
{sub && <span className="block truncate text-caption text-content-muted">{sub}</span>}
</span>
<ChevronRight
size={15}
strokeWidth={2}
className="flex-none text-content-faint transition-transform group-enabled:group-hover:translate-x-0.5"
/>
</button>
)
}
@@ -5,6 +5,7 @@ import { useTranslation } from '../../i18n'
import { useToast } from '../shared/Toast'
import { useContextMenu } from '../shared/ContextMenu'
import { placesApi } from '../../api/client'
import { collectionsApi } from '../../api/collections'
import { useTripStore } from '../../store/tripStore'
import { useCanDo } from '../../store/permissionsStore'
import { useAuthStore } from '../../store/authStore'
@@ -157,8 +158,32 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
const [categoryPickerOpen, setCategoryPickerOpen] = useState(false)
const [saveToListOpen, setSaveToListOpen] = useState(false)
const [markVisitedBusy, setMarkVisitedBusy] = useState(false)
const exitSelectMode = () => { setSelectMode(false); setSelectedIds(new Set()) }
/**
* "I have been to these" for the selection, applied wherever the places are
* saved in the library (#1469). The server does the matching, so a place saved
* under a different name in a list is still found.
*/
const markSelectionVisited = useCallback(async () => {
const ids = Array.from(selectedIds)
if (ids.length === 0 || markVisitedBusy) return
setMarkVisitedBusy(true)
try {
const { updated, places: matchedPlaces } = await collectionsApi.setStatusFromTrip(props.tripId, ids, 'visited')
if (updated === 0) toast.info(t('collections.markVisitedNone'))
else toast.success(t('collections.markedVisitedTrip', { count: matchedPlaces ?? 0 }))
exitSelectMode()
} catch {
toast.error(t('common.error'))
} finally {
setMarkVisitedBusy(false)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedIds, markVisitedBusy, props.tripId, t])
// Auto-exit when all selected places have been removed from the store (e.g. after bulk delete)
useEffect(() => {
if (!selectMode || selectedIds.size === 0) return
@@ -275,6 +300,7 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
selectMode, setSelectMode, selectedIds, setSelectedIds, pendingDeleteIds, setPendingDeleteIds,
categoryPickerOpen, setCategoryPickerOpen,
saveToListOpen, setSaveToListOpen, collectionsEnabled, tripId,
markSelectionVisited, markVisitedBusy,
exitSelectMode, toggleSelected, toggleCategoryFilter, dayPickerPlace, setDayPickerPlace,
catDropOpen, setCatDropOpen, mobileShowDays, setMobileShowDays,
hasTracks, plannedIds, filtered, registerPlaceRow, isAssignedToSelectedDay, inDaySet, openContextMenu,
@@ -1,22 +1,35 @@
// FE-COMP-LLM-001 to FE-COMP-LLM-013
// FE-COMP-LLM-001 to FE-COMP-LLM-016
import { render, screen, waitFor } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildSettings } from '../../../tests/helpers/factories';
import { buildAdmin, buildSettings, buildUser } from '../../../tests/helpers/factories';
import { useSettingsStore } from '../../store/settingsStore';
import { useAuthStore } from '../../store/authStore';
import type { Settings } from '../../types';
import { ToastContainer } from '../shared/Toast';
import LlmConnectionSection from './LlmConnectionSection';
let loadSettings = vi.fn().mockResolvedValue(undefined);
function seedLlm(over: Partial<Settings> = {}, updateSettings = vi.fn().mockResolvedValue(undefined)) {
loadSettings = vi.fn().mockResolvedValue(undefined);
seedStore(useSettingsStore, {
settings: buildSettings({ language: 'en', ...over }),
isLoaded: true,
updateSettings,
loadSettings,
});
return updateSettings;
}
function seedRole(role: 'user' | 'admin') {
seedStore(useAuthStore, {
user: role === 'admin' ? buildAdmin() : buildUser(),
isAuthenticated: true,
isLoading: false,
});
}
function renderSection() {
return render(
<>
@@ -39,31 +52,30 @@ async function pickProvider(user: ReturnType<typeof userEvent.setup>, current: R
beforeEach(() => {
resetAllStores();
vi.clearAllMocks();
seedRole('user');
seedLlm();
});
describe('LlmConnectionSection', () => {
it('FE-COMP-LLM-001: defaults to the local provider with a base URL and without a key field', () => {
it('FE-COMP-LLM-001: defaults to OpenAI with a key field and no endpoint of its own', () => {
renderSection();
expect(screen.getByText('AI parsing')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Local \(Ollama\)/ })).toBeInTheDocument();
expect(screen.getByPlaceholderText('http://localhost:11434')).toBeInTheDocument();
expect(screen.queryByPlaceholderText('API key')).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: /OpenAI/ })).toBeInTheDocument();
expect(screen.getByPlaceholderText('API key')).toBeInTheDocument();
// The endpoint is instance configuration since #1772, so it has no field here.
expect(screen.queryByPlaceholderText('http://localhost:11434')).not.toBeInTheDocument();
expect(
screen.getByText('A self-hosted (Ollama) endpoint is set up once for the whole instance in the admin settings. You can still use your own OpenAI or Anthropic key here.'),
).toBeInTheDocument();
});
it('FE-COMP-LLM-002: hydrates provider, model, base URL and the multimodal toggle', () => {
seedLlm({
llm_provider: 'openai',
llm_model: 'gpt-4o-mini',
llm_base_url: 'https://api.openai.com/v1',
llm_multimodal: true,
});
it('FE-COMP-LLM-002: hydrates provider, model and the multimodal toggle', () => {
seedLlm({ llm_provider: 'openai', llm_model: 'gpt-4o-mini', llm_multimodal: true });
renderSection();
expect(screen.getByRole('button', { name: /OpenAI/ })).toBeInTheDocument();
expect(screen.getByDisplayValue('gpt-4o-mini')).toBeInTheDocument();
expect(screen.getByDisplayValue('https://api.openai.com/v1')).toBeInTheDocument();
expect(multimodalToggle()).toHaveAttribute('aria-pressed', 'true');
});
@@ -74,7 +86,7 @@ describe('LlmConnectionSection', () => {
});
renderSection();
expect(screen.getByRole('button', { name: /Local \(Ollama\)/ })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /OpenAI/ })).toBeInTheDocument();
expect(screen.queryByDisplayValue('claude-sonnet')).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: /^Save$/ })).toBeDisabled();
});
@@ -84,7 +96,6 @@ describe('LlmConnectionSection', () => {
renderSection();
expect(screen.getByPlaceholderText('••••••••')).toHaveValue('');
expect(screen.queryByPlaceholderText('http://localhost:11434')).not.toBeInTheDocument();
});
it('FE-COMP-LLM-005: without a stored key the field falls back to the plain label placeholder', () => {
@@ -94,39 +105,38 @@ describe('LlmConnectionSection', () => {
expect(screen.getByPlaceholderText('API key')).toHaveValue('');
});
it('FE-COMP-LLM-006: picking Anthropic hides the base URL and reveals the key field', async () => {
it('FE-COMP-LLM-006: the key field stays through a provider change, since both are hosted', async () => {
const user = userEvent.setup();
renderSection();
await pickProvider(user, /Local \(Ollama\)/, 'Anthropic');
await pickProvider(user, /OpenAI/, 'Anthropic');
expect(screen.queryByPlaceholderText('http://localhost:11434')).not.toBeInTheDocument();
expect(screen.getByText('Stored encrypted. Leave blank to keep the current key.')).toBeInTheDocument();
expect(screen.queryByPlaceholderText('http://localhost:11434')).not.toBeInTheDocument();
});
it('FE-COMP-LLM-007: picking OpenAI keeps the base URL and adds the key field', async () => {
it('FE-COMP-LLM-007: the provider list is exactly the two hosted ones', async () => {
const user = userEvent.setup();
renderSection();
await pickProvider(user, /Local \(Ollama\)/, 'OpenAI');
await user.click(screen.getByRole('button', { name: /OpenAI/ }));
expect(screen.getByPlaceholderText('http://localhost:11434')).toBeInTheDocument();
expect(screen.getByPlaceholderText('API key')).toBeInTheDocument();
expect(await screen.findByRole('button', { name: 'Anthropic' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /Local \(Ollama\)/ })).not.toBeInTheDocument();
});
it('FE-COMP-LLM-008: saving trims the inputs and omits the key when none was typed', async () => {
const user = userEvent.setup();
const updateSettings = seedLlm({ llm_model: '', llm_base_url: '' });
const updateSettings = seedLlm({ llm_model: '' });
renderSection();
await user.type(screen.getByPlaceholderText('qwen3:8b'), ' qwen3:8b ');
await user.type(screen.getByPlaceholderText('http://localhost:11434'), ' http://ollama.local ');
await user.type(screen.getByPlaceholderText('qwen3:8b'), ' gpt-4o-mini ');
await user.click(screen.getByRole('button', { name: /^Save$/ }));
expect(updateSettings).toHaveBeenCalledWith({
llm_provider: 'local',
llm_model: 'qwen3:8b',
llm_base_url: 'http://ollama.local',
llm_provider: 'openai',
llm_model: 'gpt-4o-mini',
llm_base_url: '',
llm_multimodal: false,
});
await screen.findByText('AI settings saved');
@@ -144,14 +154,13 @@ describe('LlmConnectionSection', () => {
await waitFor(() => expect(screen.getByPlaceholderText('••••••••')).toHaveValue(''));
});
it('FE-COMP-LLM-010: a non-local provider never persists a base URL', async () => {
const user = userEvent.setup();
const updateSettings = seedLlm({ llm_provider: 'anthropic', llm_base_url: 'http://leftover' });
it('FE-COMP-LLM-010: a stored local provider falls back to OpenAI without saving anything', () => {
const updateSettings = seedLlm({ llm_provider: 'local', llm_model: 'nuextract', llm_base_url: 'http://192.168.1.5:11434' });
renderSection();
await user.click(screen.getByRole('button', { name: /^Save$/ }));
expect(updateSettings).toHaveBeenCalledWith(expect.objectContaining({ llm_base_url: '' }));
expect(screen.getByRole('button', { name: /OpenAI/ })).toBeInTheDocument();
expect(screen.queryByDisplayValue('http://192.168.1.5:11434')).not.toBeInTheDocument();
expect(updateSettings).not.toHaveBeenCalled();
});
it('FE-COMP-LLM-011: the multimodal toggle is part of the saved payload', async () => {
@@ -193,4 +202,45 @@ describe('LlmConnectionSection', () => {
release();
await waitFor(() => expect(saveBtn).toBeEnabled());
});
it('FE-COMP-LLM-014: saving clears a leftover base URL instead of resending it', async () => {
const user = userEvent.setup();
const updateSettings = seedLlm({ llm_provider: 'local', llm_model: 'nuextract', llm_base_url: 'http://192.168.1.5:11434' });
renderSection();
await user.click(screen.getByRole('button', { name: /^Save$/ }));
expect(updateSettings).toHaveBeenCalledWith({
llm_provider: 'openai',
llm_model: 'nuextract',
llm_base_url: '',
llm_multimodal: false,
});
});
it('FE-COMP-LLM-015: a refused save pulls the stored settings back in', async () => {
const user = userEvent.setup();
seedLlm({ llm_provider: 'anthropic' }, vi.fn().mockRejectedValue(new Error('Admin access required')));
renderSection();
await user.click(screen.getByRole('button', { name: /^Save$/ }));
await screen.findByText('Could not save AI settings');
expect(loadSettings).toHaveBeenCalled();
});
// The point of #1772: an instance has one endpoint, so this surface is the same
// for the person who runs it. The admin sets it on the addon, not here.
it('FE-COMP-LLM-016: an admin sees the same two providers and no endpoint field', async () => {
const user = userEvent.setup();
seedRole('admin');
seedLlm({ llm_provider: 'local', llm_model: 'qwen3:8b', llm_base_url: 'http://localhost:11434' });
renderSection();
expect(screen.getByRole('button', { name: /OpenAI/ })).toBeInTheDocument();
expect(screen.queryByPlaceholderText('http://localhost:11434')).not.toBeInTheDocument();
await user.click(screen.getByRole('button', { name: /OpenAI/ }));
expect(screen.queryByRole('button', { name: /Local \(Ollama\)/ })).not.toBeInTheDocument();
});
});
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react'
import React, { useEffect, useMemo, useState } from 'react'
import { Sparkles, Save } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { useToast } from '../shared/Toast'
@@ -16,6 +16,14 @@ type Provider = NonNullable<Settings['llm_provider']>
* instance-wide model on the addon — the server resolves the admin config first.
* The API key is stored encrypted and never prefilled: a blank field keeps the
* stored key (mirrors the AirTrail connection layout).
*
* A free-form endpoint does not live here at all (#1772): the request goes out
* from the server, so only whoever runs the instance may name its target, and
* an instance has exactly one such target. It is configured once on the addon
* in the admin settings, including for the admin's own account. What is left
* here are the two hosted providers, which go to a fixed address with the
* user's own key. The server enforces this on both the read and the write path,
* so this is only the matching surface.
*/
export default function LlmConnectionSection(): React.ReactElement {
const { t } = useTranslation()
@@ -23,28 +31,36 @@ export default function LlmConnectionSection(): React.ReactElement {
const settings = useSettingsStore(s => s.settings)
const isLoaded = useSettingsStore(s => s.isLoaded)
const updateSettings = useSettingsStore(s => s.updateSettings)
const loadSettings = useSettingsStore(s => s.loadSettings)
const [provider, setProvider] = useState<Provider>('local')
const [provider, setProvider] = useState<Provider>('openai')
const [model, setModel] = useState('')
const [baseUrl, setBaseUrl] = useState('')
const [apiKey, setApiKey] = useState('')
const [multimodal, setMultimodal] = useState(false)
const [hasStoredKey, setHasStoredKey] = useState(false)
const [saving, setSaving] = useState(false)
// Hydrate from the loaded settings. llm_api_key arrives masked, so we only use
// its presence to drive the placeholder — never the value itself.
// its presence to drive the placeholder, never the value itself. A stored
// 'local' from before #1772 shows as OpenAI (local state only, nothing is
// saved until Save is pressed) so the form never offers a value the server
// would refuse.
useEffect(() => {
if (!isLoaded) return
setProvider(settings.llm_provider || 'local')
const stored = settings.llm_provider || 'openai'
setProvider(stored === 'local' ? 'openai' : stored)
setModel(settings.llm_model || '')
setBaseUrl(settings.llm_base_url || '')
setMultimodal(settings.llm_multimodal === true)
setHasStoredKey(!!settings.llm_api_key)
}, [isLoaded, settings.llm_provider, settings.llm_model, settings.llm_base_url, settings.llm_multimodal, settings.llm_api_key])
}, [isLoaded, settings.llm_provider, settings.llm_model, settings.llm_multimodal, settings.llm_api_key])
const needsKey = provider !== 'local'
const showBaseUrl = provider === 'local' || provider === 'openai'
const providerOptions = useMemo(
() => [
{ value: 'openai', label: t('settings.aiParsing.providerOpenai') },
{ value: 'anthropic', label: t('settings.aiParsing.providerAnthropic') },
],
[t],
)
const handleSave = async () => {
setSaving(true)
@@ -52,7 +68,9 @@ export default function LlmConnectionSection(): React.ReactElement {
const payload: Partial<Settings> = {
llm_provider: provider,
llm_model: model.trim(),
llm_base_url: showBaseUrl ? baseUrl.trim() : '',
// Always cleared: the endpoint is instance configuration now, and this
// also drops a value left over from before #1772.
llm_base_url: '',
llm_multimodal: multimodal,
}
// Send the key only when the user typed a new one — a blank field means
@@ -64,6 +82,11 @@ export default function LlmConnectionSection(): React.ReactElement {
if (key) setHasStoredKey(true)
toast.success(t('settings.aiParsing.toast.saved'))
} catch {
// updateSettings patches the store before the request and keeps the patch
// when the request fails, so a refused save (the 403 from #1772, or any
// other error) would leave the form showing a value the server never
// stored. Pull the stored settings back in so what is on screen is real.
await loadSettings()
toast.error(t('settings.aiParsing.toast.saveError'))
} finally {
setSaving(false)
@@ -80,12 +103,9 @@ export default function LlmConnectionSection(): React.ReactElement {
<CustomSelect
value={provider}
onChange={v => setProvider(v as Provider)}
options={[
{ value: 'local', label: t('settings.aiParsing.providerLocal') },
{ value: 'openai', label: t('settings.aiParsing.providerOpenai') },
{ value: 'anthropic', label: t('settings.aiParsing.providerAnthropic') },
]}
options={providerOptions}
/>
<p className="mt-1 text-xs text-content-faint">{t('settings.aiParsing.localAdminOnly')}</p>
</div>
<div>
@@ -100,35 +120,20 @@ export default function LlmConnectionSection(): React.ReactElement {
/>
</div>
{showBaseUrl && (
<div>
<label className="block text-sm font-medium mb-1.5 text-content-secondary">{t('settings.aiParsing.baseUrl')}</label>
<input
type="url"
autoComplete="off"
value={baseUrl}
onChange={e => setBaseUrl(e.target.value)}
placeholder="http://localhost:11434"
className="w-full px-3 py-2.5 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-slate-400 border-edge bg-surface-secondary text-content"
/>
<p className="mt-1 text-xs text-content-faint">{t('settings.aiParsing.baseUrlHint')}</p>
</div>
)}
{needsKey && (
<div>
<label className="block text-sm font-medium mb-1.5 text-content-secondary">{t('settings.aiParsing.apiKey')}</label>
<input
type="password"
value={apiKey}
onChange={e => setApiKey(e.target.value)}
autoComplete="off"
placeholder={hasStoredKey && !apiKey ? '••••••••' : t('settings.aiParsing.apiKey')}
className="w-full px-3 py-2.5 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-slate-400 border-edge bg-surface-secondary text-content"
/>
<p className="mt-1 text-xs text-content-faint">{t('settings.aiParsing.apiKeyHint')}</p>
</div>
)}
{/* Both remaining providers are hosted and need a key, so this is no
longer conditional (#1772). */}
<div>
<label className="block text-sm font-medium mb-1.5 text-content-secondary">{t('settings.aiParsing.apiKey')}</label>
<input
type="password"
value={apiKey}
onChange={e => setApiKey(e.target.value)}
autoComplete="off"
placeholder={hasStoredKey && !apiKey ? '••••••••' : t('settings.aiParsing.apiKey')}
className="w-full px-3 py-2.5 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-slate-400 border-edge bg-surface-secondary text-content"
/>
<p className="mt-1 text-xs text-content-faint">{t('settings.aiParsing.apiKeyHint')}</p>
</div>
<div>
<div className="flex items-center gap-3">
@@ -9,6 +9,7 @@ import { useSystemNoticeStore } from '../../store/systemNoticeStore.js';
import type { SystemNoticeDTO } from '../../store/systemNoticeStore.js';
import { useTranslation, isRtlLanguage } from '../../i18n/index.js';
import { runNoticeAction } from './noticeActions.js';
import { lockBodyScroll } from '../../utils/bodyScrollLock.js';
const ReactMarkdown = React.lazy(() =>
import('react-markdown').then(m => ({ default: m.default }))
@@ -504,15 +505,14 @@ function useSystemNoticeModal(notices: SystemNoticeDTO[]) {
return () => document.removeEventListener('keydown', handler);
}, [visible, idx, notices.length, canPage, language]); // eslint-disable-line react-hooks/exhaustive-deps
// Body scroll lock
// Body scroll lock. Ref-counted and keyed on a boolean, not on the notice
// object: the old version cleared body.overflow on every run of this effect,
// which since #1809 would let the page scroll away behind an open sheet.
const locksScroll = visible && !!notice;
useEffect(() => {
if (visible && notice) {
document.body.style.overflow = 'hidden';
} else {
document.body.style.overflow = '';
}
return () => { document.body.style.overflow = ''; };
}, [visible, notice]);
if (!locksScroll) return;
return lockBodyScroll();
}, [locksScroll]);
// Reset center slot scroll to top on navigation (keyboard / pager buttons).
useEffect(() => {
@@ -1,4 +1,4 @@
// FE-COMP-VCYSET-001 to FE-COMP-VCYSET-014
// FE-COMP-VCYSET-001 to FE-COMP-VCYSET-016
// Covers the calendar editor / draft rows and the leave-year block of VacaySettings,
// which VacaySettings.test.tsx only reaches at the surface.
import React from 'react'
@@ -144,7 +144,7 @@ describe('VacaySettings calendars', () => {
expect(updateHolidayCalendar).toHaveBeenLastCalledWith(3, { region: 'NL' })
// The region list is only offered because the holiday data is county-split.
await pickLoadedOption('Select region (optional)', 'Nordrhein-Westfalen')
await pickLoadedOption('Select region (required)', 'Nordrhein-Westfalen')
expect(updateHolidayCalendar).toHaveBeenLastCalledWith(3, { region: 'DE-NW' })
})
@@ -159,7 +159,7 @@ describe('VacaySettings calendars', () => {
})
const { container } = render(<VacaySettings onClose={vi.fn()} />)
expect(screen.queryByRole('button', { name: 'Select region (optional)' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Select region (required)' })).not.toBeInTheDocument()
const trash = trashButtons(container)[0]
fireEvent.mouseEnter(trash)
@@ -186,6 +186,9 @@ describe('VacaySettings calendars', () => {
fireEvent.change(screen.getByPlaceholderText('Label (optional)'), { target: { value: ' Feiertage ' } })
await pickLoadedOption('Select country', 'Germany')
// Germany has no regional holidays here, but the draft only unlocks once that
// answer is in (see FE-COMP-VCYSET-015).
await waitFor(() => expect(screen.getByRole('button', { name: 'Add' })).toBeEnabled())
fireEvent.click(screen.getByRole('button', { name: 'Add' }))
await waitFor(() => expect(addHolidayCalendar).toHaveBeenCalledWith(expect.objectContaining({
@@ -203,10 +206,10 @@ describe('VacaySettings calendars', () => {
fireEvent.click(screen.getByRole('button', { name: 'Add calendar' }))
await pickLoadedOption('Select country', 'Germany')
await screen.findByRole('button', { name: 'Select region (optional)' })
await screen.findByRole('button', { name: 'Select region (required)' })
expect(screen.getByRole('button', { name: 'Add' })).toBeDisabled()
await pickLoadedOption('Select region (optional)', 'Bayern')
await pickLoadedOption('Select region (required)', 'Bayern')
fireEvent.click(screen.getByRole('button', { name: 'Add' }))
await waitFor(() => expect(addHolidayCalendar).toHaveBeenCalledWith(expect.objectContaining({ region: 'DE-BY' })))
@@ -232,7 +235,7 @@ describe('VacaySettings calendars', () => {
expect(screen.queryByRole('button', { name: 'United States' })).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Netherlands' }))
await pickLoadedOption('Select region (optional)', 'Northern Region')
await pickLoadedOption('Select region (required)', 'Northern Region')
fireEvent.click(screen.getByRole('button', { name: 'Add' }))
await waitFor(() => expect(addHolidayCalendar).toHaveBeenCalledWith(expect.objectContaining({
@@ -321,4 +324,71 @@ describe('VacaySettings calendars', () => {
year_type: 'anniversary', year_start_month: 1, year_start_day: 1, hire_date: null,
})
})
it('FE-COMP-VCYSET-015: the draft stays blocked while the region list is still loading', async () => {
let release: (() => void) | undefined
server.use(http.get('/api/addons/vacay/holidays/:year/:country', async () => {
await new Promise<void>(resolve => { release = resolve })
return HttpResponse.json([
{ date: '2026-11-01', name: 'All Saints', localName: 'Allerheiligen', global: false, counties: ['DE-BY', 'DE-NW'] },
])
}))
useVacayStore.setState({ plan: buildPlan({ holidays_enabled: true }), addHolidayCalendar: vi.fn(async () => {}) })
render(<VacaySettings onClose={vi.fn()} />)
fireEvent.click(screen.getByRole('button', { name: 'Add calendar' }))
await pickLoadedOption('Select country', 'Germany')
// An empty list means "no answer yet", not "this country needs no region" (#1813).
expect(screen.getByRole('button', { name: 'Add' })).toBeDisabled()
expect(screen.getByRole('button', { name: 'Add' })).toHaveAttribute('aria-busy', 'true')
await waitFor(() => expect(release).toBeDefined())
release?.()
await screen.findByRole('button', { name: 'Select region (required)' })
expect(screen.getByRole('button', { name: 'Add' })).toBeDisabled()
expect(screen.getByRole('button', { name: 'Add' })).toHaveAttribute('aria-busy', 'false')
await pickLoadedOption('Select region (required)', 'Bayern')
expect(screen.getByRole('button', { name: 'Add' })).toBeEnabled()
})
it('FE-COMP-VCYSET-016: switching a calendar country drops the old region list at once', async () => {
let releaseNl: (() => void) | undefined
server.use(http.get('/api/addons/vacay/holidays/:year/:country', async ({ params }) => {
if (params.country === 'NL') await new Promise<void>(resolve => { releaseNl = resolve })
return HttpResponse.json([{
date: '2026-11-01', name: 'All Saints', localName: 'Allerheiligen', global: false,
counties: params.country === 'NL' ? ['NL-NH'] : ['DE-BY', 'DE-NW'],
}])
}))
const updateHolidayCalendar = vi.fn(async (id: number, data: { region?: string }) => {
const plan = useVacayStore.getState().plan
if (!plan) return
useVacayStore.setState({
plan: { ...plan, holiday_calendars: (plan.holiday_calendars ?? []).map(c => (c.id === id ? { ...c, ...data } : c)) },
})
})
useVacayStore.setState({
plan: buildPlan({
holidays_enabled: true,
holiday_calendars: [{ id: 3, plan_id: 1, region: 'DE', label: null, color: '#fecaca', sort_order: 0 }],
}),
updateHolidayCalendar,
})
render(<VacaySettings onClose={vi.fn()} />)
await screen.findByRole('button', { name: 'Select region (required)' })
await pickLoadedOption('Germany', 'Netherlands')
expect(updateHolidayCalendar).toHaveBeenLastCalledWith(3, { region: 'NL' })
// The Dutch list is still on its way, so the German regions must be gone:
// otherwise DE-BY can be saved for the Netherlands (#1813).
await waitFor(() => expect(screen.queryByRole('button', { name: 'Select region (required)' })).not.toBeInTheDocument())
await waitFor(() => expect(releaseNl).toBeDefined())
releaseNl?.()
await screen.findByRole('button', { name: 'Select region (required)' })
})
})
+35 -20
View File
@@ -1,5 +1,5 @@
import { useState, useEffect, useMemo } from 'react'
import { type LucideIcon, CalendarOff, AlertCircle, Building2, Unlink, ArrowRightLeft, Globe, Plus, Trash2, CalendarDays, CalendarRange, GraduationCap } from 'lucide-react'
import { type LucideIcon, CalendarOff, AlertCircle, Building2, Unlink, ArrowRightLeft, Globe, Loader2, Plus, Trash2, CalendarDays, CalendarRange, GraduationCap } from 'lucide-react'
import { useVacayStore } from '../../store/vacayStore'
import { getIntlLanguage, useTranslation } from '../../i18n'
import { useToast } from '../shared/Toast'
@@ -434,6 +434,30 @@ function SettingToggle({ icon: Icon, label, hint, value, onChange }: SettingTogg
)
}
/**
* Region options for a holiday-calendar country.
*
* The loaded list is tagged with the country it belongs to, so switching country
* drops the previous list in the same render instead of leaving it selectable while
* the next request is still running (#1813: picking a German region for the
* Netherlands was possible that way). `loadingRegions` tells "not answered yet"
* apart from "this country has no regions"; on the list alone both are empty.
*/
function useRegionOptions(country: string, calendarType: 'public_holiday' | 'school_holiday') {
const [loaded, setLoaded] = useState<{ country: string; options: { value: string; label: string }[] }>({ country: '', options: [] })
useEffect(() => {
if (!country) return
const load = calendarType === 'school_holiday' ? fetchSchoolHolidayRegionOptions : fetchRegionOptions
let stale = false
load(country).then(options => { if (!stale) setLoaded({ country, options }) })
return () => { stale = true }
}, [calendarType, country])
const ready = loaded.country === country
return { regions: ready ? loaded.options : [], loadingRegions: Boolean(country) && !ready }
}
// ── Existing calendar row (inline edit) ──────────────────────────────────────
function CalendarRow({ cal, countries, calendarType, onUpdate, onDelete }: {
cal: VacayHolidayCalendar
@@ -446,21 +470,15 @@ function CalendarRow({ cal, countries, calendarType, onUpdate, onDelete }: {
const { t } = useTranslation()
const [localColor, setLocalColor] = useState(cal.color)
const [localLabel, setLocalLabel] = useState(cal.label || '')
const [regions, setRegions] = useState<{ value: string; label: string }[]>([])
const [baseRegion] = cal.region.split('|')
const selectedCountry = baseRegion.split('-')[0]
const selectedRegion = cal.region.includes('|group:') || baseRegion.includes('-') ? cal.region : ''
const { regions } = useRegionOptions(selectedCountry, calendarType)
useEffect(() => { setLocalColor(cal.color) }, [cal.color])
useEffect(() => { setLocalLabel(cal.label || '') }, [cal.label])
useEffect(() => {
if (!selectedCountry) { setRegions([]); return }
const load = calendarType === 'school_holiday' ? fetchSchoolHolidayRegionOptions : fetchRegionOptions
load(selectedCountry).then(setRegions)
}, [calendarType, selectedCountry])
const PRESET_COLORS = ['#fecaca', '#fed7aa', '#fde68a', '#bbf7d0', '#a5f3fc', '#c7d2fe', '#e9d5ff', '#fda4af', '#6366f1', '#ef4444', '#22c55e', '#3b82f6']
const [showColorPicker, setShowColorPicker] = useState(false)
@@ -533,21 +551,16 @@ function AddCalendarForm({ countries, calendarType, onAdd, onCancel, defaultColo
const [region, setRegion] = useState('')
const [color, setColor] = useState(defaultColor)
const [label, setLabel] = useState('')
const [regions, setRegions] = useState<{ value: string; label: string }[]>([])
const [loadingRegions, setLoadingRegions] = useState(false)
const [baseRegion] = region.split('|')
const selectedCountry = baseRegion.split('-')[0] || ''
const selectedRegion = region.includes('|group:') || baseRegion.includes('-') ? region : ''
const { regions, loadingRegions } = useRegionOptions(selectedCountry, calendarType)
useEffect(() => {
if (!selectedCountry) { setRegions([]); return }
setLoadingRegions(true)
const load = calendarType === 'school_holiday' ? fetchSchoolHolidayRegionOptions : fetchRegionOptions
load(selectedCountry).then(list => { setRegions(list) }).finally(() => setLoadingRegions(false))
}, [calendarType, selectedCountry])
const canAdd = selectedCountry && (regions.length === 0 || selectedRegion !== '')
// Adding is blocked while the region list is on its way: an empty list would
// otherwise pass as "this country needs no region" and create a calendar that
// draws nothing (#1813). The button shows a spinner so the wait is visible.
const canAdd = Boolean(selectedCountry) && !loadingRegions && (regions.length === 0 || selectedRegion !== '')
const PRESET_COLORS = ['#fecaca', '#fed7aa', '#fde68a', '#bbf7d0', '#a5f3fc', '#c7d2fe', '#e9d5ff', '#fda4af', '#6366f1', '#ef4444', '#22c55e', '#3b82f6']
const [showColorPicker, setShowColorPicker] = useState(false)
@@ -579,7 +592,7 @@ function AddCalendarForm({ countries, calendarType, onAdd, onCancel, defaultColo
/>
<CustomSelect
value={selectedCountry}
onChange={v => { setRegion(String(v)); setRegions([]) }}
onChange={v => setRegion(String(v))}
options={countries}
placeholder={t('vacay.selectCountry')}
searchable
@@ -596,9 +609,11 @@ function AddCalendarForm({ countries, calendarType, onAdd, onCancel, defaultColo
<div className="flex gap-1.5 pt-0.5">
<button
disabled={!canAdd}
aria-busy={loadingRegions}
onClick={() => onAdd({ region: region || selectedCountry, color, label: label.trim() || null })}
className="flex-1 text-xs px-2 py-1.5 rounded-md font-medium transition-colors disabled:opacity-40 bg-content text-surface-card"
className="flex-1 flex items-center justify-center gap-1.5 text-xs px-2 py-1.5 rounded-md font-medium transition-colors disabled:opacity-40 bg-content text-surface-card"
>
{loadingRegions && <Loader2 size={12} className="animate-spin" />}
{t('vacay.add')}
</button>
<button
@@ -1,12 +1,14 @@
import { render, screen, fireEvent } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import Modal from './Modal';
import { lockBodyScroll, resetBodyScrollLock } from '../../utils/bodyScrollLock';
describe('Modal', () => {
const onClose = vi.fn();
beforeEach(() => {
onClose.mockClear();
resetBodyScrollLock();
document.body.style.overflow = '';
});
@@ -80,4 +82,18 @@ describe('Modal', () => {
render(<Modal isOpen={true} onClose={onClose} />);
expect(document.body.style.overflow).toBe('hidden');
});
// #1809: the document is the scroller on a phone, so closing this modal must
// not unlock the page while another overlay is still holding the lock.
it('FE-COMP-MODAL-012: unmounting keeps a lock another overlay still holds', () => {
const otherOverlay = lockBodyScroll();
const { unmount } = render(<Modal isOpen={true} onClose={onClose} />);
expect(document.body.style.overflow).toBe('hidden');
unmount();
expect(document.body.style.overflow).toBe('hidden');
otherOverlay();
expect(document.body.style.overflow).toBe('');
});
});
+12 -8
View File
@@ -1,6 +1,7 @@
import React, { useEffect, useCallback, useRef } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import { lockBodyScroll } from '../../utils/bodyScrollLock'
const sizeClasses: Record<string, string> = {
sm: 'max-w-sm',
@@ -39,16 +40,19 @@ export default function Modal({
}, [onClose])
useEffect(() => {
if (isOpen) {
document.addEventListener('keydown', handleEsc)
document.body.style.overflow = 'hidden'
}
return () => {
document.removeEventListener('keydown', handleEsc)
document.body.style.overflow = ''
}
if (!isOpen) return
document.addEventListener('keydown', handleEsc)
return () => document.removeEventListener('keydown', handleEsc)
}, [isOpen, handleEsc])
// Separate from the key listener so a new onClose identity does not release
// and re-take the lock on every render. The shared lock is ref-counted: this
// modal must not clear a lock another overlay is still holding (#1809).
useEffect(() => {
if (!isOpen) return
return lockBodyScroll()
}, [isOpen])
const mouseDownTarget = useRef<EventTarget | null>(null)
if (!isOpen) return null