mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 10:24:05 +00:00
feat(journey): the enhancements from discussion #2299
roel-de-vries pitched seventeen changes to Journey. Four were already built or rest on a misunderstanding, one cannot work as described, and three would take away more than they give; the rest are here, plus two things the list did not ask for. **The entry you write on the move now has a name.** Quick capture hid the title field outright and offered a note instead, so every entry caught on a phone arrived nameless and a day's timeline read as a column of identical placeholders. One line of input; it is the single change in this branch that users will feel most. **The map stops yanking.** Stepping through the timeline called flyTo with a zoom floor of 12, so reading a journey from a country view snapped to street level on the first scroll and stayed there — every marker filling the screen, and no sense of where anything was. Both renderers pan now and leave the frame the reader chose. The initial fitBounds still decides how close a journey opens. **The phone timeline is photos.** A 64px thumbnail beside three lines of text spent the card on a story nobody reads at that size and truncated the title after a few characters. The picture is the card now, with the name and place on it, the country's flag and the date in the corners, and the day carried as a colour rather than as a number nobody was reading. Above the carousel, a segment per day: it says how long the journey is, how far in you are, and takes you to day nine without swiping past days three to eight. Everything else, briefly: - A plus in each day header, starting a draft on that day instead of on today. - A journey opens on today when today is part of it, and at the beginning when it is not — a journey that ended last spring is something you read. - Suggestions can be waved away one at a time. The row survives so the trip sync does not offer the same place again; journey settings brings them all back. - Mood, weather and the pros/cons list can be switched off per journey. Nothing written is erased — the form stops asking, the values stay. - The weather fills itself in at the desk the way it already did on the phone. The date picks the source, so writing up last Tuesday gets last Tuesday's. - Enter opens the next pro or con, below the one you are in. - The verdict moved behind the story's fold, and the fold itself came in from nine lines to four. - The external picker lost the count it was printing twice and some padding it could not afford inside the editor. - The phone can reorder entries within a day at last; the desktop arrows finally have translated labels. - Marker labels are off where a carousel already names the entry, and on where they are the only name a marker has. - Search over a journey's titles, stories, places and tags, accent-blind. - An entry knows which country it happened in, resolved once from its coordinates against the bundled boundaries. Not built, and why: the photos-for-markers idea needs clustering first or thirty markers become soup, and the active entry's photo is already on screen in the card below. Removing mood, weather and the verdict outright would take them from everyone who uses them, so they became switches. `capture` on the file picker takes the photo library away on a phone, which is why the camera is a second input; it is hidden on desktop now instead. The suggestion strip in the new-entry flow would be a third surface over the same data — tapping a suggestion already opens the editor filled in. The one gap the list missed and this branch does not close: Journey is the only domain with no offline path. That belongs in its own change.
This commit is contained in:
@@ -327,18 +327,26 @@ describe('JourneyDetailPage', () => {
|
||||
|
||||
// ── FE-PAGE-JOURNEYDETAIL-008 ──────────────────────────────────────────
|
||||
describe('FE-PAGE-JOURNEYDETAIL-008: Shows VerdictSection when entry has pros/cons', () => {
|
||||
it('renders the Pros & Cons section header', async () => {
|
||||
// The verdict moved behind the story's fold in discussion #2299: it belongs to
|
||||
// one entry, and a feed of open pro/con tables reads as a spreadsheet.
|
||||
async function openTheFold() {
|
||||
const user = userEvent.setup();
|
||||
await renderAndWait();
|
||||
await user.click(screen.getAllByText('Show more')[0]);
|
||||
}
|
||||
|
||||
it('renders the Pros & Cons section header once the entry is opened', async () => {
|
||||
await openTheFold();
|
||||
expect(screen.getByText('Pros & Cons')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders pro items', async () => {
|
||||
await renderAndWait();
|
||||
await openTheFold();
|
||||
expect(screen.getByText('Great food')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders con items', async () => {
|
||||
await renderAndWait();
|
||||
await openTheFold();
|
||||
expect(screen.getByText('Crowded')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -843,14 +851,11 @@ describe('JourneyDetailPage', () => {
|
||||
|
||||
// ── Helper: open entry editor ───────────────────────────────────────────
|
||||
async function openEntryEditor(user: ReturnType<typeof userEvent.setup>) {
|
||||
// The + button is inside the view controls row, after the tab group
|
||||
// Structure: div.justify-between > [div(tabs), button(+)]
|
||||
// The tab group div contains the Timeline/Gallery/Map buttons
|
||||
const tabGroup = screen.getByRole('button', { name: /timeline/i }).parentElement!;
|
||||
// The + button is the next sibling of the tab group
|
||||
const addBtn = tabGroup.nextElementSibling as HTMLElement;
|
||||
expect(addBtn).toBeTruthy();
|
||||
expect(addBtn.tagName).toBe('BUTTON');
|
||||
// By name rather than by position: the controls row also carries the search
|
||||
// box now, so "next sibling of the tab group" stopped being the + button
|
||||
// (discussion #2299). The day headers' own plus buttons are labelled "Add an
|
||||
// entry on this day" and do not answer to this.
|
||||
const addBtn = screen.getByRole('button', { name: /^add entry$/i });
|
||||
|
||||
await user.click(addBtn);
|
||||
|
||||
@@ -922,10 +927,11 @@ describe('JourneyDetailPage', () => {
|
||||
await renderAndWait();
|
||||
await openEntryEditor(user);
|
||||
|
||||
// The editor shows "Pros & Cons" label (displayed uppercase via CSS class)
|
||||
// The timeline view already shows "Pros & Cons" from the first entry, so use getAllByText
|
||||
// The editor shows "Pros & Cons" label (displayed uppercase via CSS class).
|
||||
// Exactly one: the timeline's copy sits behind the entry's fold now, and this
|
||||
// test never opens it (discussion #2299).
|
||||
const prosConsLabels = screen.getAllByText('Pros & Cons');
|
||||
expect(prosConsLabels.length).toBeGreaterThanOrEqual(2);
|
||||
expect(prosConsLabels).toHaveLength(1);
|
||||
// It also shows sub-labels Pros and Cons
|
||||
expect(screen.getByText('Pros')).toBeInTheDocument();
|
||||
expect(screen.getByText('Cons')).toBeInTheDocument();
|
||||
@@ -2197,13 +2203,13 @@ describe('JourneyDetailPage', () => {
|
||||
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
|
||||
await openGalleryWithProvider(user);
|
||||
|
||||
// Footer shows "0 selected" initially
|
||||
// The count lives on the Add button alone now: the separate "N selected" pill
|
||||
// beside it said the same thing twice and cost the grid a row (#2299).
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('selected')).toBeInTheDocument();
|
||||
expect(screen.queryByText('selected')).toBeNull();
|
||||
});
|
||||
|
||||
// Add button shows "Add" (disabled when 0 selected)
|
||||
const addBtn = screen.getByRole('button', { name: /^Add/ });
|
||||
const addBtn = screen.getByRole('button', { name: /^Add$/ });
|
||||
expect(addBtn).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -2754,7 +2760,7 @@ describe('JourneyDetailPage', () => {
|
||||
|
||||
// After selection, the Add button should show count
|
||||
await waitFor(() => {
|
||||
const addBtn = screen.getByRole('button', { name: /^Add/ });
|
||||
const addBtn = screen.getByRole('button', { name: /^Add \(\d+\)$/ });
|
||||
expect(addBtn.textContent).toContain('1');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@ import EmptyState from '../components/shared/EmptyState'
|
||||
import { Outlet } from 'react-router'
|
||||
import {
|
||||
ArrowLeft, MoreHorizontal, List, Grid, MapPin,
|
||||
Plus, ChevronUp, ChevronDown, Eye, EyeOff, BookOpen, Image,
|
||||
Plus, ChevronUp, ChevronDown, Eye, EyeOff, BookOpen, Image, Search, X,
|
||||
} from 'lucide-react'
|
||||
import MobileMapTimeline from '../components/Journey/MobileMapTimeline'
|
||||
import DawarichSuggestionsPanel from '../components/Dawarich/DawarichSuggestionsPanel'
|
||||
@@ -18,7 +18,7 @@ import MobileEntryView from '../components/Journey/MobileEntryView'
|
||||
import { useJourneyStore } from '../store/journeyStore'
|
||||
import { computeJourneyLifecycle } from '../utils/journeyLifecycle'
|
||||
import { useJourneyDetail } from './journeyDetail/useJourneyDetail'
|
||||
import { createDraftJourneyEntry, pickGradient, groupByDate, formatDate, photoUrl } from './journeyDetail/JourneyDetailPage.helpers'
|
||||
import { createDraftJourneyEntry, pickGradient, groupByDate, formatDate, photoUrl, matchJourneyEntries } from './journeyDetail/JourneyDetailPage.helpers'
|
||||
import { EntryCard, SkeletonCard, CheckinCard } from '../components/Journey/JourneyDetailPageEntryCard'
|
||||
import { GalleryView } from '../components/Journey/JourneyDetailPageGalleryView'
|
||||
import { EntryEditor } from '../components/Journey/JourneyDetailPageEntryEditor'
|
||||
@@ -45,6 +45,7 @@ function JourneyDetailPageDesktop() {
|
||||
showInvite, setShowInvite, showAddTrip, setShowAddTrip,
|
||||
unlinkTrip, setUnlinkTrip, showSettings, setShowSettings,
|
||||
hideSkeletons, setHideSkeletons,
|
||||
query, setQuery, dismissSuggestion, restoreSuggestions, openAtEntryId,
|
||||
mapRef, fullMapRef, galleryUploadRef, galleryProviders, setGalleryProviders, galleryBrowseRef,
|
||||
activeLocationId, handleMarkerClick, handleLocationClick,
|
||||
mapEntries, sidebarMapItems, tripDates, isMobile, tracks,
|
||||
@@ -63,7 +64,10 @@ function JourneyDetailPageDesktop() {
|
||||
)
|
||||
}
|
||||
|
||||
const timelineEntries = current.entries.filter(e => (!hideSkeletons || e.type !== 'skeleton'))
|
||||
const timelineEntries = matchJourneyEntries(
|
||||
current.entries.filter(e => (!hideSkeletons || e.type !== 'skeleton')),
|
||||
query,
|
||||
)
|
||||
const dayGroups = groupByDate(timelineEntries)
|
||||
const sortedDates = [...dayGroups.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
|
||||
|
||||
@@ -133,6 +137,9 @@ function JourneyDetailPageDesktop() {
|
||||
onAddEntry={canEditEntries ? () => {
|
||||
setEditingEntry(createDraftJourneyEntry(current.id))
|
||||
} : undefined}
|
||||
showMood={current.show_mood !== 0}
|
||||
showWeather={current.show_weather !== 0}
|
||||
initialEntryId={openAtEntryId}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -362,6 +369,30 @@ function JourneyDetailPageDesktop() {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{/* Search. A journey kept over a season is a very long scroll, and the
|
||||
wheel was the only way through it (discussion #2299). Grows on focus
|
||||
rather than standing open at full width, so it costs the row nothing
|
||||
until it is used. */}
|
||||
{view === 'timeline' && !isMobile && (
|
||||
<div
|
||||
className="inline-flex items-center gap-1.5 h-9 rounded-full px-3 transition-[width] duration-200"
|
||||
style={{ background: 'var(--vg-surf2)', border: '1px solid var(--vg-line)', width: query ? 240 : 150 }}
|
||||
>
|
||||
<Search size={14} style={{ color: 'var(--vg-ink3)' }} className="flex-shrink-0" />
|
||||
<input
|
||||
value={query}
|
||||
onChange={e => setQuery(e.target.value)}
|
||||
placeholder={t('journey.detail.searchPlaceholder')}
|
||||
className="min-w-0 flex-1 bg-transparent text-[12.5px] outline-none"
|
||||
style={{ color: 'var(--vg-ink)' }}
|
||||
/>
|
||||
{query && (
|
||||
<button type="button" onClick={() => setQuery('')} aria-label={t('common.clear')} className="flex-shrink-0">
|
||||
<X size={13} style={{ color: 'var(--vg-ink3)' }} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{canEditEntries && view === 'timeline' && (
|
||||
<button type="button"
|
||||
onClick={() => {
|
||||
@@ -394,7 +425,10 @@ function JourneyDetailPageDesktop() {
|
||||
)}
|
||||
|
||||
{sortedDates.length === 0 && (
|
||||
<EmptyState scene="journey" title={t('journey.detail.noEntries')} />
|
||||
<EmptyState
|
||||
scene="journey"
|
||||
title={query ? t('journey.detail.searchEmpty', { query }) : t('journey.detail.noEntries')}
|
||||
/>
|
||||
)}
|
||||
|
||||
{sortedDates.map((date, dayIdx) => {
|
||||
@@ -411,7 +445,23 @@ function JourneyDetailPageDesktop() {
|
||||
</div>
|
||||
<h3 className="text-[14px] font-semibold capitalize" style={{ color: 'var(--vg-ink)' }}>{new Date(date + 'T00:00:00').toLocaleDateString(undefined, { weekday: 'long', day: 'numeric', month: 'long' })}</h3>
|
||||
</div>
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-[0.07em]" style={{ background: 'var(--vg-surf2)', color: 'var(--vg-ink3)' }}><MapPin size={12} /> {entries.length} {t('journey.synced.places')}</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-[0.07em]" style={{ background: 'var(--vg-surf2)', color: 'var(--vg-ink3)' }}><MapPin size={12} /> {entries.length} {t('journey.synced.places')}</span>
|
||||
{/* The only Add button used to be at the very top and always
|
||||
started on today, so putting something into an earlier day
|
||||
meant correcting the date by hand (discussion #2299). */}
|
||||
{canEditEntries && (
|
||||
<button type="button"
|
||||
onClick={() => setEditingEntry(createDraftJourneyEntry(current.id, new Date(), date))}
|
||||
aria-label={t('journey.detail.addOnThisDay')}
|
||||
title={t('journey.detail.addOnThisDay')}
|
||||
className="w-7 h-7 rounded-full flex items-center justify-center transition-colors hover:bg-surface-hover"
|
||||
style={{ background: 'var(--vg-surf2)', color: 'var(--vg-ink)' }}
|
||||
>
|
||||
<Plus size={14} strokeWidth={2.6} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{entries.map((entry, idx) => {
|
||||
@@ -438,7 +488,7 @@ function JourneyDetailPageDesktop() {
|
||||
type="button"
|
||||
onClick={() => move(-1)}
|
||||
disabled={idx === 0}
|
||||
aria-label="Move up"
|
||||
aria-label={t('dayplan.moveUp')}
|
||||
className="w-7 h-7 rounded-full bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 shadow-sm text-zinc-600 dark:text-zinc-300 flex items-center justify-center hover:bg-zinc-50 dark:hover:bg-zinc-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
<ChevronUp size={14} />
|
||||
@@ -447,7 +497,7 @@ function JourneyDetailPageDesktop() {
|
||||
type="button"
|
||||
onClick={() => move(1)}
|
||||
disabled={idx === entries.length - 1}
|
||||
aria-label="Move down"
|
||||
aria-label={t('dayplan.moveDown')}
|
||||
className="w-7 h-7 rounded-full bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 shadow-sm text-zinc-600 dark:text-zinc-300 flex items-center justify-center hover:bg-zinc-50 dark:hover:bg-zinc-700 disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
|
||||
>
|
||||
<ChevronDown size={14} />
|
||||
@@ -456,7 +506,11 @@ function JourneyDetailPageDesktop() {
|
||||
)}
|
||||
<div className={canReorder ? 'flex-1 min-w-0' : ''}>
|
||||
{entry.type === 'skeleton' ? (
|
||||
<SkeletonCard entry={entry} onClick={canEditEntries ? () => setEditingEntry(entry) : undefined} />
|
||||
<SkeletonCard
|
||||
entry={entry}
|
||||
onClick={canEditEntries ? () => setEditingEntry(entry) : undefined}
|
||||
onDismiss={canEditEntries ? () => dismissSuggestion(entry) : undefined}
|
||||
/>
|
||||
) : entry.type === 'checkin' ? (
|
||||
<CheckinCard entry={entry} onClick={canEditEntries ? () => setEditingEntry(entry) : undefined} />
|
||||
) : (
|
||||
@@ -585,6 +639,9 @@ function JourneyDetailPageDesktop() {
|
||||
onUploadPhotos={async (entryId, files, cbs) => {
|
||||
return await uploadPhotos(entryId, files, cbs)
|
||||
}}
|
||||
showVerdict={current.show_verdict !== 0}
|
||||
showMood={current.show_mood !== 0}
|
||||
showWeather={current.show_weather !== 0}
|
||||
onAddProviderPhotos={async (entryId, group) => {
|
||||
await journeyApi.addProviderPhotos(entryId, group.provider, group.assetIds, undefined, group.passphrase, group.mediaTypes)
|
||||
}}
|
||||
@@ -603,6 +660,7 @@ function JourneyDetailPageDesktop() {
|
||||
onSaved={() => { setShowSettings(false); loadJourney(Number(id)) }}
|
||||
onOpenInvite={() => { setShowInvite(true) }}
|
||||
onRefresh={() => loadJourney(Number(id))}
|
||||
onRestoreSuggestions={canEditEntries ? restoreSuggestions : undefined}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -98,6 +98,8 @@ function buildHook(over: Record<string, unknown> = {}): Record<string, unknown>
|
||||
unlinkTrip: null, setUnlinkTrip: vi.fn(),
|
||||
showSettings: false, setShowSettings: vi.fn(),
|
||||
hideSkeletons: false, setHideSkeletons: vi.fn(),
|
||||
query: '', setQuery: vi.fn(), dismissSuggestion: vi.fn(async () => {}),
|
||||
restoreSuggestions: vi.fn(async () => {}), openAtEntryId: null,
|
||||
mapRef: { current: null }, fullMapRef: { current: null }, galleryUploadRef: { current: null },
|
||||
galleryProviders: [], setGalleryProviders: vi.fn(), galleryBrowseRef: { current: null },
|
||||
activeLocationId: null, handleMarkerClick: vi.fn(), handleLocationClick: vi.fn(),
|
||||
@@ -231,21 +233,21 @@ describe('JourneyDetailPage wiring', () => {
|
||||
|
||||
it('FE-JRN-DETWIRE-011: the reorder arrows move an entry within its day', async () => {
|
||||
const { hook } = setup();
|
||||
const down = screen.getAllByRole('button', { name: 'Move down' })[0];
|
||||
const upFirst = screen.getAllByRole('button', { name: 'Move up' })[0];
|
||||
const down = screen.getAllByRole('button', { name: 'dayplan.moveDown' })[0];
|
||||
const upFirst = screen.getAllByRole('button', { name: 'dayplan.moveUp' })[0];
|
||||
expect(upFirst).toBeDisabled();
|
||||
|
||||
fireEvent.click(down);
|
||||
await waitFor(() => expect(hook.reorderEntries).toHaveBeenCalledWith(7, [2, 1]));
|
||||
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'Move up' })[1]);
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'dayplan.moveUp' })[1]);
|
||||
expect(hook.reorderEntries).toHaveBeenLastCalledWith(7, [2, 1]);
|
||||
});
|
||||
|
||||
it('FE-JRN-DETWIRE-012: a failing reorder is reported to the user', async () => {
|
||||
const reorderEntries = vi.fn(async () => { throw new Error('conflict'); });
|
||||
setup({ reorderEntries });
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'Move down' })[0]);
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'dayplan.moveDown' })[0]);
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('common.errorOccurred'));
|
||||
});
|
||||
|
||||
|
||||
@@ -828,6 +828,8 @@ export default function JourneyPublicPage() {
|
||||
publicPhotoUrl={(photoId) => `/api/public/journey/${token}/photos/${photoId}/original`}
|
||||
carouselBottom="calc(env(safe-area-inset-bottom, 16px) + 8px)"
|
||||
cartoApiKey={cartoApiKey}
|
||||
showMood={journey.show_mood !== 0}
|
||||
showWeather={journey.show_weather !== 0}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { distanceBetweenGeoPoints, groupPhotosByDate, sortProviderPhotos } from './JourneyDetailPage.helpers';
|
||||
import {
|
||||
createDraftJourneyEntry,
|
||||
distanceBetweenGeoPoints,
|
||||
groupPhotosByDate,
|
||||
matchJourneyEntries,
|
||||
sortProviderPhotos,
|
||||
} from './JourneyDetailPage.helpers';
|
||||
|
||||
describe('Journey provider photo ranking', () => {
|
||||
it('places GPS photos nearest the selected Journey location and keeps photos without GPS', () => {
|
||||
@@ -61,3 +67,49 @@ describe('Journey provider photo grouping', () => {
|
||||
expect(groupPhotosByDate(photos).map((g) => g.date)).toEqual(['2026-03-16', '__unknown__']);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe('createDraftJourneyEntry', () => {
|
||||
it('starts on today when nobody says otherwise', () => {
|
||||
const draft = createDraftJourneyEntry(7, new Date('2026-03-15T14:30:00'));
|
||||
expect(draft.entry_date).toBe('2026-03-15');
|
||||
expect(draft.entry_time).toBe('14:30');
|
||||
});
|
||||
|
||||
it('takes the day it was started from, so a plus in an earlier day header lands there', () => {
|
||||
// The whole point of the day-header plus: it used to open on today no matter
|
||||
// where in the journal you pressed it (discussion #2299).
|
||||
const draft = createDraftJourneyEntry(7, new Date('2026-03-15T14:30:00'), '2026-03-09');
|
||||
expect(draft.entry_date).toBe('2026-03-09');
|
||||
expect(draft.entry_time).toBe('14:30');
|
||||
});
|
||||
});
|
||||
|
||||
describe('matchJourneyEntries', () => {
|
||||
const entries = [
|
||||
{ id: 1, title: 'Mercado da Ribeira', story: 'Ate too much', location_name: 'Lisbon', tags: ['food'] },
|
||||
{ id: 2, title: 'Tram 28', story: null, location_name: 'Lisbon', tags: [] },
|
||||
{ id: 3, title: null, story: 'Long drive north', location_name: 'Café Central, Porto', tags: ['drive'] },
|
||||
];
|
||||
|
||||
it('an empty query is not a filter', () => {
|
||||
expect(matchJourneyEntries(entries, '')).toBe(entries);
|
||||
expect(matchJourneyEntries(entries, ' ')).toBe(entries);
|
||||
});
|
||||
|
||||
it('matches the words a reader would remember: title, story, place and tags', () => {
|
||||
expect(matchJourneyEntries(entries, 'mercado').map((e) => e.id)).toEqual([1]);
|
||||
expect(matchJourneyEntries(entries, 'drive').map((e) => e.id)).toEqual([3]);
|
||||
expect(matchJourneyEntries(entries, 'lisbon').map((e) => e.id)).toEqual([1, 2]);
|
||||
expect(matchJourneyEntries(entries, 'food').map((e) => e.id)).toEqual([1]);
|
||||
});
|
||||
|
||||
it('is blind to case and to accents, so a query typed plainly still finds the place', () => {
|
||||
expect(matchJourneyEntries(entries, 'cafe').map((e) => e.id)).toEqual([3]);
|
||||
expect(matchJourneyEntries(entries, 'CAFÉ').map((e) => e.id)).toEqual([3]);
|
||||
});
|
||||
|
||||
it('answers with nothing rather than everything when nothing matches', () => {
|
||||
expect(matchJourneyEntries(entries, 'reykjavik')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -29,8 +29,18 @@ export function groupByDate(entries: JourneyEntry[]): Map<string, JourneyEntry[]
|
||||
return groups;
|
||||
}
|
||||
|
||||
export function createDraftJourneyEntry(journeyId: number, now = new Date()): JourneyEntry {
|
||||
const entryDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
|
||||
/**
|
||||
* A blank entry for the editor to open on.
|
||||
*
|
||||
* `onDate` is what the plus button in a day header hands in. Without it every new
|
||||
* entry landed on today no matter where in the journal you started it, so
|
||||
* writing up the third day of a trip you got back from last week meant correcting
|
||||
* the date by hand every time (discussion #2299). The clock still comes from now:
|
||||
* a day has one date but no one obvious hour, and the picker is right there.
|
||||
*/
|
||||
export function createDraftJourneyEntry(journeyId: number, now = new Date(), onDate?: string): JourneyEntry {
|
||||
const entryDate = onDate
|
||||
|| `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
|
||||
const entryTime = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
|
||||
return {
|
||||
id: 0,
|
||||
@@ -167,3 +177,33 @@ export function sortProviderPhotos<T extends ProviderPhotoAsset>(photos: T[], lo
|
||||
})
|
||||
.map((item) => item.photo);
|
||||
}
|
||||
|
||||
/**
|
||||
* The entries a search box's text still lets through.
|
||||
*
|
||||
* A journey kept over months is a long scroll with no way in but the wheel: the
|
||||
* only handle on "where was that meal in Lisbon" was remembering roughly which
|
||||
* week it was (discussion #2299). Matching runs over the words the reader would
|
||||
* actually remember — the title, the story, the place and the tags — and is
|
||||
* accent- and case-blind, so `cafe` finds `Café`.
|
||||
*
|
||||
* An empty query is not a filter: it returns the list untouched, same reference.
|
||||
*/
|
||||
export function matchJourneyEntries<T extends {
|
||||
title?: string | null;
|
||||
story?: string | null;
|
||||
location_name?: string | null;
|
||||
tags?: string[];
|
||||
}>(entries: T[], query: string): T[] {
|
||||
const needle = query ? foldForSearch(query) : '';
|
||||
if (!needle) return entries;
|
||||
return entries.filter((entry) => {
|
||||
const haystack = [entry.title, entry.story, entry.location_name, ...(entry.tags ?? [])];
|
||||
return haystack.some((part) => part && foldForSearch(part).includes(needle));
|
||||
});
|
||||
}
|
||||
|
||||
/** Lowercase and strip diacritics, so a query typed without accents still matches. */
|
||||
function foldForSearch(value: string): string {
|
||||
return value.trim().toLowerCase().normalize('NFD').replace(/\p{Diacritic}/gu, '');
|
||||
}
|
||||
|
||||
@@ -71,6 +71,7 @@ export function useJourneyDetail() {
|
||||
const [unlinkTrip, setUnlinkTrip] = useState<{ trip_id: number; title: string } | null>(null)
|
||||
const [showSettings, setShowSettings] = useState(false)
|
||||
const [hideSkeletons, setHideSkeletons] = useState(false)
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (id) loadJourney(Number(id)).catch(() => {})
|
||||
@@ -269,6 +270,34 @@ export function useJourneyDetail() {
|
||||
el.scrollTo({ top: edge === 'top' ? 0 : el.scrollHeight, behavior: 'smooth' })
|
||||
}, [])
|
||||
|
||||
/**
|
||||
* Wave one trip-derived suggestion away.
|
||||
*
|
||||
* Optimistic in effect rather than in code: the server drops the row from every
|
||||
* read, and the store's own update already removes an entry the response no
|
||||
* longer describes — so a reload is all the confirmation the list needs.
|
||||
*/
|
||||
const dismissSuggestion = useCallback(async (entry: JourneyEntry) => {
|
||||
try {
|
||||
await updateEntry(entry.id, { dismissed: true })
|
||||
if (current) await loadJourney(current.id)
|
||||
toast.success(t('journey.suggestions.dismissed'))
|
||||
} catch {
|
||||
toast.error(t('common.errorOccurred'))
|
||||
}
|
||||
}, [updateEntry, loadJourney, current, toast, t])
|
||||
|
||||
const restoreSuggestions = useCallback(async () => {
|
||||
if (!current) return
|
||||
try {
|
||||
const { restored } = await journeyApi.restoreSuggestions(current.id)
|
||||
await loadJourney(current.id)
|
||||
toast.success(t('journey.suggestions.restored', { count: String(restored) }))
|
||||
} catch {
|
||||
toast.error(t('common.errorOccurred'))
|
||||
}
|
||||
}, [current, loadJourney, toast, t])
|
||||
|
||||
const handleMarkerClick = useCallback((entryId: string) => {
|
||||
const el = document.querySelector(`[data-entry-id="${entryId}"]`)
|
||||
if (!el) return
|
||||
@@ -351,6 +380,53 @@ export function useJourneyDetail() {
|
||||
})
|
||||
}, [mapEntries, current?.entries])
|
||||
|
||||
/**
|
||||
* Where a journey should open: on today, when today is part of it.
|
||||
*
|
||||
* Every load used to start at the first entry, so keeping a journal on a trip
|
||||
* meant scrolling past everything already written before you could add to it
|
||||
* (discussion #2299). "Today" means the last day at or before now — a rest day
|
||||
* with nothing written still lands you at yesterday rather than at the start.
|
||||
*
|
||||
* Only while the journey is running, though. A journey that ended last spring
|
||||
* is something you read, and reading starts at the beginning; opening it at the
|
||||
* last page would be the worse of the two mistakes.
|
||||
*/
|
||||
const openAtEntryId = useMemo(() => {
|
||||
const entries = current?.entries ?? []
|
||||
if (entries.length === 0) return null
|
||||
const dated = [...entries].sort((a, b) => a.entry_date.localeCompare(b.entry_date))
|
||||
const today = new Date()
|
||||
const todayKey = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
|
||||
const first = dated[0]!.entry_date
|
||||
const last = dated[dated.length - 1]!.entry_date
|
||||
if (todayKey < first || todayKey > last) return null
|
||||
const reached = dated.filter(e => e.entry_date <= todayKey)
|
||||
const target = reached[reached.length - 1] ?? dated[0]!
|
||||
// The first entry OF that day, not the last one before now: a day is read
|
||||
// from its beginning.
|
||||
const dayStart = dated.find(e => e.entry_date === target.entry_date) ?? target
|
||||
return String(dayStart.id)
|
||||
}, [current?.entries])
|
||||
|
||||
// Desktop only: scroll it into the feed once per journey, after the list is up.
|
||||
// The scroll-sync primes at 300ms and would otherwise pick a winner from the top
|
||||
// of the feed and pin the map there.
|
||||
const openedAtRef = useRef<number | null>(null)
|
||||
useEffect(() => {
|
||||
if (isMobile || !current || view !== 'timeline') return
|
||||
if (openedAtRef.current === current.id) return
|
||||
if (!openAtEntryId) { openedAtRef.current = current.id; return }
|
||||
const timer = window.setTimeout(() => {
|
||||
const el = document.querySelector(`[data-entry-id="${openAtEntryId}"]`)
|
||||
if (!el) return
|
||||
openedAtRef.current = current.id
|
||||
el.scrollIntoView({ block: 'center' })
|
||||
setActiveEntryId(openAtEntryId)
|
||||
}, 350)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [current, openAtEntryId, isMobile, view])
|
||||
|
||||
const locatedEntryIdsRef = useRef(new Set<string>())
|
||||
useEffect(() => {
|
||||
locatedEntryIdsRef.current = new Set(sidebarMapItems.map(m => m.id))
|
||||
@@ -423,6 +499,8 @@ export function useJourneyDetail() {
|
||||
showInvite, setShowInvite, showAddTrip, setShowAddTrip,
|
||||
unlinkTrip, setUnlinkTrip, showSettings, setShowSettings,
|
||||
hideSkeletons, setHideSkeletons,
|
||||
query, setQuery, dismissSuggestion, restoreSuggestions,
|
||||
openAtEntryId,
|
||||
mapRef, fullMapRef, galleryUploadRef, galleryProviders, setGalleryProviders, galleryBrowseRef,
|
||||
activeLocationId, handleMarkerClick, handleLocationClick,
|
||||
mapEntries, sidebarMapItems, tripDates, isMobile, tracks: mapTracks, dawarichTrail,
|
||||
|
||||
Reference in New Issue
Block a user