mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 16:10:07 +00:00
feat(places): Places replaces Collections, with All places, place sheets and a calmer list
- Collections is Places now: /places opens "All places", every place of the trips and lists with where it comes from, the same filter row (where from, status, category, order), map bar (search, lock, list toggle) and place sheet as a list; /places/saved and /places/:id are the lists, and the old /collections links still land there. On the phone the same, with its own sheet. A place sheet shows each trip (planned day or trip dates, stay, booking, notes) and each list (status, labels, rating, notes) as one row that opens it. - The rail: a calm "New list" with its plus tile, All places and All saved as views, a "My lists" heading, every name on one edge. Lists can carry one of 24 symbols, shown in their colour in the rail and the editor. - A saved place's row keeps to two lines: its category as an icon before the name, its average vote as a star on the picture. Map pins wear the same star. - The place forms put the category in front of the name as a tile that opens the category list, instead of a row of chips. - All saved gets a subtitle; the import dialog opens centred. - Fixes: a pasted coordinate pair splits from either field of the place form; "more" in All places frees itself when a filter changes mid-load; place names on the trip map and the rating badge follow the reading direction.
This commit is contained in:
@@ -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.",
|
||||
|
||||
@@ -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,
|
||||
|
||||
+15
-16
@@ -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. */}
|
||||
<Route path="studio" element={<JourneyStudioPage />} />
|
||||
</Route>
|
||||
<Route
|
||||
path="/collections"
|
||||
element={
|
||||
<ProtectedRoute addonId="collections">
|
||||
<ViewportRoute phone={MCollectionsScreen} desktop={CollectionsPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/collections/:id"
|
||||
element={
|
||||
<ProtectedRoute addonId="collections">
|
||||
<ViewportRoute phone={MCollectionsScreen} desktop={CollectionsPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
{['/places', '/places/saved', '/places/:id'].map(path => (
|
||||
<Route
|
||||
key={path}
|
||||
path={path}
|
||||
element={
|
||||
<ProtectedRoute addonId="collections">
|
||||
<ViewportRoute phone={MCollectionsScreen} desktop={CollectionsPage} />
|
||||
</ProtectedRoute>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
{/* Collections became Places (PLC-07); the old links keep working. */}
|
||||
<Route path="/collections" element={<LegacyCollectionsRedirect />} />
|
||||
<Route path="/collections/:id" element={<LegacyCollectionsRedirect />} />
|
||||
<Route
|
||||
path="/notifications"
|
||||
element={
|
||||
|
||||
@@ -56,6 +56,10 @@ const ROUTES: [string, string, string][] = [
|
||||
['/atlas', 'm-atlas', 'd-atlas'],
|
||||
['/journey', 'm-journey', 'd-journey'],
|
||||
['/journey/1', 'm-journey-detail', 'd-journey-detail'],
|
||||
['/places', 'm-collections', 'd-collections'],
|
||||
['/places/saved', 'm-collections', 'd-collections'],
|
||||
['/places/1', 'm-collections', 'd-collections'],
|
||||
// The old Collections links land in Places (PLC-07).
|
||||
['/collections', 'm-collections', 'd-collections'],
|
||||
['/collections/1', 'm-collections', 'd-collections'],
|
||||
['/notifications', 'm-notifications', 'd-notifications'],
|
||||
|
||||
@@ -402,18 +402,18 @@ describe('collectionsApi', () => {
|
||||
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(['<kml/>'], '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)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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}` };
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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 = (
|
||||
<DialogHeader
|
||||
tile={<DialogTile><MapPinned size={20} strokeWidth={1.9} className="text-content-muted" /></DialogTile>}
|
||||
// The category is the tile in front of the name: one tap picks it, no chip row below.
|
||||
tile={categories.length > 0
|
||||
? <CategoryTileMenu categories={categories} value={categoryId} onChange={setCategoryId} t={t} />
|
||||
: <DialogTile><MapPinned size={20} strokeWidth={1.9} className="text-content-muted" /></DialogTile>}
|
||||
tint={NEUTRAL_TINT}
|
||||
labelId={labelId}
|
||||
onClose={onClose}
|
||||
@@ -178,39 +177,6 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
|
||||
/>
|
||||
</EditorField>
|
||||
|
||||
{categories.length > 0 && (
|
||||
<EditorField label={t('collections.category')}>
|
||||
<div role="group" aria-label={t('collections.category')} className="flex flex-wrap gap-1.5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCategoryId(null)}
|
||||
aria-pressed={categoryId == null}
|
||||
className={`${CHIP} ${categoryId == null ? CHIP_NONE_ON : CHIP_OFF}`}
|
||||
style={fs(12, 'body')}
|
||||
>
|
||||
{t('collections.noCategory')}
|
||||
</button>
|
||||
{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 (
|
||||
<button
|
||||
key={cat.id}
|
||||
type="button"
|
||||
onClick={() => setCategoryId(cat.id)}
|
||||
aria-pressed={on}
|
||||
className={`${CHIP} ${CHIP_OFF}`}
|
||||
style={{ ...fs(12, 'body'), ...(on ? { color: col, background: `color-mix(in oklch, ${col} 15%, transparent)`, borderColor: `color-mix(in oklch, ${col} 40%, transparent)` } : {}) }}
|
||||
>
|
||||
<Icon size={13} /> {cat.name}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</EditorField>
|
||||
)}
|
||||
|
||||
<DialogSection
|
||||
label={<label htmlFor={`${fieldId}-description`}>{t('collections.description')}</label>}
|
||||
action={<NoteFormatToolbar textareaRef={descRef} onChange={setDescription} compact customTooltips />}
|
||||
|
||||
@@ -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 (
|
||||
<Tooltip label={category.name ?? ''} placement="top">
|
||||
<span
|
||||
className="col-lrow-caticon"
|
||||
style={{ ['--cat' as string]: category.color || 'var(--accent)' }}
|
||||
aria-label={category.name ?? undefined}
|
||||
role="img"
|
||||
>
|
||||
<Icon size={14} strokeWidth={2.2} />
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -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<React.ComponentProps<typeof CategoryTileMenu>, 't' | 'categories' | 'onChange'>;
|
||||
|
||||
function Harness(props: Props & { onChange: (id: number | null) => void }): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
return <CategoryTileMenu categories={CATEGORIES} {...props} t={t} />;
|
||||
}
|
||||
|
||||
function setup(props: Partial<Props> = {}) {
|
||||
const onChange = vi.fn<(id: number | null) => void>();
|
||||
render(<Harness value={null} {...props} onChange={onChange} />);
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -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<HTMLDivElement>(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 (
|
||||
<div className="relative flex-none" ref={ref}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className={`grid place-items-center rounded-[14px] shadow-sm transition-transform hover:scale-[1.03] ${tone ? '' : 'bg-surface-card text-content-muted'}`}
|
||||
// The category's own colour, the one data-driven value of the tile.
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
...(tone ? { background: `color-mix(in srgb, ${tone} 16%, var(--bg-card))`, color: tone } : {}),
|
||||
}}
|
||||
>
|
||||
<Icon size={Math.round(size * 0.43)} strokeWidth={1.9} />
|
||||
</button>
|
||||
{open && (
|
||||
<div
|
||||
role="listbox"
|
||||
aria-label={t('collections.category')}
|
||||
className="absolute start-0 top-[calc(100%+6px)] z-50 max-h-[280px] w-[220px] overflow-y-auto rounded-xl border border-edge-faint bg-surface-card p-1.5 shadow-lg"
|
||||
>
|
||||
{[null, ...categories].map((cat) => {
|
||||
const on = (cat?.id ?? null) === value;
|
||||
const OptIcon = cat ? getCategoryIcon(cat.icon ?? undefined) : Shapes;
|
||||
return (
|
||||
<button
|
||||
key={cat?.id ?? 'none'}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={on}
|
||||
onClick={() => {
|
||||
onChange(cat?.id ?? null);
|
||||
setOpen(false);
|
||||
}}
|
||||
className={`flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-start text-body ${on ? 'bg-surface-secondary font-semibold text-content' : 'text-content-muted hover:bg-surface-secondary hover:text-content'}`}
|
||||
>
|
||||
<OptIcon size={15} className="flex-none" style={cat?.color ? { color: cat.color } : undefined} />
|
||||
<span className="min-w-0 flex-1 truncate">{cat?.name ?? t('collections.noCategory')}</span>
|
||||
{on && <Check size={14} className="flex-none" />}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<HTMLDivElement>(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 (
|
||||
<div className="col-filter" ref={ref}>
|
||||
<button type="button" className={`col-filter-btn${open ? ' open' : ''}${cur.key === options[0]?.key ? ' is-default' : ''}`} onClick={() => setOpen(o => !o)} aria-haspopup="listbox" aria-expanded={open} title={cur.label}>
|
||||
{cur.icon ?? lead}
|
||||
<span className="col-filter-lbl">{cur.label}</span>
|
||||
<ChevronDown size={14} className="col-filter-chev" />
|
||||
</button>
|
||||
{open && (
|
||||
<div className="col-filter-pop" role="listbox">
|
||||
{options.map(o => (
|
||||
<button
|
||||
key={o.key}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={o.key === current}
|
||||
className={`col-filter-opt${o.key === current ? ' on' : ''}`}
|
||||
onClick={() => { onSelect(o.key); setOpen(false) }}
|
||||
>
|
||||
{o.icon ?? <span className="col-filter-dot ghost" />}
|
||||
<span className="col-filter-lbl">{o.label}</span>
|
||||
{o.count != null && <span className="col-filter-count">{o.count}</span>}
|
||||
{o.key === current && <Check size={13} className="col-filter-check" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
import FilterDropdown, { type FilterOption as Opt } from './FilterDropdown'
|
||||
|
||||
interface CollectionFilterBarProps {
|
||||
statusFilter: StatusFilter
|
||||
@@ -146,12 +91,12 @@ export default function CollectionFilterBar({
|
||||
<Plus size={15} />
|
||||
</button>
|
||||
)}
|
||||
<Dropdown current={statusFilter} options={statusOpts} onSelect={k => onStatusFilter(k as StatusFilter)} lead={<Layers size={13} />} />
|
||||
<FilterDropdown current={statusFilter} options={statusOpts} onSelect={k => onStatusFilter(k as StatusFilter)} lead={<Layers size={13} />} />
|
||||
{categoryOptions.length > 0 && (
|
||||
<Dropdown current={categoryFilter} options={catOpts} onSelect={k => onCategoryFilter(k as number | 'all')} lead={<Tag size={13} />} />
|
||||
<FilterDropdown current={categoryFilter} options={catOpts} onSelect={k => onCategoryFilter(k as number | 'all')} lead={<Tag size={13} />} />
|
||||
)}
|
||||
<Dropdown current={ratingFilter} options={ratingOpts} onSelect={k => onRatingFilter(k as number | 'all')} lead={<Star size={13} />} />
|
||||
<Dropdown current={sortMode} options={sortOpts} onSelect={k => onSortMode(k as CollectionSortMode)} lead={<ArrowDownUp size={13} />} />
|
||||
<FilterDropdown current={ratingFilter} options={ratingOpts} onSelect={k => onRatingFilter(k as number | 'all')} lead={<Star size={13} />} />
|
||||
<FilterDropdown current={sortMode} options={sortOpts} onSelect={k => onSortMode(k as CollectionSortMode)} lead={<ArrowDownUp size={13} />} />
|
||||
{showSelect && (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import React, { useEffect, useMemo, useRef } from 'react'
|
||||
import { Check, GripVertical, Info, MapPin } from 'lucide-react'
|
||||
import { Check, GripVertical, Info, MapPin, Star } from 'lucide-react'
|
||||
import type { CollectionPlace, CollectionStatus, CollectionLabel } from '@trek/shared'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import PlaceAvatar from '../shared/PlaceAvatar'
|
||||
import StatusBadge from './StatusBadge'
|
||||
import CollectionPlaceTags from './CollectionPlaceTags'
|
||||
import { usePlaceReorder } from './usePlaceReorder'
|
||||
import CategoryBadge from './CategoryBadge'
|
||||
|
||||
/** A vote average as the map's pins write it: a whole number bare, else one decimal. */
|
||||
const ratingLabel = (rating: number): string => (Number.isInteger(rating) ? String(rating) : rating.toFixed(1))
|
||||
|
||||
|
||||
interface CollectionListProps {
|
||||
places: CollectionPlace[]
|
||||
@@ -82,10 +87,20 @@ export default function CollectionList({
|
||||
{selectMode ? (
|
||||
<span className={`col-lcheck${selected ? ' on' : ''}`}>{selected && <Check size={14} strokeWidth={3} />}</span>
|
||||
) : (
|
||||
<PlaceAvatar place={place} size={40} category={place.category ? { color: place.category.color ?? undefined, icon: place.category.icon ?? undefined } : null} />
|
||||
<span className="col-lrow-avatar">
|
||||
<PlaceAvatar place={place} size={40} category={place.category ? { color: place.category.color ?? undefined, icon: place.category.icon ?? undefined } : null} />
|
||||
{/* The category rides on the tile's corner, so the row keeps to two lines. */}
|
||||
{/* The list's average vote on the other corner, so the row needs no line for it. */}
|
||||
{typeof place.rating_avg === 'number' && place.rating_avg > 0 && (
|
||||
<span className="col-lrow-ratebadge" role="img" aria-label={t('collections.ratingBadge', { rating: ratingLabel(place.rating_avg) })}>
|
||||
<Star aria-hidden="true" />
|
||||
<span className={Number.isInteger(place.rating_avg) ? 'n' : 'n frac'}>{ratingLabel(place.rating_avg)}</span>
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<div className="li">
|
||||
<div className="t">{place.name}</div>
|
||||
<div className="t">{place.category?.name && <CategoryBadge category={place.category} />}<span className="nm">{place.name}</span></div>
|
||||
{place.address && (
|
||||
<div className="s">
|
||||
<MapPin size={11} />
|
||||
@@ -93,7 +108,7 @@ export default function CollectionList({
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<CollectionPlaceTags place={place} labels={placeLabels} />
|
||||
<CollectionPlaceTags place={place} labels={placeLabels} showCategory={false} />
|
||||
<div className="col-lrow-status">
|
||||
<StatusBadge status={place.status} onChange={selectMode || !onStatusChange ? undefined : next => onStatusChange(place.id, next)} t={t} />
|
||||
</div>
|
||||
|
||||
@@ -298,14 +298,15 @@ describe('CollectionPlaceDetail', () => {
|
||||
renderDetail({ canEdit: true, categories: CATEGORIES, place: { ...place, category_id: 1 } });
|
||||
await user.click(await screen.findByRole('button', { name: 'Edit' }));
|
||||
|
||||
expect(screen.getByText('Category')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /^Food$/ })).toHaveClass('on');
|
||||
// The category is the tile in front of the name; it opens the list to pick from.
|
||||
await user.click(screen.getByRole('button', { name: 'Category: Food' }));
|
||||
expect(screen.getByRole('option', { name: 'Food' })).toHaveAttribute('aria-selected', 'true');
|
||||
await user.click(screen.getByRole('option', { name: 'Museums' }));
|
||||
expect(screen.getByRole('button', { name: 'Category: Museums' })).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /^Museums$/ }));
|
||||
expect(screen.getByRole('button', { name: /^Museums$/ })).toHaveClass('on');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'No category' }));
|
||||
expect(screen.getByRole('button', { name: 'No category' })).toHaveClass('on');
|
||||
await user.click(screen.getByRole('button', { name: 'Category: Museums' }));
|
||||
await user.click(screen.getByRole('option', { name: 'No category' }));
|
||||
expect(screen.getByRole('button', { name: 'Category: No category' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLDETAIL-023: saving from edit mode sends the whole patch and leaves edit mode', async () => {
|
||||
@@ -318,10 +319,11 @@ describe('CollectionPlaceDetail', () => {
|
||||
});
|
||||
await user.click(await screen.findByRole('button', { name: 'Edit' }));
|
||||
|
||||
const nameInput = screen.getByLabelText('List name');
|
||||
const nameInput = screen.getByLabelText('Name');
|
||||
await user.clear(nameInput);
|
||||
await user.type(nameInput, ' Renamed Cafe ');
|
||||
await user.click(screen.getByRole('button', { name: /^Museums$/ }));
|
||||
await user.click(screen.getByRole('button', { name: /^Category: / }));
|
||||
await user.click(screen.getByRole('option', { name: 'Museums' }));
|
||||
await user.click(screen.getByRole('button', { name: /Nightlife/ }));
|
||||
const desc = screen.getByPlaceholderText('Add a description…');
|
||||
await user.clear(desc);
|
||||
@@ -351,7 +353,7 @@ describe('CollectionPlaceDetail', () => {
|
||||
const props = renderDetail({ canEdit: true, place: { ...place, description: 'Nice spot', links: [] } });
|
||||
await user.click(await screen.findByRole('button', { name: 'Edit' }));
|
||||
|
||||
await user.clear(screen.getByLabelText('List name'));
|
||||
await user.clear(screen.getByLabelText('Name'));
|
||||
await user.clear(screen.getByPlaceholderText('Add a description…'));
|
||||
await user.click(screen.getByRole('button', { name: /Save/ }));
|
||||
|
||||
@@ -372,7 +374,7 @@ describe('CollectionPlaceDetail', () => {
|
||||
await user.click(screen.getByRole('button', { name: /Save/ }));
|
||||
|
||||
await waitFor(() => expect(addToast).toHaveBeenCalledWith('Name taken', 'error', undefined));
|
||||
expect(screen.getByLabelText('List name')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Name')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-COLDETAIL-026: Cancel discards the edits and returns to read mode', async () => {
|
||||
@@ -380,7 +382,7 @@ describe('CollectionPlaceDetail', () => {
|
||||
const props = renderDetail({ canEdit: true });
|
||||
await user.click(await screen.findByRole('button', { name: 'Edit' }));
|
||||
|
||||
await user.type(screen.getByLabelText('List name'), ' Extra');
|
||||
await user.type(screen.getByLabelText('Name'), ' Extra');
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }));
|
||||
|
||||
expect(props.onSave).not.toHaveBeenCalled();
|
||||
@@ -452,7 +454,7 @@ describe('CollectionPlaceDetail', () => {
|
||||
const user = userEvent.setup();
|
||||
const props = renderDetail({ canEdit: true });
|
||||
await user.click(await screen.findByRole('button', { name: 'Edit' }));
|
||||
expect(screen.getByLabelText('List name')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Name')).toBeInTheDocument();
|
||||
|
||||
const other: CollectionPlace = { ...place, id: 2, name: 'Second Bar', description: null, links: [] };
|
||||
render(<TranslatedDetail {...{ ...props, place: other }} />);
|
||||
|
||||
@@ -3,7 +3,7 @@ import Markdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import remarkBreaks from 'remark-breaks'
|
||||
import { markdownLinkComponents } from '../shared/markdownLink'
|
||||
import { X, Pencil, Copy, Trash2, MapPin, Link2, Plus, ExternalLink, Check, Tag, Tags, Camera, Loader2, Navigation } from 'lucide-react'
|
||||
import { X, Pencil, Copy, Trash2, MapPin, Link2, Plus, ExternalLink, Check, Tags, Camera, Loader2, Navigation } from 'lucide-react'
|
||||
import type { CollectionPlace, CollectionStatus, CollectionLink, CollectionLabel } from '@trek/shared'
|
||||
import type { Category, TranslationFn } from '../../types'
|
||||
import MarkdownToolbar from '../Journey/MarkdownToolbar'
|
||||
@@ -17,6 +17,7 @@ import { Tooltip } from '../shared/Tooltip'
|
||||
import PlaceRating from '../shared/StarRating'
|
||||
import { useCollectionPlaceForm } from './useCollectionPlaceForm'
|
||||
import { CollectionLocationSearch } from './CollectionLocationSearch'
|
||||
import CategoryTileMenu from './CategoryTileMenu'
|
||||
|
||||
function linkHost(url: string): string {
|
||||
try { return new URL(url).hostname.replace(/^www\./, '') } catch { return url }
|
||||
@@ -134,9 +135,13 @@ export default function CollectionPlaceDetail({
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-detail-head">
|
||||
{editing
|
||||
? <input value={name} onChange={e => setName(e.target.value)} className="col-detail-name-input" autoFocus aria-label={t('collections.listName')} />
|
||||
: <h2 className="col-detail-name">{place.name}</h2>}
|
||||
{editing ? (
|
||||
// The category rides in front of the name instead of a chip row in the form.
|
||||
<div className="flex items-center gap-2.5">
|
||||
{categories.length > 0 && <CategoryTileMenu categories={categories} value={categoryId} onChange={setCategoryId} size={40} t={t} />}
|
||||
<input value={name} onChange={e => setName(e.target.value)} className="col-detail-name-input min-w-0 flex-1" autoFocus aria-label={t('common.name')} />
|
||||
</div>
|
||||
) : <h2 className="col-detail-name">{place.name}</h2>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -176,22 +181,6 @@ export default function CollectionPlaceDetail({
|
||||
|
||||
{editing ? (
|
||||
<div className="col-detail-edit">
|
||||
{/* Category */}
|
||||
<div className="col-detail-field">
|
||||
<div className="col-detail-label"><Tag size={12} /> {t('collections.category')}</div>
|
||||
<div className="col-detail-cats">
|
||||
<button type="button" onClick={() => setCategoryId(null)} className={`col-detail-cat${categoryId == null ? ' on' : ''}`}>{t('collections.noCategory')}</button>
|
||||
{categories.map(cat => {
|
||||
const Icon = getCategoryIcon(cat.icon ?? undefined)
|
||||
const on = categoryId === cat.id
|
||||
return (
|
||||
<button key={cat.id} type="button" onClick={() => setCategoryId(cat.id)} className={`col-detail-cat${on ? ' on' : ''}`} style={{ ['--cat' as string]: cat.color || '#6366f1' }}>
|
||||
<Icon size={12} /> {cat.name}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{/* A place that has no position yet can be looked up here (#2837). */}
|
||||
{needsPosition && <CollectionLocationSearch picked={positionPicked} onPick={pickPosition} t={t} />}
|
||||
{/* Address (#1870): free text, the coordinates stay separate */}
|
||||
|
||||
@@ -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<HTMLDivElement>(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.
|
||||
|
||||
@@ -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: <span data-testid="trip-icon" />, count: 8 },
|
||||
{ key: 3, label: 'Food' },
|
||||
];
|
||||
|
||||
function setup(current: string | number = 'all') {
|
||||
const onSelect = vi.fn<(key: string | number) => void>();
|
||||
const view = render(
|
||||
<FilterDropdown current={current} options={OPTIONS} onSelect={onSelect} lead={<span data-testid="lead" />} />
|
||||
);
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<HTMLDivElement>(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 (
|
||||
<div className="col-filter" ref={ref}>
|
||||
<button
|
||||
type="button"
|
||||
className={`col-filter-btn${open ? 'open' : ''}${cur.key === options[0]?.key ? 'is-default' : ''}`}
|
||||
onClick={() => setOpen((o) => !o)}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={open}
|
||||
title={cur.label}
|
||||
>
|
||||
{cur.icon ?? lead}
|
||||
<span className="col-filter-lbl">{cur.label}</span>
|
||||
<ChevronDown size={14} className="col-filter-chev" />
|
||||
</button>
|
||||
{open && (
|
||||
<div className="col-filter-pop" role="listbox">
|
||||
{options.map((o) => (
|
||||
<button
|
||||
key={o.key}
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={o.key === current}
|
||||
className={`col-filter-opt${o.key === current ? 'on' : ''}`}
|
||||
onClick={() => {
|
||||
onSelect(o.key);
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
{o.icon ?? <span className="col-filter-dot ghost" />}
|
||||
<span className="col-filter-lbl">{o.label}</span>
|
||||
{o.count != null && <span className="col-filter-count">{o.count}</span>}
|
||||
{o.key === current && <Check size={13} className="col-filter-check" />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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={(
|
||||
<DialogHeader
|
||||
tile={<DialogTile><FileDown size={20} strokeWidth={1.9} className="text-content-muted" /></DialogTile>}
|
||||
|
||||
@@ -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 <Navigate to={placesPathForLegacy(pathname, search) ?? PLACES_ROOT} replace />;
|
||||
}
|
||||
@@ -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<React.ComponentProps<typeof LibraryFilterBar>, 't'>;
|
||||
|
||||
function Harness(props: Props): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
return <LibraryFilterBar {...props} t={t} />;
|
||||
}
|
||||
|
||||
function setup(over: Partial<Props> = {}) {
|
||||
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(<Harness {...props} />);
|
||||
const triggers = Array.from(view.container.querySelectorAll<HTMLButtonElement>('.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');
|
||||
});
|
||||
});
|
||||
@@ -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: <Luggage size={13} />, count: counts.trip },
|
||||
{ key: 'list', label: t('collections.library.kindLists'), icon: <Bookmark size={13} />, 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: <Icon size={13} style={{ color: STATUS_META[s].color }} />,
|
||||
};
|
||||
}),
|
||||
];
|
||||
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: <Icon size={13} style={{ color: c.color ?? undefined }} /> };
|
||||
}),
|
||||
];
|
||||
const sortOpts: FilterOption[] = [
|
||||
{ key: 'name', label: t('collections.sort.nameAsc') },
|
||||
{ key: 'updated', label: t('collections.library.sortUpdated') },
|
||||
];
|
||||
return (
|
||||
<div className="col-filterbar">
|
||||
<FilterDropdown
|
||||
current={kind}
|
||||
options={kindOpts}
|
||||
onSelect={(k) => onKind(k as LibraryKindFilter)}
|
||||
lead={<Globe2 size={13} />}
|
||||
/>
|
||||
<FilterDropdown
|
||||
current={status}
|
||||
options={statusOpts}
|
||||
onSelect={(k) => onStatus(k as CollectionStatus | 'all')}
|
||||
lead={<Layers size={13} />}
|
||||
/>
|
||||
{categories.length > 0 && (
|
||||
<FilterDropdown
|
||||
current={categoryId}
|
||||
options={catOpts}
|
||||
onSelect={(k) => onCategory(k as number | 'all')}
|
||||
lead={<Tag size={13} />}
|
||||
/>
|
||||
)}
|
||||
<FilterDropdown
|
||||
current={sort}
|
||||
options={sortOpts}
|
||||
onSelect={(k) => onSort(k as PlacesLibrarySort)}
|
||||
lead={<ArrowDownUp size={13} />}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<React.ComponentProps<typeof LibraryOrigins>, 't'>;
|
||||
|
||||
function Harness(props: Props): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
return <LibraryOrigins {...props} t={t} />;
|
||||
}
|
||||
|
||||
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(
|
||||
<Harness origins={[listOrigin({ collection_name: 'Favourites' }), tripOrigin({ trip_title: 'Rome 2026' })]} />
|
||||
);
|
||||
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(
|
||||
<Harness
|
||||
origins={[
|
||||
listOrigin({ collection_place_id: 1, collection_name: 'A list' }),
|
||||
tripOrigin({ place_id: 2, trip_title: 'First trip' }),
|
||||
listOrigin({ collection_place_id: 3, collection_name: 'B list' }),
|
||||
tripOrigin({ place_id: 4, trip_title: 'Second trip' }),
|
||||
]}
|
||||
/>
|
||||
);
|
||||
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(<Harness origins={[tripOrigin()]} />);
|
||||
expect(pillTexts(container)).toEqual(['Rome 2026']);
|
||||
expect(container.querySelector('.col-origin-pill.more')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -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 (
|
||||
<div className="col-lrow-origins">
|
||||
{ordered.slice(0, SHOWN).map((origin) => {
|
||||
const Icon = origin.kind === 'trip' ? Luggage : Bookmark;
|
||||
return (
|
||||
<span
|
||||
key={origin.kind === 'trip' ? `t${origin.place_id}` : `l${origin.collection_place_id}`}
|
||||
className="col-origin-pill"
|
||||
title={
|
||||
origin.kind === 'trip'
|
||||
? t('collections.library.fromTrip', { name: originName(origin) })
|
||||
: t('collections.library.fromList', { name: originName(origin) })
|
||||
}
|
||||
>
|
||||
<Icon size={12} className="flex-none" aria-hidden="true" />
|
||||
<span>{originName(origin)}</span>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
{rest > 0 && (
|
||||
<span className="col-origin-pill more">{t('collections.library.moreOrigins', { count: rest })}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 }) => (
|
||||
<div role="menu" aria-label="nav-menu">
|
||||
{targets.map((target) => (
|
||||
<span key={target.id}>{target.label}</span>
|
||||
))}
|
||||
<button type="button" onClick={onClose}>
|
||||
menu-close
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
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<React.ComponentProps<typeof LibraryPlaceDetail>, 't'>;
|
||||
|
||||
function Harness(props: Props): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
return <LibraryPlaceDetail {...props} t={t} />;
|
||||
}
|
||||
|
||||
/** 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<Props> = {}) {
|
||||
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(<Harness {...props} />);
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<PlacesLibraryOrigin, { kind: 'trip' }>;
|
||||
type ListOrigin = Extract<PlacesLibraryOrigin, { kind: 'list' }>;
|
||||
type TripDetail = Extract<PlacesLibraryDetail, { kind: 'trip' }>;
|
||||
type ListDetail = Extract<PlacesLibraryDetail, { kind: 'list' }>;
|
||||
|
||||
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 (
|
||||
<span className="col-origin-notes">
|
||||
<span className="col-detail-label">
|
||||
<NotebookPen size={11} /> {t('collections.notes')}
|
||||
</span>
|
||||
<span className="txt">{text}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<button
|
||||
type="button"
|
||||
className="col-origin"
|
||||
onClick={onOpen}
|
||||
aria-label={`${t('collections.library.openTrip')}: ${originName(origin)}`}
|
||||
>
|
||||
<span className="col-origin-head">
|
||||
<span className="col-origin-ico">
|
||||
<Luggage size={15} />
|
||||
</span>
|
||||
<span className="col-origin-title">
|
||||
<span className="nm">{originName(origin)}</span>
|
||||
{line && <span className="sub">{line}</span>}
|
||||
</span>
|
||||
{origin.read_only && <span className="col-origin-tag">{t('collections.library.readOnly')}</span>}
|
||||
<ChevronRight size={16} className="col-origin-chev" />
|
||||
</span>
|
||||
{extras && (
|
||||
<span className="col-origin-chips">
|
||||
{detail.info.name !== entryName && (
|
||||
<span className="col-origin-chip">{t('collections.library.calledHere', { name: detail.info.name })}</span>
|
||||
)}
|
||||
{detail.has_accommodation && (
|
||||
<span className="col-origin-chip">
|
||||
<Hotel size={11} /> {t('collections.library.stay')}
|
||||
</span>
|
||||
)}
|
||||
{detail.has_reservation && (
|
||||
<span className="col-origin-chip">
|
||||
<Ticket size={11} /> {t('collections.library.booking')}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<Notes text={detail.notes} t={t} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<button
|
||||
type="button"
|
||||
className="col-origin"
|
||||
onClick={onOpen}
|
||||
aria-label={`${t('collections.library.openList')}: ${originName(origin)}`}
|
||||
>
|
||||
<span className="col-origin-head">
|
||||
<span className="col-origin-ico">
|
||||
<Bookmark size={15} />
|
||||
</span>
|
||||
<span className="col-origin-title">
|
||||
<span className="nm">{originName(origin)}</span>
|
||||
</span>
|
||||
<StatusBadge status={origin.status} t={t} />
|
||||
<ChevronRight size={16} className="col-origin-chev" />
|
||||
</span>
|
||||
{extras && (
|
||||
<span className="col-origin-chips">
|
||||
{detail.info.name !== entryName && (
|
||||
<span className="col-origin-chip">{t('collections.library.calledHere', { name: detail.info.name })}</span>
|
||||
)}
|
||||
{detail.labels.map((label) => (
|
||||
<span
|
||||
key={label.id}
|
||||
className="col-labelchip on static"
|
||||
style={{ ['--label' as string]: label.color || 'var(--accent)' }}
|
||||
>
|
||||
<span className="col-labelchip-dot" /> {label.name}
|
||||
</span>
|
||||
))}
|
||||
{detail.rating.average != null && (
|
||||
<span className="col-origin-chip">
|
||||
<Star size={11} />{' '}
|
||||
{t('collections.library.rating', {
|
||||
rating: detail.rating.average.toFixed(1),
|
||||
count: detail.rating.count,
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<Notes text={detail.notes} t={t} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<HTMLButtonElement>(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 (
|
||||
<div
|
||||
className={`col-detail${anchorRect ? 'docked' : ''}`}
|
||||
style={dockStyle}
|
||||
role="dialog"
|
||||
aria-label={entry?.name ?? t('collections.library.title')}
|
||||
>
|
||||
<div
|
||||
className="col-detail-cover"
|
||||
style={
|
||||
cover ? undefined : { backgroundImage: entityGradient(entry ? entry.key.length + entry.name.length : 0) }
|
||||
}
|
||||
>
|
||||
{cover && <img src={cover} alt="" />}
|
||||
<div className="col-detail-cover-scrim" />
|
||||
<div className="absolute end-[12px] start-[14px] top-[12px] z-[2] flex items-center gap-[8px]">
|
||||
{entry?.category && (
|
||||
<span
|
||||
className="col-detail-cover-cat min-w-0"
|
||||
style={{ ['--cat' as string]: entry.category.color || 'var(--accent)' }}
|
||||
>
|
||||
<CatIcon size={12} className="flex-none" />
|
||||
<span className="truncate">{entry.category.name}</span>
|
||||
</span>
|
||||
)}
|
||||
<button type="button" className="col-detail-close ms-auto" onClick={onClose} aria-label={t('common.close')}>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
{entry && (
|
||||
<div className="col-detail-head">
|
||||
<h2 className="col-detail-name">{entry.name}</h2>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="col-detail-body">
|
||||
{loading && !entry ? (
|
||||
<div className="flex justify-center py-6 text-content-faint">
|
||||
<Loader2 size={20} className="animate-spin" />
|
||||
</div>
|
||||
) : (
|
||||
entry && (
|
||||
<>
|
||||
{(entry.address || entry.lat == null || entry.lng == null) && (
|
||||
<div className="col-detail-meta">
|
||||
{entry.address && (
|
||||
<span className="col-detail-addr">
|
||||
<MapPin size={13} /> {entry.address}
|
||||
</span>
|
||||
)}
|
||||
{(entry.lat == null || entry.lng == null) && (
|
||||
<span className="col-detail-addr">
|
||||
<MapPinOff size={13} className="text-warning" /> {t('places.noCoordinates')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{description && <div className="col-detail-md whitespace-pre-wrap">{description}</div>}
|
||||
{trips.length > 0 && (
|
||||
<section className="col-detail-field">
|
||||
<div className="col-detail-label">
|
||||
<Luggage size={12} /> {t('collections.library.inTrips')}
|
||||
</div>
|
||||
{trips.map(({ origin, detail }) => (
|
||||
<TripCard
|
||||
key={origin.place_id}
|
||||
origin={origin}
|
||||
detail={detail}
|
||||
entryName={entry.name}
|
||||
language={language}
|
||||
onOpen={() => onOpenTrip(origin.trip_id, origin.place_id)}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{lists.length > 0 && (
|
||||
<section className="col-detail-field">
|
||||
<div className="col-detail-label">
|
||||
<Bookmark size={12} /> {t('collections.library.inLists')}
|
||||
</div>
|
||||
{lists.map(({ origin, detail }) => (
|
||||
<ListCard
|
||||
key={origin.collection_place_id}
|
||||
origin={origin}
|
||||
detail={detail}
|
||||
entryName={entry.name}
|
||||
onOpen={() => onOpenList(origin.collection_id, origin.collection_place_id)}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
|
||||
{entry && (
|
||||
<div className="col-detail-footer">
|
||||
{targets.length > 0 && (
|
||||
<>
|
||||
<button
|
||||
ref={navRef}
|
||||
type="button"
|
||||
className="col-detail-btn"
|
||||
onClick={() => (targets.length === 1 ? openNavigationTarget(targets[0]) : setNavOpen((o) => !o))}
|
||||
>
|
||||
<Navigation size={14} />{' '}
|
||||
{targets.length === 1 ? navigationTargetLabel(targets[0], t) : t('inspector.navigation')}
|
||||
</button>
|
||||
{navOpen && (
|
||||
<NavigationMenu targets={targets} anchor={navRef.current} onClose={() => setNavOpen(false)} />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<div className="col-detail-footer-spacer" />
|
||||
{trips[0] && (
|
||||
<button
|
||||
type="button"
|
||||
className="col-detail-btn"
|
||||
onClick={() => onSaveToList(trips[0].origin, trips[0].detail)}
|
||||
>
|
||||
<BookmarkPlus size={14} /> {t('inspector.saveToCollection')}
|
||||
</button>
|
||||
)}
|
||||
{lists[0] && (
|
||||
<button
|
||||
type="button"
|
||||
className="col-detail-btn"
|
||||
onClick={() => onCopyToTrip(lists[0].origin.collection_place_id)}
|
||||
>
|
||||
<Copy size={14} /> {t('collections.copyToTrip')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -131,6 +131,7 @@ describe('ListEditorModal', () => {
|
||||
expect(actions.createCollection).toHaveBeenCalledWith({
|
||||
name: 'Rome',
|
||||
color: '#6366f1',
|
||||
icon: 'Bookmark',
|
||||
description: 'gelato',
|
||||
links: [],
|
||||
})
|
||||
|
||||
@@ -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 = (
|
||||
<DialogHeader
|
||||
tile={<DialogTile><Bookmark size={20} strokeWidth={1.9} style={{ color }} /></DialogTile>}
|
||||
tile={<DialogTile><TileIcon size={20} strokeWidth={1.9} style={{ color }} /></DialogTile>}
|
||||
tint={`color-mix(in srgb, ${color} 12%, transparent)`}
|
||||
labelId={labelId}
|
||||
onClose={onClose}
|
||||
@@ -149,6 +151,29 @@ export default function ListEditorModal({ target, onClose, onCreated, onRequestD
|
||||
</div>
|
||||
</EditorField>
|
||||
|
||||
<EditorField label={t('collections.listIcon')}>
|
||||
<div role="group" aria-label={t('collections.listIcon')} className="flex flex-wrap gap-1.5">
|
||||
{LIST_ICON_NAMES.map(name => {
|
||||
const Icon = LIST_ICONS[name]
|
||||
const on = icon === name
|
||||
return (
|
||||
<button
|
||||
key={name}
|
||||
type="button"
|
||||
onClick={() => setIcon(name)}
|
||||
aria-label={name}
|
||||
aria-pressed={on}
|
||||
className={`grid h-9 w-9 place-items-center rounded-[10px] transition-colors ${on ? '' : 'text-content-muted hover:bg-surface-secondary hover:text-content'}`}
|
||||
// The list's own colour on the picked symbol, the one data-driven value here.
|
||||
style={on ? { color, background: `color-mix(in srgb, ${color} 16%, transparent)` } : undefined}
|
||||
>
|
||||
<Icon size={17} strokeWidth={2} />
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</EditorField>
|
||||
|
||||
<EditorField label={t('collections.description')} htmlFor={`${labelId}-description`}>
|
||||
<textarea
|
||||
id={`${labelId}-description`}
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
import React from 'react'
|
||||
import { Plus, Layers, Users, Upload } from 'lucide-react'
|
||||
import { Plus, Layers, Users, Upload, Globe2 } from 'lucide-react'
|
||||
import type { Collection } from '@trek/shared'
|
||||
import type { TranslationFn } from '../../types'
|
||||
import { ALL_SAVED } from '../../store/collectionStore'
|
||||
import type { ActiveCollectionId, IncomingCollectionInvite } from '../../store/collectionStore'
|
||||
import CollectionInviteCard from './CollectionInviteCard'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { listIcon } from './listIcons'
|
||||
|
||||
interface ListsRailProps {
|
||||
ownedLists: Collection[]
|
||||
sharedLists: Collection[]
|
||||
activeId: ActiveCollectionId
|
||||
/** How many places the lists hold together, beside "All saved". */
|
||||
savedCount?: number
|
||||
/** The overview of every place is open (PLC-07); it sits above the lists. */
|
||||
libraryActive?: boolean
|
||||
onSelectLibrary?: () => void
|
||||
incomingInvites: IncomingCollectionInvite[]
|
||||
onSelect: (id: ActiveCollectionId) => void
|
||||
onNewList: () => void
|
||||
@@ -21,10 +28,12 @@ interface ListsRailProps {
|
||||
}
|
||||
|
||||
function ListRow({ list, active, onSelect }: { list: Collection; active: boolean; onSelect: (id: number) => void }): React.ReactElement {
|
||||
const ListIcon = listIcon(list.icon)
|
||||
return (
|
||||
<div className="col-row">
|
||||
<button type="button" onClick={() => onSelect(list.id)} className={`col-row-btn${active ? ' on' : ''}`}>
|
||||
<span className="dot" style={{ background: list.color || '#6366f1' }} />
|
||||
{/* The list's own symbol in its own colour (the default one without a colour). */}
|
||||
<span className="ico tile list" style={{ ['--list' as string]: list.color || '#6366f1' }}><ListIcon size={15} /></span>
|
||||
<span className="nm">{list.name}</span>
|
||||
<span className="ct">{list.place_count ?? 0}</span>
|
||||
</button>
|
||||
@@ -40,7 +49,7 @@ function ListRow({ list, active, onSelect }: { list: Collection; active: boolean
|
||||
*/
|
||||
export default function ListsRail(props: ListsRailProps): React.ReactElement {
|
||||
const {
|
||||
ownedLists, sharedLists, activeId, incomingInvites,
|
||||
ownedLists, sharedLists, activeId, incomingInvites, libraryActive = false, onSelectLibrary, savedCount = 0,
|
||||
onSelect, onNewList, onImportList, onAcceptInvite, onDeclineInvite, t,
|
||||
} = props
|
||||
|
||||
@@ -48,29 +57,39 @@ export default function ListsRail(props: ListsRailProps): React.ReactElement {
|
||||
<>
|
||||
<div className="col-rail-newrow">
|
||||
<button type="button" onClick={onNewList} className="col-rail-new">
|
||||
<Plus size={16} /> {t('collections.newList')}
|
||||
<span className="col-rail-plus"><Plus size={15} strokeWidth={2.4} /></span> {t('collections.newList')}
|
||||
</button>
|
||||
{/* Import sits beside New rather than in the hero: a file becomes a NEW
|
||||
list, so it belongs where lists are made, not on the one open. */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={onImportList}
|
||||
className="col-rail-new col-rail-import"
|
||||
aria-label={t('collections.file.importButton')}
|
||||
title={t('collections.file.importTitle')}
|
||||
>
|
||||
<Upload size={15} />
|
||||
</button>
|
||||
<Tooltip label={t('collections.file.importTitle')} placement="bottom">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onImportList}
|
||||
className="col-rail-new col-rail-import"
|
||||
aria-label={t('collections.file.importButton')}
|
||||
>
|
||||
<Upload size={16} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{onSelectLibrary && (
|
||||
<div className="col-row">
|
||||
<button type="button" onClick={onSelectLibrary} className={`col-row-btn${libraryActive ? ' on' : ''}`} aria-current={libraryActive ? 'page' : undefined}>
|
||||
<span className="ico tile"><Globe2 size={15} /></span>
|
||||
<span className="nm">{t('collections.library.title')}</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="col-row">
|
||||
<button type="button" onClick={() => onSelect(ALL_SAVED)} className={`col-row-btn${activeId === ALL_SAVED ? ' on' : ''}`}>
|
||||
<span className="ico"><Layers size={16} /></span>
|
||||
<button type="button" onClick={() => onSelect(ALL_SAVED)} className={`col-row-btn${!libraryActive && activeId === ALL_SAVED ? ' on' : ''}`}>
|
||||
<span className="ico tile"><Layers size={15} /></span>
|
||||
<span className="nm">{t('collections.allSaved')}</span>
|
||||
{savedCount > 0 && <span className="ct">{savedCount}</span>}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{ownedLists.length > 0 && <div className="col-rail-sep" />}
|
||||
{ownedLists.length > 0 && <div className="col-rail-label">{t('collections.myLists')}</div>}
|
||||
{ownedLists.map(list => (
|
||||
<ListRow key={list.id} list={list} active={activeId === list.id} onSelect={onSelect} />
|
||||
))}
|
||||
|
||||
@@ -107,7 +107,7 @@ describe('MSaveToCollectionSheet', () => {
|
||||
expect(screen.queryByRole('button', { name: 'View' })).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /New list/ }));
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/collections');
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/places/saved');
|
||||
expect(useSaveToCollectionStore.getState().target).toBeNull();
|
||||
});
|
||||
|
||||
@@ -239,7 +239,7 @@ describe('MSaveToCollectionSheet', () => {
|
||||
await screen.findByText('Favorites');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'View' }));
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/collections');
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/places/saved');
|
||||
expect(useSaveToCollectionStore.getState().target).toBeNull();
|
||||
});
|
||||
|
||||
|
||||
@@ -10,6 +10,9 @@ const SKIP_KEYS: Record<CollectionMapSkipReason, string> = {
|
||||
invalid: 'collections.file.mapSkipInvalid',
|
||||
};
|
||||
|
||||
/** What a list file holds for a place; the file schema leaves its places to the server to check. */
|
||||
type MapPlace = { name?: string; address?: string | null };
|
||||
|
||||
interface MapImportPreviewProps {
|
||||
file: CollectionFile;
|
||||
map: Pick<CollectionMapReadResult, 'skipped' | 'folders'>;
|
||||
@@ -51,7 +54,7 @@ export default function MapImportPreview({
|
||||
</button>
|
||||
</div>
|
||||
<ul className="m-0 flex max-h-[34vh] list-none flex-col gap-0.5 overflow-y-auto rounded-[14px] border border-edge-faint bg-surface-secondary p-1.5">
|
||||
{file.places.map((place, index) => {
|
||||
{(file.places as MapPlace[]).map((place, index) => {
|
||||
const on = picked.has(index);
|
||||
const folder = map.folders[index];
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
// FE-COMP-PLACESLIBVIEW-001 to FE-COMP-PLACESLIBVIEW-020
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import React from 'react';
|
||||
|
||||
import {
|
||||
libraryDetail,
|
||||
libraryEntry,
|
||||
libraryInfo,
|
||||
libraryState,
|
||||
type PlacesLibraryState,
|
||||
threeEntries,
|
||||
tripDetail,
|
||||
tripOrigin,
|
||||
} from '../../../tests/helpers/placesLibrary';
|
||||
import { act, fireEvent, render, screen, within } from '../../../tests/helpers/render';
|
||||
import { resetAllStores } from '../../../tests/helpers/store';
|
||||
import { useTranslation } from '../../i18n/TranslationContext';
|
||||
import { useCollectionStore } from '../../store/collectionStore';
|
||||
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore';
|
||||
import type CollectionMapPanel from './CollectionMapPanel';
|
||||
import type CopyToTripModal from './CopyToTripModal';
|
||||
import type LibraryPlaceDetail from './LibraryPlaceDetail';
|
||||
import PlacesLibraryView from './PlacesLibraryView';
|
||||
|
||||
type MapProps = React.ComponentProps<typeof CollectionMapPanel>;
|
||||
type DetailProps = React.ComponentProps<typeof LibraryPlaceDetail>;
|
||||
type CopyProps = React.ComponentProps<typeof CopyToTripModal>;
|
||||
|
||||
const seen = vi.hoisted(() => ({
|
||||
lib: null as PlacesLibraryState | null,
|
||||
map: null as MapProps | null,
|
||||
detail: null as DetailProps | null,
|
||||
copy: null as CopyProps | null,
|
||||
rect: { left: 300, width: 600 } as { left: number; width: number } | null,
|
||||
}));
|
||||
|
||||
vi.mock('./usePlacesLibrary', () => ({
|
||||
usePlacesLibrary: () => seen.lib,
|
||||
}));
|
||||
|
||||
// The map stack does not render in jsdom; the panel's contract is what the view hands it.
|
||||
vi.mock('./CollectionMapPanel', () => ({
|
||||
default: (props: MapProps) => {
|
||||
seen.map = props;
|
||||
return <div data-testid="map-panel">{`markers:${props.places.length}`}</div>;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('./LibraryPlaceDetail', () => ({
|
||||
default: (props: DetailProps) => {
|
||||
seen.detail = props;
|
||||
return <div data-testid="place-detail" />;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('./CopyToTripModal', () => ({
|
||||
default: (props: CopyProps) => {
|
||||
seen.copy = props;
|
||||
return <div data-testid="copy-modal">{`copy:${props.placeIds.join(',')}`}</div>;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../shared/PlaceAvatar', () => ({ default: () => <span data-testid="avatar" /> }));
|
||||
|
||||
vi.mock('../../hooks/useElementRect', () => ({
|
||||
useElementRect: () => ({ ref: () => undefined, rect: seen.rect }),
|
||||
}));
|
||||
|
||||
function captured<T>(value: T | null): T {
|
||||
if (value == null) throw new Error('not rendered');
|
||||
return value;
|
||||
}
|
||||
|
||||
type ViewProps = Omit<React.ComponentProps<typeof PlacesLibraryView>, 't'>;
|
||||
|
||||
function Harness(props: ViewProps): React.ReactElement {
|
||||
const { t } = useTranslation();
|
||||
return <PlacesLibraryView {...props} t={t} />;
|
||||
}
|
||||
|
||||
const openSave = vi.fn<(target: Parameters<ReturnType<typeof useSaveToCollectionStore.getState>['open']>[0]) => void>();
|
||||
const copyToTrip = vi.fn<ReturnType<typeof useCollectionStore.getState>['copyToTrip']>();
|
||||
|
||||
function setup(lib: Partial<PlacesLibraryState> = {}, over: Partial<ViewProps> = {}) {
|
||||
seen.lib = libraryState(lib);
|
||||
const props: ViewProps = {
|
||||
categories: [],
|
||||
dark: false,
|
||||
isWide: false,
|
||||
language: 'en',
|
||||
view: 'list',
|
||||
onView: vi.fn(),
|
||||
mapLocked: false,
|
||||
onToggleMapLocked: vi.fn(),
|
||||
navigate: vi.fn(),
|
||||
...over,
|
||||
};
|
||||
const view = render(<Harness {...props} />);
|
||||
return { ...view, props, lib: captured(seen.lib) };
|
||||
}
|
||||
|
||||
const rows = () => Array.from(document.querySelectorAll<HTMLElement>('.col-lrow'));
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seen.lib = null;
|
||||
seen.map = null;
|
||||
seen.detail = null;
|
||||
seen.copy = null;
|
||||
seen.rect = { left: 300, width: 600 };
|
||||
openSave.mockReset();
|
||||
copyToTrip.mockReset();
|
||||
copyToTrip.mockResolvedValue({ copied: 1, skipped: [] });
|
||||
useSaveToCollectionStore.setState({ open: openSave });
|
||||
useCollectionStore.setState({ copyToTrip });
|
||||
});
|
||||
|
||||
describe('PlacesLibraryView: the rows', () => {
|
||||
it('FE-COMP-PLACESLIBVIEW-001: one row per place with its name, address and where it comes from', () => {
|
||||
setup({ entries: threeEntries() });
|
||||
expect(rows()).toHaveLength(3);
|
||||
const [first, second] = rows();
|
||||
expect(within(first).getByText('Pantheon')).toBeInTheDocument();
|
||||
expect(within(first).getByText('Piazza della Rotonda')).toBeInTheDocument();
|
||||
expect(within(first).getByText('Rome 2026')).toBeInTheDocument();
|
||||
expect(within(second).getByText('Favourites')).toBeInTheDocument();
|
||||
expect(screen.getAllByTestId('avatar')).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBVIEW-002: a click, Enter or Space opens a place, other keys do not', () => {
|
||||
const { lib } = setup({ entries: threeEntries() });
|
||||
const [first, second, third] = rows();
|
||||
fireEvent.click(first);
|
||||
fireEvent.keyDown(second, { key: 'Enter' });
|
||||
fireEvent.keyDown(third, { key: ' ' });
|
||||
fireEvent.keyDown(third, { key: 'a' });
|
||||
expect(lib.open).toHaveBeenNthCalledWith(1, 'trip:1');
|
||||
expect(lib.open).toHaveBeenNthCalledWith(2, 'trip:2');
|
||||
expect(lib.open).toHaveBeenNthCalledWith(3, 'list:30');
|
||||
expect(lib.open).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBVIEW-003: the open place is marked and its sheet shows', () => {
|
||||
setup({ entries: threeEntries(), selectedKey: 'trip:2' });
|
||||
expect(rows().map((r) => r.classList.contains('sel'))).toEqual([false, true, false]);
|
||||
expect(screen.getByTestId('place-detail')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBVIEW-004: "more" counts what is left, loads it and waits while it loads', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { lib, unmount } = setup({ entries: threeEntries(), total: 8, hasMore: true });
|
||||
await user.click(screen.getByRole('button', { name: 'Show 5 more' }));
|
||||
expect(lib.loadMore).toHaveBeenCalledTimes(1);
|
||||
unmount();
|
||||
|
||||
setup({ entries: threeEntries(), total: 8, hasMore: true, loadingMore: true });
|
||||
expect(screen.getByRole('button', { name: 'Show 5 more' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBVIEW-005: no "more" once everything is there, and no sheet without a place open', () => {
|
||||
setup({ entries: threeEntries(), total: 3 });
|
||||
expect(screen.queryByRole('button', { name: /more/ })).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('place-detail')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('PlacesLibraryView: states', () => {
|
||||
it('FE-COMP-PLACESLIBVIEW-006: offline it says it needs a connection', () => {
|
||||
setup({ offline: true, entries: threeEntries() });
|
||||
expect(screen.getByText('All places needs a connection.')).toBeInTheDocument();
|
||||
expect(rows()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBVIEW-007: a failure shows as an alert', () => {
|
||||
setup({ error: 'Library is down' });
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Library is down');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBVIEW-008: the first load shows a spinner, a later one keeps the rows', () => {
|
||||
const { container, unmount } = setup({ loading: true });
|
||||
expect(container.querySelector('.col-loading')).not.toBeNull();
|
||||
unmount();
|
||||
|
||||
const again = setup({ loading: true, entries: threeEntries() });
|
||||
expect(again.container.querySelector('.col-loading')).toBeNull();
|
||||
expect(rows()).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBVIEW-009: with no places at all it says so and offers nothing to clear', () => {
|
||||
setup();
|
||||
expect(screen.getByText('No places yet')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Clear filters' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBVIEW-010: a filter that matches nothing offers to clear the filters', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { lib } = setup({ filtered: true });
|
||||
expect(screen.getByText('No matches')).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Clear filters' }));
|
||||
expect(lib.resetFilters).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PlacesLibraryView: search, filters and the map', () => {
|
||||
it('FE-COMP-PLACESLIBVIEW-011: on a narrow screen the search sits above the places and there is no map', () => {
|
||||
const { lib } = setup({ entries: threeEntries(), search: 'pan' });
|
||||
const search = screen.getByRole('textbox', { name: 'Search all places' });
|
||||
expect(search).toHaveValue('pan');
|
||||
fireEvent.change(search, { target: { value: 'pant' } });
|
||||
expect(lib.setSearch).toHaveBeenCalledWith('pant');
|
||||
expect(screen.queryByTestId('map-panel')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBVIEW-012: the filter row reaches the hook', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { lib, container } = setup({ entries: threeEntries(), counts: { all: 3, trip: 2, list: 2 } });
|
||||
const kindTrigger = container.querySelector<HTMLButtonElement>('.col-filter-btn');
|
||||
await user.click(captured(kindTrigger));
|
||||
await user.click(screen.getByRole('option', { name: /Trips/ }));
|
||||
expect(lib.setKind).toHaveBeenCalledWith('trip');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBVIEW-013: a wide screen splits into the list and a map of the places with a position', () => {
|
||||
const { container } = setup({ entries: threeEntries(), selectedKey: 'trip:2' }, { isWide: true });
|
||||
expect(container.querySelector('.col-split')).not.toBeNull();
|
||||
expect(screen.getByTestId('map-panel')).toHaveTextContent('markers:2');
|
||||
expect(screen.queryByRole('textbox', { name: 'Search all places' })).not.toBeInTheDocument();
|
||||
const map = captured(seen.map);
|
||||
expect(map.places.map((p) => p.name)).toEqual(['Pantheon', 'Trevi Fountain']);
|
||||
expect(map.selectedPlaceId).toBe(2);
|
||||
expect(map.overlay).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBVIEW-014: a pin opens its place, the map closes it, the map search is the same search', () => {
|
||||
const { lib } = setup({ entries: threeEntries() }, { isWide: true });
|
||||
const map = captured(seen.map);
|
||||
expect(map.selectedPlaceId).toBeNull();
|
||||
act(() => map.onSelect(2));
|
||||
expect(lib.show).toHaveBeenCalledWith('trip:2');
|
||||
act(() => map.onSelect(99));
|
||||
expect(lib.show).toHaveBeenCalledTimes(1);
|
||||
act(() => map.onDeselect());
|
||||
expect(lib.close).toHaveBeenCalledTimes(1);
|
||||
act(() => map.onSearch('trevi'));
|
||||
expect(lib.setSearch).toHaveBeenCalledWith('trevi');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBVIEW-015: going to the map alone closes the place, coming back does not', () => {
|
||||
const { lib, props, unmount } = setup({ entries: threeEntries() }, { isWide: true, view: 'list' });
|
||||
act(() => captured(seen.map).onToggleView());
|
||||
expect(lib.close).toHaveBeenCalledTimes(1);
|
||||
expect(props.onView).toHaveBeenCalledWith('map');
|
||||
unmount();
|
||||
|
||||
const back = setup({ entries: threeEntries() }, { isWide: true, view: 'map' });
|
||||
expect(back.container.querySelector('.col-split.map-full')).not.toBeNull();
|
||||
act(() => captured(seen.map).onToggleView());
|
||||
expect(back.lib.close).not.toHaveBeenCalled();
|
||||
expect(back.props.onView).toHaveBeenCalledWith('list');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBVIEW-016: a wide screen without any position keeps the plain list', () => {
|
||||
const unplaced = threeEntries().map((e) => ({ ...e, lat: null, lng: null }));
|
||||
const { container } = setup({ entries: unplaced }, { isWide: true });
|
||||
expect(container.querySelector('.col-split')).toBeNull();
|
||||
expect(screen.getByRole('textbox', { name: 'Search all places' })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('PlacesLibraryView: the place sheet', () => {
|
||||
it('FE-COMP-PLACESLIBVIEW-017: the sheet docks over the list, over the map alone, or nowhere without the split', () => {
|
||||
const split = setup({ entries: threeEntries(), selectedKey: 'trip:1' }, { isWide: true });
|
||||
expect(captured(seen.detail).anchorRect).toEqual({ left: 300, width: 600 });
|
||||
split.unmount();
|
||||
|
||||
const mapAlone = setup({ entries: threeEntries(), selectedKey: 'trip:1' }, { isWide: true, view: 'map' });
|
||||
expect(captured(seen.detail).anchorRect).toEqual({ left: 312, width: 420 });
|
||||
mapAlone.unmount();
|
||||
|
||||
seen.rect = { left: 0, width: 300 };
|
||||
const narrowMap = setup({ entries: threeEntries(), selectedKey: 'trip:1' }, { isWide: true, view: 'map' });
|
||||
expect(captured(seen.detail).anchorRect).toEqual({ left: 12, width: 276 });
|
||||
narrowMap.unmount();
|
||||
|
||||
seen.rect = null;
|
||||
const unmeasured = setup({ entries: threeEntries(), selectedKey: 'trip:1' }, { isWide: true, view: 'map' });
|
||||
expect(captured(seen.detail).anchorRect).toBeNull();
|
||||
unmeasured.unmount();
|
||||
|
||||
setup({ entries: threeEntries(), selectedKey: 'trip:1' });
|
||||
expect(captured(seen.detail).anchorRect).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBVIEW-018: the sheet gets what the hook loaded and opens a list or a trip by its route', () => {
|
||||
const detail = libraryDetail(libraryEntry(), [tripDetail()]);
|
||||
const { lib, props } = setup({
|
||||
entries: threeEntries(),
|
||||
selectedKey: 'trip:42',
|
||||
detail,
|
||||
detailLoading: true,
|
||||
cover: '/uploads/c.jpg',
|
||||
});
|
||||
const sheet = captured(seen.detail);
|
||||
expect(sheet.data).toBe(detail);
|
||||
expect(sheet.loading).toBe(true);
|
||||
expect(sheet.cover).toBe('/uploads/c.jpg');
|
||||
expect(sheet.language).toBe('en');
|
||||
|
||||
act(() => sheet.onOpenList(3, 30));
|
||||
expect(props.navigate).toHaveBeenLastCalledWith('/places/3?place=30');
|
||||
act(() => sheet.onOpenTrip(5, 42));
|
||||
expect(props.navigate).toHaveBeenLastCalledWith('/trips/5?place=42');
|
||||
act(() => sheet.onClose());
|
||||
expect(lib.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBVIEW-019: keeping a trip place in a list hands over what the trip knows of it', () => {
|
||||
const entry = libraryEntry({ category: { id: 3, name: 'Restaurant', color: null, icon: null } });
|
||||
setup({ entries: [entry], selectedKey: 'trip:42', detail: libraryDetail(entry, [tripDetail()]) });
|
||||
const info = libraryInfo({
|
||||
name: 'Colosseo',
|
||||
description: 'Arena',
|
||||
website: 'https://colosseo.example',
|
||||
phone: '+39 06',
|
||||
image_url: '/uploads/c.jpg',
|
||||
});
|
||||
act(() => captured(seen.detail).onSaveToList(tripOrigin(), tripDetail({ info })));
|
||||
expect(openSave).toHaveBeenCalledWith({
|
||||
name: 'Colosseo',
|
||||
source_trip_id: 5,
|
||||
source_place_id: 42,
|
||||
description: 'Arena',
|
||||
lat: 41.89,
|
||||
lng: 12.49,
|
||||
address: 'Piazza del Colosseo',
|
||||
category_id: 3,
|
||||
image_url: '/uploads/c.jpg',
|
||||
website: 'https://colosseo.example',
|
||||
phone: '+39 06',
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBVIEW-020: copying a saved place opens the trip picker, which copies it and closes', async () => {
|
||||
setup({ entries: threeEntries(), selectedKey: 'list:30' });
|
||||
expect(screen.queryByTestId('copy-modal')).not.toBeInTheDocument();
|
||||
act(() => captured(seen.detail).onCopyToTrip(900));
|
||||
expect(screen.getByTestId('copy-modal')).toHaveTextContent('copy:900');
|
||||
|
||||
const modal = captured(seen.copy);
|
||||
expect(modal.isOpen).toBe(true);
|
||||
const carry = { include_notes: true } as Parameters<CopyProps['onCopy']>[1];
|
||||
await act(async () => {
|
||||
await modal.onCopy(7, carry);
|
||||
});
|
||||
expect(copyToTrip).toHaveBeenCalledWith(7, [900], undefined, carry);
|
||||
|
||||
act(() => modal.onClose());
|
||||
expect(screen.queryByTestId('copy-modal')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,305 @@
|
||||
import type { CollectionPlace, PlacesLibraryEntry } from '@trek/shared';
|
||||
import { Loader2, MapPin, Search } from 'lucide-react';
|
||||
import React, { useMemo, useState } from 'react';
|
||||
import { useElementRect } from '../../hooks/useElementRect';
|
||||
import { useCollectionStore } from '../../store/collectionStore';
|
||||
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore';
|
||||
import type { Category, TranslationFn } from '../../types';
|
||||
import { placesPath } from '../../utils/placesRoutes';
|
||||
import EmptyState from '../shared/EmptyState';
|
||||
import PlaceAvatar from '../shared/PlaceAvatar';
|
||||
import CategoryBadge from './CategoryBadge';
|
||||
import CollectionMapPanel from './CollectionMapPanel';
|
||||
import CopyToTripModal from './CopyToTripModal';
|
||||
import LibraryFilterBar from './LibraryFilterBar';
|
||||
import LibraryOrigins from './LibraryOrigins';
|
||||
import LibraryPlaceDetail from './LibraryPlaceDetail';
|
||||
import { usePlacesLibrary } from './usePlacesLibrary';
|
||||
|
||||
interface PlacesLibraryViewProps {
|
||||
categories: Category[];
|
||||
dark: boolean;
|
||||
isWide: boolean;
|
||||
language: string;
|
||||
/** The list and map halves of the page, shared with the lists: split, or the map alone. */
|
||||
view: 'list' | 'map';
|
||||
onView: (view: 'list' | 'map') => void;
|
||||
mapLocked: boolean;
|
||||
onToggleMapLocked: () => void;
|
||||
navigate: (to: string) => void;
|
||||
t: TranslationFn;
|
||||
}
|
||||
|
||||
/** A map point per entry with a position; the map speaks CollectionPlace, keyed by a running id. */
|
||||
function toMapPlaces(entries: PlacesLibraryEntry[]) {
|
||||
const keyOf = new Map<number, string>();
|
||||
const idOf = new Map<string, number>();
|
||||
const places = entries.flatMap((entry, i) => {
|
||||
if (entry.lat == null || entry.lng == null) return [];
|
||||
const id = i + 1;
|
||||
keyOf.set(id, entry.key);
|
||||
idOf.set(entry.key, id);
|
||||
return [
|
||||
{
|
||||
id,
|
||||
name: entry.name,
|
||||
lat: entry.lat,
|
||||
lng: entry.lng,
|
||||
address: entry.address,
|
||||
image_url: entry.image_url,
|
||||
category_id: entry.category?.id ?? null,
|
||||
category: entry.category,
|
||||
status: 'idea',
|
||||
} as unknown as CollectionPlace,
|
||||
];
|
||||
});
|
||||
return { places, keyOf, idOf };
|
||||
}
|
||||
|
||||
/**
|
||||
* "All places" on the desktop (PLC-07): every place of the user's trips and lists,
|
||||
* one row each with where it comes from, beside a map of them, with the same filter
|
||||
* row, map bar (search, lock, list toggle) and place sheet as a list. Opening a place
|
||||
* docks its sheet over the list column (PLC-08); the list keeps its scroll underneath.
|
||||
*/
|
||||
export default function PlacesLibraryView({
|
||||
categories,
|
||||
dark,
|
||||
isWide,
|
||||
language,
|
||||
view,
|
||||
onView,
|
||||
mapLocked,
|
||||
onToggleMapLocked,
|
||||
navigate,
|
||||
t,
|
||||
}: PlacesLibraryViewProps): React.ReactElement {
|
||||
const lib = usePlacesLibrary({ active: true, t });
|
||||
const openSave = useSaveToCollectionStore((s) => s.open);
|
||||
const copyToTrip = useCollectionStore((s) => s.copyToTrip);
|
||||
const [copyId, setCopyId] = useState<number | null>(null);
|
||||
const listCol = useElementRect<HTMLDivElement>();
|
||||
const mapCol = useElementRect<HTMLDivElement>();
|
||||
const map = useMemo(() => toMapPlaces(lib.entries), [lib.entries]);
|
||||
const selectedMapId = lib.selectedKey ? (map.idOf.get(lib.selectedKey) ?? null) : null;
|
||||
const split = isWide && map.places.length > 0;
|
||||
|
||||
const filterBar = (
|
||||
<LibraryFilterBar
|
||||
kind={lib.kind}
|
||||
counts={lib.counts}
|
||||
onKind={lib.setKind}
|
||||
status={lib.status}
|
||||
onStatus={lib.setStatus}
|
||||
categoryId={lib.categoryId}
|
||||
categories={categories}
|
||||
onCategory={lib.setCategoryId}
|
||||
sort={lib.sort}
|
||||
onSort={lib.setSort}
|
||||
t={t}
|
||||
/>
|
||||
);
|
||||
|
||||
let rows: React.ReactNode;
|
||||
if (lib.offline) rows = <EmptyState scene="search" title={t('collections.library.offline')} />;
|
||||
else if (lib.error)
|
||||
rows = (
|
||||
<p role="alert" className="m-0 rounded-xl bg-danger-soft px-3 py-2 text-body text-danger">
|
||||
{lib.error}
|
||||
</p>
|
||||
);
|
||||
else if (lib.loading && lib.entries.length === 0)
|
||||
rows = (
|
||||
<div className="col-loading">
|
||||
<div className="col-spinner" />
|
||||
</div>
|
||||
);
|
||||
else if (lib.entries.length === 0) {
|
||||
rows = (
|
||||
<div className="flex flex-col items-center">
|
||||
<EmptyState
|
||||
scene={lib.filtered ? 'search' : 'collections'}
|
||||
title={t(lib.filtered ? 'collections.empty.noMatchTitle' : 'collections.library.emptyTitle')}
|
||||
className={lib.filtered ? 'pb-4' : undefined}
|
||||
/>
|
||||
{lib.filtered && (
|
||||
<button type="button" onClick={lib.resetFilters} className="col-cta col-cta-ghost">
|
||||
{t('collections.library.resetFilters')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
rows = (
|
||||
<div className="col-listview">
|
||||
{lib.entries.map((entry) => (
|
||||
<div
|
||||
key={entry.key}
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
data-no-press
|
||||
onClick={() => lib.open(entry.key)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
lib.open(entry.key);
|
||||
}
|
||||
}}
|
||||
className={`col-lrow${lib.selectedKey === entry.key ? 'sel' : ''}`}
|
||||
>
|
||||
<span className="col-lrow-avatar">
|
||||
<PlaceAvatar
|
||||
place={{
|
||||
id: map.idOf.get(entry.key) ?? 0,
|
||||
name: entry.name,
|
||||
image_url: entry.image_url,
|
||||
google_place_id: null,
|
||||
osm_id: null,
|
||||
lat: entry.lat,
|
||||
lng: entry.lng,
|
||||
}}
|
||||
size={40}
|
||||
category={
|
||||
entry.category
|
||||
? ({ color: entry.category.color ?? undefined, icon: entry.category.icon ?? undefined } as Category)
|
||||
: null
|
||||
}
|
||||
/>
|
||||
</span>
|
||||
<div className="li">
|
||||
<div className="t">
|
||||
{entry.category?.name && <CategoryBadge category={entry.category} />}
|
||||
<span className="nm">{entry.name}</span>
|
||||
</div>
|
||||
{entry.address && (
|
||||
<div className="s">
|
||||
<MapPin size={11} />
|
||||
<span>{entry.address}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<LibraryOrigins origins={entry.origins} t={t} />
|
||||
</div>
|
||||
))}
|
||||
{lib.hasMore && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void lib.loadMore()}
|
||||
disabled={lib.loadingMore}
|
||||
className="col-cta col-cta-ghost self-center"
|
||||
>
|
||||
{lib.loadingMore && <Loader2 size={15} className="animate-spin" />}{' '}
|
||||
{t('collections.library.more', { count: lib.total - lib.entries.length })}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// The map carries the search on a wide screen, as it does for a list; without it the row above the places does.
|
||||
const listColumn = (
|
||||
<>
|
||||
{!split && (
|
||||
<div className="col-toolbar">
|
||||
<div className="col-toolbar-spacer" />
|
||||
<div className="col-search">
|
||||
<Search size={15} />
|
||||
<input
|
||||
value={lib.search}
|
||||
onChange={(e) => lib.setSearch(e.target.value)}
|
||||
placeholder={t('collections.library.search')}
|
||||
aria-label={t('collections.library.search')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{filterBar}
|
||||
{rows}
|
||||
</>
|
||||
);
|
||||
|
||||
const anchor = !split
|
||||
? null
|
||||
: view === 'map'
|
||||
? mapCol.rect
|
||||
? { left: mapCol.rect.left + 12, width: Math.min(420, mapCol.rect.width - 24) }
|
||||
: null // rtl-lint-disable: a measured viewport position, like the list dock
|
||||
: listCol.rect;
|
||||
|
||||
return (
|
||||
<>
|
||||
{split ? (
|
||||
<div className={`col-split${view === 'map' ? 'map-full' : ''}`}>
|
||||
<div className="col-split-list" ref={listCol.ref}>
|
||||
{listColumn}
|
||||
</div>
|
||||
<div className="col-split-map" ref={mapCol.ref}>
|
||||
<CollectionMapPanel
|
||||
places={map.places}
|
||||
selectedPlaceId={selectedMapId}
|
||||
onSelect={(id) => {
|
||||
const key = map.keyOf.get(id);
|
||||
if (key) lib.show(key);
|
||||
}}
|
||||
onDeselect={lib.close}
|
||||
dark={dark}
|
||||
overlay
|
||||
view={view}
|
||||
onToggleView={() => {
|
||||
if (view !== 'map') lib.close();
|
||||
onView(view === 'map' ? 'list' : 'map');
|
||||
}}
|
||||
search={lib.search}
|
||||
onSearch={lib.setSearch}
|
||||
mapLocked={mapLocked}
|
||||
onToggleMapLocked={onToggleMapLocked}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
listColumn
|
||||
)}
|
||||
|
||||
{lib.selectedKey && (
|
||||
<LibraryPlaceDetail
|
||||
data={lib.detail}
|
||||
loading={lib.detailLoading}
|
||||
cover={lib.cover}
|
||||
language={language}
|
||||
anchorRect={anchor}
|
||||
onClose={lib.close}
|
||||
onOpenList={(collectionId, placeId) => navigate(`${placesPath(collectionId)}?place=${placeId}`)}
|
||||
onOpenTrip={(tripId, placeId) => navigate(`/trips/${tripId}?place=${placeId}`)}
|
||||
onSaveToList={(origin, d) =>
|
||||
openSave({
|
||||
name: d.info.name,
|
||||
source_trip_id: origin.trip_id,
|
||||
source_place_id: origin.place_id,
|
||||
description: d.info.description,
|
||||
lat: d.info.lat,
|
||||
lng: d.info.lng,
|
||||
address: d.info.address,
|
||||
category_id: lib.detail?.entry.category?.id ?? null,
|
||||
image_url: d.info.image_url,
|
||||
website: d.info.website,
|
||||
phone: d.info.phone,
|
||||
})
|
||||
}
|
||||
onCopyToTrip={setCopyId}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
|
||||
{copyId != null && (
|
||||
<CopyToTripModal
|
||||
isOpen
|
||||
placeIds={[copyId]}
|
||||
onClose={() => setCopyId(null)}
|
||||
onCopy={(tripId, carry) => copyToTrip(tripId, [copyId], undefined, carry)}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -112,7 +112,7 @@ describe('SaveToCollectionModal', () => {
|
||||
|
||||
expect(await screen.findByText('Create a list first to save places.')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: /New list/ }));
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/collections');
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/places/saved');
|
||||
expect(useSaveToCollectionStore.getState().target).toBeNull();
|
||||
});
|
||||
|
||||
@@ -327,7 +327,7 @@ describe('SaveToCollectionModal', () => {
|
||||
await screen.findByText('Favorites');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'View' }));
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/collections');
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/places/saved');
|
||||
expect(useSaveToCollectionStore.getState().target).toBeNull();
|
||||
unmount();
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
// FE-COMP-LIBDATES-001 to FE-COMP-LIBDATES-003
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { dayDate, tripLine, tripRange } from './libraryDates';
|
||||
|
||||
describe('libraryDates', () => {
|
||||
it('FE-COMP-LIBDATES-001: a trip reads as one short range, or one date when only one end is known', () => {
|
||||
// ICU spaces the dash differently between versions.
|
||||
expect(tripRange('2026-12-01', '2026-12-05', 'en-GB')).toMatch(/^1\s?–\s?5 Dec$/);
|
||||
expect(tripRange('2026-12-01', null, 'en-GB')).toBe('1 Dec');
|
||||
expect(tripRange(null, null, 'en-GB')).toBeNull();
|
||||
expect(tripRange('not a date', null, 'en-GB')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-LIBDATES-002: a planned day carries its weekday', () => {
|
||||
expect(dayDate('2026-12-02', 'en-GB')).toMatch(/^Wed,? 2 Dec$/);
|
||||
expect(dayDate(null, 'en-GB')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-LIBDATES-003: a trip origin names its planned day, counts the others, or falls back to the trip dates', () => {
|
||||
const t = (k: string, p?: Record<string, string | number>) => `${k}${p ? JSON.stringify(p) : ''}`;
|
||||
const trip = { trip_start: '2026-12-01', trip_end: '2026-12-05' };
|
||||
const day = (n: number, time: string | null) => ({
|
||||
day_id: n,
|
||||
day_number: n,
|
||||
date: '2026-12-02',
|
||||
title: null,
|
||||
time,
|
||||
end_time: null,
|
||||
});
|
||||
expect(tripLine(trip, { days: [] }, 'en-GB', t)).toMatch(/^1\s?–\s?5 Dec$/);
|
||||
expect(tripLine(trip, { days: [day(2, '10:00')] }, 'en-GB', t)).toMatch(
|
||||
/^collections\.library\.dayOn\{"day":2,"date":"Wed,? 2 Dec, 10:00"\}$/
|
||||
);
|
||||
expect(tripLine(trip, { days: [day(2, null), day(3, null)] }, 'en-GB', t)).toMatch(
|
||||
/collections\.library\.moreOrigins\{"count":1\}$/
|
||||
);
|
||||
expect(tripLine(trip, { days: [{ ...day(4, null), date: null }] }, 'en-GB', t)).toBe(
|
||||
'collections.library.day{"day":4}'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { PlacesLibraryTripDetail, PlacesLibraryTripOrigin } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* The dates of "All places" in the reader's language: a trip as one short range
|
||||
* ("1 to 5 Dec" in the locale's own form), a planned day as its weekday and date ("Wed, 2 Dec"). Dates are
|
||||
* calendar days without a time zone, read and written in UTC so no zone shifts them.
|
||||
*/
|
||||
const SHORT: Intl.DateTimeFormatOptions = { day: 'numeric', month: 'short', timeZone: 'UTC' };
|
||||
|
||||
const asDate = (iso: string | null | undefined): Date | null => {
|
||||
if (!iso) return null;
|
||||
const d = new Date(`${iso.slice(0, 10)}T00:00:00Z`);
|
||||
return Number.isNaN(d.getTime()) ? null : d;
|
||||
};
|
||||
|
||||
export function tripRange(
|
||||
start: string | null | undefined,
|
||||
end: string | null | undefined,
|
||||
language: string
|
||||
): string | null {
|
||||
const a = asDate(start);
|
||||
const b = asDate(end);
|
||||
if (a && b) return new Intl.DateTimeFormat(language, SHORT).formatRange(a, b);
|
||||
const one = a ?? b;
|
||||
return one ? new Intl.DateTimeFormat(language, SHORT).format(one) : null;
|
||||
}
|
||||
|
||||
export function dayDate(date: string | null | undefined, language: string): string | null {
|
||||
const d = asDate(date);
|
||||
return d ? new Intl.DateTimeFormat(language, { ...SHORT, weekday: 'short' }).format(d) : null;
|
||||
}
|
||||
|
||||
/** What a trip origin says under its name: the planned day, or the trip's dates when it is not planned yet. */
|
||||
export function tripLine(
|
||||
origin: Pick<PlacesLibraryTripOrigin, 'trip_start' | 'trip_end'>,
|
||||
detail: Pick<PlacesLibraryTripDetail, 'days'>,
|
||||
language: string,
|
||||
t: (key: string, params?: Record<string, string | number>) => string
|
||||
): string | null {
|
||||
const day = detail.days[0];
|
||||
if (!day) return tripRange(origin.trip_start, origin.trip_end, language);
|
||||
const when = [dayDate(day.date, language), day.time].filter(Boolean).join(', ');
|
||||
const first = when
|
||||
? t('collections.library.dayOn', { day: day.day_number, date: when })
|
||||
: t('collections.library.day', { day: day.day_number });
|
||||
return detail.days.length > 1
|
||||
? `${first} ${t('collections.library.moreOrigins', { count: detail.days.length - 1 })}`
|
||||
: first;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// FE-COMP-LISTICONS-001
|
||||
import { Bookmark, Heart } from 'lucide-react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { DEFAULT_LIST_ICON, LIST_ICON_NAMES, listIcon } from './listIcons';
|
||||
|
||||
describe('listIcons', () => {
|
||||
it('FE-COMP-LISTICONS-001: resolves a known symbol and falls back to the bookmark', () => {
|
||||
expect(listIcon('Heart')).toBe(Heart);
|
||||
expect(listIcon('NoSuchIcon')).toBe(Bookmark);
|
||||
expect(listIcon(null)).toBe(Bookmark);
|
||||
expect(LIST_ICON_NAMES[0]).toBe(DEFAULT_LIST_ICON);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import {
|
||||
Baby,
|
||||
Bed,
|
||||
Bike,
|
||||
Bookmark,
|
||||
Camera,
|
||||
Coffee,
|
||||
Flag,
|
||||
Gift,
|
||||
Heart,
|
||||
Landmark,
|
||||
type LucideIcon,
|
||||
MapPin,
|
||||
Mountain,
|
||||
Music,
|
||||
Palette,
|
||||
PawPrint,
|
||||
Plane,
|
||||
ShoppingBag,
|
||||
Snowflake,
|
||||
Star,
|
||||
Sun,
|
||||
TreePine,
|
||||
Utensils,
|
||||
Waves,
|
||||
Wine,
|
||||
} from 'lucide-react';
|
||||
|
||||
/**
|
||||
* The symbols a list can wear (the column has always been there, holding "Bookmark").
|
||||
* A small curated set rather than every Lucide icon: a list is told apart at a glance,
|
||||
* and two dozen symbols are enough for food, nature, culture, nights out and stays.
|
||||
*/
|
||||
export const LIST_ICONS: Record<string, LucideIcon> = {
|
||||
Bookmark,
|
||||
Heart,
|
||||
Star,
|
||||
Utensils,
|
||||
Coffee,
|
||||
Wine,
|
||||
Landmark,
|
||||
Palette,
|
||||
Music,
|
||||
Camera,
|
||||
Mountain,
|
||||
TreePine,
|
||||
Waves,
|
||||
Sun,
|
||||
Snowflake,
|
||||
Bike,
|
||||
Bed,
|
||||
Plane,
|
||||
ShoppingBag,
|
||||
Gift,
|
||||
Baby,
|
||||
PawPrint,
|
||||
Flag,
|
||||
MapPin,
|
||||
};
|
||||
|
||||
export const LIST_ICON_NAMES = Object.keys(LIST_ICONS);
|
||||
export const DEFAULT_LIST_ICON = 'Bookmark';
|
||||
|
||||
/** The symbol of a list; one this build does not know falls back to the bookmark. */
|
||||
export function listIcon(name: string | null | undefined): LucideIcon {
|
||||
return (name && LIST_ICONS[name]) || Bookmark;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-COMP-LISTEDITORHOOK-001 to FE-COMP-LISTEDITORHOOK-011: the list create / edit logic
|
||||
// FE-COMP-LISTEDITORHOOK-001 to FE-COMP-LISTEDITORHOOK-012: the list create / edit logic
|
||||
// behind both the desktop dialog and the phone sheet.
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import type { Collection } from '@trek/shared';
|
||||
@@ -136,6 +136,7 @@ describe('useListEditor', () => {
|
||||
expect(actions.createCollection).toHaveBeenCalledWith({
|
||||
name: 'Rome',
|
||||
color: '#6366f1',
|
||||
icon: 'Bookmark',
|
||||
description: null,
|
||||
links: [{ label: 'Map', url: 'https://maps.example' }],
|
||||
});
|
||||
@@ -153,6 +154,7 @@ describe('useListEditor', () => {
|
||||
expect(actions.updateCollection).toHaveBeenCalledWith(4, {
|
||||
name: 'Tokyo',
|
||||
color: '#ec4899',
|
||||
icon: 'Bookmark',
|
||||
description: 'Food spots',
|
||||
links: [{ label: 'Blog', url: 'https://a.example' }],
|
||||
cover_image: 'https://img.example/u.jpg',
|
||||
@@ -240,4 +242,14 @@ describe('useListEditor', () => {
|
||||
unmount();
|
||||
expect(URL.revokeObjectURL).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('FE-COMP-LISTEDITORHOOK-012: a list keeps the symbol it was given, and a picked one is saved', async () => {
|
||||
const { result } = setup({ target: { ...LIST, icon: 'Wine' } });
|
||||
expect(result.current.icon).toBe('Wine');
|
||||
act(() => result.current.setIcon('Heart'));
|
||||
await act(async () => {
|
||||
await result.current.save();
|
||||
});
|
||||
expect(actions.updateCollection).toHaveBeenCalledWith(4, expect.objectContaining({ icon: 'Heart' }));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useCollectionStore } from '../../store/collectionStore';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { getApiErrorMessage } from '../../utils/apiError';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import { DEFAULT_LIST_ICON } from './listIcons';
|
||||
|
||||
export interface CoverSearchPhoto {
|
||||
id: string;
|
||||
@@ -62,6 +63,7 @@ export function useListEditor({
|
||||
|
||||
const [name, setName] = useState('');
|
||||
const [color, setColor] = useState(defaultColor);
|
||||
const [icon, setIcon] = useState(DEFAULT_LIST_ICON);
|
||||
const [description, setDescription] = useState('');
|
||||
const [links, setLinks] = useState<CollectionLink[]>([]);
|
||||
const [coverFile, setCoverFile] = useState<File | null>(null);
|
||||
@@ -90,6 +92,7 @@ export function useListEditor({
|
||||
const edit = target !== 'new' ? target : null;
|
||||
setName(edit?.name ?? '');
|
||||
setColor(edit?.color ?? defaultColor);
|
||||
setIcon(edit?.icon || DEFAULT_LIST_ICON);
|
||||
setDescription(edit?.description ?? '');
|
||||
setLinks(edit?.links ?? []);
|
||||
setCoverFile(null);
|
||||
@@ -156,6 +159,7 @@ export function useListEditor({
|
||||
const payload = {
|
||||
name: trimmed,
|
||||
color,
|
||||
icon,
|
||||
description: description.trim() || null,
|
||||
links: cleanListLinks(links, normalizeLinkUrl),
|
||||
...(pendingUnsplashUrl ? { cover_image: pendingUnsplashUrl } : {}),
|
||||
@@ -187,6 +191,8 @@ export function useListEditor({
|
||||
setName,
|
||||
color,
|
||||
setColor,
|
||||
icon,
|
||||
setIcon,
|
||||
description,
|
||||
setDescription,
|
||||
links,
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
// FE-COMP-PLACESLIBHOOK-001 to FE-COMP-PLACESLIBHOOK-025: the "All places" logic behind
|
||||
// the desktop view and the phone screen (PLC-07, PLC-08).
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import type { PlacesLibraryDetailResponse, PlacesLibraryPageResponse } from '@trek/shared';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import {
|
||||
libraryDetail,
|
||||
libraryEntry,
|
||||
libraryInfo,
|
||||
libraryPage,
|
||||
listDetail,
|
||||
listOrigin,
|
||||
tripDetail,
|
||||
} from '../../../tests/helpers/placesLibrary';
|
||||
import { OnlineOnlyError } from '../../repo/onlineOnly';
|
||||
import { placesLibraryRepo } from '../../repo/placesLibraryRepo';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { entryHasPosition, parseEntryKey, usePlacesLibrary } from './usePlacesLibrary';
|
||||
|
||||
vi.mock('../../repo/placesLibraryRepo', () => ({
|
||||
placesLibraryRepo: { list: vi.fn(), detail: vi.fn(), coverPhoto: vi.fn() },
|
||||
}));
|
||||
|
||||
const list = vi.mocked(placesLibraryRepo.list);
|
||||
const detail = vi.mocked(placesLibraryRepo.detail);
|
||||
const coverPhoto = vi.mocked(placesLibraryRepo.coverPhoto);
|
||||
|
||||
// A stable identity t: the hook's failure handler depends on it.
|
||||
const t: TranslationFn = (key) => key;
|
||||
|
||||
const FIRST_PAGE = { sort: 'name', limit: 60 };
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve: (value: T) => void = () => undefined;
|
||||
const promise = new Promise<T>((res) => {
|
||||
resolve = res;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function apiError(message: string) {
|
||||
return { response: { data: { error: message } } };
|
||||
}
|
||||
|
||||
function mount(active = true) {
|
||||
return renderHook(({ on }: { on: boolean }) => usePlacesLibrary({ active: on, t }), {
|
||||
initialProps: { on: active },
|
||||
});
|
||||
}
|
||||
|
||||
async function mountLoaded(page: PlacesLibraryPageResponse = libraryPage([libraryEntry()])) {
|
||||
list.mockResolvedValue(page);
|
||||
const view = mount();
|
||||
await waitFor(() => expect(view.result.current.loading).toBe(false));
|
||||
return view;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
list.mockReset();
|
||||
detail.mockReset();
|
||||
coverPhoto.mockReset();
|
||||
coverPhoto.mockResolvedValue(null);
|
||||
});
|
||||
|
||||
describe('parseEntryKey and entryHasPosition', () => {
|
||||
it('FE-COMP-PLACESLIBHOOK-001: reads a trip or list key and refuses anything else', () => {
|
||||
expect(parseEntryKey('trip:42')).toEqual({ kind: 'trip', id: 42 });
|
||||
expect(parseEntryKey('list:900')).toEqual({ kind: 'list', id: 900 });
|
||||
expect(parseEntryKey('own:3')).toBeNull();
|
||||
expect(parseEntryKey('trip:abc')).toBeNull();
|
||||
expect(parseEntryKey('trip:4:5')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-002: an entry is a map point only with two finite coordinates', () => {
|
||||
expect(entryHasPosition({ lat: 41.9, lng: 12.5 })).toBe(true);
|
||||
expect(entryHasPosition({ lat: 0, lng: 0 })).toBe(true);
|
||||
expect(entryHasPosition({ lat: null, lng: 12.5 })).toBe(false);
|
||||
expect(entryHasPosition({ lat: 41.9, lng: null })).toBe(false);
|
||||
expect(entryHasPosition({ lat: Number.NaN, lng: 12.5 })).toBe(false);
|
||||
expect(entryHasPosition({ lat: 41.9, lng: Number.POSITIVE_INFINITY })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('usePlacesLibrary: the first page', () => {
|
||||
it('FE-COMP-PLACESLIBHOOK-003: asks nothing while inactive and loads once it becomes active', async () => {
|
||||
list.mockResolvedValue(libraryPage([]));
|
||||
const { rerender, result } = mount(false);
|
||||
expect(list).not.toHaveBeenCalled();
|
||||
expect(result.current.loading).toBe(false);
|
||||
|
||||
rerender({ on: true });
|
||||
await waitFor(() => expect(list).toHaveBeenCalledTimes(1));
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-004: loads the first page with its total, counts and cursor', async () => {
|
||||
const pending = deferred<PlacesLibraryPageResponse>();
|
||||
list.mockReturnValue(pending.promise);
|
||||
const { result } = mount();
|
||||
expect(result.current.loading).toBe(true);
|
||||
expect(list).toHaveBeenCalledWith(FIRST_PAGE, expect.any(AbortSignal));
|
||||
|
||||
const placed = libraryEntry({ key: 'trip:1', name: 'Pantheon' });
|
||||
const unplaced = libraryEntry({ key: 'list:2', name: 'Somewhere', lat: null, lng: null });
|
||||
await act(async () => {
|
||||
pending.resolve(
|
||||
libraryPage([placed, unplaced], { total: 7, counts: { all: 7, trip: 4, list: 3 }, next_cursor: 'c1' })
|
||||
);
|
||||
await pending.promise;
|
||||
});
|
||||
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.entries).toEqual([placed, unplaced]);
|
||||
expect(result.current.mappable).toEqual([placed]);
|
||||
expect(result.current.total).toBe(7);
|
||||
expect(result.current.counts).toEqual({ all: 7, trip: 4, list: 3 });
|
||||
expect(result.current.hasMore).toBe(true);
|
||||
expect(result.current.error).toBeNull();
|
||||
expect(result.current.offline).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-005: without a connection it says offline instead of failing', async () => {
|
||||
list.mockRejectedValue(new OnlineOnlyError());
|
||||
const { result } = mount();
|
||||
await waitFor(() => expect(result.current.offline).toBe(true));
|
||||
expect(result.current.error).toBeNull();
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
|
||||
it("FE-COMP-PLACESLIBHOOK-006: a failure shows the server's message, else the generic error", async () => {
|
||||
list.mockRejectedValueOnce(apiError('Library is down'));
|
||||
const { result } = mount();
|
||||
await waitFor(() => expect(result.current.error).toBe('Library is down'));
|
||||
|
||||
list.mockRejectedValueOnce(new Error('network'));
|
||||
act(() => result.current.reload());
|
||||
await waitFor(() => expect(result.current.error).toBe('common.error'));
|
||||
expect(result.current.offline).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-007: reload asks for the first page again and clears an earlier error', async () => {
|
||||
list.mockRejectedValueOnce(apiError('Boom'));
|
||||
const { result } = mount();
|
||||
await waitFor(() => expect(result.current.error).toBe('Boom'));
|
||||
|
||||
list.mockResolvedValueOnce(libraryPage([libraryEntry()]));
|
||||
act(() => result.current.reload());
|
||||
await waitFor(() => expect(result.current.entries).toHaveLength(1));
|
||||
expect(result.current.error).toBeNull();
|
||||
expect(list).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('usePlacesLibrary: filters and search', () => {
|
||||
it('FE-COMP-PLACESLIBHOOK-008: each filter goes to the server and marks the overview as filtered', async () => {
|
||||
const { result } = await mountLoaded(libraryPage([]));
|
||||
expect(result.current.filtered).toBe(false);
|
||||
|
||||
act(() => result.current.setKind('trip'));
|
||||
await waitFor(() =>
|
||||
expect(list).toHaveBeenLastCalledWith({ ...FIRST_PAGE, kind: 'trip' }, expect.any(AbortSignal))
|
||||
);
|
||||
expect(result.current.filtered).toBe(true);
|
||||
|
||||
act(() => {
|
||||
result.current.setCategoryId(3);
|
||||
result.current.setStatus('want');
|
||||
result.current.setSort('updated');
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(list).toHaveBeenLastCalledWith(
|
||||
{ kind: 'trip', category_id: 3, status: 'want', sort: 'updated', limit: 60 },
|
||||
expect.any(AbortSignal)
|
||||
)
|
||||
);
|
||||
expect(result.current.kind).toBe('trip');
|
||||
expect(result.current.categoryId).toBe(3);
|
||||
expect(result.current.status).toBe('want');
|
||||
expect(result.current.sort).toBe('updated');
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-009: clearing the filters keeps the order but drops every filter', async () => {
|
||||
const { result } = await mountLoaded(libraryPage([]));
|
||||
act(() => {
|
||||
result.current.setKind('list');
|
||||
result.current.setStatus('visited');
|
||||
result.current.setSort('updated');
|
||||
result.current.setSearch('rome');
|
||||
});
|
||||
await waitFor(() => expect(result.current.filtered).toBe(true));
|
||||
|
||||
act(() => result.current.resetFilters());
|
||||
expect(result.current.search).toBe('');
|
||||
expect(result.current.kind).toBe('all');
|
||||
expect(result.current.categoryId).toBe('all');
|
||||
expect(result.current.status).toBe('all');
|
||||
expect(result.current.sort).toBe('updated');
|
||||
expect(result.current.filtered).toBe(false);
|
||||
await waitFor(() => expect(list).toHaveBeenLastCalledWith({ sort: 'updated', limit: 60 }, expect.any(AbortSignal)));
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-010: typing settles before it asks, trimmed, and only the last word asks', async () => {
|
||||
const { result } = await mountLoaded(libraryPage([]));
|
||||
act(() => result.current.setSearch('ro'));
|
||||
act(() => result.current.setSearch(' rome '));
|
||||
expect(result.current.search).toBe(' rome ');
|
||||
expect(list).toHaveBeenCalledTimes(1);
|
||||
expect(result.current.filtered).toBe(false);
|
||||
|
||||
await waitFor(() => expect(list).toHaveBeenLastCalledWith({ ...FIRST_PAGE, q: 'rome' }, expect.any(AbortSignal)));
|
||||
expect(list).toHaveBeenCalledTimes(2);
|
||||
expect(list).not.toHaveBeenCalledWith(expect.objectContaining({ q: 'ro' }), expect.anything());
|
||||
expect(result.current.filtered).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-011: a filter change drops the page still on its way', async () => {
|
||||
const stale = deferred<PlacesLibraryPageResponse>();
|
||||
list.mockReturnValueOnce(stale.promise);
|
||||
const { result } = mount();
|
||||
const firstSignal = list.mock.calls[0]?.[1];
|
||||
|
||||
const fresh = libraryEntry({ key: 'trip:2', name: 'Fresh' });
|
||||
list.mockResolvedValueOnce(libraryPage([fresh]));
|
||||
act(() => result.current.setKind('trip'));
|
||||
expect(firstSignal?.aborted).toBe(true);
|
||||
await waitFor(() => expect(result.current.entries).toEqual([fresh]));
|
||||
|
||||
await act(async () => {
|
||||
stale.resolve(libraryPage([libraryEntry({ key: 'trip:1', name: 'Stale' })]));
|
||||
await stale.promise;
|
||||
});
|
||||
expect(result.current.entries).toEqual([fresh]);
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('usePlacesLibrary: more pages', () => {
|
||||
it('FE-COMP-PLACESLIBHOOK-012: "more" appends the next page from the cursor without doubles', async () => {
|
||||
const { result } = await mountLoaded(
|
||||
libraryPage([libraryEntry({ key: 'trip:1' }), libraryEntry({ key: 'trip:2' })], {
|
||||
total: 3,
|
||||
next_cursor: 'c1',
|
||||
})
|
||||
);
|
||||
list.mockResolvedValueOnce(
|
||||
libraryPage([libraryEntry({ key: 'trip:2' }), libraryEntry({ key: 'trip:3' })], { next_cursor: null })
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.loadMore();
|
||||
});
|
||||
|
||||
expect(list).toHaveBeenLastCalledWith({ ...FIRST_PAGE, cursor: 'c1' }, expect.any(AbortSignal));
|
||||
expect(result.current.entries.map((e) => e.key)).toEqual(['trip:1', 'trip:2', 'trip:3']);
|
||||
expect(result.current.hasMore).toBe(false);
|
||||
expect(result.current.loadingMore).toBe(false);
|
||||
expect(result.current.total).toBe(3);
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-013: "more" asks nothing when there is no next page', async () => {
|
||||
const { result } = await mountLoaded(libraryPage([libraryEntry()]));
|
||||
await act(async () => {
|
||||
await result.current.loadMore();
|
||||
});
|
||||
expect(list).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-014: "more" shows its loading state and a failure as the error', async () => {
|
||||
const { result } = await mountLoaded(libraryPage([libraryEntry()], { next_cursor: 'c1' }));
|
||||
const next = deferred<PlacesLibraryPageResponse>();
|
||||
list.mockReturnValueOnce(next.promise.then(() => Promise.reject(apiError('Page gone'))));
|
||||
|
||||
let call: Promise<void> = Promise.resolve();
|
||||
act(() => {
|
||||
call = result.current.loadMore();
|
||||
});
|
||||
expect(result.current.loadingMore).toBe(true);
|
||||
|
||||
await act(async () => {
|
||||
next.resolve(libraryPage([]));
|
||||
await call;
|
||||
});
|
||||
expect(result.current.loadingMore).toBe(false);
|
||||
expect(result.current.error).toBe('Page gone');
|
||||
expect(result.current.entries).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-025: a filter changed while "more" loads frees the button again', async () => {
|
||||
const { result } = await mountLoaded(libraryPage([libraryEntry()], { next_cursor: 'c1' }));
|
||||
const next = deferred<PlacesLibraryPageResponse>();
|
||||
list.mockReturnValueOnce(next.promise);
|
||||
act(() => {
|
||||
void result.current.loadMore();
|
||||
});
|
||||
expect(result.current.loadingMore).toBe(true);
|
||||
list.mockResolvedValue(libraryPage([libraryEntry()]));
|
||||
act(() => result.current.setKind('trip'));
|
||||
expect(result.current.loadingMore).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-015: "more" without a connection says offline', async () => {
|
||||
const { result } = await mountLoaded(libraryPage([libraryEntry()], { next_cursor: 'c1' }));
|
||||
list.mockRejectedValueOnce(new OnlineOnlyError());
|
||||
await act(async () => {
|
||||
await result.current.loadMore();
|
||||
});
|
||||
expect(result.current.offline).toBe(true);
|
||||
expect(result.current.error).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('usePlacesLibrary: the open entry', () => {
|
||||
it('FE-COMP-PLACESLIBHOOK-016: opening an entry loads what its origin keeps; opening it again closes it', async () => {
|
||||
const { result } = await mountLoaded();
|
||||
const answer = libraryDetail(libraryEntry({ image_url: '/uploads/own.jpg' }), [tripDetail()]);
|
||||
const pending = deferred<PlacesLibraryDetailResponse>();
|
||||
detail.mockReturnValueOnce(pending.promise);
|
||||
|
||||
act(() => result.current.open('trip:42'));
|
||||
expect(result.current.selectedKey).toBe('trip:42');
|
||||
expect(result.current.detailLoading).toBe(true);
|
||||
expect(detail).toHaveBeenCalledWith('trip', 42, expect.any(AbortSignal));
|
||||
|
||||
await act(async () => {
|
||||
pending.resolve(answer);
|
||||
await pending.promise;
|
||||
});
|
||||
expect(result.current.detail).toBe(answer);
|
||||
expect(result.current.detailLoading).toBe(false);
|
||||
|
||||
act(() => result.current.open('trip:42'));
|
||||
expect(result.current.selectedKey).toBeNull();
|
||||
expect(result.current.detail).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-017: show keeps an entry open, close shuts it, a saved place is asked as a list one', async () => {
|
||||
const { result } = await mountLoaded();
|
||||
detail.mockResolvedValue(libraryDetail(libraryEntry({ key: 'list:900', origins: [listOrigin()] }), [listDetail()]));
|
||||
|
||||
act(() => result.current.show('list:900'));
|
||||
act(() => result.current.show('list:900'));
|
||||
expect(result.current.selectedKey).toBe('list:900');
|
||||
await waitFor(() => expect(result.current.detail?.entry.key).toBe('list:900'));
|
||||
expect(detail).toHaveBeenCalledTimes(1);
|
||||
expect(detail).toHaveBeenCalledWith('list', 900, expect.any(AbortSignal));
|
||||
|
||||
act(() => result.current.close());
|
||||
expect(result.current.selectedKey).toBeNull();
|
||||
expect(result.current.detail).toBeNull();
|
||||
expect(result.current.cover).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-018: a key it cannot read loads nothing', async () => {
|
||||
const { result } = await mountLoaded();
|
||||
act(() => result.current.open('own:5'));
|
||||
expect(result.current.selectedKey).toBe('own:5');
|
||||
expect(detail).not.toHaveBeenCalled();
|
||||
expect(result.current.detail).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-019: a failed detail closes the entry and shows the error', async () => {
|
||||
const { result } = await mountLoaded();
|
||||
detail.mockRejectedValueOnce(apiError('Place is gone'));
|
||||
act(() => result.current.open('trip:42'));
|
||||
await waitFor(() => expect(result.current.error).toBe('Place is gone'));
|
||||
expect(result.current.selectedKey).toBeNull();
|
||||
expect(result.current.detail).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-020: a detail without a connection says offline', async () => {
|
||||
const { result } = await mountLoaded();
|
||||
detail.mockRejectedValueOnce(new OnlineOnlyError());
|
||||
act(() => result.current.open('trip:42'));
|
||||
await waitFor(() => expect(result.current.offline).toBe(true));
|
||||
expect(result.current.selectedKey).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-021: reload asks for the open entry again too', async () => {
|
||||
const { result } = await mountLoaded();
|
||||
detail.mockResolvedValue(libraryDetail(libraryEntry(), [tripDetail()]));
|
||||
act(() => result.current.open('trip:42'));
|
||||
await waitFor(() => expect(result.current.detail).not.toBeNull());
|
||||
|
||||
act(() => result.current.reload());
|
||||
await waitFor(() => expect(detail).toHaveBeenCalledTimes(2));
|
||||
expect(list).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('usePlacesLibrary: the cover', () => {
|
||||
it("FE-COMP-PLACESLIBHOOK-022: the entry's own image wins, else the first origin image", async () => {
|
||||
const { result } = await mountLoaded();
|
||||
detail.mockResolvedValueOnce(libraryDetail(libraryEntry({ image_url: '/uploads/entry.jpg' }), [tripDetail()]));
|
||||
act(() => result.current.open('trip:42'));
|
||||
await waitFor(() => expect(result.current.cover).toBe('/uploads/entry.jpg'));
|
||||
|
||||
act(() => result.current.close());
|
||||
detail.mockResolvedValueOnce(
|
||||
libraryDetail(libraryEntry({ key: 'trip:7', origins: [] }), [
|
||||
tripDetail(),
|
||||
listDetail({ info: libraryInfo({ image_url: '/uploads/list.jpg' }) }),
|
||||
])
|
||||
);
|
||||
act(() => result.current.open('trip:7'));
|
||||
await waitFor(() => expect(result.current.cover).toBe('/uploads/list.jpg'));
|
||||
expect(coverPhoto).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("FE-COMP-PLACESLIBHOOK-023: without an image of its own it asks the provider's photo", async () => {
|
||||
const { result } = await mountLoaded();
|
||||
const entry = libraryEntry();
|
||||
coverPhoto.mockResolvedValueOnce('https://photos.example/colosseum.jpg');
|
||||
detail.mockResolvedValueOnce(libraryDetail(entry, [tripDetail()]));
|
||||
act(() => result.current.open('trip:42'));
|
||||
await waitFor(() => expect(result.current.cover).toBe('https://photos.example/colosseum.jpg'));
|
||||
expect(coverPhoto).toHaveBeenCalledWith(entry);
|
||||
});
|
||||
|
||||
it('FE-COMP-PLACESLIBHOOK-024: a failed photo lookup leaves the gradient', async () => {
|
||||
const { result } = await mountLoaded();
|
||||
coverPhoto.mockRejectedValueOnce(new Error('no photo'));
|
||||
detail.mockResolvedValueOnce(libraryDetail(libraryEntry(), [tripDetail()]));
|
||||
act(() => result.current.open('trip:42'));
|
||||
await waitFor(() => expect(coverPhoto).toHaveBeenCalledTimes(1));
|
||||
await act(async () => {
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(result.current.cover).toBeNull();
|
||||
expect(result.current.detail).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,249 @@
|
||||
import type {
|
||||
CollectionStatus,
|
||||
PlacesLibraryCounts,
|
||||
PlacesLibraryDetailResponse,
|
||||
PlacesLibraryEntry,
|
||||
PlacesLibraryKind,
|
||||
PlacesLibrarySort,
|
||||
} from '@trek/shared';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
|
||||
import { OnlineOnlyError } from '../../repo/onlineOnly';
|
||||
import { placesLibraryRepo } from '../../repo/placesLibraryRepo';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { getApiErrorMessage } from '../../utils/apiError';
|
||||
|
||||
/** Which origins the overview shows: all, only trip places, only saved ones. */
|
||||
export type LibraryKindFilter = 'all' | PlacesLibraryKind;
|
||||
|
||||
const PAGE = 60;
|
||||
/** How long typing settles before the search asks the server. */
|
||||
const SEARCH_SETTLE_MS = 250;
|
||||
const NO_COUNTS: PlacesLibraryCounts = { all: 0, trip: 0, list: 0 };
|
||||
|
||||
/** The origin an entry is opened from: its key, `trip:<place id>` or `list:<saved place id>`. */
|
||||
export function parseEntryKey(key: string): { kind: PlacesLibraryKind; id: number } | null {
|
||||
const match = /^(trip|list):(\d+)$/.exec(key);
|
||||
return match ? { kind: match[1] as PlacesLibraryKind, id: Number(match[2]) } : null;
|
||||
}
|
||||
|
||||
/** An entry with coordinates, as a point for the map. */
|
||||
export function entryHasPosition(entry: Pick<PlacesLibraryEntry, 'lat' | 'lng'>): boolean {
|
||||
return entry.lat != null && entry.lng != null && Number.isFinite(entry.lat) && Number.isFinite(entry.lng);
|
||||
}
|
||||
|
||||
/**
|
||||
* "All places" (PLC-07, PLC-08): every place of the user's trips and lists in one
|
||||
* overview, behind the desktop view and the phone screen, which render their own
|
||||
* markup over it. Online only like the lists themselves; a filter change starts a
|
||||
* fresh first page, "more" appends the next one, and opening an entry loads what
|
||||
* each of its origins keeps.
|
||||
*/
|
||||
export function usePlacesLibrary({ active, t }: { active: boolean; t: TranslationFn }) {
|
||||
const [search, setSearch] = useState('');
|
||||
const [query, setQuery] = useState('');
|
||||
const [kind, setKind] = useState<LibraryKindFilter>('all');
|
||||
const [categoryId, setCategoryId] = useState<number | 'all'>('all');
|
||||
const [sort, setSort] = useState<PlacesLibrarySort>('name');
|
||||
const [status, setStatus] = useState<CollectionStatus | 'all'>('all');
|
||||
|
||||
const [entries, setEntries] = useState<PlacesLibraryEntry[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [counts, setCounts] = useState<PlacesLibraryCounts>(NO_COUNTS);
|
||||
const [cursor, setCursor] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [loadingMore, setLoadingMore] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [offline, setOffline] = useState(false);
|
||||
const [reloadSeq, setReloadSeq] = useState(0);
|
||||
|
||||
const [selectedKey, setSelectedKey] = useState<string | null>(null);
|
||||
const [detail, setDetail] = useState<PlacesLibraryDetailResponse | null>(null);
|
||||
const [detailLoading, setDetailLoading] = useState(false);
|
||||
// The provider's photo for a place without its own, as a list's place sheet shows it.
|
||||
const [cover, setCover] = useState<string | null>(null);
|
||||
|
||||
// Typing settles before it asks.
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setQuery(search.trim()), SEARCH_SETTLE_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [search]);
|
||||
|
||||
const filters = useMemo(
|
||||
() => ({
|
||||
...(query ? { q: query } : {}),
|
||||
...(kind !== 'all' ? { kind } : {}),
|
||||
...(categoryId !== 'all' ? { category_id: categoryId } : {}),
|
||||
...(status !== 'all' ? { status } : {}),
|
||||
sort,
|
||||
limit: PAGE,
|
||||
}),
|
||||
[query, kind, categoryId, status, sort]
|
||||
);
|
||||
|
||||
const fail = useCallback(
|
||||
(err: unknown) => {
|
||||
if (err instanceof OnlineOnlyError) setOffline(true);
|
||||
else setError(getApiErrorMessage(err, t('common.error')));
|
||||
},
|
||||
[t]
|
||||
);
|
||||
|
||||
// The first page, again for every filter change and every reload.
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
const ctrl = new AbortController();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setOffline(false);
|
||||
placesLibraryRepo
|
||||
.list(filters, ctrl.signal)
|
||||
.then((page) => {
|
||||
if (ctrl.signal.aborted) return;
|
||||
setEntries(page.entries);
|
||||
setTotal(page.total);
|
||||
setCounts(page.counts);
|
||||
setCursor(page.next_cursor);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!ctrl.signal.aborted) fail(err);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!ctrl.signal.aborted) setLoading(false);
|
||||
});
|
||||
return () => ctrl.abort();
|
||||
}, [active, filters, reloadSeq, fail]);
|
||||
|
||||
const moreRef = useRef<AbortController | null>(null);
|
||||
const loadMore = useCallback(async () => {
|
||||
if (!cursor || loadingMore) return;
|
||||
moreRef.current?.abort();
|
||||
const ctrl = new AbortController();
|
||||
moreRef.current = ctrl;
|
||||
setLoadingMore(true);
|
||||
try {
|
||||
const page = await placesLibraryRepo.list({ ...filters, cursor }, ctrl.signal);
|
||||
if (ctrl.signal.aborted) return;
|
||||
setEntries((prev) => [...prev, ...page.entries.filter((e) => !prev.some((p) => p.key === e.key))]);
|
||||
setCursor(page.next_cursor);
|
||||
} catch (err) {
|
||||
if (!ctrl.signal.aborted) fail(err);
|
||||
} finally {
|
||||
// Only the latest request lets go of the button: an aborted one was replaced or
|
||||
// dropped by a filter change, which lets go of it itself.
|
||||
if (moreRef.current === ctrl) setLoadingMore(false);
|
||||
}
|
||||
}, [cursor, loadingMore, filters, fail]);
|
||||
|
||||
// A filter change starts over, so a page still on its way is dropped and "more" is free again.
|
||||
useEffect(
|
||||
() => () => {
|
||||
moreRef.current?.abort();
|
||||
moreRef.current = null;
|
||||
setLoadingMore(false);
|
||||
},
|
||||
[filters]
|
||||
);
|
||||
|
||||
// The entry that is open, and what its origins keep.
|
||||
useEffect(() => {
|
||||
const ref = selectedKey ? parseEntryKey(selectedKey) : null;
|
||||
if (!ref) {
|
||||
setDetail(null);
|
||||
return;
|
||||
}
|
||||
const ctrl = new AbortController();
|
||||
setDetailLoading(true);
|
||||
placesLibraryRepo
|
||||
.detail(ref.kind, ref.id, ctrl.signal)
|
||||
.then((res) => {
|
||||
if (!ctrl.signal.aborted) setDetail(res);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (ctrl.signal.aborted) return;
|
||||
setDetail(null);
|
||||
setSelectedKey(null);
|
||||
fail(err);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!ctrl.signal.aborted) setDetailLoading(false);
|
||||
});
|
||||
return () => {
|
||||
ctrl.abort();
|
||||
setDetailLoading(false);
|
||||
};
|
||||
}, [selectedKey, reloadSeq, fail]);
|
||||
|
||||
useEffect(() => {
|
||||
setCover(null);
|
||||
const entry = detail?.entry;
|
||||
if (!entry) return;
|
||||
const own = entry.image_url ?? detail.details.map((d) => d.info.image_url).find(Boolean) ?? null;
|
||||
if (own) {
|
||||
setCover(own);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
placesLibraryRepo
|
||||
.coverPhoto(entry)
|
||||
.then((url) => {
|
||||
if (!cancelled) setCover(url);
|
||||
})
|
||||
// No photo is the gradient, which is what a failed lookup should look like too.
|
||||
.catch(() => {
|
||||
if (!cancelled) setCover(null);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [detail]);
|
||||
|
||||
const reload = useCallback(() => setReloadSeq((n) => n + 1), []);
|
||||
const open = useCallback((key: string | null) => setSelectedKey((cur) => (cur === key ? null : key)), []);
|
||||
const show = useCallback((key: string) => setSelectedKey(key), []);
|
||||
const close = useCallback(() => setSelectedKey(null), []);
|
||||
|
||||
const filtered = query !== '' || kind !== 'all' || categoryId !== 'all' || status !== 'all';
|
||||
const resetFilters = useCallback(() => {
|
||||
setSearch('');
|
||||
setQuery('');
|
||||
setKind('all');
|
||||
setCategoryId('all');
|
||||
setStatus('all');
|
||||
}, []);
|
||||
|
||||
const mappable = useMemo(() => entries.filter(entryHasPosition), [entries]);
|
||||
|
||||
return {
|
||||
search,
|
||||
setSearch,
|
||||
kind,
|
||||
setKind,
|
||||
categoryId,
|
||||
setCategoryId,
|
||||
sort,
|
||||
setSort,
|
||||
status,
|
||||
setStatus,
|
||||
filtered,
|
||||
resetFilters,
|
||||
entries,
|
||||
mappable,
|
||||
total,
|
||||
counts,
|
||||
hasMore: cursor != null,
|
||||
loading,
|
||||
loadingMore,
|
||||
loadMore,
|
||||
error,
|
||||
offline,
|
||||
reload,
|
||||
selectedKey,
|
||||
open,
|
||||
show,
|
||||
close,
|
||||
detail,
|
||||
detailLoading,
|
||||
cover,
|
||||
};
|
||||
}
|
||||
@@ -271,7 +271,7 @@ describe('useSaveToCollection', () => {
|
||||
act(() => result.current.openCollections());
|
||||
|
||||
expect(useSaveToCollectionStore.getState().target).toBeNull();
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/collections');
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/places/saved');
|
||||
});
|
||||
|
||||
it('FE-COMP-SAVETOCOLHOOK-014: a load landing after the target changed is dropped', async () => {
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useTranslation } from '../../i18n';
|
||||
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore';
|
||||
import { useServerPing } from '../../sync/useServerPing';
|
||||
import { getApiErrorMessage } from '../../utils/apiError';
|
||||
import { PLACES_SAVED } from '../../utils/placesRoutes';
|
||||
import { useToast } from '../shared/Toast';
|
||||
|
||||
type MembershipEntry = CollectionMembership['lists'][number];
|
||||
@@ -193,7 +194,7 @@ export function useSaveToCollection() {
|
||||
|
||||
const openCollections = () => {
|
||||
close();
|
||||
navigate('/collections');
|
||||
navigate(PLACES_SAVED);
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useTranslation } from '../../i18n'
|
||||
import { entityGradient } from '../../utils/gradients'
|
||||
import { useCollectionLists } from './useCollectionLists'
|
||||
import { readShownCollections, rememberShownCollections } from './collectionsWidgetMemory'
|
||||
import { placesPath } from '../../utils/placesRoutes'
|
||||
|
||||
/**
|
||||
* Dashboard sidebar widget — a glassy `.tool` card that surfaces the user's
|
||||
@@ -47,7 +48,7 @@ export default function CollectionsWidget({ onOpen }: { onOpen: () => void }): R
|
||||
key={list.id}
|
||||
className="col-badge"
|
||||
style={{ ['--badge-color' as string]: list.color || '#6366f1' }}
|
||||
onClick={() => navigate(`/collections/${list.id}`)}
|
||||
onClick={() => navigate(placesPath(list.id))}
|
||||
>
|
||||
{list.cover_image
|
||||
? <img className="col-badge-media" src={list.cover_image} alt="" />
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { LucideIcon } from 'lucide-react'
|
||||
import { resolvePluginIcon } from '../shared/PluginIcon'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { visibleManagedNavItems } from '../../managed'
|
||||
import { addonPath } from './navItems'
|
||||
import { isNavItemActive, useCreateAction } from './useCreateAction'
|
||||
|
||||
const ADDON_NAV: Record<string, { icon: LucideIcon; labelKey: string }> = {
|
||||
@@ -37,7 +38,7 @@ export default function BottomNav() {
|
||||
{ to: '/dashboard', label: t('nav.myTrips'), icon: LayoutGrid },
|
||||
...globalAddons.flatMap(addon => {
|
||||
const nav = ADDON_NAV[addon.id]
|
||||
return nav ? [{ to: `/${addon.id}`, label: t(nav.labelKey), icon: nav.icon }] : []
|
||||
return nav ? [{ to: addonPath(addon.id), label: t(nav.labelKey), icon: nav.icon }] : []
|
||||
}),
|
||||
...pagePlugins.map(p => ({ to: `/plugins/${p.id}`, label: p.name, icon: resolvePluginIcon(p.icon) })),
|
||||
// Empty in this repository — see client/src/managed.
|
||||
|
||||
@@ -17,6 +17,7 @@ import { useCollapseOnOverflow } from '../../hooks/useCollapseOnOverflow'
|
||||
import { openMailInbox } from '../MailIngest/mailInboxOpener'
|
||||
import { useMailInboxShell } from '../MailIngest/useMailInboxShell'
|
||||
import MailInboxDialog from '../MailIngest/MailInboxDialog'
|
||||
import { addonPath } from './navItems'
|
||||
import UserMenuFooter from './UserMenuFooter'
|
||||
|
||||
const ADDON_ICONS: Record<string, LucideIcon> = { CalendarDays, Briefcase, Globe, Compass, Bookmark }
|
||||
@@ -105,7 +106,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
|
||||
}
|
||||
|
||||
const tabs = [{ id: '__trips', path: '/dashboard', label: t('nav.myTrips'), Icon: Briefcase },
|
||||
...globalAddons.map(a => ({ id: a.id, path: `/${a.id}`, label: getAddonName(a), Icon: ADDON_ICONS[a.icon] || CalendarDays })),
|
||||
...globalAddons.map(a => ({ id: a.id, path: addonPath(a.id), label: getAddonName(a), Icon: ADDON_ICONS[a.icon] || CalendarDays })),
|
||||
...pagePlugins.map(p => ({ id: `plugin:${p.id}`, path: `/plugins/${p.id}`, label: p.name, Icon: resolvePluginIcon(p.icon) })),
|
||||
// Empty in this repository — see client/src/managed.
|
||||
...visibleManagedNavItems(user?.role === 'admin').map(m => ({ id: `managed:${m.id}`, path: m.path, label: m.label, Icon: m.Icon }))
|
||||
|
||||
@@ -54,6 +54,11 @@ export const MOBILE_NAV_MAX_BAR = 2
|
||||
* assistant comes last: it takes a slot only one of the addons left free, rather
|
||||
* than sitting alone behind the More button.
|
||||
*/
|
||||
/** Where an addon's page lives: its id, except Collections, which became Places (PLC-07). */
|
||||
export function addonPath(id: string): string {
|
||||
return id === 'collections' ? '/places' : `/${id}`
|
||||
}
|
||||
|
||||
export const DEFAULT_DOCK_IDS = ['vacay', 'journey', 'atlas', 'collections', ASSISTANT_NAV_ID]
|
||||
|
||||
export function buildNavItems(
|
||||
@@ -68,7 +73,7 @@ export function buildNavItems(
|
||||
const translated = t(key)
|
||||
return {
|
||||
id: a.id,
|
||||
to: `/${a.id}`,
|
||||
to: addonPath(a.id),
|
||||
label: translated && translated !== key ? translated : a.name || a.id,
|
||||
icon: ADDON_ICONS[a.id] ?? resolvePluginIcon(a.icon),
|
||||
}
|
||||
|
||||
@@ -91,14 +91,14 @@ describe('useCreateAction', () => {
|
||||
});
|
||||
|
||||
it('FE-COMP-CREATEACTION-008: collections add a place to the open list on the phone only', () => {
|
||||
const all = at('/collections', true);
|
||||
const all = at('/places', true);
|
||||
expect(all.label).toBe('collections.addPlace');
|
||||
act(() => all.run());
|
||||
expect(mockNavigate).toHaveBeenLastCalledWith('/collections?create=place');
|
||||
const one = at('/collections/12', true);
|
||||
expect(mockNavigate).toHaveBeenLastCalledWith('/places?create=place');
|
||||
const one = at('/places/12', true);
|
||||
act(() => one.run());
|
||||
expect(mockNavigate).toHaveBeenLastCalledWith('/collections/12?create=place');
|
||||
expect(at('/collections/12', false).label).toBe('dashboard.newTrip');
|
||||
expect(mockNavigate).toHaveBeenLastCalledWith('/places/12?create=place');
|
||||
expect(at('/places/12', false).label).toBe('dashboard.newTrip');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -27,8 +27,8 @@ export function useCreateAction(phone: boolean): CreateAction {
|
||||
const inJourney = useMatch('/journey/:id');
|
||||
const onJourneyList = useMatch('/journey');
|
||||
const onAtlas = useMatch('/atlas');
|
||||
const onCollections = useMatch('/collections');
|
||||
const inCollection = useMatch('/collections/:id');
|
||||
const onCollections = useMatch('/places');
|
||||
const inCollection = useMatch('/places/:id');
|
||||
|
||||
if (inTrip) {
|
||||
const id = inTrip.params.id ?? '';
|
||||
@@ -52,10 +52,10 @@ export function useCreateAction(phone: boolean): CreateAction {
|
||||
return { label: t('atlas.searchCountry'), run: () => navigate('/atlas?search=1') };
|
||||
}
|
||||
if (phone && (onCollections || inCollection)) {
|
||||
// Picking a list moves the route to /collections/:id, so the exact match
|
||||
// Picking a list moves the route to /places/:id, so the exact match
|
||||
// alone dropped the "+" through to creating a trip (#1930). The handoff keeps
|
||||
// the id, otherwise adding would land on "All saved".
|
||||
const path = inCollection ? `/collections/${inCollection.params.id}` : '/collections';
|
||||
const path = inCollection ? `/places/${inCollection.params.id}` : '/places';
|
||||
return { label: t('collections.addPlace'), run: () => navigate(`${path}?create=place`) };
|
||||
}
|
||||
return { label: t('dashboard.newTrip'), run: () => navigate('/dashboard?create=1') };
|
||||
|
||||
@@ -3,17 +3,16 @@ import { afterEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { controlBoxes, layoutPlaceNames, tagPlaceName } from './placeNameLabels';
|
||||
|
||||
type Rect = { left: number; top: number; width: number; height: number };
|
||||
type Rect = { x: number; y: number; w: number; h: number };
|
||||
|
||||
/** jsdom lays nothing out, so every element answers the box it was given. */
|
||||
function place(el: Element, r: Rect): void {
|
||||
el.getBoundingClientRect = () =>
|
||||
({ ...r, right: r.left + r.width, bottom: r.top + r.height, x: r.left, y: r.top, toJSON: () => ({}) }) as DOMRect;
|
||||
el.getBoundingClientRect = () => ({ x: r.x, y: r.y, width: r.w, height: r.h, toJSON: () => ({}) }) as DOMRect;
|
||||
}
|
||||
|
||||
function mapWith(pins: { name: string; priority: 0 | 1 | 2; at: Rect; label: Rect }[]): HTMLElement {
|
||||
const container = document.createElement('div');
|
||||
place(container, { left: 0, top: 0, width: 800, height: 600 });
|
||||
place(container, { x: 0, y: 0, w: 800, h: 600 });
|
||||
document.body.appendChild(container);
|
||||
for (const pin of pins) {
|
||||
const el = document.createElement('div');
|
||||
@@ -42,8 +41,8 @@ describe('place names on the map', () => {
|
||||
{
|
||||
name: '<b>Senso-ji</b>',
|
||||
priority: 0,
|
||||
at: { left: 10, top: 10, width: 20, height: 20 },
|
||||
label: { left: 36, top: 12, width: 80, height: 16 },
|
||||
at: { x: 10, y: 10, w: 20, h: 20 },
|
||||
label: { x: 36, y: 12, w: 80, h: 16 },
|
||||
},
|
||||
]);
|
||||
layoutPlaceNames(c, true);
|
||||
@@ -57,14 +56,14 @@ describe('place names on the map', () => {
|
||||
{
|
||||
name: 'Plain',
|
||||
priority: 0,
|
||||
at: { left: 10, top: 10, width: 20, height: 20 },
|
||||
label: { left: 36, top: 12, width: 80, height: 16 },
|
||||
at: { x: 10, y: 10, w: 20, h: 20 },
|
||||
label: { x: 36, y: 12, w: 80, h: 16 },
|
||||
},
|
||||
{
|
||||
name: 'Picked',
|
||||
priority: 2,
|
||||
at: { left: 10, top: 60, width: 20, height: 20 },
|
||||
label: { left: 40, top: 14, width: 80, height: 16 },
|
||||
at: { x: 10, y: 60, w: 20, h: 20 },
|
||||
label: { x: 40, y: 14, w: 80, h: 16 },
|
||||
},
|
||||
]);
|
||||
layoutPlaceNames(c, true);
|
||||
@@ -78,29 +77,29 @@ describe('place names on the map', () => {
|
||||
{
|
||||
name: 'Covers a pin',
|
||||
priority: 0,
|
||||
at: { left: 10, top: 10, width: 20, height: 20 },
|
||||
label: { left: 36, top: 12, width: 80, height: 16 },
|
||||
at: { x: 10, y: 10, w: 20, h: 20 },
|
||||
label: { x: 36, y: 12, w: 80, h: 16 },
|
||||
},
|
||||
{
|
||||
name: 'Neighbour',
|
||||
priority: 0,
|
||||
at: { left: 60, top: 8, width: 20, height: 20 },
|
||||
label: { left: 300, top: 300, width: 40, height: 16 },
|
||||
at: { x: 60, y: 8, w: 20, h: 20 },
|
||||
label: { x: 300, y: 300, w: 40, h: 16 },
|
||||
},
|
||||
{
|
||||
name: 'Edge',
|
||||
priority: 0,
|
||||
at: { left: 760, top: 200, width: 20, height: 20 },
|
||||
label: { left: 786, top: 202, width: 80, height: 16 },
|
||||
at: { x: 760, y: 200, w: 20, h: 20 },
|
||||
label: { x: 786, y: 202, w: 80, h: 16 },
|
||||
},
|
||||
{
|
||||
name: 'Under control',
|
||||
priority: 0,
|
||||
at: { left: 400, top: 500, width: 20, height: 20 },
|
||||
label: { left: 426, top: 502, width: 80, height: 16 },
|
||||
at: { x: 400, y: 500, w: 20, h: 20 },
|
||||
label: { x: 426, y: 502, w: 80, h: 16 },
|
||||
},
|
||||
]);
|
||||
layoutPlaceNames(c, true, [{ left: 450, top: 490, right: 520, bottom: 530 }]);
|
||||
layoutPlaceNames(c, true, [{ x0: 450, y0: 490, x1: 520, y1: 530 }]);
|
||||
const hidden = labels(c).map((l) => l.hasAttribute('data-hidden'));
|
||||
expect(hidden).toEqual([true, false, true, true]);
|
||||
});
|
||||
@@ -110,8 +109,8 @@ describe('place names on the map', () => {
|
||||
{
|
||||
name: 'Senso-ji',
|
||||
priority: 0,
|
||||
at: { left: 10, top: 10, width: 20, height: 20 },
|
||||
label: { left: 36, top: 12, width: 80, height: 16 },
|
||||
at: { x: 10, y: 10, w: 20, h: 20 },
|
||||
label: { x: 36, y: 12, w: 80, h: 16 },
|
||||
},
|
||||
]);
|
||||
layoutPlaceNames(c, true);
|
||||
@@ -123,9 +122,9 @@ describe('place names on the map', () => {
|
||||
it('FE-MAP-PLACENAMES-005: control boxes are read off the elements the selector finds', () => {
|
||||
const c = document.createElement('div');
|
||||
const btn = document.createElement('button');
|
||||
place(btn, { left: 5, top: 6, width: 30, height: 30 });
|
||||
place(btn, { x: 5, y: 6, w: 30, h: 30 });
|
||||
c.appendChild(btn);
|
||||
expect(controlBoxes(c, 'button')).toEqual([{ left: 5, top: 6, right: 35, bottom: 36 }]);
|
||||
expect(controlBoxes(c, 'button')).toEqual([{ x0: 5, y0: 6, x1: 35, y1: 36 }]);
|
||||
expect(controlBoxes(null, 'button')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -25,18 +25,24 @@ export function tagPlaceName(el: HTMLElement | null | undefined, name: string, p
|
||||
el.setAttribute(PRIORITY_ATTR, String(priority));
|
||||
}
|
||||
|
||||
/** A screen box: x0/y0 the top corner the reading starts at on screen, x1/y1 the opposite one. Plain geometry. */
|
||||
interface Box {
|
||||
left: number;
|
||||
top: number;
|
||||
right: number;
|
||||
bottom: number;
|
||||
x0: number;
|
||||
y0: number;
|
||||
x1: number;
|
||||
y1: number;
|
||||
}
|
||||
|
||||
const boxOf = (el: Element): Box => {
|
||||
const r = el.getBoundingClientRect();
|
||||
return { x0: r.x, y0: r.y, x1: r.x + r.width, y1: r.y + r.height };
|
||||
};
|
||||
|
||||
// Overlaps nothing: a marker that was not measured cannot push a label away.
|
||||
const NO_BOX: Box = { left: Infinity, top: Infinity, right: -Infinity, bottom: -Infinity };
|
||||
const NO_BOX: Box = { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity };
|
||||
|
||||
const overlaps = (a: Box, b: Box, gap = 2): boolean =>
|
||||
a.left < b.right + gap && b.left < a.right + gap && a.top < b.bottom + gap && b.top < a.bottom + gap;
|
||||
a.x0 < b.x1 + gap && b.x0 < a.x1 + gap && a.y0 < b.y1 + gap && b.y0 < a.y1 + gap;
|
||||
|
||||
function ensureLabel(marker: HTMLElement): HTMLElement {
|
||||
const name = marker.getAttribute(PLACE_NAME_ATTR) ?? '';
|
||||
@@ -64,12 +70,9 @@ export function layoutPlaceNames(container: HTMLElement | null, enabled: boolean
|
||||
container.querySelectorAll(`.${LABEL_CLASS}`).forEach((label) => label.remove());
|
||||
return;
|
||||
}
|
||||
const frame = container.getBoundingClientRect();
|
||||
const frame = boxOf(container);
|
||||
const markerBoxes = new Map<HTMLElement, Box>();
|
||||
for (const marker of markers) {
|
||||
const r = marker.getBoundingClientRect();
|
||||
markerBoxes.set(marker, { left: r.left, top: r.top, right: r.right, bottom: r.bottom });
|
||||
}
|
||||
for (const marker of markers) markerBoxes.set(marker, boxOf(marker));
|
||||
const ordered = markers
|
||||
.map((marker, index) => ({ marker, index, priority: Number(marker.getAttribute(PRIORITY_ATTR) ?? 0) }))
|
||||
.sort((a, b) => b.priority - a.priority || a.index - b.index);
|
||||
@@ -78,10 +81,8 @@ export function layoutPlaceNames(container: HTMLElement | null, enabled: boolean
|
||||
for (const { marker } of ordered) {
|
||||
const label = ensureLabel(marker);
|
||||
label.removeAttribute(HIDDEN_ATTR);
|
||||
const r = label.getBoundingClientRect();
|
||||
const box: Box = { left: r.left, top: r.top, right: r.right, bottom: r.bottom };
|
||||
const offFrame =
|
||||
box.left < frame.left || box.right > frame.right || box.top < frame.top || box.bottom > frame.bottom;
|
||||
const box = boxOf(label);
|
||||
const offFrame = box.x0 < frame.x0 || box.x1 > frame.x1 || box.y0 < frame.y0 || box.y1 > frame.y1;
|
||||
const coversMarker = markers.some(
|
||||
(other) => other !== marker && overlaps(box, markerBoxes.get(other) ?? NO_BOX, 0)
|
||||
);
|
||||
@@ -95,10 +96,7 @@ export function layoutPlaceNames(container: HTMLElement | null, enabled: boolean
|
||||
/** The boxes of the map controls inside `container` that a label must leave free. */
|
||||
export function controlBoxes(container: HTMLElement | null, selector: string): Box[] {
|
||||
if (!container) return [];
|
||||
return Array.from(container.querySelectorAll<HTMLElement>(selector)).map((el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
return { left: r.left, top: r.top, right: r.right, bottom: r.bottom };
|
||||
});
|
||||
return Array.from(container.querySelectorAll<HTMLElement>(selector)).map(boxOf);
|
||||
}
|
||||
|
||||
/** What no label may cover: the controls drawn over the map beside it. */
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
element, so it pans with it; placeNameLabels.ts decides which ones stay visible. */
|
||||
.trek-place-name {
|
||||
position: absolute;
|
||||
left: calc(100% + 6px); /* rtl-lint-disable: map geometry, the label sits beside the pin on screen */
|
||||
/* After the pin in the reading direction, so an Arabic map reads the name from the pin outward. */
|
||||
inset-inline-start: calc(100% + 6px);
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
max-width: 13em;
|
||||
|
||||
@@ -26,12 +26,12 @@ describe('cornerBadgeHtml', () => {
|
||||
it('FE-MAP-RATINGBADGE-101: day numbers win the corner over the rating', () => {
|
||||
const html = cornerBadgeHtml([2, 5], 4.5, true, -4);
|
||||
expect(html).toContain('2 · 5');
|
||||
expect(html).toContain('bottom:-4px;right:-4px');
|
||||
expect(html).not.toContain('#f59e0b');
|
||||
expect(html).toContain('bottom:-4px;inset-inline-end:-4px');
|
||||
expect(html).not.toContain('#fbbf24');
|
||||
});
|
||||
|
||||
it('FE-MAP-RATINGBADGE-102: without numbers the rating shows when asked for, else nothing', () => {
|
||||
expect(cornerBadgeHtml(null, 4, true, -2)).toContain('#f59e0b');
|
||||
expect(cornerBadgeHtml(null, 4, true, -2)).toContain('#fbbf24');
|
||||
expect(cornerBadgeHtml([], 4, false, -2)).toBe('');
|
||||
expect(cornerBadgeHtml([3], null, true, -2)).toContain('height:18px');
|
||||
});
|
||||
|
||||
@@ -1,29 +1,32 @@
|
||||
/** Lucide's star, the one the lists wear. */
|
||||
const STAR_PATH =
|
||||
'M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z';
|
||||
|
||||
/**
|
||||
* The rating a place carries, as a disc on the corner of its marker.
|
||||
* The rating a place carries, as a star on the corner of its marker.
|
||||
*
|
||||
* Bottom right, where a trip's day numbers sit — the two never appear together, since
|
||||
* a numbered stop is one you have already planned and this answers the question you
|
||||
* ask before that: of all these photos, which did I like. Amber rather than the number
|
||||
* badge's white, so a glance tells them apart without reading either.
|
||||
*
|
||||
* A rounded value and no star: at eighteen pixels a star is a smudge, and "4.5" is
|
||||
* already the whole sentence.
|
||||
* A star like the one the lists put on a place's picture, so the vote reads the same on
|
||||
* the map and beside it; the figure inside is rounded to one decimal.
|
||||
*/
|
||||
export function ratingBadgeHtml(rating: number | null | undefined): string {
|
||||
if (typeof rating !== 'number' || !(rating > 0)) return '';
|
||||
const label = Number.isInteger(rating) ? String(rating) : rating.toFixed(1);
|
||||
// A star rather than a disc, as in the lists; its box a little over the old disc,
|
||||
// since a star fills less of it. Leaflet lifts every svg in a marker to z-index 200,
|
||||
// so both layers name theirs, or the star covers its own figure.
|
||||
return `<span style="
|
||||
position:absolute;bottom:-4px;right:-4px;
|
||||
min-width:18px;height:18px;border-radius:9px;
|
||||
padding:0 4px;
|
||||
background:#f59e0b;
|
||||
border:1.5px solid rgba(255,255,255,0.92);
|
||||
box-shadow:0 1px 4px rgba(0,0,0,0.25);
|
||||
position:absolute;bottom:-6px;right:-6px;
|
||||
width:22px;height:22px;
|
||||
display:flex;align-items:center;justify-content:center;
|
||||
font-size:9px;font-weight:800;color:#fff;
|
||||
font-family:var(--font-system);line-height:1;
|
||||
box-sizing:border-box;white-space:nowrap;
|
||||
">${label}</span>`;
|
||||
"><svg viewBox="0 0 24 24" width="22" height="22" style="position:absolute;inset:0;z-index:0;overflow:visible"
|
||||
fill="#fbbf24" stroke="rgba(255,255,255,0.92)" stroke-width="1.3" stroke-linejoin="round"><path d="${STAR_PATH}"/></svg>
|
||||
<span style="position:relative;z-index:1;margin-top:2px;font-size:${label.length > 1 ? 6.5 : 8.5}px;font-weight:800;line-height:1;
|
||||
color:#111;font-family:var(--font-system);white-space:nowrap;">${label}</span></span>`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -40,7 +43,7 @@ export function cornerBadgeHtml(
|
||||
if (!orderNumbers || orderNumbers.length === 0) return showRating ? ratingBadgeHtml(rating) : '';
|
||||
const many = orderNumbers.length > 1;
|
||||
return `<span style="
|
||||
position:absolute;bottom:${inset}px;right:${inset}px;
|
||||
position:absolute;bottom:${inset}px;inset-inline-end:${inset}px;
|
||||
min-width:18px;height:${many ? 16 : 18}px;border-radius:${many ? 8 : 9}px;
|
||||
padding:0 ${many ? 4 : 3}px;
|
||||
background:rgba(255,255,255,0.94);
|
||||
|
||||
@@ -28,7 +28,7 @@ export function usePlaceNameLayout(
|
||||
cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(() => {
|
||||
const scope = container.parentElement ?? container;
|
||||
const controls = enabled ? controlBoxes(scope, PLACE_NAMES_CONTROLS).filter((b) => b.right > b.left) : [];
|
||||
const controls = enabled ? controlBoxes(scope, PLACE_NAMES_CONTROLS).filter((b) => b.x1 > b.x0) : [];
|
||||
layoutPlaceNames(container, enabled, controls);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { MapPinOff } from 'lucide-react';
|
||||
import type React from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { EditorField, GRID_2, INPUT, PANEL } from '../shared/dialogParts';
|
||||
@@ -24,6 +25,15 @@ interface PlaceFormLocationProps {
|
||||
*/
|
||||
export function PlaceFormLocation({ fieldId, form, onChange, warnWithoutCoordinates }: PlaceFormLocationProps) {
|
||||
const { t } = useTranslation();
|
||||
// "48.85, 2.35" pasted into either coordinate fills both halves.
|
||||
const pastePair = (e: React.ClipboardEvent<HTMLInputElement>) => {
|
||||
const pair = parseCoordinatePair(e.clipboardData.getData('text'));
|
||||
if (pair) {
|
||||
e.preventDefault();
|
||||
onChange('lat', pair[0]);
|
||||
onChange('lng', pair[1]);
|
||||
}
|
||||
};
|
||||
const hint = warnWithoutCoordinates && addressWithoutCoordinates(form) && (
|
||||
<span className="flex items-start gap-1 text-content-muted">
|
||||
<MapPinOff size={12} strokeWidth={2} aria-hidden="true" className="mt-px flex-none text-warning" />
|
||||
@@ -49,15 +59,7 @@ export function PlaceFormLocation({ fieldId, form, onChange, warnWithoutCoordina
|
||||
mode="signed"
|
||||
value={form.lat}
|
||||
onValueChange={(v) => onChange('lat', v)}
|
||||
onPaste={(e) => {
|
||||
// "48.85, 2.35" pasted into the latitude fills both halves.
|
||||
const pair = parseCoordinatePair(e.clipboardData.getData('text'));
|
||||
if (pair) {
|
||||
e.preventDefault();
|
||||
onChange('lat', pair[0]);
|
||||
onChange('lng', pair[1]);
|
||||
}
|
||||
}}
|
||||
onPaste={pastePair}
|
||||
placeholder={t('places.formLat')}
|
||||
className={INPUT}
|
||||
/>
|
||||
@@ -68,6 +70,7 @@ export function PlaceFormLocation({ fieldId, form, onChange, warnWithoutCoordina
|
||||
mode="signed"
|
||||
value={form.lng}
|
||||
onValueChange={(v) => onChange('lng', v)}
|
||||
onPaste={pastePair}
|
||||
placeholder={t('places.formLng')}
|
||||
className={INPUT}
|
||||
/>
|
||||
|
||||
@@ -6,6 +6,7 @@ import { collectionToursRepo } from '../../../repo/collectionToursRepo';
|
||||
import { OnlineOnlyError } from '../../../repo/onlineOnly';
|
||||
import { useAuthStore } from '../../../store/authStore';
|
||||
import { canAddToCollection } from '../../../utils/collectionAccess';
|
||||
import { PLACES_SAVED } from '../../../utils/placesRoutes';
|
||||
import { useToast } from '../../shared/Toast';
|
||||
|
||||
/** The saved tour of a trip that is to be kept. */
|
||||
@@ -127,7 +128,7 @@ export function useSaveTourToCollection(target: TourSaveTarget, { startOpen = fa
|
||||
retry: () => setOpening((value) => value + 1),
|
||||
openCollections: () => {
|
||||
setOpen(false);
|
||||
void navigate('/collections');
|
||||
void navigate(PLACES_SAVED);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ const TOURS = { slug: COLLECTIONS, anchor: 'whole-tours' }
|
||||
|
||||
export const { context: collectionsContext, guides: collectionsGuides } = defineScreen({
|
||||
id: 'collections',
|
||||
route: '/collections',
|
||||
route: '/places',
|
||||
icon: 'bookmark',
|
||||
bullets: 7,
|
||||
docs: [{ slug: COLLECTIONS }, { slug: 'Admin-Categories' }, { slug: 'Admin-Addons' }],
|
||||
|
||||
@@ -1171,6 +1171,9 @@ body {
|
||||
/* ── Leaflet z-index ───────────────────────────── */
|
||||
.leaflet-container {
|
||||
z-index: 0;
|
||||
/* Leaflet's own grey showed as a bright band past the edge of the world when a map
|
||||
framed places on several continents, and while tiles were still loading. */
|
||||
background: var(--bg-secondary);
|
||||
}
|
||||
.leaflet-pane {
|
||||
z-index: 0 !important;
|
||||
|
||||
@@ -63,9 +63,9 @@ describe('MBottomNav', () => {
|
||||
it('FE-COMP-MBOTTOMNAV-002: on the collections overview the "+" adds a place', async () => {
|
||||
const user = userEvent.setup();
|
||||
withCollections();
|
||||
render(<MBottomNav />, { initialEntries: ['/collections'] });
|
||||
render(<MBottomNav />, { initialEntries: ['/places'] });
|
||||
await user.click(screen.getByRole('button', { name: 'Add a place' }));
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/collections?create=place');
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/places?create=place');
|
||||
});
|
||||
|
||||
// #1930: picking a list moves the route to /collections/:id, which the exact
|
||||
@@ -73,18 +73,18 @@ describe('MBottomNav', () => {
|
||||
it('FE-COMP-MBOTTOMNAV-003: inside a collection the "+" adds a place, not a trip', async () => {
|
||||
const user = userEvent.setup();
|
||||
withCollections();
|
||||
render(<MBottomNav />, { initialEntries: ['/collections/7'] });
|
||||
render(<MBottomNav />, { initialEntries: ['/places/7'] });
|
||||
await user.click(screen.getByRole('button', { name: 'Add a place' }));
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/collections/7?create=place');
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/places/7?create=place');
|
||||
expect(mockNavigate).not.toHaveBeenCalledWith('/dashboard?create=1');
|
||||
});
|
||||
|
||||
it('FE-COMP-MBOTTOMNAV-004: the handoff keeps the list the user is looking at', async () => {
|
||||
const user = userEvent.setup();
|
||||
withCollections();
|
||||
render(<MBottomNav />, { initialEntries: ['/collections/123'] });
|
||||
render(<MBottomNav />, { initialEntries: ['/places/123'] });
|
||||
await user.click(screen.getByRole('button', { name: 'Add a place' }));
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/collections/123?create=place');
|
||||
expect(mockNavigate).toHaveBeenCalledWith('/places/123?create=place');
|
||||
});
|
||||
|
||||
it('FE-COMP-MBOTTOMNAV-005: on the journey list the "+" starts a journey', async () => {
|
||||
|
||||
@@ -108,7 +108,10 @@ export default function MCollAddSheet({ open, collectionId, collectionName, list
|
||||
)}
|
||||
|
||||
<Eyebrow className="mb-[6px] mt-4">{t('common.name').toUpperCase()}</Eyebrow>
|
||||
<input value={name} onChange={e => setName(e.target.value)} placeholder={t('common.name')} className={INPUT_CLS} />
|
||||
{/* The category rides in front of the name: one row instead of two. */}
|
||||
<MCollCategoryPicker variant="tile" categories={categories} value={categoryId} onChange={setCategoryId} t={t}>
|
||||
<input value={name} onChange={e => setName(e.target.value)} placeholder={t('common.name')} className={INPUT_CLS} />
|
||||
</MCollCategoryPicker>
|
||||
|
||||
{/* Address (#1870): a picked hit fills it, but it stays editable so a
|
||||
hand-typed place can carry one too (the desktop dialog always could). */}
|
||||
@@ -121,8 +124,6 @@ export default function MCollAddSheet({ open, collectionId, collectionName, list
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Eyebrow className="mb-[6px] mt-[14px]">{t('collections.category').toUpperCase()}</Eyebrow>
|
||||
<MCollCategoryPicker categories={categories} value={categoryId} onChange={setCategoryId} t={t} />
|
||||
|
||||
<Eyebrow className="mb-[6px] mt-[14px]">{t('mobileCollections.status').toUpperCase()}</Eyebrow>
|
||||
{/* Two by two on a phone, so every status label keeps its room */}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react'
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import { Check, ChevronDown, ChevronUp } from 'lucide-react'
|
||||
import type { Category, TranslationFn } from '../../../types'
|
||||
import { categoryMeta, NO_CATEGORY_META, tint } from './collectionsMobileModel'
|
||||
@@ -7,6 +7,13 @@ interface MCollCategoryPickerProps {
|
||||
categories: Category[]
|
||||
value: number | null
|
||||
onChange: (id: number | null) => void
|
||||
/**
|
||||
* `tile` puts the category in front of the place's name as a tinted tile, with the
|
||||
* name field (the children) beside it: the category belongs to the place, and the
|
||||
* form loses a whole row. `row` is the full-width trigger.
|
||||
*/
|
||||
variant?: 'row' | 'tile'
|
||||
children?: ReactNode
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
@@ -14,7 +21,7 @@ interface MCollCategoryPickerProps {
|
||||
* Category dropdown of the add/edit-place sheets: a trigger row with the tinted
|
||||
* 26px icon chip and an overlay list of "No category" + the admin categories.
|
||||
*/
|
||||
export default function MCollCategoryPicker({ categories, value, onChange, t }: MCollCategoryPickerProps) {
|
||||
export default function MCollCategoryPicker({ categories, value, onChange, variant = 'row', children, t }: MCollCategoryPickerProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const selected = value != null ? categories.find(c => c.id === value) ?? null : null
|
||||
@@ -27,8 +34,18 @@ export default function MCollCategoryPicker({ categories, value, onChange, t }:
|
||||
...categories.map(c => ({ id: c.id, name: c.name })),
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
const trigger = variant === 'tile' ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(v => !v)}
|
||||
aria-expanded={open}
|
||||
aria-label={`${t('collections.category')}: ${selected?.name ?? t('collections.noCategory')}`}
|
||||
className="flex h-[42px] w-[42px] flex-none items-center justify-center rounded-full border border-m-rowbr"
|
||||
style={{ background: tint(selectedMeta.color, '1f'), color: selectedMeta.color }}
|
||||
>
|
||||
<SelectedIcon size={17} strokeWidth={2.2} />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(v => !v)}
|
||||
@@ -45,6 +62,11 @@ export default function MCollCategoryPicker({ categories, value, onChange, t }:
|
||||
</span>
|
||||
<Chevron size={15} strokeWidth={2.2} className="flex-none text-m-faint" />
|
||||
</button>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
{variant === 'tile' ? <div className="flex items-center gap-2">{trigger}<div className="min-w-0 flex-1">{children}</div></div> : trigger}
|
||||
{open && (
|
||||
<div className="absolute inset-x-0 top-[calc(100%+6px)] z-[5] max-h-[210px] overflow-y-auto rounded-[14px] border border-[color:var(--m-rowbr)] bg-m-sheetop shadow-[0_20px_44px_-18px_rgba(0,0,0,.45)]">
|
||||
{options.map((opt, i) => {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { normalizeLinkUrl } from '../../../pages/collections/collectionsModel'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import MCollLinksEditor from './MCollLinksEditor'
|
||||
import { listCoverGradient, SWATCH_COLORS } from './collectionsMobileModel'
|
||||
import { LIST_ICONS, LIST_ICON_NAMES } from '../../../components/Collections/listIcons'
|
||||
import { CancelPill, INPUT_CLS, PrimaryPill, SheetFooter, SheetHeader, TEXTAREA_CLS } from './MCollSheetKit'
|
||||
|
||||
// Scrims over the cover photo / Unsplash thumbs — fixed dark overlays in both themes.
|
||||
@@ -30,7 +31,7 @@ interface MCollEditSheetProps {
|
||||
*/
|
||||
export default function MCollEditSheet({ target, onClose, onCreated, onRequestDelete, t }: MCollEditSheetProps) {
|
||||
const {
|
||||
editing, fileRef, name, setName, color, setColor, description, setDescription, links, setLinks,
|
||||
editing, fileRef, name, setName, color, setColor, icon, setIcon, description, setDescription, links, setLinks,
|
||||
coverPreview, coverQuery, setCoverQuery, coverResults, searchingCover, saving, close, pickCover, searchCover, pickUnsplash, save,
|
||||
} = useListEditor({ target, onClose, onCreated, t, defaultColor: SWATCH_COLORS[0], holdLastTarget: true, normalizeLinkUrl })
|
||||
|
||||
@@ -133,6 +134,27 @@ export default function MCollEditSheet({ target, onClose, onCreated, onRequestDe
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className={`${label} mt-[14px] mb-[6px]`}>{t('collections.listIcon')}</div>
|
||||
<div role="group" aria-label={t('collections.listIcon')} className="flex flex-wrap gap-[6px]">
|
||||
{LIST_ICON_NAMES.map(name => {
|
||||
const Icon = LIST_ICONS[name]
|
||||
const on = icon === name
|
||||
return (
|
||||
<button
|
||||
key={name}
|
||||
type="button"
|
||||
onClick={() => setIcon(name)}
|
||||
aria-label={name}
|
||||
aria-pressed={on}
|
||||
className={`grid h-9 w-9 place-items-center rounded-[10px] ${on ? '' : 'text-m-muted'}`}
|
||||
style={on ? { color, background: `${color}26` } : undefined}
|
||||
>
|
||||
<Icon size={17} strokeWidth={2} />
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className={`${label} mt-[14px]`}>{t('collections.description')}</div>
|
||||
<textarea rows={2} value={description} onChange={e => setDescription(e.target.value)} placeholder={t('collections.descriptionPlaceholder')} className={TEXTAREA_CLS} />
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import MDancingTrek, { type TrekScene } from '../../components/MDancingTrek';
|
||||
|
||||
/*
|
||||
* The filter chips, their dropdown panel and the empty note of the phone's places
|
||||
* screens: the lists and "All places" (PLC-07) wear the same ones.
|
||||
*/
|
||||
|
||||
export const FILTER_CHIP =
|
||||
'flex min-w-0 flex-1 items-center justify-center gap-[5px] rounded-full py-2 text-[0.75rem] font-semibold';
|
||||
|
||||
export const CHIP_IDLE = 'border border-m-rowbr bg-m-sheetop text-m-ink';
|
||||
export const CHIP_ON = 'border border-transparent bg-m-act text-m-actfg';
|
||||
|
||||
export const DROP_PANEL = 'rounded-[14px] border border-m-rowbr bg-m-sheetop shadow-xl';
|
||||
|
||||
/** One row of the status or category dropdown: icon, name, count. */
|
||||
export function DropRow({
|
||||
icon,
|
||||
label,
|
||||
count,
|
||||
on,
|
||||
onPick,
|
||||
}: {
|
||||
icon: ReactNode;
|
||||
label: string;
|
||||
count?: number;
|
||||
on: boolean;
|
||||
onPick: () => void;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onPick}
|
||||
className={`flex w-full items-center gap-[9px] rounded-[11px] p-[10px] text-[0.8125rem] font-semibold text-m-ink ${on ? 'bg-m-ic' : ''}`}
|
||||
>
|
||||
{icon}
|
||||
<span dir="auto" className="min-w-0 flex-1 truncate text-start">
|
||||
{label}
|
||||
</span>
|
||||
{count != null && <span className="font-geist text-[0.6875rem] font-bold text-m-faint">{count}</span>}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function EmptyNote({ icon, scene, title }: { icon?: ReactNode; scene?: TrekScene; title: string }) {
|
||||
return (
|
||||
<div className="flex min-h-[60vh] flex-col items-center justify-center gap-[6px] px-6 text-center">
|
||||
{scene ? (
|
||||
<MDancingTrek scene={scene} className="mb-2" />
|
||||
) : (
|
||||
<span className="flex h-10 w-10 items-center justify-center rounded-xl bg-m-ic text-m-faint">{icon}</span>
|
||||
)}
|
||||
<p className="font-geist text-[0.8125rem] font-medium text-m-muted">{title}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,17 +1,29 @@
|
||||
import { Layers, Plus } from 'lucide-react';
|
||||
import { Globe2, Layers, Plus } from 'lucide-react';
|
||||
|
||||
import { listIcon } from '../../../components/Collections/listIcons';
|
||||
import { ALL_SAVED } from '../../../store/collectionStore';
|
||||
|
||||
/** A list's symbol in its colour, in the slot the dot used to take. */
|
||||
function ListIcon({ name, color }: { name?: string | null; color: string }) {
|
||||
const Icon = listIcon(name);
|
||||
return <Icon size={15} strokeWidth={2.2} className="flex-none" style={{ color }} />;
|
||||
}
|
||||
|
||||
interface ListEntry {
|
||||
id: number;
|
||||
name: string;
|
||||
/** The list's own colour, already resolved to the default for a list without one. */
|
||||
color: string;
|
||||
place_count?: number | null;
|
||||
/** The list's symbol (Bookmark when it never got one). */
|
||||
icon?: string | null;
|
||||
}
|
||||
|
||||
interface MCollListNavProps {
|
||||
lists: ListEntry[];
|
||||
/** "All places" (PLC-07) is open; it sits above the saved places. */
|
||||
library?: boolean;
|
||||
onSelectLibrary?: () => void;
|
||||
allSaved: boolean;
|
||||
activeId: number | typeof ALL_SAVED | null;
|
||||
onSelect: (id: number | typeof ALL_SAVED) => void;
|
||||
@@ -25,11 +37,31 @@ interface MCollListNavProps {
|
||||
* room for two panes they stand in a column of their own beside the places,
|
||||
* the way Notes on an iPad keeps its folders in view.
|
||||
*/
|
||||
export default function MCollListNav({ lists, allSaved, activeId, onSelect, onNewList, t }: MCollListNavProps) {
|
||||
export default function MCollListNav({
|
||||
lists,
|
||||
library = false,
|
||||
onSelectLibrary,
|
||||
allSaved,
|
||||
activeId,
|
||||
onSelect,
|
||||
onNewList,
|
||||
t,
|
||||
}: MCollListNavProps) {
|
||||
const row =
|
||||
'flex w-full items-center gap-[10px] rounded-[11px] p-[10px] text-start outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--m-act)]';
|
||||
return (
|
||||
<>
|
||||
{onSelectLibrary && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onSelectLibrary}
|
||||
aria-current={library ? 'page' : undefined}
|
||||
className={`${row} text-[length:calc(13px*var(--fs-scale-body,1))] font-semibold text-m-ink ${library ? 'bg-m-ic' : 'hover:bg-m-ic'}`}
|
||||
>
|
||||
<Globe2 size={15} strokeWidth={2} className="flex-none" />
|
||||
<span className="min-w-0 flex-1 truncate">{t('collections.library.title')}</span>
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSelect(ALL_SAVED)}
|
||||
@@ -51,7 +83,7 @@ export default function MCollListNav({ lists, allSaved, activeId, onSelect, onNe
|
||||
className={`${row} ${active ? 'bg-[color:var(--m-ic)]' : 'hover:bg-[color:var(--m-ic)]'}`}
|
||||
style={active ? { boxShadow: `inset 0 0 0 1.5px ${l.color}` } : undefined}
|
||||
>
|
||||
<span className="h-[9px] w-[9px] flex-none rounded-full" style={{ background: l.color }} />
|
||||
<ListIcon name={l.icon} color={l.color} />
|
||||
<span className="min-w-0 flex-1 truncate text-[length:calc(13px*var(--fs-scale-body,1))] font-semibold text-m-ink">
|
||||
{l.name}
|
||||
</span>
|
||||
|
||||
@@ -162,13 +162,13 @@ export default function MCollPlaceSheet({
|
||||
{editing ? (
|
||||
<>
|
||||
<Eyebrow className="mb-[6px] mt-4">{t('common.name').toUpperCase()}</Eyebrow>
|
||||
<input value={name} onChange={e => setName(e.target.value)} className={INPUT_CLS} />
|
||||
<MCollCategoryPicker variant="tile" categories={categories} value={categoryId} onChange={setCategoryId} t={t}>
|
||||
<input value={name} onChange={e => setName(e.target.value)} className={INPUT_CLS} />
|
||||
</MCollCategoryPicker>
|
||||
{/* Address (#1870): free text, same as the add sheet offers */}
|
||||
<Eyebrow className="mb-[6px] mt-[14px]">{t('places.formAddress').toUpperCase()}</Eyebrow>
|
||||
<input value={address} onChange={e => setAddress(e.target.value)} placeholder={t('places.formAddressPlaceholder')} className={INPUT_CLS} />
|
||||
{needsPosition && <MCollLocationSearch picked={positionPicked} onPick={pickPosition} t={t} />}
|
||||
<Eyebrow className="mb-[6px] mt-[14px]">{t('collections.category').toUpperCase()}</Eyebrow>
|
||||
<MCollCategoryPicker categories={categories} value={categoryId} onChange={setCategoryId} t={t} />
|
||||
{labels.length > 0 && (
|
||||
<>
|
||||
<Eyebrow className="mb-[6px] mt-[14px]">{t('collections.labels.title').toUpperCase()}</Eyebrow>
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
Tag, Tags, Trash2,
|
||||
} from 'lucide-react'
|
||||
import type { CollectionStatus } from '@trek/shared'
|
||||
import MDancingTrek, { type TrekScene } from '../../components/MDancingTrek'
|
||||
import { useCollections } from '../../../pages/collections/useCollections'
|
||||
import { STATUS_ORDER } from '../../../pages/collections/collectionsModel'
|
||||
import type { StatusFilter } from '../../../store/collectionStore'
|
||||
@@ -25,6 +24,8 @@ import MCollInvites from './MCollInvites'
|
||||
import { STATUS_SPEC, categoryMeta } from './collectionsMobileModel'
|
||||
import MConfirmSheet from '../settings/MConfirmSheet'
|
||||
import MCollListNav from './MCollListNav'
|
||||
import MPlacesLibrary from './MPlacesLibrary'
|
||||
import { CHIP_IDLE, CHIP_ON, DROP_PANEL, DropRow, EmptyNote, FILTER_CHIP } from './MCollFilterKit'
|
||||
import { usePlaceReorder } from '../../../components/Collections/usePlaceReorder'
|
||||
import { useIsSplit } from '../../../hooks/sizeClass'
|
||||
import { skipNextRouteTransition } from '../../routeTransition'
|
||||
@@ -38,52 +39,9 @@ const HEADER_CIRCLE =
|
||||
// its chips. The labels are short enough to fit in every locale now, but a long
|
||||
// label name in the filter chip, or a bumped-up text size, still has to ellipsise
|
||||
// inside the panel rather than spill out of it.
|
||||
const FILTER_CHIP =
|
||||
'flex min-w-0 flex-1 items-center justify-center gap-[5px] rounded-full py-2 text-[0.75rem] font-semibold'
|
||||
|
||||
const CHIP_IDLE = 'border border-[color:var(--m-rowbr)] bg-m-sheetop text-m-ink'
|
||||
const CHIP_ON = 'border border-transparent bg-m-act text-m-actfg'
|
||||
|
||||
const DROP_PANEL =
|
||||
'rounded-[14px] border border-[color:var(--m-rowbr)] bg-m-sheetop shadow-[0_20px_44px_-18px_rgba(0,0,0,.45)]'
|
||||
|
||||
/** The filter chips that open a dropdown; at most one is open at a time. */
|
||||
type FilterDrop = 'status' | 'category' | 'label'
|
||||
|
||||
/** One row of the status or category dropdown: icon, name, count. */
|
||||
function DropRow({ icon, label, count, on, onPick }: {
|
||||
icon: ReactNode
|
||||
label: string
|
||||
count: number
|
||||
on: boolean
|
||||
onPick: () => void
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onPick}
|
||||
className={`flex w-full items-center gap-[9px] rounded-[11px] p-[10px] text-[0.8125rem] font-semibold text-m-ink ${on ? 'bg-[color:var(--m-ic)]' : ''}`}
|
||||
>
|
||||
{icon}
|
||||
<span dir="auto" className="min-w-0 flex-1 truncate text-start">{label}</span>
|
||||
<span className="font-geist text-[0.6875rem] font-bold text-m-faint">{count}</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyNote({ icon, scene, title }: { icon?: ReactNode; scene?: TrekScene; title: string }) {
|
||||
return (
|
||||
<div className="flex min-h-[60vh] flex-col items-center justify-center gap-[6px] px-6 text-center">
|
||||
{scene ? (
|
||||
<MDancingTrek scene={scene} className="mb-2" />
|
||||
) : (
|
||||
<span className="flex h-10 w-10 items-center justify-center rounded-xl bg-[color:var(--m-ic)] text-m-faint">{icon}</span>
|
||||
)}
|
||||
<p className="font-geist text-[0.8125rem] font-medium text-m-muted">{title}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Mobile collections screen: list switcher (dropdown + left drawer), list/map
|
||||
* view toggle with clustering, real status/label filter chips, the select mode
|
||||
@@ -142,7 +100,7 @@ export default function MCollections() {
|
||||
if (ratingFilter !== 'all') setRatingFilter('all')
|
||||
}, [ratingFilter, setRatingFilter])
|
||||
|
||||
const title = c.isAllSaved ? t('collections.allSaved') : (c.activeCollection?.name ?? t('collections.title'))
|
||||
const title = c.isLibrary ? t('collections.library.title') : c.isAllSaved ? t('collections.allSaved') : (c.activeCollection?.name ?? t('collections.title'))
|
||||
const isRealList = !c.isAllSaved && typeof c.activeId === 'number'
|
||||
const canManageLabels = isRealList && c.canEdit
|
||||
const canEditList = isRealList && c.isOwner && c.activeCollection != null
|
||||
@@ -169,7 +127,7 @@ export default function MCollections() {
|
||||
? (c.labelOptions.find(l => l.id === c.labelFilter[0])?.name ?? '1')
|
||||
: String(c.labelFilter.length)
|
||||
|
||||
const selectList = (id: number | typeof ALL_SAVED) => {
|
||||
const selectList = (id: number | typeof ALL_SAVED | 'library') => {
|
||||
setDrop(false)
|
||||
// Another list is the same screen with other content, not a page opened
|
||||
// over it: the URL changes, but the page must not slide in.
|
||||
@@ -202,12 +160,14 @@ export default function MCollections() {
|
||||
}
|
||||
|
||||
const navLists = [...c.ownedLists, ...c.sharedLists].map(l => ({
|
||||
id: l.id, name: l.name, place_count: l.place_count, color: l.color || '#6366F1',
|
||||
id: l.id, name: l.name, place_count: l.place_count, color: l.color || '#6366F1', icon: l.icon,
|
||||
}))
|
||||
const listNav = (
|
||||
<MCollListNav
|
||||
lists={navLists}
|
||||
allSaved={c.isAllSaved}
|
||||
library={c.isLibrary}
|
||||
onSelectLibrary={() => selectList('library')}
|
||||
allSaved={!c.isLibrary && c.isAllSaved}
|
||||
activeId={c.activeId}
|
||||
onSelect={selectList}
|
||||
onNewList={openNewList}
|
||||
@@ -280,7 +240,12 @@ export default function MCollections() {
|
||||
|
||||
<MCollInvites invites={c.orderedInvites} onAccept={c.handleAcceptInvite} onDecline={c.handleDeclineInvite} t={t} />
|
||||
|
||||
{c.loading && c.collections.length === 0 ? (
|
||||
{c.isLibrary ? (
|
||||
// Every place of the trips and lists (PLC-07); it needs no list of one's own.
|
||||
<div className={`mt-3 ${c.view === 'map' ? 'flex min-h-0 flex-1 flex-col' : ''}`}>
|
||||
<MPlacesLibrary categories={c.categories} language={c.language} dark={c.dark} view={c.view} onView={c.setView} navigate={c.navigate} t={t} />
|
||||
</div>
|
||||
) : c.loading && c.collections.length === 0 ? (
|
||||
<MSkeleton variant="rows" count={5} className="pt-2" />
|
||||
) : noLists ? (
|
||||
<div className="mt-6">
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
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 { useRef, useState } from 'react';
|
||||
import { tripLine } from '../../../components/Collections/libraryDates';
|
||||
import { originName } from '../../../components/Collections/LibraryOrigins';
|
||||
import {
|
||||
getNavigationTargets,
|
||||
navigationTargetLabel,
|
||||
openNavigationTarget,
|
||||
} from '../../../components/Planner/placeNavigation';
|
||||
import { NavigationMenu } from '../../../components/shared/NavigationMenu';
|
||||
import type { TranslationFn } from '../../../types';
|
||||
import { entityGradient } from '../../../utils/gradients';
|
||||
import MSheet from '../../components/MSheet';
|
||||
import { categoryMeta, STATUS_SPEC, tint, UNCATEGORIZED_META } from './collectionsMobileModel';
|
||||
import { Eyebrow } from './MCollSheetKit';
|
||||
|
||||
type TripOrigin = Extract<PlacesLibraryOrigin, { kind: 'trip' }>;
|
||||
type ListOrigin = Extract<PlacesLibraryOrigin, { kind: 'list' }>;
|
||||
type TripDetail = Extract<PlacesLibraryDetail, { kind: 'trip' }>;
|
||||
type ListDetail = Extract<PlacesLibraryDetail, { kind: 'list' }>;
|
||||
|
||||
interface MLibraryPlaceSheetProps {
|
||||
open: boolean;
|
||||
data: PlacesLibraryDetailResponse | null;
|
||||
loading: boolean;
|
||||
cover: string | null;
|
||||
language: string;
|
||||
onClose: () => void;
|
||||
onOpenList: (collectionId: number, collectionPlaceId: number) => void;
|
||||
onOpenTrip: (tripId: number, placeId: number) => void;
|
||||
onSaveToList: (origin: TripOrigin, detail: TripDetail) => void;
|
||||
onCopyToTrip: (collectionPlaceId: number) => void;
|
||||
t: TranslationFn;
|
||||
}
|
||||
|
||||
const CARD = 'flex w-full flex-col gap-[9px] rounded-2xl border border-m-rowbr bg-m-sheet p-3 text-start';
|
||||
const ICO = 'flex h-[34px] w-[34px] flex-none items-center justify-center rounded-[10px] bg-m-ic text-m-muted';
|
||||
const CHIP =
|
||||
'inline-flex items-center gap-1 rounded-full border border-m-rowbr bg-m-ic px-[9px] py-[3px] text-caption font-semibold text-m-muted';
|
||||
const ACTION =
|
||||
'flex flex-1 items-center justify-center gap-[6px] rounded-[13px] border border-m-rowbr bg-m-sheet px-2 py-[11px] text-caption font-semibold text-m-ink';
|
||||
|
||||
function Notes({ text, t }: { text: string | null; t: TranslationFn }) {
|
||||
if (!text?.trim()) return null;
|
||||
return (
|
||||
<span className="block rounded-xl bg-m-ic px-3 py-2">
|
||||
<span className="flex items-center gap-1 text-caption font-semibold text-m-faint">
|
||||
<NotebookPen size={11} /> {t('collections.notes')}
|
||||
</span>
|
||||
<span dir="auto" className="mt-1 block whitespace-pre-wrap text-body text-m-ink">
|
||||
{text}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One place of "All places" on the phone (PLC-08): the sheet a list's place opens
|
||||
* in, with the cover, then every trip and list the place sits in and what each
|
||||
* keeps of it, and the things to do with it at the bottom.
|
||||
*/
|
||||
export default function MLibraryPlaceSheet({
|
||||
open,
|
||||
data,
|
||||
loading,
|
||||
cover,
|
||||
language,
|
||||
onClose,
|
||||
onOpenList,
|
||||
onOpenTrip,
|
||||
onSaveToList,
|
||||
onCopyToTrip,
|
||||
t,
|
||||
}: MLibraryPlaceSheetProps) {
|
||||
const [navOpen, setNavOpen] = useState(false);
|
||||
const navRef = useRef<HTMLButtonElement | null>(null);
|
||||
const entry = data?.entry ?? null;
|
||||
const meta = categoryMeta(entry?.category) ?? UNCATEGORIZED_META;
|
||||
const CatIcon = meta.icon;
|
||||
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());
|
||||
|
||||
return (
|
||||
<MSheet open={open} onClose={onClose} ariaLabel={entry?.name ?? t('collections.library.title')}>
|
||||
<div
|
||||
className="relative h-[150px] flex-none overflow-hidden"
|
||||
style={
|
||||
cover ? undefined : { backgroundImage: entityGradient(entry ? entry.name.length + entry.key.length : 0) }
|
||||
}
|
||||
>
|
||||
{cover && <img src={cover} alt="" className="absolute inset-0 h-full w-full object-cover" />}
|
||||
<div className="absolute inset-0 bg-gradient-to-b from-transparent to-black/60" />
|
||||
<div className="absolute inset-x-3 top-3 flex items-center gap-2">
|
||||
{entry?.category && (
|
||||
<span
|
||||
className="inline-flex min-w-0 items-center gap-1 rounded-full bg-m-sheetop px-[10px] py-[3px] text-caption font-bold"
|
||||
style={{ color: meta.color }}
|
||||
>
|
||||
<CatIcon size={12} className="flex-none" /> <span className="truncate">{entry.category.name}</span>
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label={t('common.close')}
|
||||
className="ms-auto flex h-8 w-8 items-center justify-center rounded-full bg-black/30 text-white"
|
||||
>
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
{entry && (
|
||||
<h2 dir="auto" className="absolute inset-x-4 bottom-3 m-0 truncate text-title font-extrabold text-white">
|
||||
{entry.name}
|
||||
</h2>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-4 pb-4 pt-3">
|
||||
{loading && !entry ? (
|
||||
<div className="flex justify-center py-10 text-m-faint">
|
||||
<Loader2 size={20} className="animate-spin" />
|
||||
</div>
|
||||
) : (
|
||||
entry && (
|
||||
<>
|
||||
{entry.address && (
|
||||
<p dir="auto" className="m-0 flex items-center gap-1 text-caption text-m-muted">
|
||||
<MapPin size={12} className="flex-none" /> {entry.address}
|
||||
</p>
|
||||
)}
|
||||
{(entry.lat == null || entry.lng == null) && (
|
||||
<p className="m-0 mt-1 flex items-center gap-1 text-caption text-m-muted">
|
||||
<MapPinOff size={12} className="flex-none text-warning" /> {t('places.noCoordinates')}
|
||||
</p>
|
||||
)}
|
||||
{description && (
|
||||
<p dir="auto" className="m-0 mt-3 whitespace-pre-wrap text-body text-m-ink">
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{trips.length > 0 && (
|
||||
<>
|
||||
<Eyebrow className="mb-[6px] mt-4">{t('collections.library.inTrips').toUpperCase()}</Eyebrow>
|
||||
<div className="flex flex-col gap-2">
|
||||
{trips.map(({ origin, detail }) => {
|
||||
const line = tripLine(origin, detail, language, t);
|
||||
return (
|
||||
<button
|
||||
key={origin.place_id}
|
||||
type="button"
|
||||
className={CARD}
|
||||
onClick={() => onOpenTrip(origin.trip_id, origin.place_id)}
|
||||
aria-label={`${t('collections.library.openTrip')}: ${originName(origin)}`}
|
||||
>
|
||||
<span className="flex items-center gap-[10px]">
|
||||
<span className={ICO}>
|
||||
<Luggage size={15} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span dir="auto" className="block truncate text-body font-bold text-m-ink">
|
||||
{originName(origin)}
|
||||
</span>
|
||||
{line && <span className="block truncate text-caption text-m-muted">{line}</span>}
|
||||
</span>
|
||||
{origin.read_only && <span className={CHIP}>{t('collections.library.readOnly')}</span>}
|
||||
<ChevronRight size={16} className="flex-none text-m-faint rtl:-scale-x-100" />
|
||||
</span>
|
||||
{(detail.has_accommodation || detail.has_reservation || detail.info.name !== entry.name) && (
|
||||
<span className="flex flex-wrap gap-[6px]">
|
||||
{detail.info.name !== entry.name && (
|
||||
<span className={CHIP}>
|
||||
{t('collections.library.calledHere', { name: detail.info.name })}
|
||||
</span>
|
||||
)}
|
||||
{detail.has_accommodation && (
|
||||
<span className={CHIP}>
|
||||
<Hotel size={11} /> {t('collections.library.stay')}
|
||||
</span>
|
||||
)}
|
||||
{detail.has_reservation && (
|
||||
<span className={CHIP}>
|
||||
<Ticket size={11} /> {t('collections.library.booking')}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<Notes text={detail.notes} t={t} />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{lists.length > 0 && (
|
||||
<>
|
||||
<Eyebrow className="mb-[6px] mt-4">{t('collections.library.inLists').toUpperCase()}</Eyebrow>
|
||||
<div className="flex flex-col gap-2">
|
||||
{lists.map(({ origin, detail }) => {
|
||||
const status = STATUS_SPEC[origin.status];
|
||||
const StatusIcon = status.icon;
|
||||
return (
|
||||
<button
|
||||
key={origin.collection_place_id}
|
||||
type="button"
|
||||
className={CARD}
|
||||
onClick={() => onOpenList(origin.collection_id, origin.collection_place_id)}
|
||||
aria-label={`${t('collections.library.openList')}: ${originName(origin)}`}
|
||||
>
|
||||
<span className="flex items-center gap-[10px]">
|
||||
<span className={ICO}>
|
||||
<Bookmark size={15} />
|
||||
</span>
|
||||
<span dir="auto" className="min-w-0 flex-1 truncate text-body font-bold text-m-ink">
|
||||
{originName(origin)}
|
||||
</span>
|
||||
<span
|
||||
className="inline-flex flex-none items-center gap-1 rounded-full px-[9px] py-[3px] text-caption font-bold"
|
||||
style={{ background: tint(status.color, '1f'), color: status.color }}
|
||||
>
|
||||
<StatusIcon size={11} /> {t(status.labelKey)}
|
||||
</span>
|
||||
<ChevronRight size={16} className="flex-none text-m-faint rtl:-scale-x-100" />
|
||||
</span>
|
||||
{(detail.labels.length > 0 ||
|
||||
detail.rating.average != null ||
|
||||
detail.info.name !== entry.name) && (
|
||||
<span className="flex flex-wrap gap-[6px]">
|
||||
{detail.info.name !== entry.name && (
|
||||
<span className={CHIP}>
|
||||
{t('collections.library.calledHere', { name: detail.info.name })}
|
||||
</span>
|
||||
)}
|
||||
{detail.labels.map((label) => (
|
||||
<span key={label.id} className={CHIP}>
|
||||
<span
|
||||
className="h-2 w-2 rounded-full"
|
||||
style={{ background: label.color || 'var(--m-act)' }}
|
||||
/>{' '}
|
||||
{label.name}
|
||||
</span>
|
||||
))}
|
||||
{detail.rating.average != null && (
|
||||
<span className={CHIP}>
|
||||
<Star size={11} />{' '}
|
||||
{t('collections.library.rating', {
|
||||
rating: detail.rating.average.toFixed(1),
|
||||
count: detail.rating.count,
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<Notes text={detail.notes} t={t} />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="mt-4 flex gap-2">
|
||||
{targets.length > 0 && (
|
||||
<>
|
||||
<button
|
||||
ref={navRef}
|
||||
type="button"
|
||||
className={ACTION}
|
||||
onClick={() => (targets.length === 1 ? openNavigationTarget(targets[0]) : setNavOpen((o) => !o))}
|
||||
>
|
||||
<Navigation size={14} />{' '}
|
||||
{targets.length === 1 ? navigationTargetLabel(targets[0], t) : t('inspector.navigation')}
|
||||
</button>
|
||||
{navOpen && (
|
||||
<NavigationMenu
|
||||
targets={targets}
|
||||
anchor={navRef.current}
|
||||
onClose={() => setNavOpen(false)}
|
||||
title={t('inspector.navigation')}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{trips[0] && (
|
||||
<button
|
||||
type="button"
|
||||
className={ACTION}
|
||||
onClick={() => onSaveToList(trips[0].origin, trips[0].detail)}
|
||||
>
|
||||
<BookmarkPlus size={14} /> {t('inspector.saveToCollection')}
|
||||
</button>
|
||||
)}
|
||||
{lists[0] && (
|
||||
<button
|
||||
type="button"
|
||||
className={ACTION}
|
||||
onClick={() => onCopyToTrip(lists[0].origin.collection_place_id)}
|
||||
>
|
||||
<Copy size={14} /> {t('collections.copyToTrip')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</MSheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
import type { CollectionPlace, CollectionStatus, PlacesLibraryEntry, PlacesLibrarySort } from '@trek/shared';
|
||||
import {
|
||||
ArrowDownUp,
|
||||
Bookmark,
|
||||
ChevronDown,
|
||||
Globe2,
|
||||
Layers,
|
||||
List,
|
||||
Loader2,
|
||||
Luggage,
|
||||
Map as MapIcon,
|
||||
MapPin,
|
||||
Search,
|
||||
Shapes,
|
||||
} from 'lucide-react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import CollectionMap from '../../../components/Collections/CollectionMap';
|
||||
import { originName } from '../../../components/Collections/LibraryOrigins';
|
||||
import { usePlacesLibrary, type LibraryKindFilter } from '../../../components/Collections/usePlacesLibrary';
|
||||
import { STATUS_ORDER } from '../../../pages/collections/collectionsModel';
|
||||
import { useCollectionStore } from '../../../store/collectionStore';
|
||||
import { useSaveToCollectionStore } from '../../../store/saveToCollectionStore';
|
||||
import type { Category, TranslationFn } from '../../../types';
|
||||
import { placesPath } from '../../../utils/placesRoutes';
|
||||
import { categoryMeta, STATUS_SPEC, tint, UNCATEGORIZED_META } from './collectionsMobileModel';
|
||||
import { CHIP_IDLE, CHIP_ON, DROP_PANEL, DropRow, EmptyNote, FILTER_CHIP } from './MCollFilterKit';
|
||||
import MCollTripPickerSheet from './MCollTripPickerSheet';
|
||||
import MLibraryPlaceSheet from './MLibraryPlaceSheet';
|
||||
|
||||
interface MPlacesLibraryProps {
|
||||
categories: Category[];
|
||||
language: string;
|
||||
dark: boolean;
|
||||
/** The screen's list or map, shared with the lists so the screen lays itself out for it. */
|
||||
view: 'list' | 'map';
|
||||
onView: (view: 'list' | 'map') => void;
|
||||
navigate: (to: string) => void;
|
||||
t: TranslationFn;
|
||||
}
|
||||
|
||||
type Drop = 'kind' | 'status' | 'category' | 'sort';
|
||||
|
||||
/** A map point per entry with a position; the map speaks CollectionPlace, keyed by a running id. */
|
||||
function toMapPlaces(entries: PlacesLibraryEntry[]) {
|
||||
const keyOf = new Map<number, string>();
|
||||
const places = entries.flatMap((entry, i) => {
|
||||
if (entry.lat == null || entry.lng == null) return [];
|
||||
keyOf.set(i + 1, entry.key);
|
||||
return [
|
||||
{
|
||||
id: i + 1,
|
||||
name: entry.name,
|
||||
lat: entry.lat,
|
||||
lng: entry.lng,
|
||||
address: entry.address,
|
||||
image_url: entry.image_url,
|
||||
category_id: entry.category?.id ?? null,
|
||||
category: entry.category,
|
||||
status: 'idea',
|
||||
} as unknown as CollectionPlace,
|
||||
];
|
||||
});
|
||||
return { places, keyOf };
|
||||
}
|
||||
|
||||
/** One entry of "All places" as a card: the category tile, name and address, and where it comes from. */
|
||||
function Row({ entry, onOpen, t }: { entry: PlacesLibraryEntry; onOpen: () => void; t: TranslationFn }) {
|
||||
const meta = categoryMeta(entry.category) ?? UNCATEGORIZED_META;
|
||||
const Icon = meta.icon;
|
||||
const trips = entry.origins.filter((o) => o.kind === 'trip');
|
||||
const lists = entry.origins.filter((o) => o.kind === 'list');
|
||||
const first = trips[0] ?? lists[0];
|
||||
const more = entry.origins.length - 1;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="mt-2 flex w-full items-center gap-[11px] rounded-2xl border border-m-rowbr bg-m-sheetop px-3 py-[11px] text-start"
|
||||
>
|
||||
<span
|
||||
className="flex h-10 w-10 flex-none items-center justify-center rounded-xl"
|
||||
style={{ background: tint(meta.color, '1f'), color: meta.color }}
|
||||
>
|
||||
<Icon size={17} strokeWidth={2.2} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span dir="auto" className="block truncate text-body font-bold text-m-ink">
|
||||
{entry.name}
|
||||
</span>
|
||||
{entry.address && (
|
||||
<span className="mt-[2px] flex items-center gap-[3px] truncate text-caption text-m-muted">
|
||||
<MapPin size={10} strokeWidth={2.2} className="flex-none" />
|
||||
<span dir="auto" className="truncate">
|
||||
{entry.address}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{first && (
|
||||
<span className="flex max-w-[42%] flex-none items-center gap-1 rounded-full border border-m-rowbr bg-m-ic px-2 py-[3px] text-caption font-semibold text-m-muted">
|
||||
{first.kind === 'trip' ? (
|
||||
<Luggage size={11} className="flex-none" />
|
||||
) : (
|
||||
<Bookmark size={11} className="flex-none" />
|
||||
)}
|
||||
<span dir="auto" className="truncate">
|
||||
{originName(first)}
|
||||
</span>
|
||||
{more > 0 && (
|
||||
<span className="flex-none text-m-faint">{t('collections.library.moreOrigins', { count: more })}</span>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* "All places" on the phone (PLC-07): every place of the user's trips and lists as
|
||||
* cards, with the same filter chips as a list (where from, status, category, order),
|
||||
* a search and the map. A card or a pin opens the place sheet (PLC-08).
|
||||
*/
|
||||
export default function MPlacesLibrary({ categories, language, dark, view, onView, navigate, t }: MPlacesLibraryProps) {
|
||||
const lib = usePlacesLibrary({ active: true, t });
|
||||
const openSave = useSaveToCollectionStore((s) => s.open);
|
||||
const copyToTrip = useCollectionStore((s) => s.copyToTrip);
|
||||
const [drop, setDrop] = useState<Drop | null>(null);
|
||||
const [copyId, setCopyId] = useState<number | null>(null);
|
||||
const map = useMemo(() => toMapPlaces(lib.entries), [lib.entries]);
|
||||
|
||||
const kindLabel = (k: LibraryKindFilter) =>
|
||||
t(
|
||||
k === 'all'
|
||||
? 'collections.library.kindAll'
|
||||
: k === 'trip'
|
||||
? 'collections.library.kindTrips'
|
||||
: 'collections.library.kindLists'
|
||||
);
|
||||
const category = lib.categoryId === 'all' ? null : (categories.find((c) => c.id === lib.categoryId) ?? null);
|
||||
const pick = (fn: () => void) => {
|
||||
fn();
|
||||
setDrop(null);
|
||||
};
|
||||
const chip = (on: boolean) => `${FILTER_CHIP} ${on ? CHIP_ON : CHIP_IDLE}`;
|
||||
|
||||
return (
|
||||
<div className={view === 'map' ? 'flex min-h-0 flex-1 flex-col' : ''}>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="flex flex-none rounded-xl border border-m-rowbr bg-m-sheetop p-[3px]">
|
||||
{(['list', 'map'] as const).map((v) => (
|
||||
<button
|
||||
key={v}
|
||||
type="button"
|
||||
onClick={() => onView(v)}
|
||||
aria-label={t(v === 'list' ? 'collections.view.list' : 'collections.view.map')}
|
||||
aria-pressed={view === v}
|
||||
className={`flex h-[30px] w-[38px] items-center justify-center rounded-[9px] ${view === v ? 'bg-m-act text-m-actfg' : 'text-m-muted'}`}
|
||||
>
|
||||
{v === 'list' ? <List size={15} strokeWidth={2} /> : <MapIcon size={15} strokeWidth={2} />}
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
<div className="flex h-9 min-w-0 flex-1 items-center gap-2 rounded-xl border border-m-rowbr bg-m-sheetop px-[13px]">
|
||||
<Search size={15} strokeWidth={2.2} className="flex-none text-m-muted" />
|
||||
<input
|
||||
value={lib.search}
|
||||
onChange={(e) => lib.setSearch(e.target.value)}
|
||||
enterKeyHint="search"
|
||||
placeholder={t('collections.library.search')}
|
||||
aria-label={t('collections.library.search')}
|
||||
className="min-w-0 flex-1 bg-transparent text-body text-m-ink outline-none placeholder:text-m-faint"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative mt-2 flex items-center gap-[6px]">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDrop((d) => (d === 'kind' ? null : 'kind'))}
|
||||
aria-expanded={drop === 'kind'}
|
||||
className={chip(lib.kind !== 'all')}
|
||||
>
|
||||
<Globe2 size={13} strokeWidth={2} className="flex-none" />
|
||||
<span className="truncate">{kindLabel(lib.kind)}</span>
|
||||
<ChevronDown size={12} strokeWidth={2} className="flex-none" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDrop((d) => (d === 'status' ? null : 'status'))}
|
||||
aria-expanded={drop === 'status'}
|
||||
className={chip(lib.status !== 'all')}
|
||||
>
|
||||
<Layers size={13} strokeWidth={2} className="flex-none" />
|
||||
<span className="truncate">
|
||||
{lib.status === 'all' ? t('collections.status.filterAll') : t(STATUS_SPEC[lib.status].labelKey)}
|
||||
</span>
|
||||
<ChevronDown size={12} strokeWidth={2} className="flex-none" />
|
||||
</button>
|
||||
{categories.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDrop((d) => (d === 'category' ? null : 'category'))}
|
||||
aria-expanded={drop === 'category'}
|
||||
aria-label={`${t('collections.category')}: ${category?.name ?? t('collections.status.filterAll')}`}
|
||||
className={chip(category != null)}
|
||||
>
|
||||
<Shapes size={13} strokeWidth={2} className="flex-none" />
|
||||
<span dir="auto" className="truncate">
|
||||
{category?.name ?? t('collections.status.filterAll')}
|
||||
</span>
|
||||
<ChevronDown size={12} strokeWidth={2} className="flex-none" />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDrop((d) => (d === 'sort' ? null : 'sort'))}
|
||||
aria-expanded={drop === 'sort'}
|
||||
aria-label={t('collections.library.sortLabel')}
|
||||
className={`${chip(lib.sort !== 'name')} !flex-none px-3`}
|
||||
>
|
||||
<ArrowDownUp size={13} strokeWidth={2} className="flex-none" />
|
||||
</button>
|
||||
|
||||
{drop && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('common.close')}
|
||||
className="fixed inset-0 z-10 cursor-default"
|
||||
onClick={() => setDrop(null)}
|
||||
/>
|
||||
)}
|
||||
{drop && (
|
||||
<div
|
||||
className={`absolute inset-x-0 top-[calc(100%+6px)] z-20 max-h-[300px] overflow-y-auto p-[6px] ${DROP_PANEL}`}
|
||||
>
|
||||
{drop === 'kind' &&
|
||||
(['all', 'trip', 'list'] as const).map((k) => (
|
||||
<DropRow
|
||||
key={k}
|
||||
icon={
|
||||
k === 'trip' ? (
|
||||
<Luggage size={15} className="flex-none" />
|
||||
) : k === 'list' ? (
|
||||
<Bookmark size={15} className="flex-none" />
|
||||
) : (
|
||||
<Globe2 size={15} className="flex-none" />
|
||||
)
|
||||
}
|
||||
label={kindLabel(k)}
|
||||
count={lib.counts[k]}
|
||||
on={lib.kind === k}
|
||||
onPick={() => pick(() => lib.setKind(k))}
|
||||
/>
|
||||
))}
|
||||
{drop === 'status' && (
|
||||
<>
|
||||
<DropRow
|
||||
icon={<Layers size={15} className="flex-none" />}
|
||||
label={t('collections.status.filterAll')}
|
||||
on={lib.status === 'all'}
|
||||
onPick={() => pick(() => lib.setStatus('all'))}
|
||||
/>
|
||||
{STATUS_ORDER.map((s: CollectionStatus) => {
|
||||
const meta = STATUS_SPEC[s];
|
||||
const Icon = meta.icon;
|
||||
return (
|
||||
<DropRow
|
||||
key={s}
|
||||
icon={<Icon size={15} className="flex-none" style={{ color: meta.color }} />}
|
||||
label={t(meta.labelKey)}
|
||||
on={lib.status === s}
|
||||
onPick={() => pick(() => lib.setStatus(s))}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
{drop === 'category' && (
|
||||
<>
|
||||
<DropRow
|
||||
icon={<Shapes size={15} className="flex-none" />}
|
||||
label={t('collections.status.filterAll')}
|
||||
on={lib.categoryId === 'all'}
|
||||
onPick={() => pick(() => lib.setCategoryId('all'))}
|
||||
/>
|
||||
{categories.map((c) => {
|
||||
const meta = categoryMeta(c) ?? UNCATEGORIZED_META;
|
||||
const Icon = meta.icon;
|
||||
return (
|
||||
<DropRow
|
||||
key={c.id}
|
||||
icon={<Icon size={15} className="flex-none" style={{ color: meta.color }} />}
|
||||
label={c.name}
|
||||
on={lib.categoryId === c.id}
|
||||
onPick={() => pick(() => lib.setCategoryId(c.id))}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
{drop === 'sort' &&
|
||||
(['name', 'updated'] as PlacesLibrarySort[]).map((s) => (
|
||||
<DropRow
|
||||
key={s}
|
||||
icon={<ArrowDownUp size={15} className="flex-none" />}
|
||||
label={t(s === 'name' ? 'collections.sort.nameAsc' : 'collections.library.sortUpdated')}
|
||||
on={lib.sort === s}
|
||||
onPick={() => pick(() => lib.setSort(s))}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{lib.offline ? (
|
||||
<EmptyNote scene="collections" title={t('collections.library.offline')} />
|
||||
) : lib.error ? (
|
||||
<p role="alert" className="mt-3 rounded-xl bg-danger-soft px-3 py-2 text-body text-danger">
|
||||
{lib.error}
|
||||
</p>
|
||||
) : lib.loading && lib.entries.length === 0 ? (
|
||||
<div className="flex justify-center py-16 text-m-faint">
|
||||
<Loader2 size={20} className="animate-spin" />
|
||||
</div>
|
||||
) : lib.entries.length === 0 ? (
|
||||
<EmptyNote
|
||||
scene={lib.filtered ? 'search' : 'collections'}
|
||||
title={t(lib.filtered ? 'collections.empty.noMatchTitle' : 'collections.library.emptyTitle')}
|
||||
/>
|
||||
) : view === 'map' ? (
|
||||
<div className="mt-3 min-h-0 flex-1 overflow-hidden rounded-2xl border border-m-rowbr">
|
||||
<CollectionMap
|
||||
places={map.places}
|
||||
selectedPlaceId={null}
|
||||
onOpenPlace={(id) => {
|
||||
const key = map.keyOf.get(id);
|
||||
if (key) lib.show(key);
|
||||
}}
|
||||
dark={dark}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="wide:grid wide:grid-cols-[repeat(auto-fill,minmax(min(100%,380px),1fr))] wide:gap-x-3">
|
||||
{lib.entries.map((entry) => (
|
||||
<Row key={entry.key} entry={entry} onOpen={() => lib.show(entry.key)} t={t} />
|
||||
))}
|
||||
{lib.hasMore && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void lib.loadMore()}
|
||||
disabled={lib.loadingMore}
|
||||
className="mt-3 flex w-full items-center justify-center gap-2 rounded-full border border-m-rowbr bg-m-sheetop py-[10px] text-body font-semibold text-m-ink"
|
||||
>
|
||||
{lib.loadingMore && <Loader2 size={15} className="animate-spin" />}
|
||||
{t('collections.library.more', { count: lib.total - lib.entries.length })}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<MLibraryPlaceSheet
|
||||
open={lib.selectedKey != null}
|
||||
data={lib.detail}
|
||||
loading={lib.detailLoading}
|
||||
cover={lib.cover}
|
||||
language={language}
|
||||
onClose={lib.close}
|
||||
onOpenList={(collectionId, placeId) => navigate(`${placesPath(collectionId)}?place=${placeId}`)}
|
||||
onOpenTrip={(tripId, placeId) => navigate(`/trips/${tripId}?place=${placeId}`)}
|
||||
onSaveToList={(origin, d) =>
|
||||
openSave({
|
||||
name: d.info.name,
|
||||
source_trip_id: origin.trip_id,
|
||||
source_place_id: origin.place_id,
|
||||
description: d.info.description,
|
||||
lat: d.info.lat,
|
||||
lng: d.info.lng,
|
||||
address: d.info.address,
|
||||
category_id: lib.detail?.entry.category?.id ?? null,
|
||||
image_url: d.info.image_url,
|
||||
website: d.info.website,
|
||||
phone: d.info.phone,
|
||||
})
|
||||
}
|
||||
onCopyToTrip={(id) => {
|
||||
lib.close();
|
||||
setCopyId(id);
|
||||
}}
|
||||
t={t}
|
||||
/>
|
||||
<MCollTripPickerSheet
|
||||
open={copyId != null}
|
||||
count={1}
|
||||
onCopy={(tripId, carry) => copyToTrip(tripId, copyId != null ? [copyId] : [], undefined, carry)}
|
||||
onClose={() => setCopyId(null)}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { shortZone, useDashboardTimezones, zoneOptionLabel } from '../../../comp
|
||||
import { formatTime, splitReservationDateTime } from '../../../utils/formatters'
|
||||
import { normalizeAppearance, MOBILE_DASH_TOKENS, type MobileDashToken } from '@trek/shared'
|
||||
import { MOMENT_LABEL, upcomingKey, type UpcomingReservation } from '../../../pages/dashboard/dashboardModel'
|
||||
import { PLACES_ROOT, placesPath } from '../../../utils/placesRoutes'
|
||||
|
||||
const RES_ICON: Record<string, React.ReactElement> = {
|
||||
flight: <Plane size={14} strokeWidth={2} />,
|
||||
@@ -179,7 +180,7 @@ function MCollectionsWidget(): React.ReactElement {
|
||||
icon={<Bookmark size={12} strokeWidth={2.2} />}
|
||||
title={t('collections.widget.title')}
|
||||
action={
|
||||
<button type="button" aria-label={t('collections.widget.title')} onClick={() => navigate('/collections')} className="flex text-m-faint">
|
||||
<button type="button" aria-label={t('collections.widget.title')} onClick={() => navigate(PLACES_ROOT)} className="flex text-m-faint">
|
||||
<ArrowRight size={13} strokeWidth={2} />
|
||||
</button>
|
||||
}
|
||||
@@ -191,7 +192,7 @@ function MCollectionsWidget(): React.ReactElement {
|
||||
<button
|
||||
key={list.id}
|
||||
type="button"
|
||||
onClick={() => navigate(`/collections/${list.id}`)}
|
||||
onClick={() => navigate(placesPath(list.id))}
|
||||
className="mt-[11px] flex w-full items-center rounded-[14px] p-[15px_14px] text-start text-white"
|
||||
style={{ background: list.color || entityGradient(list.id) }}
|
||||
>
|
||||
|
||||
@@ -16,6 +16,7 @@ import AddPlaceToCollectionModal from '../components/Collections/AddPlaceToColle
|
||||
import ImportFromTripModal from '../components/Collections/ImportFromTripModal'
|
||||
import ImportCollectionModal from '../components/Collections/ImportCollectionModal'
|
||||
import CollectionPlaceDetail from '../components/Collections/CollectionPlaceDetail'
|
||||
import PlacesLibraryView from '../components/Collections/PlacesLibraryView'
|
||||
import LabelManager from '../components/Collections/LabelManager'
|
||||
import BulkAssignLabelModal from '../components/Collections/BulkAssignLabelModal'
|
||||
import { ActiveCollectionTours } from '../components/Tours/collection/CollectionToursSection'
|
||||
@@ -37,7 +38,9 @@ export default function CollectionsPage(): React.ReactElement {
|
||||
}
|
||||
|
||||
function CollectionsPageDesktop(): React.ReactElement {
|
||||
const c = useCollections()
|
||||
// The refs are taken out first: read through the same object as the rest, every
|
||||
// field of it counted as a ref read during render.
|
||||
const { heroRef, listColRef, mapColRef, ...c } = useCollections()
|
||||
const { t } = c
|
||||
|
||||
const title = c.isAllSaved ? t('collections.allSaved') : (c.activeCollection?.name ?? t('collections.title'))
|
||||
@@ -193,8 +196,8 @@ function CollectionsPageDesktop(): React.ReactElement {
|
||||
} else if (desktopSplit) {
|
||||
body = (
|
||||
<div className={`col-split${c.view === 'map' ? ' map-full' : ''}`}>
|
||||
<div className="col-split-list" ref={c.listColRef}>{listColumn}</div>
|
||||
<div className="col-split-map" ref={c.mapColRef}>{mapPanel(true)}</div>
|
||||
<div className="col-split-list" ref={listColRef}>{listColumn}</div>
|
||||
<div className="col-split-map" ref={mapColRef}>{mapPanel(true)}</div>
|
||||
</div>
|
||||
)
|
||||
} else if (c.view === 'map' && c.hasMappable) {
|
||||
@@ -208,6 +211,9 @@ function CollectionsPageDesktop(): React.ReactElement {
|
||||
ownedLists={c.ownedLists}
|
||||
sharedLists={c.sharedLists}
|
||||
activeId={c.activeId}
|
||||
libraryActive={c.isLibrary}
|
||||
savedCount={c.collections.reduce((n, l) => n + (l.place_count ?? 0), 0)}
|
||||
onSelectLibrary={() => c.handleSelectList('library')}
|
||||
incomingInvites={c.incomingInvites}
|
||||
onSelect={c.handleSelectList}
|
||||
onNewList={() => { c.setMobileRailOpen(false); c.setEditorTarget('new') }}
|
||||
@@ -237,7 +243,45 @@ function CollectionsPageDesktop(): React.ReactElement {
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
{noLists ? (
|
||||
{c.isLibrary ? (
|
||||
<>
|
||||
<div ref={heroRef}>
|
||||
<CollectionHero
|
||||
eyebrow={t('collections.library.eyebrow')}
|
||||
title={t('collections.library.title')}
|
||||
color={heroColor}
|
||||
description={t('collections.library.subtitle')}
|
||||
members={[]}
|
||||
canShare={false}
|
||||
isOwner={false}
|
||||
canEdit={false}
|
||||
onEdit={() => {}}
|
||||
shareMemberCount={0}
|
||||
onShare={() => {}}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
{!c.isWide && (
|
||||
<div className="col-toolbar">
|
||||
<button type="button" className="col-rail-toggle" onClick={() => c.setMobileRailOpen(true)}>
|
||||
<Bookmark size={15} /> {t('collections.title')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<PlacesLibraryView
|
||||
categories={c.categories}
|
||||
dark={c.dark}
|
||||
isWide={c.isWide}
|
||||
language={c.language}
|
||||
view={c.view}
|
||||
onView={c.setView}
|
||||
mapLocked={c.mapLocked}
|
||||
onToggleMapLocked={c.toggleMapLocked}
|
||||
navigate={c.navigate}
|
||||
t={t}
|
||||
/>
|
||||
</>
|
||||
) : noLists ? (
|
||||
<div className="flex flex-col items-center">
|
||||
<EmptyState scene="collections" title={t('collections.empty.firstTitle')} className="pb-4" />
|
||||
<button type="button" onClick={() => c.setEditorTarget('new')} className="col-cta">
|
||||
@@ -246,13 +290,13 @@ function CollectionsPageDesktop(): React.ReactElement {
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div ref={c.heroRef}>
|
||||
<div ref={heroRef}>
|
||||
<CollectionHero
|
||||
eyebrow={eyebrow}
|
||||
title={title}
|
||||
color={heroColor}
|
||||
coverImage={heroCover}
|
||||
description={c.isAllSaved ? null : (c.activeCollection?.description ?? null)}
|
||||
description={c.isAllSaved ? t('collections.allSavedSubtitle') : (c.activeCollection?.description ?? null)}
|
||||
links={c.isAllSaved ? undefined : c.activeCollection?.links}
|
||||
members={c.members}
|
||||
canShare={c.canShare}
|
||||
|
||||
@@ -37,6 +37,7 @@ import { useSettingsStore } from '../store/settingsStore'
|
||||
import { useAddonStore } from '../store/addonStore'
|
||||
import { normalizeAppearance } from '@trek/shared'
|
||||
import '../styles/dashboard.css'
|
||||
import { PLACES_ROOT } from '../utils/placesRoutes'
|
||||
|
||||
const GRADIENTS = [
|
||||
'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
|
||||
@@ -274,7 +275,7 @@ function DashboardPageDesktop(): React.ReactElement {
|
||||
{sidebarVisible && (
|
||||
<aside className="page-sidebar">
|
||||
{showCurrency && <CurrencyTool />}
|
||||
{showCollections && <CollectionsWidget onOpen={() => navigate('/collections')} />}
|
||||
{showCollections && <CollectionsWidget onOpen={() => navigate(PLACES_ROOT)} />}
|
||||
{showTimezones && <TimezoneTool locale={locale} />}
|
||||
{showUpcoming && <UpcomingTool items={upcoming} locale={locale} onOpen={(tripId) => navigate(`/trips/${tripId}`)} />}
|
||||
<PluginWidgets plugins={widgetPlugins} tripId={spotlight ? String(spotlight.id) : null} />
|
||||
|
||||
@@ -16,11 +16,13 @@ import { useCollections } from './useCollections'
|
||||
|
||||
const navigate = vi.fn()
|
||||
let routeParams: { id?: string } = {}
|
||||
let onLibrary = false
|
||||
let searchParams = new URLSearchParams()
|
||||
const setSearchParams = vi.fn()
|
||||
vi.mock('react-router', () => ({
|
||||
useNavigate: () => navigate,
|
||||
useParams: () => routeParams,
|
||||
useMatch: () => (onLibrary ? { params: {} } : null),
|
||||
useSearchParams: () => [searchParams, setSearchParams],
|
||||
}))
|
||||
|
||||
@@ -157,6 +159,7 @@ beforeEach(() => {
|
||||
store = makeStore()
|
||||
hoisted.store = store
|
||||
routeParams = {}
|
||||
onLibrary = false
|
||||
searchParams = new URLSearchParams()
|
||||
setSearchParams.mockClear()
|
||||
wideMedia = false
|
||||
@@ -480,23 +483,23 @@ describe('useCollections — list handlers', () => {
|
||||
expect(result.current.mobileRailOpen).toBe(true)
|
||||
|
||||
act(() => result.current.handleSelectList(4))
|
||||
expect(navigate).toHaveBeenCalledWith('/collections/4')
|
||||
expect(navigate).toHaveBeenCalledWith('/places/4')
|
||||
expect(result.current.mobileRailOpen).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-PAGE-COLL-032: the All-saved entry and a null id both go to the index route', async () => {
|
||||
const { result } = await setup()
|
||||
act(() => result.current.handleSelectList('all'))
|
||||
expect(navigate).toHaveBeenLastCalledWith('/collections')
|
||||
expect(navigate).toHaveBeenLastCalledWith('/places/saved')
|
||||
|
||||
act(() => result.current.handleSelectList(null))
|
||||
expect(navigate).toHaveBeenLastCalledWith('/collections')
|
||||
expect(navigate).toHaveBeenLastCalledWith('/places/saved')
|
||||
})
|
||||
|
||||
it('FE-PAGE-COLL-033: a freshly created list is opened', async () => {
|
||||
const { result } = await setup()
|
||||
act(() => result.current.handleEditorCreated(11))
|
||||
expect(navigate).toHaveBeenCalledWith('/collections/11')
|
||||
expect(navigate).toHaveBeenCalledWith('/places/11')
|
||||
})
|
||||
|
||||
it('FE-PAGE-COLL-034: adding a place refreshes the active list', async () => {
|
||||
@@ -518,7 +521,7 @@ describe('useCollections — list handlers', () => {
|
||||
await act(async () => { await result.current.handleDeleteList() })
|
||||
|
||||
expect(store.deleteCollection).toHaveBeenCalledWith(3)
|
||||
expect(navigate).toHaveBeenCalledWith('/collections')
|
||||
expect(navigate).toHaveBeenCalledWith('/places/saved')
|
||||
expect(result.current.confirmDeleteList).toBeNull()
|
||||
})
|
||||
|
||||
@@ -720,7 +723,7 @@ describe('useCollections — invites and leaving', () => {
|
||||
const { result } = await setup()
|
||||
await act(async () => { await result.current.handleAcceptInvite(12) })
|
||||
expect(store.acceptInvite).toHaveBeenCalledWith(12)
|
||||
expect(navigate).toHaveBeenCalledWith('/collections/12')
|
||||
expect(navigate).toHaveBeenCalledWith('/places/12')
|
||||
})
|
||||
|
||||
it('FE-PAGE-COLL-057: a failing accept toasts and does not navigate', async () => {
|
||||
@@ -747,7 +750,7 @@ describe('useCollections — invites and leaving', () => {
|
||||
act(() => result.current.handleAfterLeave())
|
||||
|
||||
expect(result.current.showShare).toBe(false)
|
||||
expect(navigate).toHaveBeenCalledWith('/collections')
|
||||
expect(navigate).toHaveBeenCalledWith('/places/saved')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -854,7 +857,7 @@ describe('useCollections — websocket sync', () => {
|
||||
store.loadAll.mockClear()
|
||||
act(() => wsHandler()({ type: 'collections:deleted', collectionId: 4 }))
|
||||
|
||||
expect(navigate).toHaveBeenCalledWith('/collections')
|
||||
expect(navigate).toHaveBeenCalledWith('/places/saved')
|
||||
expect(store.loadAll).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
@@ -1104,7 +1107,7 @@ describe('useCollections — export and import as a file', () => {
|
||||
await act(async () => { await result.current.handleImportFile(listFile as never) })
|
||||
|
||||
expect(store.loadAll).toHaveBeenCalled()
|
||||
expect(navigate).toHaveBeenCalledWith('/collections/42')
|
||||
expect(navigate).toHaveBeenCalledWith('/places/42')
|
||||
expect(addToast).toHaveBeenCalledWith('2 places imported', 'success', undefined)
|
||||
expect(result.current.showImportFile).toBe(false)
|
||||
})
|
||||
@@ -1126,7 +1129,7 @@ describe('useCollections — export and import as a file', () => {
|
||||
|
||||
await expect(act(async () => { await result.current.handleImportFile(listFile as never) })).rejects.toBeTruthy()
|
||||
|
||||
expect(navigate).not.toHaveBeenCalledWith(expect.stringContaining('/collections/'))
|
||||
expect(navigate).not.toHaveBeenCalledWith(expect.stringContaining('/places/'))
|
||||
expect(result.current.showImportFile).toBe(true)
|
||||
})
|
||||
|
||||
@@ -1142,7 +1145,7 @@ describe('useCollections — export and import as a file', () => {
|
||||
|
||||
expect(seen[0]).toEqual({ id: '11', body: { file: listFile } })
|
||||
expect(store.loadAll).toHaveBeenCalled()
|
||||
expect(navigate).toHaveBeenCalledWith('/collections/11')
|
||||
expect(navigate).toHaveBeenCalledWith('/places/11')
|
||||
expect(addToast).toHaveBeenCalledWith('2 added to Lisbon 2027, 1 were already there', 'success', undefined)
|
||||
expect(result.current.showImportFile).toBe(false)
|
||||
})
|
||||
@@ -1157,7 +1160,7 @@ describe('useCollections — export and import as a file', () => {
|
||||
await act(async () => { await result.current.handleImportFileInto(listFile as never, 11) })
|
||||
|
||||
expect(store.refreshActive).toHaveBeenCalled()
|
||||
expect(navigate).not.toHaveBeenCalledWith('/collections/11')
|
||||
expect(navigate).not.toHaveBeenCalledWith('/places/11')
|
||||
expect(addToast).toHaveBeenCalledWith('2 places added to Lisbon 2027', 'success', undefined)
|
||||
})
|
||||
|
||||
@@ -1349,7 +1352,7 @@ describe('useCollections — route that is an invite (#2645)', () => {
|
||||
routeParams = { id: '14' }
|
||||
store.collections = [collection({ id: 2 })]
|
||||
await setup()
|
||||
await waitFor(() => expect(navigate).toHaveBeenCalledWith('/collections', { replace: true }))
|
||||
await waitFor(() => expect(navigate).toHaveBeenCalledWith('/places/saved', { replace: true }))
|
||||
})
|
||||
|
||||
it('FE-PAGE-COLL-089: no bounce while the lists are still loading', async () => {
|
||||
@@ -1359,7 +1362,7 @@ describe('useCollections — route that is an invite (#2645)', () => {
|
||||
await setup()
|
||||
expect(navigate).not.toHaveBeenCalled()
|
||||
await act(async () => { finish() })
|
||||
await waitFor(() => expect(navigate).toHaveBeenCalledWith('/collections', { replace: true }))
|
||||
await waitFor(() => expect(navigate).toHaveBeenCalledWith('/places/saved', { replace: true }))
|
||||
})
|
||||
|
||||
it('FE-PAGE-COLL-090: a route id that is one of the lists stays put', async () => {
|
||||
@@ -1443,4 +1446,14 @@ describe('useCollections — route that is an invite (#2645)', () => {
|
||||
await act(async () => { await result.current.handleCopyToTrip(20, { include_notes: true }) })
|
||||
expect(store.copyToTrip).toHaveBeenCalledWith(20, [4, 5], undefined, { include_notes: true })
|
||||
})
|
||||
|
||||
it('FE-PAGE-COLL-098: /places is the overview, and the rail goes there and back', async () => {
|
||||
onLibrary = true
|
||||
const { result } = await setup()
|
||||
expect(result.current.isLibrary).toBe(true)
|
||||
act(() => result.current.handleSelectList('library'))
|
||||
expect(navigate).toHaveBeenLastCalledWith('/places')
|
||||
act(() => result.current.handleSelectList('all'))
|
||||
expect(navigate).toHaveBeenLastCalledWith('/places/saved')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useNavigate, useParams, useSearchParams } from 'react-router'
|
||||
import { useMatch, useNavigate, useParams, useSearchParams } from 'react-router'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useElementSize } from '../../hooks/useElementSize'
|
||||
import { useElementRect } from '../../hooks/useElementRect'
|
||||
@@ -10,6 +10,7 @@ import { useToast } from '../../components/shared/Toast'
|
||||
import { collectionsApi } from '../../api/collections'
|
||||
import { downloadCollectionFile, downloadCollectionGpx, downloadCollectionKml, type CollectionExportFormat } from '../../components/Collections/collectionFile'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
import { PLACES_SAVED, placesPath } from '../../utils/placesRoutes'
|
||||
import type { CopyCarry, CopyCarryOptions } from '../../components/Collections/useTripCopyPicker'
|
||||
import { canAddToCollection, canRemoveFromCollection, collectionRoleOf } from '../../utils/collectionAccess'
|
||||
import { addListener, removeListener } from '../../api/websocket'
|
||||
@@ -28,13 +29,15 @@ const WS_RELOAD_SETTLE_MS = 400
|
||||
* Collections page logic — owns the page-local UI state (new/edit-list forms,
|
||||
* mobile rail drawer), pulls the collection store, wires the WebSocket live sync
|
||||
* (incl. collections:deleted clearing the active list) and keeps the route param
|
||||
* (/collections/:id) in sync with the active list. CollectionsPage stays a pure
|
||||
* (/places/:id) in sync with the active list. CollectionsPage stays a pure
|
||||
* wiring container around the rail + toolbar + view JSX.
|
||||
*/
|
||||
export function useCollections() {
|
||||
const { t, language } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const { id: routeId } = useParams<{ id: string }>()
|
||||
// /places is the overview of every place (PLC-07); the lists live below it.
|
||||
const isLibrary = useMatch({ path: '/places', end: true }) != null
|
||||
const toast = useToast()
|
||||
|
||||
const dm = useSettingsStore(s => s.settings.dark_mode)
|
||||
@@ -117,7 +120,7 @@ export function useCollections() {
|
||||
return () => cancelAnimationFrame(raf)
|
||||
}, [view, isWide])
|
||||
|
||||
// The invite notification links to /collections/:id, a list the invitee
|
||||
// The invite notification links to /collections/:id (now /places/:id), a list the invitee
|
||||
// cannot read before they accept (#2645). When the route is such an invite
|
||||
// the page offers it instead of opening the list, and lists it first.
|
||||
const routeInvite = useMemo(() => {
|
||||
@@ -130,8 +133,8 @@ export function useCollections() {
|
||||
[routeInvite, incomingInvites],
|
||||
)
|
||||
|
||||
// Keep the active list in sync with the URL (/collections/:id, or the
|
||||
// "All saved" union at /collections). A pending invite on the route shows
|
||||
// Keep the active list in sync with the URL (/places/:id, or the
|
||||
// "All saved" union at /places/saved and behind the overview at /places). A pending invite on the route shows
|
||||
// the union behind its card.
|
||||
useEffect(() => {
|
||||
const next: ActiveCollectionId = routeId && !routeInvite ? Number(routeId) : ALL_SAVED
|
||||
@@ -150,10 +153,10 @@ export function useCollections() {
|
||||
const id = Number(routeId)
|
||||
if (Number.isNaN(id)) return
|
||||
if (collections.some(l => l.id === id) || incomingInvites.some(inv => inv.collection_id === id)) return
|
||||
navigate('/collections', { replace: true })
|
||||
navigate(PLACES_SAVED, { replace: true })
|
||||
}, [listsLoaded, loading, routeId, collections, incomingInvites, navigate])
|
||||
|
||||
// A link to one saved place (/collections/:id?place=<id>, the assistant's
|
||||
// A link to one saved place (/places/:id?place=<id>, the assistant's
|
||||
// "Open in Collections") opens it once the list on the route holds it, and
|
||||
// then drops the param, so a reload or the back button does not reopen it.
|
||||
// A list that has loaded without the place (deleted or moved since) drops
|
||||
@@ -182,7 +185,7 @@ export function useCollections() {
|
||||
if (!msg.type?.startsWith('collections:')) return
|
||||
if (msg.type === 'collections:deleted' || msg.type === 'collections:removed') {
|
||||
if (msg.collectionId != null && activeId === msg.collectionId) {
|
||||
navigate('/collections')
|
||||
navigate(PLACES_SAVED)
|
||||
}
|
||||
loadAll()
|
||||
return
|
||||
@@ -280,15 +283,15 @@ export function useCollections() {
|
||||
const counts = useMemo(() => statusCounts(places), [places])
|
||||
|
||||
// ── Handlers ────────────────────────────────────────────────────────
|
||||
const handleSelectList = useCallback((id: ActiveCollectionId) => {
|
||||
const handleSelectList = useCallback((id: ActiveCollectionId | 'library') => {
|
||||
setMobileRailOpen(false)
|
||||
navigate(id === ALL_SAVED || id === null ? '/collections' : `/collections/${id}`)
|
||||
navigate(placesPath(id === 'library' ? 'library' : id === ALL_SAVED || id === null ? 'saved' : id))
|
||||
}, [navigate])
|
||||
|
||||
// The editor modal owns its own form + create/update/upload calls; the hook
|
||||
// just opens it and navigates to a freshly created list.
|
||||
const handleEditorCreated = useCallback((id: number) => {
|
||||
navigate(`/collections/${id}`)
|
||||
navigate(placesPath(id))
|
||||
}, [navigate])
|
||||
|
||||
const handlePlaceAdded = useCallback(() => { refreshActive() }, [refreshActive])
|
||||
@@ -351,7 +354,7 @@ export function useCollections() {
|
||||
const result = await collectionsApi.importFile({ file, name })
|
||||
await loadAll()
|
||||
const created = result.collection as Collection
|
||||
navigate(`/collections/${created.id}`)
|
||||
navigate(placesPath(created.id))
|
||||
if (result.skipped > 0) {
|
||||
toast.info(t('collections.file.doneSkipped', { count: result.imported, skipped: result.skipped }))
|
||||
} else {
|
||||
@@ -374,7 +377,7 @@ export function useCollections() {
|
||||
const duplicates = result.duplicates ?? 0
|
||||
await loadAll()
|
||||
if (activeId === collectionId) refreshActive()
|
||||
else navigate(`/collections/${collectionId}`)
|
||||
else navigate(placesPath(collectionId))
|
||||
if (result.imported === 0 && duplicates > 0) {
|
||||
toast.info(t('collections.file.doneIntoNothing', { name }))
|
||||
} else if (duplicates > 0) {
|
||||
@@ -393,7 +396,7 @@ export function useCollections() {
|
||||
setConfirmDeleteList(null)
|
||||
try {
|
||||
await deleteCollection(id)
|
||||
if (activeId === id) navigate('/collections')
|
||||
if (activeId === id) navigate(PLACES_SAVED)
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
}
|
||||
@@ -501,7 +504,7 @@ export function useCollections() {
|
||||
const handleAcceptInvite = useCallback(async (collectionId: number) => {
|
||||
try {
|
||||
await acceptInvite(collectionId)
|
||||
navigate(`/collections/${collectionId}`)
|
||||
navigate(placesPath(collectionId))
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
}
|
||||
@@ -519,7 +522,7 @@ export function useCollections() {
|
||||
// the rail and close the share modal. Errors are surfaced inside the modal.
|
||||
const handleAfterLeave = useCallback(() => {
|
||||
setShowShare(false)
|
||||
navigate('/collections')
|
||||
navigate(PLACES_SAVED)
|
||||
}, [navigate])
|
||||
|
||||
// ── Detail panel (re-pointed PlaceInspector in collection mode) ──────
|
||||
@@ -580,7 +583,7 @@ export function useCollections() {
|
||||
}, [copyIds, copyToTrip, selectMode, clearSelection])
|
||||
|
||||
return {
|
||||
t, language, dark, navigate,
|
||||
t, language, dark, navigate, isLibrary,
|
||||
isWide, heroRef: hero.ref, heroHeight: hero.height,
|
||||
listColRef: listCol.ref, listColRect: listCol.rect, mapColRef: mapCol.ref, mapColRect: mapCol.rect, categories,
|
||||
mapLocked, toggleMapLocked,
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { PlacesLibraryDetailResponse, PlacesLibraryPageResponse } from '@trek/shared';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mapsApi } from '../api/client';
|
||||
import { placesLibraryApi } from '../api/placesLibrary';
|
||||
import { OnlineOnlyError } from './onlineOnly';
|
||||
import { placesLibraryRepo } from './placesLibraryRepo';
|
||||
|
||||
// FE-REPO-PLACES-LIBRARY-001 to FE-REPO-PLACES-LIBRARY-002
|
||||
// FE-REPO-PLACES-LIBRARY-001 to FE-REPO-PLACES-LIBRARY-004
|
||||
|
||||
const network = vi.hoisted(() => ({ offline: false }));
|
||||
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: () => network.offline }));
|
||||
@@ -41,4 +42,27 @@ describe('placesLibraryRepo', () => {
|
||||
expect(list).toHaveBeenCalledWith({ sort: 'updated' }, signal);
|
||||
expect(detail).toHaveBeenCalledWith('list', 9, signal);
|
||||
});
|
||||
|
||||
it("FE-REPO-PLACES-LIBRARY-003: a cover photo is the provider's photo for the place's position", async () => {
|
||||
const photo = vi.spyOn(mapsApi, 'placePhoto').mockResolvedValueOnce({ photoUrl: 'https://photos.example/c.jpg' });
|
||||
expect(await placesLibraryRepo.coverPhoto({ name: 'Colosseum', lat: 41.89, lng: 12.49 })).toBe(
|
||||
'https://photos.example/c.jpg'
|
||||
);
|
||||
expect(photo).toHaveBeenCalledWith('41.89,12.49', 41.89, 12.49, 'Colosseum');
|
||||
|
||||
photo.mockResolvedValueOnce({ photoUrl: null });
|
||||
expect(await placesLibraryRepo.coverPhoto({ name: 'Colosseum', lat: 41.89, lng: 12.49 })).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-REPO-PLACES-LIBRARY-004: a place without a position has no cover, and offline nothing is asked', async () => {
|
||||
const photo = vi.spyOn(mapsApi, 'placePhoto');
|
||||
expect(await placesLibraryRepo.coverPhoto({ name: 'Nowhere', lat: null, lng: 12.49 })).toBeNull();
|
||||
expect(await placesLibraryRepo.coverPhoto({ name: 'Nowhere', lat: 41.89, lng: null })).toBeNull();
|
||||
|
||||
network.offline = true;
|
||||
await expect(placesLibraryRepo.coverPhoto({ name: 'Colosseum', lat: 41.89, lng: 12.49 })).rejects.toBeInstanceOf(
|
||||
OnlineOnlyError
|
||||
);
|
||||
expect(photo).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
PlacesLibraryPageResponse,
|
||||
PlacesLibraryQueryInput,
|
||||
} from '@trek/shared';
|
||||
import { mapsApi } from '../api/client';
|
||||
import { placesLibraryApi } from '../api/placesLibrary';
|
||||
import { requireOnline } from './onlineOnly';
|
||||
|
||||
@@ -23,4 +24,15 @@ export const placesLibraryRepo = {
|
||||
requireOnline();
|
||||
return await placesLibraryApi.detail(kind, id, signal);
|
||||
},
|
||||
|
||||
/**
|
||||
* A cover photo from the maps provider for a place without its own image, the one
|
||||
* the lists show too: looked up by the place's position. Null when there is none.
|
||||
*/
|
||||
async coverPhoto(place: { name: string; lat: number | null; lng: number | null }): Promise<string | null> {
|
||||
if (place.lat == null || place.lng == null) return null;
|
||||
requireOnline();
|
||||
const res = await mapsApi.placePhoto(`${place.lat},${place.lng}`, place.lat, place.lng, place.name);
|
||||
return res?.photoUrl ?? null;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -29,14 +29,18 @@
|
||||
}
|
||||
.trek-dash .col-rail-newrow { display: flex; align-items: stretch; gap: 6px; margin-bottom: 6px; }
|
||||
.trek-dash .col-rail-new {
|
||||
display: flex; align-items: center; gap: 9px; width: 100%;
|
||||
padding: 10px 12px; border-radius: var(--r-sm);
|
||||
border: 1px dashed var(--line-2); color: var(--ink-2);
|
||||
font-size: 13px; font-weight: 500; transition: background .15s, color .15s, border-color .15s;
|
||||
display: flex; align-items: center; gap: 10px; width: 100%; height: 44px;
|
||||
/* 10px plus the 1px border: the plus sits where the tiles and dots of the rows below sit. */
|
||||
padding: 0 12px; padding-inline-start: 10px; border-radius: 12px;
|
||||
border: 1px solid var(--line); background: var(--surface-2); color: var(--ink);
|
||||
font-size: 13.5px; font-weight: 600; transition: background .15s, border-color .15s, box-shadow .15s;
|
||||
}
|
||||
.trek-dash .col-rail-new:hover { background: var(--surface-2); color: var(--ink); border-color: var(--ink-3); }
|
||||
.trek-dash .col-rail-new:hover { background: var(--surface); border-color: var(--line-2); box-shadow: var(--sh-xs); }
|
||||
/* The plus as a small accent disc: the one thing in the rail that makes something. */
|
||||
.trek-dash .col-rail-plus { width: 28px; height: 28px; flex-shrink: 0; display: grid; place-items: center; border-radius: 8px; background: var(--accent); color: var(--accent-text); }
|
||||
/* Square, icon-only: "New list" is the primary action and keeps the label. */
|
||||
.trek-dash .col-rail-import { width: auto; flex: 0 0 auto; padding: 10px; justify-content: center; }
|
||||
.trek-dash .col-rail-import { width: 44px; flex: 0 0 44px; padding: 0; justify-content: center; color: var(--ink-2); }
|
||||
.trek-dash .col-rail-import:hover { color: var(--ink); }
|
||||
.trek-dash .col-rail-label {
|
||||
display: flex; align-items: center; gap: 6px; padding: 14px 11px 5px;
|
||||
font-size: 10.5px; text-transform: uppercase; letter-spacing: .13em; color: var(--ink-3); font-weight: 600;
|
||||
@@ -55,9 +59,16 @@
|
||||
}
|
||||
.trek-dash .col-row-btn:hover { background: var(--surface-2); color: var(--ink); }
|
||||
.trek-dash .col-row-btn.on { background: var(--surface-2); color: var(--ink); box-shadow: var(--sh-xs); }
|
||||
.trek-dash .col-row-btn .dot { width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0; }
|
||||
.trek-dash .col-row-btn .dot { width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0; margin-inline: 9px; }
|
||||
/* The dot keeps the 28px slot the view tiles take, so every name in the rail starts at one edge. */
|
||||
.trek-dash .col-row-btn .ico { color: var(--ink-3); flex-shrink: 0; display: grid; place-items: center; }
|
||||
.trek-dash .col-row-btn.on .ico { color: var(--ink-2); }
|
||||
/* The two views above the lists wear a small tile, filled in the accent when open. */
|
||||
.trek-dash .col-row-btn .ico.tile { width: 28px; height: 28px; border-radius: 8px; background: var(--surface-2); color: var(--ink-2); transition: background .15s, color .15s; }
|
||||
.trek-dash .col-row-btn.on .ico.tile { background: var(--accent); color: var(--accent-text); }
|
||||
/* A list's tile wears the list's colour, open or not. */
|
||||
.trek-dash .col-row-btn .ico.tile.list, .trek-dash .col-row-btn.on .ico.tile.list { background: color-mix(in srgb, var(--list) 16%, transparent); color: var(--list); }
|
||||
.trek-dash .col-row-btn.on .ico.tile.list { box-shadow: inset 0 0 0 1.5px color-mix(in srgb, var(--list) 45%, transparent); }
|
||||
.trek-dash .col-row-btn .nm { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.trek-dash .col-row-btn .ct { font-size: 11.5px; color: var(--ink-3); font-variant-numeric: tabular-nums; flex-shrink: 0; }
|
||||
/* The kebab lives to the right of the count and is always visible (just dimmed)
|
||||
@@ -691,3 +702,39 @@
|
||||
.trek-dash .col-lrow.drop-before::before { top: -5px; }
|
||||
.trek-dash .col-lrow.drop-after::after { bottom: -5px; }
|
||||
.trek-dash .col-reorder-note { display: flex; align-items: center; gap: 6px; margin: 0 2px 8px; font-size: 12px; color: var(--ink-3); }
|
||||
|
||||
/* "All places" (PLC-07/08): a trip or list the place sits in, inside the place sheet. */
|
||||
.trek-dash .col-origin { display: flex; flex-direction: column; gap: 10px; width: 100%; padding: 10px 12px; border-radius: 14px; background: var(--surface-2); border: 1px solid var(--line); text-align: start; cursor: pointer; transition: background .12s, border-color .12s; }
|
||||
.trek-dash .col-origin:hover { background: var(--surface); border-color: var(--line-2); }
|
||||
.trek-dash .col-origin-chev { flex-shrink: 0; color: var(--ink-3); transition: transform .12s, color .12s; }
|
||||
.trek-dash .col-origin:hover .col-origin-chev { color: var(--ink); transform: translateX(2px); }
|
||||
[dir="rtl"] .trek-dash .col-origin-chev { transform: scaleX(-1); }
|
||||
.trek-dash .col-origin-head { display: flex; align-items: center; gap: 10px; min-width: 0; }
|
||||
.trek-dash .col-origin-ico { width: 34px; height: 34px; flex-shrink: 0; display: grid; place-items: center; border-radius: 9px; background: var(--surface); color: var(--ink-2); box-shadow: var(--sh-xs); }
|
||||
.trek-dash .col-origin-title { display: flex; flex-direction: column; min-width: 0; flex: 1 1 auto; }
|
||||
.trek-dash .col-origin-title .nm { font-size: 13.5px; font-weight: 600; color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.trek-dash .col-origin-title .sub { font-size: 12px; color: var(--ink-3); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-top: 1px; }
|
||||
.trek-dash .col-origin-tag { flex-shrink: 0; padding: 3px 9px; border-radius: 999px; font-size: 11px; font-weight: 600; color: var(--ink-3); background: var(--surface); border: 1px solid var(--line); }
|
||||
.trek-dash .col-origin-sub { font-size: 12px; color: var(--ink-3); }
|
||||
.trek-dash .col-origin-chips { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.trek-dash .col-origin-chip { display: inline-flex; align-items: center; gap: 5px; padding: 4px 10px; border-radius: 999px; font-size: 11.5px; font-weight: 600; color: var(--ink-2); background: var(--surface); border: 1px solid var(--line); }
|
||||
.trek-dash .col-origin-chip .dim { font-weight: 500; color: var(--ink-3); }
|
||||
.trek-dash .col-origin-notes { display: flex; flex-direction: column; gap: 4px; padding: 9px 12px; border-radius: 10px; background: var(--surface); }
|
||||
.trek-dash .col-origin-notes .txt { font-size: 13px; line-height: 1.5; color: var(--ink-2); white-space: pre-wrap; }
|
||||
/* The places of "All places" name where they come from at the row's end. */
|
||||
.trek-dash .col-lrow-origins { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 6px; min-width: 0; }
|
||||
.trek-dash .col-origin-pill { display: inline-flex; align-items: center; gap: 5px; max-width: 170px; padding: 4px 10px; border-radius: 999px; font-size: 11.5px; font-weight: 600; color: var(--ink-2); background: var(--surface-2); border: 1px solid var(--line); }
|
||||
.trek-dash .col-origin-pill span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.trek-dash .col-origin-pill.more { color: var(--ink-3); }
|
||||
|
||||
/* A saved place's tile holds its average vote on the corner; the category sits before the name. */
|
||||
.trek-dash .col-lrow-avatar { position: relative; display: inline-flex; width: 40px; height: 40px; }
|
||||
.trek-dash .col-lrow .li .t { display: flex; align-items: center; gap: 6px; }
|
||||
.trek-dash .col-lrow .li .t .nm { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.trek-dash .col-lrow-caticon { display: inline-flex; flex-shrink: 0; color: var(--cat, var(--accent)); }
|
||||
.trek-dash .col-lrow-caticon svg { display: block; }
|
||||
/* The average vote on the tile's other corner: an amber star, as on the map's pins, its figure inside. */
|
||||
.trek-dash .col-lrow-ratebadge { position: absolute; bottom: -7px; inset-inline-end: -8px; width: 30px; height: 30px; display: grid; place-items: center; }
|
||||
.trek-dash .col-lrow-ratebadge svg { position: absolute; inset: 0; width: 100%; height: 100%; fill: #fbbf24; stroke: var(--surface); stroke-width: 2; stroke-linejoin: round; }
|
||||
.trek-dash .col-lrow-ratebadge .n { position: relative; margin-top: 3px; font-size: 10.5px; font-weight: 800; line-height: 1; color: #111; font-variant-numeric: tabular-nums; }
|
||||
.trek-dash .col-lrow-ratebadge .n.frac { font-size: 8.5px; letter-spacing: -.02em; }
|
||||
|
||||
@@ -161,8 +161,6 @@ export interface Settings {
|
||||
map_booking_labels?: boolean
|
||||
/** The names of a trip's places stand beside their pins on the trip map (PLC-05); absent reads as off. */
|
||||
map_place_labels?: boolean
|
||||
/** Place names beside the trip map's markers (#2796). */
|
||||
map_place_labels?: boolean
|
||||
map_poi_pill_enabled?: boolean
|
||||
/** The trip map pans to where the assistant searches and suggests places; absent reads as on. */
|
||||
assistant_map_follow?: boolean
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// FE-UTIL-PLACESROUTES-001 to FE-UTIL-PLACESROUTES-002
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { placesPath, placesPathForLegacy } from './placesRoutes';
|
||||
|
||||
describe('placesRoutes', () => {
|
||||
it('FE-UTIL-PLACESROUTES-001: names the overview, the saved union and one list', () => {
|
||||
expect(placesPath('library')).toBe('/places');
|
||||
expect(placesPath(null)).toBe('/places');
|
||||
expect(placesPath('saved')).toBe('/places/saved');
|
||||
expect(placesPath(12)).toBe('/places/12');
|
||||
});
|
||||
|
||||
it('FE-UTIL-PLACESROUTES-002: sends an old Collections link on, query kept, and leaves other paths alone', () => {
|
||||
expect(placesPathForLegacy('/collections')).toBe('/places');
|
||||
expect(placesPathForLegacy('/collections/7', '?place=3')).toBe('/places/7?place=3');
|
||||
expect(placesPathForLegacy('/collections/7/')).toBe('/places/7');
|
||||
expect(placesPathForLegacy('/trips/7')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* Where Places lives (PLC-07). The old Collections area moved under /places: the
|
||||
* overview of every place from the trips and lists is /places, the union of the
|
||||
* saved lists /places/saved, and one list /places/:id. The old /collections links
|
||||
* (bookmarks, notifications, the assistant's cards) are sent on by the router.
|
||||
*/
|
||||
export const PLACES_ROOT = '/places';
|
||||
export const PLACES_SAVED = '/places/saved';
|
||||
|
||||
/** The path of one list, of the saved union (`'saved'`) or of the overview (`'library'`). */
|
||||
export function placesPath(target: number | 'saved' | 'library' | null | undefined): string {
|
||||
if (typeof target === 'number') return `${PLACES_ROOT}/${target}`;
|
||||
return target === 'saved' ? PLACES_SAVED : PLACES_ROOT;
|
||||
}
|
||||
|
||||
/** The new home of an old /collections path, query string kept. Null when it is not one. */
|
||||
export function placesPathForLegacy(pathname: string, search = ''): string | null {
|
||||
const match = /^\/collections(?:\/(\d+))?\/?$/.exec(pathname);
|
||||
if (!match) return null;
|
||||
return `${match[1] ? placesPath(Number(match[1])) : PLACES_ROOT}${search}`;
|
||||
}
|
||||
@@ -49,7 +49,7 @@ export function isInstalledApp(): boolean {
|
||||
|
||||
/** Routes that are a place to come back to; the root, auth pages and settings are not. */
|
||||
function resumable(path: string): boolean {
|
||||
return /^\/(trips\/\d+|journey(\/\d+)?|collections|vacay|atlas|files)(\/|\?|$)/.test(path)
|
||||
return /^\/(trips\/\d+|journey(\/\d+)?|collections|places|vacay|atlas|files)(\/|\?|$)/.test(path)
|
||||
}
|
||||
|
||||
const tripIdOf = (path: string): string | null => /^\/trips\/(\d+)/.exec(path)?.[1] ?? null
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
import type {
|
||||
PlacesLibraryDetail,
|
||||
PlacesLibraryDetailResponse,
|
||||
PlacesLibraryEntry,
|
||||
PlacesLibraryInfo,
|
||||
PlacesLibraryListDetail,
|
||||
PlacesLibraryListOrigin,
|
||||
PlacesLibraryPageResponse,
|
||||
PlacesLibraryTripDetail,
|
||||
PlacesLibraryTripOrigin,
|
||||
} from '@trek/shared';
|
||||
import { vi } from 'vitest';
|
||||
|
||||
import type { usePlacesLibrary } from '../../src/components/Collections/usePlacesLibrary';
|
||||
|
||||
/*
|
||||
* Builders for "All places" (PLC-07, PLC-08): an entry with its origins, a page of
|
||||
* them, and what each origin keeps of a place. One trip place 42 in "Rome 2026"
|
||||
* and one saved place 900 in "Favourites", both the Colosseum, unless told otherwise.
|
||||
*/
|
||||
|
||||
export function tripOrigin(over: Partial<PlacesLibraryTripOrigin> = {}): PlacesLibraryTripOrigin {
|
||||
return {
|
||||
kind: 'trip',
|
||||
trip_id: 5,
|
||||
trip_title: 'Rome 2026',
|
||||
trip_start: null,
|
||||
trip_end: null,
|
||||
place_id: 42,
|
||||
can_edit: true,
|
||||
read_only: false,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
export function listOrigin(over: Partial<PlacesLibraryListOrigin> = {}): PlacesLibraryListOrigin {
|
||||
return {
|
||||
kind: 'list',
|
||||
collection_id: 9,
|
||||
collection_name: 'Favourites',
|
||||
collection_place_id: 900,
|
||||
status: 'want',
|
||||
can_edit: true,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
export function libraryInfo(over: Partial<PlacesLibraryInfo> = {}): PlacesLibraryInfo {
|
||||
return {
|
||||
name: 'Colosseum',
|
||||
address: 'Piazza del Colosseo',
|
||||
lat: 41.89,
|
||||
lng: 12.49,
|
||||
description: null,
|
||||
website: null,
|
||||
phone: null,
|
||||
image_url: null,
|
||||
category: null,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
export function tripDetail(over: Partial<PlacesLibraryTripDetail> = {}): PlacesLibraryTripDetail {
|
||||
return {
|
||||
kind: 'trip',
|
||||
place_id: 42,
|
||||
info: libraryInfo(),
|
||||
notes: null,
|
||||
rating: { average: null, count: 0, mine: null },
|
||||
days: [],
|
||||
has_accommodation: false,
|
||||
has_reservation: false,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
export function listDetail(over: Partial<PlacesLibraryListDetail> = {}): PlacesLibraryListDetail {
|
||||
return {
|
||||
kind: 'list',
|
||||
collection_place_id: 900,
|
||||
info: libraryInfo(),
|
||||
notes: null,
|
||||
labels: [],
|
||||
rating: { average: null, count: 0, mine: null },
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
export function libraryEntry(over: Partial<PlacesLibraryEntry> = {}): PlacesLibraryEntry {
|
||||
return {
|
||||
key: 'trip:42',
|
||||
name: 'Colosseum',
|
||||
address: 'Piazza del Colosseo',
|
||||
lat: 41.89,
|
||||
lng: 12.49,
|
||||
category: null,
|
||||
image_url: null,
|
||||
updated_at: null,
|
||||
origins: [tripOrigin()],
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
export function libraryPage(
|
||||
entries: PlacesLibraryEntry[],
|
||||
over: Partial<PlacesLibraryPageResponse> = {}
|
||||
): PlacesLibraryPageResponse {
|
||||
return {
|
||||
entries,
|
||||
total: entries.length,
|
||||
counts: { all: entries.length, trip: entries.length, list: 0 },
|
||||
next_cursor: null,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
/** An entry with one detail per origin, in the order of its origins. */
|
||||
export function libraryDetail(entry: PlacesLibraryEntry, details: PlacesLibraryDetail[]): PlacesLibraryDetailResponse {
|
||||
return { entry, details };
|
||||
}
|
||||
|
||||
/** The Colosseum in the trip and in a list, with what both keep of it. */
|
||||
export function bothOrigins(over: Partial<PlacesLibraryEntry> = {}): PlacesLibraryDetailResponse {
|
||||
const entry = libraryEntry({ origins: [tripOrigin(), listOrigin()], ...over });
|
||||
return libraryDetail(entry, [tripDetail(), listDetail()]);
|
||||
}
|
||||
|
||||
/** What usePlacesLibrary hands a view, for the view tests that mock the hook. */
|
||||
export type PlacesLibraryState = ReturnType<typeof usePlacesLibrary>;
|
||||
|
||||
/** An idle "All places" with nothing loaded, every setter and action a mock. */
|
||||
export function libraryState(over: Partial<PlacesLibraryState> = {}): PlacesLibraryState {
|
||||
return {
|
||||
search: '',
|
||||
setSearch: vi.fn(),
|
||||
kind: 'all',
|
||||
setKind: vi.fn(),
|
||||
categoryId: 'all',
|
||||
setCategoryId: vi.fn(),
|
||||
sort: 'name',
|
||||
setSort: vi.fn(),
|
||||
status: 'all',
|
||||
setStatus: vi.fn(),
|
||||
filtered: false,
|
||||
resetFilters: vi.fn(),
|
||||
entries: [],
|
||||
mappable: [],
|
||||
total: 0,
|
||||
counts: { all: 0, trip: 0, list: 0 },
|
||||
hasMore: false,
|
||||
loading: false,
|
||||
loadingMore: false,
|
||||
loadMore: vi.fn(() => Promise.resolve()),
|
||||
error: null,
|
||||
offline: false,
|
||||
reload: vi.fn(),
|
||||
selectedKey: null,
|
||||
open: vi.fn(),
|
||||
show: vi.fn(),
|
||||
close: vi.fn(),
|
||||
detail: null,
|
||||
detailLoading: false,
|
||||
cover: null,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
/** Three places: two in trips with a position, one saved without. */
|
||||
export function threeEntries(): PlacesLibraryEntry[] {
|
||||
return [
|
||||
libraryEntry({
|
||||
key: 'trip:1',
|
||||
name: 'Pantheon',
|
||||
address: 'Piazza della Rotonda',
|
||||
origins: [tripOrigin({ place_id: 1 })],
|
||||
}),
|
||||
libraryEntry({
|
||||
key: 'trip:2',
|
||||
name: 'Trevi Fountain',
|
||||
address: null,
|
||||
origins: [tripOrigin({ place_id: 2 }), listOrigin({ collection_place_id: 20 })],
|
||||
}),
|
||||
libraryEntry({
|
||||
key: 'list:30',
|
||||
name: 'Secret garden',
|
||||
address: null,
|
||||
lat: null,
|
||||
lng: null,
|
||||
origins: [listOrigin({ collection_place_id: 30, collection_name: 'Wishlist' })],
|
||||
}),
|
||||
];
|
||||
}
|
||||
@@ -174,7 +174,7 @@ describe('MBottomNav', () => {
|
||||
it.each([
|
||||
['/journey', 'New Journey', '/journey?create=1'],
|
||||
['/journey/4', 'Add Entry', '/journey/4?create=entry'],
|
||||
['/collections', 'Add a place', '/collections?create=place'],
|
||||
['/places', 'Add a place', '/places?create=place'],
|
||||
['/trips/7', 'Add Place/Activity', '/trips/7?create=place'],
|
||||
['/dashboard', 'New Trip', '/dashboard?create=1'],
|
||||
['/atlas', 'Search a country...', '/atlas?search=1'],
|
||||
@@ -216,7 +216,7 @@ describe('MBottomNav', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'More' }));
|
||||
fireEvent.click(screen.getByRole('button', { name: /Collections/ }));
|
||||
|
||||
expect(at()).toBe('/collections');
|
||||
expect(at()).toBe('/places');
|
||||
});
|
||||
|
||||
it('FE-MOB-NAV-018: vacay owns its centre slot, so the dock offers no create action (#1811)', () => {
|
||||
|
||||
@@ -207,7 +207,7 @@ describe('MCollAddSheet', () => {
|
||||
await user.click(screen.getByRole('button', { name: /collections.status.visited/ }))
|
||||
expect(screen.getByRole('button', { name: /collections.status.visited/ })).toHaveAttribute('aria-pressed', 'true')
|
||||
|
||||
await user.click(screen.getByText('collections.noCategory'))
|
||||
await user.click(screen.getByRole('button', { name: 'collections.category: collections.noCategory' }))
|
||||
await user.click(screen.getByText('Museum', { selector: 'span' }))
|
||||
await user.click(screen.getByRole('button', { name: /common.add/ }))
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import MCollCategoryPicker from '../../../../src/mobile/screens/collections/MCol
|
||||
import type { Category } from '../../../../src/types'
|
||||
import { useTranslation } from '../../../../src/i18n'
|
||||
|
||||
// FE-MOB-CCATP-001 to FE-MOB-CCATP-010
|
||||
// FE-MOB-CCATP-001 to FE-MOB-CCATP-011
|
||||
|
||||
const CATEGORIES = [
|
||||
// In CATEGORY_SPEC — takes the design colour/icon, not the DB row.
|
||||
@@ -101,4 +101,19 @@ describe('MCollCategoryPicker', () => {
|
||||
expect(options).toHaveLength(1)
|
||||
expect(options[0]).toHaveTextContent('No category')
|
||||
})
|
||||
|
||||
it('FE-MOB-CCATP-011: as a tile it sits in front of the name field and opens the same list', () => {
|
||||
const onChange = vi.fn<(id: number | null) => void>()
|
||||
render(
|
||||
<Harness variant="tile" categories={CATEGORIES} value={2} onChange={onChange}>
|
||||
<input aria-label="Name" />
|
||||
</Harness>,
|
||||
)
|
||||
expect(screen.getByRole('textbox', { name: 'Name' })).toBeInTheDocument()
|
||||
const tile = screen.getByRole('button', { name: /Winery/ })
|
||||
expect(tile).toHaveAttribute('aria-expanded', 'false')
|
||||
fireEvent.click(tile)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Restaurant' }))
|
||||
expect(onChange).toHaveBeenCalledWith(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
// FE-MOB-COLLFILTERKIT-001 to FE-MOB-COLLFILTERKIT-004
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { DropRow, EmptyNote } from '../../../../src/mobile/screens/collections/MCollFilterKit';
|
||||
import { render, screen } from '../../../helpers/render';
|
||||
|
||||
describe('MCollFilterKit', () => {
|
||||
it('FE-MOB-COLLFILTERKIT-001: a dropdown row shows its icon, name and count and reports a tap', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onPick = vi.fn();
|
||||
render(<DropRow icon={<span data-testid="row-icon" />} label="Trips" count={6} on={false} onPick={onPick} />);
|
||||
const row = screen.getByRole('button', { name: /^Trips/ });
|
||||
expect(row).toHaveTextContent('Trips6');
|
||||
expect(screen.getByTestId('row-icon')).toBeInTheDocument();
|
||||
expect(row).not.toHaveClass('bg-m-ic');
|
||||
await user.click(row);
|
||||
expect(onPick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-MOB-COLLFILTERKIT-002: the chosen row is marked, and a row without a count shows none', () => {
|
||||
render(<DropRow icon={null} label="Idea" on onPick={vi.fn()} />);
|
||||
const row = screen.getByRole('button', { name: 'Idea' });
|
||||
expect(row).toHaveClass('bg-m-ic');
|
||||
expect(row).toHaveTextContent(/^Idea$/);
|
||||
});
|
||||
|
||||
it('FE-MOB-COLLFILTERKIT-003: the empty note with a scene shows the mascot above its title', () => {
|
||||
const { container } = render(<EmptyNote scene="search" title="No matches" />);
|
||||
expect(screen.getByText('No matches')).toBeInTheDocument();
|
||||
expect(container.querySelector('svg')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('FE-MOB-COLLFILTERKIT-004: without a scene the empty note shows its icon instead', () => {
|
||||
const { container } = render(<EmptyNote icon={<span data-testid="note-icon" />} title="Nothing here" />);
|
||||
expect(screen.getByTestId('note-icon')).toBeInTheDocument();
|
||||
expect(screen.getByText('Nothing here')).toBeInTheDocument();
|
||||
expect(container.querySelector('svg')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -219,7 +219,7 @@ describe('MCollections', () => {
|
||||
|
||||
it('FE-MOB-COLSCR-002: with no lists at all the dock + button starts the first one; the screen has no button of its own', async () => {
|
||||
mocks.coll = makeHook({ collections: [], ownedLists: [], activeCollection: null, activeId: null, canShare: false })
|
||||
render(<MCollections />, { initialEntries: ['/collections?create=place'] })
|
||||
render(<MCollections />, { initialEntries: ['/places?create=place'] })
|
||||
|
||||
expect(screen.getByText('collections.empty.firstTitle')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: /^collections.newList$/ })).not.toBeInTheDocument()
|
||||
@@ -628,7 +628,7 @@ describe('MCollections', () => {
|
||||
})
|
||||
|
||||
it('FE-MOB-COLSCR-025: the ?create= hand-off from the bottom nav opens the add sheet once', async () => {
|
||||
render(<MCollections />, { initialEntries: ['/collections?create=place'] })
|
||||
render(<MCollections />, { initialEntries: ['/places?create=place'] })
|
||||
|
||||
await waitFor(() => expect(fn('setShowAddPlace')).toHaveBeenCalledWith(true))
|
||||
// The param is consumed so a re-render does not re-open the sheet.
|
||||
@@ -637,21 +637,21 @@ describe('MCollections', () => {
|
||||
|
||||
it('FE-MOB-COLSCR-026: the union hand-off opens the sheet when at least one list can take the place', async () => {
|
||||
mocks.coll = makeHook({ isAllSaved: true, activeId: ALL_SAVED, activeCollection: null, canShare: false, canEdit: false })
|
||||
render(<MCollections />, { initialEntries: ['/collections?create=1'] })
|
||||
render(<MCollections />, { initialEntries: ['/places?create=1'] })
|
||||
|
||||
await waitFor(() => expect(fn('setShowAddPlace')).toHaveBeenCalledWith(true))
|
||||
})
|
||||
|
||||
it('FE-MOB-COLSCR-027: without an editable target the hand-off is ignored', async () => {
|
||||
mocks.coll = makeHook({ activeId: null, activeCollection: null, canEdit: false, canShare: false, ownedLists: [] })
|
||||
render(<MCollections />, { initialEntries: ['/collections?create=place'] })
|
||||
render(<MCollections />, { initialEntries: ['/places?create=place'] })
|
||||
|
||||
await waitFor(() => expect(screen.getByText('collections.title')).toBeInTheDocument())
|
||||
expect(fn('setShowAddPlace')).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-MOB-COLSCR-028: an unrelated query param leaves the sheet closed', () => {
|
||||
render(<MCollections />, { initialEntries: ['/collections?tab=map'] })
|
||||
render(<MCollections />, { initialEntries: ['/places?tab=map'] })
|
||||
expect(fn('setShowAddPlace')).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
// FE-MOB-LIBPLACESHEET-001 to FE-MOB-LIBPLACESHEET-012
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import type { PlacesLibraryDetailResponse } from '@trek/shared';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { type NavigationTarget, openNavigationTarget } from '../../../../src/components/Planner/placeNavigation';
|
||||
import { useTranslation } from '../../../../src/i18n';
|
||||
import MLibraryPlaceSheet from '../../../../src/mobile/screens/collections/MLibraryPlaceSheet';
|
||||
import {
|
||||
bothOrigins,
|
||||
libraryDetail,
|
||||
libraryEntry,
|
||||
libraryInfo,
|
||||
listDetail,
|
||||
listOrigin,
|
||||
tripDetail,
|
||||
tripOrigin,
|
||||
} from '../../../helpers/placesLibrary';
|
||||
import { render, screen, within } from '../../../helpers/render';
|
||||
import { resetAllStores } from '../../../helpers/store';
|
||||
|
||||
const nav = vi.hoisted(() => ({ targets: [] as NavigationTarget[] }));
|
||||
|
||||
vi.mock('../../../../src/components/Planner/placeNavigation', () => ({
|
||||
getNavigationTargets: () => nav.targets,
|
||||
navigationTargetLabel: (target: NavigationTarget) => target.label,
|
||||
openNavigationTarget: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../../src/components/shared/NavigationMenu', () => ({
|
||||
NavigationMenu: ({
|
||||
targets,
|
||||
onClose,
|
||||
title,
|
||||
}: {
|
||||
targets: NavigationTarget[];
|
||||
onClose: () => void;
|
||||
title?: string;
|
||||
}) => (
|
||||
<div role="menu" aria-label={title}>
|
||||
{targets.map((target) => (
|
||||
<span key={target.id}>{target.label}</span>
|
||||
))}
|
||||
<button type="button" onClick={onClose}>
|
||||
menu-close
|
||||
</button>
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
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<ComponentProps<typeof MLibraryPlaceSheet>, 't'>;
|
||||
|
||||
function Harness(props: Props) {
|
||||
const { t } = useTranslation();
|
||||
return <MLibraryPlaceSheet {...props} t={t} />;
|
||||
}
|
||||
|
||||
/** 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({ status: 'visited' })];
|
||||
data.details = [
|
||||
tripDetail({
|
||||
info: libraryInfo({ name: 'Colosseo', description: ' ' }),
|
||||
notes: 'Book the underground tour',
|
||||
days: [
|
||||
{ day_id: 1, day_number: 2, date: null, title: null, time: null, end_time: null },
|
||||
{ day_id: 2, day_number: 4, date: null, title: null, time: null, end_time: null },
|
||||
],
|
||||
has_accommodation: true,
|
||||
has_reservation: true,
|
||||
}),
|
||||
listDetail({
|
||||
info: libraryInfo({ name: 'Il Colosseo', description: 'Ancient arena' }),
|
||||
labels: [{ id: 1, name: 'Must see', color: null }],
|
||||
rating: { average: 4, count: 1, mine: 4 },
|
||||
notes: 'Go at sunset',
|
||||
}),
|
||||
];
|
||||
return data;
|
||||
}
|
||||
|
||||
function setup(over: Partial<Props> = {}) {
|
||||
const props: Props = {
|
||||
open: true,
|
||||
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(<Harness {...props} />);
|
||||
return { ...view, props };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
nav.targets = [];
|
||||
vi.mocked(openNavigationTarget).mockClear();
|
||||
});
|
||||
|
||||
describe('MLibraryPlaceSheet: the sheet', () => {
|
||||
it('FE-MOB-LIBPLACESHEET-001: closed it renders nothing', () => {
|
||||
setup({ open: false });
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-LIBPLACESHEET-002: while it loads it shows a spinner and nothing to do yet', () => {
|
||||
setup({ data: null, loading: true });
|
||||
const dialog = screen.getByRole('dialog', { name: 'All places' });
|
||||
expect(dialog.querySelector('.animate-spin')).not.toBeNull();
|
||||
expect(within(dialog).getAllByRole('button')).toHaveLength(1);
|
||||
expect(within(dialog).queryByRole('heading')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-LIBPLACESHEET-003: the head carries the cover, the category and the name, the body the address and description', () => {
|
||||
setup({ cover: '/uploads/cover.jpg' });
|
||||
const dialog = screen.getByRole('dialog', { name: 'Colosseum' });
|
||||
expect(within(dialog).getByRole('heading', { name: 'Colosseum' })).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('Restaurant')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('Piazza del Colosseo')).toBeInTheDocument();
|
||||
expect(within(dialog).getByText('Ancient arena')).toBeInTheDocument();
|
||||
expect(dialog.querySelector('img')).toHaveAttribute('src', '/uploads/cover.jpg');
|
||||
expect(within(dialog).queryByText('No coordinates, so not on the map')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-LIBPLACESHEET-004: without a cover, an address or coordinates it says why it is not on the map', () => {
|
||||
const entry = libraryEntry({ lat: 41.89, lng: null, address: null });
|
||||
setup({ data: libraryDetail(entry, [tripDetail()]) });
|
||||
const dialog = screen.getByRole('dialog', { name: 'Colosseum' });
|
||||
expect(dialog.querySelector('img')).toBeNull();
|
||||
expect(within(dialog).getByText('No coordinates, so not on the map')).toBeInTheDocument();
|
||||
expect(within(dialog).queryByText('Piazza del Colosseo')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-LIBPLACESHEET-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).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('MLibraryPlaceSheet: where the place sits', () => {
|
||||
it('FE-MOB-LIBPLACESHEET-006: a trip shows its days, 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 +1')).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-MOB-LIBPLACESHEET-007: a list shows its status, its name there, labels, votes and notes', 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('Visited')).toBeInTheDocument();
|
||||
expect(within(card).getByText('Called Il Colosseo here')).toBeInTheDocument();
|
||||
expect(within(card).getByText('Must see')).toBeInTheDocument();
|
||||
expect(within(card).getByText('4.0 from 1 vote')).toBeInTheDocument();
|
||||
expect(within(card).getByText('Go at sunset')).toBeInTheDocument();
|
||||
await user.click(card);
|
||||
expect(props.onOpenList).toHaveBeenCalledWith(9, 900);
|
||||
});
|
||||
|
||||
it('FE-MOB-LIBPLACESHEET-008: a plain trip place shows its trip dates and no chips', () => {
|
||||
const entry = libraryEntry({ origins: [tripOrigin({ trip_start: '2026-12-01', trip_end: null })] });
|
||||
setup({ data: libraryDetail(entry, [tripDetail()]) });
|
||||
const card = screen.getByRole('button', { name: 'Open in the trip: Rome 2026' });
|
||||
expect(card).toHaveTextContent(/Dec/);
|
||||
expect(within(card).queryByText('Stay')).not.toBeInTheDocument();
|
||||
expect(within(card).queryByText('Read only')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('IN YOUR LISTS')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-LIBPLACESHEET-009: an origin the server sent no detail for is left out', () => {
|
||||
const data = bothOrigins();
|
||||
data.details = [tripDetail()];
|
||||
setup({ data });
|
||||
expect(screen.queryByRole('button', { name: 'Open in the list: Favourites' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /Copy to trip/ })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('MLibraryPlaceSheet: what to do with it', () => {
|
||||
it('FE-MOB-LIBPLACESHEET-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-MOB-LIBPLACESHEET-011: one map app opens straight away, none hides the button', async () => {
|
||||
const user = userEvent.setup();
|
||||
nav.targets = [GOOGLE];
|
||||
const entry = libraryEntry({ key: 'list:900', origins: [listOrigin()] });
|
||||
const { unmount } = setup({ data: libraryDetail(entry, [listDetail()]) });
|
||||
expect(screen.queryByRole('button', { name: /Save to Collection/ })).not.toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: /Google Maps/ }));
|
||||
expect(openNavigationTarget).toHaveBeenCalledWith(GOOGLE);
|
||||
unmount();
|
||||
|
||||
nav.targets = [];
|
||||
setup();
|
||||
expect(screen.queryByRole('button', { name: /Navigation|Google Maps/ })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-LIBPLACESHEET-012: several map apps open a titled menu that closes again', 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', { name: 'Navigation' });
|
||||
expect(within(menu).getByText('OpenStreetMap')).toBeInTheDocument();
|
||||
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();
|
||||
expect(openNavigationTarget).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,339 @@
|
||||
// FE-MOB-PLACESLIB-001 to FE-MOB-PLACESLIB-018
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type CollectionMap from '../../../../src/components/Collections/CollectionMap';
|
||||
import { useTranslation } from '../../../../src/i18n';
|
||||
import type MCollTripPickerSheet from '../../../../src/mobile/screens/collections/MCollTripPickerSheet';
|
||||
import type MLibraryPlaceSheet from '../../../../src/mobile/screens/collections/MLibraryPlaceSheet';
|
||||
import MPlacesLibrary from '../../../../src/mobile/screens/collections/MPlacesLibrary';
|
||||
import { useCollectionStore } from '../../../../src/store/collectionStore';
|
||||
import { useSaveToCollectionStore } from '../../../../src/store/saveToCollectionStore';
|
||||
import type { Category } from '../../../../src/types';
|
||||
import {
|
||||
libraryDetail,
|
||||
libraryEntry,
|
||||
libraryInfo,
|
||||
libraryState,
|
||||
type PlacesLibraryState,
|
||||
threeEntries,
|
||||
tripDetail,
|
||||
tripOrigin,
|
||||
} from '../../../helpers/placesLibrary';
|
||||
import { act, fireEvent, render, screen } from '../../../helpers/render';
|
||||
import { resetAllStores } from '../../../helpers/store';
|
||||
|
||||
type MapProps = ComponentProps<typeof CollectionMap>;
|
||||
type SheetProps = ComponentProps<typeof MLibraryPlaceSheet>;
|
||||
type PickerProps = ComponentProps<typeof MCollTripPickerSheet>;
|
||||
|
||||
const seen = vi.hoisted(() => ({
|
||||
lib: null as PlacesLibraryState | null,
|
||||
map: null as MapProps | null,
|
||||
sheet: null as SheetProps | null,
|
||||
picker: null as PickerProps | null,
|
||||
}));
|
||||
|
||||
vi.mock('../../../../src/components/Collections/usePlacesLibrary', () => ({
|
||||
usePlacesLibrary: () => seen.lib,
|
||||
}));
|
||||
|
||||
// Keep the map stack out of jsdom; what the screen hands it is the contract.
|
||||
vi.mock('../../../../src/components/Collections/CollectionMap', () => ({
|
||||
default: (props: MapProps) => {
|
||||
seen.map = props;
|
||||
return <div data-testid="map">{`markers:${props.places.length}`}</div>;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../../src/mobile/screens/collections/MLibraryPlaceSheet', () => ({
|
||||
default: (props: SheetProps) => {
|
||||
seen.sheet = props;
|
||||
return props.open ? <div data-testid="place-sheet" /> : null;
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../../src/mobile/screens/collections/MCollTripPickerSheet', () => ({
|
||||
default: (props: PickerProps) => {
|
||||
seen.picker = props;
|
||||
return props.open ? <div data-testid="trip-picker" /> : null;
|
||||
},
|
||||
}));
|
||||
|
||||
const CATEGORIES = [
|
||||
{ id: 3, name: 'Restaurant', color: '#E8843D', icon: 'Utensils' },
|
||||
{ id: 5, name: 'Museum', color: '#9B5DE5', icon: 'Landmark' },
|
||||
] as unknown as Category[];
|
||||
|
||||
type Props = Omit<ComponentProps<typeof MPlacesLibrary>, 't'>;
|
||||
|
||||
function Harness(props: Props) {
|
||||
const { t } = useTranslation();
|
||||
return <MPlacesLibrary {...props} t={t} />;
|
||||
}
|
||||
|
||||
function captured<T>(value: T | null): T {
|
||||
if (value == null) throw new Error('not rendered');
|
||||
return value;
|
||||
}
|
||||
|
||||
const openSave = vi.fn<(target: Parameters<ReturnType<typeof useSaveToCollectionStore.getState>['open']>[0]) => void>();
|
||||
const copyToTrip = vi.fn<ReturnType<typeof useCollectionStore.getState>['copyToTrip']>();
|
||||
|
||||
function setup(lib: Partial<PlacesLibraryState> = {}, over: Partial<Props> = {}) {
|
||||
seen.lib = libraryState(lib);
|
||||
const props: Props = {
|
||||
categories: CATEGORIES,
|
||||
language: 'en',
|
||||
dark: false,
|
||||
view: 'list',
|
||||
onView: vi.fn(),
|
||||
navigate: vi.fn(),
|
||||
...over,
|
||||
};
|
||||
const view = render(<Harness {...props} />);
|
||||
return { ...view, props, lib: captured(seen.lib) };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores();
|
||||
seen.lib = null;
|
||||
seen.map = null;
|
||||
seen.sheet = null;
|
||||
seen.picker = null;
|
||||
openSave.mockReset();
|
||||
copyToTrip.mockReset();
|
||||
copyToTrip.mockResolvedValue({ copied: 1, skipped: [] });
|
||||
useSaveToCollectionStore.setState({ open: openSave });
|
||||
useCollectionStore.setState({ copyToTrip });
|
||||
});
|
||||
|
||||
describe('MPlacesLibrary: the head', () => {
|
||||
it('FE-MOB-PLACESLIB-001: the list or map switch shows which one is on and asks for the other', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { props } = setup();
|
||||
expect(screen.getByRole('button', { name: 'List' })).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(screen.getByRole('button', { name: 'Map' })).toHaveAttribute('aria-pressed', 'false');
|
||||
await user.click(screen.getByRole('button', { name: 'Map' }));
|
||||
expect(props.onView).toHaveBeenCalledWith('map');
|
||||
});
|
||||
|
||||
it('FE-MOB-PLACESLIB-002: the search shows and changes the search', () => {
|
||||
const { lib } = setup({ search: 'pan' });
|
||||
const input = screen.getByRole('textbox', { name: 'Search all places' });
|
||||
expect(input).toHaveValue('pan');
|
||||
fireEvent.change(input, { target: { value: 'pant' } });
|
||||
expect(lib.setSearch).toHaveBeenCalledWith('pant');
|
||||
});
|
||||
|
||||
it('FE-MOB-PLACESLIB-003: where from opens with its counts and picks a kind', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { lib } = setup({ counts: { all: 9, trip: 6, list: 4 } });
|
||||
const [kindChip] = screen.getAllByRole('button', { name: 'All' });
|
||||
await user.click(kindChip);
|
||||
expect(kindChip).toHaveAttribute('aria-expanded', 'true');
|
||||
expect(screen.getByRole('button', { name: /^Trips/ })).toHaveTextContent('Trips6');
|
||||
expect(screen.getByRole('button', { name: /^Lists/ })).toHaveTextContent('Lists4');
|
||||
await user.click(screen.getByRole('button', { name: /^Trips/ }));
|
||||
expect(lib.setKind).toHaveBeenCalledWith('trip');
|
||||
expect(screen.queryByRole('button', { name: /^Lists/ })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-PLACESLIB-004: a chosen kind names itself on its chip', () => {
|
||||
setup({ kind: 'list' });
|
||||
expect(screen.getByRole('button', { name: 'Lists' })).toHaveAttribute('aria-expanded', 'false');
|
||||
});
|
||||
|
||||
it('FE-MOB-PLACESLIB-005: status lists every status and picks one or all', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { lib } = setup({ status: 'visited' });
|
||||
const statusChip = screen.getByRole('button', { name: 'Visited' });
|
||||
await user.click(statusChip);
|
||||
await user.click(screen.getByRole('button', { name: 'Want to go' }));
|
||||
expect(lib.setStatus).toHaveBeenLastCalledWith('want');
|
||||
|
||||
await user.click(statusChip);
|
||||
expect(screen.getByRole('button', { name: 'Want to revisit' })).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Idea' }));
|
||||
expect(lib.setStatus).toHaveBeenLastCalledWith('idea');
|
||||
|
||||
await user.click(statusChip);
|
||||
const allRows = screen.getAllByRole('button', { name: 'All' });
|
||||
await user.click(allRows[allRows.length - 1]);
|
||||
expect(lib.setStatus).toHaveBeenLastCalledWith('all');
|
||||
});
|
||||
|
||||
it('FE-MOB-PLACESLIB-006: category names the current one and picks another or all', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { lib } = setup({ categoryId: 3 });
|
||||
const chip = screen.getByRole('button', { name: 'Category: Restaurant' });
|
||||
await user.click(chip);
|
||||
await user.click(screen.getByRole('button', { name: 'Museum' }));
|
||||
expect(lib.setCategoryId).toHaveBeenLastCalledWith(5);
|
||||
|
||||
await user.click(chip);
|
||||
const allRows = screen.getAllByRole('button', { name: 'All' });
|
||||
await user.click(allRows[allRows.length - 1]);
|
||||
expect(lib.setCategoryId).toHaveBeenLastCalledWith('all');
|
||||
});
|
||||
|
||||
it('FE-MOB-PLACESLIB-007: without categories there is no category chip', () => {
|
||||
setup({}, { categories: [] });
|
||||
expect(screen.queryByRole('button', { name: /^Category:/ })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-PLACESLIB-008: the order chip picks name or last changed', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { lib } = setup();
|
||||
await user.click(screen.getByRole('button', { name: 'Sort' }));
|
||||
expect(screen.getByRole('button', { name: 'Name (A–Z)' })).toBeInTheDocument();
|
||||
await user.click(screen.getByRole('button', { name: 'Last changed' }));
|
||||
expect(lib.setSort).toHaveBeenCalledWith('updated');
|
||||
});
|
||||
|
||||
it('FE-MOB-PLACESLIB-009: a tap beside the open dropdown or on its chip again closes it', async () => {
|
||||
const user = userEvent.setup();
|
||||
setup();
|
||||
const sortChip = screen.getByRole('button', { name: 'Sort' });
|
||||
await user.click(sortChip);
|
||||
await user.click(screen.getByRole('button', { name: 'Close' }));
|
||||
expect(screen.queryByRole('button', { name: 'Last changed' })).not.toBeInTheDocument();
|
||||
|
||||
await user.click(sortChip);
|
||||
expect(sortChip).toHaveAttribute('aria-expanded', 'true');
|
||||
fireEvent.click(sortChip);
|
||||
expect(screen.queryByRole('button', { name: 'Last changed' })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('MPlacesLibrary: the places', () => {
|
||||
it('FE-MOB-PLACESLIB-010: a card per place names it, its address and its first origin, the rest counted', () => {
|
||||
setup({ entries: threeEntries() });
|
||||
const pantheon = screen.getByRole('button', { name: /Pantheon/ });
|
||||
expect(pantheon).toHaveTextContent('Piazza della Rotonda');
|
||||
expect(pantheon).toHaveTextContent('Rome 2026');
|
||||
const trevi = screen.getByRole('button', { name: /Trevi Fountain/ });
|
||||
expect(trevi).toHaveTextContent('Rome 2026+1');
|
||||
expect(screen.getByRole('button', { name: /Secret garden/ })).toHaveTextContent('Wishlist');
|
||||
});
|
||||
|
||||
it('FE-MOB-PLACESLIB-011: a card opens its place', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { lib } = setup({ entries: threeEntries() });
|
||||
await user.click(screen.getByRole('button', { name: /Secret garden/ }));
|
||||
expect(lib.show).toHaveBeenCalledWith('list:30');
|
||||
});
|
||||
|
||||
it('FE-MOB-PLACESLIB-012: "more" counts what is left and loads it, and waits while it loads', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { lib, unmount } = setup({ entries: threeEntries(), total: 4, hasMore: true });
|
||||
await user.click(screen.getByRole('button', { name: 'Show 1 more' }));
|
||||
expect(lib.loadMore).toHaveBeenCalledTimes(1);
|
||||
unmount();
|
||||
|
||||
setup({ entries: threeEntries(), total: 4, hasMore: true, loadingMore: true });
|
||||
expect(screen.getByRole('button', { name: 'Show 1 more' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('FE-MOB-PLACESLIB-013: offline, failed, loading and empty each say so', () => {
|
||||
const offline = setup({ offline: true });
|
||||
expect(screen.getByText('All places needs a connection.')).toBeInTheDocument();
|
||||
offline.unmount();
|
||||
|
||||
const failed = setup({ error: 'Library is down' });
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Library is down');
|
||||
failed.unmount();
|
||||
|
||||
const loading = setup({ loading: true });
|
||||
expect(loading.container.querySelector('.animate-spin')).not.toBeNull();
|
||||
loading.unmount();
|
||||
|
||||
const empty = setup();
|
||||
expect(screen.getByText('No places yet')).toBeInTheDocument();
|
||||
empty.unmount();
|
||||
|
||||
setup({ filtered: true });
|
||||
expect(screen.getByText('No matches')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-MOB-PLACESLIB-014: the map shows the places with a position and a pin opens its place', () => {
|
||||
const { lib } = setup({ entries: threeEntries() }, { view: 'map', dark: true });
|
||||
expect(screen.getByTestId('map')).toHaveTextContent('markers:2');
|
||||
const map = captured(seen.map);
|
||||
expect(map.dark).toBe(true);
|
||||
expect(map.places.map((p) => p.name)).toEqual(['Pantheon', 'Trevi Fountain']);
|
||||
act(() => map.onOpenPlace(2));
|
||||
expect(lib.show).toHaveBeenCalledWith('trip:2');
|
||||
act(() => map.onOpenPlace(99));
|
||||
expect(lib.show).toHaveBeenCalledTimes(1);
|
||||
expect(screen.queryByRole('button', { name: /Pantheon/ })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('MPlacesLibrary: the place sheet', () => {
|
||||
it('FE-MOB-PLACESLIB-015: the sheet is open while a place is and gets what the hook loaded', () => {
|
||||
const detail = libraryDetail(libraryEntry(), [tripDetail()]);
|
||||
const { lib, unmount } = setup({ selectedKey: 'trip:42', detail, detailLoading: true, cover: '/uploads/c.jpg' });
|
||||
const sheet = captured(seen.sheet);
|
||||
expect(screen.getByTestId('place-sheet')).toBeInTheDocument();
|
||||
expect(sheet.data).toBe(detail);
|
||||
expect(sheet.loading).toBe(true);
|
||||
expect(sheet.cover).toBe('/uploads/c.jpg');
|
||||
act(() => sheet.onClose());
|
||||
expect(lib.close).toHaveBeenCalledTimes(1);
|
||||
unmount();
|
||||
|
||||
setup();
|
||||
expect(captured(seen.sheet).open).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-MOB-PLACESLIB-016: opening a list or a trip goes to its route', () => {
|
||||
const { props } = setup({ selectedKey: 'trip:42' });
|
||||
const sheet = captured(seen.sheet);
|
||||
act(() => sheet.onOpenList(3, 30));
|
||||
expect(props.navigate).toHaveBeenLastCalledWith('/places/3?place=30');
|
||||
act(() => sheet.onOpenTrip(5, 42));
|
||||
expect(props.navigate).toHaveBeenLastCalledWith('/trips/5?place=42');
|
||||
});
|
||||
|
||||
it('FE-MOB-PLACESLIB-017: keeping a trip place in a list hands over what the trip knows of it', () => {
|
||||
const entry = libraryEntry({ category: { id: 3, name: 'Restaurant', color: null, icon: null } });
|
||||
setup({ selectedKey: 'trip:42', detail: libraryDetail(entry, [tripDetail()]) });
|
||||
const info = libraryInfo({ name: 'Colosseo', description: 'Arena', website: 'https://c.example', phone: '+39' });
|
||||
act(() => captured(seen.sheet).onSaveToList(tripOrigin(), tripDetail({ info })));
|
||||
expect(openSave).toHaveBeenCalledWith({
|
||||
name: 'Colosseo',
|
||||
source_trip_id: 5,
|
||||
source_place_id: 42,
|
||||
description: 'Arena',
|
||||
lat: 41.89,
|
||||
lng: 12.49,
|
||||
address: 'Piazza del Colosseo',
|
||||
category_id: 3,
|
||||
image_url: null,
|
||||
website: 'https://c.example',
|
||||
phone: '+39',
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-MOB-PLACESLIB-018: copying closes the place and opens the trip picker, which copies it', async () => {
|
||||
const { lib } = setup({ selectedKey: 'list:30' });
|
||||
expect(captured(seen.picker).open).toBe(false);
|
||||
expect(captured(seen.picker).count).toBe(1);
|
||||
|
||||
act(() => captured(seen.sheet).onCopyToTrip(900));
|
||||
expect(lib.close).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByTestId('trip-picker')).toBeInTheDocument();
|
||||
|
||||
const picker = captured(seen.picker);
|
||||
const carry = { include_notes: false } as Parameters<PickerProps['onCopy']>[1];
|
||||
await act(async () => {
|
||||
await picker.onCopy(7, carry);
|
||||
});
|
||||
expect(copyToTrip).toHaveBeenCalledWith(7, [900], undefined, carry);
|
||||
|
||||
act(() => picker.onClose());
|
||||
expect(screen.queryByTestId('trip-picker')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -242,10 +242,10 @@ describe('MCollectionsWidget', () => {
|
||||
render(<><MobileDashWidget id="collections" upcoming={[]} /><LocationEcho /></>);
|
||||
|
||||
fireEvent.click(await screen.findByText('Tokyo eats'));
|
||||
expect(screen.getByTestId('loc')).toHaveTextContent('/collections/7');
|
||||
expect(screen.getByTestId('loc')).toHaveTextContent('/places/7');
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Collections' }));
|
||||
expect(screen.getByTestId('loc')).toHaveTextContent('/collections');
|
||||
expect(screen.getByTestId('loc')).toHaveTextContent('/places');
|
||||
});
|
||||
|
||||
it('FE-MOB-DWID-018: a failed fetch falls back to the empty hint', async () => {
|
||||
|
||||
@@ -891,8 +891,9 @@ const admin: TranslationStrings = {
|
||||
'admin.tabs.github': 'GitHub',
|
||||
'admin.addons.catalog.journey.name': 'يوميات',
|
||||
'admin.addons.catalog.journey.description': 'تتبّع الرحلات ويوميات سفر مع تسجيلات الوصول والصور وقصص كل يوم',
|
||||
'admin.addons.catalog.collections.name': 'المجموعات',
|
||||
'admin.addons.catalog.collections.description': 'اجمع الأماكن من أي رحلة في قوائم مسماة وأعد استخدامها',
|
||||
'admin.addons.catalog.collections.name': 'أماكني',
|
||||
'admin.addons.catalog.collections.description':
|
||||
'كل مكان من رحلاتك وقوائمك في عرض واحد، مع قوائم مسمّاة لجمعها وإعادة استخدامها',
|
||||
'admin.passkey.title': 'تسجيل الدخول بمفتاح المرور',
|
||||
'admin.passkey.cardHint': 'اسمح للمستخدمين بتسجيل الدخول باستخدام مفاتيح المرور (WebAuthn). معطّل افتراضيًا.',
|
||||
'admin.passkey.login': 'تفعيل تسجيل الدخول بمفتاح المرور',
|
||||
|
||||
@@ -135,7 +135,7 @@ const collection: TranslationStrings = {
|
||||
'collections.hero.mine': 'مجموعتي',
|
||||
'collections.hero.shared': 'تمت مشاركتها معك',
|
||||
'collections.hero.all': 'مكتبتك',
|
||||
'collections.title': 'المجموعات',
|
||||
'collections.title': 'أماكني',
|
||||
'collections.subtitle': 'أماكنك المحفوظة، منظمة في قوائم',
|
||||
|
||||
'collections.newList': 'قائمة جديدة',
|
||||
@@ -148,7 +148,52 @@ const collection: TranslationStrings = {
|
||||
'collections.listName': 'اسم القائمة',
|
||||
'collections.listNamePlaceholder': 'مثال: طوكيو 2025',
|
||||
'collections.listColor': 'اللون',
|
||||
'collections.listIcon': 'الرمز',
|
||||
'collections.allSaved': 'كل المحفوظات',
|
||||
'collections.myLists': 'قوائمي',
|
||||
'collections.allSavedSubtitle': 'كل مكان حفظته، من جميع قوائمك معًا.',
|
||||
'collections.library.title': 'كل الأماكن',
|
||||
'collections.library.eyebrow': 'أماكني',
|
||||
'collections.library.subtitle': 'كل مكان من رحلاتك وقوائمك في عرض واحد.',
|
||||
'collections.library.search': 'ابحث في كل الأماكن',
|
||||
'collections.library.kindAll': 'الكل',
|
||||
'collections.library.kindTrips': 'الرحلات',
|
||||
'collections.library.kindLists': 'القوائم',
|
||||
'collections.library.sortLabel': 'ترتيب',
|
||||
'collections.library.sortUpdated': 'آخر تعديل',
|
||||
'collections.library.offline': 'عرض «كل الأماكن» يحتاج إلى اتصال.',
|
||||
'collections.library.emptyTitle': 'لا توجد أماكن بعد',
|
||||
'collections.library.resetFilters': 'مسح عوامل التصفية',
|
||||
'collections.library.more': 'عرض {count} آخر',
|
||||
'collections.library.more.zero': 'لا يوجد المزيد',
|
||||
'collections.library.more.one': 'عرض واحد آخر',
|
||||
'collections.library.more.two': 'عرض اثنين آخرين',
|
||||
'collections.library.more.few': 'عرض {count} آخرين',
|
||||
'collections.library.more.many': 'عرض {count} آخر',
|
||||
'collections.library.moreOrigins': '+{count}',
|
||||
'collections.library.moreOrigins.zero': '+{count}',
|
||||
'collections.library.moreOrigins.one': '+{count}',
|
||||
'collections.library.moreOrigins.two': '+{count}',
|
||||
'collections.library.moreOrigins.few': '+{count}',
|
||||
'collections.library.moreOrigins.many': '+{count}',
|
||||
'collections.library.fromTrip': 'في الرحلة {name}',
|
||||
'collections.library.fromList': 'في القائمة {name}',
|
||||
'collections.library.inTrips': 'في رحلاتك',
|
||||
'collections.library.inLists': 'في قوائمك',
|
||||
'collections.library.readOnly': 'للقراءة فقط',
|
||||
'collections.library.calledHere': 'اسمه هنا {name}',
|
||||
'collections.library.day': 'اليوم {day}',
|
||||
'collections.library.dayOn': 'اليوم {day}، {date}',
|
||||
'collections.library.stay': 'الإقامة',
|
||||
'collections.library.booking': 'الحجز',
|
||||
'collections.library.openTrip': 'فتح في الرحلة',
|
||||
'collections.library.openList': 'فتح في القائمة',
|
||||
'collections.library.rating': '{rating} من {count} صوت',
|
||||
'collections.library.rating.zero': '{rating} من دون أصوات',
|
||||
'collections.library.rating.one': '{rating} من صوت واحد',
|
||||
'collections.library.rating.two': '{rating} من صوتين',
|
||||
'collections.library.rating.few': '{rating} من {count} أصوات',
|
||||
'collections.library.rating.many': '{rating} من {count} صوتًا',
|
||||
'collections.shared': 'مشتركة',
|
||||
|
||||
'collections.empty.title': 'لا توجد أماكن بعد',
|
||||
|
||||
@@ -7,7 +7,7 @@ const mobileNav: TranslationStrings = {
|
||||
'mobileNav.navigation': 'التنقل',
|
||||
'mobileNav.railSettings': 'الإعدادات',
|
||||
'mobileNav.railAdmin': 'الإدارة',
|
||||
'mobileNav.railCollections': 'المجموعات',
|
||||
'mobileNav.railCollections': 'أماكني',
|
||||
};
|
||||
|
||||
export default mobileNav;
|
||||
|
||||
@@ -917,9 +917,9 @@ const admin: TranslationStrings = {
|
||||
'admin.addons.catalog.journey.name': 'Səyahət gündəliyi',
|
||||
'admin.addons.catalog.journey.description':
|
||||
'Qeydiyyatlar, fotolar və gündəlik hekayələrlə səyahət izləmə və səyahət gündəliyi',
|
||||
'admin.addons.catalog.collections.name': 'Kolleksiyalar',
|
||||
'admin.addons.catalog.collections.name': 'Məkanlarım',
|
||||
'admin.addons.catalog.collections.description':
|
||||
'İstənilən səyahətdən məkanları adlandırılmış siyahılarda toplayın və yenidən istifadə edin',
|
||||
'Səyahətlərinizdəki və siyahılarınızdakı bütün məkanlar bir görünüşdə, onları toplamaq və təkrar istifadə etmək üçün adlandırılmış siyahılarla',
|
||||
'admin.passkey.title': 'Keçid açarı ilə giriş',
|
||||
'admin.passkey.cardHint':
|
||||
'İstifadəçilərə keçid açarları (WebAuthn) ilə daxil olmağa icazə verin. Standart olaraq deaktivdir.',
|
||||
|
||||
@@ -87,7 +87,7 @@ const collection: TranslationStrings = {
|
||||
'collections.hero.mine': 'Mənim kolleksiyam',
|
||||
'collections.hero.shared': 'Sizinlə paylaşılan',
|
||||
'collections.hero.all': 'Kitabxananız',
|
||||
'collections.title': 'Kolleksiyalar',
|
||||
'collections.title': 'Məkanlarım',
|
||||
'collections.subtitle': 'Siyahılar üzrə təşkil edilmiş saxlanılan məkanlarınız',
|
||||
|
||||
'collections.newList': 'Yeni siyahı',
|
||||
@@ -100,7 +100,40 @@ const collection: TranslationStrings = {
|
||||
'collections.listName': 'Siyahının adı',
|
||||
'collections.listNamePlaceholder': 'məs. Tokio 2025',
|
||||
'collections.listColor': 'Rəng',
|
||||
'collections.listIcon': 'Simvol',
|
||||
'collections.allSaved': 'Bütün saxlanılanlar',
|
||||
'collections.myLists': 'Siyahılarım',
|
||||
'collections.allSavedSubtitle': 'Saxladığınız hər məkan, bütün siyahılarınızdan birlikdə.',
|
||||
'collections.library.title': 'Bütün məkanlar',
|
||||
'collections.library.eyebrow': 'Məkanlarım',
|
||||
'collections.library.subtitle': 'Səyahətlərinizdəki və siyahılarınızdakı hər məkan bir yerdə.',
|
||||
'collections.library.search': 'Bütün məkanlarda axtar',
|
||||
'collections.library.kindAll': 'Hamısı',
|
||||
'collections.library.kindTrips': 'Səyahətlər',
|
||||
'collections.library.kindLists': 'Siyahılar',
|
||||
'collections.library.sortLabel': 'Sırala',
|
||||
'collections.library.sortUpdated': 'Son dəyişiklik',
|
||||
'collections.library.offline': '«Bütün məkanlar» görünüşü üçün bağlantı lazımdır.',
|
||||
'collections.library.emptyTitle': 'Hələ məkan yoxdur',
|
||||
'collections.library.resetFilters': 'Filtrləri təmizlə',
|
||||
'collections.library.more': 'Daha {count} göstər',
|
||||
'collections.library.more.one': 'Daha {count} göstər',
|
||||
'collections.library.moreOrigins': '+{count}', // same-as-en
|
||||
'collections.library.moreOrigins.one': '+{count}', // same-as-en
|
||||
'collections.library.fromTrip': '{name} səyahətində',
|
||||
'collections.library.fromList': '{name} siyahısında',
|
||||
'collections.library.inTrips': 'Səyahətlərinizdə',
|
||||
'collections.library.inLists': 'Siyahılarınızda',
|
||||
'collections.library.readOnly': 'Yalnız oxumaq üçün',
|
||||
'collections.library.calledHere': 'Burada adı {name}',
|
||||
'collections.library.day': 'Gün {day}',
|
||||
'collections.library.dayOn': 'Gün {day}, {date}',
|
||||
'collections.library.stay': 'Qalma',
|
||||
'collections.library.booking': 'Rezervasiya',
|
||||
'collections.library.openTrip': 'Səyahətdə aç',
|
||||
'collections.library.openList': 'Siyahıda aç',
|
||||
'collections.library.rating': '{count} səsdən {rating}',
|
||||
'collections.library.rating.one': '{count} səsdən {rating}',
|
||||
'collections.shared': 'Paylaşılan',
|
||||
|
||||
'collections.empty.title': 'Hələ məkan yoxdur',
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user