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
@@ -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. */