mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-23 15:36:33 +00:00
Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c85c3833e6 | |||
| f3e05f48e1 | |||
| 746f53ff7e | |||
| 7f9a4da52a | |||
| 8043b7952d | |||
| e198392060 | |||
| deea669e28 | |||
| d6b624e400 | |||
| 263d650460 | |||
| a3fc696510 | |||
| 9f6f62c6ae | |||
| a70ff750a6 | |||
| 815a523d1c | |||
| 30382dc366 |
@@ -1,10 +1,11 @@
|
||||
import { Check, LoaderCircle, MapPin, Undo2 } from 'lucide-react';
|
||||
import { Check, CheckCheck, ListChecks, LoaderCircle, MapPin, Undo2 } from 'lucide-react';
|
||||
import { type ReactNode, useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { blockKeyOf } from '../../store/assistantMapModel';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import { DialogButton, NEUTRAL_TINT } from '../shared/DialogShell';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import AssistantCompareSwitch from './AssistantCompareSwitch';
|
||||
@@ -13,6 +14,8 @@ import AssistantWeekOverview from './AssistantWeekOverview';
|
||||
import { type ChangeItem, undoLeftMs } from './assistantParts';
|
||||
import { useAssistantView } from './assistantViewContext';
|
||||
import { ChangeRows } from './cards/ChangeCardSlots';
|
||||
import CardHeader from './cards/parts/CardHeader';
|
||||
import { CardFoot } from './cards/parts/CardSection';
|
||||
import { ICON_BUTTON } from './cards/parts/assistantTones';
|
||||
import { useChangeExclusions } from './cards/useChangeExclusions';
|
||||
import { changePoints, type DayChange } from './dayAfterModel';
|
||||
@@ -60,6 +63,9 @@ function undoableNow(item: ChangeItem, undone: Readonly<Record<string, true>>, n
|
||||
);
|
||||
}
|
||||
|
||||
/** The band of a card whose changes are all decided: the green of a done booking. */
|
||||
const DONE_TINT = 'color-mix(in srgb, var(--success) 9%, transparent)';
|
||||
|
||||
/** The waiting changes the user left on that touch the day plan. */
|
||||
function dayChangesOf(items: readonly ChangeItem[], excluded: ReadonlySet<string>): DayChange[] {
|
||||
return items.flatMap((i) =>
|
||||
@@ -69,17 +75,18 @@ function dayChangesOf(items: readonly ChangeItem[], excluded: ReadonlySet<string
|
||||
);
|
||||
}
|
||||
|
||||
/** The card's head: what the card is, what can be done with it as a whole, and how many changes it holds. */
|
||||
/** The change card's band: tinted green once everything in it is decided, what it holds and its actions. */
|
||||
function CardHead({ open, count, actions }: { open: boolean; count: number; actions?: ReactNode }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="mb-1 flex min-h-7 items-center gap-2">
|
||||
<span className="min-w-0 flex-1 truncate text-caption font-semibold text-content-secondary">
|
||||
{t(open ? 'assistant.change.title' : 'assistant.change.doneTitle')}
|
||||
</span>
|
||||
{actions}
|
||||
<span className="text-caption tabular-nums text-content-faint">{count}</span>
|
||||
</div>
|
||||
<CardHeader
|
||||
icon={open ? ListChecks : CheckCheck}
|
||||
tone={open ? 'info' : 'success'}
|
||||
tint={open ? NEUTRAL_TINT : DONE_TINT}
|
||||
title={t(open ? 'assistant.change.title' : 'assistant.change.doneTitle')}
|
||||
count={count}
|
||||
actions={actions}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -224,7 +231,7 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
|
||||
const open = pending.length > 0;
|
||||
return (
|
||||
<section className="trek-popover-enter rounded-xl border border-edge-faint bg-surface-card px-3 pb-2 pt-2.5 shadow-card">
|
||||
<section className="trek-popover-enter overflow-hidden rounded-[16px] border border-edge-faint bg-surface-card px-3.5 pb-3 pt-3 shadow-card">
|
||||
<CardHead
|
||||
open={open}
|
||||
count={items.length}
|
||||
@@ -257,25 +264,19 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
<p className="sr-only" role="status">
|
||||
{t('assistant.change.pending', { count: pending.length })}
|
||||
</p>
|
||||
<div className="flex justify-end gap-2 border-t border-edge-faint pt-2.5">
|
||||
<button
|
||||
type="button"
|
||||
disabled={isRunning}
|
||||
onClick={() => void submit(false)}
|
||||
className="rounded-lg px-3 py-1.5 text-body text-content-secondary hover:bg-surface-hover hover:text-content disabled:opacity-50"
|
||||
>
|
||||
<CardFoot>
|
||||
<DialogButton disabled={isRunning} onClick={() => void submit(false)}>
|
||||
{t('assistant.change.discard')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
</DialogButton>
|
||||
<DialogButton
|
||||
variant="primary"
|
||||
disabled={isRunning || chosen === 0}
|
||||
onClick={() => void submit(true)}
|
||||
className="inline-flex items-center gap-1.5 rounded-lg bg-accent px-3 py-1.5 text-body font-medium text-accent-text hover:bg-accent-hover disabled:opacity-50"
|
||||
icon={<Check size={14} aria-hidden="true" />}
|
||||
>
|
||||
<Check size={14} aria-hidden="true" />
|
||||
{pending.length === 1 ? t('assistant.change.apply') : t('assistant.change.applyN', { count: chosen })}
|
||||
</button>
|
||||
</div>
|
||||
</DialogButton>
|
||||
</CardFoot>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
|
||||
@@ -103,11 +103,7 @@ export default function AssistantHeader({ tripId, thread, tripTitle, onClose, dr
|
||||
<div className="min-w-0 flex-1">
|
||||
{thread.isRunning ? (
|
||||
// While it works, the line over the title says what it does right now.
|
||||
<p role="status" className="m-0 flex min-w-0 items-center gap-1.5 text-caption font-medium">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="trek-assistant-pulse h-1.5 w-1.5 flex-shrink-0 rounded-full bg-accent"
|
||||
/>
|
||||
<p role="status" className="m-0 flex min-w-0 items-center text-caption font-medium">
|
||||
<span className="trek-assistant-shimmer truncate">{live?.text ?? t('assistant.step.working')}</span>
|
||||
</p>
|
||||
) : (
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useCallback, useMemo } from 'react';
|
||||
import { useLocation, useMatch, useNavigate } from 'react-router';
|
||||
|
||||
import { rememberListsSubTab } from '../../hooks/useListsSubTab';
|
||||
import { useAssistantStore } from '../../store/assistantStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import AssistantWindow from './AssistantWindow';
|
||||
import { plannerSearchOf } from './assistantShowOnMap';
|
||||
@@ -22,7 +23,7 @@ function useRouteTripId(): number | null {
|
||||
* notification opens a place, a tab of the trip opens as `?tab=` (a list's
|
||||
* own tab remembered first), and another page is simply navigated to. A day
|
||||
* picked in the chat (its weather) selects that day the same way, and "On
|
||||
* map" on a card brings the planner's map back first.
|
||||
* map" on a card brings the planner's map back first from a tab without one.
|
||||
*/
|
||||
export default function AssistantHost() {
|
||||
const navigate = useNavigate();
|
||||
@@ -54,8 +55,12 @@ export default function AssistantHost() {
|
||||
[navigate, openPlanner, tripId]
|
||||
);
|
||||
const focusDay = useCallback((dayId: number) => openPlanner(`?day=${dayId}`), [openPlanner]);
|
||||
// "On map" from another tab of the planner (Tours, Costs, ...) first brings the map back.
|
||||
const revealMap = useCallback(() => openPlanner('?tab=plan'), [openPlanner]);
|
||||
// "On map" from a tab without a map (Costs, Lists, ...) first brings the plan's map back; the Tours tab
|
||||
// shows the route on its own map. A map on screen tells the assistant its view, which is how it is known.
|
||||
const revealMap = useCallback(() => {
|
||||
if (useAssistantStore.getState().mapView?.tripId === tripId) return;
|
||||
openPlanner('?tab=plan');
|
||||
}, [openPlanner, tripId]);
|
||||
|
||||
return <AssistantWindow trip={trip} onOpen={open} onFocusDay={focusDay} onRevealMap={revealMap} />;
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import AssistantFollowUps from './AssistantFollowUps';
|
||||
import AssistantMarkdown from './AssistantMarkdown';
|
||||
import AssistantMentionText from './AssistantMentionText';
|
||||
import AssistantPlaceStrip from './AssistantPlaceStrip';
|
||||
import AssistantRemembered from './AssistantRemembered';
|
||||
import AssistantShareDialog from './AssistantShareDialog';
|
||||
import AssistantToolSteps from './AssistantToolSteps';
|
||||
import AssistantWeatherStrip from './AssistantWeatherStrip';
|
||||
@@ -129,6 +130,9 @@ function Answer({ message }: { message: StoredMessage }) {
|
||||
return <AssistantPlaceStrip key={block.key} found={block.found} message={message} />;
|
||||
}
|
||||
if (block.kind === 'weather') return <AssistantWeatherStrip key={block.key} days={block.days} />;
|
||||
if (block.kind === 'remembered') {
|
||||
return <AssistantRemembered key={block.key} note={block.note} live={writing} />;
|
||||
}
|
||||
if (block.kind === 'cards') return <AssistantCardBlock key={block.key} block={block} message={message} />;
|
||||
return <AssistantChangeCard key={block.key} items={block.items} />;
|
||||
})}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import type { AssistantFoundPlace } from '@trek/shared';
|
||||
import { Check, ChevronDown, LoaderCircle, MapPin, Plus, Star } from 'lucide-react';
|
||||
import { Check, MapPin, Plus, Star } from 'lucide-react';
|
||||
import { createElement, type ReactNode, useRef } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { getCategoryIcon } from '../shared/categoryIcons';
|
||||
import { PopoverListPanel } from '../shared/dialogParts';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import { usePopoverList } from '../shared/usePopoverList';
|
||||
import { useAssistantView } from './assistantViewContext';
|
||||
import type { useAssistantPlaceStrip } from './useAssistantPlaceStrip';
|
||||
import { useFoundPlacePhoto } from './useFoundPlacePhoto';
|
||||
@@ -16,110 +14,14 @@ type Strip = ReturnType<typeof useAssistantPlaceStrip>;
|
||||
const ACTION =
|
||||
'inline-flex items-center gap-1 rounded-lg bg-surface-secondary text-caption font-medium text-content transition-colors hover:bg-surface-hover disabled:cursor-default disabled:opacity-50 disabled:hover:bg-surface-secondary';
|
||||
|
||||
/** "+ Day 3" for the day in focus, a list of the trip's days beside it; "Pick a day" when no day is in focus. */
|
||||
function SuggestButton({ place, strip, tall }: { place: AssistantFoundPlace; strip: Strip; tall: boolean }) {
|
||||
/** "Add to trip": opens the planner's place form filled in with the place, its details loading beside it. */
|
||||
function AddButton({ place, strip, tall }: { place: AssistantFoundPlace; strip: Strip; tall: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const { days, focusDay, disabled, blockedKey, adding } = strip;
|
||||
const list = usePopoverList(focusDay ? days.findIndex((d) => d.id === focusDay.id) : 0, {
|
||||
estimatedHeight: Math.ceil(days.length / 7) * 44 + 16,
|
||||
});
|
||||
const { open, toggle, close, triggerRef, listId } = list;
|
||||
const height = tall ? 'h-10' : 'h-7';
|
||||
const busy = adding === place.ref;
|
||||
|
||||
const pick = (dayId: number) => {
|
||||
close();
|
||||
void strip.suggest(place, dayId);
|
||||
};
|
||||
|
||||
const buttons = (
|
||||
<span className="inline-flex min-w-0 gap-px">
|
||||
{focusDay ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
onClick={() => void strip.suggest(place, focusDay.id)}
|
||||
aria-label={t('assistant.place.addTo', { day: focusDay.label })}
|
||||
className={`${ACTION} ${height} rounded-e-none px-2`}
|
||||
>
|
||||
{busy ? (
|
||||
<LoaderCircle size={12} aria-hidden="true" className="animate-spin" />
|
||||
) : (
|
||||
<Plus size={12} aria-hidden="true" />
|
||||
)}
|
||||
<span className="truncate">{t('assistant.place.addToShort', { n: focusDay.n })}</span>
|
||||
</button>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
onClick={toggle}
|
||||
aria-expanded={open}
|
||||
aria-controls={open ? listId : undefined}
|
||||
aria-label={t('assistant.place.pickDay')}
|
||||
className={`${ACTION} ${height} rounded-s-none px-1.5`}
|
||||
>
|
||||
<ChevronDown size={12} aria-hidden="true" />
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
onClick={toggle}
|
||||
aria-expanded={open}
|
||||
aria-controls={open ? listId : undefined}
|
||||
className={`${ACTION} ${height} px-2`}
|
||||
>
|
||||
<Plus size={12} aria-hidden="true" />
|
||||
<span className="truncate">{t('assistant.place.pickDay')}</span>
|
||||
<ChevronDown size={12} aria-hidden="true" className="text-content-faint" />
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{blockedKey ? (
|
||||
<Tooltip label={t(blockedKey)} placement="top">
|
||||
{/* A disabled button gets no pointer events; the wrapper carries the reason. */}
|
||||
<span className="inline-flex min-w-0">{buttons}</span>
|
||||
</Tooltip>
|
||||
) : (
|
||||
buttons
|
||||
)}
|
||||
{/* A grid of day tiles, not a list: a month-long trip still fits in a few rows. */}
|
||||
<PopoverListPanel list={list} label={t('assistant.place.pickDay')} className="w-[15.5rem] p-2">
|
||||
<div className="grid grid-cols-7 gap-1">
|
||||
{days.map((day) => {
|
||||
const current = day.id === focusDay?.id;
|
||||
return (
|
||||
<Tooltip key={day.id} label={day.label} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => pick(day.id)}
|
||||
aria-label={day.label}
|
||||
aria-pressed={current}
|
||||
className={`flex h-10 flex-col items-center justify-center rounded-lg leading-none outline-none transition-colors focus-visible:ring-2 focus-visible:ring-accent ${
|
||||
current ? 'bg-accent text-accent-text' : 'text-content hover:bg-surface-hover'
|
||||
}`}
|
||||
>
|
||||
<span className="text-body font-semibold tabular-nums">{day.n}</span>
|
||||
{day.weekday && (
|
||||
<span className={`mt-0.5 text-caption ${current ? 'text-accent-text' : 'text-content-faint'}`}>
|
||||
{day.weekday}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</PopoverListPanel>
|
||||
</>
|
||||
<button type="button" onClick={() => strip.open(place)} className={`${ACTION} ${tall ? 'h-10' : 'h-7'} px-2`}>
|
||||
<Plus size={12} aria-hidden="true" />
|
||||
<span className="truncate">{t('assistant.place.add')}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -219,7 +121,7 @@ function PlaceAction({
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return strip.canSuggest ? <SuggestButton place={place} strip={strip} tall={tall} /> : null;
|
||||
return strip.canAdd ? <AddButton place={place} strip={strip} tall={tall} /> : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -227,9 +129,10 @@ function PlaceAction({
|
||||
* with the category it most likely belongs in on it (or that category's icon
|
||||
* on its colour), its name, address and rating, whether it is open now while
|
||||
* the trip runs, how far it is from the last stop of the day in focus, and one
|
||||
* way on: "+ Day 3" for a new place, "On map" for one the trip has. A click on
|
||||
* the card shows it on the map, and resting the pointer on it pins it there
|
||||
* for a moment.
|
||||
* way on: "Add to trip" for a new place, "On map" for one the trip has. A click
|
||||
* on a new place opens the place form filled in with it (one the trip has, or
|
||||
* any where nothing can be added, shows on the map), and resting the pointer on
|
||||
* it pins it there for a moment.
|
||||
*/
|
||||
export default function AssistantPlaceCard({
|
||||
place,
|
||||
@@ -259,7 +162,7 @@ export default function AssistantPlaceCard({
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => strip.show(place)}
|
||||
onClick={() => (place.inTripPlaceId === null && strip.canAdd ? strip.open(place) : strip.show(place))}
|
||||
onFocus={() => strip.hover(place)}
|
||||
onBlur={() => strip.hover(null)}
|
||||
className="flex flex-col text-start outline-none focus-visible:bg-surface-hover"
|
||||
|
||||
@@ -2,9 +2,8 @@
|
||||
* FE-AI-PLACES-001 to FE-AI-PLACES-010
|
||||
*
|
||||
* The strip of places a search found: what a card says, that its picture only
|
||||
* ever comes from TREK's photo proxy, "+ Day N" for the day in focus or a
|
||||
* picked one, why it waits while a change is undecided, the map's part, and
|
||||
* no "+ Day" in a journey's chat.
|
||||
* ever comes from TREK's photo proxy, "Add to trip" opening the place form on
|
||||
* the day in focus, the map's part, and no "Add to trip" in a journey's chat.
|
||||
*/
|
||||
import type { AssistantFoundPlace, AssistantMessage, AssistantPlaces } from '@trek/shared';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
@@ -67,7 +66,6 @@ const answer = (parts: AssistantMessage['parts'] = []): AssistantMessage => ({
|
||||
parts,
|
||||
});
|
||||
|
||||
const addFoundPlace = vi.fn(async () => {});
|
||||
const requestCamera = vi.fn();
|
||||
const setPreviewPin = vi.fn();
|
||||
const onRevealMap = vi.fn();
|
||||
@@ -83,7 +81,6 @@ function seed({ focusDayId = 31, messages = [] as AssistantMessage[] } = {}) {
|
||||
categories: [buildCategory({ id: 5, name: 'Restaurant', icon: 'Utensils' })],
|
||||
});
|
||||
useAssistantStore.setState({
|
||||
addFoundPlace,
|
||||
requestCamera,
|
||||
setPreviewPin,
|
||||
byTrip: {
|
||||
@@ -165,34 +162,30 @@ describe('AssistantPlaceStrip', () => {
|
||||
expect(fetchPhoto).toHaveBeenCalledWith('good', 'good', 41.889, 12.47, 'Trattoria s1:0', expect.any(Function));
|
||||
});
|
||||
|
||||
it('FE-AI-PLACES-004: "+ Day 1" suggests the place for the day in focus', () => {
|
||||
it('FE-AI-PLACES-004: "Add to trip" opens the place form with the place, on the day in focus', () => {
|
||||
seed();
|
||||
renderStrip({ toolCallId: 's1', places: [place('s1:0')], more: 0 });
|
||||
fireEvent.click(screen.getByRole('button', { name: /^Add to/ }));
|
||||
expect(addFoundPlace).toHaveBeenCalledWith(TRIP, 's1:0', 31);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Add to trip' }));
|
||||
expect(onRevealMap).toHaveBeenCalled();
|
||||
expect(useAssistantStore.getState().placeDraft).toMatchObject({ tripId: TRIP, dayId: 31, place: { ref: 's1:0' } });
|
||||
});
|
||||
|
||||
it('FE-AI-PLACES-005: another day is picked from the list, and without a focus the list is the only way', () => {
|
||||
it('FE-AI-PLACES-005: a click on a new place opens the form too, without a day when none is in focus', () => {
|
||||
seed({ focusDayId: 0 });
|
||||
renderStrip({ toolCallId: 's1', places: [place('s1:0')], more: 0 });
|
||||
fireEvent.click(screen.getByRole('button', { name: /Pick a day/ }));
|
||||
fireEvent.click(screen.getByRole('button', { name: /Nov 3/ }));
|
||||
expect(addFoundPlace).toHaveBeenCalledWith(TRIP, 's1:0', 32);
|
||||
fireEvent.click(screen.getByText('Trattoria s1:0'));
|
||||
expect(useAssistantStore.getState().placeDraft).toMatchObject({ dayId: null, place: { ref: 's1:0' } });
|
||||
expect(requestCamera).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-AI-PLACES-006: waits while a change is undecided, and offline', () => {
|
||||
it('FE-AI-PLACES-006: opening the form waits for nothing: an undecided change and offline leave it on', () => {
|
||||
const waiting = answer([
|
||||
{ type: 'tool-call', toolCallId: 'w1', toolName: 'create_place', args: {}, approval: { id: 'w1' } },
|
||||
]);
|
||||
seed({ messages: [waiting] });
|
||||
const { unmount } = renderStrip({ toolCallId: 's1', places: [place('s1:0')], more: 0 });
|
||||
expect(screen.getByRole('button', { name: /^Add to/ })).toBeDisabled();
|
||||
unmount();
|
||||
|
||||
seed();
|
||||
setForcedOffline(true);
|
||||
renderStrip({ toolCallId: 's1', places: [place('s1:0')], more: 0 });
|
||||
expect(screen.getByRole('button', { name: /^Add to/ })).toBeDisabled();
|
||||
expect(screen.getByRole('button', { name: 'Add to trip' })).toBeEnabled();
|
||||
});
|
||||
|
||||
it('FE-AI-PLACES-007: a suggested place says so, and one the trip has goes to the map instead', () => {
|
||||
@@ -234,15 +227,14 @@ describe('AssistantPlaceStrip', () => {
|
||||
expect(setPreviewPin).toHaveBeenLastCalledWith(null);
|
||||
});
|
||||
|
||||
it('FE-AI-PLACES-010: a journey chat lists the places but offers no "+ Day" while the trip is on screen', () => {
|
||||
// The journey key never matches the planner's trip, so the trip check already hides "+ Day";
|
||||
it('FE-AI-PLACES-010: a journey chat lists the places but offers no "Add to trip" while the trip is on screen', () => {
|
||||
// The journey key never matches the planner's trip, so the trip check already hides "Add to trip";
|
||||
// the scope check in the hook is defence in depth for the day trips and journeys share keys.
|
||||
seed();
|
||||
renderStrip({ toolCallId: 's1', places: [place('s1:0')], more: 0 }, answer(), {
|
||||
tripId: assistantChatKey({ kind: 'journey', journeyId: TRIP }),
|
||||
});
|
||||
expect(screen.getByText('Trattoria s1:0')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /^Add to/ })).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: /Pick a day/ })).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: 'Add to trip' })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* FE-AI-REMEMBER-001 to FE-AI-REMEMBER-002
|
||||
*
|
||||
* A note the assistant kept on its own: a quiet line naming it, the trip
|
||||
* notes read again while the answer is written, and the notes a tap away.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import AssistantRemembered from './AssistantRemembered';
|
||||
import { type AssistantView, AssistantViewContext } from './assistantViewContext';
|
||||
|
||||
const SETTINGS = useSettingsStore.getState();
|
||||
|
||||
function renderLine(live: boolean) {
|
||||
const view: AssistantView = { tripId: 4, variant: 'window', density: 'compact' };
|
||||
return render(
|
||||
<AssistantViewContext.Provider value={view}>
|
||||
<AssistantRemembered note="We eat vegetarian" live={live} />
|
||||
</AssistantViewContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
useSettingsStore.setState(SETTINGS, true);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('AssistantRemembered', () => {
|
||||
it('FE-AI-REMEMBER-001: names the note, and reads the notes again only while the answer is written', () => {
|
||||
const loadSettings = vi.fn(async () => {});
|
||||
useSettingsStore.setState({ loadSettings });
|
||||
const { unmount } = renderLine(false);
|
||||
expect(screen.getByText('We eat vegetarian')).toBeInTheDocument();
|
||||
expect(screen.getByText('Noted for this trip:')).toBeInTheDocument();
|
||||
expect(loadSettings).not.toHaveBeenCalled();
|
||||
unmount();
|
||||
renderLine(true);
|
||||
expect(loadSettings).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-AI-REMEMBER-002: the pencil opens the trip notes', () => {
|
||||
useSettingsStore.setState({ loadSettings: vi.fn(async () => {}) });
|
||||
renderLine(false);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Edit trip notes' }));
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { BookmarkCheck, Pencil } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import AssistantMemoryDialog from './AssistantMemoryDialog';
|
||||
import { useAssistantScope } from './assistantViewContext';
|
||||
|
||||
/**
|
||||
* A note the assistant kept in the trip notes on its own, as a quiet line in
|
||||
* its answer, with the notes a tap away to change or drop it. Kept while the
|
||||
* answer is written, the notes on this device are read again, so the dialog
|
||||
* never saves over the note with what it held before.
|
||||
*/
|
||||
export default function AssistantRemembered({ note, live }: { note: string; live: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const scope = useAssistantScope();
|
||||
const loadSettings = useSettingsStore((s) => s.loadSettings);
|
||||
const [editing, setEditing] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (live) void loadSettings();
|
||||
}, [live, loadSettings]);
|
||||
|
||||
const tripId = scope.kind === 'trip' ? scope.tripId : null;
|
||||
return (
|
||||
<div className="flex min-w-0 items-center gap-2 rounded-lg bg-surface-secondary px-2.5 py-1.5 text-caption">
|
||||
<BookmarkCheck size={13} strokeWidth={2.2} aria-hidden="true" className="flex-none text-success" />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="font-semibold text-content-secondary">{t('assistant.memory.kept')}</span>{' '}
|
||||
<bdi className="text-content-muted">{note}</bdi>
|
||||
</span>
|
||||
{tripId !== null && (
|
||||
<Tooltip label={t('assistant.memory.edit')} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEditing(true)}
|
||||
aria-label={t('assistant.memory.edit')}
|
||||
className="grid h-6 w-6 flex-none place-items-center rounded-md text-content-faint transition-colors hover:bg-surface-hover hover:text-content"
|
||||
>
|
||||
<Pencil size={12} aria-hidden="true" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
{editing && tripId !== null && <AssistantMemoryDialog tripId={tripId} onClose={() => setEditing(false)} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -177,7 +177,7 @@ describe('AssistantSurface', () => {
|
||||
],
|
||||
},
|
||||
},
|
||||
{ type: 'text', text: 'Rain on Monday, so the market is a good pick.' },
|
||||
{ type: 'text', text: 'Rain on Monday, so Nishiki Market is a good pick.' },
|
||||
],
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -168,20 +168,6 @@
|
||||
animation: trek-assistant-busy 1.8s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* The dot beside what the assistant does right now: a soft beat, a halo going out. */
|
||||
@keyframes trek-assistant-pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
}
|
||||
70%,
|
||||
100% {
|
||||
box-shadow: 0 0 0 6px transparent;
|
||||
}
|
||||
}
|
||||
.trek-assistant-pulse {
|
||||
animation: trek-assistant-pulse 1.4s ease-out infinite;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.trek-assistant-pop,
|
||||
.trek-assistant-enter {
|
||||
@@ -190,8 +176,7 @@
|
||||
.trek-assistant-settle {
|
||||
transition: none;
|
||||
}
|
||||
.trek-assistant-busy,
|
||||
.trek-assistant-pulse {
|
||||
.trek-assistant-busy {
|
||||
animation: none;
|
||||
}
|
||||
.trek-assistant-shimmer {
|
||||
@@ -211,8 +196,7 @@
|
||||
[data-reduce-motion] .trek-assistant-settle {
|
||||
transition: none;
|
||||
}
|
||||
[data-reduce-motion] .trek-assistant-busy,
|
||||
[data-reduce-motion] .trek-assistant-pulse {
|
||||
[data-reduce-motion] .trek-assistant-busy {
|
||||
animation: none;
|
||||
}
|
||||
[data-reduce-motion] .trek-assistant-shimmer {
|
||||
|
||||
@@ -111,6 +111,14 @@ describe('the questions an answer offers', () => {
|
||||
|
||||
it('FE-AI-FOLLOW-007: an answer that asks the user something waits for their answer, not for "tell me more"', () => {
|
||||
expect(followUpsFor(of([{ type: 'text', text: 'Should I plan it anyway?' }]), true)).toEqual([]);
|
||||
// Not the found places' chips either, but the model's own answers to its question.
|
||||
const asked = of([
|
||||
{ type: 'data-trek-places', data: { toolCallId: 's', places: [], more: 0 } },
|
||||
{ type: 'text', text: 'Shall I plan it there?' },
|
||||
]);
|
||||
expect(followUpsFor(asked, true)).toEqual([]);
|
||||
const offered = of([...asked.parts, { type: 'data-trek-follow-ups', data: { questions: ['Yes, plan it'] } }]);
|
||||
expect(followUpsFor(offered, true).map((f) => f.text)).toEqual(['Yes, plan it']);
|
||||
expect(followUpsFor(of([{ type: 'text', text: 'Here it is.' }]), true).map((f) => f.id)).toEqual(['more', 'next']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -126,11 +126,12 @@ export function followUpsFor(message: AssistantMessage, canEdit: boolean): reado
|
||||
if (fromModel.length > 0) return fromModel;
|
||||
const fromCards = cardFollowUps(message, canEdit);
|
||||
if (fromCards.length > 0) return fromCards;
|
||||
// An answer that asks the user something waits for their answer: only the model's own offer fits it.
|
||||
if (endsWithQuestion(message)) return [];
|
||||
const fromChanges = changeFollowUps(message, canEdit);
|
||||
if (fromChanges !== null) return fromChanges.length > 0 ? fromChanges : GENERAL;
|
||||
const types = new Set(message.parts.map((part) => part.type));
|
||||
if (types.has('data-trek-places')) return PLACES;
|
||||
if (types.has('data-trek-weather')) return WEATHER;
|
||||
// An answer that asks the user something waits for their answer, not for "tell me more".
|
||||
return types.has('text') && !endsWithQuestion(message) ? GENERAL : [];
|
||||
return types.has('text') ? GENERAL : [];
|
||||
}
|
||||
|
||||
@@ -200,7 +200,7 @@ describe('messageBlocks: found places and weather', () => {
|
||||
read('s2', []),
|
||||
places('s2', [found('s2:0', { name: 'Place s1:0' }), found('s2:1', { googlePlaceId: 'ChIJa', lat: 40 })], 3),
|
||||
places('s3', [found('s3:0', { lat: 40 })]),
|
||||
{ type: 'text', text: 'Three good ones.' },
|
||||
{ type: 'text', text: 'Three good ones, Place s3:0 first.' },
|
||||
]),
|
||||
false
|
||||
);
|
||||
@@ -208,10 +208,66 @@ describe('messageBlocks: found places and weather', () => {
|
||||
expect(blocks[0]).toMatchObject({ steps: [{ toolCallId: 's1' }, { toolCallId: 's2' }] });
|
||||
// The same name at the same spot, or the same Google id, shows once.
|
||||
expect(blocks[1]).toMatchObject({
|
||||
found: { toolCallId: 's3', more: 5, places: [{ ref: 's1:0' }, { ref: 's1:1' }, { ref: 's3:0' }] },
|
||||
found: { toolCallId: 's3', more: 5, places: [{ ref: 's3:0' }, { ref: 's1:0' }, { ref: 's1:1' }] },
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-AI-PARTS-008d: an answer that planned a tour shows no found places, even one whose planning failed', () => {
|
||||
const blocks = messageBlocks(
|
||||
message([
|
||||
places('s1', [found('s1:0', { name: 'Treseburg' })]),
|
||||
{
|
||||
type: 'tool-call',
|
||||
toolCallId: 'h1',
|
||||
toolName: 'propose_hike',
|
||||
args: {},
|
||||
result: 'Router down',
|
||||
isError: true,
|
||||
},
|
||||
{ type: 'text', text: 'Treseburg is the turning point.' },
|
||||
]),
|
||||
false
|
||||
);
|
||||
expect(blocks.map((b) => b.kind)).not.toContain('places');
|
||||
});
|
||||
|
||||
it('FE-AI-PARTS-008c: a note kept in the trip notes is a line of its own, a refused or running one a step', () => {
|
||||
const kept = (id: string, extra: Record<string, unknown>): AssistantMessagePart =>
|
||||
({
|
||||
type: 'tool-call',
|
||||
toolCallId: id,
|
||||
toolName: 'remember_for_trip',
|
||||
args: { note: ' Vegetarian ' },
|
||||
...extra,
|
||||
}) as AssistantMessagePart;
|
||||
const blocks = messageBlocks(
|
||||
message([
|
||||
kept('m1', { result: { notes: 'Vegetarian' } }),
|
||||
kept('m2', { result: 'The trip notes are full.', isError: true }),
|
||||
]),
|
||||
false
|
||||
);
|
||||
expect(blocks).toMatchObject([
|
||||
{ kind: 'remembered', note: 'Vegetarian' },
|
||||
{ kind: 'steps', steps: [{ toolCallId: 'm2' }] },
|
||||
]);
|
||||
expect(messageBlocks(message([kept('m3', {})]), true)).toMatchObject([{ kind: 'steps' }]);
|
||||
});
|
||||
|
||||
it('FE-AI-PARTS-008b: an answer that names none of the places it found shows no strip', () => {
|
||||
const blocks = messageBlocks(
|
||||
message([places('s1', [found('s1:0', { name: 'Café Ñandú' })]), { type: 'text', text: 'It rains all day.' }]),
|
||||
false
|
||||
);
|
||||
expect(blocks.map((b) => b.kind)).toEqual(['text']);
|
||||
// Named with other accents and case, it is the same place.
|
||||
const named = messageBlocks(
|
||||
message([places('s1', [found('s1:0', { name: 'Café Ñandú' })]), { type: 'text', text: 'Try cafe nandu.' }]),
|
||||
false
|
||||
);
|
||||
expect(named.map((b) => b.kind)).toEqual(['places', 'text']);
|
||||
});
|
||||
|
||||
it('FE-AI-PARTS-009: drops the places a change of the model proposes, and the strip if none is left', () => {
|
||||
const blocks = messageBlocks(
|
||||
message([
|
||||
|
||||
@@ -66,6 +66,8 @@ type MessageBlock =
|
||||
| { kind: 'change'; key: string; items: ChangeItem[] }
|
||||
| { kind: 'places'; key: string; found: AssistantPlaces }
|
||||
| { kind: 'weather'; key: string; days: AssistantWeatherDay[] }
|
||||
// A note the model kept in the trip notes on its own, as a quiet line.
|
||||
| { kind: 'remembered'; key: string; note: string }
|
||||
| CardsBlock;
|
||||
|
||||
/** How cards are laid out: the group each joins, and which ones give way to a change they served. */
|
||||
@@ -93,6 +95,54 @@ function proposed(place: AssistantFoundPlace, effects: readonly AssistantChangeE
|
||||
});
|
||||
}
|
||||
|
||||
/** A name as it is compared with the answer's words: lower case, without accents or marks. */
|
||||
function folded(text: string): string {
|
||||
return text.normalize('NFKD').replace(/\p{M}/gu, '').toLocaleLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* The found places the answer names, first, then the rest; null when the
|
||||
* answer is written and names none of them. A search the answer does not
|
||||
* draw on is the model's own groundwork and shows no strip.
|
||||
*/
|
||||
function namedFirst(places: readonly AssistantFoundPlace[], text: string): AssistantFoundPlace[] | null {
|
||||
if (text.trim() === '') return [...places];
|
||||
const words = folded(text);
|
||||
const named = places.filter((place) => {
|
||||
const name = folded(place.name).trim();
|
||||
return name.length >= 3 && words.includes(name);
|
||||
});
|
||||
if (named.length === 0) return null;
|
||||
return [...named, ...places.filter((place) => !named.includes(place))];
|
||||
}
|
||||
|
||||
/**
|
||||
* The tools that plan or save a tour. An answer that ran one is about the
|
||||
* tour, planned or not: the places its searches went through to find the
|
||||
* points are the model's groundwork, not suggestions, and show no strip.
|
||||
*/
|
||||
const TOUR_PLANNING_TOOLS: ReadonlySet<string> = new Set([
|
||||
'propose_hike',
|
||||
'create_hike',
|
||||
'update_tour',
|
||||
'propose_city_walk',
|
||||
'create_city_walk',
|
||||
'plan_paddle_route',
|
||||
'plan_ski_route',
|
||||
'prepare_tour_change',
|
||||
'save_tour_change',
|
||||
]);
|
||||
|
||||
/** The tool that keeps a note in the trip notes; kept at once, without a card. */
|
||||
const REMEMBER_TOOL = 'remember_for_trip';
|
||||
|
||||
/** The note a call kept, once it is kept; null for any other call, one still running or one refused. */
|
||||
function rememberedNote(part: Extract<AssistantMessagePart, { type: 'tool-call' }>): string | null {
|
||||
if (part.toolName !== REMEMBER_TOOL || part.approval || part.result === undefined || part.isError) return null;
|
||||
const note = (part.args as { note?: unknown }).note;
|
||||
return typeof note === 'string' && note.trim() !== '' ? note.trim() : null;
|
||||
}
|
||||
|
||||
/** Every day the answer's weather steps looked up, one entry per date (the later look wins), by date. */
|
||||
function weatherDays(parts: readonly AssistantMessagePart[]): AssistantWeatherDay[] {
|
||||
const byDate = new Map<string, AssistantWeatherDay>();
|
||||
@@ -256,7 +306,9 @@ export function messageBlocks(
|
||||
|
||||
// An answer about a tour shows the tour, not the places its searches went through to find it.
|
||||
const changeCards = message.parts.flatMap((p) => (p.type === 'data-trek-change' && p.data.card ? [p.data.card] : []));
|
||||
const placesHidden = [...cards.values(), ...changeCards].some((card) => rules.hidesFoundPlaces?.(card) === true);
|
||||
const placesHidden =
|
||||
[...cards.values(), ...changeCards].some((card) => rules.hidesFoundPlaces?.(card) === true) ||
|
||||
message.parts.some((p) => p.type === 'tool-call' && TOUR_PLANNING_TOOLS.has(p.toolName));
|
||||
const blocks: MessageBlock[] = [];
|
||||
message.parts.forEach((part, index) => {
|
||||
if (part.type === 'text') {
|
||||
@@ -265,8 +317,13 @@ export function messageBlocks(
|
||||
}
|
||||
if (part.type === 'data-trek-places' && index === lastPlaces && !placesHidden) {
|
||||
const found = allFound(message.parts);
|
||||
const places = found.places.filter((place) => !proposed(place, effects));
|
||||
if (places.length > 0) blocks.push({ kind: 'places', key: `places-${index}`, found: { ...found, places } });
|
||||
const text = message.parts.map((p) => (p.type === 'text' ? p.text : '')).join(' ');
|
||||
const places = namedFirst(
|
||||
found.places.filter((place) => !proposed(place, effects)),
|
||||
text
|
||||
);
|
||||
if (places && places.length > 0)
|
||||
blocks.push({ kind: 'places', key: `places-${index}`, found: { ...found, places } });
|
||||
return;
|
||||
}
|
||||
if (part.type === 'data-trek-weather' && index === firstWeather) {
|
||||
@@ -286,6 +343,11 @@ export function messageBlocks(
|
||||
pushChange(blocks, item, fromStrip);
|
||||
return;
|
||||
}
|
||||
const note = rememberedNote(part);
|
||||
if (note !== null) {
|
||||
blocks.push({ kind: 'remembered', key: `remembered-${part.toolCallId}`, note });
|
||||
return;
|
||||
}
|
||||
const step: ToolStep = {
|
||||
toolCallId: part.toolCallId,
|
||||
toolName: part.toolName,
|
||||
|
||||
@@ -134,7 +134,7 @@ function BodySlot({ item, settled }: { item: ChangeItem; settled: boolean }) {
|
||||
const view = item.card ? viewOf(item.card) : null;
|
||||
if (!view?.Body || !item.card) return null;
|
||||
return (
|
||||
<div className={`pb-1.5 ps-[38px] ${settled ? 'opacity-60' : ''}`}>
|
||||
<div className={`mt-1.5 pb-1.5 ${view.wideBody ? '' : 'ps-[38px]'} ${settled ? 'opacity-60' : ''}`}>
|
||||
<Slot item={item} view={view} name="Body" />
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { AssistantMessage, AtlasCountryCard as CountryCard } from '@trek/shared';
|
||||
import { Briefcase, MapPin, Radio } from 'lucide-react';
|
||||
import { Briefcase, Globe2, MapPin, Radio } from 'lucide-react';
|
||||
|
||||
import { useTranslation } from '../../../../i18n';
|
||||
import { SoftPill, WhiteBadge } from '../../../Planner/planParts';
|
||||
@@ -8,8 +8,10 @@ import type { ChangeItem } from '../../assistantParts';
|
||||
import type { CardEntry } from '../cardTypes';
|
||||
import { CardFacts } from '../parts/CardFacts';
|
||||
import CardFrame from '../parts/CardFrame';
|
||||
import CardHeader from '../parts/CardHeader';
|
||||
import { CardOpenButton } from '../parts/CardOpen';
|
||||
import { CardMore } from '../parts/CardRows';
|
||||
import { CardFoot } from '../parts/CardSection';
|
||||
import { CONTINENT_LABEL, continentOf, shortDay, STATUS_LOOK } from './atlasCardModel';
|
||||
import { ATLAS_PAGE } from './atlasPage';
|
||||
import { ChangeFlag, FlagTile, StatusFact } from './AtlasParts';
|
||||
@@ -112,14 +114,15 @@ export default function AtlasCountryBlock({ cards }: { cards: readonly CardEntry
|
||||
if (countries.length === 0) return null;
|
||||
return (
|
||||
<CardFrame label={t('assistant.domain.atlas')}>
|
||||
<CardHeader icon={Globe2} tone="info" title={t('assistant.domain.atlas')} />
|
||||
{countries.map((entry, index) => (
|
||||
<div key={entry.toolCallId} className={index > 0 ? 'mt-2 border-t border-edge-faint pt-2' : ''}>
|
||||
{entry.card.kind === 'atlasCountry' && <CountrySection card={entry.card} />}
|
||||
</div>
|
||||
))}
|
||||
<div className="mt-1 flex justify-end">
|
||||
<CardFoot>
|
||||
<CardOpenButton target={ATLAS_PAGE} labelKey="assistant.card.atlas.open" />
|
||||
</div>
|
||||
</CardFoot>
|
||||
</CardFrame>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -78,7 +78,6 @@ export function ExpenseFacts({ card }: SlotProps) {
|
||||
<>
|
||||
<CategoryFact row={row} />
|
||||
<DateFact row={row} />
|
||||
{row.place && <PlaceFact place={row.place} />}
|
||||
{split && (
|
||||
<FactChange
|
||||
icon={Tag}
|
||||
@@ -92,13 +91,16 @@ export function ExpenseFacts({ card }: SlotProps) {
|
||||
);
|
||||
}
|
||||
|
||||
/** The split under the row, and the expense's note under it: too long for the faint line beside the icons. */
|
||||
/** Under the row: the place it belongs to beside the split, and the expense's note under them. */
|
||||
export function ExpenseBody({ card }: SlotProps) {
|
||||
const row = card.rows[0];
|
||||
if (!row) return null;
|
||||
return (
|
||||
<span className="flex flex-col items-start gap-1">
|
||||
<SplitLine row={row} />
|
||||
<span className="flex flex-col items-start gap-1.5">
|
||||
<span className="flex flex-wrap items-center gap-1.5">
|
||||
{row.place && <PlaceFact place={row.place} />}
|
||||
<SplitLine row={row} />
|
||||
</span>
|
||||
{row.note && <NotePill note={row.note} />}
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -121,8 +121,7 @@ describe('an expense in a change row', () => {
|
||||
expect(screen.getByText(money(84))).toHaveClass('line-through');
|
||||
});
|
||||
|
||||
it('FE-AI-CARD-BUD-012: the facts name the category, day and place, and what an update changes', () => {
|
||||
const onOpen = vi.fn();
|
||||
it('FE-AI-CARD-BUD-012: the facts name the category and day, and what an update changes', () => {
|
||||
const update = expense({
|
||||
category: 'transport',
|
||||
date: '2026-06-05',
|
||||
@@ -132,7 +131,7 @@ describe('an expense in a change row', () => {
|
||||
split: 'equal',
|
||||
before: { name: null, amount: null, category: 'food', date: '2026-06-03', split: 'custom' },
|
||||
});
|
||||
inView(<ExpenseFacts card={expenses([update])} item={changeItem('a', null)} />, { onOpen });
|
||||
inView(<ExpenseFacts card={expenses([update])} item={changeItem('a', null)} />);
|
||||
expect(screen.getByText('Food & drink')).toHaveClass('line-through');
|
||||
expect(screen.getByText('Transport')).toBeInTheDocument();
|
||||
expect(screen.getByText('Split unevenly')).toHaveClass('line-through');
|
||||
@@ -140,6 +139,14 @@ describe('an expense in a change row', () => {
|
||||
expect(screen.getByText('1 receipt')).toBeInTheDocument();
|
||||
// The note is too long for the faint line beside the row's buttons: it sits under the row.
|
||||
expect(screen.queryByText('Window table')).toBeNull();
|
||||
// The place sits under the row, beside the split.
|
||||
expect(screen.queryByText('Lokanta')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-AI-CARD-BUD-012c: the place sits under the row beside the split, and opens on the map', () => {
|
||||
const onOpen = vi.fn();
|
||||
const row = expense({ place: { id: 12, name: 'Lokanta' } });
|
||||
inView(<ExpenseBody card={expenses([row])} item={changeItem('a', null)} />, { onOpen });
|
||||
fireEvent.click(screen.getByRole('button', { name: /Lokanta/ }));
|
||||
expect(onOpen).toHaveBeenCalledWith({ kind: 'map', placeId: 12, dayId: null });
|
||||
});
|
||||
|
||||
@@ -126,6 +126,8 @@ export interface CardView<K extends TrekCardKind> {
|
||||
Facts?: ComponentType<CardSlotProps<K>>;
|
||||
Body?: ComponentType<CardSlotProps<K>>;
|
||||
ownsSubject?: boolean;
|
||||
/** The body runs the whole width of the change card instead of under the row's text (a tour's drawing). */
|
||||
wideBody?: boolean;
|
||||
Group?: ComponentType<CardRunProps & { place: 'head' | 'foot' }>;
|
||||
Run?: ComponentType<CardRunProps>;
|
||||
runnable?(card: TrekCardOf<K>): boolean;
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import type { AssistantMessage, JourneyEntryLook } from '@trek/shared';
|
||||
import { ArrowUpRight } from 'lucide-react';
|
||||
import { ArrowUpRight, BookOpen } from 'lucide-react';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { useTranslation } from '../../../../i18n';
|
||||
import { DAY_COLORS } from '../../../Journey/dayColors';
|
||||
import { cardTitle } from '../../../Journey/journeyCard';
|
||||
import JourneyEntryCover from '../../../Journey/JourneyEntryCover';
|
||||
import { LinkedJournalIcon } from '../../../Trips/LinkedJournalIcon';
|
||||
import { useAssistantView } from '../../assistantViewContext';
|
||||
import type { CardEntry } from '../cardTypes';
|
||||
import CardFrame from '../parts/CardFrame';
|
||||
import CardHeader from '../parts/CardHeader';
|
||||
import { CardFoot } from '../parts/CardSection';
|
||||
import CardStrip from '../parts/CardStrip';
|
||||
import { type JournalEntries, coverEntryOf, mergeJournalCards, titleSourceOf } from './journeyCardModel';
|
||||
import { EntryMarks, EntryStory, EntryThumb, EntryWhen } from './JourneyEntryParts';
|
||||
@@ -33,9 +34,6 @@ const TITLE_BUTTON =
|
||||
'block w-full rounded-md text-start outline-none hover:underline focus-visible:ring-2 focus-visible:ring-accent';
|
||||
/** The phone's taller target, the title still at the top of the row. */
|
||||
const TITLE_BUTTON_TALL = `${TITLE_BUTTON} min-h-10`;
|
||||
const FOOTER = 'mt-1 flex items-center gap-2 border-t border-edge-faint pt-2 text-caption';
|
||||
const FOOTER_TITLE = 'min-w-0 flex-1 truncate text-content-muted';
|
||||
const FAINT = 'text-content-faint';
|
||||
const OPEN = 'inline-flex flex-none items-center gap-1 font-medium text-accent hover:underline';
|
||||
const OPEN_TALL = 'inline-flex h-10 flex-none items-center gap-1 font-medium text-accent hover:underline';
|
||||
/** The size and corners of the journal's own tile, so the count stands in the row like one more entry. */
|
||||
@@ -47,29 +45,40 @@ const TILE = 'flex-none snap-start';
|
||||
|
||||
type Open = ((entryId: number | null) => void) | null;
|
||||
|
||||
/** The journal's name and the way into it, under the card. */
|
||||
function JournalFooter({ journal, open }: { journal: JournalEntries; open: Open }) {
|
||||
/**
|
||||
* The way into the journal under its entries: in the foot bar of the card, or
|
||||
* under the strip of tiles with how many entries it holds, which the strip
|
||||
* has no band to say.
|
||||
*/
|
||||
function JournalFooter({ open, count }: { open: Open; count?: number }) {
|
||||
const { t } = useTranslation();
|
||||
const { variant } = useAssistantView();
|
||||
const title = journal.journalTitle ?? t('assistant.card.journey.label');
|
||||
const count = journal.entries.length + journal.more;
|
||||
const button = open && (
|
||||
<button type="button" onClick={() => open(null)} className={variant === 'fullscreen' ? OPEN_TALL : OPEN}>
|
||||
{t('assistant.card.journey.open')}
|
||||
<ArrowUpRight size={12} aria-hidden="true" className="rtl:-scale-x-100" />
|
||||
</button>
|
||||
);
|
||||
if (count === undefined) return button ? <CardFoot>{button}</CardFoot> : null;
|
||||
return (
|
||||
<div className={FOOTER}>
|
||||
<LinkedJournalIcon size={12} className={FAINT} />
|
||||
<span title={title} className={FOOTER_TITLE}>
|
||||
<bdi>{title}</bdi>
|
||||
{count > 2 && <span className="ms-1.5 tabular-nums">{t('assistant.card.journey.entries', { count })}</span>}
|
||||
<div className="mt-1 flex items-center gap-2 text-caption">
|
||||
<span className="min-w-0 flex-1 truncate tabular-nums text-content-muted">
|
||||
{t('assistant.card.journey.entries', { count })}
|
||||
</span>
|
||||
{open && (
|
||||
<button type="button" onClick={() => open(null)} className={variant === 'fullscreen' ? OPEN_TALL : OPEN}>
|
||||
{t('assistant.card.journey.open')}
|
||||
<ArrowUpRight size={12} aria-hidden="true" className="rtl:-scale-x-100" />
|
||||
</button>
|
||||
)}
|
||||
{button}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The band of the entries: the journal's name, and how many entries it holds once there are more than two. */
|
||||
function JournalHead({ journal }: { journal: JournalEntries }) {
|
||||
const { t } = useTranslation();
|
||||
const title = journal.journalTitle ?? t('assistant.card.journey.label');
|
||||
const count = journal.entries.length + journal.more;
|
||||
const meta = count > 2 ? t('assistant.card.journey.entries', { count }) : undefined;
|
||||
return <CardHeader icon={BookOpen} tone="info" title={title} meta={meta} />;
|
||||
}
|
||||
|
||||
/** One entry as a row: its photo, its title (the way to it), its facts and the start of its text. */
|
||||
function EntryRow({
|
||||
look,
|
||||
@@ -116,10 +125,11 @@ function JournalRows({ journal, fallbackRef }: { journal: JournalEntries; fallba
|
||||
const hover = useEntryHover(journal.journeyId, fallbackRef);
|
||||
return (
|
||||
<CardFrame label={t('assistant.card.journey.label')}>
|
||||
<JournalHead journal={journal} />
|
||||
{journal.entries.map((look, index) => (
|
||||
<EntryRow key={look.entryId ?? `new-${index}`} look={look} divided={index > 0} open={open} hover={hover} />
|
||||
))}
|
||||
<JournalFooter journal={journal} open={open} />
|
||||
<JournalFooter open={open} />
|
||||
</CardFrame>
|
||||
);
|
||||
}
|
||||
@@ -152,7 +162,7 @@ function JournalStrip({ journal, fallbackRef }: { journal: JournalEntries; fallb
|
||||
</li>
|
||||
)}
|
||||
</CardStrip>
|
||||
<JournalFooter journal={journal} open={open} />
|
||||
<JournalFooter open={open} count={journal.entries.length + journal.more} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import type { PackingListCard as PackingCard, PackingCardGroup } from '@trek/shared';
|
||||
import { Check } from 'lucide-react';
|
||||
import { Backpack, Check } from 'lucide-react';
|
||||
|
||||
import { useTranslation } from '../../../../i18n';
|
||||
import { SoftPill } from '../../../Planner/planParts';
|
||||
import { PackedBar, PackTile } from '../../../Tours/packing/packingLinkParts';
|
||||
import { PackedBar } from '../../../Tours/packing/packingLinkParts';
|
||||
import AssistantChangeFields from '../../AssistantChangeFields';
|
||||
import type { ChangeItem } from '../../assistantParts';
|
||||
import type { CardEntry, EntityTarget } from '../cardTypes';
|
||||
import CardFrame from '../parts/CardFrame';
|
||||
import { isRunnable, mergePackingCards, packingColorOf, rowCount } from './checklistModel';
|
||||
import CardHeader from '../parts/CardHeader';
|
||||
import { CardFoot } from '../parts/CardSection';
|
||||
import { isRunnable, mergePackingCards, rowCount } from './checklistModel';
|
||||
import { ChecklistFoot, ChecklistRun, type RunEntry, type RunProps } from './checklistParts';
|
||||
import { PackingGroup, PackingRowAside, PackingRowFacts } from './packingParts';
|
||||
|
||||
@@ -62,7 +64,7 @@ function useTitle(card: PackingCard): string {
|
||||
: t('assistant.card.packing.title');
|
||||
}
|
||||
|
||||
/** The head of an answer: the tile with the count, the title, how much is packed, and "All packed" once it is. */
|
||||
/** The head band of an answer: the backpack, the title, how much is packed with its bar, and "All packed" once it is. */
|
||||
function PackingHead({ card }: { card: PackingCard }) {
|
||||
const { t } = useTranslation();
|
||||
const title = useTitle(card);
|
||||
@@ -73,50 +75,46 @@ function PackingHead({ card }: { card: PackingCard }) {
|
||||
if (source.type === 'tour') caption = t('assistant.card.packing.forTour');
|
||||
else if (source.type === 'template') caption = t('assistant.card.packing.templateAdds', { count: source.itemCount });
|
||||
else if (card.progress && total > 0) caption = t('tours.packing.packed', { packed, count: total });
|
||||
const first = card.groups[0]?.key;
|
||||
const color =
|
||||
source.type === 'tour' && source.category !== null && first?.by === 'category'
|
||||
? packingColorOf(first.slot, source.category)
|
||||
: null;
|
||||
const done = card.progress !== null && total > 0 && packed === total;
|
||||
return (
|
||||
<div className="flex min-w-0 items-center gap-2.5">
|
||||
<PackTile count={source.type === 'template' ? source.itemCount : total} color={color} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<p title={title} className="m-0 line-clamp-2 text-body font-semibold leading-tight text-content">
|
||||
{title}
|
||||
</p>
|
||||
{caption && (
|
||||
<p title={caption} className="m-0 truncate text-caption text-content-faint">
|
||||
{caption}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{card.progress && total > 0 && packed === total && (
|
||||
<SoftPill tone="success" icon={<Check size={11} strokeWidth={2.4} className="flex-none" />}>
|
||||
{t('tours.packing.allPacked')}
|
||||
</SoftPill>
|
||||
<CardHeader
|
||||
icon={Backpack}
|
||||
tone={done ? 'success' : 'info'}
|
||||
title={title}
|
||||
count={source.type === 'template' ? source.itemCount : total}
|
||||
meta={caption ?? undefined}
|
||||
actions={
|
||||
done ? (
|
||||
<SoftPill tone="success" icon={<Check size={11} strokeWidth={2.4} className="flex-none" />}>
|
||||
{t('tours.packing.allPacked')}
|
||||
</SoftPill>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
{card.progress && card.progress.total > 0 && (
|
||||
<div className="mt-2.5">
|
||||
<PackedBar packed={card.progress.packed} total={card.progress.total} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
);
|
||||
}
|
||||
|
||||
/** One answer card. */
|
||||
function PackingAnswer({ card }: { card: PackingCard }) {
|
||||
const title = useTitle(card);
|
||||
const progress = card.progress;
|
||||
return (
|
||||
<CardFrame label={title}>
|
||||
<div className="flex min-w-0 flex-col gap-2.5">
|
||||
<PackingHead card={card} />
|
||||
{progress && progress.total > 0 && <PackedBar packed={progress.packed} total={progress.total} />}
|
||||
<PackingGroups card={card} inChange={false} />
|
||||
<PackingHead card={card} />
|
||||
<PackingGroups card={card} inChange={false} />
|
||||
<CardFoot>
|
||||
<ChecklistFoot
|
||||
more={card.moreGroups}
|
||||
moreKey={MORE_GROUPS[card.groupBy].labelKey}
|
||||
target={PACKING_TARGET}
|
||||
openKey="tours.packing.open"
|
||||
/>
|
||||
</div>
|
||||
</CardFoot>
|
||||
</CardFrame>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,14 +6,15 @@ import { type PillTone, SoftPill, WhiteBadge } from '../../../Planner/planParts'
|
||||
import { localToday } from '../../../Planner/today';
|
||||
import { Tooltip } from '../../../shared/Tooltip';
|
||||
import { PRIO_CONFIG } from '../../../Todo/todoListModel';
|
||||
import { PackTile } from '../../../Tours/packing/packingLinkParts';
|
||||
import AssistantChangeFields from '../../AssistantChangeFields';
|
||||
import type { ChangeItem } from '../../assistantParts';
|
||||
import { useAssistantView } from '../../assistantViewContext';
|
||||
import type { CardEntry, EntityTarget } from '../cardTypes';
|
||||
import { ChangeMark, FactChange, NoLonger } from '../parts/CardFacts';
|
||||
import CardFrame from '../parts/CardFrame';
|
||||
import CardHeader from '../parts/CardHeader';
|
||||
import { PersonFace } from '../parts/CardPeople';
|
||||
import { CardFoot } from '../parts/CardSection';
|
||||
import { useCardFormat } from '../parts/useCardFormat';
|
||||
import { isRunnable, mergeTodoCards, todoColorOf } from './checklistModel';
|
||||
import {
|
||||
@@ -204,27 +205,30 @@ function TodoAnswer({ card }: { card: TodoCard }) {
|
||||
const title = t('assistant.card.todo.title');
|
||||
return (
|
||||
<CardFrame label={title}>
|
||||
<div className="flex min-w-0 flex-col gap-2.5">
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2.5">
|
||||
<PackTile count={progress?.open ?? 0} color={null} icon={ListTodo} />
|
||||
<p className="m-0 text-body font-semibold leading-tight text-content">{title}</p>
|
||||
{progress && <SoftPill>{t('assistant.card.todo.openCount', { count: progress.open })}</SoftPill>}
|
||||
{progress && progress.overdue > 0 && (
|
||||
<CardHeader
|
||||
icon={ListTodo}
|
||||
tone={progress && progress.overdue > 0 ? 'danger' : 'info'}
|
||||
title={title}
|
||||
meta={progress ? t('assistant.card.todo.openCount', { count: progress.open }) : undefined}
|
||||
actions={
|
||||
progress && progress.overdue > 0 ? (
|
||||
<SoftPill tone="danger">{t('assistant.card.todo.overdueCount', { count: progress.overdue })}</SoftPill>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-col gap-1.5">
|
||||
{card.groups.map((group) => (
|
||||
<TodoGroup key={group.category ?? ''} group={group} inChange={false} />
|
||||
))}
|
||||
</div>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
<div className="flex min-w-0 flex-col gap-1.5">
|
||||
{card.groups.map((group) => (
|
||||
<TodoGroup key={group.category ?? ''} group={group} inChange={false} />
|
||||
))}
|
||||
</div>
|
||||
<CardFoot>
|
||||
<ChecklistFoot
|
||||
more={card.moreGroups}
|
||||
moreKey="assistant.card.todo.moreLists"
|
||||
target={TODO_TARGET}
|
||||
openKey="assistant.card.todo.open"
|
||||
/>
|
||||
</div>
|
||||
</CardFoot>
|
||||
</CardFrame>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -90,7 +90,7 @@ export function ChecklistRow({
|
||||
>
|
||||
{name}
|
||||
</bdi>
|
||||
{aside && <span className="flex flex-none flex-wrap items-center justify-end gap-1">{aside}</span>}
|
||||
{aside && <span className="flex flex-none flex-wrap items-center justify-end gap-x-2 gap-y-1">{aside}</span>}
|
||||
</div>
|
||||
{under}
|
||||
</div>
|
||||
|
||||
@@ -7,7 +7,6 @@ import { formatWeight } from '../../../Packing/packingListModel';
|
||||
import { bagFillPct } from '../../../Packing/packingListPanel.helpers';
|
||||
import { SoftPill, WhiteBadge } from '../../../Planner/planParts';
|
||||
import { Tooltip } from '../../../shared/Tooltip';
|
||||
import { CountBadge } from '../../../Tours/packing/packingLinkParts';
|
||||
import { ChangeMark, FactChange, NoLonger } from '../parts/CardFacts';
|
||||
import { PeopleStack, PersonFace } from '../parts/CardPeople';
|
||||
import { packingColorOf } from './checklistModel';
|
||||
@@ -56,15 +55,31 @@ function BagSwatch({ bag, size = 'row' }: { bag: PackingCardBag | undefined; siz
|
||||
* What a row says at its end: how many, how many packed, its weight, its tier
|
||||
* and its bag. A bag the card does not carry draws nothing rather than "Unassigned".
|
||||
*/
|
||||
/** A row's quantity and weight: quiet figures at its end, no frame each. */
|
||||
const QUIET = 'text-caption tabular-nums text-content-muted';
|
||||
|
||||
/** How many rows a group holds, quiet beside its name. */
|
||||
function GroupCount({ count }: { count: number }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<span
|
||||
aria-label={t('tours.packing.items', { count })}
|
||||
className="flex-none text-caption tabular-nums text-content-faint"
|
||||
>
|
||||
{count}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function PackingRowAside({ row, bag }: { row: PackingCardItem; bag: PackingCardBag | undefined }) {
|
||||
const { t } = useTranslation();
|
||||
const personal = t('assistant.card.packing.tierPersonal');
|
||||
const partial = !row.checked && row.packed > 0 && row.packed < row.quantity;
|
||||
return (
|
||||
<>
|
||||
{row.quantity > 1 && <WhiteBadge>×{row.quantity}</WhiteBadge>}
|
||||
{partial && <WhiteBadge>{`${row.packed}/${row.quantity}`}</WhiteBadge>}
|
||||
{row.weightGrams !== null && <WhiteBadge>{formatWeight(row.weightGrams)}</WhiteBadge>}
|
||||
{row.quantity > 1 && <span className={QUIET}>×{row.quantity}</span>}
|
||||
{partial && <span className={QUIET}>{`${row.packed}/${row.quantity}`}</span>}
|
||||
{row.weightGrams !== null && <span className={QUIET}>{formatWeight(row.weightGrams)}</span>}
|
||||
{row.tier === 'personal' && (
|
||||
<Tooltip label={personal}>
|
||||
<span role="img" aria-label={personal} className="flex text-content-faint">
|
||||
@@ -216,7 +231,7 @@ function BagHead({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
if (!bag) {
|
||||
const badge = inChange ? undefined : <CountBadge count={group.count} />;
|
||||
const badge = inChange ? undefined : <GroupCount count={group.count} />;
|
||||
const lead = <BagSwatch bag={undefined} size="head" />;
|
||||
return <ChecklistHead color="" name={t('packing.noBag')} lead={lead} badge={badge} />;
|
||||
}
|
||||
@@ -283,7 +298,7 @@ export function PackingGroup({
|
||||
<ChecklistHead
|
||||
color={packingColorOf(key.slot, name)}
|
||||
name={name}
|
||||
badge={inChange ? undefined : <CountBadge count={group.count} />}
|
||||
badge={inChange ? undefined : <GroupCount count={group.count} />}
|
||||
people={group.assignees}
|
||||
removed={group.assigneesRemoved}
|
||||
/>
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { ReactNode } from 'react';
|
||||
|
||||
/**
|
||||
* The frame every answer card sits in, the same as the change card's: a
|
||||
* rounded card on the chat. A waiting change shows its frame dashed, a
|
||||
* rounded card on the chat whose head band (CardHeader) runs to its edges. A waiting change shows its frame dashed, a
|
||||
* removed one faded, a settled one (discarded, expired, undone) fainter
|
||||
* still. The chat card (a message in the trip chat) sits on the quieter
|
||||
* secondary surface.
|
||||
@@ -32,7 +32,7 @@ export default function CardFrame({
|
||||
return (
|
||||
<section
|
||||
aria-label={label}
|
||||
className={`trek-assistant-enter rounded-xl border px-3 pb-2 pt-2.5 shadow-card ${STATE[state]} ${
|
||||
className={`trek-assistant-enter overflow-hidden rounded-[16px] border px-3.5 pb-3 pt-3 shadow-card ${STATE[state]} ${
|
||||
surface === 'secondary' ? 'bg-surface-secondary' : 'bg-surface-card'
|
||||
}`}
|
||||
>
|
||||
|
||||
@@ -1,43 +1,94 @@
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
import { WhiteBadge } from '../../../Planner/planParts';
|
||||
import { fs, NEUTRAL_TINT } from '../../../shared/DialogShell';
|
||||
import type { Tone } from './assistantTones';
|
||||
import KindTile from './KindTile';
|
||||
|
||||
/**
|
||||
* The head of an answer card: its tile, what it is about (wrapping to two
|
||||
* lines at most, the whole title in its tooltip), how many it holds, one
|
||||
* quiet line of context under it, and its actions at the end.
|
||||
* The head band of an answer card, as the trip's dialogs and booking cards
|
||||
* wear it: a tinted band across the card's top, a raised white tile with the
|
||||
* icon of what the card is about in its tone, an eyebrow naming the kind,
|
||||
* the title, one quiet line under it, a count, and the card's actions at the
|
||||
* end. It reaches the card's edges, so a card that opens with it needs no
|
||||
* other head.
|
||||
*/
|
||||
|
||||
/** The icon's colour on the white tile, per tone. */
|
||||
const GLYPH: Record<Tone, string> = {
|
||||
success: 'text-success',
|
||||
info: 'text-info',
|
||||
warning: 'text-warning',
|
||||
danger: 'text-danger',
|
||||
};
|
||||
|
||||
export default function CardHeader({
|
||||
icon,
|
||||
icon: Icon,
|
||||
tone,
|
||||
title,
|
||||
eyebrow,
|
||||
count,
|
||||
meta,
|
||||
actions,
|
||||
tile,
|
||||
tint = NEUTRAL_TINT,
|
||||
children,
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
tone: Tone;
|
||||
title: string;
|
||||
/** The kind above the title ("PACKING LIST"); none when the title says it. */
|
||||
eyebrow?: string;
|
||||
count?: number;
|
||||
meta?: ReactNode;
|
||||
actions?: ReactNode;
|
||||
/** In place of the icon tile: a drawing of what the card shows (a route's sketch). */
|
||||
tile?: ReactNode;
|
||||
tint?: string;
|
||||
/** Under the title row, on the band: a progress bar, a row of pills. */
|
||||
children?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex items-start gap-2.5">
|
||||
<KindTile icon={icon} tone={tone} size="sm" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex min-w-0 items-center gap-1.5">
|
||||
<bdi title={title} className="line-clamp-2 text-body font-semibold leading-tight text-content">
|
||||
{title}
|
||||
</bdi>
|
||||
{count !== undefined && <WhiteBadge>{count}</WhiteBadge>}
|
||||
<div className="-mx-3.5 -mt-3 mb-3 px-3.5 pb-2.5 pt-2.5" style={{ background: tint }}>
|
||||
<div className={`flex gap-2.5 ${meta ? 'items-start' : 'items-center'}`}>
|
||||
{tile ?? (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={`grid h-8 w-8 flex-none place-items-center rounded-[10px] bg-surface-card shadow-sm ${GLYPH[tone]}`}
|
||||
>
|
||||
<Icon size={15} strokeWidth={2} />
|
||||
</span>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
{eyebrow && (
|
||||
<div
|
||||
className="truncate font-geist font-bold uppercase tracking-[.08em] text-content-muted"
|
||||
style={fs(9.5)}
|
||||
>
|
||||
{eyebrow}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<bdi
|
||||
title={title}
|
||||
className="line-clamp-2 min-w-0 font-bold leading-tight tracking-[-0.01em] text-content"
|
||||
style={fs(13.5, 'body')}
|
||||
>
|
||||
{title}
|
||||
</bdi>
|
||||
{count !== undefined && (
|
||||
<span
|
||||
className="inline-flex h-[18px] flex-none items-center rounded-full bg-surface-card px-1.5 font-semibold tabular-nums text-content-secondary shadow-sm"
|
||||
style={fs(10.5)}
|
||||
>
|
||||
{count}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{meta && <div className="mt-0.5 font-geist text-caption text-content-muted">{meta}</div>}
|
||||
</div>
|
||||
{meta && <div className="mt-0.5 text-caption text-content-muted">{meta}</div>}
|
||||
{actions && <div className="flex flex-none items-center gap-1">{actions}</div>}
|
||||
</div>
|
||||
{actions && <div className="flex flex-none items-center gap-1">{actions}</div>}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -44,7 +44,11 @@ export function CardRow({
|
||||
<span className="block text-body font-semibold leading-tight text-content">{title}</span>
|
||||
{facts}
|
||||
</span>
|
||||
{aside && <span className="flex-none text-caption tabular-nums text-content-secondary">{aside}</span>}
|
||||
{aside && (
|
||||
<span className="flex flex-none items-center gap-2 text-caption tabular-nums text-content-secondary">
|
||||
{aside}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
const hover = onHover
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
import { Eyebrow, Field } from '../../../Planner/bookings/bookingParts';
|
||||
|
||||
/**
|
||||
* The body of an answer card in the trip dialogs' look: sections under an
|
||||
* eyebrow of their own, figures as framed fields with their label over them
|
||||
* (the field every booking card is made of), and a foot bar for the card's
|
||||
* ways onward, set off by a line across the card.
|
||||
*/
|
||||
|
||||
/** One part of a card under its eyebrow, with room for something on the right of the label. */
|
||||
export function CardSection({ label, aside, children }: { label: string; aside?: ReactNode; children: ReactNode }) {
|
||||
return (
|
||||
<section className="mt-3 first:mt-0">
|
||||
<div className="mb-1.5 flex min-h-4 items-center gap-2">
|
||||
<Eyebrow>{label}</Eyebrow>
|
||||
{aside && <span className="ms-auto flex items-center gap-1">{aside}</span>}
|
||||
</div>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** A card's figures, side by side in framed fields: as many columns as figures, at most four. */
|
||||
export function CardFields({ fields }: { fields: readonly { key: string; label: string; value: ReactNode }[] }) {
|
||||
if (fields.length === 0) return null;
|
||||
const columns = ['grid-cols-1', 'grid-cols-2', 'grid-cols-3', 'grid-cols-4'][Math.min(fields.length, 4) - 1];
|
||||
return (
|
||||
<div className={`grid gap-1.5 ${columns}`}>
|
||||
{fields.map((field) => (
|
||||
<div key={field.key} className="min-w-0" data-field={field.key}>
|
||||
<Field label={field.label} tabular>
|
||||
{field.value}
|
||||
</Field>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The foot of a card: its actions at the end, under a line that runs to the card's edges. */
|
||||
export function CardFoot({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div className="-mx-3.5 -mb-3 mt-3 flex flex-wrap items-center justify-end gap-1.5 border-t border-edge-faint bg-surface-secondary px-3.5 py-2.5">
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Clock, MoveHorizontal, TrendingUp } from 'lucide-react';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
import type { DistanceUnit } from '../../../../types';
|
||||
import { formatDistance, formatElevation } from '../../../../utils/units';
|
||||
import type { LegVariant } from '../../../Tours/planner/legVariants';
|
||||
import { formatTourDuration } from '../../../Tours/planner/tourDurationInput';
|
||||
|
||||
/**
|
||||
* A way's length, climb and time as one quiet line of glyphs and values,
|
||||
* without a frame around each: what a choice of ways and a change row show
|
||||
* where framed fields would crowd the row.
|
||||
*/
|
||||
|
||||
/** One figure of a way: its glyph and its value, quiet, in a line of them. */
|
||||
function Figure({ name, icon, children }: { name: string; icon: ReactNode; children: ReactNode }) {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 whitespace-nowrap" data-figure={name}>
|
||||
{icon}
|
||||
<span className="tabular-nums">{children}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const GLYPH = { size: 11, strokeWidth: 2.2, 'aria-hidden': true, className: 'flex-none text-content-faint' } as const;
|
||||
|
||||
/** A way's length, climb and time in one quiet line. */
|
||||
export default function WayFigures({ way, unit }: { way: LegVariant; unit: DistanceUnit }) {
|
||||
return (
|
||||
<span className="flex flex-wrap items-center gap-x-3 gap-y-0.5 text-caption text-content-secondary">
|
||||
<Figure name="distance" icon={<MoveHorizontal {...GLYPH} />}>
|
||||
{formatDistance(way.distanceM / 1000, unit)}
|
||||
</Figure>
|
||||
{way.gainM !== null && (
|
||||
<Figure name="ascent" icon={<TrendingUp {...GLYPH} />}>
|
||||
{formatElevation(way.gainM, unit)}
|
||||
</Figure>
|
||||
)}
|
||||
{way.minutes !== null && (
|
||||
<Figure name="time" icon={<Clock {...GLYPH} />}>
|
||||
{formatTourDuration(way.minutes)}
|
||||
</Figure>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { useTranslation } from '../../../../i18n';
|
||||
import { SoftPill } from '../../../Planner/planParts';
|
||||
import { useAssistantView } from '../../assistantViewContext';
|
||||
import { CardOpenButton } from '../parts/CardOpen';
|
||||
import { CardFoot } from '../parts/CardSection';
|
||||
import { tourTarget } from './tourLook';
|
||||
import { useTakeProposal } from './useTourRouteCard';
|
||||
|
||||
@@ -58,7 +59,7 @@ export default function TourRouteActions({
|
||||
if (take.state === 'failed') caption = t('assistant.card.tour.askAgain');
|
||||
else if (take.state !== 'taken' && take.reasonKey) caption = t(take.reasonKey);
|
||||
return (
|
||||
<div className="mt-2.5 flex flex-col items-end gap-1">
|
||||
<CardFoot>
|
||||
<div className="flex flex-wrap items-center justify-end gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
@@ -92,10 +93,10 @@ export default function TourRouteActions({
|
||||
)}
|
||||
</div>
|
||||
{take.visible && caption && (
|
||||
<p className="m-0 text-end text-caption text-content-muted" role="status">
|
||||
<p className="m-0 basis-full text-end text-caption text-content-muted" role="status">
|
||||
{caption}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</CardFoot>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -115,11 +115,11 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe('TourRouteCard', () => {
|
||||
it('FE-AI-TOUR-021: states the name, the figures as badges, the day and the hardest grade, uncertain when little is graded', () => {
|
||||
it('FE-AI-TOUR-021: states the name, the figures as framed fields, the day and the hardest grade, uncertain when little is graded', () => {
|
||||
const { container } = renderCard(HIKE);
|
||||
expect(screen.getByText('Hochfelln from Bergen')).toBeInTheDocument();
|
||||
for (const figure of ['time', 'distance', 'ascent', 'descent']) {
|
||||
expect(container.querySelector(`[data-figure="${figure}"]`)).not.toBeNull();
|
||||
expect(container.querySelector(`[data-field="${figure}"]`)).not.toBeNull();
|
||||
}
|
||||
expect(screen.getByText('8.2 km')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('640 m')).toHaveLength(2);
|
||||
@@ -159,7 +159,7 @@ describe('TourRouteCard', () => {
|
||||
|
||||
it('FE-AI-TOUR-024: a stop chip moves the spot in focus to the stop while pointed at', () => {
|
||||
renderCard(HIKE);
|
||||
const hut = screen.getByRole('button', { name: 'Strausshütte, 09:40' });
|
||||
const hut = screen.getByRole('button', { name: /^Strausshütte, 09:40/ });
|
||||
fireEvent.mouseEnter(hut);
|
||||
expect(useAssistantStore.getState().routeFocus?.focus.distanceMeters).toBeCloseTo(2400, 0);
|
||||
fireEvent.mouseLeave(hut);
|
||||
@@ -171,11 +171,11 @@ describe('TourRouteCard', () => {
|
||||
it('FE-AI-TOUR-024b: the stops run as a timeline, each walk on the line between two stops and read with the one it leads to', () => {
|
||||
renderCard(HIKE);
|
||||
const list = screen.getByRole('list', { name: 'Stops along the way' });
|
||||
// One row per stop; the lines between them are not rows.
|
||||
expect(list.querySelectorAll('[role="listitem"]')).toHaveLength(5);
|
||||
// One row per stop; the walks between them are hidden, read with the stop they lead to.
|
||||
expect(list.querySelectorAll('li:not([aria-hidden="true"])')).toHaveLength(5);
|
||||
// The place beside the way has no time: the hut measures from the start, then each stop from the last.
|
||||
expect(screen.getAllByText(/from the last stop$/)).toHaveLength(3);
|
||||
const legs = [...list.querySelectorAll('[aria-hidden="true"]')].map((leg) => leg.textContent).filter(Boolean);
|
||||
expect(screen.getAllByRole('button', { name: /from the last stop$/ })).toHaveLength(3);
|
||||
const legs = [...list.querySelectorAll('li[aria-hidden="true"]')].map((leg) => leg.textContent).filter(Boolean);
|
||||
expect(legs).toHaveLength(3);
|
||||
});
|
||||
|
||||
@@ -234,18 +234,21 @@ describe('TourRouteCard', () => {
|
||||
const decide = vi.fn(async (_key: number, decisions: { toolCallId: string; approved: boolean }[]) => {
|
||||
// The server applies the take; the thread shows it applied with the new tour's place.
|
||||
const chat = chatOf(useAssistantStore.getState(), TRIP);
|
||||
const applied = heldTake(true);
|
||||
applied.parts.push({
|
||||
// The server sends the answer back with the take joined to it, now applied with the new tour's place.
|
||||
const applied = proposed();
|
||||
applied.parts.push(...heldTake(true).parts, {
|
||||
type: 'data-trek-applied',
|
||||
data: { toolCallId: decisions[0]?.toolCallId ?? '', entity: 'tour', ids: [77], dayId: 22, undoUntil: null },
|
||||
});
|
||||
useAssistantStore.setState({ byTrip: { [TRIP]: { ...chat, messages: [proposed(), applied] } } });
|
||||
useAssistantStore.setState({ byTrip: { [TRIP]: { ...chat, messages: [applied] } } });
|
||||
});
|
||||
seed([proposed()]);
|
||||
useAssistantStore.setState({ decide });
|
||||
takeProposal.mockImplementationOnce(async () => {
|
||||
const chat = chatOf(useAssistantStore.getState(), TRIP);
|
||||
useAssistantStore.setState({ byTrip: { [TRIP]: { ...chat, messages: [proposed(), heldTake(undefined)] } } });
|
||||
const joined = proposed();
|
||||
joined.parts.push(...heldTake(undefined).parts);
|
||||
useAssistantStore.setState({ byTrip: { [TRIP]: { ...chat, messages: [joined] } } });
|
||||
return 'held';
|
||||
});
|
||||
renderCard(HIKE, { onOpen });
|
||||
@@ -374,7 +377,7 @@ describe('TourRouteCard', () => {
|
||||
it('FE-AI-TOUR-042: the day shows the latest start when none is set, and the walk in the dark in red', () => {
|
||||
const schedule = HIKE.schedule as NonNullable<Route['schedule']>;
|
||||
renderCard({ ...HIKE, schedule: { ...schedule, start: null, arrive: null, latestStart: '10:30' } });
|
||||
expect(screen.getByText('Start by 10:30 to finish before sunset')).toBeInTheDocument();
|
||||
expect(screen.getByText('Start by 10:30')).toBeInTheDocument();
|
||||
|
||||
const { container } = renderCard({
|
||||
...HIKE,
|
||||
@@ -382,6 +385,6 @@ describe('TourRouteCard', () => {
|
||||
schedule: { ...schedule, start: '06:00', arrive: '19:00', latestStart: '10:30' },
|
||||
});
|
||||
expect(container.querySelectorAll('[data-testid="tour-day"] .bg-danger')).toHaveLength(2);
|
||||
expect(screen.getAllByText('Start by 10:30 to finish before sunset')).toHaveLength(1);
|
||||
expect(screen.getAllByText('Start by 10:30')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,11 +4,11 @@ import { useMemo } from 'react';
|
||||
import { useTranslation } from '../../../../i18n';
|
||||
import type { DistanceIndexedProfileSample } from '../../../../utils/routeGeometry';
|
||||
import { variantPaintCss } from '../../../Tours/planner/legVariantPaint';
|
||||
import { useAssistantView } from '../../assistantViewContext';
|
||||
import CardFrame from '../parts/CardFrame';
|
||||
import { CardSection } from '../parts/CardSection';
|
||||
import TourRouteActions from './TourRouteActions';
|
||||
import TourRouteDay from './TourRouteDay';
|
||||
import TourRouteHead from './TourRouteHead';
|
||||
import TourRouteHead, { TourRouteFields } from './TourRouteHead';
|
||||
import { profileSamples } from './tourRouteModel';
|
||||
import { TourRouteProblem, TourRouteWarnings } from './TourRouteNotes';
|
||||
import TourRouteProfile from './TourRouteProfile';
|
||||
@@ -40,19 +40,30 @@ export function TourRouteBody({
|
||||
compare?: ReadonlyArray<{ key: string; samples: readonly DistanceIndexedProfileSample[]; color: string }>;
|
||||
letter?: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const samples = useMemo(() => profileSamples(card), [card]);
|
||||
return (
|
||||
<>
|
||||
<TourRouteProfile
|
||||
toolCallId={toolCallId}
|
||||
card={card}
|
||||
samples={samples}
|
||||
color={color}
|
||||
focus={route.focus}
|
||||
onFocus={route.setFocus}
|
||||
compare={compare}
|
||||
/>
|
||||
<TourRouteStops card={card} samples={samples} onFocus={route.setFocus} />
|
||||
<TourRouteFields card={card} />
|
||||
{/* A way drawn straight has neither heights nor the line to say so under: no section at all. */}
|
||||
{(samples.length >= 2 || card.routed) && (
|
||||
<CardSection label={t('tours.planner.inspector.elevation')}>
|
||||
<TourRouteProfile
|
||||
toolCallId={toolCallId}
|
||||
card={card}
|
||||
samples={samples}
|
||||
color={color}
|
||||
focus={route.focus}
|
||||
onFocus={route.setFocus}
|
||||
compare={compare}
|
||||
/>
|
||||
</CardSection>
|
||||
)}
|
||||
{card.stops.length > 0 && (
|
||||
<CardSection label={t('assistant.card.tour.stops')}>
|
||||
<TourRouteStops card={card} samples={samples} onFocus={route.setFocus} />
|
||||
</CardSection>
|
||||
)}
|
||||
<TourRouteDay card={card} />
|
||||
<TourRouteWarnings card={card} />
|
||||
<TourRouteProblem card={card} />
|
||||
@@ -63,12 +74,11 @@ export function TourRouteBody({
|
||||
|
||||
export default function TourRouteCard({ toolCallId, card }: { toolCallId: string; card: Route }) {
|
||||
const { t } = useTranslation();
|
||||
const { density } = useAssistantView();
|
||||
const route = useTourRouteCard(toolCallId, card);
|
||||
return (
|
||||
<div {...route.handlers} className={`rounded-xl ${route.litFromMap ? 'ring-1 ring-accent' : ''}`}>
|
||||
<CardFrame label={routeName(card, t)}>
|
||||
<TourRouteHead card={card} sketchHeight={density === 'roomy' ? 64 : 56} onShow={route.showOnMap} />
|
||||
<TourRouteHead card={card} onShow={route.showOnMap} />
|
||||
<TourRouteBody toolCallId={toolCallId} card={card} route={route} color={variantPaintCss('current')} />
|
||||
</CardFrame>
|
||||
</div>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { createElement } from 'react';
|
||||
|
||||
import { useTranslation } from '../../../../i18n';
|
||||
import { SoftPill } from '../../../Planner/planParts';
|
||||
import { Tooltip } from '../../../shared/Tooltip';
|
||||
import { weatherIconFor } from '../../../Weather/weatherIcons';
|
||||
import { useCardFormat } from '../parts/useCardFormat';
|
||||
import { type BarSpan, dayBarOf, forecastHours, RAIN_SHOWN_PCT } from './tourRouteDayModel';
|
||||
@@ -93,9 +94,13 @@ export default function TourRouteDay({ card }: { card: TourRouteCard }) {
|
||||
)}
|
||||
{!schedule.start && schedule.latestStart && (
|
||||
<div className="mt-1 flex">
|
||||
<SoftPill icon={<Clock size={10} strokeWidth={2.2} aria-hidden="true" />}>
|
||||
{t('assistant.card.tour.latestStart', { time: format.clock(schedule.latestStart) })}
|
||||
</SoftPill>
|
||||
<Tooltip label={t('assistant.card.tour.latestStart', { time: format.clock(schedule.latestStart) })}>
|
||||
<span className="inline-flex">
|
||||
<SoftPill icon={<Clock size={10} strokeWidth={2.2} aria-hidden="true" />}>
|
||||
{t('assistant.card.tour.latestStartShort', { time: format.clock(schedule.latestStart) })}
|
||||
</SoftPill>
|
||||
</span>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)}
|
||||
{schedule.weather === 'climate' && (
|
||||
|
||||
@@ -4,12 +4,14 @@ import { createElement } from 'react';
|
||||
|
||||
import { useTranslation } from '../../../../i18n';
|
||||
import { SoftPill, WhiteBadge } from '../../../Planner/planParts';
|
||||
import { fs, PILL } from '../../../shared/DialogShell';
|
||||
import { Tooltip } from '../../../shared/Tooltip';
|
||||
import { SacStepChip } from '../../../Tours/hike/SacStepChip';
|
||||
import { variantPaintCss } from '../../../Tours/planner/legVariantPaint';
|
||||
import { formatTourDuration } from '../../../Tours/planner/tourDurationInput';
|
||||
import { tourDayRowIcon } from '../../../Tours/tourDayRowIcon';
|
||||
import { CardFacts } from '../parts/CardFacts';
|
||||
import CardHeader from '../parts/CardHeader';
|
||||
import { CardFields } from '../parts/CardSection';
|
||||
import RouteSketch from '../parts/RouteSketch';
|
||||
import { useCardFormat } from '../parts/useCardFormat';
|
||||
import { factKeysOf, factValue, percentText, type FactKey } from './tourRouteModel';
|
||||
@@ -89,7 +91,7 @@ export function TourGrade({ card }: { card: TourRouteCard }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** The day a route is planned on, as words: "Day 2, Tue 14 Oct", or the date alone. */
|
||||
/** The day a route is planned on, as a white pill on the band: "Day 2, Tue 14 Oct", or the date alone. */
|
||||
function DayPill({ card }: { card: TourRouteCard }) {
|
||||
const { t } = useTranslation();
|
||||
const format = useCardFormat();
|
||||
@@ -98,7 +100,12 @@ function DayPill({ card }: { card: TourRouteCard }) {
|
||||
const date = format.date(schedule.date);
|
||||
const text =
|
||||
schedule.dayNumber !== null ? `${t('assistant.card.tour.day', { day: schedule.dayNumber })}, ${date}` : date;
|
||||
return <SoftPill icon={<CalendarDays size={10} strokeWidth={2.2} aria-hidden="true" />}>{text}</SoftPill>;
|
||||
return (
|
||||
<span className={PILL} style={fs(11)}>
|
||||
<CalendarDays size={11} strokeWidth={2.2} aria-hidden="true" className="flex-none text-content-faint" />
|
||||
{text}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** The route drawn small: a button that shows it on the map. */
|
||||
@@ -127,35 +134,51 @@ export function TourRouteSketch({
|
||||
);
|
||||
}
|
||||
|
||||
export default function TourRouteHead({
|
||||
card,
|
||||
sketchHeight,
|
||||
onShow,
|
||||
}: {
|
||||
card: TourRouteCard;
|
||||
sketchHeight: number;
|
||||
onShow: () => void;
|
||||
}) {
|
||||
/** The route's figures as framed fields, each under its label: distance, climb, descent and time, as known. */
|
||||
export function TourRouteFields({ card }: { card: TourRouteCard }) {
|
||||
const { t } = useTranslation();
|
||||
const format = useCardFormat();
|
||||
const fields = factKeysOf(card).flatMap((key) => {
|
||||
const value = factValue(card, key);
|
||||
if (value === null) return [];
|
||||
// A field's label is short; how the time was reckoned is the figure badges' tooltip.
|
||||
const label = t(FACT_LOOK[key].labelKey ?? 'tours.planner.inspector.duration');
|
||||
let text: string;
|
||||
if (key === 'time') text = formatTourDuration(value);
|
||||
else text = key === 'distance' ? format.distance(value / 1000) : format.elevation(value);
|
||||
return [{ key, label, value: text }];
|
||||
});
|
||||
return <CardFields fields={fields} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* The head band of a route card: the route drawn small on a raised tile, what
|
||||
* kind of tour it is above its name, the label under it, and its grade and
|
||||
* the day it is planned on as pills on the band.
|
||||
*/
|
||||
export default function TourRouteHead({ card, onShow }: { card: TourRouteCard; onShow: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const name = routeName(card, t);
|
||||
const tile = (
|
||||
<span className="w-12 flex-none overflow-hidden rounded-[10px] bg-surface-card p-1 shadow-sm">
|
||||
<TourRouteSketch card={card} height={48} onShow={onShow} />
|
||||
</span>
|
||||
);
|
||||
return (
|
||||
<div className="flex items-start gap-2.5">
|
||||
<div className="w-[72px] flex-none">
|
||||
<TourRouteSketch card={card} height={sketchHeight} onShow={onShow} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex min-w-0 items-start gap-2">
|
||||
<bdi title={name} className="line-clamp-2 min-w-0 flex-1 text-body font-semibold leading-tight text-content">
|
||||
{name}
|
||||
</bdi>
|
||||
<TourGrade card={card} />
|
||||
</div>
|
||||
{card.label && <p className="m-0 mt-0.5 truncate text-caption text-content-muted">{card.label}</p>}
|
||||
<CardFacts>
|
||||
<TourRouteFigures card={card} />
|
||||
<CardHeader
|
||||
icon={tourDayRowIcon(card.activity)}
|
||||
tone="info"
|
||||
tile={tile}
|
||||
eyebrow={t(TOUR_TYPE_WORDS[card.activity].labelKey)}
|
||||
title={name}
|
||||
meta={card.label ?? undefined}
|
||||
>
|
||||
{((card.activity === 'hike' && card.grades) || card.schedule) && (
|
||||
<div className="mt-2.5 flex flex-wrap items-center gap-1.5">
|
||||
{card.activity === 'hike' && card.grades && <TourGrade card={card} />}
|
||||
<DayPill card={card} />
|
||||
</CardFacts>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardHeader>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,8 @@ import { tourDayRowIcon } from '../../../Tours/tourDayRowIcon';
|
||||
import type { ChangeItem } from '../../assistantParts';
|
||||
import { verbLookOf } from '../cardLooks';
|
||||
import KindTile from '../parts/KindTile';
|
||||
import { TourGrade, TourRouteFigures, TourRouteSketch } from './TourRouteHead';
|
||||
import WayFigures from './TourFigureLine';
|
||||
import { TourGrade, TourRouteSketch } from './TourRouteHead';
|
||||
import { legVariantOf, previousVariantOf, profileBands, profileSamples } from './tourRouteModel';
|
||||
import { useTourRouteCard } from './useTourRouteCard';
|
||||
|
||||
@@ -37,29 +38,33 @@ export default function TourRouteInRow({ card, item }: { card: TourRouteCard; it
|
||||
const samples = useMemo(() => profileSamples(card), [card]);
|
||||
const previous = previousVariantOf(card);
|
||||
const notPlanned = card.problem?.why === 'not_planned';
|
||||
const grades = card.activity === 'hike' ? card.grades : null;
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5" data-testid="tour-route-row">
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="w-16 flex-none">
|
||||
<TourRouteSketch card={card} height={40} onShow={showOnMap} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="flex flex-wrap items-center gap-1">
|
||||
<TourRouteFigures card={card} />
|
||||
<TourGrade card={card} />
|
||||
{previous && (
|
||||
<VariantDelta
|
||||
variant={legVariantOf(card, 'current')}
|
||||
current={previous}
|
||||
unit={unit}
|
||||
t={t}
|
||||
hint={t('assistant.card.tour.deltaBefore')}
|
||||
/>
|
||||
)}
|
||||
<div
|
||||
className="flex flex-col gap-2 rounded-[12px] border border-edge-faint bg-surface-secondary p-2.5"
|
||||
data-testid="tour-route-row"
|
||||
>
|
||||
<div className="flex items-center gap-2.5">
|
||||
<span className="w-14 flex-none overflow-hidden rounded-[10px] bg-surface-card p-1 shadow-sm">
|
||||
<TourRouteSketch card={card} height={36} onShow={showOnMap} />
|
||||
</span>
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-1">
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
<span className="min-w-0 flex-1">
|
||||
<WayFigures way={legVariantOf(card, 'current')} unit={unit} />
|
||||
</span>
|
||||
{grades && grades.highest !== null && <TourGrade card={card} />}
|
||||
</span>
|
||||
{notPlanned && (
|
||||
<p className="m-0 mt-1 text-caption text-content-faint">{t('assistant.card.tour.notPlanned')}</p>
|
||||
{previous && (
|
||||
<VariantDelta
|
||||
variant={legVariantOf(card, 'current')}
|
||||
current={previous}
|
||||
unit={unit}
|
||||
t={t}
|
||||
hint={t('assistant.card.tour.deltaBefore')}
|
||||
/>
|
||||
)}
|
||||
{notPlanned && <p className="m-0 text-caption text-content-faint">{t('assistant.card.tour.notPlanned')}</p>}
|
||||
</div>
|
||||
</div>
|
||||
{!notPlanned && samples.length >= 2 && (
|
||||
|
||||
@@ -87,7 +87,7 @@ export default function TourRouteProfile({ toolCallId, card, samples, color, foc
|
||||
const bands = useMemo(() => profileBands(card, samples), [card, samples]);
|
||||
if (samples.length < 2) {
|
||||
if (!card.routed) return null;
|
||||
return <p className="m-0 mt-2 text-caption text-content-faint">{t('assistant.card.tour.noHeights')}</p>;
|
||||
return <p className="m-0 text-caption text-content-faint">{t('assistant.card.tour.noHeights')}</p>;
|
||||
}
|
||||
const phone = variant === 'fullscreen';
|
||||
const focusGrade = focus ? gradeAt(grades, focus.distanceMeters) : null;
|
||||
@@ -112,7 +112,7 @@ export default function TourRouteProfile({ toolCallId, card, samples, color, foc
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mt-2">
|
||||
<div className="rounded-[12px] border border-edge-faint bg-surface-secondary px-2 pb-1.5 pt-2">
|
||||
<ElevationProfile
|
||||
samples={samples}
|
||||
color={color}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { TourRouteCard, TourRouteStop } from '@trek/shared';
|
||||
import { AlertTriangle, Flag, MapPin, MountainSnow, type LucideIcon } from 'lucide-react';
|
||||
import { AlertTriangle, Clock, Flag, MapPin, MountainSnow, type LucideIcon } from 'lucide-react';
|
||||
import { createElement, type ReactNode } from 'react';
|
||||
|
||||
import { useTranslation } from '../../../../i18n';
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
type RouteProfileFocus,
|
||||
} from '../../../../utils/routeGeometry';
|
||||
import { TOUR_POI_LOOKS } from '../../../Map/poiCategories';
|
||||
import { SoftPill, WhiteBadge } from '../../../Planner/planParts';
|
||||
import { SoftPill } from '../../../Planner/planParts';
|
||||
import { Tooltip } from '../../../shared/Tooltip';
|
||||
import { StageEndCorner } from '../../../Tours/stages/StageParts';
|
||||
import { useCardFormat } from '../parts/useCardFormat';
|
||||
@@ -18,12 +18,13 @@ import { FLAG_LOOK, stopName } from './tourRouteWords';
|
||||
|
||||
/**
|
||||
* The stops of a route as a timeline in the order they lie along it: one row
|
||||
* per stop (the start and the end, the huts, summits and stations on the way
|
||||
* with their clock, what lies a little off the way quieter), joined by a line
|
||||
* that carries the walking time of the stretch between two stops, so a time
|
||||
* is never read as belonging to the stop beside it. Pointing at a chip or
|
||||
* tapping it moves the spot in focus there, on the profile and on the map
|
||||
* alike. Past eight the middle ones fold into a count that names them.
|
||||
* per stop on a line down the card (the start and the end filled, the huts,
|
||||
* summits and stations on the way with their glyph, what lies a little off
|
||||
* the way quieter), its name, how far off the way or how long the stay under
|
||||
* it, and its clock at the end; the walk between two stops sits on the line
|
||||
* between their rows, so a time is never read as a stop's own. Pointing at a
|
||||
* row or tapping it moves the spot in focus there, on the profile and on the
|
||||
* map alike. Past eight the middle ones fold into a row that names them.
|
||||
*/
|
||||
|
||||
/** A stop's glyph: the flag at either end, the mountain at the highest point, the place's own for a kind. */
|
||||
@@ -46,12 +47,31 @@ function focusOf(stop: TourRouteStop, samples: readonly DistanceIndexedProfileSa
|
||||
);
|
||||
}
|
||||
|
||||
function StopChip({
|
||||
/** A stop's mark on the line: filled at the start and the end, a ring with its glyph on the way, smaller off it. */
|
||||
function Marker({ stop }: { stop: TourRouteStop }) {
|
||||
const end = stop.role === 'start' || stop.role === 'end';
|
||||
const along = stop.role === 'along';
|
||||
const glyph = createElement(iconOf(stop), { size: along ? 9 : 10, strokeWidth: 2.2, 'aria-hidden': true });
|
||||
let look = 'h-5 w-5 bg-surface-card text-content-muted ring-1 ring-inset ring-edge';
|
||||
if (end) look = 'h-5 w-5 bg-accent text-accent-text';
|
||||
else if (along) look = 'h-4 w-4 bg-surface-secondary text-content-faint ring-1 ring-inset ring-edge-faint';
|
||||
return (
|
||||
<span className="relative z-[1] flex w-5 flex-none justify-center">
|
||||
<span className={`grid place-items-center rounded-full ${look}`}>{glyph}</span>
|
||||
{stop.stageEnd && <StageEndCorner />}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function StopRow({
|
||||
stop,
|
||||
leg,
|
||||
samples,
|
||||
onFocus,
|
||||
}: {
|
||||
stop: TourRouteStop;
|
||||
/** The walk from the last stop with a time to this one, read with it. */
|
||||
leg: number | null;
|
||||
samples: readonly DistanceIndexedProfileSample[];
|
||||
onFocus: (focus: RouteProfileFocus | null) => void;
|
||||
}) {
|
||||
@@ -65,44 +85,45 @@ function StopChip({
|
||||
: null;
|
||||
const stay = stop.stayMinutes ? t('assistant.card.tour.stay', { time: format.minutes(stop.stayMinutes) }) : null;
|
||||
const clock = stop.clock ? format.clock(stop.clock) : null;
|
||||
const label = [name, clock, off, stay].filter(Boolean).join(', ');
|
||||
const glyph = createElement(iconOf(stop), {
|
||||
size: 10,
|
||||
strokeWidth: 2.2,
|
||||
'aria-hidden': true,
|
||||
className: 'flex-none text-content-faint',
|
||||
});
|
||||
const body = (
|
||||
<>
|
||||
<bdi className="max-w-[10rem] truncate">{name}</bdi>
|
||||
{clock && <span className="tabular-nums text-content-muted">{clock}</span>}
|
||||
{off && <span className="text-content-faint">{off}</span>}
|
||||
</>
|
||||
);
|
||||
const walked = leg !== null ? t('assistant.card.tour.legTime', { time: format.minutes(leg) }) : null;
|
||||
const label = [name, clock, off, stay, walked].filter(Boolean).join(', ');
|
||||
const point = () => onFocus(focusOf(stop, samples));
|
||||
const under = [off, stay].filter((part): part is string => part !== null);
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<Tooltip label={label}>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={label}
|
||||
onMouseEnter={() => onFocus(focusOf(stop, samples))}
|
||||
onMouseLeave={() => onFocus(null)}
|
||||
onFocus={() => onFocus(focusOf(stop, samples))}
|
||||
onBlur={() => onFocus(null)}
|
||||
onClick={() => onFocus(focusOf(stop, samples))}
|
||||
className="relative inline-flex rounded-full focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
|
||||
>
|
||||
{along ? <WhiteBadge icon={glyph}>{body}</WhiteBadge> : <SoftPill icon={glyph}>{body}</SoftPill>}
|
||||
{stop.stageEnd && <StageEndCorner />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
{stay && <span className="text-caption text-content-faint">{stay}</span>}
|
||||
{stop.flag && (
|
||||
<SoftPill tone="warning" icon={<AlertTriangle size={10} strokeWidth={2.2} aria-hidden="true" />}>
|
||||
{t(FLAG_LOOK[stop.flag].labelKey)}
|
||||
</SoftPill>
|
||||
)}
|
||||
</span>
|
||||
<li className="flex">
|
||||
<button
|
||||
type="button"
|
||||
aria-label={label}
|
||||
onMouseEnter={point}
|
||||
onMouseLeave={() => onFocus(null)}
|
||||
onFocus={point}
|
||||
onBlur={() => onFocus(null)}
|
||||
onClick={point}
|
||||
className="-mx-1.5 flex min-w-0 flex-1 items-center gap-2.5 rounded-[10px] px-1.5 py-1 text-start transition-colors hover:bg-surface-hover focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
|
||||
>
|
||||
<Marker stop={stop} />
|
||||
<span className="min-w-0 flex-1">
|
||||
<bdi
|
||||
className={`block truncate leading-tight ${along ? 'text-caption text-content-secondary' : 'text-body font-medium text-content'}`}
|
||||
>
|
||||
{name}
|
||||
</bdi>
|
||||
{(under.length > 0 || stop.flag) && (
|
||||
<span className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-caption text-content-faint">
|
||||
{under.map((part) => (
|
||||
<span key={part}>{part}</span>
|
||||
))}
|
||||
{stop.flag && (
|
||||
<SoftPill tone="warning" icon={<AlertTriangle size={10} strokeWidth={2.2} aria-hidden="true" />}>
|
||||
{t(FLAG_LOOK[stop.flag].labelKey)}
|
||||
</SoftPill>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{clock && <span className="flex-none text-caption tabular-nums text-content-muted">{clock}</span>}
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -112,38 +133,36 @@ function legMinutes(from: TourRouteStop | undefined, to: TourRouteStop): number
|
||||
return to.minutes - from.minutes;
|
||||
}
|
||||
|
||||
/** The line between two rows, with the stretch's walking time on it. */
|
||||
/** The walk between two rows, beside the line: read with the row it leads to, so hidden here. */
|
||||
function Leg({ minutes }: { minutes: number | null }) {
|
||||
const format = useCardFormat();
|
||||
if (minutes === null) return <li aria-hidden="true" className="h-1.5" />;
|
||||
return (
|
||||
// Read with the stop it leads to; a list holds only its rows.
|
||||
<span aria-hidden="true" className="flex min-h-[14px] items-stretch gap-2">
|
||||
<span className="flex w-2.5 flex-none justify-center">
|
||||
<span className="w-px bg-edge" />
|
||||
<li aria-hidden="true" className="flex items-center py-0.5 ps-[30px]">
|
||||
<span className="inline-flex items-center gap-1 rounded-full bg-surface-secondary px-2 py-0.5 text-caption tabular-nums text-content-muted">
|
||||
<Clock size={10} strokeWidth={2.2} className="flex-none text-content-faint" />
|
||||
{format.minutes(minutes)}
|
||||
</span>
|
||||
{minutes !== null && (
|
||||
<span className="text-caption tabular-nums leading-tight text-content-faint">{format.minutes(minutes)}</span>
|
||||
)}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/** One row of the timeline: its dot on the line, then the stop, read after the walk that leads to it. */
|
||||
function Row({ end, leg, children }: { end: boolean; leg?: number | null; children: ReactNode }) {
|
||||
/** The middle stops folded into one row past eight, naming them in its tooltip. */
|
||||
function FoldedRow({ stops }: { stops: readonly TourRouteStop[] }) {
|
||||
const { t } = useTranslation();
|
||||
const format = useCardFormat();
|
||||
const names = stops.map((stop) => stopName(stop, t)).join(', ');
|
||||
return (
|
||||
<span role="listitem" className="flex items-center gap-2">
|
||||
{leg != null && (
|
||||
<span className="sr-only">{t('assistant.card.tour.legTime', { time: format.minutes(leg) })}</span>
|
||||
)}
|
||||
<span className="flex w-2.5 flex-none justify-center">
|
||||
<span
|
||||
className={`h-2 w-2 rounded-full ${end ? 'bg-content-muted' : 'border border-content-faint bg-surface-card'}`}
|
||||
/>
|
||||
<li className="flex items-center gap-2.5 py-1">
|
||||
<span className="relative z-[1] flex w-5 flex-none justify-center">
|
||||
<span className="h-2 w-2 rounded-full border border-dashed border-content-faint bg-surface-card" />
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-wrap items-center gap-1.5">{children}</span>
|
||||
</span>
|
||||
<Tooltip label={names}>
|
||||
<span className="text-caption text-content-muted underline decoration-dotted underline-offset-2">
|
||||
{t('assistant.card.tour.stopsMore', { count: stops.length })}
|
||||
<span className="sr-only">{`: ${names}`}</span>
|
||||
</span>
|
||||
</Tooltip>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -159,42 +178,30 @@ export default function TourRouteStops({
|
||||
const { t } = useTranslation();
|
||||
const { head, folded, tail } = chipStops(card);
|
||||
if (head.length === 0) return null;
|
||||
const names = folded.map((stop) => stopName(stop, t)).join(', ');
|
||||
// The time is walked from the last stop that has one: a place beside the way has none.
|
||||
let walked: TourRouteStop | undefined;
|
||||
const rows: ReactNode[] = [];
|
||||
const pushStop = (stop: TourRouteStop, key: string) => {
|
||||
const leg = legMinutes(walked, stop);
|
||||
if (rows.length > 0) rows.push(<Leg key={`${key}-leg`} minutes={leg} />);
|
||||
rows.push(
|
||||
<Row key={key} end={stop.role === 'start' || stop.role === 'end'} leg={leg}>
|
||||
<StopChip stop={stop} samples={samples} onFocus={onFocus} />
|
||||
</Row>
|
||||
);
|
||||
rows.push(<StopRow key={key} stop={stop} leg={leg} samples={samples} onFocus={onFocus} />);
|
||||
if (stop.minutes !== null) walked = stop;
|
||||
};
|
||||
head.forEach((stop, index) => pushStop(stop, `h-${index}`));
|
||||
if (folded.length > 0) {
|
||||
rows.push(<Leg key="f-leg" minutes={null} />);
|
||||
rows.push(
|
||||
<Row key="f" end={false}>
|
||||
<Tooltip label={names}>
|
||||
<span className="inline-flex">
|
||||
<WhiteBadge>
|
||||
{t('assistant.card.tour.stopsMore', { count: folded.length })}
|
||||
<span className="sr-only">{`: ${names}`}</span>
|
||||
</WhiteBadge>
|
||||
</span>
|
||||
</Tooltip>
|
||||
</Row>
|
||||
);
|
||||
rows.push(<FoldedRow key="f" stops={folded} />);
|
||||
// The folded stretch's time is not one leg; the next stop measures from the last folded one.
|
||||
walked = [...folded].reverse().find((stop) => stop.minutes !== null) ?? walked;
|
||||
}
|
||||
tail.forEach((stop, index) => pushStop(stop, `t-${index}`));
|
||||
return (
|
||||
<div className="mt-2 flex flex-col" role="list" aria-label={t('assistant.card.tour.stops')}>
|
||||
{rows}
|
||||
<div className="relative">
|
||||
{/* The line down the timeline, from the first mark to the last, under the marks. */}
|
||||
<span aria-hidden="true" className="absolute bottom-3 start-[9.5px] top-3 w-px bg-edge" />
|
||||
<ul className="relative m-0 flex list-none flex-col p-0" aria-label={t('assistant.card.tour.stops')}>
|
||||
{rows}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,19 +1,128 @@
|
||||
import type { TourRouteCard as Route } from '@trek/shared';
|
||||
import { Route as RouteIcon } from 'lucide-react';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { useTranslation } from '../../../../i18n';
|
||||
import { chatOf, useAssistantStore } from '../../../../store/assistantStore';
|
||||
import { useSettingsStore } from '../../../../store/settingsStore';
|
||||
import type { DistanceUnit } from '../../../../types';
|
||||
import { formatDistance, formatElevation } from '../../../../utils/units';
|
||||
import { SacStepChip } from '../../../Tours/hike/SacStepChip';
|
||||
import { variantPaintCss } from '../../../Tours/planner/legVariantPaint';
|
||||
import { VariantDelta } from '../../../Tours/planner/LegVariantsCard';
|
||||
import { VariantFigures, WayChoice } from '../../../Tours/planner/mapCardParts';
|
||||
import { type LegVariant, variantDelta } from '../../../Tours/planner/legVariants';
|
||||
import { VariantMark } from '../../../Tours/planner/mapCardParts';
|
||||
import { formatTourDuration } from '../../../Tours/planner/tourDurationInput';
|
||||
import { useAssistantView } from '../../assistantViewContext';
|
||||
import CardFrame from '../parts/CardFrame';
|
||||
import CardHeader from '../parts/CardHeader';
|
||||
import { CardSection } from '../parts/CardSection';
|
||||
import WayFigures from './TourFigureLine';
|
||||
import { TourRouteBody } from './TourRouteCard';
|
||||
import { legVariantOf, profileSamples, type RouteEntry, WAY_KEYS } from './tourRouteModel';
|
||||
import { routeName, TOUR_TYPE_WORDS } from './tourRouteWords';
|
||||
import { useLineHover, useTourRouteCard } from './useTourRouteCard';
|
||||
|
||||
/** The ways of one answer with the chosen one known: its choices, then the chosen way's body. */
|
||||
/** A signed difference: a plus for more, a minus sign for less, nothing for none worth printing. */
|
||||
function signed(value: number, format: (absolute: number) => string): string | null {
|
||||
const text = format(Math.abs(value));
|
||||
if (Math.abs(value) < 1e-9 || /^0\s/.test(text)) return null;
|
||||
return `${value > 0 ? '+' : '−'}${text}`;
|
||||
}
|
||||
|
||||
/** How a way differs from the chosen one, as one faint line: "Compared with way A: −4.3 km −178 m −1 h 33 min". */
|
||||
function WayDelta({
|
||||
way,
|
||||
chosen,
|
||||
letter,
|
||||
unit,
|
||||
}: {
|
||||
way: LegVariant;
|
||||
chosen: LegVariant;
|
||||
letter: string;
|
||||
unit: DistanceUnit;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const delta = variantDelta(way, chosen);
|
||||
const parts = [
|
||||
signed(delta.distanceM / 1000, (km) => formatDistance(km, unit)),
|
||||
delta.gainM === null ? null : signed(delta.gainM, (m) => formatElevation(m, unit)),
|
||||
delta.minutes === null ? null : signed(delta.minutes, formatTourDuration),
|
||||
].filter((part): part is string => part !== null);
|
||||
if (parts.length === 0) return null;
|
||||
return (
|
||||
<span
|
||||
className="flex flex-wrap items-center gap-x-2 text-caption text-content-faint"
|
||||
data-testid="leg-variant-delta"
|
||||
>
|
||||
<span>{t('assistant.card.tour.deltaTo', { letter })}</span>
|
||||
{parts.map((part) => (
|
||||
<span key={part} className="tabular-nums text-content-muted">
|
||||
{part}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** One way to choose: its letter in the colour it is drawn in, its name and grade, its figures, how it differs. */
|
||||
function WayOption({
|
||||
entry,
|
||||
index,
|
||||
chosen,
|
||||
chosenWay,
|
||||
chosenLetter,
|
||||
unit,
|
||||
onSelect,
|
||||
onHover,
|
||||
}: {
|
||||
entry: RouteEntry;
|
||||
index: number;
|
||||
chosen: boolean;
|
||||
chosenWay: LegVariant;
|
||||
chosenLetter: string;
|
||||
unit: DistanceUnit;
|
||||
onSelect: () => void;
|
||||
onHover: (on: boolean) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const key = WAY_KEYS[index] ?? 'a';
|
||||
const letter = key.toUpperCase();
|
||||
const way = legVariantOf(entry.card, key);
|
||||
const grades = entry.card.grades;
|
||||
const name = entry.card.label ?? t('tours.variants.option', { letter });
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={chosen}
|
||||
aria-label={name}
|
||||
onClick={onSelect}
|
||||
onMouseEnter={() => onHover(true)}
|
||||
onMouseLeave={() => onHover(false)}
|
||||
onFocus={() => onHover(true)}
|
||||
onBlur={() => onHover(false)}
|
||||
className={`flex w-full items-start gap-2.5 rounded-[12px] border px-2.5 py-2 text-start transition-colors ${
|
||||
chosen
|
||||
? 'border-accent bg-surface-card shadow-sm'
|
||||
: 'border-edge-faint bg-surface-secondary hover:border-edge hover:bg-surface-card'
|
||||
}`}
|
||||
>
|
||||
<VariantMark variant={way} chosen={chosen} />
|
||||
<span className="flex min-w-0 flex-1 flex-col gap-1">
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
<bdi className="min-w-0 flex-1 truncate text-body font-semibold leading-tight text-content">{name}</bdi>
|
||||
{grades && grades.highest !== null && (
|
||||
<SacStepChip step={grades.highest} uncertain={grades.unknownShare >= 0.5} />
|
||||
)}
|
||||
</span>
|
||||
<WayFigures way={way} unit={unit} />
|
||||
{!chosen && <WayDelta way={way} chosen={chosenWay} letter={chosenLetter} unit={unit} />}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** The ways of one answer with the chosen one known: the band, the choices, then the chosen way's body. */
|
||||
function WaysCard({
|
||||
entries,
|
||||
chosen,
|
||||
@@ -44,57 +153,49 @@ function WaysCard({
|
||||
[entries, chosenIndex]
|
||||
);
|
||||
|
||||
const current = legVariantOf(chosen.card, chosenKey);
|
||||
const chosenWay = legVariantOf(chosen.card, chosenKey);
|
||||
// Side by side where the window is roomy; on the phone the ways stay rows, so a finger scrubs the profile freely.
|
||||
let columns = '';
|
||||
if (density === 'roomy' && variant !== 'fullscreen') columns = entries.length >= 3 ? 'grid-cols-3' : 'grid-cols-2';
|
||||
const title = t('assistant.card.tour.ways', { count: entries.length });
|
||||
const card: Route = chosen.card;
|
||||
return (
|
||||
<div {...route.handlers} className={`rounded-xl ${route.litFromMap ? 'ring-1 ring-accent' : ''}`}>
|
||||
<div {...route.handlers} className={`rounded-[16px] ${route.litFromMap ? 'ring-1 ring-accent' : ''}`}>
|
||||
<CardFrame label={title}>
|
||||
<p className="m-0 text-caption text-content-muted">{title}</p>
|
||||
<div role="radiogroup" aria-label={title} className={`mt-1.5 grid gap-1.5 ${columns}`}>
|
||||
{entries.map((entry, index) => {
|
||||
const key = WAY_KEYS[index] ?? 'a';
|
||||
const letter = key.toUpperCase();
|
||||
const way = legVariantOf(entry.card, key);
|
||||
const grades = entry.card.grades;
|
||||
return (
|
||||
<WayChoice
|
||||
<CardHeader
|
||||
icon={RouteIcon}
|
||||
tone="info"
|
||||
eyebrow={t(TOUR_TYPE_WORDS[card.activity].labelKey)}
|
||||
title={routeName(card, t)}
|
||||
meta={title}
|
||||
/>
|
||||
<CardSection label={t('assistant.card.tour.waysPick')}>
|
||||
<div role="radiogroup" aria-label={title} className={`grid gap-1.5 ${columns}`}>
|
||||
{entries.map((entry, index) => (
|
||||
<WayOption
|
||||
key={entry.toolCallId}
|
||||
way={way}
|
||||
name={entry.card.label ?? t('tours.variants.option', { letter })}
|
||||
entry={entry}
|
||||
index={index}
|
||||
chosen={index === chosenIndex}
|
||||
aside={
|
||||
<>
|
||||
{index !== chosenIndex && (
|
||||
<VariantDelta
|
||||
variant={way}
|
||||
current={current}
|
||||
unit={unit}
|
||||
t={t}
|
||||
hint={t('assistant.card.tour.deltaTo', { letter: chosenKey.toUpperCase() })}
|
||||
/>
|
||||
)}
|
||||
{grades && <SacStepChip step={grades.highest} uncertain={grades.unknownShare >= 0.5} />}
|
||||
</>
|
||||
}
|
||||
chosenWay={chosenWay}
|
||||
chosenLetter={chosenKey.toUpperCase()}
|
||||
unit={unit}
|
||||
onSelect={() => pick(tripId, blockKey, entry.toolCallId)}
|
||||
onHover={(on) => hover(entry.toolCallId, on)}
|
||||
>
|
||||
<VariantFigures variant={way} unit={unit} t={t} />
|
||||
</WayChoice>
|
||||
);
|
||||
})}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</CardSection>
|
||||
<div className="mt-3">
|
||||
<TourRouteBody
|
||||
toolCallId={chosen.toolCallId}
|
||||
card={chosen.card}
|
||||
route={route}
|
||||
color={variantPaintCss(chosenKey)}
|
||||
compare={compare}
|
||||
letter={chosenKey.toUpperCase()}
|
||||
/>
|
||||
</div>
|
||||
<TourRouteBody
|
||||
toolCallId={chosen.toolCallId}
|
||||
card={chosen.card}
|
||||
route={route}
|
||||
color={variantPaintCss(chosenKey)}
|
||||
compare={compare}
|
||||
letter={chosenKey.toUpperCase()}
|
||||
/>
|
||||
</CardFrame>
|
||||
</div>
|
||||
);
|
||||
@@ -102,12 +203,12 @@ function WaysCard({
|
||||
|
||||
/**
|
||||
* Two or three ways of one route an answer proposed, as the planner offers a
|
||||
* section's ways: each a choice with its letter in the colour it is drawn in,
|
||||
* its own words, how it differs from the chosen one and its hardest grade,
|
||||
* its figures below. One profile holds them all, the chosen way filled and
|
||||
* the others thin on the same axes; under it the chosen way's stops, day and
|
||||
* warnings, and "Plan way B". A choice is kept per answer, and pointing at a
|
||||
* way lights its line on the map.
|
||||
* section's ways: a band naming the route, each way a choice with its letter
|
||||
* in the colour it is drawn in, its name and hardest grade, its figures and
|
||||
* how it differs from the chosen one; one profile holds them all, the chosen
|
||||
* way filled and the others thin on the same axes; under it the chosen way's
|
||||
* figures, stops, day and warnings, and "Plan way B". A choice is kept per
|
||||
* answer, and pointing at a way lights its line on the map.
|
||||
*/
|
||||
export default function TourWays({ entries }: { entries: readonly RouteEntry[] }) {
|
||||
const { tripId } = useAssistantView();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { type AssistantApplied, cumulativeMetres, type TourRouteCard, type TrekCard } from '@trek/shared';
|
||||
import { Route } from 'lucide-react';
|
||||
import { Circle, CircleCheck, CircleSlash, Route } from 'lucide-react';
|
||||
|
||||
import type { RouteLineSpec, RouteUse } from '../../../../types/assistantMap';
|
||||
import type { EntityTarget, PackLook } from '../cardTypes';
|
||||
@@ -86,6 +86,9 @@ export const TOUR_LOOK = {
|
||||
verbs: {
|
||||
addTour: { Icon: Route, tone: 'success', labelKey: 'assistant.change.verb.addTour' },
|
||||
updateTour: { Icon: Route, tone: 'info', labelKey: 'assistant.change.verb.updateTour' },
|
||||
markVisited: { Icon: CircleCheck, tone: 'success', labelKey: 'assistant.change.verb.markVisited' },
|
||||
markSkipped: { Icon: CircleSlash, tone: 'info', labelKey: 'assistant.change.verb.markSkipped' },
|
||||
markPlanned: { Icon: Circle, tone: 'info', labelKey: 'assistant.change.verb.markPlanned' },
|
||||
},
|
||||
tools: {},
|
||||
steps: {
|
||||
@@ -96,6 +99,7 @@ export const TOUR_LOOK = {
|
||||
list_tours: { stepKey: 'assistant.step.readingTours' },
|
||||
find_tours_for_day: { stepKey: 'assistant.step.readingTours' },
|
||||
search_tour_pois: { stepKey: 'assistant.step.tourPois' },
|
||||
get_city_walk_progress: { stepKey: 'assistant.step.readingTour' },
|
||||
},
|
||||
entities: {
|
||||
tour: {
|
||||
|
||||
@@ -67,6 +67,9 @@ describe('takeInThread', () => {
|
||||
it('FE-AI-TOUR-048: a take that names its proposal is matched by it, not by its way', () => {
|
||||
const other = { ...GENTLE, line: [[47.9, 12.8, 600], ...GENTLE.line.slice(1)] } satisfies TourRouteCard;
|
||||
expect(takeInThread([proposal, take(other, {}, 'take_proposal', 'call_1')], 'call_1', HIKE)).toBe('waiting');
|
||||
// The server joins a take to the answer that drew the proposal: found there too.
|
||||
const joined = { ...proposal, parts: [...proposal.parts, ...take(other, {}, 'take_proposal', 'call_1').parts] };
|
||||
expect(takeInThread([joined], 'call_1', HIKE)).toBe('waiting');
|
||||
// The same way taken from another proposal leaves this one free.
|
||||
expect(
|
||||
takeInThread([proposal, take(HIKE, { approved: true }, 'take_proposal', 'call_2')], 'call_1', HIKE)
|
||||
|
||||
@@ -45,7 +45,8 @@ export function takeOfProposal(
|
||||
): { id: string; state: 'waiting' | 'applied'; placeId: number | null } | null {
|
||||
const from = proposalIndex(messages, toolCallId);
|
||||
if (from < 0) return null;
|
||||
for (const message of messages.slice(from + 1)) {
|
||||
// The server joins a take to the answer that drew its proposal, so that answer is searched as well as the later ones.
|
||||
for (const message of messages.slice(from)) {
|
||||
const open = new Map<string, 'waiting' | 'applied'>();
|
||||
for (const part of message.parts) {
|
||||
if (part.type !== 'tool-call' || part.toolName !== TAKE_TOOL || part.approval?.resolution) continue;
|
||||
|
||||
@@ -14,6 +14,6 @@ import TourRouteInRow, { TourRouteLead } from './TourRouteInRow';
|
||||
* file.
|
||||
*/
|
||||
export const TOUR_VIEWS = {
|
||||
tourRoute: { Block: TourRouteBlock, Lead: TourRouteLead, Body: TourRouteInRow },
|
||||
tourRoute: { Block: TourRouteBlock, Lead: TourRouteLead, Body: TourRouteInRow, wideBody: true },
|
||||
tourList: { Block: TourListCard },
|
||||
} satisfies { [K in 'tourRoute' | 'tourList']: CardView<K> };
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import type { CSSProperties } from 'react';
|
||||
|
||||
import { Palmtree } from 'lucide-react';
|
||||
|
||||
import { useTranslation } from '../../../../i18n';
|
||||
import { safeHexColor } from '../../../../utils/safeColor';
|
||||
import type { CardEntry } from '../cardTypes';
|
||||
import CardFrame from '../parts/CardFrame';
|
||||
import CardHeader from '../parts/CardHeader';
|
||||
import { CardOpenButton } from '../parts/CardOpen';
|
||||
import { CardFoot } from '../parts/CardSection';
|
||||
import { useViewerId } from '../parts/useViewerId';
|
||||
import VacayBalance from './VacayBalance';
|
||||
import { balanceLines, mergeVacayCards, type VacayView } from './vacayCardModel';
|
||||
@@ -26,7 +30,6 @@ const SQUARE = 'size-2 flex-none rounded-sm';
|
||||
const COMPANY = 'size-2 flex-none rounded-sm bg-warning-soft ring-1 ring-inset ring-warning';
|
||||
const TRIP = 'size-1.5 flex-none rounded-full bg-info';
|
||||
const OTHER = 'mt-1.5 text-caption text-content-muted';
|
||||
const FOOT = 'mt-1 flex justify-end';
|
||||
|
||||
interface LegendItem {
|
||||
key: string;
|
||||
@@ -79,13 +82,14 @@ export default function VacayAnswerBlock({ cards }: { cards: readonly CardEntry[
|
||||
const first = own[0] ?? null;
|
||||
return (
|
||||
<CardFrame label={t('assistant.card.vacay.label')}>
|
||||
<CardHeader icon={Palmtree} tone="info" title={t('assistant.card.vacay.label')} />
|
||||
{view.months.length > 0 && <VacayMonthStrip view={view} placed={[]} labelOf={() => ''} />}
|
||||
<Legend view={view} />
|
||||
{view.otherDays > 0 && <p className={OTHER}>{t('assistant.card.vacay.otherDays', { count: view.otherDays })}</p>}
|
||||
<VacayBalance lines={lines} view={view} mode="read" />
|
||||
<div className={FOOT}>
|
||||
<CardFoot>
|
||||
<CardOpenButton target={{ kind: 'page', path: vacayPathOf(first) }} labelKey="assistant.card.vacay.open" />
|
||||
</div>
|
||||
</CardFoot>
|
||||
</CardFrame>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,38 +1,18 @@
|
||||
import { type AssistantFoundPlace, categoryIdForKind } from '@trek/shared';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { useCallback } from 'react';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
|
||||
import { useNetworkMode } from '../../hooks/useNetworkMode';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { useCanDo } from '../../store/permissionsStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import type { Assignment } from '../../types';
|
||||
import { dayLabel } from '../../utils/dayLabel';
|
||||
import { haversineKm } from '../../utils/geo';
|
||||
import { safeHexColor } from '../../utils/safeColor';
|
||||
import { formatDistance } from '../../utils/units';
|
||||
import { hasUndecided } from './assistantParts';
|
||||
import { useAssistantScope, useAssistantView } from './assistantViewContext';
|
||||
import { useCardPoint } from './cards/parts/useCardPoint';
|
||||
|
||||
/** A day a found place can be suggested for, named the way the day list names it. */
|
||||
interface StripDay {
|
||||
id: number;
|
||||
/** Its place in the trip, 1 for the first day: "+ Day 3". */
|
||||
n: number;
|
||||
label: string;
|
||||
/** Its weekday, short ("Sat"), for the day grid; null for a day without a date. */
|
||||
weekday: string | null;
|
||||
}
|
||||
|
||||
/** The short weekday of a `YYYY-MM-DD` date, read as that calendar day wherever the reader is. */
|
||||
function weekdayOf(date: string | null | undefined, locale: string): string | null {
|
||||
if (!date || !/^\d{4}-\d{2}-\d{2}$/.test(date)) return null;
|
||||
return new Intl.DateTimeFormat(locale, { weekday: 'short', timeZone: 'UTC' }).format(new Date(`${date}T00:00:00Z`));
|
||||
}
|
||||
|
||||
/** The trip category a found place most likely belongs in, for its line and its icon. */
|
||||
interface StripCategory {
|
||||
name: string;
|
||||
@@ -54,20 +34,17 @@ function lastSpot(stops: readonly Assignment[] | undefined): { lat: number; lng:
|
||||
|
||||
/**
|
||||
* What the strip of found places needs, the same for the window and the
|
||||
* phone: the trip's days to suggest a place for, the day in focus, how far a
|
||||
* place is from that day's last stop, its likely category, whether a
|
||||
* suggestion can be made now and why not, and the map's part (the pin while
|
||||
* the pointer rests on a card, the camera on a click).
|
||||
* phone: the day in focus, how far a place is from that day's last stop, its
|
||||
* likely category, whether a place can be added, and the map's part (the pin
|
||||
* while the pointer rests on a card, the camera on a click).
|
||||
*
|
||||
* Suggesting writes nothing: the server holds the place as a change card to
|
||||
* decide like any other. It waits while another change is undecided, because
|
||||
* one decision answers all open cards.
|
||||
* Adding opens the planner's own place form, filled in with the place and on
|
||||
* the day in focus: the traveller sees everything about it and saves it as
|
||||
* any other place, so nothing waits for the chat's open decisions.
|
||||
*/
|
||||
export function useAssistantPlaceStrip() {
|
||||
const { t, locale } = useTranslation();
|
||||
const { tripId } = useAssistantView();
|
||||
const { tripId, onRevealMap } = useAssistantView();
|
||||
const scope = useAssistantScope();
|
||||
const { offline } = useNetworkMode();
|
||||
const can = useCanDo();
|
||||
const unit = useSettingsStore((s) => s.settings.distance_unit ?? 'metric');
|
||||
const { trip, days, assignments, categories } = useTripStore(
|
||||
@@ -81,44 +58,15 @@ export function useAssistantPlaceStrip() {
|
||||
};
|
||||
})
|
||||
);
|
||||
const { focusDayId, isRunning, threadId, waiting } = useAssistantStore(
|
||||
useShallow((s) => {
|
||||
const chat = chatOf(s, tripId);
|
||||
return {
|
||||
focusDayId: chat.focus?.dayId ?? null,
|
||||
isRunning: chat.isRunning,
|
||||
threadId: chat.threadId,
|
||||
waiting: hasUndecided(chat.messages),
|
||||
};
|
||||
})
|
||||
);
|
||||
const addFoundPlace = useAssistantStore((s) => s.addFoundPlace);
|
||||
const focusDayId = useAssistantStore((s) => chatOf(s, tripId).focus?.dayId ?? null);
|
||||
const openPlaceDraft = useAssistantStore((s) => s.openPlaceDraft);
|
||||
const point = useCardPoint();
|
||||
const [adding, setAdding] = useState<string | null>(null);
|
||||
|
||||
const stripDays = useMemo(
|
||||
(): StripDay[] =>
|
||||
(days ?? []).map((day, index) => ({
|
||||
id: day.id,
|
||||
n: index + 1,
|
||||
label: dayLabel(day, index, t, locale),
|
||||
weekday: weekdayOf(day.date, locale),
|
||||
})),
|
||||
[days, t, locale]
|
||||
);
|
||||
const focusDay = stripDays.find((d) => d.id === focusDayId) ?? null;
|
||||
const focusDay = (days ?? []).find((d) => d.id === focusDayId) ?? null;
|
||||
const from = focusDay && assignments ? lastSpot(assignments[String(focusDay.id)]) : null;
|
||||
|
||||
/**
|
||||
* Whether "+ Day" shows at all: a trip's chat (a journey's has no days), the
|
||||
* planner holds the trip and the user may add to it.
|
||||
*/
|
||||
const canSuggest = scope.kind === 'trip' && !!trip && can('place_edit', trip) && stripDays.length > 0;
|
||||
/** Why "+ Day" is off right now, as a tooltip; null when it is on. */
|
||||
let blockedKey: string | null = null;
|
||||
if (offline) blockedKey = 'assistant.error.offline';
|
||||
else if (waiting) blockedKey = 'assistant.composer.decideFirst';
|
||||
const disabled = blockedKey !== null || isRunning || threadId === null || adding !== null;
|
||||
/** Whether "Add to trip" shows at all: a trip's chat (a journey's has no days), the planner holds the trip and the user may add to it. */
|
||||
const canAdd = scope.kind === 'trip' && !!trip && can('place_edit', trip);
|
||||
|
||||
const categoryOf = (place: AssistantFoundPlace): StripCategory | null => {
|
||||
const id = categoryIdForKind(place.kind, categories);
|
||||
@@ -130,14 +78,11 @@ export function useAssistantPlaceStrip() {
|
||||
const distanceOf = (place: AssistantFoundPlace): string | null =>
|
||||
from ? formatDistance(haversineKm(from, place), unit) : null;
|
||||
|
||||
const suggest = async (place: AssistantFoundPlace, dayId: number) => {
|
||||
if (disabled) return;
|
||||
setAdding(place.ref);
|
||||
try {
|
||||
await addFoundPlace(tripId, place.ref, dayId);
|
||||
} finally {
|
||||
setAdding(null);
|
||||
}
|
||||
/** Opens the place form with it; on the phone the chat steps aside first. */
|
||||
const open = (place: AssistantFoundPlace) => {
|
||||
if (!canAdd || !trip) return;
|
||||
onRevealMap?.();
|
||||
openPlaceDraft(trip.id, place, focusDay?.id ?? null);
|
||||
};
|
||||
|
||||
/** Shows the place on the map; on the phone the chat steps aside first. */
|
||||
@@ -151,17 +96,5 @@ export function useAssistantPlaceStrip() {
|
||||
[hoverPoint]
|
||||
);
|
||||
|
||||
return {
|
||||
days: stripDays,
|
||||
focusDay,
|
||||
canSuggest,
|
||||
disabled,
|
||||
blockedKey,
|
||||
adding,
|
||||
categoryOf,
|
||||
distanceOf,
|
||||
suggest,
|
||||
show,
|
||||
hover,
|
||||
};
|
||||
return { canAdd, categoryOf, distanceOf, open, show, hover };
|
||||
}
|
||||
|
||||
@@ -128,7 +128,7 @@ export function placeEditForm(
|
||||
}
|
||||
|
||||
/** A position the form opens on: a POI tapped on the map, or a right-click on it. */
|
||||
export interface PlacePrefill {
|
||||
export type PlacePrefill = {
|
||||
lat: number
|
||||
lng: number
|
||||
name?: string
|
||||
@@ -136,6 +136,8 @@ export interface PlacePrefill {
|
||||
website?: string
|
||||
phone?: string
|
||||
osm_id?: string
|
||||
/** A place Google knows, such as one the assistant found: the details column reads it by this id. */
|
||||
google_place_id?: string
|
||||
}
|
||||
|
||||
/** A blank form at a prefilled position, with what the POI already knew. */
|
||||
@@ -149,6 +151,7 @@ export function prefillForm(prefill: PlacePrefill, extra: Partial<PlaceFormData>
|
||||
website: prefill.website || '',
|
||||
phone: prefill.phone || '',
|
||||
osm_id: prefill.osm_id,
|
||||
google_place_id: prefill.google_place_id,
|
||||
...extra,
|
||||
}
|
||||
}
|
||||
@@ -170,7 +173,7 @@ export function openingDetailsSelection(
|
||||
}
|
||||
}
|
||||
if (prefill) {
|
||||
return { placeId: prefill.osm_id || undefined, lat: prefill.lat, lng: prefill.lng, name: prefill.name || '' }
|
||||
return { placeId: prefill.google_place_id || prefill.osm_id || undefined, lat: prefill.lat, lng: prefill.lng, name: prefill.name || '' }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import { weekFromPeriods } from './placeHours'
|
||||
import type { PlaceOpeningHours } from '@trek/shared'
|
||||
import {
|
||||
DEFAULT_FORM, endsBeforeStart, findDuplicatePlace, formPin, mergeResult, parseCoordinatePair, placeEditForm, placeFormPayload,
|
||||
prefillForm, type PlaceFormData,
|
||||
prefillForm, type PlaceFormData, type PlacePrefill,
|
||||
} from './PlaceFormModal.helpers'
|
||||
import { useNewCategory, usePlaceForm } from './usePlaceForm'
|
||||
import { usePlaceSearch } from './usePlaceSearch'
|
||||
@@ -64,7 +64,7 @@ interface PlaceFormModalProps {
|
||||
onClose: () => void
|
||||
onSave: (data: PlaceSubmitData, files?: File[]) => Promise<{ id: number } | void> | void
|
||||
place: Place | null
|
||||
prefillCoords?: { lat: number; lng: number; name?: string; address?: string; website?: string; phone?: string; osm_id?: string; stop_type?: RoadtripStopType | null; duration_minutes?: number; category?: string } | null
|
||||
prefillCoords?: (PlacePrefill & { stop_type?: RoadtripStopType | null; duration_minutes?: number; category?: string }) | null
|
||||
tripId: number
|
||||
categories: Category[]
|
||||
onCategoryCreated: (category: { name: string; color?: string; icon?: string }) => Promise<Category> | undefined
|
||||
|
||||
@@ -15,13 +15,15 @@ import type { SaveState } from './useBookStore'
|
||||
* which is exactly the wrong habit for the one time it says something else.
|
||||
*/
|
||||
export function SaveIndicator({
|
||||
state, t, onAcceptTheirs, onKeepMine, onRetry,
|
||||
state, t, onAcceptTheirs, onKeepMine, onRetry, onReload = reloadStudio,
|
||||
}: {
|
||||
state: SaveState
|
||||
t: (k: string) => string
|
||||
onAcceptTheirs: (current: BookRecord) => void
|
||||
onKeepMine: (current: BookRecord) => void
|
||||
onRetry: () => void
|
||||
/** Load this Studio again, for a book a newer one saved. A full reload by default. */
|
||||
onReload?: () => void
|
||||
}) {
|
||||
if (state.status === 'conflict') {
|
||||
return (
|
||||
@@ -43,6 +45,24 @@ export function SaveIndicator({
|
||||
)
|
||||
}
|
||||
|
||||
if (state.status === 'newer') {
|
||||
/*
|
||||
* The one state with a way out the user has to take themselves: a newer
|
||||
* Studio saved this book, this tab cannot write it without losing what
|
||||
* that one added, and only a reload brings the newer Studio here. Loud
|
||||
* like a conflict, because until then nothing done here is kept.
|
||||
*/
|
||||
return (
|
||||
<div className="st-save is-conflict" role="alert">
|
||||
<AlertTriangle size={13} />
|
||||
<span>{t('journey.studio.saveNewer')}</span>
|
||||
<button type="button" onClick={onReload}>
|
||||
{t('journey.studio.saveReload')}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (state.status === 'readonly') {
|
||||
/*
|
||||
* Not an error and not retryable: this person was invited to read the
|
||||
@@ -86,3 +106,8 @@ export function SaveIndicator({
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/** The default way back to a current Studio: the page again, which loads the newest build. */
|
||||
function reloadStudio() {
|
||||
window.location.reload()
|
||||
}
|
||||
|
||||
@@ -260,7 +260,10 @@ function PhotoView({ el, big, print, dropLabel }: {
|
||||
src={photoSrc(el.photoId!, big)}
|
||||
alt=""
|
||||
draggable={false}
|
||||
loading="lazy"
|
||||
// Lazy on the canvas, where a long book scrolls past; eager in print,
|
||||
// where every sheet is laid out at once and a picture the browser put
|
||||
// off is a picture missing from the PDF.
|
||||
loading={print ? 'eager' : 'lazy'}
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* FE-STUDIO-ICON-001 to FE-STUDIO-ICON-002
|
||||
*
|
||||
* The icons the book engine takes (BOOK_ICON_NAMES in @trek/shared) are the
|
||||
* drawings the Studio's icon tab offers, no more and no fewer: one the engine
|
||||
* took that this lucide does not have would print as the fallback glyph, and
|
||||
* one the tab offers that the engine refused would be a drawing a person can
|
||||
* place and the assistant cannot. When lucide-react moves, run
|
||||
* `node scripts/gen-book-icon-names.mjs` in shared/ and this passes again.
|
||||
*/
|
||||
import { BOOK_DESIGN_ICONS, BOOK_ICON_NAMES } from '@trek/shared';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { FEATURED_ICONS, ICON_NAMES } from './iconLibrary';
|
||||
|
||||
describe('the icons the book engine takes', () => {
|
||||
it('FE-STUDIO-ICON-001: are every drawing the icon tab offers, and nothing it does not', () => {
|
||||
// `Icon` is the component every drawing is built on, not a drawing.
|
||||
const offered = ICON_NAMES.filter((name) => name !== 'Icon');
|
||||
const missing = offered.filter((name) => !BOOK_ICON_NAMES.has(name));
|
||||
const extra = [...BOOK_ICON_NAMES].filter((name) => !offered.includes(name));
|
||||
expect({ missing, extra }).toEqual({ missing: [], extra: [] });
|
||||
});
|
||||
|
||||
it('FE-STUDIO-ICON-002: hold the whole travel shelf the tab opens on', () => {
|
||||
expect(BOOK_DESIGN_ICONS.filter((name) => !BOOK_ICON_NAMES.has(name))).toEqual([]);
|
||||
expect(FEATURED_ICONS).toEqual([...BOOK_DESIGN_ICONS]);
|
||||
});
|
||||
});
|
||||
@@ -60,9 +60,10 @@ export const ICON_NAMES: string[] = buildNames()
|
||||
* of them quietly drops it instead of drawing a fallback in the shelf.
|
||||
*/
|
||||
/*
|
||||
* The shelf itself lives in @trek/shared (book-icons.ts), because the book
|
||||
* engine places icons from the same list: the assistant may only name a
|
||||
* drawing a person could pick here.
|
||||
* The shelf itself lives in @trek/shared (book-icons.ts), beside the whole
|
||||
* list the book engine takes (BOOK_ICON_NAMES): the assistant may name any
|
||||
* drawing a person could pick here, and iconLibrary.test.ts holds that list
|
||||
* to ICON_NAMES.
|
||||
*/
|
||||
const FEATURED: readonly string[] = BOOK_DESIGN_ICONS
|
||||
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* FE-STUDIO-PRINT-001 to FE-STUDIO-PRINT-004
|
||||
*
|
||||
* When the print view of a book may be printed: every picture in, the SVG
|
||||
* ones too wherever they sit (a map marker, a photo behind a clip path), and
|
||||
* a ceiling that gives a book of many photographs longer before the Save
|
||||
* button gives up waiting.
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { printReadyCeilingMs, svgImagesToWait, whenReady } from './printReady';
|
||||
|
||||
const SVG = 'http://www.w3.org/2000/svg';
|
||||
const XLINK = 'http://www.w3.org/1999/xlink';
|
||||
|
||||
/** A print document as the frame holds it, built from markup. */
|
||||
function printDoc(markup: string): Document {
|
||||
const doc = document.implementation.createHTMLDocument('print');
|
||||
doc.body.innerHTML = markup;
|
||||
return doc;
|
||||
}
|
||||
|
||||
/** An iframe whose document and window are the given ones, as the print view's frame is once it loaded. */
|
||||
function frameOf(doc: Document, win: Partial<Window> = {}): HTMLIFrameElement {
|
||||
const iframe = document.createElement('iframe');
|
||||
Object.defineProperty(iframe, 'contentDocument', { value: doc, configurable: true });
|
||||
Object.defineProperty(iframe, 'contentWindow', { value: win, configurable: true });
|
||||
return iframe;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('the pictures to wait for', () => {
|
||||
it('FE-STUDIO-PRINT-001: finds an SVG image inside a clip path and in the defs, not only a marker photo', () => {
|
||||
const doc = printDoc(
|
||||
`<svg xmlns="${SVG}"><defs><clipPath id="c"><image href="/a.jpg"/></clipPath>` +
|
||||
`<image id="d" href="/b.jpg"/></defs><image href="/c.jpg"/></svg>`
|
||||
);
|
||||
expect(svgImagesToWait(doc).map((el) => el.getAttribute('href'))).toEqual(['/a.jpg', '/b.jpg', '/c.jpg']);
|
||||
});
|
||||
|
||||
it('FE-STUDIO-PRINT-002: takes an xlink source, and leaves out an image that names none and would never load', () => {
|
||||
const doc = printDoc(`<svg xmlns="${SVG}"><image/></svg>`);
|
||||
const linked = doc.createElementNS(SVG, 'image');
|
||||
linked.setAttributeNS(XLINK, 'xlink:href', '/x.jpg');
|
||||
doc.querySelector('svg')?.appendChild(linked);
|
||||
expect(svgImagesToWait(doc)).toEqual([linked]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the ceiling', () => {
|
||||
it('FE-STUDIO-PRINT-003: waits eight seconds for an ordinary book and fifteen for one of more than 40 photos', () => {
|
||||
expect(printReadyCeilingMs(0)).toBe(8000);
|
||||
expect(printReadyCeilingMs(40)).toBe(8000);
|
||||
expect(printReadyCeilingMs(41)).toBe(15000);
|
||||
});
|
||||
|
||||
it('FE-STUDIO-PRINT-004: holds a large book past eight seconds while an image is still loading', async () => {
|
||||
vi.useFakeTimers();
|
||||
const many = Array.from({ length: 41 }, (_, i) => `<image href="/p${i}.jpg"/>`).join('');
|
||||
const doc = printDoc(`<svg xmlns="${SVG}">${many}</svg>`);
|
||||
let ready = false;
|
||||
// A window without its own timers: the wait falls back to the global one, which the fake timers drive.
|
||||
void whenReady(frameOf(doc)).then(() => {
|
||||
ready = true;
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(8100);
|
||||
expect(ready).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(7000);
|
||||
expect(ready).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* When the print view of a book is actually printable.
|
||||
*
|
||||
* Both halves matter and neither is covered by the load event: a photograph
|
||||
* still decoding prints as an empty box, and a face still loading prints in the
|
||||
* fallback, the exact substitution the bundled typefaces exist to prevent.
|
||||
*/
|
||||
|
||||
/** How long the print view waits at most, and the photo count past which a book gets the longer wait. */
|
||||
const PRINT_READY = {
|
||||
ceilingMs: 8000,
|
||||
largeCeilingMs: 15000,
|
||||
largeBookPhotos: 40,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* The longest the Save button stays off for a book of `photos` pictures. A
|
||||
* book of a few dozen photographs from a slow provider can take longer than
|
||||
* eight seconds to decode; one that has not finished must not go to the press.
|
||||
*/
|
||||
export function printReadyCeilingMs(photos: number): number {
|
||||
return photos > PRINT_READY.largeBookPhotos ? PRINT_READY.largeCeilingMs : PRINT_READY.ceilingMs;
|
||||
}
|
||||
|
||||
/** What `whenReady` reads off the print document: its `<img>` elements, its SVG and its fonts. */
|
||||
interface PrintDocument {
|
||||
images: ArrayLike<Element & { complete?: boolean }>;
|
||||
querySelectorAll?: (selector: string) => ArrayLike<Element>;
|
||||
fonts?: { ready: Promise<unknown> };
|
||||
}
|
||||
|
||||
const XLINK = 'http://www.w3.org/1999/xlink';
|
||||
|
||||
/**
|
||||
* The SVG pictures to wait for: every `<image>` that names a source, wherever
|
||||
* it sits. `doc.images` does not collect them, and they are not only the
|
||||
* photographs in a map's markers: a photo cut to a mask or set behind clipped
|
||||
* type is an `<image>` inside a `<clipPath>` or `<defs>`, which the selector
|
||||
* reaches just the same. One that names no source would never fire an event,
|
||||
* so it is left out rather than left to hold the button until the ceiling.
|
||||
*/
|
||||
export function svgImagesToWait(doc: PrintDocument): Element[] {
|
||||
const found = Array.from(doc.querySelectorAll?.('image') ?? []);
|
||||
return found.filter((el) => !!(el.getAttribute('href') || el.getAttributeNS(XLINK, 'href')));
|
||||
}
|
||||
|
||||
/** Resolves when the element has loaded or failed: a picture that will not load must not hold the button hostage. */
|
||||
function settle(el: Element): Promise<void> {
|
||||
return new Promise<void>((resolve) => {
|
||||
el.addEventListener('load', () => resolve(), { once: true });
|
||||
el.addEventListener('error', () => resolve(), { once: true });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait until the print view's pictures and faces are in, or until the
|
||||
* ceiling, which rises for a book with many photographs. Without `complete`
|
||||
* on an SVG image there is no way to tell one that is still coming from one
|
||||
* whose events fired before this ran, and a Save button that never enables is
|
||||
* worse than a marker that prints blank.
|
||||
*/
|
||||
export async function whenReady(iframe: HTMLIFrameElement): Promise<void> {
|
||||
const win = iframe.contentWindow;
|
||||
const doc = iframe.contentDocument as PrintDocument | null;
|
||||
if (!win || !doc) return;
|
||||
|
||||
const imgs = Array.from(doc.images);
|
||||
const svg = svgImagesToWait(doc);
|
||||
const images = imgs.map((img) => (img.complete ? Promise.resolve() : settle(img)));
|
||||
|
||||
const wait = win.setTimeout?.bind(win) ?? setTimeout;
|
||||
const ceiling = new Promise<void>((resolve) => {
|
||||
wait(resolve, printReadyCeilingMs(imgs.length + svg.length));
|
||||
});
|
||||
|
||||
await Promise.race([Promise.all([...images, ...svg.map(settle), doc.fonts?.ready ?? Promise.resolve()]), ceiling]);
|
||||
}
|
||||
@@ -23,6 +23,8 @@
|
||||
* standalone PWA. An overlay with a `srcdoc` iframe works everywhere.
|
||||
*/
|
||||
|
||||
import { whenReady } from './printReady'
|
||||
|
||||
/*
|
||||
* The only literal colours in Studio, and deliberately so.
|
||||
*
|
||||
@@ -254,47 +256,3 @@ ${singleRule(input)}
|
||||
|
||||
return close
|
||||
}
|
||||
|
||||
/**
|
||||
* When the document is actually printable.
|
||||
*
|
||||
* Both halves matter and neither is covered by the load event: a photograph
|
||||
* still decoding prints as an empty box, and a face still loading prints in the
|
||||
* fallback — the exact substitution the bundled typefaces exist to prevent.
|
||||
*/
|
||||
async function whenReady(iframe: HTMLIFrameElement): Promise<void> {
|
||||
const win = iframe.contentWindow
|
||||
const doc = iframe.contentDocument
|
||||
if (!win || !doc) return
|
||||
|
||||
const settle = (el: Element) => new Promise<void>(resolve => {
|
||||
// A picture that will not load must not hold the button hostage — better a
|
||||
// book with one gap than a dialog that never finishes.
|
||||
el.addEventListener('load', () => resolve(), { once: true })
|
||||
el.addEventListener('error', () => resolve(), { once: true })
|
||||
})
|
||||
|
||||
const images = Array.from(doc.images).map(img => (img.complete ? Promise.resolve() : settle(img)))
|
||||
|
||||
/*
|
||||
* The photographs inside the map's markers are SVG `<image>`, which
|
||||
* `doc.images` does not collect and which has no `complete` to ask, so there
|
||||
* is nothing to do but wait on the events. Missing them meant a book could go
|
||||
* to print with its route beads still blank.
|
||||
*/
|
||||
const svgImages = Array.from(doc.querySelectorAll?.('image') ?? []).map(settle)
|
||||
|
||||
/*
|
||||
* And a ceiling over the lot. Without `complete` to fall back on there is no
|
||||
* way to tell a picture that is still coming from one whose events already
|
||||
* fired before this ran, and a Save button that never enables is worse than a
|
||||
* marker that prints blank.
|
||||
*/
|
||||
const wait = win.setTimeout?.bind(win) ?? setTimeout
|
||||
const ceiling = new Promise<void>(resolve => { wait(resolve, 8000) })
|
||||
|
||||
await Promise.race([
|
||||
Promise.all([...images, ...svgImages, doc.fonts?.ready ?? Promise.resolve()]),
|
||||
ceiling,
|
||||
])
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import type { BookDocument, BookRecord } from '@trek/shared'
|
||||
import { normalizeBookDocument } from '@trek/shared'
|
||||
import { BOOK_SCHEMA_NEWER_CODE, readBookDocument, stampBookSchemaRev } from '@trek/shared'
|
||||
import { journeyApi } from '../../api/client'
|
||||
import { addListener, removeListener } from '../../api/websocket'
|
||||
|
||||
@@ -54,6 +54,16 @@ import { addListener, removeListener } from '../../api/websocket'
|
||||
* either: it is remembered and read once that work has reached the server,
|
||||
* because the save response and the broadcast travel on different channels and
|
||||
* either can arrive first.
|
||||
*
|
||||
* ── Why a book from a newer Studio is never written ───────────────────────
|
||||
*
|
||||
* A document says which revision of the format wrote it (book-schema-rev.ts).
|
||||
* This build reads a newer one as far as it can, and what it cannot read is
|
||||
* already gone from the copy it holds: saving that copy would delete the rest
|
||||
* for everyone. So such a book is shown and never written, the same way a
|
||||
* viewer's is, until a reload brings the Studio that wrote it. The server
|
||||
* refuses the save as well, which covers a tab that loaded the book before the
|
||||
* newer Studio saved it.
|
||||
*/
|
||||
|
||||
/** How long the document has to stay still before it is written. */
|
||||
@@ -69,6 +79,8 @@ export type SaveState =
|
||||
| { status: 'conflict'; current: BookRecord }
|
||||
/** The journey is open to this user, but they may not write it (role 'viewer'). */
|
||||
| { status: 'readonly' }
|
||||
/** The book was saved by a newer Studio than this one: shown, never written, until a reload. */
|
||||
| { status: 'newer' }
|
||||
| { status: 'error' }
|
||||
|
||||
/** What the editor needs to know about a version it is handed from elsewhere. */
|
||||
@@ -176,7 +188,12 @@ export function useBookStore(
|
||||
* agreed document by identity, so a consumer that normalised on its own
|
||||
* would hand back a different object and turn every open into a save.
|
||||
*/
|
||||
const book = res.book ? { ...res.book, document: normalizeBookDocument(res.book.document) } : null
|
||||
const read = res.book ? readBookDocument(res.book.document) : null
|
||||
const book = res.book && read ? { ...res.book, document: read.document } : null
|
||||
if (read?.newer) {
|
||||
blocked.current = true
|
||||
setState({ status: 'newer' })
|
||||
}
|
||||
setRecord(book)
|
||||
version.current = book?.version ?? null
|
||||
bookId.current = book?.id ?? null
|
||||
@@ -201,7 +218,8 @@ export function useBookStore(
|
||||
try {
|
||||
const saved = await journeyApi.saveBook(journeyId, {
|
||||
title: next.title,
|
||||
document: next.document,
|
||||
// Stamped on the way out only: `synced` below keeps the editor's own object.
|
||||
document: stampBookSchemaRev(next.document),
|
||||
baseVersion: version.current ?? undefined,
|
||||
})
|
||||
setRecord(saved)
|
||||
@@ -217,8 +235,12 @@ export function useBookStore(
|
||||
* not need a second request: the editor can offer to take their version
|
||||
* or keep going from here, and either way it can say whose work it is.
|
||||
*/
|
||||
const res = (err as { response?: { status?: number; data?: { current?: BookRecord } } }).response
|
||||
if (res?.status === 409 && res.data?.current) {
|
||||
const res = (err as { response?: { status?: number; data?: { current?: BookRecord; code?: string } } }).response
|
||||
if (res?.status === 409 && res.data?.code === BOOK_SCHEMA_NEWER_CODE) {
|
||||
// A newer Studio saved the book since this tab read it: nothing here may be written over it.
|
||||
blocked.current = true
|
||||
setState({ status: 'newer' })
|
||||
} else if (res?.status === 409 && res.data?.current) {
|
||||
blocked.current = true
|
||||
setState({ status: 'conflict', current: res.data.current })
|
||||
} else if (res?.status === 403) {
|
||||
@@ -305,15 +327,15 @@ export function useBookStore(
|
||||
|
||||
/** Take the other version, discarding the local one. */
|
||||
const acceptTheirs = useCallback((current: BookRecord) => {
|
||||
const document = normalizeBookDocument(current.document)
|
||||
blocked.current = false
|
||||
const { document, newer } = readBookDocument(current.document)
|
||||
blocked.current = newer
|
||||
setRecord({ ...current, document })
|
||||
version.current = current.version
|
||||
bookId.current = current.id
|
||||
synced.current = document
|
||||
latest.current = document
|
||||
pending.current = null
|
||||
setState({ status: 'idle' })
|
||||
setState(newer ? { status: 'newer' } : { status: 'idle' })
|
||||
// A save from elsewhere passed over while the conflict was open may be
|
||||
// newer than the record it carried.
|
||||
catchUp.current()
|
||||
@@ -388,8 +410,12 @@ export function useBookStore(
|
||||
if (sameBook && !isNewer(res.book.version)) return
|
||||
// Normalised for the same reason the initial load is: a document
|
||||
// written by an older build is missing whatever the contract has
|
||||
// gained since.
|
||||
const document = normalizeBookDocument(res.book.document)
|
||||
// gained since. One written by a newer build is shown and held.
|
||||
const { document, newer } = readBookDocument(res.book.document)
|
||||
if (newer) {
|
||||
blocked.current = true
|
||||
setState({ status: 'newer' })
|
||||
}
|
||||
const held = version.current
|
||||
const taken = res.book.version
|
||||
// Undoable only when every save it folds in, past the version held,
|
||||
|
||||
@@ -625,7 +625,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
|
||||
<TourPlannerMapStage
|
||||
tripId={tripId} mapTileUrl={mapTileUrl} leftHidden={leftHidden} rightHidden={rightHidden} t={t}
|
||||
tourPlanner={tourPlanner} tourMap={tourMap} locationSearch={locationSearch} canPlaceEdit={canPlaceEdit}
|
||||
leftPanelPx={leftPanelPx} rightPanelPx={rightPanelPx}
|
||||
leftPanelPx={leftPanelPx} rightPanelPx={rightPanelPx} assistantRoutes={assistantMap}
|
||||
onViewportChange={wandererBrowser.onViewportChange} paddleChecklist={pageState.paddleChecklist}
|
||||
/>
|
||||
<div className="hidden md:block" style={{ position: 'absolute', left: 10, top: 10, bottom: 10, zIndex: 20 }}>
|
||||
|
||||
@@ -68,7 +68,7 @@ function seedJourney() {
|
||||
beforeEach(() => {
|
||||
seedJourney()
|
||||
buildBook.mockClear()
|
||||
useStudioStore.setState({ doc: null, selection: [], activeSpread: 0, past: [], future: [] })
|
||||
useStudioStore.setState({ doc: null, selection: [], activeSpread: 0, past: [], future: [], readOnly: false })
|
||||
vi.spyOn(journeyApi, 'getBook').mockResolvedValue({ book: null } as never)
|
||||
vi.spyOn(journeyApi, 'saveBook').mockResolvedValue({} as never)
|
||||
vi.spyOn(journeyApi, 'stats').mockResolvedValue(stats() as never)
|
||||
@@ -295,6 +295,31 @@ describe('pictures and stops', () => {
|
||||
|
||||
expect(result.current.canEdit).toBe(false)
|
||||
})
|
||||
|
||||
/*
|
||||
* A book a newer Studio saved has already lost, in this copy, what this build
|
||||
* cannot read. It is shown and never changed, for every role, and let go once
|
||||
* Studio closes so the next book opens as it should.
|
||||
*/
|
||||
it('FE-STUDIO-REV-001: holds a book a newer Studio saved read-only until Studio closes', async () => {
|
||||
const document = { ...shared.blankBook({ title: 'Iceland' }), schemaRev: shared.BOOK_SCHEMA_REV + 1 }
|
||||
vi.mocked(journeyApi.getBook).mockResolvedValue({
|
||||
book: { id: 3, journeyId: 9, title: 'Iceland', version: 4, updatedAt: '', updatedBy: 1, document },
|
||||
} as never)
|
||||
const { result, unmount } = await mountStudio()
|
||||
|
||||
await waitFor(() => expect(result.current.saveState.status).toBe('newer'))
|
||||
expect(result.current.canEdit).toBe(false)
|
||||
expect(result.current.canUndo).toBe(false)
|
||||
expect(useStudioStore.getState().readOnly).toBe(true)
|
||||
const before = useStudioStore.getState().doc
|
||||
act(() => { useStudioStore.getState().commit(d => ({ ...d, title: 'edited' })) })
|
||||
expect(useStudioStore.getState().doc).toBe(before)
|
||||
expect(journeyApi.saveBook).not.toHaveBeenCalled()
|
||||
|
||||
unmount()
|
||||
expect(useStudioStore.getState().readOnly).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
@@ -355,7 +380,7 @@ describe('saves from elsewhere', () => {
|
||||
const { ok } = await openAndFlush()
|
||||
expect(ok).toBe(true)
|
||||
const calls = vi.mocked(journeyApi.saveBook).mock.calls
|
||||
expect(calls[calls.length - 1][1].document.title).toBe('edited')
|
||||
expect((calls[calls.length - 1][1].document as { title?: string }).title).toBe('edited')
|
||||
})
|
||||
|
||||
it('FE-STUDIO-WIRE-002: a save of this user keeps the page by its id and is one undo away', async () => {
|
||||
|
||||
@@ -78,6 +78,7 @@ export function useJourneyStudio() {
|
||||
const past = useStudioStore(s => s.past)
|
||||
const future = useStudioStore(s => s.future)
|
||||
const commit = useStudioStore(s => s.commit)
|
||||
const setReadOnly = useStudioStore(s => s.setReadOnly)
|
||||
|
||||
const journeyId = Number(id)
|
||||
const backTo = `/journey/${id}`
|
||||
@@ -117,6 +118,21 @@ export function useJourneyStudio() {
|
||||
// every render — depending on that made the save effect fire per render.
|
||||
const { queueSave, saveNow, loaded: bookLoaded } = book
|
||||
|
||||
/*
|
||||
* A book a newer Studio saved is shown and never changed here.
|
||||
*
|
||||
* This build read it as far as it could, and what it could not read is gone
|
||||
* from its copy, so an edit made now could only ever be saved by deleting
|
||||
* the rest. The store refuses edits while this holds and the controls that
|
||||
* add to the book go with `canEdit`; the save indicator asks for a reload.
|
||||
* Released when Studio closes, so the next book opens as it should.
|
||||
*/
|
||||
const newerBook = book.state.status === 'newer'
|
||||
useEffect(() => {
|
||||
setReadOnly(newerBook)
|
||||
return () => setReadOnly(false)
|
||||
}, [newerBook, setReadOnly])
|
||||
|
||||
/*
|
||||
* Who else is in here, and where their pointers are.
|
||||
*
|
||||
@@ -595,9 +611,10 @@ export function useJourneyStudio() {
|
||||
/*
|
||||
* A viewer may open the book and change nothing: not the pages, not the
|
||||
* journey behind them. The server refuses either anyway; this keeps the
|
||||
* controls that would only ever answer with a 403 off the screen.
|
||||
* controls that would only ever answer with a 403 off the screen. A book a
|
||||
* newer Studio saved is held the same way, for everyone (see `newerBook`).
|
||||
*/
|
||||
const canEdit = (journey?.my_role ?? 'owner') !== 'viewer'
|
||||
const canEdit = (journey?.my_role ?? 'owner') !== 'viewer' && !newerBook
|
||||
const toast = useToast()
|
||||
|
||||
/**
|
||||
@@ -798,8 +815,8 @@ export function useJourneyStudio() {
|
||||
|
||||
undo,
|
||||
redo,
|
||||
canUndo: past.length > 0,
|
||||
canRedo: future.length > 0,
|
||||
canUndo: !newerBook && past.length > 0,
|
||||
canRedo: !newerBook && future.length > 0,
|
||||
|
||||
pxPerMm: PX_PER_MM,
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { useOutsidePressGuard } from '../../components/Ferratas/useOutsidePressG
|
||||
import { MAP_LAYER_SWITCHER_INSET, MAP_ROUND_CONTROL_SIZE } from '../../components/Map/MapLayerSwitcher';
|
||||
import { MapUndoHint } from '../../components/Map/MapUndoHint';
|
||||
import { MapViewAuto as MapView } from '../../components/Map/MapViewAuto';
|
||||
import type { AssistantMapProps } from '../../components/Map/mapViewContract';
|
||||
import LocationSelect from '../../components/Planner/LocationSelect';
|
||||
import { ChecklistObstaclePanel } from '../../components/Tours/paddle/ObstacleDecisionPanel';
|
||||
import PaddleObstacleOverlay from '../../components/Tours/paddle/PaddleObstacleOverlay';
|
||||
@@ -74,6 +75,11 @@ export interface TourPlannerMapStageProps
|
||||
onViewportChange?: (bounds: FerrataBbox) => void;
|
||||
/** The open paddle tour's checklist (PAD-06): its part for the picked object rides in the object's map card. */
|
||||
paddleChecklist?: PageState['paddleChecklist'];
|
||||
/** The routes the assistant's cards show and its camera, as on the plan's map, so a proposed hike shows here too. */
|
||||
assistantRoutes?: Pick<
|
||||
AssistantMapProps,
|
||||
'assistantCamera' | 'assistantRouteLines' | 'onAssistantRouteHover' | 'onAssistantRoutePoint'
|
||||
>;
|
||||
}
|
||||
|
||||
/** What the map reads of the tour on screen: a GPX file viewed as it came in has its analysis and no points. */
|
||||
@@ -104,6 +110,7 @@ export function TourPlannerMapStage({
|
||||
rightPanelPx,
|
||||
onViewportChange,
|
||||
paddleChecklist,
|
||||
assistantRoutes,
|
||||
}: Readonly<TourPlannerMapStageProps>): ReactElement {
|
||||
const [terrain3d, setTerrain3d] = useState(false);
|
||||
// How high the 3D map's controls reach: one row, or two once the grade legend moved above the dock.
|
||||
@@ -285,6 +292,7 @@ export function TourPlannerMapStage({
|
||||
onViewportChange={viewportChanged}
|
||||
placeTool={placeTool}
|
||||
{...poiMarkers}
|
||||
{...assistantRoutes}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
import { useAssistantStore } from '../../store/assistantStore';
|
||||
import type { PlaceFormOpeners } from './usePlaceFormOpeners';
|
||||
|
||||
/**
|
||||
* A place the assistant found, opened in the place form when its card is
|
||||
* clicked: filled in with what the search knew, the details column reading
|
||||
* the rest (photos, hours, description) by its Google id. The form is the
|
||||
* planner's own, so the place is saved as any other, on the day in focus.
|
||||
*/
|
||||
export function useAssistantPlaceDraft(tripId: number, openAddPlaceFromPoi: PlaceFormOpeners['openAddPlaceFromPoi']) {
|
||||
const draft = useAssistantStore((s) => (s.placeDraft?.tripId === tripId ? s.placeDraft : null));
|
||||
const takePlaceDraft = useAssistantStore((s) => s.takePlaceDraft);
|
||||
|
||||
useEffect(() => {
|
||||
if (!draft) return;
|
||||
takePlaceDraft(draft.seq);
|
||||
const { place } = draft;
|
||||
openAddPlaceFromPoi(
|
||||
{
|
||||
lat: place.lat,
|
||||
lng: place.lng,
|
||||
name: place.name,
|
||||
address: place.address,
|
||||
website: null,
|
||||
phone: null,
|
||||
osm_id: place.osmId ?? '',
|
||||
google_place_id: place.googlePlaceId,
|
||||
poi_type: place.kind,
|
||||
},
|
||||
draft.dayId
|
||||
);
|
||||
}, [draft, openAddPlaceFromPoi, takePlaceDraft]);
|
||||
}
|
||||
@@ -76,7 +76,7 @@ export function usePlaceFormOpeners(options: PlaceFormOpenersOptions) {
|
||||
// Open the Add-Place form pre-filled from an OSM "explore" POI marker: all the
|
||||
// data already comes from the POI, so no reverse-geocode is needed.
|
||||
const openAddPlaceFromPoi = useCallback((
|
||||
poi: { lat: number; lng: number; name: string; address: string | null; website: string | null; phone: string | null; osm_id: string; category?: string | null; poi_type?: string | null },
|
||||
poi: { lat: number; lng: number; name: string; address: string | null; website: string | null; phone: string | null; osm_id: string; google_place_id?: string | null; category?: string | null; poi_type?: string | null },
|
||||
dayId?: number | null,
|
||||
/** Index within that day. Omitted, the place is appended, which is what every caller did before. */
|
||||
position?: number | null,
|
||||
@@ -100,6 +100,7 @@ export function usePlaceFormOpeners(options: PlaceFormOpenersOptions) {
|
||||
// A plugin POI's `plugin:<pluginId>:<id>` rides along as it is. The server never
|
||||
// takes that prefix for a Google place id, so the details column makes no Google call.
|
||||
osm_id: poi.osm_id,
|
||||
google_place_id: poi.google_place_id || undefined,
|
||||
// What the map search filed it under, so the form can preselect a category (#2282).
|
||||
category: poi.poi_type || poi.category || undefined,
|
||||
stop_type: stop?.stopType ?? null,
|
||||
|
||||
@@ -27,7 +27,7 @@ export function usePlannerDialogs(options: PlannerDialogsOptions) {
|
||||
const { tripId, tripActions, searchParams, setSearchParams } = options
|
||||
const [showPlaceForm, setShowPlaceForm] = useState<boolean>(false)
|
||||
const [editingPlace, setEditingPlace] = useState<Place | null>(null)
|
||||
const [prefillCoords, setPrefillCoords] = useState<{ lat: number; lng: number; name?: string; address?: string; website?: string; phone?: string; osm_id?: string; stop_type?: RoadtripStopType | null; duration_minutes?: number; category?: string } | null>(null)
|
||||
const [prefillCoords, setPrefillCoords] = useState<{ lat: number; lng: number; name?: string; address?: string; website?: string; phone?: string; osm_id?: string; google_place_id?: string; stop_type?: RoadtripStopType | null; duration_minutes?: number; category?: string } | null>(null)
|
||||
const [editingAssignmentId, setEditingAssignmentId] = useState<number | null>(null)
|
||||
// Day context of the open form. Set only by the day-scoped entry points (the
|
||||
// mobile day toolbar, a long-press on the mobile map); every other opener
|
||||
|
||||
@@ -52,6 +52,7 @@ import { usePlannerDialogs } from './usePlannerDialogs'
|
||||
import { usePlaceDeepLink } from './usePlaceDeepLink'
|
||||
import { useAssistantDeepLink } from './useAssistantDeepLink'
|
||||
import { useAssistantCompareView, useAssistantMapLink } from './useAssistantMapLink'
|
||||
import { useAssistantPlaceDraft } from './useAssistantPlaceDraft'
|
||||
import { usePlannerMapView } from './usePlannerMapView'
|
||||
import { useMapPlaces } from './useMapPlaces'
|
||||
import { useRoadtripFeed } from './useRoadtripFeed'
|
||||
@@ -593,6 +594,7 @@ export function useTripPlanner() {
|
||||
setPrefillCoords, setEditingPlace, setEditingAssignmentId, setPlaceFormDayId, setPlaceFormPosition, setShowPlaceForm,
|
||||
roadtripActive, roadtripFeedActive, roadtripRoutes, roadtripCorridor, manualStopTargetFor, isTourPlace,
|
||||
})
|
||||
useAssistantPlaceDraft(tripId, openAddPlaceFromPoi)
|
||||
|
||||
const {
|
||||
handleReorder, handleReorderDays, handleUpdateDayTitle, handleMoveToDay, handleRemoveAssignment,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* FE-AI-ROUTE-001 to FE-AI-ROUTE-005
|
||||
* FE-AI-ROUTE-001 to FE-AI-ROUTE-006
|
||||
*
|
||||
* Which routes of the chat's cards the plan's map draws, and how: changes
|
||||
* that still stand on the map with the way they replace, the cards of the
|
||||
@@ -127,6 +127,20 @@ describe('assistantRouteModel', () => {
|
||||
expect(refs[1]?.card).toBe(SAVED);
|
||||
});
|
||||
|
||||
it('FE-AI-ROUTE-006: once one of the ways is taken into the trip, the answer draws none of them; a discarded take brings them back', () => {
|
||||
const latest = message([...read('call_1', HIKE), ...read('call_2', GENTLE)], 'msg-1');
|
||||
const take = (approval: Approval) => {
|
||||
const parts = held('t1', PENDING, approval);
|
||||
const change = parts[1] as Extract<AssistantMessagePart, { type: 'data-trek-change' }>;
|
||||
change.data = { ...change.data, takenFrom: 'call_2' };
|
||||
return message(parts, 'msg-2');
|
||||
};
|
||||
const waiting = routeRefs([latest, take({})], {}, NOBODY, LOOK, AS_WAYS);
|
||||
expect(waiting.map((ref) => `${ref.toolCallId}:${ref.use}`)).toEqual(['t1:before', 't1:pending']);
|
||||
const discarded = routeRefs([latest, take({ approved: false })], {}, NOBODY, LOOK, AS_WAYS);
|
||||
expect(discarded.map((ref) => ref.toolCallId)).toEqual(['call_1', 'call_2']);
|
||||
});
|
||||
|
||||
it("FE-AI-ROUTE-003: lines lie in order (replaced way, others, the chosen way, the lit one) in their ways' colours", () => {
|
||||
const previous = { line: flat(HIKE), distanceM: 8000, ascentM: null, minutes: null };
|
||||
const messages = [
|
||||
|
||||
@@ -101,7 +101,8 @@ function standsOnMap(part: ToolCallPart, receipt: AssistantApplied | undefined,
|
||||
/**
|
||||
* The cards of the latest answer that draws any, laid out as the chat lays
|
||||
* them out: a group of several is a choice of ways, each with its letter, the
|
||||
* chosen one (by `picks`, else the first) picked. Older answers drop.
|
||||
* chosen one (by `picks`, else the first) picked. Older answers drop, and so
|
||||
* do the ways of a group once one of them was taken into the trip.
|
||||
*/
|
||||
function lookRefs(
|
||||
messages: readonly AssistantMessage[],
|
||||
@@ -111,6 +112,7 @@ function lookRefs(
|
||||
layout: AnswerLayout
|
||||
): RouteRef[] {
|
||||
const chosenIds = new Set(Object.values(picks));
|
||||
const taken = takenProposals(messages);
|
||||
for (let index = messages.length - 1; index >= 0; index--) {
|
||||
const answers = (messages[index]?.parts ?? []).flatMap((part): RouteCardEntry[] =>
|
||||
part.type === 'data-trek-card' && part.data.card && !changeIds.has(part.data.toolCallId)
|
||||
@@ -121,6 +123,7 @@ function lookRefs(
|
||||
const drawn = new Set(lined.map((entry) => entry.toolCallId));
|
||||
if (drawn.size === 0) continue;
|
||||
return layout(answers).flatMap((group) => {
|
||||
if (group.some((entry) => taken.has(entry.toolCallId))) return [];
|
||||
const ways = group.length >= 2;
|
||||
const chosen = group.find((entry) => chosenIds.has(entry.toolCallId)) ?? group[0];
|
||||
return group.flatMap((entry, position): RouteRef[] => {
|
||||
@@ -133,6 +136,28 @@ function lookRefs(
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* The proposals taken into the trip ("Plan this") and not discarded since:
|
||||
* each stands as its change from then on, so its answer's ways leave the map.
|
||||
*/
|
||||
function takenProposals(messages: readonly AssistantMessage[]): Set<string> {
|
||||
const dropped = new Set<string>();
|
||||
for (const message of messages) {
|
||||
for (const part of message.parts) {
|
||||
if (part.type !== 'tool-call' || !part.approval) continue;
|
||||
if (part.approval.approved === false || part.approval.resolution) dropped.add(part.toolCallId);
|
||||
}
|
||||
}
|
||||
const taken = new Set<string>();
|
||||
for (const message of messages) {
|
||||
for (const part of message.parts) {
|
||||
if (part.type !== 'data-trek-change' || !part.data.takenFrom) continue;
|
||||
if (!dropped.has(part.data.toolCallId)) taken.add(part.data.takenFrom);
|
||||
}
|
||||
}
|
||||
return taken;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every card of the chat the map draws now, in the part it plays: the
|
||||
* changes that still stand on the map (each with the way it replaces), then
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
type AssistantDecision,
|
||||
type AssistantErrorCode,
|
||||
type AssistantFocus,
|
||||
type AssistantFoundPlace,
|
||||
type AssistantMapView,
|
||||
type AssistantMention,
|
||||
type AssistantMessage,
|
||||
@@ -149,6 +150,8 @@ interface AssistantState {
|
||||
routeFocus: { tripId: number; ref: string; focus: RouteProfileFocus; source: 'card' | 'map' } | null;
|
||||
/** A line a card asks the map to draw while the pointer rests on it (a day of a drive, a saved tour). */
|
||||
routePreview: { tripId: number; ref: string; lines: LatLng[][]; color: string } | null;
|
||||
/** A found place to open in the planner's place form, filled in; `seq` tells a new one from the same place asked again. */
|
||||
placeDraft: { tripId: number; seq: number; place: AssistantFoundPlace; dayId: number | null } | null;
|
||||
/** The route card the phone shows over the map. */
|
||||
routePeek: { tripId: number; toolCallId: string } | null;
|
||||
/** Where the floating window sits after its last move or resize, for the map to frame around it. */
|
||||
@@ -207,6 +210,9 @@ interface AssistantState {
|
||||
|
||||
setMapHover: (tripId: number, hoveredId: string | null, source: AssistantMapSource) => void;
|
||||
requestCamera: (tripId: number, points: LatLng[], mode: 'fit' | 'pan', why: 'user' | 'auto') => void;
|
||||
/** Opens a found place in the planner's place form; the planner takes it with `takePlaceDraft`. */
|
||||
openPlaceDraft: (tripId: number, place: AssistantFoundPlace, dayId: number | null) => void;
|
||||
takePlaceDraft: (seq: number) => void;
|
||||
setPreviewPin: (preview: AssistantState['preview']) => void;
|
||||
setWindowRect: (rect: WindowRect | null) => void;
|
||||
setMapView: (mapView: AssistantState['mapView']) => void;
|
||||
@@ -820,6 +826,11 @@ function mapActions(ctx: Ctx) {
|
||||
},
|
||||
requestCamera: (tripId: number, points: LatLng[], mode: 'fit' | 'pan', why: 'user' | 'auto') =>
|
||||
requestCameraOn(ctx, tripId, points, mode, why),
|
||||
openPlaceDraft: (tripId: number, place: AssistantFoundPlace, dayId: number | null) =>
|
||||
ctx.set({ placeDraft: { tripId, seq: (ctx.get().placeDraft?.seq ?? 0) + 1, place, dayId } }),
|
||||
takePlaceDraft: (seq: number) => {
|
||||
if (ctx.get().placeDraft?.seq === seq) ctx.set({ placeDraft: null });
|
||||
},
|
||||
setPreviewPin: (preview: AssistantState['preview']) => ctx.set({ preview }),
|
||||
setWindowRect: (rect: WindowRect | null) => ctx.set({ windowRect: rect }),
|
||||
setMapView: (mapView: AssistantState['mapView']) => ctx.set({ mapView }),
|
||||
@@ -923,6 +934,7 @@ export const useAssistantStore = create<AssistantState>((set, get) => {
|
||||
mapLink: null,
|
||||
camera: null,
|
||||
preview: null,
|
||||
placeDraft: null,
|
||||
windowRect: null,
|
||||
mapView: null,
|
||||
studioHosts: {},
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* FE-STUDIO-READONLY-001 to FE-STUDIO-READONLY-002
|
||||
*
|
||||
* A book held as it is (one a newer Studio saved): every edit, undo and redo
|
||||
* is refused while it holds, and a version from elsewhere is still taken, so
|
||||
* the page on screen stays current.
|
||||
*/
|
||||
import { blankBook, type BookDocument } from '@trek/shared';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { useStudioStore } from './studioStore';
|
||||
|
||||
const STUDIO = useStudioStore.getState();
|
||||
|
||||
function book(title = 'Lisbon'): BookDocument {
|
||||
let seq = 0;
|
||||
return blankBook({ title, newId: (prefix) => `${prefix}-${++seq}` });
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useStudioStore.setState({ ...STUDIO, doc: null, past: [], future: [], readOnly: false });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
useStudioStore.getState().setReadOnly(false);
|
||||
});
|
||||
|
||||
describe('a book held as it is', () => {
|
||||
it('FE-STUDIO-READONLY-001: refuses edits, undo and redo while held, and takes them again once let go', () => {
|
||||
const store = useStudioStore.getState();
|
||||
store.load(book());
|
||||
store.commit((d) => ({ ...d, title: 'one' }));
|
||||
const edited = useStudioStore.getState().doc;
|
||||
|
||||
store.setReadOnly(true);
|
||||
store.commit((d) => ({ ...d, title: 'two' }));
|
||||
store.apply((d) => ({ ...d, title: 'three' }));
|
||||
store.undo();
|
||||
expect(useStudioStore.getState().doc).toBe(edited);
|
||||
expect(useStudioStore.getState().canUndo()).toBe(false);
|
||||
|
||||
store.setReadOnly(false);
|
||||
expect(useStudioStore.getState().canUndo()).toBe(true);
|
||||
store.undo();
|
||||
expect(useStudioStore.getState().doc?.title).toBe('Lisbon');
|
||||
expect(useStudioStore.getState().canRedo()).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-STUDIO-READONLY-002: still takes a version saved elsewhere, so the page shown stays current', () => {
|
||||
const store = useStudioStore.getState();
|
||||
store.load(book());
|
||||
store.setReadOnly(true);
|
||||
const theirs = book('Porto');
|
||||
store.adoptRemote(theirs, { undoable: false });
|
||||
expect(useStudioStore.getState().doc).toBe(theirs);
|
||||
store.load(book('Faro'));
|
||||
expect(useStudioStore.getState().doc?.title).toBe('Faro');
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,15 @@ interface StudioState {
|
||||
* 4.2). Not part of the book or its history; opening a book clears it.
|
||||
*/
|
||||
hintSpread: string | null
|
||||
/**
|
||||
* Whether the open book is held as it is. True for a book a newer Studio
|
||||
* saved (useBookStore's `newer`): this build has already dropped what
|
||||
* it cannot read from its copy, so every edit, undo and redo is refused
|
||||
* rather than shown as work that can never be saved. Loading and taking a
|
||||
* remote version still work, so the page stays current while it is shown.
|
||||
*/
|
||||
readOnly: boolean
|
||||
setReadOnly: (readOnly: boolean) => void
|
||||
|
||||
load: (doc: BookDocument) => void
|
||||
/**
|
||||
@@ -135,7 +144,9 @@ export const useStudioStore = create<StudioState>((set, get) => ({
|
||||
gestureBase: null,
|
||||
clipboard: null,
|
||||
hintSpread: null,
|
||||
readOnly: false,
|
||||
|
||||
setReadOnly: readOnly => set({ readOnly, gestureBase: null }),
|
||||
load: doc => set({ doc, selection: [], activeSpread: 0, past: [], future: [], gestureBase: null, hintSpread: null }),
|
||||
adoptRemote: (doc, opts) => set(s => {
|
||||
if (!s.doc) return { doc, selection: [], activeSpread: 0, past: [], future: [], gestureBase: null }
|
||||
@@ -180,13 +191,13 @@ export const useStudioStore = create<StudioState>((set, get) => ({
|
||||
}),
|
||||
|
||||
commit: fn => set(s => {
|
||||
if (!s.doc) return {}
|
||||
if (!s.doc || s.readOnly) return {}
|
||||
const next = fn(s.doc)
|
||||
if (next === s.doc) return {}
|
||||
return { doc: next, past: [...s.past, s.doc].slice(-HISTORY_LIMIT), future: [] }
|
||||
}),
|
||||
|
||||
apply: fn => set(s => (s.doc ? { doc: fn(s.doc) } : {})),
|
||||
apply: fn => set(s => (s.doc && !s.readOnly ? { doc: fn(s.doc) } : {})),
|
||||
|
||||
updateElement: (spreadIndex, id, patch) => get().apply(doc =>
|
||||
replaceSpread(doc, spreadIndex, sp => ({
|
||||
@@ -420,16 +431,16 @@ export const useStudioStore = create<StudioState>((set, get) => ({
|
||||
|
||||
undo: () => set(s => {
|
||||
const prev = s.past[s.past.length - 1]
|
||||
if (!prev || !s.doc) return {}
|
||||
if (!prev || !s.doc || s.readOnly) return {}
|
||||
return { doc: prev, past: s.past.slice(0, -1), future: [s.doc, ...s.future].slice(0, HISTORY_LIMIT), selection: [] }
|
||||
}),
|
||||
|
||||
redo: () => set(s => {
|
||||
const next = s.future[0]
|
||||
if (!next || !s.doc) return {}
|
||||
if (!next || !s.doc || s.readOnly) return {}
|
||||
return { doc: next, future: s.future.slice(1), past: [...s.past, s.doc].slice(-HISTORY_LIMIT), selection: [] }
|
||||
}),
|
||||
|
||||
canUndo: () => get().past.length > 0,
|
||||
canRedo: () => get().future.length > 0,
|
||||
canUndo: () => !get().readOnly && get().past.length > 0,
|
||||
canRedo: () => !get().readOnly && get().future.length > 0,
|
||||
}))
|
||||
|
||||
@@ -99,3 +99,19 @@ describe('a conflict', () => {
|
||||
expect(screen.getByRole('alert')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
describe('a book a newer Studio saved', () => {
|
||||
/*
|
||||
* Nothing done in this tab is kept until it reloads, so the state is loud
|
||||
* like a conflict and offers the one way out there is.
|
||||
*/
|
||||
it('is announced, says why, and reloads on request', () => {
|
||||
const onReload = vi.fn()
|
||||
draw({ status: 'newer' }, { onReload })
|
||||
|
||||
expect(screen.getByRole('alert')).toBeTruthy()
|
||||
expect(screen.getByText('journey.studio.saveNewer')).toBeTruthy()
|
||||
fireEvent.click(screen.getByText('journey.studio.saveReload'))
|
||||
expect(onReload).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -121,6 +121,17 @@ describe('photo frames', () => {
|
||||
expect(container.querySelector('img')).not.toBeNull()
|
||||
})
|
||||
|
||||
/*
|
||||
* The print view lays every sheet out at once; a picture the browser put off
|
||||
* until it scrolled into view is a picture missing from the PDF.
|
||||
*/
|
||||
it('loads a photo lazily on the canvas and at once in print', () => {
|
||||
const { container: canvas } = draw([photo()])
|
||||
expect(canvas.querySelector('img')?.getAttribute('loading')).toBe('lazy')
|
||||
const { container: printing } = draw([photo()], { print: true })
|
||||
expect(printing.querySelector('img')?.getAttribute('loading')).toBe('eager')
|
||||
})
|
||||
|
||||
it('cuts a masked photo with an objectBoundingBox clip, so it follows a resize', () => {
|
||||
const { container } = draw([photo({ mask: 'heart' })])
|
||||
const clip = container.querySelector('clipPath')!
|
||||
|
||||
@@ -776,3 +776,88 @@ describe('unmounting', () => {
|
||||
expect(api.saveBook).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
// -- A book a newer Studio saved ----------------------------------------------
|
||||
|
||||
/*
|
||||
* This build reads such a book as far as it can, and what it cannot read is
|
||||
* already gone from its copy. Showing it is fine; writing it would delete the
|
||||
* rest for everyone, so nothing is written until a reload.
|
||||
*/
|
||||
describe('a book a newer Studio saved', () => {
|
||||
const newer = (title = 'newer') => ({ ...doc(title), schemaRev: 99 }) as unknown as BookDocument
|
||||
|
||||
/** A 409 for a book a newer Studio saved since this tab read it. */
|
||||
function newerError() {
|
||||
return Object.assign(new Error('Request failed'), {
|
||||
response: { status: 409, data: { error: 'Book was saved by a newer version of TREK Studio', code: 'book_schema_newer', schemaRev: 2 } },
|
||||
})
|
||||
}
|
||||
|
||||
it('FE-STUDIO-REV-002: opens it, says so, and writes nothing, not even on flush', async () => {
|
||||
api.getBook.mockResolvedValue({ book: record({ version: 5, document: newer() }) })
|
||||
const { result } = await mount()
|
||||
|
||||
expect(result.current.state.status).toBe('newer')
|
||||
expect(result.current.record?.document.title).toBe('newer')
|
||||
act(() => { result.current.queueSave(doc('edited'), 'T') })
|
||||
await tick()
|
||||
let ok: boolean | undefined
|
||||
await act(async () => { ok = await result.current.flush() })
|
||||
|
||||
expect(ok).toBe(false)
|
||||
expect(api.saveBook).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-STUDIO-REV-003: stops on the server refusing a save over a newer book, and does not try again', async () => {
|
||||
api.saveBook.mockRejectedValue(newerError())
|
||||
const { result } = await mount()
|
||||
|
||||
act(() => { result.current.queueSave(doc('a'), 'T') })
|
||||
await tick()
|
||||
expect(result.current.state.status).toBe('newer')
|
||||
|
||||
act(() => { result.current.queueSave(doc('b'), 'T') })
|
||||
await tick()
|
||||
expect(api.saveBook).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('FE-STUDIO-REV-004: shows a newer version another editor saved, and holds it the same way', async () => {
|
||||
api.getBook.mockResolvedValue({ book: record({ version: 4, document: doc('ours') }) })
|
||||
const onRemote = vi.fn()
|
||||
const { result } = renderHook(() => useBookStore(9, onRemote))
|
||||
await tick(0)
|
||||
api.getBook.mockResolvedValue({ book: record({ version: 6, document: newer('theirs') }) })
|
||||
|
||||
await remoteSave(6)
|
||||
|
||||
expect(onRemote.mock.calls[0][0].title).toBe('theirs')
|
||||
expect(result.current.state.status).toBe('newer')
|
||||
act(() => { result.current.queueSave(doc('mine'), 'T') })
|
||||
await tick()
|
||||
expect(api.saveBook).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-STUDIO-REV-005: taking their side of a conflict holds the book when theirs is newer', async () => {
|
||||
const theirs = record({ version: 6, document: newer('theirs') })
|
||||
api.saveBook.mockRejectedValueOnce(conflictError(theirs))
|
||||
const { result } = await mount()
|
||||
|
||||
act(() => { result.current.queueSave(doc('mine'), 'T') })
|
||||
await tick()
|
||||
expect(result.current.state.status).toBe('conflict')
|
||||
|
||||
act(() => { result.current.acceptTheirs(theirs) })
|
||||
expect(result.current.state.status).toBe('newer')
|
||||
})
|
||||
|
||||
/* A book of today goes out exactly as it went out before the revision existed. */
|
||||
it('FE-STUDIO-REV-006: sends a book of today without a revision in it', async () => {
|
||||
const { result } = await mount()
|
||||
|
||||
act(() => { result.current.queueSave(doc('a'), 'T') })
|
||||
await tick()
|
||||
|
||||
expect(api.saveBook.mock.calls[0][1].document).not.toHaveProperty('schemaRev')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -173,7 +173,6 @@
|
||||
"client/src/pages/tripPlanner/plannerTypes.ts": 1,
|
||||
"client/src/pages/tripPlanner/useBookingEdits.ts": 1,
|
||||
"client/src/pages/tripPlanner/useDayPlanEdits.ts": 1,
|
||||
"client/src/pages/tripPlanner/usePlaceFormOpeners.ts": 1,
|
||||
"client/src/pages/tripPlanner/useRoadtripAlternatives.ts": 1,
|
||||
"client/src/pages/tripPlanner/useRoadtripStopEdits.ts": 1,
|
||||
"client/src/push/webPush.ts": 1,
|
||||
|
||||
@@ -2,17 +2,37 @@
|
||||
* How the Studio assistant designs a book (journey-studio-wp13.md 7): the
|
||||
* designer's rules it works by, appended to the Studio's standing
|
||||
* instructions (studioPrompt). Static, so the prompt cache stays stable.
|
||||
*
|
||||
* Restraint is one way to design a book, not the only one. The print rules
|
||||
* (resolution, fold, trim, bleed, binding, legible words) hold for every
|
||||
* book; how full, layered and loud a page is follows the energy the person
|
||||
* asked for. The type scale is given in points on a 210 mm page, as
|
||||
* design-style.ts sets it, so it scales with the page the same way. The
|
||||
* questions under "Look, judge, revise" are the critique a designer runs on a
|
||||
* proof, answered silently before every proposal.
|
||||
*/
|
||||
export const BOOK_DESIGN_PROMPT = `How you design:
|
||||
- Act as a book designer, not a form filler: decide the story first (chapters, pacing), then the pages.
|
||||
- Map the person's words to design_book's directives: "calm, lots of white" is style minimal and density airy; "like a magazine" is editorial; "bold" is bold and rich; "scrapbook" is scrapbook; a page count is pages.min and pages.max; "only Portugal" is a scope.
|
||||
- Hierarchy: one dominant element per page; heading, then body, then captions; never two equal heroes on a spread.
|
||||
- Whitespace is a beat: after a loud spread a quiet one; margins at least the safe area plus 6 mm.
|
||||
- Rhythm: vary the beats, never three alike in a row; grids for bursts, a quiet page for a long story.
|
||||
- Alignment: everything on the margin grid and the gutter; align and distribute instead of eyeballing.
|
||||
- Colour from the photos: one accent, an ink and a paper; at most two typefaces in the whole book.
|
||||
- Never upscale: under 200 dpi make the frame smaller; keep the focal point visible; no words on a busy part of a photo without a scrim.
|
||||
- Act as a book designer, not a form filler: decide the story first (chapters, pacing), then the energy of the book, then the pages.
|
||||
- Map the person's words to design_book's directives: "calm, lots of white" is style minimal and density airy; "like a magazine" is editorial; "bold", "lively" or "loud" is bold and rich; "scrapbook" is scrapbook; a page count is pages.min and pages.max; "only Portugal" is a scope.
|
||||
- Before you call design_book, state the brief in one line: the energy (calm, lively or loud), the cover photo, the title words and the look.
|
||||
Always, whatever the energy:
|
||||
- Never upscale: under 200 dpi make the frame smaller; keep the focal point visible.
|
||||
- Nothing that matters in the fold, past the trim or outside the safe area; a picture meant to bleed reaches the bleed; mind the binding on a double spread.
|
||||
- Words on a photo sit on a quiet part of it, a scrim or a colour block; running text at 4.5:1 contrast, display type at 3:1.
|
||||
- Bound texts keep the journal in sync: prefer bindings over copied words; never invent captions or facts.
|
||||
- Check every changed page with describe_book_page and the designId, look at the ones that matter most with preview_book_page and the designId when you can see images, and fix their findings with revise_book_design before you propose.
|
||||
The energy decides the rest:
|
||||
- Calm: one dominant element per page; heading, then body, then captions; whitespace as a beat after a loud spread; margins at least the safe area plus 6 mm; everything on the margin grid and the gutter; one accent from the photos and two typefaces.
|
||||
- Lively: still one hero per page, now layered: a photo over a colour block or a shape, the title over a photo, photos turned 2 to 6 degrees in a white or polaroid frame, oversize display type, colour blocking in the accent.
|
||||
- Loud: lively pushed further: bigger type, stronger colour, more layers, a title that fills the cover; never two heroes on one page.
|
||||
- A deliberate overlap is a design; an accidental one (two straight photos or texts of a size half over each other) is a fault.
|
||||
- Vary the beats, never three alike in a row; a quiet page for a long story, grids for bursts.
|
||||
Type scale, in points for a 210 mm page and scaled with the page width:
|
||||
- Cover title in a display face, 72 to 180 pt, 12 to 30 % of the page height; title to subtitle at least 3:1. For a big cover raise type.display (up to 6.5, about 180 pt); keep type.scale between 0.9 and 1.1 so body stays 9 to 11 pt.
|
||||
- Date lines in spaced caps, 7 to 9 pt, tracking 0.25 to 0.4; an accent word over a title in the contrasting face (playfair italic or display), 1.2 to 1.6 times its cap height, with contrast, an outline or a shadow.
|
||||
- Body 9 to 11 pt; captions 6.5 to 8 pt with tracking 0.05 to 0.1; a display face and a body face, two typefaces at most.
|
||||
Look, judge, revise:
|
||||
- Check every changed page with describe_book_page and the designId, and look at the pages that matter most with preview_book_page and the designId when you can see images; preview the cover at least twice, the first draft and the final one.
|
||||
- Before every proposal answer silently: Is there one dominant element? Does the title read at thumbnail size? Does the energy match the brief? Is the palette the book's own? Is anything touching or overlapping by accident? Is text on a busy area without contrast? Does the decoration suit the energy? Does the page differ from the one before? Fix what fails with revise_book_design.
|
||||
- Fix every severe finding before you propose; an info finding is context, not a fault.
|
||||
- One design, one proposal: apply_book_design for a whole book, never dozens of edit_book_page calls; a single page with edit_book_page.
|
||||
- Keep what the person locked or made by hand unless they ask; say which photos you left out and why.`;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { AiToolSpec } from '../ai-connections/ai-chat-client.interface';
|
||||
import type { SettingsService } from '../settings/settings.service';
|
||||
import type { AgentToolPort } from './assistant-agent';
|
||||
import { MAX_MEMORY_CHARS, tripMemoryOf } from './assistant-context';
|
||||
import { REMEMBER_TOOL } from './assistant-tools.constants';
|
||||
import type { ToolRun } from './assistant-tools.service';
|
||||
@@ -7,13 +8,21 @@ import type { ToolRun } from './assistant-tools.service';
|
||||
/** The longest single note the model may keep. */
|
||||
const MAX_NOTE_CHARS = 500;
|
||||
|
||||
/** How the model is offered the trip notes: one short fact per call, confirmed by the user like any change. */
|
||||
/**
|
||||
* How the model is offered the trip notes: one short fact per call, kept at
|
||||
* once without a card (the chat shows it as kept, and the notes are the
|
||||
* user's to edit in the chat menu).
|
||||
*/
|
||||
export const REMEMBER_SPEC: AiToolSpec = {
|
||||
name: REMEMBER_TOOL,
|
||||
description:
|
||||
"Keep a fact or wish about this trip in the user's trip notes, which come along with every later conversation " +
|
||||
'about this trip (for example "we travel as two", "vegetarian", "no museums before 10"). Call it whenever the ' +
|
||||
'user asks you to remember something, instead of saying you cannot. The user confirms it like any change.',
|
||||
'about this trip (for example "we travel as two", "vegetarian", "no museums before 10", "Anna has a bad knee"). ' +
|
||||
'It is kept at once, without asking: call it on your own whenever the user tells you something that will ' +
|
||||
'matter for later suggestions on this trip (who travels, needs, likes and dislikes, budget, pace, fixed ' +
|
||||
'times), and whenever they ask you to remember something, instead of saying you cannot. Keep nothing ' +
|
||||
'that only matters for this one answer, nothing already in <trip_notes>, and nothing private beyond what the ' +
|
||||
'trip needs (no passport or card numbers). Say in a few words that you noted it.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
@@ -58,3 +67,21 @@ export async function rememberForTrip(
|
||||
await settings.upsertSetting(userId, 'assistant_memory', { ...all, [String(tripId)]: next });
|
||||
return { ok: true, value: { notes: next } };
|
||||
}
|
||||
|
||||
/**
|
||||
* The turn's tools with the trip notes kept at once: remember_for_trip runs
|
||||
* as a read (the loop carries on with its answer) through `remember`, every
|
||||
* other tool as the port has it. Without a trip the port stays as it is.
|
||||
*/
|
||||
export function rememberingPort(
|
||||
port: AgentToolPort,
|
||||
remember: ((args: Record<string, unknown>) => Promise<ToolRun>) | null,
|
||||
): AgentToolPort {
|
||||
if (!remember) return port;
|
||||
return {
|
||||
specs: () => port.specs(),
|
||||
kindOf: (name) => (name === REMEMBER_TOOL && port.kindOf(name) !== null ? 'read' : port.kindOf(name)),
|
||||
pinArgs: (name, args) => (name === REMEMBER_TOOL ? { args } : port.pinArgs(name, args)),
|
||||
call: (name, args) => (name === REMEMBER_TOOL ? remember(args) : port.call(name, args)),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -226,9 +226,10 @@ type ToolGroups = Readonly<Record<string, { about: string; controllers: readonly
|
||||
const CORE_TOOL_GROUPS: ToolGroups = {
|
||||
tours: {
|
||||
about:
|
||||
'Tours: hikes, bike tours, city walks, paddling and ski routes; plan, create, change and export them ' +
|
||||
'(hikes with their heights and SAC grades), their packing, the tour library and imports from GPX files ' +
|
||||
'and Google Maps walks.',
|
||||
'Tours: hikes (also over several days in stages), city walks, bike tours, runs, rides, paddling and ski ' +
|
||||
'routes; plan, create, change and export them (hikes with their heights and SAC grades), search along a ' +
|
||||
'tour, check off a city walk under way, the recorded tracks and tour stats, their packing, tours in ' +
|
||||
'collections, the tour library and imports from GPX files and Google Maps walks.',
|
||||
controllers: [
|
||||
'ToursMcp',
|
||||
'CityWalkMcp',
|
||||
|
||||
@@ -30,11 +30,11 @@ How you work:
|
||||
- Besides the open trip you can work in the rest of TREK: tours (hikes, bike tours, city walks), the road trip, the travel journal, the vacation planner, the atlas, collections, the trip's chat, polls and notes, files and the user's settings. Their tools are not loaded at first: call use_addon_tools with the groups you need, then use them in the same reply. Tools without a trip work on the user's own data across trips.
|
||||
- Propose a deletion only when the user asks for it; it cannot be undone, and the card says so.
|
||||
- You cannot share, invite people, publish links or calendar feeds, change who can see a trip, leave, copy or delete the trip, or make a new one. If asked, say so in one sentence and where in TREK the user can do it.
|
||||
- When the user asks you to remember something for this trip (who travels, what they like or avoid), keep it with remember_for_trip; it comes back as <trip_notes> in every later conversation. Never say you cannot remember things.
|
||||
- Keep what will matter later with remember_for_trip on your own, without asking: who travels, needs, likes and dislikes, budget, pace, fixed times the user mentions, and anything they ask you to remember. It is kept at once and comes back as <trip_notes> in every later conversation; say briefly that you noted it. Where you are not sure it lasts, offer it as a follow-up instead ("Remember: …"). Never say you cannot remember things.
|
||||
- Expenses and their ids come from list_budget_items. Change an existing one with update_budget_item; never add a second entry to correct one. For what each person's share comes to, use get_budget_per_person; for who pays whom, get_settlement_summary.
|
||||
- For the wind on a day (a paddle, a sail, a ridge walk), use get_wind_forecast: it has the gusts and the direction hour by hour.
|
||||
- End every answer with one suggest_follow_ups call, alone in its step after your text: up to three short messages the user would plausibly send next, about what you just discussed (a hike you planned: an easier variant, what to pack; never the day plan when the answer was not about it). When you asked the user a question, offer its likely answers instead ("Yes, plan it anyway", "Rather in the Harz"). Skip it only while changes wait for the user's decision.
|
||||
- If the request is unclear, ask one short question instead of guessing.`;
|
||||
- If the request is unclear, ask one short question instead of guessing. A request that names what and roughly where is clear: propose it at once (a proposal saves nothing) and say in a sentence what you assumed, rather than asking whether you may.`;
|
||||
|
||||
/** The instructions with the packages' lines about their cards, built once so the provider's cache holds. */
|
||||
const STANDING = INSTRUCTIONS + CARD_PROMPT_LINES.map((line) => `\n- ${line}`).join('');
|
||||
@@ -58,7 +58,7 @@ How you work:
|
||||
- Read get_book and describe_book_page before you change a page. Page and element ids come from them and from the book card; never invent one. Photo ids come only from {photoSources}.
|
||||
- To change the book, call the tool for the change: the app shows each call to the user as a change card, and nothing happens until they apply it. Do not describe a change in text and ask whether to make it. Make one edit_book_page call per page in a step, with all of that page's operations.
|
||||
- Act, don't announce. Make the reads and changes you need in this reply; never end a reply with "I will now ..." and no calls. Never say a change was made unless its result says it was applied.
|
||||
- Keep every text inside its frame and nothing important in the fold or past the trim. When a result lists severe findings (overlapping photos, words past their frame, empty frames, content in the fold), fix them with the next change.
|
||||
- Keep every text inside its frame and nothing important in the fold or past the trim. When a result lists severe findings (photos or texts overlapping by accident, words past their frame, empty frames, content in the fold), fix them with the next change; a layered page (a title over a photo, a turned photo over a shape) is a design, not a finding to fix.
|
||||
- Before you propose an edit_book_page change, look at the page once with preview_book_page and the edit's ops, fix what its findings show, then propose. When a result brings the page as an image, check your work on it too: photos of other contributors are empty frames there on purpose, not missing photos.
|
||||
- Never delete pages unless the user asks for it. Never place a photo at a size its resolution cannot print.
|
||||
- Picking photos works on what TREK knows about them: the day, the place, bursts and near duplicates, sharpness, resolution and whether a photo is in the book already. Nobody can tell from that who or what is in a photo or whether it is beautiful; only a page image shows the photos themselves. Say so when asked.
|
||||
|
||||
@@ -38,7 +38,7 @@ import { mentionItems } from './assistant-cards.helpers';
|
||||
import { todayIn } from './assistant-context';
|
||||
import { DISCARDED, NOT_RUN, type Outcome, withCancelled, withOutcomes } from './assistant-decisions.helpers';
|
||||
import { messageIdOf, outputText, partsOf, toChatHistory, toThreadMessages } from './assistant-history';
|
||||
import { rememberForTrip } from './assistant-memory';
|
||||
import { rememberForTrip, rememberingPort } from './assistant-memory';
|
||||
import { toolOutputForProvider } from './assistant-output';
|
||||
import { AssistantScopes, findScopedCall, scopedThreads, tripScope } from './assistant-scope';
|
||||
import { AssistantStreamRegistry } from './assistant-stream.registry';
|
||||
@@ -812,6 +812,14 @@ export class AssistantService {
|
||||
return new Map(lists.flat().map((call) => [call.id, call]));
|
||||
}
|
||||
|
||||
/** How a trip's turn keeps a note at once; a journey's has no trip notes. */
|
||||
private remembering(userId: number, scope: AssistantScope) {
|
||||
if (scope.kind !== 'trip') return null;
|
||||
const { tripId } = scope;
|
||||
return (args: Record<string, unknown>) =>
|
||||
this.inContext(() => rememberForTrip(this.settings, userId, tripId, args));
|
||||
}
|
||||
|
||||
/**
|
||||
* The turn itself, once the stream is open: the tool session, the trip or
|
||||
* book card, the history, then the agent loop. Whatever fails after this
|
||||
@@ -848,7 +856,7 @@ export class AssistantService {
|
||||
const outcome = await runAgentLoop(
|
||||
{
|
||||
client: this.chatClients.create(spec.connection),
|
||||
tools: seeing.tools,
|
||||
tools: rememberingPort(seeing.tools, this.remembering(userId, spec.scope)),
|
||||
store: this.stepStore(spec),
|
||||
describe: this.cardContext.forTurn(gate.reader, card, spec.locale, today).describe,
|
||||
refusalOf: gate.refusalOf,
|
||||
|
||||
@@ -15,6 +15,7 @@ import { tourListCard } from './tour-lists.cards';
|
||||
import { proposalCard, savedTourCard } from './tour-route.cards';
|
||||
import { cityWalkCard, paddleCard, skiCard } from './tour-sport.cards';
|
||||
import { DELETE_CREATED_TOUR, DELETE_IMPORTED_TOUR } from './tour-undo';
|
||||
import { describeVisit, loadVisit, SET_VISIT_UNDO } from './tour-visit.cards';
|
||||
|
||||
/**
|
||||
* The tours in the assistant chat. A tour is a place with a route: its id is
|
||||
@@ -73,6 +74,12 @@ export const TOUR_CARDS: DomainCards = {
|
||||
undo: DELETE_CREATED_TOUR,
|
||||
},
|
||||
update_tour: updateTour,
|
||||
set_city_walk_visit: {
|
||||
write: { verbKey: 'markVisited', entity: 'tour' },
|
||||
load: loadVisit,
|
||||
describe: describeVisit,
|
||||
undo: SET_VISIT_UNDO,
|
||||
},
|
||||
import_tour_gpx: {
|
||||
write: { verbKey: 'importTour', entity: 'tour' },
|
||||
describe: TOUR_DESCRIBERS.import_tour_gpx,
|
||||
@@ -85,7 +92,7 @@ export const TOUR_CARDS: DomainCards = {
|
||||
},
|
||||
},
|
||||
prompt: [
|
||||
'Hikes: call propose_hike with a name, and day_id and start_time when known; to compare ways, call it up to three times in one step, each with a variant_label and along false. Call create_hike only once the user chose a way.',
|
||||
'The app draws a proposed, planned or saved tour (route, profile, stops, times, weather, warnings) and lists of tours as cards: do not repeat their figures or list them again, say in one sentence what matters.',
|
||||
'Hikes: call propose_hike with a name, and day_id and start_time when known; to compare ways, call it up to three times in one step, each with a variant_label and along false, the way you recommend first (the card shows the first one chosen). Call create_hike only once the user chose a way. A hike over several days is one hike: stage_end on each stop a day ends at (no day_id), then each stage on its day with assign_place_to_day and tourStageKey.',
|
||||
'The app draws a proposed, planned or saved tour (route, profile, stops, times, weather, warnings) and lists of tours as cards: do not repeat their figures or list them again, say in one sentence what matters. Once a tour is planned, offer what goes with it: places along it (search_tour_pois), what to pack (get_tour_packing, link_tour_packing), the GPX file (export_tour_gpx).',
|
||||
],
|
||||
};
|
||||
|
||||
@@ -139,11 +139,18 @@ function waypointStops(waypoints: readonly Row[], start: string | null): TourRou
|
||||
atM: metresOf(point.at_m) ?? 0,
|
||||
minutes,
|
||||
clock: clockOf(point.arrival) ?? clockAfter(start, minutes),
|
||||
stageEnd: point.stage_end === true && index > 0 && index < waypoints.length - 1,
|
||||
}),
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
/** How many stages a proposed hike's stops make; null for a day hike, as a saved tour's card says it. */
|
||||
function stagesOf(stops: readonly TourRouteStop[]): number | null {
|
||||
const count = 1 + stops.filter((stop) => stop.stageEnd).length;
|
||||
return count >= 2 ? Math.min(count, 60) : null;
|
||||
}
|
||||
|
||||
/** The places along a proposed way and its highest point, timed between the points around them. */
|
||||
function alongStops(value: Row, own: readonly TourRouteStop[], start: string | null): TourRouteStop[] {
|
||||
const along = rowsIn(value.along)
|
||||
@@ -248,6 +255,7 @@ export function hikeCard(
|
||||
line,
|
||||
stretches: sacStretches(sac?.segments),
|
||||
stops: sortedStops([...own, ...alongStops(plan, own, start)]),
|
||||
stages: stagesOf(own),
|
||||
schedule: scheduleOf(plan.schedule, card),
|
||||
warnings: warningsOf(plan.warnings),
|
||||
});
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { Described, PreviewContext, ToolArgs, ToolCards, UndoCall, UndoSnapshot } from '../card-types';
|
||||
import { argId, readKey, recordOf, type Row } from '../card-values';
|
||||
import { dayLabel, Rows, text } from '../preview-format';
|
||||
import type { AssistantChangeVerbKey } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* A station of a city walk checked off on its day (set_city_walk_visit): the
|
||||
* card names the station and the walk, the verb says what the mark does, and
|
||||
* the way back is the same tool with the status the station had before,
|
||||
* while the station still has the status the change gave it.
|
||||
*/
|
||||
|
||||
const PROGRESS_TOOL = 'get_city_walk_progress';
|
||||
|
||||
const VERB_OF: Readonly<Record<string, AssistantChangeVerbKey>> = {
|
||||
visited: 'markVisited',
|
||||
skipped: 'markSkipped',
|
||||
planned: 'markPlanned',
|
||||
};
|
||||
|
||||
/** What the card and its undo read: the walk on that day, as get_city_walk_progress answers it. */
|
||||
function progressArgs(args: ToolArgs): Row {
|
||||
const read: Row = { placeId: args.placeId, dayId: args.dayId };
|
||||
if (args.assignmentId !== undefined) read.assignmentId = args.assignmentId;
|
||||
return read;
|
||||
}
|
||||
|
||||
/** The station a call names, from the walk as read. */
|
||||
function stationIn(progress: unknown, key: unknown): Row | null {
|
||||
const stations = recordOf(progress).stations;
|
||||
if (!Array.isArray(stations) || typeof key !== 'string') return null;
|
||||
return (stations.map(recordOf).find((station) => station.key === key) ?? null) as Row | null;
|
||||
}
|
||||
|
||||
export async function loadVisit(args: ToolArgs, read: (tool: string, args?: ToolArgs) => Promise<unknown>) {
|
||||
if (argId(args, 'placeId') === null || argId(args, 'dayId') === null) return null;
|
||||
return await read(PROGRESS_TOOL, progressArgs(args));
|
||||
}
|
||||
|
||||
export function describeVisit(ctx: PreviewContext, args: ToolArgs, loaded: unknown): Described {
|
||||
const placeId = argId(args, 'placeId');
|
||||
const dayId = argId(args, 'dayId');
|
||||
const walk = placeId === null ? '' : (ctx.card.places.get(placeId)?.name ?? '');
|
||||
const station = stationIn(loaded, args.stationKey);
|
||||
const name = text(station?.name);
|
||||
const status = typeof args.status === 'string' ? args.status : '';
|
||||
return {
|
||||
subject: name || walk,
|
||||
rows: new Rows().add('route', name ? walk : '').add('day', dayLabel(ctx, dayId)),
|
||||
dayId,
|
||||
placeIds: placeId === null ? [] : [placeId],
|
||||
verbKey: VERB_OF[status],
|
||||
// Marking a station with the status it has already changes nothing to take back.
|
||||
undoable: station === null || station.status !== status,
|
||||
};
|
||||
}
|
||||
|
||||
/** The walk as the undo read it before it checks. */
|
||||
function readProgress(snapshot: UndoSnapshot, call: UndoCall | undefined): unknown {
|
||||
return call ? snapshot.reads.get(readKey(PROGRESS_TOOL, progressArgs(call.args))) : undefined;
|
||||
}
|
||||
|
||||
export const SET_VISIT_UNDO: NonNullable<ToolCards['undo']> = {
|
||||
tool: 'set_city_walk_visit',
|
||||
args: (args, result) => {
|
||||
const answer = recordOf(result);
|
||||
const before = answer.previous_status;
|
||||
if (typeof before !== 'string' || typeof answer.station_key !== 'string') return null;
|
||||
const assignmentId = recordOf(answer.walk).assignment_id;
|
||||
return {
|
||||
placeId: args.placeId,
|
||||
dayId: args.dayId,
|
||||
stationKey: answer.station_key,
|
||||
status: before,
|
||||
...(typeof assignmentId === 'number' ? { assignmentId } : {}),
|
||||
};
|
||||
},
|
||||
reads: (args) => [{ tool: PROGRESS_TOOL, args: progressArgs(args) }],
|
||||
unchanged: (result, snapshot, call) => {
|
||||
const answer = recordOf(result);
|
||||
const station = stationIn(readProgress(snapshot, call), answer.station_key);
|
||||
return station !== null && station.status === answer.status;
|
||||
},
|
||||
};
|
||||
@@ -8,7 +8,14 @@ import { JourneyDomainService } from './journey-domain.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { BookDocument, BookRecord, BookSummary } from '@trek/shared';
|
||||
import { BOOK_DESIGN_LIMITS, normalizeBookDocument } from '@trek/shared';
|
||||
import {
|
||||
BOOK_DESIGN_LIMITS,
|
||||
BOOK_SCHEMA_NEWER_CODE,
|
||||
BOOK_SCHEMA_REV,
|
||||
bookSchemaRev,
|
||||
normalizeBookDocument,
|
||||
stampBookSchemaRev,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* What an edit of the book hands back to `editBook`: the record's title and
|
||||
@@ -59,6 +66,15 @@ interface BookEditOptions extends BookWriteOrigin {
|
||||
*
|
||||
* The alternative — last write wins — is not a simpler version of this. It is
|
||||
* the same thing with the failure moved somewhere nobody sees it.
|
||||
*
|
||||
* ── Format revisions ─────────────────────────────────────────────────────
|
||||
*
|
||||
* A book says which revision of the format wrote it (book-schema-rev.ts in
|
||||
* @trek/shared). A save from a writer older than the stored book is refused,
|
||||
* because that writer has already dropped whatever it could not read; so is
|
||||
* one newer than this server, which would drop the same on the way in. The
|
||||
* book tools write only books this server reads whole, and stamp what they
|
||||
* write with its revision.
|
||||
*/
|
||||
@Injectable()
|
||||
export class JourneyBookService {
|
||||
@@ -166,6 +182,7 @@ export class JourneyBookService {
|
||||
userId: number,
|
||||
input: { title: string; document: unknown; baseVersion?: number },
|
||||
): Promise<{ record: BookRecord } | { conflict: BookRecord }> {
|
||||
refuseNewerThanServer(bookSchemaRev(input.document));
|
||||
const document = JSON.stringify(normalizeBookDocument(input.document));
|
||||
|
||||
// M1 (rule 11/24) — JB3's existing-link read and JB4's insert are
|
||||
@@ -187,6 +204,10 @@ export class JourneyBookService {
|
||||
return { record: (await this.byId(id))! };
|
||||
}
|
||||
|
||||
// An older writer has already lost what it could not read; it does not get to save that loss.
|
||||
const stored = storedSchemaRev(existing.document);
|
||||
if (stored > bookSchemaRev(input.document)) throw newerBook(stored);
|
||||
|
||||
/*
|
||||
* The version goes in the WHERE clause rather than being checked first.
|
||||
* Read-then-write leaves a window between the two in which another save can
|
||||
@@ -249,11 +270,15 @@ export class JourneyBookService {
|
||||
if (options.expectedVersion !== undefined && current?.version !== options.expectedVersion) {
|
||||
throw bookMoved(current);
|
||||
}
|
||||
// `current` is the book as this server reads it, which for a newer book is the book minus what it dropped.
|
||||
if (row) refuseNewerThanServer(storedSchemaRev(row.document));
|
||||
const next = await edit(current);
|
||||
// What the edit hands back is checked too: a kept revision from a newer server, put back after a downgrade, would land stripped yet still stamped newer.
|
||||
refuseNewerThanServer(bookSchemaRev(next.document));
|
||||
if (current && next.unchanged) {
|
||||
return { record: current, result: next.result, wrote: false, revisionId: null };
|
||||
}
|
||||
const document = JSON.stringify(normalizeBookDocument(next.document));
|
||||
const document = JSON.stringify(normalizeBookDocument(stampBookSchemaRev(next.document)));
|
||||
if (!row) {
|
||||
const id = await this.booksRepo.insertBook(journeyId, next.title, document, userId);
|
||||
return { record: await this.written(id), result: next.result, wrote: true, revisionId: null };
|
||||
@@ -341,6 +366,31 @@ function bookMoved(current: BookRecord | null): DomainError {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The book was written by a newer revision of the format than the writer (or
|
||||
* this server) knows. 409 like a moved book, with the code the Studio reads to
|
||||
* open the book read-only and ask for a reload; no `current`, because there is
|
||||
* nothing here an older writer could safely take.
|
||||
*/
|
||||
function newerBook(schemaRev: number): DomainError {
|
||||
return new DomainError(409, 'Book was saved by a newer version of TREK Studio', {
|
||||
code: BOOK_SCHEMA_NEWER_CODE,
|
||||
details: { code: BOOK_SCHEMA_NEWER_CODE, schemaRev },
|
||||
mcpMessage:
|
||||
'This book was saved by a newer version of TREK than this server runs. Changing it here would drop what that version added, so it stays as it is.',
|
||||
});
|
||||
}
|
||||
|
||||
/** Refuse a book written by a revision this server cannot read whole. */
|
||||
function refuseNewerThanServer(schemaRev: number): void {
|
||||
if (schemaRev > BOOK_SCHEMA_REV) throw newerBook(schemaRev);
|
||||
}
|
||||
|
||||
/** The revision a stored row's document says it was written by; broken JSON reads as 1, like its document. */
|
||||
function storedSchemaRev(raw: string): number {
|
||||
return bookSchemaRev(safeParse(raw));
|
||||
}
|
||||
|
||||
/** JSON that will not parse is an empty document, never an exception. */
|
||||
function safeParse(raw: string): unknown {
|
||||
try {
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
type HikeHighPoint,
|
||||
type HikePlan,
|
||||
type HikePlanPoint,
|
||||
type HikeStop,
|
||||
type HikeProposal,
|
||||
type HikeProposalSac,
|
||||
type HikeProposeRequest,
|
||||
@@ -39,9 +40,10 @@ import {
|
||||
*/
|
||||
|
||||
/** The points a hike is planned through: as asked, and for a round trip back to its start. */
|
||||
export function hikePointsOf(waypoints: readonly HikePlanPoint[], roundTrip: boolean | undefined): HikePlanPoint[] {
|
||||
export function hikePointsOf(waypoints: readonly HikeStop[], roundTrip: boolean | undefined): HikeStop[] {
|
||||
const [start] = waypoints;
|
||||
return roundTrip === true && start ? [...waypoints, { ...start }] : [...waypoints];
|
||||
// The way back ends where the hike began: the start ends no stage there.
|
||||
return roundTrip === true && start ? [...waypoints, { ...start, stage_end: undefined }] : [...waypoints];
|
||||
}
|
||||
|
||||
/** Whether the way was planned, and why not, as the answers name it. */
|
||||
@@ -49,19 +51,29 @@ export function routeOutcomeOf(plan: HikePlan): HikeRouteOutcome {
|
||||
return plan.kind === 'routed' ? { planned: true } : { planned: false, why: plan.why, position: plan.position };
|
||||
}
|
||||
|
||||
/** The points as a tour keeps them: in order, the first the start and the last the end, with their names. */
|
||||
export function hikeWaypointsOf(points: readonly HikePlanPoint[]): TourWaypoint[] {
|
||||
/**
|
||||
* The points as a tour keeps them: in order, the first the start and the
|
||||
* last the end, with their names, and on a hike over several days the stops
|
||||
* its stages end at.
|
||||
*/
|
||||
export function hikeWaypointsOf(points: readonly HikeStop[]): TourWaypoint[] {
|
||||
const last = points.length - 1;
|
||||
return points.map(({ lat, lng, name, poi_category }, sequence) => ({
|
||||
return points.map(({ lat, lng, name, poi_category, stage_end }, sequence) => ({
|
||||
lat,
|
||||
lng,
|
||||
...(name ? { name } : {}),
|
||||
...(poi_category ? { poi_category } : {}),
|
||||
role: sequence === 0 ? 'start' : sequence === last ? 'end' : 'via',
|
||||
sequence,
|
||||
...(stage_end === true && sequence > 0 && sequence < last ? { stage_end: true } : {}),
|
||||
}));
|
||||
}
|
||||
|
||||
/** How many stages a hike's points make: one for a day hike. */
|
||||
export function hikeStagesOf(points: readonly HikeStop[]): number {
|
||||
return 1 + points.filter((point) => point.stage_end === true).length;
|
||||
}
|
||||
|
||||
/** The way a saved hike keeps from a plan: its whole line and walking time, or none, and how the planning went. */
|
||||
export interface KeptWay {
|
||||
line: GeometryPoint[] | null;
|
||||
@@ -93,7 +105,7 @@ export function keptWayOf({ plan, line }: PlannedHike): KeptWay {
|
||||
*/
|
||||
export function hikeCreateCommandOf(
|
||||
request: HikeCreateRequest,
|
||||
points: readonly HikePlanPoint[],
|
||||
points: readonly HikeStop[],
|
||||
way: KeptWay,
|
||||
limit: number,
|
||||
): TourCreateCommand {
|
||||
@@ -135,13 +147,15 @@ function savedPointAt(point: { lat: number; lng: number }, saved: readonly TourW
|
||||
* keeps its link to the trip's place it stands for, and its name where the
|
||||
* new one gives none. A saved point no new one stands on goes, with its link.
|
||||
*/
|
||||
export function repointedWaypoints(points: readonly HikePlanPoint[], saved: readonly TourWaypoint[]): TourWaypoint[] {
|
||||
export function repointedWaypoints(points: readonly HikeStop[], saved: readonly TourWaypoint[]): TourWaypoint[] {
|
||||
return hikeWaypointsOf(points).map((point) => {
|
||||
const same = savedPointAt(point, saved);
|
||||
if (!same) return point;
|
||||
const name = point.name ?? same.name;
|
||||
// Its key too: a stage is put on its day by the key of the stop it starts at.
|
||||
return {
|
||||
...point,
|
||||
...(same.key ? { key: same.key } : {}),
|
||||
...(name ? { name } : {}),
|
||||
...(same.linked_place_id ? { linked_place_id: same.linked_place_id } : {}),
|
||||
};
|
||||
@@ -319,7 +333,7 @@ export interface HikeProposalContext {
|
||||
*/
|
||||
export function hikeProposalOf(
|
||||
request: HikeProposeRequest,
|
||||
points: readonly HikePlanPoint[],
|
||||
points: readonly HikeStop[],
|
||||
planned: PlannedHike,
|
||||
context: HikeProposalContext,
|
||||
): HikeProposal {
|
||||
@@ -329,8 +343,9 @@ export function hikeProposalOf(
|
||||
const heights = routed?.has_heights && line ? heightRangeOf(line) : null;
|
||||
const minutes = routed && line && positions ? waypointMinutesOf(line, positions, routed.duration_minutes) : null;
|
||||
const arrivals = arrivalsOf(request.start_time ?? null, minutes ?? points.map(() => null));
|
||||
// One day's sun and hours say nothing about a hike over several days.
|
||||
const day =
|
||||
routed && context.date
|
||||
routed && context.date && hikeStagesOf(points) === 1
|
||||
? hikeScheduleOf({
|
||||
date: context.date,
|
||||
dayId: context.dayId,
|
||||
@@ -357,11 +372,12 @@ export function hikeProposalOf(
|
||||
: {}),
|
||||
sac: proposalSacOf(routed?.grades ?? null),
|
||||
high_point: routed ? highPointOf(line) : null,
|
||||
waypoints: points.map(({ lat, lng, name, poi_category }, index) => ({
|
||||
waypoints: points.map(({ lat, lng, name, poi_category, stage_end }, index) => ({
|
||||
lat,
|
||||
lng,
|
||||
name: name || null,
|
||||
poi_category: poi_category ?? null,
|
||||
stage_end: stage_end === true,
|
||||
at_m: positions?.[index] ?? null,
|
||||
snapped_m: routed ? (planned.snapped?.[index] ?? null) : null,
|
||||
minutes: minutes?.[index] ?? null,
|
||||
|
||||
@@ -55,7 +55,7 @@ export class HikePlanMcp {
|
||||
@Tool({
|
||||
name: 'propose_hike',
|
||||
description:
|
||||
"Plan a hike for a trip and show it to the traveller, without saving anything; give it a name. The way on foot runs through waypoints in order (the start, the points on the way such as a hut or a summit, each with its poi_category where it is one, the end; with round_trip it comes back to the start) and takes no path harder than max_hiking_difficulty on the SAC scale (1 for T1 hiking to 6 for T6 difficult alpine hiking, 2 when left out), avoiding steep climbs, steps or ferries where there is a way round when hiking_preferences asks so. TREK's router plans it as the tour planner does. The answer gives distance_m, ascent_m and descent_m, the walking time without breaks (duration_minutes: by DIN 33466, the rule hiking signposts use, where the heights are known, duration_basis din33466; else the router's, duration_basis router), min_ele_m, max_ele_m and high_point, the SAC grades OpenStreetMap records along the way (sac: highest, the graded stretches in metres along the way, and unknown_share, the part with no grade, which is unknown and never easy), every point with at_m (where it lies along the way), snapped_m (how far it was moved onto a way), minutes from the start and, with start_time, its arrival, and along: summits, huts, water and viewpoints near the way (null with along false or where they could not be searched). With day_id (a day of the trip, whose date it takes) or date, schedule gives the day: the arrival (next_day past midnight), sunrise and sunset, the weather by the hour at the highest point (weather forecast, or climate further out: last year's day) and, without start_time, latest_start to be back half an hour before sunset; warnings name a start before sunrise (dark_start), an arrival after sunset (dark_end) or within the hour before it (dusk), and the first walking hour with thunderstorms (thunder) or likely rain (rain). Where no way was planned, route says why: no_valhalla (this TREK has no router that knows hiking grades), router_unavailable (try again later), no_way (nothing within the limit joins the points: a higher limit or other points may), point_off_the_way (unreachable names the point and how far it is from any way) or too_long (longer than one hike is planned for: split it into shorter hikes). To compare ways, propose each one with its own variant_label, such as 'short and steep' or 'by the lake', and along false. The chat shows the route, its profile, times, weather and warnings as a card: never list coordinates, the hours or the figures, sum the hike up in a sentence and say what matters. Propose first and create the hike with create_hike only after the traveller said yes.",
|
||||
"Plan a hike for a trip and show it to the traveller, without saving anything; give it a name. A hike over several days (a trek from hut to hut) is one hike: mark each stop a day ends at with stage_end, and the card shows its stages. The way on foot runs through waypoints in order (the start, the points on the way such as a hut or a summit, each with its poi_category where it is one, the end; with round_trip it comes back to the start) and takes no path harder than max_hiking_difficulty on the SAC scale (1 for T1 hiking to 6 for T6 difficult alpine hiking, 2 when left out), avoiding steep climbs, steps or ferries where there is a way round when hiking_preferences asks so. TREK's router plans it as the tour planner does. The answer gives distance_m, ascent_m and descent_m, the walking time without breaks (duration_minutes: by DIN 33466, the rule hiking signposts use, where the heights are known, duration_basis din33466; else the router's, duration_basis router), min_ele_m, max_ele_m and high_point, the SAC grades OpenStreetMap records along the way (sac: highest, the graded stretches in metres along the way, and unknown_share, the part with no grade, which is unknown and never easy), every point with at_m (where it lies along the way), snapped_m (how far it was moved onto a way), minutes from the start and, with start_time, its arrival, and along: summits, huts, water and viewpoints near the way (null with along false or where they could not be searched). With day_id (a day of the trip, whose date it takes) or date, schedule gives the day: the arrival (next_day past midnight), sunrise and sunset, the weather by the hour at the highest point (weather forecast, or climate further out: last year's day) and, without start_time, latest_start to be back half an hour before sunset; warnings name a start before sunrise (dark_start), an arrival after sunset (dark_end) or within the hour before it (dusk), and the first walking hour with thunderstorms (thunder) or likely rain (rain). Where no way was planned, route says why: no_valhalla (this TREK has no router that knows hiking grades), router_unavailable (try again later), no_way (nothing within the limit joins the points: a higher limit or other points may), point_off_the_way (unreachable names the point and how far it is from any way) or too_long (longer than one hike is planned for: split it into shorter hikes). To compare ways, propose each one with its own variant_label, such as 'short and steep' or 'by the lake', and along false. The chat shows the route, its profile, times, weather and warnings as a card: never list coordinates, the hours or the figures, sum the hike up in a sentence and say what matters. Propose first and create the hike with create_hike only after the traveller said yes.",
|
||||
inputSchema: { tripId: idSchema, ...hikeProposeRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
@@ -69,7 +69,7 @@ export class HikePlanMcp {
|
||||
@Tool({
|
||||
name: 'create_hike',
|
||||
description:
|
||||
"Create a hike in a trip from points the traveller confirmed, usually the name and waypoints of a proposal of propose_hike with its max_hiking_difficulty, hiking_preferences and round_trip. It is saved the way the planner saves a new hike: a tour of type hike with its points in order (start, points on the way, end, with their names and poi_category), the way on foot planned by the same router as the proposal and kept whole (the very line a proposal of the last minutes showed), with its heights where every point has one, its distance, ascent, descent and walking time, its hiking limit and preferences, and planned_duration_minutes (the time out, breaks included) where given. Where the router did not answer, for the way or its heights (route planned false, why router_unavailable), the hike is saved with its points only (route_pending true) and TREK plans the way when someone opens it in the planner; no straight line is stored. Any other reason the proposal names (no_valhalla, no_way, point_off_the_way, too_long) refuses the hike with why, and nothing is saved. With day_id the hike is put on that day of the trip in the same write, start_time kept as the start of that visit (which needs day editing permission too); assignment names the visit, null without a day. The answer is the tour as list_tours reads it (tour.place_id is the tour's id, its revision 1), route and assignment. Put it on a day later with assign_place_to_day, link it to the packing list with link_tour_packing, export it with export_tour_gpx, change it with update_tour. Needs place editing permission on the trip. Create it only after the traveller said yes.",
|
||||
"Create a hike in a trip from points the traveller confirmed, usually the name and waypoints of a proposal of propose_hike with its max_hiking_difficulty, hiking_preferences and round_trip, and its stage_end marks for a hike over several days; then put each stage on its day with assign_place_to_day and tourStageKey (the key of the stop the stage starts at, from the stage_stops list_tours gives); leave day_id out for such a hike, which would put the whole hike on one day. It is saved the way the planner saves a new hike: a tour of type hike with its points in order (start, points on the way, end, with their names and poi_category), the way on foot planned by the same router as the proposal and kept whole (the very line a proposal of the last minutes showed), with its heights where every point has one, its distance, ascent, descent and walking time, its hiking limit and preferences, and planned_duration_minutes (the time out, breaks included) where given. Where the router did not answer, for the way or its heights (route planned false, why router_unavailable), the hike is saved with its points only (route_pending true) and TREK plans the way when someone opens it in the planner; no straight line is stored. Any other reason the proposal names (no_valhalla, no_way, point_off_the_way, too_long) refuses the hike with why, and nothing is saved. With day_id the hike is put on that day of the trip in the same write, start_time kept as the start of that visit (which needs day editing permission too); assignment names the visit, null without a day. The answer is the tour as list_tours reads it (tour.place_id is the tour's id, its revision 1), route and assignment. Put it on a day later with assign_place_to_day, link it to the packing list with link_tour_packing, export it with export_tour_gpx, change it with update_tour. Needs place editing permission on the trip. Create it only after the traveller said yes.",
|
||||
inputSchema: { tripId: idSchema.describe('The trip to create the hike in'), ...hikeCreateRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
@@ -88,7 +88,7 @@ export class HikePlanMcp {
|
||||
@Tool({
|
||||
name: 'update_tour',
|
||||
description:
|
||||
"Change a saved hike (tour_type hike) against the revision it was read at: expected_revision is tour.revision from get_tour_plan or list_tours. A new name, description or planned_duration_minutes keeps the hike's way. New waypoints (start to end; a round trip ends on its start), a new max_hiking_difficulty or new hiking_preferences plan the way anew as propose_hike plans it, and so does a hike still waiting for its way (route_pending); propose the new way to the traveller first. A hike changed since that revision is refused as a conflict: read it again and show the traveller what changed. Where the new way cannot be planned, or not with its heights, nothing is saved and the hike keeps its way; the error says why. A new point standing where a saved one stood (within 25 m) keeps that point's link to a place of the trip and its name. A hike with a section drawn by hand (a via ferrata, a free line, a ferry) or split into stages takes new points only in the planner, and the hand-drawn one no new limit or preferences either: those changes are refused here. A recorded track without points of its own (an import) takes only new waypoints, which plan it over and keep the recording. Any other type is refused: change a city walk with prepare_tour_change and save_tour_change. The hike stays on its days. The answer is the tour as saved, with its new revision, route and replanned. Needs place editing permission on the trip. Change it only after the traveller said yes.",
|
||||
"Change a saved hike (tour_type hike) against the revision it was read at: expected_revision is tour.revision from get_tour_plan or list_tours. A new name, description or planned_duration_minutes keeps the hike's way. New waypoints (start to end; a round trip ends on its start), a new max_hiking_difficulty or new hiking_preferences plan the way anew as propose_hike plans it, and so does a hike still waiting for its way (route_pending); propose the new way to the traveller first. A hike changed since that revision is refused as a conflict: read it again and show the traveller what changed. Where the new way cannot be planned, or not with its heights, nothing is saved and the hike keeps its way; the error says why. A new point standing where a saved one stood (within 25 m) keeps that point's link to a place of the trip and its name. A hike with a section drawn by hand (a via ferrata, a free line, a ferry) takes new points, a new limit or new preferences only in the planner: those changes are refused here. A hike split into stages takes new points only with stage_end given again on each stop a day ends at, and its stages keep their days where a stop stays where it was. A recorded track without points of its own (an import) takes only new waypoints, which plan it over and keep the recording. Any other type is refused: change a city walk with prepare_tour_change and save_tour_change. The hike stays on its days. The answer is the tour as saved, with its new revision, route and replanned. Needs place editing permission on the trip. Change it only after the traveller said yes.",
|
||||
inputSchema: { tripId: idSchema, ...tourUpdateRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
HIKE_ALONG_CATEGORIES,
|
||||
HIKE_ALONG_CORRIDOR_M,
|
||||
HIKE_PLAN_MAX_WAYPOINTS,
|
||||
hikeStageIssues,
|
||||
hikingPreferencesOf,
|
||||
TOUR_POI_MAX_LINE_POINTS,
|
||||
tourGpxImportFieldsSchema,
|
||||
@@ -37,6 +38,7 @@ import {
|
||||
type HikeAlongPlace,
|
||||
type HikeCreateRequest,
|
||||
type HikePlanPoint,
|
||||
type HikeStop,
|
||||
type HikeProposal,
|
||||
type HikeProposeRequest,
|
||||
type HikingPreferences,
|
||||
@@ -109,14 +111,21 @@ const HAND_DRAWN =
|
||||
* ends of its stages would go with the points they belong to, and a stage
|
||||
* that goes would leave its day. Null where new points take nothing away.
|
||||
*/
|
||||
function repointingRefusal(saved: readonly TourWaypoint[]): string | null {
|
||||
function repointingRefusal(saved: readonly TourWaypoint[], points: readonly HikeStop[]): string | null {
|
||||
if (saved.some((point) => point.fixed_leg)) return HAND_DRAWN;
|
||||
if (saved.some((point) => point.stage_end)) {
|
||||
return 'This hike is split into stages over several days, which new points would end: change its points in the planner. A new limit or new preferences plan it anew here, its stages kept.';
|
||||
// New points carry the stages of the hike themselves; without any, its stages would silently end.
|
||||
if (saved.some((point) => point.stage_end) && !points.some((point) => point.stage_end)) {
|
||||
return 'This hike is split into stages over several days: give stage_end again on each stop a day ends at, or the stages would end. A new limit or new preferences alone plan it anew here, its stages kept.';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Stage ends that do not hold (at the start or the end, too many stages): refused with their reason. */
|
||||
function refuseBadStages(points: readonly HikeStop[], roundTrip: boolean | undefined): void {
|
||||
const issues = hikeStageIssues(points, roundTrip);
|
||||
if (issues.length > 0) throw badRequest(issues.map((issue) => issue.message).join('; '));
|
||||
}
|
||||
|
||||
/**
|
||||
* A hike planned with the traveller over MCP, end to end on the server: the
|
||||
* proposal reads only and may be asked for as often as ways are compared;
|
||||
@@ -165,6 +174,7 @@ export class HikePlanService {
|
||||
* best effort: without them the proposal still answers.
|
||||
*/
|
||||
async propose(userId: number, tripId: number, request: HikeProposeRequest): Promise<HikeProposal> {
|
||||
refuseBadStages(request.waypoints, request.round_trip);
|
||||
const day = await this.dayOf(tripId, request.day_id, request.date);
|
||||
const points = hikePointsOf(request.waypoints, request.round_trip);
|
||||
const { max_hiking_difficulty: limit, hiking_preferences: preferences } = request;
|
||||
@@ -231,6 +241,7 @@ export class HikePlanService {
|
||||
* drop onto the day tell it.
|
||||
*/
|
||||
async create(userId: number, tripId: number, request: HikeCreateRequest): Promise<HikeCreated> {
|
||||
refuseBadStages(request.waypoints, request.round_trip);
|
||||
const day = request.day_id === undefined ? null : await this.dayOf(tripId, request.day_id, undefined);
|
||||
const points = hikePointsOf(request.waypoints, request.round_trip);
|
||||
const { max_hiking_difficulty: limit, hiking_preferences: preferences } = request;
|
||||
@@ -295,7 +306,8 @@ export class HikePlanService {
|
||||
'This hike is a recorded track without points of its own: give waypoints to plan it over (the recorded track is kept), or rename it with update_place.',
|
||||
);
|
||||
}
|
||||
const repointing = request.waypoints ? repointingRefusal(saved.waypoints) : null;
|
||||
if (request.waypoints) refuseBadStages(request.waypoints, false);
|
||||
const repointing = request.waypoints ? repointingRefusal(saved.waypoints, request.waypoints) : null;
|
||||
if (repointing) throw badRequest(repointing);
|
||||
const kept = hikingPreferencesOf(tour.hiking_preferences);
|
||||
// A recorded track keeps no limit of its own; planned over, it takes the planner's.
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import type { TourDayRow } from '../../db/repositories/Tours.repository';
|
||||
import { noAccess } from '../../mcp/tools/_shared';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, errorResult, ok, type McpContext } from '../../nest-mcp';
|
||||
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
|
||||
import {
|
||||
McpController,
|
||||
Tool,
|
||||
TOOL_ANNOTATIONS_READONLY,
|
||||
TOOL_ANNOTATIONS_WRITE,
|
||||
errorResult,
|
||||
ok,
|
||||
type McpContext,
|
||||
} from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
import { withoutLine } from './tour-activities.helpers';
|
||||
import { TourGpxExportService } from './tour-gpx-export.service';
|
||||
@@ -15,10 +24,13 @@ import { ToursService } from './tours.service';
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import {
|
||||
idSchema,
|
||||
stationKeySchema,
|
||||
tourPoiSearchRequestSchema,
|
||||
tourVisitUpdateRequestSchema,
|
||||
type TourDetailResponse,
|
||||
type TourListItem,
|
||||
type TourPoiSearchRequest,
|
||||
type TourVisitUpdateRequest,
|
||||
} from '@trek/shared';
|
||||
|
||||
type TourDay = Pick<TourDayRow, 'day_id' | 'day_number' | 'date' | 'title' | 'tour_stage_key'>;
|
||||
@@ -101,6 +113,7 @@ export class ToursMcp {
|
||||
private readonly gpxExport: TourGpxExportService,
|
||||
private readonly poiSearch: TourPoiSearchService,
|
||||
private readonly visits: TourVisitsService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
// Read by the addon gate of every tool here.
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
@@ -206,6 +219,70 @@ export class ToursMcp {
|
||||
}
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'set_city_walk_visit',
|
||||
description:
|
||||
'Check off a station of a city walk (tour_type walk) on one day it is on, as the travellers tap it in the day plan: visited, skipped, or planned to take a mark back. Use it when the travellers say where they are or what they did ("we are at the museum", "skip the tower"); stationKey is the key of the station from get_city_walk_progress or get_tour_plan. The mark belongs to that day only, as every visit does. The answer gives the status before and after, and the walk as it now stands that day (the same fields as get_city_walk_progress): read get_city_walk_remaining_time next for what is left. Needs the right to edit the trip days, as checking off in the day plan does. Nothing about the route changes.',
|
||||
inputSchema: {
|
||||
tripId: idSchema,
|
||||
placeId: idSchema.describe('The place id of the city walk, as list_tours gives it'),
|
||||
dayId: idSchema.describe('The day the walk is on, as find_tours_for_day gives it'),
|
||||
stationKey: stationKeySchema.describe('The key of the station, as get_city_walk_progress gives it'),
|
||||
status: tourVisitUpdateRequestSchema.shape.status.describe(
|
||||
'visited for a station seen, skipped for one left out, planned to take a mark back',
|
||||
),
|
||||
assignmentId: idSchema
|
||||
.optional()
|
||||
.describe(
|
||||
'For a walk put on that day more than once: the assignment of the run, one of that walk on that day; without it the first run of the day',
|
||||
),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
access: { group: 'trips', mode: 'write' },
|
||||
})
|
||||
async setCityWalkVisit(
|
||||
{
|
||||
tripId,
|
||||
placeId,
|
||||
dayId,
|
||||
stationKey,
|
||||
status,
|
||||
assignmentId,
|
||||
}: {
|
||||
tripId: number;
|
||||
placeId: number;
|
||||
dayId: number;
|
||||
stationKey: string;
|
||||
status: TourVisitUpdateRequest['status'];
|
||||
assignmentId?: number;
|
||||
},
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (!(await this.access.findAccessible(tripId, ctx.userId))) return noAccess();
|
||||
// Checking off in the day plan is what REST asks 'day_edit' for.
|
||||
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
let before: WalkProgress;
|
||||
try {
|
||||
before = await this.visits.progress(tripId, placeId, dayId, assignmentId);
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof NotFoundException) return errorResult('No city walk of this trip is on that day.');
|
||||
throw err;
|
||||
}
|
||||
const station = before.stations.find((one) => one.key === stationKey);
|
||||
if (!station)
|
||||
return errorResult('This walk has no station with that key on that day: read get_city_walk_progress.');
|
||||
await this.visits.update(String(tripId), before.assignment_id, stationKey, { status });
|
||||
const after = await this.visits.progress(tripId, placeId, dayId, before.assignment_id);
|
||||
return ok({
|
||||
station_key: stationKey,
|
||||
name: station.name,
|
||||
previous_status: station.status,
|
||||
status,
|
||||
walk: after,
|
||||
});
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'get_city_walk_remaining_time',
|
||||
description:
|
||||
|
||||
@@ -202,8 +202,8 @@ function proposalFor(asked: HikeProposeRequest): HikeProposal {
|
||||
sac: { segments: [{ from_m: 0, to_m: 1112, sac: 2 }], highest: 2, unknown_share: 0 },
|
||||
high_point: { lat: 47.61, lng: 11.3, ele_m: 880, at_m: 1112 },
|
||||
waypoints: [
|
||||
{ ...WAYPOINTS[0], poi_category: null, at_m: 0, snapped_m: 2, minutes: 0, arrival: null },
|
||||
{ ...WAYPOINTS[1], at_m: 1112, snapped_m: 3, minutes: 22, arrival: null },
|
||||
{ ...WAYPOINTS[0], poi_category: null, at_m: 0, snapped_m: 2, minutes: 0, arrival: null, stage_end: false },
|
||||
{ ...WAYPOINTS[1], at_m: 1112, snapped_m: 3, minutes: 22, arrival: null, stage_end: false },
|
||||
],
|
||||
along: null,
|
||||
max_hiking_difficulty: 2,
|
||||
|
||||
@@ -9,14 +9,18 @@
|
||||
* viewer's write is refused with the tool's own words, and an operation the
|
||||
* engine refuses with the operation it names; a REST save and an MCP write
|
||||
* send the same event to the same users, REST leaving out the tab that saved
|
||||
* and MCP none; and the tools are gone while the Journey addon is off.
|
||||
* and MCP none; the tools are gone while the Journey addon is off; and a book
|
||||
* a newer Studio wrote is refused with 409 and its code over both, even when
|
||||
* its document holds what this build cannot parse.
|
||||
*/
|
||||
import { ADDON_IDS } from '../../src/addons';
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { JourneyBooks } from '../../src/db/entities/JourneyBooks.entity';
|
||||
import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp';
|
||||
import { withRequestContext } from '../../src/nest/database/request-context';
|
||||
import { authCookie } from '../helpers/auth';
|
||||
import { addJourneyContributor, makeJourney } from '../helpers/factories/journeys';
|
||||
import { findRow, updateRows } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { spyOnRealtime, type RealtimeSpies } from '../helpers/fake-realtime';
|
||||
@@ -198,4 +202,62 @@ describe('Studio book over MCP and REST', () => {
|
||||
expect(names.filter((name) => BOOK_TOOLS.includes(name))).toEqual([]);
|
||||
expect(names.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('JBE2E-005: a book a newer Studio saved refuses a REST save with 409 and its code, and an MCP write in its words', async () => {
|
||||
const { owner, journey, inner } = await journeyWithBook();
|
||||
const before = await request(app.getHttpServer())
|
||||
.get(`/api/journeys/${journey.id}/book`)
|
||||
.set('Cookie', authCookie(owner.id));
|
||||
const row = await findRow(orm, JourneyBooks, { journey: journey.id });
|
||||
const newer = JSON.stringify({ ...JSON.parse(String(row?.document)), schemaRev: 2 });
|
||||
await updateRows(orm, JourneyBooks, { journey: journey.id }, { document: newer });
|
||||
|
||||
const saved = await request(app.getHttpServer())
|
||||
.put(`/api/journeys/${journey.id}/book`)
|
||||
.set('Cookie', authCookie(owner.id))
|
||||
.send({ title: before.body.book.title, document: before.body.book.document, baseVersion: 1 });
|
||||
expect(saved.status).toBe(409);
|
||||
expect(saved.body).toEqual({
|
||||
error: 'Book was saved by a newer version of TREK Studio',
|
||||
code: 'book_schema_newer',
|
||||
schemaRev: 2,
|
||||
});
|
||||
|
||||
const tool = await callTool(owner.id, 'edit_book_page', {
|
||||
journeyId: journey.id,
|
||||
spreadId: inner,
|
||||
ops: [{ op: 'background', color: '#202020' }],
|
||||
});
|
||||
expect(tool).toEqual({
|
||||
error:
|
||||
'This book was saved by a newer version of TREK than this server runs. Changing it here would drop what that version added, so it stays as it is.',
|
||||
});
|
||||
expect(sent()).toEqual([]);
|
||||
const after = await findRow(orm, JourneyBooks, { journey: journey.id });
|
||||
expect([after?.version, after?.document]).toEqual([1, newer]);
|
||||
});
|
||||
|
||||
it('JBE2E-006: a save of a book a newer Studio wrote, with a kind this one cannot read, is a 409 with its code, not a 400', async () => {
|
||||
const { owner, journey } = await journeyWithBook();
|
||||
const before = await request(app.getHttpServer())
|
||||
.get(`/api/journeys/${journey.id}/book`)
|
||||
.set('Cookie', authCookie(owner.id));
|
||||
const document = before.body.book.document as { spreads: Array<{ elements: unknown[] }> };
|
||||
const frame = { x: 10, y: 10, w: 40, h: 40 };
|
||||
document.spreads[0]?.elements.push({ id: 'from-later', kind: 'sticker', frame, stickerId: 'lemon' });
|
||||
|
||||
const saved = await request(app.getHttpServer())
|
||||
.put(`/api/journeys/${journey.id}/book`)
|
||||
.set('Cookie', authCookie(owner.id))
|
||||
.send({ title: before.body.book.title, document: { ...document, schemaRev: 2 }, baseVersion: 1 });
|
||||
expect(saved.status).toBe(409);
|
||||
expect(saved.body).toEqual({
|
||||
error: 'Book was saved by a newer version of TREK Studio',
|
||||
code: 'book_schema_newer',
|
||||
schemaRev: 2,
|
||||
});
|
||||
expect(sent()).toEqual([]);
|
||||
const after = await findRow(orm, JourneyBooks, { journey: journey.id });
|
||||
expect(after?.version).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ import { TourWaypoints } from '../../../src/db/entities/TourWaypoints.entity';
|
||||
import { Tours } from '../../../src/db/entities/Tours.entity';
|
||||
import { RoadtripRouterService } from '../../../src/nest/roadtrip/roadtrip-router.service';
|
||||
import { proposalIdOf } from '../../../src/nest/tours/tour-change-proposal';
|
||||
import { makeDayAssignment } from '../../helpers/factories/itinerary';
|
||||
import { makePlace } from '../../helpers/factories/places';
|
||||
import { createRow, deleteRows, updateRows } from '../../helpers/factories/rows';
|
||||
import { addTourWaypoints, linkTourPacking, makeTour, makeTourActivity } from '../../helpers/factories/tours';
|
||||
@@ -163,6 +164,23 @@ async function keptTour(s: Scene, app: INestApplication): Promise<void> {
|
||||
madeFor.set(s.n, row.id);
|
||||
}
|
||||
|
||||
/** A city walk of two stations on the scene's first day; the walk's place is the row made. */
|
||||
async function walkOnDay(s: Scene, app: INestApplication): Promise<void> {
|
||||
const orm = ormOf(app);
|
||||
const walk = await makePlace(orm, s.trip.id, { name: `Old town ${s.n}` });
|
||||
await makeTour(orm, walk.id, { tourTypeRef: 'walk' });
|
||||
await addTourWaypoints(orm, walk.id, [
|
||||
{ lat: 48.1, lng: 11.5, station_key: 'stop-gate', name: 'Gate' },
|
||||
{ lat: 48.108, lng: 11.5, station_key: 'stop-park', name: 'Park' },
|
||||
]);
|
||||
const visit = await makeDayAssignment(orm, s.days[0].id, walk.id);
|
||||
madeFor.set(s.n, walk.id);
|
||||
visitFor.set(s.n, visit.id);
|
||||
}
|
||||
|
||||
/** The day assignment of the walk a case's setup put on the first day, by the scene's number. */
|
||||
const visitFor = new Map<number, number>();
|
||||
|
||||
/** Two stops of a Google Maps directions link, reviewed. */
|
||||
const GOOGLE_STOPS = [
|
||||
{ name: 'Brandenburger Tor', lat: 52.5163, lng: 13.3777 },
|
||||
@@ -293,6 +311,24 @@ export const toursRoadtrip: CaseGroup = {
|
||||
stub: routerDown,
|
||||
expect: ['tours:changed', 'place:created'],
|
||||
},
|
||||
{
|
||||
tool: 'set_city_walk_visit',
|
||||
setup: walkOnDay,
|
||||
args: (s) => ({
|
||||
tripId: s.trip.id,
|
||||
placeId: made(s),
|
||||
dayId: s.days[0].id,
|
||||
stationKey: 'stop-park',
|
||||
status: 'visited',
|
||||
}),
|
||||
// The day plan checks a station off through the visits route.
|
||||
rest: {
|
||||
method: 'put',
|
||||
path: (s) => `/api/trips/${s.trip.id}/tour-visits/${visitFor.get(s.n)}/stop-park`,
|
||||
body: () => ({ status: 'visited' }),
|
||||
},
|
||||
expect: ['tours:visits'],
|
||||
},
|
||||
{
|
||||
tool: 'create_hike',
|
||||
args: (s) => ({
|
||||
|
||||
@@ -3,7 +3,13 @@
|
||||
* same note is not added twice, notes that would run past the limit are
|
||||
* refused whole, and other trips' notes stay as they are.
|
||||
*/
|
||||
import { noteOf, REMEMBER_SPEC, rememberForTrip } from '../../../../src/nest/assistant/assistant-memory';
|
||||
import type { AgentToolPort } from '../../../../src/nest/assistant/assistant-agent';
|
||||
import {
|
||||
noteOf,
|
||||
REMEMBER_SPEC,
|
||||
rememberForTrip,
|
||||
rememberingPort,
|
||||
} from '../../../../src/nest/assistant/assistant-memory';
|
||||
import type { SettingsService } from '../../../../src/nest/settings/settings.service';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
@@ -54,4 +60,31 @@ describe('the trip notes', () => {
|
||||
expect(noteOf({ note: 'y'.repeat(600) })).toHaveLength(500);
|
||||
expect(REMEMBER_SPEC.parameters).toMatchObject({ required: ['note'], additionalProperties: false });
|
||||
});
|
||||
|
||||
it('ASTMEM-005: in a trip turn the note is kept at once as a read; other tools and a journey keep the port as it is', async () => {
|
||||
const port: AgentToolPort = {
|
||||
specs: () => [REMEMBER_SPEC],
|
||||
kindOf: (name) => (name === 'remember_for_trip' || name === 'create_place' ? 'write' : null),
|
||||
pinArgs: (_name, args) => ({ args: { ...args, tripId: 4 } }),
|
||||
call: vi.fn(async () => ({ ok: true, value: 'port' })),
|
||||
};
|
||||
const remember = vi.fn(async () => ({ ok: true, value: { notes: 'Vegetarian' } }));
|
||||
const kept = rememberingPort(port, remember);
|
||||
expect(kept.kindOf('remember_for_trip')).toBe('read');
|
||||
expect(kept.kindOf('create_place')).toBe('write');
|
||||
expect(kept.kindOf('nope')).toBeNull();
|
||||
expect(kept.pinArgs('remember_for_trip', { note: 'x' })).toEqual({ args: { note: 'x' } });
|
||||
expect(kept.pinArgs('create_place', {})).toEqual({ args: { tripId: 4 } });
|
||||
expect(await kept.call('remember_for_trip', { note: 'Vegetarian' })).toEqual({
|
||||
ok: true,
|
||||
value: { notes: 'Vegetarian' },
|
||||
});
|
||||
expect(await kept.call('create_place', {})).toEqual({ ok: true, value: 'port' });
|
||||
expect(kept.specs()).toEqual([REMEMBER_SPEC]);
|
||||
expect(remember).toHaveBeenCalledTimes(1);
|
||||
expect(rememberingPort(port, null)).toBe(port);
|
||||
// A session that does not hold the tool (a journey's) never gains it.
|
||||
const journey = rememberingPort({ ...port, kindOf: () => null }, remember);
|
||||
expect(journey.kindOf('remember_for_trip')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -224,11 +224,42 @@ describe('the designer in the Studio', () => {
|
||||
it('ASTBD-008: the Studio instructions end with the design rules, cache-stable and without dashes', () => {
|
||||
const prompt = studioPrompt('German', true);
|
||||
expect(prompt.endsWith(BOOK_DESIGN_PROMPT)).toBe(true);
|
||||
expect(BOOK_DESIGN_PROMPT.split('\n').length).toBeLessThanOrEqual(14);
|
||||
// The print rules, the energy, the type scale and the critique, on a budget the cache carries every turn.
|
||||
expect(BOOK_DESIGN_PROMPT.split('\n').length).toBeLessThanOrEqual(30);
|
||||
expect(BOOK_DESIGN_PROMPT.length).toBeLessThan(6000);
|
||||
for (const tool of ['design_book', 'revise_book_design', 'apply_book_design', 'preview_book_page']) {
|
||||
expect(BOOK_DESIGN_PROMPT).toContain(tool);
|
||||
}
|
||||
expect(BOOK_DESIGN_PROMPT).not.toMatch(/[\u2013\u2014]/);
|
||||
expect(studioPrompt('German', true)).toBe(prompt);
|
||||
});
|
||||
|
||||
it('ASTBD-009: restraint is one energy among three, beside print rules that hold for every book', () => {
|
||||
for (const rule of ['200 dpi', 'fold', 'trim', 'bleed', 'binding', 'safe area']) {
|
||||
expect(BOOK_DESIGN_PROMPT, rule).toContain(rule);
|
||||
}
|
||||
for (const energy of ['- Calm:', '- Lively:', '- Loud:']) expect(BOOK_DESIGN_PROMPT).toContain(energy);
|
||||
expect(BOOK_DESIGN_PROMPT).toContain('A deliberate overlap is a design');
|
||||
});
|
||||
|
||||
it('ASTBD-010: gives the type scale in numbers against the page, and the critique to answer before a proposal', () => {
|
||||
for (const figure of ['72 to 180 pt', '12 to 30 % of the page height', 'at least 3:1', 'Body 9 to 11 pt']) {
|
||||
expect(BOOK_DESIGN_PROMPT, figure).toContain(figure);
|
||||
}
|
||||
expect(BOOK_DESIGN_PROMPT).toContain('captions 6.5 to 8 pt');
|
||||
// The cover tier carries a big title alone, and the faces named are faces the book has.
|
||||
expect(BOOK_DESIGN_PROMPT).toContain('type.display (up to 6.5');
|
||||
expect(BOOK_DESIGN_PROMPT).toContain('type.scale between 0.9 and 1.1');
|
||||
expect(BOOK_DESIGN_PROMPT).not.toMatch(/script/i);
|
||||
expect(BOOK_DESIGN_PROMPT).toContain('210 mm page and scaled with the page width');
|
||||
const rubric = BOOK_DESIGN_PROMPT.slice(BOOK_DESIGN_PROMPT.indexOf('answer silently'));
|
||||
expect(rubric.slice(0, rubric.indexOf('Fix what fails')).match(/\?/g)).toHaveLength(8);
|
||||
expect(BOOK_DESIGN_PROMPT).toContain('preview the cover at least twice');
|
||||
});
|
||||
|
||||
it('ASTBD-011: the Studio instructions take a layered page for a design and only an accidental overlap for a fault', () => {
|
||||
const prompt = studioPrompt('German', true);
|
||||
expect(prompt).toContain('photos or texts overlapping by accident');
|
||||
expect(prompt).toContain('a layered page (a title over a photo, a turned photo over a shape) is a design');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -180,6 +180,16 @@ describe('the card of a proposed hike', () => {
|
||||
expect(shown.warnings).toEqual([{ kind: 'thunder', at: '08:00', count: null }]);
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-001b: a hike over several days counts its stages and marks the stops they end at', () => {
|
||||
const base = proposal();
|
||||
const [start, summit] = base.waypoints as Array<Record<string, unknown>>;
|
||||
const hut = { ...start, lat: 47.605, name: 'Hut', at_m: 556, minutes: 11, arrival: '08:11', stage_end: true };
|
||||
const shown = route(answerCardOf(...input('propose_hike', { ...base, waypoints: [start, hut, summit] })));
|
||||
expect(shown.stages).toBe(2);
|
||||
expect(shown.stops.filter((stop) => stop.stageEnd).map((stop) => stop.name)).toEqual(['Hut']);
|
||||
expect(route(answerCardOf(...input('propose_hike', proposal()))).stages).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-002: lists the points and the places along the way in the order walked, timed between', () => {
|
||||
const shown = route(answerCardOf(...input('propose_hike', proposal())));
|
||||
expect(shown.stops.map((stop) => [stop.role, stop.kind, stop.atM, stop.minutes, stop.clock])).toEqual([
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* ASTCARD-TOUR-050 to ASTCARD-TOUR-052
|
||||
*
|
||||
* A station of a city walk checked off on its day (set_city_walk_visit): the
|
||||
* card names the station and its walk with the verb of the mark, and the way
|
||||
* back sets the status the station had before, while it still has the one the
|
||||
* change gave it.
|
||||
*/
|
||||
import { buildTripCard } from '../../../../../../src/nest/assistant/assistant-context';
|
||||
import { unchangedSinceApplied } from '../../../../../../src/nest/assistant/assistant-undo.helpers';
|
||||
import { loadFor } from '../../../../../../src/nest/assistant/cards/card-context';
|
||||
import type { PreviewContext } from '../../../../../../src/nest/assistant/cards/card-types';
|
||||
import { readKey } from '../../../../../../src/nest/assistant/cards/card-values';
|
||||
import { ASSISTANT_UNDO_MAP, ASSISTANT_WRITE_TOOLS } from '../../../../../../src/nest/assistant/cards/registry';
|
||||
import { describeToolCall } from '../../../../../../src/nest/assistant/tool-call-preview.helpers';
|
||||
import { assistantChangePreviewSchema } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const logMock = vi.hoisted(() => ({ logInfo: vi.fn(), logError: vi.fn(), logWarn: vi.fn(), logDebug: vi.fn() }));
|
||||
vi.mock('../../../../../../src/nest/audit/audit-log.logger', () => logMock);
|
||||
|
||||
const card = buildTripCard(
|
||||
1,
|
||||
7,
|
||||
{ trip: { title: 'Lisbon' }, days: [{ id: 31, day_number: 1, date: '2026-11-11', assignments: [] }] },
|
||||
{ places: [{ id: 61, name: 'Old town walk', lat: 38.71, lng: -9.14 }] },
|
||||
null,
|
||||
);
|
||||
const ctx: PreviewContext = { card, categories: new Map(), locale: 'en-GB', today: '2026-11-01', airport: () => null };
|
||||
|
||||
const PROGRESS = {
|
||||
place_id: 61,
|
||||
day_id: 31,
|
||||
assignment_id: 90,
|
||||
stations: [
|
||||
{ key: 'stop-se', name: 'Sé Cathedral', status: 'visited' },
|
||||
{ key: 'stop-castle', name: 'Castle', status: 'planned' },
|
||||
],
|
||||
};
|
||||
const ARGS = { placeId: 61, dayId: 31, stationKey: 'stop-castle', status: 'skipped' };
|
||||
const RESULT = {
|
||||
station_key: 'stop-castle',
|
||||
name: 'Castle',
|
||||
previous_status: 'planned',
|
||||
status: 'skipped',
|
||||
walk: { assignment_id: 90 },
|
||||
};
|
||||
|
||||
describe('set_city_walk_visit in the chat', () => {
|
||||
it('ASTCARD-TOUR-050: the card names the station, its walk and day, with the verb of the mark', async () => {
|
||||
const read = vi.fn(async () => PROGRESS);
|
||||
const loaded = await loadFor('set_city_walk_visit', ARGS, read);
|
||||
expect(read).toHaveBeenCalledWith('get_city_walk_progress', { placeId: 61, dayId: 31 });
|
||||
const preview = describeToolCall('set_city_walk_visit', 'tc-1', ARGS, ctx, loaded);
|
||||
expect(assistantChangePreviewSchema.safeParse(preview).success).toBe(true);
|
||||
expect(preview).toMatchObject({ subject: 'Castle', verbKey: 'markSkipped', dayId: 31, placeIds: [61] });
|
||||
expect(preview.rows.map((row) => row.labelKey)).toEqual(['route', 'day']);
|
||||
expect(ASSISTANT_WRITE_TOOLS.set_city_walk_visit).toMatchObject({ entity: 'tour' });
|
||||
// Without the walk read, the card still names the walk and says what the mark does.
|
||||
const blind = describeToolCall('set_city_walk_visit', 'tc-2', { ...ARGS, status: 'visited' }, ctx, null);
|
||||
expect(blind).toMatchObject({ subject: 'Old town walk', verbKey: 'markVisited' });
|
||||
expect(await loadFor('set_city_walk_visit', { stationKey: 'x' }, read)).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-051: a mark the station already has offers no way back', () => {
|
||||
const same = describeToolCall(
|
||||
'set_city_walk_visit',
|
||||
'tc-3',
|
||||
{ ...ARGS, stationKey: 'stop-se', status: 'visited' },
|
||||
ctx,
|
||||
PROGRESS,
|
||||
);
|
||||
expect(same.undoable).toBe(false);
|
||||
});
|
||||
|
||||
it('ASTCARD-TOUR-052: the way back sets the status before, while the station still has the one the change gave it', () => {
|
||||
const undo = ASSISTANT_UNDO_MAP.set_city_walk_visit;
|
||||
expect(undo.tool).toBe('set_city_walk_visit');
|
||||
expect(undo.args(ARGS, RESULT, null)).toEqual({
|
||||
placeId: 61,
|
||||
dayId: 31,
|
||||
stationKey: 'stop-castle',
|
||||
status: 'planned',
|
||||
assignmentId: 90,
|
||||
});
|
||||
expect(undo.args(ARGS, { status: 'skipped' }, null)).toBeNull();
|
||||
const at = (status: string) => ({
|
||||
summary: { days: [] },
|
||||
places: { places: [] },
|
||||
reads: new Map([
|
||||
[
|
||||
readKey('get_city_walk_progress', { placeId: 61, dayId: 31 }),
|
||||
{ ...PROGRESS, stations: [{ key: 'stop-castle', status }] },
|
||||
],
|
||||
]),
|
||||
});
|
||||
const call = { args: ARGS, preview: null };
|
||||
expect(unchangedSinceApplied('set_city_walk_visit', RESULT, at('skipped'), call)).toBe(true);
|
||||
expect(unchangedSinceApplied('set_city_walk_visit', RESULT, at('visited'), call)).toBe(false);
|
||||
expect(unchangedSinceApplied('set_city_walk_visit', RESULT, at('skipped'))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
hikeCreateCommandOf,
|
||||
hikePointsOf,
|
||||
hikeProposalOf,
|
||||
hikeStagesOf,
|
||||
hikeWaypointsOf,
|
||||
keptWayOf,
|
||||
positionsAlong,
|
||||
@@ -35,7 +36,7 @@ import {
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
// HIKE-PLAN-001 to HIKE-PLAN-014
|
||||
// HIKE-PLAN-001 to HIKE-PLAN-017
|
||||
|
||||
/** A plan with its line, as the router answers it: without the router's legs and snaps unless given. */
|
||||
const planned = (
|
||||
@@ -393,3 +394,52 @@ describe('where and when a proposed hike reaches its points', () => {
|
||||
expect(alongPlacesOf([], LINE)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a hike over several days', () => {
|
||||
it('HIKE-PLAN-015: keeps a stage end only on a stop between the start and the end, and the way back of a round trip ends none', () => {
|
||||
const hut = { lat: 47.002, lng: 11, name: 'Hut', stage_end: true };
|
||||
expect(hikeWaypointsOf([{ ...START, stage_end: true }, hut, SUMMIT]).map((point) => point.stage_end)).toEqual([
|
||||
undefined,
|
||||
true,
|
||||
undefined,
|
||||
]);
|
||||
expect(hikeStagesOf([START, hut, SUMMIT])).toBe(2);
|
||||
expect(hikeStagesOf([START, SUMMIT])).toBe(1);
|
||||
const loop = hikePointsOf([START, hut, SUMMIT], true);
|
||||
expect(loop.at(-1)).toMatchObject({ lat: START.lat, lng: START.lng });
|
||||
expect(loop.at(-1)?.stage_end).toBeUndefined();
|
||||
});
|
||||
|
||||
it('HIKE-PLAN-016: a proposal over several days names its stage ends and sets no schedule of a single day', () => {
|
||||
const points = [START, { lat: 47.002, lng: 11, name: 'Hut', stage_end: true }, SUMMIT];
|
||||
const day: HikeProposalContext = { dayId: 3, date: '2027-07-10', along: null, weather: null };
|
||||
const proposal = hikeProposalOf({ name: 'Trek', waypoints: points }, points, planned(ROUTED, LINE), day);
|
||||
expect(proposal.waypoints.map((point) => point.stage_end)).toEqual([false, true, false]);
|
||||
expect(proposal.schedule).toBeNull();
|
||||
expect(hikeProposalSchema.safeParse(proposal).success).toBe(true);
|
||||
const single = hikeProposalOf(
|
||||
{ name: 'Day', waypoints: [START, SUMMIT] },
|
||||
[START, SUMMIT],
|
||||
planned(ROUTED, LINE),
|
||||
day,
|
||||
);
|
||||
expect(single.schedule).not.toBeNull();
|
||||
});
|
||||
|
||||
it('HIKE-PLAN-017: new points keep the key of a saved stop they stand on, so a stage keeps its day', () => {
|
||||
const saved = [
|
||||
{ lat: 47, lng: 11, role: 'start' as const, sequence: 0, key: 'k-start' },
|
||||
{ lat: 47.002, lng: 11, role: 'via' as const, sequence: 1, key: 'k-hut', stage_end: true },
|
||||
{ lat: 47.004, lng: 11, role: 'end' as const, sequence: 2, key: 'k-end' },
|
||||
];
|
||||
const repointed = repointedWaypoints(
|
||||
[START, { lat: 47.002, lng: 11, stage_end: true }, { lat: 47.006, lng: 11 }],
|
||||
saved,
|
||||
);
|
||||
expect(repointed.map((point) => [point.key, point.stage_end])).toEqual([
|
||||
['k-start', undefined],
|
||||
['k-hut', true],
|
||||
[undefined, undefined],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -464,6 +464,7 @@ describe('HikePlanMcp: propose_hike', () => {
|
||||
snapped_m: 12,
|
||||
minutes: 0,
|
||||
arrival: '08:30',
|
||||
stage_end: false,
|
||||
},
|
||||
{
|
||||
lat: 47.505,
|
||||
@@ -474,6 +475,7 @@ describe('HikePlanMcp: propose_hike', () => {
|
||||
snapped_m: 3,
|
||||
minutes: 26,
|
||||
arrival: '08:56',
|
||||
stage_end: false,
|
||||
},
|
||||
{
|
||||
lat: 47.51,
|
||||
@@ -484,6 +486,7 @@ describe('HikePlanMcp: propose_hike', () => {
|
||||
snapped_m: 40,
|
||||
minutes: 52,
|
||||
arrival: '09:22',
|
||||
stage_end: false,
|
||||
},
|
||||
]);
|
||||
expect(proposal.high_point).toEqual({ lat: 47.51, lng: 11.1, ele_m: 1000, at_m: 1112 });
|
||||
@@ -635,6 +638,17 @@ describe('HikePlanMcp: propose_hike', () => {
|
||||
),
|
||||
).rejects.toThrow('Day not found');
|
||||
});
|
||||
|
||||
it('HIKE-MCP-022: refuses a stage end at the start or the end of a hike, which ends no day', async () => {
|
||||
const f = await fixture();
|
||||
const [first, ...rest] = WAYPOINTS;
|
||||
await expect(
|
||||
mcp.proposeHike(
|
||||
{ tripId: f.trip.id, name: 'Wrong', waypoints: [{ ...first, stage_end: true }, ...rest] },
|
||||
ctx(f.user.id),
|
||||
),
|
||||
).rejects.toThrow('a stage ends at a stop between start and end');
|
||||
});
|
||||
});
|
||||
|
||||
describe('HikePlanMcp: create_hike', () => {
|
||||
|
||||
@@ -620,6 +620,116 @@ describe('editBook', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// -- Format revisions ---------------------------------------------------------
|
||||
|
||||
/*
|
||||
* A book written by a newer revision of the format than the writer knows. The
|
||||
* older writer has already dropped what it could not read, so its save, from
|
||||
* an old tab or a replayed offline copy, must not land; nor may the book tools
|
||||
* of a server that cannot read the book whole.
|
||||
*/
|
||||
describe('format revisions', () => {
|
||||
/** A journey whose stored book says it was written by revision `schemaRev`. */
|
||||
async function storedAt(schemaRev: number) {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
await insertRow(await sharedTestOrm(testDb), JourneyBooks, {
|
||||
journey: journey.id,
|
||||
title: 'T',
|
||||
document: JSON.stringify({ ...doc('newer'), schemaRev }),
|
||||
version: 1,
|
||||
});
|
||||
return { user, journey };
|
||||
}
|
||||
|
||||
const refusalOf = (thrown: unknown) =>
|
||||
thrown instanceof DomainError ? [thrown.getStatus(), thrown.code, thrown.toBody().code] : thrown;
|
||||
|
||||
it('JBOOK-011: refuses a save from a writer older than the stored book with 409 and the code, writing and sending nothing', async () => {
|
||||
const { user, journey } = await storedAt(2);
|
||||
const rec = await recordSends();
|
||||
try {
|
||||
const thrown = await catchDomainError(() =>
|
||||
books.saveBook(journey.id, user.id, { title: 'T', document: doc('older'), baseVersion: 1 }),
|
||||
);
|
||||
expect(refusalOf(thrown)).toEqual([409, 'book_schema_newer', 'book_schema_newer']);
|
||||
expect(thrown instanceof DomainError && thrown.toBody()).toMatchObject({
|
||||
error: 'Book was saved by a newer version of TREK Studio',
|
||||
schemaRev: 2,
|
||||
});
|
||||
expect(rec.sent).toEqual([]);
|
||||
const stored = await books.getBook(journey.id, user.id);
|
||||
expect([stored?.version, stored?.document.title, stored?.document.schemaRev]).toEqual([1, 'newer', 2]);
|
||||
} finally {
|
||||
rec.restore();
|
||||
}
|
||||
});
|
||||
|
||||
it('JBOOK-012: refuses a document newer than this server reads, first save and later save alike', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const journey = createJourney(testDb, user.id);
|
||||
const ahead = { ...doc('ahead'), schemaRev: 9 };
|
||||
const first = await catchDomainError(() => books.saveBook(journey.id, user.id, { title: 'T', document: ahead }));
|
||||
expect(refusalOf(first)).toEqual([409, 'book_schema_newer', 'book_schema_newer']);
|
||||
expect(await books.getBook(journey.id, user.id)).toBeNull();
|
||||
|
||||
await books.saveBook(journey.id, user.id, { title: 'T', document: doc('one') });
|
||||
const later = await catchDomainError(() =>
|
||||
books.saveBook(journey.id, user.id, { title: 'T', document: ahead, baseVersion: 1 }),
|
||||
);
|
||||
expect(refusalOf(later)).toEqual([409, 'book_schema_newer', 'book_schema_newer']);
|
||||
expect((await books.getBook(journey.id, user.id))?.document.title).toBe('one');
|
||||
});
|
||||
|
||||
it('JBOOK-013: a save at the stored revision or above it lands as before, and a book of today stores no revision', async () => {
|
||||
const { user, journey } = await storedAt(1);
|
||||
const same = await books.saveBook(journey.id, user.id, {
|
||||
title: 'T',
|
||||
document: { ...doc('same'), schemaRev: 1 },
|
||||
baseVersion: 1,
|
||||
});
|
||||
expect(same && 'record' in same && same.record.version).toBe(2);
|
||||
|
||||
const plain = await books.saveBook(journey.id, user.id, { title: 'T', document: doc('plain'), baseVersion: 2 });
|
||||
expect(plain && 'record' in plain && plain.record.version).toBe(3);
|
||||
const row = await findRow(await sharedTestOrm(testDb), JourneyBooks, { journey: journey.id });
|
||||
expect(JSON.parse(String(row?.document))).not.toHaveProperty('schemaRev');
|
||||
});
|
||||
|
||||
it('JBOOK-014: the book tools leave a book this server cannot read whole alone, before any edit runs', async () => {
|
||||
const { user, journey } = await storedAt(2);
|
||||
const rec = await recordSends();
|
||||
try {
|
||||
const edit = vi.fn(() => ({ title: 'T', document: normalizeBookDocument(doc('tool')), result: null }));
|
||||
const thrown = await catchDomainError(() => books.editBook(journey.id, user.id, edit));
|
||||
expect(refusalOf(thrown)).toEqual([409, 'book_schema_newer', 'book_schema_newer']);
|
||||
expect(thrown instanceof DomainError && thrown.mcpMessage).toMatch(/newer version of TREK/);
|
||||
expect(edit).not.toHaveBeenCalled();
|
||||
expect(rec.sent).toEqual([]);
|
||||
expect((await books.getBook(journey.id, user.id))?.document.title).toBe('newer');
|
||||
} finally {
|
||||
rec.restore();
|
||||
}
|
||||
});
|
||||
|
||||
it('JBOOK-015: an edit that hands back a document newer than this server reads is refused, the stored book untouched', async () => {
|
||||
const { user, journey } = await storedAt(1);
|
||||
const rec = await recordSends();
|
||||
try {
|
||||
const ahead = normalizeBookDocument({ ...doc('ahead'), schemaRev: 2 });
|
||||
const thrown = await catchDomainError(() =>
|
||||
books.editBook(journey.id, user.id, () => ({ title: 'T', document: ahead, result: null })),
|
||||
);
|
||||
expect(refusalOf(thrown)).toEqual([409, 'book_schema_newer', 'book_schema_newer']);
|
||||
expect(rec.sent).toEqual([]);
|
||||
const stored = await books.getBook(journey.id, user.id);
|
||||
expect([stored?.version, stored?.document.title, stored?.document.schemaRev]).toEqual([1, 'newer', 1]);
|
||||
} finally {
|
||||
rec.restore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// -- Deleting -----------------------------------------------------------------
|
||||
|
||||
describe('deleting', () => {
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
* stale version, and forgets the draft; a journey without a book gets a new
|
||||
* one and no revision; restoring the revision puts the book back only at the
|
||||
* version the apply left, and never writes a revision that does not read
|
||||
* back; five revisions are kept.
|
||||
* back or that a newer TREK kept; five revisions are kept.
|
||||
*/
|
||||
import { JourneyBookRevisions } from '../../../../src/db/entities/JourneyBookRevisions.entity';
|
||||
import { JourneyEntryPhotos } from '../../../../src/db/entities/JourneyEntryPhotos.entity';
|
||||
@@ -321,6 +321,25 @@ describe('taking a design back', () => {
|
||||
expect(told()).toEqual([]);
|
||||
});
|
||||
|
||||
it('JBDSN-011: a revision kept by a newer TREK is refused, never put back stripped of what this one cannot read', async () => {
|
||||
const { journey, owner } = await crew();
|
||||
const answer = await designs.design(journey.id, owner.id);
|
||||
const applied = await designs.apply(journey.id, owner.id, { designId: answer.design_id });
|
||||
const revisionId = applied.revision_id ?? 0;
|
||||
const kept = await findRow(orm, JourneyBookRevisions, { id: revisionId });
|
||||
const newer = JSON.stringify({ ...JSON.parse(String(kept?.document)), schemaRev: 2 });
|
||||
await updateRows(orm, JourneyBookRevisions, { id: revisionId }, { document: newer });
|
||||
t.realtime.reset();
|
||||
|
||||
const back = { revisionId, expectedVersion: applied.version };
|
||||
expect(await refusal(() => designs.restoreRevision(journey.id, owner.id, back))).toEqual({
|
||||
status: 409,
|
||||
code: 'book_schema_newer',
|
||||
});
|
||||
expect(await version(journey.id, owner.id)).toBe(applied.version);
|
||||
expect(told()).toEqual([]);
|
||||
});
|
||||
|
||||
it('JBDSN-009: a journey keeps its newest five revisions', async () => {
|
||||
const { journey, owner } = await crew();
|
||||
const books = t.get(JourneyBookService);
|
||||
|
||||
@@ -10,6 +10,7 @@ import { TourWaypoints } from '../../../src/db/entities/TourWaypoints.entity';
|
||||
import { Tours } from '../../../src/db/entities/Tours.entity';
|
||||
import type { McpContext } from '../../../src/nest-mcp';
|
||||
import { getEntry, type ClassRef } from '../../../src/nest-mcp/metadata';
|
||||
import { McpToolGuardsService } from '../../../src/nest/mcp-shared/mcp-tool-guards.service';
|
||||
import { PlacesMcp } from '../../../src/nest/places/places.mcp';
|
||||
import { TourLibraryMcp } from '../../../src/nest/tours/tour-library.mcp';
|
||||
import { TOUR_PLAN_LINE_POINTS } from '../../../src/nest/tours/tour-plan-read';
|
||||
@@ -249,6 +250,57 @@ describe('ToursMcp', () => {
|
||||
expect(answers).toEqual(notThere.map(() => ({ error: 'No city walk of this trip is on that day.' })));
|
||||
});
|
||||
|
||||
it('TOURS-MCP-033: set_city_walk_visit checks a station off on its day, says what it was, and takes a mark back', async () => {
|
||||
const { member, trip, day1, walk, onDay1 } = await walkFixture();
|
||||
const at = { tripId: trip.id, placeId: walk.id, dayId: day1.id };
|
||||
const marked = read(
|
||||
await mcp.setCityWalkVisit({ ...at, stationKey: 'stop-park', status: 'visited' }, ctx(member.id)),
|
||||
);
|
||||
expect(marked).toMatchObject({
|
||||
station_key: 'stop-park',
|
||||
name: null,
|
||||
previous_status: 'planned',
|
||||
status: 'visited',
|
||||
walk: { assignment_id: onDay1.id },
|
||||
});
|
||||
expect(marked.walk.stations.map((station: { status: string }) => station.status)).toEqual([
|
||||
'visited',
|
||||
'skipped',
|
||||
'visited',
|
||||
]);
|
||||
const back = read(
|
||||
await mcp.setCityWalkVisit({ ...at, stationKey: 'stop-market', status: 'planned' }, ctx(member.id)),
|
||||
);
|
||||
expect(back).toMatchObject({ name: null, previous_status: 'skipped', status: 'planned' });
|
||||
const orm = await createTestOrm(db);
|
||||
expect(await countRows(orm, TourStationVisits, { station_key: 'stop-market' })).toBe(0);
|
||||
await orm.close();
|
||||
});
|
||||
|
||||
it('TOURS-MCP-034: set_city_walk_visit refuses an outsider, a member without day_edit, an unknown station and a day without the walk', async () => {
|
||||
const { user, outsider, trip, day1, day2, walk } = await walkFixture();
|
||||
const at = { tripId: trip.id, placeId: walk.id, dayId: day1.id, status: 'visited' as const };
|
||||
expect(read(await mcp.setCityWalkVisit({ ...at, stationKey: 'stop-park' }, ctx(outsider.id)))).toEqual({
|
||||
error: 'Trip not found or access denied.',
|
||||
});
|
||||
const guards = t.get(McpToolGuardsService);
|
||||
const denied = vi.spyOn(guards, 'hasTripPermission').mockResolvedValueOnce(false);
|
||||
try {
|
||||
expect(read(await mcp.setCityWalkVisit({ ...at, stationKey: 'stop-park' }, ctx(user.id)))).toEqual({
|
||||
error: 'You do not have permission to perform this action on this trip.',
|
||||
});
|
||||
expect(denied).toHaveBeenCalledWith('day_edit', trip.id, user.id);
|
||||
} finally {
|
||||
denied.mockRestore();
|
||||
}
|
||||
expect(read(await mcp.setCityWalkVisit({ ...at, stationKey: 'stop-nowhere' }, ctx(user.id))).error).toMatch(
|
||||
/no station with that key/,
|
||||
);
|
||||
expect(read(await mcp.setCityWalkVisit({ ...at, dayId: day2.id, stationKey: 'stop-park' }, ctx(user.id)))).toEqual({
|
||||
error: 'No city walk of this trip is on that day.',
|
||||
});
|
||||
});
|
||||
|
||||
it('TOURS-MCP-010: a failure other than a missing walk is not passed off as no walk', async () => {
|
||||
const { user, trip, day1, walk } = await walkFixture();
|
||||
const failure = new Error('database gone');
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
// Regenerates src/book/book-icon-names-*.data.ts, the lucide drawings the
|
||||
// Studio's icon tab offers, from the lucide-react installed at the repo root.
|
||||
// Run from shared/: `node scripts/gen-book-icon-names.mjs`.
|
||||
//
|
||||
// Read from the package's type declarations rather than imported: the shared
|
||||
// package has no lucide dependency of its own and must not grow one, the
|
||||
// contract layer stays zod only. The names are taken the way the client's
|
||||
// iconLibrary.ts takes them from the module: every PascalCase export, less the
|
||||
// `Lucide*` and `*Icon` aliases of a name that exists bare, and less `Icon`,
|
||||
// the component every drawing is built on. client/src/components/Studio/
|
||||
// iconLibrary.test.ts fails when the files and the shipped library drift apart.
|
||||
import { readFileSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const lucide = join(here, '..', '..', 'node_modules', 'lucide-react');
|
||||
const { version } = JSON.parse(readFileSync(join(lucide, 'package.json'), 'utf8'));
|
||||
const declarations = readFileSync(join(lucide, 'dist', 'lucide-react.d.ts'), 'utf8');
|
||||
|
||||
/** The last `export { ... };` of the declarations, which names every icon and its aliases. */
|
||||
const exportLine = declarations
|
||||
.split('\n')
|
||||
.filter((line) => line.startsWith('export { '))
|
||||
.pop();
|
||||
if (!exportLine) throw new Error('no export list in lucide-react.d.ts');
|
||||
|
||||
const PASCAL_CASE = /^[A-Z][A-Za-z0-9]*$/;
|
||||
const exported = exportLine
|
||||
.replace(/^export \{ /, '')
|
||||
.replace(/ \};\s*$/, '')
|
||||
.split(',')
|
||||
.map((part) =>
|
||||
part
|
||||
.trim()
|
||||
.split(/\s+as\s+/)
|
||||
.pop(),
|
||||
)
|
||||
.filter((name) => PASCAL_CASE.test(name));
|
||||
const present = new Set(exported);
|
||||
const names = [...present]
|
||||
.filter((name) => !(name.startsWith('Lucide') && present.has(name.slice(6))))
|
||||
.filter((name) => !(name.endsWith('Icon') && present.has(name.slice(0, -4))))
|
||||
.filter((name) => name !== 'Icon')
|
||||
.sort();
|
||||
|
||||
/** The three files and the initials each holds, so none of them passes a thousand lines. */
|
||||
const PARTS = [
|
||||
{ suffix: 'a-e', constant: 'BOOK_ICON_NAMES_A_E', label: 'A to E', test: /^[A-E]/ },
|
||||
{ suffix: 'f-p', constant: 'BOOK_ICON_NAMES_F_P', label: 'F to P', test: /^[F-P]/ },
|
||||
{ suffix: 'q-z', constant: 'BOOK_ICON_NAMES_Q_Z', label: 'Q to Z', test: /^[Q-Z]/ },
|
||||
];
|
||||
|
||||
for (const part of PARTS) {
|
||||
const list = names.filter((name) => part.test.test(name));
|
||||
const source = `/**
|
||||
* The lucide drawings the Studio offers, ${part.label}: part of BOOK_ICON_NAMES
|
||||
* (book-icons.ts). Generated from lucide-react ${version} by
|
||||
* scripts/gen-book-icon-names.mjs, never edited by hand; the client's
|
||||
* iconLibrary.test.ts fails when the list and the library it ships drift apart.
|
||||
*/
|
||||
export const ${part.constant}: readonly string[] = [
|
||||
${list.map((name) => ` '${name}',`).join('\n')}
|
||||
];
|
||||
`;
|
||||
writeFileSync(join(here, '..', 'src', 'book', `book-icon-names-${part.suffix}.data.ts`), source);
|
||||
}
|
||||
console.log(`wrote ${names.length} icon names from lucide-react ${version}`);
|
||||
@@ -86,7 +86,6 @@ function checkPluralForms(locale, keys, groups) {
|
||||
* ungrouped count string fails the check, so the list cannot go stale.
|
||||
*/
|
||||
export const NOT_PLURAL = [
|
||||
{ key: 'assistant.place.addToShort', because: 'the number of the day a found place would go on ("+ Day 3")' },
|
||||
{ key: 'assistant.card.tour.days', because: 'the numbers of the days a tour lies on ("Days 2, 4")' },
|
||||
{ key: 'collab.polls.optionPlaceholder', because: 'the position of a poll option ("Option 3")' },
|
||||
{ key: 'collections.importOnDay', because: 'the number of the day a place is planned on' },
|
||||
|
||||
@@ -13,6 +13,7 @@ export * from './tour-route.card';
|
||||
*/
|
||||
export const TOUR_CARD_SCHEMAS = [tourRouteCardSchema, tourListCardSchema] as const;
|
||||
/** addTour, updateTour and importTour sit in the core list already. */
|
||||
export const TOUR_VERB_KEYS = [] as const;
|
||||
/** A station of a city walk checked off on its day: visited, skipped, or the mark taken back. */
|
||||
export const TOUR_VERB_KEYS = ['markVisited', 'markSkipped', 'markPlanned'] as const;
|
||||
/** 'tour' is a core entity already. */
|
||||
export const TOUR_APPLIED_ENTITIES = [] as const;
|
||||
|
||||
@@ -1,17 +1,39 @@
|
||||
import { idSchema } from '../common/primitives.schema';
|
||||
import { BOOK_DESIGN_ICONS } from './book-icons';
|
||||
import {
|
||||
BOOK_BINDING_HINT,
|
||||
bookBadgeStyleSchema,
|
||||
bookBadgeVariantSchema,
|
||||
bookCountriesLayoutSchema,
|
||||
bookFontIdSchema,
|
||||
bookFrameStyleSchema,
|
||||
bookIconNameSchema,
|
||||
bookListLayoutSchema,
|
||||
bookMapClipSchema,
|
||||
bookMapSourceSchema,
|
||||
bookMapStyleSchema,
|
||||
bookMetricSchema,
|
||||
bookPhotoFilterSchema,
|
||||
bookPhotoFitSchema,
|
||||
bookPhotoMaskSchema,
|
||||
bookPinStyleSchema,
|
||||
bookRouteArcSchema,
|
||||
bookRouteDashSchema,
|
||||
bookRouteStyleSchema,
|
||||
bookShapeGradientSchema,
|
||||
bookShapeIdSchema,
|
||||
bookStatsLayoutSchema,
|
||||
bookStrokeStyleSchema,
|
||||
bookTextAlignSchema,
|
||||
bookTypesetFontSchema,
|
||||
} from './book-op-enums';
|
||||
import { bookElementIdSchema, bookGridIdSchema, bookSpreadIdSchema } from './book-op-ids';
|
||||
import {
|
||||
BOOK_BADGES,
|
||||
BOOK_METRICS,
|
||||
BOOK_SHAPES,
|
||||
MAX_BOOK_COUNTRIES,
|
||||
bookBadgeElementSchema,
|
||||
bookCountriesElementSchema,
|
||||
bookIconElementSchema,
|
||||
bookListElementSchema,
|
||||
bookMapElementSchema,
|
||||
bookPhotoElementSchema,
|
||||
bookShapeElementSchema,
|
||||
bookStatsElementSchema,
|
||||
bookTextElementSchema,
|
||||
@@ -28,7 +50,9 @@ import { z } from 'zod';
|
||||
*
|
||||
* Same rules as the other operations: strict objects, the fields taken from the
|
||||
* document's own shapes with their defaults removed (an omitted field leaves
|
||||
* the element as it is), every string, array and number bounded.
|
||||
* the element as it is), every string, array and number bounded. The enums
|
||||
* carry a line each on what their values mean (book-op-enums.ts), since the
|
||||
* tool schema is all a model reads of them.
|
||||
*/
|
||||
|
||||
/** A position in millimetres, inside the bounds the document takes. */
|
||||
@@ -40,7 +64,6 @@ const ids30 = z.array(bookElementIdSchema).min(1).max(30);
|
||||
|
||||
export const bookFrameInSchema = z.strictObject({ x: mmIn, y: mmIn, w: sizeIn, h: sizeIn });
|
||||
|
||||
const photo = bookPhotoElementSchema.shape;
|
||||
const text = bookTextElementSchema.shape;
|
||||
const shape = bookShapeElementSchema.shape;
|
||||
const icon = bookIconElementSchema.shape;
|
||||
@@ -55,7 +78,7 @@ const COMMON = { opacity: unit01.optional() };
|
||||
|
||||
/** What the travel kinds share with text: they are typeset. */
|
||||
const TYPESET = {
|
||||
font: map.font.unwrap().optional(),
|
||||
font: bookTypesetFontSchema.optional(),
|
||||
color: map.color.unwrap().optional(),
|
||||
accent: map.accent.unwrap().optional(),
|
||||
textScale: map.textScale.unwrap().optional(),
|
||||
@@ -64,21 +87,21 @@ const TYPESET = {
|
||||
|
||||
const PHOTO_PROPS = {
|
||||
...COMMON,
|
||||
fit: photo.fit.unwrap().optional(),
|
||||
fit: bookPhotoFitSchema.optional(),
|
||||
focalX: unit01.optional(),
|
||||
focalY: unit01.optional(),
|
||||
mask: photo.mask.unwrap().optional(),
|
||||
frameStyle: photo.frameStyle.unwrap().optional(),
|
||||
filter: photo.filter.unwrap().optional(),
|
||||
mask: bookPhotoMaskSchema.optional(),
|
||||
frameStyle: bookFrameStyleSchema.optional(),
|
||||
filter: bookPhotoFilterSchema.optional(),
|
||||
radius: z.number().finite().min(0).max(500).optional(),
|
||||
};
|
||||
/** How a text is set, each field left as it is when not named: the style op's and the page edit's text op's. */
|
||||
export const TEXT_STYLE_FIELDS = {
|
||||
font: text.font.unwrap().optional(),
|
||||
font: bookFontIdSchema.optional(),
|
||||
size: text.size.unwrap().optional(),
|
||||
weight: text.weight.unwrap().optional(),
|
||||
italic: text.italic.unwrap().optional(),
|
||||
align: text.align.unwrap().optional(),
|
||||
align: bookTextAlignSchema.optional(),
|
||||
leading: text.leading.unwrap().optional(),
|
||||
tracking: text.tracking.unwrap().optional(),
|
||||
color: text.color.unwrap().optional(),
|
||||
@@ -87,10 +110,10 @@ const TEXT_PROPS = { ...COMMON, ...TEXT_STYLE_FIELDS };
|
||||
const SHAPE_PROPS = {
|
||||
...COMMON,
|
||||
fill: shape.fill.unwrap().optional(),
|
||||
gradient: shape.gradient.unwrap().optional(),
|
||||
gradient: bookShapeGradientSchema.optional(),
|
||||
stroke: shape.stroke.unwrap().optional(),
|
||||
strokeWidth: z.number().finite().min(0).max(20).optional(),
|
||||
strokeStyle: shape.strokeStyle.unwrap().optional(),
|
||||
strokeStyle: bookStrokeStyleSchema.optional(),
|
||||
radius: z.number().finite().min(0).max(500).optional(),
|
||||
};
|
||||
const ICON_PROPS = {
|
||||
@@ -101,39 +124,39 @@ const ICON_PROPS = {
|
||||
const MAP_PROPS = {
|
||||
...COMMON,
|
||||
...TYPESET,
|
||||
style: map.style.unwrap().optional(),
|
||||
style: bookMapStyleSchema.optional(),
|
||||
showLand: map.showLand.unwrap().optional(),
|
||||
showRoute: map.showRoute.unwrap().optional(),
|
||||
showPins: map.showPins.unwrap().optional(),
|
||||
showLabels: map.showLabels.unwrap().optional(),
|
||||
routeStyle: map.routeStyle.unwrap().optional(),
|
||||
routeArc: map.routeArc.unwrap().optional(),
|
||||
routeDash: map.routeDash.unwrap().optional(),
|
||||
pinStyle: map.pinStyle.unwrap().optional(),
|
||||
clip: map.clip.unwrap().optional(),
|
||||
routeStyle: bookRouteStyleSchema.optional(),
|
||||
routeArc: bookRouteArcSchema.optional(),
|
||||
routeDash: bookRouteDashSchema.optional(),
|
||||
pinStyle: bookPinStyleSchema.optional(),
|
||||
clip: bookMapClipSchema.optional(),
|
||||
fitPadding: map.fitPadding.unwrap().optional(),
|
||||
fitToCountries: map.fitToCountries.unwrap().optional(),
|
||||
};
|
||||
const STATS_PROPS = {
|
||||
...COMMON,
|
||||
...TYPESET,
|
||||
layout: stats.layout.unwrap().optional(),
|
||||
layout: bookStatsLayoutSchema.optional(),
|
||||
showIcons: stats.showIcons.unwrap().optional(),
|
||||
units: stats.units.unwrap().optional(),
|
||||
units: stats.units.unwrap().describe('Kilometres (metric) or miles (imperial).').optional(),
|
||||
};
|
||||
const COUNTRIES_PROPS = {
|
||||
...COMMON,
|
||||
...TYPESET,
|
||||
layout: countries.layout.unwrap().optional(),
|
||||
layout: bookCountriesLayoutSchema.optional(),
|
||||
showOutline: countries.showOutline.unwrap().optional(),
|
||||
showFlag: countries.showFlag.unwrap().optional(),
|
||||
showName: countries.showName.unwrap().optional(),
|
||||
align: countries.align.unwrap().optional(),
|
||||
align: countries.align.unwrap().describe('How the names sit in the frame.').optional(),
|
||||
};
|
||||
const BADGE_PROPS = {
|
||||
...COMMON,
|
||||
...TYPESET,
|
||||
style: badge.style.unwrap().optional(),
|
||||
style: bookBadgeStyleSchema.optional(),
|
||||
showIcon: badge.showIcon.unwrap().optional(),
|
||||
showLabel: badge.showLabel.unwrap().optional(),
|
||||
autoColor: badge.autoColor.unwrap().optional(),
|
||||
@@ -143,13 +166,12 @@ const BADGE_PROPS = {
|
||||
const LIST_PROPS = {
|
||||
...COMMON,
|
||||
...TYPESET,
|
||||
layout: list.layout.unwrap().optional(),
|
||||
layout: bookListLayoutSchema.optional(),
|
||||
showMarks: list.showMarks.unwrap().optional(),
|
||||
proLabel: z.string().max(80).optional(),
|
||||
conLabel: z.string().max(80).optional(),
|
||||
};
|
||||
const metric = z.enum(BOOK_METRICS);
|
||||
const METRICS = z.array(metric).min(1).max(7);
|
||||
const METRICS = z.array(bookMetricSchema).min(1).max(7);
|
||||
|
||||
/**
|
||||
* The look of an element, per kind, for `style`. Values the journey owns (a
|
||||
@@ -159,7 +181,7 @@ const METRICS = z.array(metric).min(1).max(7);
|
||||
export const bookElementPropsSchema = z.discriminatedUnion('kind', [
|
||||
z.strictObject({ kind: z.literal('photo'), ...PHOTO_PROPS }),
|
||||
z.strictObject({ kind: z.literal('text'), ...TEXT_PROPS }),
|
||||
z.strictObject({ kind: z.literal('shape'), shape: z.enum(BOOK_SHAPES).optional(), ...SHAPE_PROPS }),
|
||||
z.strictObject({ kind: z.literal('shape'), shape: bookShapeIdSchema.optional(), ...SHAPE_PROPS }),
|
||||
z.strictObject({ kind: z.literal('icon'), ...ICON_PROPS }),
|
||||
z.strictObject({ kind: z.literal('map'), ...MAP_PROPS }),
|
||||
z.strictObject({ kind: z.literal('stats'), metrics: METRICS.optional(), ...STATS_PROPS }),
|
||||
@@ -189,9 +211,15 @@ export function bindingNamesItsSource(
|
||||
const bindingIn = text.binding
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.refine(bindingNamesItsSource, { message: 'an entry binding needs its entryId, a photo binding its photoId' });
|
||||
.refine(bindingNamesItsSource, { message: 'an entry binding needs its entryId, a photo binding its photoId' })
|
||||
.describe(BOOK_BINDING_HINT);
|
||||
const iso2 = z.string().regex(/^[A-Za-z]{2}$/);
|
||||
const listItem = z.strictObject({ text: z.string().max(400), tone: z.enum(['pro', 'con', 'plain']) });
|
||||
const listItem = z.strictObject({
|
||||
text: z.string().max(400),
|
||||
tone: z
|
||||
.enum(['pro', 'con', 'plain'])
|
||||
.describe('pro or con sets the line in that column with its mark; plain has none.'),
|
||||
});
|
||||
|
||||
/**
|
||||
* Where a map is of: the whole journey or one trip, the two scopes a stored map
|
||||
@@ -210,18 +238,21 @@ export const bookNewElementSchema = z.discriminatedUnion('kind', [
|
||||
z
|
||||
.strictObject({
|
||||
kind: z.literal('text'),
|
||||
preset: z.enum(BOOK_TEXT_PRESETS).optional(),
|
||||
preset: z
|
||||
.enum(BOOK_TEXT_PRESETS)
|
||||
.describe('A Studio text preset: heading, subheading, body, caption, or quote (the large quotation mark).')
|
||||
.optional(),
|
||||
text: z.string().max(2000).optional(),
|
||||
binding: bindingIn.optional(),
|
||||
...TEXT_PROPS,
|
||||
})
|
||||
.refine((v) => v.text !== undefined || v.binding !== undefined, { message: 'give the words or a binding' }),
|
||||
z.strictObject({ kind: z.literal('shape'), shape: z.enum(BOOK_SHAPES), ...SHAPE_PROPS }),
|
||||
z.strictObject({ kind: z.literal('icon'), name: z.enum(BOOK_DESIGN_ICONS), ...ICON_PROPS }),
|
||||
z.strictObject({ kind: z.literal('shape'), shape: bookShapeIdSchema, ...SHAPE_PROPS }),
|
||||
z.strictObject({ kind: z.literal('icon'), name: bookIconNameSchema, ...ICON_PROPS }),
|
||||
z.strictObject({
|
||||
kind: z.literal('map'),
|
||||
scope: mapScope,
|
||||
source: z.enum(['vector', 'relief', 'satellite']).optional(),
|
||||
source: bookMapSourceSchema.optional(),
|
||||
...MAP_PROPS,
|
||||
}),
|
||||
z.strictObject({ kind: z.literal('stats'), metrics: METRICS, ...STATS_PROPS }),
|
||||
@@ -232,7 +263,7 @@ export const bookNewElementSchema = z.discriminatedUnion('kind', [
|
||||
}),
|
||||
z.strictObject({
|
||||
kind: z.literal('badge'),
|
||||
variant: z.enum(BOOK_BADGES),
|
||||
variant: bookBadgeVariantSchema,
|
||||
entryId: idSchema.optional(),
|
||||
code: z.string().max(24).optional(),
|
||||
text: z.string().max(200).optional(),
|
||||
@@ -274,20 +305,27 @@ export const BOOK_ELEMENT_OP_SCHEMAS = [
|
||||
z.strictObject({
|
||||
op: z.literal('arrange'),
|
||||
elementIds: ids30,
|
||||
to: z.enum(['front', 'forward', 'backward', 'back']),
|
||||
to: z
|
||||
.enum(['front', 'forward', 'backward', 'back'])
|
||||
.describe('front and back go to either end of the paint order; forward and backward one step.'),
|
||||
}),
|
||||
/** Line elements up on an edge or a centre line of the selection, their page, or its safe area. */
|
||||
z.strictObject({
|
||||
op: z.literal('align'),
|
||||
elementIds: ids30,
|
||||
edge: z.enum(['left', 'center', 'right', 'top', 'middle', 'bottom']),
|
||||
to: z.enum(['selection', 'page', 'safe']).default('selection'),
|
||||
edge: z
|
||||
.enum(['left', 'center', 'right', 'top', 'middle', 'bottom'])
|
||||
.describe('The edge or centre line the elements line up on.'),
|
||||
to: z
|
||||
.enum(['selection', 'page', 'safe'])
|
||||
.describe('Line up within the selection, the page, or its safe area.')
|
||||
.default('selection'),
|
||||
}),
|
||||
/** Space three or more elements evenly, or by a fixed gap in millimetres. */
|
||||
z.strictObject({
|
||||
op: z.literal('distribute'),
|
||||
elementIds: z.array(bookElementIdSchema).min(3).max(30),
|
||||
axis: z.enum(['horizontal', 'vertical']),
|
||||
axis: z.enum(['horizontal', 'vertical']).describe('Space them out across the page or down it.'),
|
||||
gap: z.number().finite().min(0).max(200).optional(),
|
||||
}),
|
||||
/** Lock or unlock elements: the one operation a locked element accepts. */
|
||||
@@ -300,7 +338,11 @@ export const BOOK_ELEMENT_OP_SCHEMAS = [
|
||||
dy: z.number().finite().min(-500).max(500).optional(),
|
||||
}),
|
||||
/** The Studio's fill: a photo to the bleed of its page or the spread, unturned, cover, at the back. */
|
||||
z.strictObject({ op: z.literal('fill'), elementId: bookElementIdSchema, scope: z.enum(['page', 'spread']) }),
|
||||
z.strictObject({
|
||||
op: z.literal('fill'),
|
||||
elementId: bookElementIdSchema,
|
||||
scope: z.enum(['page', 'spread']).describe('Fill its own page to the bleed, or both pages of the spread.'),
|
||||
}),
|
||||
/** Copy elements of another page onto this one, with new ids; photos are checked against the gallery. */
|
||||
z.strictObject({ op: z.literal('copy_from'), spreadId: bookSpreadIdSchema, elementIds: ids30 }),
|
||||
/** Bring travel figures up to date with the journey: the named elements, or every one on the page. */
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user