feat(mobile): refine TREK navigation and interfaces

This commit is contained in:
Maurice
2026-12-03 23:06:17 +01:00
parent 995e9c435f
commit 00955f0ac5
553 changed files with 17703 additions and 13101 deletions
+7 -110
View File
@@ -1,31 +1,22 @@
import type { CollabLink } from '@trek/shared'
import { focusRevealedEditor } from '../shared/dialogFocus'
import { cloneElement, CSSProperties, FormEvent, ReactElement, useEffect, useId, useRef, useState } from 'react'
import { cloneElement, CSSProperties, FormEvent, ReactElement, useId, useState } from 'react'
import { createPortal } from 'react-dom'
import { ExternalLink, Link2, Pencil, Pin, Plus, Trash2, X } from 'lucide-react'
import CollabPanelHead, { HEAD_ACTION } from './CollabPanelHead'
import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT } from '../shared/DialogShell'
import { EditorField, INPUT } from '../shared/dialogParts'
import { useIsPhone } from '../../mobile/useIsPhone'
import { collabApi } from '../../api/client'
import { addListener, removeListener } from '../../api/websocket'
import { useTranslation } from '../../i18n'
import { useCanDo } from '../../store/permissionsStore'
import { useTripStore } from '../../store/tripStore'
import ConfirmDialog from '../shared/ConfirmDialog'
import EmptyState from '../shared/EmptyState'
import { Tooltip } from '../shared/Tooltip'
import { useToast } from '../shared/Toast'
import { offlineOr } from '../../utils/needsConnection'
import { collabLinkHost, useCollabLinks } from './useCollabLinks'
const FONT = "var(--font-system)"
interface CollabLink {
id: number
title: string
url: string
pinned: boolean | number
}
// The glyph holds the place until a favicon has really arrived: a host that never
// answers, or answers with a blank pixel, left the chip with an empty square.
function LinkIcon({ url }: { url: string }) {
@@ -56,10 +47,6 @@ function ChipTip({ label, phone, children }: { label: string; phone: boolean; ch
return phone ? cloneElement(children, { title: label }) : <Tooltip label={label}>{children}</Tooltip>
}
function hostOf(url: string): string {
try { return new URL(url).hostname.replace(/^www\./, '') } catch { return url }
}
/**
* The add and edit form as a modal, like the poll and note panels next to it.
* Inline it pushed the list down and gave the panel a second header, which is
@@ -173,101 +160,11 @@ export default function CollabLinks({ tripId }: { tripId: number }) {
const isPhone = useIsPhone()
const trip = useTripStore(s => s.trip)
const canEdit = useCanDo()('collab_edit', trip)
const toast = useToast()
const [links, setLinks] = useState<CollabLink[]>([])
const { links, save, toggle, remove } = useCollabLinks(tripId)
const [showForm, setShowForm] = useState(false)
const [editing, setEditing] = useState<CollabLink | null>(null)
const [pendingDeleteId, setPendingDeleteId] = useState<number | null>(null)
// Both are new objects on every render, so depending on them would reload the
// list after each keystroke and drop a link that was just added back out of it.
const toastRef = useRef(toast)
toastRef.current = toast
const tRef = useRef(t)
tRef.current = t
useEffect(() => {
let cancelled = false
collabApi.getLinks(tripId)
.then(d => { if (!cancelled) setLinks(d.links || []) })
.catch(err => {
if (cancelled) return
console.error('Failed to load collab links:', err)
toastRef.current.error(tRef.current('common.error'))
})
return () => { cancelled = true }
}, [tripId])
// Live sync, the same shape the notes panel uses. Without it the three
// collab:link events the server broadcasts would arrive nowhere and a link
// somebody else added would only appear on the next reload.
useEffect(() => {
if (!tripId) return
const handler = (msg: { type?: string; tripId?: number | string; link?: CollabLink; linkId?: number }) => {
// The panel is not remounted on a trip change, so an event still in
// flight from the trip we just left must not land in this list.
if (String(msg?.tripId) !== String(tripId)) return
if (msg.type === 'collab:link:created' && msg.link) {
setLinks(prev => prev.some(l => l.id === msg.link!.id) ? prev : [msg.link!, ...prev])
}
if (msg.type === 'collab:link:updated' && msg.link) {
setLinks(prev => prev
.map(l => l.id === msg.link!.id ? { ...l, ...msg.link! } : l)
.sort((a, b) => Number(b.pinned) - Number(a.pinned)))
}
if (msg.type === 'collab:link:deleted' && msg.linkId) {
setLinks(prev => prev.filter(l => l.id !== msg.linkId))
}
}
addListener(handler)
return () => removeListener(handler)
}, [tripId])
// Every write says something when it fails. Silence left the pin looking
// unchanged and the delete looking ignored, with an unhandled rejection in
// the console as the only trace.
const add = async (data: { title: string; url: string }) => {
try {
const d = await collabApi.createLink(tripId, data)
setLinks(v => [d.link, ...v])
} catch (err) {
console.error('Failed to add collab link:', err)
toast.error(offlineOr(t, t('common.error')))
throw err
}
}
const toggle = async (link: CollabLink) => {
try {
const d = await collabApi.updateLink(tripId, link.id, { pinned: !link.pinned })
setLinks(v => v.map(x => x.id === link.id ? d.link : x).sort((a, b) => Number(b.pinned) - Number(a.pinned)))
} catch (err) {
console.error('Failed to pin collab link:', err)
toast.error(offlineOr(t, t('common.error')))
}
}
const edit = async (link: CollabLink, data: { title: string; url: string }) => {
try {
const d = await collabApi.updateLink(tripId, link.id, data)
setLinks(v => v.map(x => x.id === link.id ? d.link : x))
} catch (err) {
console.error('Failed to edit collab link:', err)
toast.error(offlineOr(t, t('common.error')))
throw err
}
}
const remove = async (id: number) => {
try {
await collabApi.deleteLink(tripId, id)
setLinks(v => v.filter(x => x.id !== id))
} catch (err) {
console.error('Failed to delete collab link:', err)
toast.error(offlineOr(t, t('common.error')))
}
}
return (
<div style={{ height: '100%', display: 'flex', flexDirection: 'column', fontFamily: FONT }}>
{/* Header: the desktop's head band; the phone keeps its own */}
@@ -316,7 +213,7 @@ export default function CollabLinks({ tripId }: { tripId: number }) {
<LinkIcon key={link.url} url={link.url} />
<span className="collab-link-chip__text">
<span className="collab-link-chip__title">{link.title}</span>
<span className="collab-link-chip__host">{hostOf(link.url)}</span>
<span className="collab-link-chip__host">{collabLinkHost(link.url)}</span>
</span>
</a>
</ChipTip>
@@ -346,8 +243,8 @@ export default function CollabLinks({ tripId }: { tripId: number }) {
</div>
{/* Create and edit modals */}
{showForm && <LinkModal onClose={() => setShowForm(false)} onSave={add} />}
{editing && <LinkModal key={editing.id} link={editing} onClose={() => setEditing(null)} onSave={data => edit(editing, data)} />}
{showForm && <LinkModal onClose={() => setShowForm(false)} onSave={save} />}
{editing && <LinkModal key={editing.id} link={editing} onClose={() => setEditing(null)} onSave={data => save(data, editing.id)} />}
{/* The delete is shared: the link goes for every member, and on the phone the
button is a thumb's width from pin. Same guard as the notes panel. */}
@@ -51,6 +51,9 @@ export function useCollabChatData({
}: CollabChatDataOptions) {
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState(false);
const [loadAttempt, setLoadAttempt] = useState(0);
const retryLoad = useCallback(() => setLoadAttempt((attempt) => attempt + 1), []);
const [hasMore, setHasMore] = useState(false);
const [loadingMore, setLoadingMore] = useState(false);
const [text, setText] = useState('');
@@ -96,6 +99,7 @@ export function useCollabChatData({
useEffect(() => {
let cancelled = false;
setLoading(true);
setLoadError(false);
collabApi
.getMessages(tripId)
.then((data: MessagesResponse) => {
@@ -107,12 +111,14 @@ export function useCollabChatData({
setTimeout(() => scrollToBottom(), 30);
})
.catch(() => {
if (!cancelled) setLoading(false);
if (cancelled) return;
setLoadError(true);
setLoading(false);
});
return () => {
cancelled = true;
};
}, [tripId, scrollToBottom]);
}, [tripId, loadAttempt, scrollToBottom]);
useEffect(() => {
const handler = (event: Record<string, unknown>) => {
@@ -259,6 +265,8 @@ export function useCollabChatData({
messages,
setMessages,
loading,
loadError,
retryLoad,
setLoading,
hasMore,
setHasMore,
@@ -0,0 +1,126 @@
import type { CollabLink } from '@trek/shared';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from '../../i18n';
import { collabLinkRepo, type LinkFields } from '../../repo/collabLinkRepo';
import { offlineOr } from '../../utils/needsConnection';
import { useToast } from '../shared/Toast';
type LinksState = { tripId: number; links: CollabLink[]; status: 'loading' | 'ready' | 'error' };
const EMPTY_LINKS: CollabLink[] = [];
export function collabLinkHost(url: string): string {
try {
return new URL(url).hostname.replace(/^www\./, '');
} catch {
return url;
}
}
function insertLink(links: CollabLink[], link: CollabLink): CollabLink[] {
return links.some((row) => row.id === link.id) ? links : [link, ...links];
}
function updateLink(links: CollabLink[], link: CollabLink): CollabLink[] {
return links
.map((row) => (row.id === link.id ? { ...row, ...link } : row))
.sort((a, b) => Number(b.pinned) - Number(a.pinned));
}
export function useCollabLinks(tripId: number) {
const { t } = useTranslation();
const toast = useToast();
const [state, setState] = useState<LinksState>({ tripId, links: EMPTY_LINKS, status: 'loading' });
const [attempt, setAttempt] = useState(0);
const reportLoadError = useRef(() => toast.error(t('common.error')));
reportLoadError.current = () => toast.error(t('common.error'));
useEffect(() => {
let cancelled = false;
const changes: Array<(links: CollabLink[]) => CollabLink[]> = [];
let reading = true;
setState((current) => ({
tripId,
links: current.tripId === tripId ? current.links : EMPTY_LINKS,
status: 'loading',
}));
const handler = (msg: { type?: string; tripId?: number | string; link?: CollabLink; linkId?: number }) => {
if (String(msg.tripId) !== String(tripId)) return;
const { link, linkId } = msg;
const change =
msg.type === 'collab:link:created' && link
? (links: CollabLink[]) => insertLink(links, link)
: msg.type === 'collab:link:updated' && link
? (links: CollabLink[]) => updateLink(links, link)
: msg.type === 'collab:link:deleted' && linkId
? (links: CollabLink[]) => links.filter((row) => row.id !== linkId)
: null;
if (!change) return;
if (reading) changes.push(change);
setState((current) => (current.tripId === tripId ? { ...current, links: change(current.links) } : current));
};
const unsubscribe = collabLinkRepo.subscribe(handler);
void collabLinkRepo.list(tripId).then(
(data) => {
if (cancelled) return;
reading = false;
const links = changes.reduce((rows, change) => change(rows), data.links || []);
setState({ tripId, links, status: 'ready' });
},
() => {
if (cancelled) return;
reading = false;
setState((current) => ({ ...current, status: 'error' }));
reportLoadError.current();
}
);
return () => {
cancelled = true;
unsubscribe();
};
}, [tripId, attempt]);
const changeLinks = (update: (links: CollabLink[]) => CollabLink[]) =>
setState((current) => (current.tripId === tripId ? { ...current, links: update(current.links) } : current));
const reportWriteError = () => toast.error(offlineOr(t, t('common.error')));
const save = async (data: LinkFields, id?: number) => {
try {
const { link } =
id == null ? await collabLinkRepo.create(tripId, data) : await collabLinkRepo.update(tripId, id, data);
changeLinks((links) => (id == null ? insertLink(links, link) : updateLink(links, link)));
} catch (error) {
reportWriteError();
throw error;
}
};
const toggle = async (link: CollabLink) => {
try {
const { link: saved } = await collabLinkRepo.update(tripId, link.id, { pinned: !link.pinned });
changeLinks((links) => updateLink(links, saved));
} catch {
reportWriteError();
}
};
const remove = async (id: number) => {
try {
await collabLinkRepo.remove(tripId, id);
changeLinks((links) => links.filter((link) => link.id !== id));
} catch {
reportWriteError();
}
};
return {
links: state.tripId === tripId ? state.links : EMPTY_LINKS,
status: state.tripId === tripId ? state.status : 'loading',
retry: () => setAttempt((value) => value + 1),
save,
toggle,
remove,
};
}
@@ -122,7 +122,7 @@ describe('DuplicatePairCard', () => {
const user = userEvent.setup();
const { props, container } = setup({ variant: 'sheet' });
const card = within(container).getByRole('article');
expect(card.className).toContain('bg-m-sheet');
expect(card).toHaveClass('bg-m-ic');
expect(screen.getByText('The same name at the same spot')).toBeInTheDocument();
await user.click(screen.getAllByRole('button', { name: /Keep this one/ })[1]);
expect(props.onMerge).toHaveBeenCalledWith('b');
@@ -8,7 +8,7 @@ const LOOK = {
dialog: {
card: 'rounded-xl border border-edge-faint bg-surface-secondary p-3',
side: 'flex min-w-0 flex-col gap-1.5 rounded-lg bg-surface-card p-2.5',
name: 'text-body font-semibold text-content',
name: 'truncate text-body font-semibold text-content',
sub: 'text-caption text-content-faint',
diff: 'rounded bg-warning-soft px-1 text-content',
chip: 'inline-flex max-w-full items-center gap-1 rounded-full border border-edge-faint px-2 py-0.5 text-caption text-content-muted',
@@ -18,16 +18,16 @@ const LOOK = {
link: 'text-caption font-semibold text-content-muted hover:text-content disabled:opacity-50',
},
sheet: {
card: 'rounded-2xl border border-m-rowbr bg-m-sheet p-3',
side: 'flex min-w-0 flex-col gap-1.5 rounded-xl bg-m-sheetop p-2.5',
name: 'text-body font-bold text-m-ink',
card: 'rounded-[14px] bg-m-ic p-3',
side: 'flex min-w-0 flex-col gap-2 rounded-xl border border-m-rowbr bg-m-sheetop p-2.5',
name: 'line-clamp-2 break-words text-control font-semibold leading-tight text-m-ink',
sub: 'text-caption text-m-muted',
diff: 'rounded bg-warning-soft px-1 text-m-ink',
chip: 'inline-flex max-w-full items-center gap-1 rounded-full border border-m-rowbr bg-m-ic px-2 py-0.5 text-caption text-m-muted',
keep: 'inline-flex items-center justify-center gap-1.5 rounded-full border border-m-rowbr bg-m-ic px-2.5 py-[7px] text-caption font-semibold text-m-ink disabled:opacity-50',
keep: 'inline-flex min-h-11 items-center justify-center gap-1.5 rounded-xl bg-m-ic px-2 py-2 text-start text-caption font-semibold leading-tight text-m-ink disabled:opacity-50',
reason: 'text-caption font-semibold text-m-muted',
note: 'text-caption text-m-faint',
link: 'text-caption font-semibold text-m-muted disabled:opacity-50',
link: 'min-h-11 rounded-xl px-2 text-start text-control font-medium text-m-muted active:bg-m-sheetop disabled:opacity-50',
},
} as const;
@@ -54,7 +54,7 @@ function Side({
differing.includes(field) ? <span className={look.diff}>{text}</span> : text;
return (
<div className={look.side}>
<span dir="auto" className={`${look.name} truncate`}>
<span dir="auto" className={look.name}>
{mark('name', side.name)}
</span>
{(side.address || differing.includes('address')) && (
@@ -77,7 +77,11 @@ function Side({
</span>
{canMerge && (
<button type="button" onClick={onKeep} disabled={busy} className={`mt-auto ${look.keep}`}>
{busy ? <Loader2 size={12} className="animate-spin" /> : <Check size={12} />}{' '}
{busy ? (
<Loader2 size={12} className="flex-none animate-spin" aria-hidden />
) : (
<Check size={12} className="flex-none" aria-hidden />
)}
{t('collections.duplicates.keepThis')}
</button>
)}
@@ -85,6 +85,35 @@ describe('parseEntryKey and entryHasPosition', () => {
});
describe('usePlacesLibrary: the first page', () => {
it('uses the restored filters on its first request and opens the previous place', async () => {
const restoredDetail = libraryDetail(libraryEntry(), []);
list.mockResolvedValue(libraryPage([]));
detail.mockResolvedValue(restoredDetail);
const { result } = renderHook(() =>
usePlacesLibrary({
t,
active: true,
initialKey: 'trip:42',
initialFilters: {
search: 'Coffee',
kind: 'trip',
categoryId: 3,
sort: 'rating',
status: 'all',
minRating: 4,
tagNames: ['Morning'],
},
})
);
await waitFor(() => expect(result.current.detail).toBe(restoredDetail));
expect(list).toHaveBeenCalledWith(
{ q: 'Coffee', kind: 'trip', category_id: 3, sort: 'rating', min_rating: 4, tags: ['Morning'], limit: 60 },
expect.any(AbortSignal)
);
expect(detail).toHaveBeenCalledWith('trip', 42, expect.any(AbortSignal));
expect(result.current.search).toBe('Coffee');
});
it('FE-COMP-PLACESLIBHOOK-003: asks nothing while inactive and loads once it becomes active', async () => {
list.mockResolvedValue(libraryPage([]));
const { rerender, result } = mount(false);
@@ -17,6 +17,16 @@ import { getApiErrorMessage } from '../../utils/apiError';
/** Which origins the overview shows: all, only trip places, only saved ones. */
export type LibraryKindFilter = 'all' | PlacesLibraryKind;
export interface PlacesLibraryFilters {
search: string;
kind: LibraryKindFilter;
categoryId: number | 'all';
sort: PlacesLibrarySort;
status: CollectionStatus | 'all';
minRating: number | 'all';
tagNames: string[];
}
const PAGE = 60;
/** How long typing settles before the search asks the server. */
const SEARCH_SETTLE_MS = 250;
@@ -77,17 +87,17 @@ function failureOf(err: unknown, t: TranslationFn): { error: string | null; offl
}
/** The filters of "All places". */
function useLibraryFilters() {
const [search, setSearch] = useState('');
const [query, setQuery] = useState('');
const [kind, setKind] = useState<LibraryKindFilter>('all');
const [categoryId, setCategoryId] = useState<number | 'all'>('all');
const [sort, setSort] = useState<PlacesLibrarySort>('name');
const [status, setStatus] = useState<CollectionStatus | 'all'>('all');
function useLibraryFilters(initial?: PlacesLibraryFilters) {
const [search, setSearch] = useState(initial?.search ?? '');
const [query, setQuery] = useState(initial?.search.trim() ?? '');
const [kind, setKind] = useState<LibraryKindFilter>(initial?.kind ?? 'all');
const [categoryId, setCategoryId] = useState<number | 'all'>(initial?.categoryId ?? 'all');
const [sort, setSort] = useState<PlacesLibrarySort>(initial?.sort ?? 'name');
const [status, setStatus] = useState<CollectionStatus | 'all'>(initial?.status ?? 'all');
// At least this many stars on the average of the votes, as the lists filter; unrated places drop out.
const [minRating, setMinRating] = useState<number | 'all'>('all');
const [minRating, setMinRating] = useState<number | 'all'>(initial?.minRating ?? 'all');
// PLC-21: tag names of the lists and trips, any of which an entry must carry, whatever their case.
const [tagNames, setTagNames] = useState<string[]>([]);
const [tagNames, setTagNames] = useState<string[]>(initial?.tagNames ?? []);
const toggleTagName = useCallback(
(name: string) =>
setTagNames((names) => {
@@ -158,8 +168,8 @@ function useLibraryFilters() {
}
/** The first page for the filters and the pages "more" appends. */
function useLibraryPages(active: boolean, reloadSeq: number, t: TranslationFn) {
const { filters, controls } = useLibraryFilters();
function useLibraryPages(active: boolean, reloadSeq: number, t: TranslationFn, initial?: PlacesLibraryFilters) {
const { filters, controls } = useLibraryFilters(initial);
const [page, setPage] = useState<PageState>(EMPTY_PAGE);
// The request "more" is loading for; another key means the button is free again.
const [moreFor, setMoreFor] = useState<string | null>(null);
@@ -231,8 +241,13 @@ function useLibraryPages(active: boolean, reloadSeq: number, t: TranslationFn) {
}
/** The entry that is open and what its origins keep. */
function useLibraryDetail(entries: readonly PlacesLibraryEntry[], reloadSeq: number, onError: (err: unknown) => void) {
const [selectedKey, setSelectedKey] = useState<string | null>(null);
function useLibraryDetail(
entries: readonly PlacesLibraryEntry[],
reloadSeq: number,
onError: (err: unknown) => void,
initialKey?: string
) {
const [selectedKey, setSelectedKey] = useState<string | null>(initialKey ?? null);
const [loaded, setLoaded] = useState<{ key: string; detail: PlacesLibraryDetailResponse } | null>(null);
const [settled, setSettled] = useState<string | null>(null);
// Where the open entry is read from, as text so a page arriving later does not ask again.
@@ -348,15 +363,25 @@ export function useTagOptions(entries: readonly PlacesLibraryEntry[], picked: re
* fresh first page, "more" appends the next one, and opening an entry loads what
* each of its origins keeps.
*/
export function usePlacesLibrary({ active, t }: { active: boolean; t: TranslationFn }) {
export function usePlacesLibrary({
active,
t,
initialFilters,
initialKey,
}: {
active: boolean;
t: TranslationFn;
initialFilters?: PlacesLibraryFilters;
initialKey?: string;
}) {
const [ownSeq, setReloadSeq] = useState(0);
// A place saved to a list from here or anywhere else adds an origin: read again then too.
const savedVersion = useSaveToCollectionStore((st) => st.version);
const reloadSeq = ownSeq + savedVersion;
const [detailError, setDetailError] = useState<{ error: string | null; offline: boolean } | null>(null);
const pages = useLibraryPages(active, reloadSeq, t);
const pages = useLibraryPages(active, reloadSeq, t, initialFilters);
const onDetailError = useCallback((err: unknown) => setDetailError(failureOf(err, t)), [t]);
const sel = useLibraryDetail(pages.page.entries, reloadSeq, onDetailError);
const sel = useLibraryDetail(pages.page.entries, reloadSeq, onDetailError, initialKey);
const cover = useLibraryCover(sel.detail);
const reload = useCallback(() => {
setDetailError(null);
@@ -6,6 +6,7 @@ import userEvent from '@testing-library/user-event'
import { render, screen, waitFor, act } from '../../../tests/helpers/render'
import { server } from '../../../tests/helpers/msw/server'
import ContributorInviteDialog from './ContributorInviteDialog'
import MJourneyInviteFrame from '../../mobile/screens/journey/MJourneyInviteFrame'
type ToastKind = 'success' | 'error' | 'warning' | 'info'
@@ -198,29 +199,22 @@ describe('ContributorInviteDialog on a phone', () => {
Object.defineProperty(window, 'innerWidth', { value: width, configurable: true, writable: true })
})
it('FE-JRN-INVITE-013: keeps the panel it had, with the filled role button and the header close', async () => {
it('FE-JRN-INVITE-013: uses the mobile sheet with a labelled role selector and close action', async () => {
const user = userEvent.setup()
const { onClose, onInvited } = mountDialog()
const { onClose, onInvited } = mountDialog({ Frame: MJourneyInviteFrame })
await screen.findByText('maurice')
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(screen.getByRole('dialog', { name: 'Invite Contributor' })).toBeInTheDocument()
const viewerBtn = screen.getByRole('button', { name: 'Viewer' })
const editorBtn = screen.getByRole('button', { name: 'Editor' })
expect(viewerBtn.className).toContain('bg-zinc-900')
expect(editorBtn.className).not.toContain('bg-zinc-900')
expect(viewerBtn).toHaveAttribute('aria-pressed', 'true')
expect(editorBtn).toHaveAttribute('aria-pressed', 'false')
await user.click(editorBtn)
expect(editorBtn.className).toContain('bg-zinc-900')
expect(viewerBtn.className).not.toContain('bg-zinc-900')
expect(editorBtn).toHaveAttribute('aria-pressed', 'true')
expect(viewerBtn).toHaveAttribute('aria-pressed', 'false')
// The header close button carries only an icon, so it is addressed by position.
const headerClose = screen.getByRole('heading', { name: 'Invite Contributor' })
.parentElement!.querySelector('button')!
act(() => { headerClose.click() })
expect(onClose).toHaveBeenCalledTimes(1)
// Escape is the desktop's: the phone panel never had it.
await user.keyboard('{Escape}')
await user.click(screen.getByRole('button', { name: 'Close' }))
expect(onClose).toHaveBeenCalledTimes(1)
expect(onInvited).not.toHaveBeenCalled()
})
@@ -232,7 +226,7 @@ describe('ContributorInviteDialog on a phone', () => {
return HttpResponse.json({ ok: true })
}))
const user = userEvent.setup()
const { onInvited } = mountDialog({ existingUserIds: [1] })
const { onInvited } = mountDialog({ existingUserIds: [1], Frame: MJourneyInviteFrame })
await screen.findByText('julien')
await user.type(screen.getByPlaceholderText('Username or email...'), 'zzz')
@@ -1,4 +1,4 @@
import { useEffect, useId, useState } from 'react'
import { useEffect, useId, useState, type ComponentType } from 'react'
import { X, Check, UserPlus, Search, Loader2 } from 'lucide-react'
import { journeyApi, authApi } from '../../api/client'
import { useTranslation } from '../../i18n'
@@ -10,37 +10,56 @@ import { TripMemberAvatar } from '../Trips/TripMemberAvatar'
import { avatarSrc } from '../../utils/avatarSrc'
const ROLES = ['viewer', 'editor'] as const
type InviteRole = (typeof ROLES)[number]
type InviteUser = { id: number; username: string; email?: string; avatar?: string | null }
export interface ContributorInviteFrameProps {
users: InviteUser[]
loading: boolean
search: string
onSearch: (value: string) => void
selectedUserId: number | null
onSelectUser: (id: number) => void
role: InviteRole
roles: readonly InviteRole[]
onRoleChange: (role: InviteRole) => void
sending: boolean
onClose: () => void
onInvite: () => Promise<void>
}
/**
* Adds a person to a journey. The desktop draws it in the planner's dialog
* frame; the phone, which opens it from its journey screen, keeps the panel it
* has always had. Both read and write the same state below.
*/
export default function ContributorInviteDialog({ journeyId, existingUserIds, onClose, onInvited }: {
export default function ContributorInviteDialog({ journeyId, existingUserIds, onClose, onInvited, Frame }: {
journeyId: number
existingUserIds: number[]
onClose: () => void
onInvited: () => void
Frame?: ComponentType<ContributorInviteFrameProps>
}) {
const { t } = useTranslation()
const phone = useIsPhone()
const labelId = useId()
const [users, setUsers] = useState<{ id: number; username: string; email?: string; avatar?: string | null }[]>([])
const [users, setUsers] = useState<InviteUser[]>([])
const [loading, setLoading] = useState(true)
const [search, setSearch] = useState('')
const [selectedUserId, setSelectedUserId] = useState<number | null>(null)
const [role, setRole] = useState<'editor' | 'viewer'>('viewer')
const [role, setRole] = useState<InviteRole>('viewer')
const [sending, setSending] = useState(false)
const toast = useToast()
useEffect(() => {
authApi.listUsers().then(d => setUsers(d.users || [])).catch(() => {})
authApi.listUsers().then(d => setUsers(d.users || [])).catch(() => {}).finally(() => setLoading(false))
}, [])
// Captured and stopped on the desktop: the dialog is usually opened from the
// journey settings, which close on Escape as well, and one key press should
// only take back this dialog, not the one under it.
useEffect(() => {
if (phone) return
if (phone || Frame) return
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return
e.stopPropagation()
@@ -48,7 +67,7 @@ export default function ContributorInviteDialog({ journeyId, existingUserIds, on
}
document.addEventListener('keydown', onKey, true)
return () => document.removeEventListener('keydown', onKey, true)
}, [phone, onClose])
}, [phone, Frame, onClose])
const filtered = users.filter(u => {
if (existingUserIds.includes(u.id)) return false
@@ -59,7 +78,7 @@ export default function ContributorInviteDialog({ journeyId, existingUserIds, on
})
const handleInvite = async () => {
if (!selectedUserId) return
if (!selectedUserId || sending) return
setSending(true)
try {
await journeyApi.addContributor(journeyId, selectedUserId, role)
@@ -72,6 +91,12 @@ export default function ContributorInviteDialog({ journeyId, existingUserIds, on
}
}
if (Frame) {
return <Frame users={filtered} loading={loading} search={search} onSearch={setSearch}
selectedUserId={selectedUserId} onSelectUser={setSelectedUserId} role={role} roles={ROLES}
onRoleChange={setRole} sending={sending} onClose={onClose} onInvite={handleInvite} />
}
if (phone) {
return (
<div className="fixed inset-0 z-[200] flex items-center justify-center p-5 bg-[rgba(9,9,11,0.75)]">
@@ -32,6 +32,7 @@ interface Props {
publicHint?: boolean;
/** Start unfolded, where the thread already has a section of its own. */
defaultOpen?: boolean;
mobile?: boolean;
}
const GUEST_NAME_KEY = 'trek.journey.guestName';
@@ -68,9 +69,10 @@ export default function JourneyEntryComments({
onDelete,
publicHint,
defaultOpen,
mobile = false,
}: Props) {
const { t, locale } = useTranslation();
const [open, setOpen] = useState(!!defaultOpen);
const [expanded, setExpanded] = useState<boolean | null>(null);
const [body, setBody] = useState('');
const [name, setName] = useState(guest ? rememberedName : '');
const [trap, setTrap] = useState('');
@@ -78,6 +80,7 @@ export default function JourneyEntryComments({
const [message, setMessage] = useState<string | null>(null);
if (!canWrite && comments.length === 0) return null;
const open = expanded ?? Boolean(defaultOpen || (mobile && comments.length));
const submit = async (e: FormEvent) => {
e.preventDefault();
@@ -108,9 +111,13 @@ export default function JourneyEntryComments({
aria-expanded={open}
onClick={(e) => {
e.stopPropagation();
setOpen((shown) => !shown);
setExpanded(!open);
}}
className="inline-flex items-center gap-1.5 self-start text-caption font-medium text-content-faint transition-colors hover:text-content"
className={
mobile
? 'flex min-h-11 w-full items-center gap-2 rounded-xl bg-m-sheetop px-3 text-start text-control font-medium text-m-ink'
: 'inline-flex items-center gap-1.5 self-start text-caption font-medium text-content-faint transition-colors hover:text-content'
}
>
<MessageCircle size={13} />
{comments.length > 0 ? t('journey.comments.count', { count: comments.length }) : t('journey.comments.write')}
@@ -121,7 +128,7 @@ export default function JourneyEntryComments({
return (
// The thread sits inside clickable cards: a click in it must not open the entry.
<div className="flex flex-col gap-3" onClick={(e) => e.stopPropagation()} role="presentation">
{!defaultOpen && toggle}
{!defaultOpen && !mobile && toggle}
{comments.length > 0 && (
<ul className="flex flex-col gap-2.5">
{comments.map((c) => {
@@ -149,7 +156,13 @@ export default function JourneyEntryComments({
<p className="mt-0.5 whitespace-pre-wrap break-words text-body text-content-muted">{c.body}</p>
</div>
{(mayHide || mayDelete) && (
<div className="flex flex-none items-center gap-0.5 opacity-40 transition-opacity group-hover:opacity-100">
<div
className={
mobile
? 'flex flex-none items-center gap-0.5'
: 'flex flex-none items-center gap-0.5 opacity-40 transition-opacity group-hover:opacity-100'
}
>
{mayHide && (
<Tooltip
label={c.hidden ? t('journey.comments.show') : t('journey.comments.hide')}
@@ -159,7 +172,7 @@ export default function JourneyEntryComments({
type="button"
aria-label={c.hidden ? t('journey.comments.show') : t('journey.comments.hide')}
onClick={() => void onHide?.(c.id, !c.hidden)}
className="flex h-7 w-7 items-center justify-center rounded-full text-content-faint hover:bg-surface-secondary hover:text-content"
className={`flex ${mobile ? 'size-11' : 'size-7'} items-center justify-center rounded-full text-content-faint hover:bg-surface-secondary hover:text-content`}
>
{c.hidden ? <Eye size={13} /> : <EyeOff size={13} />}
</button>
@@ -171,7 +184,7 @@ export default function JourneyEntryComments({
type="button"
aria-label={t('common.delete')}
onClick={() => void onDelete?.(c.id)}
className="flex h-7 w-7 items-center justify-center rounded-full text-content-faint hover:bg-danger-soft hover:text-danger"
className={`flex ${mobile ? 'size-11' : 'size-7'} items-center justify-center rounded-full text-content-faint hover:bg-danger-soft hover:text-danger`}
>
<Trash2 size={13} />
</button>
@@ -216,14 +229,22 @@ export default function JourneyEntryComments({
rows={1}
placeholder={t('journey.comments.write')}
aria-label={t('journey.comments.write')}
className="max-h-40 min-h-[38px] flex-1 resize-none rounded-xl border border-edge bg-surface px-3 py-2 text-body text-content outline-none [field-sizing:content] placeholder:text-content-faint focus:border-content-faint"
className={`max-h-40 min-w-0 flex-1 resize-none rounded-xl border px-3 py-2 text-body outline-none [field-sizing:content] ${
mobile
? 'min-h-11 border-m-rowbr bg-m-sheetop text-m-ink placeholder:text-m-muted'
: 'min-h-[38px] border-edge bg-surface text-content placeholder:text-content-faint focus:border-content-faint'
}`}
/>
<Tooltip label={t('journey.comments.send')} placement="top">
<button
type="submit"
aria-label={t('journey.comments.send')}
disabled={busy || !body.trim() || (guest && !name.trim())}
className="flex h-[38px] w-[38px] flex-none items-center justify-center rounded-full bg-accent text-accent-text transition-opacity hover:bg-accent-hover disabled:opacity-40"
className={`flex flex-none items-center justify-center rounded-full transition-opacity disabled:opacity-40 ${
mobile
? 'size-11 bg-m-act text-m-actfg'
: 'size-[38px] bg-accent text-accent-text hover:bg-accent-hover'
}`}
>
<SendHorizontal size={15} />
</button>
@@ -231,7 +252,9 @@ export default function JourneyEntryComments({
</div>
{message && <p className="text-caption text-danger">{message}</p>}
{publicHint && !guest && (
<p className="text-caption text-content-faint">{t('journey.comments.publicHint')}</p>
<p className={`text-caption ${mobile ? 'font-normal text-m-muted' : 'text-content-faint'}`}>
{t('journey.comments.publicHint')}
</p>
)}
</form>
)}
@@ -252,10 +275,12 @@ export function MemberEntryComments({
entryId,
thread,
defaultOpen,
mobile,
}: {
entryId: number;
thread: MemberThreadState;
defaultOpen?: boolean;
mobile?: boolean;
}) {
const { t } = useTranslation();
const toast = useToast();
@@ -268,6 +293,7 @@ export function MemberEntryComments({
comments={thread.byEntry.get(entryId) ?? []}
canWrite
defaultOpen={defaultOpen}
mobile={mobile}
canModerate={thread.canModerate}
publicHint
onAdd={async (body) => ((await thread.add(entryId, body)) ? null : t('journey.comments.failed'))}
@@ -134,14 +134,13 @@ describe('JourneyEntryCover', () => {
expect(container.querySelector('svg.lucide-play')).toBeNull()
})
it('FE-JRN-COVER-011: only the phone draws a card without a photo in the deep day colour, opaque even as a suggestion', () => {
it('FE-JRN-COVER-011: the phone shows a neutral surface for suggestions without photos', () => {
const entry = buildEntry({ photos: [], type: 'skeleton' })
const phone = render(<JourneyEntryCover entry={entry} dayColor="#6366f1" isActive={false} onClick={() => {}} tone="mobile" />)
const phoneCard = phone.getByRole('button')
// d9, the deep wash (jsdom spells the colour out as rgba)
expect(phoneCard.style.backgroundImage).toMatch(/rgba\(99, 102, 241, 0\.85/)
expect(phoneCard.className).not.toContain('opacity-90')
expect(phone.container.querySelector('svg.lucide-map-pin')?.getAttribute('class')).toContain('-mt-6')
expect(phoneCard.style.backgroundImage).toBe('')
expect(phoneCard).toHaveClass('bg-m-sheetop', 'text-m-ink')
expect(phone.container.querySelector('svg.lucide-map-pin')).not.toBeInTheDocument()
phone.unmount()
// The desktop and shared timelines keep their faint wash and the day-coloured pin.
@@ -154,4 +153,12 @@ describe('JourneyEntryCover', () => {
expect(pin.getAttribute('class')).not.toContain('-mt-6')
expect(pin.style.color).not.toBe('')
})
it('fills a mobile card with its photo and draws the text in white', () => {
const { container } = render(<JourneyEntryCover entry={buildEntry()} dayColor="#6366f1" isActive onClick={() => {}} tone="mobile" />)
expect(container.querySelector('button')).toHaveClass('text-[color:var(--m-viewer-ink)]')
expect(container.querySelector('img[src*="/api/photos/"]')).toHaveClass('absolute', 'inset-0', 'size-full', 'object-cover')
expect(container.querySelector('.bg-gradient-to-t')).toBeInTheDocument()
})
})
@@ -20,10 +20,8 @@ import type { JourneyEntry } from '../../store/journeyStore'
* answers "how many stops into this day am I", which is not a question anyone
* asks; the day scrubber above the carousel answers the one they do.
*
* Two shells draw this card. `tone` picks the surface a card without a photo
* falls back to, because the phone shell's tokens are scoped to `.m-root` and
* the tablet timeline is outside it. Everything else is a photo and white text,
* which needs no tokens at all.
* Photos fill the cover. The mobile shell uses a neutral card for entries
* without a photo and a lighter active treatment over the map.
*/
/** A card's photo, plus what says whether a clip has a poster to draw (#2341). */
@@ -82,7 +80,10 @@ export default function JourneyEntryCover({
size = 'regular',
}: Props) {
const large = size === 'large'
const box = large ? 'h-[196px] w-[176px]' : size === 'compact' ? 'h-[112px] w-[124px]' : 'h-[152px] w-[136px]'
const mobile = tone === 'mobile'
const box = size === 'compact' ? 'h-[112px] w-[124px]'
: large ? (mobile ? 'h-[144px] w-[176px]' : 'h-[196px] w-[176px]')
: mobile ? 'h-[116px] w-[144px]' : 'h-[152px] w-[136px]'
const { t, locale } = useTranslation()
const isSuggestion = entry.type === 'skeleton'
@@ -100,12 +101,44 @@ export default function JourneyEntryCover({
const mood = showMood ? moodMeta(entry.mood) : undefined
const weather = showWeather ? weatherMeta(entry.weather) : undefined
const mobile = tone === 'mobile'
const emptyGround = mobile ? 'bg-[color:var(--m-sheetop)]' : 'bg-white dark:bg-zinc-800'
// The mark of a card without a photo: white and raised clear of the name on the
// phone's deep day colour, the day's own colour on the faint wash elsewhere.
const emptyIcon = mobile ? '-mt-6 opacity-80' : 'opacity-60'
const emptyIconStyle = mobile ? undefined : { color: dayColor }
if (mobile) {
return (
<button type="button" onClick={onClick} aria-current={isActive ? 'true' : undefined}
className={`relative isolate flex ${box} flex-none origin-bottom flex-col justify-between overflow-hidden rounded-[18px] border bg-m-sheetop p-2.5 text-start shadow-sm transition-transform motion-reduce:transition-none ${src ? 'text-[color:var(--m-viewer-ink)]' : 'text-m-ink'} ${isActive ? 'z-[1] scale-[1.035]' : 'border-m-rowbr'}`}
style={isActive ? { borderColor: dayColor } : undefined}
>
{src && (
<>
<img src={src} alt="" loading="lazy" className="absolute inset-0 -z-10 size-full rounded-[inherit] object-cover" />
<span className="pointer-events-none absolute inset-x-0 bottom-0 -z-10 h-24 bg-gradient-to-t from-[color:var(--m-viewer-bg)] via-[color:var(--overlay)] to-transparent" />
</>
)}
{isSuggestion && <span className="sr-only">{t('journey.entry.suggestion')}</span>}
<span className="flex w-full min-w-0 items-start justify-between gap-1.5">
<span className="flex min-w-0 flex-wrap items-center gap-1">
<span className={`whitespace-nowrap rounded-md px-1.5 py-0.5 text-caption font-medium ${src ? 'bg-[color:var(--overlay)]' : 'bg-m-ic text-m-muted'}`}>{date}</span>
{mood && <mood.icon size={12} style={{ color: mood.color }} />}
{weather && <weather.icon size={12} className={src ? undefined : 'text-m-muted'} />}
</span>
{posterless && (
<span className="grid h-9 w-12 flex-none place-items-center rounded-lg bg-m-ic text-m-muted">
<Play size={14} fill="currentColor" />
</span>
)}
</span>
<span className="flex w-full min-w-0 flex-col gap-0.5">
<bdi className="line-clamp-2 text-control font-semibold leading-tight">{title}</bdi>
{place && (
<span className={`flex min-w-0 items-center gap-1 text-caption leading-snug ${src ? '' : 'text-m-muted'}`}>
{entry.country_code && <span className="flex-none"><CountryFlag code={entry.country_code} size={12} /></span>}
<bdi className="truncate">{place}</bdi>
</span>
)}
</span>
</button>
)
}
// One ground for every corner mark. Dark rather than a white veil: these sit on
// whatever photograph the traveller took, and a bright sky swallowed the white one.
const badge = 'rounded-full bg-black/45 px-[7px] py-[2px] text-[10px] font-bold whitespace-nowrap text-white backdrop-blur-[2px]'
@@ -123,11 +156,9 @@ export default function JourneyEntryCover({
// growing its box moved every card after it once a swipe had landed, and the
// snap then pulled the strip again, which read as a jolt (carousels keep the
// room for it with their gap and top padding).
// White on the root: every mark and line on the card is white, over a photo or
// over the day's colour alike.
className={`relative text-white ${box} flex-none origin-bottom overflow-hidden rounded-[18px] text-start transition-[transform,box-shadow] duration-200 ease-[cubic-bezier(.2,.8,.2,1)] motion-reduce:transition-none ${
isActive ? 'z-[1] scale-[1.18] shadow-[0_18px_40px_-16px_rgba(0,0,0,.55)]' : 'scale-100 shadow-[0_10px_24px_-14px_rgba(0,0,0,.5)]'
} ${src ? '' : emptyGround} ${isSuggestion && !mobile ? 'opacity-90' : ''}`}
} ${src ? '' : 'bg-white dark:bg-zinc-800'} ${isSuggestion ? 'opacity-90' : ''}`}
// backgroundImage, not background: the shorthand would drop the opaque colour
// the class supplies and leave the map showing through a card that is only a
// faint wash of the day's colour.
@@ -139,14 +170,7 @@ export default function JourneyEntryCover({
// ring lost its top edge to that clip.
style={{
boxShadow: `inset 0 0 0 ${isActive ? 2.5 : 1.5}px ${dayColor}${isActive ? '' : 'b3'}`,
// Without a photograph the phone's card is the day's colour, deep enough to
// carry the white name like a photo does, rather than a grey that read as
// empty. Its ground stays opaque (no dimming for a suggestion either): it
// floats over the map, whose labels read through anything less. The desktop
// and shared timelines keep their faint wash of the day.
...(src ? null : { backgroundImage: mobile
? `linear-gradient(160deg, ${dayColor}d9, ${dayColor}8c 55%, ${dayColor}59)`
: `linear-gradient(160deg, ${dayColor}2e, ${dayColor}0d)` }),
...(src ? null : { backgroundImage: `linear-gradient(160deg, ${dayColor}2e, ${dayColor}0d)` }),
}}
>
{src ? (
@@ -154,8 +178,8 @@ export default function JourneyEntryCover({
) : (
<span className="absolute inset-0 flex items-center justify-center">
{posterless
? <Play size={24} strokeWidth={1.8} fill="currentColor" style={emptyIconStyle} className={`ml-0.5 ${emptyIcon}`} />
: <MapPin size={24} strokeWidth={1.8} style={emptyIconStyle} className={emptyIcon} />}
? <Play size={24} strokeWidth={1.8} fill="currentColor" className="ms-0.5 opacity-60" style={{ color: dayColor }} />
: <MapPin size={24} strokeWidth={1.8} className="opacity-60" style={{ color: dayColor }} />}
</span>
)}
@@ -196,7 +220,7 @@ export default function JourneyEntryCover({
</span>
)}
{weather && (
<span className={`${badgeDot}`}>
<span className={badgeDot}>
<weather.icon size={11} strokeWidth={2.4} />
</span>
)}
@@ -1,4 +1,5 @@
import { useState, useEffect, useCallback, useRef } from 'react'
import { useOverlay } from '../../hooks/overlayStack'
import { createPortal } from 'react-dom'
import { ChevronLeft, ChevronRight, Loader2, X, ZoomIn, ZoomOut } from 'lucide-react'
import VideoPlayer from './VideoPlayerLazy'
@@ -53,6 +54,7 @@ const SAFE = (side: 'top' | 'bottom' | 'left' | 'right') =>
`max(env(safe-area-inset-${side}, 0px), var(--safe-area-inset-${side}, 0px), var(--trek-native-safe-${side}, 0px))`
export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }: Props) {
useOverlay(true, onClose, true)
const [idx, setIdx] = useState(startIndex)
const touchStart = useRef<{ x: number; y: number } | null>(null)
const dialogRef = useRef<HTMLDivElement>(null)
@@ -87,13 +89,12 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose()
if (e.key === 'ArrowLeft') (rtl ? next : prev)()
if (e.key === 'ArrowRight') (rtl ? prev : next)()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [prev, next, onClose, rtl])
}, [prev, next, rtl])
// A pinch, a double tap or a pan of an enlarged photo belongs to the zoom; only
// the rest is a swipe that turns the page or closes the lightbox.
@@ -168,8 +168,8 @@ export function useJourneySettings({ journey, onSaved, onRefresh, onContentChang
}
};
const handleRemoveContributor = async (c: JourneyContributor) => {
if (!window.confirm(t('journey.contributors.removeConfirm', { username: c.username }))) return;
const handleRemoveContributor = async (c: JourneyContributor, confirmed = false) => {
if (!confirmed && !window.confirm(t('journey.contributors.removeConfirm', { username: c.username }))) return;
try {
await journeyApi.removeContributor(journey.id, c.user_id);
toast.success(t('journey.contributors.removed'));
+9 -14
View File
@@ -41,25 +41,20 @@ const ADDON_ICONS: Record<string, LucideIcon> = {
/** The bar holds Dashboard + at most this many custom items; the rest go to More.
* Two keeps the dock at 3 entries (Dashboard + 2) so the More slot still fits. */
export const MOBILE_NAV_MAX_BAR = 2
/**
* The built-in dock next to Dashboard for an un-customised account, in priority
* order: the first MOBILE_NAV_MAX_BAR of these that are actually enabled take the
* slots, everything else starts under More.
*
* Journey outranks Atlas because a phone in the field wants the journal it writes
* to every day, not the map of countries it already visited. Journey ships
* disabled though, so an instance that never turned it on keeps the Vacay/Atlas
* dock it has today. Listing all four known global addons rather than just the
* top two also keeps the dock filled when one of them is switched off. The
* assistant comes last: it takes a slot only one of the addons left free, rather
* than sitting alone behind the More button.
*/
/** Where an addon's page lives: its id, except Collections, which became Places (PLC-07). */
export function addonPath(id: string): string {
return id === 'collections' ? '/places' : `/${id}`
}
export const DEFAULT_DOCK_IDS = ['vacay', 'journey', 'atlas', 'collections', ASSISTANT_NAV_ID]
/**
* The built-in dock next to Dashboard for an un-customised account, in priority
* order: the first MOBILE_NAV_MAX_BAR of these that are actually enabled take the
* slots, everything else starts under More.
*
* Places and Journey sit beside trips when enabled. The remaining enabled
* destinations fill unused slots, and the customizer keeps saved choices.
*/
export const DEFAULT_DOCK_IDS = ['collections', 'journey', 'vacay', 'atlas', ASSISTANT_NAV_ID]
export function buildNavItems(
globalAddons: { id: string; name: string; icon: string }[],
@@ -14,7 +14,13 @@ import { useToast } from '../shared/Toast';
* own address; it is the person's own, so a fellow traveller gets another.
* Nothing where the import is off for the person.
*/
export default function TripMailForward({ tripId }: { tripId: number }): ReactElement | null {
export default function TripMailForward({
tripId,
mobile = false,
}: {
tripId: number;
mobile?: boolean;
}): ReactElement | null {
const { t } = useTranslation();
const toast = useToast();
const settings = useMailIngestStore((s) => s.settings);
@@ -62,7 +68,7 @@ export default function TripMailForward({ tripId }: { tripId: number }): ReactEl
};
return (
<div className="mt-1 flex flex-col gap-2 rounded-xl bg-surface-tertiary px-3.5 py-3">
<div className={`mt-1 flex flex-col gap-2 rounded-xl px-3.5 py-3 ${mobile ? 'bg-m-ic' : 'bg-surface-tertiary'}`}>
<div className="flex items-center gap-2 text-body font-semibold text-content">
<Mail size={15} strokeWidth={2} className="text-content-muted" />
{t('mailInbox.trip.title')}
@@ -72,7 +78,7 @@ export default function TripMailForward({ tripId }: { tripId: number }): ReactEl
<div className="flex min-w-0 items-center gap-2">
<code
dir="ltr"
className="min-w-0 flex-1 truncate rounded-lg bg-surface-card px-2.5 py-1.5 font-geist text-caption text-content"
className={`min-w-0 flex-1 truncate rounded-lg px-2.5 py-1.5 font-geist text-caption text-content ${mobile ? 'bg-m-sheetop' : 'bg-surface-card'}`}
>
{address.address}
</code>
@@ -80,7 +86,7 @@ export default function TripMailForward({ tripId }: { tripId: number }): ReactEl
type="button"
onClick={() => void copy()}
aria-label={t('mailInbox.settings.copy')}
className="grid h-8 w-8 flex-none place-items-center rounded-lg bg-surface-card text-content-muted hover:text-content"
className={`grid flex-none place-items-center rounded-lg text-content-muted hover:text-content ${mobile ? 'size-11 bg-m-sheetop' : 'size-8 bg-surface-card'}`}
>
<Copy size={14} strokeWidth={2} />
</button>
@@ -90,7 +96,7 @@ export default function TripMailForward({ tripId }: { tripId: number }): ReactEl
type="button"
onClick={() => void create()}
disabled={creating}
className="inline-flex w-fit items-center gap-1.5 rounded-lg bg-surface-card px-3 py-1.5 text-caption font-semibold text-content hover:bg-surface-hover disabled:opacity-50"
className={`inline-flex w-fit items-center gap-1.5 rounded-lg px-3 py-1.5 text-caption font-semibold text-content hover:bg-surface-hover disabled:opacity-50 ${mobile ? 'min-h-11 bg-m-sheetop' : 'bg-surface-card'}`}
>
<Plus size={13} strokeWidth={2.2} />
{t('mailInbox.trip.create')}
+3 -16
View File
@@ -1,9 +1,7 @@
import { Type } from 'lucide-react';
import { useTranslation } from '../../i18n';
import { useSettingsStore } from '../../store/settingsStore';
import { useToast } from '../shared/Toast';
import { MapTogglePill } from './MapTogglePill';
import { usePlaceNamesSetting } from './usePlaceNameLayout';
import { usePlaceNamesToggle } from './usePlaceNameLayout';
/**
* Turns the place names beside the trip map's pins on and off (#2796). The choice is
@@ -11,23 +9,12 @@ import { usePlaceNamesSetting } from './usePlaceNameLayout';
*/
export function PlaceNamesPill() {
const { t } = useTranslation();
const on = usePlaceNamesSetting();
const updateSetting = useSettingsStore((s) => s.updateSetting);
const toast = useToast();
// The switch flips at once; a save that fails turns it back and says so.
const toggle = async () => {
try {
await updateSetting('map_place_labels', !on);
} catch (err) {
useSettingsStore.setState((s) => ({ settings: { ...s.settings, map_place_labels: on } }));
toast.error(err instanceof Error ? err.message : t('common.error'));
}
};
const { on, setOn } = usePlaceNamesToggle();
return (
<MapTogglePill
active={on}
onToggle={() => {
void toggle();
void setOn(!on);
}}
label={on ? t('map.placeNames.hide') : t('map.placeNames.show')}
testId="place-names-pill"
+16 -3
View File
@@ -1,5 +1,5 @@
import { withHotelBookends } from './RouteCalculator'
import { getTransportRouteEndpoints, getTransportForDay, getMergedItems, isCarrierTransport, hasCarrierEndpointOnDay } from '../../utils/dayMerge'
import { getSpanPhase, getTransportRouteEndpoints, getTransportForDay, getMergedItems, isCarrierTransport, hasCarrierEndpointOnDay, stopDayIds } from '../../utils/dayMerge'
import { getDayBookendHotels, shouldDrawMorningLeg, shouldDrawEveningLeg, type CarrierEdge } from '../../utils/dayOrder'
import { withinDriveRange } from '@trek/shared/roadtrip'
import type { Accommodation, AssignmentsMap, Day, Place, Reservation } from '../../types'
@@ -43,6 +43,15 @@ export interface DayRouteInputs {
places?: Place[]
/** MDT-02: where the stages of the trip's multi-day tours run, so a day holding one routes to it. */
tourStageStops?: TourStageStops
includeLocatedBookings?: boolean
}
/** A reservation linked to a place can be a stop in the itinerary without being a transport leg. */
export function locatedBookingWaypoint(reservation: Reservation, dayId: number, places?: readonly Place[]) {
if (reservation.place_id == null || reservation.type === 'hotel' || TRANSPORT_TYPES.includes(reservation.type)
|| getSpanPhase(reservation, dayId) === 'middle') return null
const place = places?.find(candidate => candidate.id === reservation.place_id)
return place && place.lat != null && place.lng != null ? { lat: place.lat, lng: place.lng } : null
}
/**
@@ -79,16 +88,18 @@ export function buildDayRouteRuns(dayId: number, input: DayRouteInputs): DayRout
// it; getMergedItems places each leg by its own saved position, falling back to its
// time. Notes carry no coordinates, so none are passed.
const dayTransports = thisOrder == null ? [] : getTransportForDay({
reservations: allReservations.filter(r => TRANSPORT_TYPES.includes(r.type)),
reservations: allReservations.filter(r => TRANSPORT_TYPES.includes(r.type)
|| (input.includeLocatedBookings && !!locatedBookingWaypoint(r, dayId, input.places))),
dayId,
dayAssignmentIds: da.map(a => a.id),
days: allDays,
stopDays: input.includeLocatedBookings ? stopDayIds(assignments) : undefined,
})
const merged = getMergedItems({ dayAssignments: da, dayNotes: [], dayTransports, dayId })
const projected = projectedById(da, input.toursEnabled ?? false, input.places, input.tourStageStops)
type Entry =
| { kind: 'place'; id: number; lat: number; lng: number; pos: number; time: string | null; mode: string | null; incoming: string | null }
| { kind: 'place'; id?: number; lat: number; lng: number; pos: number; time: string | null; mode: string | null; incoming: string | null }
| { kind: 'tour'; start: { lat: number; lng: number } | null; end: { lat: number; lng: number } | null; pos: number; time: string | null; mode: string | null; incoming: string | null }
| { kind: 'transport'; from: { lat: number; lng: number } | null; to: { lat: number; lng: number } | null; pos: number; carrier: boolean }
const entries: Entry[] = merged.flatMap((item): Entry[] => {
@@ -111,6 +122,8 @@ export function buildDayRouteRuns(dayId: number, input: DayRouteInputs): DayRout
}]
}
if (item.type !== 'transport') return []
const booking = input.includeLocatedBookings ? locatedBookingWaypoint(item.data, dayId, input.places) : null
if (booking) return [{ kind: 'place', ...booking, pos: item.sortKey, time: null, mode: null, incoming: null }]
const { from, to } = getTransportRouteEndpoints(item.data, dayId)
return [{ kind: 'transport', from, to, pos: item.sortKey, carrier: isCarrierTransport(item.data) }]
})
@@ -1,6 +1,8 @@
import { useCallback, useEffect } from 'react';
import { useTranslation } from '../../i18n';
import { useSettingsStore } from '../../store/settingsStore';
import { useToast } from '../shared/Toast';
import { controlBoxes, layoutPlaceNames, PLACE_NAMES_CONTROLS } from './placeNameLabels';
/** Whether the trip map shows its place names, the reader's own setting (#2796). */
@@ -8,6 +10,23 @@ export function usePlaceNamesSetting(): boolean {
return useSettingsStore((s) => s.settings.map_place_labels) === true;
}
/** Flips the reader's label setting at once and restores it if saving fails. */
export function usePlaceNamesToggle() {
const { t } = useTranslation();
const on = usePlaceNamesSetting();
const updateSetting = useSettingsStore((s) => s.updateSetting);
const toast = useToast();
const setOn = async (value: boolean) => {
try {
await updateSetting('map_place_labels', value);
} catch (err) {
useSettingsStore.setState((s) => ({ settings: { ...s.settings, map_place_labels: on } }));
toast.error(err instanceof Error ? err.message : t('common.error'));
}
};
return { on, setOn };
}
/**
* Keeps the place names of one map laid out: once after every change of the markers
* (a cluster opening, a day picked) and after every move or zoom the renderer reports
@@ -24,7 +24,7 @@ interface KategorieGruppeProps {
onRename: (oldName: string, newName: string) => Promise<void>
onDeleteAll: (items: PackingItem[]) => Promise<void>
onDeleteItem: (item: PackingItem) => Promise<void>
onAddItem: (category: string, name: string) => Promise<void>
onAddItem: (category: string, name: string) => Promise<unknown>
assignees: CategoryAssignee[]
tripMembers: TripMember[]
onSetAssignees: (category: string, userIds: number[]) => Promise<void>
@@ -80,6 +80,19 @@ describe('usePackingItemActions', () => {
expect(phone.acts.addPackingItem).toHaveBeenCalledWith(7, { name: 'Tent', category: 'Camp', visibility: 'common' });
});
it('uses the personal placeholder when both scopes have the same category name', async () => {
const shared = buildPackingItem({ id: 4, name: PACKING_PLACEHOLDER_NAME, category: 'Camp' });
const personal = buildPackingItem({ ...shared, id: 5, is_private: 1, owner_id: 9 });
const { result, acts } = setup({ items: [shared, personal], view: 'personal' });
await act(async () => {
await result.current.addItemToCategory('Camp', 'Tent');
});
expect(acts.updatePackingItem).toHaveBeenCalledWith(7, 5, { name: 'Tent' });
expect(acts.updatePackingItem).toHaveBeenCalledOnce();
});
it('FE-PACK-ITEMACT-003: in my list a new item is shared the way the category already is (#2241)', async () => {
const own = buildPackingItem({
id: 5,
@@ -57,13 +57,18 @@ export function usePackingItemActions({
const [addingCategory, setAddingCategory] = useState(false);
const [newCategoryName, setNewCategoryName] = useState('');
const addItemToCategory = async (category: string, name: string) => {
const addItemToCategory = async (category: string | null, name: string) => {
try {
// Reuse the '...' placeholder slot when the category already has one, so a
// freshly-emptied category keeps its position (and therefore its colour)
// instead of the new item being appended to the end of the list.
const pool = placeholderFrom === 'store' ? useTripStore.getState().packingItems : items;
const placeholder = pool.find((i) => i.category === category && isPackingPlaceholder(i));
const placeholder = packingViewItems(pool, view).find(
(i) =>
(i.category || null) === category &&
isPackingPlaceholder(i) &&
(view === 'common' || i.owner_id == null || i.owner_id === currentUserId)
);
if (placeholder) {
await updatePackingItem(tripId, placeholder.id, { name });
} else {
@@ -71,12 +76,13 @@ export function usePackingItemActions({
// category's own items agree on (#2241).
await addPackingItem(tripId, {
name,
category,
...newItemSharing(items, category, view, currentUserId),
...(category ? { category, ...newItemSharing(items, category, view, currentUserId) } : { visibility: view }),
} as Parameters<typeof addPackingItem>[1]);
}
return true;
} catch {
toast.error(t('packing.toast.addError'));
return false;
}
};
@@ -88,7 +94,7 @@ export function usePackingItemActions({
// removing the placeholder is how an empty category is dismissed.
const deleteItem = async (item: PackingItem) => {
try {
if (isLastCustomItemInCategory(item, items)) {
if (isLastCustomItemInCategory(item, packingViewItems(items, item.is_private ? 'personal' : 'common'))) {
if (item.checked) await togglePackingItem(tripId, item.id, false);
await updatePackingItem(tripId, item.id, {
name: PACKING_PLACEHOLDER_NAME,
@@ -106,7 +112,7 @@ export function usePackingItemActions({
/** Moves every item of a category to the new name, one write each; a failure stops it and is thrown. */
const renameCategory = async (oldName: string, newName: string) => {
const toUpdate = items.filter((i) => (i.category || defaultCategory) === oldName);
const toUpdate = packingViewItems(items, view).filter((i) => (i.category || defaultCategory) === oldName);
for (const item of toUpdate) {
await updatePackingItem(tripId, item.id, { category: newName });
}
@@ -136,7 +142,7 @@ export function usePackingItemActions({
/** Removes the checked items of the open view only, the ones the button's count names. */
const clearChecked = async () => {
let failed = false;
for (const item of packingViewItems(items, view).filter((i) => i.checked)) {
for (const item of packingViewItems(items, view).filter((i) => i.checked && !isPackingPlaceholder(i))) {
try {
await deletePackingItem(tripId, item.id);
} catch {
@@ -8,6 +8,7 @@ import { useBackgroundTasksStore } from '../../store/backgroundTasksStore';
import { resetAllStores } from '../../../tests/helpers/store';
import { saveImportFiles } from '../../db/offlineDb';
import BookingImportModal from './BookingImportModal';
import MBookingImportSheet from '../../mobile/screens/trip/sheets/MBookingImportSheet';
vi.mock('../../db/offlineDb', () => ({ saveImportFiles: vi.fn(async () => {}) }));
@@ -36,6 +37,32 @@ beforeEach(() => {
});
describe('BookingImportModal', () => {
it('uploads the selected mobile PDF once and keeps it for the booking review', async () => {
const onClose = vi.fn();
const pdf = new File(['%PDF-1.4'], 'booking.pdf', { type: 'application/pdf' });
const upload = vi.fn(() => HttpResponse.json({ jobId: 'mobile-pdf' }));
server.use(http.post('/api/trips/4/reservations/import/booking/async', upload));
render(<MBookingImportSheet {...defaultProps} kind="bookings" onClose={onClose} />);
expect(screen.getByRole('dialog', { name: 'Import booking confirmations' })).toBeInTheDocument();
await userEvent.upload(fileInput(), [pdf, eml()]);
await userEvent.click(screen.getByRole('button', { name: 'Remove: booking.eml' }));
const submit = screen.getByRole('button', { name: 'Import' });
await waitFor(() => expect(submit).toBeEnabled());
await userEvent.click(submit);
await waitFor(() => expect(onClose).toHaveBeenCalledOnce());
expect(upload).toHaveBeenCalledOnce();
expect(saveImportFiles).toHaveBeenCalledWith('mobile-pdf', [pdf]);
expect(useBackgroundTasksStore.getState().tasks.find(task => task.id === 'mobile-pdf'))
.toMatchObject({ kind: 'bookings', total: 1 });
});
it('opens the mobile dialog with an explanation if the server has no parser', async () => {
server.use(http.get('/api/health/features', () => HttpResponse.json({ bookingImport: false, aiParsing: false })));
render(<MBookingImportSheet {...defaultProps} />);
expect(await screen.findByText(/import is not available on this server/i)).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Import' })).not.toBeInTheDocument();
});
it('FE-PLANNER-BOOKIMP-001: renders nothing while closed', () => {
render(<BookingImportModal {...defaultProps} isOpen={false} />);
expect(screen.queryByText('Import booking confirmations')).not.toBeInTheDocument();
@@ -1,6 +1,6 @@
import { createPortal } from 'react-dom'
import { useSharedImportStore } from '../../native/sharedFiles'
import { useState, useRef, useEffect } from 'react'
import { useState, useRef, useEffect, type ReactNode, type DragEventHandler } from 'react'
import { Upload, X } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { reservationsApi, healthApi } from '../../api/client'
@@ -11,13 +11,34 @@ import { saveImportFiles } from '../../db/offlineDb'
import { isEffectivelyOffline } from '../../sync/networkMode'
import TripMailForward from '../MailIngest/TripMailForward'
interface BookingImportModalProps {
export interface BookingImportModalProps {
isOpen: boolean
onClose: () => void
tripId: number
/** The tab this import was started from, carried into the job so the review
* can pick the right form for an item whose type had to be guessed (#2076). */
kind?: 'transports' | 'bookings'
renderContent?: (view: BookingImportView) => ReactNode
}
export interface BookingImportView {
tripId: number
files: File[]
fileInput: ReactNode
pickFiles: () => void
removeFile: (index: number) => void
dragHandlers: {
onDragOver: DragEventHandler
onDragLeave: DragEventHandler
onDrop: DragEventHandler
}
isDragOver: boolean
loading: boolean
error: string
available: boolean | null
readsPhotos: boolean
handleClose: () => void
handleParse: () => Promise<void>
}
const ACCEPTED_EXTS = ['.eml', '.pdf', '.pkpass', '.html', '.htm', '.txt']
@@ -30,7 +51,7 @@ const MAX_FILES = 5
* (progress over the WebSocket). When it finishes, the trip page opens the per-item
* review flow — so the user can navigate and keep editing while it works.
*/
export default function BookingImportModal({ isOpen, onClose, tripId, kind }: BookingImportModalProps) {
export default function BookingImportModal({ isOpen, onClose, tripId, kind, renderContent }: BookingImportModalProps) {
const { t } = useTranslation()
const addTask = useBackgroundTasksStore((s) => s.addTask)
const fileInputRef = useRef<HTMLInputElement>(null)
@@ -44,6 +65,7 @@ export default function BookingImportModal({ isOpen, onClose, tripId, kind }: Bo
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [aiParsing, setAiParsing] = useState(false)
const [uploadAvailable, setUploadAvailable] = useState<boolean | null>(null)
const [readsPhotos, setReadsPhotos] = useState(false)
// Only a model that reads images can do anything with a photo, so photos are offered only then.
const acceptedExts: readonly string[] = readsPhotos ? [...ACCEPTED_EXTS, ...LLM_PHOTO_EXTENSIONS] : ACCEPTED_EXTS
@@ -60,6 +82,7 @@ export default function BookingImportModal({ isOpen, onClose, tripId, kind }: Bo
setIsDragOver(false)
setLoading(false)
setError('')
setUploadAvailable(null)
}
}
@@ -72,8 +95,22 @@ export default function BookingImportModal({ isOpen, onClose, tripId, kind }: Bo
useEffect(() => {
if (!isOpen) return
healthApi.features().then((f) => setAiParsing(!!f.aiParsing)).catch(() => setAiParsing(false))
llmRepo.readsPhotos().then(setReadsPhotos).catch(() => setReadsPhotos(false))
let active = true
healthApi.features().then((f) => {
if (!active) return
setAiParsing(!!f.aiParsing)
setUploadAvailable(!!(f.bookingImport || f.aiParsing))
}).catch(() => {
if (!active) return
setAiParsing(false)
// Let the import endpoint report a connection or capability error if the feature check fails.
setUploadAvailable(true)
})
llmRepo.readsPhotos().then(
(supported) => { if (active) setReadsPhotos(supported) },
() => { if (active) setReadsPhotos(false) }
)
return () => { active = false }
}, [isOpen])
const handleClose = () => { reset(); onClose() }
@@ -115,7 +152,7 @@ export default function BookingImportModal({ isOpen, onClose, tripId, kind }: Bo
// Start the parse in the background and close — the widget takes it from here.
const handleParse = async () => {
if (files.length === 0 || loading) return
if (files.length === 0 || loading || (renderContent && !uploadAvailable)) return
// Reading a booking runs on the server: offline there is nothing to send it to.
if (isEffectivelyOffline()) { setError(t('reservations.needsConnection')); return }
setLoading(true)
@@ -136,6 +173,27 @@ export default function BookingImportModal({ isOpen, onClose, tripId, kind }: Bo
if (!isOpen) return null
const fileInput = (
<input
ref={fileInputRef}
type="file"
accept={acceptedExts.join(',')}
multiple
hidden
onChange={handleInputChange}
/>
)
if (renderContent) {
return renderContent({
tripId, files, fileInput, isDragOver, loading, error, available: uploadAvailable, readsPhotos,
pickFiles: () => fileInputRef.current?.click(),
removeFile: index => setFiles(current => current.filter((_, i) => i !== index)),
dragHandlers: { onDragOver: handleDragOver, onDragLeave: handleDragLeave, onDrop: handleDrop },
handleClose, handleParse,
})
}
return createPortal(
<div
role="presentation"
@@ -169,14 +227,7 @@ export default function BookingImportModal({ isOpen, onClose, tripId, kind }: Bo
{readsPhotos && <> {t('reservations.import.acceptedPhotos')}</>}
</div>
<input
ref={fileInputRef}
type="file"
accept={acceptedExts.join(',')}
multiple
style={{ display: 'none' }}
onChange={handleInputChange}
/>
{fileInput}
<button
type="button"
@@ -224,7 +275,7 @@ export default function BookingImportModal({ isOpen, onClose, tripId, kind }: Bo
{t('common.cancel')}
</button>
<button type="button"
onClick={handleParse}
onClick={() => void handleParse()}
disabled={files.length === 0 || loading}
className={files.length > 0 && !loading ? 'bg-accent text-accent-text' : 'bg-surface-tertiary text-content-faint'}
style={{ padding: '8px 16px', borderRadius: 10, border: 'none', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, cursor: files.length > 0 && !loading ? 'pointer' : 'default', fontFamily: 'inherit' }}
@@ -5,11 +5,7 @@ import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { IcsSubscribeModal } from './IcsSubscribeModal';
// The phone keeps the dialog's own markup, the desktop draws it in the shared
// dialog frame. useIsPhone reads matchMedia, which the test setup always
// answers with false, so the phone is switched on by hand.
const phone = vi.hoisted(() => ({ value: false }));
vi.mock('../../mobile/useIsPhone', () => ({ useIsPhone: () => phone.value }));
import MIcsSubscribeSheet from '../../mobile/screens/trip/sheets/MIcsSubscribeSheet';
const ENDPOINT = '/api/trips/9/feed';
const TOKEN_URL = `${ENDPOINT}/token`;
@@ -31,17 +27,13 @@ function tokenHandlers(handler: (method: string) => Response | Promise<Response>
];
}
afterEach(() => { phone.value = false; });
// Everything a user can do with the link works the same on both shells.
describe.each([['phone', true], ['desktop', false]] as const)('IcsSubscribeModal on the %s', (_shell, isPhone) => {
beforeEach(() => { phone.value = isPhone; });
describe.each([['phone', MIcsSubscribeSheet], ['desktop', IcsSubscribeModal]] as const)('IcsSubscribeModal on the %s', (_shell, SubscribeDialog) => {
it('FE-PLANNER-ICS-001: shows the loading state until the token read resolves', async () => {
let release: (() => void) | null = null;
const gate = new Promise<void>(res => { release = res; });
server.use(http.get(TOKEN_URL, async () => { await gate; return HttpResponse.json({ feed_url: null }); }));
render(<IcsSubscribeModal {...defaultProps} />);
render(<SubscribeDialog {...defaultProps} />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
release!();
await waitFor(() => expect(screen.queryByText('Loading...')).not.toBeInTheDocument());
@@ -49,7 +41,7 @@ describe.each([['phone', true], ['desktop', false]] as const)('IcsSubscribeModal
it('FE-PLANNER-ICS-002: renders title and description in the header', async () => {
server.use(http.get(TOKEN_URL, () => HttpResponse.json({ feed_url: null })));
render(<IcsSubscribeModal {...defaultProps} />);
render(<SubscribeDialog {...defaultProps} />);
expect(screen.getByText('Subscribe to this trip')).toBeInTheDocument();
expect(screen.getByText('Keep the itinerary in your own calendar.')).toBeInTheDocument();
await screen.findByRole('button', { name: /Enable calendar subscription/i });
@@ -57,7 +49,7 @@ describe.each([['phone', true], ['desktop', false]] as const)('IcsSubscribeModal
it('FE-PLANNER-ICS-003: with no token yet it offers the enable button, no links', async () => {
server.use(http.get(TOKEN_URL, () => HttpResponse.json({ feed_url: null })));
render(<IcsSubscribeModal {...defaultProps} />);
render(<SubscribeDialog {...defaultProps} />);
expect(await screen.findByRole('button', { name: /Enable calendar subscription/i })).toBeInTheDocument();
expect(screen.getByText(/Creates a secret link/i)).toBeInTheDocument();
expect(screen.queryByRole('link', { name: /Add to Google Calendar/i })).not.toBeInTheDocument();
@@ -69,7 +61,7 @@ describe.each([['phone', true], ['desktop', false]] as const)('IcsSubscribeModal
http.get(TOKEN_URL, () => { seen.push('GET'); return HttpResponse.json({ feed_url: null }); }),
http.post(TOKEN_URL, () => { seen.push('POST'); return HttpResponse.json({ feed_url: 'https://trek.example/api/trips/9/feed/tok.ics' }); }),
);
render(<IcsSubscribeModal {...defaultProps} />);
render(<SubscribeDialog {...defaultProps} />);
fireEvent.click(await screen.findByRole('button', { name: /Enable calendar subscription/i }));
expect(await screen.findByRole('link', { name: /Add to Google Calendar/i })).toBeInTheDocument();
expect(seen).toEqual(['GET', 'POST']);
@@ -79,7 +71,7 @@ describe.each([['phone', true], ['desktop', false]] as const)('IcsSubscribeModal
it('FE-PLANNER-ICS-005: an absolute feed_url is handed to the links as https and webcal', async () => {
server.use(http.get(TOKEN_URL, () => HttpResponse.json({ feed_url: 'https://trek.example/feed/tok.ics' })));
render(<IcsSubscribeModal {...defaultProps} />);
render(<SubscribeDialog {...defaultProps} />);
expect(await screen.findByText('https://trek.example/feed/tok.ics')).toBeInTheDocument();
expect(screen.getByRole('link', { name: /Add to Apple Calendar \/ Outlook/i }))
.toHaveAttribute('href', 'webcal://trek.example/feed/tok.ics');
@@ -87,7 +79,7 @@ describe.each([['phone', true], ['desktop', false]] as const)('IcsSubscribeModal
it('FE-PLANNER-ICS-006: a host-relative feed_url is resolved against the current origin', async () => {
server.use(http.get(TOKEN_URL, () => HttpResponse.json({ feed_url: '/api/trips/9/feed/tok.ics' })));
render(<IcsSubscribeModal {...defaultProps} />);
render(<SubscribeDialog {...defaultProps} />);
const absolute = `${window.location.origin}/api/trips/9/feed/tok.ics`;
expect(await screen.findByText(absolute)).toBeInTheDocument();
expect(screen.getByRole('link', { name: /Add to Apple Calendar \/ Outlook/i }))
@@ -96,7 +88,7 @@ describe.each([['phone', true], ['desktop', false]] as const)('IcsSubscribeModal
it('FE-PLANNER-ICS-012: a feed_url with neither scheme nor leading slash is used verbatim', async () => {
server.use(http.get(TOKEN_URL, () => HttpResponse.json({ feed_url: 'trips/9/feed/tok.ics' })));
render(<IcsSubscribeModal {...defaultProps} />);
render(<SubscribeDialog {...defaultProps} />);
// Nothing to absolutize against, so the raw value reaches the copy rows and
// the webcal handoff stays schemeless rather than being mangled.
expect(await screen.findAllByText('trips/9/feed/tok.ics')).toHaveLength(2);
@@ -110,7 +102,7 @@ describe.each([['phone', true], ['desktop', false]] as const)('IcsSubscribeModal
http.get(TOKEN_URL, () => HttpResponse.json({ feed_url: 'https://trek.example/feed/old.ics' })),
http.put(TOKEN_URL, () => { method = 'PUT'; return HttpResponse.json({ feed_url: 'https://trek.example/feed/new.ics' }); }),
);
render(<IcsSubscribeModal {...defaultProps} />);
render(<SubscribeDialog {...defaultProps} />);
fireEvent.click(await screen.findByRole('button', { name: /Regenerate/i }));
expect(await screen.findByText('https://trek.example/feed/new.ics')).toBeInTheDocument();
expect(method).toBe('PUT');
@@ -122,7 +114,7 @@ describe.each([['phone', true], ['desktop', false]] as const)('IcsSubscribeModal
http.get(TOKEN_URL, () => HttpResponse.json({ feed_url: 'https://trek.example/feed/tok.ics' })),
http.delete(TOKEN_URL, () => { method = 'DELETE'; return HttpResponse.json({ feed_url: null }); }),
);
render(<IcsSubscribeModal {...defaultProps} />);
render(<SubscribeDialog {...defaultProps} />);
fireEvent.click(await screen.findByRole('button', { name: /Turn off/i }));
expect(await screen.findByRole('button', { name: /Enable calendar subscription/i })).toBeInTheDocument();
expect(method).toBe('DELETE');
@@ -130,7 +122,7 @@ describe.each([['phone', true], ['desktop', false]] as const)('IcsSubscribeModal
it('FE-PLANNER-ICS-009: a failing token read still leaves the dialog usable', async () => {
server.use(http.get(TOKEN_URL, () => HttpResponse.error()));
render(<IcsSubscribeModal {...defaultProps} />);
render(<SubscribeDialog {...defaultProps} />);
// The catch swallows the error, loading clears, and the enable path is offered.
expect(await screen.findByRole('button', { name: /Enable calendar subscription/i })).toBeInTheDocument();
});
@@ -141,7 +133,7 @@ describe.each([['phone', true], ['desktop', false]] as const)('IcsSubscribeModal
? HttpResponse.json({ feed_url: 'https://trek.example/feed/keep.ics' })
: new HttpResponse(null, { status: 500 }))),
);
render(<IcsSubscribeModal {...defaultProps} />);
render(<SubscribeDialog {...defaultProps} />);
const regenerate = await screen.findByRole('button', { name: /Regenerate/i });
fireEvent.click(regenerate);
await waitFor(() => expect(regenerate).not.toBeDisabled());
@@ -150,7 +142,7 @@ describe.each([['phone', true], ['desktop', false]] as const)('IcsSubscribeModal
it('FE-PLANNER-ICS-017: the day overview switch is on, and off adds days=0 to every link (#2602)', async () => {
server.use(http.get(TOKEN_URL, () => HttpResponse.json({ feed_url: 'https://trek.example/feed/tok.ics' })));
render(<IcsSubscribeModal {...defaultProps} />);
render(<SubscribeDialog {...defaultProps} />);
const toggle = await screen.findByRole('button', { name: 'Day overview events' });
expect(toggle).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByRole('link', { name: /Add to Apple Calendar \/ Outlook/i }))
@@ -170,27 +162,23 @@ describe.each([['phone', true], ['desktop', false]] as const)('IcsSubscribeModal
it('FE-PLANNER-ICS-018: the day overview switch only shows once there is a link to change', async () => {
server.use(http.get(TOKEN_URL, () => HttpResponse.json({ feed_url: null })));
render(<IcsSubscribeModal {...defaultProps} />);
render(<SubscribeDialog {...defaultProps} />);
await screen.findByRole('button', { name: /Enable calendar subscription/i });
expect(screen.queryByRole('button', { name: 'Day overview events' })).not.toBeInTheDocument();
});
});
describe('IcsSubscribeModal on the phone', () => {
beforeEach(() => { phone.value = true; });
it('FE-PLANNER-ICS-011: the close button and a backdrop click both call onClose, an inner click does not', async () => {
const onClose = vi.fn();
server.use(http.get(TOKEN_URL, () => HttpResponse.json({ feed_url: null })));
render(<IcsSubscribeModal {...defaultProps} onClose={onClose} />);
render(<MIcsSubscribeSheet {...defaultProps} onClose={onClose} />);
await screen.findByRole('button', { name: /Enable calendar subscription/i });
const closeBtn = screen.getByText('Subscribe to this trip').closest('div')!.parentElement!
.querySelector('button') as HTMLButtonElement;
fireEvent.click(closeBtn);
fireEvent.click(screen.getByRole('button', { name: 'Close' }));
expect(onClose).toHaveBeenCalledTimes(1);
const backdrop = document.querySelector('[style*="position: fixed"]') as HTMLElement;
const backdrop = document.querySelector('[data-m-scrim]')!.parentElement!;
fireEvent.click(backdrop);
expect(onClose).toHaveBeenCalledTimes(2);
@@ -200,10 +188,9 @@ describe('IcsSubscribeModal on the phone', () => {
it('FE-PLANNER-ICS-013: the phone keeps its own sheet, not the desktop dialog frame', async () => {
server.use(http.get(TOKEN_URL, () => HttpResponse.json({ feed_url: null })));
render(<IcsSubscribeModal {...defaultProps} />);
render(<MIcsSubscribeSheet {...defaultProps} />);
await screen.findByRole('button', { name: /Enable calendar subscription/i });
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(document.querySelector('[style*="z-index: 9999"]')).not.toBeNull();
expect(screen.getByRole('dialog', { name: defaultProps.title })).toHaveAttribute('data-m-sheet', 'open');
});
});
@@ -1,13 +1,11 @@
import { useState, useEffect, useCallback, useId, type ReactNode } from 'react'
import { createPortal } from 'react-dom'
import { X, RefreshCw, Calendar, Power } from 'lucide-react'
import { useState, useEffect, useId, type ReactNode } from 'react'
import { RefreshCw, Calendar, Power } from 'lucide-react'
import { SubscribeLinks } from './SubscribeLinks'
import ToggleSwitch from '../Settings/ToggleSwitch'
import { useIsPhone } from '../../mobile/useIsPhone'
import { useTranslation } from '../../i18n'
import { DialogButton, DialogFooter, DialogHeader, DialogShell, DialogTile, FooterSpacer, NEUTRAL_TINT, fs } from '../shared/DialogShell'
interface IcsSubscribeModalProps {
export interface IcsSubscribeModalProps {
/** Token endpoint base, e.g. `/api/trips/123/feed` or `/api/feed/user`. */
endpoint: string
title: string
@@ -34,7 +32,7 @@ function withDayEvents(url: string, dayEvents: boolean): string {
}
/** The switch for those summaries, above the links it changes, on both shells. */
function DayEventsSwitch({ on, onToggle }: { on: boolean; onToggle: () => void }) {
export function DayEventsSwitch({ on, onToggle }: { on: boolean; onToggle: () => void }) {
const { t } = useTranslation()
const hintId = useId()
return (
@@ -50,42 +48,31 @@ function DayEventsSwitch({ on, onToggle }: { on: boolean; onToggle: () => void }
)
}
/**
* Shared subscribe dialog for the per-trip and all-trips ICS feeds. Opening it
* only *reads* the current token — it never mints one silently. The user
* explicitly enables the public link, and can rotate or fully turn it off.
*
* The phone keeps its own markup; the desktop draws the same steps in the
* planner's dialog frame, with the link's controls in the bar at the foot.
*/
export function IcsSubscribeModal({ endpoint, title, description, onClose }: IcsSubscribeModalProps) {
/** Opening reads the token. Creating or changing it always takes an explicit action. */
export function useIcsSubscription(endpoint: string) {
const tokenUrl = `${endpoint}/token`
const [feedUrl, setFeedUrl] = useState<string | null>(null)
const [loading, setLoading] = useState(true)
const [loadedTokenUrl, setLoadedTokenUrl] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [dayEvents, setDayEvents] = useState(true)
const toggleDayEvents = () => setDayEvents(on => !on)
const isPhone = useIsPhone()
const { t } = useTranslation()
const titleId = useId()
const httpsUrl = feedUrl ? withDayEvents(absolutize(feedUrl), dayEvents) : ''
const webcalUrl = httpsUrl ? httpsUrl.replace(/^https?:\/\//, 'webcal://') : ''
const load = useCallback(async () => {
setLoading(true)
try {
const res = await fetch(tokenUrl, { credentials: 'include' })
if (res.ok) {
const data = await res.json() as { feed_url: string | null }
setFeedUrl(data.feed_url)
}
} catch { /* ignore */ }
setLoading(false)
useEffect(() => {
let active = true
void fetch(tokenUrl, { credentials: 'include' })
.then(async res => res.ok ? (await res.json() as { feed_url: string | null }).feed_url : null)
.catch(() => null)
.then(url => {
if (!active) return
setFeedUrl(url)
setLoadedTokenUrl(tokenUrl)
})
return () => { active = false }
}, [tokenUrl])
useEffect(() => { load() }, [load])
const mutate = async (method: 'POST' | 'PUT' | 'DELETE') => {
setBusy(true)
try {
@@ -98,143 +85,27 @@ export function IcsSubscribeModal({ endpoint, title, description, onClose }: Ics
setBusy(false)
}
if (!isPhone) {
return (
<DesktopSubscribeDialog
titleId={titleId}
title={title}
description={description}
onClose={onClose}
loading={loading}
busy={busy}
feedUrl={feedUrl}
httpsUrl={httpsUrl}
webcalUrl={webcalUrl}
mutate={mutate}
dayEvents={dayEvents}
onToggleDayEvents={toggleDayEvents}
/>
)
}
return { loading: loadedTokenUrl !== tokenUrl, busy, feedUrl, httpsUrl, webcalUrl, mutate, dayEvents, toggleDayEvents }
}
return createPortal(
<div
role="presentation"
style={{
position: 'fixed', inset: 0, zIndex: 9999,
background: 'rgba(0,0,0,0.5)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
padding: '16px',
}}
onClick={e => { if (e.target === e.currentTarget) onClose() }}
>
<div style={{
background: 'var(--bg-card, white)',
borderRadius: 14,
padding: '22px 24px',
width: '100%',
maxWidth: 420,
boxShadow: '0 16px 48px rgba(0,0,0,0.22)',
border: '1px solid var(--border-faint)',
color: 'var(--text-primary)',
fontFamily: 'inherit',
position: 'relative',
}}>
{/* Header */}
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<Calendar size={16} strokeWidth={2} style={{ color: 'var(--accent, #6366f1)' }} />
<span style={{ fontWeight: 600, fontSize: 14 }}>{title}</span>
</div>
<button type="button"
onClick={onClose}
aria-label={t('common.close')}
style={{
background: 'none', border: 'none', cursor: 'pointer', padding: 4,
color: 'var(--text-muted)', borderRadius: 6, display: 'flex',
}}
>
<X size={15} strokeWidth={2} />
</button>
</div>
<p style={{ fontSize: 12, color: 'var(--text-muted)', marginBottom: 16, lineHeight: 1.5 }}>
{description}
</p>
{loading ? (
<div style={{ textAlign: 'center', padding: '16px 0', color: 'var(--text-muted)', fontSize: 12 }}>
{t('common.loading')}
</div>
) : !feedUrl ? (
<>
<button type="button"
onClick={() => mutate('POST')}
disabled={busy}
style={{
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
width: '100%', padding: '9px 14px', borderRadius: 9, border: 'none',
background: 'var(--accent, #6366f1)', color: 'var(--accent-text, #fff)',
fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
cursor: busy ? 'default' : 'pointer', opacity: busy ? 0.6 : 1,
}}
>
<Calendar size={14} strokeWidth={2} />
{t('dashboard.ics.enable')}
</button>
<p style={{ fontSize: 10, color: 'var(--text-muted)', marginTop: 8, lineHeight: 1.4 }}>
{t('dashboard.ics.enableHint')}
</p>
</>
) : (
<>
<div style={{ marginBottom: 16 }}>
<DayEventsSwitch on={dayEvents} onToggle={toggleDayEvents} />
</div>
<SubscribeLinks httpsUrl={httpsUrl} webcalUrl={webcalUrl} />
<div style={{ marginTop: 16, paddingTop: 12, borderTop: '1px solid var(--border-faint)', display: 'flex', gap: 8 }}>
<button type="button"
onClick={() => mutate('PUT')}
disabled={busy}
style={{
display: 'flex', alignItems: 'center', gap: 6,
background: 'none', border: '1px solid var(--border-primary)',
borderRadius: 7, padding: '5px 10px',
fontSize: 11, color: 'var(--text-muted)',
cursor: busy ? 'default' : 'pointer',
fontFamily: 'inherit', opacity: busy ? 0.6 : 1,
}}
>
<RefreshCw size={11} strokeWidth={2} style={{ animation: busy ? 'spin 0.8s linear infinite' : 'none' }} />
{t('dashboard.ics.regenerate')}
</button>
<button type="button"
onClick={() => mutate('DELETE')}
disabled={busy}
style={{
display: 'flex', alignItems: 'center', gap: 6,
background: 'none', border: '1px solid var(--border-primary)',
borderRadius: 7, padding: '5px 10px',
fontSize: 11, color: 'var(--danger, #dc2626)',
cursor: busy ? 'default' : 'pointer',
fontFamily: 'inherit', opacity: busy ? 0.6 : 1,
}}
>
<Power size={11} strokeWidth={2} />
{t('dashboard.ics.turnOff')}
</button>
</div>
<p style={{ fontSize: 10, color: 'var(--text-muted)', marginTop: 6, lineHeight: 1.4 }}>
{t('dashboard.ics.manageHint')}
</p>
</>
)}
</div>
<style>{`@keyframes spin { to { transform: rotate(360deg); } }`}</style>
</div>,
document.body
export function IcsSubscribeModal({ endpoint, title, description, onClose }: IcsSubscribeModalProps) {
const titleId = useId()
const { loading, busy, feedUrl, httpsUrl, webcalUrl, mutate, dayEvents, toggleDayEvents } = useIcsSubscription(endpoint)
return (
<DesktopSubscribeDialog
titleId={titleId}
title={title}
description={description}
onClose={onClose}
loading={loading}
busy={busy}
feedUrl={feedUrl}
httpsUrl={httpsUrl}
webcalUrl={webcalUrl}
mutate={mutate}
dayEvents={dayEvents}
onToggleDayEvents={toggleDayEvents}
/>
)
}
@@ -282,7 +153,7 @@ function DesktopSubscribeDialog({ titleId, title, description, onClose, loading,
footer = (
<DialogFooter>
<FooterSpacer />
<DialogButton variant="primary" onClick={() => mutate('POST')} disabled={busy} icon={<Calendar size={14} strokeWidth={2} />}>
<DialogButton variant="primary" onClick={() => void mutate('POST')} disabled={busy} icon={<Calendar size={14} strokeWidth={2} />}>
{t('dashboard.ics.enable')}
</DialogButton>
</DialogFooter>
@@ -299,11 +170,11 @@ function DesktopSubscribeDialog({ titleId, title, description, onClose, loading,
)
footer = (
<DialogFooter>
<DialogButton onClick={() => mutate('PUT')} disabled={busy} icon={<RefreshCw size={14} strokeWidth={2} className={busy ? 'animate-spin' : ''} />}>
<DialogButton onClick={() => void mutate('PUT')} disabled={busy} icon={<RefreshCw size={14} strokeWidth={2} className={busy ? 'animate-spin' : ''} />}>
{t('dashboard.ics.regenerate')}
</DialogButton>
<FooterSpacer />
<button type="button" onClick={() => mutate('DELETE')} disabled={busy} className={TURN_OFF_BTN} style={fs(13, 'body')}>
<button type="button" onClick={() => void mutate('DELETE')} disabled={busy} className={TURN_OFF_BTN} style={fs(13, 'body')}>
<Power size={14} strokeWidth={2} />
{t('dashboard.ics.turnOff')}
</button>
@@ -86,6 +86,20 @@ describe('PlaceDetailsColumn', () => {
expect(placeEnrichment).not.toHaveBeenCalled()
})
it('lets a mobile user upload a picture without opening an empty details group', () => {
renderColumn({
selection: null,
variant: 'mobile',
image: {
chosen: { kind: 'none' },
own: { currentUrl: null, attached: [], pendingPreview: null, canUpload: true, onUpload: vi.fn(), onPickAttached: vi.fn(), onRemove: vi.fn() },
},
})
expect(screen.getByRole('button', { name: 'places.uploadImage' })).toHaveTextContent('places.uploadImage')
expect(screen.queryByText('places.details.empty')).not.toBeInTheDocument()
expect(placeEnrichment).not.toHaveBeenCalled()
})
it('FE-PDC-002: shows a loading state, then the result', async () => {
let settle: (v: MapsPlaceEnrichmentResult) => void = () => {}
placeEnrichment.mockReturnValue(new Promise<MapsPlaceEnrichmentResult>((r) => { settle = r }))
@@ -68,7 +68,7 @@ interface PlaceDetailsColumnProps {
* small eyebrows. The default is the phone sheet's look: a card in the mobile
* tokens with the same one-line hints.
*/
variant?: 'sheet' | 'dialog'
variant?: 'sheet' | 'dialog' | 'mobile'
/** False on an instance with no Google key, which is most of them. */
t: TranslationFn
}
@@ -91,8 +91,7 @@ function SheetHint({ icon, children }: { icon: React.ReactNode; children: React.
*/
function Overline({ children }: { children: React.ReactNode }): React.ReactElement {
return (
// The phone form's eyebrow (mobile Eyebrow), so these labels match Name, Notes and the rest below.
<p className="font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] font-bold uppercase tracking-[.09em] text-m-faint">{children}</p>
<p className="text-control font-medium text-m-ink">{children}</p>
)
}
@@ -133,6 +132,7 @@ export default function PlaceDetailsColumn({
t,
}: PlaceDetailsColumnProps): React.ReactElement {
const dialog = variant === 'dialog'
const mobile = variant === 'mobile'
const adoptBlockedId = useId()
const [data, setData] = useState<MapsPlaceEnrichmentResult | null>(null)
const [state, setState] = useState<LoadState>('idle')
@@ -233,12 +233,27 @@ export default function PlaceDetailsColumn({
!data?.hours &&
!data?.rating
const pictures = (
<PictureBlock
photos={state === 'ready' && !data?.disabled ? (data?.photos ?? []) : []}
chosen={image?.chosen ?? chosenImage(selectedImageUrl, null, null)}
onPickImage={onPickImage}
own={image?.own}
dialog={dialog}
mobile={mobile}
t={t}
/>
)
if (mobile && !selection) return pictures
return (
// 320px, not 288: the picture grid was doing (288 - 24 - 12) / 3 = 84px
// tiles, which is too small to tell a facade from a foyer. The column is
// stretched to the form's height by the row it sits in, so the extra room
// costs nothing that was being used.
<aside className={dialog ? `${SIDE_COLUMN} ${fluid ? '' : 'sm:w-80'}` : `w-full ${fluid ? '' : 'sm:w-80'} shrink-0 flex flex-col self-stretch`}>
{mobile && pictures}
{dialog ? (
<ColumnHead icon={<Landmark size={13} strokeWidth={2.2} />}>{t('places.details.title')}</ColumnHead>
) : (
@@ -247,11 +262,12 @@ export default function PlaceDetailsColumn({
aria-expanded={open}
aria-controls={bodyId}
onClick={() => setOpen(o => !o)}
// A badge over the column's blocks: what they are, and the fold.
className="flex h-[36px] w-full shrink-0 items-center gap-2 rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] pe-3 ps-3.5 text-start"
className={mobile
? 'mt-3 flex min-h-11 w-full shrink-0 items-center gap-2 rounded-xl border border-m-rowbr bg-m-sheetop px-3 text-start'
: 'flex h-[36px] w-full shrink-0 items-center gap-2 rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] pe-3 ps-3.5 text-start'}
>
<Landmark size={13} strokeWidth={2.2} className="flex-none text-m-muted" />
<span className="min-w-0 flex-1 truncate font-geist text-caption font-semibold text-m-ink">{t('places.details.title')}</span>
<span className="min-w-0 flex-1 text-control font-medium text-m-ink">{t('places.details.title')}</span>
<ChevronDown
size={13}
strokeWidth={2.2}
@@ -268,14 +284,7 @@ export default function PlaceDetailsColumn({
<div className={dialog ? 'flex min-h-0 flex-1 flex-col gap-3.5 overflow-y-auto px-3 pb-3' : `min-h-0 overflow-hidden ${open ? '' : 'invisible'}`}>
<div className={dialog ? 'contents' : 'space-y-3 pt-3'}>
{/* The place's picture first: its own ones are there whatever the sources answer. */}
<PictureBlock
photos={state === 'ready' && !data?.disabled ? (data?.photos ?? []) : []}
chosen={image?.chosen ?? chosenImage(selectedImageUrl, null, null)}
onPickImage={onPickImage}
own={image?.own}
dialog={dialog}
t={t}
/>
{!mobile && pictures}
{/* Nothing picked yet, which is a state rather than a fault: one quiet
line, in the dialog and on the phone alike, so the form's own fields
@@ -348,6 +357,7 @@ function PictureBlock({
onPickImage,
own,
dialog,
mobile,
t,
}: {
photos: PlacePhotoCandidate[]
@@ -355,10 +365,11 @@ function PictureBlock({
onPickImage: (url: string | null) => void
own?: PlaceImageOwn
dialog: boolean
mobile: boolean
t: TranslationFn
}): React.ReactElement | null {
if (!offersPictures(photos, own)) return null
const picker = <PlaceImagePicker photos={photos} chosen={chosen} onPickUrl={onPickImage} own={own} dialog={dialog} t={t} />
const picker = <PlaceImagePicker photos={photos} chosen={chosen} onPickUrl={onPickImage} own={own} dialog={dialog} mobile={mobile} t={t} />
return (
<Block label={t('places.details.pickImage')} dialog={dialog}>
{dialog ? <div className={`${COLUMN_CARD} p-2`}>{picker}</div> : picker}
@@ -66,13 +66,23 @@ export function PendingFiles({
export function PlaceImageSection({
image,
onPickUrl,
mobile = false,
t,
}: {
image: { own: PlaceImageOwn; chosen: ChosenImage };
onPickUrl: (url: string | null) => void;
mobile?: boolean;
t: TranslationFn;
}) {
if (!offersPictures([], image.own)) return null;
if (mobile) {
return (
<section>
<h3 className="mb-2 text-control font-medium text-m-ink">{t('places.details.pickImage')}</h3>
<PlaceImagePicker photos={[]} chosen={image.chosen} onPickUrl={onPickUrl} own={image.own} mobile t={t} />
</section>
);
}
return (
<div className="min-w-0">
<div className={LABEL}>{t('places.details.pickImage')}</div>
@@ -32,6 +32,7 @@ interface PlaceImagePickerProps {
own?: PlaceImageOwn;
/** On a white card, without native tooltips: hovering moves the credit line instead. */
dialog?: boolean;
mobile?: boolean;
t: TranslationFn;
}
@@ -67,6 +68,7 @@ export default function PlaceImagePicker({
onPickUrl,
own,
dialog = false,
mobile = false,
t,
}: PlaceImagePickerProps): React.ReactElement | null {
const [hovered, setHovered] = useState<Credit>(null);
@@ -76,55 +78,62 @@ export default function PlaceImagePicker({
const shown = hovered ?? creditFor(chosen, photos, attached, own, t);
const removable = !!own && chosen.kind !== 'none';
const upload = own?.canUpload && (
<UploadTile
own={own}
selected={chosen.kind === 'upload'}
dialog={dialog}
mobile={mobile}
onHover={(on) => setHovered(on ? { kind: 'own', label: t('places.image.own') } : null)}
t={t}
/>
);
const showUploadRow = mobile && !own?.pendingPreview;
const showTiles = Boolean(current || attached.length || photos.length || (upload && !showUploadRow));
return (
<>
<div className="grid grid-cols-3 gap-1.5">
{own?.canUpload && (
<UploadTile
own={own}
selected={chosen.kind === 'upload'}
dialog={dialog}
onHover={(on) => setHovered(on ? { kind: 'own', label: t('places.image.own') } : null)}
t={t}
/>
)}
{current && (
<button
type="button"
onClick={() => (chosen.kind === 'current' ? own?.onRemove() : onPickUrl(current))}
aria-pressed={chosen.kind === 'current'}
aria-label={t('places.image.current')}
onMouseEnter={() => setHovered({ kind: 'own', label: t('places.image.current') })}
onMouseLeave={() => setHovered(null)}
className={`${TILE} ${ring(chosen.kind === 'current', dialog)}`}
>
<img src={current} alt="" className="h-full w-full object-cover" />
{chosen.kind === 'current' && <Picked />}
</button>
)}
{attached.map((file) => (
<AttachedTile
key={file.id}
file={file}
selected={chosen.kind === 'attached' && chosen.fileId === file.id}
onPick={() => own?.onPickAttached(file)}
onHover={(on) => setHovered(on ? { kind: 'own', label: file.original_name } : null)}
dialog={dialog}
/>
))}
{photos.map((photo) => (
<PhotoTile
key={photo.key}
photo={photo}
selected={chosen.kind === 'url' && chosen.url === photo.url}
onPick={onPickUrl}
onHover={(on) => setHovered(on ? { kind: 'photo', photo } : null)}
dialog={dialog}
t={t}
/>
))}
</div>
{showUploadRow && upload}
{showTiles && (
<div className={`grid grid-cols-3 gap-1.5 ${showUploadRow && upload ? 'mt-2' : ''}`}>
{!showUploadRow && upload}
{current && (
<button
type="button"
onClick={() => (chosen.kind === 'current' ? own?.onRemove() : onPickUrl(current))}
aria-pressed={chosen.kind === 'current'}
aria-label={t('places.image.current')}
onMouseEnter={() => setHovered({ kind: 'own', label: t('places.image.current') })}
onMouseLeave={() => setHovered(null)}
className={`${TILE} ${ring(chosen.kind === 'current', dialog)}`}
>
<img src={current} alt="" className="h-full w-full object-cover" />
{chosen.kind === 'current' && <Picked />}
</button>
)}
{attached.map((file) => (
<AttachedTile
key={file.id}
file={file}
selected={chosen.kind === 'attached' && chosen.fileId === file.id}
onPick={() => own?.onPickAttached(file)}
onHover={(on) => setHovered(on ? { kind: 'own', label: file.original_name } : null)}
dialog={dialog}
/>
))}
{photos.map((photo) => (
<PhotoTile
key={photo.key}
photo={photo}
selected={chosen.kind === 'url' && chosen.url === photo.url}
onPick={onPickUrl}
onHover={(on) => setHovered(on ? { kind: 'photo', photo } : null)}
dialog={dialog}
t={t}
/>
))}
</div>
)}
{(shown || removable) && (
<CreditLine shown={shown} onRemove={removable ? own?.onRemove : undefined} dialog={dialog} t={t} />
)}
@@ -137,12 +146,14 @@ function UploadTile({
own,
selected,
dialog,
mobile,
onHover,
t,
}: {
own: PlaceImageOwn;
selected: boolean;
dialog: boolean;
mobile: boolean;
onHover: (on: boolean) => void;
t: TranslationFn;
}): React.ReactElement {
@@ -162,36 +173,53 @@ function UploadTile({
const preview = own.pendingPreview;
return (
<>
<Tooltip label={t('places.uploadImage')} placement="top">
{mobile && !preview ? (
<button
type="button"
onClick={() => fileRef.current?.click()}
disabled={reading}
aria-pressed={selected}
aria-label={t('places.uploadImage')}
className={`${TILE} ${ring(selected, dialog)} ${preview ? '' : dialog ? 'border border-edge-faint bg-surface-secondary hover:bg-surface-tertiary' : 'border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)]'}`}
onMouseEnter={() => onHover(!!preview)}
onMouseLeave={() => onHover(false)}
aria-busy={reading}
className="flex min-h-11 w-full items-center gap-2 rounded-xl border border-m-rowbr bg-m-sheetop px-3 py-2 text-start text-control font-medium text-m-ink disabled:opacity-60"
>
{preview ? (
<>
<img src={preview} alt="" className="h-full w-full object-cover" />
{selected && <Picked />}
</>
{reading ? (
<Loader2 size={17} className="shrink-0 animate-spin text-m-muted" aria-hidden />
) : (
// Icon only: the tooltip and the button's name say what it does.
<span className="flex h-full w-full items-center justify-center">
<span className="grid h-11 w-11 place-items-center rounded-full bg-surface-card text-content-muted shadow-sm transition-transform duration-150 group-hover:scale-105 group-hover:text-content">
{reading ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
<ImagePlus className="h-5 w-5" strokeWidth={1.9} />
)}
</span>
</span>
<ImagePlus size={17} className="shrink-0 text-m-muted" aria-hidden />
)}
{t('places.uploadImage')}
</button>
</Tooltip>
) : (
<Tooltip label={t('places.uploadImage')} placement="top">
<button
type="button"
onClick={() => fileRef.current?.click()}
disabled={reading}
aria-pressed={selected}
aria-label={t('places.uploadImage')}
className={`${TILE} ${ring(selected, dialog)} ${preview ? '' : dialog ? 'border border-edge-faint bg-surface-secondary hover:bg-surface-tertiary' : 'border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)]'}`}
onMouseEnter={() => onHover(!!preview)}
onMouseLeave={() => onHover(false)}
>
{preview ? (
<>
<img src={preview} alt="" className="h-full w-full object-cover" />
{selected && <Picked />}
</>
) : (
// Icon only: the tooltip and the button's name say what it does.
<span className="flex h-full w-full items-center justify-center">
<span className="grid h-11 w-11 place-items-center rounded-full bg-surface-card text-content-muted shadow-sm transition-transform duration-150 group-hover:scale-105 group-hover:text-content">
{reading ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
<ImagePlus className="h-5 w-5" strokeWidth={1.9} />
)}
</span>
</span>
)}
</button>
</Tooltip>
)}
<input ref={fileRef} type="file" accept="image/*,.heic,.heif" className="hidden" onChange={(e) => void pick(e)} />
</>
);
@@ -8,11 +8,9 @@ interface SubscribeLinksProps {
}
/**
* Shared presentation for calendar subscription URLs. Renders one-click
* subscribe actions (Google deep link + webcal handoff) plus a copy fallback.
* Used by both the per-trip and all-trips subscribe modals.
* The provider links and clipboard behavior shared by both subscription dialogs.
*/
export function SubscribeLinks({ httpsUrl, webcalUrl }: SubscribeLinksProps) {
export function useSubscribeLinks(httpsUrl: string, webcalUrl: string) {
const { t } = useTranslation()
const [copied, setCopied] = useState<'https' | 'webcal' | null>(null)
@@ -41,6 +39,17 @@ export function SubscribeLinks({ httpsUrl, webcalUrl }: SubscribeLinksProps) {
} catch { /* ignore */ }
}
const manualLinks = [
{ label: 'Google Calendar', hint: t('dashboard.ics.pasteFromUrl'), url: httpsUrl, copied: copied === 'https', onCopy: () => void copy(httpsUrl, 'https') },
{ label: 'Apple Calendar / Outlook', hint: 'webcal://', url: webcalUrl, copied: copied === 'webcal', onCopy: () => void copy(webcalUrl, 'webcal') },
]
return { googleUrl, manualLinks }
}
export function SubscribeLinks({ httpsUrl, webcalUrl }: SubscribeLinksProps) {
const { t } = useTranslation()
const { googleUrl, manualLinks } = useSubscribeLinks(httpsUrl, webcalUrl)
return (
<div>
{/* One-click subscribe actions */}
@@ -78,22 +87,7 @@ export function SubscribeLinks({ httpsUrl, webcalUrl }: SubscribeLinksProps) {
<summary style={{ cursor: 'pointer', userSelect: 'none', marginBottom: 8 }}>
{t('dashboard.ics.copyManually')}
</summary>
<UrlRow
label="Google Calendar"
copyLabel={t('common.copy')}
hint={t('dashboard.ics.pasteFromUrl')}
url={httpsUrl}
copied={copied === 'https'}
onCopy={() => copy(httpsUrl, 'https')}
/>
<UrlRow
label="Apple Calendar / Outlook"
copyLabel={t('common.copy')}
hint="webcal://"
url={webcalUrl}
copied={copied === 'webcal'}
onCopy={() => copy(webcalUrl, 'webcal')}
/>
{manualLinks.map(link => <UrlRow key={link.label} {...link} copyLabel={t('common.copy')} />)}
</details>
</div>
)
@@ -6,6 +6,7 @@ import { useAuthStore } from '../../store/authStore'
import { useSettingsStore } from '../../store/settingsStore'
import { buildUser, buildReservation } from '../../../tests/helpers/factories'
import TransitJourneyModal from './TransitJourneyModal'
import MTransitJourneySheet from '../../mobile/screens/trip/sheets/MTransitJourneySheet'
function makeReservation() {
return {
@@ -231,17 +232,7 @@ describe('TransitJourneyModal', () => {
})
})
describe('TransitJourneyModal (mobile viewport)', () => {
const desktopWidth = window.innerWidth
beforeEach(() => {
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: 420 })
})
afterEach(() => {
Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: desktopWidth })
})
describe('MTransitJourneySheet', () => {
function makeMobileReservation() {
const res = makeReservation()
res.metadata = {
@@ -263,13 +254,14 @@ describe('TransitJourneyModal (mobile viewport)', () => {
return res
}
it('FE-PLANNER-TRANSITJOURNEY-015: renders the per-leg rail with platform, headsign and meta line', () => {
render(<TransitJourneyModal {...makeProps({ reservation: makeMobileReservation() })} />)
it('FE-PLANNER-TRANSITJOURNEY-015: renders the per-leg rail with platform, headsign and separate facts', () => {
render(<MTransitJourneySheet {...makeProps({ reservation: makeMobileReservation() })} />)
expect(screen.getByText('U2')).toBeInTheDocument()
expect(screen.getByText(/Platform 2/)).toBeInTheDocument()
expect(screen.getByText('Ruhleben')).toBeInTheDocument()
// mins · stops · agency collapse into one quiet line.
expect(screen.getByText(/24 min · 6 stops · BVG/)).toBeInTheDocument()
expect(screen.getByText('24 min')).toBeInTheDocument()
expect(screen.getByText('6 stops')).toBeInTheDocument()
expect(screen.getByText('BVG')).toBeInTheDocument()
expect(screen.getByText('08:36')).toBeInTheDocument()
// The meta-less leg falls back to its mode as the badge and shows no meta line.
expect(screen.getByText('BUS')).toBeInTheDocument()
@@ -280,7 +272,7 @@ describe('TransitJourneyModal (mobile viewport)', () => {
const reservation = makeMobileReservation()
const line = 'Melbourne Airport Express via Southern Cross'
reservation.metadata.transit.legs[1] = { ...reservation.metadata.transit.legs[1], line, line_text_color: undefined }
render(<TransitJourneyModal {...makeProps({ reservation })} />)
render(<MTransitJourneySheet {...makeProps({ reservation })} />)
const label = screen.getByText(line)
expect(label.parentElement).toHaveStyle({ maxInlineSize: '40%', color: '#fff' })
@@ -288,13 +280,30 @@ describe('TransitJourneyModal (mobile viewport)', () => {
expect(screen.getByText('Ruhleben')).toBeInTheDocument()
})
it('FE-PLANNER-TRANSITJOURNEY-016: mobile stat tiles stay iconless but keep value + caption', () => {
render(<TransitJourneyModal {...makeProps({ reservation: makeMobileReservation() })} />)
it('FE-PLANNER-TRANSITJOURNEY-016: shows mobile route facts and keeps deletion behind More', async () => {
const user = userEvent.setup()
render(<MTransitJourneySheet {...makeProps({ reservation: makeMobileReservation() })} />)
expect(screen.getByText('Transfers')).toBeInTheDocument()
expect(screen.getByText('Walking')).toBeInTheDocument()
expect(screen.getByText('1')).toBeInTheDocument()
// Delete collapses to an icon-only button on a phone.
const deleteBtn = screen.getByRole('button', { name: 'Delete' })
expect(deleteBtn.textContent?.trim()).toBe('')
expect(screen.queryByRole('button', { name: 'Delete' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'More' }))
expect(screen.getByRole('button', { name: 'Delete' })).toBeVisible()
})
it('opens the mobile journey in read mode and saves name and notes from the separate form', async () => {
const user = userEvent.setup()
const onSave = vi.fn().mockResolvedValue({})
render(<MTransitJourneySheet {...makeProps({ reservation: makeMobileReservation(), onSave })} />)
expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: /^Edit$/ }))
const title = screen.getByDisplayValue('Fernsehturm → Zoo')
await user.clear(title)
await user.type(title, 'To the zoo')
await user.type(screen.getByRole('textbox', { name: 'Notes' }), 'Meet on the platform')
await user.click(screen.getByRole('button', { name: 'Save' }))
expect(onSave).toHaveBeenCalledWith({ title: 'To the zoo', notes: 'Meet on the platform' })
})
})
@@ -1,9 +1,8 @@
import { useEffect, useRef, useState } from 'react'
import { useEffect, useState } from 'react'
import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import remarkBreaks from 'remark-breaks'
import { ArrowRight, ArrowRightLeft, Bold, CalendarDays, Clock, Code, Footprints, Heading2, Italic, Link2, List, ListChecks, MoveRight, Pencil, RefreshCw, Strikethrough, TramFront, Trash2 } from 'lucide-react'
import Modal from '../shared/Modal'
import { CalendarDays, Clock, Pencil, RefreshCw } from 'lucide-react'
import ConfirmDialog from '../shared/ConfirmDialog'
import { DialogShell, DialogSection, DialogFooter, FooterSpacer, DialogButton, DeleteButton, PILL, fs } from '../shared/DialogShell'
import { Segmented, TEXTAREA } from '../shared/dialogParts'
@@ -14,10 +13,8 @@ import { deleteBodyKey } from './bookings/bookingsModel'
import { useTranslation } from '../../i18n'
import { useSettingsStore } from '../../store/settingsStore'
import { useTripStore } from '../../store/tripStore'
import { splitReservationDateTime, formatTime } from '../../utils/formatters'
import { TransitTitle, TransitLineBadge, TransitMetaBadges, TransitWalkDivider, fmtTransitDuration } from './transitDisplay'
import type { Reservation } from '../../types'
import { useIsPhone } from '../../mobile/useIsPhone'
import { TransitTitle } from './transitDisplay'
import { TRANSIT_NOTE_TOOLS, transitJourneyFacts, useTransitNoteFormatting, type TransitJourneyModalProps } from './transitJourneyModel'
/**
* The journey view for an automated public-transit entry (#1065): a roomy modal
@@ -27,41 +24,11 @@ import { useIsPhone } from '../../mobile/useIsPhone'
* details" hands off to the full transport editor for the booking fields
* (travelers, costs, files, code, status — #2148).
*/
interface TransitLegMeta {
mode?: string
line?: string | null
line_color?: string | null
line_text_color?: string | null
headsign?: string | null
agency?: string | null
duration?: number
stops?: number
from?: { name?: string; time?: string | null; track?: string | null }
to?: { name?: string; time?: string | null; track?: string | null }
}
interface TransitJourneyModalProps {
reservation: Reservation
onClose: () => void
/** Partial field update — endpoints + itinerary stay untouched. */
onSave: (fields: { title: string; notes: string | null }) => Promise<unknown>
onDelete: () => Promise<unknown>
onChangeRoute: () => void
/** Switch to the full transport editor (travelers, costs, files, code, status). */
onEditDetails?: () => void
canEdit: boolean
}
export default function TransitJourneyModal({ reservation, onClose, onSave, onDelete, onChangeRoute, onEditDetails, canEdit }: TransitJourneyModalProps) {
const { t, locale } = useTranslation()
const isMobile = useIsPhone()
const timeFormat = useSettingsStore(st => st.settings.time_format) || '24h'
const budgetItems = useTripStore(st => st.budgetItems)
const res = reservation
const meta = typeof res.metadata === 'string' ? (() => { try { return JSON.parse(res.metadata || '{}') } catch { return {} } })() : (res.metadata || {})
const transit = meta.transit && Array.isArray(meta.transit.legs) ? meta.transit : null
const [title, setTitle] = useState(res.title || '')
const [editingTitle, setEditingTitle] = useState(false)
const [notes, setNotes] = useState(res.notes || '')
@@ -69,52 +36,7 @@ export default function TransitJourneyModal({ reservation, onClose, onSave, onDe
const [notesTab, setNotesTab] = useState<'write' | 'preview'>(() => (res.notes ? 'preview' : 'write'))
const [saving, setSaving] = useState(false)
const [confirmDelete, setConfirmDelete] = useState(false)
const titleInputRef = useRef<HTMLInputElement | null>(null)
const notesRef = useRef<HTMLTextAreaElement | null>(null)
// Markdown toolbar: wrap the selection / prefix the current lines, then
// restore focus and a sensible cursor.
const applyMd = (action: { wrap?: [string, string]; linePrefix?: string }) => {
const el = notesRef.current
if (!el) return
const start = el.selectionStart ?? 0
const end = el.selectionEnd ?? 0
const value = notes
let next = value
let selStart = start
let selEnd = end
if (action.wrap) {
const [pre, post] = action.wrap
const selected = value.slice(start, end)
next = value.slice(0, start) + pre + selected + post + value.slice(end)
selStart = start + pre.length
selEnd = selStart + selected.length
} else if (action.linePrefix) {
const prefix = action.linePrefix
const lineStart = value.lastIndexOf('\n', start - 1) + 1
const block = value.slice(lineStart, end)
const prefixed = block.split('\n').map(l => prefix + l).join('\n')
next = value.slice(0, lineStart) + prefixed + value.slice(end)
selStart = start + prefix.length
selEnd = end + (prefixed.length - block.length)
}
setNotes(next)
requestAnimationFrame(() => {
el.focus()
el.setSelectionRange(selStart, selEnd)
})
}
const MD_TOOLS: { Icon: typeof Bold; label: string; action: { wrap?: [string, string]; linePrefix?: string } }[] = [
{ Icon: Bold, label: 'Bold', action: { wrap: ['**', '**'] } },
{ Icon: Italic, label: 'Italic', action: { wrap: ['*', '*'] } },
{ Icon: Strikethrough, label: 'Strikethrough', action: { wrap: ['~~', '~~'] } },
{ Icon: Heading2, label: 'Heading', action: { linePrefix: '## ' } },
{ Icon: List, label: 'List', action: { linePrefix: '- ' } },
{ Icon: ListChecks, label: 'Checklist', action: { linePrefix: '- [ ] ' } },
{ Icon: Link2, label: 'Link', action: { wrap: ['[', '](https://)'] } },
{ Icon: Code, label: 'Code', action: { wrap: ['`', '`'] } },
]
const { notesRef, applyMd } = useTransitNoteFormatting(notes, setNotes)
useEffect(() => {
setTitle(res.title || '')
@@ -123,8 +45,6 @@ export default function TransitJourneyModal({ reservation, onClose, onSave, onDe
setNotesTab(res.notes ? 'preview' : 'write')
}, [res.id])
useEffect(() => { if (editingTitle) titleInputRef.current?.focus() }, [editingTitle])
const dirty = title !== (res.title || '') || notes !== (res.notes || '')
const save = async () => {
@@ -136,394 +56,109 @@ export default function TransitJourneyModal({ reservation, onClose, onSave, onDe
} finally { setSaving(false) }
}
const { date, time } = splitReservationDateTime(res.reservation_time)
const { time: endTime } = splitReservationDateTime(res.reservation_end_time)
const dateStr = date ? new Date(date + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'long', day: 'numeric', month: 'long', timeZone: 'UTC' }) : ''
const statTiles = transit ? [
{ Icon: Clock, value: transit.duration > 0 ? fmtTransitDuration(transit.duration, t) : '—', label: t('transit.durationLabel') },
{ Icon: ArrowRightLeft, value: String(transit.transfers ?? 0), label: t('transit.transfersLabel') },
{ Icon: Footprints, value: transit.walk_seconds > 59 ? t('transit.min', { count: Math.round(transit.walk_seconds / 60) }) : '—', label: t('transit.walkLabel') },
] : []
if (!isMobile) {
const titleId = `transit-journey-${res.id}`
const timeText = time ? `${formatTime(time, locale, timeFormat)}${endTime ? ` – ${formatTime(endTime, locale, timeFormat)}` : ''}` : ''
const header = (
<BookingDialogHeader
tone="transit"
type="transit"
labelId={titleId}
onClose={onClose}
title={<TransitTitle title={title} iconSize={16} />}
onTitleClick={canEdit ? () => setEditingTitle(true) : undefined}
titleTooltip={t('reservations.rename')}
titleInput={editingTitle ? {
value: title,
onChange: setTitle,
label: t('reservations.titleLabel'),
autoFocus: true,
onBlur: () => setEditingTitle(false),
onKeyDown: e => {
if (e.key === 'Enter') setEditingTitle(false)
// Spent here, so the dialog stays open and only the rename is dropped.
if (e.key === 'Escape') { e.preventDefault(); setTitle(res.title || ''); setEditingTitle(false) }
},
} : undefined}
pills={(
<>
<TypePill type="transit" />
{dateStr && <span className={PILL}><CalendarDays size={13} strokeWidth={2.2} className="text-content-faint" />{dateStr}</span>}
{timeText && <span className={PILL}><Clock size={13} strokeWidth={2.2} className="text-content-faint" /><span className="tabular-nums">{timeText}</span></span>}
</>
)}
/>
)
const footer = (
<DialogFooter>
{canEdit && <DialogButton onClick={onChangeRoute} icon={<RefreshCw size={14} strokeWidth={2} />}>{t('transit.changeRoute')}</DialogButton>}
{canEdit && onEditDetails && <DialogButton onClick={onEditDetails} icon={<Pencil size={14} strokeWidth={2} />}>{t('transit.editDetails')}</DialogButton>}
<FooterSpacer />
{canEdit && <DeleteButton onClick={() => setConfirmDelete(true)} />}
{canEdit
? <DialogButton variant="primary" onClick={save} disabled={saving || !title.trim() || !dirty}>{saving ? t('common.saving') : t('common.save')}</DialogButton>
: <DialogButton variant="primary" onClick={onClose}>{t('common.close')}</DialogButton>}
</DialogFooter>
)
const noteTools = canEdit && (
<span className="flex items-center gap-2">
{notesTab === 'write' && (
<span className="flex gap-px rounded-[10px] bg-surface-tertiary p-[3px]">
{MD_TOOLS.map(({ Icon, label, action }) => (
<Tooltip key={label} label={label} placement="top">
<button type="button" onClick={() => applyMd(action)} aria-label={label}
className="grid h-7 w-7 place-items-center rounded-[8px] text-content-muted hover:bg-surface-card hover:text-content">
<Icon size={13} strokeWidth={2} />
</button>
</Tooltip>
))}
</span>
)}
<Segmented<'write' | 'preview'>
value={notesTab}
onChange={setNotesTab}
label={t('reservations.notes')}
options={[{ value: 'write', label: t('common.edit') }, { value: 'preview', label: t('common.preview') }]}
/>
</span>
)
return (
<>
<DialogShell onClose={onClose} labelledBy={titleId} blocked={confirmDelete} header={header} footer={footer}>
{transit && (
<div className="flex gap-2">
{statTiles.map(({ value, label }) => (
<div key={label} className="min-w-0 flex-1 rounded-[12px] bg-surface-tertiary px-3 py-2.5 text-center">
<div className="truncate font-bold tabular-nums tracking-[-0.01em] text-content" style={fs(18, 'subtitle')}>{value}</div>
<div className="mt-0.5 truncate font-geist text-content-faint" style={fs(10.5)}>{label}</div>
</div>
))}
</div>
)}
{transit && transit.legs.length > 0 && (
<DialogSection label={t('transit.itinerary')}>
<TransitLegs legs={transit.legs as TransitLegMeta[]} />
</DialogSection>
)}
<DialogSection label={t('reservations.notes')} action={noteTools}>
{canEdit && notesTab === 'write' ? (
<textarea
ref={notesRef}
value={notes}
onChange={e => setNotes(e.target.value)}
placeholder={t('reservations.notesPlaceholder')}
aria-label={t('reservations.notes')}
className={TEXTAREA}
style={{ minHeight: 130, resize: 'vertical', lineHeight: 1.55 }}
/>
) : (
<div className={`rounded-[10px] border border-edge-faint bg-surface-card px-3.5 py-3 ${canEdit ? 'min-h-[130px]' : ''}`}>
{notes.trim()
? <div className="collab-note-md break-words text-content" style={fs(13, 'body')}><Markdown remarkPlugins={[remarkGfm, remarkBreaks]}>{notes}</Markdown></div>
: <span className="text-content-faint" style={fs(12.5, 'body')}>{t('reservations.notesPlaceholder')}</span>}
</div>
)}
</DialogSection>
</DialogShell>
<ConfirmDialog
isOpen={confirmDelete}
onClose={() => setConfirmDelete(false)}
onConfirm={async () => { setConfirmDelete(false); await onDelete(); onClose() }}
title={t('reservations.confirm.deleteTitle')}
message={t(deleteBodyKey(res.id, budgetItems), { name: res.title })}
/>
</>
)
}
return (
<Modal
isOpen
const { dateStr, timeText, legs, statTiles } = transitJourneyFacts(res, t, locale, timeFormat)
const titleId = `transit-journey-${res.id}`
const header = (
<BookingDialogHeader
tone="transit"
type="transit"
labelId={titleId}
onClose={onClose}
title={t('transit.journey')}
size="2xl"
footer={
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
{canEdit && (
<button type="button" onClick={() => setConfirmDelete(true)} aria-label={t('common.delete')} title={t('common.delete')} style={{
display: 'inline-flex', alignItems: 'center', gap: 5, padding: isMobile ? '9px 11px' : '8px 14px', borderRadius: 10,
border: '1px solid rgba(239,68,68,0.3)', background: 'rgba(239,68,68,0.06)', color: '#ef4444',
fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
}}>
<Trash2 size={13} /> {!isMobile && t('common.delete')}
</button>
)}
<div style={{ flex: 1 }} />
{canEdit && (
<button type="button" onClick={onChangeRoute} className="text-content-muted" style={{
display: 'inline-flex', alignItems: 'center', gap: 6, padding: '8px 16px', borderRadius: 10,
border: '1px solid var(--border-primary)', background: 'none',
fontSize: 'calc(12px * var(--fs-scale-body, 1))', cursor: 'pointer', fontFamily: 'inherit',
}}>
<RefreshCw size={13} /> {t('transit.changeRoute')}
</button>
)}
{canEdit && onEditDetails && (
<button type="button" onClick={onEditDetails} className="text-content-muted" style={{
display: 'inline-flex', alignItems: 'center', gap: 6, padding: '8px 16px', borderRadius: 10,
border: '1px solid var(--border-primary)', background: 'none',
fontSize: 'calc(12px * var(--fs-scale-body, 1))', cursor: 'pointer', fontFamily: 'inherit',
}}>
<Pencil size={13} /> {t('transit.editDetails')}
</button>
)}
{canEdit ? (
<button type="button" onClick={save} disabled={saving || !title.trim() || !dirty} className="bg-[var(--text-primary)] text-[var(--bg-primary)]" style={{
padding: '8px 20px', borderRadius: 10, border: 'none',
fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
opacity: saving || !title.trim() || !dirty ? 0.5 : 1,
}}>
{saving ? t('common.saving') : t('common.save')}
</button>
) : (
<button type="button" onClick={onClose} className="bg-accent text-accent-text" style={{ padding: '8px 20px', borderRadius: 10, border: 'none', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>
{t('common.close')}
</button>
)}
</div>
}
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 18, fontFamily: 'var(--font-system)' }}>
{/* header: icon + inline-renamable title + date/time */}
<div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
<div style={{ width: isMobile ? 40 : 48, height: isMobile ? 40 : 48, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: 13, background: '#7c3aed18' }}>
<TramFront size={isMobile ? 19 : 23} strokeWidth={1.8} color="#7c3aed" />
title={<TransitTitle title={title} iconSize={16} />}
onTitleClick={canEdit ? () => setEditingTitle(true) : undefined}
titleTooltip={t('reservations.rename')}
titleInput={editingTitle ? {
value: title,
onChange: setTitle,
label: t('reservations.titleLabel'),
autoFocus: true,
onBlur: () => setEditingTitle(false),
onKeyDown: e => {
if (e.key === 'Enter') setEditingTitle(false)
// Spent here, so the dialog stays open and only the rename is dropped.
if (e.key === 'Escape') { e.preventDefault(); setTitle(res.title || ''); setEditingTitle(false) }
},
} : undefined}
pills={(
<>
<TypePill type="transit" />
{dateStr && <span className={PILL}><CalendarDays size={13} strokeWidth={2.2} className="text-content-faint" />{dateStr}</span>}
{timeText && <span className={PILL}><Clock size={13} strokeWidth={2.2} className="text-content-faint" /><span className="tabular-nums">{timeText}</span></span>}
</>
)}
/>
)
const footer = (
<DialogFooter>
{canEdit && <DialogButton onClick={onChangeRoute} icon={<RefreshCw size={14} strokeWidth={2} />}>{t('transit.changeRoute')}</DialogButton>}
{canEdit && onEditDetails && <DialogButton onClick={onEditDetails} icon={<Pencil size={14} strokeWidth={2} />}>{t('transit.editDetails')}</DialogButton>}
<FooterSpacer />
{canEdit && <DeleteButton onClick={() => setConfirmDelete(true)} />}
{canEdit
? <DialogButton variant="primary" onClick={save} disabled={saving || !title.trim() || !dirty}>{saving ? t('common.saving') : t('common.save')}</DialogButton>
: <DialogButton variant="primary" onClick={onClose}>{t('common.close')}</DialogButton>}
</DialogFooter>
)
const noteTools = canEdit && (
<span className="flex items-center gap-2">
{notesTab === 'write' && (
<span className="flex gap-px rounded-[10px] bg-surface-tertiary p-[3px]">
{TRANSIT_NOTE_TOOLS.map(({ Icon, label, action }) => (
<Tooltip key={label} label={label} placement="top">
<button type="button" onClick={() => applyMd(action)} aria-label={label}
className="grid h-7 w-7 place-items-center rounded-[8px] text-content-muted hover:bg-surface-card hover:text-content">
<Icon size={13} strokeWidth={2} />
</button>
</Tooltip>
))}
</span>
)}
<Segmented<'write' | 'preview'>
value={notesTab}
onChange={setNotesTab}
label={t('reservations.notes')}
options={[{ value: 'write', label: t('common.edit') }, { value: 'preview', label: t('common.preview') }]}
/>
</span>
)
return (
<>
<DialogShell onClose={onClose} labelledBy={titleId} blocked={confirmDelete} header={header} footer={footer}>
{statTiles.length > 0 && (
<div className="flex gap-2">
{statTiles.map(({ value, label }) => (
<div key={label} className="min-w-0 flex-1 rounded-[12px] bg-surface-tertiary px-3 py-2.5 text-center">
<div className="truncate font-bold tabular-nums tracking-[-0.01em] text-content" style={fs(18, 'subtitle')}>{value}</div>
<div className="mt-0.5 truncate font-geist text-content-faint" style={fs(10.5)}>{label}</div>
</div>
))}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
{editingTitle ? (
<input
ref={titleInputRef}
value={title}
onChange={e => setTitle(e.target.value)}
onBlur={() => setEditingTitle(false)}
onKeyDown={e => { if (e.key === 'Enter') setEditingTitle(false); if (e.key === 'Escape') { setTitle(res.title || ''); setEditingTitle(false) } }}
className="text-content"
aria-label={t('reservations.titleLabel')}
style={{ width: '100%', border: 'none', outline: 'none', background: 'transparent', padding: 0, fontFamily: 'inherit', fontSize: 'calc(17px * var(--fs-scale-subtitle, 1))', fontWeight: 700, letterSpacing: '-0.015em', borderBottom: '1.5px solid var(--text-primary)' }}
/>
) : (
<div className="text-content" style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 'calc(17px * var(--fs-scale-subtitle, 1))', fontWeight: 700, letterSpacing: '-0.015em', minWidth: 0 }}>
<span style={{ minWidth: 0, overflow: 'hidden' }}><TransitTitle title={title} iconSize={15} /></span>
{canEdit && (
<button type="button" onClick={() => setEditingTitle(true)} aria-label={t('common.edit')} title={t('common.edit')} className="text-content-faint" style={{ border: 'none', background: 'none', padding: 3, cursor: 'pointer', display: 'flex', flexShrink: 0 }}>
<Pencil size={13} strokeWidth={1.8} />
</button>
)}
</div>
)}
<div className="text-content-muted" style={{ fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', marginTop: 3 }}>
{[dateStr, time ? `${formatTime(time, locale, timeFormat)}${endTime ? ` – ${formatTime(endTime, locale, timeFormat)}` : ''}` : ''].filter(Boolean).join(' · ')}
</div>
</div>
</div>
{transit && (
<>
{/* journey stats — three full-width tiles; iconless and flat on mobile */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: isMobile ? 6 : 10 }}>
{statTiles.map(({ Icon, value, label }, i) => (
isMobile ? (
<div key={i} className="bg-surface-tertiary" style={{ padding: '7px 6px 6px', borderRadius: 11, textAlign: 'center', minWidth: 0 }}>
<div className="text-content" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 700, letterSpacing: '-0.01em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{value}</div>
<div className="text-content-faint" style={{ fontSize: 'calc(9px * var(--fs-scale-caption, 1))', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em', marginTop: 1 }}>{label}</div>
</div>
) : (
<div key={i} className="bg-surface-tertiary" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 16px', borderRadius: 12 }}>
<div className="bg-surface-card" style={{ width: 34, height: 34, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', borderRadius: 10 }}>
<Icon size={16} strokeWidth={1.9} className="text-content-muted" />
</div>
<div style={{ minWidth: 0 }}>
<div className="text-content" style={{ fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 700, letterSpacing: '-0.01em', whiteSpace: 'nowrap' }}>{value}</div>
<div className="text-content-faint" style={{ fontSize: 'calc(10.5px * var(--fs-scale-caption, 1))', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</div>
</div>
</div>
)
))}
</div>
{/* stop-by-stop itinerary */}
<div className="bg-surface-tertiary" style={{ padding: isMobile ? '11px 10px' : '14px 16px', borderRadius: 12 }}>
<div className="text-content-faint" style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em', marginBottom: 12 }}>
{t('transit.itinerary')}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{(transit.legs as TransitLegMeta[]).map((leg, i) => {
if (leg.mode === 'WALK') return <TransitWalkDivider key={i} leg={leg} t={t} size={isMobile ? 'sm' : 'md'} />
const mins = leg.duration ? Math.round(leg.duration / 60) : null
if (isMobile) {
// The wide from → to line plus the chip row doesn't fit a
// phone: each leg becomes a depart / ride / arrive rail in
// the line's color, meta as one quiet text line.
const color = leg.line_color || 'var(--text-muted)'
const metaLine = [
mins ? t('transit.min', { count: mins }) : null,
leg.stops ? t('transit.stops', { count: leg.stops }) : null,
leg.agency || null,
].filter(Boolean).join(' · ')
// Names wrap instead of clipping; the platform gets its
// own quiet line below so it never pushes the name out.
const stopName = (stop: TransitLegMeta['from']) => (
<div style={{ minWidth: 0 }}>
<div className="text-content" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, lineHeight: 1.35, overflowWrap: 'anywhere' }}>
{stop?.name}
</div>
{stop?.track && (
<div className="text-content-faint" style={{ fontSize: 'calc(10.5px * var(--fs-scale-caption, 1))', fontWeight: 500, marginTop: 1 }}>
{t('transit.platform', { track: stop.track })}
</div>
)}
</div>
)
const timeCell = (time?: string | null) => (
<div className="text-content-muted" style={{ fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 600, textAlign: 'end', paddingTop: 1 }}>
{time || ''}
</div>
)
return (
<div key={i} style={{ display: 'grid', gridTemplateColumns: '34px 14px 1fr', columnGap: 8 }}>
{timeCell(leg.from?.time)}
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
<span style={{ width: 9, height: 9, borderRadius: '50%', border: `2.5px solid ${color}`, background: 'var(--bg-tertiary)', flexShrink: 0, marginTop: 3 }} />
<span style={{ flex: 1, width: 3, borderRadius: 2, background: color, marginTop: 2 }} />
</div>
{stopName(leg.from)}
<div />
<div style={{ display: 'flex', justifyContent: 'center' }}>
<span style={{ width: 3, borderRadius: 2, background: color }} />
</div>
<div style={{ padding: '6px 0 8px', minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
<TransitLineBadge label={leg.line || leg.mode} besideText={Boolean(leg.headsign)} wrap style={{ background: leg.line_color || 'var(--bg-hover)', color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--text-primary)', borderRadius: 6, padding: '1px 7px', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 700, flexShrink: 0 }} />
{leg.headsign && (
<span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 'calc(11px * var(--fs-scale-caption, 1))', minWidth: 0 }}>
<MoveRight size={10} style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{leg.headsign}</span>
</span>
)}
</div>
{metaLine && (
<div className="text-content-faint" style={{ fontSize: 'calc(10.5px * var(--fs-scale-caption, 1))', marginTop: 3 }}>{metaLine}</div>
)}
</div>
{timeCell(leg.to?.time)}
<div style={{ display: 'flex', justifyContent: 'center' }}>
<span style={{ width: 9, height: 9, borderRadius: '50%', border: `2.5px solid ${color}`, background: 'var(--bg-tertiary)', marginTop: 3 }} />
</div>
{stopName(leg.to)}
</div>
)
}
return (
<div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
<div className="text-content-muted" style={{ width: 44, flexShrink: 0, textAlign: 'end', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, paddingTop: 1 }}>
{leg.from?.time || ''}
</div>
<TransitLineBadge label={leg.line || leg.mode} besideText style={{ background: leg.line_color || 'var(--bg-hover)', color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--text-primary)', borderRadius: 6, padding: '2px 8px', fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 700, flexShrink: 0 }} />
<div style={{ flex: 1, minWidth: 0 }}>
<div className="text-content" style={{ fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 5, flexWrap: 'wrap' }}>
<span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.from?.name}</span>
{leg.from?.track && <span className="text-content-faint" style={{ fontWeight: 500 }}>({t('transit.platform', { track: leg.from.track })})</span>}
<ArrowRight size={12} className="text-content-faint" style={{ flexShrink: 0 }} />
<span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.to?.name}</span>
</div>
<div style={{ marginTop: 3 }}>
<TransitMetaBadges items={[
{ icon: Clock, text: leg.from?.time ? `${leg.from.time}${leg.to?.time ? ` – ${leg.to.time}` : ''}` : '' },
{ text: mins ? t('transit.min', { count: mins }) : '' },
{ text: leg.stops ? t('transit.stops', { count: leg.stops }) : '' },
{ icon: MoveRight, text: leg.headsign || '' },
{ text: leg.agency || '', dim: true },
]} />
</div>
</div>
</div>
)
})}
</div>
</div>
</>
)}
{/* notes — full width, markdown */}
<div>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6, gap: 8, flexWrap: 'wrap' }}>
<label className="text-content-faint" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.03em' }}>{t('reservations.notes')}</label>
{canEdit && (
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
{notesTab === 'write' && (
<div className="bg-surface-secondary" style={{ display: 'flex', borderRadius: 8, padding: 2, gap: 1 }}>
{MD_TOOLS.map(({ Icon, label, action }) => (
<button key={label} type="button" onClick={() => applyMd(action)} title={label} aria-label={label}
className="text-content-muted"
style={{ width: 26, height: 24, display: 'grid', placeItems: 'center', borderRadius: 6, border: 0, background: 'transparent', cursor: 'pointer' }}
onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-card)' }}
onMouseLeave={e => { e.currentTarget.style.background = 'transparent' }}>
<Icon size={13} strokeWidth={2} />
</button>
))}
</div>
)}
<div className="bg-surface-secondary" style={{ display: 'flex', borderRadius: 8, padding: 2, gap: 2 }}>
{([['write', t('common.edit')], ['preview', t('common.preview')]] as const).map(([tab, label]) => (
<button key={tab} type="button" onClick={() => setNotesTab(tab)}
className={notesTab === tab ? 'bg-surface-card text-content' : 'text-content-muted'}
style={{ padding: '4px 12px', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500, borderRadius: 6, border: 0, cursor: 'pointer', fontFamily: 'inherit', background: notesTab === tab ? undefined : 'transparent' }}>
{label}
</button>
))}
</div>
</div>
)}
</div>
{legs.length > 0 && (
<DialogSection label={t('transit.itinerary')}>
<TransitLegs legs={legs} />
</DialogSection>
)}
<DialogSection label={t('reservations.notes')} action={noteTools}>
{canEdit && notesTab === 'write' ? (
<textarea
ref={notesRef}
value={notes}
onChange={e => setNotes(e.target.value)}
placeholder={t('reservations.notesPlaceholder')}
className="w-full border border-edge rounded-[10px] px-[12px] py-[10px] text-[13px] font-[inherit] outline-none box-border text-content bg-surface-input"
aria-label={t('reservations.notes')}
className={TEXTAREA}
style={{ minHeight: 130, resize: 'vertical', lineHeight: 1.55 }}
/>
) : (
<div className="bg-surface-tertiary" style={{ borderRadius: 10, padding: '12px 14px', minHeight: canEdit ? 130 : undefined }}>
<div className={`rounded-[10px] border border-edge-faint bg-surface-card px-3.5 py-3 ${canEdit ? 'min-h-[130px]' : ''}`}>
{notes.trim()
? <div className="collab-note-md text-content" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', wordBreak: 'break-word', overflowWrap: 'anywhere' }}><Markdown remarkPlugins={[remarkGfm, remarkBreaks]}>{notes}</Markdown></div>
: <span className="text-content-faint" style={{ fontSize: 'calc(12.5px * var(--fs-scale-body, 1))' }}>{t('reservations.notesPlaceholder')}</span>}
? <div className="collab-note-md break-words text-content" style={fs(13, 'body')}><Markdown remarkPlugins={[remarkGfm, remarkBreaks]}>{notes}</Markdown></div>
: <span className="text-content-faint" style={fs(12.5, 'body')}>{t('reservations.notesPlaceholder')}</span>}
</div>
)}
</div>
</div>
</DialogSection>
</DialogShell>
<ConfirmDialog
isOpen={confirmDelete}
onClose={() => setConfirmDelete(false)}
@@ -531,6 +166,6 @@ export default function TransitJourneyModal({ reservation, onClose, onSave, onDe
title={t('reservations.confirm.deleteTitle')}
message={t(deleteBodyKey(res.id, budgetItems), { name: res.title })}
/>
</Modal>
</>
)
}
@@ -1,7 +1,7 @@
import React, { useEffect, useMemo, useRef, useState } from 'react'
import React, { useEffect, useId, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import tzlookup from 'tz-lookup'
import { ArrowLeftRight, ArrowRight, Bus, CableCar, ChevronDown, ChevronUp, Clock, Footprints, MapPin, Sailboat, Search, TramFront, TrainFront, TrainFrontTunnel } from 'lucide-react'
import { ArrowLeftRight, ArrowRight, Bus, CableCar, ChevronDown, ChevronUp, Clock, Footprints, MapPin, Sailboat, Search, SlidersHorizontal, TramFront, TrainFront, TrainFrontTunnel } from 'lucide-react'
import CustomTimePicker from '../shared/CustomTimePicker'
import { TransitLineBadge, TransitMetaBadges } from './transitDisplay'
import { transitApi } from '../../api/client'
@@ -215,15 +215,17 @@ function useFloatingList(anchorRef: React.RefObject<HTMLElement | null>, open: b
return pos
}
function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
function StopPicker({ label, value, onPick, quickPicks, near, placeholder, mobile }: {
label: string
value: PickedPlace | null
onPick: (p: PickedPlace | null) => void
quickPicks: PickedPlace[]
near: string | null
placeholder: string
mobile?: boolean
}) {
const { language } = useTranslation()
const fieldId = useId()
const [text, setText] = useState('')
const [results, setResults] = useState<TransitPlaceResult[]>([])
const [open, setOpen] = useState(false)
@@ -286,28 +288,30 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
return (
<div ref={rootRef} style={{ position: 'relative', flex: 1, minWidth: 0 }}>
<label className="block text-[11px] font-semibold text-content-faint mb-[5px] uppercase tracking-[0.03em]">{label}</label>
<div ref={fieldRef} className="bg-surface-input border border-edge" style={{ display: 'flex', alignItems: 'center', gap: 7, borderRadius: 10, padding: '0 10px', height: 38 }}>
<MapPin size={14} className="text-content-faint" style={{ flexShrink: 0 }} />
<label htmlFor={fieldId} className={mobile ? 'mb-1.5 block text-control font-medium text-m-ink' : 'mb-[5px] block text-[11px] font-semibold uppercase tracking-[0.03em] text-content-faint'}>{label}</label>
<div ref={fieldRef} className={mobile
? 'flex min-h-11 items-center gap-2 rounded-xl border border-m-rowbr bg-m-sheetop px-3 focus-within:ring-1 focus-within:ring-m-act'
: 'flex h-[38px] items-center gap-[7px] rounded-[10px] border border-edge bg-surface-input px-2.5'}>
<MapPin size={16} className={mobile ? 'shrink-0 text-m-muted' : 'shrink-0 text-content-faint'} aria-hidden />
<input
id={fieldId}
value={display}
onChange={e => search(e.target.value)}
// Opens its list on focus, so a dialog must not focus it by itself (#1302).
data-no-autofocus
onFocus={() => setOpen(true)}
placeholder={placeholder}
className="text-content"
style={{ border: 0, background: 'none', outline: 'none', fontSize: 'calc(13px * var(--fs-scale-body, 1))', width: '100%', fontFamily: 'inherit' }}
className={mobile ? 'min-w-0 flex-1 border-0 bg-transparent py-2 text-control text-m-ink outline-none placeholder:text-m-muted'
: 'w-full border-0 bg-transparent text-control text-content outline-none'}
/>
</div>
{open && listPos && suggestions.length > 0 && createPortal(
// On the page rather than inside the dialog, so a dialog that scrolls or clips
// its content cannot cut the list off before anything is typed.
<div ref={listRef} className="bg-surface-card border border-edge z-[var(--z-toast)]" style={{ position: 'fixed', left: listPos.left, width: listPos.width, ...(listPos.above ? { bottom: listPos.bottom } : { top: listPos.top }), borderRadius: 10, boxShadow: 'var(--shadow-dropdown)', overflow: 'hidden', maxHeight: listPos.maxHeight, overflowY: 'auto' }}>
<div ref={listRef} className={`border z-[var(--z-toast)] ${mobile ? 'm-root divide-y divide-m-rowbr border-m-rowbr bg-m-sheetop' : 'border-edge bg-surface-card'}`} style={{ position: 'fixed', left: listPos.left, width: listPos.width, ...(listPos.above ? { bottom: listPos.bottom } : { top: listPos.top }), borderRadius: 12, boxShadow: 'var(--shadow-dropdown)', overflow: 'hidden', maxHeight: listPos.maxHeight, overflowY: 'auto' }}>
{suggestions.map(r => (
<button type="button" key={pickedPlaceKey(r)} onClick={() => pick(r)}
className="text-content"
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'start', padding: '8px 10px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
className={`flex w-full items-center gap-2 border-0 bg-transparent px-3 py-2 text-start text-control ${mobile ? 'min-h-11 text-m-ink active:bg-m-ic' : 'text-content'}`}
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
@@ -340,7 +344,7 @@ function LineBadge({ leg, wrap = false }: { leg: TransitLeg; wrap?: boolean }) {
)
}
function ItineraryCard({ it, tzFrom, tzTo, is12h, expanded, onToggle, onAdd, adding, late, t }: {
function ItineraryCard({ it, tzFrom, tzTo, is12h, expanded, onToggle, onAdd, adding, late, t, mobile }: {
it: TransitItinerary
tzFrom: string
tzTo: string
@@ -349,6 +353,7 @@ function ItineraryCard({ it, tzFrom, tzTo, is12h, expanded, onToggle, onAdd, add
onToggle: () => void
onAdd: () => void
adding: boolean
mobile: boolean
/** CW-08: the next city walk this connection arrives too late for. */
late: WalkLate | null
t: (k: string, p?: Record<string, string | number>) => string
@@ -356,8 +361,8 @@ function ItineraryCard({ it, tzFrom, tzTo, is12h, expanded, onToggle, onAdd, add
const transitLegs = it.legs.filter(l => l.mode !== 'WALK')
const walkMins = Math.round(it.walkSeconds / 60)
return (
<div className="bg-surface-card border border-edge" style={{ borderRadius: 14, overflow: 'hidden' }}>
<button type="button" onClick={onToggle} style={{ display: 'block', width: '100%', textAlign: 'start', padding: '12px 14px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit' }}>
<div className={`overflow-hidden rounded-[14px] border ${mobile ? 'border-m-rowbr bg-m-sheetop' : 'border-edge bg-surface-card'}`}>
<button type="button" aria-expanded={expanded} onClick={onToggle} className="block w-full border-0 bg-transparent px-3.5 py-3 text-start">
<div style={{ display: 'flex', alignItems: 'baseline', gap: 10, flexWrap: 'wrap' }}>
<span className="text-content" style={{ fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 700, letterSpacing: '-0.01em' }}>
{fmtTimeInTz(it.startTime, tzFrom, is12h)} – {fmtTimeInTz(it.endTime, tzTo, is12h)}
@@ -461,8 +466,9 @@ function ItineraryCard({ it, tzFrom, tzTo, is12h, expanded, onToggle, onAdd, add
<button type="button"
onClick={onAdd}
disabled={adding}
className="bg-accent text-accent-text"
style={{ marginTop: 12, width: '100%', border: 'none', borderRadius: 10, padding: '9px 0', fontWeight: 600, fontSize: 'calc(13px * var(--fs-scale-body, 1))', cursor: adding ? 'default' : 'pointer', fontFamily: 'inherit', opacity: adding ? 0.6 : 1 }}
className={`mt-3 w-full border-0 text-control font-semibold disabled:opacity-60 ${mobile
? 'min-h-11 rounded-full bg-m-act px-3 py-2 text-m-actfg'
: 'rounded-[10px] bg-accent py-[9px] text-accent-text'}`}
>
{adding ? t('transit.adding') : t('transit.addToDay')}
</button>
@@ -491,9 +497,10 @@ interface TransitSearchPanelProps {
initialTime?: string | null
/** CW-08: the two city walks the leg runs between; said only while the search is for their day. */
walk?: WalkTransitContext | null
mobile?: boolean
}
export default function TransitSearchPanel({ day, days, places, accommodations = [], onAdd, initialFrom = null, initialTo = null, initialTime = null, walk = null }: TransitSearchPanelProps) {
export default function TransitSearchPanel({ day, days, places, accommodations = [], onAdd, initialFrom = null, initialTo = null, initialTime = null, walk = null, mobile = false }: TransitSearchPanelProps) {
const { t, language } = useTranslation()
const toast = useToast()
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
@@ -663,6 +670,13 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
const tzFrom = from ? tzAt(from.lat, from.lng) : 'UTC'
const tzTo = to ? tzAt(to.lat, to.lng) : tzFrom
const canSearch = !!from && !!to && !!time && !loading
const prefOptions = [
{ value: 'best', label: t('transit.pref.best') },
{ value: 'transfers', label: t('transit.pref.transfers') },
{ value: 'walking', label: t('transit.pref.walking') },
] as const
const departOptions = [{ arrive: false, label: t('transit.depart') }, { arrive: true, label: t('transit.arrive') }]
const mobileChoice = (active: boolean) => `inline-flex min-h-10 items-center justify-center gap-1.5 rounded-full px-3 py-1.5 text-caption font-medium ${active ? 'bg-m-act text-m-actfg' : 'bg-m-sheetop text-m-ink'}`
const segBtn = (active: boolean): React.CSSProperties => ({
padding: isMobile ? '6px 5px' : '6px 11px', fontSize: isMobile ? 'calc(11px * var(--fs-scale-body, 1))' : 'calc(12px * var(--fs-scale-body, 1))', borderRadius: 7, fontWeight: 500,
@@ -675,9 +689,9 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, fontFamily: 'var(--font-system)' }}>
<WalkTransitNote walk={walkHere} />
{/* from / to — stacked tight on mobile, swap button on desktop only */}
<div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row', gap: 8, alignItems: isMobile ? 'stretch' : 'flex-end' }}>
<StopPicker label={t('transit.from')} value={from} onPick={setFrom} quickPicks={quickPicks} near={near} placeholder={t('transit.searchStop')} />
{!isMobile && (
<div className={mobile ? 'flex flex-col gap-2.5 rounded-[14px] bg-m-ic p-3' : `flex gap-2 ${isMobile ? 'flex-col' : 'items-end'}`}>
<StopPicker mobile={mobile} label={t('transit.from')} value={from} onPick={setFrom} quickPicks={quickPicks} near={near} placeholder={t('transit.searchStop')} />
{!mobile && !isMobile && (
<button type="button"
onClick={() => { const f = from; setFrom(to); setTo(f) }}
aria-label={t('transit.swap')}
@@ -688,10 +702,52 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
<ArrowLeftRight size={15} />
</button>
)}
<StopPicker label={t('transit.to')} value={to} onPick={setTo} quickPicks={quickPicks} near={near} placeholder={t('transit.searchStop')} />
<StopPicker mobile={mobile} label={t('transit.to')} value={to} onPick={setTo} quickPicks={quickPicks} near={near} placeholder={t('transit.searchStop')} />
</div>
{/* search options — one calm card: when + how on top, modes + go below */}
{mobile ? (
<>
<div className="space-y-2 rounded-[14px] bg-m-ic p-3">
<div className="flex flex-wrap items-center gap-2">
<div className="flex min-h-11 flex-1 rounded-full bg-m-sheetop p-0.5">
{departOptions.map(({ arrive, label }) => (
<button key={label} type="button" aria-pressed={arriveBy === arrive} onClick={() => setArriveBy(arrive)}
className={`${mobileChoice(arriveBy === arrive)} min-w-0 flex-1 !px-2`}>
{label}
</button>
))}
</div>
<div className="min-w-[88px] flex-none">
<CustomTimePicker value={time} onChange={setTime} aria-label={t('reservations.time')} />
</div>
</div>
<details className="group border-t border-m-rowbr">
<summary className="flex min-h-11 cursor-pointer list-none items-center gap-2 text-control font-medium [&::-webkit-details-marker]:hidden">
<SlidersHorizontal size={16} className="shrink-0 text-m-muted" aria-hidden />
<span className="flex-1">{t('places.filters')}</span>
{activeModes.size < MODE_GROUPS.length && <span className="rounded-full bg-m-sheetop px-2 py-1 text-caption tabular-nums">{activeModes.size}</span>}
<ChevronDown size={16} className="shrink-0 text-m-muted group-open:rotate-180" aria-hidden />
</summary>
<div className="flex flex-wrap gap-1.5 pb-2">
{prefOptions.map(({ value, label }) => (
<button key={value} type="button" aria-pressed={pref === value} onClick={() => setPref(value)} className={mobileChoice(pref === value)}>{label}</button>
))}
</div>
<div className="flex flex-wrap gap-1.5 border-t border-m-rowbr pt-2">
{MODE_GROUPS.map(({ key, labelKey, Icon }) => (
<button key={key} type="button" aria-pressed={activeModes.has(key)} onClick={() => toggleMode(key)} className={mobileChoice(activeModes.has(key))}>
<Icon size={15} strokeWidth={2} />{t(labelKey)}
</button>
))}
</div>
</details>
</div>
<button type="button" onClick={search} disabled={!canSearch || !day.date}
className="flex min-h-11 items-center justify-center gap-2 rounded-full bg-m-act px-4 py-2 text-control font-semibold text-m-actfg disabled:opacity-40">
<Search size={16} aria-hidden />{t(loading ? 'transit.searching' : 'transit.search')}
</button>
</>
) : (
<div className="bg-surface-tertiary" style={{ borderRadius: 14, padding: '12px 14px', display: 'flex', flexDirection: 'column', gap: 12 }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
@@ -710,9 +766,9 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
)}
</div>
<div className="bg-surface-secondary" style={{ display: 'flex', borderRadius: 9, padding: 3, width: isMobile ? '100%' : undefined }}>
<button type="button" onClick={() => setPref('best')} style={{ ...segBtn(pref === 'best'), flex: isMobile ? 1 : undefined }}>{t('transit.pref.best')}</button>
<button type="button" onClick={() => setPref('transfers')} style={{ ...segBtn(pref === 'transfers'), flex: isMobile ? 1 : undefined }}>{t('transit.pref.transfers')}</button>
<button type="button" onClick={() => setPref('walking')} style={{ ...segBtn(pref === 'walking'), flex: isMobile ? 1 : undefined }}>{t('transit.pref.walking')}</button>
{prefOptions.map(({ value, label }) => (
<button key={value} type="button" onClick={() => setPref(value)} style={{ ...segBtn(pref === value), flex: isMobile ? 1 : undefined }}>{label}</button>
))}
</div>
</div>
@@ -751,6 +807,7 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
</button>
</div>
</div>
)}
{/* results */}
{loading && (
@@ -778,6 +835,7 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
onToggle={() => setExpandedIdx(expandedIdx === idx ? null : idx)}
onAdd={() => addItinerary(it, idx)}
adding={addingIdx === idx}
mobile={mobile}
late={lateForWalk(walkHere, day.date ?? null, { date: dateYMDInTz(it.endTime, tzTo), time: timeHHmmInTz(it.endTime, tzTo) })}
t={t}
/>
@@ -181,14 +181,14 @@ export interface BookingFilters {
}
/** Everything a person could look a booking up by: its title, type, route, codes, carrier, place and people. */
export function searchText(r: Reservation, typeLabel: string): string {
export function searchText(r: Reservation, typeLabel: string, includeCodes = true): string {
const meta = parseMeta(r)
const legs = Array.isArray(meta.legs) ? meta.legs : []
return [
r.title, typeLabel, r.location, r.place_name, r.accommodation_name, r.notes, r.confirmation_number,
r.title, typeLabel, r.location, r.place_name, r.accommodation_name, r.notes, includeCodes ? r.confirmation_number : null,
meta.airline, meta.flight_number, meta.train_number, meta.departure_airport, meta.arrival_airport,
...(r.endpoints || []).flatMap(e => [e.name, e.code]),
...legs.flatMap((l: Record<string, unknown>) => [l.confirmation_number, l.flight_number, l.airline, l.train_number]),
...legs.flatMap((l: Record<string, unknown> | null) => [includeCodes ? l?.confirmation_number : null, l?.flight_number, l?.airline, l?.train_number]),
...(r.travelers || []).map(tv => tv.username),
].filter(v => typeof v === 'string' && v).join(' ').toLowerCase()
}
@@ -26,13 +26,18 @@ export function listSections(groups: StatusGroups, t: (key: string) => string) {
* filters in useBookingsView, remembered for the session, and shares the
* predicates with the phone through bookingsModel.
*/
export function useReservationListFilter(all: Reservation[], days: Day[], memberCount: number) {
export function useReservationListFilter(
all: Reservation[],
days: Day[],
memberCount: number,
matches?: (reservation: Reservation) => boolean
) {
const [travelerFilter, setTravelerFilter] = useState<Set<number>>(new Set());
// The moment the tab opened: what was over by then moves into the folded Past
// section (#3156). Taken once, so a list does not reshuffle while it is read.
const [now] = useState(() => new Date());
const groups = groupTransports(
all.filter((r) => onTravelers(r, travelerFilter)),
all.filter((r) => onTravelers(r, travelerFilter) && (!matches || matches(r))),
days,
now
);
+9 -1
View File
@@ -26,6 +26,14 @@ export interface OptimizedDay {
usedHotel: boolean;
}
function optimizableStops(assignments: Assignment[]): Assignment[] {
return assignments.filter((a) => !a.place?.place_time && a.place?.lat != null && a.place?.lng != null);
}
export function canOptimizeDay(assignments: Assignment[]): boolean {
return optimizableStops(assignments).length >= 2;
}
/**
* Optimized order for a day's assignments: timed places keep their slot, the
* remaining located stops are rerouted (optionally anchored to the day's
@@ -46,7 +54,7 @@ export function optimizeDayOrder(
if (a.place?.place_time) locked.set(idx, a);
else movable.push(a);
});
const withCoords = movable.filter((a) => a.place?.lat != null && a.place?.lng != null);
const withCoords = optimizableStops(dayAssignments);
if (withCoords.length < 2) return null;
const noCoords = movable.filter((a) => a.place?.lat == null || a.place?.lng == null);
const anchors = fromAccommodation
@@ -0,0 +1,109 @@
import { Bold, Code, Heading2, Italic, Link2, List, ListChecks, Strikethrough } from 'lucide-react';
import { useRef } from 'react';
import type { Reservation } from '../../types';
import { parseReservationMetadata } from '../../utils/flightLegs';
import { formatTime, splitReservationDateTime } from '../../utils/formatters';
import { transitSummary } from './bookings/transitParts';
import { fmtTransitDuration } from './transitDisplay';
export interface TransitJourneyModalProps {
reservation: Reservation;
onClose: () => void;
/** Partial field update — endpoints + itinerary stay untouched. */
onSave: (fields: { title: string; notes: string | null }) => Promise<unknown>;
onDelete: () => Promise<unknown>;
onChangeRoute: () => void;
/** Switch to the full transport editor (travelers, costs, files, code, status). */
onEditDetails?: () => void;
canEdit: boolean;
}
export function transitJourneyFacts(
reservation: Reservation,
t: Parameters<typeof fmtTransitDuration>[1],
locale: string,
timeFormat: string
) {
const { date, time } = splitReservationDateTime(reservation.reservation_time);
const { time: endTime } = splitReservationDateTime(reservation.reservation_end_time);
const timeText = time
? [time, endTime]
.filter(Boolean)
.map((value) => formatTime(value, locale, timeFormat))
.join(' – ')
: '';
const dateStr = date
? new Date(date + 'T00:00:00Z').toLocaleDateString(locale, {
weekday: 'long',
day: 'numeric',
month: 'long',
timeZone: 'UTC',
})
: '';
const transit = transitSummary(parseReservationMetadata(reservation));
const statTiles = transit
? [
{ value: transit.duration ? fmtTransitDuration(transit.duration, t) : '—', label: t('transit.durationLabel') },
{ value: String(transit.transfers), label: t('transit.transfersLabel') },
{
value: transit.walk > 59 ? t('transit.min', { count: Math.round(transit.walk / 60) }) : '—',
label: t('transit.walkLabel'),
},
]
: [];
return { dateStr, timeText, legs: transit?.legs ?? [], statTiles };
}
type FormatAction = { wrap?: [string, string]; linePrefix?: string };
export const TRANSIT_NOTE_TOOLS: { Icon: typeof Bold; label: string; action: FormatAction }[] = [
{ Icon: Bold, label: 'Bold', action: { wrap: ['**', '**'] } },
{ Icon: Italic, label: 'Italic', action: { wrap: ['*', '*'] } },
{ Icon: Strikethrough, label: 'Strikethrough', action: { wrap: ['~~', '~~'] } },
{ Icon: Heading2, label: 'Heading', action: { linePrefix: '## ' } },
{ Icon: List, label: 'List', action: { linePrefix: '- ' } },
{ Icon: ListChecks, label: 'Checklist', action: { linePrefix: '- [ ] ' } },
{ Icon: Link2, label: 'Link', action: { wrap: ['[', '](https://)'] } },
{ Icon: Code, label: 'Code', action: { wrap: ['`', '`'] } },
];
export function useTransitNoteFormatting(notes: string, setNotes: (value: string) => void) {
const notesRef = useRef<HTMLTextAreaElement | null>(null);
// Markdown toolbar: wrap the selection / prefix the current lines, then
// restore focus and a sensible cursor.
const applyMd = (action: FormatAction) => {
const el = notesRef.current;
if (!el) return;
const start = el.selectionStart ?? 0;
const end = el.selectionEnd ?? 0;
const value = notes;
let next = value;
let selStart = start;
let selEnd = end;
if (action.wrap) {
const [pre, post] = action.wrap;
const selected = value.slice(start, end);
next = value.slice(0, start) + pre + selected + post + value.slice(end);
selStart = start + pre.length;
selEnd = selStart + selected.length;
} else if (action.linePrefix) {
const prefix = action.linePrefix;
const lineStart = value.lastIndexOf('\n', start - 1) + 1;
const block = value.slice(lineStart, end);
const prefixed = block
.split('\n')
.map((l) => prefix + l)
.join('\n');
next = value.slice(0, lineStart) + prefixed + value.slice(end);
selStart = start + prefix.length;
selEnd = end + (prefixed.length - block.length);
}
setNotes(next);
requestAnimationFrame(() => {
el.focus();
el.setSelectionRange(selStart, selEnd);
});
};
return { notesRef, applyMd };
}
@@ -14,7 +14,7 @@ export interface PlacesColumnFileImportOptions {
canEdit: boolean;
/** The imported tours' place ids, so the places pool leaves them out at once. */
onToursChanged?: (placeIds?: number[]) => void | Promise<void>;
/** The new tours are in, after the trip's places were read again. */
/** The tours finished importing and no point-only files are waiting in the places step. */
onImported?: (tours: TourListItem[]) => void;
}
@@ -47,7 +47,9 @@ export function usePlacesColumnFileImport({
tripId,
canEdit: canEdit && toursEnabled,
onToursChanged,
onImported,
onImported: (tours) => {
if (!placesFiles?.length) onImported?.(tours);
},
onNoTrack: setPlacesFiles,
});
@@ -33,7 +33,7 @@ interface RoadtripStayModalProps {
* Zero clears it: the rail reads "no stay" and "nothing planned" as the same thing.
* The visit rides along, so the stay lands on it and not on every visit of the place.
*/
onSave: (placeId: number, minutes: number, assignmentId?: number) => Promise<void> | void
onSave: (placeId: number, minutes: number, assignmentId?: number) => Promise<boolean | void> | boolean | void
}
/** The round minus and plus beside the number. */
@@ -90,8 +90,7 @@ export default function RoadtripStayModal({ stop, onClose, onSave }: RoadtripSta
if (saving) return
setSaving(true)
try {
await onSave(stop.placeId, value, stop.assignmentId)
onClose()
if (await onSave(stop.placeId, value, stop.assignmentId) !== false) onClose()
} finally {
setSaving(false)
}
@@ -7,9 +7,8 @@ import { generateUUID } from '../../sync/mutationQueue';
import { getApiErrorMessage } from '../../types';
/**
* A route shared from Google Maps, read and appended to a day of the trip: the logic
* behind the desktop's import dialog (GoogleRouteImport) and the large screens' sheet
* (MRtRouteImportSheet), so the two cannot drift.
* A route shared from Google Maps, read and appended to a day of the trip through
* the desktop import dialog.
*
* A link is previewed first, the stops it names in order, and only the ones that resolved
* to a place are appended, at least two of them. One request id per opening and per day
@@ -27,7 +27,11 @@ export function tripOfflineState(
* The offline state of one trip, read again each time `active` turns on (the
* menu opening), so it shows the last sync rather than the one before it.
*/
export function useTripOfflineStatus(trip: Trip | null | undefined, active: boolean): TripOfflineState | null {
export function useTripOfflineStatus(
trip: Trip | null | undefined,
active: boolean,
revision = 0
): TripOfflineState | null {
const [state, setState] = useState<TripOfflineState | null>(null);
useEffect(() => {
if (!active || !trip) return;
@@ -46,6 +50,6 @@ export function useTripOfflineStatus(trip: Trip | null | undefined, active: bool
return () => {
cancelled = true;
};
}, [trip, active]);
}, [trip, active, revision]);
return state;
}
@@ -2,11 +2,12 @@ import {
BIKE_PROFILES,
importableTourTypeSchema,
type BikeProfile,
type ImportableTourType,
type PaddleBoatType,
type PaddleWaterContext,
} from '@trek/shared';
import { Info } from 'lucide-react';
import { useId } from 'react';
import { useId, type ComponentType, type ReactNode } from 'react';
import { useTranslation } from '../../i18n';
import { LABEL, Segmented } from '../shared/dialogParts';
import { DialogSection } from '../shared/DialogShell';
@@ -22,6 +23,18 @@ const WATERS: readonly PaddleWaterContext[] = ['river', 'lake'];
/** Every type a GPX file can come in as: the planner's, and ski, which is only kept (SKI-02). */
const IMPORT_TYPES = importableTourTypeSchema.options;
export interface GpxImportTypeFieldProps {
value: ImportableTourType;
onChange: (value: ImportableTourType) => void;
labelId: string;
types: readonly ImportableTourType[];
}
export interface GpxPreviewSectionProps {
label: ReactNode;
children: ReactNode;
}
/** A paddle import's boat and water, side by side, each chosen on purpose. */
function PaddleImportFields({ choices }: { choices: GpxImportChoicesState }) {
const { t } = useTranslation();
@@ -65,14 +78,22 @@ function PaddleImportFields({ choices }: { choices: GpxImportChoicesState }) {
* discipline and technique (SKI-02), and for a ride (HOR-02) what the import
* keeps and does not work out.
*/
export function GpxImportTypeSection({ choices }: { choices: GpxImportChoicesState }) {
export function GpxImportTypeSection({
choices,
TypeField = TourTypeSelect,
Section = DialogSection,
}: {
choices: GpxImportChoicesState;
TypeField?: ComponentType<GpxImportTypeFieldProps>;
Section?: ComponentType<GpxPreviewSectionProps>;
}) {
const { t } = useTranslation();
const typeLabelId = useId();
const { chosen } = choices;
return (
<DialogSection label={<span id={typeLabelId}>{t('tours.import.previewAs')}</span>}>
<Section label={<span id={typeLabelId}>{t('tours.import.previewAs')}</span>}>
<div className="flex flex-col gap-3">
<TourTypeSelect value={chosen.type} onChange={choices.setType} labelId={typeLabelId} types={IMPORT_TYPES} />
<TypeField value={chosen.type} onChange={choices.setType} labelId={typeLabelId} types={IMPORT_TYPES} />
{chosen.type === 'bike' && (
<div data-testid="gpx-preview-bike" className="min-w-0">
<span className={LABEL}>{t('tours.bike.profile')}</span>
@@ -94,6 +115,6 @@ export function GpxImportTypeSection({ choices }: { choices: GpxImportChoicesSta
</div>
)}
</div>
</DialogSection>
</Section>
);
}
@@ -1,10 +1,11 @@
import type { TourFileLeftOut, TourGpxImportFields } from '@trek/shared';
import { AlertTriangle, Ban, Clock, FileDown, Layers, MapPin, Shapes } from 'lucide-react';
import { useId, useMemo, useState } from 'react';
import { useId, useMemo, useState, type ComponentType, type ReactNode } from 'react';
import { OFM_POSITRON } from '../../constants/mapDefaults';
import { useTileUrl } from '../../hooks/useTileUrl';
import { useTranslation } from '../../i18n';
import { useSettingsStore } from '../../store/settingsStore';
import { computeMapViewport, TILE_SIZE_GL } from '../../utils/mapViewport';
import { formatDistance, formatElevation } from '../../utils/units';
import { MapViewAuto } from '../Map/MapViewAuto';
import { SoftPill } from '../Planner/planParts';
@@ -22,13 +23,31 @@ import {
} from '../shared/DialogShell';
import { recordedDay, recordedMinutes } from './activity/tourActivityModel';
import { importFields, importMissing, useGpxImportChoices } from './gpxImportChoices';
import { GpxImportTypeSection } from './GpxImportTypeSection';
import {
GpxImportTypeSection,
type GpxImportTypeFieldProps,
type GpxPreviewSectionProps,
} from './GpxImportTypeSection';
import { InfoDot, TourNotice } from './tourParts';
import { formatPlannedTourDuration } from './tourPresentation';
import type { GpxPreviewFile, TourGpxImport } from './useTourGpxImport';
export interface GpxPreviewFrameProps {
fileNames: readonly string[];
busy: boolean;
canImport: boolean;
confirmLabel: string;
onCancel: () => void;
onImport: () => void;
map: ReactNode;
tracks: ReactNode;
options: ReactNode;
}
const BADGE =
'inline-flex flex-none items-center rounded-full bg-surface-secondary px-2 font-geist tabular-nums leading-[20px] text-content-secondary';
// Clear the map tools along the top of the compact card.
const COMPACT_MAP_PADDING = { top: 64, right: 24, bottom: 16, left: 24 }; // rtl-lint-disable: physical map viewport
/** ACT-01: when a track was recorded and how long it took, where every point carried a time. */
function RecordedBadge({ track }: { track: GpxPreviewFile['tracks'][number] }) {
@@ -191,14 +210,30 @@ export default function TourGpxPreviewDialog({
gpxImport,
initial,
offerPoints = false,
frame,
typeField,
section,
}: {
gpxImport: TourGpxImport;
initial?: TourGpxImportFields;
offerPoints?: boolean;
frame?: ComponentType<GpxPreviewFrameProps>;
typeField?: ComponentType<GpxImportTypeFieldProps>;
section?: ComponentType<GpxPreviewSectionProps>;
}) {
const { preview } = gpxImport;
if (!preview) return null;
return <PreviewDialog gpxImport={gpxImport} files={preview} initial={initial ?? HIKE} offerPoints={offerPoints} />;
return (
<PreviewDialog
gpxImport={gpxImport}
files={preview}
initial={initial ?? HIKE}
offerPoints={offerPoints}
frame={frame}
typeField={typeField}
section={section}
/>
);
}
const HIKE: TourGpxImportFields = { tour_type: 'hike' };
@@ -235,11 +270,17 @@ function PreviewDialog({
files,
initial,
offerPoints,
frame: Frame,
typeField,
section: Section = DialogSection,
}: {
gpxImport: TourGpxImport;
files: GpxPreviewFile[];
initial: TourGpxImportFields;
offerPoints: boolean;
frame?: ComponentType<GpxPreviewFrameProps>;
typeField?: ComponentType<GpxImportTypeFieldProps>;
section?: ComponentType<GpxPreviewSectionProps>;
}) {
const { t } = useTranslation();
const labelId = useId();
@@ -260,11 +301,85 @@ function PreviewDialog({
[files]
);
const focusPoints = useMemo(() => lines.flat(), [lines]);
// The GL map can spend its first paint waiting for its style. Give the
// compact preview an opening camera as well as a fit for the live map.
const openingCamera = useMemo(() => {
if (!Frame) return null;
return computeMapViewport(
focusPoints.map(([lat, lng]) => ({ lat, lng })),
{
tileSize: TILE_SIZE_GL,
width: 280,
height: 160,
padding: COMPACT_MAP_PADDING,
}
);
}, [Frame, focusPoints]);
const canImport = canConfirm(fresh, addsPoints, importMissing(choices.chosen) === null) && !gpxImport.importing;
const confirmLabel = fresh > 0 ? t('tours.import.previewConfirm', { count: fresh }) : t('tours.import.pointsConfirm');
const fields = importFields(choices.chosen);
const title = files.length === 1 ? files[0].file.name : t('tours.import.previewFiles', { count: files.length });
const onImport = () => {
void gpxImport.confirm(fields, { points: addsPoints });
};
const map = (
<div
data-testid="gpx-preview-map"
className={`relative flex-none overflow-hidden rounded-[14px] border border-edge-faint ${Frame ? 'h-40' : 'h-[280px]'}`}
>
<MapViewAuto
places={[]}
route={lines}
tileUrl={tileUrl}
focusPoints={focusPoints}
focusKey={files.map(({ file }) => file.name).join('|')}
fitPadding={Frame ? COMPACT_MAP_PADDING : undefined}
center={openingCamera?.center}
zoom={openingCamera?.zoom}
followSelection={false}
/>
</div>
);
const trackList = (
<Section label={t('tours.import.previewTracks', { count: tracks.length })}>
<ul className="m-0 flex list-none flex-col gap-1.5 p-0">
{tracks.map(({ file, track }, index) => (
<PreviewTrackRow key={`${file.name}-${index}`} name={file.name} number={index + 1} track={track} />
))}
</ul>
<PreviewExtras
leftOut={leftOut}
offerPoints={offerPoints}
withPoints={withPoints}
onTogglePoints={() => setWithPoints((on) => !on)}
/>
{fresh === 0 && !addsPoints && (
<div className="mt-2">
<TourNotice tone="warning" icon={<AlertTriangle size={13} strokeWidth={2} />}>
{t('tours.import.previewAllDuplicates')}
</TourNotice>
</div>
)}
</Section>
);
const options = <GpxImportTypeSection choices={choices} TypeField={typeField} Section={Section} />;
if (Frame) {
return (
<Frame
fileNames={files.map(({ file }) => file.name)}
busy={gpxImport.importing}
canImport={canImport}
confirmLabel={confirmLabel}
onImport={onImport}
onCancel={gpxImport.cancel}
map={map}
tracks={trackList}
options={options}
/>
);
}
return (
<DialogShell
onClose={gpxImport.cancel}
@@ -298,49 +413,16 @@ function PreviewDialog({
data-testid="gpx-preview-import"
icon={<FileDown size={14} strokeWidth={2} />}
disabled={!canImport}
onClick={() => void gpxImport.confirm(fields, { points: addsPoints })}
onClick={onImport}
>
{confirmLabel}
</DialogButton>
</DialogFooter>
}
>
<div
data-testid="gpx-preview-map"
className="relative h-[280px] flex-none overflow-hidden rounded-[14px] border border-edge-faint"
>
<MapViewAuto
places={[]}
route={lines}
tileUrl={tileUrl}
focusPoints={focusPoints}
focusKey={files.map(({ file }) => file.name).join('|')}
followSelection={false}
/>
</div>
<DialogSection label={t('tours.import.previewTracks', { count: tracks.length })}>
<ul className="m-0 flex list-none flex-col gap-1.5 p-0">
{tracks.map(({ file, track }, index) => (
<PreviewTrackRow key={`${file.name}-${index}`} name={file.name} number={index + 1} track={track} />
))}
</ul>
<PreviewExtras
leftOut={leftOut}
offerPoints={offerPoints}
withPoints={withPoints}
onTogglePoints={() => setWithPoints((on) => !on)}
/>
{fresh === 0 && !addsPoints && (
<div className="mt-2">
<TourNotice tone="warning" icon={<AlertTriangle size={13} strokeWidth={2} />}>
{t('tours.import.previewAllDuplicates')}
</TourNotice>
</div>
)}
</DialogSection>
<GpxImportTypeSection choices={choices} />
{map}
{trackList}
{options}
</DialogShell>
);
}
@@ -1,6 +1,7 @@
import type { TourFileLeftOut, TourGpxImportFields, TourGpxPreviewTrack, TourListItem } from '@trek/shared';
import { useCallback, useState } from 'react';
import { useTranslation } from '../../i18n';
import { documentPickerAccept } from '../../native/platform';
import { tourRepo } from '../../repo/tourRepo';
import { useTripStore } from '../../store/tripStore';
import { getApiErrorCode, getApiErrorMessage } from '../../utils/apiError';
@@ -238,7 +239,7 @@ export function useTourGpxImport({ tripId, canEdit, onToursChanged, onImported,
if (!canEdit || importing || preview) return;
const input = document.createElement('input');
input.type = 'file';
input.accept = TOUR_FILE_EXTENSIONS.join(',');
input.accept = documentPickerAccept(TOUR_FILE_EXTENSIONS.join(','));
input.multiple = true;
input.addEventListener('change', () => void importFiles(Array.from(input.files ?? [])), { once: true });
input.click();
@@ -128,6 +128,21 @@ describe('TripJournalLinkSection', () => {
expect(await screen.findByText('Link a journal')).toBeInTheDocument();
});
it('lets the mobile settings confirm unlinking before sending the request', async () => {
const user = userEvent.setup();
const requestUnlink = vi.fn<(confirm: () => void) => void>();
answer = LINKED;
render(<TripJournalLinkSection tripId={TRIP} requestUnlink={requestUnlink} />);
await user.click(await screen.findByRole('button', { name: 'Unlink' }));
expect(requestUnlink).toHaveBeenCalledOnce();
expect(deletes).toBe(0);
expect(screen.queryByText('Unlink this journal?')).not.toBeInTheDocument();
requestUnlink.mock.calls[0][0]();
await waitFor(() => expect(deletes).toBe(1));
});
it('FE-TJL-SECTION-006: editing access lists the trip with each one as the link holds them', async () => {
const user = userEvent.setup();
answer = { ...LINKED, link: LINKED.link && { ...LINKED.link, members: [] } };
@@ -13,9 +13,8 @@ import { useTripJournalLink, type JournalMemberChoice } from './useTripJournalLi
const ROWS = 'flex flex-col gap-0.5 rounded-[14px] border border-edge-faint bg-surface-secondary p-1.5';
const ROW = 'flex min-h-[48px] items-center gap-3 rounded-[10px] px-2.5 py-1.5';
const SEGMENT = 'rounded-full px-2.5 py-1 font-semibold';
/** The phone sheet's buttons, the round 38px ones its other areas use. */
const SHEET_BUTTON =
'flex h-[38px] min-w-0 items-center justify-center gap-1.5 whitespace-nowrap rounded-full px-3 [&>svg]:flex-none text-[length:calc(12px*var(--fs-scale-body,1))] font-semibold disabled:opacity-40';
'flex min-h-11 min-w-0 items-center justify-center gap-1.5 rounded-full px-3 py-2 text-control font-semibold [&>svg]:flex-none disabled:opacity-40';
const ROLES: { value: TripJournalLinkRole | null; labelKey: string }[] = [
{ value: null, labelKey: 'trip.journal.roleNone' },
@@ -29,7 +28,15 @@ const ROLES: { value: TripJournalLinkRole | null; labelKey: string }[] = [
* Hidden with the Journey addon off, and for someone who can neither link one
* nor see one that is linked.
*/
export function TripJournalLinkSection({ tripId, framed = true }: { tripId: number; framed?: boolean }) {
export function TripJournalLinkSection({
tripId,
framed = true,
requestUnlink,
}: {
tripId: number;
framed?: boolean;
requestUnlink?: (confirm: () => void) => void;
}) {
const { t } = useTranslation();
const j = useTripJournalLink(tripId);
const [askUnlink, setAskUnlink] = useState(false);
@@ -37,34 +44,57 @@ export function TripJournalLinkSection({ tripId, framed = true }: { tripId: numb
// The desktop dialog names the area above it already; the phone sheet gets the card with its own title.
const Frame = framed ? JournalCard : Bare;
const unlink = () => {
void j.unlink();
};
const askToUnlink = () => {
if (requestUnlink) requestUnlink(unlink);
else setAskUnlink(true);
};
const saveLabel = j.mode === 'pick' ? t('trip.journal.linkSubmit') : t('common.save');
return (
<>
<Frame>
{j.mode === 'view' && <JournalView j={j} framed={framed} onUnlink={() => setAskUnlink(true)} />}
{j.mode === 'pick' && <JournalPicker j={j} />}
{(j.mode === 'members' || (j.mode === 'pick' && j.pickedId != null)) && <MemberChooser j={j} />}
{j.mode !== 'view' && (
<div className="flex justify-end gap-2">
<DialogButton onClick={j.cancel} disabled={j.busy}>
{t('common.cancel')}
</DialogButton>
<DialogButton
variant="primary"
onClick={() => void j.save()}
disabled={!j.canSave}
icon={<Link2 size={14} strokeWidth={2.2} />}
>
{j.mode === 'pick' ? t('trip.journal.linkSubmit') : t('common.save')}
</DialogButton>
</div>
)}
{j.mode === 'view' && <JournalView j={j} framed={framed} onUnlink={askToUnlink} />}
{j.mode === 'pick' && <JournalPicker j={j} mobile={framed} />}
{(j.mode === 'members' || (j.mode === 'pick' && j.pickedId != null)) && <MemberChooser j={j} mobile={framed} />}
{j.mode !== 'view' &&
(framed ? (
<div className="flex flex-wrap justify-end gap-2">
<button type="button" className={`${SHEET_BUTTON} bg-m-sheetop`} onClick={j.cancel} disabled={j.busy}>
{t('common.cancel')}
</button>
<button
type="button"
className={`${SHEET_BUTTON} bg-m-act text-m-actfg`}
onClick={() => void j.save()}
disabled={!j.canSave}
>
{saveLabel}
</button>
</div>
) : (
<div className="flex justify-end gap-2">
<DialogButton onClick={j.cancel} disabled={j.busy}>
{t('common.cancel')}
</DialogButton>
<DialogButton
variant="primary"
onClick={() => void j.save()}
disabled={!j.canSave}
icon={<Link2 size={14} strokeWidth={2.2} />}
>
{saveLabel}
</DialogButton>
</div>
))}
</Frame>
<ConfirmDialog
isOpen={askUnlink}
onClose={() => setAskUnlink(false)}
onConfirm={() => {
setAskUnlink(false);
void j.unlink();
unlink();
}}
title={t('trip.journal.unlinkTitle')}
message={t('trip.journal.unlinkMessage')}
@@ -80,7 +110,17 @@ export function TripJournalLinkSection({ tripId, framed = true }: { tripId: numb
*/
function JournalView({ j, framed, onUnlink }: { j: JournalLink; framed: boolean; onUnlink: () => void }) {
const { t } = useTranslation();
if (!j.link) return j.canLink ? <AddRowButton onClick={j.startPick}>{t('trip.journal.link')}</AddRowButton> : null;
if (!j.link) {
if (!j.canLink) return null;
return framed ? (
<button type="button" className={`${SHEET_BUTTON} w-full bg-m-act text-m-actfg`} onClick={j.startPick}>
<Link2 size={16} aria-hidden />
{t('trip.journal.link')}
</button>
) : (
<AddRowButton onClick={j.startPick}>{t('trip.journal.link')}</AddRowButton>
);
}
if (!framed) return <LinkedJournalCards j={j} onUnlink={onUnlink} />;
return (
<>
@@ -104,11 +144,7 @@ function SheetActions({ j, onUnlink }: { j: JournalLink; onUnlink: () => void })
{(j.canLink || j.canUnlink) && (
<div className="flex gap-2">
{j.canLink && (
<button
type="button"
onClick={j.startPick}
className={`${SHEET_BUTTON} flex-1 bg-[color:var(--m-ic)] text-m-ink`}
>
<button type="button" onClick={j.startPick} className={`${SHEET_BUTTON} flex-1 bg-m-sheetop text-m-ink`}>
<BookOpen size={14} strokeWidth={2.2} />
{t('trip.journal.change')}
</button>
@@ -118,7 +154,7 @@ function SheetActions({ j, onUnlink }: { j: JournalLink; onUnlink: () => void })
type="button"
onClick={onUnlink}
disabled={j.busy}
className={`${SHEET_BUTTON} flex-1 bg-[color:var(--m-ic)] text-[color:var(--m-st-danger)]`}
className={`${SHEET_BUTTON} flex-1 bg-m-sheetop text-[color:var(--m-st-danger)]`}
>
<Unlink size={14} strokeWidth={2.2} />
{t('trip.journal.unlink')}
@@ -134,8 +170,8 @@ function SheetActions({ j, onUnlink }: { j: JournalLink; onUnlink: () => void })
function JournalCard({ children }: { children: ReactNode }) {
const { t } = useTranslation();
return (
<section className="flex flex-col gap-3 rounded-[18px] border border-[color:var(--m-inbr)] bg-[color:var(--m-inner)] p-3">
<p className="m-0 font-geist text-caption leading-snug text-m-muted">{t('trip.journal.hint')}</p>
<section className="flex flex-col gap-3 rounded-[14px] bg-m-ic p-3">
<p className="m-0 text-caption leading-snug text-m-muted">{t('trip.journal.hint')}</p>
{children}
</section>
);
@@ -253,8 +289,8 @@ function LinkedJournal({ j }: { j: JournalLink }) {
const members = link.members ?? [];
return (
<div className="flex flex-col gap-2">
<div className="flex items-center gap-3 rounded-[14px] bg-[color:var(--m-ic)] p-2">
<span className="grid h-11 w-11 flex-none place-items-center overflow-hidden rounded-[11px] bg-m-card text-m-muted">
<div className="flex items-center gap-3 rounded-xl bg-m-sheetop p-2">
<span className="grid h-11 w-11 flex-none place-items-center overflow-hidden rounded-lg bg-m-ic text-m-muted">
{link.cover_image ? (
<img src={`/uploads/${link.cover_image}`} alt="" className="h-full w-full object-cover" />
) : (
@@ -275,7 +311,7 @@ function LinkedJournal({ j }: { j: JournalLink }) {
</span>
</div>
{members.length > 0 ? (
<div className="flex flex-col">
<div className="divide-y divide-m-rowbr rounded-xl bg-m-sheetop px-2.5">
{members.map((m) => (
<div key={m.user_id} className="flex items-center gap-2.5 py-1.5">
<TripMemberAvatar username={m.username} avatarUrl={m.avatar_url} size={30} />
@@ -294,7 +330,7 @@ function LinkedJournal({ j }: { j: JournalLink }) {
}
/** The journals of one's own to choose from; one only contributed to is not one's to give away. */
function JournalPicker({ j }: { j: JournalLink }) {
function JournalPicker({ j, mobile }: { j: JournalLink; mobile: boolean }) {
const { t } = useTranslation();
if (j.journals == null) return <div className="h-10 animate-pulse rounded-[10px] bg-surface-tertiary" />;
if (j.journals.length === 0)
@@ -313,7 +349,7 @@ function JournalPicker({ j }: { j: JournalLink }) {
...j.journals.map((journal) => ({ value: String(journal.id), label: journal.title })),
]}
searchable
size="sm"
size={mobile ? 'md' : 'sm'}
/>
);
}
@@ -323,7 +359,7 @@ function JournalPicker({ j }: { j: JournalLink }) {
* people the link would let in for the first time are named: from then on they
* see the journal in their own Journey list as well.
*/
function MemberChooser({ j }: { j: JournalLink }) {
function MemberChooser({ j, mobile }: { j: JournalLink; mobile: boolean }) {
const { t } = useTranslation();
if (j.candidates == null) return <div className="h-24 animate-pulse rounded-[14px] bg-surface-tertiary" />;
if (j.candidates.length === 0)
@@ -334,35 +370,47 @@ function MemberChooser({ j }: { j: JournalLink }) {
);
return (
<div className="flex flex-col gap-2.5">
<div className="flex items-center justify-between gap-2">
<span className="font-semibold text-content-secondary" style={fs(12, 'body')}>
<div className={mobile ? 'space-y-2' : 'flex items-center justify-between gap-2'}>
<span
className={mobile ? 'text-control font-semibold' : 'font-semibold text-content-secondary'}
style={mobile ? undefined : fs(12, 'body')}
>
{t('trip.journal.members')}
</span>
<div className="flex gap-1.5">
<div className={mobile ? 'flex flex-wrap gap-2' : 'flex gap-1.5'}>
<button
type="button"
onClick={() => j.setAll('viewer')}
className="text-content-muted hover:text-content"
style={fs(11.5)}
className={mobile ? `${SHEET_BUTTON} bg-m-sheetop` : 'text-content-muted hover:text-content'}
style={mobile ? undefined : fs(11.5)}
>
{t('trip.journal.allRead')}
</button>
<span className="text-content-faint" aria-hidden>
/
</span>
{!mobile && (
<span className="text-content-faint" aria-hidden>
/
</span>
)}
<button
type="button"
onClick={() => j.setAll(null)}
className="text-content-muted hover:text-content"
style={fs(11.5)}
className={mobile ? `${SHEET_BUTTON} bg-m-sheetop` : 'text-content-muted hover:text-content'}
style={mobile ? undefined : fs(11.5)}
>
{t('trip.journal.allNone')}
</button>
</div>
</div>
<div className={ROWS}>
<div className={mobile ? 'divide-y divide-m-rowbr rounded-xl bg-m-sheetop px-2.5' : ROWS}>
{j.candidates.map((c) => (
<MemberRow key={c.user_id} c={c} choice={j.choice} onRole={j.setRole} showAccess={j.mode === 'pick'} />
<MemberRow
key={c.user_id}
c={c}
choice={j.choice}
onRole={j.setRole}
showAccess={j.mode === 'pick'}
mobile={mobile}
/>
))}
</div>
{j.newlyGranted.length > 0 && (
@@ -385,16 +433,18 @@ function MemberRow({
choice,
onRole,
showAccess,
mobile,
}: {
c: TripJournalCandidate;
choice: JournalMemberChoice;
onRole: (userId: number, role: TripJournalLinkRole | null) => void;
showAccess: boolean;
mobile: boolean;
}) {
const { t } = useTranslation();
const current = choice[c.user_id] ?? null;
return (
<div className={ROW}>
<div className={mobile ? 'flex min-h-12 flex-wrap items-center gap-2 py-2' : ROW}>
<TripMemberAvatar username={c.username} avatarUrl={c.avatar_url} />
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">
<span className="truncate font-semibold text-content" style={fs(13, 'body')}>
@@ -417,7 +467,11 @@ function MemberRow({
<div
role="radiogroup"
aria-label={c.username}
className="flex flex-none gap-0.5 rounded-full bg-surface-card p-0.5 ring-1 ring-edge-faint"
className={
mobile
? 'flex w-full gap-0.5 rounded-full bg-m-ic p-1'
: 'flex flex-none gap-0.5 rounded-full bg-surface-card p-0.5 ring-1 ring-edge-faint'
}
>
{ROLES.map((r) => (
<button
@@ -426,8 +480,12 @@ function MemberRow({
role="radio"
aria-checked={current === r.value}
onClick={() => onRole(c.user_id, r.value)}
className={`${SEGMENT} ${current === r.value ? 'bg-accent text-accent-text' : 'text-content-muted hover:text-content'}`}
style={fs(11, 'body')}
className={
mobile
? `min-h-9 min-w-0 flex-1 rounded-full px-1.5 py-1 text-caption font-medium ${current === r.value ? 'bg-m-act text-m-actfg' : 'text-m-ink'}`
: `${SEGMENT} ${current === r.value ? 'bg-accent text-accent-text' : 'text-content-muted hover:text-content'}`
}
style={mobile ? undefined : fs(11, 'body')}
>
{t(r.labelKey)}
</button>
@@ -9,6 +9,7 @@ import { type DateField, dateFieldOrder, dateLayout, formatDisplayDate } from '.
import { useDateFormat } from '../../hooks/useDateFormat';
import { useRemeasureSignal } from '../../hooks/useAnchoredPosition';
import { useWeekStartDay } from '../../hooks/useWeekStartDay';
import { useOverlay } from '../../hooks/overlayStack';
import { leadingBlanks, weekdayLabels } from '../../utils/calendarWeek';
import { selectionHaptic } from '../../native/haptics';
@@ -33,6 +34,7 @@ interface CustomDatePickerProps {
max?: string;
/** What the field is, for a picker without a visible label around it; the trigger reads it with its date. */
ariaLabel?: string;
clearLabel?: string;
}
export function CustomDatePicker({
@@ -46,6 +48,7 @@ export function CustomDatePicker({
min,
max,
ariaLabel,
clearLabel,
}: CustomDatePickerProps) {
const { locale, t } = useTranslation();
const weekStart = useWeekStartDay();
@@ -203,6 +206,7 @@ export function CustomDatePicker({
const [textInput, setTextInput] = useState('');
const [isTyping, setIsTyping] = useState(false);
useOverlay(open || isTyping, () => { setOpen(false); setIsTyping(false); }, true);
const handleTextSubmit = () => {
setIsTyping(false);
@@ -677,7 +681,7 @@ export function CustomDatePicker({
onChange('');
setOpen(false);
}}
aria-label={t('common.datepicker.clearDate')}
aria-label={clearLabel ?? t('common.datepicker.clearDate')}
style={{
background: 'none',
border: 'none',
+17 -12
View File
@@ -2,6 +2,7 @@ import React, { useState, useRef, useEffect, useId } from 'react'
import { createPortal } from 'react-dom'
import { ChevronDown, Check } from 'lucide-react'
import { scrollAnchorIntoView } from '../../hooks/useAnchoredPosition'
import { useOverlay } from '../../hooks/overlayStack'
import { useTranslation } from '../../i18n'
import { selectionHaptic } from '../../native/haptics'
import { useAnchoredPopover } from './useAnchoredPopover'
@@ -99,6 +100,9 @@ export default function CustomSelect({
// resizes the viewport, instead of freezing at the rect measured on open (#1999).
const { open, bounded, box: anchored, setOpen } = useAnchoredPopover(ref, { disabled })
const menuOpen = open && (!bounded || !!anchored)
const formRect = menuOpen && !bounded ? ref.current?.closest('.m-form-sheet .m-fs-body')?.getBoundingClientRect() : undefined
const expandedWidth = formRect && anchored ? Math.min(MENU_MAX_WIDTH, formRect.width - 36) : 0
const expandMenu = Boolean(formRect && anchored && expandedWidth > anchored.width + 12)
useEffect(() => {
if (!menuOpen || !searchable || !searchRef.current) return
@@ -161,14 +165,11 @@ export default function CustomSelect({
setSearch('')
triggerRef.current?.focus()
}
useOverlay(open, closeMenu, true)
const handleKeyDown = (event: React.KeyboardEvent) => {
if (disabled) return
if (event.key === 'Escape' && open) {
event.preventDefault()
event.stopPropagation()
closeMenu()
} else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault()
const backwards = event.key === 'ArrowUp'
if (!open) {
@@ -191,6 +192,7 @@ export default function CustomSelect({
ref={triggerRef}
id={id}
data-field-trigger=""
data-select-has-badge={selected?.badge && !selected.icon ? '' : undefined}
type="button"
aria-label={ariaLabel}
aria-expanded={open}
@@ -212,11 +214,11 @@ export default function CustomSelect({
onMouseLeave={e => { if (!open) e.currentTarget.style.borderColor = 'var(--border-primary)' }}
>
{selected?.icon && <span style={{ display: 'flex', flexShrink: 0 }}>{selected.icon}</span>}
<span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: selected ? 'var(--text-primary)' : 'var(--text-faint)' }}>
<span data-select-label="" style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: selected ? 'var(--text-primary)' : 'var(--text-faint)' }}>
{selected ? selected.label : placeholder}
</span>
{selected?.badge && (
<span style={{
<span data-select-badge="" style={{
flexShrink: 0, fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-muted)',
background: 'var(--bg-tertiary)', padding: '2px 7px', borderRadius: 999,
letterSpacing: '0.01em',
@@ -227,16 +229,17 @@ export default function CustomSelect({
{/* Dropdown */}
{menuOpen && createPortal(
<div ref={dropRef} id={menuId} role="group" aria-label={ariaLabel || selected?.label || placeholder || undefined} onKeyDown={handleKeyDown} style={{
<div ref={dropRef} id={menuId} role="group" aria-label={ariaLabel || selected?.label || placeholder || undefined}
className={formRect ? 'm-root m-form-select-menu' : undefined} onKeyDown={handleKeyDown} style={{
position: 'fixed',
...(anchored
? {
...(anchored.flipped ? { bottom: anchored.bottom } : { top: anchored.top }),
left: anchored.left,
left: expandMenu && formRect ? Math.max(8, formRect.left + 18) : anchored.left,
// Never narrower than the trigger, and never past the right-hand edge of
// the window. The cap is read at render time rather than measured, and
// that is enough: every reason the anchor moved already re-renders this.
...(!bounded && menuFit === 'content'
...(expandMenu ? { width: expandedWidth } : !bounded && menuFit === 'content'
? {
minWidth: anchored.width,
width: 'max-content',
@@ -310,6 +313,8 @@ export default function CustomSelect({
<button
key={option.value}
type="button"
data-select-option=""
aria-pressed={isSelected}
onClick={() => { if (!isSelected) selectionHaptic(); onChange(option.value); closeMenu() }}
style={{
width: '100%', display: 'flex', alignItems: 'center', gap: 8,
@@ -322,9 +327,9 @@ export default function CustomSelect({
onMouseLeave={e => e.currentTarget.style.background = isSelected ? 'var(--bg-hover)' : 'transparent'}
>
{option.icon && <span style={{ display: 'flex', flexShrink: 0 }}>{option.icon}</span>}
<span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{option.label}</span>
<span data-select-label="" style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{option.label}</span>
{option.badge && (
<span style={{
<span data-select-badge="" style={{
flexShrink: 0, fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-muted)',
background: 'var(--bg-tertiary)', padding: '2px 7px', borderRadius: 999,
letterSpacing: '0.01em',
@@ -550,6 +550,12 @@ describe('CustomTimePicker honours the configured time format', () => {
expect(screen.getByRole('textbox')).toHaveProperty('value', '14:30');
});
it('keeps an explicitly empty placeholder in 12h mode', () => {
use('12h');
render(<CustomTimePicker value="" placeholder="" onChange={onChange} />);
expect(screen.getByRole('textbox')).toHaveProperty('placeholder', '');
});
// Display alone is not enough: a value stored as "3:00 PM" stays that way in the
// database until someone edits the field. The picker hands the parsed HH:MM back to
// the form instead, so the next save writes a clean value.
@@ -4,6 +4,7 @@ import { Clock } from 'lucide-react'
import { useSettingsStore } from '../../store/settingsStore'
import { formatClockTime, parseMeridiemTime } from '../../utils/formatters'
import { useAnchoredPosition } from '../../hooks/useAnchoredPosition'
import { useOverlay } from '../../hooks/overlayStack'
import { TimeSpinnerColumn } from './TimeSpinnerColumn'
import { spinnerButtonStyle } from './timeSpinnerStyle'
@@ -26,6 +27,7 @@ interface CustomTimePickerProps {
export default function CustomTimePicker({ value, onChange, placeholder = '00:00', style = {}, disabled = false, ...aria }: CustomTimePickerProps) {
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
const [open, setOpen] = useState(false)
useOverlay(open, () => setOpen(false), true)
const [inputFocused, setInputFocused] = useState(false)
const ref = useRef<HTMLDivElement>(null)
const dropRef = useRef<HTMLDivElement>(null)
@@ -142,7 +144,7 @@ export default function CustomTimePicker({ value, onChange, placeholder = '00:00
onChange={handleInput}
onFocus={() => setInputFocused(true)}
onBlur={() => { setInputFocused(false); handleBlur() }}
placeholder={is12h ? '2:30 PM' : placeholder}
placeholder={is12h && placeholder ? '2:30 PM' : placeholder}
disabled={disabled}
style={{
flex: 1, border: 'none', outline: 'none', background: 'transparent',
+3 -2
View File
@@ -82,6 +82,7 @@ interface PlaceRatingProps {
size?: number
/** Hide the voter avatar strip (compact mobile rows). */
compact?: boolean
hideEmptyLabel?: boolean
}
/**
@@ -90,7 +91,7 @@ interface PlaceRatingProps {
* voter avatars. Hovering reveals a custom tooltip listing every voter with
* their stars.
*/
export default function PlaceRating({ ratings, ratingAvg, onRate, size = 16, compact = false }: PlaceRatingProps) {
export default function PlaceRating({ ratings, ratingAvg, onRate, size = 16, compact = false, hideEmptyLabel = false }: PlaceRatingProps) {
const { t } = useTranslation()
const currentUserId = useAuthStore(s => s.user?.id)
const [tip, setTip] = useState<{ top: number; left: number } | null>(null)
@@ -114,7 +115,7 @@ export default function PlaceRating({ ratings, ratingAvg, onRate, size = 16, com
<span style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-secondary)', fontVariantNumeric: 'tabular-nums' }}>
{(Math.round(avg * 10) / 10).toLocaleString()} <span style={{ fontWeight: 400, color: 'var(--text-faint)' }}>({ratings.length})</span>
</span>
) : (
) : !hideEmptyLabel && (
<span style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)' }}>{t('places.notRated')}</span>
)}