mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 21:11:14 +00:00
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:
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user