fix(places): the first CI run on the place view and the copies in step

Imports the picture icon the media sections draw for "use as the place
picture", narrows the types the type check refused, moves the dropdown
open state and the media lightbox into one module each for both views,
replaces an await in a loop, and lowers the ratchet baselines to the counts
the run measured. The tests follow the place view: the vote route of a trip
place lives with the votes now, the history holds an entry per copy that
followed an edit, the rate_library_place tool has its broadcast case, and
the row tags of a list are dots behind the name.
This commit is contained in:
Maurice
2026-11-29 23:53:36 +00:00
parent 71392ec9c1
commit 7104fa6dd4
21 changed files with 180 additions and 123 deletions
+10 -6
View File
@@ -2,7 +2,8 @@ import { expect, test, type Locator } from '@playwright/test';
// #2981: labels, category and status took the whole row, so a place with two or
// three long labels showed one letter of its name or none, and the status pill
// ran out of the card. Measured in a real browser because the layout is the bug.
// ran out of the card. The labels are tags now, shown as dots behind the name.
// Measured in a real browser because the layout is the bug.
const PLACES = [
{ name: 'Oceanario de Lisboa', labels: ['Core shortlist', 'Heritage specialist', 'Pair with another stop'] },
{ name: 'Cove of Ursa', labels: ['Heritage specialist', 'Pair with another stop'] },
@@ -83,11 +84,14 @@ for (const viewport of [
// The whole name fits: it is not cut to an ellipsis.
expect(await name.evaluate((el) => el.scrollWidth <= el.clientWidth + 1)).toBe(true);
await expectInside(row);
// Every label is either on the row or counted by its "+N" chip.
const shown = await row.locator('.col-lrow-label:not(.is-over)').count();
// Read without waiting: a row whose labels all fit has no "+N".
const [more] = await row.locator('.col-lrow-more').allTextContents();
expect(shown + (more ? Number(more.replace('+', '')) : 0)).toBe(place.labels.length);
// The labels are the place's tags: dots behind the name, every name in their label.
const dots = row.locator('.li .t [role="img"]:not(.col-lrow-caticon)');
if (place.labels.length === 0) {
await expect(dots).toHaveCount(0);
} else {
const named = ((await dots.getAttribute('aria-label')) ?? '').split(', ');
expect([...named].sort()).toEqual([...place.labels].sort());
}
}
// The map's label strip stays inside the map: whole, or folded into its button.
const topbar = page.locator('.col-map-topbar');
+4 -4
View File
@@ -1,18 +1,18 @@
{
"src": {
"@typescript-eslint/no-non-null-assertion": 345,
"@typescript-eslint/no-misused-promises": 812,
"@typescript-eslint/no-misused-promises": 810,
"no-console": 85,
"complexity": 215,
"complexity": 214,
"@typescript-eslint/no-explicit-any": 114,
"trek/no-swallowed-catch": 124,
"max-params": 31,
"trek/store-without-selector": 65,
"react-hooks/refs": 389,
"react-hooks/refs": 385,
"react-hooks/set-state-in-effect": 188,
"@typescript-eslint/no-floating-promises": 162,
"react-hooks/exhaustive-deps": 112,
"@typescript-eslint/no-unused-vars": 100,
"@typescript-eslint/no-unused-vars": 99,
"react-hooks/immutability": 26,
"max-lines-per-function": 126,
"react-hooks/static-components": 38,
@@ -346,7 +346,8 @@ describe('useCollabChatData on a box that changes size', () => {
it('FE-COLLAB-CHATDATA-017: a list at its newest message stays there when a rotation or a fold resizes it', async () => {
vi.stubGlobal('ResizeObserver', Observer);
const { list, grow } = await mountList(400);
expect(observed).toContain(list);
// The observer starts in an effect after the list is drawn; under load that comes a tick later.
await waitFor(() => expect(observed).toContain(list));
grow(900);
report();
expect(list.scrollTop).toBe(900);
@@ -112,7 +112,7 @@ function StatusSegment({
type Form = ReturnType<typeof useCollectionPlaceForm>;
/** The cover: the picture or a gradient, the category, the picture controls, close, and the name. */
/** The cover: the picture or a gradient, the category, the picture controls and the name. */
function Cover({
place,
form,
@@ -120,7 +120,6 @@ function Cover({
categories,
labelId,
onUploadImage,
onClose,
t,
}: {
place: CollectionPlace;
@@ -129,7 +128,6 @@ function Cover({
categories: Category[];
labelId: string;
onUploadImage?: (file: File) => Promise<void>;
onClose: () => void;
t: TranslationFn;
}) {
const coverInputRef = useRef<HTMLInputElement>(null);
@@ -478,7 +476,6 @@ export default function CollectionPlaceDetail({
categories={categories}
labelId={labelId}
onUploadImage={onUploadImage}
onClose={onClose}
t={t}
/>
<div className="place-aside-body">
@@ -1,5 +1,6 @@
import { Check, ChevronDown } from 'lucide-react';
import React, { useEffect, useRef, useState } from 'react';
import React from 'react';
import { useDropdownOpen } from './useDropdownOpen';
export interface FilterOption {
key: string | number;
@@ -20,23 +21,7 @@ export default function FilterDropdown({
onSelect: (key: string | number) => void;
lead: React.ReactNode;
}): React.ReactElement {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const onDoc = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
};
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') setOpen(false);
};
document.addEventListener('mousedown', onDoc);
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('mousedown', onDoc);
document.removeEventListener('keydown', onKey);
};
}, [open]);
const { open, setOpen, ref } = useDropdownOpen();
const cur = options.find((o) => o.key === current) ?? options[0];
return (
@@ -0,0 +1,29 @@
import React from 'react';
import PhotoLightbox from '../Journey/PhotoLightbox';
import type { usePlaceMedia } from './usePlaceMedia';
/** The open picture of a place's media, for the desktop sheet and the phone sheet alike. */
export default function PlaceMediaLightbox({
media,
label,
}: {
media: ReturnType<typeof usePlaceMedia>;
label: string;
}): React.ReactElement | null {
if (media.open === null) return null;
return (
<PhotoLightbox
photos={media.photos.map((p) => ({
id: p.id,
src: p.src,
thumbSrc: p.thumbSrc,
caption: p.caption,
provider: p.provider,
mediaType: p.mediaType,
}))}
startIndex={media.open}
onClose={media.close}
label={label}
/>
);
}
@@ -1,10 +1,10 @@
import type { PlacesLibraryEntry } from '@trek/shared';
import { Bookmark, FileText, Images, Layers, Loader2, Luggage, Plus, Upload } from 'lucide-react';
import { Bookmark, FileText, ImageUp, Images, Layers, Loader2, Luggage, Plus, Upload } from 'lucide-react';
import React from 'react';
import type { TranslationFn } from '../../types';
import PhotoLightbox from '../Journey/PhotoLightbox';
import { Tooltip } from '../shared/Tooltip';
import PlaceCard from './PlaceCard';
import PlaceMediaLightbox from './PlaceMediaLightbox';
import { useMediaAdd } from './mediaAdd';
import { usePlaceMedia, type MediaTarget } from './usePlaceMedia';
@@ -134,21 +134,7 @@ export function PlaceMediaView({
))}
</PlaceCard>
)}
{m.open !== null && (
<PhotoLightbox
photos={m.photos.map((p) => ({
id: p.id,
src: p.src,
thumbSrc: p.thumbSrc,
caption: p.caption,
provider: p.provider,
mediaType: p.mediaType,
}))}
startIndex={m.open}
onClose={m.close}
label={label}
/>
)}
<PlaceMediaLightbox media={m} label={label} />
</>
);
}
@@ -1,6 +1,7 @@
import { Check, ChevronDown, Tag } from 'lucide-react';
import React, { useEffect, useRef, useState } from 'react';
import React from 'react';
import type { TranslationFn } from '../../types';
import { useDropdownOpen } from './useDropdownOpen';
/**
* The tag filter of All places, shaped like the dropdowns beside it but with
@@ -18,23 +19,7 @@ export default function TagFilterDropdown({
onToggle: (name: string) => void;
t: TranslationFn;
}): React.ReactElement | null {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const onDoc = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
};
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') setOpen(false);
};
document.addEventListener('mousedown', onDoc);
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('mousedown', onDoc);
document.removeEventListener('keydown', onKey);
};
}, [open]);
const { open, setOpen, ref } = useDropdownOpen();
if (tags.length === 0) return null;
const label =
@@ -0,0 +1,27 @@
import { useEffect, useRef, useState } from 'react';
/**
* Whether a compact filter dropdown is open, closed again by a press outside
* its element or by Escape. The filter dropdowns of the lists and All places
* share it.
*/
export function useDropdownOpen() {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const onDoc = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
};
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') setOpen(false);
};
document.addEventListener('mousedown', onDoc);
document.addEventListener('keydown', onKey);
return () => {
document.removeEventListener('mousedown', onDoc);
document.removeEventListener('keydown', onKey);
};
}, [open]);
return { open, setOpen, ref };
}
@@ -102,7 +102,7 @@ describe('usePlaceSheet', () => {
it('FE-COMP-PLACESHEET-003: each tab counts what it holds, the files and pictures together', () => {
parts.notes = { notes: [1, 2], targets: [] };
parts.activities = { activities: [1], canLink: false };
parts.media = { photos: [1, 2], files: [1] };
parts.media = { photos: [1, 2], files: [1], targets: [] };
parts.history = { entries: [1, 2, 3, 4] };
const { result } = setup(bothOrigins());
expect(result.current.counts).toEqual({ overview: 0, notes: 2, activities: 1, media: 3, history: 4 });
@@ -234,7 +234,7 @@ export default function PlaceInspector({
.catch(() => { if (!cancelled) setProviderDetails([]) })
return () => { cancelled = true }
}, [placeIdForDetails])
const { t, locale, language } = useTranslation()
const { t, locale } = useTranslation()
const placeLang = usePlaceLanguage()
// Currency-less prices mean "the trip's currency"; null in collection mode (EUR fallback below).
const tripCurrency = useTripStore(s => s.trip?.currency)
@@ -282,7 +282,7 @@ export default function MCollPlaceSheet({
<MPlaceSheetShell
open={place != null}
name={held?.name ?? null}
category={held?.category}
category={held?.category?.name ? { ...held.category, name: held.category.name } : null}
cover={form.cover}
seed={held?.id ?? 0}
// While editing, the form's address and position fields stand for them (#1870).
@@ -1,8 +1,19 @@
import type { PlacesLibraryEntry } from '@trek/shared';
import { Bookmark, ChevronRight, FileText, Images, Layers, Loader2, Luggage, Plus, Upload } from 'lucide-react';
import {
Bookmark,
ChevronRight,
FileText,
ImageUp,
Images,
Layers,
Loader2,
Luggage,
Plus,
Upload,
} from 'lucide-react';
import PlaceMediaLightbox from '../../../components/Collections/PlaceMediaLightbox';
import { useMediaAdd } from '../../../components/Collections/mediaAdd';
import { usePlaceMedia, type MediaTarget } from '../../../components/Collections/usePlaceMedia';
import PhotoLightbox from '../../../components/Journey/PhotoLightbox';
import type { TranslationFn } from '../../../types';
import MPlaceCard, { M_ICO, M_ROW } from './MPlaceCard';
import './libraryCover.css';
@@ -151,21 +162,7 @@ export function MPlaceMediaView({
))}
</MPlaceCard>
)}
{m.open !== null && (
<PhotoLightbox
photos={m.photos.map((p) => ({
id: p.id,
src: p.src,
thumbSrc: p.thumbSrc,
caption: p.caption,
provider: p.provider,
mediaType: p.mediaType,
}))}
startIndex={m.open}
onClose={m.close}
label={label}
/>
)}
<PlaceMediaLightbox media={m} label={label} />
</>
);
}
+2 -2
View File
@@ -22,14 +22,14 @@ export type OriginTagRef =
| { kind: 'trip'; trip_id: number; place_id: number };
/** What the edit form of All places changes of a place's copy. */
export interface PlaceDetailsPatch {
export type PlaceDetailsPatch = {
name: string;
category_id: number | null;
address: string | null;
description: string | null;
lat?: number | null;
lng?: number | null;
}
};
/**
* PLC-07/PLC-08, online only on purpose, like the collections themselves:
+2
View File
@@ -154,6 +154,8 @@ export function libraryState(over: Partial<PlacesLibraryState> = {}): PlacesLibr
setStatus: vi.fn(),
tagNames: [],
toggleTagName: vi.fn(),
minRating: 'all',
setMinRating: vi.fn(),
filtered: false,
resetFilters: vi.fn(),
entries: [],
+1 -2
View File
@@ -87,8 +87,7 @@
"src/nest/packing/admin-packing-templates.controller.ts": 3,
"src/nest/packing/packing.controller.ts": 1,
"src/nest/packing/packing.dto.ts": 1,
"src/nest/places/places.controller.ts": 1,
"src/nest/places/places.mcp.ts": 5,
"src/nest/places/places.mcp.ts": 3,
"src/nest/platform/discovery-metadata.service.ts": 3,
"src/nest/plugins/host/plugin-jobs.ts": 1,
"src/nest/plugins/host/rpc/host-surface.rpc.ts": 8,
+3 -1
View File
@@ -1,3 +1,5 @@
import { inOrder } from './in-order';
/** Told that somebody joined a list or a trip: its id and theirs. */
export type JoinListener = (containerId: number, userId: number) => Promise<void>;
@@ -16,6 +18,6 @@ export class JoinListeners {
}
async joined(containerId: number, userId: number): Promise<void> {
for (const listener of this.listeners) await listener(containerId, userId);
await inOrder(this.listeners, (listener) => listener(containerId, userId));
}
}
+31 -8
View File
@@ -115,7 +115,14 @@ describe('the history of a place', () => {
});
const page = await changes(f.me.id, 'trip', f.places.cafe.id);
expect(page.next_cursor).toBeNull();
expect(page.entries).toEqual([
// The saved copy of Café follows the edit and keeps its own entries, made after the trip's.
expect(page.entries.map((entry) => [entry.origin.kind, entry.field])).toEqual([
['list', 'address'],
['list', 'name'],
['trip', 'address'],
['trip', 'name'],
]);
expect(page.entries.slice(2)).toEqual([
expect.objectContaining({
field: 'address',
old_value: 'Herrengasse 14, Wien',
@@ -139,7 +146,8 @@ describe('the history of a place', () => {
expect(status.status).toBe(200);
const fromTrip = await changes(f.me.id, 'trip', f.places.cafe.id);
expect(fieldsOf(fromTrip)).toEqual(['status', 'notes', 'phone']);
// The phone follows onto the saved copy; notes and status stay the list's own.
expect(fieldsOf(fromTrip)).toEqual(['status', 'notes', 'phone', 'phone']);
expect(fromTrip.entries[0]).toEqual(
expect.objectContaining({
old_value: 'want',
@@ -180,11 +188,17 @@ describe('the history of a place', () => {
it('PHIST-E2E-004: a cleared value takes the earlier changes of its field along, and is no change itself', async () => {
await editSavedPlace(f.me.id, f.saved.savedCafe.id, { notes: 'First' });
await editSavedPlace(f.me.id, f.saved.savedCafe.id, { notes: 'Second', address: 'Herrengasse 14' });
expect(fieldsOf(await changes(f.me.id, 'list', f.saved.savedCafe.id))).toEqual(['notes', 'address', 'notes']);
// The address follows onto the trip place, the notes stay the list's.
expect(fieldsOf(await changes(f.me.id, 'list', f.saved.savedCafe.id))).toEqual([
'address',
'notes',
'address',
'notes',
]);
await editSavedPlace(f.me.id, f.saved.savedCafe.id, { notes: null });
const page = await changes(f.me.id, 'list', f.saved.savedCafe.id);
expect(fieldsOf(page)).toEqual(['address']);
expect(fieldsOf(page)).toEqual(['address', 'address']);
expect(JSON.stringify(page)).not.toContain('First');
expect(JSON.stringify(page)).not.toContain('Try the cake');
@@ -199,15 +213,21 @@ describe('the history of a place', () => {
await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { website: 'https://b.example' });
await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { website: 'https://c.example' });
const first = await history(f.me.id, 'trip', f.places.cafe.id, { limit: '2' });
// Each edit writes the trip place and the saved copy that follows it.
const first = await history(f.me.id, 'trip', f.places.cafe.id, { limit: '4' });
expect(first.status).toBe(200);
const one = first.body as PlaceHistoryPageResponse;
expect(one.entries.map((entry) => entry.new_value)).toEqual(['https://c.example', 'https://b.example']);
expect(one.entries.map((entry) => entry.new_value)).toEqual([
'https://c.example',
'https://c.example',
'https://b.example',
'https://b.example',
]);
expect(one.next_cursor).not.toBeNull();
const second = await history(f.me.id, 'trip', f.places.cafe.id, { limit: '2', cursor: one.next_cursor ?? '' });
const second = await history(f.me.id, 'trip', f.places.cafe.id, { limit: '4', cursor: one.next_cursor ?? '' });
const two = second.body as PlaceHistoryPageResponse;
expect(two.entries.map((entry) => entry.new_value)).toEqual(['https://a.example']);
expect(two.entries.map((entry) => entry.new_value)).toEqual(['https://a.example', 'https://a.example']);
expect(two.next_cursor).toBeNull();
expect((await history(f.me.id, 'trip', f.places.cafe.id, { cursor: 'abc' })).status).toBe(400);
@@ -231,9 +251,12 @@ describe('the history of a place', () => {
const read = await callTool(f.me.id, 'get_library_place_history', { kind: 'trip', id: f.places.cafe.id });
expect(read.error).toBeNull();
const page = read.answer as PlaceHistoryPageResponse;
// The saved copy follows over MCP too, with the same editor.
expect(page.entries).toEqual([
expect.objectContaining({ field: 'address', editor: expect.objectContaining({ id: f.me.id }) }),
expect.objectContaining({ field: 'address', editor: expect.objectContaining({ id: f.me.id }) }),
]);
expect(page.entries.map((entry) => entry.origin.kind)).toEqual(['list', 'trip']);
const refused = await callTool(f.friend.id, 'get_library_place_history', { kind: 'trip', id: f.places.cafe.id });
expect(refused.answer).toBeNull();
+2 -21
View File
@@ -18,7 +18,6 @@ import { db } from '../../src/db/database';
import { BudgetItems } from '../../src/db/entities/BudgetItems.entity';
import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';
import { Days } from '../../src/db/entities/Days.entity';
import { PlaceRatings } from '../../src/db/entities/PlaceRatings.entity';
import { Places } from '../../src/db/entities/Places.entity';
import { Tours } from '../../src/db/entities/Tours.entity';
import { Trips } from '../../src/db/entities/Trips.entity';
@@ -341,26 +340,8 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
expect((await findRow(orm, Places, { id: 9 }))!.name).toBe('Walk');
});
it("PUT/DELETE :id/rating stores and clears the caller's vote", async () => {
await insertRow(orm, Places, { id: 9, trip: 5, name: 'Rated' });
const rated = await request(server)
.put('/api/trips/5/places/9/rating')
.set('Cookie', sessionCookie(1))
.send({ rating: 4 });
expect(rated.status).toBe(200);
expect(
(await findRows(orm, PlaceRatings, { place: 9 }, { id: 'asc' })).map((r) => ({
user_id: r.user_id,
rating: r.rating,
})),
).toEqual([{ user_id: 1, rating: 4 }]);
const cleared = await request(server).delete('/api/trips/5/places/9/rating').set('Cookie', sessionCookie(1));
expect(cleared.status).toBe(200);
expect(await countRows(orm, PlaceRatings, { place: 9 })).toBe(0);
});
// The vote routes of a trip place live in PlaceVotesModule now (one vote per person across
// copies); tests/e2e/place-votes.e2e.test.ts runs them on the whole app.
it('DELETE :id removes the row, 404 for a foreign place', async () => {
await insertRow(orm, Places, { id: 9, trip: 5, name: 'Gone' });
await insertRow(orm, Places, { id: 10, trip: 6, name: 'Foreign' });
@@ -185,6 +185,19 @@ export const plan: CaseGroup = {
rest: { method: 'put', path: (s) => `${placesPath(s)}/${s.place.id}/rating`, body: () => ({ rating: 4 }) },
expect: ['place:updated'],
},
{
// The vote by entry key of All places lands on every copy of the place and starts
// from none of them, so the voting tab hears of the trip place too.
tool: 'rate_library_place',
needs: ['place'],
args: (s) => ({ key: `trip:${s.place.id}`, rating: 4 }),
rest: {
method: 'put',
path: () => '/api/addons/collections/library/places/rating',
body: (s) => ({ key: `trip:${s.place.id}`, rating: 4 }),
},
expect: [{ event: 'place:updated', all: true }],
},
{
// The hotel of a stay: the night and its partner booking go with the place,
// and the deleting tab hears that too, since it only removed the place.
@@ -26,7 +26,15 @@ const origins = {
record: vi.fn(async () => undefined),
recordImported: vi.fn(async () => undefined),
};
const guards = { hasTripPermission: vi.fn(async () => true), safeBroadcast: vi.fn() };
const guards = {
hasTripPermission: vi.fn(async () => true),
safeBroadcast: vi.fn(),
// How the edit reaches the caller's other copies of the place (place-copies.port.ts).
copyFollow: vi.fn(async (userId: number, reach: { trips: boolean; lists: boolean }) => ({
editor: { id: userId, role: 'user' },
reach,
})),
};
const tripAccess = { findAccessible: vi.fn(async () => ({ id: 1, user_id: 5 })) };
const mcp = new PlacesMcp(
@@ -80,3 +88,21 @@ describe('PlacesMcp origin tracking', () => {
expect(origins.record).not.toHaveBeenCalled();
});
});
describe('PlacesMcp: the copies follow an edit', () => {
it('PMO-005: an update hands the caller and the kinds the token may write to the copies', async () => {
await mcp.updatePlace(
{ tripId: 1, placeId: 8, name: 'X' } as never,
{
userId: 4,
scopes: ['places:write'],
isStaticToken: false,
} as never,
);
expect(guards.copyFollow).toHaveBeenCalledWith(4, { trips: true, lists: false });
expect(places.update.mock.calls.at(-1)?.[5]).toEqual({
editor: { id: 4, role: 'user' },
reach: { trips: true, lists: false },
});
});
});