diff --git a/client/scripts/feature-pairs.json b/client/scripts/feature-pairs.json index d5a6c160e..19fe7a7f7 100644 --- a/client/scripts/feature-pairs.json +++ b/client/scripts/feature-pairs.json @@ -303,6 +303,18 @@ "desktop": ["src/components/Collections/CollectionLocationSearch.tsx"], "mobile": ["src/mobile/screens/collections/MCollLocationSearch.tsx"] }, + { + "feature": "Places: a place of all places", + "hooks": ["src/components/Collections/libraryDates.ts"], + "desktop": ["src/components/Collections/LibraryPlaceDetail.tsx"], + "mobile": ["src/mobile/screens/collections/MLibraryPlaceSheet.tsx"] + }, + { + "feature": "Places: all places", + "hooks": ["src/components/Collections/usePlacesLibrary.ts"], + "desktop": ["src/components/Collections/PlacesLibraryView.tsx"], + "mobile": ["src/mobile/screens/collections/MPlacesLibrary.tsx"] + }, { "feature": "Collection sharing", "hooks": ["src/components/Collections/useCollectionSharing.ts"], @@ -1132,6 +1144,7 @@ } ], "mobileOnly": { + "src/mobile/screens/collections/MCollFilterKit.tsx": "Markup only: the filter chips, dropdown rows and empty note the phone's lists and all-places screens share; the desktop draws its own filter row (FilterDropdown).", "src/mobile/screens/trip/sheets/MReviewNotice.tsx": "The transport sheet's row asking for a look at an imported booking; the desktop dialog folds the same \"looks right\" action into its review pill (ReviewPill in bookingParts.tsx), so there is no separate twin.", "src/mobile/screens/mail/MMailInboxHost.tsx": "Mounts the phone shell's one inbox sheet and reads the person's import settings; the desktop mounts its dialog from the Navbar, so there is no twin.", "src/mobile/screens/admin/MAdminOidcCard.tsx": "Markup only; the OIDC card of MAdminSettingsSection, with the form state from useAdmin and the save from its useAdminSettingsActions handed in through props.", diff --git a/client/scripts/rtl-baseline.json b/client/scripts/rtl-baseline.json index 62b7815b6..c32868824 100644 --- a/client/scripts/rtl-baseline.json +++ b/client/scripts/rtl-baseline.json @@ -24,8 +24,8 @@ "components/Map/DawarichTrailPill.tsx": 1, "components/Map/LocationButton.tsx": 1, "components/Map/MapTogglePill.tsx": 1, - "components/Map/MapView.tsx": 5, - "components/Map/MapViewGL.tsx": 7, + "components/Map/MapView.tsx": 4, + "components/Map/MapViewGL.tsx": 6, "components/Map/NightPauseTooltip.tsx": 1, "components/Map/PlaceHoverCard.tsx": 1, "components/Map/PoiCategoryPill.tsx": 1, diff --git a/client/src/App.tsx b/client/src/App.tsx index d7f64da73..f4f474b23 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -1,5 +1,6 @@ import React, { useEffect, useLayoutEffect, useState, useRef, ReactNode, Suspense } from 'react' import { Routes, Route, Navigate, useLocation, useNavigationType } from 'react-router' +import LegacyCollectionsRedirect from './components/Collections/LegacyCollectionsRedirect' import { useAuthStore } from './store/authStore' import { useSettingsStore } from './store/settingsStore' import { applyAppearance } from './theme/applyAppearance' @@ -637,22 +638,20 @@ export default function App() { journey, not navigated away to. */} } /> - - - - } - /> - - - - } - /> + {['/places', '/places/saved', '/places/:id'].map(path => ( + + + + } + /> + ))} + {/* Collections became Places (PLC-07); the old links keep working. */} + } /> + } /> { folders: ['Views'], skipped: [{ name: 'Tram 28', folder: null, reason: 'line' }], } - let upload: File | null = null + let contentType: string | null = null server.use( - http.post(`${BASE}/map/read`, async ({ request }) => { - upload = (await request.formData()).get('file') as File | null + // jsdom cannot read a multipart body back, so the header says what was sent. + http.post(`${BASE}/map/read`, ({ request }) => { + contentType = request.headers.get('content-type') return HttpResponse.json(read) }), ) const res = await collectionsApi.readMap(new File([''], 'lisbon.kml')) - expect(upload).not.toBeNull() - expect((upload as unknown as File).name).toBe('lisbon.kml') + expect(contentType).toMatch(/^multipart\/form-data/) expect(res).toEqual(read) }) }) diff --git a/client/src/components/Assistant/AssistantAskButton.test.tsx b/client/src/components/Assistant/AssistantAskButton.test.tsx index b094e2365..862f4deae 100644 --- a/client/src/components/Assistant/AssistantAskButton.test.tsx +++ b/client/src/components/Assistant/AssistantAskButton.test.tsx @@ -50,7 +50,7 @@ describe('AssistantAskButton', () => { expect(screen.queryByRole('button')).not.toBeInTheDocument(); unmount(); - renderAt('/collections/3'); + renderAt('/places/3'); expect(screen.queryByRole('button')).not.toBeInTheDocument(); }); }); diff --git a/client/src/components/Assistant/cards/collection/CollectionCardBlocks.test.tsx b/client/src/components/Assistant/cards/collection/CollectionCardBlocks.test.tsx index 0188a6a32..7140a1c40 100644 --- a/client/src/components/Assistant/cards/collection/CollectionCardBlocks.test.tsx +++ b/client/src/components/Assistant/cards/collection/CollectionCardBlocks.test.tsx @@ -54,7 +54,7 @@ describe('collection answer cards', () => { expect(within(card).getByText('Idea')).toBeInTheDocument(); expect(within(card).getByText('3')).toBeInTheDocument(); fireEvent.click(within(card).getByRole('button', { name: /Open list/ })); - expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/collections/12' }); + expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/places/12' }); }); it('FE-AI-COLL-040: the places to revisit have a pill of their own in the head, in the visited tone (#2567)', () => { @@ -86,7 +86,7 @@ describe('collection answer cards', () => { expect(screen.getByText('Spot 4')).toBeInTheDocument(); expect(screen.queryByText('Spot 5')).toBeNull(); fireEvent.click(screen.getByRole('button', { name: '7 more in this list' })); - expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/collections/12' }); + expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/places/12' }); }); it('FE-AI-COLL-013: a roomy chat shows eight rows', () => { @@ -144,7 +144,7 @@ describe('collection answer cards', () => { expect(screen.queryByText('Paris food')).toBeNull(); expect(screen.getByText('Invite from Maya')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: /Rome/ })); - expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/collections/40' }); + expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/places/40' }); }); it('FE-AI-COLL-018: where a place is saved reads as its lists with its status in each', () => { diff --git a/client/src/components/Assistant/cards/collection/CollectionChangeSlots.test.tsx b/client/src/components/Assistant/cards/collection/CollectionChangeSlots.test.tsx index aa83c4d2b..c42d21630 100644 --- a/client/src/components/Assistant/cards/collection/CollectionChangeSlots.test.tsx +++ b/client/src/components/Assistant/cards/collection/CollectionChangeSlots.test.tsx @@ -94,7 +94,7 @@ describe('collection change cards', () => { const view = draw([applied(pending('save_place_to_collection', 'Septime', card), 'collection_place', [77])]); expect(screen.queryByRole('button', { name: 'Show on map' })).toBeNull(); fireEvent.click(screen.getByRole('button', { name: 'Open in Collections' })); - expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/collections/12?place=77' }); + expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/places/12?place=77' }); }); it('FE-AI-COLL-023: a save the place matched already says where it is saved', () => { diff --git a/client/src/components/Assistant/cards/collection/collectionCardModel.ts b/client/src/components/Assistant/cards/collection/collectionCardModel.ts index 1f02961da..e0ede3662 100644 --- a/client/src/components/Assistant/cards/collection/collectionCardModel.ts +++ b/client/src/components/Assistant/cards/collection/collectionCardModel.ts @@ -8,6 +8,7 @@ import type { TrekCard, } from '@trek/shared'; +import { placesPath } from '../../../../utils/placesRoutes'; import type { EntityTarget } from '../cardTypes'; /** @@ -26,12 +27,12 @@ export const MAX_FACTS = 4; /** Where a list opens in Collections. */ export function listTarget(listId: number | null): EntityTarget { - return { kind: 'page', path: listId === null ? '/collections' : `/collections/${listId}` }; + return { kind: 'page', path: placesPath(listId === null ? 'saved' : listId) }; } /** Where a saved place opens: its list, with the place selected. */ function placeTarget(listId: number, placeId: number | null): EntityTarget { - const path = `/collections/${listId}`; + const path = placesPath(listId); return { kind: 'page', path: placeId === null ? path : `${path}?place=${placeId}` }; } diff --git a/client/src/components/Assistant/cards/collection/collectionLook.test.ts b/client/src/components/Assistant/cards/collection/collectionLook.test.ts index b0fe99c63..3d2e43260 100644 --- a/client/src/components/Assistant/cards/collection/collectionLook.test.ts +++ b/client/src/components/Assistant/cards/collection/collectionLook.test.ts @@ -62,9 +62,9 @@ describe('collection look', () => { it('FE-AI-COLL-002: an applied list opens in Collections, unless the change deleted it or declined its invite', () => { const look = ENTITY_LOOK.collection; expect(look.openLabelKey).toBe('assistant.card.collection.openList'); - expect(look.open?.(applied('collection', [12]), null)).toEqual({ kind: 'page', path: '/collections/12' }); + expect(look.open?.(applied('collection', [12]), null)).toEqual({ kind: 'page', path: '/places/12' }); const card = listsCard({ lists: [listRow({ id: 13 })] }); - expect(look.open?.(applied('collection', []), card)).toEqual({ kind: 'page', path: '/collections/13' }); + expect(look.open?.(applied('collection', []), card)).toEqual({ kind: 'page', path: '/places/13' }); for (const change of ['remove', 'decline'] as const) { expect(look.open?.(applied('collection', [12]), listsCard({ lists: [listRow({ change })] }))).toBeNull(); } @@ -76,10 +76,10 @@ describe('collection look', () => { const card = placesCard(); expect(look.open?.(applied('collection_place', [34]), card)).toEqual({ kind: 'page', - path: '/collections/12?place=34', + path: '/places/12?place=34', }); const removed = placesCard({ places: [savedPlace({ delta: emptyDelta({ removed: true }) })] }); - expect(look.open?.(applied('collection_place', [34]), removed)).toEqual({ kind: 'page', path: '/collections/12' }); + expect(look.open?.(applied('collection_place', [34]), removed)).toEqual({ kind: 'page', path: '/places/12' }); expect(look.open?.(applied('collection_place', [34]), null)).toBeNull(); }); diff --git a/client/src/components/Collections/AddPlaceToCollectionModal.test.tsx b/client/src/components/Collections/AddPlaceToCollectionModal.test.tsx index 161521f80..ea2bf3370 100644 --- a/client/src/components/Collections/AddPlaceToCollectionModal.test.tsx +++ b/client/src/components/Collections/AddPlaceToCollectionModal.test.tsx @@ -308,13 +308,17 @@ describe('AddPlaceToCollectionModal', () => { it('FE-COMP-ADDPLACECOL-018: a category can be picked and cleared again', async () => { setup() typeName('Manual spot') - fireEvent.click(screen.getByRole('button', { name: /Food/ })) - fireEvent.click(screen.getByRole('button', { name: /Museum/ })) + // The category is the tile in front of the name; it opens the list to pick from. + fireEvent.click(screen.getByRole('button', { name: 'Category: No category' })) + fireEvent.click(screen.getByRole('option', { name: 'Food' })) + fireEvent.click(screen.getByRole('button', { name: 'Category: Food' })) + fireEvent.click(screen.getByRole('option', { name: 'Museum' })) fireEvent.click(screen.getByRole('button', { name: /Add$/ })) await waitFor(() => expect(savedBodies).toHaveLength(1)) expect(savedBodies[0]).toMatchObject({ category_id: 4 }) - fireEvent.click(screen.getByRole('button', { name: 'No category' })) + fireEvent.click(screen.getByRole('button', { name: /^Category: / })) + fireEvent.click(screen.getByRole('option', { name: 'No category' })) typeName('Second spot') fireEvent.click(screen.getByRole('button', { name: /Add$/ })) await waitFor(() => expect(savedBodies).toHaveLength(2)) @@ -323,8 +327,7 @@ describe('AddPlaceToCollectionModal', () => { it('FE-COMP-ADDPLACECOL-019: without categories the category row is not rendered', () => { setup({ categories: [] }) - expect(screen.queryByText('Category')).not.toBeInTheDocument() - expect(screen.queryByRole('button', { name: 'No category' })).not.toBeInTheDocument() + expect(screen.queryByRole('button', { name: /^Category: / })).not.toBeInTheDocument() }) it('FE-COMP-ADDPLACECOL-020: links are normalised and blank rows dropped', async () => { diff --git a/client/src/components/Collections/AddPlaceToCollectionModal.tsx b/client/src/components/Collections/AddPlaceToCollectionModal.tsx index 661489cb5..562c5689c 100644 --- a/client/src/components/Collections/AddPlaceToCollectionModal.tsx +++ b/client/src/components/Collections/AddPlaceToCollectionModal.tsx @@ -7,13 +7,13 @@ import { DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, D import { AddRowButton, EditorField, INPUT, Segmented, TEXTAREA } from '../shared/dialogParts' import NoteFormatToolbar from '../shared/NoteFormatToolbar' import { Tooltip } from '../shared/Tooltip' -import { getCategoryIcon } from '../shared/categoryIcons' import { normalizeLinkUrl, STATUS_META, STATUS_ORDER } from '../../pages/collections/collectionsModel' import type { Category, TranslationFn } from '../../types' import type { CollectionStatus } from '@trek/shared' import { str } from './addPlaceModel' import { useAddPlaceToCollection } from './useAddPlaceToCollection' import { PlaceFormLocation } from '../Planner/PlaceFormLocation' +import CategoryTileMenu from './CategoryTileMenu' /** * The search row, pinned to the top of the scrolling body. The dialog stays open @@ -22,10 +22,6 @@ import { PlaceFormLocation } from '../Planner/PlaceFormLocation' * margins let its background cover the body's padding while it is stuck. */ const STICKY_SEARCH = 'sticky top-0 z-20 -mx-6 -mt-5 bg-surface-card px-6 pb-4 pt-5' -/** A chip of the category row; the picked one wears the category's own colour. */ -const CHIP = 'inline-flex items-center gap-1.5 rounded-full border px-3 py-1 font-semibold' -const CHIP_OFF = 'border-edge-faint bg-surface-card text-content-muted hover:text-content' -const CHIP_NONE_ON = 'border-content bg-surface-card text-content' const ROW_ACTION = 'grid h-8 w-8 flex-none place-items-center rounded-[9px] text-content-faint hover:bg-surface-secondary' interface AddPlaceToCollectionModalProps { @@ -65,7 +61,10 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec const header = ( } + // The category is the tile in front of the name: one tap picks it, no chip row below. + tile={categories.length > 0 + ? + : } tint={NEUTRAL_TINT} labelId={labelId} onClose={onClose} @@ -178,39 +177,6 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec /> - {categories.length > 0 && ( - -
- - {categories.map(cat => { - const Icon = getCategoryIcon(cat.icon ?? undefined) - const on = categoryId === cat.id - const col = cat.color || '#6366f1' // theme-lint-disable: the category's own colour, and the default one without a colour is drawn in - return ( - - ) - })} -
-
- )} - {t('collections.description')}} action={} diff --git a/client/src/components/Collections/CategoryBadge.tsx b/client/src/components/Collections/CategoryBadge.tsx new file mode 100644 index 000000000..386daca09 --- /dev/null +++ b/client/src/components/Collections/CategoryBadge.tsx @@ -0,0 +1,24 @@ +import React from 'react'; +import { getCategoryIcon } from '../shared/categoryIcons'; +import { Tooltip } from '../shared/Tooltip'; + +/** A place's category as its icon in its colour, in front of the name; the tooltip names it. */ +export default function CategoryBadge({ + category, +}: { + category: { name?: string | null; color?: string | null; icon?: string | null }; +}): React.ReactElement { + const Icon = getCategoryIcon(category.icon ?? undefined); + return ( + + + + + + ); +} diff --git a/client/src/components/Collections/CategoryTileMenu.test.tsx b/client/src/components/Collections/CategoryTileMenu.test.tsx new file mode 100644 index 000000000..7c7010096 --- /dev/null +++ b/client/src/components/Collections/CategoryTileMenu.test.tsx @@ -0,0 +1,102 @@ +// FE-COMP-CATTILEMENU-001 to FE-COMP-CATTILEMENU-007 +import userEvent from '@testing-library/user-event'; +import React from 'react'; + +import { fireEvent, render, screen, within } from '../../../tests/helpers/render'; +import { useTranslation } from '../../i18n/TranslationContext'; +import type { Category } from '../../types'; +import CategoryTileMenu from './CategoryTileMenu'; + +const CATEGORIES = [ + { id: 3, name: 'Restaurant', color: '#E8843D', icon: 'Utensils' }, + { id: 5, name: 'Museum', color: null, icon: null }, +] as unknown as Category[]; + +type Props = Omit, 't' | 'categories' | 'onChange'>; + +function Harness(props: Props & { onChange: (id: number | null) => void }): React.ReactElement { + const { t } = useTranslation(); + return ; +} + +function setup(props: Partial = {}) { + const onChange = vi.fn<(id: number | null) => void>(); + render(); + return { onChange }; +} + +describe('CategoryTileMenu', () => { + it('FE-COMP-CATTILEMENU-001: without a category the tile says so and is closed', () => { + setup(); + const tile = screen.getByRole('button', { name: 'Category: No category' }); + expect(tile).toHaveAttribute('aria-expanded', 'false'); + expect(tile).toHaveAttribute('title', 'Category: No category'); + expect(tile).toHaveStyle({ width: '46px', height: '46px' }); + expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); + }); + + it('FE-COMP-CATTILEMENU-002: a category names itself on the tile in the size asked for', () => { + setup({ value: 3, size: 40 }); + const tile = screen.getByRole('button', { name: 'Category: Restaurant' }); + expect(tile).toHaveStyle({ width: '40px', height: '40px' }); + expect(tile).not.toHaveClass('bg-surface-card'); + }); + + it('FE-COMP-CATTILEMENU-003: a value with no category behind it reads as none', () => { + setup({ value: 99 }); + expect(screen.getByRole('button', { name: 'Category: No category' })).toHaveClass('bg-surface-card'); + }); + + it('FE-COMP-CATTILEMENU-004: the list offers "No category" and every category, the current one selected', async () => { + const user = userEvent.setup(); + setup({ value: 5 }); + await user.click(screen.getByRole('button', { name: 'Category: Museum' })); + const list = screen.getByRole('listbox', { name: 'Category' }); + const options = within(list).getAllByRole('option'); + expect(options.map((o) => o.textContent)).toEqual(['No category', 'Restaurant', 'Museum']); + expect(options[2]).toHaveAttribute('aria-selected', 'true'); + expect(options[0]).toHaveAttribute('aria-selected', 'false'); + }); + + it('FE-COMP-CATTILEMENU-005: picking a category or none reports it and closes the list', async () => { + const user = userEvent.setup(); + const { onChange } = setup({ value: 3 }); + const tile = screen.getByRole('button', { name: 'Category: Restaurant' }); + + await user.click(tile); + await user.click(screen.getByRole('option', { name: 'Museum' })); + expect(onChange).toHaveBeenLastCalledWith(5); + expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); + + await user.click(tile); + await user.click(screen.getByRole('option', { name: 'No category' })); + expect(onChange).toHaveBeenLastCalledWith(null); + }); + + it('FE-COMP-CATTILEMENU-006: Escape closes the list and goes no further, so the dialog around it stays', async () => { + const user = userEvent.setup(); + setup(); + await user.click(screen.getByRole('button', { name: 'Category: No category' })); + const outer = vi.fn(); + document.body.addEventListener('keydown', outer); + + fireEvent.keyDown(screen.getByRole('listbox'), { key: 'Escape' }); + expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); + expect(outer).not.toHaveBeenCalled(); + document.body.removeEventListener('keydown', outer); + }); + + it('FE-COMP-CATTILEMENU-007: a press outside closes it, a press inside and other keys do not', async () => { + const user = userEvent.setup(); + setup(); + const tile = screen.getByRole('button', { name: 'Category: No category' }); + await user.click(tile); + fireEvent.mouseDown(screen.getByRole('listbox')); + fireEvent.keyDown(document, { key: 'ArrowDown' }); + expect(screen.getByRole('listbox')).toBeInTheDocument(); + + fireEvent.mouseDown(document.body); + expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); + expect(tile).toHaveAttribute('aria-expanded', 'false'); + }); +}); diff --git a/client/src/components/Collections/CategoryTileMenu.tsx b/client/src/components/Collections/CategoryTileMenu.tsx new file mode 100644 index 000000000..3734ed5d1 --- /dev/null +++ b/client/src/components/Collections/CategoryTileMenu.tsx @@ -0,0 +1,103 @@ +import { Check, Shapes } from 'lucide-react'; +import React, { useEffect, useRef, useState } from 'react'; +import type { Category, TranslationFn } from '../../types'; +import { getCategoryIcon } from '../shared/categoryIcons'; + +interface CategoryTileMenuProps { + categories: Category[]; + value: number | null; + onChange: (id: number | null) => void; + /** The tile's side in pixels: 46 in a dialog's head band, 40 beside the sheet's name field. */ + size?: number; + t: TranslationFn; +} + +/** + * The place's category as the tile in front of its name: its icon in its colour, + * and a tap opens the list to pick another. It replaces the row of category chips + * the forms had, so the category reads as part of the place and the form loses a row. + */ +export default function CategoryTileMenu({ + categories, + value, + onChange, + size = 46, + t, +}: CategoryTileMenuProps): React.ReactElement { + const [open, setOpen] = useState(false); + const ref = useRef(null); + useEffect(() => { + if (!open) return; + const onDoc = (e: MouseEvent) => { + if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false); + }; + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape') { + e.stopPropagation(); + setOpen(false); + } + }; + document.addEventListener('mousedown', onDoc); + document.addEventListener('keydown', onKey, true); + return () => { + document.removeEventListener('mousedown', onDoc); + document.removeEventListener('keydown', onKey, true); + }; + }, [open]); + + const current = value != null ? (categories.find((c) => c.id === value) ?? null) : null; + const Icon = current ? getCategoryIcon(current.icon ?? undefined) : Shapes; + const tone = current?.color || null; + const label = `${t('collections.category')}: ${current?.name ?? t('collections.noCategory')}`; + + return ( +
+ + {open && ( +
+ {[null, ...categories].map((cat) => { + const on = (cat?.id ?? null) === value; + const OptIcon = cat ? getCategoryIcon(cat.icon ?? undefined) : Shapes; + return ( + + ); + })} +
+ )} +
+ ); +} diff --git a/client/src/components/Collections/CollectionFilterBar.tsx b/client/src/components/Collections/CollectionFilterBar.tsx index 1293b236e..9aa684219 100644 --- a/client/src/components/Collections/CollectionFilterBar.tsx +++ b/client/src/components/Collections/CollectionFilterBar.tsx @@ -1,67 +1,12 @@ -import React, { useEffect, useRef, useState } from 'react' -import { ChevronDown, Check, Layers, Tag, CheckSquare, Star, Plus, ArrowDownUp, DownloadCloud } from 'lucide-react' +import React from 'react' +import { Layers, Tag, CheckSquare, Star, Plus, ArrowDownUp, DownloadCloud } from 'lucide-react' import type { StatusFilter, CollectionSortMode } from '../../store/collectionStore' import type { TranslationFn } from '../../types' import { getCategoryIcon } from '../shared/categoryIcons' import { STATUS_META, STATUS_ORDER } from '../../pages/collections/collectionsModel' import type { CategoryOption, LabelOption } from '../../pages/collections/collectionsModel' import CollectionLabelFilter from './CollectionLabelFilter' - -interface Opt { - key: string | number - label: string - icon?: React.ReactNode - count?: number -} - -/** Small custom dropdown — compact trigger + click-away popover. */ -function Dropdown({ current, options, onSelect, lead }: { - current: string | number - options: Opt[] - onSelect: (key: string | number) => void - lead: React.ReactNode -}): React.ReactElement { - const [open, setOpen] = useState(false) - const ref = useRef(null) - useEffect(() => { - if (!open) return - const onDoc = (e: MouseEvent) => { if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false) } - const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false) } - document.addEventListener('mousedown', onDoc) - document.addEventListener('keydown', onKey) - return () => { document.removeEventListener('mousedown', onDoc); document.removeEventListener('keydown', onKey) } - }, [open]) - - const cur = options.find(o => o.key === current) ?? options[0] - return ( -
- - {open && ( -
- {options.map(o => ( - - ))} -
- )} -
- ) -} +import FilterDropdown, { type FilterOption as Opt } from './FilterDropdown' interface CollectionFilterBarProps { statusFilter: StatusFilter @@ -146,12 +91,12 @@ export default function CollectionFilterBar({ )} - onStatusFilter(k as StatusFilter)} lead={} /> + onStatusFilter(k as StatusFilter)} lead={} /> {categoryOptions.length > 0 && ( - onCategoryFilter(k as number | 'all')} lead={} /> + onCategoryFilter(k as number | 'all')} lead={} /> )} - onRatingFilter(k as number | 'all')} lead={} /> - onSortMode(k as CollectionSortMode)} lead={} /> + onRatingFilter(k as number | 'all')} lead={} /> + onSortMode(k as CollectionSortMode)} lead={} /> {showSelect && ( - {categories.map(cat => { - const Icon = getCategoryIcon(cat.icon ?? undefined) - const on = categoryId === cat.id - return ( - - ) - })} - - {/* A place that has no position yet can be looked up here (#2837). */} {needsPosition && } {/* Address (#1870): free text, the coordinates stay separate */} diff --git a/client/src/components/Collections/CollectionPlaceTags.tsx b/client/src/components/Collections/CollectionPlaceTags.tsx index 1ce89ef5e..000e1257a 100644 --- a/client/src/components/Collections/CollectionPlaceTags.tsx +++ b/client/src/components/Collections/CollectionPlaceTags.tsx @@ -92,14 +92,17 @@ function labelsThatFit(row: HTMLElement): number { export default function CollectionPlaceTags({ place, labels, + showCategory = true, }: { place: CollectionPlace; labels: CollectionLabel[]; + /** Off where the row shows the category on the place's tile instead. */ + showCategory?: boolean; }): React.ReactElement | null { const ref = useRef(null); const [fit, setFit] = useState(labels.length); const labelKey = labels.map((l) => `${l.id}:${l.name}`).join('|'); - const categoryName = place.category?.name ?? null; + const categoryName = showCategory ? (place.category?.name ?? null) : null; // Fitted on every change of the row's width and once more whenever its labels change: // observing anew hands the observer's first notification to the new labels. diff --git a/client/src/components/Collections/FilterDropdown.test.tsx b/client/src/components/Collections/FilterDropdown.test.tsx new file mode 100644 index 000000000..e3a86fe80 --- /dev/null +++ b/client/src/components/Collections/FilterDropdown.test.tsx @@ -0,0 +1,93 @@ +// FE-COMP-FILTERDROPDOWN-001 to FE-COMP-FILTERDROPDOWN-007 +import userEvent from '@testing-library/user-event'; + +import { fireEvent, render, screen, within } from '../../../tests/helpers/render'; +import FilterDropdown, { type FilterOption } from './FilterDropdown'; + +const OPTIONS: FilterOption[] = [ + { key: 'all', label: 'Everything', count: 12 }, + { key: 'trip', label: 'Trips', icon: , count: 8 }, + { key: 3, label: 'Food' }, +]; + +function setup(current: string | number = 'all') { + const onSelect = vi.fn<(key: string | number) => void>(); + const view = render( + } /> + ); + const trigger = view.container.querySelector('.col-filter-btn'); + if (!(trigger instanceof HTMLButtonElement)) throw new Error('no trigger'); + return { ...view, onSelect, trigger }; +} + +describe('FilterDropdown', () => { + it('FE-COMP-FILTERDROPDOWN-001: the trigger names the current option and marks the default one', () => { + const { trigger } = setup(); + expect(trigger).toHaveTextContent('Everything'); + expect(trigger).toHaveAttribute('title', 'Everything'); + expect(trigger).toHaveAttribute('aria-haspopup', 'listbox'); + expect(trigger).toHaveAttribute('aria-expanded', 'false'); + expect(trigger).toHaveClass('is-default'); + expect(within(trigger).getByTestId('lead')).toBeInTheDocument(); + expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); + }); + + it('FE-COMP-FILTERDROPDOWN-002: a chosen option shows its own icon and drops the default mark', () => { + const { trigger } = setup('trip'); + expect(trigger).toHaveTextContent('Trips'); + expect(trigger).not.toHaveClass('is-default'); + expect(within(trigger).getByTestId('trip-icon')).toBeInTheDocument(); + expect(within(trigger).queryByTestId('lead')).not.toBeInTheDocument(); + }); + + it('FE-COMP-FILTERDROPDOWN-003: an unknown current value falls back to the first option', () => { + const { trigger } = setup('gone'); + expect(trigger).toHaveTextContent('Everything'); + }); + + it('FE-COMP-FILTERDROPDOWN-004: opening lists every option with its count and the current one selected', async () => { + const user = userEvent.setup(); + const { trigger } = setup(3); + await user.click(trigger); + expect(trigger).toHaveAttribute('aria-expanded', 'true'); + const options = within(screen.getByRole('listbox')).getAllByRole('option'); + expect(options.map((o) => o.textContent)).toEqual(['Everything12', 'Trips8', 'Food']); + expect(options[2]).toHaveAttribute('aria-selected', 'true'); + expect(options[0]).toHaveAttribute('aria-selected', 'false'); + }); + + it('FE-COMP-FILTERDROPDOWN-005: picking an option reports its key and closes the list', async () => { + const user = userEvent.setup(); + const { trigger, onSelect } = setup(); + await user.click(trigger); + await user.click(screen.getByRole('option', { name: /Food/ })); + expect(onSelect).toHaveBeenCalledWith(3); + expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); + }); + + it('FE-COMP-FILTERDROPDOWN-006: Escape and a press outside close it, the trigger toggles it', async () => { + const user = userEvent.setup(); + const { trigger, onSelect } = setup(); + await user.click(trigger); + fireEvent.keyDown(document, { key: 'Escape' }); + expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); + + await user.click(trigger); + fireEvent.mouseDown(document.body); + expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); + + await user.click(trigger); + await user.click(trigger); + expect(screen.queryByRole('listbox')).not.toBeInTheDocument(); + expect(onSelect).not.toHaveBeenCalled(); + }); + + it('FE-COMP-FILTERDROPDOWN-007: another key and a press inside leave it open', async () => { + const user = userEvent.setup(); + const { trigger } = setup(); + await user.click(trigger); + fireEvent.keyDown(document, { key: 'Enter' }); + fireEvent.mouseDown(screen.getByRole('listbox')); + expect(screen.getByRole('listbox')).toBeInTheDocument(); + }); +}); diff --git a/client/src/components/Collections/FilterDropdown.tsx b/client/src/components/Collections/FilterDropdown.tsx new file mode 100644 index 000000000..c829a5db2 --- /dev/null +++ b/client/src/components/Collections/FilterDropdown.tsx @@ -0,0 +1,80 @@ +import { Check, ChevronDown } from 'lucide-react'; +import React, { useEffect, useRef, useState } from 'react'; + +export interface FilterOption { + key: string | number; + label: string; + icon?: React.ReactNode; + count?: number; +} + +/** Small custom dropdown — compact trigger + click-away popover. */ +export default function FilterDropdown({ + current, + options, + onSelect, + lead, +}: { + current: string | number; + options: FilterOption[]; + onSelect: (key: string | number) => void; + lead: React.ReactNode; +}): React.ReactElement { + const [open, setOpen] = useState(false); + const ref = useRef(null); + useEffect(() => { + if (!open) return; + const onDoc = (e: MouseEvent) => { + if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false); + }; + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape') setOpen(false); + }; + document.addEventListener('mousedown', onDoc); + document.addEventListener('keydown', onKey); + return () => { + document.removeEventListener('mousedown', onDoc); + document.removeEventListener('keydown', onKey); + }; + }, [open]); + + const cur = options.find((o) => o.key === current) ?? options[0]; + return ( +
+ + {open && ( +
+ {options.map((o) => ( + + ))} +
+ )} +
+ ); +} diff --git a/client/src/components/Collections/ImportCollectionModal.tsx b/client/src/components/Collections/ImportCollectionModal.tsx index dcc7a7de3..2fa14b82f 100644 --- a/client/src/components/Collections/ImportCollectionModal.tsx +++ b/client/src/components/Collections/ImportCollectionModal.tsx @@ -280,8 +280,6 @@ export default function ImportCollectionModal({ onClose={onClose} labelledBy={titleId} width="narrow" - // The body grows once a file is read; the top edge stays where it was. - align="top" header={( } diff --git a/client/src/components/Collections/LegacyCollectionsRedirect.tsx b/client/src/components/Collections/LegacyCollectionsRedirect.tsx new file mode 100644 index 000000000..404810cb7 --- /dev/null +++ b/client/src/components/Collections/LegacyCollectionsRedirect.tsx @@ -0,0 +1,8 @@ +import { Navigate, useLocation } from 'react-router'; +import { PLACES_ROOT, placesPathForLegacy } from '../../utils/placesRoutes'; + +/** An old /collections link (a bookmark, a notification, an assistant card) lands in Places (PLC-07). */ +export default function LegacyCollectionsRedirect() { + const { pathname, search } = useLocation(); + return ; +} diff --git a/client/src/components/Collections/LibraryFilterBar.test.tsx b/client/src/components/Collections/LibraryFilterBar.test.tsx new file mode 100644 index 000000000..2b0f70b2a --- /dev/null +++ b/client/src/components/Collections/LibraryFilterBar.test.tsx @@ -0,0 +1,95 @@ +// FE-COMP-LIBFILTERBAR-001 to FE-COMP-LIBFILTERBAR-006 +import userEvent from '@testing-library/user-event'; +import React from 'react'; + +import { render, screen, within } from '../../../tests/helpers/render'; +import { useTranslation } from '../../i18n/TranslationContext'; +import type { Category } from '../../types'; +import LibraryFilterBar from './LibraryFilterBar'; + +const CATEGORIES = [ + { id: 3, name: 'Restaurant', color: '#E8843D', icon: 'Utensils' }, + { id: 5, name: 'Museum', color: null, icon: null }, +] as unknown as Category[]; + +type Props = Omit, 't'>; + +function Harness(props: Props): React.ReactElement { + const { t } = useTranslation(); + return ; +} + +function setup(over: Partial = {}) { + const props: Props = { + kind: 'all', + counts: { all: 12, trip: 8, list: 5 }, + onKind: vi.fn(), + status: 'all', + onStatus: vi.fn(), + categoryId: 'all', + categories: CATEGORIES, + onCategory: vi.fn(), + sort: 'name', + onSort: vi.fn(), + ...over, + }; + const view = render(); + const triggers = Array.from(view.container.querySelectorAll('.col-filter-btn')); + return { ...view, props, triggers }; +} + +const optionTexts = () => + within(screen.getByRole('listbox')) + .getAllByRole('option') + .map((o) => o.textContent); + +describe('LibraryFilterBar', () => { + it('FE-COMP-LIBFILTERBAR-001: shows where from, status, category and order, each at its default', () => { + const { triggers } = setup(); + expect(triggers.map((b) => b.textContent)).toEqual(['All', 'All', 'All', 'Name (A–Z)']); + }); + + it('FE-COMP-LIBFILTERBAR-002: without categories there is no category filter', () => { + const { triggers } = setup({ categories: [] }); + expect(triggers.map((b) => b.textContent)).toEqual(['All', 'All', 'Name (A–Z)']); + }); + + it('FE-COMP-LIBFILTERBAR-003: where from lists trips and lists with their counts and reports the pick', async () => { + const user = userEvent.setup(); + const { triggers, props } = setup(); + await user.click(triggers[0]); + expect(optionTexts()).toEqual(['All12', 'Trips8', 'Lists5']); + await user.click(screen.getByRole('option', { name: /Trips/ })); + expect(props.onKind).toHaveBeenCalledWith('trip'); + }); + + it('FE-COMP-LIBFILTERBAR-004: status offers every list status and reports the pick', async () => { + const user = userEvent.setup(); + const { triggers, props } = setup({ status: 'visited' }); + expect(triggers[1]).toHaveTextContent('Visited'); + await user.click(triggers[1]); + expect(optionTexts()).toEqual(['All', 'Idea', 'Want to go', 'Visited', 'Want to revisit']); + await user.click(screen.getByRole('option', { name: 'Want to go' })); + expect(props.onStatus).toHaveBeenCalledWith('want'); + }); + + it('FE-COMP-LIBFILTERBAR-005: category lists the categories by name and reports the id', async () => { + const user = userEvent.setup(); + const { triggers, props } = setup({ categoryId: 3 }); + expect(triggers[2]).toHaveTextContent('Restaurant'); + await user.click(triggers[2]); + expect(optionTexts()).toEqual(['All', 'Restaurant', 'Museum']); + await user.click(screen.getByRole('option', { name: 'Museum' })); + expect(props.onCategory).toHaveBeenCalledWith(5); + }); + + it('FE-COMP-LIBFILTERBAR-006: order switches between name and last changed', async () => { + const user = userEvent.setup(); + const { triggers, props } = setup({ sort: 'updated' }); + expect(triggers[3]).toHaveTextContent('Last changed'); + await user.click(triggers[3]); + expect(optionTexts()).toEqual(['Name (A–Z)', 'Last changed']); + await user.click(screen.getByRole('option', { name: 'Name (A–Z)' })); + expect(props.onSort).toHaveBeenCalledWith('name'); + }); +}); diff --git a/client/src/components/Collections/LibraryFilterBar.tsx b/client/src/components/Collections/LibraryFilterBar.tsx new file mode 100644 index 000000000..2e88088a6 --- /dev/null +++ b/client/src/components/Collections/LibraryFilterBar.tsx @@ -0,0 +1,99 @@ +import type { CollectionStatus, PlacesLibraryCounts, PlacesLibrarySort } from '@trek/shared'; +import { ArrowDownUp, Bookmark, Globe2, Layers, Luggage, Tag } from 'lucide-react'; +import React from 'react'; +import { STATUS_META, STATUS_ORDER } from '../../pages/collections/collectionsModel'; +import type { Category, TranslationFn } from '../../types'; +import { getCategoryIcon } from '../shared/categoryIcons'; +import FilterDropdown, { type FilterOption } from './FilterDropdown'; +import type { LibraryKindFilter } from './usePlacesLibrary'; + +interface LibraryFilterBarProps { + kind: LibraryKindFilter; + counts: PlacesLibraryCounts; + onKind: (kind: LibraryKindFilter) => void; + status: CollectionStatus | 'all'; + onStatus: (status: CollectionStatus | 'all') => void; + categoryId: number | 'all'; + categories: Category[]; + onCategory: (id: number | 'all') => void; + sort: PlacesLibrarySort; + onSort: (sort: PlacesLibrarySort) => void; + t: TranslationFn; +} + +/** + * The filter row of "All places", built from the same compact dropdowns as the + * lists' row: where a place comes from (trips, lists or both, with their counts), + * the status it has in a list, its category, and the order. + */ +export default function LibraryFilterBar({ + kind, + counts, + onKind, + status, + onStatus, + categoryId, + categories, + onCategory, + sort, + onSort, + t, +}: LibraryFilterBarProps): React.ReactElement { + const kindOpts: FilterOption[] = [ + { key: 'all', label: t('collections.library.kindAll'), count: counts.all }, + { key: 'trip', label: t('collections.library.kindTrips'), icon: , count: counts.trip }, + { key: 'list', label: t('collections.library.kindLists'), icon: , count: counts.list }, + ]; + const statusOpts: FilterOption[] = [ + { key: 'all', label: t('common.all') }, + ...STATUS_ORDER.map((s) => { + const Icon = STATUS_META[s].icon; + return { + key: s, + label: t(STATUS_META[s].labelKey), + icon: , + }; + }), + ]; + const catOpts: FilterOption[] = [ + { key: 'all', label: t('common.all') }, + ...categories.map((c) => { + const Icon = getCategoryIcon(c.icon ?? undefined); + return { key: c.id, label: c.name, icon: }; + }), + ]; + const sortOpts: FilterOption[] = [ + { key: 'name', label: t('collections.sort.nameAsc') }, + { key: 'updated', label: t('collections.library.sortUpdated') }, + ]; + return ( +
+ onKind(k as LibraryKindFilter)} + lead={} + /> + onStatus(k as CollectionStatus | 'all')} + lead={} + /> + {categories.length > 0 && ( + onCategory(k as number | 'all')} + lead={} + /> + )} + onSort(k as PlacesLibrarySort)} + lead={} + /> +
+ ); +} diff --git a/client/src/components/Collections/LibraryOrigins.test.tsx b/client/src/components/Collections/LibraryOrigins.test.tsx new file mode 100644 index 000000000..a9c134cc5 --- /dev/null +++ b/client/src/components/Collections/LibraryOrigins.test.tsx @@ -0,0 +1,54 @@ +// FE-COMP-LIBORIGINS-001 to FE-COMP-LIBORIGINS-004 +import React from 'react'; + +import { listOrigin, tripOrigin } from '../../../tests/helpers/placesLibrary'; +import { render, screen } from '../../../tests/helpers/render'; +import { useTranslation } from '../../i18n/TranslationContext'; +import LibraryOrigins, { originName } from './LibraryOrigins'; + +type Props = Omit, 't'>; + +function Harness(props: Props): React.ReactElement { + const { t } = useTranslation(); + return ; +} + +const pillTexts = (container: HTMLElement) => + Array.from(container.querySelectorAll('.col-origin-pill')).map((el) => el.textContent); + +describe('LibraryOrigins', () => { + it("FE-COMP-LIBORIGINS-001: an origin goes by its list's or its trip's name", () => { + expect(originName(listOrigin({ collection_name: 'Wishlist' }))).toBe('Wishlist'); + expect(originName(tripOrigin({ trip_title: 'Japan 2027' }))).toBe('Japan 2027'); + }); + + it('FE-COMP-LIBORIGINS-002: trips come before lists, each with a title saying where the place is', () => { + const { container } = render( + + ); + expect(pillTexts(container)).toEqual(['Rome 2026', 'Favourites']); + expect(screen.getByTitle('In the trip Rome 2026')).toBeInTheDocument(); + expect(screen.getByTitle('In the list Favourites')).toBeInTheDocument(); + }); + + it('FE-COMP-LIBORIGINS-003: past two origins the rest is counted', () => { + const { container } = render( + + ); + expect(pillTexts(container)).toEqual(['First trip', 'Second trip', '+2']); + expect(screen.queryByText('A list')).not.toBeInTheDocument(); + }); + + it('FE-COMP-LIBORIGINS-004: two origins or fewer show no count', () => { + const { container } = render(); + expect(pillTexts(container)).toEqual(['Rome 2026']); + expect(container.querySelector('.col-origin-pill.more')).toBeNull(); + }); +}); diff --git a/client/src/components/Collections/LibraryOrigins.tsx b/client/src/components/Collections/LibraryOrigins.tsx new file mode 100644 index 000000000..411ec1d9c --- /dev/null +++ b/client/src/components/Collections/LibraryOrigins.tsx @@ -0,0 +1,51 @@ +import type { PlacesLibraryOrigin } from '@trek/shared'; +import { Bookmark, Luggage } from 'lucide-react'; +import React from 'react'; +import type { TranslationFn } from '../../types'; + +/** How many origins a row names before it counts the rest. */ +const SHOWN = 2; + +/** The name an origin goes by: the list's or the trip's. */ +export function originName(origin: PlacesLibraryOrigin): string { + return origin.kind === 'list' ? origin.collection_name : origin.trip_title; +} + +/** + * Where an entry of "All places" comes from (PLC-07): a chip per list and per trip, + * trips first because they are what was actually planned, the rest counted. + */ +export default function LibraryOrigins({ + origins, + t, +}: { + origins: PlacesLibraryOrigin[]; + t: TranslationFn; +}): React.ReactElement { + const ordered = [...origins].sort((a, b) => (a.kind === b.kind ? 0 : a.kind === 'trip' ? -1 : 1)); + const rest = ordered.length - SHOWN; + return ( +
+ {ordered.slice(0, SHOWN).map((origin) => { + const Icon = origin.kind === 'trip' ? Luggage : Bookmark; + return ( + + + ); + })} + {rest > 0 && ( + {t('collections.library.moreOrigins', { count: rest })} + )} +
+ ); +} diff --git a/client/src/components/Collections/LibraryPlaceDetail.test.tsx b/client/src/components/Collections/LibraryPlaceDetail.test.tsx new file mode 100644 index 000000000..c561658eb --- /dev/null +++ b/client/src/components/Collections/LibraryPlaceDetail.test.tsx @@ -0,0 +1,245 @@ +// FE-COMP-LIBPLACEDETAIL-001 to FE-COMP-LIBPLACEDETAIL-013 +import userEvent from '@testing-library/user-event'; +import type { PlacesLibraryDetailResponse } from '@trek/shared'; +import React from 'react'; + +import { + bothOrigins, + libraryDetail, + libraryEntry, + libraryInfo, + listDetail, + listOrigin, + tripDetail, + tripOrigin, +} from '../../../tests/helpers/placesLibrary'; +import { render, screen, within } from '../../../tests/helpers/render'; +import { useTranslation } from '../../i18n/TranslationContext'; +import { type NavigationTarget, openNavigationTarget } from '../Planner/placeNavigation'; +import LibraryPlaceDetail from './LibraryPlaceDetail'; + +const nav = vi.hoisted(() => ({ targets: [] as NavigationTarget[] })); + +vi.mock('../Planner/placeNavigation', () => ({ + getNavigationTargets: () => nav.targets, + navigationTargetLabel: (target: NavigationTarget) => target.label, + openNavigationTarget: vi.fn(), +})); + +vi.mock('../shared/NavigationMenu', () => ({ + NavigationMenu: ({ targets, onClose }: { targets: NavigationTarget[]; onClose: () => void }) => ( +
+ {targets.map((target) => ( + {target.label} + ))} + +
+ ), +})); + +const GOOGLE: NavigationTarget = { id: 'google', label: 'Google Maps', url: 'https://maps.example/g' }; +const OSM: NavigationTarget = { id: 'osm', label: 'OpenStreetMap', url: 'https://maps.example/o' }; + +type Props = Omit, 't'>; + +function Harness(props: Props): React.ReactElement { + const { t } = useTranslation(); + return ; +} + +/** The Colosseum in a read-only trip, planned and booked there, and in a list with labels and votes. */ +function fullDetail(): PlacesLibraryDetailResponse { + const data = bothOrigins({ category: { id: 3, name: 'Restaurant', color: '#E8843D', icon: 'Utensils' } }); + data.entry.origins = [tripOrigin({ read_only: true }), listOrigin()]; + data.details = [ + tripDetail({ + info: libraryInfo({ name: 'Colosseo' }), + notes: 'Book the underground tour', + days: [{ day_id: 1, day_number: 2, date: null, title: null, time: '10:00', end_time: null }], + has_accommodation: true, + has_reservation: true, + }), + listDetail({ + info: libraryInfo({ description: 'Ancient arena' }), + notes: ' ', + labels: [{ id: 1, name: 'Must see', color: '#EF4444' }], + rating: { average: 4.5, count: 2, mine: 5 }, + }), + ]; + return data; +} + +function setup(over: Partial = {}) { + const props: Props = { + data: fullDetail(), + loading: false, + cover: null, + language: 'en', + onClose: vi.fn(), + onOpenList: vi.fn(), + onOpenTrip: vi.fn(), + onSaveToList: vi.fn(), + onCopyToTrip: vi.fn(), + ...over, + }; + const view = render(); + return { ...view, props }; +} + +beforeEach(() => { + nav.targets = []; + vi.mocked(openNavigationTarget).mockClear(); +}); + +describe('LibraryPlaceDetail: the sheet', () => { + it('FE-COMP-LIBPLACEDETAIL-001: while it loads it shows a spinner and nothing to do yet', () => { + const { container } = setup({ data: null, loading: true }); + const dialog = screen.getByRole('dialog', { name: 'All places' }); + expect(container.querySelector('.animate-spin')).not.toBeNull(); + expect(within(dialog).getAllByRole('button')).toHaveLength(1); + expect(within(dialog).getByRole('button', { name: 'Close' })).toBeInTheDocument(); + expect(screen.queryByRole('heading')).not.toBeInTheDocument(); + }); + + it('FE-COMP-LIBPLACEDETAIL-002: the head carries the cover, the category and the name, the body the address', () => { + const { container } = setup({ cover: '/uploads/cover.jpg' }); + expect(screen.getByRole('dialog', { name: 'Colosseum' })).toBeInTheDocument(); + expect(screen.getByRole('heading', { name: 'Colosseum' })).toBeInTheDocument(); + expect(screen.getByText('Restaurant')).toBeInTheDocument(); + expect(screen.getByText('Piazza del Colosseo')).toBeInTheDocument(); + expect(container.querySelector('.col-detail-cover img')).toHaveAttribute('src', '/uploads/cover.jpg'); + expect(screen.queryByText('No coordinates, so not on the map')).not.toBeInTheDocument(); + expect(screen.getByText('Ancient arena')).toBeInTheDocument(); + }); + + it('FE-COMP-LIBPLACEDETAIL-003: without a cover or coordinates it falls back to the gradient and says why it is not on the map', () => { + const entry = libraryEntry({ lat: null, lng: null, address: null }); + const { container } = setup({ data: libraryDetail(entry, [tripDetail()]) }); + expect(container.querySelector('.col-detail-cover img')).toBeNull(); + expect(screen.getByText('No coordinates, so not on the map')).toBeInTheDocument(); + expect(container.querySelector('.col-detail-cover-cat')).toBeNull(); + }); + + it('FE-COMP-LIBPLACEDETAIL-004: docked it takes the column it is given, otherwise it stays centred', () => { + const { container, unmount } = setup({ anchorRect: { left: 120, width: 400 } }); + const docked = container.querySelector('.col-detail'); + expect(docked).toHaveClass('docked'); + expect(docked).toHaveStyle({ left: '120px', width: '400px' }); + unmount(); + + const centred = setup({ anchorRect: null }).container.querySelector('.col-detail'); + expect(centred).not.toHaveClass('docked'); + }); + + it('FE-COMP-LIBPLACEDETAIL-005: the close button closes it', async () => { + const user = userEvent.setup(); + const { props } = setup(); + await user.click(screen.getByRole('button', { name: 'Close' })); + expect(props.onClose).toHaveBeenCalledTimes(1); + }); +}); + +describe('LibraryPlaceDetail: where the place sits', () => { + it('FE-COMP-LIBPLACEDETAIL-006: a trip shows its planned day, its name there, a stay, a booking and its notes', async () => { + const user = userEvent.setup(); + const { props } = setup(); + expect(screen.getByText('In your trips')).toBeInTheDocument(); + const card = screen.getByRole('button', { name: 'Open in the trip: Rome 2026' }); + expect(within(card).getByText('Day 2, 10:00')).toBeInTheDocument(); + expect(within(card).getByText('Read only')).toBeInTheDocument(); + expect(within(card).getByText('Called Colosseo here')).toBeInTheDocument(); + expect(within(card).getByText('Stay')).toBeInTheDocument(); + expect(within(card).getByText('Booking')).toBeInTheDocument(); + expect(within(card).getByText('Book the underground tour')).toBeInTheDocument(); + + await user.click(card); + expect(props.onOpenTrip).toHaveBeenCalledWith(5, 42); + }); + + it('FE-COMP-LIBPLACEDETAIL-007: a list shows its status, labels and votes, and no notes when they are blank', async () => { + const user = userEvent.setup(); + const { props } = setup(); + expect(screen.getByText('In your lists')).toBeInTheDocument(); + const card = screen.getByRole('button', { name: 'Open in the list: Favourites' }); + expect(within(card).getByText('Want to go')).toBeInTheDocument(); + expect(within(card).getByText('Must see')).toBeInTheDocument(); + expect(within(card).getByText('4.5 from 2 votes')).toBeInTheDocument(); + expect(within(card).queryByText('Notes')).not.toBeInTheDocument(); + expect(within(card).queryByText(/^Called/)).not.toBeInTheDocument(); + + await user.click(card); + expect(props.onOpenList).toHaveBeenCalledWith(9, 900); + }); + + it('FE-COMP-LIBPLACEDETAIL-008: a plain trip place shows only its trip dates, nothing else', () => { + const entry = libraryEntry({ origins: [tripOrigin({ trip_start: '2026-12-01', trip_end: '2026-12-05' })] }); + setup({ data: libraryDetail(entry, [tripDetail()]) }); + const card = screen.getByRole('button', { name: 'Open in the trip: Rome 2026' }); + expect(card.querySelector('.col-origin-title .sub')?.textContent).toMatch(/1.*5/); + expect(card.querySelector('.col-origin-chips')).toBeNull(); + expect(within(card).queryByText('Read only')).not.toBeInTheDocument(); + expect(screen.queryByText('In your lists')).not.toBeInTheDocument(); + }); + + it('FE-COMP-LIBPLACEDETAIL-009: an origin the server sent no detail for is left out', () => { + const data = bothOrigins(); + data.details = [tripDetail()]; + setup({ data }); + expect(screen.getByRole('button', { name: 'Open in the trip: Rome 2026' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Open in the list: Favourites' })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /Copy to trip/ })).not.toBeInTheDocument(); + }); +}); + +describe('LibraryPlaceDetail: what to do with it', () => { + it('FE-COMP-LIBPLACEDETAIL-010: a trip place can be kept in a list, a saved one copied to a trip', async () => { + const user = userEvent.setup(); + const { props } = setup(); + await user.click(screen.getByRole('button', { name: /Save to Collection/ })); + expect(props.onSaveToList).toHaveBeenCalledWith(props.data?.entry.origins[0], props.data?.details[0]); + + await user.click(screen.getByRole('button', { name: /Copy to trip/ })); + expect(props.onCopyToTrip).toHaveBeenCalledWith(900); + }); + + it('FE-COMP-LIBPLACEDETAIL-011: a place only in a list cannot be saved again', () => { + const entry = libraryEntry({ key: 'list:900', origins: [listOrigin()] }); + setup({ data: libraryDetail(entry, [listDetail()]) }); + expect(screen.queryByRole('button', { name: /Save to Collection/ })).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: /Copy to trip/ })).toBeInTheDocument(); + }); + + it('FE-COMP-LIBPLACEDETAIL-012: one map app opens straight away, none hides the button', async () => { + const user = userEvent.setup(); + nav.targets = [GOOGLE]; + const { unmount } = setup(); + await user.click(screen.getByRole('button', { name: /Google Maps/ })); + expect(openNavigationTarget).toHaveBeenCalledWith(GOOGLE); + expect(screen.queryByRole('menu')).not.toBeInTheDocument(); + unmount(); + + nav.targets = []; + setup(); + expect(screen.queryByRole('button', { name: /Navigation|Google Maps/ })).not.toBeInTheDocument(); + }); + + it('FE-COMP-LIBPLACEDETAIL-013: several map apps open a menu that the button and the menu itself close', async () => { + const user = userEvent.setup(); + nav.targets = [GOOGLE, OSM]; + setup(); + const button = screen.getByRole('button', { name: /Navigation/ }); + await user.click(button); + const menu = screen.getByRole('menu'); + expect(within(menu).getByText('OpenStreetMap')).toBeInTheDocument(); + expect(openNavigationTarget).not.toHaveBeenCalled(); + + await user.click(within(menu).getByRole('button', { name: 'menu-close' })); + expect(screen.queryByRole('menu')).not.toBeInTheDocument(); + + await user.click(button); + await user.click(button); + expect(screen.queryByRole('menu')).not.toBeInTheDocument(); + }); +}); diff --git a/client/src/components/Collections/LibraryPlaceDetail.tsx b/client/src/components/Collections/LibraryPlaceDetail.tsx new file mode 100644 index 000000000..6a1d78247 --- /dev/null +++ b/client/src/components/Collections/LibraryPlaceDetail.tsx @@ -0,0 +1,362 @@ +import type { PlacesLibraryDetail, PlacesLibraryDetailResponse, PlacesLibraryOrigin } from '@trek/shared'; +import { + Bookmark, + BookmarkPlus, + ChevronRight, + Copy, + Hotel, + Loader2, + Luggage, + MapPin, + MapPinOff, + Navigation, + NotebookPen, + Star, + Ticket, + X, +} from 'lucide-react'; +import React, { useRef, useState } from 'react'; +import type { TranslationFn } from '../../types'; +import { entityGradient } from '../../utils/gradients'; +import { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../Planner/placeNavigation'; +import { getCategoryIcon } from '../shared/categoryIcons'; +import { NavigationMenu } from '../shared/NavigationMenu'; +import { tripLine } from './libraryDates'; +import { originName } from './LibraryOrigins'; +import StatusBadge from './StatusBadge'; + +type TripOrigin = Extract; +type ListOrigin = Extract; +type TripDetail = Extract; +type ListDetail = Extract; + +interface LibraryPlaceDetailProps { + data: PlacesLibraryDetailResponse | null; + loading: boolean; + /** The place's own image, or the provider's photo for it. */ + cover: string | null; + language: string; + /** Where the sheet docks: over the list column in the split, centred otherwise. */ + anchorRect?: { left: number; width: number } | null; + onClose: () => void; + onOpenList: (collectionId: number, collectionPlaceId: number) => void; + onOpenTrip: (tripId: number, placeId: number) => void; + /** Keeps the place in a list, from what the trip knows of it. */ + onSaveToList: (origin: TripOrigin, detail: TripDetail) => void; + /** Copies a saved place into a trip (the list's own copy flow). */ + onCopyToTrip: (collectionPlaceId: number) => void; + t: TranslationFn; +} + +function Notes({ text, t }: { text: string | null; t: TranslationFn }) { + if (!text?.trim()) return null; + return ( + + + {t('collections.notes')} + + {text} + + ); +} + +function TripCard({ + origin, + detail, + entryName, + language, + onOpen, + t, +}: { + origin: TripOrigin; + detail: TripDetail; + entryName: string; + language: string; + onOpen: () => void; + t: TranslationFn; +}) { + const line = tripLine(origin, detail, language, t); + const extras = detail.has_accommodation || detail.has_reservation || detail.info.name !== entryName; + return ( + + ); +} + +function ListCard({ + origin, + detail, + entryName, + onOpen, + t, +}: { + origin: ListOrigin; + detail: ListDetail; + entryName: string; + onOpen: () => void; + t: TranslationFn; +}) { + const extras = detail.labels.length > 0 || detail.rating.average != null || detail.info.name !== entryName; + return ( + + ); +} + +/** + * One place of "All places" (PLC-08), in the same sheet a saved place opens in: + * docked over the list column, cover and category on top, then every trip and list + * the place sits in with what each keeps of it, so a note from a list and a day from + * a trip are never mistaken for one another. The list stays as it was underneath. + */ +export default function LibraryPlaceDetail({ + data, + loading, + cover, + language, + anchorRect, + onClose, + onOpenList, + onOpenTrip, + onSaveToList, + onCopyToTrip, + t, +}: LibraryPlaceDetailProps): React.ReactElement { + const [navOpen, setNavOpen] = useState(false); + const navRef = useRef(null); + const entry = data?.entry ?? null; + const CatIcon = getCategoryIcon(entry?.category?.icon ?? undefined); + const targets = entry + ? getNavigationTargets({ name: entry.name, address: entry.address, lat: entry.lat, lng: entry.lng }) + : []; + const pairs = + entry && data + ? entry.origins.map((origin, i) => ({ origin, detail: data.details[i] })).filter((p) => p.detail) + : []; + const trips = pairs.filter( + (p): p is { origin: TripOrigin; detail: TripDetail } => p.origin.kind === 'trip' && p.detail.kind === 'trip' + ); + const lists = pairs.filter( + (p): p is { origin: ListOrigin; detail: ListDetail } => p.origin.kind === 'list' && p.detail.kind === 'list' + ); + const description = pairs.map((p) => p.detail.info.description).find((d) => d?.trim()); + const dockStyle = anchorRect + ? { left: anchorRect.left, width: anchorRect.width, transform: 'none' as const } + : undefined; + + return ( +
+
+ {cover && } +
+
+ {entry?.category && ( + + + {entry.category.name} + + )} + +
+ {entry && ( +
+

{entry.name}

+
+ )} +
+ +
+ {loading && !entry ? ( +
+ +
+ ) : ( + entry && ( + <> + {(entry.address || entry.lat == null || entry.lng == null) && ( +
+ {entry.address && ( + + {entry.address} + + )} + {(entry.lat == null || entry.lng == null) && ( + + {t('places.noCoordinates')} + + )} +
+ )} + {description &&
{description}
} + {trips.length > 0 && ( +
+
+ {t('collections.library.inTrips')} +
+ {trips.map(({ origin, detail }) => ( + onOpenTrip(origin.trip_id, origin.place_id)} + t={t} + /> + ))} +
+ )} + {lists.length > 0 && ( +
+
+ {t('collections.library.inLists')} +
+ {lists.map(({ origin, detail }) => ( + onOpenList(origin.collection_id, origin.collection_place_id)} + t={t} + /> + ))} +
+ )} + + ) + )} +
+ + {entry && ( +
+ {targets.length > 0 && ( + <> + + {navOpen && ( + setNavOpen(false)} /> + )} + + )} +
+ {trips[0] && ( + + )} + {lists[0] && ( + + )} +
+ )} +
+ ); +} diff --git a/client/src/components/Collections/ListEditorModal.test.tsx b/client/src/components/Collections/ListEditorModal.test.tsx index 71e1907b5..aec934d22 100644 --- a/client/src/components/Collections/ListEditorModal.test.tsx +++ b/client/src/components/Collections/ListEditorModal.test.tsx @@ -131,6 +131,7 @@ describe('ListEditorModal', () => { expect(actions.createCollection).toHaveBeenCalledWith({ name: 'Rome', color: '#6366f1', + icon: 'Bookmark', description: 'gelato', links: [], }) diff --git a/client/src/components/Collections/ListEditorModal.tsx b/client/src/components/Collections/ListEditorModal.tsx index 26197f5ce..12402f797 100644 --- a/client/src/components/Collections/ListEditorModal.tsx +++ b/client/src/components/Collections/ListEditorModal.tsx @@ -1,11 +1,12 @@ import React, { useId } from 'react' -import { Bookmark, ImagePlus, Trash2, Search, Loader2 } from 'lucide-react' +import { ImagePlus, Trash2, Search, Loader2 } from 'lucide-react' import { DeleteButton, DialogButton, DialogFooter, DialogHeader, DialogSection, DialogShell, DialogTile, FooterSpacer, fs } from '../shared/DialogShell' import { AddRowButton, EditorField, INPUT, TEXTAREA } from '../shared/dialogParts' import { Tooltip } from '../shared/Tooltip' import { normalizeLinkUrl } from '../../pages/collections/collectionsModel' import type { TranslationFn } from '../../types' import type { Collection } from '@trek/shared' +import { LIST_ICONS, LIST_ICON_NAMES, listIcon } from './listIcons' import { useListEditor } from './useListEditor' const SWATCHES = ['#6366f1', '#ec4899', '#14b8a6', '#f97316', '#8b5cf6', '#ef4444', '#3b82f6', '#22c55e'] @@ -32,16 +33,17 @@ interface ListEditorModalProps { export default function ListEditorModal({ target, onClose, onCreated, onRequestDelete, t }: ListEditorModalProps): React.ReactElement | null { const labelId = useId() const { - editing, fileRef, name, setName, color, setColor, description, setDescription, links, setLinks, setLink, + editing, fileRef, name, setName, color, setColor, icon, setIcon, description, setDescription, links, setLinks, setLink, coverPreview, coverQuery, setCoverQuery, coverResults, searchingCover, saving, pickCover, searchCover, pickUnsplash, save, } = useListEditor({ target, onClose, onCreated, t, defaultColor: '#6366f1', normalizeLinkUrl }) + const TileIcon = listIcon(icon) if (!target) return null // The list's own colour runs through the dialog: the head band, its tile and the cover. const header = ( } + tile={} tint={`color-mix(in srgb, ${color} 12%, transparent)`} labelId={labelId} onClose={onClose} @@ -149,6 +151,29 @@ export default function ListEditorModal({ target, onClose, onCreated, onRequestD
+ +
+ {LIST_ICON_NAMES.map(name => { + const Icon = LIST_ICONS[name] + const on = icon === name + return ( + + ) + })} +
+
+