fix(ci): repair trip assistant checks

Fix the mobile dashboard import and align the assistant UI with client layer and lint rules. Document the OpenRouter setting, share the reservation status schema, and update coverage for external POI identifiers and the empty costs view.
This commit is contained in:
Maurice
2026-12-02 22:56:54 +01:00
parent 62a3e63f3f
commit 86e98fde65
18 changed files with 635 additions and 514 deletions
-1
View File
@@ -1425,7 +1425,6 @@
"src/mobile/screens/vacay/MVacayShareSheet.tsx",
"src/mobile/screens/vacay/useMVacay.ts",
"src/mobile/screens/vacay/vacayDayModel.ts",
"src/mobile/useIsPhone.ts",
"src/pages/AdminPage.test.tsx",
"src/pages/AdminPage.tsx",
"src/pages/AtlasPage.tsx",
@@ -11,7 +11,7 @@ import type { Place } from '../../types';
import { formatTime } from '../../utils/formatters';
import { TimePill } from '../Planner/planParts';
import { getCategoryIcon } from '../shared/categoryIcons';
import { isDayNoteProposal, isVisitProposal, planField, proposalNote } from './AssistantPlanFields';
import { isDayNoteProposal, isVisitProposal, planField, proposalNote } from './assistantPlanFieldsModel';
/** What a waiting change does to one day, as a row of the preview. */
interface PreviewRow {
@@ -54,28 +54,57 @@ function rowOf(
detail: proposalNote(preview, edits) ?? undefined,
};
}
const kind = visitKind(preview, dayId);
if (!kind) return null;
const place = places.find((p) => p.id === effect?.placeId);
const row = {
toolCallId,
name: edits?.place?.name ?? effect?.place?.name ?? place?.name ?? subject,
categoryId:
edits?.categoryId === undefined ? (effect?.place?.categoryId ?? place?.category_id ?? null) : edits.categoryId,
categoryName: edits?.categoryId === undefined ? planField(preview, 'category') : undefined,
start: edits?.startTime === undefined ? planField(preview, 'time') : (edits.startTime ?? undefined),
end: edits?.endTime === undefined ? planField(preview, 'endTime') : (edits.endTime ?? undefined),
return { toolCallId, kind, ...visitSubject(preview, place, edits), ...visitDetails(preview, place, edits) };
}
function visitSubject(
preview: AssistantChangePreview,
place: Place | undefined,
edits: AssistantPlanEdits | undefined
) {
const proposed = preview.effect?.place;
const categoryId = edits?.categoryId;
return {
name: edits?.place?.name ?? proposed?.name ?? place?.name ?? preview.subject,
categoryId: categoryId === undefined ? (proposed?.categoryId ?? place?.category_id ?? null) : categoryId,
categoryName: categoryId === undefined ? planField(preview, 'category') : undefined,
};
}
function editedText(value: string | null | undefined, original: string | undefined): string | undefined {
return value === undefined ? original : (value ?? undefined);
}
function visitDetails(
preview: AssistantChangePreview,
place: Place | undefined,
edits: AssistantPlanEdits | undefined
) {
return {
start: editedText(edits?.startTime, planField(preview, 'time')),
end: editedText(edits?.endTime, planField(preview, 'endTime')),
detail:
(edits?.notes === undefined ? planField(preview, 'notes') : edits.notes) ||
(edits?.place?.description === undefined ? planField(preview, 'description') : edits.place.description) ||
editedText(edits?.notes, planField(preview, 'notes')) ||
editedText(edits?.place?.description, planField(preview, 'description')) ||
place?.description ||
(edits?.place?.address === undefined ? planField(preview, 'address') : edits.place.address) ||
editedText(edits?.place?.address, planField(preview, 'address')) ||
place?.address ||
undefined,
};
if (!effect) return preview.dayId === dayId && isVisitProposal(preview) ? { ...row, kind: 'add' } : null;
if (effect.dayId === dayId)
return { ...row, kind: effect.kind === 'remove' ? 'remove' : effect.kind === 'move' ? 'in' : 'add' };
if (effect.kind === 'move' && effect.fromDayId === dayId) return { ...row, kind: 'out' };
return null;
}
function visitKind(preview: AssistantChangePreview, dayId: number): PreviewRow['kind'] | null {
const { effect } = preview;
if (!effect) return preview.dayId === dayId && isVisitProposal(preview) ? 'add' : null;
if (effect.dayId === dayId) {
if (effect.kind === 'remove') return 'remove';
if (effect.kind === 'move') return 'in';
return 'add';
}
return effect.kind === 'move' && effect.fromDayId === dayId ? 'out' : null;
}
const LOOK: Record<PreviewRow['kind'], { icon: LucideIcon; row: string; name: string; badgeKey: string }> = {
@@ -3,12 +3,12 @@ import { assistantPlanEditsSchema, parsePlaceHours, placeOpeningHoursSchema } fr
import { useCallback, useEffect, useState } from 'react';
import { useTranslation } from '../../i18n';
import { useIsPhone } from '../../mobile/useIsPhone';
import { useIsPhone } from '../../hooks/useIsPhone';
import { useAssistantStore } from '../../store/assistantStore';
import { useTripStore } from '../../store/tripStore';
import PlaceFormModal from '../Planner/PlaceFormModal';
import { DEFAULT_FORM, formPin, type PlaceFormData } from '../Planner/PlaceFormModal.helpers';
import { planField } from './AssistantPlanFields';
import { planField } from './assistantPlanFieldsModel';
import { useAssistantView } from './assistantViewContext';
type PlacePatch = NonNullable<AssistantPlanEdits['place']>;
@@ -17,14 +17,16 @@ function originalForm(preview: AssistantChangePreview, rawArgs: unknown, categor
const args = rawArgs && typeof rawArgs === 'object' ? (rawArgs as Record<string, unknown>) : {};
const value = (key: string) => (typeof args[key] === 'string' ? args[key] : '');
const point = preview.effect?.place;
const coordinate = (key: 'lat' | 'lng') => String(typeof args[key] === 'number' ? args[key] : (point?.[key] ?? ''));
const text = (key: 'address' | 'description') => value(key) || planField(preview, key) || '';
const hours = placeOpeningHoursSchema.safeParse(args.opening_hours);
return {
...DEFAULT_FORM,
name: value('name') || point?.name || preview.subject,
address: value('address') || planField(preview, 'address') || '',
description: value('description') || planField(preview, 'description') || '',
lat: String(typeof args.lat === 'number' ? args.lat : (point?.lat ?? '')),
lng: String(typeof args.lng === 'number' ? args.lng : (point?.lng ?? '')),
address: text('address'),
description: text('description'),
lat: coordinate('lat'),
lng: coordinate('lng'),
category_id: String(categoryId ?? ''),
place_time: planField(preview, 'time') ?? '',
end_time: planField(preview, 'endTime') ?? '',
@@ -53,10 +55,16 @@ function restoreDraft(form: PlaceFormData, edits: AssistantPlanEdits | undefined
...(lng === undefined ? {} : { lng: String(lng ?? '') }),
...(place_notes === undefined ? {} : { notes: place_notes ?? '' }),
...(opening_hours === undefined ? {} : { opening_hours: opening_hours ? JSON.stringify(opening_hours) : '' }),
...(edits?.startTime === undefined ? {} : { place_time: edits.startTime ?? '' }),
...(edits?.endTime === undefined ? {} : { end_time: edits.endTime ?? '' }),
...(edits?.notes === undefined ? {} : { assignment_notes: edits.notes ?? '' }),
...(edits?.categoryId === undefined ? {} : { category_id: String(edits.categoryId ?? '') }),
...visitDraft(edits ?? {}),
};
}
function visitDraft({ startTime, endTime, notes, categoryId }: AssistantPlanEdits): Partial<PlaceFormData> {
return {
...(startTime === undefined ? {} : { place_time: startTime ?? '' }),
...(endTime === undefined ? {} : { end_time: endTime ?? '' }),
...(notes === undefined ? {} : { assignment_notes: notes ?? '' }),
...(categoryId === undefined ? {} : { category_id: String(categoryId ?? '') }),
};
}
@@ -1,4 +1,4 @@
import type { AssistantChangeLabelKey, AssistantChangePreview, AssistantPlanEdits } from '@trek/shared';
import type { AssistantChangePreview, AssistantPlanEdits } from '@trek/shared';
import { Check, Pencil } from 'lucide-react';
import { lazy, Suspense, useEffect, useId, useState } from 'react';
@@ -15,36 +15,11 @@ import {
NEUTRAL_TINT,
} from '../shared/DialogShell';
import { Tooltip } from '../shared/Tooltip';
import { isVisitProposal, planField, proposalNote } from './assistantPlanFieldsModel';
import { useAssistantView } from './assistantViewContext';
const AssistantPlaceProposal = lazy(() => import('./AssistantPlaceProposal'));
export function isVisitProposal(preview: AssistantChangePreview | null | undefined) {
return preview?.verbKey === 'addPlaceToDay' || preview?.verbKey === 'assignPlace';
}
export function isDayNoteProposal(preview: AssistantChangePreview | null | undefined) {
return preview?.verbKey === 'addDayNote' || preview?.verbKey === 'updateDayNote';
}
export function planField(preview: AssistantChangePreview, field: AssistantChangeLabelKey) {
return preview.rows.find((row) => row.labelKey === field)?.after;
}
export function dayNoteBody(preview: AssistantChangePreview) {
return planField(preview, 'content') ?? (preview.verbKey === 'addDayNote' ? planField(preview, 'time') : undefined);
}
export function proposalNote(preview: AssistantChangePreview, edits: AssistantPlanEdits | undefined) {
return isVisitProposal(preview)
? edits?.notes === undefined
? planField(preview, 'notes')
: edits.notes
: edits?.noteBody === undefined
? dayNoteBody(preview)
: edits.noteBody;
}
interface ProposalEditProps {
preview: AssistantChangePreview;
args?: unknown;
@@ -0,0 +1,27 @@
import type { AssistantChangeLabelKey, AssistantChangePreview, AssistantPlanEdits } from '@trek/shared';
export function isVisitProposal(preview: AssistantChangePreview | null | undefined) {
return preview?.verbKey === 'addPlaceToDay' || preview?.verbKey === 'assignPlace';
}
export function isDayNoteProposal(preview: AssistantChangePreview | null | undefined) {
return preview?.verbKey === 'addDayNote' || preview?.verbKey === 'updateDayNote';
}
export function planField(preview: AssistantChangePreview, field: AssistantChangeLabelKey) {
return preview.rows.find((row) => row.labelKey === field)?.after;
}
export function dayNoteBody(preview: AssistantChangePreview) {
return planField(preview, 'content') ?? (preview.verbKey === 'addDayNote' ? planField(preview, 'time') : undefined);
}
export function proposalNote(preview: AssistantChangePreview, edits: AssistantPlanEdits | undefined) {
return isVisitProposal(preview)
? edits?.notes === undefined
? planField(preview, 'notes')
: edits.notes
: edits?.noteBody === undefined
? dayNoteBody(preview)
: edits.noteBody;
}
@@ -6,12 +6,8 @@ import { useTranslation } from '../../../i18n';
import { Tooltip } from '../../shared/Tooltip';
import AssistantChangeFields from '../AssistantChangeFields';
import type { ChangeItem } from '../assistantParts';
import AssistantPlanFields, {
isDayNoteProposal,
isVisitProposal,
planField,
proposalNote,
} from '../AssistantPlanFields';
import AssistantPlanFields from '../AssistantPlanFields';
import { isDayNoteProposal, isVisitProposal, planField, proposalNote } from '../assistantPlanFieldsModel';
import { useAssistantView } from '../assistantViewContext';
import { useChangeHover } from '../useChangeHover';
import { isSingleBookingDraft } from './booking/bookingCardModel';
@@ -244,15 +240,7 @@ function PendingRow({
const preview = item.preview;
const view = item.card ? viewOf(item.card) : null;
const inlineBooking = inlineBookingCard(item);
const aside = <Slot item={item} view={view} name="Aside" />;
const visit = isVisitProposal(preview);
const dayNote = isDayNoteProposal(preview);
const editable = preview && (visit || dayNote);
const note = editable ? proposalNote(preview, edits) : null;
const receipt = preview?.verbKey === 'importBooking' ? planField(preview, 'attachedTo') : undefined;
const rows = preview?.rows.filter(
(row) => !(groupedDay && row.labelKey === 'day') && !(dayNote && row.labelKey === 'time')
);
const editable = preview && (isVisitProposal(preview) || isDayNoteProposal(preview));
return (
<div
{...handlers}
@@ -285,38 +273,7 @@ function PendingRow({
{inlineBooking ? (
<Slot name="Body" item={item} view={view} fallback={<ChangeHead item={item} view={view} struck={false} />} />
) : preview ? (
<>
{view?.ownsSubject ? (
aside
) : (
<SubjectLine
subject={edits?.place?.name ?? edits?.noteTitle ?? preview.subject}
struck={false}
aside={view?.Aside && aside}
block
/>
)}
<span className="mt-1 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-caption text-content-faint">
{!visit && <span className="me-0.5 min-w-0 truncate">{verbLabel(preview, t)}</span>}
<DomainChip domain={preview.domain} />
{view?.Facts ? (
<Slot item={item} view={view} name="Facts" fallback={<AssistantChangeFields rows={preview.rows} />} />
) : (
<AssistantChangeFields rows={rows ?? preview.rows} visit={visit} edits={edits} />
)}
</span>
{receipt && (
<div
className="mt-1 flex min-w-0 items-center gap-1.5 text-caption text-content-muted"
title={t('assistant.attach.chip.keepWithBooking')}
>
<Paperclip size={13} className="flex-none" aria-hidden="true" />
<span className="sr-only">{t('assistant.attach.chip.keepWithBooking')}</span>
<bdi className="truncate">{receipt}</bdi>
</div>
)}
{note && <bdi className="mt-1 block truncate text-caption text-content-muted">{note}</bdi>}
</>
<PendingDetails item={item} preview={preview} view={view} edits={edits} groupedDay={groupedDay} />
) : (
<span className="trek-skeleton inline-block h-4 w-40" aria-hidden="true" />
)}
@@ -334,6 +291,64 @@ function PendingRow({
);
}
function PendingDetails({
item,
preview,
view,
edits,
groupedDay,
}: {
item: ChangeItem;
preview: AssistantChangePreview;
view: View | null;
edits: AssistantPlanEdits | undefined;
groupedDay: boolean;
}) {
const { t } = useTranslation();
const aside = <Slot item={item} view={view} name="Aside" />;
const visit = isVisitProposal(preview);
const dayNote = isDayNoteProposal(preview);
const note = visit || dayNote ? proposalNote(preview, edits) : null;
const receipt = preview.verbKey === 'importBooking' ? planField(preview, 'attachedTo') : undefined;
const rows = preview.rows.filter(
(row) => !(groupedDay && row.labelKey === 'day') && !(dayNote && row.labelKey === 'time')
);
return (
<>
{view?.ownsSubject ? (
aside
) : (
<SubjectLine
subject={edits?.place?.name ?? edits?.noteTitle ?? preview.subject}
struck={false}
aside={view?.Aside && aside}
block
/>
)}
<span className="mt-1 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-caption text-content-faint">
{!visit && <span className="me-0.5 min-w-0 truncate">{verbLabel(preview, t)}</span>}
<DomainChip domain={preview.domain} />
{view?.Facts ? (
<Slot item={item} view={view} name="Facts" fallback={<AssistantChangeFields rows={preview.rows} />} />
) : (
<AssistantChangeFields rows={rows} visit={visit} edits={edits} />
)}
</span>
{receipt && (
<div
className="mt-1 flex min-w-0 items-center gap-1.5 text-caption text-content-muted"
title={t('assistant.attach.chip.keepWithBooking')}
>
<Paperclip size={13} className="flex-none" aria-hidden="true" />
<span className="sr-only">{t('assistant.attach.chip.keepWithBooking')}</span>
<bdi className="truncate">{receipt}</bdi>
</div>
)}
{note && <bdi className="mt-1 block truncate text-caption text-content-muted">{note}</bdi>}
</>
);
}
interface RowsProps {
items: readonly ChangeItem[];
/** The waiting rows wait behind the week grid. */
+5 -5
View File
@@ -141,6 +141,9 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
const noDate = t('costs.noDate')
const dayGroups = useMemo(() => groupLedgerByDay(filtered, filteredSettlements, locale, noDate), [filtered, filteredSettlements, locale, noDate])
const emptyLedger = !hasExpenses && dayGroups.length === 0
const mobileEmptyLedger = emptyLedger
? <EmptyState scene="costs" title={t('costs.emptyText')} />
: <div className="text-content-faint" style={{ textAlign: 'center', padding: '36px 16px', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>{search ? t('costs.noMatch') : t('costs.emptyText')}</div>
// ── filter dropdown options (category + single day) ──────────────────────
const categoryOptions = useMemo(() => [
@@ -286,7 +289,6 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
{/* The same four columns as the cards above: the ledger takes three, the
sidebar the last, so it lines up with the total-spend card. */}
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', columnGap: 16, rowGap: 32, alignItems: 'start' }} className="costs-grid">
{/* expenses */}
<div className="costs-main" style={{ gridColumn: emptyLedger ? '1 / -1' : 'span 3', minWidth: 0 }}>
{dayBanner}
@@ -469,7 +471,6 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
function MobileBody() {
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, paddingTop: 8 }}>
{/* Total card */}
{hasExpenses ? <section style={{ background: 'linear-gradient(135deg,#1f2937,#111827)', color: '#fff', borderRadius: 22, padding: '20px 20px 16px', boxShadow: '0 8px 24px -8px rgba(0,0,0,0.28)' }}>
<div style={{ fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', textTransform: 'uppercase', letterSpacing: '0.12em', color: 'rgba(255,255,255,0.6)', fontWeight: 600 }}>{t('costs.totalSpend')}</div>
<div style={{ fontSize: 'calc(44px * var(--fs-scale-title, 1))', fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1, marginTop: 8, display: 'flex', alignItems: 'baseline' }}>{bigMoney(totals.totalSpend, 24, 'rgba(255,255,255,0.6)')}</div>
@@ -562,8 +563,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
<CustomSelect value={dayFilter} onChange={v => setDayFilter(String(v))} options={dayOptions} size="sm" searchable style={{ flex: 1, minWidth: 0 }} />
</div>
{dayBanner}
{emptyLedger ? <EmptyState scene="costs" title={t('costs.emptyText')} /> : dayGroups.length === 0
? <div className="text-content-faint" style={{ textAlign: 'center', padding: '36px 16px', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>{search ? t('costs.noMatch') : t('costs.emptyText')}</div>
{dayGroups.length === 0
? mobileEmptyLedger
: dayGroups.map(g => {
const dtot = g.entries.reduce((a, en) => en.kind === 'expense' ? a + baseTotal(en.e) : a, 0)
return (
@@ -590,7 +591,6 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
</div>
</>}
{/* By category */}
{hasExpenses && <div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
<div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.byCategory')}</div>
{categoryBars}
+389 -330
View File
@@ -64,42 +64,18 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
isOpen,
onClose,
place,
prefillCoords,
categories,
isMobile,
collectionsEnabled,
form,
mapsSearch,
setMapsSearch,
mapsResults,
isSearchingMaps,
acSuggestions,
setAcSuggestions,
acSource,
searchSource,
acHighlight,
setAcHighlight,
t,
language,
googleAnswers,
placesEnrichEnabled,
canUploadFiles,
fetchSuggestions,
sourceLabel,
handleChange,
handleMapsSearch,
handleSelectMapsResult,
handleNearby,
pin,
nearbyList,
distanceUnit,
handleSelectSuggestion,
handleSearchKeyDown,
hasTimeError,
handleSubmit,
isSaving,
duplicateWarning,
detailsSelection,
serviceStop,
serviceStopDuplicate,
} = S;
@@ -278,313 +254,396 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
{assignmentOnly ? (
schedule
) : (
<div className={inRow ? ROW : STACK}>
{showDetails && (
<PlaceDetailsColumn
selection={detailsSelection}
selectedImageUrl={form.image_url}
onPickImage={S.pickImage}
image={S.image}
onAdoptDescription={S.adoptDescription}
onHours={(hours) => S.setDetailsHours(weekFromPeriods(hours.periods))}
hasDescription={!!form.description.trim()}
language={language}
timeFormat={S.timeFormat}
locale={S.locale}
variant="dialog"
// Stacked above the form in a narrow window, it takes the form's width.
fluid={isMobile}
t={t}
/>
)}
<form onSubmit={handleSubmit} className={FORM_COLUMN}>
{/* Place search: typed-ahead suggestions, a full search, and a pasted map link. */}
<div className={PANEL}>
<EditorField label={t('common.search')} htmlFor={`${fieldId}-search`}>
<div className="relative">
<div className="flex items-stretch gap-2">
<input
id={`${fieldId}-search`}
type="text"
// A new place starts at the search; an edit or a place brought
// in from the map already has what the search would give.
ref={!place && !prefillCoords ? focusRevealedEditor : undefined}
value={mapsSearch}
onChange={(e) => {
setMapsSearch(e.target.value);
S.setEmptySearch(null);
}}
onKeyDown={handleSearchKeyDown}
onBlur={() => setTimeout(() => setAcSuggestions([]), 150)}
onFocus={() => {
if (mapsSearch.trim().length >= 2 && acSuggestions.length === 0 && mapsResults.length === 0) {
fetchSuggestions(mapsSearch.trim());
}
}}
placeholder={t('places.mapsSearchPlaceholder')}
className={`${INPUT} flex-1`}
/>
<Tooltip label={t('common.search')}>
<button
type="button"
onClick={() => {
setAcSuggestions([]);
void handleMapsSearch();
}}
disabled={isSearchingMaps}
aria-label={t('common.search')}
className={`${SIDE_BUTTON} bg-accent text-accent-text hover:opacity-90`}
style={fs(13, 'body')}
>
{isSearchingMaps ? '...' : <Search size={15} strokeWidth={2.2} aria-hidden="true" />}
</button>
</Tooltip>
{pin && (
<Tooltip label={t('places.nearby')}>
<button
type="button"
onClick={handleNearby}
disabled={isSearchingMaps}
aria-label={t('places.nearby')}
className={`${SIDE_BUTTON} border border-edge bg-surface-card text-content-secondary hover:bg-surface-hover`}
>
<LocateFixed size={15} strokeWidth={2.2} aria-hidden="true" />
</button>
</Tooltip>
)}
</div>
{/* Autocomplete dropdown. Capped and scrolling, because plugin rows can
follow the core ones (#2221) and the list must stay inside the dialog;
the row the arrow keys land on is scrolled into view. */}
{acSuggestions.length > 0 && (
<div className="absolute inset-x-0 z-20 mt-1 max-h-96 overflow-y-auto rounded-[12px] border border-edge-faint bg-surface-card p-1 shadow-dropdown">
{acSuggestions.map((s, idx) => (
<button
key={s.placeId}
ref={idx === acHighlight ? (el) => el?.scrollIntoView?.({ block: 'nearest' }) : undefined}
type="button"
onMouseDown={() => handleSelectSuggestion(s)}
onMouseEnter={() => setAcHighlight(idx)}
className={`${PICK_ROW} ${idx === acHighlight ? 'bg-surface-tertiary' : 'hover:bg-surface-hover'}`}
>
<span className="min-w-0 flex-1">
<span className="block truncate font-medium text-content" style={fs(13, 'body')}>
{s.mainText}
</span>
{s.secondaryText && (
<span className="block truncate text-content-muted" style={fs(11.5)}>
{s.secondaryText}
</span>
)}
</span>
<SourceBadge label={sourceLabel(s, acSource)} />
</button>
))}
</div>
)}
</div>
</EditorField>
{/* Nothing found (#2472): say so, and offer the hand-made way in, taking
the query as the name when there is none yet. */}
{S.emptySearch && mapsResults.length === 0 && !isSearchingMaps && (
<div className="flex items-center gap-3 rounded-[12px] border border-dashed border-edge bg-surface-card px-3 py-2.5">
<span className="grid h-8 w-8 flex-none place-items-center rounded-full bg-surface-tertiary text-content-muted">
<PencilLine size={15} strokeWidth={2} />
</span>
<span className="min-w-0 flex-1">
<span className="block truncate font-semibold text-content" style={fs(12.5, 'body')}>
{t('places.searchNothing', { query: S.emptySearch })}
</span>
<span className="block text-content-muted" style={fs(11.5)}>
{t('places.searchNothingHint')}
</span>
</span>
<button
type="button"
onClick={() => {
if (!form.name.trim()) handleChange('name', S.emptySearch!);
S.setEmptySearch(null);
document
.getElementById(`${fieldId}-contact`)
?.scrollIntoView?.({ behavior: 'smooth', block: 'center' });
}}
className="flex-none rounded-full bg-accent px-3 py-1.5 font-semibold text-accent-text hover:opacity-90"
style={fs(12, 'body')}
>
{t('places.addByHand')}
</button>
</div>
)}
{/* Search results (populated after full search) */}
{mapsResults.length > 0 && (
<div className="max-h-40 overflow-y-auto rounded-[10px] border border-edge-faint bg-surface-card p-1">
{mapsResults.map((result, idx) => (
<button
key={idx}
type="button"
onClick={() =>
handleSelectMapsResult(result, { mode: 'search', rank: idx, count: mapsResults.length })
}
className={`${PICK_ROW} hover:bg-surface-hover`}
>
<span className="min-w-0 flex-1">
<span className="block truncate font-medium text-content" style={fs(13, 'body')}>
{result.name}
</span>
{result.address && (
<span className="block truncate text-content-muted" style={fs(11.5)}>
{result.address}
</span>
)}
</span>
{nearbyList && typeof result.distance_m === 'number' && (
<SoftPill>{formatDistance(result.distance_m / 1000, distanceUnit)}</SoftPill>
)}
<SourceBadge label={sourceLabel(result, searchSource)} />
</button>
))}
</div>
)}
{/* The index answers first and Google only when it finds nothing, so a
list with the wrong place on it never reaches Google by itself. One
quiet line under the list sends the same query there, on an instance
where Google holds the key slot and for a list Google did not
already produce. */}
{mapsResults.length > 0 && !nearbyList && offersGoogleRetry(searchSource, googleAnswers) && (
<button
type="button"
onClick={() => handleMapsSearch('google')}
disabled={isSearchingMaps}
className="inline-flex items-center gap-1 self-start text-content-faint transition-colors hover:text-content disabled:opacity-50"
style={fs(12)}
>
<RotateCcw size={11} strokeWidth={2} aria-hidden="true" />
{t('places.searchGoogleInstead')}
</button>
)}
</div>
<PlaceFormLocation
fieldId={fieldId}
form={form}
onChange={handleChange}
warnWithoutCoordinates={!serviceStop}
/>
{/* For a stop on a drive: the kind of stop, how long, and where it belongs.
The category it replaces is gone from the head band too: refuelling is
not a taste, it is a fact about the place, so it lives in
`places.stop_type` and not in the trip's own editable category list. */}
{serviceStop && (
<div className={`${PANEL} ${SERVICE_STOP_LABELS}`}>
<ServiceStopSection
mode={serviceStop}
stopType={form.stop_type ?? null}
onStopType={S.handleStopKind}
minutes={form.duration_minutes ?? 0}
onMinutes={S.handleStopMinutes}
leg={S.serviceStopLeg}
onLeg={S.setServiceStopLeg}
lat={form.lat ? Number.parseFloat(form.lat) : null}
lng={form.lng ? Number.parseFloat(form.lng) : null}
/>
</div>
)}
{/* Extra labels next to the one category, to filter the places by. Not for a
stop on a drive, which is not an activity anyone looks up by its tags. */}
{!serviceStop && <PlaceFormTags tags={S.tagField} t={t} manage={!proposal} />}
{/* The day in context: its times. They live on the day-assignment, not on
the pool place (#2163), so they are only shown when a single assignment
is in context (itinerary edit, or a single-assignment pool edit). Hidden
when creating, and for unassigned or multi-day pool edits where a single
time is ambiguous and would not persist. */}
{schedule}
{/* Description, notes and the note for this day, one at a time. The day
note follows the times: only with a single assignment in context. */}
<PlaceFormTexts
fieldId={fieldId}
description={form.description}
notes={form.notes}
dayNotes={proposal || (place && S.assignmentId) ? (form.assignment_notes ?? '') : null}
dayNumber={S.dayNumber}
initialTab={proposal ? 'assignment_notes' : undefined}
onChange={(field, value) => handleChange(field, value)}
t={t}
/>
{!showDetails && (
<div className={PANEL}>
<PlaceImageSection image={S.image} onPickUrl={S.pickImage} t={t} />
</div>
)}
{/* Link, files and how to reach the place, in one card. */}
<div className={PANEL}>
{/* The link and the files side by side, as on a booking. */}
<div className={canUploadFiles ? GRID_2 : ''}>
<EditorField label={t('places.formWebsite')} htmlFor={`${fieldId}-website`}>
<input
id={`${fieldId}-website`}
type="url"
value={form.website}
onChange={(e) => handleChange('website', e.target.value)}
placeholder="https://..."
className={INPUT}
/>
</EditorField>
{canUploadFiles && (
<PendingFiles
files={S.pendingFiles}
fileRef={S.fileRef}
onAdd={S.handleFileAdd}
onRemove={S.handleRemoveFile}
t={t}
/>
)}
</div>
{/* Phone, e-mail and the place's own hours, for what the search did not
know or a place nobody has listed (#2472). */}
<PlaceContactFields
id={`${fieldId}-contact`}
phone={form.phone ?? ''}
email={form.email ?? ''}
openingHours={form.opening_hours ?? ''}
suggestedHours={S.detailsHours}
onChange={(field, value, origin) => handleChange(field, value, origin)}
/>
</div>
{/* Costs — create / view the expense linked to this place (#1298).
Same block, same flow as a booking: save first, then the editor.
Never for a stop on a drive: a petrol stop is not an activity with a budget
line, and the fuel it buys is an expense of the trip rather than of a place. */}
{S.isBudgetEnabled && !serviceStop && !proposal && (
<div className={PANEL}>
<BookingCostsSection
placeId={place?.id ?? null}
reservationId={null}
hintKey="places.createExpenseHint"
onCreate={S.handleCreateExpense}
onEdit={S.handleEditExpense}
onRemove={S.handleRemoveExpense}
labelClassName={LABEL}
customTooltips
whiteButtons
/>
</div>
)}
</form>
{twoColumn && <CollectionPicker bias={S.locationBias} onSelect={handleSelectMapsResult} t={t} />}
</div>
<PlaceFormColumns
state={S}
fieldId={fieldId}
proposal={!!proposal}
schedule={schedule}
className={inRow ? ROW : STACK}
showDetails={showDetails}
twoColumn={twoColumn}
/>
)}
</DialogShell>
);
}
type PlaceFormState = ReturnType<typeof usePlaceFormModal>;
function PlaceFormColumns({
state: S,
fieldId,
proposal,
schedule,
className,
showDetails,
twoColumn,
}: {
state: PlaceFormState;
fieldId: string;
proposal: boolean;
schedule: ReactNode;
className: string;
showDetails: boolean;
twoColumn: boolean;
}) {
const {
form,
place,
isMobile,
detailsSelection,
language,
t,
handleSubmit,
handleChange,
serviceStop,
handleSelectMapsResult,
} = S;
return (
<div className={className}>
{showDetails && (
<PlaceDetailsColumn
selection={detailsSelection}
selectedImageUrl={form.image_url}
onPickImage={S.pickImage}
image={S.image}
onAdoptDescription={S.adoptDescription}
onHours={(hours) => S.setDetailsHours(weekFromPeriods(hours.periods))}
hasDescription={!!form.description.trim()}
language={language}
timeFormat={S.timeFormat}
locale={S.locale}
variant="dialog"
// Stacked above the form in a narrow window, it takes the form's width.
fluid={isMobile}
t={t}
/>
)}
<form onSubmit={handleSubmit} className={FORM_COLUMN}>
<PlaceSearchFields state={S} fieldId={fieldId} />
<PlaceFormLocation
fieldId={fieldId}
form={form}
onChange={handleChange}
warnWithoutCoordinates={!serviceStop}
/>
{/* For a stop on a drive: the kind of stop, how long, and where it belongs.
The category it replaces is gone from the head band too: refuelling is
not a taste, it is a fact about the place, so it lives in
`places.stop_type` and not in the trip's own editable category list. */}
{serviceStop && (
<div className={`${PANEL} ${SERVICE_STOP_LABELS}`}>
<ServiceStopSection
mode={serviceStop}
stopType={form.stop_type ?? null}
onStopType={S.handleStopKind}
minutes={form.duration_minutes ?? 0}
onMinutes={S.handleStopMinutes}
leg={S.serviceStopLeg}
onLeg={S.setServiceStopLeg}
lat={form.lat ? Number.parseFloat(form.lat) : null}
lng={form.lng ? Number.parseFloat(form.lng) : null}
/>
</div>
)}
{/* Extra labels next to the one category, to filter the places by. Not for a
stop on a drive, which is not an activity anyone looks up by its tags. */}
{!serviceStop && <PlaceFormTags tags={S.tagField} t={t} manage={!proposal} />}
{/* The day in context: its times. They live on the day-assignment, not on
the pool place (#2163), so they are only shown when a single assignment
is in context (itinerary edit, or a single-assignment pool edit). Hidden
when creating, and for unassigned or multi-day pool edits where a single
time is ambiguous and would not persist. */}
{schedule}
{/* Description, notes and the note for this day, one at a time. The day
note follows the times: only with a single assignment in context. */}
<PlaceFormTexts
fieldId={fieldId}
description={form.description}
notes={form.notes}
dayNotes={proposal || (place && S.assignmentId) ? (form.assignment_notes ?? '') : null}
dayNumber={S.dayNumber}
initialTab={proposal ? 'assignment_notes' : undefined}
onChange={(field, value) => handleChange(field, value)}
t={t}
/>
{!showDetails && (
<div className={PANEL}>
<PlaceImageSection image={S.image} onPickUrl={S.pickImage} t={t} />
</div>
)}
<PlaceContactAndFiles state={S} fieldId={fieldId} />
{/* Costs — create / view the expense linked to this place (#1298).
Same block, same flow as a booking: save first, then the editor.
Never for a stop on a drive: a petrol stop is not an activity with a budget
line, and the fuel it buys is an expense of the trip rather than of a place. */}
{S.isBudgetEnabled && !serviceStop && !proposal && (
<div className={PANEL}>
<BookingCostsSection
placeId={place?.id ?? null}
reservationId={null}
hintKey="places.createExpenseHint"
onCreate={S.handleCreateExpense}
onEdit={S.handleEditExpense}
onRemove={S.handleRemoveExpense}
labelClassName={LABEL}
customTooltips
whiteButtons
/>
</div>
)}
</form>
{twoColumn && <CollectionPicker bias={S.locationBias} onSelect={handleSelectMapsResult} t={t} />}
</div>
);
}
function PlaceSearchFields({ state: S, fieldId }: { state: PlaceFormState; fieldId: string }) {
const {
t,
place,
prefillCoords,
form,
mapsSearch,
setMapsSearch,
isSearchingMaps,
mapsResults,
acSuggestions,
setAcSuggestions,
acHighlight,
setAcHighlight,
acSource,
searchSource,
googleAnswers,
pin,
nearbyList,
distanceUnit,
fetchSuggestions,
sourceLabel,
handleChange,
handleMapsSearch,
handleNearby,
handleSelectMapsResult,
handleSelectSuggestion,
handleSearchKeyDown,
} = S;
return (
<div className={PANEL}>
<EditorField label={t('common.search')} htmlFor={`${fieldId}-search`}>
<div className="relative">
<div className="flex items-stretch gap-2">
<input
id={`${fieldId}-search`}
type="text"
// A new place starts at the search; an edit or a place brought
// in from the map already has what the search would give.
ref={!place && !prefillCoords ? focusRevealedEditor : undefined}
value={mapsSearch}
onChange={(e) => {
setMapsSearch(e.target.value);
S.setEmptySearch(null);
}}
onKeyDown={handleSearchKeyDown}
onBlur={() => setTimeout(() => setAcSuggestions([]), 150)}
onFocus={() => {
if (mapsSearch.trim().length >= 2 && acSuggestions.length === 0 && mapsResults.length === 0) {
fetchSuggestions(mapsSearch.trim());
}
}}
placeholder={t('places.mapsSearchPlaceholder')}
className={`${INPUT} flex-1`}
/>
<Tooltip label={t('common.search')}>
<button
type="button"
onClick={() => {
setAcSuggestions([]);
void handleMapsSearch();
}}
disabled={isSearchingMaps}
aria-label={t('common.search')}
className={`${SIDE_BUTTON} bg-accent text-accent-text hover:opacity-90`}
style={fs(13, 'body')}
>
{isSearchingMaps ? '...' : <Search size={15} strokeWidth={2.2} aria-hidden="true" />}
</button>
</Tooltip>
{pin && (
<Tooltip label={t('places.nearby')}>
<button
type="button"
onClick={handleNearby}
disabled={isSearchingMaps}
aria-label={t('places.nearby')}
className={`${SIDE_BUTTON} border border-edge bg-surface-card text-content-secondary hover:bg-surface-hover`}
>
<LocateFixed size={15} strokeWidth={2.2} aria-hidden="true" />
</button>
</Tooltip>
)}
</div>
{/* Autocomplete dropdown. Capped and scrolling, because plugin rows can
follow the core ones (#2221) and the list must stay inside the dialog;
the row the arrow keys land on is scrolled into view. */}
{acSuggestions.length > 0 && (
<div className="absolute inset-x-0 z-20 mt-1 max-h-96 overflow-y-auto rounded-[12px] border border-edge-faint bg-surface-card p-1 shadow-dropdown">
{acSuggestions.map((s, idx) => (
<button
key={s.placeId}
ref={idx === acHighlight ? (el) => el?.scrollIntoView?.({ block: 'nearest' }) : undefined}
type="button"
onMouseDown={() => handleSelectSuggestion(s)}
onMouseEnter={() => setAcHighlight(idx)}
className={`${PICK_ROW} ${idx === acHighlight ? 'bg-surface-tertiary' : 'hover:bg-surface-hover'}`}
>
<span className="min-w-0 flex-1">
<span className="block truncate font-medium text-content" style={fs(13, 'body')}>
{s.mainText}
</span>
{s.secondaryText && (
<span className="block truncate text-content-muted" style={fs(11.5)}>
{s.secondaryText}
</span>
)}
</span>
<SourceBadge label={sourceLabel(s, acSource)} />
</button>
))}
</div>
)}
</div>
</EditorField>
{/* Nothing found (#2472): say so, and offer the hand-made way in, taking
the query as the name when there is none yet. */}
{S.emptySearch && mapsResults.length === 0 && !isSearchingMaps && (
<div className="flex items-center gap-3 rounded-[12px] border border-dashed border-edge bg-surface-card px-3 py-2.5">
<span className="grid h-8 w-8 flex-none place-items-center rounded-full bg-surface-tertiary text-content-muted">
<PencilLine size={15} strokeWidth={2} />
</span>
<span className="min-w-0 flex-1">
<span className="block truncate font-semibold text-content" style={fs(12.5, 'body')}>
{t('places.searchNothing', { query: S.emptySearch })}
</span>
<span className="block text-content-muted" style={fs(11.5)}>
{t('places.searchNothingHint')}
</span>
</span>
<button
type="button"
onClick={() => {
if (!form.name.trim()) handleChange('name', S.emptySearch!);
S.setEmptySearch(null);
document
.getElementById(`${fieldId}-contact`)
?.scrollIntoView?.({ behavior: 'smooth', block: 'center' });
}}
className="flex-none rounded-full bg-accent px-3 py-1.5 font-semibold text-accent-text hover:opacity-90"
style={fs(12, 'body')}
>
{t('places.addByHand')}
</button>
</div>
)}
{/* Search results (populated after full search) */}
{mapsResults.length > 0 && (
<div className="max-h-40 overflow-y-auto rounded-[10px] border border-edge-faint bg-surface-card p-1">
{mapsResults.map((result, idx) => (
<button
key={idx}
type="button"
onClick={() =>
handleSelectMapsResult(result, { mode: 'search', rank: idx, count: mapsResults.length })
}
className={`${PICK_ROW} hover:bg-surface-hover`}
>
<span className="min-w-0 flex-1">
<span className="block truncate font-medium text-content" style={fs(13, 'body')}>
{result.name}
</span>
{result.address && (
<span className="block truncate text-content-muted" style={fs(11.5)}>
{result.address}
</span>
)}
</span>
{nearbyList && typeof result.distance_m === 'number' && (
<SoftPill>{formatDistance(result.distance_m / 1000, distanceUnit)}</SoftPill>
)}
<SourceBadge label={sourceLabel(result, searchSource)} />
</button>
))}
</div>
)}
{/* The index answers first and Google only when it finds nothing, so a
list with the wrong place on it never reaches Google by itself. One
quiet line under the list sends the same query there, on an instance
where Google holds the key slot and for a list Google did not
already produce. */}
{mapsResults.length > 0 && !nearbyList && offersGoogleRetry(searchSource, googleAnswers) && (
<button
type="button"
onClick={() => handleMapsSearch('google')}
disabled={isSearchingMaps}
className="inline-flex items-center gap-1 self-start text-content-faint transition-colors hover:text-content disabled:opacity-50"
style={fs(12)}
>
<RotateCcw size={11} strokeWidth={2} aria-hidden="true" />
{t('places.searchGoogleInstead')}
</button>
)}
</div>
);
}
function PlaceContactAndFiles({ state: S, fieldId }: { state: PlaceFormState; fieldId: string }) {
const { canUploadFiles, form, handleChange, t } = S;
return (
<div className={PANEL}>
{/* The link and the files side by side, as on a booking. */}
<div className={canUploadFiles ? GRID_2 : ''}>
<EditorField label={t('places.formWebsite')} htmlFor={`${fieldId}-website`}>
<input
id={`${fieldId}-website`}
type="url"
value={form.website}
onChange={(e) => handleChange('website', e.target.value)}
placeholder="https://..."
className={INPUT}
/>
</EditorField>
{canUploadFiles && (
<PendingFiles
files={S.pendingFiles}
fileRef={S.fileRef}
onAdd={S.handleFileAdd}
onRemove={S.handleRemoveFile}
t={t}
/>
)}
</div>
{/* Phone, e-mail and the place's own hours, for what the search did not
know or a place nobody has listed (#2472). */}
<PlaceContactFields
id={`${fieldId}-contact`}
phone={form.phone ?? ''}
email={form.email ?? ''}
openingHours={form.opening_hours ?? ''}
suggestedHours={S.detailsHours}
onChange={(field, value, origin) => handleChange(field, value, origin)}
/>
</div>
);
}
@@ -379,6 +379,25 @@ export function usePlaceFormModal(props: PlaceFormModalProps) {
if (isOpen) previewDraft?.(form);
}, [form, isOpen, previewDraft]);
const saveProposal = (draft: PlaceProposal) => {
if (draft.disabled || hasTimeError) return;
try {
draft.onSave(form);
onClose();
} catch (error) {
toast.error(error instanceof Error ? error.message : t('places.saveError'));
}
};
const openExpenseAfterSave = (saved: { id: number } | void) => {
const intent = expenseIntentRef.current;
expenseIntentRef.current = null;
const savedId = (saved && 'id' in saved ? saved.id : null) ?? place?.id ?? null;
if (!intent || !onOpenExpense || !savedId) return;
if (intent.editItem) onOpenExpense({ editItem: intent.editItem });
else onOpenExpense({ prefill: { placeId: savedId, name: form.name.trim(), category: 'activities' } });
};
const handleSubmit = async (e?: { preventDefault?: () => void }) => {
e?.preventDefault?.();
if (!form.name.trim()) {
@@ -388,16 +407,7 @@ export function usePlaceFormModal(props: PlaceFormModalProps) {
toast.error(t('places.nameRequired'));
return;
}
if (proposal) {
if (proposal.disabled || hasTimeError) return;
try {
proposal.onSave(form);
onClose();
} catch (error) {
toast.error(error instanceof Error ? error.message : t('places.saveError'));
}
return;
}
if (proposal) return saveProposal(proposal);
// #1152: only for new places, and only on the first attempt — a second click
// (with the warning already showing) is the explicit "add anyway" confirmation.
//
@@ -440,13 +450,7 @@ export function usePlaceFormModal(props: PlaceFormModalProps) {
// Open the Costs editor for the saved place when the user asked to
// create/edit its linked expense — gated on an id, so a create that the
// server refused never opens an editor pointing at nothing (#1298).
const intent = expenseIntentRef.current;
expenseIntentRef.current = null;
const savedId = (saved && 'id' in saved ? saved.id : null) ?? place?.id ?? null;
if (intent && onOpenExpense && savedId) {
if (intent.editItem) onOpenExpense({ editItem: intent.editItem });
else onOpenExpense({ prefill: { placeId: savedId, name: form.name.trim(), category: 'activities' } });
}
openExpenseAfterSave(saved);
onClose();
} catch (err: unknown) {
// The save did not happen, so the intent behind it cannot be honoured: the place
+52
View File
@@ -0,0 +1,52 @@
import { useState, useEffect } from 'react';
import { isNativeApp } from '../native/platform';
/**
* The phone shell's viewport: narrower than the md breakpoint (768px), or a
* touch screen short enough to be a phone on its side.
*
* Width alone flipped a phone into the desktop planner the moment it was
* turned: most phones are wider than 767px in landscape. That swapped the
* whole route tree, so an open sheet, what was typed into it and the map's
* position were gone. A tablet stays where it was, since none is under 500px
* tall, and a desktop window keeps following its width, since its pointer is
* fine.
*
* The phone rules in `index.css` repeat this query; keep them in step.
*
* The app is the exception: inside it the phone shell applies at every size.
* An iPad, an iPad in Split View or Stage Manager and a foldable unfolded all
* get the touch shell, laid out for their width (see `hooks/sizeClass.ts`), never
* the desktop pages. Only that keeps one route tree across a fold, a
* rotation or a window resize, so nothing open or typed is lost, and only the
* touch shell has the app's own features (Wallet, sharing into a trip, the
* edge swipe back).
*/
export const PHONE_QUERY = '(max-width: 767px), (pointer: coarse) and (max-height: 500px)';
/** Whether the phone shell applies right now, for code that is not a component. */
export function isPhoneViewport(): boolean {
if (isNativeApp()) return true;
return (
typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia(PHONE_QUERY).matches
);
}
/**
* True while the phone shell applies (see {@link PHONE_QUERY}). Reactive:
* follows viewport resizes and orientation changes via matchMedia.
*/
export function useIsPhone(): boolean {
const [isPhone, setIsPhone] = useState(isPhoneViewport);
useEffect(() => {
if (isNativeApp()) return;
const mq = window.matchMedia(PHONE_QUERY);
const handler = (e: MediaQueryListEvent) => setIsPhone(e.matches);
setIsPhone(mq.matches);
mq.addEventListener('change', handler);
return () => mq.removeEventListener('change', handler);
}, []);
return isPhone;
}
@@ -4,7 +4,6 @@ import {
LayoutGrid, List, MapPin, Pencil, Plus, RefreshCw, Sparkles, Trash2, Users,
} from 'lucide-react'
import { useTranslation } from '../../../i18n'
import MDancingTrek from '../../components/MDancingTrek'
import { useDashboard } from '../../../pages/dashboard/useDashboard'
import {
type DashboardTrip, MS_PER_DAY, daysUntil, fullDate, getTripStatus,
@@ -18,7 +17,6 @@ import MDemoWelcome from './MDemoWelcome'
import { IcsSubscribeModal } from '../../../components/Planner/IcsSubscribeModal'
import PluginWidgets from '../../../components/Plugins/PluginWidgets'
import { entityGradient } from '../../../utils/gradients';
import MContextMenu from '../../components/MContextMenu';
import MGlassBar from '../../components/MGlassBar'
import MIconBtn from '../../components/MIconBtn'
import MSegmented from '../../components/MSegmented'
+1 -50
View File
@@ -1,50 +1 @@
import { useState, useEffect } from 'react'
import { isNativeApp } from '../native/platform'
/**
* The phone shell's viewport: narrower than the md breakpoint (768px), or a
* touch screen short enough to be a phone on its side.
*
* Width alone flipped a phone into the desktop planner the moment it was
* turned: most phones are wider than 767px in landscape. That swapped the
* whole route tree, so an open sheet, what was typed into it and the map's
* position were gone. A tablet stays where it was, since none is under 500px
* tall, and a desktop window keeps following its width, since its pointer is
* fine.
*
* The phone rules in `index.css` repeat this query; keep them in step.
*
* The app is the exception: inside it the phone shell applies at every size.
* An iPad, an iPad in Split View or Stage Manager and a foldable unfolded all
* get the touch shell, laid out for their width (see `hooks/sizeClass.ts`), never
* the desktop pages. Only that keeps one route tree across a fold, a
* rotation or a window resize, so nothing open or typed is lost, and only the
* touch shell has the app's own features (Wallet, sharing into a trip, the
* edge swipe back).
*/
export const PHONE_QUERY = '(max-width: 767px), (pointer: coarse) and (max-height: 500px)'
/** Whether the phone shell applies right now, for code that is not a component. */
export function isPhoneViewport(): boolean {
if (isNativeApp()) return true
return typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia(PHONE_QUERY).matches
}
/**
* True while the phone shell applies (see {@link PHONE_QUERY}). Reactive:
* follows viewport resizes and orientation changes via matchMedia.
*/
export function useIsPhone(): boolean {
const [isPhone, setIsPhone] = useState(isPhoneViewport)
useEffect(() => {
if (isNativeApp()) return
const mq = window.matchMedia(PHONE_QUERY)
const handler = (e: MediaQueryListEvent) => setIsPhone(e.matches)
setIsPhone(mq.matches)
mq.addEventListener('change', handler)
return () => mq.removeEventListener('change', handler)
}, [])
return isPhone
}
export { isPhoneViewport, PHONE_QUERY, useIsPhone } from '../hooks/useIsPhone';
@@ -264,9 +264,9 @@ describe('MCostsTab', () => {
it('FE-MOB-COSTT-012: shows the empty panel without any expense', async () => {
await renderTab(planner({ budgetItems: [] }))
expect(screen.getByText('costs.noCategories')).toBeInTheDocument()
expect(screen.queryByText('costs.byCategory')).not.toBeInTheDocument()
expect(screen.getByText('costs.emptyText')).toBeInTheDocument()
expect(up(screen.getByText('costs.totalSpend'), 1).textContent).toContain('$0.00')
expect(screen.queryByText('costs.totalSpend')).not.toBeInTheDocument()
})
it('FE-MOB-COSTT-013: groups the expenses by day with a per-day total', async () => {
+1
View File
@@ -99,6 +99,7 @@ DEMO_MODE=false # Demo mode: resets data hourly
# KITINERARY_EXTRACTOR_PATH= # Full path to the kitinerary-extractor binary. Unset, TREK searches /usr/lib/*/libexec/kf6/ and then PATH; the official image pins it. Set it to run a newer extractor than your distribution packages — the version in use is in the startup log and in GET /api/admin/system-info. (default: auto-detected)
# LLM_TIMEOUT_MS=900000 # Ceiling (ms) for one AI-parsing call before it is abandoned. One value for every provider, and the underlying HTTP client is held to it too. Generous by default so heavier parsing work fits without a code change; lower it on a cloud provider to fail fast. (default: 900000)
# OPENROUTER_PROVIDER= # Optional upstream provider slug for OpenRouter chat and booking extraction. Unset keeps OpenRouter's routing and fallbacks.
# LLM_MAX_OUTPUT_TOKENS=8192 # Longest answer (tokens) one AI-parsing call may ask for. Raise it when a document with many bookings comes back cut off; keep prompt plus cap inside your model's context. (default: 4096 for OpenAI-compatible, 8192 for Anthropic)
# VAPID_PUBLIC_KEY= # Web Push: the public half of the key pair browsers subscribe with (base64url, 65 bytes). Leave both halves unset and TREK generates a pair on first start and keeps it in the database, so it travels with every backup. Set both to use a pair of your own, e.g. printed by `npx web-push generate-vapid-keys`. Changing the pair later means every device has to turn push on again.
@@ -18,7 +18,7 @@ import { AssignmentsService } from '../assignments/assignments.service';
import {
idSchema, transportLegInputSchema, reservationUrlSchema, type TransportLegInput, bookingPriceSchema, bookingBudgetCategorySchema,
TRANSPORT_RESERVATION_TYPES, MCP_CREATABLE_TRANSPORT_TYPES, LEG_RESERVATION_TYPES, BOOKING_RESERVATION_TYPES,
RESERVATION_STATUSES, type ReservationStatus, typeToCostCategory,
RESERVATION_STATUSES, initialReservationStatusSchema, type ReservationStatus, typeToCostCategory,
} from '@trek/shared';
import { RESERVATION_METADATA } from '../../db/json-columns';
import { decodeJson } from '../../utils/json-column';
@@ -367,10 +367,7 @@ export class ReservationsMcp {
tripId: idSchema,
title: z.string().min(1).max(200),
type: z.enum(BOOKING_TYPES).describe('Reservation type: "hotel", "restaurant", "event", "tour", "activity", "parking", or "other"'),
status: z
.enum(['pending', 'confirmed'])
.optional()
.describe('Use confirmed when the provider already confirmed the reservation; otherwise leave pending'),
status: initialReservationStatusSchema.optional().describe('Use confirmed when the provider already confirmed it'),
reservation_time: z.string().optional().describe('ISO 8601 datetime or time string'),
reservation_end_time: z.string().optional().describe('When it ends: a dinner from 19:00 to 21:30, a tour that runs all afternoon. Ignored for hotels, whose span is the check-in/check-out days.'),
url: urlField,
@@ -105,6 +105,7 @@ const NOT_ROW_ID_FIELDS: Record<string, string> = {
client_id: 'an OAuth or OIDC client id is a string',
accessKeyId: 'an S3 access key id is a credential',
google_place_id: 'a Google place id is a provider string',
amap_poi_id: 'an Amap POI id is a provider string',
osm_id: 'an OpenStreetMap id is a provider string such as "node/123"',
placeId: 'a maps provider place id is a provider string',
pickedPlaceId: 'a maps provider place id is a provider string',
@@ -116,7 +116,9 @@ describe('attachedPort', () => {
it('ASTATL-005: the standing instructions say how an attached file is read and booked', () => {
const prompt = systemPrompt('English');
expect(prompt).toContain('Read its content with read_attached_file');
expect(prompt).toContain('If TREK already offered or saved a booking from the file, reuse that proposal or booking.');
expect(prompt).toContain(
'If TREK already offered or saved a booking from the file, reuse that proposal or booking.',
);
expect(prompt).toContain('Only propose create_reservation for a booking that has neither been offered nor saved.');
});
@@ -28,6 +28,9 @@ export const reservationTypeSchema = z.enum(RESERVATION_TYPE_KEYS).or(z.string()
/** A reservation's `status` as the API returns it: a known status, or a stored value outside them. */
export const reservationStatusSchema = z.enum(RESERVATION_STATUSES).or(z.string());
/** A new reservation starts pending or already confirmed. */
export const initialReservationStatusSchema = z.enum(['pending', 'confirmed']);
// Inside reservationSchema the two fields stay z.string(), described by the
// catalog. Zod 4 types a union field as optional for a consumer compiled
// without strictNullChecks (the client), so the union there would loosen the