feat(places): tags on places, owned by the trip

A place keeps its one category, which decides its marker, and can now carry
any number of tags as extra labels to filter by.

- Tags belong to the trip (tags.trip_id): every member sees the same list and
  whoever may edit the trip's places adds, renames and deletes. Personal tags
  stay what they were.
- The place form picks them on desktop and mobile through one shared hook,
  usePlaceTags, and can add a new tag to the trip on the spot.
- The existing category filter of the places list lists the tags as well.
- Tags show on the place (inspector pills, phone place sheet); the marker is
  untouched.
- MCP: create_place, create_and_assign_place and update_place take `tags`,
  and list/create/update/delete_trip_tag manage a trip's tags.
- /api/trips/:tripId/tags and the tripTags:changed event keep every client
  of the trip in step.
This commit is contained in:
Mariano
2026-11-17 06:35:09 +00:00
committed by Maurice
parent e952586f60
commit 33d074c786
108 changed files with 3634 additions and 118 deletions
+11
View File
@@ -0,0 +1,11 @@
import type { TripTagCreateRequest, TripTagListResponse, TripTagResponse } from '@trek/shared';
import apiClient from './client';
/** The tags a trip owns: every member reads them, and whoever may edit its places adds one. */
export const tripTagsApi = {
list: (tripId: number | string): Promise<TripTagListResponse> =>
apiClient.get(`/trips/${tripId}/tags`).then((r) => r.data),
/** Answers the trip's existing tag when it already has one of that name. */
create: (tripId: number | string, body: TripTagCreateRequest): Promise<TripTagResponse> =>
apiClient.post(`/trips/${tripId}/tags`, body).then((r) => r.data),
};
@@ -47,6 +47,11 @@ export interface PlaceFormData {
// Which shareable fields the user typed and which a pick or the details column filled
// (placeFieldOrigins.ts). Rides along to the save as `fieldOrigins`; never shown.
fieldOrigins?: PlaceFieldOrigins
// The ids of the place's tags, always the whole set, as the save takes them. Absent
// until one is ticked or unticked in the form (usePlaceTags): a missing key writes
// nothing, so a save that never touched the tags cannot undo a tag put on the place
// elsewhere in the meantime.
tags?: number[]
}
export function isGoogleMapsUrl(input: string): boolean {
@@ -0,0 +1,99 @@
// FE-PLANNER-PLACEFORM-TAGS-001 to FE-PLANNER-PLACEFORM-TAGS-004: the place's tags in the
// desktop dialog. The logic is usePlaceTags', tested on its own; this is the form around it.
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildPlace, buildTag } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import { placeFormProps, seedPlaceFormStores } from '../../../tests/helpers/placeFormSetup';
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useTripStore } from '../../store/tripStore';
import PlaceFormModal from './PlaceFormModal';
vi.mock('../shared/CustomTimePicker', async () => ({
default: (await import('../../../tests/helpers/placeForm')).TimePickerStub,
}));
const monument = buildTag({ id: 7, trip_id: 1, name: 'Monument', color: '#6366f1' });
const zone = buildTag({ id: 8, trip_id: 1, name: 'Zone', color: '#10b981' });
const tagGroup = () => screen.getByRole('group', { name: 'Tags' });
const tagSwitch = (name: string) => within(tagGroup()).getByRole('button', { name });
beforeEach(() => {
resetAllStores();
seedPlaceFormStores();
seedStore(useTripStore, { tripTags: [monument, zone] });
});
describe('PlaceFormModal, the tags', () => {
it('FE-PLANNER-PLACEFORM-TAGS-001: a new place is saved with the tags ticked in the form', async () => {
const user = userEvent.setup();
const onSave = vi.fn().mockResolvedValue(undefined);
render(<PlaceFormModal {...placeFormProps} onSave={onSave} />);
expect(tagSwitch('Monument')).toHaveAttribute('aria-pressed', 'false');
await user.type(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), 'Belem Tower');
await user.click(tagSwitch('Monument'));
expect(tagSwitch('Monument')).toHaveAttribute('aria-pressed', 'true');
await user.click(screen.getByRole('button', { name: /^Add$/i }));
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ name: 'Belem Tower', tags: [7] }));
});
it('FE-PLANNER-PLACEFORM-TAGS-002: an edit starts from the tags the place carries and saves the whole set', async () => {
const user = userEvent.setup();
const onSave = vi.fn().mockResolvedValue(undefined);
const place = buildPlace({ name: 'Belem Tower', tags: [{ id: 8, name: 'Zone' }] });
render(<PlaceFormModal {...placeFormProps} place={place} onSave={onSave} />);
expect(tagSwitch('Zone')).toHaveAttribute('aria-pressed', 'true');
await user.click(tagSwitch('Monument'));
await user.click(tagSwitch('Zone'));
await user.click(screen.getByRole('button', { name: /^Update$/i }));
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ tags: [7] }));
});
it('FE-PLANNER-PLACEFORM-TAGS-003: an edit that never touched the tags leaves them out of the save', async () => {
const user = userEvent.setup();
const onSave = vi.fn().mockResolvedValue(undefined);
const place = buildPlace({ name: 'Belem Tower', tags: [{ id: 8, name: 'Zone' }] });
render(<PlaceFormModal {...placeFormProps} place={place} onSave={onSave} />);
await user.click(screen.getByRole('button', { name: /^Update$/i }));
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
expect(onSave.mock.calls[0][0]).not.toHaveProperty('tags');
});
it('FE-PLANNER-PLACEFORM-TAGS-004: a name typed into the tag field becomes a tag of the trip, ticked, without saving the place', async () => {
const user = userEvent.setup();
const onSave = vi.fn().mockResolvedValue(undefined);
let sent: unknown;
server.use(
http.post('/api/trips/1/tags', async ({ request }) => {
sent = await request.json();
return HttpResponse.json({ tag: buildTag({ id: 9, trip_id: 1, name: 'Viewpoint' }) }, { status: 201 });
})
);
render(<PlaceFormModal {...placeFormProps} onSave={onSave} />);
const field = screen.getByRole('textbox', { name: 'New tag' });
expect(screen.getByRole('button', { name: 'Add tag' })).toBeDisabled();
await user.type(field, 'Viewpoint{Enter}');
expect(await within(tagGroup()).findByRole('button', { name: 'Viewpoint' })).toHaveAttribute(
'aria-pressed',
'true'
);
expect(sent).toMatchObject({ name: 'Viewpoint' });
expect(field).toHaveValue('');
expect(useTripStore.getState().tripTags.map((tag) => tag.name)).toEqual(['Monument', 'Viewpoint', 'Zone']);
expect(onSave).not.toHaveBeenCalled();
});
});
@@ -23,6 +23,8 @@ import {
prefillForm, savedCategoryId, type PlaceFormData, type PlacePrefill,
} from './PlaceFormModal.helpers'
import { useNewCategory, usePlaceForm } from './usePlaceForm'
import { usePlaceTags } from './usePlaceTags'
import { PlaceFormTags } from './PlaceFormTags'
import { usePlaceSearch } from './usePlaceSearch'
import { guessCategoryId } from '@trek/shared'
import { offersGoogleRetry } from '../../utils/placeSource'
@@ -128,6 +130,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
const image = usePlaceImageField({
place, imageUrl: form.image_url, pendingImage, canUploadFiles, stageUpload, stageAttached, removeImage,
})
const tagField = usePlaceTags({ tripId, place, tags: form.tags, setForm, t, toast })
// The index the picked place came from, as its row named it, shown as a pill
// in the head band. Null for a place typed by hand or taken from the saved list.
const [pickedSource, setPickedSource] = useState<string | null>(null)
@@ -451,6 +454,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
handlePaste,
pickImage,
image,
tagField,
adoptDescription,
hasTimeError,
handleSubmit,
@@ -792,6 +796,9 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
</div>
)}
{/* Extra labels next to the one category, to filter the places by. Not for a
stop on a drive, which is not an activity anyone looks up by its tags. */}
{!serviceStop && <PlaceFormTags tags={S.tagField} t={t} />}
{/* The day in context: its times and its own note. Both live on the
day-assignment, not on the pool place (#2163), so they are only shown
@@ -0,0 +1,68 @@
// FE-PLANNER-PLFORMTAGS-001 to FE-PLANNER-PLFORMTAGS-004: the markup of the place form's tags
// on the desktop. The state behind it is usePlaceTags', tested on its own.
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, within } from '../../../tests/helpers/render';
import { PlaceFormTags } from './PlaceFormTags';
import type { PlaceTagsField } from './usePlaceTags';
const t = (key: string) => key;
function field(overrides: Partial<PlaceTagsField> = {}): PlaceTagsField {
return {
options: [
{ id: 7, name: 'Monument', color: '#6366f1', on: true },
{ id: 8, name: 'Zone', on: false },
],
toggle: vi.fn(),
name: '',
setName: vi.fn(),
saving: false,
canAdd: false,
addNew: vi.fn(() => Promise.resolve()),
handleNameKey: vi.fn(),
...overrides,
};
}
describe('PlaceFormTags', () => {
it('FE-PLANNER-PLFORMTAGS-001: shows every tag on offer as a switch that says whether it is on', () => {
render(<PlaceFormTags tags={field()} t={t} />);
const group = screen.getByRole('group', { name: 'places.tags' });
expect(within(group).getByRole('button', { name: 'Monument' })).toHaveAttribute('aria-pressed', 'true');
expect(within(group).getByRole('button', { name: 'Zone' })).toHaveAttribute('aria-pressed', 'false');
});
it('FE-PLANNER-PLFORMTAGS-002: a click on a tag switches that tag', () => {
const tags = field();
render(<PlaceFormTags tags={tags} t={t} />);
fireEvent.click(screen.getByRole('button', { name: 'Zone' }));
expect(tags.toggle).toHaveBeenCalledTimes(1);
expect(tags.toggle).toHaveBeenCalledWith(8);
});
it('FE-PLANNER-PLFORMTAGS-003: the name of a new tag is typed into the field, whose keys go to the hook', () => {
const tags = field({ name: 'View' });
render(<PlaceFormTags tags={tags} t={t} />);
const input = screen.getByRole('textbox', { name: 'places.newTag' });
expect(input).toHaveValue('View');
expect(input).toHaveAttribute('maxlength', '50');
fireEvent.change(input, { target: { value: 'Viewpoint' } });
expect(tags.setName).toHaveBeenCalledWith('Viewpoint');
fireEvent.keyDown(input, { key: 'Enter' });
expect(tags.handleNameKey).toHaveBeenCalledTimes(1);
});
it('FE-PLANNER-PLFORMTAGS-004: the add button waits for a name, then adds the tag; a trip without tags shows the field alone', () => {
const idle = field({ options: [] });
const { unmount } = render(<PlaceFormTags tags={idle} t={t} />);
expect(screen.getByRole('button', { name: 'places.addTag' })).toBeDisabled();
expect(within(screen.getByRole('group', { name: 'places.tags' })).getAllByRole('button')).toHaveLength(1);
unmount();
const ready = field({ name: 'Viewpoint', canAdd: true });
render(<PlaceFormTags tags={ready} t={t} />);
fireEvent.click(screen.getByRole('button', { name: 'places.addTag' }));
expect(ready.addNew).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,71 @@
import { TRIP_TAG_NAME_MAX } from '@trek/shared';
import { Plus, Tag as TagIcon } from 'lucide-react';
import { DialogSection, fs } from '../shared/DialogShell';
import type { PlaceTagsField } from './usePlaceTags';
type Translate = (key: string, params?: Record<string, string | number>) => string;
const ROW = 'flex flex-wrap items-center gap-1.5';
const CHIP =
'inline-flex min-w-0 max-w-full items-center gap-1.5 rounded-full border px-2.5 py-1 font-medium transition-colors';
const CHIP_ON = 'border-transparent bg-accent text-accent-text';
const CHIP_OFF = 'border-edge bg-surface-input text-content-secondary hover:text-content';
const NEW_TAG = 'inline-flex min-w-0 items-center gap-1';
const NEW_TAG_INPUT =
'w-36 min-w-0 rounded-full border border-dashed border-edge bg-transparent px-2.5 py-1 text-content outline-none placeholder:text-content-faint focus:border-solid focus:border-content-faint';
const ADD_BUTTON =
'grid h-[26px] w-[26px] flex-none place-items-center rounded-full bg-surface-card text-content-muted shadow-sm ring-1 ring-edge-faint transition-colors hover:text-content disabled:cursor-default disabled:opacity-50';
/**
* The tags of the place form on the desktop: every tag on offer as a switch, and a
* field that adds a new one to the trip. The state is usePlaceTags'; this is its markup.
*/
export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate }) {
return (
<DialogSection label={t('places.tags')}>
<div role="group" aria-label={t('places.tags')} className={ROW}>
{tags.options.map((tag) => (
<button
key={tag.id}
type="button"
aria-pressed={tag.on}
onClick={() => tags.toggle(tag.id)}
className={`${CHIP} ${tag.on ? CHIP_ON : CHIP_OFF}`}
style={fs(12, 'body')}
>
<TagIcon
size={12}
strokeWidth={2.2}
className="flex-none"
style={{ color: tag.on ? undefined : tag.color }}
/>
<span className="truncate">{tag.name}</span>
</button>
))}
<span className={NEW_TAG}>
<input
type="text"
value={tags.name}
onChange={(e) => tags.setName(e.target.value)}
onKeyDown={tags.handleNameKey}
maxLength={TRIP_TAG_NAME_MAX}
aria-label={t('places.newTag')}
placeholder={t('places.newTag')}
className={NEW_TAG_INPUT}
style={fs(12, 'body')}
/>
<button
type="button"
onClick={() => void tags.addNew()}
disabled={!tags.canAdd}
aria-label={t('places.addTag')}
className={ADD_BUTTON}
>
<Plus size={13} strokeWidth={2.4} />
</button>
</span>
</div>
</DialogSection>
);
}
@@ -1782,6 +1782,17 @@ describe('PlaceInspector', () => {
expect(header.textContent).not.toContain('·');
});
it('FE-PLANNER-INSPECTOR-106b: the tags of the place are pills beside its category, each once and by name', () => {
const tags = [{ id: 8, name: 'Zone', color: '#10b981' }, { id: 7, name: 'Monument' }, { id: 8, name: 'Zone' }];
render(<PlaceInspector {...defaultProps} place={{ ...place, id: 716, category_id: cat.id, tags }} />);
const header = document.querySelector('header') as HTMLElement;
const pills = ['Landmark', 'Monument', 'Zone'].map(name => within(header).getByText(name));
expect(pills[0].compareDocumentPosition(pills[1]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(pills[1].compareDocumentPosition(pills[2]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
// The tag's own colour is on its mark only; the pill and the marker keep theirs.
expect((pills[2].querySelector('svg') as SVGElement).style.color).toBe('rgb(16, 185, 129)');
});
it('FE-PLANNER-INSPECTOR-107: the rating block is labelled and quotes the first usable review', async () => {
vi.mocked(mapsApi.details).mockResolvedValue({
place: { rating: 4.1, reviews: [{ text: 'meh' }, { text: 'Lovely staff and view' }] },
@@ -1,8 +1,20 @@
import { Banknote, ChevronDown, ChevronUp, Mail, MapPin, MapPinOff, Phone, Star, X } from 'lucide-react';
import {
Banknote,
ChevronDown,
ChevronUp,
Mail,
MapPin,
MapPinOff,
Phone,
Star,
Tag as TagIcon,
X,
} from 'lucide-react';
import type { KeyboardEvent, ReactNode, RefObject } from 'react';
import { useTranslation } from '../../i18n';
import type { Category, Place } from '../../types';
import { tagChoices } from '../../utils/placeTags';
import AssistantAskButton from '../Assistant/AssistantAskButton';
import DawarichIcon from '../shared/DawarichIcon';
import { NEUTRAL_TINT, fs } from '../shared/DialogShell';
@@ -84,9 +96,12 @@ export function InspectorHead({
const hasCoords = !!(place.lat && place.lng);
// A typed address that never got coordinates: the place has no marker, and says why (#2837).
const offMap = addressWithoutCoordinates(place);
// The extra labels of the place, beside its one category. They never reach the marker.
const tags = tagChoices(place.tags);
const hasPills =
openNow !== null ||
!!category ||
tags.length > 0 ||
!!time ||
rating != null ||
!!price ||
@@ -174,6 +189,12 @@ export function InspectorHead({
{category.name}
</span>
)}
{tags.map((tag) => (
<span key={tag.id} className={HEAD_PILL} style={fs(10.5)}>
<TagIcon size={11} strokeWidth={2} className="flex-none" style={{ color: tag.color }} />
{tag.name}
</span>
))}
{time && <TimePill>{time}</TimePill>}
{rating != null && rating > 0 && (
<span className={HEAD_PILL} style={fs(10.5)}>
@@ -0,0 +1,149 @@
// FE-PLANNER-SIDEBAR-TAGS-001 to FE-PLANNER-SIDEBAR-TAGS-005: the tags in the category filter
// of the desktop places list. The predicate itself is covered in utils/placesFilter.test.ts.
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildCategory, buildPlace, buildTag, buildTrip, buildUser } from '../../../tests/helpers/factories';
import { render, screen, within } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useAuthStore } from '../../store/authStore';
import { useTripStore } from '../../store/tripStore';
import PlacesSidebar from './PlacesSidebar';
// The rows' pictures would ask the server for photos.
vi.mock('../../services/photoService', () => ({
getCached: vi.fn(() => null),
isLoading: vi.fn(() => false),
fetchPhoto: vi.fn(),
onThumbReady: vi.fn(() => () => undefined),
}));
const monument = buildTag({ id: 7, trip_id: 1, name: 'Monument', color: '#6366f1' });
const zone = buildTag({ id: 8, trip_id: 1, name: 'Zone', color: '#10b981' });
const park = buildCategory({ id: 4, name: 'Park', color: '#22c55e' });
const tower = buildPlace({
name: 'Belem Tower',
address: 'Lisbon',
category_id: 4,
tags: [{ id: 7, name: 'Monument' }],
});
const garden = buildPlace({ name: 'Estrela Garden', address: 'Lisbon', category_id: 4 });
const market = buildPlace({
name: 'Time Out Market',
address: 'Lisbon',
category_id: null,
// A traveller's personal tag, put on the place through the API: the trip does not list it.
tags: [
{ id: 8, name: 'Zone' },
{ id: 50, name: 'Hidden gem' },
],
});
const props = {
tripId: 1,
places: [tower, garden, market],
categories: [park],
assignments: {},
selectedDayId: null,
selectedPlaceId: null,
onPlaceClick: vi.fn(),
onAddPlace: vi.fn(),
onAssignToDay: vi.fn(),
onEditPlace: vi.fn(),
onDeletePlace: vi.fn(),
days: [],
isMobile: false,
};
type User = ReturnType<typeof userEvent.setup>;
const trigger = () => screen.getByRole('button', { name: 'Categories' });
async function openFilter(user: User) {
if (trigger().getAttribute('aria-expanded') !== 'true') await user.click(trigger());
}
/** What the closed filter says is in force, read from its tooltip. */
async function filterLabel(user: User) {
if (trigger().getAttribute('aria-expanded') === 'true') await user.click(trigger());
// The tip opens when the pointer comes in, so it leaves first.
await user.unhover(trigger());
await user.hover(trigger());
const text = (await screen.findByRole('tooltip')).textContent;
await user.unhover(trigger());
return text;
}
beforeEach(() => {
resetAllStores();
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }), tripTags: [monument, zone] });
});
describe('PlacesSidebar category filter: tags', () => {
it('FE-PLANNER-SIDEBAR-TAGS-001: lists the tags under the categories, the ones of the trip and any other a place carries', async () => {
const user = userEvent.setup();
render(<PlacesSidebar {...props} />);
await openFilter(user);
expect(screen.getByText('Tags')).toBeInTheDocument();
for (const name of ['Park', 'No Category', 'Hidden gem', 'Monument', 'Zone']) {
expect(screen.getByRole('button', { name })).toHaveAttribute('aria-pressed', 'false');
}
});
it('FE-PLANNER-SIDEBAR-TAGS-002: a ticked tag keeps the places that carry it', async () => {
const user = userEvent.setup();
render(<PlacesSidebar {...props} />);
await openFilter(user);
await user.click(screen.getByRole('button', { name: 'Monument' }));
expect(screen.getByRole('button', { name: 'Monument' })).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByText('Belem Tower')).toBeInTheDocument();
expect(screen.queryByText('Estrela Garden')).not.toBeInTheDocument();
expect(screen.queryByText('Time Out Market')).not.toBeInTheDocument();
expect(useTripStore.getState().placesCategoryFilter).toEqual(new Set(['tag:7']));
expect(await filterLabel(user)).toBe('Categories: Monument');
});
it('FE-PLANNER-SIDEBAR-TAGS-003: a category and a tag ticked together both have to hold, and the filter names them', async () => {
const user = userEvent.setup();
render(<PlacesSidebar {...props} />);
await openFilter(user);
await user.click(screen.getByRole('button', { name: 'Park' }));
expect(screen.getByText('Estrela Garden')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Monument' }));
expect(screen.getByText('Belem Tower')).toBeInTheDocument();
expect(screen.queryByText('Estrela Garden')).not.toBeInTheDocument();
expect(within(trigger()).getByText('2')).toBeInTheDocument();
expect(await filterLabel(user)).toBe('Categories: Park, Monument');
});
it('FE-PLANNER-SIDEBAR-TAGS-004: clearing the filter unticks the tags as well', async () => {
const user = userEvent.setup();
render(<PlacesSidebar {...props} />);
await openFilter(user);
await user.click(screen.getByRole('button', { name: 'Zone' }));
await user.click(screen.getByRole('button', { name: 'No Category' }));
expect(screen.getByText('Time Out Market')).toBeInTheDocument();
expect(screen.queryByText('Belem Tower')).not.toBeInTheDocument();
expect(await filterLabel(user)).toBe('Categories: No Category, Zone');
await openFilter(user);
await user.click(screen.getByText('Clear filter'));
expect(useTripStore.getState().placesCategoryFilter.size).toBe(0);
expect(screen.getByText('Belem Tower')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Zone' })).toHaveAttribute('aria-pressed', 'false');
});
it('FE-PLANNER-SIDEBAR-TAGS-005: a trip with tags and no category still has the filter; with neither it has none', async () => {
const user = userEvent.setup();
const { unmount } = render(<PlacesSidebar {...props} categories={[]} />);
await openFilter(user);
expect(screen.getByRole('button', { name: 'Monument' })).toBeInTheDocument();
unmount();
seedStore(useTripStore, { tripTags: [] });
render(<PlacesSidebar {...props} categories={[]} places={[garden]} />);
expect(screen.queryByRole('button', { name: 'Categories' })).not.toBeInTheDocument();
});
});
@@ -8,9 +8,10 @@ import { Eyebrow } from './bookings/bookingParts'
import { tintOf } from './planParts'
import { CategoryTile } from './PlacesBulkCategoryModal'
import type { SidebarState } from './usePlacesSidebar'
import { placesFilterTabs } from './usePlacesPool'
import { placesFilterTabs, usePlacesFilterTags } from './usePlacesPool'
import { PLACES_SORTS, type PlacesSort } from './placesSort'
import { RATING_FLOORS, UNCATEGORIZED } from '../../utils/placesFilter'
import { RATING_FLOORS, UNCATEGORIZED, tagFilterKey } from '../../utils/placesFilter'
import type { TagChoice } from '../../utils/placeTags'
/**
* Below this the two labels stop fitting side by side and both buttons fall back
@@ -249,22 +250,31 @@ function FilterDropdown({ label, active, badge, icon, open, setOpen, name, child
)
}
/** Which categories to show, many at once; the label says what is in force. */
/**
* What the category filter says is in force: nothing, the one name, or how many
* categories. Once a tag is ticked too it is no count of categories any more, so
* the names say it.
*/
function categoryFilterLabel({ t, categories, categoryFilters }: SidebarState, tags: TagChoice[]): string {
if (categoryFilters.size === 0) return t('places.allCategories')
const tagNames = tags.filter(tag => categoryFilters.has(tagFilterKey(tag.id))).map(tag => tag.name)
if (tagNames.length === 0 && categoryFilters.size > 1) {
return `${categoryFilters.size} ${t('places.categoriesSelected', { count: categoryFilters.size })}`
}
const names = categories.filter(c => categoryFilters.has(String(c.id))).map(c => c.name)
if (categoryFilters.has(UNCATEGORIZED)) names.push(t('places.noCategory'))
return [...names, ...tagNames].join(', ') || t('places.allCategories')
}
/** Which categories and which tags to show, many at once; the label says what is in force. */
function CategoryFilter(S: SidebarState) {
const { t, places, categories, categoryFilters, setCategoryFilters, toggleCategoryFilter } = S
const [open, setOpen] = useState(false)
if (categories.length === 0) return null
let label = t('places.allCategories')
if (categoryFilters.size === 1) {
const only = categories.find(c => categoryFilters.has(String(c.id)))
if (categoryFilters.has(UNCATEGORIZED)) label = t('places.noCategory')
else if (only) label = only.name
} else if (categoryFilters.size > 1) {
label = `${categoryFilters.size} ${t('places.categoriesSelected', { count: categoryFilters.size })}`
}
const tags = usePlacesFilterTags(places)
if (categories.length === 0 && tags.length === 0) return null
return (
<FilterDropdown name={t('categories.title')} label={label} active={categoryFilters.size > 0} badge={categoryFilters.size}
icon={<Tag size={14} strokeWidth={2} />} open={open} setOpen={setOpen}>
<FilterDropdown name={t('categories.title')} label={categoryFilterLabel(S, tags)} active={categoryFilters.size > 0}
badge={categoryFilters.size} icon={<Tag size={14} strokeWidth={2} />} open={open} setOpen={setOpen}>
{categories.map(c => (
<CategoryChoice
key={c.id}
@@ -282,6 +292,21 @@ function CategoryFilter(S: SidebarState) {
label={t('places.noCategory')}
/>
)}
{/* The tags, in the same list: a place has one category and any number of these. */}
{tags.length > 0 && <Eyebrow className="px-1.5 pb-1 pt-2">{t('places.tags')}</Eyebrow>}
{tags.map(tag => (
<CategoryChoice
key={tagFilterKey(tag.id)}
on={categoryFilters.has(tagFilterKey(tag.id))}
onClick={() => toggleCategoryFilter(tagFilterKey(tag.id))}
tile={(
<span className="grid h-[22px] w-[22px] flex-none place-items-center rounded-[7px] bg-surface-tertiary text-content-faint">
<Tag size={11} strokeWidth={2.2} style={{ color: tag.color }} />
</span>
)}
label={tag.name}
/>
))}
{categoryFilters.size > 0 && (
<button type="button" onClick={() => setCategoryFilters(new Set())}
className="mt-1 flex w-full items-center gap-1.5 rounded-[9px] border-t border-edge-faint px-1.5 pb-1 pt-2 text-start font-semibold text-content-muted hover:text-content"
@@ -0,0 +1,183 @@
// FE-PLANNER-PLTAGS-001 to FE-PLANNER-PLTAGS-008: the tags of the place form, the one logic
// path behind the desktop dialog and the phone sheet.
import { act, renderHook, waitFor } from '@testing-library/react';
import { useState, type KeyboardEvent } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildTag } from '../../../tests/helpers/factories';
import { resetAllStores } from '../../../tests/helpers/store';
import { useTripStore, type TripStoreState } from '../../store/tripStore';
import type { Place, Tag } from '../../types';
import { DEFAULT_FORM } from './PlaceFormModal.helpers';
import { usePlaceTags } from './usePlaceTags';
const t = (key: string) => key;
const makeToast = () => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() });
const monument = buildTag({ id: 7, trip_id: 5, name: 'Monument', color: '#6366f1' });
const zone = buildTag({ id: 8, trip_id: 5, name: 'Zone', color: '#10b981' });
/** A traveller's personal tag, put on the place through the API: the trip does not list it. */
const personal = { id: 50, name: 'Hidden gem', color: '#f59e0b' };
const addTripTag = vi.fn<TripStoreState['addTripTag']>();
let toast: ReturnType<typeof makeToast>;
function setOnline(online: boolean): void {
Object.defineProperty(navigator, 'onLine', { value: online, writable: true, configurable: true });
}
beforeEach(() => {
resetAllStores();
setOnline(true);
toast = makeToast();
addTripTag.mockReset();
useTripStore.setState({ tripTags: [monument, zone], addTripTag });
});
afterEach(() => {
setOnline(true);
});
/** The hook over a form of its own, as both shells run it. */
function setup(place: Pick<Place, 'tags'> | null = null) {
return renderHook(() => {
const [form, setForm] = useState(DEFAULT_FORM);
return { form, field: usePlaceTags({ tripId: 5, place, tags: form.tags, setForm, t, toast }) };
});
}
function key(name: string) {
const preventDefault = vi.fn();
return { event: { key: name, preventDefault } as unknown as KeyboardEvent<HTMLInputElement>, preventDefault };
}
describe('usePlaceTags', () => {
it('FE-PLANNER-PLTAGS-001: offers the tags of the trip by name, none ticked for a new place', () => {
const { result } = setup();
expect(result.current.field.options).toEqual([
{ id: 7, name: 'Monument', color: '#6366f1', on: false },
{ id: 8, name: 'Zone', color: '#10b981', on: false },
]);
// Nothing was touched, so the save has no tags to send.
expect(result.current.form.tags).toBeUndefined();
expect(result.current.field.canAdd).toBe(false);
});
it('FE-PLANNER-PLTAGS-002: ticks what the place carries and keeps a personal tag of it on offer', () => {
const { result } = setup({ tags: [{ id: 8, name: 'Zone (old name)' }, personal] });
expect(result.current.field.options).toEqual([
{ id: 50, name: 'Hidden gem', color: '#f59e0b', on: true },
{ id: 7, name: 'Monument', color: '#6366f1', on: false },
// The trip's own name and colour, not the copy on the place.
{ id: 8, name: 'Zone', color: '#10b981', on: true },
]);
expect(result.current.form.tags).toBeUndefined();
});
it('FE-PLANNER-PLTAGS-003: a tick writes the whole set into the form, starting from what the place carries', () => {
const { result } = setup({ tags: [{ id: 8, name: 'Zone' }, personal] });
act(() => result.current.field.toggle(7));
expect(result.current.form.tags).toEqual([8, 50, 7]);
expect(result.current.field.options.map((tag) => tag.on)).toEqual([true, true, true]);
act(() => result.current.field.toggle(50));
expect(result.current.form.tags).toEqual([8, 7]);
act(() => result.current.field.toggle(8));
act(() => result.current.field.toggle(7));
// Every tag off is an answer too: the save takes the tags off the place.
expect(result.current.form.tags).toEqual([]);
expect(result.current.field.options.map((tag) => tag.on)).toEqual([false, false, false]);
});
it('FE-PLANNER-PLTAGS-004: a typed name becomes a tag of the trip, ticked, and the field is empty again', async () => {
const viewpoint = buildTag({ id: 9, trip_id: 5, name: 'Viewpoint' });
addTripTag.mockResolvedValue(viewpoint);
const { result } = setup();
act(() => result.current.field.setName(' Viewpoint '));
expect(result.current.field.canAdd).toBe(true);
await act(() => result.current.field.addNew());
expect(addTripTag).toHaveBeenCalledWith(5, { name: 'Viewpoint', color: expect.stringMatching(/^#[0-9a-f]{6}$/) });
expect(result.current.form.tags).toEqual([9]);
expect(result.current.field.name).toBe('');
expect(result.current.field.saving).toBe(false);
expect(toast.error).not.toHaveBeenCalled();
});
it('FE-PLANNER-PLTAGS-005: a name the trip has already ticks that tag once, and an empty name asks nothing', async () => {
addTripTag.mockResolvedValue(zone);
const { result } = setup({ tags: [{ id: 8, name: 'Zone' }] });
act(() => result.current.field.setName(' '));
expect(result.current.field.canAdd).toBe(false);
await act(() => result.current.field.addNew());
expect(addTripTag).not.toHaveBeenCalled();
act(() => result.current.field.setName('zone'));
await act(() => result.current.field.addNew());
expect(result.current.form.tags).toEqual([8]);
});
it('FE-PLANNER-PLTAGS-006: a tag that could not be added says so and keeps the name; offline it asks for a connection', async () => {
addTripTag.mockRejectedValue(new Error('refused'));
const { result } = setup();
act(() => result.current.field.setName('Viewpoint'));
await act(() => result.current.field.addNew());
expect(toast.error).toHaveBeenLastCalledWith('places.tagCreateError');
expect(result.current.field.name).toBe('Viewpoint');
expect(result.current.field.saving).toBe(false);
expect(result.current.form.tags).toBeUndefined();
setOnline(false);
await act(() => result.current.field.addNew());
expect(toast.error).toHaveBeenLastCalledWith('common.needsConnection');
});
it('FE-PLANNER-PLTAGS-007: Enter in the name field adds the tag instead of saving the place; an empty field leaves the key alone', async () => {
addTripTag.mockResolvedValue(buildTag({ id: 9, trip_id: 5, name: 'Viewpoint' }));
const { result } = setup();
const empty = key('Enter');
act(() => result.current.field.handleNameKey(empty.event));
expect(empty.preventDefault).not.toHaveBeenCalled();
act(() => result.current.field.setName('Viewpoint'));
const letter = key('a');
act(() => result.current.field.handleNameKey(letter.event));
expect(letter.preventDefault).not.toHaveBeenCalled();
expect(addTripTag).not.toHaveBeenCalled();
const enter = key('Enter');
act(() => result.current.field.handleNameKey(enter.event));
await waitFor(() => expect(result.current.form.tags).toEqual([9]));
expect(enter.preventDefault).toHaveBeenCalledTimes(1);
expect(addTripTag).toHaveBeenCalledTimes(1);
});
it('FE-PLANNER-PLTAGS-008: a tick made while a tag is on its way is kept, and a second request waits for the first', async () => {
let answer: (tag: Tag) => void = () => undefined;
addTripTag.mockReturnValue(new Promise<Tag>((resolve) => (answer = resolve)));
const { result } = setup();
act(() => result.current.field.setName('Viewpoint'));
let pending: Promise<void> = Promise.resolve();
act(() => {
pending = result.current.field.addNew();
});
expect(result.current.field.saving).toBe(true);
expect(result.current.field.canAdd).toBe(false);
await act(() => result.current.field.addNew());
expect(addTripTag).toHaveBeenCalledTimes(1);
act(() => result.current.field.toggle(7));
await act(async () => {
answer(buildTag({ id: 9, trip_id: 5, name: 'Viewpoint' }));
await pending;
});
expect(result.current.form.tags).toEqual([7, 9]);
});
});
@@ -0,0 +1,77 @@
import { useMemo, useState, type Dispatch, type KeyboardEvent, type SetStateAction } from 'react';
import type { useTranslation } from '../../i18n';
import { useTripStore } from '../../store/tripStore';
import type { Place } from '../../types';
import { offlineOr } from '../../utils/needsConnection';
import { nextTagColor, placeTagIds, tagChoices } from '../../utils/placeTags';
import type { useToast } from '../shared/Toast';
import type { PlaceFormData } from './PlaceFormModal.helpers';
type Translate = ReturnType<typeof useTranslation>['t'];
type Toast = ReturnType<typeof useToast>;
interface PlaceTagsOptions {
tripId: number | string;
/** The place being edited, for the tags it carries already; none while a place is being added. */
place: Pick<Place, 'tags'> | null | undefined;
/** The form's own tags: absent until one is ticked or unticked. */
tags: PlaceFormData['tags'];
setForm: Dispatch<SetStateAction<PlaceFormData>>;
t: Translate;
toast: Toast;
}
/**
* The tags of the place form: the one logic path behind the desktop dialog and the
* phone sheet, which draw their own markup over it. It offers the trip's tags and any
* personal tag the place carries already, keeps which of them are ticked in the form
* itself, so the save sends them, and adds a new tag to the trip, ticked straight away.
*/
export function usePlaceTags({ tripId, place, tags, setForm, t, toast }: PlaceTagsOptions) {
const tripTags = useTripStore((s) => s.tripTags);
const addTripTag = useTripStore((s) => s.addTripTag);
const carried = place?.tags;
const saved = useMemo(() => placeTagIds(carried), [carried]);
const selected = tags ?? saved;
const options = useMemo(
() => tagChoices(tripTags, carried).map((tag) => ({ ...tag, on: selected.includes(tag.id) })),
[tripTags, carried, selected]
);
const [name, setName] = useState('');
const [saving, setSaving] = useState(false);
/** Changes the ticked set from what it is when the change lands, not from what it was when it was asked for. */
const change = (next: (ids: number[]) => number[]) =>
setForm((prev) => ({ ...prev, tags: next(prev.tags ?? saved) }));
const toggle = (id: number) =>
change((ids) => (ids.includes(id) ? ids.filter((other) => other !== id) : [...ids, id]));
/** The typed name becomes a tag of the trip, or is the one it has already, and is ticked. */
const addNew = async () => {
const wanted = name.trim();
if (!wanted || saving) return;
setSaving(true);
try {
const tag = await addTripTag(tripId, { name: wanted, color: nextTagColor(tripTags) });
change((ids) => (ids.includes(tag.id) ? ids : [...ids, tag.id]));
setName('');
} catch {
toast.error(offlineOr(t, t('places.tagCreateError')));
} finally {
setSaving(false);
}
};
/** Enter in the name field adds the tag; with a name typed it never reaches the place's own save. */
const handleNameKey = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key !== 'Enter' || !name.trim()) return;
e.preventDefault();
void addNew();
};
return { options, toggle, name, setName, saving, canAdd: !!name.trim() && !saving, addNew, handleNameKey };
}
export type PlaceTagsField = ReturnType<typeof usePlaceTags>;
@@ -1,9 +1,9 @@
// FE-PLANNER-POOL-001 to FE-PLANNER-POOL-016: the places pool's search, filters and
// FE-PLANNER-POOL-001 to FE-PLANNER-POOL-017: the places pool's search, filters and
// multi-select behind the desktop sidebar ('exit') and the phone browser ('prune').
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildPlace } from '../../../tests/helpers/factories';
import { buildPlace, buildTag } from '../../../tests/helpers/factories';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { collectionsApi } from '../../api/collections';
import { useTripStore } from '../../store/tripStore';
@@ -11,6 +11,7 @@ import {
placesFilterTabs,
poolHasTracks,
usePlacesCategoryFilter,
usePlacesFilterTags,
usePlacesPool,
type PlacesPoolOptions,
} from './usePlacesPool';
@@ -287,4 +288,29 @@ describe('usePlacesPool', () => {
act(() => result.current.setSelectedIds(new Set([12345])));
expect(result.current.selectedIds.size).toBe(0);
});
it('FE-PLANNER-POOL-017: the filter offers the tags of the trip and any other a listed place carries, by name', () => {
const monument = buildTag({ id: 7, name: 'Monument', color: '#6366f1' });
const zone = buildTag({ id: 8, name: 'Zone', color: 'not a colour' });
seedStore(useTripStore, { tripTags: [zone, monument] });
const places = [
buildPlace({ tags: [{ id: 7, name: 'Monument (old name)' }] }),
buildPlace({ tags: [{ id: 50, name: 'Hidden gem', color: '#f59e0b' }] }),
buildPlace(),
];
const { result, rerender } = renderHook((listed: typeof places) => usePlacesFilterTags(listed), {
initialProps: places,
});
expect(result.current).toEqual([
{ id: 50, name: 'Hidden gem', color: '#f59e0b' },
// The trip's own name, not the copy on the place.
{ id: 7, name: 'Monument', color: '#6366f1' },
// A colour that is no plain hex value is left out: the row keeps the colour of its text.
{ id: 8, name: 'Zone', color: undefined },
]);
// The same places and tags are the same list, so a row does not redraw for nothing.
const first = result.current;
rerender(places);
expect(result.current).toBe(first);
});
});
+12 -2
View File
@@ -5,6 +5,7 @@ import type { useTranslation } from '../../i18n';
import { useTripStore } from '../../store/tripStore';
import type { Place } from '../../types';
import { offlineOr } from '../../utils/needsConnection';
import { tagChoices } from '../../utils/placeTags';
import { useToast } from '../shared/Toast';
/** What the pool shows: everything, what is not on a day yet, what is, or the tracks. */
@@ -30,8 +31,8 @@ export function placesFilterTabs(t: Translate, hasTracks: boolean) {
/**
* The category filter of the places pool: a set of category ids (plus the
* no-category bucket), many at once. It lives in the trip store, so the list
* and the map markers filter on the same values (#1541).
* no-category bucket) and of tags, many at once. It lives in the trip store, so
* the list and the map markers filter on the same values (#1541).
*/
export function usePlacesCategoryFilter() {
const categoryFilters = useTripStore((s) => s.placesCategoryFilter);
@@ -45,6 +46,15 @@ export function usePlacesCategoryFilter() {
return { categoryFilters, setCategoryFilters, toggleCategoryFilter };
}
/**
* The tags the category filter offers under the categories, for both shells: the
* trip's own, and any other tag one of the listed places carries.
*/
export function usePlacesFilterTags(places: Place[]) {
const tripTags = useTripStore((s) => s.tripTags);
return useMemo(() => tagChoices(tripTags, ...places.map((place) => place.tags)), [tripTags, places]);
}
export interface PlacesPoolOptions {
tripId: number;
/** Every place of the trip: a selected place that is gone from here is gone. */
+12
View File
@@ -0,0 +1,12 @@
import type { Tag } from '@trek/shared';
import { offlineDb } from './offlineDb';
/** The trip's tags as the server last listed them; none while the device never read them. */
export async function cachedTripTags(tripId: number): Promise<Tag[]> {
return (await offlineDb.tripTags.get(tripId))?.tags ?? [];
}
/** Keeps the trip's tags as the server listed them. */
export async function cacheTripTags(tripId: number, tags: Tag[]): Promise<void> {
await offlineDb.tripTags.put({ tripId, tags });
}
+17
View File
@@ -70,6 +70,16 @@ interface CachedTourDraft {
draft: TourDraft;
}
/**
* The tags a trip owns, as the server last listed them: one row per trip, so the
* place form and the category filter still offer them offline. Not the `tags`
* table, which holds the signed-in user's personal ones.
*/
interface CachedTripTags {
tripId: number;
tags: Tag[];
}
/**
* A road route as the router answered it, kept on the device so a trip opens
* with its roads drawn instead of asking the router for every leg again (#2794).
@@ -293,6 +303,7 @@ export class TrekOfflineDb extends Dexie {
tourStationVisits!: Table<CachedTourStationVisit, [number, string]>;
tourDrafts!: Table<CachedTourDraft, number>;
routeCache!: Table<CachedRoute, string>;
tripTags!: Table<CachedTripTags, number>;
constructor(name: string = ANON_DB_NAME) {
super(name);
@@ -385,6 +396,10 @@ export class TrekOfflineDb extends Dexie {
// whole route shown opens drawn instead of re-routing every leg (#2794). Not per
// trip: the same waypoints are the same road in any trip; `savedAt` to prune.
this.version(14).stores({ routeCache: 'key, savedAt' });
// v15: the tags a trip owns, one list per trip, so they are offered offline
// and go with the trip.
this.version(15).stores({ tripTags: 'tripId' });
}
}
@@ -686,10 +701,12 @@ export async function clearTripData(tripId: number): Promise<void> {
offlineDb.ferrataTiles,
offlineDb.tourStationVisits,
offlineDb.tourDrafts,
offlineDb.tripTags,
],
async () => {
await offlineDb.roadtripPreferences.delete(tripId);
await offlineDb.tourDrafts.delete(tripId);
await offlineDb.tripTags.delete(tripId);
await offlineDb.budgetSettlements.delete(tripId);
await offlineDb.days.where('trip_id').equals(tripId).delete();
await offlineDb.places.where('trip_id').equals(tripId).delete();
@@ -0,0 +1,46 @@
// FE-MOB-PFILTER-TAGS-001 to FE-MOB-PFILTER-TAGS-003: the tags in the phone's category filter,
// which ticks them into the same set as the categories.
import { beforeEach, describe, expect, it } from 'vitest';
import { buildCategory, buildPlace, buildTag } from '../../../../../tests/helpers/factories';
import { fireEvent, render, screen } from '../../../../../tests/helpers/render';
import { resetAllStores } from '../../../../../tests/helpers/store';
import { useTripStore } from '../../../../store/tripStore';
import { MCategoryFilterList } from './MPlacesFilterControls';
const park = buildCategory({ id: 4, name: 'Park' });
const monument = buildTag({ id: 7, trip_id: 1, name: 'Monument', color: '#6366f1' });
const tower = buildPlace({ category_id: 4, tags: [{ id: 7, name: 'Monument' }] });
// A traveller's personal tag, put on the place through the API: the trip does not list it.
const market = buildPlace({ category_id: 4, tags: [{ id: 50, name: 'Hidden gem' }] });
beforeEach(() => {
resetAllStores();
useTripStore.setState({ tripTags: [monument] });
});
describe('MCategoryFilterList: tags', () => {
it('FE-MOB-PFILTER-TAGS-001: lists the tags after the categories, the ones of the trip and any other a place carries', () => {
render(<MCategoryFilterList categories={[park]} places={[tower, market]} />);
expect(screen.getAllByRole('checkbox').map((row) => row.textContent)).toEqual(['Park', 'Hidden gem', 'Monument']);
expect(screen.getByRole('checkbox', { name: 'Monument' })).toHaveAttribute('aria-checked', 'false');
});
it('FE-MOB-PFILTER-TAGS-002: a tag is ticked into the set the categories filter through, and out of it again', () => {
render(<MCategoryFilterList categories={[park]} places={[tower, market]} />);
fireEvent.click(screen.getByRole('checkbox', { name: 'Monument' }));
fireEvent.click(screen.getByRole('checkbox', { name: 'Park' }));
expect([...useTripStore.getState().placesCategoryFilter]).toEqual(['tag:7', '4']);
expect(screen.getByRole('checkbox', { name: 'Monument' })).toHaveAttribute('aria-checked', 'true');
fireEvent.click(screen.getByRole('checkbox', { name: 'Monument' }));
expect([...useTripStore.getState().placesCategoryFilter]).toEqual(['4']);
expect(screen.getByRole('checkbox', { name: 'Monument' })).toHaveAttribute('aria-checked', 'false');
});
it('FE-MOB-PFILTER-TAGS-003: a trip without tags lists the categories alone', () => {
useTripStore.setState({ tripTags: [] });
render(<MCategoryFilterList categories={[park]} places={[buildPlace({ category_id: 4 })]} />);
expect(screen.getAllByRole('checkbox').map((row) => row.textContent)).toEqual(['Park']);
});
});
@@ -1,11 +1,11 @@
import { ReactNode } from 'react'
import { Check, MapPin, Star } from 'lucide-react'
import { Check, MapPin, Star, Tag as TagIcon } from 'lucide-react'
import MChip from '../../../components/MChip'
import { useTripStore } from '../../../../store/tripStore'
import { getCategoryIcon } from '../../../../components/shared/categoryIcons'
import { RATING_FLOORS, UNCATEGORIZED } from '../../../../utils/placesFilter'
import { RATING_FLOORS, UNCATEGORIZED, tagFilterKey } from '../../../../utils/placesFilter'
import { useTranslation } from '../../../../i18n'
import { usePlacesCategoryFilter } from '../../../../components/Planner/usePlacesPool'
import { usePlacesCategoryFilter, usePlacesFilterTags } from '../../../../components/Planner/usePlacesPool'
import type { Category, Place } from '../../../../types'
/**
@@ -48,10 +48,14 @@ function CategoryFilterRow({ checked, onToggle, label, children }: {
)
}
/** The trip's categories as a multi-select, plus "no category" while a place has none. */
/**
* The trip's categories as a multi-select, plus "no category" while a place has
* none, and after them the tags, which filter through the same set.
*/
export function MCategoryFilterList({ categories, places }: { categories: Category[]; places: Place[] }) {
const { t } = useTranslation()
const { categoryFilters, toggleCategoryFilter: toggle } = usePlacesCategoryFilter()
const tags = usePlacesFilterTags(places)
return (
<>
{categories.map(c => {
@@ -76,6 +80,16 @@ export function MCategoryFilterList({ categories, places }: { categories: Catego
<MapPin size={14} strokeWidth={2} className="flex-none text-m-faint" />
</CategoryFilterRow>
)}
{tags.map(tag => (
<CategoryFilterRow
key={tagFilterKey(tag.id)}
checked={categoryFilters.has(tagFilterKey(tag.id))}
onToggle={() => toggle(tagFilterKey(tag.id))}
label={tag.name}
>
<TagIcon size={14} strokeWidth={2} className="flex-none text-m-faint" style={{ color: tag.color }} />
</CategoryFilterRow>
))}
</>
)
}
@@ -12,12 +12,14 @@ import {
type PlaceFormData,
} from '../../../../components/Planner/PlaceFormModal.helpers'
import { usePlaceForm } from '../../../../components/Planner/usePlaceForm'
import { usePlaceTags } from '../../../../components/Planner/usePlaceTags'
import { addressWithoutCoordinates } from '../../../../components/Planner/placeCoordinates'
import { Eyebrow, FIELD_AREA_CLS, FIELD_CLS, FormSheetBody, FormSheetFooter, FormSheetHeader } from './PlSheetChrome'
import { useAddonStore } from '../../../../store/addonStore'
import type { BookingExpenseRequest } from '../../../../components/Planner/BookingCostsSection.types'
import PlPlaceSearch, { type PlSearchPick } from './PlPlaceSearch'
import PlCategoryPicker from './PlCategoryPicker'
import { PlTagPicker } from './PlTags'
import PlTimeFields from './PlTimeFields'
import PlFileAttach from './PlFileAttach'
import MLinkedCosts from './MLinkedCosts'
@@ -91,6 +93,7 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
// the edit chrome doesn't flip to "add" while fading out.
const [sheetPlace, setSheetPlace] = useState<Place | null>(null)
const [sheetAssignmentId, setSheetAssignmentId] = useState<number | null>(null)
const tagField = usePlaceTags({ tripId: planner.tripId, place: sheetPlace, tags: form.tags, setForm, t, toast })
const placesEnrichEnabled = useAuthStore(s => s.placesEnrichEnabled)
const { language, locale } = useTranslation()
@@ -342,6 +345,7 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
<Eyebrow className="mb-[6px] mt-3 uppercase">{t('places.formCategory')}</Eyebrow>
<PlCategoryPicker planner={planner} value={form.category_id} onChange={id => handleChange('category_id', id)} />
<PlTagPicker tags={tagField} t={t} />
{/* Times live per day-assignment — only editable when one is in context.
Same for the day-specific note (#2163). */}
@@ -31,6 +31,7 @@ import type { Assignment, Day, Reservation, TripMember } from '../../../../types
import PlacePhotoGallery from '../../../../components/Planner/PlacePhotoGallery'
import { ActionCircle, Eyebrow, INNER_CLS } from './MTripSheetUi'
import { FormSheetBody } from './PlSheetChrome'
import { PlTagChips } from './PlTags'
/**
* Place inspector sheet (glass card), opened by the current place selection —
@@ -235,6 +236,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
<span dir="auto" className="truncate">{category.name}</span>
</span>
)}
<PlTagChips tags={place.tags} />
</div>
<button
type="button"
@@ -0,0 +1,86 @@
// FE-MOB-PLTAGS-001 to FE-MOB-PLTAGS-005: the phone's tag markup, which is the picker of the
// place form (its state is usePlaceTags', tested on its own) and the chips of the place sheet.
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, within } from '../../../../../tests/helpers/render';
import type { PlaceTagsField } from '../../../../components/Planner/usePlaceTags';
import { PlTagChips, PlTagPicker } from './PlTags';
const t = (key: string) => key;
function field(overrides: Partial<PlaceTagsField> = {}): PlaceTagsField {
return {
options: [
{ id: 7, name: 'Monument', color: '#6366f1', on: true },
{ id: 8, name: 'Zone', on: false },
],
toggle: vi.fn(),
name: '',
setName: vi.fn(),
saving: false,
canAdd: false,
addNew: vi.fn(() => Promise.resolve()),
handleNameKey: vi.fn(),
...overrides,
};
}
describe('PlTagPicker', () => {
it('FE-MOB-PLTAGS-001: labels the tags and shows each as a chip that says whether it is on', () => {
render(<PlTagPicker tags={field()} t={t} />);
expect(screen.getAllByText('places.tags').length).toBeGreaterThan(0);
const group = screen.getByRole('group', { name: 'places.tags' });
expect(within(group).getByRole('button', { name: 'Monument' })).toHaveAttribute('aria-pressed', 'true');
expect(within(group).getByRole('button', { name: 'Zone' })).toHaveAttribute('aria-pressed', 'false');
});
it('FE-MOB-PLTAGS-002: a tap on a chip switches that tag', () => {
const tags = field();
render(<PlTagPicker tags={tags} t={t} />);
fireEvent.click(screen.getByRole('button', { name: 'Monument' }));
expect(tags.toggle).toHaveBeenCalledTimes(1);
expect(tags.toggle).toHaveBeenCalledWith(7);
});
it('FE-MOB-PLTAGS-003: a new tag is typed and confirmed, and the confirm waits for a name', () => {
const idle = field();
const { unmount } = render(<PlTagPicker tags={idle} t={t} />);
expect(screen.getByRole('button', { name: 'places.addTag' })).toBeDisabled();
const input = screen.getByRole('textbox', { name: 'places.newTag' });
fireEvent.change(input, { target: { value: 'Viewpoint' } });
expect(idle.setName).toHaveBeenCalledWith('Viewpoint');
fireEvent.keyDown(input, { key: 'Enter' });
expect(idle.handleNameKey).toHaveBeenCalledTimes(1);
unmount();
const ready = field({ name: 'Viewpoint', canAdd: true });
render(<PlTagPicker tags={ready} t={t} />);
expect(screen.getByRole('textbox', { name: 'places.newTag' })).toHaveValue('Viewpoint');
fireEvent.click(screen.getByRole('button', { name: 'places.addTag' }));
expect(ready.addNew).toHaveBeenCalledTimes(1);
});
});
describe('PlTagChips', () => {
it('FE-MOB-PLTAGS-004: shows the tags a place carries, each once and by name', () => {
const { container } = render(
<PlTagChips
tags={[
{ id: 8, name: 'Zone', color: '#10b981' },
{ id: 7, name: 'Monument' },
{ id: 8, name: 'Zone' },
]}
/>
);
expect(screen.getByText('Monument')).toBeInTheDocument();
expect(screen.getAllByText('Zone')).toHaveLength(1);
expect(container.textContent).toBe('MonumentZone');
});
it('FE-MOB-PLTAGS-005: draws nothing for a place without tags, or with tags that have no name yet', () => {
const { container, rerender } = render(<PlTagChips tags={undefined} />);
expect(container).toBeEmptyDOMElement();
rerender(<PlTagChips tags={[{ id: 9 }]} />);
expect(container).toBeEmptyDOMElement();
});
});
@@ -0,0 +1,84 @@
import { TRIP_TAG_NAME_MAX } from '@trek/shared';
import { Check, Tag as TagIcon } from 'lucide-react';
import type { PlaceTagsField } from '../../../../components/Planner/usePlaceTags';
import type { Place } from '../../../../types';
import { tagChoices } from '../../../../utils/placeTags';
import MChip from '../../../components/MChip';
import { Eyebrow, FIELD_CLS } from './PlSheetChrome';
type Translate = (key: string, params?: Record<string, string | number>) => string;
const LABEL = 'mb-[6px] mt-3 uppercase';
const PICKER = 'flex flex-wrap gap-[6px]';
const NEW_TAG = 'mt-2 flex items-center gap-2';
const CONFIRM =
'flex h-10 w-10 flex-none items-center justify-center rounded-[12px] bg-m-act text-m-actfg disabled:opacity-40';
const CHIPS = 'mt-[6px] flex flex-wrap gap-1';
const CHIP =
'inline-flex max-w-full items-center gap-1 rounded-full border border-[color:var(--m-faint)] px-2 py-[2px] font-geist text-caption font-semibold text-m-muted';
/**
* The tags of the place form on the phone: its label, every tag on offer as a chip to
* switch on or off, and a field that adds a new one to the trip. The state is
* usePlaceTags', run by the sheet; this is its markup.
*/
export function PlTagPicker({ tags, t }: { tags: PlaceTagsField; t: Translate }) {
return (
<>
<Eyebrow className={LABEL}>{t('places.tags')}</Eyebrow>
<div role="group" aria-label={t('places.tags')} className={PICKER}>
{tags.options.map((tag) => (
<MChip key={tag.id} pressable active={tag.on} onClick={() => tags.toggle(tag.id)}>
<TagIcon
size={12}
strokeWidth={2.2}
className="flex-none"
style={{ color: tag.on ? undefined : tag.color }}
/>
{tag.name}
</MChip>
))}
</div>
<div className={NEW_TAG}>
<input
type="text"
value={tags.name}
onChange={(e) => tags.setName(e.target.value)}
onKeyDown={tags.handleNameKey}
maxLength={TRIP_TAG_NAME_MAX}
aria-label={t('places.newTag')}
placeholder={t('places.newTag')}
className={FIELD_CLS}
/>
<button
type="button"
onClick={() => void tags.addNew()}
disabled={!tags.canAdd}
aria-label={t('places.addTag')}
className={CONFIRM}
>
<Check size={15} strokeWidth={2.4} />
</button>
</div>
</>
);
}
/** The tags a place carries, under its category on the phone's place sheet; nothing for a place without any. */
export function PlTagChips({ tags }: { tags: Place['tags'] }) {
const shown = tagChoices(tags);
if (shown.length === 0) return null;
return (
<div className={CHIPS}>
{shown.map((tag) => (
<span key={tag.id} className={CHIP}>
<TagIcon size={10} strokeWidth={2} className="flex-none" style={{ color: tag.color }} />
<span dir="auto" className="truncate">
{tag.name}
</span>
</span>
))}
</div>
);
}
+33 -2
View File
@@ -1,4 +1,4 @@
// FE-REPO-PLACE-001 to FE-REPO-PLACE-013, FE-REPO-PLACE-030
// FE-REPO-PLACE-001 to FE-REPO-PLACE-013, FE-REPO-PLACE-030 to FE-REPO-PLACE-032
// Offline write paths (mutation queue + optimistic Dexie rows) and the bulk
// online paths, which tests/unit/repo/placeRepo.test.ts does not touch.
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
@@ -8,7 +8,7 @@ import { server } from '../../tests/helpers/msw/server'
import { placeRepo } from './placeRepo'
import { offlineDb, clearAll } from '../db/offlineDb'
import type { QueuedMutation } from '../db/offlineDb'
import { buildPlace } from '../../tests/helpers/factories'
import { buildPlace, buildTag } from '../../tests/helpers/factories'
function setOnline(v: boolean): void {
Object.defineProperty(navigator, 'onLine', { value: v, writable: true, configurable: true })
@@ -66,6 +66,37 @@ describe('placeRepo — field origins offline', () => {
})
})
describe('placeRepo — tags offline', () => {
it('FE-REPO-PLACE-031: the queued body names the tags by id, the optimistic row carries the tags themselves', async () => {
const monument = buildTag({ id: 7, trip_id: 3, name: 'Monument' })
await offlineDb.tripTags.put({ tripId: 3, tags: [monument] })
const { place } = await placeRepo.create(3, { name: 'Belem Tower', tags: [7, 99] })
// The trip's tag as the device knows it; an id it does not know shows nothing until the sync.
expect(place.tags).toEqual([monument])
expect((await offlineDb.places.get(place.id))?.tags).toEqual([monument])
expect((await queue())[0].body).toEqual({ name: 'Belem Tower', tags: [7, 99] })
})
it('FE-REPO-PLACE-032: an update keeps a tag of the place the trip does not list, and a write without tags leaves them', async () => {
const zone = buildTag({ id: 8, trip_id: 3, name: 'Zone' })
await offlineDb.tripTags.put({ tripId: 3, tags: [zone] })
const personal = { id: 50, name: 'Hidden gem', color: '#f59e0b' }
await offlineDb.places.put(buildPlace({ id: 12, trip_id: 3, tags: [personal] }))
const tagged = await placeRepo.update(3, 12, { tags: [50, 8] })
expect(tagged.place.tags).toEqual([personal, zone])
const renamed = await placeRepo.update(3, 12, { name: 'Renamed' })
expect(renamed.place.tags).toEqual([personal, zone])
const cleared = await placeRepo.update(3, 12, { tags: [] })
expect(cleared.place.tags).toEqual([])
expect((await offlineDb.places.get(12))?.tags).toEqual([])
})
})
describe('placeRepo.update — offline', () => {
it('FE-REPO-PLACE-003: merges into the cached row and sends the concurrency token', async () => {
await offlineDb.places.put(buildPlace({ id: 90, trip_id: 3, name: 'Old', updated_at: '2026-01-01T00:00:00.000Z' }))
+11 -6
View File
@@ -1,4 +1,5 @@
import { placesApi } from '../api/client'
import { cachedTripTags } from '../db/cacheTripTags'
import { offlineDb, replaceTripRows, upsertPlaces } from '../db/offlineDb'
import { mutationQueue, generateUUID, nextTempId } from '../sync/mutationQueue'
import { isEffectivelyOffline } from '../sync/networkMode'
@@ -8,11 +9,15 @@ import type { Place } from '../types'
/**
* What of a write the optimistic row keeps. `fieldOrigins` says which fields the
* user typed; it travels in the queued body for the server's origin tracking and
* is no column of the place.
* is no column of the place. `tags` names the place's tags by id, while a row
* carries the tags themselves, so the row gets the ones the device knows by those
* ids: the trip's cached ones, and those the place had before.
*/
function placeRow(data: Record<string, unknown>): Record<string, unknown> {
const { fieldOrigins: _origins, ...row } = data
return row
async function placeRow(tripId: number, data: Record<string, unknown>, before?: Place): Promise<Record<string, unknown>> {
const { fieldOrigins: _origins, tags, ...row } = data
if (!Array.isArray(tags)) return row
const known = [...(await cachedTripTags(tripId)), ...(before?.tags ?? [])]
return { ...row, tags: tags.flatMap(id => known.find(tag => tag.id === id) ?? []) }
}
export const placeRepo = {
@@ -35,7 +40,7 @@ export const placeRepo = {
if (isEffectivelyOffline()) {
const tempId = nextTempId()
const tempPlace: Place = {
...(placeRow(data) as Partial<Place>),
...(await placeRow(Number(tripId), data) as Partial<Place>),
id: tempId,
trip_id: Number(tripId),
name: (data.name as string) ?? 'New place',
@@ -66,7 +71,7 @@ export const placeRepo = {
// a row without it is invisible and never cleaned up.
const optimistic: Place = {
...(existing ?? {} as Place),
...(placeRow(data) as Partial<Place>),
...(await placeRow(Number(tripId), data, existing) as Partial<Place>),
id: Number(id),
trip_id: Number(tripId),
}
+96
View File
@@ -0,0 +1,96 @@
// FE-REPO-TRIPTAG-001 to FE-REPO-TRIPTAG-007: the tags a trip owns, read through to the
// server and kept on this device, read from there without a connection, and added
// online only.
import 'fake-indexeddb/auto';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildTag } from '../../tests/helpers/factories';
import { clearAll, clearTripData, offlineDb } from '../db/offlineDb';
import { isEffectivelyOffline } from '../sync/networkMode';
import { OnlineOnlyError } from './onlineOnly';
import { tripTagRepo } from './tripTagRepo';
const { client } = vi.hoisted(() => ({ client: { get: vi.fn(), post: vi.fn() } }));
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: vi.fn(() => false) }));
vi.mock('../api/client', () => ({ default: client, apiClient: client }));
const monument = buildTag({ id: 7, trip_id: 4, name: 'Monument' });
const zone = buildTag({ id: 8, trip_id: 4, name: 'Zone' });
/** An axios failure that never reached the server. */
const networkError = () => Object.assign(new Error('Network Error'), { isAxiosError: true });
beforeEach(async () => {
await clearAll();
vi.clearAllMocks();
vi.mocked(isEffectivelyOffline).mockReturnValue(false);
});
describe('tripTagRepo', () => {
it('FE-REPO-TRIPTAG-001: reads the tags of the trip and keeps them on this device', async () => {
client.get.mockResolvedValue({ data: { tags: [monument, zone] } });
expect(await tripTagRepo.list('4')).toEqual({ tags: [monument, zone] });
expect(client.get).toHaveBeenCalledWith('/trips/4/tags');
expect((await offlineDb.tripTags.get(4))?.tags).toEqual([monument, zone]);
});
it('FE-REPO-TRIPTAG-002: without a connection answers what the device last read, and nothing for a trip it never read', async () => {
await offlineDb.tripTags.put({ tripId: 4, tags: [monument] });
vi.mocked(isEffectivelyOffline).mockReturnValue(true);
expect(await tripTagRepo.list(4)).toEqual({ tags: [monument] });
expect(await tripTagRepo.list(5)).toEqual({ tags: [] });
expect(client.get).not.toHaveBeenCalled();
});
it('FE-REPO-TRIPTAG-003: a request that never reached the server falls back to the device, a refusal does not', async () => {
await offlineDb.tripTags.put({ tripId: 4, tags: [zone] });
client.get.mockRejectedValueOnce(networkError());
expect(await tripTagRepo.list(4)).toEqual({ tags: [zone] });
const refused = Object.assign(new Error('Forbidden'), { isAxiosError: true, response: { status: 403 } });
client.get.mockRejectedValueOnce(refused);
await expect(tripTagRepo.list(4)).rejects.toBe(refused);
});
it('FE-REPO-TRIPTAG-004: a new tag is sent to the trip and joins the list on this device, by name', async () => {
await offlineDb.tripTags.put({ tripId: 4, tags: [zone] });
client.post.mockResolvedValue({ data: { tag: monument } });
expect(await tripTagRepo.create(4, { name: 'Monument', color: '#6366f1' })).toEqual(monument);
expect(client.post).toHaveBeenCalledWith('/trips/4/tags', { name: 'Monument', color: '#6366f1' });
expect((await offlineDb.tripTags.get(4))?.tags.map((tag) => tag.name)).toEqual(['Monument', 'Zone']);
});
it('FE-REPO-TRIPTAG-005: the tag the trip has already under that name is not kept twice', async () => {
await offlineDb.tripTags.put({ tripId: 4, tags: [monument, zone] });
client.post.mockResolvedValue({ data: { tag: zone } });
await tripTagRepo.create(4, { name: 'zone' });
expect((await offlineDb.tripTags.get(4))?.tags.map((tag) => tag.id)).toEqual([7, 8]);
});
it('FE-REPO-TRIPTAG-006: adding a tag needs a connection, and says so before anything is sent', async () => {
vi.mocked(isEffectivelyOffline).mockReturnValue(true);
await expect(tripTagRepo.create(4, { name: 'Monument' })).rejects.toBeInstanceOf(OnlineOnlyError);
expect(client.post).not.toHaveBeenCalled();
expect(await offlineDb.tripTags.get(4)).toBeUndefined();
});
it('FE-REPO-TRIPTAG-007: the tags kept for a trip go with it, and another trip keeps its own', async () => {
await offlineDb.tripTags.bulkPut([
{ tripId: 4, tags: [monument] },
{ tripId: 5, tags: [zone] },
]);
await clearTripData(4);
expect(await offlineDb.tripTags.get(4)).toBeUndefined();
expect((await offlineDb.tripTags.get(5))?.tags).toEqual([zone]);
});
});
+37
View File
@@ -0,0 +1,37 @@
import type { Tag, TripTagCreateRequest, TripTagListResponse } from '@trek/shared';
import { tripTagsApi } from '../api/tripTags';
import { cachedTripTags, cacheTripTags } from '../db/cacheTripTags';
import { withTripTag } from '../utils/placeTags';
import { requireOnline } from './onlineOnly';
import { onlineThenCache } from './withOfflineFallback';
/**
* The tags a trip owns. Reading them works offline, from the list the device last
* read. Adding one is online only, on purpose: the place it is then put on is saved
* with the tag's id, and a queued place cannot name a tag the server has not made.
* Putting a tag the trip already has on a place is the place's own write, which the
* offline queue holds like any other.
*/
export const tripTagRepo = {
async list(tripId: number | string): Promise<TripTagListResponse> {
const id = Number(tripId);
return onlineThenCache(
async () => {
const result = await tripTagsApi.list(id);
await cacheTripTags(id, result.tags);
return result;
},
async () => ({ tags: await cachedTripTags(id) })
);
},
/** The new tag, or the one the trip already has under that name. */
async create(tripId: number | string, body: TripTagCreateRequest): Promise<Tag> {
requireOnline();
const id = Number(tripId);
const { tag } = await tripTagsApi.create(id, body);
await cacheTripTags(id, withTripTag(await cachedTripTags(id), tag));
return tag;
},
};
@@ -719,6 +719,13 @@ export const STORE_REFRESHES: Partial<Record<TrekWsTripEventName, StoreRefresh>>
const tripId = get().trip?.id
if (tripId) void get().reloadPackingItems(tripId)
}),
// A tag of the trip added, renamed or deleted elsewhere: the event says only
// that the list changed, and the read takes a rename or a delete into the
// places that carry the tag.
'tripTags:changed': get => refreshOncePerBurst('tripTags', () => {
const tripId = get().trip?.id
if (tripId) void get().loadTripTags(tripId)
}),
}
/**
@@ -0,0 +1,135 @@
// FE-STORE-TRIPTAGS-001 to FE-STORE-TRIPTAGS-006: the tags of the open trip in the store,
// and what a tag renamed or deleted elsewhere does to the places that carry it.
import 'fake-indexeddb/auto';
import { http, HttpResponse } from 'msw';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { buildAssignment, buildPlace, buildTag, buildTrip } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores } from '../../../tests/helpers/store';
import { clearAll } from '../../db/offlineDb';
import { OnlineOnlyError } from '../../repo/onlineOnly';
import { useTripStore } from '../tripStore';
const monument = buildTag({ id: 7, trip_id: 5, name: 'Monument', color: '#6366f1' });
const zone = buildTag({ id: 8, trip_id: 5, name: 'Zone', color: '#10b981' });
function setOnline(online: boolean): void {
Object.defineProperty(navigator, 'onLine', { value: online, writable: true, configurable: true });
}
/** What the server lists as the tags of trip 5. */
function serve(tags: unknown[]): void {
server.use(http.get('/api/trips/5/tags', () => HttpResponse.json({ tags })));
}
beforeEach(async () => {
await clearAll();
resetAllStores();
setOnline(true);
useTripStore.setState({ trip: buildTrip({ id: 5 }) });
});
afterEach(() => {
setOnline(true);
});
describe('tripTagsSlice', () => {
it('FE-STORE-TRIPTAGS-001: reads the tags of the open trip, and drops an answer for a trip that is no longer open', async () => {
serve([monument, zone]);
await useTripStore.getState().loadTripTags(5);
expect(useTripStore.getState().tripTags.map((tag) => tag.name)).toEqual(['Monument', 'Zone']);
server.use(
http.get('/api/trips/6/tags', () => HttpResponse.json({ tags: [buildTag({ id: 9, name: 'Other trip' })] }))
);
await useTripStore.getState().loadTripTags(6);
expect(useTripStore.getState().tripTags.map((tag) => tag.name)).toEqual(['Monument', 'Zone']);
});
it('FE-STORE-TRIPTAGS-002: a tag renamed or deleted elsewhere is taken into the places and visits that carry it', async () => {
const tagged = buildPlace({
id: 21,
trip_id: 5,
tags: [
{ id: 7, name: 'Monument', color: '#6366f1' },
{ id: 8, name: 'Zone' },
],
});
const untouched = buildPlace({ id: 22, trip_id: 5, tags: [{ id: 50, name: 'Hidden gem' }] });
const visit = buildAssignment({ id: 31, place: { ...tagged } });
const otherVisit = buildAssignment({ id: 32, place: { ...untouched } });
useTripStore.setState({
tripTags: [monument, zone],
places: [tagged, untouched],
assignments: { '11': [visit, otherVisit] },
placesCategoryFilter: new Set(['4', 'tag:7', 'tag:8']),
});
serve([{ ...monument, name: 'Landmark', color: '#ef4444' }]);
await useTripStore.getState().loadTripTags(5);
const state = useTripStore.getState();
expect(state.tripTags.map((tag) => tag.name)).toEqual(['Landmark']);
expect(state.places[0].tags).toEqual([{ id: 7, name: 'Landmark', color: '#ef4444' }]);
expect(state.assignments['11'][0].place.tags).toEqual([{ id: 7, name: 'Landmark', color: '#ef4444' }]);
// What carries none of the changed tags is the same object as before.
expect(state.places[1]).toBe(untouched);
expect(state.assignments['11'][1]).toBe(otherVisit);
// The deleted tag no longer filters; the renamed one and the category still do.
expect([...state.placesCategoryFilter]).toEqual(['4', 'tag:7']);
});
it('FE-STORE-TRIPTAGS-003: a reading that changes no tag on a place leaves the places and the filter as they are', async () => {
const tagged = buildPlace({ id: 21, trip_id: 5, tags: [{ id: 7, name: 'Monument', color: '#6366f1' }] });
const filter = new Set(['tag:7']);
const assignments = { '11': [buildAssignment({ id: 31, place: { ...tagged } })] };
useTripStore.setState({ tripTags: [monument], places: [tagged], assignments, placesCategoryFilter: filter });
serve([monument, zone]);
await useTripStore.getState().loadTripTags(5);
const state = useTripStore.getState();
expect(state.tripTags).toHaveLength(2);
expect(state.places[0]).toBe(tagged);
expect(state.assignments).toBe(assignments);
expect(state.placesCategoryFilter).toBe(filter);
});
it('FE-STORE-TRIPTAGS-004: a reading the server refuses keeps the tags on screen', async () => {
useTripStore.setState({ tripTags: [monument] });
server.use(http.get('/api/trips/5/tags', () => HttpResponse.json({ error: 'Trip not found' }, { status: 404 })));
await useTripStore.getState().loadTripTags(5);
expect(useTripStore.getState().tripTags).toEqual([monument]);
});
it('FE-STORE-TRIPTAGS-005: a new tag joins the list by name, and the one the trip has already is not listed twice', async () => {
useTripStore.setState({ tripTags: [zone] });
let sent: unknown;
server.use(
http.post('/api/trips/5/tags', async ({ request }) => {
sent = await request.json();
return HttpResponse.json({ tag: monument }, { status: 201 });
})
);
expect(await useTripStore.getState().addTripTag(5, { name: 'Monument', color: '#6366f1' })).toEqual(monument);
expect(sent).toEqual({ name: 'Monument', color: '#6366f1' });
expect(useTripStore.getState().tripTags.map((tag) => tag.name)).toEqual(['Monument', 'Zone']);
await useTripStore.getState().addTripTag(5, { name: 'monument' });
expect(useTripStore.getState().tripTags.map((tag) => tag.id)).toEqual([7, 8]);
});
it('FE-STORE-TRIPTAGS-006: without a connection a new tag is refused and the list stays; another trip starts without tags', async () => {
useTripStore.setState({ tripTags: [zone] });
setOnline(false);
await expect(useTripStore.getState().addTripTag(5, { name: 'Monument' })).rejects.toBeInstanceOf(OnlineOnlyError);
expect(useTripStore.getState().tripTags).toEqual([zone]);
useTripStore.getState().resetTrip();
expect(useTripStore.getState().tripTags).toEqual([]);
});
});
+64
View File
@@ -0,0 +1,64 @@
import type { Tag, TripTagCreateRequest } from '@trek/shared';
import type { StoreApi } from 'zustand';
import { tripTagRepo } from '../../repo/tripTagRepo';
import { withoutTagFilters } from '../../utils/placesFilter';
import { tagChanges, withTagChanges, withTripTag } from '../../utils/placeTags';
import type { TripStoreState } from '../tripStore';
type SetState = StoreApi<TripStoreState>['setState'];
type GetState = StoreApi<TripStoreState>['getState'];
export interface TripTagsSlice {
/** The tags the open trip owns, the same list for everybody on it (`tags` holds the user's personal ones). */
tripTags: Tag[];
/** Reads the trip's tags again: on a reconnect, and when they changed elsewhere (`tripTags:changed`). */
loadTripTags: (tripId: number | string) => Promise<void>;
/** Adds a tag to the trip, or hands back the one it already has under that name. Needs a connection. */
addTripTag: (tripId: number | string, data: TripTagCreateRequest) => Promise<Tag>;
}
/**
* The store once the trip's tags were read again. A place carries a copy of each of
* its tags, so a tag renamed, recoloured or deleted elsewhere is taken into the places
* and into the visits that embed them, and a deleted one leaves the category filter.
*/
function withTripTags(state: TripStoreState, tags: Tag[]): Partial<TripStoreState> {
const changes = tagChanges(state.tripTags, tags);
if (!changes) return { tripTags: tags };
return {
tripTags: tags,
places: state.places.map((place) => withTagChanges(place, changes)),
assignments: Object.fromEntries(
Object.entries(state.assignments).map(([dayId, visits]) => [
dayId,
visits.map((visit) => {
const place = visit.place && withTagChanges(visit.place, changes);
return place === visit.place ? visit : { ...visit, place };
}),
])
),
placesCategoryFilter: withoutTagFilters(state.placesCategoryFilter, changes.removed),
};
}
export const createTripTagsSlice = (set: SetState, get: GetState): TripTagsSlice => ({
tripTags: [],
loadTripTags: async (tripId) => {
try {
const { tags } = await tripTagRepo.list(tripId);
// Another trip was opened while the answer was on its way.
if (String(get().trip?.id) !== String(tripId)) return;
set((state) => withTripTags(state, tags));
} catch {
// The tags on screen stay; the next reload or reconnect reads them again.
}
},
addTripTag: async (tripId, data) => {
const tag = await tripTagRepo.create(tripId, data);
set((state) => ({ tripTags: withTripTag(state.tripTags, tag) }));
return tag;
},
});
+14 -3
View File
@@ -10,6 +10,7 @@ import { todoRepo } from '../repo/todoRepo'
import { budgetRepo } from '../repo/budgetRepo'
import { reservationRepo } from '../repo/reservationRepo'
import { fileRepo } from '../repo/fileRepo'
import { tripTagRepo } from '../repo/tripTagRepo'
import { isEffectivelyOnline } from '../sync/networkMode'
import { createPlacesSlice } from './slices/placesSlice'
import { createAssignmentsSlice } from './slices/assignmentsSlice'
@@ -20,6 +21,7 @@ import { createTodoSlice } from './slices/todoSlice'
import { createBudgetSlice } from './slices/budgetSlice'
import { createReservationsSlice } from './slices/reservationsSlice'
import { createFilesSlice } from './slices/filesSlice'
import { createTripTagsSlice } from './slices/tripTagsSlice'
import { handleRemoteEvent } from './slices/remoteEventHandler'
import type {
Trip, Day, Place, Assignment, DayNote, PackingItem, TodoItem,
@@ -36,6 +38,7 @@ import type { TodoSlice } from './slices/todoSlice'
import type { BudgetSlice } from './slices/budgetSlice'
import type { ReservationsSlice } from './slices/reservationsSlice'
import type { FilesSlice } from './slices/filesSlice'
import type { TripTagsSlice } from './slices/tripTagsSlice'
import type { PlacesRatingFloor } from '../utils/placesFilter'
/** The part of the world the trip's plan map shows, as its last move left it. */
@@ -63,7 +66,8 @@ export interface TripStoreState
TodoSlice,
BudgetSlice,
ReservationsSlice,
FilesSlice {
FilesSlice,
TripTagsSlice {
trip: Trip | null
days: Day[]
places: Place[]
@@ -152,7 +156,7 @@ export const useTripStore = create<TripStoreState>((set, get) => ({
// Clear every trip-scoped slice so switching trips (or losing access to one)
// can never leave a previous trip's data visible. Global tags/categories are
// left intact. Called at the top of loadTrip.
// left intact; the trip's own tags go with it. Called at the top of loadTrip.
resetTrip: () => set({
trip: null,
days: [],
@@ -164,6 +168,7 @@ export const useTripStore = create<TripStoreState>((set, get) => ({
budgetItems: [],
files: [],
reservations: [],
tripTags: [],
selectedDayId: null,
placesFilter: 'all',
placesCategoryFilter: new Set<string>(),
@@ -179,7 +184,7 @@ export const useTripStore = create<TripStoreState>((set, get) => ({
get().resetTrip()
set({ isLoading: true, error: null })
try {
const [tripData, daysData, placesData, packingData, todoData, budgetData, reservationsData, filesData, tagsData, categoriesData] = await Promise.all([
const [tripData, daysData, placesData, packingData, todoData, budgetData, reservationsData, filesData, tagsData, categoriesData, tripTagsData] = await Promise.all([
tripRepo.get(tripId),
dayRepo.list(tripId),
placeRepo.list(tripId),
@@ -197,6 +202,9 @@ export const useTripStore = create<TripStoreState>((set, get) => ({
isEffectivelyOnline()
? categoriesApi.list().catch(() => offlineDb.categories.toArray().then(categories => ({ categories })))
: offlineDb.categories.toArray().then(categories => ({ categories })),
// The trip's own tags, non-fatal like the three above: without them the
// places still show the tags they carry.
tripTagRepo.list(tripId).catch(() => ({ tags: [] as Tag[] })),
])
const assignmentsMap: AssignmentsMap = {}
@@ -219,6 +227,7 @@ export const useTripStore = create<TripStoreState>((set, get) => ({
files: filesData.files,
tags: tagsData.tags,
categories: categoriesData.categories,
tripTags: tripTagsData.tags,
isLoading: false,
})
} catch (err: unknown) {
@@ -241,6 +250,7 @@ export const useTripStore = create<TripStoreState>((set, get) => ({
get().loadBudgetItems(tripId),
get().loadReservations(tripId),
get().loadFiles(tripId),
get().loadTripTags(tripId),
])
// Accommodations live in planner-local state, not this store — nudge the
// planner to reload them too (e.g. a trip date change made while offline).
@@ -344,4 +354,5 @@ export const useTripStore = create<TripStoreState>((set, get) => ({
...createBudgetSlice(set, get),
...createReservationsSlice(set, get),
...createFilesSlice(set, get),
...createTripTagsSlice(set, get),
}))
+9
View File
@@ -1,5 +1,6 @@
import { roadtripPreferencesRepo } from '../repo/roadtripPreferencesRepo'
import { tourRepo } from '../repo/tourRepo'
import { tripTagRepo } from '../repo/tripTagRepo'
/**
* Trip sync manager — seeds Dexie with trip data for offline use.
*
@@ -155,6 +156,14 @@ async function syncTrip(tripId: number): Promise<void> {
await roadtripPreferencesRepo.read(tripId).catch(() => { /* optional cache */ })
}
// The trip's own tags, which the repo keeps as it reads them. Never fatal either.
try {
await tripTagRepo.list(tripId)
} catch {
// An optional cache: the places carry the tags they have, so without this
// list only the unused ones are missing offline, until the next sync.
}
// Tours, the same way: optional, and never fatal. Without them every Tour
// reads as a plain place offline. Asked only while the addon is on, so a
// sync of many trips does not spend a refused request on each.
+105
View File
@@ -0,0 +1,105 @@
import { describe, expect, it } from 'vitest';
import { buildPlace, buildTag } from '../../tests/helpers/factories';
import { nextTagColor, placeTagIds, tagChanges, tagChoices, withTagChanges, withTripTag } from './placeTags';
describe('placeTags', () => {
it('FE-UTIL-PLTAGS-001: offers each tag once and by name, as the first list that has it says', () => {
const zone = buildTag({ id: 2, name: 'Zone', color: '#10b981' });
const monument = buildTag({ id: 1, name: 'Monument', color: '#6366f1' });
const carried = [
{ id: 2, name: 'Zone (old name)', color: '#000000' },
{ id: 9, name: 'Hidden gem', color: '#f97316' },
];
expect(tagChoices([zone, monument], carried, undefined)).toEqual([
{ id: 9, name: 'Hidden gem', color: '#f97316' },
{ id: 1, name: 'Monument', color: '#6366f1' },
{ id: 2, name: 'Zone', color: '#10b981' },
]);
expect(tagChoices()).toEqual([]);
expect(tagChoices(undefined)).toEqual([]);
});
it('FE-UTIL-PLTAGS-002: leaves out a copy that cannot be shown and a colour that is no plain hex value', () => {
const choices = tagChoices([
{ name: 'No id' },
{ id: 3 },
{ id: 4, name: 'Painted', color: 'url(https://example.test/pixel)' },
{ id: 5, name: 'Plain' },
]);
expect(choices).toEqual([
{ id: 4, name: 'Painted', color: undefined },
{ id: 5, name: 'Plain', color: undefined },
]);
expect(choices[0].color).toBeUndefined();
});
it('FE-UTIL-PLTAGS-003: names the tags of a place by id, each once, whatever else the copy lacks', () => {
expect(placeTagIds([{ id: 4, name: 'A' }, { id: 5 }, { name: 'No id' }, { id: 4, name: 'A' }])).toEqual([4, 5]);
expect(placeTagIds(undefined)).toEqual([]);
});
it('FE-UTIL-PLTAGS-004: colours new tags by turn', () => {
const first = nextTagColor([]);
const second = nextTagColor([buildTag()]);
expect(first).toMatch(/^#[0-9a-f]{6}$/);
expect(second).toMatch(/^#[0-9a-f]{6}$/);
expect(second).not.toBe(first);
// Past the last colour it starts over.
expect(nextTagColor(Array.from({ length: 8 }, () => buildTag()))).toBe(first);
});
it('FE-UTIL-PLTAGS-005: adds a tag to the list by name, and replaces the one of the same id', () => {
const monument = buildTag({ id: 1, name: 'Monument' });
const zone = buildTag({ id: 2, name: 'Zone' });
const added = withTripTag([zone], monument);
expect(added.map((tag) => tag.name)).toEqual(['Monument', 'Zone']);
const renamed = withTripTag(added, { ...zone, name: 'Area' });
expect(renamed.map((tag) => [tag.id, tag.name])).toEqual([
[2, 'Area'],
[1, 'Monument'],
]);
});
it('FE-UTIL-PLTAGS-006: tells which tags were renamed, recoloured or deleted between two readings', () => {
const monument = buildTag({ id: 1, name: 'Monument', color: '#6366f1' });
const zone = buildTag({ id: 2, name: 'Zone', color: '#10b981' });
const walk = buildTag({ id: 3, name: 'Walk', color: '#f97316' });
expect(tagChanges([monument, zone], [monument, zone])).toBeNull();
// A new tag is on no place yet, so it changes nothing there.
expect(tagChanges([monument], [monument, zone])).toBeNull();
const changes = tagChanges(
[monument, zone, walk],
[
{ ...monument, name: 'Landmark' },
{ ...walk, color: '#ef4444' },
]
);
expect([...(changes?.removed ?? [])]).toEqual([2]);
expect([...(changes?.renamed.keys() ?? [])]).toEqual([1, 3]);
});
it('FE-UTIL-PLTAGS-007: takes the changes into the copies a place carries, and leaves an untouched place alone', () => {
const monument = buildTag({ id: 1, name: 'Monument', color: '#6366f1' });
const zone = buildTag({ id: 2, name: 'Zone', color: '#10b981' });
const changes = tagChanges([monument, zone], [{ ...monument, name: 'Landmark', color: '#ef4444' }]);
if (!changes) throw new Error('expected changes');
const place = buildPlace({
tags: [
{ id: 1, name: 'Monument', color: '#6366f1', created_at: '2026-01-01' },
{ id: 2, name: 'Zone' },
{ id: 9, name: 'Own' },
{ name: 'No id' },
],
});
expect(withTagChanges(place, changes).tags).toEqual([
{ id: 1, name: 'Landmark', color: '#ef4444', created_at: '2026-01-01' },
{ id: 9, name: 'Own' },
{ name: 'No id' },
]);
const untouched = buildPlace({ tags: [{ id: 9, name: 'Own' }] });
expect(withTagChanges(untouched, changes)).toBe(untouched);
const untagged = buildPlace();
expect(withTagChanges(untagged, changes)).toBe(untagged);
});
});
+80
View File
@@ -0,0 +1,80 @@
import type { Place, Tag } from '@trek/shared';
import { safeHexColor } from './safeColor';
/** A tag as a place carries it: the compact row of a place list, where every field is optional. */
type PlaceTag = NonNullable<Place['tags']>[number];
/** A tag as a picker, a filter row and a chip show it. */
export interface TagChoice {
id: number;
name: string;
/** Absent for a colour that is no plain hex value: the chip then keeps the colour of its text. */
color?: string;
}
/**
* The tags of the given lists, each once and by name, as far as they can be shown. A tag
* reads as the first list that has it says, so with the trip's own tags ahead of the
* copies a place carries, the name and the colour are the current ones.
*/
export function tagChoices(...lists: (readonly PlaceTag[] | undefined)[]): TagChoice[] {
const choices = new Map<number, TagChoice>();
for (const tag of lists.flatMap((list) => list ?? [])) {
if (tag.id == null || !tag.name || choices.has(tag.id)) continue;
choices.set(tag.id, { id: tag.id, name: tag.name, color: safeHexColor(tag.color, '') || undefined });
}
return [...choices.values()].sort((a, b) => a.name.localeCompare(b.name));
}
/** The ids of the tags a place carries, as a write names them. */
export function placeTagIds(carried: readonly PlaceTag[] | undefined): number[] {
return [...new Set((carried ?? []).flatMap((tag) => (tag.id == null ? [] : [tag.id])))];
}
// What a new tag is coloured with, one after the other, so the tags of a trip tell apart at a glance.
const NEW_TAG_COLORS = ['#6366f1', '#ec4899', '#f97316', '#10b981', '#06b6d4', '#8b5cf6', '#ef4444', '#f59e0b'];
/** The colour the next new tag of a trip gets. */
export function nextTagColor(tripTags: readonly unknown[]): string {
return NEW_TAG_COLORS[tripTags.length % NEW_TAG_COLORS.length];
}
/** The trip's tags with one more, or with the one of that id as it is now, by name as the server lists them. */
export function withTripTag(tripTags: readonly Tag[], tag: Tag): Tag[] {
return [...tripTags.filter((other) => other.id !== tag.id), tag].sort((a, b) => a.name.localeCompare(b.name));
}
/** What changed between two readings of a trip's tags, as far as the copies on its places go. */
interface TagChanges {
/** The tags that are gone. */
removed: ReadonlySet<number>;
/** The tags with another name or colour, as they are now. */
renamed: ReadonlyMap<number, Tag>;
}
/** Null when no tag was renamed, recoloured or deleted between the two readings. */
export function tagChanges(before: readonly Tag[], after: readonly Tag[]): TagChanges | null {
const now = new Map(after.map((tag) => [tag.id, tag]));
const removed = new Set<number>();
const renamed = new Map<number, Tag>();
for (const old of before) {
const tag = now.get(old.id);
if (!tag) removed.add(old.id);
else if (tag.name !== old.name || tag.color !== old.color) renamed.set(tag.id, tag);
}
return removed.size > 0 || renamed.size > 0 ? { removed, renamed } : null;
}
/** A place with its tags as the trip has them now; the same object when none of its tags changed. */
export function withTagChanges<P extends { tags?: PlaceTag[] }>(place: P, changes: TagChanges): P {
const touched = (tag: PlaceTag) => tag.id != null && (changes.removed.has(tag.id) || changes.renamed.has(tag.id));
if (!place.tags?.some(touched)) return place;
const tags = place.tags
.filter((tag) => tag.id == null || !changes.removed.has(tag.id))
.map((tag) => {
const now = tag.id == null ? undefined : changes.renamed.get(tag.id);
return now ? { ...tag, name: now.name, color: now.color } : tag;
});
return { ...place, tags };
}
+41 -1
View File
@@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest'
import { buildPlace } from '../../tests/helpers/factories'
import {
RATING_FLOORS, countActivePlacesFilters, matchesCategoryFilter, matchesPlacesFilter,
matchesPoolFilter, matchesRatingFloor,
matchesPoolFilter, matchesRatingFloor, tagFilterKey, withoutTagFilters,
} from './placesFilter'
const NONE = new Set<string>()
@@ -67,4 +67,44 @@ describe('placesFilter', () => {
expect(countActivePlacesFilters({ filter: 'all', categoryFilters: new Set(['1', '2']), ratingFilter: 'all' })).toBe(1)
expect(countActivePlacesFilters({ filter: 'tracks', categoryFilters: new Set(['1']), ratingFilter: 3 })).toBe(3)
})
it('FE-UTIL-PLFILTER-008: a ticked tag keeps the places that carry it, whatever their category', () => {
const monument = buildPlace({ category_id: 4, tags: [{ id: 7, name: 'Monument' }, { id: 8, name: 'Zone' }] })
const plain = buildPlace({ category_id: 4 })
const bare = buildPlace({ category_id: null, tags: [{ id: 8, name: 'Zone' }] })
expect(tagFilterKey(7)).toBe('tag:7')
expect(matchesCategoryFilter(monument, new Set(['tag:7']))).toBe(true)
expect(matchesCategoryFilter(plain, new Set(['tag:7']))).toBe(false)
expect(matchesCategoryFilter(bare, new Set(['tag:7']))).toBe(false)
// Several ticked tags: carrying one of them is enough.
expect(matchesCategoryFilter(bare, new Set(['tag:7', 'tag:8']))).toBe(true)
// A copy without an id (a row still being written) matches no tag.
expect(matchesCategoryFilter(buildPlace({ tags: [{ name: 'Zone' }] }), new Set(['tag:8']))).toBe(false)
})
it('FE-UTIL-PLFILTER-009: categories and tags ticked together both have to hold', () => {
const monument = buildPlace({ category_id: 4, tags: [{ id: 7, name: 'Monument' }] })
const other = buildPlace({ category_id: 5, tags: [{ id: 7, name: 'Monument' }] })
const untagged = buildPlace({ category_id: 4 })
const bare = buildPlace({ category_id: null, tags: [{ id: 7, name: 'Monument' }] })
const both = new Set(['4', 'tag:7'])
expect(matchesCategoryFilter(monument, both)).toBe(true)
expect(matchesCategoryFilter(other, both)).toBe(false)
expect(matchesCategoryFilter(untagged, both)).toBe(false)
expect(matchesCategoryFilter(bare, both)).toBe(false)
expect(matchesCategoryFilter(bare, new Set(['uncategorized', 'tag:7']))).toBe(true)
// The whole filter follows: the tag narrows the list and the map alike.
const state = { filter: 'all', categoryFilters: both, ratingFilter: 'all' as const }
expect(matchesPlacesFilter(monument, state, { plannedIds: null })).toBe(true)
expect(matchesPlacesFilter(untagged, state, { plannedIds: null })).toBe(false)
expect(countActivePlacesFilters(state)).toBe(1)
})
it('FE-UTIL-PLFILTER-010: a tag that is gone leaves the filter, and a filter without it stays the same set', () => {
const filters = new Set(['4', 'tag:7', 'tag:8'])
expect([...withoutTagFilters(filters, [7])]).toEqual(['4', 'tag:8'])
expect([...withoutTagFilters(filters, new Set([7, 8, 9]))]).toEqual(['4'])
expect(withoutTagFilters(filters, [9])).toBe(filters)
expect(withoutTagFilters(filters, [])).toBe(filters)
})
})
+30 -6
View File
@@ -2,12 +2,12 @@ import type { Place } from '../types'
/**
* The trip's places filter, in one place: the pool (all / unplanned / planned /
* tracks), the category set and the minimum rating. The desktop list, the phone
* list and the map markers of both shells apply this same predicate to the same
* values, held in the trip store (#1541). The map keeps two deliberate
* differences of its own: with a day open, "planned" shows that day's plan only
* (#2024), and the stops of collapsed days are left off the map (except under
* "planned").
* tracks), the category set, which the tags filter through as well, and the
* minimum rating. The desktop list, the phone list and the map markers of both
* shells apply this same predicate to the same values, held in the trip store
* (#1541). The map keeps two deliberate differences of its own: with a day
* open, "planned" shows that day's plan only (#2024), and the stops of
* collapsed days are left off the map (except under "planned").
*/
/** A minimum of average stars: 'all', or a floor that unrated places fall through. */
@@ -19,12 +19,36 @@ export const RATING_FLOORS = ['all', 5, 4, 3, 2, 1] as const
/** The pseudo category id that stands for "no category". */
export const UNCATEGORIZED = 'uncategorized'
const TAG_KEY = 'tag:'
/** A tag's entry in the category filter set, which holds category ids, UNCATEGORIZED and these. */
export const tagFilterKey = (tagId: number): string => `${TAG_KEY}${tagId}`
/**
* The ticked categories and the ticked tags are two questions with one answer each:
* a place passes when it is in one of the ticked categories, if any is ticked, and
* carries one of the ticked tags, if any is ticked.
*/
export function matchesCategoryFilter(place: Place, categoryFilters: ReadonlySet<string>): boolean {
if (categoryFilters.size === 0) return true
const tagsTicked = [...categoryFilters].filter(key => key.startsWith(TAG_KEY)).length
if (tagsTicked > 0 && !carriesTickedTag(place, categoryFilters)) return false
if (tagsTicked === categoryFilters.size) return true
if (place.category_id == null) return categoryFilters.has(UNCATEGORIZED)
return categoryFilters.has(String(place.category_id))
}
function carriesTickedTag(place: Place, ticked: ReadonlySet<string>): boolean {
return (place.tags ?? []).some(tag => tag.id != null && ticked.has(tagFilterKey(tag.id)))
}
/** The filter set without the entries of tags that are gone; the same set when it held none of them. */
export function withoutTagFilters(categoryFilters: Set<string>, goneTagIds: Iterable<number>): Set<string> {
const gone = [...goneTagIds].map(tagFilterKey).filter(key => categoryFilters.has(key))
if (gone.length === 0) return categoryFilters
return new Set([...categoryFilters].filter(key => !gone.includes(key)))
}
export function matchesRatingFloor(place: Place, floor: PlacesRatingFloor): boolean {
if (floor === 'all') return true
return place.rating_avg != null && place.rating_avg >= floor