mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-23 23:46:35 +00:00
feat: six community requests — import dedup, accommodations in the feed, OAuth refresh race, visited-from-trip, journal jumps, phone packing rows (#1915)
* fix(places): match imports on the provider id so renamed places are not duplicated Re-importing a Google Maps list duplicated every place the user had renamed. buildDedupSet only ever collected names and, for unnamed places, coordinates, and isPlaceDuplicate returns on the name before it reaches the coordinate fallback, so a renamed place was findable by neither. The ids were stored all along, and even backfilled onto matched places, they were simply never read. Match on google_place_id / google_ftid / osm_id first, keeping name and coordinates in their old roles below it. Widening the coordinate check instead would have merged the restaurant and the bar in the same building. The collection copy carried a hand-mirrored port of the same predicate; it now uses the shared helpers and gets the fix with them. Closes #1550 * feat(calendar): put accommodations into the subscribed feed as all-day stays A hotel keeps its dates on the linked stay, not on the reservation: the booking form writes reservation_time = NULL for type 'hotel', and day_accommodations carries start day, end day and the check-in/out clock. The feed only ever read the reservation, so a stay showed up once on the arrival day at best, and not at all when it came from the booking form. Join the stay in and emit the reservation as an all-day range over every night, which also keeps it correct when days are reordered later — the dates now come from the day rows rather than from the copy stamped at creation time. Check-in and check-out become their own timed events when the stay records a clock, because an all-day event cannot carry the time you actually need reminding of. The check-in window, when set, becomes that event's DTEND. Closes #1586 * fix(oauth): treat a concurrent refresh as a race, not as a stolen token Refresh rotation is a race by construction. Several MCP clients share one refresh token, both post it within the same second, and the loser was read as a replay: chain revoked, MCP sessions torn down, browser window asking to log in again. That is the daily re-authentication people were seeing, not a short lifetime — access tokens last an hour and refresh tokens roll for thirty days. A revoked refresh token now only counts as a replay once it is outside a 30-second grace window, and only when the rotation that revoked it left a successor still alive. Inside the window the caller gets its own pair branched off the same parent, so both clients walk away with a working token. Explicit revocation leaves no live successor and a chain killed by a real replay has none either, so neither can slip through the window. Closes #1007 * feat(collections): mark a place visited from the trip it belongs to A place saved in several lists had to be opened in each of them to say you had been there, which is the wrong way round: you find out you have been somewhere while looking at the trip, not while browsing the library. The save picker now shows each list's own status and cycles it in place, with one action for "visited, wherever this is saved". The planner's selection bar and the mobile bulk toolbar carry the same thing for a whole selection — select all, one tap, done. Matching happens on the server with the signals findMembership already uses plus the source link a place saved from this trip carries, so a copy renamed inside a list is still found. Lists you may only read are skipped rather than refused; a shared list you cannot edit should not stop you marking your own. Closes #1469 * feat(journey): jump to the top or back to the last entry in a long journal Everything that adds to a journal sits at the top — the entry button, the gallery upload — and where you left off sits at the bottom, so adding one photo to a long journey meant scrolling the whole way twice. Two buttons float over the middle of the feed, clear of the Add Entry column on one side and the reorder arrows on the other, each appearing only when there is more than a screenful to travel in that direction. They live in a zero-height sticky box so they take no layout space and never push the timeline around. While in the header, the status pill also picks up the height of the round buttons beside it. Closes #1088 * fix(packing): give the item name the row back on phones An item name had roughly a third of the row to itself: a spelled-out sharing sentence, an empty weight column and two round action buttons took the rest, so anything longer than a word was cut off. Sharing is now the icon it always was next to a label rather than a sentence in the layout, an unset weight prints nothing instead of a dash, and edit/delete sit behind one overflow button that opens the same inline menu the bag picker already uses. The to-do list needed none of this — it wraps its chips onto a second line already. Closes #1525 * docs(wiki): cover the six community changes - Calendar feeds: accommodations as an all-day range plus check-in/check-out - Collections: setting the visited status from a trip, and how places are matched - Journey: the jump buttons on a long journal - Packing: what the phone row keeps and what moved behind the overflow button - Places: re-importing a list no longer duplicates renamed places - MCP setup: the rotation race no longer ends an OAuth session * test(collections): assert the stored status instead of a private method tests/ sits outside the build tsconfig, so reaching into getPlaceById only showed up in the dedicated typecheck step. Reading the row is the better assertion anyway — it pins what was persisted, not what a getter returns.
This commit is contained in:
@@ -17,6 +17,7 @@ import type {
|
||||
CollectionInviteActionRequest,
|
||||
CollectionInviteCancelRequest,
|
||||
CollectionStatus,
|
||||
CollectionSetStatusManyResponse,
|
||||
Collection,
|
||||
CollectionPlace,
|
||||
CollectionLabel,
|
||||
@@ -77,6 +78,10 @@ export const collectionsApi = {
|
||||
postMultipart(`${base}/places/${pid}/image`, formData),
|
||||
setStatus: (pid: number, status: CollectionStatus): Promise<CollectionPlace> =>
|
||||
ax.post(`${base}/places/${pid}/status`, { status }).then((r: AxiosResponse) => r.data),
|
||||
setStatusMany: (ids: number[], status: CollectionStatus): Promise<CollectionSetStatusManyResponse> =>
|
||||
ax.post(`${base}/places/status-many`, { ids, status }).then((r: AxiosResponse) => r.data),
|
||||
setStatusFromTrip: (tripId: number, placeIds: number[], status: CollectionStatus): Promise<CollectionSetStatusManyResponse> =>
|
||||
ax.post(`${base}/places/status-from-trip`, { trip_id: tripId, place_ids: placeIds, status }).then((r: AxiosResponse) => r.data),
|
||||
ratePlace: (pid: number, rating: number | null): Promise<CollectionPlace> =>
|
||||
rating === null
|
||||
? ax.delete(`${base}/places/${pid}/rating`).then((r: AxiosResponse) => r.data)
|
||||
|
||||
@@ -115,7 +115,7 @@ describe('MSaveToCollectionSheet', () => {
|
||||
it('FE-COMP-MSAVESHEET-006: lists already holding the place are marked saved', async () => {
|
||||
vi.spyOn(collectionsApi, 'membership').mockResolvedValue({
|
||||
saved: true,
|
||||
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900 }],
|
||||
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900, status: 'want', can_edit: true }],
|
||||
});
|
||||
openFor();
|
||||
render(<MSaveToCollectionSheet />);
|
||||
@@ -167,7 +167,7 @@ describe('MSaveToCollectionSheet', () => {
|
||||
it('FE-COMP-MSAVESHEET-010: tapping a saved list removes that place instead', async () => {
|
||||
vi.spyOn(collectionsApi, 'membership').mockResolvedValue({
|
||||
saved: true,
|
||||
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900 }],
|
||||
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900, status: 'want', can_edit: true }],
|
||||
});
|
||||
const del = vi.spyOn(collectionsApi, 'deletePlace').mockResolvedValue({});
|
||||
openFor();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useMemo, useState, useCallback } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { Bookmark, BookmarkCheck, Check, Loader2, Plus, X } from 'lucide-react'
|
||||
import { Bookmark, BookmarkCheck, Check, CheckCircle2, Loader2, Plus, X } from 'lucide-react'
|
||||
import MSheet from '../../mobile/components/MSheet'
|
||||
import MIconBtn from '../../mobile/components/MIconBtn'
|
||||
import { useToast } from '../shared/Toast'
|
||||
@@ -8,7 +8,8 @@ import { useTranslation } from '../../i18n'
|
||||
import { collectionsApi } from '../../api/collections'
|
||||
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore'
|
||||
import { getApiErrorMessage } from '../../utils/apiError'
|
||||
import type { Collection, CollectionMembership } from '@trek/shared'
|
||||
import { STATUS_META, nextStatus } from '../../pages/collections/collectionsModel'
|
||||
import type { Collection, CollectionMembership, CollectionStatus } from '@trek/shared'
|
||||
|
||||
/**
|
||||
* Mobile counterpart of SaveToCollectionModal — the same store-driven list
|
||||
@@ -71,12 +72,44 @@ export default function MSaveToCollectionSheet() {
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [target])
|
||||
|
||||
const savedByCollection = new Map<number, number>()
|
||||
for (const l of membership?.lists ?? []) savedByCollection.set(l.collection_id, l.place_id)
|
||||
const savedByCollection = new Map<number, CollectionMembership['lists'][number]>()
|
||||
for (const l of membership?.lists ?? []) savedByCollection.set(l.collection_id, l)
|
||||
|
||||
/** Lists holding this place that the viewer may edit and that are not visited yet. */
|
||||
const unvisited = (membership?.lists ?? []).filter(l => l.can_edit && l.status !== 'visited')
|
||||
|
||||
const handleStatus = async (entry: CollectionMembership['lists'][number], next: CollectionStatus) => {
|
||||
if (busyId != null) return
|
||||
setBusyId(entry.collection_id)
|
||||
try {
|
||||
await collectionsApi.setStatus(entry.place_id, next)
|
||||
await refreshMembership()
|
||||
bumpVersion()
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
} finally {
|
||||
setBusyId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleVisitedEverywhere = async () => {
|
||||
if (busyId != null || unvisited.length === 0) return
|
||||
setBusyId(-1)
|
||||
try {
|
||||
const { updated } = await collectionsApi.setStatusMany(unvisited.map(l => l.place_id), 'visited')
|
||||
toast.success(t('collections.markedVisited', { count: updated }))
|
||||
await refreshMembership()
|
||||
bumpVersion()
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
} finally {
|
||||
setBusyId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleToggle = async (list: Collection) => {
|
||||
if (busyId != null || !target) return
|
||||
const savedPlaceId = savedByCollection.get(list.id)
|
||||
const savedPlaceId = savedByCollection.get(list.id)?.place_id
|
||||
setBusyId(list.id)
|
||||
try {
|
||||
if (savedPlaceId != null) {
|
||||
@@ -156,8 +189,11 @@ export default function MSaveToCollectionSheet() {
|
||||
</div>
|
||||
) : (
|
||||
lists.map(list => {
|
||||
const saved = savedByCollection.has(list.id)
|
||||
const entry = savedByCollection.get(list.id)
|
||||
const saved = !!entry
|
||||
const busy = busyId === list.id
|
||||
const statusMeta = entry ? STATUS_META[entry.status] : null
|
||||
const StatusIcon = statusMeta?.icon
|
||||
return (
|
||||
<button
|
||||
key={list.id}
|
||||
@@ -178,9 +214,27 @@ export default function MSaveToCollectionSheet() {
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[0.8125rem] font-semibold text-m-ink">{list.name}</span>
|
||||
<span className="mt-px block font-geist text-[0.65625rem] text-m-muted">
|
||||
{t('collections.placeCount', { count: list.place_count ?? 0 })}
|
||||
</span>
|
||||
{/* Saved lists show their own status here instead of the place
|
||||
count — that number matters when picking a list, the status
|
||||
matters once the place is in it (#1469). */}
|
||||
{entry && statusMeta && StatusIcon ? (
|
||||
<span
|
||||
role={entry.can_edit ? 'button' : undefined}
|
||||
tabIndex={entry.can_edit ? 0 : undefined}
|
||||
aria-label={t(statusMeta.labelKey)}
|
||||
onClick={entry.can_edit ? e => { e.preventDefault(); e.stopPropagation(); void handleStatus(entry, nextStatus(entry.status)) } : undefined}
|
||||
onKeyDown={entry.can_edit ? e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); e.stopPropagation(); void handleStatus(entry, nextStatus(entry.status)) } } : undefined}
|
||||
className="mt-[3px] inline-flex items-center gap-1 rounded-full bg-[color:var(--m-inner)] px-2 py-[3px] font-geist text-[0.65625rem] font-semibold"
|
||||
style={{ color: statusMeta.color }}
|
||||
>
|
||||
<StatusIcon size={11} strokeWidth={2.4} />
|
||||
{t(statusMeta.labelKey)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="mt-px block font-geist text-[0.65625rem] text-m-muted">
|
||||
{t('collections.placeCount', { count: list.place_count ?? 0 })}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{list.is_owner === false && (
|
||||
<span className="flex-none font-geist text-[0.5625rem] font-bold uppercase tracking-[.05em] text-m-faint">
|
||||
@@ -200,6 +254,22 @@ export default function MSaveToCollectionSheet() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{unvisited.length > 0 && (
|
||||
<div className="flex-none px-[14px] pb-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleVisitedEverywhere}
|
||||
disabled={busyId != null}
|
||||
className="flex w-full items-center justify-center gap-1.5 rounded-[14px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] py-[10px] text-[0.78125rem] font-semibold text-m-ink disabled:opacity-60"
|
||||
>
|
||||
{busyId === -1
|
||||
? <Loader2 size={14} className="animate-spin" />
|
||||
: <CheckCircle2 size={14} strokeWidth={2.2} />}
|
||||
{unvisited.length > 1 ? t('collections.markVisitedAll') : t('collections.markVisited')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{lists.length > 0 && (
|
||||
<div className="flex flex-none items-center justify-between gap-2 border-t border-[color:var(--m-rowbr)] px-[18px] py-3">
|
||||
<button
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-COMP-SAVETOCOL-001 to FE-COMP-SAVETOCOL-016
|
||||
// FE-COMP-SAVETOCOL-001 to FE-COMP-SAVETOCOL-020
|
||||
import React from 'react';
|
||||
import { afterEach, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor, within } from '../../../tests/helpers/render';
|
||||
@@ -120,7 +120,7 @@ describe('SaveToCollectionModal', () => {
|
||||
it('FE-COMP-SAVETOCOL-006: lists already holding the place are marked saved', async () => {
|
||||
vi.spyOn(collectionsApi, 'membership').mockResolvedValue({
|
||||
saved: true,
|
||||
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900 }],
|
||||
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900, status: 'want', can_edit: true }],
|
||||
});
|
||||
openFor();
|
||||
render(<SaveToCollectionModal />);
|
||||
@@ -194,7 +194,7 @@ describe('SaveToCollectionModal', () => {
|
||||
it('FE-COMP-SAVETOCOL-011: picking a saved list removes that place instead', async () => {
|
||||
vi.spyOn(collectionsApi, 'membership').mockResolvedValue({
|
||||
saved: true,
|
||||
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900 }],
|
||||
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900, status: 'want', can_edit: true }],
|
||||
});
|
||||
const del = vi.spyOn(collectionsApi, 'deletePlace').mockResolvedValue({});
|
||||
const save = vi.spyOn(collectionsApi, 'savePlace');
|
||||
@@ -263,6 +263,65 @@ describe('SaveToCollectionModal', () => {
|
||||
expect(screen.queryByText('Favorites')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
// ── Per-list status + "visited everywhere" (#1469) ────────────────────────
|
||||
|
||||
const savedIn = (over: Partial<CollectionMembership['lists'][number]> = {}): CollectionMembership => ({
|
||||
saved: true,
|
||||
lists: [{ collection_id: 1, name: 'Favorites', place_id: 900, status: 'want', can_edit: true, ...over }],
|
||||
});
|
||||
|
||||
it('FE-COMP-SAVETOCOL-017: a saved list shows its own status and one tap cycles it', async () => {
|
||||
vi.spyOn(collectionsApi, 'membership').mockResolvedValue(savedIn());
|
||||
const setStatus = vi.spyOn(collectionsApi, 'setStatus').mockResolvedValue({} as never);
|
||||
const del = vi.spyOn(collectionsApi, 'deletePlace').mockResolvedValue({});
|
||||
openFor();
|
||||
render(<SaveToCollectionModal />);
|
||||
|
||||
const badge = await screen.findByRole('button', { name: 'Want to go' });
|
||||
fireEvent.click(badge);
|
||||
|
||||
// want → visited, and the row toggle must NOT have fired underneath it.
|
||||
await waitFor(() => expect(setStatus).toHaveBeenCalledWith(900, 'visited'));
|
||||
expect(del).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-COMP-SAVETOCOL-018: the header action marks every list holding the place visited', async () => {
|
||||
vi.spyOn(collectionsApi, 'membership').mockResolvedValue({
|
||||
saved: true,
|
||||
lists: [
|
||||
{ collection_id: 1, name: 'Favorites', place_id: 900, status: 'want', can_edit: true },
|
||||
{ collection_id: 2, name: 'Wishlist', place_id: 901, status: 'idea', can_edit: true },
|
||||
],
|
||||
});
|
||||
const many = vi.spyOn(collectionsApi, 'setStatusMany').mockResolvedValue({ updated: 2 });
|
||||
openFor();
|
||||
render(<SaveToCollectionModal />);
|
||||
|
||||
fireEvent.click(await screen.findByRole('button', { name: 'Visited everywhere' }));
|
||||
await waitFor(() => expect(many).toHaveBeenCalledWith([900, 901], 'visited'));
|
||||
});
|
||||
|
||||
it('FE-COMP-SAVETOCOL-019: the action disappears once every list is visited', async () => {
|
||||
vi.spyOn(collectionsApi, 'membership').mockResolvedValue(savedIn({ status: 'visited' }));
|
||||
openFor();
|
||||
render(<SaveToCollectionModal />);
|
||||
|
||||
await screen.findByText('Favorites');
|
||||
expect(screen.queryByRole('button', { name: /Visited everywhere|Mark visited/ })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-SAVETOCOL-020: a read-only list shows its status but does not offer to change it', async () => {
|
||||
vi.spyOn(collectionsApi, 'membership').mockResolvedValue(savedIn({ can_edit: false }));
|
||||
openFor();
|
||||
render(<SaveToCollectionModal />);
|
||||
|
||||
await screen.findByText('Favorites');
|
||||
expect(screen.queryByRole('button', { name: 'Want to go' })).not.toBeInTheDocument();
|
||||
expect(screen.getByTitle('Want to go')).toBeInTheDocument();
|
||||
// Nothing to offer: the only list holding it is one the viewer cannot edit.
|
||||
expect(screen.queryByRole('button', { name: /Visited everywhere|Mark visited/ })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-SAVETOCOL-014: the footer navigates to the collections page or just closes', async () => {
|
||||
openFor();
|
||||
const { unmount } = render(<SaveToCollectionModal />);
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import React, { useEffect, useMemo, useState, useCallback } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { Bookmark, BookmarkCheck, Check, Loader2, Plus } from 'lucide-react'
|
||||
import { Bookmark, BookmarkCheck, Check, CheckCircle2, Loader2, Plus } from 'lucide-react'
|
||||
import Modal from '../shared/Modal'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { collectionsApi } from '../../api/collections'
|
||||
import StatusBadge from './StatusBadge'
|
||||
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore'
|
||||
import { getApiErrorMessage } from '../../utils/apiError'
|
||||
import type { Collection, CollectionMembership } from '@trek/shared'
|
||||
import type { Collection, CollectionMembership, CollectionStatus } from '@trek/shared'
|
||||
|
||||
/**
|
||||
* Globally-mounted list picker for the "Save to Collection" entry points
|
||||
@@ -70,12 +71,44 @@ export default function SaveToCollectionModal(): React.ReactElement | null {
|
||||
|
||||
if (!target) return null
|
||||
|
||||
const savedByCollection = new Map<number, number>()
|
||||
for (const l of membership?.lists ?? []) savedByCollection.set(l.collection_id, l.place_id)
|
||||
const savedByCollection = new Map<number, CollectionMembership['lists'][number]>()
|
||||
for (const l of membership?.lists ?? []) savedByCollection.set(l.collection_id, l)
|
||||
|
||||
/** Lists holding this place that the viewer may edit and that are not visited yet. */
|
||||
const unvisited = (membership?.lists ?? []).filter(l => l.can_edit && l.status !== 'visited')
|
||||
|
||||
const handleStatus = async (entry: CollectionMembership['lists'][number], next: CollectionStatus) => {
|
||||
if (busyId != null) return
|
||||
setBusyId(entry.collection_id)
|
||||
try {
|
||||
await collectionsApi.setStatus(entry.place_id, next)
|
||||
await refreshMembership()
|
||||
bumpVersion()
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
} finally {
|
||||
setBusyId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleVisitedEverywhere = async () => {
|
||||
if (busyId != null || unvisited.length === 0) return
|
||||
setBusyId(-1)
|
||||
try {
|
||||
const { updated } = await collectionsApi.setStatusMany(unvisited.map(l => l.place_id), 'visited')
|
||||
toast.success(t('collections.markedVisited', { count: updated }))
|
||||
await refreshMembership()
|
||||
bumpVersion()
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
} finally {
|
||||
setBusyId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleToggle = async (list: Collection) => {
|
||||
if (busyId != null) return
|
||||
const savedPlaceId = savedByCollection.get(list.id)
|
||||
const savedPlaceId = savedByCollection.get(list.id)?.place_id
|
||||
setBusyId(list.id)
|
||||
try {
|
||||
if (savedPlaceId != null) {
|
||||
@@ -140,7 +173,23 @@ export default function SaveToCollectionModal(): React.ReactElement | null {
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-2">
|
||||
<p className="text-[13px] font-semibold text-content truncate">{target.name}</p>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<p className="flex-1 min-w-0 text-[13px] font-semibold text-content truncate">{target.name}</p>
|
||||
{/* One tap for "I have been here", however many lists hold it (#1469). */}
|
||||
{unvisited.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleVisitedEverywhere}
|
||||
disabled={busyId != null}
|
||||
className="shrink-0 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-edge bg-surface-card text-[11px] font-semibold text-content-secondary hover:bg-surface-hover disabled:opacity-60"
|
||||
>
|
||||
{busyId === -1
|
||||
? <Loader2 size={12} className="animate-spin" />
|
||||
: <CheckCircle2 size={12} strokeWidth={2.2} />}
|
||||
{unvisited.length > 1 ? t('collections.markVisitedAll') : t('collections.markVisited')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-8 text-content-faint">
|
||||
<Loader2 size={20} className="animate-spin" />
|
||||
@@ -162,7 +211,8 @@ export default function SaveToCollectionModal(): React.ReactElement | null {
|
||||
) : (
|
||||
<div className="flex flex-col gap-1 max-h-[50vh] overflow-y-auto -mx-1 px-1">
|
||||
{lists.map(list => {
|
||||
const saved = savedByCollection.has(list.id)
|
||||
const entry = savedByCollection.get(list.id)
|
||||
const saved = !!entry
|
||||
const busy = busyId === list.id
|
||||
return (
|
||||
<button
|
||||
@@ -170,13 +220,24 @@ export default function SaveToCollectionModal(): React.ReactElement | null {
|
||||
type="button"
|
||||
onClick={() => handleToggle(list)}
|
||||
disabled={busyId != null}
|
||||
className={`flex items-center gap-3 px-3 py-2.5 rounded-xl border text-left transition-colors disabled:opacity-60 ${saved ? 'border-accent bg-accent-subtle' : 'border-edge bg-surface-card hover:bg-surface-hover'}`}
|
||||
className={`flex items-center gap-2.5 px-3 py-2.5 rounded-xl border text-left transition-colors disabled:opacity-60 ${saved ? 'border-accent bg-accent-subtle' : 'border-edge bg-surface-card hover:bg-surface-hover'}`}
|
||||
>
|
||||
<span className="w-2.5 h-2.5 rounded-full shrink-0" style={{ background: list.color || 'var(--accent)' }} />
|
||||
<span className="flex-1 min-w-0 text-[13px] font-medium text-content truncate">{list.name}</span>
|
||||
{list.is_owner === false && (
|
||||
<span className="text-[10px] uppercase font-semibold text-content-faint">{t('collections.shared')}</span>
|
||||
)}
|
||||
{/* Per-list status, so one place can be an idea in one list and
|
||||
visited in another. A role=button span, safe to nest here. */}
|
||||
{entry && (
|
||||
<StatusBadge
|
||||
status={entry.status}
|
||||
showLabel={false}
|
||||
size={12}
|
||||
onChange={entry.can_edit ? next => { void handleStatus(entry, next) } : undefined}
|
||||
t={t}
|
||||
/>
|
||||
)}
|
||||
<span className={`w-5 h-5 rounded-md flex items-center justify-center shrink-0 ${saved ? 'bg-accent text-accent-text' : 'border border-edge text-transparent'}`}>
|
||||
{busy ? <Loader2 size={13} className="animate-spin text-content-faint" /> : saved ? <BookmarkCheck size={13} /> : <Check size={13} />}
|
||||
</span>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { Check, Tag, Trash2, Bookmark } from 'lucide-react'
|
||||
import { Check, CheckCircle2, Loader2, Tag, Trash2, Bookmark } from 'lucide-react'
|
||||
import Tooltip from '../shared/Tooltip'
|
||||
import type { SidebarState } from './usePlacesSidebar'
|
||||
|
||||
export function PlacesSelectionBar(S: SidebarState) {
|
||||
const { t, selectedIds, filtered, setSelectedIds, isMobile, setPendingDeleteIds, onBulkDeletePlaces, setCategoryPickerOpen, collectionsEnabled, setSaveToListOpen } = S
|
||||
const { t, selectedIds, filtered, setSelectedIds, isMobile, setPendingDeleteIds, onBulkDeletePlaces, setCategoryPickerOpen, collectionsEnabled, setSaveToListOpen, markSelectionVisited, markVisitedBusy } = S
|
||||
return (
|
||||
<div style={{
|
||||
margin: '6px 16px', padding: '5px 8px 5px 10px', borderRadius: 8,
|
||||
@@ -68,6 +68,25 @@ export function PlacesSelectionBar(S: SidebarState) {
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
{collectionsEnabled && (
|
||||
<Tooltip label={t('collections.markVisitedSelection')} placement="bottom">
|
||||
<button
|
||||
onClick={() => { if (selectedIds.size === 0) return; void markSelectionVisited() }}
|
||||
disabled={selectedIds.size === 0 || markVisitedBusy}
|
||||
aria-label={t('collections.markVisitedSelection')}
|
||||
className={selectedIds.size > 0 ? 'bg-transparent text-content-muted' : 'bg-transparent text-content-faint'}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: 24, height: 24, borderRadius: 6, border: 'none',
|
||||
cursor: selectedIds.size > 0 ? 'pointer' : 'default', padding: 0,
|
||||
}}
|
||||
onMouseEnter={e => { if (selectedIds.size > 0) e.currentTarget.style.background = 'var(--bg-hover)' }}
|
||||
onMouseLeave={e => { e.currentTarget.style.background = 'transparent' }}
|
||||
>
|
||||
{markVisitedBusy ? <Loader2 size={13} className="animate-spin" /> : <CheckCircle2 size={13} strokeWidth={2} />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip label={t('places.deleteSelected')} placement="bottom">
|
||||
<button
|
||||
onClick={() => {
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useTranslation } from '../../i18n'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { useContextMenu } from '../shared/ContextMenu'
|
||||
import { placesApi } from '../../api/client'
|
||||
import { collectionsApi } from '../../api/collections'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
@@ -157,8 +158,32 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
|
||||
const [categoryPickerOpen, setCategoryPickerOpen] = useState(false)
|
||||
const [saveToListOpen, setSaveToListOpen] = useState(false)
|
||||
|
||||
const [markVisitedBusy, setMarkVisitedBusy] = useState(false)
|
||||
|
||||
const exitSelectMode = () => { setSelectMode(false); setSelectedIds(new Set()) }
|
||||
|
||||
/**
|
||||
* "I have been to these" for the selection, applied wherever the places are
|
||||
* saved in the library (#1469). The server does the matching, so a place saved
|
||||
* under a different name in a list is still found.
|
||||
*/
|
||||
const markSelectionVisited = useCallback(async () => {
|
||||
const ids = Array.from(selectedIds)
|
||||
if (ids.length === 0 || markVisitedBusy) return
|
||||
setMarkVisitedBusy(true)
|
||||
try {
|
||||
const { updated, places: matchedPlaces } = await collectionsApi.setStatusFromTrip(props.tripId, ids, 'visited')
|
||||
if (updated === 0) toast.info(t('collections.markVisitedNone'))
|
||||
else toast.success(t('collections.markedVisitedTrip', { count: matchedPlaces ?? 0 }))
|
||||
exitSelectMode()
|
||||
} catch {
|
||||
toast.error(t('common.error'))
|
||||
} finally {
|
||||
setMarkVisitedBusy(false)
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [selectedIds, markVisitedBusy, props.tripId, t])
|
||||
|
||||
// Auto-exit when all selected places have been removed from the store (e.g. after bulk delete)
|
||||
useEffect(() => {
|
||||
if (!selectMode || selectedIds.size === 0) return
|
||||
@@ -275,6 +300,7 @@ export function usePlacesSidebar(props: PlacesSidebarProps) {
|
||||
selectMode, setSelectMode, selectedIds, setSelectedIds, pendingDeleteIds, setPendingDeleteIds,
|
||||
categoryPickerOpen, setCategoryPickerOpen,
|
||||
saveToListOpen, setSaveToListOpen, collectionsEnabled, tripId,
|
||||
markSelectionVisited, markVisitedBusy,
|
||||
exitSelectMode, toggleSelected, toggleCategoryFilter, dayPickerPlace, setDayPickerPlace,
|
||||
catDropOpen, setCatDropOpen, mobileShowDays, setMobileShowDays,
|
||||
hasTracks, plannedIds, filtered, registerPlaceRow, isAssignedToSelectedDay, inDaySet, openContextMenu,
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { ReactNode, useEffect, useMemo, useState } from 'react'
|
||||
import {
|
||||
Bookmark, Check, CheckCheck, ListChecks, MapPin, MoreHorizontal, Plus,
|
||||
Bookmark, Check, CheckCheck, CheckCircle2, ListChecks, Loader2, MapPin, MoreHorizontal, Plus,
|
||||
SlidersHorizontal, Tag, Trash2, X,
|
||||
} from 'lucide-react'
|
||||
import MDancingTrek from '../../../components/MDancingTrek'
|
||||
import { useTripStore } from '../../../../store/tripStore'
|
||||
import { useAddonStore } from '../../../../store/addonStore'
|
||||
import { useToast } from '../../../../components/shared/Toast'
|
||||
import { collectionsApi } from '../../../../api/collections'
|
||||
import PlaceAvatar from '../../../../components/shared/PlaceAvatar'
|
||||
import { getCategoryIcon } from '../../../../components/shared/categoryIcons'
|
||||
import { resolveTrackColor } from '../../../../components/Map/trackColors'
|
||||
@@ -43,6 +45,8 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
|
||||
const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set())
|
||||
const [categoryPickerOpen, setCategoryPickerOpen] = useState(false)
|
||||
const [saveToListOpen, setSaveToListOpen] = useState(false)
|
||||
const [markVisitedBusy, setMarkVisitedBusy] = useState(false)
|
||||
const toast = useToast()
|
||||
const [confirmDeleteOpen, setConfirmDeleteOpen] = useState(false)
|
||||
|
||||
// Entering the browser from the edit segment starts on the unplanned pool.
|
||||
@@ -85,6 +89,23 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
|
||||
return next
|
||||
})
|
||||
|
||||
/** Mark the selection visited in every list it is saved to (#1469). */
|
||||
const markSelectionVisited = async () => {
|
||||
const ids = [...selectedIds]
|
||||
if (ids.length === 0 || markVisitedBusy) return
|
||||
setMarkVisitedBusy(true)
|
||||
try {
|
||||
const { updated, places: matched } = await collectionsApi.setStatusFromTrip(trip.id, ids, 'visited')
|
||||
if (updated === 0) toast.info(t('collections.markVisitedNone'))
|
||||
else toast.success(t('collections.markedVisitedTrip', { count: matched ?? 0 }))
|
||||
exitSelectMode()
|
||||
} catch {
|
||||
toast.error(t('common.error'))
|
||||
} finally {
|
||||
setMarkVisitedBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Compare the ids, not just the counts: a place removed remotely while another
|
||||
// one is selected keeps the sizes equal without the sets matching.
|
||||
const allSelected = filtered.length > 0 && filtered.every(p => selectedIds.has(p.id))
|
||||
@@ -223,6 +244,15 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
|
||||
<Bookmark size={14} strokeWidth={2} />
|
||||
</BulkBtn>
|
||||
)}
|
||||
{collectionsEnabled && (
|
||||
<BulkBtn
|
||||
label={t('collections.markVisitedSelection')}
|
||||
disabled={selectedIds.size === 0 || markVisitedBusy}
|
||||
onClick={markSelectionVisited}
|
||||
>
|
||||
{markVisitedBusy ? <Loader2 size={14} className="animate-spin" /> : <CheckCircle2 size={14} strokeWidth={2} />}
|
||||
</BulkBtn>
|
||||
)}
|
||||
<BulkBtn label={t('places.deleteSelected')} disabled={selectedIds.size === 0} onClick={() => setConfirmDeleteOpen(true)}>
|
||||
<Trash2 size={14} strokeWidth={2} />
|
||||
</BulkBtn>
|
||||
|
||||
@@ -767,6 +767,7 @@ function PackingItemRow({ item, planner, currentUserId, editMode, canEdit, bagTr
|
||||
}) {
|
||||
const { t, tripId, tripActions } = planner
|
||||
const [bagPickerOpen, setBagPickerOpen] = useState(false)
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
const [creatingBag, setCreatingBag] = useState(false)
|
||||
const [newBagName, setNewBagName] = useState('')
|
||||
|
||||
@@ -821,16 +822,26 @@ function PackingItemRow({ item, planner, currentUserId, editMode, canEdit, bagTr
|
||||
{isPlaceholder ? t('packing.addItemPlaceholder') : item.name}
|
||||
</span>
|
||||
|
||||
{/* Sharing state is an icon, not a sentence (#1525): "Taken care of by
|
||||
Alexander" spelled out took a third of the row away from the item
|
||||
name. The full wording lives on the pill as its label. */}
|
||||
{badgeSharedToMe && (
|
||||
<span className="flex flex-none items-center gap-1 whitespace-nowrap rounded-full bg-[color:var(--m-ic)] px-2 py-[2px] font-geist text-[0.59375rem] font-bold text-m-muted">
|
||||
<HandHelping size={9} strokeWidth={2.2} />
|
||||
{t('packing.takenCareOf', { name: item.owner_username || '' })}
|
||||
<span
|
||||
className="flex h-5 w-5 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-muted"
|
||||
title={t('packing.takenCareOf', { name: item.owner_username || '' })}
|
||||
aria-label={t('packing.takenCareOf', { name: item.owner_username || '' })}
|
||||
>
|
||||
<HandHelping size={11} strokeWidth={2.2} />
|
||||
</span>
|
||||
)}
|
||||
{!badgeSharedToMe && badgeSharedByMe && (
|
||||
<span className="flex flex-none items-center gap-1 whitespace-nowrap rounded-full bg-[color:var(--m-ic)] px-2 py-[2px] font-geist text-[0.59375rem] font-bold text-m-muted">
|
||||
<UserRound size={9} strokeWidth={2.2} />
|
||||
{t('packing.sharedWithCount', { count: recipients.length })}
|
||||
<span
|
||||
className="flex flex-none items-center gap-[2px] rounded-full bg-[color:var(--m-ic)] px-[5px] py-[3px] font-geist text-[0.59375rem] font-bold text-m-muted"
|
||||
title={t('packing.sharedWithCount', { count: recipients.length })}
|
||||
aria-label={t('packing.sharedWithCount', { count: recipients.length })}
|
||||
>
|
||||
<UserRound size={10} strokeWidth={2.2} />
|
||||
{recipients.length}
|
||||
</span>
|
||||
)}
|
||||
{!badgeSharedToMe && !badgeSharedByMe && badgeBroughtBy && (
|
||||
@@ -850,16 +861,18 @@ function PackingItemRow({ item, planner, currentUserId, editMode, canEdit, bagTr
|
||||
</span>
|
||||
)}
|
||||
|
||||
{editMode && bagTrackingEnabled && (
|
||||
{/* A weight nobody entered is not worth a column: "— g" on every row
|
||||
cost as much width as a real value (#1525). */}
|
||||
{editMode && bagTrackingEnabled && item.weight_grams != null && (
|
||||
<span className="flex-none font-geist text-[0.625rem] font-semibold tabular-nums text-m-faint">
|
||||
{item.weight_grams != null ? formatWeight(item.weight_grams) : '— g'}
|
||||
{formatWeight(item.weight_grams)}
|
||||
</span>
|
||||
)}
|
||||
|
||||
{bagTrackingEnabled && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBagPickerOpen(v => !v)}
|
||||
onClick={() => { setMenuOpen(false); setBagPickerOpen(v => !v) }}
|
||||
aria-label={t('packing.bags')}
|
||||
className="h-[18px] w-[18px] flex-none rounded-full"
|
||||
style={bag
|
||||
@@ -868,18 +881,43 @@ function PackingItemRow({ item, planner, currentUserId, editMode, canEdit, bagTr
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Edit and delete moved behind one button (#1525): two round targets
|
||||
plus their gaps were the widest thing on an edit-mode row, and
|
||||
neither is used often enough to earn a permanent seat. */}
|
||||
{editMode && canEdit && (
|
||||
<>
|
||||
<button type="button" onClick={onEdit} aria-label={t('common.edit')} className="flex h-7 w-7 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-muted">
|
||||
<Pencil size={11} strokeWidth={2} />
|
||||
</button>
|
||||
<button type="button" onClick={onDelete} aria-label={t('common.delete')} className="flex h-7 w-7 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-muted">
|
||||
<Trash2 size={11} strokeWidth={2} />
|
||||
</button>
|
||||
</>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setBagPickerOpen(false); setMenuOpen(v => !v) }}
|
||||
aria-label={t('mobileTrip.more')}
|
||||
aria-expanded={menuOpen}
|
||||
className={`flex h-7 w-7 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] ${menuOpen ? 'text-m-ink' : 'text-m-muted'}`}
|
||||
>
|
||||
<MoreHorizontal size={13} strokeWidth={2} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{menuOpen && editMode && canEdit && (
|
||||
<div className="mb-[6px] ml-[28px] overflow-hidden rounded-[13px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-glass)] backdrop-blur-[24px]">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setMenuOpen(false); onEdit() }}
|
||||
className="flex w-full items-center gap-[9px] border-b border-[color:var(--m-rowbr)] px-3 py-2 text-left text-[0.75rem] font-medium text-m-ink"
|
||||
>
|
||||
<Pencil size={12} strokeWidth={2} />
|
||||
{t('common.edit')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { setMenuOpen(false); onDelete() }}
|
||||
className="flex w-full items-center gap-[9px] px-3 py-2 text-left text-[0.75rem] font-medium text-[color:var(--m-st-danger)]"
|
||||
>
|
||||
<Trash2 size={12} strokeWidth={2} />
|
||||
{t('common.delete')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{bagPickerOpen && bagTrackingEnabled && (
|
||||
<div className="mb-[6px] ml-[28px] overflow-hidden rounded-[13px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-glass)] backdrop-blur-[24px]">
|
||||
<button type="button" onClick={() => assignBag(null)} className="flex w-full items-center gap-[9px] border-b border-[color:var(--m-rowbr)] px-3 py-2 text-left text-[0.75rem] font-medium text-m-muted">
|
||||
|
||||
@@ -45,6 +45,7 @@ function JourneyDetailPageDesktop() {
|
||||
hideSkeletons, setHideSkeletons,
|
||||
mapRef, fullMapRef, activeLocationId, handleMarkerClick, handleLocationClick,
|
||||
mapEntries, sidebarMapItems, tripDates, isMobile, tracks,
|
||||
feedEdge, scrollFeedTo,
|
||||
loadJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto,
|
||||
} = useJourneyDetail()
|
||||
|
||||
@@ -210,12 +211,12 @@ function JourneyDetailPageDesktop() {
|
||||
{/* Status badge — keep completed/upcoming/draft/archived, but drop live + synced-with-trips per UX trim */}
|
||||
<div className="hidden md:flex items-center gap-2">
|
||||
{lifecycle !== 'live' && lifecycle !== 'archived' && (
|
||||
<div className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/[0.12] backdrop-blur border border-white/15 rounded-full text-[11px] font-medium">
|
||||
<div className="inline-flex h-[34px] items-center gap-1.5 px-3.5 bg-white/[0.12] backdrop-blur border border-white/15 rounded-full text-[11px] font-medium">
|
||||
{t(`journey.status.${lifecycle === 'upcoming' ? 'upcoming' : lifecycle === 'draft' ? 'draft' : 'completed'}`)}
|
||||
</div>
|
||||
)}
|
||||
{lifecycle === 'archived' && (
|
||||
<div className="inline-flex items-center gap-1.5 px-2.5 py-1 bg-white/[0.12] backdrop-blur border border-white/15 rounded-full text-[11px] font-medium">
|
||||
<div className="inline-flex h-[34px] items-center gap-1.5 px-3.5 bg-white/[0.12] backdrop-blur border border-white/15 rounded-full text-[11px] font-medium">
|
||||
{t('journey.status.archived')}
|
||||
</div>
|
||||
)}
|
||||
@@ -427,6 +428,41 @@ function JourneyDetailPageDesktop() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Jump to the top (where adding lives) and back to the last entry
|
||||
(where reading left off) — #1088. Centred over the feed and
|
||||
clear of both edges: the right one belongs to the Add Entry
|
||||
buttons, the left to the reorder arrows. Zero-height sticky box
|
||||
so it rides the scroll without taking layout space, and each
|
||||
half appears only when there is somewhere to go. */}
|
||||
{!isMobile && (!feedEdge.atTop || !feedEdge.atBottom) && (
|
||||
<div className="sticky bottom-0 z-20 h-0 pointer-events-none">
|
||||
<div className="absolute bottom-6 left-1/2 -translate-x-1/2 flex gap-1.5 pointer-events-auto">
|
||||
{!feedEdge.atTop && (
|
||||
<button
|
||||
onClick={() => scrollFeedTo('top')}
|
||||
aria-label={t('journey.detail.jumpToTop')}
|
||||
title={t('journey.detail.jumpToTop')}
|
||||
className="w-8 h-8 rounded-full flex items-center justify-center shadow-md transition-transform hover:-translate-y-0.5"
|
||||
style={{ background: 'var(--vg-surf)', border: '1px solid var(--vg-line)', color: 'var(--vg-ink)' }}
|
||||
>
|
||||
<ChevronUp size={16} strokeWidth={2.4} />
|
||||
</button>
|
||||
)}
|
||||
{!feedEdge.atBottom && (
|
||||
<button
|
||||
onClick={() => scrollFeedTo('bottom')}
|
||||
aria-label={t('journey.detail.jumpToLast')}
|
||||
title={t('journey.detail.jumpToLast')}
|
||||
className="w-8 h-8 rounded-full flex items-center justify-center shadow-md transition-transform hover:translate-y-0.5"
|
||||
style={{ background: 'var(--vg-surf)', border: '1px solid var(--vg-line)', color: 'var(--vg-ink)' }}
|
||||
>
|
||||
<ChevronDown size={16} strokeWidth={2.4} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
@@ -105,6 +105,7 @@ function buildHook(over: Record<string, unknown> = {}): Record<string, unknown>
|
||||
mapRef: { current: null }, fullMapRef: { current: null },
|
||||
activeLocationId: null, handleMarkerClick: vi.fn(), handleLocationClick: vi.fn(),
|
||||
mapEntries: [], sidebarMapItems: [], tripDates: new Set<string>(), isMobile: false,
|
||||
feedEdge: { atTop: true, atBottom: true }, scrollFeedTo: vi.fn(),
|
||||
loadJourney: vi.fn(), updateEntry: vi.fn(async () => {}), deleteEntry: vi.fn(async () => {}),
|
||||
reorderEntries: vi.fn(async () => {}), uploadPhotos: vi.fn(async () => ({ succeeded: [], failed: [] })),
|
||||
deletePhoto: vi.fn(async () => {}),
|
||||
@@ -458,4 +459,38 @@ describe('JourneyDetailPage wiring', () => {
|
||||
setup({ current: buildDetail({ cover_image: 'covers/j.jpg' }) });
|
||||
expect(document.querySelector('img[src="/uploads/covers/j.jpg"]')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// ── Jump buttons (#1088) ──────────────────────────────────────────────────
|
||||
|
||||
it('FE-JRN-DETWIRE-029: a feed with nowhere to jump shows no buttons', () => {
|
||||
setup({ feedEdge: { atTop: true, atBottom: true } });
|
||||
expect(screen.queryByLabelText('journey.detail.jumpToTop')).not.toBeInTheDocument();
|
||||
expect(screen.queryByLabelText('journey.detail.jumpToLast')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-JRN-DETWIRE-030: each button appears only when that direction is available', () => {
|
||||
const { unmount } = setup({ feedEdge: { atTop: false, atBottom: true } });
|
||||
expect(screen.getByLabelText('journey.detail.jumpToTop')).toBeInTheDocument();
|
||||
expect(screen.queryByLabelText('journey.detail.jumpToLast')).not.toBeInTheDocument();
|
||||
unmount();
|
||||
|
||||
setup({ feedEdge: { atTop: true, atBottom: false } });
|
||||
expect(screen.queryByLabelText('journey.detail.jumpToTop')).not.toBeInTheDocument();
|
||||
expect(screen.getByLabelText('journey.detail.jumpToLast')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-JRN-DETWIRE-031: the buttons scroll the feed to the matching end', () => {
|
||||
const { hook } = setup({ feedEdge: { atTop: false, atBottom: false } });
|
||||
|
||||
fireEvent.click(screen.getByLabelText('journey.detail.jumpToTop'));
|
||||
expect(hook.scrollFeedTo).toHaveBeenCalledWith('top');
|
||||
|
||||
fireEvent.click(screen.getByLabelText('journey.detail.jumpToLast'));
|
||||
expect(hook.scrollFeedTo).toHaveBeenLastCalledWith('bottom');
|
||||
});
|
||||
|
||||
it('FE-JRN-DETWIRE-032: the phone layout has its own chrome and gets no jump buttons', () => {
|
||||
setup({ isMobile: true, feedEdge: { atTop: false, atBottom: false } });
|
||||
expect(screen.queryByLabelText('journey.detail.jumpToTop')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-JRN-DETHOOK-001 to FE-JRN-DETHOOK-022
|
||||
// FE-JRN-DETHOOK-001 to FE-JRN-DETHOOK-025
|
||||
import { describe, it, expect, beforeEach, afterEach, vi, type Mock } from 'vitest';
|
||||
import { useLocation } from 'react-router';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
@@ -335,4 +335,52 @@ describe('useJourneyDetail', () => {
|
||||
await waitFor(() => expect(invalidateSize).toHaveBeenCalled());
|
||||
expect(latest.view).toBe('gallery');
|
||||
});
|
||||
|
||||
// ── Jump to top / to the last entry (#1088) ────────────────────────────────
|
||||
|
||||
/** jsdom has no layout, so hand the feed the numbers a real scrollport would report. */
|
||||
function stubFeedScroll(metrics: { scrollTop: number; scrollHeight: number; clientHeight: number }) {
|
||||
const feed = screen.getByTestId('feed');
|
||||
for (const [prop, value] of Object.entries(metrics)) {
|
||||
Object.defineProperty(feed, prop, { value, configurable: true });
|
||||
}
|
||||
return feed;
|
||||
}
|
||||
|
||||
it('FE-JRN-DETHOOK-023: a feed short enough to read in one go offers no jump', async () => {
|
||||
setup();
|
||||
await waitFor(() => expect(latest.current).not.toBeNull());
|
||||
const feed = stubFeedScroll({ scrollTop: 0, scrollHeight: 900, clientHeight: 800 });
|
||||
|
||||
fireEvent.scroll(feed);
|
||||
await waitFor(() => expect(latest.feedEdge).toEqual({ atTop: true, atBottom: true }));
|
||||
});
|
||||
|
||||
it('FE-JRN-DETHOOK-024: deep in a long journal both directions are offered', async () => {
|
||||
setup();
|
||||
await waitFor(() => expect(latest.current).not.toBeNull());
|
||||
const feed = stubFeedScroll({ scrollTop: 3000, scrollHeight: 9000, clientHeight: 800 });
|
||||
|
||||
fireEvent.scroll(feed);
|
||||
await waitFor(() => expect(latest.feedEdge).toEqual({ atTop: false, atBottom: false }));
|
||||
|
||||
// Back at the bottom only the way up is left.
|
||||
Object.defineProperty(feed, 'scrollTop', { value: 8200, configurable: true });
|
||||
fireEvent.scroll(feed);
|
||||
await waitFor(() => expect(latest.feedEdge).toEqual({ atTop: false, atBottom: true }));
|
||||
});
|
||||
|
||||
it('FE-JRN-DETHOOK-025: the jumps scroll the feed, not the window', async () => {
|
||||
setup();
|
||||
await waitFor(() => expect(latest.current).not.toBeNull());
|
||||
const feed = stubFeedScroll({ scrollTop: 3000, scrollHeight: 9000, clientHeight: 800 });
|
||||
const scrollTo = vi.fn();
|
||||
Object.defineProperty(feed, 'scrollTo', { value: scrollTo, configurable: true });
|
||||
|
||||
latest.scrollFeedTo('top');
|
||||
expect(scrollTo).toHaveBeenCalledWith({ top: 0, behavior: 'smooth' });
|
||||
|
||||
latest.scrollFeedTo('bottom');
|
||||
expect(scrollTo).toHaveBeenLastCalledWith({ top: 9000, behavior: 'smooth' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -186,6 +186,58 @@ export function useJourneyDetail() {
|
||||
return () => scrollCleanupRef.current?.()
|
||||
}, [current?.entries, setupScrollSync])
|
||||
|
||||
// ── Jump to top / to the last entry (#1088) ───────────────────────────────
|
||||
// A long journal is a long scroll: everything that adds to it — the entry
|
||||
// button, the gallery upload — sits at the top, and where you were reading
|
||||
// sits at the bottom. Two buttons beat two trips of the scroll wheel.
|
||||
const [feedEdge, setFeedEdge] = useState<{ atTop: boolean; atBottom: boolean }>({ atTop: true, atBottom: true })
|
||||
|
||||
useEffect(() => {
|
||||
const feed = feedRef.current
|
||||
if (!feed) return
|
||||
// 400px of travel before either button is worth offering; below that the
|
||||
// scroll is short enough that a button is just clutter.
|
||||
const THRESHOLD = 400
|
||||
let frame: number | null = null
|
||||
let pending = false
|
||||
const measure = () => {
|
||||
pending = false
|
||||
const el = feedRef.current
|
||||
if (!el) return
|
||||
const scrolled = el.scrollTop
|
||||
const remaining = el.scrollHeight - el.clientHeight - scrolled
|
||||
setFeedEdge(prev => {
|
||||
const next = { atTop: scrolled <= THRESHOLD, atBottom: remaining <= THRESHOLD }
|
||||
return prev.atTop === next.atTop && prev.atBottom === next.atBottom ? prev : next
|
||||
})
|
||||
}
|
||||
// The "already scheduled" flag is its own variable rather than the frame id:
|
||||
// the id is only assigned once requestAnimationFrame returns, which is after
|
||||
// the callback has already run whenever rAF fires synchronously.
|
||||
const onScroll = () => {
|
||||
if (pending) return
|
||||
pending = true
|
||||
frame = window.requestAnimationFrame(measure)
|
||||
}
|
||||
feed.addEventListener('scroll', onScroll, { passive: true })
|
||||
measure()
|
||||
// Entries load in batches, so the scrollable height grows after mount.
|
||||
const ro = new ResizeObserver(measure)
|
||||
ro.observe(feed)
|
||||
if (feed.firstElementChild) ro.observe(feed.firstElementChild)
|
||||
return () => {
|
||||
feed.removeEventListener('scroll', onScroll)
|
||||
ro.disconnect()
|
||||
if (frame != null) window.cancelAnimationFrame(frame)
|
||||
}
|
||||
}, [current?.id, view])
|
||||
|
||||
const scrollFeedTo = useCallback((edge: 'top' | 'bottom') => {
|
||||
const el = feedRef.current
|
||||
if (!el) return
|
||||
el.scrollTo({ top: edge === 'top' ? 0 : el.scrollHeight, behavior: 'smooth' })
|
||||
}, [])
|
||||
|
||||
const handleMarkerClick = useCallback((entryId: string) => {
|
||||
const el = document.querySelector(`[data-entry-id="${entryId}"]`)
|
||||
if (!el) return
|
||||
@@ -303,6 +355,7 @@ export function useJourneyDetail() {
|
||||
hideSkeletons, setHideSkeletons,
|
||||
mapRef, fullMapRef, activeLocationId, handleMarkerClick, handleLocationClick,
|
||||
mapEntries, sidebarMapItems, tripDates, isMobile, tracks,
|
||||
feedEdge, scrollFeedTo,
|
||||
loadJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user