fix(client): work through the findings from the coverage pass

214 items came out of writing the tests. Real defects are corrected, dead code
is removed rather than covered, and the tests that pinned the old behaviour
move with them.

Also drops two agent coverage scratch files that slipped into the coverage PR
and adds the ignore rule that keeps them out.
This commit is contained in:
Maurice
2026-07-29 11:57:24 +02:00
committed by Maurice
parent a4bf815d24
commit 72a82b3c44
425 changed files with 3155 additions and 1968 deletions
@@ -1,4 +1,4 @@
import React, { useCallback, useEffect, useState } from 'react'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { RefreshCw, ClipboardList } from 'lucide-react'
import { adminApi } from '../../../api/client'
import { useTranslation } from '../../../i18n'
@@ -24,8 +24,10 @@ export default function MAdminAuditLogPanel({ serverTimezone }: AuditLogPanelPro
const { t, locale } = useTranslation()
const [entries, setEntries] = useState<AuditEntry[]>([])
const [total, setTotal] = useState(0)
const [offset, setOffset] = useState(0)
const [loading, setLoading] = useState(true)
// Never rendered, only carried between pages — a ref keeps loadMore from
// capturing a page number that is already spent.
const offsetRef = useRef(0)
const limit = 100
const loadFirstPage = useCallback(async () => {
@@ -37,18 +39,18 @@ export default function MAdminAuditLogPanel({ serverTimezone }: AuditLogPanelPro
}
setEntries(data.entries || [])
setTotal(data.total ?? 0)
setOffset(0)
offsetRef.current = 0
} catch {
setEntries([])
setTotal(0)
setOffset(0)
offsetRef.current = 0
} finally {
setLoading(false)
}
}, [])
const loadMore = useCallback(async () => {
const nextOffset = offset + limit
const nextOffset = offsetRef.current + limit
setLoading(true)
try {
const data = (await adminApi.auditLog({ limit, offset: nextOffset })) as {
@@ -57,13 +59,13 @@ export default function MAdminAuditLogPanel({ serverTimezone }: AuditLogPanelPro
}
setEntries((prev) => [...prev, ...(data.entries || [])])
setTotal(data.total ?? 0)
setOffset(nextOffset)
offsetRef.current = nextOffset
} catch {
/* keep existing */
} finally {
setLoading(false)
}
}, [offset])
}, [])
useEffect(() => {
loadFirstPage()
@@ -85,7 +85,8 @@ export default function MAdminBackupPanel() {
const loadAutoSettings = async () => {
try {
const data = await backupApi.getAutoSettings()
setAutoSettings(data.settings)
// A 200 without a settings block would blank the whole schedule form.
if (data.settings) setAutoSettings(data.settings)
if (data.timezone) setServerTimezone(data.timezone)
} catch {}
}
@@ -170,7 +171,7 @@ export default function MAdminBackupPanel() {
setAutoSettingsSaving(true)
try {
const data = await backupApi.setAutoSettings(autoSettings)
setAutoSettings(data.settings)
if (data.settings) setAutoSettings(data.settings)
setAutoSettingsDirty(false)
toast.success(t('backup.toast.settingsSaved'))
} catch {
@@ -61,7 +61,6 @@ export default function MAdminCategoryManager() {
}
const handleSave = async () => {
if (!form.name.trim()) { toast.error(t('categories.toast.nameRequired')); return }
setIsSaving(true)
try {
if (editingId) {
@@ -5,7 +5,7 @@ import { useTranslation } from '../../../i18n'
import { useToast } from '../../../components/shared/Toast'
import { MapView } from '../../../components/Map/MapView'
import { SYMBOLS, currenciesWith } from '../../../components/Budget/BudgetPanel.constants'
import type { DistanceUnit, Place } from '../../../types'
import { getApiErrorMessage, type DistanceUnit, type Place } from '../../../types'
import {
MAPBOX_DEFAULT_STYLE,
defaultStyleForProvider,
@@ -89,7 +89,7 @@ export default function MAdminDefaultUserSettings(): React.ReactElement {
setDefaults(updated)
toast.success(t('admin.defaultSettings.saved'))
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : t('common.error'))
toast.error(getApiErrorMessage(err, t('common.error')))
}
}
@@ -105,7 +105,7 @@ export default function MAdminDefaultUserSettings(): React.ReactElement {
}
toast.success(t('admin.defaultSettings.reset'))
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : t('common.error'))
toast.error(getApiErrorMessage(err, t('common.error')))
}
}
@@ -144,7 +144,7 @@ export default function MAdminDefaultUserSettings(): React.ReactElement {
transport_mode: null,
website: null,
phone: null,
created_at: Date(),
created_at: new Date().toISOString(),
}], [])
if (!loaded) {
@@ -20,6 +20,42 @@ interface AppUser {
email: string
}
const SELECT_CLASS =
'mb-2 h-[42px] w-full rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 text-[0.84375rem] text-m-ink outline-none focus:border-[color:var(--m-faint)]'
function Btn({
id, label, sub, icon: Icon, color, sending, onClick,
}: {
id: string
label: string
sub: string
icon: LucideIcon
color: string
sending: string | null
onClick: () => void
}) {
return (
<button
type="button"
onClick={onClick}
disabled={sending !== null}
className="flex w-full items-center gap-3 rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 py-[11px] text-left disabled:opacity-50"
>
<span
className="flex h-8 w-8 flex-none items-center justify-center rounded-[10px]"
style={{ background: `${color}20`, color }}
>
<Icon className="h-4 w-4" />
</span>
<div className="min-w-0 flex-1">
<p className="text-[0.8125rem] font-bold text-m-ink">{label}</p>
<p className="truncate font-geist text-[0.625rem] text-m-faint">{sub}</p>
</div>
{sending === id && <Loader2 size={14} className="flex-none animate-spin text-m-faint" />}
</button>
)
}
// Dev-only notification testing panel, re-skinned to the mobile admin system.
// All state, fetches and fire() payloads are ported verbatim from the desktop
// DevNotificationsPanel — only the presentation layer changes.
@@ -50,8 +86,8 @@ export default function MAdminDevNotificationsPanel(): React.ReactElement {
try {
await adminApi.sendTestNotification(payload)
toast.success(`Sent: ${label}`)
} catch (err: any) {
toast.error(err.message || 'Failed')
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : 'Failed')
} finally {
setSending(null)
}
@@ -62,53 +98,6 @@ export default function MAdminDevNotificationsPanel(): React.ReactElement {
const username = user?.username || 'Admin'
const tripTitle = selectedTrip?.title || 'Test Trip'
// ── Helpers ──────────────────────────────────────────────────────────────
const Btn = ({
id, label, sub, icon: Icon, color, onClick,
}: {
id: string; label: string; sub: string; icon: LucideIcon; color: string; onClick: () => void
}) => (
<button
type="button"
onClick={onClick}
disabled={sending !== null}
className="flex w-full items-center gap-3 rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 py-[11px] text-left disabled:opacity-50"
>
<span
className="flex h-8 w-8 flex-none items-center justify-center rounded-[10px]"
style={{ background: `${color}20`, color }}
>
<Icon className="h-4 w-4" />
</span>
<div className="min-w-0 flex-1">
<p className="text-[0.8125rem] font-bold text-m-ink">{label}</p>
<p className="truncate font-geist text-[0.625rem] text-m-faint">{sub}</p>
</div>
{sending === id && <Loader2 size={14} className="flex-none animate-spin text-m-faint" />}
</button>
)
const TripSelector = () => (
<select
value={selectedTripId ?? ''}
onChange={e => setSelectedTripId(Number(e.target.value))}
className="mb-2 h-[42px] w-full rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 text-[0.84375rem] text-m-ink outline-none focus:border-[color:var(--m-faint)]"
>
{trips.map(trip => <option key={trip.id} value={trip.id}>{trip.title}</option>)}
</select>
)
const UserSelector = () => (
<select
value={selectedUserId ?? ''}
onChange={e => setSelectedUserId(Number(e.target.value))}
className="mb-2 h-[42px] w-full rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 text-[0.84375rem] text-m-ink outline-none focus:border-[color:var(--m-faint)]"
>
{users.map(u => <option key={u.id} value={u.id}>{u.username} ({u.email})</option>)}
</select>
)
return (
<div className="space-y-3">
{/* Dev header */}
@@ -128,7 +117,7 @@ export default function MAdminDevNotificationsPanel(): React.ReactElement {
hint="Test how each in-app notification type renders, sent to yourself."
/>
<div className="mt-2 grid grid-cols-1 gap-2">
<Btn id="simple-me" label="Simple → Me" sub="test_simple · user" icon={Bell} color="#6366f1"
<Btn sending={sending} id="simple-me" label="Simple → Me" sub="test_simple · user" icon={Bell} color="#6366f1"
onClick={() => fire('simple-me', {
event: 'test_simple',
scope: 'user',
@@ -136,7 +125,7 @@ export default function MAdminDevNotificationsPanel(): React.ReactElement {
params: {},
})}
/>
<Btn id="boolean-me" label="Boolean → Me" sub="test_boolean · user" icon={CheckCircle} color="#10b981"
<Btn sending={sending} id="boolean-me" label="Boolean → Me" sub="test_boolean · user" icon={CheckCircle} color="#10b981"
onClick={() => fire('boolean-me', {
event: 'test_boolean',
scope: 'user',
@@ -149,7 +138,7 @@ export default function MAdminDevNotificationsPanel(): React.ReactElement {
},
})}
/>
<Btn id="navigate-me" label="Navigate → Me" sub="test_navigate · user" icon={Navigation} color="#f59e0b"
<Btn sending={sending} id="navigate-me" label="Navigate → Me" sub="test_navigate · user" icon={Navigation} color="#f59e0b"
onClick={() => fire('navigate-me', {
event: 'test_navigate',
scope: 'user',
@@ -157,7 +146,7 @@ export default function MAdminDevNotificationsPanel(): React.ReactElement {
params: {},
})}
/>
<Btn id="simple-admins" label="Simple → All Admins" sub="test_simple · admin" icon={Zap} color="#ef4444"
<Btn sending={sending} id="simple-admins" label="Simple → All Admins" sub="test_simple · admin" icon={Zap} color="#ef4444"
onClick={() => fire('simple-admins', {
event: 'test_simple',
scope: 'admin',
@@ -176,9 +165,15 @@ export default function MAdminDevNotificationsPanel(): React.ReactElement {
hint="Fires each trip event to all members of the selected trip (excluding yourself)."
/>
<div className="mt-2">
<TripSelector />
<select
value={selectedTripId ?? ''}
onChange={e => setSelectedTripId(Number(e.target.value))}
className={SELECT_CLASS}
>
{trips.map(trip => <option key={trip.id} value={trip.id}>{trip.title}</option>)}
</select>
<div className="grid grid-cols-1 gap-2">
<Btn id="booking_change" label="booking_change" sub="navigate · trip" icon={Calendar} color="#6366f1"
<Btn sending={sending} id="booking_change" label="booking_change" sub="navigate · trip" icon={Calendar} color="#6366f1"
onClick={() => selectedTripId && fire('booking_change', {
event: 'booking_change',
scope: 'trip',
@@ -186,7 +181,7 @@ export default function MAdminDevNotificationsPanel(): React.ReactElement {
params: { actor: username, trip: tripTitle, booking: 'Test Hotel', type: 'hotel', tripId: String(selectedTripId) },
})}
/>
<Btn id="trip_reminder" label="trip_reminder" sub="navigate · trip" icon={Clock} color="#10b981"
<Btn sending={sending} id="trip_reminder" label="trip_reminder" sub="navigate · trip" icon={Clock} color="#10b981"
onClick={() => selectedTripId && fire('trip_reminder', {
event: 'trip_reminder',
scope: 'trip',
@@ -194,7 +189,7 @@ export default function MAdminDevNotificationsPanel(): React.ReactElement {
params: { trip: tripTitle, tripId: String(selectedTripId) },
})}
/>
<Btn id="photos_shared" label="photos_shared" sub="navigate · trip" icon={Image} color="#f59e0b"
<Btn sending={sending} id="photos_shared" label="photos_shared" sub="navigate · trip" icon={Image} color="#f59e0b"
onClick={() => selectedTripId && fire('photos_shared', {
event: 'photos_shared',
scope: 'trip',
@@ -202,7 +197,7 @@ export default function MAdminDevNotificationsPanel(): React.ReactElement {
params: { actor: username, trip: tripTitle, count: '5', tripId: String(selectedTripId) },
})}
/>
<Btn id="collab_message" label="collab_message" sub="navigate · trip" icon={MessageSquare} color="#8b5cf6"
<Btn sending={sending} id="collab_message" label="collab_message" sub="navigate · trip" icon={MessageSquare} color="#8b5cf6"
onClick={() => selectedTripId && fire('collab_message', {
event: 'collab_message',
scope: 'trip',
@@ -210,7 +205,7 @@ export default function MAdminDevNotificationsPanel(): React.ReactElement {
params: { actor: username, trip: tripTitle, preview: 'This is a test message preview.', tripId: String(selectedTripId) },
})}
/>
<Btn id="packing_tagged" label="packing_tagged" sub="navigate · trip" icon={Tag} color="#ec4899"
<Btn sending={sending} id="packing_tagged" label="packing_tagged" sub="navigate · trip" icon={Tag} color="#ec4899"
onClick={() => selectedTripId && fire('packing_tagged', {
event: 'packing_tagged',
scope: 'trip',
@@ -231,9 +226,16 @@ export default function MAdminDevNotificationsPanel(): React.ReactElement {
hint="Fires each user event to the selected recipient."
/>
<div className="mt-2">
<UserSelector />
<select
value={selectedUserId ?? ''}
onChange={e => setSelectedUserId(Number(e.target.value))}
className={SELECT_CLASS}
>
{users.map(u => <option key={u.id} value={u.id}>{u.username} ({u.email})</option>)}
</select>
<div className="grid grid-cols-1 gap-2">
<Btn
sending={sending}
id={`trip_invite-${selectedUserId}`}
label="trip_invite"
sub="navigate · user"
@@ -247,6 +249,7 @@ export default function MAdminDevNotificationsPanel(): React.ReactElement {
})}
/>
<Btn
sending={sending}
id={`vacay_invite-${selectedUserId}`}
label="vacay_invite"
sub="navigate · user"
@@ -271,7 +274,7 @@ export default function MAdminDevNotificationsPanel(): React.ReactElement {
hint="Fires to all admin users."
/>
<div className="mt-2 grid grid-cols-1 gap-2">
<Btn id="version_available" label="version_available" sub="navigate · admin" icon={Download} color="#64748b"
<Btn sending={sending} id="version_available" label="version_available" sub="navigate · admin" icon={Download} color="#64748b"
onClick={() => fire('version_available', {
event: 'version_available',
scope: 'admin',
@@ -6,6 +6,7 @@ import { MAdminButton, MAdminCard } from './MAdminUi'
const REPO = 'mauriceboe/TREK'
const PER_PAGE = 10
const MAX_PAGES_PER_LOAD = 5
interface GithubRelease {
id: number
@@ -39,27 +40,49 @@ export default function MAdminGitHubPanel({ isPrerelease = false }: { isPrerelea
const [hasMore, setHasMore] = useState(true)
const [loadingMore, setLoadingMore] = useState(false)
const fetchReleases = async (pageNum = 1, append = false) => {
const isShown = (release: GithubRelease) => isPrerelease || !release.prerelease
const fetchPage = async (pageNum: number) => {
try {
const res = await apiClient.get(`/admin/github-releases`, { params: { per_page: PER_PAGE, page: pageNum } })
const data = Array.isArray(res.data) ? res.data : []
setReleases(prev => append ? [...prev, ...data] : data)
setHasMore(data.length === PER_PAGE)
return Array.isArray(res.data) ? res.data as GithubRelease[] : []
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'Unknown error')
return null
}
}
// Keep pulling pages until at least one release survives the prerelease filter,
// otherwise a page of nothing but prereleases leaves an empty timeline behind a
// "Load more" button. MAX_PAGES_PER_LOAD bounds the walk.
const loadFrom = async (startPage: number, append: boolean) => {
const collected: GithubRelease[] = []
let pageNum = startPage
let more = true
for (let i = 0; i < MAX_PAGES_PER_LOAD; i++) {
const data = await fetchPage(pageNum)
if (!data) return
collected.push(...data)
more = data.length === PER_PAGE
if (!more || collected.some(isShown)) break
pageNum += 1
}
setReleases(prev => append ? [...prev, ...collected] : collected)
setHasMore(more)
setPage(pageNum)
setError(null)
}
useEffect(() => {
setLoading(true)
fetchReleases(1).finally(() => setLoading(false))
loadFrom(1, false).finally(() => setLoading(false))
}, [])
const handleLoadMore = async () => {
const next = page + 1
setLoadingMore(true)
await fetchReleases(next, true)
setPage(next)
await loadFrom(page + 1, true)
setLoadingMore(false)
}
@@ -152,7 +175,7 @@ export default function MAdminGitHubPanel({ isPrerelease = false }: { isPrerelea
{ href: 'https://github.com/mauriceboe/TREK/wiki', color: '#6366f1', icon: <BookOpen size={18} className="text-[#6366f1]" />, title: 'Wiki', sub: t('settings.about.wikiHint') },
]
const shownReleases = isPrerelease ? releases : releases.filter(r => !r.prerelease)
const shownReleases = releases.filter(isShown)
return (
<div className="space-y-3">
@@ -188,7 +211,7 @@ export default function MAdminGitHubPanel({ isPrerelease = false }: { isPrerelea
<Loader2 className="h-6 w-6 animate-spin text-m-muted" />
</div>
</MAdminCard>
) : error ? (
) : error && releases.length === 0 ? (
<MAdminCard>
<div className="py-4 text-center">
<p className="text-[0.8125rem] text-m-muted">{t('admin.github.error')}</p>
@@ -301,6 +324,13 @@ export default function MAdminGitHubPanel({ isPrerelease = false }: { isPrerelea
</div>
</div>
{/* A failed "Load more" keeps the timeline and stays retryable */}
{error && (
<p className="pb-1 text-center font-geist text-[0.625rem] text-m-faint">
{t('admin.github.error')} — {error}
</p>
)}
{/* Load more */}
{hasMore && (
<div className="pt-1 text-center">
@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react'
import { useState, useEffect, useRef } from 'react'
import { Key, Trash2, User, Loader2, Shield } from 'lucide-react'
import { adminApi } from '../../../api/client'
import { useToast } from '../../../components/shared/Toast'
@@ -52,15 +52,20 @@ export default function MAdminMcpTokensPanel() {
const toast = useToast()
const { t, locale } = useTranslation()
// The loader runs once, but a language switch while the requests are in flight
// must still toast in the current locale — hence the ref instead of the closure.
const latest = useRef({ t, toast })
latest.current = { t, toast }
useEffect(() => {
adminApi.oauthSessions()
.then(d => setSessions(d.sessions || []))
.catch(() => toast.error(t('admin.oauthSessions.loadError')))
.catch(() => latest.current.toast.error(latest.current.t('admin.oauthSessions.loadError')))
.finally(() => setSessionsLoading(false))
adminApi.mcpTokens()
.then(d => setTokens(d.tokens || []))
.catch(() => toast.error(t('admin.mcpTokens.loadError')))
.catch(() => latest.current.toast.error(latest.current.t('admin.mcpTokens.loadError')))
.finally(() => setTokensLoading(false))
}, [])
@@ -119,7 +119,6 @@ export default function MAdminNotificationsSection({ admin, t }: MAdminNotificat
const testAdminWebhook = async () => {
const url = smtpValues.admin_webhook_url === '••••••••' ? undefined : smtpValues.admin_webhook_url
if (!url && smtpValues.admin_webhook_url !== '••••••••') return
try {
if (url) await authApi.updateAppSettings({ admin_webhook_url: url }).catch(() => {})
const result = await notificationsApi.testWebhook(url)
@@ -77,16 +77,18 @@ export default function MAdminNotifyMatrix({ t, toast }: { t: TranslationFn; toa
key={ch}
className="w-[44px] flex-none text-center font-geist text-[0.5625rem] font-bold uppercase tracking-[0.04em] text-m-faint"
>
{t(ADMIN_CHANNEL_LABEL_KEYS[ch]) || ch}
{t(ADMIN_CHANNEL_LABEL_KEYS[ch])}
</span>
))}
</div>
{matrix.event_types.map((eventType) => {
const implemented = matrix.implemented_combos[eventType] ?? []
// Only version_available has a label key so far; anything else keeps its raw id.
const labelKey = ADMIN_EVENT_LABEL_KEYS[eventType]
return (
<div key={eventType} className="flex items-center gap-1 border-b border-[color:var(--m-rowbr)] py-2">
<span className="min-w-0 flex-1 truncate text-[0.8125rem] text-m-ink">
{t(ADMIN_EVENT_LABEL_KEYS[eventType]) || eventType}
{labelKey ? t(labelKey) : eventType}
</span>
{visibleChannels.map((ch) => (
<span key={ch} className="flex w-[44px] flex-none justify-center">
@@ -162,7 +162,7 @@ export default function MAdminPackingTemplateManager() {
await adminApi.deleteTemplateCategory(expandedId, catId)
setCategories(prev => prev.filter(c => c.id !== catId))
setItems(prev => prev.filter(i => i.category_id !== catId))
} catch { toast.error(t('admin.packingTemplates.deleteError')) }
} catch { toast.error(t('admin.toast.deleteError')) }
}
// Item CRUD
@@ -190,7 +190,7 @@ export default function MAdminPackingTemplateManager() {
try {
await adminApi.deleteTemplateItem(expandedId, itemId)
setItems(prev => prev.filter(i => i.id !== itemId))
} catch { toast.error(t('admin.packingTemplates.deleteError')) }
} catch { toast.error(t('admin.toast.deleteError')) }
}
return (
@@ -107,6 +107,8 @@ interface RegistryDetail extends RegistryItem {
icon: string | null
requiredAddons?: string[]
pluginDependencies?: PluginDep[]
/** Display slice of the manifest's capabilities — drives the same chips as an installed row. */
capabilities?: { widget?: { slot?: string }; tripPage?: { replaces?: string[] } }
} | null
}
@@ -309,13 +311,8 @@ const CHIP_PENDING = 'text-[color:var(--m-st-pending)] border-[color:color-mix(i
const PENDING_CARD = 'border-[color:color-mix(in_srgb,var(--m-st-pending)_28%,transparent)] bg-[color:color-mix(in_srgb,var(--m-st-pending)_10%,transparent)]'
const ACT_PILL = 'inline-flex flex-none items-center justify-center gap-[5px] whitespace-nowrap rounded-full px-3 py-[7px] text-[0.6875rem] font-bold bg-m-act text-m-actfg disabled:opacity-50'
function ReviewedBadge({ t, compact }: { t: T; compact?: boolean }) {
if (compact) return <ShieldCheck size={13} className="shrink-0 text-[color:var(--m-st-confirmed)]" aria-label={t('admin.plugins.reviewed')} />
return (
<span className="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-semibold text-[color:var(--m-st-confirmed)] bg-[color:color-mix(in_srgb,var(--m-st-confirmed)_14%,transparent)]">
<ShieldCheck size={11} /> {t('admin.plugins.reviewed')}
</span>
)
function ReviewedBadge({ t }: { t: T }) {
return <ShieldCheck size={13} className="shrink-0 text-[color:var(--m-st-confirmed)]" aria-label={t('admin.plugins.reviewed')} />
}
/** Marks a manually-uploaded (sideloaded) plugin: no registry, unsigned, not reviewed. */
@@ -533,7 +530,12 @@ export default function MAdminPluginsPanel() {
if (!runtimeOn || !Array.from(e.dataTransfer.types).includes('Files')) return
e.preventDefault(); dragDepth.current++; setDragActive(true)
}
const onDragLeave = () => { if (--dragDepth.current <= 0) { dragDepth.current = 0; setDragActive(false) } }
// Mirrors onDragEnter: a leave that had no matching enter (a non-file drag) is ignored
// instead of driving the depth counter negative.
const onDragLeave = () => {
if (dragDepth.current === 0) return
if (--dragDepth.current === 0) setDragActive(false)
}
const onDrop = (e: DragEvent) => {
e.preventDefault(); dragDepth.current = 0; setDragActive(false)
if (!runtimeOn) return
@@ -1146,7 +1148,7 @@ function InstalledRow({ p, t, busy, hasUpdate, latestVer, blocked, onToggle, onU
<div className="flex flex-wrap items-center gap-2">
<span className="text-[0.90625rem] font-bold tracking-[-.006em] text-m-ink">{p.name}</span>
{p.version && <span className="text-[11.5px] font-medium tabular-nums text-m-faint">v{p.version}</span>}
{p.reviewed_at && <ReviewedBadge t={t} compact />}
{p.reviewed_at && <ReviewedBadge t={t} />}
{p.source_repo === 'local:upload' && <SideloadedBadge t={t} />}
{p.source_repo === 'local:link' && <DevLinkBadge t={t} />}
{/* Registry plugins only — a sideloaded/dev-linked plugin already says something
@@ -1395,7 +1397,7 @@ function PluginDetailSheet({ item, installed, busy, onInstall, onClose, t, local
}, [item.id])
const manifest = detail?.manifest ?? null
const caps = manifest ? deriveCaps(manifest.permissions, {}, t) : []
const caps = manifest ? deriveCaps(manifest.permissions, manifest.capabilities ?? {}, t) : []
const repoUrl = `https://github.com/${item.repo}`
const homepage = item.homepage && /^https?:\/\//i.test(item.homepage) && item.homepage !== repoUrl ? item.homepage : null
const sizeKb = detail?.size ? Math.max(1, Math.round(detail.size / 1024)) : null
@@ -1421,7 +1423,7 @@ function PluginDetailSheet({ item, installed, busy, onInstall, onClose, t, local
<div className="min-w-0 flex-1 pt-8">
<div className="flex flex-wrap items-center gap-2">
<h3 className="text-lg font-bold tracking-tight text-m-ink">{item.name}</h3>
{item.reviewedAt && <ReviewedBadge t={t} compact />}
{item.reviewedAt && <ReviewedBadge t={t} />}
</div>
<p className="mt-0.5 text-[12.5px] text-m-faint">{item.author}{item.latest ? ` · v${item.latest}` : ''}</p>
</div>
@@ -210,7 +210,7 @@ export default function MAdminSheets({ admin, t }: MAdminSheetsProps) {
</p>
{updateInfo?.is_docker === false ? (
<a
href="https://github.com/mauriceboe/TREK/wiki/Updating"
href="https://github.com/liketrek/TREK/wiki/Updating"
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-2 rounded-xl bg-[color:var(--m-ic)] px-3 py-3 text-[0.8125rem] font-bold text-m-ink underline"
@@ -5,7 +5,6 @@ import apiClient from '../../../api/client'
import { continentForCountry } from '@trek/shared'
import { getApiErrorMessage } from '../../../types'
import { useToast } from '../../../components/shared/Toast'
import { countryCodeToFlag } from '../../../pages/atlas/atlasModel'
import MSheet from '../../components/MSheet'
import type { AtlasController } from './atlasController'
@@ -134,12 +133,15 @@ export default function MAtlasCountryPopup({ atlas }: MAtlasCountryPopupProps) {
if (remaining.length === 0) delete next[countryCode]
return next
})
// Drop the country too once no manually-marked region and no trip/place keeps it.
// Drop the country too once no visible region is left — how a region was
// derived does not matter, the server hides it either way. Countries with
// real place/trip data are never hidden server-side (#1490), so removing
// them here would only flash and reappear on the next load.
setData((prev) => {
if (!prev) return prev
const c = prev.countries.find((c) => c.code === countryCode)
if (!c || c.placeCount > 0 || c.tripCount > 0) return prev
const remainingRegions = (visitedRegions[countryCode] || []).filter((r) => r.code !== regionCode && r.manuallyMarked)
const remainingRegions = (visitedRegions[countryCode] || []).filter((r) => r.code !== regionCode)
if (remainingRegions.length > 0) return prev
const cont = continentForCountry(countryCode)
return {
@@ -184,7 +186,10 @@ export default function MAtlasCountryPopup({ atlas }: MAtlasCountryPopupProps) {
className="h-[34px] w-12 rounded-[6px] object-cover shadow-[0_1px_3px_rgba(0,0,0,.25)]"
/>
) : (
<span className="text-[2.25rem] leading-none">{countryCodeToFlag(a.code)}</span>
// flagcdn only serves alpha-2, so anything else gets a neutral placeholder.
<span className="flex h-[34px] w-12 items-center justify-center rounded-[6px] bg-[color:var(--m-ic)] text-m-faint">
<MapPin size={18} strokeWidth={2} />
</span>
)}
<div className="mt-3 text-[1.0625rem] font-extrabold text-m-ink">{a.name}</div>
{a.countryName && (a.type === 'choose-region' || a.type === 'unmark-region') && (
@@ -6,7 +6,7 @@ import { mapsApi } from '../../../api/client'
import { collectionsApi } from '../../../api/collections'
import { useTranslation } from '../../../i18n'
import { useToast } from '../../../components/shared/Toast'
import { getApiErrorMessage } from '../../../types'
import { getApiErrorMessage } from '../../../utils/apiError'
import { STATUS_ORDER } from '../../../pages/collections/collectionsModel'
import MSheet from '../../components/MSheet'
import MCollCategoryPicker from './MCollCategoryPicker'
@@ -51,14 +51,18 @@ export default function MCollAddSheet({ open, collectionId, collectionName, list
useEffect(() => {
if (open) return
setQuery(''); setResults([]); setPicked(null); setName(''); setCategoryId(null); setStatus('idea'); setDescription('')
setTargetId(null)
}, [open])
// Opened from a specific list → target is fixed; from "All Saved" (no active
// list) → default to the sole list if there is one, else pick it in-sheet.
// The lists may still be loading when the sheet opens, so the default is
// applied again once they arrive — without overruling a pick already made.
useEffect(() => {
if (open) setTargetId(collectionId ?? (lists.length === 1 ? lists[0].id : null))
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, collectionId])
if (!open) return
if (collectionId != null) { setTargetId(collectionId); return }
setTargetId(prev => (prev != null && lists.some(l => l.id === prev) ? prev : (lists.length === 1 ? lists[0].id : null)))
}, [open, collectionId, lists])
const search = async () => {
if (!query.trim() || searching) return
@@ -5,7 +5,7 @@ import type { TranslationFn } from '../../../types'
import { tripsApi } from '../../../api/client'
import { useCollectionStore } from '../../../store/collectionStore'
import { useToast } from '../../../components/shared/Toast'
import { getApiErrorMessage } from '../../../types'
import { getApiErrorMessage } from '../../../utils/apiError'
import { normalizeLinkUrl } from '../../../pages/collections/collectionsModel'
import MSheet from '../../components/MSheet'
import MCollLinksEditor from './MCollLinksEditor'
@@ -91,6 +91,13 @@ export default function MCollEditSheet({ target, onClose, onCreated, onRequestDe
useEffect(() => () => dropObjectUrl(), [])
// A create that only failed at the cover step already produced the list —
// hand it over on the way out instead of leaving it behind unnoticed.
const close = () => {
if (createdId != null) onCreated(createdId)
onClose()
}
const pickCover = (file: File | undefined) => {
if (!file) return
dropObjectUrl()
@@ -164,13 +171,13 @@ export default function MCollEditSheet({ target, onClose, onCreated, onRequestDe
return (
<MSheet
open={target != null}
onClose={onClose}
onClose={close}
material="opaque"
ariaLabel={editing ? t('collections.editListTitle') : t('collections.newList')}
>
<SheetHeader
title={editing ? t('collections.editListTitle') : t('collections.newList')}
onClose={onClose}
onClose={close}
closeLabel={t('common.close')}
/>
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] py-[14px]">
@@ -271,7 +278,7 @@ export default function MCollEditSheet({ target, onClose, onCreated, onRequestDe
<Trash2 size={13} strokeWidth={2} /> {t('collections.deleteList')}
</button>
)}
<CancelPill className="ml-auto" onClick={onClose}>{t('common.cancel')}</CancelPill>
<CancelPill className="ml-auto" onClick={close}>{t('common.cancel')}</CancelPill>
<PrimaryPill onClick={save} disabled={!name.trim() || saving}>
{saving && <Loader2 size={14} className="animate-spin" />}
{editing ? t('common.save') : t('collections.create')}
@@ -66,6 +66,16 @@ export default function MCollLabelsSheet({
}
}
const remove = async (labelId: number) => {
if (busy) return
setBusy(true)
try {
await onDelete(labelId)
} finally {
setBusy(false)
}
}
const assign = async () => {
if (checked.length === 0 || busy) return
setBusy(true)
@@ -160,9 +170,10 @@ export default function MCollLabelsSheet({
</button>
<button
type="button"
onClick={() => onDelete(label.id)}
onClick={() => remove(label.id)}
disabled={busy}
aria-label={t('common.delete')}
className="flex h-7 w-7 flex-none items-center justify-center rounded-full text-[color:var(--m-st-danger)] active:bg-[color:var(--m-ic)]"
className="flex h-7 w-7 flex-none items-center justify-center rounded-full text-[color:var(--m-st-danger)] active:bg-[color:var(--m-ic)] disabled:opacity-40"
>
<Trash2 size={13} strokeWidth={2.2} />
</button>
@@ -32,6 +32,8 @@ export default function MCollListPickerSheet({ mode, lists, count, onPick, onClo
setBusyId(id)
try {
await onPick(id)
} catch {
// The caller reports its own failures; the sheet only releases the row.
} finally {
setBusyId(null)
}
@@ -1,125 +0,0 @@
import { Check, Layers, Plus, X } from 'lucide-react'
import type { Collection } from '@trek/shared'
import type { TranslationFn } from '../../../types'
import type { ActiveCollectionId } from '../../../store/collectionStore'
import type { IncomingCollectionInvite } from '../../../store/collectionStore'
import { ALL_SAVED } from '../../../store/collectionStore'
import MSheet from '../../components/MSheet'
import { Eyebrow } from './MCollSheetKit'
interface MCollListsDrawerProps {
open: boolean
onClose: () => void
ownedLists: Collection[]
sharedLists: Collection[]
activeId: ActiveCollectionId
incomingInvites: IncomingCollectionInvite[]
onSelect: (id: ActiveCollectionId) => void
onNewList: () => void
onAcceptInvite: (collectionId: number) => void
onDeclineInvite: (collectionId: number) => void
t: TranslationFn
}
function ListRow({ list, active, onClick }: { list: Collection; active: boolean; onClick: () => void }) {
return (
<button
type="button"
onClick={onClick}
className={`mb-1 flex w-full items-center gap-[10px] rounded-[13px] px-3 py-[11px] text-left ${active ? 'bg-[color:var(--m-ic)]' : ''}`}
style={active ? { boxShadow: `inset 0 0 0 1.5px ${list.color || '#6366F1'}` } : undefined}
>
<span className="h-[9px] w-[9px] flex-none rounded-full" style={{ background: list.color || '#6366F1' }} />
<span className="min-w-0 flex-1 truncate text-[0.84375rem] font-semibold text-m-ink">{list.name}</span>
<span className="font-geist text-[0.6875rem] font-bold text-m-faint">{list.place_count ?? 0}</span>
</button>
)
}
/**
* The left lists drawer: new list, the "All saved" union, the owned and shared
* lists, and — when present — incoming share invites with accept/decline.
*/
export default function MCollListsDrawer({
open, onClose, ownedLists, sharedLists, activeId, incomingInvites,
onSelect, onNewList, onAcceptInvite, onDeclineInvite, t,
}: MCollListsDrawerProps) {
return (
<MSheet open={open} onClose={onClose} variant="drawer" material="opaque" ariaLabel={t('collections.title')}>
<div className="flex h-full min-h-0 flex-col px-[18px] py-5">
<div className="flex flex-none justify-end">
<button
type="button"
onClick={onClose}
aria-label={t('common.close')}
className="flex h-8 w-8 items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-ink"
>
<X size={15} strokeWidth={2.2} />
</button>
</div>
<button
type="button"
onClick={onNewList}
className="mt-[6px] flex flex-none items-center gap-2 rounded-[14px] border border-dashed border-[color:var(--m-rowbr)] px-[14px] py-3 text-[0.8125rem] font-bold text-m-muted"
>
<Plus size={15} strokeWidth={2.2} /> {t('collections.newList')}
</button>
<button
type="button"
onClick={() => onSelect(ALL_SAVED)}
className={`mt-[10px] flex flex-none items-center gap-[9px] rounded-[11px] px-[6px] py-[10px] text-[0.84375rem] font-semibold text-m-ink ${activeId === ALL_SAVED ? 'bg-[color:var(--m-ic)]' : ''}`}
>
<Layers size={16} strokeWidth={2} /> {t('collections.allSaved')}
</button>
<div className="my-2 h-px flex-none bg-[color:var(--m-rowbr)]" />
<div className="min-h-0 flex-1 overflow-y-auto">
{ownedLists.map(l => (
<ListRow key={l.id} list={l} active={activeId === l.id} onClick={() => onSelect(l.id)} />
))}
{sharedLists.length > 0 && (
<>
<Eyebrow className="mb-[6px] mt-3 px-1 uppercase">{t('collections.shared')}</Eyebrow>
{sharedLists.map(l => (
<ListRow key={l.id} list={l} active={activeId === l.id} onClick={() => onSelect(l.id)} />
))}
</>
)}
{incomingInvites.length > 0 && (
<>
<Eyebrow className="mb-[6px] mt-3 px-1 uppercase">{t('collections.invites.title')}</Eyebrow>
{incomingInvites.map(inv => (
<div
key={inv.collection_id}
className="mb-1 flex items-center gap-[10px] rounded-[13px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheet)] px-3 py-[10px]"
>
<span className="min-w-0 flex-1">
<span className="block truncate text-[0.8125rem] font-semibold text-m-ink">{inv.name}</span>
<span className="block truncate font-geist text-[0.625rem] text-m-muted">
{t('collections.invites.from')} {inv.from.username}
</span>
</span>
<button
type="button"
onClick={() => onAcceptInvite(inv.collection_id)}
aria-label={t('collections.invites.accept')}
className="flex h-7 w-7 flex-none items-center justify-center rounded-full bg-m-act text-m-actfg"
>
<Check size={13} strokeWidth={2.6} />
</button>
<button
type="button"
onClick={() => onDeclineInvite(inv.collection_id)}
aria-label={t('collections.invites.decline')}
className="flex h-7 w-7 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-ink"
>
<X size={13} strokeWidth={2.4} />
</button>
</div>
))}
</>
)}
</div>
</div>
</MSheet>
)
}
@@ -8,7 +8,7 @@ import type { Category, TranslationFn } from '../../../types'
import { mapsApi } from '../../../api/client'
import { useToast } from '../../../components/shared/Toast'
import { normalizeImageFile } from '../../../utils/convertHeic'
import { getApiErrorMessage } from '../../../types'
import { getApiErrorMessage } from '../../../utils/apiError'
import { normalizeLinkUrl, STATUS_ORDER } from '../../../pages/collections/collectionsModel'
import MSheet from '../../components/MSheet'
import PlaceRating from '../../../components/shared/StarRating'
@@ -58,7 +58,7 @@ export default function MDashboard(): React.ReactElement {
spotlight, upcoming, gridTrips, isLoading, loadError, retryLoad,
tripFilter, setTripFilter, viewMode, toggleViewMode,
showForm, setShowForm, editingTrip, setEditingTrip,
deleteTrip, setDeleteTrip, copyTrip, setCopyTrip, setTrips,
deleteTrip, setDeleteTrip, copyTrip, setCopyTrip, applyCoverUpdate,
handleCreate, handleUpdate, confirmDelete, handleArchive, handleUnarchive, confirmCopy,
} = useDashboard()
@@ -287,7 +287,7 @@ export default function MDashboard(): React.ReactElement {
trip={editingTrip}
onClose={() => { setShowForm(false); setEditingTrip(null) }}
onSave={editingTrip ? handleUpdate : handleCreate}
onCoverUpdate={(tripId, coverUrl) => setTrips(prev => prev.map(tr => tr.id === tripId ? { ...tr, cover_image: coverUrl } : tr))}
onCoverUpdate={applyCoverUpdate}
onArchive={editingTrip
? () => (editingTrip.is_archived ? handleUnarchive(editingTrip.id) : handleArchive(editingTrip.id))
: undefined}
@@ -215,11 +215,12 @@ export default function MNewTripSheet({ open, trip, onClose, onSave, onCoverUpda
setCoverPreview(null)
return
}
if (!trip?.id) return
// Anything else is a cover stored on the trip, so this is the edit sheet.
const id = trip!.id
try {
await tripsApi.update(trip.id, { cover_image: null })
await tripsApi.update(id, { cover_image: null })
setCoverPreview(null)
onCoverUpdate?.(trip.id, null)
onCoverUpdate?.(id, null)
} catch {
toast.error(t('dashboard.coverRemoveError'))
}
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { ChevronLeft, MapPin, Grid3x3, Upload, MoreHorizontal, Play, Image, Camera } from 'lucide-react'
import JourneyMap from '../../../components/Journey/JourneyMapAuto'
import type { JourneyMapAutoHandle } from '../../../components/Journey/JourneyMapAuto'
@@ -47,7 +47,12 @@ export default function MJourneyDetail() {
const cardRefs = useRef<Map<number, HTMLDivElement>>(new Map())
const [activeIndex, setActiveIndex] = useState(0)
const entries = (current?.entries || []).filter(e => !hideSkeletons || e.type !== 'skeleton')
// Stable identity: the scroll effect below re-attaches on every change and
// would otherwise drop the pending settle timer on any unrelated render.
const entries = useMemo(
() => (current?.entries || []).filter(e => !hideSkeletons || e.type !== 'skeleton'),
[current?.entries, hideSkeletons],
)
const syncMapToCard = useCallback((index: number) => {
const entry = entries[index]
@@ -149,7 +149,9 @@ export default function MPhotoProvidersSection(): React.ReactElement {
...prev,
[provider.id]: { ...(prev[provider.id] || {}), ...nextValues },
}))
if (typeof res.data?.connected === 'boolean') {
// The status route owns the badge when there is one — otherwise the two
// responses would race and the later one would win.
if (!cfg.status_get && typeof res.data?.connected === 'boolean') {
setProviderConnected(prev => ({ ...prev, [provider.id]: !!res.data.connected }))
}
}).catch(() => { })
@@ -206,7 +208,8 @@ export default function MPhotoProvidersSection(): React.ReactElement {
if (ok) {
toast.success(t('memories.connectionSuccess', { provider_name: provider.name }))
} else {
toast.error(`${t('memories.connectionError', { provider_name: provider.name })} ${res.data?.error ? `: ${String(res.data.error)}` : ''}`)
const detail = res.data?.error ? `: ${String(res.data.error)}` : ''
toast.error(`${t('memories.connectionError', { provider_name: provider.name })}${detail}`)
}
} catch {
toast.error(t('memories.connectionError', { provider_name: provider.name }))
@@ -113,7 +113,6 @@ export default function MSettingsAccount() {
}
const copyBackupCodes = async () => {
if (!backupCodesText) return
try {
await navigator.clipboard.writeText(backupCodesText)
toast.success(t('settings.mfa.backupCopied'))
@@ -123,7 +122,6 @@ export default function MSettingsAccount() {
}
const downloadBackupCodes = () => {
if (!backupCodesText) return
const blob = new Blob([backupCodesText + '\n'], { type: 'text/plain;charset=utf-8' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
@@ -136,7 +134,6 @@ export default function MSettingsAccount() {
}
const printBackupCodes = () => {
if (!backupCodesText) return
const html = `<!doctype html><html><head><meta charset="utf-8"/><title>TREK MFA Backup Codes</title>
<style>body{font-family:Arial,sans-serif;padding:32px}h1{font-size:20px}pre{font-size:16px;line-height:1.6}</style>
</head><body><h1>TREK MFA Backup Codes</h1><p>${new Date().toLocaleString()}</p><pre>${backupCodesText}</pre></body></html>`
@@ -166,7 +163,7 @@ export default function MSettingsAccount() {
await deleteAvatar()
toast.success(t('settings.avatarRemoved'))
} catch {
toast.error(t('settings.avatarError'))
toast.error(t('settings.avatarRemoveError'))
}
}
@@ -565,10 +562,6 @@ function MPasskeysCard({ demoMode }: { demoMode?: boolean }): React.ReactElement
const canAdd = enabled && configured
const handleAdd = async () => {
if (!addPwd) {
toast.error(t('settings.passkey.passwordRequired'))
return
}
setBusy(true)
try {
const options = await authApi.passkey.registerOptions(addPwd)
@@ -603,10 +596,6 @@ function MPasskeysCard({ demoMode }: { demoMode?: boolean }): React.ReactElement
}
const handleDelete = async (id: number) => {
if (!deletePwd) {
toast.error(t('settings.passkey.passwordRequired'))
return
}
setBusy(true)
try {
await authApi.passkey.delete(id, deletePwd)
@@ -125,9 +125,12 @@ export default function MSettingsMcp() {
}
}, [])
// Re-read after create/rotate so the rows show what the server actually stored.
const reloadClients = () => oauthApi.clients.list().then((d) => setClients(d.clients || [])).catch(() => {})
useEffect(() => {
authApi.mcpTokens.list().then((d) => setTokens(d.tokens || [])).catch(() => {})
oauthApi.clients.list().then((d) => setClients(d.clients || [])).catch(() => {})
reloadClients()
oauthApi.sessions.list().then((d) => setSessions(d.sessions || [])).catch(() => {})
}, [])
@@ -180,7 +183,7 @@ export default function MSettingsMcp() {
...(isMachine ? { allows_client_credentials: true } : {}),
})
setCreatedClient(d.client)
setClients((prev) => [...prev, { ...d.client, client_secret: undefined }])
await reloadClients()
setNewName('')
setNewUris('')
setNewScopes([])
@@ -209,6 +212,7 @@ export default function MSettingsMcp() {
const d = await oauthApi.clients.rotate(id)
setRotatedSecret(d.client_secret)
setRotateId(null)
await reloadClients()
} catch {
toast.error(t('settings.oauth.toast.rotateError'))
} finally {
@@ -150,14 +150,14 @@ function PluginSettingsForm({ id, name, icon }: { id: string; name: string; icon
}
}
const pickerField = (fields ?? []).find(f => f.key === pickerKey && f.input_type === 'select' && !!f.options)
const pickerField = fields.find(f => f.key === pickerKey && f.input_type === 'select' && !!f.options)
return (
<>
<MSetCard title={name} icon={resolvePluginIcon(icon)}>
{hasFields && (
<div className="flex flex-col gap-[14px]">
{(fields ?? []).map(f => {
{fields.map(f => {
const requiredMark = f.required ? <span className="text-[color:var(--m-st-danger)]"> *</span> : null
if (f.input_type === 'checkbox') {
return (
@@ -20,11 +20,20 @@ const STEPS: { scene: TrekScene; key: string }[] = [
const STEP_MS = 1400
// Reduced motion parks on the paper-plane / "loading photos" beat.
const STILL_INDEX = 2
const REDUCE_MOTION = '(prefers-reduced-motion: reduce)'
export default function MTripLoadingSplash({ title }: { title: string }) {
const { t } = useTranslation()
const reduceMotion =
typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
const [reduceMotion, setReduceMotion] = useState(() => window.matchMedia?.(REDUCE_MOTION)?.matches ?? false)
// The splash can be up long enough for the OS setting to be flipped under it.
useEffect(() => {
const mq = window.matchMedia?.(REDUCE_MOTION)
if (!mq) return
const sync = () => setReduceMotion(mq.matches)
sync()
mq.addEventListener('change', sync)
return () => mq.removeEventListener('change', sync)
}, [])
const [index, setIndex] = useState(0)
useEffect(() => {
@@ -298,7 +298,7 @@ export default function MTripShell({
{days.length > 0 && (
<div className="absolute left-4 right-4 z-[25] flex top-[calc(var(--m-safe-top,12px)+50px)]">
<div className="flex flex-1 items-center gap-[2px] overflow-x-auto rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] p-[3px] backdrop-blur-[24px] backdrop-saturate-[1.7]">
{days.map(day => {
{days.map((day, idx) => {
const active = day.id === planner.selectedDayId
return (
<button
@@ -310,7 +310,7 @@ export default function MTripShell({
active ? 'bg-m-act text-m-actfg shadow-[0_6px_16px_-6px_rgba(0,0,0,.4)]' : 'text-m-ink'
}`}
>
{dayChipLabel(day, language, t('planner.dayN', { n: day.day_number ?? 0 }))}
{dayChipLabel(day, language, t('planner.dayN', { n: day.day_number ?? idx + 1 }))}
</button>
)
})}
@@ -85,7 +85,9 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
return next
})
const allSelected = filtered.length > 0 && selectedIds.size === filtered.length
// Compare the ids, not just the counts: a place removed remotely while another
// one is selected keeps the sizes equal without the sets matching.
const allSelected = filtered.length > 0 && filtered.every(p => selectedIds.has(p.id))
const toggleAllVisible = () => {
if (allSelected) setSelectedIds(new Set())
else setSelectedIds(new Set(filtered.map(p => p.id)))
@@ -334,9 +336,12 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
count={selectedIds.size}
categories={categories}
onClose={() => setCategoryPickerOpen(false)}
onPick={categoryId => {
planner.confirmChangeCategory([...selectedIds], categoryId)
onPick={async categoryId => {
const ids = [...selectedIds]
setCategoryPickerOpen(false)
// Drop the selection only once the bulk edit went through — a failed
// one has to stay retryable with the same set.
try { await planner.confirmChangeCategory(ids, categoryId) } catch { return }
exitSelectMode()
}}
/>
@@ -357,9 +362,10 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
confirmLabel={t('common.delete')}
cancelLabel={t('common.cancel')}
danger
onConfirm={() => {
planner.confirmDeletePlaces([...selectedIds])
onConfirm={async () => {
const ids = [...selectedIds]
setConfirmDeleteOpen(false)
try { await planner.confirmDeletePlaces(ids) } catch { return }
exitSelectMode()
}}
/>
@@ -46,7 +46,8 @@ export default function MPlanTimeline({ planner, shell }: MPlanTimelineProps) {
// Plugin time contributions in the day plan (dayScheduleProvider hook) —
// slotted under their anchor rows, same as the desktop sidebar.
const daySchedule = usePluginDaySchedule(planner.tripId)
const dayId = tl.day?.id
const day = tl.day
const dayId = day?.id
const dayScheduleFor = (anchor: 'assignment' | 'reservation', id: number) =>
(dayId != null
? (anchor === 'assignment' ? daySchedule.byAssignment[dayId]?.[id] : daySchedule.byReservation[dayId]?.[id])
@@ -88,7 +89,7 @@ export default function MPlanTimeline({ planner, shell }: MPlanTimelineProps) {
style={{ top: `calc(var(--m-safe-top, 12px) + ${editing ? 140 : tl.upNext ? 216 : 102}px)` }}
>
{(tl.hotelChips.length > 0 || tl.weatherTemp != null) && (
<TimelineHeader tl={tl} onOpenDay={() => tl.day && shell.openSheet('day', { dayId: tl.day.id })} />
<TimelineHeader tl={tl} onOpenDay={() => day && shell.openSheet('day', { dayId: day.id })} />
)}
{tl.hotelLegs.top && (
@@ -96,7 +97,7 @@ export default function MPlanTimeline({ planner, shell }: MPlanTimelineProps) {
)}
{dayId != null && daySchedule.byPosition[dayId]?.start.map(si => <PlanScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)}
{tl.rows.map(row => {
{day && tl.rows.map(row => {
switch (row.kind) {
case 'place':
return (
@@ -119,7 +120,7 @@ export default function MPlanTimeline({ planner, shell }: MPlanTimelineProps) {
<Fragment key={row.key}>
<TransportRow
res={row.res}
dayId={tl.day!.id}
dayId={day.id}
chrome={chrome}
reorder={reorderFor(row.item)}
onOpen={() => {
@@ -136,7 +137,7 @@ export default function MPlanTimeline({ planner, shell }: MPlanTimelineProps) {
<TransitRow
res={row.res}
transit={row.transit}
dayId={tl.day!.id}
dayId={day.id}
open={tl.openTransitKeys.has(row.key)}
chrome={chrome}
reorder={reorderFor(row.item)}
@@ -153,11 +154,11 @@ export default function MPlanTimeline({ planner, shell }: MPlanTimelineProps) {
note={row.note}
chrome={chrome}
reorder={reorderFor(row.item)}
onEdit={() => tl.day && shell.openSheet('note', { dayId: tl.day.id, note: row.note })}
onEdit={() => shell.openSheet('note', { dayId: day.id, note: row.note })}
/>
)
case 'conn':
return <ConnRow key={row.key} seg={row.seg} onTap={canEdit && row.assignmentId != null ? e => openLegMenu(e, row.assignmentId!) : undefined} />
return <ConnRow key={row.key} seg={row.seg} onTap={editing && row.assignmentId != null ? e => openLegMenu(e, row.assignmentId!) : undefined} />
}
})}
@@ -179,7 +180,7 @@ export default function MPlanTimeline({ planner, shell }: MPlanTimelineProps) {
<PlanAction
icon={PencilLine}
label={t('mobileTrip.addNoteShort')}
onClick={() => tl.day && shell.openSheet('note', { dayId: tl.day.id })}
onClick={() => day && shell.openSheet('note', { dayId: day.id })}
/>
<PlanAction icon={Ticket} label={t('mobileTrip.addBookingShort')} onClick={tl.addBooking} />
<PlanAction icon={TrainFront} label={t('mobileTrip.addTransportShort')} onClick={tl.addTransport} />
@@ -222,7 +222,9 @@ function LineBadge({ leg, className = '' }: { leg: TransitLegDisplay; className?
}
function TransitStrip({ legs }: { legs: TransitLegDisplay[] }) {
const shown = legs.filter(l => l.mode !== 'WALK' || (l.duration || 0) >= 60)
// Sub-minute walks are noise; a walk without a duration is not — dropping it
// would make the strip disagree with the expanded leg list.
const shown = legs.filter(l => l.mode !== 'WALK' || l.duration == null || l.duration >= 60)
return (
<div className="mt-1.5 flex flex-wrap items-center gap-1 text-m-faint">
{shown.map((leg, i) => (
@@ -231,7 +233,7 @@ function TransitStrip({ legs }: { legs: TransitLegDisplay[] }) {
{leg.mode === 'WALK' ? (
<span className="inline-flex items-center gap-[2px] font-geist text-[0.625rem] font-bold">
<Footprints size={11} strokeWidth={2.2} />
{Math.round((leg.duration || 0) / 60)}
{leg.duration != null ? Math.round(leg.duration / 60) : ''}
</span>
) : (
<LineBadge leg={leg} />
@@ -359,12 +361,12 @@ export function TransitRow({ res, transit, dayId, open, chrome, reorder, onToggl
// ── b4) Walk/drive connector between two located places ─────────────────────
export function ConnRow({ seg, onTap }: { seg: RouteSegment; onTap?: (e: MouseEvent) => void }) {
// The leg's chosen mode (#1281) drives the icon + duration; tap to change it.
/** The connector line of a routed leg — the leg's own mode (#1281) picks icon and duration. */
function TravelLine({ seg }: { seg: RouteSegment }) {
const mode = seg.mode
const Icon = mode === 'walking' ? Footprints : mode?.startsWith('plugin:') ? Zap : Car
const durationText = seg.durationText ?? (mode === 'walking' ? seg.walkingText : seg.drivingText)
const inner = (
return (
<>
<span className="h-px flex-1 bg-[color:var(--m-rowbr)]" />
<span className="inline-flex items-center gap-[3px] whitespace-nowrap font-geist text-[0.59375rem] font-semibold text-m-faint">
@@ -384,6 +386,11 @@ export function ConnRow({ seg, onTap }: { seg: RouteSegment; onTap?: (e: MouseEv
<span className="h-px flex-1 bg-[color:var(--m-rowbr)]" />
</>
)
}
export function ConnRow({ seg, onTap }: { seg: RouteSegment; onTap?: (e: MouseEvent) => void }) {
// Tap to change the leg's mode (#1281).
const inner = <TravelLine seg={seg} />
const cls = 'mt-[5px] flex w-full items-center gap-2 py-px text-[color:var(--m-conn)]'
return onTap
? <button type="button" onClick={onTap} className={cls}>{inner}</button>
@@ -421,21 +428,11 @@ export function HotelConnRow({ seg, name, placement }: {
name: string
placement: 'top' | 'bottom'
}) {
// Same line as the connectors between two stops, so a bookend leg routed with a
// plugin profile or set to walking reads the same as the rest of the day (#1281).
const travel = (
<div className="flex items-center gap-2 py-px text-[color:var(--m-conn)]">
<span className="h-px flex-1 bg-[color:var(--m-rowbr)]" />
<span className="inline-flex items-center gap-[3px] whitespace-nowrap font-geist text-[0.59375rem] font-semibold text-m-faint">
<Footprints size={10} strokeWidth={2} />
{seg.walkingText}
</span>
<span className="whitespace-nowrap font-geist text-[0.59375rem] font-semibold text-m-faint">
· {seg.distanceText} ·
</span>
<span className="inline-flex items-center gap-[3px] whitespace-nowrap font-geist text-[0.59375rem] font-semibold text-m-faint">
<Car size={10} strokeWidth={2} />
{seg.drivingText}
</span>
<span className="h-px flex-1 bg-[color:var(--m-rowbr)]" />
<TravelLine seg={seg} />
</div>
)
const hotel = (
@@ -203,6 +203,11 @@ export function useMPlanTimeline(planner: TripPlanner) {
updateRouteForDay(dayId)
} catch (err: unknown) {
toast.error(err instanceof Error ? err.message : t('trip.toast.reorderError'))
// The optimistic transport positions and leg metadata written above are
// not undone one by one — pull the server state back in so the timeline
// stops showing an order that was never accepted.
void tripActions.refreshDays(tripId)
void tripActions.loadReservations(tripId)
}
}, [dayAssignments, tripActions, tripId, pushUndo, updateRouteForDay, toast, t])
@@ -46,7 +46,6 @@ export default function ImpFileStep({ planner, onBack, onDone }: ImpFileStepProp
}
const selectFiles = (incoming: File[]) => {
if (incoming.length === 0) return
const valid: File[] = []
let firstError: string | null = null
for (const f of incoming) {
@@ -65,28 +64,27 @@ export default function ImpFileStep({ planner, onBack, onDone }: ImpFileStepProp
setError('')
setSummary(null)
let totalCreated = 0
// Counted per format so a mixed selection gets each half's own label.
let gpxCreated = 0
let kmlCreated = 0
let totalSkipped = 0
const createdIds: number[] = []
const gpxIds: number[] = []
const kmlIds: number[] = []
const errors: string[] = []
let mergedSummary: ImportSummary | null = null
let importedGpx = false
let importedKml = false
for (const f of files) {
const ext = f.name.toLowerCase().split('.').pop()
try {
if (ext === 'gpx') {
importedGpx = true
const result = await placesApi.importGpx(tripId, f, gpxOpts)
totalCreated += result.count ?? 0
gpxCreated += result.count ?? 0
totalSkipped += result.skipped ?? 0
if (result.places?.length > 0) createdIds.push(...result.places.map((p: { id: number }) => p.id))
if (result.places?.length > 0) gpxIds.push(...result.places.map((p: { id: number }) => p.id))
} else {
importedKml = true
const result = await placesApi.importMapFile(tripId, f, kmlOpts)
totalCreated += result.count ?? 0
if (result.places?.length > 0) createdIds.push(...result.places.map((p: { id: number }) => p.id))
kmlCreated += result.count ?? 0
if (result.places?.length > 0) kmlIds.push(...result.places.map((p: { id: number }) => p.id))
const s = result.summary as ImportSummary | undefined
if (s) {
mergedSummary = mergedSummary
@@ -98,8 +96,9 @@ export default function ImpFileStep({ planner, onBack, onDone }: ImpFileStepProp
errors: [...mergedSummary.errors, ...(s.errors ?? [])],
}
: s
totalSkipped += s.skippedCount ?? 0
}
// A response without a summary carries the count on the top level.
totalSkipped += s?.skippedCount ?? result.skipped ?? 0
}
} catch (err: unknown) {
const message =
@@ -110,8 +109,12 @@ export default function ImpFileStep({ planner, onBack, onDone }: ImpFileStepProp
await tripActions.loadTrip(tripId)
const createdIds = [...gpxIds, ...kmlIds]
if (createdIds.length > 0) {
pushUndo(importedGpx && !importedKml ? t('undo.importGpx') : t('undo.importKeyholeMarkup'), async () => {
const undoLabel = gpxIds.length > 0 && kmlIds.length > 0
? t('undo.importFiles')
: gpxIds.length > 0 ? t('undo.importGpx') : t('undo.importKeyholeMarkup')
pushUndo(undoLabel, async () => {
try {
await placesApi.bulkDelete(tripId, createdIds)
} catch {
@@ -121,10 +124,9 @@ export default function ImpFileStep({ planner, onBack, onDone }: ImpFileStepProp
})
}
if (totalCreated > 0) {
const key = importedKml && !importedGpx ? 'places.kmlKmzImported' : 'places.gpxImported'
toast.success(t(key, { count: totalCreated }))
} else if (totalSkipped > 0 && errors.length === 0) {
if (gpxCreated > 0) toast.success(t('places.gpxImported', { count: gpxCreated }))
if (kmlCreated > 0) toast.success(t('places.kmlKmzImported', { count: kmlCreated }))
if (gpxCreated === 0 && kmlCreated === 0 && totalSkipped > 0 && errors.length === 0) {
toast.warning(t('places.importAllSkipped'))
}
@@ -20,10 +20,11 @@ interface HotelForm {
check_in_end: string
check_out: string
confirmation: string
place_id: number | null
/** '' = nothing picked yet, which is what keeps the save button disabled. */
place_id: number | ''
}
const EMPTY_FORM: HotelForm = { check_in: '', check_in_end: '', check_out: '', confirmation: '', place_id: null }
const EMPTY_FORM: HotelForm = { check_in: '', check_in_end: '', check_out: '', confirmation: '', place_id: '' }
/**
* Add/edit accommodation sheet — the mobile counterpart of the desktop
@@ -60,7 +61,7 @@ export default function MAccommodationSheet({ planner, shell }: MTripSheetsProps
check_in_end: editing.check_in_end || '',
check_out: editing.check_out || '',
confirmation: editing.confirmation || '',
place_id: editing.place_id ?? null,
place_id: editing.place_id ?? '',
})
} else {
const idx = days.findIndex(d => d.id === payload.dayId)
@@ -71,8 +72,10 @@ export default function MAccommodationSheet({ planner, shell }: MTripSheetsProps
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, payload.dayId, payload.accId])
// Cancelling / saving returns to the day sheet it was opened from.
const back = () => shell.openSheet('day', { dayId: payload.dayId })
// Cancelling / saving returns to the day sheet it was opened from — opened for
// an edit there is no dayId in the payload, so fall back to the stay's own
// start day instead of leaving the day sheet without one.
const back = () => shell.openSheet('day', { dayId: payload.dayId ?? editing?.start_day_id })
const firstId = days[0]?.id
const lastId = days[days.length - 1]?.id
@@ -89,27 +92,29 @@ export default function MAccommodationSheet({ planner, shell }: MTripSheetsProps
const filteredPlaces = categoryFilter != null ? places.filter(p => p.category_id === categoryFilter) : places
const save = async () => {
if (!form.place_id || saving) return
setSaving(true)
const body = {
place_id: form.place_id,
start_day_id: range.start,
end_day_id: range.end,
check_in: form.check_in || null,
check_in_end: form.check_in_end || null,
check_out: form.check_out || null,
confirmation: form.confirmation || null,
}
// Only the write itself decides whether the save failed — a refresh that
// trips afterwards must not be reported as a failed save.
try {
const body = {
place_id: form.place_id,
start_day_id: range.start,
end_day_id: range.end,
check_in: form.check_in || null,
check_in_end: form.check_in_end || null,
check_out: form.check_out || null,
confirmation: form.confirmation || null,
}
if (editing) await accommodationsApi.update(tripId, editing.id, body)
else await accommodationsApi.create(tripId, body)
planner.loadAccommodations()
back()
} catch {
planner.toast.error(t('common.error'))
return
} finally {
setSaving(false)
}
planner.loadAccommodations()
back()
}
return (
@@ -115,7 +115,8 @@ export default function MBrowseActionsSheet({ planner, shell }: MTripSheetsProps
className={`flex w-full items-center gap-2 px-3 py-[10px] text-left ${i > 0 ? 'border-t border-[color:var(--m-rowbr)]' : ''}`}
>
<span className="min-w-0 flex-1 truncate text-[0.78125rem] font-semibold">
{d.title || t('planner.dayN', { n: (d.day_number ?? i + 1) || '?' })}
{/* A day_number of 0 is as unusable as a missing one — both take the row position. */}
{d.title || t('planner.dayN', { n: d.day_number || i + 1 })}
</span>
{d.date && (
<span className="flex-none font-geist text-[0.65625rem] font-medium text-m-muted">
@@ -244,9 +244,12 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
const save = async () => {
if (!valid || saving) return
setSaving(true)
// A picked payer always goes out, even when nobody shares the expense: the
// server re-derives total_price from the payer sum (CostsPanel.helpers), so
// dropping the payer would store the entry with a total of 0.
const payerList = multiPayer
? [...payerIds].map(id => ({ user_id: id, amount: parseFloat(payerAmounts[id]) || 0 })).filter(p => p.amount > 0)
: (payerId > 0 && participants.size > 0) ? [{ user_id: payerId, amount: totalNum }] : []
: payerId > 0 ? [{ user_id: payerId, amount: totalNum }] : []
const memberList = [...participants].map(id => ({
user_id: id,
amount: splitMode === 'custom'
@@ -193,7 +193,8 @@ export default function MDaySheet({ planner, shell }: MTripSheetsProps) {
weekday: 'long', day: 'numeric', month: 'long', timeZone: 'UTC',
})
: null
const dayLabel = day?.title || t('planner.dayN', { n: (day?.day_number ?? dayIndex + 1) || '?' })
// A day_number of 0 is as unusable as a missing one — both fall back to the row position.
const dayLabel = day?.title || t('planner.dayN', { n: day ? day.day_number || dayIndex + 1 : '?' })
const WeatherIcon = weatherIconFor(weather?.main)
const stayBadge = (acc: (typeof dayAccommodations)[number]) => {
@@ -21,6 +21,7 @@ export default function MExportSheet({ planner, shell }: MTripSheetsProps) {
const dayNotes = useTripStore(s => s.dayNotes)
const [subscribeOpen, setSubscribeOpen] = useState(false)
const [pdfBusy, setPdfBusy] = useState(false)
const [icsBusy, setIcsBusy] = useState(false)
const exportPdf = async () => {
if (!planner.trip || pdfBusy) return
@@ -48,6 +49,8 @@ export default function MExportSheet({ planner, shell }: MTripSheetsProps) {
}
const downloadIcs = async () => {
if (icsBusy) return
setIcsBusy(true)
try {
const res = await fetch(`/api/trips/${planner.tripId}/export.ics`, { credentials: 'include' })
if (!res.ok) throw new Error()
@@ -56,11 +59,16 @@ export default function MExportSheet({ planner, shell }: MTripSheetsProps) {
const a = document.createElement('a')
a.href = url
a.download = `${planner.trip?.title || 'trip'}.ics`
document.body.appendChild(a)
a.click()
URL.revokeObjectURL(url)
// Firefox/Safari cancel the download when the object URL is revoked
// before they picked the blob up.
setTimeout(() => { URL.revokeObjectURL(url); a.remove() }, 100)
shell.closeSheet()
} catch {
planner.toast.error(t('planner.icsExportFailed'))
} finally {
setIcsBusy(false)
}
}
@@ -85,7 +93,7 @@ export default function MExportSheet({ planner, shell }: MTripSheetsProps) {
/>
<ExportRow
icon={FileDown}
title={t('mobileTrip.icsDownload')}
title={icsBusy ? t('common.loading') : t('mobileTrip.icsDownload')}
sub={`${planner.trip?.title || 'trip'}.ics`}
onClick={() => void downloadIcs()}
/>
@@ -38,13 +38,19 @@ export default function MNoteSheet({ planner, open, payload, onClose }: MNoteShe
// the sheet still shows through its exit animation.
const [sheetPayload, setSheetPayload] = useState<MNoteSheetPayload | undefined>(undefined)
// Keyed on what the payload points AT, not on its object identity — a caller
// that rebuilds the payload inline (or a store refresh of the note) must not
// reseed the fields under the user's fingers.
const payloadNoteId = payload?.note?.id
const payloadDayId = payload?.dayId
useEffect(() => {
if (!open) return
setSheetPayload(payload)
setIcon(payload?.note?.icon || 'FileText')
setTitle(payload?.note?.text || '')
setDetail(payload?.note?.time || '')
}, [open, payload])
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, payloadNoteId, payloadDayId])
const note = sheetPayload?.note ?? null
const dayId = sheetPayload?.dayId ?? selectedDayId
@@ -187,8 +187,10 @@ export default function MPlaceEditSheet({ planner }: MPlaceEditSheetProps) {
}
}
// End before start blocks the save — tied to the values, not to which entry
// point opened the sheet.
const hasTimeError = Boolean(
sheetPlace && form.place_time && form.end_time &&
form.place_time && form.end_time &&
form.place_time.length >= 5 && form.end_time.length >= 5 &&
form.end_time <= form.place_time,
)
@@ -53,6 +53,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
setFilesExpanded(false)
setDayPickerOpen(false)
setParticipantPickerOpen(false)
setColorPickerOpen(false)
}
const category = place?.category
@@ -150,7 +151,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
try {
await planner.tripActions.updatePlace(planner.tripId, place.id, { image_url: null })
} catch (err: unknown) {
planner.toast.error(translateApiError(t, err, 'places.imageUploadError'))
planner.toast.error(translateApiError(t, err, 'places.imageRemoveError'))
} finally {
setImgBusy(false)
}
@@ -157,8 +157,12 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati
const isEndBeforeStart = (() => {
if (isHotel || !form.end_date || !form.reservation_time) return false
const sDate = form.reservation_time.split('T')[0]
const sTime = form.reservation_time.split('T')[1] || '00:00'
return `${form.end_date}T${form.reservation_end_time || '00:00'}` <= `${sDate}T${sTime}`
const sTime = form.reservation_time.split('T')[1] || ''
const eTime = form.reservation_end_time || ''
// Without a time on either side the booking is all-day, so an end on the
// start day is fine — only compare the dates there.
if (!sTime || !eTime) return form.end_date < sDate
return `${form.end_date}T${eTime}` <= `${sDate}T${sTime}`
})()
const startDate = (form.reservation_time || '').split('T')[0] || ''
@@ -188,7 +192,7 @@ export default function MReservationSheet({ planner, onOpenExpense }: MReservati
}
const handleSubmit = async () => {
if (!form.title.trim() || isSaving) return
// Only the costs button reaches this without the footer's date check.
if (isEndBeforeStart) { toast.error(t('reservations.validation.endBeforeStart')); return }
const withExpense = expenseIntentRef.current
expenseIntentRef.current = false
@@ -194,6 +194,10 @@ export default function MTransportFormSheet({ planner, onOpenExpense }: MTranspo
// day drag, insertDay or a trip-date shift (mirrors TransportModal).
const endpointDayId = (ep?: { local_date?: string | null } | null) =>
editingTransport ? '' : resolveDayId(days, ep?.local_date)
// Origin and destination fall back to the reservation's own day columns. An
// intermediate stop has none, so when metadata.legs is missing (imported or
// MCP-created bookings) its local_date is the only day left to seed from.
const stopDayId = (ep?: { local_date?: string | null } | null) => resolveDayId(days, ep?.local_date)
if (type === 'flight') {
const orderedEps = orderedEndpoints(src)
@@ -206,11 +210,12 @@ export default function MTransportFormSheet({ planner, onOpenExpense }: MTranspo
const legOut = metaLegs[i]
const isFirst = i === 0
const isLast = i === orderedEps.length - 1
const stopDay = !isFirst && !isLast ? stopDayId(ep) : ''
return {
airport: airportFromEndpoint(ep),
arrDayId: legInto?.arr_day_id ?? (endpointDayId(ep) || (isLast ? (src.end_day_id ?? '') : '')),
arrDayId: legInto?.arr_day_id ?? (endpointDayId(ep) || (isLast ? (src.end_day_id ?? '') : stopDay)),
arrTime: legInto?.arr_time ?? (!isFirst ? (ep.local_time ?? '') : ''),
depDayId: legOut?.dep_day_id ?? (endpointDayId(ep) || (isFirst ? (src.day_id ?? '') : '')),
depDayId: legOut?.dep_day_id ?? (endpointDayId(ep) || (isFirst ? (src.day_id ?? '') : stopDay)),
depTime: legOut?.dep_time ?? (!isLast ? (ep.local_time ?? '') : ''),
airline: legOut?.airline ?? (isFirst ? (meta.airline ?? '') : ''),
flight_number: legOut?.flight_number ?? (isFirst ? (meta.flight_number ?? '') : ''),
@@ -243,11 +248,12 @@ export default function MTransportFormSheet({ planner, onOpenExpense }: MTranspo
const legOut = metaLegs[i]
const isFirst = i === 0
const isLast = i === orderedEps.length - 1
const stopDay = !isFirst && !isLast ? stopDayId(ep) : ''
return {
location: locationFromEndpoint(ep),
arrDayId: legInto?.arr_day_id ?? (endpointDayId(ep) || (isLast ? (src.end_day_id ?? '') : '')),
arrDayId: legInto?.arr_day_id ?? (endpointDayId(ep) || (isLast ? (src.end_day_id ?? '') : stopDay)),
arrTime: legInto?.arr_time ?? (!isFirst ? (ep.local_time ?? '') : ''),
depDayId: legOut?.dep_day_id ?? (endpointDayId(ep) || (isFirst ? (src.day_id ?? '') : '')),
depDayId: legOut?.dep_day_id ?? (endpointDayId(ep) || (isFirst ? (src.day_id ?? '') : stopDay)),
depTime: legOut?.dep_time ?? (!isLast ? (ep.local_time ?? '') : ''),
train_number: legOut?.train_number ?? (isFirst ? (meta.train_number ?? '') : ''),
platform: legOut?.platform ?? (isFirst ? (meta.platform ?? '') : ''),
@@ -357,9 +363,13 @@ export default function MTransportFormSheet({ planner, onOpenExpense }: MTranspo
const firstWp = flightWps[0]
const lastWp = flightWps[flightWps.length - 1]
const trainWps = form.type === 'train' ? trainWaypoints : []
const firstTrainWp = trainWps[0]
const lastTrainWp = trainWps[trainWps.length - 1]
const trainStations = form.type === 'train' ? trainWaypoints.filter(w => w.location) : []
const trainStations = trainWps.filter(w => w.location)
// The day/time anchors have to be the rows that actually become endpoints
// (same as the flight path); only a train without a single picked station
// falls back to the raw rows so its day and time survive.
const trainAnchors = trainStations.length > 0 ? trainStations : trainWps
const firstTrainWp = trainAnchors[0]
const lastTrainWp = trainAnchors[trainAnchors.length - 1]
// Per-leg day-plan positions are owned by the day planner — keep them on re-save.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const origLegs: any[] = res ? (parseReservationMetadata(res).legs || []) : []
@@ -85,7 +85,8 @@ export default function PlPlaceSearch({ planner, locationBias, onPick, onResolvi
const result = await mapsApi.autocomplete(input, language, locationBias, controller.signal)
setSuggestions(result.suggestions || [])
} catch (err: unknown) {
if (err instanceof Error && (err.name === 'AbortError' || err.name === 'CanceledError')) return
// Superseded request — axios rejects an aborted call with CanceledError.
if (err instanceof Error && err.name === 'CanceledError') return
setSuggestions([])
}
},
@@ -7,7 +7,7 @@ import { openFile } from '../../../../utils/fileDownload'
import { useTranslation } from '../../../../i18n'
import type { Reservation } from '../../../../types'
import MConfirmSheet from '../../settings/MConfirmSheet'
import { CountPill, Field, SectionHeader, StatusDot, TabScroller, TravelerAvatars, TravelerFilterRow } from './tabChrome'
import { ConfirmationCode, CountPill, Field, SectionHeader, StatusDot, TabScroller, TravelerAvatars, TravelerFilterRow } from './tabChrome'
import { STATUS_COLOR, type MTabScreenProps } from './tabModel'
import { groupTransports, orderedEndpoints, parseTransportMeta } from './transportsModel'
import { BOOKING_TYPE_COLOR } from './bookingsModel'
@@ -183,73 +183,71 @@ function BookingCard({ res, planner, canEdit, compact }: {
)}
</div>
{/* Body */}
{/* Body — split around the booking code so the reveal can be its own
control instead of a click handler buried inside the card button. */}
{!compact && (
<button type="button" onClick={openEdit} className="block w-full px-3 pb-3 pt-[9px] text-left">
<div className="flex gap-2">
<Field label={t('reservations.date')} className="flex-[1.4]">{dayValue}</Field>
<Field label={t('reservations.time')} className="flex-1" tabular>{timeValue}</Field>
</div>
<div className="px-3 pb-3 pt-[9px]">
<button type="button" onClick={openEdit} className="block w-full text-left">
<div className="flex gap-2">
<Field label={t('reservations.date')} className="flex-[1.4]">{dayValue}</Field>
<Field label={t('reservations.time')} className="flex-1" tabular>{timeValue}</Field>
</div>
</button>
{res.confirmation_number && (
<div className="mt-2">
<div className="mb-[3px] font-geist text-[0.5625rem] font-bold uppercase tracking-[.08em] text-m-faint">
{t('reservations.confirmationCode')}
</div>
<div
onClick={e => { if (blurCodes) { e.stopPropagation(); setCodeRevealed(v => !v) } }}
className={`overflow-hidden text-ellipsis whitespace-nowrap rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-[7px] text-center font-geist text-[0.71875rem] font-semibold tabular-nums text-m-ink ${
blurCodes && !codeRevealed ? 'blur-[4px] select-none' : ''
}`}
>
{res.confirmation_number}
</div>
</div>
<ConfirmationCode
code={res.confirmation_number}
label={t('reservations.confirmationCode')}
blurred={!!blurCodes && !codeRevealed}
onToggle={blurCodes ? () => setCodeRevealed(v => !v) : undefined}
/>
)}
{metaCells.length > 0 && (
<div className="mt-2 flex gap-2">
{metaCells.slice(0, 3).map((c, i) => (
<Field key={i} label={c.label} className="flex-1">{c.value}</Field>
))}
</div>
)}
<TravelerAvatars travelers={res.travelers || []} label={t('reservations.travelers.label')} />
{res.location && (
<div className="mt-2 flex items-center gap-[6px] rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-[7px]">
<MapPin size={12} strokeWidth={2} className="flex-none text-m-muted" />
<span className="truncate text-[0.71875rem] font-semibold text-m-ink">{res.location}</span>
</div>
)}
{res.notes && (
<div className="mt-2 rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-2">
<p className="whitespace-pre-wrap font-geist text-[0.6875rem] leading-[1.5] text-m-muted">{res.notes}</p>
</div>
)}
{files.length > 0 && (
<div className="mt-2">
<div className="mb-[3px] font-geist text-[0.5625rem] font-bold uppercase tracking-[.08em] text-m-faint">
{t('files.title')}
</div>
<div className="flex flex-col gap-1">
{files.map(f => (
<span
key={f.id}
onClick={e => { e.stopPropagation(); openFile(f.url, f.original_name) }}
className="flex items-center gap-[6px] rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-[7px]"
>
<FileText size={12} strokeWidth={2} className="flex-none text-m-muted" />
<span className="truncate font-geist text-[0.65625rem] font-semibold text-m-muted">{f.original_name}</span>
</span>
<button type="button" onClick={openEdit} className="block w-full text-left">
{metaCells.length > 0 && (
<div className="mt-2 flex gap-2">
{metaCells.slice(0, 3).map((c, i) => (
<Field key={i} label={c.label} className="flex-1">{c.value}</Field>
))}
</div>
</div>
)}
</button>
)}
<TravelerAvatars travelers={res.travelers || []} label={t('reservations.travelers.label')} />
{res.location && (
<div className="mt-2 flex items-center gap-[6px] rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-[7px]">
<MapPin size={12} strokeWidth={2} className="flex-none text-m-muted" />
<span className="truncate text-[0.71875rem] font-semibold text-m-ink">{res.location}</span>
</div>
)}
{res.notes && (
<div className="mt-2 rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-2">
<p className="whitespace-pre-wrap font-geist text-[0.6875rem] leading-[1.5] text-m-muted">{res.notes}</p>
</div>
)}
{files.length > 0 && (
<div className="mt-2">
<div className="mb-[3px] font-geist text-[0.5625rem] font-bold uppercase tracking-[.08em] text-m-faint">
{t('files.title')}
</div>
<div className="flex flex-col gap-1">
{files.map(f => (
<span
key={f.id}
onClick={e => { e.stopPropagation(); openFile(f.url, f.original_name) }}
className="flex items-center gap-[6px] rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-[7px]"
>
<FileText size={12} strokeWidth={2} className="flex-none text-m-muted" />
<span className="truncate font-geist text-[0.65625rem] font-semibold text-m-muted">{f.original_name}</span>
</span>
))}
</div>
</div>
)}
</button>
</div>
)}
<MConfirmSheet
@@ -24,6 +24,12 @@ const PAGE_SIZE = 100
const LONG_PRESS_MS = 500
const DOUBLE_TAP_MS = 300
const MOVE_CANCEL_PX = 10
const POPOVER_WIDTH = 224
// Emoji grid + reply row, plus the delete row when it is shown — used to keep
// the popover inside the viewport.
const POPOVER_HEIGHT = 150
const POPOVER_DELETE_ROW = 37
const POPOVER_MARGIN = 8
interface MCollabChatProps {
planner: TripPlanner
@@ -383,7 +389,9 @@ function ChatBubbleRow({ msg, own, showHeader, isLastInGroup, marginTop, is12h,
}
const bigEmoji = isEmojiOnlyText(msg.text)
const hasReply = !!(msg.reply_text || msg.reply_to)
// A reply to a since-deleted message keeps reply_to but loses the quoted
// text — no quote box then instead of an empty one.
const hasReply = !!msg.reply_text
const initial = (msg.username || '?')[0]?.toUpperCase() || '?'
return (
@@ -431,7 +439,7 @@ function ChatBubbleRow({ msg, own, showHeader, isLastInGroup, marginTop, is12h,
{hasReply && (
<div className="mb-1 rounded-[10px] bg-[color:var(--m-card)] px-[10px] py-[5px]">
<div className="font-geist text-[0.625rem] font-bold opacity-70">{msg.reply_username}</div>
<div className="truncate text-[0.71875rem] opacity-80">{(msg.reply_text || '').slice(0, 80)}</div>
<div className="truncate text-[0.71875rem] opacity-80">{msg.reply_text?.slice(0, 80)}</div>
</div>
)}
<span className="whitespace-pre-wrap break-words">{msg.text}</span>
@@ -485,9 +493,10 @@ function MessageActionsPopover({ x, y, canDeleteOwn, t, onReact, onReply, onDele
return () => document.removeEventListener('pointerdown', close)
}, [onClose])
const width = 224
const left = Math.max(width / 2 + 8, Math.min(x, window.innerWidth - width / 2 - 8))
const top = Math.max(64, y - 96)
const width = POPOVER_WIDTH
const left = Math.max(width / 2 + POPOVER_MARGIN, Math.min(x, window.innerWidth - width / 2 - POPOVER_MARGIN))
const height = POPOVER_HEIGHT + (canDeleteOwn ? POPOVER_DELETE_ROW : 0)
const top = Math.max(64, Math.min(y - 96, window.innerHeight - height - POPOVER_MARGIN))
return ReactDOM.createPortal(
<div className="m-root fixed inset-0 z-[55]">
@@ -151,11 +151,18 @@ export default function MCollabNotes({ planner }: MCollabNotesProps) {
}
}, [tripId, toast, t])
// Returns whether the file is really gone — the form sheet only drops the
// chip once the server confirmed it.
const handleDeleteFile = useCallback(async (noteId: number, fileId: number) => {
try {
await collabApi.deleteNoteFile(tripId, noteId, fileId)
setNotes(prev => prev.map(n => (
n.id === noteId ? { ...n, attachments: n.attachments.filter(f => f.id !== fileId) } : n
)))
return true
} catch {
toast.error(t('common.error'))
return false
}
}, [tripId, toast, t])
@@ -357,7 +364,7 @@ function NoteFormSheet({ open, target, categories, colorMap, canUploadFiles, onC
canUploadFiles: boolean
onClose: () => void
onSubmit: (data: NoteFormSubmitData) => Promise<void>
onDeleteExistingFile: (noteId: number, fileId: number) => void
onDeleteExistingFile: (noteId: number, fileId: number) => Promise<boolean>
t: TripPlanner['t']
}) {
const note = target && target !== 'new' ? target : null
@@ -432,7 +439,7 @@ function NoteFormSheet({ open, target, categories, colorMap, canUploadFiles, onC
className={FIELD_CLS}
/>
<Eyebrow className="mb-[5px] mt-3 uppercase">{t('collab.notes.contentPlaceholder')}</Eyebrow>
<Eyebrow className="mb-[5px] mt-3 uppercase">{t('collab.notes.content')}</Eyebrow>
<textarea
value={content}
onChange={e => setContent(e.target.value)}
@@ -515,11 +522,12 @@ function NoteFormSheet({ open, target, categories, colorMap, canUploadFiles, onC
{f.original_name.length > 20 ? `${f.original_name.slice(0, 17)}...` : f.original_name}
<button
type="button"
onClick={() => {
if (note) onDeleteExistingFile(note.id, f.id)
setExistingFiles(prev => prev.filter(x => x.id !== f.id))
onClick={async () => {
if (!note) return
const removed = await onDeleteExistingFile(note.id, f.id)
if (removed) setExistingFiles(prev => prev.filter(x => x.id !== f.id))
}}
aria-label={t('collab.notes.delete')}
aria-label={t('collab.notes.removeFile', { name: f.original_name })}
className="text-[color:var(--m-st-danger)]"
>
<X size={10} strokeWidth={2.4} />
@@ -535,7 +543,7 @@ function NoteFormSheet({ open, target, categories, colorMap, canUploadFiles, onC
<button
type="button"
onClick={() => setPendingFiles(prev => prev.filter((_, j) => j !== i))}
aria-label={t('collab.notes.delete')}
aria-label={t('collab.notes.removeFile', { name: f.name })}
className="text-m-faint"
>
<X size={10} strokeWidth={2.4} />
@@ -113,7 +113,8 @@ export default function MCollabPolls({ planner }: MCollabPollsProps) {
const handleVote = useCallback(async (pollId: number, optionIndex: number) => {
try {
const res = (await collabApi.votePoll(tripId, pollId, optionIndex)) as PollResponse
setPolls(prev => prev.map(p => (p.id === res.poll.id ? res.poll : p)))
// Reconcile against the poll we asked about, like handleClosePoll does.
setPolls(prev => prev.map(p => (p.id === pollId ? res.poll : p)))
} catch {
toast.error(t('common.error'))
}
@@ -9,6 +9,7 @@ import { useSettingsStore } from '../../../../store/settingsStore'
import { useExchangeRates } from '../../../../hooks/useExchangeRates'
import { useTranslation } from '../../../../i18n'
import { formatMoney } from '../../../../utils/formatters'
import { downloadBlob } from '../../../../utils/fileDownload'
import { budgetApi } from '../../../../api/client'
import MCostSheet from '../sheets/MCostSheet'
import { catMeta, COST_CAT_META } from '../../../../components/Budget/costsCategories'
@@ -113,12 +114,7 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
const handleExportCsv = useCallback(() => {
const { filename, content } = buildCostsCsv(budgetItems, { base, ctx, locale, tripTitle: trip?.title, t })
const blob = new Blob(['' + content], { type: 'text/csv;charset=utf-8;' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = filename
a.click()
URL.revokeObjectURL(url)
downloadBlob(blob, filename)
}, [budgetItems, base, ctx, locale, trip?.title, t])
// Header intent signals (spec 03 §3.8 addExpense/csvGo) — increment-only
@@ -215,40 +211,32 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
{/* Settle up (spec §3.4) */}
<div className="mt-2 rounded-2xl border border-[color:var(--m-rowbr)] bg-m-card p-[13px]">
<div
role="button"
tabIndex={0}
aria-expanded={settleOpen}
onClick={() => setSettleOpen(v => !v)}
onKeyDown={e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
setSettleOpen(v => !v)
}
}}
className="flex w-full cursor-pointer items-center gap-[7px]"
>
<span className="text-[0.875rem] font-extrabold text-m-ink">{t('costs.settleUp')}</span>
<CountPill>{flows.length}</CountPill>
{canEdit ? (
{/* Toggle and "Add payment" are siblings, not nested: a control inside a
control reads as one element to a screen reader. */}
<div className="flex w-full items-center gap-[7px]">
<button
type="button"
aria-expanded={settleOpen}
onClick={() => setSettleOpen(v => !v)}
className="flex min-w-0 flex-1 items-center gap-[7px] text-left"
>
<span className="text-[0.875rem] font-extrabold text-m-ink">{t('costs.settleUp')}</span>
<CountPill>{flows.length}</CountPill>
{settleOpen ? (
<ChevronUp size={14} strokeWidth={2} className="ml-auto flex-none text-m-faint" />
) : (
<ChevronDown size={14} strokeWidth={2} className="ml-auto flex-none text-m-faint" />
)}
</button>
{canEdit && (
<button
type="button"
onClick={e => {
e.stopPropagation()
setAddPaymentOpen(true)
}}
className="ml-auto flex flex-none items-center gap-[5px] rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-[11px] py-[6px] font-[inherit] text-[0.71875rem] font-semibold text-m-muted"
onClick={() => setAddPaymentOpen(true)}
className="flex flex-none items-center gap-[5px] rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-[11px] py-[6px] font-[inherit] text-[0.71875rem] font-semibold text-m-muted"
>
<Plus size={11} strokeWidth={2.2} />
{t('costs.addPayment')}
</button>
) : (
<span className="ml-auto" />
)}
{settleOpen ? (
<ChevronUp size={14} strokeWidth={2} className="flex-none text-m-faint" />
) : (
<ChevronDown size={14} strokeWidth={2} className="flex-none text-m-faint" />
)}
</div>
@@ -108,7 +108,15 @@ export default function MFileLightbox({ files, index, onIndexChange, onClose, t
</div>
{/* Media + nav */}
<div className="relative flex min-h-0 flex-1 items-center justify-center" onClick={e => { if (e.target === e.currentTarget) onClose() }}>
<div
className="relative flex min-h-0 flex-1 items-center justify-center"
onClick={e => {
if (e.target !== e.currentTarget) return
// Without this the click also reaches the overlay handler above.
e.stopPropagation()
onClose()
}}
>
{hasPrev && (
<button
type="button"
@@ -28,6 +28,7 @@ export default function MFileTrashSheet({ planner, open, onClose }: MFileTrashSh
const [files, setFiles] = useState<TripFile[]>([])
const [loading, setLoading] = useState(false)
const [busyId, setBusyId] = useState<number | null>(null)
const [emptying, setEmptying] = useState(false)
const [confirmEmpty, setConfirmEmpty] = useState(false)
const [confirmDeleteId, setConfirmDeleteId] = useState<number | null>(null)
@@ -68,11 +69,14 @@ export default function MFileTrashSheet({ planner, open, onClose }: MFileTrashSh
.finally(() => setBusyId(null))
}
// Row actions stay disabled while this runs so a restore cannot race the empty.
const emptyTrash = () => {
setConfirmEmpty(false)
setEmptying(true)
filesApi.emptyTrash(tripId)
.then(() => { setFiles([]); toast.success(t('files.toast.trashEmptied')) })
.catch(() => toast.error(t('files.toast.deleteError')))
.finally(() => setEmptying(false))
}
return (
@@ -88,7 +92,8 @@ export default function MFileTrashSheet({ planner, open, onClose }: MFileTrashSh
<button
type="button"
onClick={() => setConfirmEmpty(true)}
className="font-geist text-[0.6875rem] font-bold text-[color:var(--m-st-danger)]"
disabled={emptying}
className="font-geist text-[0.6875rem] font-bold text-[color:var(--m-st-danger)] disabled:opacity-50"
>
{t('files.emptyTrash')}
</button>
@@ -127,7 +132,7 @@ export default function MFileTrashSheet({ planner, open, onClose }: MFileTrashSh
type="button"
aria-label={t('files.restore')}
onClick={() => restore(file.id)}
disabled={busy}
disabled={busy || emptying}
className="flex h-8 w-8 items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-muted disabled:opacity-50"
>
{busy ? <Loader2 size={13} className="animate-spin" /> : <RotateCcw size={13} strokeWidth={2} />}
@@ -136,7 +141,7 @@ export default function MFileTrashSheet({ planner, open, onClose }: MFileTrashSh
type="button"
aria-label={t('common.delete')}
onClick={() => setConfirmDeleteId(file.id)}
disabled={busy}
disabled={busy || emptying}
className="flex h-8 w-8 items-center justify-center rounded-full bg-[color:var(--m-ic)] text-[color:var(--m-st-danger)] disabled:opacity-50"
>
<Trash2 size={13} strokeWidth={2} />
@@ -60,18 +60,22 @@ export default function MFilesTab({ planner, shell }: MTabScreenProps) {
if (tooBig.length > 0) planner.toast.error(t('files.uploadErrorSize'))
if (okFiles.length === 0) return
setUploading(true)
try {
for (const file of okFiles) {
const fd = new FormData()
fd.append('file', file)
let uploaded = 0
const failures: unknown[] = []
for (const file of okFiles) {
const fd = new FormData()
fd.append('file', file)
try {
await planner.tripActions.addFile(planner.tripId, fd)
uploaded++
} catch (err) {
// One rejected file must not drop the rest of the batch.
failures.push(err)
}
planner.toast.success(t('files.uploaded', { count: okFiles.length }))
} catch (err) {
planner.toast.error(translateApiError(t, err, 'files.uploadError'))
} finally {
setUploading(false)
}
setUploading(false)
if (uploaded > 0) planner.toast.success(t('files.uploaded', { count: uploaded }))
if (failures.length > 0) planner.toast.error(translateApiError(t, failures[0], 'files.uploadError'))
}
const onPickFiles = (e: ChangeEvent<HTMLInputElement>) => {
@@ -122,8 +126,8 @@ export default function MFilesTab({ planner, shell }: MTabScreenProps) {
const openRow = (file: TripFile) => {
if (isMedia(file.mime_type)) {
const idx = mediaFiles.findIndex(f => f.id === file.id)
setLightboxIndex(idx >= 0 ? idx : 0)
// Only rows out of `visible` get here, so the file is always in mediaFiles.
setLightboxIndex(mediaFiles.findIndex(f => f.id === file.id))
} else {
// Wallet passes and everything else (PDF/docs) share the same browser-native
// handling as the transport/reservation file chips: openFile() opens PDFs
@@ -41,12 +41,16 @@ export default function MPackItemSheet({
const [weight, setWeight] = useState('')
const [saving, setSaving] = useState(false)
// Keyed on the item id, not the object: packingSlice swaps the object on every
// update, and a WebSocket refresh must not overwrite what is being typed.
const heldId = item?.id
useEffect(() => {
if (!open || !item) return
setName(isPackingPlaceholder(item) ? '' : item.name)
setQuantity(String(item.quantity || 1))
setWeight(item.weight_grams != null ? String(item.weight_grams) : '')
}, [open, item])
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, heldId])
if (!item) {
return <MSheet open={false} onClose={onClose} />
@@ -81,7 +85,6 @@ export default function MPackItemSheet({
const handleSave = async () => {
const trimmedName = name.trim()
if (!trimmedName || saving) { onClose(); return }
setSaving(true)
try {
const qty = Math.max(1, Math.min(999, parseInt(quantity, 10) || 1))
@@ -221,7 +221,9 @@ export default function MPackingListTab({ planner }: { planner: TripPlanner }) {
const applyTemplate = async (templateId: number) => {
try {
const data = await packingApi.applyTemplate(tripId, templateId)
// Land the items in the list the user is looking at — without the
// visibility the API defaults to 'common' and they vanish from My list.
const data = await packingApi.applyTemplate(tripId, templateId, view)
useTripStore.setState(s => ({ packingItems: [...s.packingItems, ...(data.items || [])] }))
toast.success(t('packing.templateApplied', { count: data.count }))
setActionsOpen(false)
@@ -177,10 +177,10 @@ export default function MTaskSheet({ planner, open, itemId, categories, members,
{cat}
</button>
))}
{/* A category nobody else uses yet (stored on this task or just typed)
has nothing to switch to — it is the active label, not a choice. */}
{category && !categories.includes(category) && (
<button type="button" onClick={() => setCategory(category)} className={pillCls(true)}>
{category}
</button>
<span className={pillCls(true)}>{category}</span>
)}
{!addingCategory ? (
<button
@@ -9,12 +9,17 @@ import type { TodoItem, TripMember } from '../../../../types'
import type { TripPlanner } from '../MTripShell'
import { TabScroller } from './tabChrome'
import {
PRIORITY_COLOR, PRIORITY_LABEL, filterTodoItems, isTodoOverdue, sortTodoRows,
todoCategories, todoCategoryOpenCount, todoCounts, type TodoFilter,
PRIORITY_COLOR, PRIORITY_LABEL, filterTodoItems, filterTodoItemsByCategory, isTodoOverdue,
sortTodoRows, todoCategories, todoCategoryOpenCount, todoCounts, type TodoSmartFilter,
} from './listsModel'
import MTaskSheet from './MTaskSheet'
const BUILTIN_FILTERS: TodoFilter[] = ['all', 'my', 'overdue', 'done']
const BUILTIN_FILTERS: TodoSmartFilter[] = ['all', 'my', 'overdue', 'done']
// The rail holds two kinds of bucket: the four built-ins, addressed by id, and
// the category buckets, addressed by name — so a category a user called "all"
// or "done" gets its own bucket instead of the built-in one.
type ActiveFilter = { kind: 'smart'; id: TodoSmartFilter } | { kind: 'category'; name: string }
/**
* To-do sub-tab (spec 03 §4.5-4.7): progress card with "New task", the
@@ -29,7 +34,7 @@ export default function MTodoListTab({ planner }: { planner: TripPlanner }) {
const currentUserId = useAuthStore(s => s.user?.id) ?? null
const tripMembers = planner.tripMembers
const [filter, setFilter] = useState<TodoFilter>('all')
const [active, setActive] = useState<ActiveFilter>({ kind: 'smart', id: 'all' })
const [sortByPriority, setSortByPriority] = useState(false)
const [editingItemId, setEditingItemId] = useState<number | null>(null)
const [creatingTask, setCreatingTask] = useState(false)
@@ -38,12 +43,18 @@ export default function MTodoListTab({ planner }: { planner: TripPlanner }) {
const categories = useMemo(() => todoCategories(items), [items])
const counts = todoCounts(items, currentUserId, today)
const rows = useMemo(
() => sortTodoRows(filterTodoItems(items, filter, currentUserId, today), sortByPriority, today),
[items, filter, currentUserId, today, sortByPriority],
() => sortTodoRows(
active.kind === 'category'
? filterTodoItemsByCategory(items, active.name)
: filterTodoItems(items, active.id, currentUserId, today),
sortByPriority,
today,
),
[items, active, currentUserId, today, sortByPriority],
)
const pct = items.length > 0 ? Math.round((counts.done / items.length) * 100) : 0
const defaultCategoryForNew = !BUILTIN_FILTERS.includes(filter) ? filter : null
const defaultCategoryForNew = active.kind === 'category' ? active.name : null
const openCreate = () => { setEditingItemId(null); setCreatingTask(true) }
const openEdit = (id: number) => { setCreatingTask(false); setEditingItemId(id) }
@@ -55,9 +66,9 @@ export default function MTodoListTab({ planner }: { planner: TripPlanner }) {
active ? 'bg-m-act text-m-actfg' : 'bg-[color:var(--m-ic)] text-m-ink'
}`
const filterLabel = (f: TodoFilter) =>
const filterLabel = (f: TodoSmartFilter) =>
f === 'all' ? t('todo.filter.all') : f === 'my' ? t('todo.filter.my') : f === 'overdue' ? t('todo.filter.overdue') : t('todo.filter.done')
const filterCount = (f: TodoFilter) =>
const filterCount = (f: TodoSmartFilter) =>
f === 'all' ? counts.open : f === 'my' ? counts.my : f === 'overdue' ? counts.overdue : counts.done
return (
@@ -87,7 +98,12 @@ export default function MTodoListTab({ planner }: { planner: TripPlanner }) {
{items.length > 0 && (
<div className="mt-[10px] flex items-center gap-[6px] overflow-x-auto whitespace-nowrap">
{BUILTIN_FILTERS.map(f => (
<button key={f} type="button" onClick={() => setFilter(f)} className={filterPill(filter === f)}>
<button
key={f}
type="button"
onClick={() => setActive({ kind: 'smart', id: f })}
className={filterPill(active.kind === 'smart' && active.id === f)}
>
{filterLabel(f)}
<span className="font-geist text-[0.5625rem] opacity-70">{filterCount(f)}</span>
</button>
@@ -103,7 +119,12 @@ export default function MTodoListTab({ planner }: { planner: TripPlanner }) {
</button>
{categories.length > 0 && <span className="h-4 w-px flex-none bg-[color:var(--m-rowbr)]" />}
{categories.map(cat => (
<button key={cat} type="button" onClick={() => setFilter(cat)} className={filterPill(filter === cat)}>
<button
key={cat}
type="button"
onClick={() => setActive({ kind: 'category', name: cat })}
className={filterPill(active.kind === 'category' && active.name === cat)}
>
{cat}
<span className="font-geist text-[0.5625rem] opacity-70">{todoCategoryOpenCount(items, cat)}</span>
</button>
@@ -160,7 +181,11 @@ function TaskCard({ item, members, today, onToggle, onOpen }: {
const assignee = members.find(m => m.id === item.assigned_user_id)
const prioColor = item.priority ? PRIORITY_COLOR[item.priority] : undefined
const avatarSrcUrl = assignee ? assignee.avatar_url || avatarSrc(assignee.avatar) : null
const dueLabel = item.due_date ? formatDate(item.due_date, locale) || item.due_date : null
// formatDate() renders "Invalid Date" for anything it can't parse — a due date
// that isn't a real date stays raw instead.
const dueLabel = item.due_date
? (Number.isNaN(Date.parse(`${item.due_date}T00:00:00Z`)) ? item.due_date : formatDate(item.due_date, locale))
: null
return (
<div className={`mt-2 flex items-start gap-[10px] rounded-2xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 py-[11px] ${done ? 'opacity-60' : ''}`}>
@@ -7,7 +7,7 @@ import { openFile } from '../../../../utils/fileDownload'
import { useTranslation } from '../../../../i18n'
import type { Reservation } from '../../../../types'
import MConfirmSheet from '../../settings/MConfirmSheet'
import { CountPill, Field, SectionHeader, StatusDot, TabScroller, TravelerAvatars, TravelerFilterRow } from './tabChrome'
import { ConfirmationCode, CountPill, Field, SectionHeader, StatusDot, TabScroller, TravelerAvatars, TravelerFilterRow } from './tabChrome'
import { STATUS_COLOR, type MTabScreenProps } from './tabModel'
import {
TRANSPORT_TYPE_COLOR,
@@ -205,71 +205,69 @@ function TransportCard({ res, planner, shell, canEdit, compact }: {
)}
</div>
{/* Body */}
{/* Body — split around the booking code so the reveal can be its own
control instead of a click handler buried inside the card button. */}
{!compact && (
<button type="button" onClick={openDetail} className="block w-full px-3 pb-3 pt-[9px] text-left">
<div className="flex gap-2">
<Field label={t('reservations.date')} className="flex-[1.4]">{dayValue}</Field>
<Field label={t('reservations.time')} className="flex-1" tabular>{timeValue}</Field>
</div>
<div className="px-3 pb-3 pt-[9px]">
<button type="button" onClick={openDetail} className="block w-full text-left">
<div className="flex gap-2">
<Field label={t('reservations.date')} className="flex-[1.4]">{dayValue}</Field>
<Field label={t('reservations.time')} className="flex-1" tabular>{timeValue}</Field>
</div>
</button>
{res.confirmation_number && (
<div className="mt-2">
<div className="mb-[3px] font-geist text-[0.5625rem] font-bold uppercase tracking-[.08em] text-m-faint">
{t('reservations.confirmationCode')}
</div>
<div
onClick={e => { if (blurCodes) { e.stopPropagation(); setCodeRevealed(v => !v) } }}
className={`overflow-hidden text-ellipsis whitespace-nowrap rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-[7px] text-center font-geist text-[0.71875rem] font-semibold tabular-nums text-m-ink ${
blurCodes && !codeRevealed ? 'blur-[4px] select-none' : ''
}`}
>
{res.confirmation_number}
</div>
</div>
<ConfirmationCode
code={res.confirmation_number}
label={t('reservations.confirmationCode')}
blurred={!!blurCodes && !codeRevealed}
onToggle={blurCodes ? () => setCodeRevealed(v => !v) : undefined}
/>
)}
{eps.length >= 2 && (
<div className="mt-2 flex flex-wrap items-center justify-center gap-2 rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-2 text-[0.71875rem] font-semibold text-m-ink">
{eps.map((ep, i) => (
<span key={i} className="inline-flex min-w-0 items-center gap-2">
{i > 0 && <TypeIcon size={12} strokeWidth={2.2} className="flex-none" style={{ color: typeColor }} />}
<span className="truncate">{ep.name}</span>
</span>
))}
</div>
)}
{metaCells.length > 0 && (
<div className="mt-2 flex gap-2">
{metaCells.slice(0, 3).map((c, i) => (
<Field key={i} label={c.label} className="flex-1">{c.value}</Field>
))}
</div>
)}
<TravelerAvatars travelers={res.travelers || []} label={t('reservations.travelers.label')} />
{files.length > 0 && (
<div className="mt-2">
<div className="mb-[3px] font-geist text-[0.5625rem] font-bold uppercase tracking-[.08em] text-m-faint">
{t('files.title')}
</div>
<div className="flex flex-col gap-1">
{files.map(f => (
<span
key={f.id}
onClick={e => { e.stopPropagation(); openFile(f.url, f.original_name) }}
className="flex items-center gap-[6px] rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-[7px]"
>
<FileText size={12} strokeWidth={2} className="flex-none text-m-muted" />
<span className="truncate font-geist text-[0.65625rem] font-semibold text-m-muted">{f.original_name}</span>
<button type="button" onClick={openDetail} className="block w-full text-left">
{eps.length >= 2 && (
<div className="mt-2 flex flex-wrap items-center justify-center gap-2 rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-2 text-[0.71875rem] font-semibold text-m-ink">
{eps.map((ep, i) => (
<span key={i} className="inline-flex min-w-0 items-center gap-2">
{i > 0 && <TypeIcon size={12} strokeWidth={2.2} className="flex-none" style={{ color: typeColor }} />}
<span className="truncate">{ep.name}</span>
</span>
))}
</div>
</div>
)}
</button>
)}
{metaCells.length > 0 && (
<div className="mt-2 flex gap-2">
{metaCells.slice(0, 3).map((c, i) => (
<Field key={i} label={c.label} className="flex-1">{c.value}</Field>
))}
</div>
)}
<TravelerAvatars travelers={res.travelers || []} label={t('reservations.travelers.label')} />
{files.length > 0 && (
<div className="mt-2">
<div className="mb-[3px] font-geist text-[0.5625rem] font-bold uppercase tracking-[.08em] text-m-faint">
{t('files.title')}
</div>
<div className="flex flex-col gap-1">
{files.map(f => (
<span
key={f.id}
onClick={e => { e.stopPropagation(); openFile(f.url, f.original_name) }}
className="flex items-center gap-[6px] rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-[7px]"
>
<FileText size={12} strokeWidth={2} className="flex-none text-m-muted" />
<span className="truncate font-geist text-[0.65625rem] font-semibold text-m-muted">{f.original_name}</span>
</span>
))}
</div>
</div>
)}
</button>
</div>
)}
<MConfirmSheet
@@ -105,7 +105,8 @@ export function isPackingPlaceholder(item: Pick<PackingItem, 'name'>): boolean {
// ── To-do ────────────────────────────────────────────────────────────────
export type TodoFilter = 'all' | 'my' | 'overdue' | 'done' | string
export type TodoSmartFilter = 'all' | 'my' | 'overdue' | 'done'
export type TodoFilter = TodoSmartFilter | string
export function isTodoOverdue(item: TodoItem, today: string): boolean {
return !!item.due_date && !item.checked && item.due_date < today
@@ -120,11 +121,21 @@ export function filterTodoItems(
): TodoItem[] {
if (filter === 'all') return items.filter(i => !i.checked)
if (filter === 'done') return items.filter(i => !!i.checked)
if (filter === 'my') return items.filter(i => !i.checked && i.assigned_user_id === currentUserId)
// No resolved user means nothing is "mine" — matching the todoCounts badge.
if (filter === 'my') return currentUserId ? items.filter(i => !i.checked && i.assigned_user_id === currentUserId) : []
if (filter === 'overdue') return items.filter(i => isTodoOverdue(i, today))
return items.filter(i => i.category === filter)
}
/**
* Category bucket, addressed by name instead of through `filterTodoItems` — a
* category literally called 'all'/'my'/'overdue'/'done' keeps its own rows
* rather than collapsing into the smart filter of the same id.
*/
export function filterTodoItemsByCategory(items: TodoItem[], category: string): TodoItem[] {
return items.filter(i => i.category === category)
}
/**
* Row order (spec 03 §4.7): done sinks to the end, open-overdue floats to the
* top, and — only while the priority toggle is on — ties break by ascending
@@ -88,6 +88,33 @@ export function Field({ label, children, className = '', tabular = false }: {
)
}
/**
* Booking code with the optional shoulder-surfing blur (setting
* blur_booking_codes). While the blur is on the box is a real button so the
* reveal works by keyboard too; without it there is nothing to operate and it
* stays a plain value box.
*/
export function ConfirmationCode({ code, label, blurred, onToggle }: {
code: string
label: string
blurred: boolean
onToggle?: () => void
}) {
const boxCls = `block w-full overflow-hidden text-ellipsis whitespace-nowrap rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-[7px] text-center font-geist text-[0.71875rem] font-semibold tabular-nums text-m-ink ${
blurred ? 'blur-[4px] select-none' : ''
}`
return (
<div className="mt-2">
<div className="mb-[3px] font-geist text-[0.5625rem] font-bold uppercase tracking-[.08em] text-m-faint">
{label}
</div>
{onToggle
? <button type="button" onClick={onToggle} aria-pressed={!blurred} className={boxCls}>{code}</button>
: <div className={boxCls}>{code}</div>}
</div>
)
}
/** 7px status dot; `color` is a --m-st-* token from STATUS_COLOR. */
export function StatusDot({ color }: { color: string }) {
return <span className="h-[7px] w-[7px] flex-none rounded-full" style={{ background: color }} />
@@ -452,8 +452,11 @@ function CalendarEditor({ cal, countries, calendarType = 'public_holiday', onUpd
const { t } = useTranslation()
const [label, setLabel] = useState(cal.label || '')
const [regions, setRegions] = useState<Option[]>([])
const country = cal.region.split('-')[0]
const region = cal.region.includes('-') ? cal.region : ''
// A school-holiday group carries a `|group:…` suffix — strip it before the
// country is read off, otherwise the region lookup finds nothing.
const [baseRegion] = cal.region.split('|')
const country = baseRegion.split('-')[0]
const region = cal.region.includes('|group:') || baseRegion.includes('-') ? cal.region : ''
useEffect(() => { setLabel(cal.label || '') }, [cal.label])
useEffect(() => {
@@ -498,8 +501,9 @@ function AddCalendarDraft({ countries, calendarType = 'public_holiday', onAdd, o
const [label, setLabel] = useState('')
const [regions, setRegions] = useState<Option[]>([])
const country = region.split('-')[0] || ''
const selectedRegion = region.includes('-') ? region : ''
const [baseRegion] = region.split('|')
const country = baseRegion.split('-')[0] || ''
const selectedRegion = region.includes('|group:') || baseRegion.includes('-') ? region : ''
useEffect(() => {
if (!country) { setRegions([]); return }