diff --git a/client/scripts/format-baseline.json b/client/scripts/format-baseline.json index d4157106d..0c989e623 100644 --- a/client/scripts/format-baseline.json +++ b/client/scripts/format-baseline.json @@ -400,8 +400,6 @@ "src/components/Journey/moodConfig.ts", "src/components/Journey/photoZoom.test.ts", "src/components/Journey/photoZoom.ts", - "src/components/Journey/stripMarkdown.test.ts", - "src/components/Journey/stripMarkdown.ts", "src/components/Journey/useConnectedPhotoProviders.test.tsx", "src/components/Journey/useConnectedPhotoProviders.ts", "src/components/Journey/useEntryPhotoOrder.test.ts", diff --git a/client/src/components/Assistant/cards/journey/JourneyChangeSlots.tsx b/client/src/components/Assistant/cards/journey/JourneyChangeSlots.tsx new file mode 100644 index 000000000..933cfa26c --- /dev/null +++ b/client/src/components/Assistant/cards/journey/JourneyChangeSlots.tsx @@ -0,0 +1,126 @@ +import type { AssistantChangeRow, JourneyEntriesCard } from '@trek/shared'; +import { AlignLeft, CalendarDays, Clock, MapPin, Tag, Type } from 'lucide-react'; + +import { useTranslation } from '../../../../i18n'; +import type { ChangeItem } from '../../assistantParts'; +import { FactChange } from '../parts/CardFacts'; +import { EntryMarks, EntryStory, EntryThumb } from './JourneyEntryParts'; +import { flagOf, stateOf } from './journeyTones'; +import { entryHoverProps, useEntryHover } from './useEntryHover'; + +/** + * What a change row of a journal entry adds to the row it already is (its + * verb and subject): the facts, words and states it changes, each old to new, + * the entry's photo at the end of the subject line when it has one already, + * and under the row the start of its text and how it reads. A deleted entry made from a trip place says it + * goes back to a suggestion. A change that failed, was discarded or ran out + * shows the row alone. + */ + +const GONE: ReadonlySet = new Set(['failed', 'discarded', 'expired']); + +/** The facts a journal change row names on its faint line, in this order: when, then where. */ +const FACT_ICONS = { day: CalendarDays, time: Clock, location: MapPin } as const; +/** The words an update rewrites, named only when they change: the entry's title and its text. */ +const WORD_ICONS = { name: Type, text: AlignLeft } as const; +type FactRow = AssistantChangeRow & { labelKey: keyof typeof FACT_ICONS }; +type WordRow = AssistantChangeRow & { labelKey: keyof typeof WORD_ICONS }; +const TO_SUGGESTION = 'mt-1 text-caption text-content-faint'; +const HOVER_BOX = 'flex flex-none'; + +/** A row's old value, for a row that had one. */ +function beforeOf(row: AssistantChangeRow): string | null { + return row.op !== 'add' && row.before ? row.before : null; +} + +/** A row that holds something: a new value, or an old one it clears. */ +function holds(row: AssistantChangeRow): boolean { + return row.after !== '' || beforeOf(row) !== null; +} + +/** A state an update sets (who sees the entry, its mood, weather or kind, a flag), named in the user's words. */ +function StateChange({ row }: { row: AssistantChangeRow }) { + const { t } = useTranslation(); + const flag = flagOf(row.field, row.after); + if (flag) return ; + const was = stateOf(row.field, row.before); + const now = stateOf(row.field, row.after); + const Icon = (now ?? was)?.Icon ?? Tag; + const named = (tone: typeof now, value: string | null) => (tone ? t(tone.labelKey) : value); + return ( + + ); +} + +/** + * When and where the entry is, before and after on a change (the day, the + * time and the place), then the title and text an update rewrites and the + * states it sets. A value an update clears reads as removed. + */ +export function JourneyEntryFacts({ item }: { card: JourneyEntriesCard; item: ChangeItem }) { + const { t } = useTranslation(); + const rows = item.preview?.rows ?? []; + const removed = t('assistant.card.common.removed'); + const order = Object.keys(FACT_ICONS); + const facts = rows + .filter((row): row is FactRow => row.labelKey in FACT_ICONS && holds(row)) + .sort((a, b) => order.indexOf(a.labelKey) - order.indexOf(b.labelKey)); + // A new entry's text and a deleted one's show under the row already; only a rewrite names them here. + const words = rows.filter((row): row is WordRow => row.op === 'change' && row.labelKey in WORD_ICONS && holds(row)); + const states = rows.filter((row) => row.labelKey === 'field' && holds(row)); + return ( + <> + {facts.map((row) => ( + + ))} + {words.map((row) => ( + + ))} + {states.map((row) => )} + + ); +} + +/** The entry's photo beside the subject, for an entry that is written already; resting on it shows its place. */ +export function JourneyEntryAside({ card, item }: { card: JourneyEntriesCard; item: ChangeItem }) { + const hover = useEntryHover(card.journeyId, item.toolCallId); + const look = card.entries[0]; + if (!look || look.photoId === null || GONE.has(item.state)) return null; + return ( + + + + ); +} + +/** The start of the entry's text and its marks, under the row; resting on them shows its place on the map. */ +export function JourneyEntryBody({ card, item }: { card: JourneyEntriesCard; item: ChangeItem }) { + const { t } = useTranslation(); + const hover = useEntryHover(card.journeyId, item.toolCallId); + const look = card.entries[0]; + if (!look || GONE.has(item.state)) return null; + return ( +
+ + + {card.change === 'willDelete' && look.fromTripPlace && ( +

{t('assistant.card.journey.toSuggestion')}

+ )} +
+ ); +} diff --git a/client/src/components/Assistant/cards/journey/JourneyEntriesBlock.tsx b/client/src/components/Assistant/cards/journey/JourneyEntriesBlock.tsx new file mode 100644 index 000000000..9d351bf7f --- /dev/null +++ b/client/src/components/Assistant/cards/journey/JourneyEntriesBlock.tsx @@ -0,0 +1,170 @@ +import type { AssistantMessage, JourneyEntryLook } from '@trek/shared'; +import { ArrowUpRight } 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 CardStrip from '../parts/CardStrip'; +import { type JournalEntries, coverEntryOf, mergeJournalCards, titleSourceOf } from './journeyCardModel'; +import { EntryMarks, EntryStory, EntryThumb, EntryWhen } from './JourneyEntryParts'; +import { type EntryHover, entryHoverProps, useEntryHover } from './useEntryHover'; +import { useJourneyOpen } from './useJourneyOpen'; + +/** + * The entries an answer read from one journal. One or two stand as rows + * under each other, with their photo, facts and the start of their text; + * three or more run as a strip of the journal's own tiles, the ones the read + * left out counted in a last tile. Either way the journal's name closes the + * card with the way into it, and every entry opens where it is written. + * Resting on an entry with a place, or tabbing to it, shows it on the plan's + * map. + */ + +const ROW = '-mx-1.5 flex gap-2.5 rounded-[12px] px-1.5 py-2 hover:bg-surface-hover'; +const ROW_DIVIDED = '-mx-1.5 flex gap-2.5 rounded-[12px] border-t border-edge-faint px-1.5 py-2 hover:bg-surface-hover'; +const TITLE = 'line-clamp-2 text-body font-semibold leading-tight text-content'; +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. */ +const MORE_TILE_BOX = 'flex h-[152px] w-[136px] flex-none items-center justify-center rounded-[18px]'; +const MORE_TILE_LOOK = + 'border border-dashed border-edge px-3 text-center text-caption text-content-muted hover:bg-surface-hover'; +const MORE_TILE = `${MORE_TILE_BOX} ${MORE_TILE_LOOK}`; +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 }) { + const { t } = useTranslation(); + const { variant } = useAssistantView(); + const title = journal.journalTitle ?? t('assistant.card.journey.label'); + const count = journal.entries.length + journal.more; + return ( +
+ + + {title} + {count > 2 && {t('assistant.card.journey.entries', { count })}} + + {open && ( + + )} +
+ ); +} + +/** One entry as a row: its photo, its title (the way to it), its facts and the start of its text. */ +function EntryRow({ + look, + divided, + open, + hover, +}: { + look: JourneyEntryLook; + divided: boolean; + open: Open; + hover: EntryHover; +}) { + const { t } = useTranslation(); + const { density, variant } = useAssistantView(); + const roomy = density === 'roomy'; + const title = {cardTitle(titleSourceOf(look), t)}; + return ( +
+ +
+ {open ? ( + + ) : ( + title + )} + + + +
+
+ ); +} + +/** One or two entries, under each other. */ +function JournalRows({ journal, fallbackRef }: { journal: JournalEntries; fallbackRef: string }) { + const { t } = useTranslation(); + const open = useJourneyOpen(journal.journeyId, journal.tripJournal); + const hover = useEntryHover(journal.journeyId, fallbackRef); + return ( + + {journal.entries.map((look, index) => ( + 0} open={open} hover={hover} /> + ))} + + + ); +} + +/** Three or more entries, as the journal's own tiles in a row, the rest counted at its end. */ +function JournalStrip({ journal, fallbackRef }: { journal: JournalEntries; fallbackRef: string }) { + const { t } = useTranslation(); + const open = useJourneyOpen(journal.journeyId, journal.tripJournal); + const hover = useEntryHover(journal.journeyId, fallbackRef); + const label = journal.journalTitle ?? t('assistant.card.journey.label'); + return ( +
+ + {journal.entries.map((look, index) => ( +
  • + open?.(look.entryId)} + tone="app" + /> +
  • + ))} + {journal.more > 0 && ( +
  • + +
  • + )} +
    + +
    + ); +} + +/** The answer cards of one journal, as rows or as a strip by how many entries they hold. */ +export default function JourneyEntriesBlock({ cards }: { cards: readonly CardEntry[]; message: AssistantMessage }) { + const journal = useMemo(() => mergeJournalCards(cards), [cards]); + if (!journal || journal.entries.length === 0) return null; + const fallbackRef = cards[0]?.toolCallId ?? 'card'; + return journal.entries.length <= 2 ? ( + + ) : ( + + ); +} diff --git a/client/src/components/Assistant/cards/journey/JourneyEntriesCard.test.tsx b/client/src/components/Assistant/cards/journey/JourneyEntriesCard.test.tsx new file mode 100644 index 000000000..e06013017 --- /dev/null +++ b/client/src/components/Assistant/cards/journey/JourneyEntriesCard.test.tsx @@ -0,0 +1,298 @@ +/** + * FE-AI-JOURNEY-001 to FE-AI-JOURNEY-010 + * + * The journal's cards in the chat: one or two entries as rows with their + * photo, facts and text, three or more as a strip of the journal's own tiles + * with the rest counted, each entry opening where it is written (the trip's + * Journal tab or the journal's page), the map pin while resting on one, and + * a change row of an entry with its photo, text and marks, and every field + * an update changes, old to new. + */ +import type { + AssistantApplied, + AssistantChangePreview, + AssistantMessage, + JourneyEntriesCard, + JourneyEntryLook, +} from '@trek/shared'; +import type { ReactNode } from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { fireEvent, render, screen } from '../../../../../tests/helpers/render'; +import { useAssistantStore } from '../../../../store/assistantStore'; +import { useTripJournalLinkStore } from '../../../../store/tripJournalLinkStore'; +import AssistantChangeCard from '../../AssistantChangeCard'; +import type { ChangeItem } from '../../assistantParts'; +import { type AssistantView, AssistantViewContext } from '../../assistantViewContext'; +import JourneyEntriesBlock from './JourneyEntriesBlock'; + +const TRIP = 4; +const ASSISTANT = useAssistantStore.getState(); +const LINKS = useTripJournalLinkStore.getState(); +const MESSAGE = { id: 'm1', role: 'assistant', parts: [], status: 'complete', createdAt: '' } as AssistantMessage; + +function look(over: Partial = {}): JourneyEntryLook { + return { + entryId: 12, + type: 'entry', + title: 'Sunset at the Spree', + date: '2026-10-21', + time: '14:30', + place: 'Berlin', + point: { lat: 52.52, lng: 13.405 }, + countryCode: 'DE', + story: 'The light over the river was unreal.', + mood: null, + weather: null, + photoId: 7, + video: false, + photoCount: 1, + visibility: 'private', + draft: false, + fromTripPlace: false, + dayIndex: 0, + ...over, + }; +} + +function card(entries: JourneyEntryLook[], over: Partial = {}): JourneyEntriesCard { + return { + kind: 'journeyEntries', + journeyId: 3, + journalTitle: 'Berlin 2026', + tripJournal: false, + change: 'none', + entries, + more: 0, + ...over, + }; +} + +function inView(ui: ReactNode, view: Partial = {}) { + const value: AssistantView = { tripId: TRIP, variant: 'window', ...view }; + return render({ui}); +} + +function block(cards: JourneyEntriesCard[], view: Partial = {}) { + const entries = cards.map((c, i) => ({ toolCallId: `call_${i}`, card: c })); + return inView(, view); +} + +afterEach(() => { + useAssistantStore.setState(ASSISTANT, true); + useTripJournalLinkStore.setState(LINKS, true); + vi.restoreAllMocks(); +}); + +describe('the journal entries card', () => { + it('FE-AI-JOURNEY-001: one entry reads as a row with its photo, facts, marks and text under the journal', () => { + const { container } = block([card([look({ visibility: 'public', draft: true, photoCount: 4, video: true })])]); + expect(screen.getByRole('region', { name: 'Journal entries' })).toBeInTheDocument(); + expect(screen.getByText('Sunset at the Spree')).toBeInTheDocument(); + expect(screen.getByText('14:30')).toBeInTheDocument(); + expect(screen.getByText('Berlin')).toBeInTheDocument(); + expect(screen.getByText('The light over the river was unreal.')).toBeInTheDocument(); + expect(screen.getByText('Public')).toBeInTheDocument(); + expect(screen.getByText('Draft')).toBeInTheDocument(); + expect(screen.getByText('4 photos')).toBeInTheDocument(); + expect(screen.getByText('Opens with a video')).toBeInTheDocument(); + expect(screen.getByText('Berlin 2026')).toBeInTheDocument(); + expect(container.querySelector('img')).toHaveAttribute('src', '/api/photos/7/thumbnail'); + }); + + it('FE-AI-JOURNEY-002: an entry without a photo takes the width, and a known mood and weather are named', () => { + const { container } = block([card([look({ photoId: null, mood: 'amazing', weather: 'cold' })])]); + expect(container.querySelector('img')).toBeNull(); + expect(screen.getByText('Amazing')).toBeInTheDocument(); + // `cold` is the id the journal stores for snow. + expect(screen.getByText('Snowy')).toBeInTheDocument(); + block([card([look({ entryId: 20, mood: 'ecstatic', weather: 'Drizzle at noon' })], { journeyId: 8 })]); + expect(screen.getByText('Drizzle at noon')).toBeInTheDocument(); + expect(screen.queryByText('ecstatic')).toBeNull(); + }); + + it('FE-AI-JOURNEY-003: three or more entries run as the journal tiles, the ones left out counted at the end', () => { + const entries = [ + look({ entryId: 1, title: 'Arrival', dayIndex: 0 }), + look({ entryId: 2, title: 'Museum Island', dayIndex: 1 }), + look({ entryId: 3, title: 'Teufelsberg', dayIndex: 1, photoId: null }), + ]; + block([card(entries, { more: 5 })]); + expect(screen.getByRole('region', { name: 'Berlin 2026' })).toBeInTheDocument(); + expect(screen.getAllByRole('listitem')).toHaveLength(4); + expect(screen.getByRole('button', { name: /Museum Island/ })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: '5 more in the journal' })).toBeInTheDocument(); + expect(screen.getByText('8 entries')).toBeInTheDocument(); + }); + + it('FE-AI-JOURNEY-004: two reads of one journal draw as one card, each entry once', () => { + block([card([look({ entryId: 1, title: 'Old title' })]), card([look({ entryId: 1, title: 'New title' })])]); + expect(screen.getByText('New title')).toBeInTheDocument(); + expect(screen.queryByText('Old title')).toBeNull(); + }); + + it("FE-AI-JOURNEY-005: an entry opens in the trip's Journal tab when the trip shows that journal, else on its page", () => { + const onOpen = vi.fn(); + const first = block([card([look()])], { onOpen }); + fireEvent.click(screen.getByRole('button', { name: 'Sunset at the Spree' })); + expect(onOpen).toHaveBeenLastCalledWith({ kind: 'page', path: '/journey/3?entry=12' }); + fireEvent.click(screen.getByRole('button', { name: /Open in the journal/ })); + expect(onOpen).toHaveBeenLastCalledWith({ kind: 'page', path: '/journey/3' }); + first.unmount(); + + useTripJournalLinkStore.setState({ + byTrip: { + [String(TRIP)]: { + link: { + journey_id: 3, + title: 'Berlin 2026', + subtitle: null, + cover_image: null, + owner_id: 1, + linked_by: 1, + created_at: 0, + my_role: 'editor', + members: null, + }, + can_link: true, + can_unlink: true, + can_edit_members: false, + }, + }, + }); + block([card([look()])], { onOpen }); + fireEvent.click(screen.getByRole('button', { name: 'Sunset at the Spree' })); + expect(onOpen).toHaveBeenLastCalledWith({ kind: 'tab', tab: 'journal', params: { entry: '12' } }); + }); + + it('FE-AI-JOURNEY-006: without a shell to open into, the title is no button and the card has no way out', () => { + block([card([look()])]); + expect(screen.queryByRole('button', { name: 'Sunset at the Spree' })).toBeNull(); + expect(screen.queryByRole('button', { name: /Open in the journal/ })).toBeNull(); + }); + + it('FE-AI-JOURNEY-007: resting on an entry with a place pins it on the map; leaving and going take the pin away', () => { + const setPreviewPin = vi.fn(); + useAssistantStore.setState({ setPreviewPin }); + const { unmount } = block([card([look(), look({ entryId: 13, title: 'Nowhere', point: null })])]); + fireEvent.mouseEnter(screen.getByText('Sunset at the Spree').closest('div') as HTMLElement); + expect(setPreviewPin).toHaveBeenLastCalledWith({ + tripId: TRIP, + ref: 'journey:3:12', + lat: 52.52, + lng: 13.405, + name: 'Sunset at the Spree', + }); + fireEvent.mouseLeave(screen.getByText('Sunset at the Spree').closest('div') as HTMLElement); + expect(setPreviewPin).toHaveBeenLastCalledWith(null); + unmount(); + expect(setPreviewPin).toHaveBeenLastCalledWith(null); + }); +}); + +describe('a change row of a journal entry', () => { + const DELETE_ROWS: AssistantChangePreview['rows'] = [ + { op: 'add', labelKey: 'day', before: null, after: 'Tue, Oct 21' }, + { op: 'add', labelKey: 'location', before: null, after: 'Museum Island' }, + { op: 'add', labelKey: 'text', before: null, after: 'Not a fact' }, + ]; + + function item( + state: ChangeItem['state'], + held: JourneyEntriesCard, + over: Partial = {} + ): ChangeItem { + const preview: AssistantChangePreview = { + toolCallId: 'w1', + verbKey: 'removeJournalEntry', + subject: 'Sunset at the Spree', + rows: DELETE_ROWS, + dayId: null, + placeIds: [], + undoable: false, + domain: 'journey', + card: held, + ...over, + }; + const receipt: AssistantApplied = { + toolCallId: 'w1', + entity: 'journey_entry', + ids: [12], + dayId: null, + undoUntil: null, + }; + return { toolCallId: 'w1', preview, applied: state === 'applied' ? receipt : null, state, card: held }; + } + + it('FE-AI-JOURNEY-008: a waiting delete shows the photo, the text and that it goes back to a suggestion; a receipt opens it', () => { + const entry = look({ fromTripPlace: true, visibility: 'shared' }); + const held = card([entry], { change: 'willDelete', tripJournal: true }); + const onOpen = vi.fn(); + const first = inView(, { onOpen }); + expect(screen.getByText('Delete the journal entry')).toBeInTheDocument(); + expect(screen.getByText('The light over the river was unreal.')).toBeInTheDocument(); + expect(screen.getByText('Shared')).toBeInTheDocument(); + expect(screen.getByText('Goes back to a suggestion')).toBeInTheDocument(); + expect(screen.getByText('Tue, Oct 21')).toBeInTheDocument(); + expect(screen.getByText('Museum Island')).toBeInTheDocument(); + expect(screen.queryByText('Not a fact')).toBeNull(); + expect(document.querySelector('img')).toHaveAttribute('src', '/api/photos/7/thumbnail'); + first.unmount(); + + const second = inView(, { onOpen }); + expect(screen.queryByRole('button', { name: 'Show on map' })).toBeNull(); + fireEvent.click(screen.getByRole('button', { name: 'Open in the journal' })); + expect(onOpen).toHaveBeenCalledWith({ kind: 'tab', tab: 'journal', params: { entry: '12' } }); + second.unmount(); + + inView(, { onOpen }); + expect(screen.queryByText('Goes back to a suggestion')).toBeNull(); + expect(document.querySelector('img')).toBeNull(); + }); + + it('FE-AI-JOURNEY-009: a waiting update names every field it changes old to new, a cleared one as removed', () => { + const rows: AssistantChangePreview['rows'] = [ + { op: 'change', labelKey: 'name', before: 'Sunset', after: 'Sunset at the Spree' }, + { op: 'change', labelKey: 'time', before: '14:30', after: '' }, + { op: 'change', labelKey: 'text', before: 'Old story', after: 'New story' }, + { op: 'change', labelKey: 'field', field: 'visibility', before: 'private', after: 'public' }, + { op: 'change', labelKey: 'field', field: 'mood', before: 'good', after: '' }, + { op: 'change', labelKey: 'field', field: 'weather', before: 'sunny', after: 'Drizzle' }, + { op: 'change', labelKey: 'field', field: 'is_draft', before: '✓', after: '✗' }, + ]; + const held = card([look({ photoId: null })], { change: 'changed' }); + inView(); + expect(screen.getByText('Change the journal entry')).toBeInTheDocument(); + expect(screen.getByText('Sunset')).toHaveClass('line-through'); + expect(screen.getByText('14:30')).toHaveClass('line-through'); + expect(screen.getByText('Old story')).toHaveClass('line-through'); + expect(screen.getByText('New story')).toBeInTheDocument(); + expect(screen.getByText('Private')).toHaveClass('line-through'); + expect(screen.getByText('Public')).toBeInTheDocument(); + expect(screen.getByText('Good')).toHaveClass('line-through'); + expect(screen.getByText('Sunny')).toHaveClass('line-through'); + expect(screen.getByText('Drizzle')).toBeInTheDocument(); + expect(screen.getByText('No longer a draft')).toBeInTheDocument(); + expect(screen.getAllByText('Removed')).toHaveLength(2); + }); + + it('FE-AI-JOURNEY-010: resting on a waiting change shows its entry on the map, and leaving takes the pin away', () => { + const setPreviewPin = vi.fn(); + useAssistantStore.setState({ setPreviewPin }); + const held = card([look()], { change: 'changed' }); + inView(); + const story = screen.getByText('The light over the river was unreal.'); + fireEvent.mouseEnter(story); + expect(setPreviewPin).toHaveBeenLastCalledWith({ + tripId: TRIP, + ref: 'journey:3:12', + lat: 52.52, + lng: 13.405, + name: 'Sunset at the Spree', + }); + fireEvent.mouseLeave(story); + expect(setPreviewPin).toHaveBeenLastCalledWith(null); + fireEvent.focus(document.querySelector('img')?.parentElement?.parentElement as HTMLElement); + expect(setPreviewPin).toHaveBeenLastCalledWith(expect.objectContaining({ ref: 'journey:3:12' })); + }); +}); diff --git a/client/src/components/Assistant/cards/journey/JourneyEntryParts.tsx b/client/src/components/Assistant/cards/journey/JourneyEntryParts.tsx new file mode 100644 index 000000000..eb2a2e23e --- /dev/null +++ b/client/src/components/Assistant/cards/journey/JourneyEntryParts.tsx @@ -0,0 +1,128 @@ +import type { JourneyEntryLook } from '@trek/shared'; +import { CalendarDays, Globe, Images, MapPin, Play, Users } from 'lucide-react'; + +import { useTranslation } from '../../../../i18n'; +import { cardDateLabel, cardPlace } from '../../../Journey/journeyCard'; +import { SoftPill, TimePill, WhiteBadge } from '../../../Planner/planParts'; +import CountryFlag from '../../../shared/CountryFlag'; +import { CardFacts } from '../parts/CardFacts'; +import { titleSourceOf } from './journeyCardModel'; +import { moodOf, weatherOf } from './journeyTones'; + +/** + * The pieces a journal entry is drawn from in the chat, the same in an + * answer, a change row and a receipt: its photo, the facts of when and where + * as the planner's badges, the marks of how it reads (shared, draft, mood, + * weather, more photos) and the start of its text. Every fact wraps, none is + * cut. + */ + +const THUMB_SIZE = { sm: 'size-11', md: 'size-16', lg: 'size-20' } as const; +const THUMB_BOX = 'relative flex-none'; +const THUMB_IMG = 'size-full rounded-lg bg-surface-secondary object-cover'; +const VIDEO_MARK = 'absolute bottom-1 end-1'; +const ICON = 'flex-none text-content-faint'; +const STORY = { + compact: 'mt-1.5 line-clamp-2 text-caption text-content-secondary', + roomy: 'mt-1.5 line-clamp-3 text-caption text-content-secondary', +} as const; + +/** The entry's photo as a square, a clip marked as one; nothing without a photo. */ +export function EntryThumb({ look, size }: { look: JourneyEntryLook; size: keyof typeof THUMB_SIZE }) { + const { t } = useTranslation(); + if (look.photoId === null) return null; + return ( + + + {look.video && ( + + )} + + ); +} + +/** When and where: the day, the time, the place with its flag. */ +export function EntryWhen({ look }: { look: JourneyEntryLook }) { + const { locale } = useTranslation(); + const place = cardPlace(titleSourceOf(look)); + return ( + + + {look.time && {look.time}} + {(place || look.countryCode) && ( + + )} + + ); +} + +/** Shared or public; nothing for a private entry. */ +function VisibilityMark({ visibility }: { visibility: JourneyEntryLook['visibility'] }) { + const { t } = useTranslation(); + if (visibility === 'private') return null; + const shared = visibility === 'shared'; + const Icon = shared ? Users : Globe; + return ( + + ); +} + +/** A mood the journal knows, in its own colour; nothing for any other. */ +function MoodMark({ id }: { id: string | null }) { + const { t } = useTranslation(); + const mood = moodOf(id); + if (!mood) return null; + return ( + // The mood's own colour, the theme's token the journal draws it in. + + ); +} + +/** The weather by the journal's name for it, or as the traveller wrote it. */ +function WeatherMark({ weather }: { weather: string | null }) { + const { t } = useTranslation(); + if (!weather) return null; + const known = weatherOf(weather); + return ( + + ); +} + +/** How the entry reads: shared or public, a draft, its mood and weather, its photos past the first. */ +export function EntryMarks({ look }: { look: JourneyEntryLook }) { + const { t } = useTranslation(); + const mood = moodOf(look.mood) !== null; + if (look.visibility === 'private' && !look.draft && !mood && !look.weather && look.photoCount < 2) return null; + return ( + + + {look.draft && {t('journey.entry.draft')}} + + + {look.photoCount > 1 && ( + + )} + + ); +} + +/** The start of the entry's text, two lines where room is short, three where there is room. */ +export function EntryStory({ look, roomy }: { look: JourneyEntryLook; roomy: boolean }) { + if (!look.story) return null; + return

    {look.story}

    ; +} diff --git a/client/src/components/Assistant/cards/journey/journeyCardModel.test.ts b/client/src/components/Assistant/cards/journey/journeyCardModel.test.ts new file mode 100644 index 000000000..60e2f07e1 --- /dev/null +++ b/client/src/components/Assistant/cards/journey/journeyCardModel.test.ts @@ -0,0 +1,175 @@ +/** + * FE-AI-JOURNEY-MODEL-001 to FE-AI-JOURNEY-MODEL-009 + * + * The pure side of the journal's cards: where an entry opens, how the cards + * of one answer about one journal merge, how an entry reads to the journal's + * own tile, the mood and weather names, and the journal's look in the chat: + * its verbs, tools, steps, what an applied entry opens, its grouping and the + * lookup that gives way to the change it served. + */ +import type { AssistantApplied, JourneyEntriesCard, JourneyEntryLook, TrekCard } from '@trek/shared'; +import { describe, expect, it } from 'vitest'; + +import { CARD_RULES, ENTITY_LOOK, STEP_LOOKS, TOOL_LABELS, VERB_LOOK } from '../cardLooks'; +import { coverEntryOf, journalTarget, mergeJournalCards } from './journeyCardModel'; +import { flagOf, moodOf, stateOf, weatherOf } from './journeyTones'; +import { JOURNEY_LOOK } from './journeyLook'; + +function look(over: Partial = {}): JourneyEntryLook { + return { + entryId: 12, + type: 'entry', + title: 'Sunset', + date: '2026-10-21', + time: null, + place: 'Berlin', + point: null, + countryCode: 'DE', + story: null, + mood: null, + weather: null, + photoId: null, + video: false, + photoCount: 0, + visibility: 'private', + draft: false, + fromTripPlace: false, + dayIndex: null, + ...over, + }; +} + +function card(entries: JourneyEntryLook[], over: Partial = {}): JourneyEntriesCard { + return { + kind: 'journeyEntries', + journeyId: 3, + journalTitle: null, + tripJournal: false, + change: 'none', + entries, + more: 0, + ...over, + }; +} + +describe('journeyCardModel', () => { + it('FE-AI-JOURNEY-MODEL-001: an entry opens in the Journal tab of the trip that shows it, else on the journal page', () => { + expect(journalTarget(3, 12, true)).toEqual({ kind: 'tab', tab: 'journal', params: { entry: '12' } }); + expect(journalTarget(3, null, true)).toEqual({ kind: 'tab', tab: 'journal' }); + expect(journalTarget(3, 12, false)).toEqual({ kind: 'page', path: '/journey/3?entry=12' }); + expect(journalTarget(3, null, false)).toEqual({ kind: 'page', path: '/journey/3' }); + }); + + it('FE-AI-JOURNEY-MODEL-002: the reads of one journal merge: each entry once, the later read winning, by day', () => { + const later = look({ entryId: 2, date: '2026-10-22', title: 'Later' }); + const merged = mergeJournalCards([ + { toolCallId: 'a', card: card([look({ entryId: 2, date: '2026-10-22' }), look({ entryId: 1 })], { more: 4 }) }, + { toolCallId: 'b', card: card([later], { journalTitle: 'B' }) }, + { toolCallId: 'c', card: card([look({ entryId: null, date: '2026-10-20' })], { tripJournal: true }) }, + ]); + expect(merged?.entries.map((e) => e.entryId)).toEqual([null, 1, 2]); + expect(merged?.entries[2]?.title).toBe('Later'); + expect(merged).toMatchObject({ journeyId: 3, journalTitle: 'B', tripJournal: true, more: 4 }); + expect(mergeJournalCards([{ toolCallId: 'x', card: { kind: 'tourList' } as TrekCard }])).toBeNull(); + }); + + it("FE-AI-JOURNEY-MODEL-003: an entry reads to the journal's tile with its photo, never one without a picture", () => { + expect(coverEntryOf(look({ photoId: 7, video: true }))).toMatchObject({ + id: 12, + entry_date: '2026-10-21', + location_name: 'Berlin', + country_code: 'DE', + photos: [{ photo_id: 7, media_type: 'video' }], + }); + expect(coverEntryOf(look({ entryId: null })).photos).toEqual([]); + }); + + it('FE-AI-JOURNEY-MODEL-004: moods and weathers read as the journal draws them, anything else as nothing', () => { + expect(moodOf('amazing')).toMatchObject({ labelKey: 'journey.mood.amazing', color: 'var(--mood-amazing)' }); + // Neither journal editor writes "tired"; the journal shows no mood for it. + expect(moodOf('tired')).toBeNull(); + // `cold` is the id the journal stores for snow. + expect(weatherOf('cold')?.labelKey).toBe('journey.weather.cold'); + expect(weatherOf('sunny')?.labelKey).toBe('journey.weather.sunny'); + expect(weatherOf('drizzle at noon')).toBeNull(); + expect(moodOf('toString')).toBeNull(); + expect(moodOf(null)).toBeNull(); + }); + + it('FE-AI-JOURNEY-MODEL-009: the states an update sets are named by field, flags by on and off', () => { + expect(stateOf('visibility', 'public')?.labelKey).toBe('journey.visibility.public'); + expect(stateOf('type', 'skeleton')?.labelKey).toBe('journey.entry.suggestion'); + expect(stateOf('mood', 'good')?.labelKey).toBe('journey.mood.good'); + expect(stateOf('weather', 'cold')?.labelKey).toBe('journey.weather.cold'); + expect(stateOf('weather', 'Drizzle')).toBeNull(); + expect(stateOf('visibility', 'toString')).toBeNull(); + expect(stateOf(undefined, 'public')).toBeNull(); + expect(flagOf('is_draft', '✓')?.labelKey).toBe('journey.entry.draft'); + expect(flagOf('is_draft', '✗')?.labelKey).toBe('assistant.card.journey.notDraft'); + expect(flagOf('dismissed', '✗')?.labelKey).toBe('assistant.card.journey.restored'); + expect(flagOf('stats_excluded', '✓')?.labelKey).toBe('journey.editor.statsExcluded'); + expect(flagOf('visibility', '✓')).toBeNull(); + }); + + it('FE-AI-JOURNEY-MODEL-005: the journal names its verbs, tools and reading steps in the merged look', () => { + expect(VERB_LOOK.addJournalEntry.labelKey).toBe('assistant.change.verb.addJournalEntry'); + expect(VERB_LOOK.removeJournalEntry.tone).toBe('danger'); + expect(TOOL_LABELS.link_trip_journal?.labelKey).toBe('assistant.tool.link_trip_journal'); + expect(STEP_LOOKS.list_journey_entries?.stepKey).toBe('assistant.step.readingJournal'); + expect(JOURNEY_LOOK.cards.journeyEntries.followUps.find((f) => f.edits)?.id).toBe('journalToday'); + }); + + it('FE-AI-JOURNEY-MODEL-006: an applied entry opens where its card says; reads group per journal and yield to its change', () => { + const applied: AssistantApplied = { + toolCallId: 'w', + entity: 'journey_entry', + ids: [40], + dayId: null, + undoUntil: null, + }; + const entity = ENTITY_LOOK.journey_entry; + expect(entity.onMap).toBeUndefined(); + expect(entity.open?.(applied, card([look()], { tripJournal: true }))).toEqual({ + kind: 'tab', + tab: 'journal', + params: { entry: '40' }, + }); + const fromCard = entity.open?.({ ...applied, ids: [] }, card([look()])); + expect(fromCard).toEqual({ kind: 'page', path: '/journey/3?entry=12' }); + expect(entity.open?.(applied, null)).toBeNull(); + + const read = card([look()]); + expect(CARD_RULES.group(read)).toBe('journey:3'); + expect(CARD_RULES.yieldsToChange(read, card([look()], { change: 'changed' }))).toBe(true); + expect(CARD_RULES.yieldsToChange(read, card([look()], { journeyId: 9, change: 'changed' }))).toBe(false); + expect(CARD_RULES.yieldsToChange(read, { kind: 'tourList' } as TrekCard)).toBe(false); + }); + + it('FE-AI-JOURNEY-MODEL-007: a list answer stays beside a change that touches only part of it, or writes a new entry', () => { + const list = card([look({ entryId: 1 }), look({ entryId: 2, date: '2026-10-22' })]); + expect(CARD_RULES.yieldsToChange(list, card([look({ entryId: null })], { change: 'new' }))).toBe(false); + expect(CARD_RULES.yieldsToChange(list, card([look({ entryId: 2 })], { change: 'changed' }))).toBe(false); + const lookup = card([look({ entryId: 2 })]); + expect(CARD_RULES.yieldsToChange(lookup, card([look({ entryId: 2 })], { change: 'willDelete' }))).toBe(true); + expect(CARD_RULES.yieldsToChange(card([]), card([look()], { change: 'changed' }))).toBe(false); + }); + + it('FE-AI-JOURNEY-MODEL-008: merged reads count their days over the whole card, a lone entry read included', () => { + const merged = mergeJournalCards([ + { + toolCallId: 'a', + card: card([ + look({ entryId: 1, date: '2026-10-20', dayIndex: 0 }), + look({ entryId: 2, date: '2026-10-22', dayIndex: 1 }), + ]), + }, + { toolCallId: 'b', card: card([look({ entryId: 2, date: '2026-10-22', dayIndex: null })]) }, + { toolCallId: 'c', card: card([look({ entryId: 3, date: '2026-10-21', dayIndex: 0 })]) }, + ]); + expect(merged?.entries.map((e) => [e.entryId, e.dayIndex])).toEqual([ + [1, 0], + [3, 1], + [2, 2], + ]); + }); +}); diff --git a/client/src/components/Assistant/cards/journey/journeyCardModel.ts b/client/src/components/Assistant/cards/journey/journeyCardModel.ts new file mode 100644 index 000000000..90287f224 --- /dev/null +++ b/client/src/components/Assistant/cards/journey/journeyCardModel.ts @@ -0,0 +1,95 @@ +import type { JourneyEntryLook } from '@trek/shared'; + +import type { CoverEntry } from '../../../Journey/JourneyEntryCover'; +import type { CardEntry, EntityTarget } from '../cardTypes'; + +/** + * The pure side of the journal's cards: where an entry opens, how the cards + * of one answer about one journal become one, and how an entry looks to the + * journal's own tile. + */ + +/** + * Where an entry opens: the trip's own Journal tab when the journal is the + * one the trip shows, else the journal's page, at that entry either way. + */ +export function journalTarget(journeyId: number, entryId: number | null, inTrip: boolean): EntityTarget { + const entry = entryId === null ? null : String(entryId); + if (inTrip) return { kind: 'tab', tab: 'journal', ...(entry === null ? {} : { params: { entry } }) }; + return { kind: 'page', path: entry === null ? `/journey/${journeyId}` : `/journey/${journeyId}?entry=${entry}` }; +} + +/** The cards of one journal in one answer, drawn as one. */ +export interface JournalEntries { + journeyId: number; + journalTitle: string | null; + tripJournal: boolean; + entries: JourneyEntryLook[]; + more: number; +} + +/** By day; the sort is stable, so a day keeps the order its read gave it (the journal's own). */ +function byDay(a: JourneyEntryLook, b: JourneyEntryLook): number { + if (a.date === b.date) return 0; + return a.date < b.date ? -1 : 1; +} + +/** + * The entries with their day counted again over all of them: each read counts + * its own days, and a lone entry's read counts none, so one card colours a + * day the same wherever its entries came from. + */ +function withDays(entries: readonly JourneyEntryLook[]): JourneyEntryLook[] { + const days = [...new Set(entries.map((look) => look.date))]; + return entries.map((look) => ({ ...look, dayIndex: days.indexOf(look.date) })); +} + +/** + * The cards of one answer about one journal as one: every entry once (a + * later read of an entry wins), in the journal's order, its days counted over + * the whole card, the most a read left out kept as `more`. Null when none is a + * journal card. + */ +export function mergeJournalCards(cards: readonly CardEntry[]): JournalEntries | null { + const own = cards.flatMap((entry) => (entry.card.kind === 'journeyEntries' ? [entry.card] : [])); + const first = own[0]; + if (!first) return null; + const byId = new Map(); + own.forEach((card, cardIndex) => { + card.entries.forEach((look, index) => { + byId.set(look.entryId === null ? `new-${cardIndex}-${index}` : String(look.entryId), look); + }); + }); + return { + journeyId: first.journeyId, + journalTitle: own.map((card) => card.journalTitle).find((title) => title !== null) ?? null, + tripJournal: own.some((card) => card.tripJournal), + entries: withDays([...byId.values()].sort(byDay)), + more: Math.max(0, ...own.map((card) => card.more)), + }; +} + +/** An entry as the journal's own tile reads it. */ +export function coverEntryOf(look: JourneyEntryLook): CoverEntry { + return { + id: look.entryId ?? 0, + type: look.type, + title: look.title, + story: look.story, + location_name: look.place, + location_lat: look.point?.lat ?? null, + location_lng: look.point?.lng ?? null, + country_code: look.countryCode, + entry_date: look.date, + entry_time: look.time, + mood: look.mood, + weather: look.weather, + // The server picked a photo that has a picture, so no clip here lacks its poster. + photos: look.photoId === null ? [] : [{ photo_id: look.photoId, media_type: look.video ? 'video' : 'image' }], + }; +} + +/** What `cardTitle` reads of an entry. */ +export function titleSourceOf(look: JourneyEntryLook): Pick { + return { title: look.title, type: look.type, location_name: look.place }; +} diff --git a/client/src/components/Assistant/cards/journey/journeyLook.ts b/client/src/components/Assistant/cards/journey/journeyLook.ts index 928a58c50..4337dbe00 100644 --- a/client/src/components/Assistant/cards/journey/journeyLook.ts +++ b/client/src/components/Assistant/cards/journey/journeyLook.ts @@ -1,18 +1,63 @@ +import { BookOpen, BookOpenText, BookPlus, BookX } from 'lucide-react'; + import type { PackLook } from '../cardTypes'; +import { journalTarget } from './journeyCardModel'; /** * What the journeys bring to the chat's pure look: the verbs, tool names and * steps they add, what an applied change of theirs opens, and the look of each - * of their kinds. Empty until the journey cards fill it. A look stays pure, - * icons and literals only: the chat's main chunk reads every look, so whatever - * a look imports ships with it. + * of their kinds. A look stays pure, icons and literals only: the chat's main + * chunk reads every look, so whatever a look imports ships with it. + * + * An applied entry opens in the journal: in the trip's Journal tab when the + * card saw that the trip shows this journal, else on the journal's page. */ export const JOURNEY_LOOK = { - verbs: {}, - tools: {}, - steps: {}, - entities: {}, + verbs: { + addJournalEntry: { Icon: BookPlus, tone: 'success', labelKey: 'assistant.change.verb.addJournalEntry' }, + updateJournalEntry: { Icon: BookOpenText, tone: 'info', labelKey: 'assistant.change.verb.updateJournalEntry' }, + removeJournalEntry: { Icon: BookX, tone: 'danger', labelKey: 'assistant.change.verb.removeJournalEntry' }, + }, + tools: { + create_journey: { labelKey: 'assistant.tool.create_journey' }, + update_journey: { labelKey: 'assistant.tool.update_journey' }, + add_journey_trip: { labelKey: 'assistant.tool.add_journey_trip' }, + link_trip_journal: { labelKey: 'assistant.tool.link_trip_journal' }, + reorder_journey_entries: { labelKey: 'assistant.tool.reorder_journey_entries' }, + }, + steps: { + get_trip_journal: { stepKey: 'assistant.step.readingJournal' }, + list_journey_entries: { stepKey: 'assistant.step.readingJournal' }, + get_journey: { stepKey: 'assistant.step.readingJournal' }, + get_journey_entry: { stepKey: 'assistant.step.readingJournal' }, + }, + entities: { + journey_entry: { + Icon: BookOpen, + openLabelKey: 'assistant.card.journey.open', + open: (applied, card) => + card?.kind === 'journeyEntries' + ? journalTarget(card.journeyId, applied.ids[0] ?? card.entries[0]?.entryId ?? null, card.tripJournal) + : null, + }, + }, cards: { - journeyEntries: {}, + journeyEntries: { + entity: () => 'journey_entry', + followUps: [ + { id: 'journalToday', labelKey: 'assistant.followUp.journalToday', edits: true }, + { id: 'journalSummary', labelKey: 'assistant.followUp.journalSummary' }, + ], + // The reads of one journal in one answer draw as one card. + group: (card) => `journey:${card.journeyId}`, + // A read that looked up an entry gives way to the change it served: the change shows the entry already. + // A read holding entries the change leaves alone stays, and a new entry has no read to replace. + yieldsToChange: (answer, change) => { + if (change.kind !== 'journeyEntries' || change.journeyId !== answer.journeyId) return false; + const touched = new Set(change.entries.flatMap((look) => (look.entryId === null ? [] : [look.entryId]))); + const readIds = answer.entries.map((read) => read.entryId); + return readIds.length > 0 && readIds.every((id) => id !== null && touched.has(id)); + }, + }, }, } satisfies PackLook<'journeyEntries'>; diff --git a/client/src/components/Assistant/cards/journey/journeyTones.ts b/client/src/components/Assistant/cards/journey/journeyTones.ts new file mode 100644 index 000000000..2f18f5814 --- /dev/null +++ b/client/src/components/Assistant/cards/journey/journeyTones.ts @@ -0,0 +1,125 @@ +import { + BookOpenText, + Cloud, + CloudLightning, + CloudRain, + CloudSun, + Eye, + EyeOff, + Frown, + Globe, + Lock, + type LucideIcon, + MapPinCheck, + Meh, + PenLine, + Route, + Smile, + SmilePlus, + Snowflake, + Sparkles, + Sun, + Users, +} from 'lucide-react'; + +/** + * How the states of a journal entry read in the chat, the way the journal + * draws them: its moods with the glyphs of its tiles, its weathers, and the + * words for what an update sets beyond the text (who sees the entry, its + * kind, a draft, the route, a waved-away suggestion). + */ + +/** How a state is drawn: its glyph and the key of its name. */ +interface EntryTone { + Icon: LucideIcon; + labelKey: string; +} + +/** + * The four moods the journal's editors write, with the glyphs its tiles draw + * them in; the colour is the theme's mood token of the same name. Any other + * id is left out, the way the journal leaves it out. + */ +const MOODS: Readonly> = { + amazing: { Icon: SmilePlus, labelKey: 'journey.mood.amazing', color: 'var(--mood-amazing)' }, + good: { Icon: Smile, labelKey: 'journey.mood.good', color: 'var(--mood-good)' }, + neutral: { Icon: Meh, labelKey: 'journey.mood.neutral', color: 'var(--mood-neutral)' }, + rough: { Icon: Frown, labelKey: 'journey.mood.rough', color: 'var(--mood-rough)' }, +}; + +/** The six weathers the journal offers. `cold` is the id it stores for snow, and its name says so. */ +const WEATHERS: Readonly> = { + sunny: { Icon: Sun, labelKey: 'journey.weather.sunny' }, + partly: { Icon: CloudSun, labelKey: 'journey.weather.partly' }, + cloudy: { Icon: Cloud, labelKey: 'journey.weather.cloudy' }, + rainy: { Icon: CloudRain, labelKey: 'journey.weather.rainy' }, + stormy: { Icon: CloudLightning, labelKey: 'journey.weather.stormy' }, + cold: { Icon: Snowflake, labelKey: 'journey.weather.cold' }, +}; + +const VISIBILITIES: Readonly> = { + private: { Icon: Lock, labelKey: 'journey.visibility.private' }, + shared: { Icon: Users, labelKey: 'journey.visibility.shared' }, + public: { Icon: Globe, labelKey: 'journey.visibility.public' }, +}; + +const TYPES: Readonly> = { + entry: { Icon: BookOpenText, labelKey: 'assistant.card.journey.typeEntry' }, + checkin: { Icon: MapPinCheck, labelKey: 'assistant.card.journey.typeCheckin' }, + skeleton: { Icon: Sparkles, labelKey: 'journey.entry.suggestion' }, +}; + +/** The flags an update sets, each by what it reads as when on (✓) and when off (✗). */ +const FLAGS: Readonly> = { + is_draft: { + on: { Icon: PenLine, labelKey: 'journey.entry.draft' }, + off: { Icon: PenLine, labelKey: 'assistant.card.journey.notDraft' }, + }, + stats_excluded: { + on: { Icon: Route, labelKey: 'journey.editor.statsExcluded' }, + off: { Icon: Route, labelKey: 'assistant.card.journey.onRoute' }, + }, + dismissed: { + on: { Icon: EyeOff, labelKey: 'journey.suggestions.dismissed' }, + off: { Icon: Eye, labelKey: 'assistant.card.journey.restored' }, + }, +}; + +/** How a flag comes on a change row, the way the server writes a boolean. */ +const FLAG_ON = '✓'; + +/** An own entry of a table only, so `toString` and the like name nothing. */ +function own(table: Readonly>, id: string | null | undefined): T | null { + if (!id || !Object.prototype.hasOwnProperty.call(table, id)) return null; + return table[id] ?? null; +} + +/** A mood the journal knows; null for any other. */ +export function moodOf(id: string | null): (EntryTone & { color: string }) | null { + return own(MOODS, id); +} + +/** A weather the journal offers; null for a free word the traveller wrote. */ +export function weatherOf(id: string | null): EntryTone | null { + return own(WEATHERS, id); +} + +/** A flag of a change row: what it reads as now; null for a field that is no flag. */ +export function flagOf(field: string | undefined, value: string): EntryTone | null { + const flag = own(FLAGS, field); + if (!flag) return null; + return value === FLAG_ON ? flag.on : flag.off; +} + +/** + * A state of a change row by the field it sets (the tool's own name) and a + * value as stored: its glyph and name, or null where the card has no name for + * it (a weather the traveller wrote in their words, which reads as it is). + */ +export function stateOf(field: string | undefined, value: string | null): EntryTone | null { + if (field === 'mood') return moodOf(value); + if (field === 'weather') return weatherOf(value); + if (field === 'visibility') return own(VISIBILITIES, value); + if (field === 'type') return own(TYPES, value); + return null; +} diff --git a/client/src/components/Assistant/cards/journey/journeyViews.tsx b/client/src/components/Assistant/cards/journey/journeyViews.tsx index c6641bc97..2466c2ab9 100644 --- a/client/src/components/Assistant/cards/journey/journeyViews.tsx +++ b/client/src/components/Assistant/cards/journey/journeyViews.tsx @@ -1,12 +1,21 @@ -import { type CardView, PENDING_VIEW } from '../cardTypes'; +import type { CardView } from '../cardTypes'; +import { JourneyEntryAside, JourneyEntryBody, JourneyEntryFacts } from './JourneyChangeSlots'; +import JourneyEntriesBlock from './JourneyEntriesBlock'; /** - * How the kinds of the journeys draw in the chat; each one draws nothing until - * its cards are built. This file only maps each kind to its view: the - * components live in sibling files, since a file that exports anything besides - * components breaks fast refresh, and lint:warnings holds + * How the kinds of the journeys draw in the chat: the entries a read found + * as a block of their own, and a change row of an entry with its photo beside + * the subject, its day, time and place and whatever an update changes on the + * faint line, and the start of its text under it. This file only maps each + * kind to its view: the components live in sibling files, since a file that + * exports anything besides components breaks fast refresh, and lint:warnings holds * react-refresh/only-export-components at zero for a new file. */ export const JOURNEY_VIEWS = { - journeyEntries: PENDING_VIEW, + journeyEntries: { + Block: JourneyEntriesBlock, + Aside: JourneyEntryAside, + Facts: JourneyEntryFacts, + Body: JourneyEntryBody, + }, } satisfies { [K in 'journeyEntries']: CardView }; diff --git a/client/src/components/Assistant/cards/journey/useEntryHover.ts b/client/src/components/Assistant/cards/journey/useEntryHover.ts new file mode 100644 index 000000000..cedfec295 --- /dev/null +++ b/client/src/components/Assistant/cards/journey/useEntryHover.ts @@ -0,0 +1,41 @@ +import type { JourneyEntryLook } from '@trek/shared'; + +import { useTranslation } from '../../../../i18n'; +import { cardTitle } from '../../../Journey/journeyCard'; +import { useCardPoint } from '../parts/useCardPoint'; +import { titleSourceOf } from './journeyCardModel'; + +/** Shows an entry on the plan's map, or takes it away (null). */ +export type EntryHover = (look: JourneyEntryLook | null) => void; + +/** + * The way a card's entries show on the map while the pointer rests on one or + * the keyboard is on it: a pin under the entry's own key; nothing for one + * without a place. The pin goes when the card does. + */ +export function useEntryHover(journeyId: number, fallbackRef: string): EntryHover { + const { t } = useTranslation(); + const point = useCardPoint(); + return (look) => { + if (!look?.point) { + point.hover(null); + return; + } + point.hover({ + ref: `journey:${journeyId}:${look.entryId ?? fallbackRef}`, + lat: look.point.lat, + lng: look.point.lng, + name: cardTitle(titleSourceOf(look), t), + }); + }; +} + +/** What an element standing for one entry listens to: the pointer resting on it and the focus inside it. */ +export function entryHoverProps(hover: EntryHover, look: JourneyEntryLook) { + return { + onMouseEnter: () => hover(look), + onMouseLeave: () => hover(null), + onFocus: () => hover(look), + onBlur: () => hover(null), + }; +} diff --git a/client/src/components/Assistant/cards/journey/useJourneyOpen.ts b/client/src/components/Assistant/cards/journey/useJourneyOpen.ts new file mode 100644 index 000000000..a1db87216 --- /dev/null +++ b/client/src/components/Assistant/cards/journey/useJourneyOpen.ts @@ -0,0 +1,19 @@ +import { useTripJournalLinkStore } from '../../../../store/tripJournalLinkStore'; +import { useAssistantView } from '../../assistantViewContext'; +import { journalTarget } from './journeyCardModel'; + +/** + * Opens an entry of a journal from a card, decided when it is clicked: in the + * trip's Journal tab when the trip shows this journal (as the card saw it, or + * as the trip's journal link says now), else on the journal's page. Null where + * the shell around the chat cannot open anything. + */ +export function useJourneyOpen(journeyId: number, tripJournal: boolean): ((entryId: number | null) => void) | null { + const { tripId, onOpen } = useAssistantView(); + const shown = useTripJournalLinkStore((s) => { + const link = s.byTrip[String(tripId)]?.link; + return !!link && link.my_role !== null && link.journey_id === journeyId; + }); + if (!onOpen) return null; + return (entryId) => onOpen(journalTarget(journeyId, entryId, tripJournal || shown)); +} diff --git a/client/src/components/Journey/stripMarkdown.test.ts b/client/src/components/Journey/stripMarkdown.test.ts deleted file mode 100644 index d932c06df..000000000 --- a/client/src/components/Journey/stripMarkdown.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -// FE-UTIL-STRIPMD-001 to FE-UTIL-STRIPMD-006 - -import { describe, it, expect } from 'vitest'; -import { stripMarkdown } from './stripMarkdown'; - -describe('stripMarkdown', () => { - it('FE-UTIL-STRIPMD-001: strips bold and italic formatting', () => { - expect(stripMarkdown('**bold** and _italic_')).toBe('bold and italic'); - expect(stripMarkdown('__also bold__ and *also italic*')).toBe('also bold and also italic'); - }); - - it('FE-UTIL-STRIPMD-002: strips headings', () => { - expect(stripMarkdown('# Heading 1')).toBe('Heading 1'); - expect(stripMarkdown('## Heading 2')).toBe('Heading 2'); - expect(stripMarkdown('### Heading 3')).toBe('Heading 3'); - }); - - it('FE-UTIL-STRIPMD-003: converts links to text and removes images', () => { - expect(stripMarkdown('[click here](https://example.com)')).toBe('click here'); - expect(stripMarkdown('![alt text](image.jpg)')).toBe(''); - }); - - it('FE-UTIL-STRIPMD-004: strips code blocks and inline code', () => { - expect(stripMarkdown('use `console.log`')).toBe('use console.log'); - expect(stripMarkdown('```\ncode block\n```')).toBe(''); - }); - - it('FE-UTIL-STRIPMD-005: strips blockquotes and lists', () => { - expect(stripMarkdown('> quoted text')).toBe('quoted text'); - expect(stripMarkdown('- item one')).toBe('item one'); - expect(stripMarkdown('1. first item')).toBe('first item'); - }); - - it('FE-UTIL-STRIPMD-006: strips strikethrough and horizontal rules', () => { - expect(stripMarkdown('~~deleted~~')).toBe('deleted'); - expect(stripMarkdown('---')).toBe(''); - }); -}); diff --git a/client/src/pages/journeyDetail/useJourneyDetail.test.tsx b/client/src/pages/journeyDetail/useJourneyDetail.test.tsx index 818788be7..c3533d3e4 100644 --- a/client/src/pages/journeyDetail/useJourneyDetail.test.tsx +++ b/client/src/pages/journeyDetail/useJourneyDetail.test.tsx @@ -1,6 +1,6 @@ -// FE-JRN-DETHOOK-001 to FE-JRN-DETHOOK-032 +// FE-JRN-DETHOOK-001 to FE-JRN-DETHOOK-039 import { describe, it, expect, beforeEach, afterEach, vi, type Mock } from 'vitest'; -import { useLocation } from 'react-router'; +import { useLocation, useSearchParams } from 'react-router'; import { delay, http, HttpResponse } from 'msw'; import { server } from '../../../tests/helpers/msw/server'; import { act, render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'; @@ -91,9 +91,12 @@ function Harness({ renderEntries = true }: { renderEntries?: boolean }) { const state = useJourneyDetail(); latest = state; const location = useLocation(); + const [, setSearchParams] = useSearchParams(); return (
    {location.search} + {/* A link into the open journal, the way the assistant chat's "Open in the journal" sends one. */} +