mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 13:10:29 +00:00
feat(assistant): hike, walk and route cards with their lines on the map, and "Plan this"
This commit is contained in:
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* FE-AI-PEEK-001 to FE-AI-PEEK-007
|
||||
*
|
||||
* The phone's peek at a route over the map: found where the chat shows the
|
||||
* route (an answer's card, one of its ways, a held change), its name,
|
||||
* figures and profile with the readout under it, the ways as marks a tap
|
||||
* chooses between, the map's spot read in the readout, and a close button;
|
||||
* loaded on first use. Closing it, or moving it to another way, takes the
|
||||
* light a tap on the map put on the line along.
|
||||
*/
|
||||
import type { AssistantMessage, AssistantMessagePart, TourRouteCard } from '@trek/shared';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { GENTLE, HIKE } from '../../../../tests/helpers/assistantTour';
|
||||
import { buildTrip, buildUser } from '../../../../tests/helpers/factories';
|
||||
import { act, fireEvent, render, screen } from '../../../../tests/helpers/render';
|
||||
import { chatOf, useAssistantStore } from '../../../store/assistantStore';
|
||||
import { useAuthStore } from '../../../store/authStore';
|
||||
import { useTripStore } from '../../../store/tripStore';
|
||||
import RoutePeek from './RoutePeek';
|
||||
import RoutePeekLazy from './RoutePeekLazy';
|
||||
import { peekRoute } from './routePeekModel';
|
||||
|
||||
const TRIP = 4;
|
||||
const ASSISTANT = useAssistantStore.getState();
|
||||
const TRIPS = useTripStore.getState();
|
||||
const AUTH = useAuthStore.getState();
|
||||
|
||||
function read(toolCallId: string, card: TourRouteCard): AssistantMessagePart[] {
|
||||
return [
|
||||
{ type: 'tool-call', toolCallId, toolName: 'propose_hike', args: {}, result: {} },
|
||||
{ type: 'data-trek-card', data: { toolCallId, card } },
|
||||
];
|
||||
}
|
||||
|
||||
function held(toolCallId: string, card: TourRouteCard): AssistantMessagePart[] {
|
||||
return [
|
||||
{ type: 'tool-call', toolCallId, toolName: 'create_hike', args: {}, approval: { id: toolCallId } },
|
||||
{
|
||||
type: 'data-trek-change',
|
||||
data: {
|
||||
toolCallId,
|
||||
verbKey: 'addTour',
|
||||
subject: 'Hochfelln',
|
||||
rows: [],
|
||||
dayId: null,
|
||||
placeIds: [],
|
||||
undoable: true,
|
||||
card: { ...card, source: 'pending' },
|
||||
},
|
||||
} as AssistantMessagePart,
|
||||
];
|
||||
}
|
||||
|
||||
function message(parts: AssistantMessagePart[]): AssistantMessage {
|
||||
return { id: 'msg-1', role: 'assistant', parts, status: 'complete', createdAt: '2026-10-21T08:00:00.000Z' };
|
||||
}
|
||||
|
||||
const WAYS = message([...read('call_1', { ...HIKE, label: 'Short and steep' }), ...read('call_2', GENTLE)]);
|
||||
|
||||
function setChat(messages: AssistantMessage[], peek: string | null) {
|
||||
useAssistantStore.setState((s) => ({
|
||||
byTrip: { [TRIP]: { ...chatOf(s, TRIP), threadId: 7, messages } },
|
||||
routePeek: peek === null ? null : { tripId: TRIP, toolCallId: peek },
|
||||
}));
|
||||
}
|
||||
|
||||
function renderPeek() {
|
||||
return render(<RoutePeek tripId={TRIP} onOpen={vi.fn()} onFocusDay={vi.fn()} onRevealMap={vi.fn()} />);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useAuthStore.setState({ user: buildUser({ id: 1 }) });
|
||||
useTripStore.setState({ trip: buildTrip({ id: TRIP, user_id: 1 }) });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
useAssistantStore.setState(ASSISTANT, true);
|
||||
useTripStore.setState(TRIPS, true);
|
||||
useAuthStore.setState(AUTH, true);
|
||||
});
|
||||
|
||||
describe('peekRoute', () => {
|
||||
it('FE-AI-PEEK-001: finds a route among the ways of an answer, on its own, or as a held change, and nothing else', () => {
|
||||
const ways = peekRoute([WAYS], 'call_2');
|
||||
expect(ways?.entry.toolCallId).toBe('call_2');
|
||||
expect(ways?.ways.map((way) => way.toolCallId)).toEqual(['call_1', 'call_2']);
|
||||
expect(ways?.blockKey).toBe('tour:call_1');
|
||||
|
||||
const alone = peekRoute([message(read('call_9', HIKE))], 'call_9');
|
||||
expect(alone?.ways).toEqual([]);
|
||||
|
||||
const change = peekRoute([message(held('call_5', HIKE))], 'call_5');
|
||||
expect(change?.entry.card.source).toBe('pending');
|
||||
expect(change?.ways).toEqual([]);
|
||||
|
||||
expect(peekRoute([WAYS], 'call_7')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('RoutePeek', () => {
|
||||
it('FE-AI-PEEK-002: shows nothing while closed, for another trip, or once the route is gone', () => {
|
||||
setChat([WAYS], null);
|
||||
const { container } = renderPeek();
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
|
||||
act(() => useAssistantStore.setState({ routePeek: { tripId: 9, toolCallId: 'call_1' } }));
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
|
||||
act(() => useAssistantStore.setState({ routePeek: { tripId: TRIP, toolCallId: 'call_7' } }));
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('FE-AI-PEEK-003: names the route with its grade and figures over its profile, and closes', () => {
|
||||
setChat([message(read('call_9', HIKE))], 'call_9');
|
||||
renderPeek();
|
||||
const peek = screen.getByTestId('route-peek');
|
||||
expect(peek).toHaveAccessibleName('Hochfelln from Bergen');
|
||||
expect(screen.getByTestId('tour-grade')).toBeInTheDocument();
|
||||
expect(peek.querySelector('[data-figure="distance"]')).not.toBeNull();
|
||||
expect(screen.getByRole('group', { name: 'Elevation profile of Hochfelln from Bergen' })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('group', { name: /way/ })).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close the route' }));
|
||||
expect(useAssistantStore.getState().routePeek).toBeNull();
|
||||
expect(screen.queryByTestId('route-peek')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-AI-PEEK-004: the ways are marks with 44 px targets, and a tap chooses one for the answer and shows it', () => {
|
||||
setChat([WAYS], 'call_1');
|
||||
renderPeek();
|
||||
const group = screen.getByRole('group', { name: '2 ways' });
|
||||
const marks = group.querySelectorAll('button');
|
||||
expect(marks).toHaveLength(2);
|
||||
expect(marks[0]).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(marks[0]).toHaveClass('h-11', 'w-11');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Long and gentle' }));
|
||||
expect(chatOf(useAssistantStore.getState(), TRIP).picks).toEqual({ 'tour:call_1': 'call_2' });
|
||||
expect(useAssistantStore.getState().routePeek).toEqual({ tripId: TRIP, toolCallId: 'call_2' });
|
||||
expect(screen.getByRole('button', { name: 'Long and gentle' })).toHaveAttribute('aria-pressed', 'true');
|
||||
});
|
||||
|
||||
it('FE-AI-PEEK-005: a spot picked on the map is read in the row under the profile, and the hint shows otherwise', () => {
|
||||
setChat([message(read('call_9', HIKE))], 'call_9');
|
||||
renderPeek();
|
||||
expect(screen.getByText('Slide along the profile to read it')).toBeInTheDocument();
|
||||
|
||||
const focus = { distanceMeters: 4100, elevationMeters: 1400, lat: 47.795, lng: 12.625, sampleIndex: 5 };
|
||||
act(() => useAssistantStore.getState().setRouteFocus({ tripId: TRIP, ref: 'call_9', focus, source: 'map' }));
|
||||
expect(screen.getByTestId('tour-profile-readout')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-AI-PEEK-006: the peek loads with its route the first time a route is shown over the map', async () => {
|
||||
setChat([message(read('call_9', HIKE))], 'call_9');
|
||||
render(<RoutePeekLazy tripId={TRIP} onOpen={vi.fn()} onFocusDay={vi.fn()} onRevealMap={vi.fn()} />);
|
||||
expect(await screen.findByTestId('route-peek')).toHaveAccessibleName('Hochfelln from Bergen');
|
||||
});
|
||||
|
||||
it('FE-AI-PEEK-007: closing the peek puts out the light a map tap put on its line, not a light from the chat', () => {
|
||||
setChat([WAYS], 'call_1');
|
||||
act(() => useAssistantStore.getState().setMapHover(TRIP, 'call_1', 'map'));
|
||||
renderPeek();
|
||||
// Another way in the peek moves the light with it.
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Long and gentle' }));
|
||||
expect(useAssistantStore.getState().mapLink).toEqual({ tripId: TRIP, hoveredId: 'call_2', source: 'map' });
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close the route' }));
|
||||
expect(useAssistantStore.getState().mapLink).toEqual({ tripId: TRIP, hoveredId: null, source: 'map' });
|
||||
|
||||
act(() => {
|
||||
useAssistantStore.getState().setMapHover(TRIP, 'call_1', 'card');
|
||||
useAssistantStore.getState().setRoutePeek({ tripId: TRIP, toolCallId: 'call_1' });
|
||||
});
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close the route' }));
|
||||
expect(useAssistantStore.getState().mapLink).toEqual({ tripId: TRIP, hoveredId: 'call_1', source: 'card' });
|
||||
expect(useAssistantStore.getState().routePeek).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import { X } from 'lucide-react';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { chatOf, useAssistantStore } from '../../../store/assistantStore';
|
||||
import { variantPaintCss } from '../../Tours/planner/legVariantPaint';
|
||||
import { VariantMark } from '../../Tours/planner/mapCardParts';
|
||||
import { type AssistantView, AssistantViewContext, useAssistantView } from '../assistantViewContext';
|
||||
import { TourGrade, TourRouteFigures } from '../cards/tour/TourRouteHead';
|
||||
import { profileSamples, WAY_KEYS } from '../cards/tour/tourRouteModel';
|
||||
import TourRouteProfile from '../cards/tour/TourRouteProfile';
|
||||
import { routeName } from '../cards/tour/tourRouteWords';
|
||||
import { useTourRouteCard } from '../cards/tour/useTourRouteCard';
|
||||
import { moveRoutePeek } from './routePeekControl';
|
||||
import { type PeekRoute, peekRoute } from './routePeekModel';
|
||||
|
||||
/** The peek's body, for the route found: its ways, its name and figures, its profile and the way to close it. */
|
||||
function PeekBody({ route }: { route: PeekRoute }) {
|
||||
const { t } = useTranslation();
|
||||
const { tripId } = useAssistantView();
|
||||
const { entry, ways, blockKey } = route;
|
||||
const { card, toolCallId } = entry;
|
||||
const pick = useAssistantStore((s) => s.pick);
|
||||
const shown = useTourRouteCard(toolCallId, card, ways.length > 0 ? ways.map((way) => way.card) : undefined);
|
||||
const samples = useMemo(() => profileSamples(card), [card]);
|
||||
const index = ways.findIndex((way) => way.toolCallId === toolCallId);
|
||||
const color = variantPaintCss(index >= 0 ? (WAY_KEYS[index] ?? 'a') : 'current');
|
||||
const name = routeName(card, t);
|
||||
const waysLabel = t('assistant.card.tour.ways', { count: ways.length });
|
||||
|
||||
return (
|
||||
<section
|
||||
aria-label={name}
|
||||
data-testid="route-peek"
|
||||
className="trek-assistant-enter absolute inset-x-3 bottom-[calc(env(safe-area-inset-bottom,0px)+142px)] z-[42] rounded-2xl border border-edge-faint bg-surface-elevated px-3 pb-3 pt-2 shadow-elevated backdrop-blur-2xl"
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="min-w-0 flex-1 pt-1.5">
|
||||
<h3 className="m-0 line-clamp-2 text-body font-semibold leading-tight text-content">
|
||||
<bdi>{name}</bdi>
|
||||
</h3>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-1">
|
||||
<TourGrade card={card} />
|
||||
<TourRouteFigures card={card} />
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => moveRoutePeek(tripId, null)}
|
||||
aria-label={t('assistant.card.tour.peekClose')}
|
||||
className="-me-1.5 grid h-11 w-11 flex-none place-items-center rounded-full text-content-secondary hover:bg-surface-hover"
|
||||
>
|
||||
<X size={18} strokeWidth={2.2} aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
{ways.length > 0 && (
|
||||
<div role="group" aria-label={waysLabel} className="mt-1 flex items-center gap-1">
|
||||
{ways.map((way, position) => {
|
||||
const key = WAY_KEYS[position] ?? 'a';
|
||||
const letter = key.toUpperCase();
|
||||
const chosen = way.toolCallId === toolCallId;
|
||||
return (
|
||||
<button
|
||||
key={way.toolCallId}
|
||||
type="button"
|
||||
aria-pressed={chosen}
|
||||
aria-label={way.card.label ?? t('tours.variants.option', { letter })}
|
||||
onClick={() => {
|
||||
pick(tripId, blockKey, way.toolCallId);
|
||||
moveRoutePeek(tripId, way.toolCallId);
|
||||
}}
|
||||
className="grid h-11 w-11 place-items-center rounded-full hover:bg-surface-hover"
|
||||
>
|
||||
<VariantMark variant={{ key, current: false }} chosen={chosen} />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<TourRouteProfile
|
||||
toolCallId={toolCallId}
|
||||
card={card}
|
||||
samples={samples}
|
||||
color={color}
|
||||
focus={shown.focus}
|
||||
onFocus={shown.setFocus}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Finds the route the peek is open on in this trip's chat; nothing while it is closed or the route is gone. */
|
||||
function PeekFinder() {
|
||||
const { tripId } = useAssistantView();
|
||||
const toolCallId = useAssistantStore((s) => (s.routePeek?.tripId === tripId ? s.routePeek.toolCallId : null));
|
||||
const messages = useAssistantStore((s) => chatOf(s, tripId).messages);
|
||||
const route = useMemo(() => (toolCallId ? peekRoute(messages, toolCallId) : null), [messages, toolCallId]);
|
||||
return route ? <PeekBody route={route} /> : null;
|
||||
}
|
||||
|
||||
interface RoutePeekProps {
|
||||
tripId: number;
|
||||
onOpen: NonNullable<AssistantView['onOpen']>;
|
||||
onFocusDay: NonNullable<AssistantView['onFocusDay']>;
|
||||
onRevealMap: NonNullable<AssistantView['onRevealMap']>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone's peek at a route over the map, while the chat stands aside:
|
||||
* opened by "On map" on a route card or a tap on a route line. It shows the
|
||||
* route as its card does in brief (name, grade, figures) and its height
|
||||
* profile with the readout under it, a finger scrubbing along it while the
|
||||
* map's pin follows; the ways of an answer as their marks, 44 px targets, a
|
||||
* tap choosing one as the card's choice does; and a close button. The map
|
||||
* stays usable around it, and the chat's pill below brings the chat back.
|
||||
*/
|
||||
export default function RoutePeek({ tripId, onOpen, onFocusDay, onRevealMap }: RoutePeekProps) {
|
||||
const view = useMemo<AssistantView>(
|
||||
() => ({ tripId, variant: 'fullscreen', density: 'compact', onOpen, onFocusDay, onRevealMap }),
|
||||
[tripId, onOpen, onFocusDay, onRevealMap]
|
||||
);
|
||||
return (
|
||||
<AssistantViewContext.Provider value={view}>
|
||||
<PeekFinder />
|
||||
</AssistantViewContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { type ComponentProps, Suspense } from 'react';
|
||||
|
||||
import { lazyWithRetry } from '../../../utils/lazyWithRetry';
|
||||
import CardBoundary from '../cards/parts/CardBoundary';
|
||||
|
||||
/**
|
||||
* The phone's route peek, loaded the first time a route is shown over the
|
||||
* map, so the trip screen does not carry the route cards' code before the
|
||||
* chat ever draws one. A peek that fails to load or to draw shows nothing:
|
||||
* the map and the chat's pill stay as they are.
|
||||
*/
|
||||
const RoutePeek = lazyWithRetry(() => import('./RoutePeek'));
|
||||
|
||||
export default function RoutePeekLazy(props: ComponentProps<typeof RoutePeek>) {
|
||||
return (
|
||||
<CardBoundary>
|
||||
<Suspense fallback={null}>
|
||||
<RoutePeek {...props} />
|
||||
</Suspense>
|
||||
</CardBoundary>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { useAssistantStore } from '../../../store/assistantStore';
|
||||
|
||||
/**
|
||||
* Opens the phone's route peek on another route, or closes it, and moves the
|
||||
* light a tap on the map put on a route with it. On the phone no pointer
|
||||
* ever leaves a line, so nothing else would put that light out: the line
|
||||
* would stay lit on the map and its card in the chat after the peek is gone.
|
||||
* A light the chat itself put on (a card under the finger) is left alone.
|
||||
* Kept apart from the peek, so the trip screen can close it without loading
|
||||
* the peek's code.
|
||||
*/
|
||||
export function moveRoutePeek(tripId: number, toolCallId: string | null): void {
|
||||
const { mapLink, setMapHover, setRoutePeek } = useAssistantStore.getState();
|
||||
if (mapLink?.tripId === tripId && mapLink.source === 'map' && mapLink.hoveredId !== null) {
|
||||
setMapHover(tripId, toolCallId, 'map');
|
||||
}
|
||||
setRoutePeek(toolCallId === null ? null : { tripId, toolCallId });
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import type { AssistantMessage } from '@trek/shared';
|
||||
|
||||
import { messageBlocks } from '../assistantParts';
|
||||
import { routeEntries, type RouteEntry, wayGroups } from '../cards/tour/tourRouteModel';
|
||||
|
||||
/**
|
||||
* The route the phone's peek shows, found where the chat shows it: the card,
|
||||
* and when it is one of the ways of an answer, all of them with the key the
|
||||
* chat keeps the chosen way under (the ways card's own, `tour:<first call>`).
|
||||
*/
|
||||
export interface PeekRoute {
|
||||
entry: RouteEntry;
|
||||
/** The ways it is one of, in the answer's order; empty for a route on its own. */
|
||||
ways: RouteEntry[];
|
||||
blockKey: string;
|
||||
}
|
||||
|
||||
/** The route card of a call, laid out as the chat lays it out; null when the chat holds no route under it. */
|
||||
export function peekRoute(messages: readonly AssistantMessage[], toolCallId: string): PeekRoute | null {
|
||||
for (const message of messages) {
|
||||
for (const block of messageBlocks(message, false)) {
|
||||
if (block.kind === 'cards') {
|
||||
for (const group of wayGroups(routeEntries(block.entries))) {
|
||||
const entry = group.find((way) => way.toolCallId === toolCallId);
|
||||
if (!entry) continue;
|
||||
const ways = group.length >= 2 ? group : [];
|
||||
return { entry, ways, blockKey: `tour:${group[0]?.toolCallId ?? ''}` };
|
||||
}
|
||||
} else if (block.kind === 'change') {
|
||||
const card = block.items.find((item) => item.toolCallId === toolCallId)?.card;
|
||||
if (card?.kind === 'tourRoute') return { entry: { toolCallId, card }, ways: [], blockKey: '' };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
Reference in New Issue
Block a user