mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 16:33:16 +00:00
feat(journey): complete sharing, photo drafts and Studio maps
Connect the Journey backend to the web and mobile UI, including public access and subscriptions, day recordings, photo drafts and per-map framing. Preserve legacy recording responses and cover the new behavior in every locale.
This commit is contained in:
@@ -658,9 +658,15 @@
|
||||
],
|
||||
"mobile": ["src/mobile/screens/journey/MJourneySettingsSheet.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Journey entries from photos: useJourneyEntriesFromPhotos",
|
||||
"hooks": ["src/components/Journey/useJourneyEntriesFromPhotos.ts"],
|
||||
"desktop": ["src/components/Journey/JourneyFromPhotosDialog.tsx"],
|
||||
"mobile": ["src/mobile/screens/journey/MJourneyFromPhotosSheet.tsx"]
|
||||
},
|
||||
{
|
||||
"feature": "Journey settings: useJourneyShareLink",
|
||||
"hooks": ["src/components/Journey/useJourneyShareLink.ts"],
|
||||
"hooks": ["src/components/Journey/useJourneyShareLink.ts", "src/components/Journey/useJourneyShareAccess.ts"],
|
||||
"desktop": ["src/components/Journey/JourneyShareSection.tsx"],
|
||||
"mobile": ["src/mobile/screens/journey/MJourneySettingsSheet.tsx"]
|
||||
},
|
||||
|
||||
@@ -72,6 +72,7 @@ const JourneyDetailPage = lazyWithRetry(() => import('./pages/JourneyDetailPage'
|
||||
const JourneyStudioPage = lazyWithRetry(() => import('./pages/JourneyStudioPage'))
|
||||
const CollectionsPage = lazyWithRetry(() => import('./pages/CollectionsPage'))
|
||||
const JourneyPublicPage = lazyWithRetry(() => import('./pages/JourneyPublicPage'))
|
||||
const JourneyFollowPage = lazyWithRetry(() => import('./pages/JourneyFollowPage'))
|
||||
const SharedTripPage = lazyWithRetry(() => import('./pages/SharedTripPage'))
|
||||
const JoinTripPage = lazyWithRetry(() => import('./pages/JoinTripPage'))
|
||||
const InAppNotificationsPage = lazyWithRetry(() => import('./pages/InAppNotificationsPage.tsx'))
|
||||
@@ -518,6 +519,7 @@ export default function App() {
|
||||
<Route path="/login" element={<PublicRoute redirectAuthed><LoginPage /></PublicRoute>} />
|
||||
<Route path="/shared/:token" element={<PublicRoute><SharedTripPage /></PublicRoute>} />
|
||||
<Route path="/public/journey/:token" element={<PublicRoute><JourneyPublicPage /></PublicRoute>} />
|
||||
<Route path="/public/journey-follow/:action" element={<PublicRoute><JourneyFollowPage /></PublicRoute>} />
|
||||
<Route path="/register" element={<PublicRoute redirectAuthed><LoginPage /></PublicRoute>} />
|
||||
<Route path="/forgot-password" element={<PublicRoute><ForgotPasswordPage /></PublicRoute>} />
|
||||
<Route path="/native-handoff" element={<PublicRoute><NativeHandoffPage /></PublicRoute>} />
|
||||
|
||||
@@ -1047,12 +1047,6 @@ export const journeyApi = {
|
||||
createShareLink: (id: number, perms: JourneyShareLinkRequest) => apiClient.post(`/journeys/${id}/share-link`, perms).then(r => r.data),
|
||||
deleteShareLink: (id: number) => apiClient.delete(`/journeys/${id}/share-link`).then(r => r.data),
|
||||
getPublicJourney: (token: string) => apiClient.get(`/public/journey/${token}`).then(r => r.data),
|
||||
/**
|
||||
* A reader's password for a protected link (#2553). The answer sets the link's
|
||||
* unlock cookie, which every later read and photo of that link sends along.
|
||||
*/
|
||||
unlockPublicJourney: (token: string, password: string): Promise<{ success: true }> =>
|
||||
apiClient.post(`/public/journey/${token}/unlock`, { password }).then(r => r.data),
|
||||
}
|
||||
|
||||
// Photo providers (Immich, Synology Photos, …) behind /api/integrations/memories.
|
||||
|
||||
@@ -28,7 +28,7 @@ const upstream = { timeout: DAWARICH_UPSTREAM_TIMEOUT_MS };
|
||||
*/
|
||||
export const journeyRecordingsApi = {
|
||||
list: (journeyId: number, signal?: AbortSignal): Promise<JourneyRecordedDaysResponse> =>
|
||||
apiClient.get(base(journeyId), { signal }).then((r) => r.data),
|
||||
apiClient.get(base(journeyId), { signal, params: { includeGpx: true } }).then((r) => r.data),
|
||||
prep: (journeyId: number, signal?: AbortSignal): Promise<JourneyRecordingPrep> =>
|
||||
apiClient.get(`${base(journeyId)}/prep`, { signal }).then((r) => r.data),
|
||||
preview: (
|
||||
|
||||
@@ -34,6 +34,10 @@ export const journeySocialApi = {
|
||||
|
||||
publicComments: (token: string, signal?: AbortSignal): Promise<JourneyPublicCommentsResponse> =>
|
||||
apiClient.get(`${pub(token)}/comments`, { signal }).then((r) => r.data),
|
||||
recordPublicView: (token: string): Promise<{ success: true }> =>
|
||||
apiClient.post(`${pub(token)}/view`).then((r) => r.data),
|
||||
unlockPublicJourney: (token: string, password: string): Promise<{ success: true }> =>
|
||||
apiClient.post(`${pub(token)}/unlock`, { password }).then((r) => r.data),
|
||||
addPublicComment: (
|
||||
token: string,
|
||||
entryId: number,
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { JourneyRecordedDay } from '@trek/shared';
|
||||
import { Route } from 'lucide-react';
|
||||
import { FileUp, RefreshCw, Route, Trash2 } from 'lucide-react';
|
||||
import type React from 'react';
|
||||
import { useRef } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { formatDistance } from '../../utils/units';
|
||||
import { ContextMenu, useContextMenu } from '../shared/ContextMenu';
|
||||
import DawarichIcon from '../shared/DawarichIcon';
|
||||
import { fs } from '../shared/DialogShell';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
@@ -15,14 +17,28 @@ const ROUND =
|
||||
const PILL =
|
||||
'inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 font-bold tabular-nums transition-colors aria-disabled:cursor-default [&:not([aria-disabled=true])]:hover:bg-surface-hover';
|
||||
|
||||
const GPX_TYPES = '.gpx,application/gpx+xml';
|
||||
|
||||
/** Reading a day's route from a GPX file (#3085): open to every editor, with or without Dawarich. */
|
||||
export interface DayGpx {
|
||||
/** The day's route read from a file, if it keeps one. */
|
||||
day: JourneyRecordedDay | undefined;
|
||||
canImport: boolean;
|
||||
busy: boolean;
|
||||
onImport: (file: File) => void;
|
||||
onRemove: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The recorded route of one journey day in its header (JRN-01).
|
||||
* The recorded route of one journey day in its header (JRN-01, #3085).
|
||||
*
|
||||
* A day that keeps its route shows how far it went, for everyone who can open
|
||||
* the journey, with whose recording it is and since when in the tooltip; an
|
||||
* editor opens it to check it against Dawarich again, replace it or drop it.
|
||||
* A day without one offers an editor whose Dawarich answers to take it over;
|
||||
* offline the offer stays, dimmed, and says why.
|
||||
* editor opens a Dawarich day to check it again, replace it or drop it, and a
|
||||
* day read from a GPX file to replace or drop that file's route. A day without
|
||||
* one offers an editor one button: take it over from Dawarich, read it from a
|
||||
* GPX file, or a small menu with both when both are possible. Offline the
|
||||
* Dawarich offer stays, dimmed, and says why.
|
||||
*/
|
||||
export default function JourneyDayRecordingButton({
|
||||
day,
|
||||
@@ -30,23 +46,48 @@ export default function JourneyDayRecordingButton({
|
||||
canTakeOver,
|
||||
needsConnection,
|
||||
onOpen,
|
||||
gpx,
|
||||
}: {
|
||||
/** The day's route taken over from Dawarich. */
|
||||
day: JourneyRecordedDay | undefined;
|
||||
canEdit: boolean;
|
||||
canTakeOver: boolean;
|
||||
needsConnection: boolean;
|
||||
onOpen: () => void;
|
||||
gpx?: DayGpx;
|
||||
}): React.ReactElement | null {
|
||||
const { t, locale } = useTranslation();
|
||||
const unit = useSettingsStore((s) => s.settings.distance_unit) ?? 'metric';
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
const menu = useContextMenu();
|
||||
|
||||
const canImportGpx = !!gpx?.canImport && canEdit;
|
||||
const pickFile = () => fileRef.current?.click();
|
||||
const fileInput = canImportGpx ? (
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept={GPX_TYPES}
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = '';
|
||||
if (file) gpx?.onImport(file);
|
||||
}}
|
||||
/>
|
||||
) : null;
|
||||
|
||||
const keptLabel = (kept: JourneyRecordedDay) => {
|
||||
const distance = formatDistance(kept.stats.distanceMeters / 1000, unit);
|
||||
const date = new Date(kept.savedAt).toLocaleDateString(locale, { day: 'numeric', month: 'short' });
|
||||
const text = kept.importedBy
|
||||
? t('journey.recording.keptBy', { distance, name: kept.importedBy.username, date })
|
||||
: t('journey.recording.keptOn', { distance, date });
|
||||
return { distance, label: kept.provisional ? `${text} ${t('journey.recording.keptRunning')}` : text };
|
||||
};
|
||||
|
||||
if (day) {
|
||||
const distance = formatDistance(day.stats.distanceMeters / 1000, unit);
|
||||
const date = new Date(day.savedAt).toLocaleDateString(locale, { day: 'numeric', month: 'short' });
|
||||
const kept = day.importedBy
|
||||
? t('journey.recording.keptBy', { distance, name: day.importedBy.username, date })
|
||||
: t('journey.recording.keptOn', { distance, date });
|
||||
const label = day.provisional ? `${kept} ${t('journey.recording.keptRunning')}` : kept;
|
||||
const { distance, label } = keptLabel(day);
|
||||
return (
|
||||
<Tooltip label={label} placement="top">
|
||||
<button
|
||||
@@ -66,21 +107,104 @@ export default function JourneyDayRecordingButton({
|
||||
);
|
||||
}
|
||||
|
||||
if (!canTakeOver && !needsConnection) return null;
|
||||
if (gpx?.day) {
|
||||
const { distance, label } = keptLabel(gpx.day);
|
||||
const full = `${label} ${t('journey.recording.gpx.source')}`;
|
||||
return (
|
||||
<>
|
||||
{fileInput}
|
||||
<Tooltip label={full} placement="top" disabled={!!menu.menu}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={
|
||||
canImportGpx
|
||||
? (e) =>
|
||||
menu.open(
|
||||
e,
|
||||
[
|
||||
{ label: t('journey.recording.replace'), icon: RefreshCw, onClick: pickFile },
|
||||
{ label: t('journey.recording.remove'), icon: Trash2, onClick: gpx.onRemove, danger: true },
|
||||
],
|
||||
true
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
aria-disabled={!canImportGpx || gpx.busy}
|
||||
aria-label={full}
|
||||
aria-haspopup={canImportGpx ? 'menu' : undefined}
|
||||
data-testid="journey-day-recording"
|
||||
className={PILL}
|
||||
style={{ ...fs(10.5), background: 'var(--vg-surf2)', color: 'var(--vg-ink)' }}
|
||||
>
|
||||
<FileUp size={12} strokeWidth={2.4} aria-hidden="true" />
|
||||
{distance}
|
||||
</button>
|
||||
</Tooltip>
|
||||
<ContextMenu menu={menu.menu} onClose={menu.close} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
if (!canTakeOver && !needsConnection && !canImportGpx) return null;
|
||||
|
||||
// Only a file to read: the button opens the file picker straight away.
|
||||
if (canImportGpx && !canTakeOver) {
|
||||
const label = t('journey.recording.gpx.import');
|
||||
return (
|
||||
<>
|
||||
{fileInput}
|
||||
<Tooltip label={label} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
onClick={gpx?.busy ? undefined : pickFile}
|
||||
aria-disabled={!!gpx?.busy}
|
||||
aria-label={label}
|
||||
data-testid="journey-day-recording"
|
||||
className={ROUND}
|
||||
style={{ background: 'var(--vg-surf2)', color: 'var(--vg-ink3)' }}
|
||||
>
|
||||
<Route size={14} strokeWidth={2.2} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const label = canTakeOver ? t('journey.recording.takeOver') : t('dawarich.error.offline');
|
||||
return (
|
||||
<Tooltip label={label} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
onClick={canTakeOver ? onOpen : undefined}
|
||||
aria-disabled={!canTakeOver}
|
||||
aria-label={label}
|
||||
data-testid="journey-day-recording"
|
||||
className={ROUND}
|
||||
style={{ background: 'var(--vg-surf2)' }}
|
||||
>
|
||||
<DawarichIcon size={15} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<>
|
||||
{fileInput}
|
||||
<Tooltip label={label} placement="top" disabled={!!menu.menu}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={
|
||||
canTakeOver
|
||||
? canImportGpx
|
||||
? (e) =>
|
||||
menu.open(
|
||||
e,
|
||||
[
|
||||
{ label: t('journey.recording.takeOver'), icon: Route, onClick: onOpen },
|
||||
{ label: t('journey.recording.gpx.import'), icon: FileUp, onClick: pickFile },
|
||||
],
|
||||
true
|
||||
)
|
||||
: onOpen
|
||||
: canImportGpx
|
||||
? pickFile
|
||||
: undefined
|
||||
}
|
||||
aria-disabled={!canTakeOver && !canImportGpx}
|
||||
aria-label={label}
|
||||
aria-haspopup={canTakeOver && canImportGpx ? 'menu' : undefined}
|
||||
data-testid="journey-day-recording"
|
||||
className={ROUND}
|
||||
style={{ background: 'var(--vg-surf2)' }}
|
||||
>
|
||||
<DawarichIcon size={15} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<ContextMenu menu={menu.menu} onClose={menu.close} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useState, useEffect, type ReactNode } from 'react'
|
||||
import { MapPin, Clock, Pencil, Trash2, Plus, PencilLine, RouteOff, X } from 'lucide-react'
|
||||
import { formatLocationName } from '../../utils/formatters'
|
||||
import { useTranslation } from '../../i18n'
|
||||
@@ -14,9 +14,11 @@ import { MoodChip, WeatherChip } from './JourneyDetailPageChips'
|
||||
import { ExpandableStory } from './JourneyDetailPageExpandableStory'
|
||||
import { VerdictSection } from './JourneyDetailPageVerdictSection'
|
||||
|
||||
export function EntryCard({ entry, readOnly, onEdit, onDelete, onPhotoClick }: {
|
||||
export function EntryCard({ entry, readOnly, onEdit, onDelete, onPhotoClick, comments }: {
|
||||
entry: JourneyEntry
|
||||
readOnly?: boolean
|
||||
/** The comment thread under the entry (#1702), drawn by the page. */
|
||||
comments?: ReactNode
|
||||
onEdit: () => void
|
||||
onDelete: () => void
|
||||
onPhotoClick: (photos: JourneyPhoto[], index: number) => void
|
||||
@@ -178,6 +180,8 @@ export function EntryCard({ entry, readOnly, onEdit, onDelete, onPhotoClick }: {
|
||||
)))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{comments && <div className="pt-3 mt-3 border-t border-zinc-100 dark:border-zinc-800">{comments}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useState, useRef } from 'react'
|
||||
import { RefreshCw, Camera, X, Play } from 'lucide-react'
|
||||
import { RefreshCw, Camera, X, Play, NotebookPen } from 'lucide-react'
|
||||
import JourneyFromPhotosDialog from './JourneyFromPhotosDialog'
|
||||
import { useJourneyStore } from '../../store/journeyStore'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useToast } from '../shared/Toast'
|
||||
@@ -68,6 +69,11 @@ export function GalleryView({ entries, gallery, journeyId, userId, trips, canEdi
|
||||
// Deleting is final on the server and takes the photo out of every entry that
|
||||
// uses it too, so the tile only asks; the dialog does the deleting (#2593).
|
||||
const [deleteTarget, setDeleteTarget] = useState<GalleryPhoto | null>(null)
|
||||
const [showFromPhotos, setShowFromPhotos] = useState(false)
|
||||
const coverOf = (galleryPhotoId: number) => {
|
||||
const photo = allPhotos.find(p => p.id === galleryPhotoId)
|
||||
return photo && !posterlessVideo(photo) ? photoUrl(photo, 'thumbnail') : null
|
||||
}
|
||||
|
||||
const handleDeletePhoto = async (galleryPhotoId: number) => {
|
||||
const store = useJourneyStore.getState()
|
||||
@@ -89,7 +95,26 @@ export function GalleryView({ entries, gallery, journeyId, userId, trips, canEdi
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-[0.07em]" style={{ background: 'var(--vg-surf2)', color: 'var(--vg-ink3)' }}>
|
||||
<Camera size={11} /> {allPhotos.length} {t('journey.detail.photos', { count: allPhotos.length })}
|
||||
</span>
|
||||
{/* #1920: the gallery's loose photos as drafts, grouped by day and place. */}
|
||||
{canEdit && allPhotos.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowFromPhotos(true)}
|
||||
className="inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-caption font-semibold transition-colors hover:bg-surface-hover"
|
||||
style={{ background: 'var(--vg-surf2)', color: 'var(--vg-ink)' }}
|
||||
>
|
||||
<NotebookPen size={13} /> {t('journey.fromPhotos.title')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{showFromPhotos && (
|
||||
<JourneyFromPhotosDialog
|
||||
journeyId={journeyId}
|
||||
coverOf={coverOf}
|
||||
onCreated={onRefresh}
|
||||
onClose={() => setShowFromPhotos(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{allPhotos.length === 0 ? (
|
||||
<EmptyState scene="journey" title={t('journey.detail.noPhotos')} />
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import JourneyEntryComments, { GuestEntryComments, MemberEntryComments } from './JourneyEntryComments';
|
||||
|
||||
vi.mock('../../i18n', () => ({ useTranslation: () => ({ t: (key: string) => key, locale: 'en' }) }));
|
||||
|
||||
afterEach(() => localStorage.removeItem('trek.journey.guestName'));
|
||||
|
||||
const entry = {
|
||||
id: 17,
|
||||
author_name: 'Robin',
|
||||
is_guest: false,
|
||||
body: 'A quiet spot by the river',
|
||||
created_at: '2026-05-14T09:00:00Z',
|
||||
};
|
||||
|
||||
describe('Journey entry comments', () => {
|
||||
it('opens and closes a thread and omits the control for an empty read-only thread', () => {
|
||||
const onAdd = vi.fn();
|
||||
const { rerender } = render(<JourneyEntryComments comments={[entry]} canWrite={false} onAdd={onAdd} />);
|
||||
const control = () => screen.getByRole('button', { name: 'journey.comments.count' });
|
||||
expect(control()).toHaveAttribute('aria-expanded', 'false');
|
||||
fireEvent.click(control());
|
||||
expect(control()).toHaveAttribute('aria-expanded', 'true');
|
||||
expect(screen.getByText(entry.body)).toBeVisible();
|
||||
fireEvent.click(control());
|
||||
expect(screen.queryByText(entry.body)).toBeNull();
|
||||
rerender(<JourneyEntryComments comments={[]} canWrite={false} onAdd={onAdd} />);
|
||||
expect(screen.queryByRole('button')).toBeNull();
|
||||
});
|
||||
|
||||
it('takes a guest name, shows a refusal, and remembers the name after a successful retry', async () => {
|
||||
const addComment = vi.fn().mockResolvedValueOnce('rate_limited').mockResolvedValueOnce('ok');
|
||||
render(<GuestEntryComments entryId={13} thread={{ commentsOpen: true, byEntry: new Map(), addComment }} />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'journey.comments.write' }));
|
||||
const text = screen.getByRole('textbox', { name: 'journey.comments.write' });
|
||||
const name = screen.getByRole('textbox', { name: 'common.name' });
|
||||
const send = screen.getByRole('button', { name: 'journey.comments.send' });
|
||||
fireEvent.change(text, { target: { value: ' Walked here too ' } });
|
||||
expect(send).toBeDisabled();
|
||||
fireEvent.change(name, { target: { value: ' Lee ' } });
|
||||
fireEvent.click(send);
|
||||
expect(await screen.findByText('common.tooManyAttempts')).toBeVisible();
|
||||
expect(text).toHaveValue(' Walked here too ');
|
||||
expect(localStorage.getItem('trek.journey.guestName')).toBeNull();
|
||||
fireEvent.click(send);
|
||||
await waitFor(() => expect(text).toHaveValue(''));
|
||||
expect(addComment).toHaveBeenLastCalledWith(13, 'Lee', 'Walked here too');
|
||||
expect(localStorage.getItem('trek.journey.guestName')).toBe('Lee');
|
||||
});
|
||||
|
||||
it('lets the moderator show and delete a hidden comment and keeps the public-sharing hint visible', () => {
|
||||
const setHidden = vi.fn().mockResolvedValue(true);
|
||||
const remove = vi.fn().mockResolvedValue(true);
|
||||
const thread = {
|
||||
byEntry: new Map([[13, [{ ...entry, hidden: true }]]]),
|
||||
canModerate: true,
|
||||
add: vi.fn().mockResolvedValue(true),
|
||||
setHidden,
|
||||
remove,
|
||||
};
|
||||
render(<MemberEntryComments entryId={13} thread={thread} defaultOpen />);
|
||||
expect(screen.getByText('journey.comments.hidden')).toBeVisible();
|
||||
expect(screen.getByText('journey.comments.publicHint')).toBeVisible();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'journey.comments.show' }));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'common.delete' }));
|
||||
expect(setHidden).toHaveBeenCalledWith(entry.id, false);
|
||||
expect(remove).toHaveBeenCalledWith(entry.id);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,312 @@
|
||||
import { JOURNEY_COMMENT_MAX_LENGTH, JOURNEY_GUEST_NAME_MAX_LENGTH } from '@trek/shared';
|
||||
import { Eye, EyeOff, MessageCircle, SendHorizontal, Trash2 } from 'lucide-react';
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
|
||||
/** One comment as the thread draws it: in the app and on the shared page alike. */
|
||||
export interface EntryCommentItem {
|
||||
id: number;
|
||||
author_name: string | null;
|
||||
is_guest: boolean;
|
||||
body: string;
|
||||
created_at: string | null;
|
||||
hidden?: boolean;
|
||||
own?: boolean;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
comments: EntryCommentItem[];
|
||||
/** Whether a new comment can be written here at all. */
|
||||
canWrite: boolean;
|
||||
/** A reader of the shared page signs with a name; a member writes as their account. */
|
||||
guest?: boolean;
|
||||
/** An editor may hide and delete every comment. */
|
||||
canModerate?: boolean;
|
||||
/** Saves a comment; resolves null when it was taken, else the text to show under the field. */
|
||||
onAdd: (body: string, name: string) => Promise<string | null>;
|
||||
onHide?: (id: number, hidden: boolean) => Promise<boolean>;
|
||||
onDelete?: (id: number) => Promise<boolean>;
|
||||
/** Members are told when the share link shows their comments to its readers too. */
|
||||
publicHint?: boolean;
|
||||
/** Start unfolded, where the thread already has a section of its own. */
|
||||
defaultOpen?: boolean;
|
||||
}
|
||||
|
||||
const GUEST_NAME_KEY = 'trek.journey.guestName';
|
||||
|
||||
function rememberedName(): string {
|
||||
try {
|
||||
return localStorage.getItem(GUEST_NAME_KEY) ?? '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function rememberName(name: string) {
|
||||
try {
|
||||
localStorage.setItem(GUEST_NAME_KEY, name);
|
||||
} catch {
|
||||
// A private window keeps no name; the field simply starts empty next time.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The comments under a journal entry (#1702): folded into one quiet line until
|
||||
* somebody opens it, then the thread oldest first and a field to add one.
|
||||
* The same thread serves the journey's members in the app and the readers of a
|
||||
* shared link, who sign with a name instead of an account.
|
||||
*/
|
||||
export default function JourneyEntryComments({
|
||||
comments,
|
||||
canWrite,
|
||||
guest,
|
||||
canModerate,
|
||||
onAdd,
|
||||
onHide,
|
||||
onDelete,
|
||||
publicHint,
|
||||
defaultOpen,
|
||||
}: Props) {
|
||||
const { t, locale } = useTranslation();
|
||||
const [open, setOpen] = useState(!!defaultOpen);
|
||||
const [body, setBody] = useState('');
|
||||
const [name, setName] = useState(guest ? rememberedName : '');
|
||||
const [trap, setTrap] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
if (!canWrite && comments.length === 0) return null;
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (busy || !body.trim() || (guest && !name.trim())) return;
|
||||
// Only a bot fills the field people never see: it is told all went well.
|
||||
if (trap) {
|
||||
setBody('');
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setMessage(null);
|
||||
const failure = await onAdd(body.trim(), name.trim());
|
||||
setBusy(false);
|
||||
if (failure) {
|
||||
setMessage(failure);
|
||||
return;
|
||||
}
|
||||
if (guest) rememberName(name.trim());
|
||||
setBody('');
|
||||
};
|
||||
|
||||
const dateOf = (iso: string | null) =>
|
||||
iso ? new Date(iso).toLocaleDateString(locale || undefined, { day: 'numeric', month: 'short' }) : '';
|
||||
|
||||
const toggle = (
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={open}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setOpen((shown) => !shown);
|
||||
}}
|
||||
className="inline-flex items-center gap-1.5 self-start text-caption font-medium text-content-faint transition-colors hover:text-content"
|
||||
>
|
||||
<MessageCircle size={13} />
|
||||
{comments.length > 0 ? t('journey.comments.count', { count: comments.length }) : t('journey.comments.write')}
|
||||
</button>
|
||||
);
|
||||
if (!open) return toggle;
|
||||
|
||||
return (
|
||||
// The thread sits inside clickable cards: a click in it must not open the entry.
|
||||
<div className="flex flex-col gap-3" onClick={(e) => e.stopPropagation()} role="presentation">
|
||||
{!defaultOpen && toggle}
|
||||
{comments.length > 0 && (
|
||||
<ul className="flex flex-col gap-2.5">
|
||||
{comments.map((c) => {
|
||||
const mayDelete = !!onDelete && (canModerate || c.own);
|
||||
const mayHide = !!onHide && canModerate;
|
||||
return (
|
||||
<li key={c.id} className={`group flex items-start gap-2 ${c.hidden ? 'opacity-50' : ''}`}>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-1.5 text-caption">
|
||||
<span className="font-semibold text-content">
|
||||
{c.author_name ?? t('journey.comments.deletedUser')}
|
||||
</span>
|
||||
{c.is_guest && (
|
||||
<span className="rounded-full bg-surface-secondary px-1.5 py-px text-caption text-content-faint">
|
||||
{t('journey.comments.guest')}
|
||||
</span>
|
||||
)}
|
||||
{c.hidden && (
|
||||
<span className="rounded-full bg-surface-secondary px-1.5 py-px text-caption text-content-faint">
|
||||
{t('journey.comments.hidden')}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-content-faint">{dateOf(c.created_at)}</span>
|
||||
</div>
|
||||
<p className="mt-0.5 whitespace-pre-wrap break-words text-body text-content-muted">{c.body}</p>
|
||||
</div>
|
||||
{(mayHide || mayDelete) && (
|
||||
<div className="flex flex-none items-center gap-0.5 opacity-40 transition-opacity group-hover:opacity-100">
|
||||
{mayHide && (
|
||||
<Tooltip
|
||||
label={c.hidden ? t('journey.comments.show') : t('journey.comments.hide')}
|
||||
placement="top"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={c.hidden ? t('journey.comments.show') : t('journey.comments.hide')}
|
||||
onClick={() => void onHide!(c.id, !c.hidden)}
|
||||
className="flex h-7 w-7 items-center justify-center rounded-full text-content-faint hover:bg-surface-secondary hover:text-content"
|
||||
>
|
||||
{c.hidden ? <Eye size={13} /> : <EyeOff size={13} />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
{mayDelete && (
|
||||
<Tooltip label={t('common.delete')} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('common.delete')}
|
||||
onClick={() => void onDelete!(c.id)}
|
||||
className="flex h-7 w-7 items-center justify-center rounded-full text-content-faint hover:bg-danger-soft hover:text-danger"
|
||||
>
|
||||
<Trash2 size={13} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{canWrite && (
|
||||
<form onSubmit={(e) => void submit(e)} className="flex flex-col gap-2">
|
||||
{guest && (
|
||||
<input
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
maxLength={JOURNEY_GUEST_NAME_MAX_LENGTH}
|
||||
placeholder={t('common.name')}
|
||||
aria-label={t('common.name')}
|
||||
autoComplete="name"
|
||||
className="w-full rounded-xl border border-edge bg-surface px-3 py-2 text-body text-content outline-none placeholder:text-content-faint focus:border-content-faint"
|
||||
/>
|
||||
)}
|
||||
{/* Left empty by people: the field sits off screen and out of the tab order. */}
|
||||
<input
|
||||
value={trap}
|
||||
onChange={(e) => setTrap(e.target.value)}
|
||||
name="website"
|
||||
tabIndex={-1}
|
||||
autoComplete="off"
|
||||
aria-hidden="true"
|
||||
className="absolute -start-[9999px] h-px w-px opacity-0"
|
||||
/>
|
||||
<div className="flex items-end gap-2">
|
||||
<textarea
|
||||
value={body}
|
||||
onChange={(e) => setBody(e.target.value)}
|
||||
maxLength={JOURNEY_COMMENT_MAX_LENGTH}
|
||||
rows={1}
|
||||
placeholder={t('journey.comments.write')}
|
||||
aria-label={t('journey.comments.write')}
|
||||
className="max-h-40 min-h-[38px] flex-1 resize-none rounded-xl border border-edge bg-surface px-3 py-2 text-body text-content outline-none [field-sizing:content] placeholder:text-content-faint focus:border-content-faint"
|
||||
/>
|
||||
<Tooltip label={t('journey.comments.send')} placement="top">
|
||||
<button
|
||||
type="submit"
|
||||
aria-label={t('journey.comments.send')}
|
||||
disabled={busy || !body.trim() || (guest && !name.trim())}
|
||||
className="flex h-[38px] w-[38px] flex-none items-center justify-center rounded-full bg-accent text-accent-text transition-opacity hover:bg-accent-hover disabled:opacity-40"
|
||||
>
|
||||
<SendHorizontal size={15} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
{message && <p className="text-caption text-danger">{message}</p>}
|
||||
{publicHint && !guest && (
|
||||
<p className="text-caption text-content-faint">{t('journey.comments.publicHint')}</p>
|
||||
)}
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface MemberThreadState {
|
||||
byEntry: ReadonlyMap<number, EntryCommentItem[]>;
|
||||
canModerate: boolean;
|
||||
add: (entryId: number, body: string) => Promise<boolean>;
|
||||
setHidden: (commentId: number, hidden: boolean) => Promise<boolean>;
|
||||
remove: (commentId: number) => Promise<boolean>;
|
||||
}
|
||||
|
||||
/** The thread under an entry for the journey's members, on `useJourneyComments`. */
|
||||
export function MemberEntryComments({
|
||||
entryId,
|
||||
thread,
|
||||
defaultOpen,
|
||||
}: {
|
||||
entryId: number;
|
||||
thread: MemberThreadState;
|
||||
defaultOpen?: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const failed = (ok: boolean) => {
|
||||
if (!ok) toast.error(t('journey.comments.failed'));
|
||||
return ok;
|
||||
};
|
||||
return (
|
||||
<JourneyEntryComments
|
||||
comments={thread.byEntry.get(entryId) ?? []}
|
||||
canWrite
|
||||
defaultOpen={defaultOpen}
|
||||
canModerate={thread.canModerate}
|
||||
publicHint
|
||||
onAdd={async (body) => ((await thread.add(entryId, body)) ? null : t('journey.comments.failed'))}
|
||||
onHide={async (id, hidden) => failed(await thread.setHidden(id, hidden))}
|
||||
onDelete={async (id) => failed(await thread.remove(id))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
type GuestOutcome = 'ok' | 'closed' | 'gone' | 'locked' | 'rate_limited' | 'invalid' | 'failed';
|
||||
|
||||
interface GuestThreadState {
|
||||
commentsOpen: boolean;
|
||||
byEntry: ReadonlyMap<number, EntryCommentItem[]>;
|
||||
addComment: (entryId: number, name: string, body: string) => Promise<GuestOutcome>;
|
||||
}
|
||||
|
||||
const GUEST_OUTCOME_KEYS: Record<Exclude<GuestOutcome, 'ok'>, string> = {
|
||||
closed: 'journey.comments.closed',
|
||||
gone: 'journey.public.notFoundMessage',
|
||||
locked: 'journey.comments.locked',
|
||||
rate_limited: 'common.tooManyAttempts',
|
||||
invalid: 'journey.comments.invalid',
|
||||
failed: 'journey.comments.failed',
|
||||
};
|
||||
|
||||
/** The thread under an entry on the shared page, for readers who sign with a name. */
|
||||
export function GuestEntryComments({ entryId, thread }: { entryId: number; thread: GuestThreadState }) {
|
||||
const { t } = useTranslation();
|
||||
if (!thread.commentsOpen) return null;
|
||||
return (
|
||||
<JourneyEntryComments
|
||||
comments={thread.byEntry.get(entryId) ?? []}
|
||||
canWrite
|
||||
guest
|
||||
onAdd={async (body, name) => {
|
||||
const outcome = await thread.addComment(entryId, name, body);
|
||||
return outcome === 'ok' ? null : t(GUEST_OUTCOME_KEYS[outcome]);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Images } from 'lucide-react';
|
||||
import { useId } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import {
|
||||
DialogButton,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogShell,
|
||||
DialogTile,
|
||||
FooterSpacer,
|
||||
NEUTRAL_TINT,
|
||||
} from '../shared/DialogShell';
|
||||
import JourneyFromPhotosList from './JourneyFromPhotosList';
|
||||
import { useJourneyEntriesFromPhotos } from './useJourneyEntriesFromPhotos';
|
||||
|
||||
/**
|
||||
* "Entries from photos" on the desktop (#1920): the gallery's loose photos as
|
||||
* proposed drafts, chosen and named here, written in one go.
|
||||
*/
|
||||
export default function JourneyFromPhotosDialog({
|
||||
journeyId,
|
||||
coverOf,
|
||||
onCreated,
|
||||
onClose,
|
||||
}: {
|
||||
journeyId: number;
|
||||
coverOf: (galleryPhotoId: number) => string | null;
|
||||
onCreated: () => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const labelId = useId();
|
||||
const state = useJourneyEntriesFromPhotos({ journeyId, onCreated, onClose });
|
||||
const allOn = state.clusters.length > 0 && state.selectedCount === state.clusters.length;
|
||||
|
||||
return (
|
||||
<DialogShell
|
||||
onClose={onClose}
|
||||
labelledBy={labelId}
|
||||
width="detail"
|
||||
header={
|
||||
<DialogHeader
|
||||
tile={
|
||||
<DialogTile>
|
||||
<Images size={18} />
|
||||
</DialogTile>
|
||||
}
|
||||
tint={NEUTRAL_TINT}
|
||||
labelId={labelId}
|
||||
onClose={onClose}
|
||||
title={t('journey.fromPhotos.title')}
|
||||
sub={t('journey.fromPhotos.text')}
|
||||
subWraps
|
||||
/>
|
||||
}
|
||||
footer={
|
||||
<DialogFooter>
|
||||
{state.clusters.length > 1 && (
|
||||
<DialogButton onClick={() => state.selectAll(!allOn)}>
|
||||
{allOn ? t('common.deselectAll') : t('common.selectAll')}
|
||||
</DialogButton>
|
||||
)}
|
||||
<FooterSpacer />
|
||||
<DialogButton onClick={onClose}>{t('common.cancel')}</DialogButton>
|
||||
<DialogButton variant="primary" disabled={!state.canSubmit} onClick={state.submit}>
|
||||
{t('journey.fromPhotos.create', { count: state.selectedCount })}
|
||||
</DialogButton>
|
||||
</DialogFooter>
|
||||
}
|
||||
>
|
||||
<div className="px-6 py-5">
|
||||
<JourneyFromPhotosList state={state} coverOf={coverOf} />
|
||||
</div>
|
||||
</DialogShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import type { JourneyEntriesFromPhotosCluster } from '@trek/shared';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import JourneyFromPhotosList from './JourneyFromPhotosList';
|
||||
|
||||
vi.mock('../../i18n', () => ({ useTranslation: () => ({ t: (key: string) => key, locale: 'en' }) }));
|
||||
|
||||
type State = ComponentProps<typeof JourneyFromPhotosList>['state'];
|
||||
|
||||
const cluster: JourneyEntriesFromPhotosCluster = {
|
||||
date: '2026-05-14',
|
||||
startTime: '09:00',
|
||||
endTime: '10:00',
|
||||
timezone: 'Europe/Rome',
|
||||
lat: null,
|
||||
lng: null,
|
||||
countryCode: null,
|
||||
locationName: null,
|
||||
suggestedTitle: 'Canal walk',
|
||||
titleSource: 'date',
|
||||
photoIds: [4, 5],
|
||||
photoCount: 2,
|
||||
coverPhotoId: 4,
|
||||
};
|
||||
|
||||
function draftState(patch: Partial<State> = {}): State {
|
||||
return {
|
||||
clusters: [],
|
||||
withoutCaptureTime: 0,
|
||||
maxGapMinutes: 180,
|
||||
setMaxGapMinutes: vi.fn(),
|
||||
loading: false,
|
||||
error: null,
|
||||
retry: vi.fn(),
|
||||
isSelected: () => true,
|
||||
titleOf: (item) => item.suggestedTitle,
|
||||
selectedCount: 1,
|
||||
toggle: vi.fn(),
|
||||
selectAll: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
busy: false,
|
||||
canSubmit: true,
|
||||
submit: vi.fn(),
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
describe('choosing gallery photo drafts', () => {
|
||||
it('shows waiting, retry and empty states in the same panel', () => {
|
||||
const coverOf = () => null;
|
||||
const retry = vi.fn();
|
||||
const { container, rerender } = render(
|
||||
<JourneyFromPhotosList coverOf={coverOf} state={draftState({ loading: true })} />
|
||||
);
|
||||
expect(container.querySelector('[aria-busy="true"]')).not.toBeNull();
|
||||
rerender(<JourneyFromPhotosList coverOf={coverOf} state={draftState({ error: 'Unavailable', retry })} />);
|
||||
expect(screen.getByText('Unavailable')).toBeVisible();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'common.errorRetry' }));
|
||||
expect(retry).toHaveBeenCalledOnce();
|
||||
rerender(<JourneyFromPhotosList coverOf={coverOf} state={draftState()} />);
|
||||
expect(screen.getByText('journey.fromPhotos.empty')).toBeVisible();
|
||||
});
|
||||
|
||||
it('renders a group, can change its selection and title, and explains missing capture data', () => {
|
||||
const coverOf = vi.fn(() => '/gallery/4');
|
||||
const toggle = vi.fn();
|
||||
const rename = vi.fn();
|
||||
const state = draftState({ clusters: [cluster], withoutCaptureTime: 1, toggle, rename });
|
||||
const { rerender } = render(<JourneyFromPhotosList coverOf={coverOf} state={state} />);
|
||||
expect(coverOf).toHaveBeenCalledWith(4);
|
||||
expect(screen.getByText('journey.fromPhotos.noPlace')).toBeVisible();
|
||||
expect(screen.getByText('journey.fromPhotos.withoutTime')).toBeVisible();
|
||||
const selection = screen.getByRole('checkbox', { name: 'Canal walk' });
|
||||
expect(selection).toBeChecked();
|
||||
fireEvent.click(selection);
|
||||
expect(toggle).toHaveBeenCalledWith(cluster);
|
||||
const title = screen.getByRole('textbox', { name: 'common.title' });
|
||||
fireEvent.change(title, { target: { value: 'Venice' } });
|
||||
expect(rename).toHaveBeenCalledWith(cluster, 'Venice');
|
||||
|
||||
rerender(<JourneyFromPhotosList coverOf={() => null} state={{ ...state, isSelected: () => false }} />);
|
||||
expect(title).toBeDisabled();
|
||||
expect(selection).not.toBeChecked();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import type { JourneyEntriesFromPhotosCluster } from '@trek/shared';
|
||||
import { Check, Image as ImageIcon, MapPin } from 'lucide-react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import type { useJourneyEntriesFromPhotos } from './useJourneyEntriesFromPhotos';
|
||||
|
||||
type FromPhotos = ReturnType<typeof useJourneyEntriesFromPhotos>;
|
||||
|
||||
function Cover({ src }: { src: string | null }) {
|
||||
if (!src) {
|
||||
return (
|
||||
<span className="flex h-12 w-12 flex-none items-center justify-center rounded-xl bg-surface-secondary text-content-faint">
|
||||
<ImageIcon size={16} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return <img src={src} alt="" className="h-12 w-12 flex-none rounded-xl object-cover" loading="lazy" />;
|
||||
}
|
||||
|
||||
/**
|
||||
* The groups the gallery's loose photos fall into (#1920), one row each: a
|
||||
* tick, the first picture, a title to keep or change, and when and how many.
|
||||
* The desktop dialog and the phone sheet both draw this list.
|
||||
*/
|
||||
export default function JourneyFromPhotosList({
|
||||
state,
|
||||
coverOf,
|
||||
}: {
|
||||
state: FromPhotos;
|
||||
/** The thumbnail of a gallery photo, or null for a clip without a poster. */
|
||||
coverOf: (galleryPhotoId: number) => string | null;
|
||||
}) {
|
||||
const { t, locale } = useTranslation();
|
||||
|
||||
const dayOf = (cluster: JourneyEntriesFromPhotosCluster) =>
|
||||
new Date(`${cluster.date}T00:00:00`).toLocaleDateString(locale || undefined, {
|
||||
weekday: 'short',
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
});
|
||||
|
||||
if (state.loading && state.clusters.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col gap-2" aria-busy="true">
|
||||
{[0, 1, 2].map((i) => (
|
||||
<div key={i} className="h-[68px] animate-pulse rounded-2xl bg-surface-secondary" />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (state.error && state.clusters.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-3 py-6 text-center">
|
||||
<p className="text-body text-content-muted">{state.error}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={state.retry}
|
||||
className="rounded-full bg-surface-secondary px-3.5 py-1.5 text-caption font-semibold text-content hover:bg-surface-tertiary"
|
||||
>
|
||||
{t('common.errorRetry')}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (state.clusters.length === 0) {
|
||||
return <p className="py-6 text-center text-body text-content-muted">{t('journey.fromPhotos.empty')}</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
{state.clusters.map((cluster) => {
|
||||
const on = state.isSelected(cluster);
|
||||
return (
|
||||
<div
|
||||
key={`${cluster.date}-${cluster.coverPhotoId}`}
|
||||
className={`flex items-center gap-3 rounded-2xl border p-2.5 transition-colors ${
|
||||
on ? 'border-edge bg-surface-card' : 'border-edge-faint opacity-60'
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
role="checkbox"
|
||||
aria-checked={on}
|
||||
aria-label={state.titleOf(cluster)}
|
||||
onClick={() => state.toggle(cluster)}
|
||||
className={`flex h-6 w-6 flex-none items-center justify-center rounded-full border transition-colors ${
|
||||
on ? 'border-accent bg-accent text-accent-text' : 'border-edge text-transparent'
|
||||
}`}
|
||||
>
|
||||
<Check size={13} strokeWidth={2.6} />
|
||||
</button>
|
||||
<Cover src={coverOf(cluster.coverPhotoId)} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<input
|
||||
value={state.titleOf(cluster)}
|
||||
onChange={(e) => state.rename(cluster, e.target.value)}
|
||||
disabled={!on}
|
||||
aria-label={t('common.title')}
|
||||
className="-mx-1.5 w-[calc(100%+12px)] truncate rounded-lg bg-transparent px-1.5 py-0.5 text-body font-semibold text-content outline-none hover:bg-surface-secondary focus:bg-surface-secondary disabled:hover:bg-transparent"
|
||||
/>
|
||||
<div className="mt-0.5 flex flex-wrap items-center gap-1.5 text-caption text-content-faint">
|
||||
<span>{dayOf(cluster)}</span>
|
||||
<span className="tabular-nums">
|
||||
{cluster.startTime === cluster.endTime
|
||||
? cluster.startTime
|
||||
: t('journey.fromPhotos.timeRange', { start: cluster.startTime, end: cluster.endTime })}
|
||||
</span>
|
||||
<span className="rounded-full bg-surface-secondary px-1.5 py-px tabular-nums">
|
||||
{t('journey.fromPhotos.photoCount', { count: cluster.photoCount })}
|
||||
</span>
|
||||
{cluster.lat === null && (
|
||||
<span className="inline-flex items-center gap-0.5">
|
||||
<MapPin size={10} />
|
||||
{t('journey.fromPhotos.noPlace')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{state.withoutCaptureTime > 0 && (
|
||||
<p className="px-1 pt-1 text-caption text-content-faint">
|
||||
{t('journey.fromPhotos.withoutTime', { count: state.withoutCaptureTime })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import {
|
||||
JOURNEY_SHARE_PASSWORD_MAX_LENGTH,
|
||||
JOURNEY_SHARE_PASSWORD_MIN_LENGTH,
|
||||
journeySharePasswordSchema,
|
||||
} from '@trek/shared';
|
||||
import { Lock } from 'lucide-react';
|
||||
import { useId, useState, type FormEvent } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import {
|
||||
DialogButton,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogShell,
|
||||
DialogTile,
|
||||
FooterSpacer,
|
||||
NEUTRAL_TINT,
|
||||
} from '../shared/DialogShell';
|
||||
|
||||
/**
|
||||
* Asks the owner for a share link's new password (#2553). The old one is never
|
||||
* shown: a password is only ever set anew or taken off.
|
||||
*/
|
||||
export default function JourneySharePasswordDialog({
|
||||
onSave,
|
||||
onClose,
|
||||
}: {
|
||||
onSave: (password: string) => Promise<boolean>;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const labelId = useId();
|
||||
const [password, setPassword] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const valid = journeySharePasswordSchema.safeParse(password).success;
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!valid || busy) return;
|
||||
setBusy(true);
|
||||
await onSave(password);
|
||||
setBusy(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<DialogShell
|
||||
onClose={onClose}
|
||||
labelledBy={labelId}
|
||||
width="narrow"
|
||||
onSubmit={(e) => void submit(e)}
|
||||
header={
|
||||
<DialogHeader
|
||||
tile={
|
||||
<DialogTile>
|
||||
<Lock size={18} />
|
||||
</DialogTile>
|
||||
}
|
||||
tint={NEUTRAL_TINT}
|
||||
labelId={labelId}
|
||||
onClose={onClose}
|
||||
title={t('journey.share.passwordTitle')}
|
||||
sub={t('journey.share.passwordText')}
|
||||
subWraps
|
||||
/>
|
||||
}
|
||||
footer={
|
||||
<DialogFooter>
|
||||
<FooterSpacer />
|
||||
<DialogButton onClick={onClose}>{t('common.cancel')}</DialogButton>
|
||||
<DialogButton variant="primary" type="submit" disabled={!valid || busy}>
|
||||
{t('common.save')}
|
||||
</DialogButton>
|
||||
</DialogFooter>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-2 px-6 py-5">
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoFocus
|
||||
autoComplete="new-password"
|
||||
maxLength={JOURNEY_SHARE_PASSWORD_MAX_LENGTH}
|
||||
placeholder={t('common.password')}
|
||||
aria-label={t('common.password')}
|
||||
className="w-full rounded-xl border border-edge bg-surface px-3.5 py-2.5 text-body text-content outline-none placeholder:text-content-faint focus:border-content-faint"
|
||||
/>
|
||||
<p className="text-caption text-content-faint">
|
||||
{t('journey.share.passwordRule', { minLength: JOURNEY_SHARE_PASSWORD_MIN_LENGTH })}
|
||||
</p>
|
||||
</div>
|
||||
</DialogShell>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,137 @@
|
||||
import { Link, List, Grid, MapPin, Check, CalendarRange, Route } from 'lucide-react'
|
||||
import { Link, List, Grid, MapPin, Check, CalendarRange, Route, MessageCircle, BellPlus, Lock, CalendarClock, Eye, X } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { fs } from '../shared/DialogShell'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
import { SHARE_MAP_EXTRAS, useJourneyShareLink, type JourneyShareLink, type JourneyShareMapExtra } from './useJourneyShareLink'
|
||||
import {
|
||||
SHARE_MAP_EXTRAS, useJourneyShareLink, type JourneyShareLink, type JourneyShareMapExtra, type JourneyShareInteraction,
|
||||
} from './useJourneyShareLink'
|
||||
import { useJourneyShareAccess } from './useJourneyShareAccess'
|
||||
import JourneySharePasswordDialog from './JourneySharePasswordDialog'
|
||||
|
||||
type ShareAccess = ReturnType<typeof useJourneyShareAccess>
|
||||
|
||||
const READER_SWITCHES: { key: JourneyShareInteraction; icon: typeof MessageCircle; labelKey: string; hintKey: string }[] = [
|
||||
{ key: 'allow_comments', icon: MessageCircle, labelKey: 'journey.share.allowComments', hintKey: 'journey.share.allowCommentsHint' },
|
||||
{ key: 'allow_subscriptions', icon: BellPlus, labelKey: 'journey.share.allowFollowers', hintKey: 'journey.share.allowFollowersHint' },
|
||||
]
|
||||
|
||||
/** The addresses following the link, folded into two counts until the owner opens them. */
|
||||
function ShareFollowers({ access }: { access: ShareAccess }) {
|
||||
const { t } = useTranslation()
|
||||
const { followers } = access
|
||||
if (followers.status !== 'ready' || (followers.count === 0 && followers.pending === 0)) return null
|
||||
return (
|
||||
<div className="ms-5 border-s border-edge ps-3">
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={access.followersOpen}
|
||||
onClick={() => access.setFollowersOpen(!access.followersOpen)}
|
||||
className="flex flex-wrap items-center gap-1.5 py-1 text-caption text-content-muted hover:text-content"
|
||||
>
|
||||
<span className="rounded-full bg-surface-secondary px-2 py-0.5 font-semibold">{t('journey.share.followers', { count: followers.count })}</span>
|
||||
{followers.pending > 0 && (
|
||||
<span className="rounded-full bg-surface-secondary px-2 py-0.5 text-content-faint">{t('journey.share.followersPending', { count: followers.pending })}</span>
|
||||
)}
|
||||
</button>
|
||||
{access.followersOpen && (
|
||||
<ul className="mt-1 flex flex-col">
|
||||
{followers.subscribers.map(sub => (
|
||||
<li key={sub.id} className="group flex items-center gap-2 py-1">
|
||||
<span className={`min-w-0 flex-1 truncate text-caption ${sub.confirmed ? 'text-content' : 'text-content-faint'}`}>{sub.email}</span>
|
||||
<Tooltip label={t('journey.share.removeFollower')} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('journey.share.removeFollower')}
|
||||
onClick={() => void access.removeFollower(sub.id)}
|
||||
className="flex h-6 w-6 flex-none items-center justify-center rounded-full text-content-faint opacity-40 transition-opacity hover:bg-danger-soft hover:text-danger group-hover:opacity-100"
|
||||
>
|
||||
<X size={12} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** What readers of the link may do besides reading (#1702, #1669): each off until switched on. */
|
||||
function ShareReaders({ link, access, onToggle }: { link: JourneyShareLink; access: ShareAccess; onToggle: (key: JourneyShareInteraction) => void }) {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{READER_SWITCHES.map(({ key, icon: Icon, labelKey, hintKey }) => {
|
||||
// Comments sit under the entries, so they need the timeline shared.
|
||||
const blocked = key === 'allow_comments' && !link.share_timeline
|
||||
const on = !blocked && !!link[key]
|
||||
return (
|
||||
<Tooltip key={key} label={blocked ? t('journey.share.needsTimeline') : ''} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={on}
|
||||
disabled={blocked}
|
||||
onClick={() => onToggle(key)}
|
||||
className={`flex w-full items-start gap-2.5 rounded-xl border px-3 py-2 text-start transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
|
||||
on ? 'border-accent bg-accent text-accent-text' : 'border-edge text-content-muted hover:border-content-faint'
|
||||
}`}
|
||||
>
|
||||
<Icon size={13} className="mt-0.5 flex-none" />
|
||||
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span className="font-medium" style={fs(12, 'body')}>{t(labelKey)}</span>
|
||||
<span className={on ? 'text-accent-text opacity-80' : 'text-content-faint'} style={fs(11)}>{t(hintKey)}</span>
|
||||
</span>
|
||||
{on && <Check size={12} className="mt-0.5 flex-none" />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
)
|
||||
})}
|
||||
{link.allow_subscriptions && <ShareFollowers access={access} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Who may open the link and until when (#2553): a password and an end date, both optional. */
|
||||
function ShareAccessCard({ access }: { access: ShareAccess }) {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<div className="flex flex-col rounded-xl border border-edge">
|
||||
<div className="flex items-center gap-2.5 px-3 py-2">
|
||||
<Lock size={13} className="flex-none text-content-muted" />
|
||||
<span className="flex-1 font-medium text-content" style={fs(12, 'body')}>{t('common.password')}</span>
|
||||
{access.hasPassword && (
|
||||
<button type="button" onClick={() => void access.removePassword()} className="rounded-full px-2.5 py-1 text-caption font-semibold text-danger hover:bg-danger-soft">
|
||||
{t('common.remove')}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" onClick={() => access.setPasswordOpen(true)} className="rounded-full bg-surface-secondary px-2.5 py-1 text-caption font-semibold text-content hover:bg-surface-tertiary">
|
||||
{access.hasPassword ? t('common.change') : t('journey.share.passwordSet')}
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex items-center gap-2.5 border-t border-edge px-3 py-2">
|
||||
<CalendarClock size={13} className="flex-none text-content-muted" />
|
||||
<span className="flex-1 font-medium text-content" style={fs(12, 'body')}>{t('journey.share.expires')}</span>
|
||||
{!access.expiry && <span className="text-caption text-content-faint">{t('journey.share.expiresNever')}</span>}
|
||||
<input
|
||||
type="date"
|
||||
value={access.expiry}
|
||||
min={access.minExpiry}
|
||||
onChange={e => access.setExpiry(e.target.value)}
|
||||
aria-label={t('journey.share.expires')}
|
||||
className="rounded-lg border border-edge bg-surface px-2 py-1 text-caption text-content outline-none focus:border-content-faint"
|
||||
/>
|
||||
{access.expiry && (
|
||||
<Tooltip label={t('journey.share.expiresNever')} placement="top">
|
||||
<button type="button" aria-label={t('journey.share.expiresNever')} onClick={() => access.setExpiry('')} className="flex h-6 w-6 items-center justify-center rounded-full text-content-faint hover:bg-surface-secondary hover:text-content">
|
||||
<X size={12} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
{access.passwordOpen && <JourneySharePasswordDialog onSave={access.savePassword} onClose={() => access.setPasswordOpen(false)} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const EXTRA_ICONS = { share_plan: CalendarRange, share_recordings: Route } as const
|
||||
|
||||
@@ -46,7 +175,8 @@ function ShareMapExtras({ link, onToggle }: { link: JourneyShareLink; onToggle:
|
||||
|
||||
export default function JourneyShareSection({ journeyId }: { journeyId: number }) {
|
||||
const { t } = useTranslation()
|
||||
const { link, loading, manageable, copied, shareUrl, createLink, togglePerm, deleteLink, copyLink } = useJourneyShareLink(journeyId)
|
||||
const { link, loading, manageable, copied, shareUrl, createLink, togglePerm, deleteLink, copyLink, setProtection } = useJourneyShareLink(journeyId)
|
||||
const access = useJourneyShareAccess(journeyId, link, setProtection)
|
||||
|
||||
if (loading || !manageable) return null
|
||||
|
||||
@@ -81,6 +211,14 @@ export default function JourneyShareSection({ journeyId }: { journeyId: number }
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{access.views > 0 && (
|
||||
<div className="-mt-1.5 flex items-center gap-1.5 ps-2 text-caption text-content-faint">
|
||||
<Eye size={12} />
|
||||
<span>{t('journey.share.views', { count: access.views })}</span>
|
||||
{access.lastViewed && <span>{t('journey.share.lastViewed', { date: access.lastViewed })}</span>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Permission toggles */}
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{[
|
||||
@@ -105,6 +243,9 @@ export default function JourneyShareSection({ journeyId }: { journeyId: number }
|
||||
))}
|
||||
<ShareMapExtras link={link} onToggle={key => void togglePerm(key)} />
|
||||
</div>
|
||||
|
||||
<ShareReaders link={link} access={access} onToggle={key => void togglePerm(key)} />
|
||||
<ShareAccessCard access={access} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
Sun, CloudSun, Cloud, CloudRain, CloudLightning, Snowflake,
|
||||
ThumbsUp, ThumbsDown,
|
||||
} from 'lucide-react'
|
||||
import type { CSSProperties } from 'react'
|
||||
import type { CSSProperties, ReactNode } from 'react'
|
||||
import JournalBody from './JournalBody'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { formatLocationName } from '../../utils/formatters'
|
||||
@@ -67,9 +67,11 @@ interface Props {
|
||||
onEdit: () => void
|
||||
onDelete: () => void
|
||||
onPhotoClick: (photos: JourneyPhoto[], index: number) => void
|
||||
/** The comment thread under the entry (#1702), drawn by the screen that opened it. */
|
||||
comments?: ReactNode
|
||||
}
|
||||
|
||||
export default function MobileEntryView({ entry, readOnly, publicPhotoUrl, onClose, onEdit, onDelete, onPhotoClick }: Props) {
|
||||
export default function MobileEntryView({ entry, readOnly, publicPhotoUrl, onClose, onEdit, onDelete, onPhotoClick, comments }: Props) {
|
||||
const { t, locale } = useTranslation()
|
||||
const photos = entry.photos || []
|
||||
const mood = entry.mood ? MOOD_CONFIG[entry.mood] : null
|
||||
@@ -292,6 +294,8 @@ export default function MobileEntryView({ entry, readOnly, publicPhotoUrl, onClo
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{comments && <div className="mt-6 border-t border-zinc-100 pt-4 dark:border-zinc-800">{comments}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div >
|
||||
|
||||
@@ -117,7 +117,7 @@ export function gpxImportErrorText(err: unknown, t: Translate): string {
|
||||
case 'gpx_too_many_days':
|
||||
return t('journey.recording.gpx.error.tooManyDays');
|
||||
default:
|
||||
return t('common.errorTitle');
|
||||
return t('journey.recording.gpx.failed');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import type { JourneyGpxImportOptions, JourneyGpxImportResult, JourneyRecordedDay } from '@trek/shared';
|
||||
import type {
|
||||
JourneyGpxImportOptions,
|
||||
JourneyGpxImportResult,
|
||||
JourneyRecordedDay,
|
||||
JourneyRecordingSource,
|
||||
} from '@trek/shared';
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { journeyRecordingsRepo } from '../../repo/journeyRecordingsRepo';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import { gpxImportErrorText } from './journeyRecordingModel';
|
||||
|
||||
interface GpxImportState {
|
||||
@@ -21,13 +27,22 @@ const IDLE: GpxImportState = { busy: false, error: null, result: null };
|
||||
* people on the journey hear of them through `journey:recording:updated`.
|
||||
* Online only: the server cuts the file into days.
|
||||
*/
|
||||
export function useJourneyGpxImport(journeyId: number | null, onKept: (days: readonly JourneyRecordedDay[]) => void) {
|
||||
export function useJourneyGpxImport(
|
||||
journeyId: number | null,
|
||||
onKept: (days: readonly JourneyRecordedDay[]) => void,
|
||||
onRemoved?: (date: string, source?: JourneyRecordingSource) => void
|
||||
) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const [state, setState] = useState<GpxImportState>(IDLE);
|
||||
|
||||
/** Reads the file, `date` keeping only that local day; answers what was kept, or null when nothing was. */
|
||||
const importGpx = useCallback(
|
||||
async (file: Blob, options?: JourneyGpxImportOptions): Promise<JourneyGpxImportResult | null> => {
|
||||
async (
|
||||
file: Blob,
|
||||
options?: JourneyGpxImportOptions,
|
||||
onFailure?: (message: string) => void
|
||||
): Promise<JourneyGpxImportResult | null> => {
|
||||
if (journeyId === null) return null;
|
||||
setState({ busy: true, error: null, result: null });
|
||||
try {
|
||||
@@ -36,7 +51,9 @@ export function useJourneyGpxImport(journeyId: number | null, onKept: (days: rea
|
||||
setState({ busy: false, error: null, result });
|
||||
return result;
|
||||
} catch (err) {
|
||||
setState({ busy: false, error: gpxImportErrorText(err, t), result: null });
|
||||
const message = gpxImportErrorText(err, t);
|
||||
setState({ busy: false, error: message, result: null });
|
||||
onFailure?.(message);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
@@ -45,5 +62,31 @@ export function useJourneyGpxImport(journeyId: number | null, onKept: (days: rea
|
||||
|
||||
const reset = useCallback(() => setState(IDLE), []);
|
||||
|
||||
return { ...state, importGpx, reset };
|
||||
/** One day's route from a file, picked in that day's header; says how it went in a toast. */
|
||||
const importDayFile = useCallback(
|
||||
async (file: Blob, date: string) => {
|
||||
const result = await importGpx(file, { date }, toast.error);
|
||||
if (!result) return;
|
||||
toast.success(t('journey.recording.gpx.imported', { count: result.days.length }));
|
||||
if (result.untimedPoints > 0) toast.info(t('journey.recording.gpx.untimed', { count: result.untimedPoints }));
|
||||
},
|
||||
[importGpx, toast, t]
|
||||
);
|
||||
|
||||
/** Drops the day's GPX route; a Dawarich route of the same day stays. */
|
||||
const removeDay = useCallback(
|
||||
async (date: string) => {
|
||||
if (journeyId === null) return;
|
||||
try {
|
||||
await journeyRecordingsRepo.remove(journeyId, date, 'gpx');
|
||||
onRemoved?.(date, 'gpx');
|
||||
toast.success(t('journey.recording.removedToast'));
|
||||
} catch {
|
||||
toast.error(t('journey.recording.gpx.removeFailed'));
|
||||
}
|
||||
},
|
||||
[journeyId, onRemoved, toast, t]
|
||||
);
|
||||
|
||||
return { ...state, importGpx, importDayFile, removeDay, reset };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { expiryDay, expiryIso, useJourneyShareAccess } from './useJourneyShareAccess';
|
||||
import type { JourneyShareLink } from './useJourneyShareLink';
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
toast: { success: vi.fn(), error: vi.fn() },
|
||||
useSubscribers: vi.fn(),
|
||||
remove: vi.fn(),
|
||||
}));
|
||||
vi.mock('../../i18n', () => ({ useTranslation: () => ({ t: (key: string) => key, locale: 'en' }) }));
|
||||
vi.mock('../shared/Toast', () => ({ useToast: () => mocks.toast }));
|
||||
vi.mock('./useJourneySubscribers', () => ({ useJourneySubscribers: mocks.useSubscribers }));
|
||||
|
||||
const LINK: JourneyShareLink = {
|
||||
token: 'abc',
|
||||
share_timeline: true,
|
||||
share_gallery: true,
|
||||
share_map: true,
|
||||
has_password: true,
|
||||
view_count: 4,
|
||||
last_viewed_at: '2026-11-30T12:00:00Z',
|
||||
allow_subscriptions: true,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.useSubscribers.mockReturnValue({ remove: mocks.remove });
|
||||
});
|
||||
|
||||
describe('owner access settings', () => {
|
||||
it('uses the end of the owner’s local day for the share deadline', () => {
|
||||
const date = '2026-11-30';
|
||||
const expires = expiryIso(date);
|
||||
expect(expires).toBe(new Date('2026-11-30T23:59:59').toISOString());
|
||||
expect(expiryDay(expires)).toBe(date);
|
||||
expect(expiryIso('')).toBeNull();
|
||||
expect(expiryIso('invalid')).toBeNull();
|
||||
expect(expiryDay(undefined)).toBe('');
|
||||
expect(expiryDay('invalid')).toBe('');
|
||||
});
|
||||
|
||||
it('keeps the dialog open after a refused password write and closes it after a retry', async () => {
|
||||
const write = vi.fn().mockResolvedValueOnce(false).mockResolvedValue(true);
|
||||
const { result } = renderHook(() => useJourneyShareAccess(7, LINK, write));
|
||||
expect(result.current.hasPassword).toBe(true);
|
||||
expect(result.current.views).toBe(4);
|
||||
expect(result.current.lastViewed).toBeTruthy();
|
||||
expect(mocks.useSubscribers).toHaveBeenCalledWith(7, true);
|
||||
act(() => result.current.setPasswordOpen(true));
|
||||
await act(async () => expect(await result.current.savePassword('abcd')).toBe(false));
|
||||
expect(result.current.passwordOpen).toBe(true);
|
||||
await act(async () => expect(await result.current.savePassword('abcde')).toBe(true));
|
||||
expect(result.current.passwordOpen).toBe(false);
|
||||
expect(mocks.toast.success).toHaveBeenCalledWith('journey.share.passwordSaved');
|
||||
await act(async () => result.current.removePassword());
|
||||
expect(write).toHaveBeenLastCalledWith({ password: null });
|
||||
act(() => result.current.setExpiry(''));
|
||||
expect(write).toHaveBeenLastCalledWith({ expires_at: null });
|
||||
});
|
||||
|
||||
it('explains a failed removal of a subscriber', async () => {
|
||||
mocks.remove.mockResolvedValue(false);
|
||||
const { result } = renderHook(() => useJourneyShareAccess(7, null, vi.fn()));
|
||||
expect(result.current.lastViewed).toBeNull();
|
||||
expect(result.current.views).toBe(0);
|
||||
expect(mocks.useSubscribers).toHaveBeenCalledWith(7, false);
|
||||
await act(async () => result.current.removeFollower(2));
|
||||
await waitFor(() => expect(mocks.toast.error).toHaveBeenCalledWith('journey.share.followerRemoveFailed'));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useToast } from '../shared/Toast';
|
||||
import type { JourneyShareLink } from './useJourneyShareLink';
|
||||
import { useJourneySubscribers } from './useJourneySubscribers';
|
||||
|
||||
type SetProtection = (change: { password?: string | null; expires_at?: string | null }) => Promise<boolean>;
|
||||
|
||||
/** The local day an ISO expiry falls on, for a date field. */
|
||||
export function expiryDay(iso: string | null | undefined): string {
|
||||
if (!iso) return '';
|
||||
const d = new Date(iso);
|
||||
if (Number.isNaN(d.getTime())) return '';
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||||
}
|
||||
|
||||
/** A link picked to run out on a day works until that day is over, in the owner's zone. */
|
||||
export function expiryIso(day: string): string | null {
|
||||
if (!day) return null;
|
||||
const end = new Date(`${day}T23:59:59`);
|
||||
return Number.isNaN(end.getTime()) ? null : end.toISOString();
|
||||
}
|
||||
|
||||
/** Today as a date field's lower bound. */
|
||||
export function todayDay(): string {
|
||||
return expiryDay(new Date().toISOString());
|
||||
}
|
||||
|
||||
/**
|
||||
* The owner's controls beside a journey's share switches (#2553, #1669), behind
|
||||
* the desktop share section and the phone settings sheet alike: the password
|
||||
* dialog, the expiry day, how often the link was opened, and the addresses that
|
||||
* follow it.
|
||||
*/
|
||||
export function useJourneyShareAccess(journeyId: number, link: JourneyShareLink | null, setProtection: SetProtection) {
|
||||
const { t, locale } = useTranslation();
|
||||
const toast = useToast();
|
||||
const [passwordOpen, setPasswordOpen] = useState(false);
|
||||
const [followersOpen, setFollowersOpen] = useState(false);
|
||||
const followers = useJourneySubscribers(journeyId, !!link?.allow_subscriptions);
|
||||
|
||||
const savePassword = async (password: string) => {
|
||||
const ok = await setProtection({ password });
|
||||
if (ok) {
|
||||
setPasswordOpen(false);
|
||||
toast.success(t('journey.share.passwordSaved'));
|
||||
}
|
||||
return ok;
|
||||
};
|
||||
|
||||
const removePassword = async () => {
|
||||
if (await setProtection({ password: null })) toast.success(t('journey.share.passwordRemoved'));
|
||||
};
|
||||
|
||||
const setExpiry = (day: string) => void setProtection({ expires_at: expiryIso(day) });
|
||||
|
||||
const removeFollower = async (id: number) => {
|
||||
if (!(await followers.remove(id))) toast.error(t('journey.share.followerRemoveFailed'));
|
||||
};
|
||||
|
||||
const views = link?.view_count ?? 0;
|
||||
const lastViewed = link?.last_viewed_at
|
||||
? new Date(link.last_viewed_at).toLocaleDateString(locale || undefined, { day: 'numeric', month: 'short' })
|
||||
: null;
|
||||
|
||||
return {
|
||||
hasPassword: !!link?.has_password,
|
||||
passwordOpen,
|
||||
setPasswordOpen,
|
||||
savePassword,
|
||||
removePassword,
|
||||
expiry: expiryDay(link?.expires_at),
|
||||
minExpiry: todayDay(),
|
||||
setExpiry,
|
||||
views,
|
||||
lastViewed,
|
||||
followers,
|
||||
followersOpen,
|
||||
setFollowersOpen,
|
||||
removeFollower,
|
||||
};
|
||||
}
|
||||
@@ -55,6 +55,19 @@ describe('useJourneyShareLink', () => {
|
||||
expect(result.current.shareUrl).toBe(`${window.location.origin}/public/journey/tok`);
|
||||
});
|
||||
|
||||
it('keeps the previous link out of the settings of another journey', async () => {
|
||||
server.use(
|
||||
http.get('/api/journeys/8/share-link', () => HttpResponse.json({ error: 'forbidden' }, { status: 403 }))
|
||||
);
|
||||
const { result, rerender } = renderHook(({ id }) => useJourneyShareLink(id), { initialProps: { id: 7 } });
|
||||
await waitFor(() => expect(result.current.shareUrl).toContain('/tok'));
|
||||
rerender({ id: 8 });
|
||||
expect(result.current.link).toBeNull();
|
||||
expect(result.current.manageable).toBe(false);
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(result.current.shareUrl).toBe('');
|
||||
});
|
||||
|
||||
it('FE-JRN-SHAREHOOK-003: a 403 marks the link as not this user to manage, other errors do not', async () => {
|
||||
server.use(http.get('/api/journeys/7/share-link', () => HttpResponse.json({ error: 'no' }, { status: 403 })));
|
||||
const refused = await loaded();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useState, type SetStateAction } from 'react';
|
||||
|
||||
import { journeyApi } from '../../api/client';
|
||||
import { useCopied } from '../../hooks/useCopied';
|
||||
@@ -70,6 +70,12 @@ export function journeyShareUrl(link: JourneyShareLink | null, origin: string):
|
||||
return link ? `${origin}/public/journey/${link.token}` : '';
|
||||
}
|
||||
|
||||
interface LoadedShareLink {
|
||||
journeyId: number;
|
||||
link: JourneyShareLink | null;
|
||||
manageable: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A journey's public share link, behind both the desktop share section and the phone
|
||||
* settings sheet, which render their own markup over it: load it, create it with every
|
||||
@@ -79,25 +85,31 @@ export function journeyShareUrl(link: JourneyShareLink | null, origin: string):
|
||||
export function useJourneyShareLink(journeyId: number) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const [link, setLink] = useState<JourneyShareLink | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loaded, setLoaded] = useState<LoadedShareLink | null>(null);
|
||||
const current = loaded?.journeyId === journeyId ? loaded : null;
|
||||
const link = current?.link ?? null;
|
||||
const { copied, copy } = useCopied();
|
||||
/** The share token is the owner's to manage; a contributor is refused. */
|
||||
const [manageable, setManageable] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
journeyApi
|
||||
.getShareLink(journeyId)
|
||||
.then((d) => setLink(d.link || null))
|
||||
.catch((err: { response?: { status?: number } }) => {
|
||||
// A 403 is the server saying this is not yours to manage. Showing the
|
||||
// section anyway would offer an editor a "create link" button that is
|
||||
// refused the moment they press it.
|
||||
if (err?.response?.status === 403) setManageable(false);
|
||||
.then((d) => {
|
||||
if (!cancelled) setLoaded({ journeyId, link: d.link ?? null, manageable: true });
|
||||
})
|
||||
.finally(() => setLoading(false));
|
||||
.catch((err: { response?: { status?: number } }) => {
|
||||
if (!cancelled) setLoaded({ journeyId, link: null, manageable: err?.response?.status !== 403 });
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [journeyId]);
|
||||
|
||||
const setLink = (next: SetStateAction<JourneyShareLink | null>) =>
|
||||
setLoaded((old) => {
|
||||
if (old?.journeyId !== journeyId) return old;
|
||||
return { ...old, link: typeof next === 'function' ? next(old.link) : next };
|
||||
});
|
||||
|
||||
const createLink = async () => {
|
||||
try {
|
||||
const res = await journeyApi.createShareLink(journeyId, {
|
||||
@@ -163,5 +175,16 @@ export function useJourneyShareLink(journeyId: number) {
|
||||
|
||||
const copyLink = () => copy(shareUrl);
|
||||
|
||||
return { link, loading, manageable, copied, shareUrl, createLink, togglePerm, deleteLink, copyLink, setProtection };
|
||||
return {
|
||||
link,
|
||||
loading: current === null,
|
||||
manageable: current?.manageable ?? false,
|
||||
copied,
|
||||
shareUrl,
|
||||
createLink,
|
||||
togglePerm,
|
||||
deleteLink,
|
||||
copyLink,
|
||||
setProtection,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
import {
|
||||
MAX_PATH_POINTS,
|
||||
MAX_PATH_SEGMENTS,
|
||||
bookMapStopFor,
|
||||
refreshPatch,
|
||||
type BookElement,
|
||||
type BookMapElement,
|
||||
type BookMapView,
|
||||
type JourneyStats,
|
||||
} from '@trek/shared';
|
||||
import { ArrowDown, ArrowLeft, ArrowRight, ArrowUp, Minus, Plus } from 'lucide-react';
|
||||
import { useRef, useState, type PointerEvent } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { Choice, Line, Section } from './StudioControls';
|
||||
import { TravelElementView } from './TravelElements';
|
||||
import { boxToView, currentMapBox, moveBox, zoomBox } from './travel/mapViewEdit';
|
||||
|
||||
type T = (key: string, params?: Record<string, string | number>) => string;
|
||||
type Kind = 'journey' | 'trip' | 'country' | 'day' | 'stop';
|
||||
interface Parts {
|
||||
tripId: number | null;
|
||||
country: string | null;
|
||||
dayDate: string | null;
|
||||
stop: BookMapElement['stop'];
|
||||
}
|
||||
|
||||
const NONE: Parts = { tripId: null, country: null, dayDate: null, stop: null };
|
||||
|
||||
function kindOf(el: BookMapElement): Kind {
|
||||
if (el.stop) return 'stop';
|
||||
if (el.dayDate) return 'day';
|
||||
if (el.country) return 'country';
|
||||
return el.tripId != null ? 'trip' : 'journey';
|
||||
}
|
||||
|
||||
/** The days the route passes through, in order. */
|
||||
function daysOf(stats: JourneyStats): string[] {
|
||||
return [...new Set(stats.points.map((p) => p.date?.slice(0, 10)).filter((d): d is string => !!d))].sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* What a map is of (#3024, #3239): the whole journey, one trip, one country,
|
||||
* one day or one stop. Picking one re-cuts the route on the spot with the
|
||||
* engine's own refresh, so the map is what a newly placed map of that scope
|
||||
* would be, and a later refresh keeps it to that scope.
|
||||
*/
|
||||
export function MapScopeSection({
|
||||
el,
|
||||
set,
|
||||
t,
|
||||
stats,
|
||||
journeyPath,
|
||||
}: {
|
||||
el: BookMapElement;
|
||||
set: (patch: Partial<BookElement>) => void;
|
||||
t: T;
|
||||
stats: JourneyStats | null;
|
||||
journeyPath: [number, number][][];
|
||||
}) {
|
||||
const { locale } = useTranslation();
|
||||
if (!stats || stats.points.length === 0) return null;
|
||||
const trips = stats.trips.filter((trip) => trip.points > 0);
|
||||
const days = daysOf(stats);
|
||||
const stops = stats.points.filter((p) => p.entryId != null);
|
||||
const kind = kindOf(el);
|
||||
|
||||
const apply = (parts: Parts) => {
|
||||
const whole = parts.tripId == null && !parts.country && !parts.dayDate && !parts.stop;
|
||||
set({
|
||||
...refreshPatch({ ...el, ...parts } as BookElement, stats),
|
||||
...parts,
|
||||
// The recorded way belongs to the whole journey; the roads went with the old legs.
|
||||
path: whole ? journeyPath.slice(0, MAX_PATH_SEGMENTS).map((seg) => seg.slice(0, MAX_PATH_POINTS)) : [],
|
||||
roads: [],
|
||||
} as Partial<BookElement>);
|
||||
};
|
||||
|
||||
const pickKind = (next: Kind) => {
|
||||
if (next === kind) return;
|
||||
if (next === 'journey') apply(NONE);
|
||||
else if (next === 'trip' && trips[0]) apply({ ...NONE, tripId: trips[0].id });
|
||||
else if (next === 'country' && stats.countries[0]) apply({ ...NONE, country: stats.countries[0].code });
|
||||
else if (next === 'day' && days[0]) apply({ ...NONE, dayDate: days[0] });
|
||||
else if (next === 'stop' && stops[0]?.entryId != null) {
|
||||
const stop = bookMapStopFor(stats, [], stops[0].entryId);
|
||||
if (stop) apply({ ...NONE, stop });
|
||||
}
|
||||
};
|
||||
|
||||
const dayLabel = (day: string) =>
|
||||
new Date(`${day}T00:00:00`).toLocaleDateString(locale || undefined, { day: 'numeric', month: 'short' });
|
||||
|
||||
const kinds: { value: Kind; label: string }[] = [
|
||||
{ value: 'journey', label: t('journey.studio.mapWholeJourney') },
|
||||
...(trips.length > 1 ? [{ value: 'trip' as const, label: t('journey.studio.mapScopeTrip') }] : []),
|
||||
...(stats.countries.length > 0 ? [{ value: 'country' as const, label: t('journey.studio.mapScopeCountry') }] : []),
|
||||
...(days.length > 0 ? [{ value: 'day' as const, label: t('journey.studio.mapScopeDay') }] : []),
|
||||
...(stops.length > 0 ? [{ value: 'stop' as const, label: t('journey.studio.mapScopeStop') }] : []),
|
||||
];
|
||||
|
||||
return (
|
||||
<Section label={t('journey.studio.mapScope')}>
|
||||
<Choice value={kind} options={kinds} onPick={pickKind} ariaLabel={t('journey.studio.mapScope')} />
|
||||
{/* The one it is of, when there is more than one to choose from. */}
|
||||
<div className="mt-2 max-h-[132px] overflow-y-auto">
|
||||
{kind === 'trip' && trips.length > 1 && (
|
||||
<Choice
|
||||
value={el.tripId ?? 0}
|
||||
options={trips.map((trip) => ({ value: trip.id, label: trip.title || t('journey.studio.untitled') }))}
|
||||
onPick={(tripId) => apply({ ...NONE, tripId })}
|
||||
/>
|
||||
)}
|
||||
{kind === 'country' && stats.countries.length > 1 && (
|
||||
<Choice
|
||||
value={el.country ?? ''}
|
||||
options={stats.countries.map((c) => ({ value: c.code, label: c.name }))}
|
||||
onPick={(country) => apply({ ...NONE, country })}
|
||||
/>
|
||||
)}
|
||||
{kind === 'day' && days.length > 1 && (
|
||||
<Choice
|
||||
value={el.dayDate ?? ''}
|
||||
options={days.map((day) => ({ value: day, label: dayLabel(day) }))}
|
||||
onPick={(dayDate) => apply({ ...NONE, dayDate })}
|
||||
/>
|
||||
)}
|
||||
{kind === 'stop' && stops.length > 1 && (
|
||||
<Choice
|
||||
value={el.stop?.entryId ?? 0}
|
||||
options={stops.map((p) => ({ value: p.entryId ?? 0, label: p.label }))}
|
||||
onPick={(entryId) => {
|
||||
const stop = bookMapStopFor(stats, [], entryId);
|
||||
if (stop) apply({ ...NONE, stop });
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
const NUDGE = 0.15;
|
||||
const ZOOM = 1.4;
|
||||
|
||||
function MapDragPreview({ el, onCommit }: { el: BookMapElement; onCommit: (view: BookMapView) => void }) {
|
||||
const [preview, setPreview] = useState<BookMapView | null>(null);
|
||||
const drag = useRef<{ x: number; y: number; box: ReturnType<typeof currentMapBox> } | null>(null);
|
||||
const viewAt = (event: PointerEvent<HTMLDivElement>) => {
|
||||
const start = drag.current;
|
||||
const { clientWidth, clientHeight } = event.currentTarget;
|
||||
if (!start || clientWidth === 0 || clientHeight === 0) return null;
|
||||
return boxToView(
|
||||
moveBox(start.box, (start.x - event.clientX) / clientWidth, (start.y - event.clientY) / clientHeight)
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="relative mt-2 max-w-56 cursor-grab touch-none overflow-hidden rounded-lg border border-edge active:cursor-grabbing"
|
||||
style={{ aspectRatio: el.frame.w / el.frame.h }}
|
||||
onPointerDown={(event) => {
|
||||
if (event.button !== 0 || !event.isPrimary) return;
|
||||
event.currentTarget.setPointerCapture(event.pointerId);
|
||||
drag.current = { x: event.clientX, y: event.clientY, box: currentMapBox(el) };
|
||||
}}
|
||||
onPointerMove={(event) => {
|
||||
if (event.currentTarget.hasPointerCapture(event.pointerId)) setPreview(viewAt(event));
|
||||
}}
|
||||
onPointerUp={(event) => {
|
||||
if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
|
||||
const view = viewAt(event);
|
||||
drag.current = null;
|
||||
setPreview(null);
|
||||
if (view) onCommit(view);
|
||||
}}
|
||||
onLostPointerCapture={() => {
|
||||
drag.current = null;
|
||||
setPreview(null);
|
||||
}}
|
||||
>
|
||||
<TravelElementView
|
||||
el={{ ...el, id: `${el.id}-framing-preview`, view: preview ?? el.view, source: 'vector' }}
|
||||
frameStyle={{ width: '100%', height: '100%', pointerEvents: 'none' }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The window a map shows (#3239): fitted to its route by itself, or framed by
|
||||
* hand, nudged and zoomed in steps from what it showed. Back to automatic
|
||||
* forgets the hand-framed view.
|
||||
*/
|
||||
export function MapViewLine({ el, set, t }: { el: BookMapElement; set: (patch: Partial<BookElement>) => void; t: T }) {
|
||||
const own = !!el.view;
|
||||
const setView = (view: BookMapView) => set({ view } as Partial<BookElement>);
|
||||
const change = (step: (box: ReturnType<typeof currentMapBox>) => ReturnType<typeof currentMapBox>) =>
|
||||
setView(boxToView(step(currentMapBox(el))));
|
||||
|
||||
const nudges = [
|
||||
{ label: t('journey.studio.mapViewLeft'), icon: ArrowLeft, run: () => change((b) => moveBox(b, -NUDGE, 0)) },
|
||||
{ label: t('journey.studio.mapViewUp'), icon: ArrowUp, run: () => change((b) => moveBox(b, 0, -NUDGE)) },
|
||||
{ label: t('journey.studio.mapViewDown'), icon: ArrowDown, run: () => change((b) => moveBox(b, 0, NUDGE)) },
|
||||
{ label: t('journey.studio.mapViewRight'), icon: ArrowRight, run: () => change((b) => moveBox(b, NUDGE, 0)) },
|
||||
{ label: t('journey.studio.zoomOut'), icon: Minus, run: () => change((b) => zoomBox(b, 1 / ZOOM)) },
|
||||
{ label: t('journey.studio.zoomIn'), icon: Plus, run: () => change((b) => zoomBox(b, ZOOM)) },
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
<Line label={t('journey.studio.mapView')}>
|
||||
<Choice
|
||||
value={own ? 'own' : 'auto'}
|
||||
options={[
|
||||
{ value: 'auto' as const, label: t('journey.studio.folioAuto') },
|
||||
{ value: 'own' as const, label: t('journey.studio.mapViewOwn') },
|
||||
]}
|
||||
onPick={(v) => {
|
||||
if (v === 'auto') set({ view: null } as Partial<BookElement>);
|
||||
else if (!own) change((b) => b);
|
||||
}}
|
||||
/>
|
||||
</Line>
|
||||
{own && (
|
||||
<>
|
||||
<MapDragPreview el={el} onCommit={setView} />
|
||||
<div className="st-row mt-2">
|
||||
{nudges.map(({ label, icon: Icon, run }) => (
|
||||
<button key={label} type="button" className="st-chip" aria-label={label} title={label} onClick={run}>
|
||||
<Icon size={13} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import type {
|
||||
BookMetric, BookStatsElement, JourneyStats,
|
||||
} from '@trek/shared'
|
||||
import {
|
||||
BOOK_BADGE_STYLES, BOOK_COUNTRY_LOOKS, BOOK_METRICS, BOOK_STATS_LOOKS, MAX_PATH_POINTS, MAX_PATH_SEGMENTS, isStale, refreshPatch,
|
||||
BOOK_BADGE_STYLES, BOOK_COUNTRY_LOOKS, BOOK_MAP_COAST_DETAILS, BOOK_METRICS, BOOK_STATS_LOOKS, isStale, refreshPatch,
|
||||
} from '@trek/shared'
|
||||
import { Swatches } from './StudioSwatches'
|
||||
import { StudioFontPicker } from './StudioFontPicker'
|
||||
@@ -17,6 +17,7 @@ import { fetchRoads } from './roadRoute'
|
||||
import { useStudioStore } from '../../store/studioStore'
|
||||
import { StudioThemeLink } from './theme/StudioThemeLink'
|
||||
import { mapZoomInUse, travelTypeInUse } from './inspector/inspectorModel'
|
||||
import { MapScopeSection, MapViewLine } from './StudioMapScope'
|
||||
|
||||
/**
|
||||
* Properties of the travel elements.
|
||||
@@ -226,8 +227,6 @@ type MapPropsInput = Props<BookMapElement> & {
|
||||
function MapContent({ el, set, t, stats, journeyPath }: MapPropsInput) {
|
||||
const cartoKey = useCartoApiKey()
|
||||
const sources = useMapSources(el.frame, el.points, { source: el.source, tileUrl: el.tileUrl })
|
||||
/** Only trips that put stops on the route: a map of the others is a blank. */
|
||||
const tripsWithRoute = (stats?.trips ?? []).filter(t => t.points > 0)
|
||||
/*
|
||||
* The grid this element will really fetch, asked for here so the panel can
|
||||
* say what it will print at. Same call the renderer makes, same answer.
|
||||
@@ -248,45 +247,7 @@ function MapContent({ el, set, t, stats, journeyPath }: MapPropsInput) {
|
||||
route on the spot rather than at the next refresh, because a control
|
||||
that changes nothing visible reads as broken.
|
||||
*/}
|
||||
{tripsWithRoute.length > 1 && (
|
||||
<Section label={t('journey.studio.mapScope')}>
|
||||
<Choice
|
||||
value={el.tripId ?? 0}
|
||||
options={[
|
||||
{ value: 0, label: t('journey.studio.mapWholeJourney') },
|
||||
...tripsWithRoute.map(trip => ({
|
||||
value: trip.id,
|
||||
label: trip.title || t('journey.studio.untitled'),
|
||||
})),
|
||||
]}
|
||||
onPick={id => {
|
||||
const tripId = id === 0 ? null : id
|
||||
// The scope it already has: a re-cut would only drop the roads loaded for these legs.
|
||||
if (!stats || tripId === (el.tripId ?? null)) return
|
||||
/*
|
||||
* Re-cut by the engine's own refresh at the new scope, so the
|
||||
* stops and countries are what refresh_travel and a newly placed
|
||||
* map of that scope hold. The recorded way is the whole
|
||||
* journey's: a trip map draws none, as the engine places none,
|
||||
* and a map of the whole journey gets it back from the journey
|
||||
* at the engine's caps, so a switch there and back loses
|
||||
* nothing. The roads go with the old legs, since entry i is the
|
||||
* way from stop i to stop i + 1 of the route that is gone.
|
||||
*/
|
||||
// Picking a trip or the whole journey is what the map is of from now on: no country, day or stop left over.
|
||||
const scope = { tripId, country: null, dayDate: null, stop: null }
|
||||
set({
|
||||
...refreshPatch({ ...el, ...scope }, stats),
|
||||
...scope,
|
||||
path: tripId == null
|
||||
? journeyPath.slice(0, MAX_PATH_SEGMENTS).map(seg => seg.slice(0, MAX_PATH_POINTS))
|
||||
: [],
|
||||
roads: [],
|
||||
} as Partial<BookElement>)
|
||||
}}
|
||||
/>
|
||||
</Section>
|
||||
)}
|
||||
<MapScopeSection el={el} set={set} t={t} stats={stats} journeyPath={journeyPath} />
|
||||
|
||||
{/* Where the picture comes from and what it looks like: one question
|
||||
with two halves, which is one group rather than two. */}
|
||||
@@ -350,6 +311,10 @@ function MapContent({ el, set, t, stats, journeyPath }: MapPropsInput) {
|
||||
two dots in the middle of it.
|
||||
*/}
|
||||
<Section label={t('journey.studio.mapFraming')}>
|
||||
<MapViewLine el={el} set={set} t={t} />
|
||||
{/* A view framed by hand is the window itself: fit and room only shape the automatic one. */}
|
||||
{!el.view && (
|
||||
<>
|
||||
<Line label={t('journey.studio.mapFit')}>
|
||||
<Choice
|
||||
value={el.fitToCountries ? 'country' : 'stops'}
|
||||
@@ -378,6 +343,8 @@ function MapContent({ el, set, t, stats, journeyPath }: MapPropsInput) {
|
||||
onPick={fitPadding => set({ fitPadding } as Partial<BookElement>)}
|
||||
/>
|
||||
</Line>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/*
|
||||
And the shape. A rectangle is a map in a box, which is what a full
|
||||
@@ -401,8 +368,21 @@ function MapContent({ el, set, t, stats, journeyPath }: MapPropsInput) {
|
||||
</Line>
|
||||
</Section>
|
||||
|
||||
{el.countries.length > 0 && ((el.source === 'vector' && el.showLand) || el.clip === 'country') && (
|
||||
<Section label={t('journey.studio.mapCoastDetail')} defaultOpen={false}>
|
||||
<Choice
|
||||
value={el.coastDetail ?? 'auto'}
|
||||
options={BOOK_MAP_COAST_DETAILS.map(value => ({
|
||||
value,
|
||||
label: t(`journey.studio.mapCoastDetail.${value}`),
|
||||
}))}
|
||||
onPick={coastDetail => set({ coastDetail } as Partial<BookElement>)}
|
||||
/>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
{el.source === 'tiles' && (
|
||||
<Section label={t('journey.studio.mapZoom')} defaultOpen={mapZoomInUse(el)}>
|
||||
<Section label={t('journey.studio.tileDetail')} defaultOpen={mapZoomInUse(el)}>
|
||||
<Choice
|
||||
value={el.zoom ?? -1}
|
||||
options={[
|
||||
|
||||
@@ -17,7 +17,7 @@ interface MapXY {
|
||||
y: number;
|
||||
}
|
||||
/** A box in projected world units: longitude as x, Mercator y growing southwards. */
|
||||
interface MapBox {
|
||||
export interface MapBox {
|
||||
minX: number;
|
||||
minY: number;
|
||||
maxX: number;
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { bookMapElementSchema, bookMapViewSchema } from '@trek/shared';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { boxToView, currentMapBox, moveBox, zoomBox } from './mapViewEdit';
|
||||
|
||||
const frame = { x: 0, y: 0, w: 100, h: 50 };
|
||||
|
||||
describe('editing the visible Studio map window', () => {
|
||||
it('starts from the automatic framing of the current route', () => {
|
||||
const el = bookMapElementSchema.parse({
|
||||
id: 'map',
|
||||
kind: 'map',
|
||||
frame,
|
||||
points: [
|
||||
{ lat: 52.51, lng: 13.38 },
|
||||
{ lat: 52.49, lng: 13.42 },
|
||||
],
|
||||
});
|
||||
const fitted = boxToView(currentMapBox(el));
|
||||
expect(fitted.west).toBeLessThan(13.38);
|
||||
expect(fitted.east).toBeGreaterThan(13.42);
|
||||
expect(fitted.south).toBeLessThan(52.49);
|
||||
expect(fitted.north).toBeGreaterThan(52.51);
|
||||
});
|
||||
|
||||
it('pans a manual view across the antimeridian and zooms it around the same centre', () => {
|
||||
const view = { west: 175, east: 181, south: -19, north: -16 };
|
||||
const el = bookMapElementSchema.parse({ id: 'map', kind: 'map', frame, view });
|
||||
const start = currentMapBox(el);
|
||||
const moved = moveBox(start, 0.5, 0);
|
||||
const closer = boxToView(zoomBox(moved, 2));
|
||||
|
||||
expect(closer.west).toBeCloseTo(179.5);
|
||||
expect(closer.east).toBeCloseTo(182.5);
|
||||
expect(closer.north).toBeLessThan(view.north);
|
||||
expect(closer.south).toBeGreaterThan(view.south);
|
||||
});
|
||||
|
||||
it('keeps an extreme drag or zoom within a valid stored world window', () => {
|
||||
const view = boxToView({ minX: 2000, maxX: 3000, minY: -900, maxY: 900 });
|
||||
expect(bookMapViewSchema.safeParse(view).success).toBe(true);
|
||||
expect(view.east - view.west).toBeLessThanOrEqual(360);
|
||||
expect(view.east).toBeLessThanOrEqual(540);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
import { MAX_BOOK_VIEW_LNG, type BookMapElement, type BookMapView } from '@trek/shared';
|
||||
import { countryDetailShapes } from '../countryDetail';
|
||||
import { COUNTRY_SHAPES, projectMercator, unprojectMercator } from '../countryShapes';
|
||||
import { fitMapWindow, mapBows, mapWantsDetail, projectMapRoute, viewBox, type MapBox } from './mapFit';
|
||||
|
||||
/*
|
||||
* A map framed by hand (#3239): the window it shows as a projected box, moved
|
||||
* and zoomed in the inspector and stored as a view in degrees. Pure, so the
|
||||
* inspector only draws what these answer.
|
||||
*/
|
||||
|
||||
const MIN_SPAN = 0.002;
|
||||
const MAX_LAT = 85;
|
||||
|
||||
/** What the map shows by itself, fitted to its route: the box a hand-framed view starts from. */
|
||||
function autoMapBox(el: BookMapElement): MapBox {
|
||||
const plain = { ...el, view: null };
|
||||
const route = projectMapRoute(plain);
|
||||
const drawLand = (el.source === 'vector' && el.showLand) || el.clip === 'country';
|
||||
const detail = countryDetailShapes(mapWantsDetail(plain, route) ? el.countries : []);
|
||||
const shapes = drawLand
|
||||
? el.countries.map((code) => detail.get(code.toUpperCase()) ?? COUNTRY_SHAPES[code.toUpperCase()]).filter(Boolean)
|
||||
: [];
|
||||
const win = fitMapWindow({
|
||||
el: plain,
|
||||
route,
|
||||
bows: mapBows(plain, route),
|
||||
shapes,
|
||||
cutToLand: el.clip === 'country' && shapes.length > 0,
|
||||
w: el.frame.w,
|
||||
h: el.frame.h,
|
||||
});
|
||||
return { minX: win.minX, minY: win.minY, maxX: win.maxX, maxY: win.maxY };
|
||||
}
|
||||
|
||||
/** The box a map shows now: its own view, or the fitted one. */
|
||||
export function currentMapBox(el: BookMapElement): MapBox {
|
||||
return el.view ? viewBox(el.view) : autoMapBox(el);
|
||||
}
|
||||
|
||||
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
|
||||
|
||||
/** A projected box as a view the schema takes: west to east at most once round, inside the poles. */
|
||||
export function boxToView(box: MapBox): BookMapView {
|
||||
const top = projectMercator(0, MAX_LAT).y;
|
||||
const bottom = projectMercator(0, -MAX_LAT).y;
|
||||
const minY = clamp(box.minY, top, bottom - MIN_SPAN);
|
||||
const maxY = clamp(box.maxY, minY + MIN_SPAN, bottom);
|
||||
const span = clamp(box.maxX - box.minX, MIN_SPAN, 360);
|
||||
const west = clamp((box.minX + box.maxX - span) / 2, -180, MAX_BOOK_VIEW_LNG - span);
|
||||
const east = Math.min(west + span, MAX_BOOK_VIEW_LNG);
|
||||
const nw = unprojectMercator(west, minY);
|
||||
const se = unprojectMercator(east, maxY);
|
||||
return { west: nw.lng, north: nw.lat, east: se.lng, south: se.lat };
|
||||
}
|
||||
|
||||
/** The same box seen closer (factor above 1) or from further away, around its middle. */
|
||||
export function zoomBox(box: MapBox, factor: number): MapBox {
|
||||
const cx = (box.minX + box.maxX) / 2;
|
||||
const cy = (box.minY + box.maxY) / 2;
|
||||
const hw = Math.max((box.maxX - box.minX) / 2 / factor, MIN_SPAN);
|
||||
const hh = Math.max((box.maxY - box.minY) / 2 / factor, MIN_SPAN);
|
||||
return { minX: cx - hw, maxX: cx + hw, minY: cy - hh, maxY: cy + hh };
|
||||
}
|
||||
|
||||
/** The box moved by a share of its own width and height. */
|
||||
export function moveBox(box: MapBox, dx: number, dy: number): MapBox {
|
||||
const w = box.maxX - box.minX;
|
||||
const h = box.maxY - box.minY;
|
||||
return { minX: box.minX + dx * w, maxX: box.maxX + dx * w, minY: box.minY + dy * h, maxY: box.maxY + dy * h };
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties, type ReactNode } from 'react'
|
||||
import { Outlet, useSearchParams } from 'react-router'
|
||||
import { BookOpen, ChevronLeft, MapPin, Grid3x3, Map as MapIcon, MoreHorizontal, Play, Image, Camera, EyeOff, Satellite, Settings2, X, Route, ListChecks } from 'lucide-react'
|
||||
import { BookOpen, ChevronLeft, MapPin, Grid3x3, Map as MapIcon, MoreHorizontal, Play, Image, Camera, EyeOff, Satellite, Settings2, X, Route, ListChecks, FileUp, Trash2, NotebookPen } from 'lucide-react'
|
||||
import JourneyLayeredMap from '../../../components/Journey/JourneyLayeredMap'
|
||||
import type { BaseLayer } from '../../../components/Map/MapLayerSwitcher'
|
||||
import PhotoLightbox from '../../../components/Journey/PhotoLightbox'
|
||||
@@ -29,7 +29,9 @@ import { useGalleryUpload } from '../../../components/Journey/useGalleryUpload'
|
||||
import { dayPrepText, dayPrepUnsettled } from '../../../components/Journey/journeyRecordingPrepModel'
|
||||
import MJourneyEntrySheet from './MJourneyEntrySheet'
|
||||
import { useIsSplit, useIsWide } from '../../../hooks/sizeClass'
|
||||
import { MemberEntryComments } from '../../../components/Journey/JourneyEntryComments'
|
||||
import MJourneyFeed from './MJourneyFeed'
|
||||
import MJourneyFromPhotosSheet from './MJourneyFromPhotosSheet'
|
||||
import MJourneySettingsSheet from './MJourneySettingsSheet'
|
||||
import MJourneyDayImportSheet from './MJourneyDayImportSheet'
|
||||
import MJourneyRecordingSheet from './MJourneyRecordingSheet'
|
||||
@@ -86,9 +88,10 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
showSettings, setShowSettings,
|
||||
hideSkeletons, setHideSkeletons,
|
||||
sidebarMapItems, tracks, mapLayers, entryTitleOf, mapPhotos, openMapPhotos, recordings, canTakeOverRecording, dayImport, dayImportDates, dawarichByDate, recordingPrep,
|
||||
gpxImport, canImportGpx,
|
||||
dismissSuggestion, restoreSuggestions, openAtEntryId,
|
||||
loadJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos,
|
||||
addPickedProviderPhotos, addEntryProviderPhotos, writeAboutPlace,
|
||||
addPickedProviderPhotos, addEntryProviderPhotos, writeAboutPlace, comments,
|
||||
} = useJourneyDetail({ journeyId, embedded })
|
||||
// A trip tab: the header goes into the trip shell's top row (tabHeadSlot.ts).
|
||||
const shellSlot = useTabHeadSlot()
|
||||
@@ -216,6 +219,15 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
// The map's base, switched from the bar: the satellite imagery or the map (#2594).
|
||||
const [mapBase, setMapBase] = useState<BaseLayer>('default')
|
||||
const [showActionMenu, setShowActionMenu] = useState(false)
|
||||
// #3085: the day a GPX file is being picked for, and the hidden picker itself.
|
||||
const gpxFileRef = useRef<HTMLInputElement>(null)
|
||||
const gpxDateRef = useRef<string | null>(null)
|
||||
const pickGpxFor = (date: string) => {
|
||||
setShowActionMenu(false)
|
||||
gpxDateRef.current = date
|
||||
gpxFileRef.current?.click()
|
||||
}
|
||||
const [showFromPhotos, setShowFromPhotos] = useState(false)
|
||||
const [pickerProvider, setPickerProvider] = useState<string | null>(null)
|
||||
// The gallery photo waiting on its delete confirm; entries have their own deleteTarget.
|
||||
const [photoDeleteTarget, setPhotoDeleteTarget] = useState<GalleryPhoto | null>(null)
|
||||
@@ -677,7 +689,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
{/* The recorded route of the day the card rail is on (JRN-01): taking it
|
||||
over, or checking, replacing or dropping the one kept. */}
|
||||
{canEditEntries && view === 'timeline' && entries[activeIndex] &&
|
||||
(canTakeOverRecording || recordings.byDate.has(entries[activeIndex].entry_date)) && (
|
||||
(canTakeOverRecording || recordings.bySource.dawarich.has(entries[activeIndex].entry_date)) && (
|
||||
<MListRow
|
||||
icon={Route}
|
||||
label={t('journey.recording.takeOverDay', {
|
||||
@@ -686,6 +698,37 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
onClick={() => { setShowActionMenu(false); recordings.open(entries[activeIndex].entry_date) }}
|
||||
/>
|
||||
)}
|
||||
{/* #1920: the gallery's loose photos as drafts. */}
|
||||
{canEditEntries && view === 'gallery' && gallery.length > 0 && (
|
||||
<MListRow
|
||||
icon={NotebookPen}
|
||||
label={t('journey.fromPhotos.title')}
|
||||
onClick={() => { setShowActionMenu(false); setShowFromPhotos(true) }}
|
||||
/>
|
||||
)}
|
||||
{/* The day's route from a GPX file (#3085), with or without Dawarich. */}
|
||||
{canEditEntries && canImportGpx && !gpxImport.busy && view === 'timeline' && entries[activeIndex] && (
|
||||
recordings.bySource.gpx.has(entries[activeIndex].entry_date) ? (
|
||||
<>
|
||||
<MListRow
|
||||
icon={FileUp}
|
||||
label={t('journey.recording.replace')}
|
||||
onClick={() => pickGpxFor(entries[activeIndex].entry_date)}
|
||||
/>
|
||||
<MListRow
|
||||
icon={Trash2}
|
||||
label={t('journey.recording.remove')}
|
||||
onClick={() => { setShowActionMenu(false); void gpxImport.removeDay(entries[activeIndex].entry_date) }}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<MListRow
|
||||
icon={FileUp}
|
||||
label={t('journey.recording.gpx.import')}
|
||||
onClick={() => pickGpxFor(entries[activeIndex].entry_date)}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
{/* The same day with its stays (JRN-02), counting the ones still waiting. */}
|
||||
{canEditEntries && canTakeOverRecording && view === 'timeline' && entries[activeIndex] &&
|
||||
dayImportRow(entries[activeIndex].entry_date, () => setShowActionMenu(false))}
|
||||
@@ -699,6 +742,32 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
</div>
|
||||
</MSheet>
|
||||
|
||||
<input
|
||||
ref={gpxFileRef}
|
||||
type="file"
|
||||
accept=".gpx,application/gpx+xml"
|
||||
className="hidden"
|
||||
onChange={e => {
|
||||
const file = e.target.files?.[0]
|
||||
const date = gpxDateRef.current
|
||||
gpxDateRef.current = null
|
||||
e.target.value = ''
|
||||
if (file && date) void gpxImport.importDayFile(file, date)
|
||||
}}
|
||||
/>
|
||||
|
||||
{showFromPhotos && (
|
||||
<MJourneyFromPhotosSheet
|
||||
journeyId={current.id}
|
||||
coverOf={id => {
|
||||
const photo = gallery.find(p => p.id === id)
|
||||
return photo && !posterlessVideo(photo) ? photoUrl(photo, 'thumbnail') : null
|
||||
}}
|
||||
onCreated={() => { void loadJourney(current.id) }}
|
||||
onClose={() => setShowFromPhotos(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Entry sheet (new / edit / read-only) */}
|
||||
{editingEntry && (
|
||||
<MJourneyEntrySheet
|
||||
@@ -706,6 +775,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
|
||||
galleryPhotos={gallery}
|
||||
quickCapture={editingEntry.id === 0}
|
||||
readOnly={!canEditEntries || readingEntry}
|
||||
comments={editingEntry.id > 0 && editingEntry.type !== 'skeleton' ? <MemberEntryComments entryId={editingEntry.id} thread={comments} defaultOpen /> : undefined}
|
||||
onEdit={readingEntry ? () => setEditEntryId(editingEntry.id) : undefined}
|
||||
showVerdict={current.show_verdict !== 0}
|
||||
showMood={current.show_mood !== 0}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useRef, useState, type CSSProperties } from 'react'
|
||||
import { useRef, useState, type CSSProperties, type ReactNode } from 'react'
|
||||
import { Briefcase, Camera, Plus, Image, Images, X, MapPin, Locate, Trash2, CheckCircle2, MinusCircle, ChevronUp, ChevronDown, EyeOff, Play, NotebookPen, Pencil } from 'lucide-react'
|
||||
import { useIsTouch } from '../../../hooks/useIsTouch'
|
||||
import { useTouchDragBridge } from '../../../hooks/useTouchDragBridge'
|
||||
@@ -87,6 +87,8 @@ interface MJourneyEntrySheetProps {
|
||||
onAddProviderPhotos?: (entryId: number, group: PendingProviderGroup) => Promise<void>
|
||||
onDelete?: () => void
|
||||
onDone: () => void
|
||||
/** The comment thread under the entry (#1702), shown while it is read. */
|
||||
comments?: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -97,7 +99,7 @@ interface MJourneyEntrySheetProps {
|
||||
export default function MJourneyEntrySheet({
|
||||
entry, galleryPhotos, quickCapture = false, readOnly = false, userId = 0, trips = [], photoProviders: providers = NO_PROVIDERS,
|
||||
showVerdict = true, showMood = true, showWeather = true, onEdit, onMoveEarlier, onMoveLater, onDismiss,
|
||||
onClose, onSave, onUploadPhotos, onAddProviderPhotos, onDelete, onDone,
|
||||
onClose, onSave, onUploadPhotos, onAddProviderPhotos, onDelete, onDone, comments,
|
||||
}: MJourneyEntrySheetProps) {
|
||||
const { t, language } = useTranslation()
|
||||
const {
|
||||
@@ -769,6 +771,12 @@ export default function MJourneyEntrySheet({
|
||||
<span className="min-w-0 flex-1 text-[0.8125rem] font-semibold">{t('journey.suggestions.dismiss')}</span>
|
||||
</button>
|
||||
)}
|
||||
{readOnly && comments && (
|
||||
<>
|
||||
<div className={`${eyebrow} mb-[6px] mt-4`}>{t('journey.comments.title')}</div>
|
||||
<div className={`${fieldShell} rounded-[14px] px-3 py-3`}>{comments}</div>
|
||||
</>
|
||||
)}
|
||||
</FormSheetBody>
|
||||
|
||||
<div className="m-fs-foot flex flex-none items-center gap-2 border-t border-[color:var(--m-rowbr)] px-[18px] pb-4 pt-3">
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { Images } from 'lucide-react';
|
||||
import JourneyFromPhotosList from '../../../components/Journey/JourneyFromPhotosList';
|
||||
import { useJourneyEntriesFromPhotos } from '../../../components/Journey/useJourneyEntriesFromPhotos';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import MSheet from '../../components/MSheet';
|
||||
import { SHEET_PRIMARY, SHEET_SECONDARY } from '../trip/sheets/MTripSheetUi';
|
||||
import { FormSheetHeader } from '../trip/sheets/PlSheetChrome';
|
||||
|
||||
/** "Entries from photos" on the phone (#1920), on the same hook and list as the desktop dialog. */
|
||||
export default function MJourneyFromPhotosSheet({
|
||||
journeyId,
|
||||
coverOf,
|
||||
onCreated,
|
||||
onClose,
|
||||
}: {
|
||||
journeyId: number;
|
||||
coverOf: (galleryPhotoId: number) => string | null;
|
||||
onCreated: () => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const state = useJourneyEntriesFromPhotos({ journeyId, onCreated, onClose });
|
||||
const allOn = state.clusters.length > 0 && state.selectedCount === state.clusters.length;
|
||||
return (
|
||||
<MSheet open onClose={onClose} variant="bottom" material="glass" ariaLabel={t('journey.fromPhotos.title')}>
|
||||
<div className="flex max-h-[86dvh] min-h-0 flex-col">
|
||||
<FormSheetHeader
|
||||
icon={Images}
|
||||
title={t('journey.fromPhotos.title')}
|
||||
subtitle={t('journey.fromPhotos.text')}
|
||||
onClose={onClose}
|
||||
closeLabel={t('common.close')}
|
||||
/>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-[14px] pb-3">
|
||||
<JourneyFromPhotosList state={state} coverOf={coverOf} />
|
||||
</div>
|
||||
<div className="flex flex-none items-center gap-2 border-t border-[color:var(--m-rowbr)] px-[18px] pb-4 pt-3">
|
||||
{state.clusters.length > 1 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => state.selectAll(!allOn)}
|
||||
className={`${SHEET_SECONDARY} whitespace-nowrap`}
|
||||
>
|
||||
{allOn ? t('common.deselectAll') : t('common.selectAll')}
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
disabled={!state.canSubmit}
|
||||
onClick={state.submit}
|
||||
className={`${SHEET_PRIMARY} flex-1 justify-center disabled:opacity-50`}
|
||||
>
|
||||
{t('journey.fromPhotos.create', { count: state.selectedCount })}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</MSheet>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useRef, useState, type ReactNode } from 'react'
|
||||
import { Image, Plus, Trash2, UserPlus, UserMinus, Unlink, Settings2, Link as LinkIcon, List, Grid3x3, MapPin, Route, Archive, ArchiveRestore, Undo2, Link2, ListChecks, RefreshCw } from 'lucide-react'
|
||||
import { Image, Plus, Trash2, UserPlus, UserMinus, Unlink, Settings2, Link as LinkIcon, List, Grid3x3, MapPin, Route, Archive, ArchiveRestore, Undo2, Link2, ListChecks, RefreshCw, MessageCircle, BellPlus, Lock, CalendarClock, Eye, X } from 'lucide-react'
|
||||
import MLinkField from '../../components/MLinkField'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import {
|
||||
@@ -20,6 +20,8 @@ import { useJourneySettings, useJourneyTripLinking } from '../../../components/J
|
||||
import {
|
||||
SHARE_MAP_EXTRAS, useJourneyShareLink, type JourneyShareLink, type JourneyShareMapExtra,
|
||||
} from '../../../components/Journey/useJourneyShareLink'
|
||||
import { useJourneyShareAccess } from '../../../components/Journey/useJourneyShareAccess'
|
||||
import JourneySharePasswordDialog from '../../../components/Journey/JourneySharePasswordDialog'
|
||||
import type { JourneyRecordingPrepState } from '../../../components/Journey/useJourneyRecordingPrep'
|
||||
import { pickGradient } from '../../../pages/journeyDetail/JourneyDetailPage.helpers'
|
||||
import { journeyCoverSrc } from './mobileJourneyMeta'
|
||||
@@ -56,8 +58,9 @@ export default function MJourneySettingsSheet({
|
||||
})
|
||||
const {
|
||||
link: shareLink, copied, shareUrl, createLink: createShareLink, togglePerm: toggleSharePerm,
|
||||
deleteLink: deleteShareLink, copyLink: copyShareUrl,
|
||||
deleteLink: deleteShareLink, copyLink: copyShareUrl, setProtection,
|
||||
} = useJourneyShareLink(journey.id)
|
||||
const shareAccess = useJourneyShareAccess(journey.id, shareLink, setProtection)
|
||||
const coverRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const coverSrc = journeyCoverSrc(journey.cover_image)
|
||||
@@ -256,6 +259,13 @@ export default function MJourneySettingsSheet({
|
||||
shareLabel={t('common.share')}
|
||||
/>
|
||||
)}
|
||||
{shareAccess.views > 0 && (
|
||||
<div className="flex items-center gap-1.5 ps-1 font-geist text-caption text-m-muted">
|
||||
<Eye size={12} strokeWidth={2} />
|
||||
<span>{t('journey.share.views', { count: shareAccess.views })}</span>
|
||||
{shareAccess.lastViewed && <span>{t('journey.share.lastViewed', { date: shareAccess.lastViewed })}</span>}
|
||||
</div>
|
||||
)}
|
||||
{([
|
||||
{ key: 'share_timeline' as const, label: t('journey.share.timeline'), icon: List },
|
||||
{ key: 'share_gallery' as const, label: t('journey.share.gallery'), icon: Grid3x3 },
|
||||
@@ -270,6 +280,23 @@ export default function MJourneySettingsSheet({
|
||||
/>
|
||||
))}
|
||||
<MShareMapExtras link={shareLink} onToggle={toggleSharePerm} />
|
||||
<ToggleRow
|
||||
icon={<MessageCircle size={16} strokeWidth={2} />}
|
||||
label={t('journey.share.allowComments')}
|
||||
hint={shareLink.share_timeline ? t('journey.share.allowCommentsHint') : t('journey.share.needsTimeline')}
|
||||
checked={!!shareLink.share_timeline && !!shareLink.allow_comments}
|
||||
disabled={!shareLink.share_timeline}
|
||||
onChange={() => { void toggleSharePerm('allow_comments') }}
|
||||
/>
|
||||
<ToggleRow
|
||||
icon={<BellPlus size={16} strokeWidth={2} />}
|
||||
label={t('journey.share.allowFollowers')}
|
||||
hint={t('journey.share.allowFollowersHint')}
|
||||
checked={!!shareLink.allow_subscriptions}
|
||||
onChange={() => { void toggleSharePerm('allow_subscriptions') }}
|
||||
/>
|
||||
{shareLink.allow_subscriptions && <MShareFollowers access={shareAccess} />}
|
||||
<MShareAccess access={shareAccess} />
|
||||
<button
|
||||
type="button"
|
||||
onClick={deleteShareLink}
|
||||
@@ -410,6 +437,83 @@ function MRecordingPrepRow({ prep, enabled }: { prep: JourneyRecordingPrepState;
|
||||
)
|
||||
}
|
||||
|
||||
type ShareAccess = ReturnType<typeof useJourneyShareAccess>
|
||||
|
||||
/** The addresses following the link (#1669): two counts, the list behind them. */
|
||||
function MShareFollowers({ access }: { access: ShareAccess }) {
|
||||
const { t } = useTranslation()
|
||||
const { followers } = access
|
||||
if (followers.status !== 'ready' || (followers.count === 0 && followers.pending === 0)) return null
|
||||
return (
|
||||
<div className="mb-1 ms-[9px] border-s-2 border-[color:var(--m-rowbr)] ps-[16px]">
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={access.followersOpen}
|
||||
onClick={() => access.setFollowersOpen(!access.followersOpen)}
|
||||
className="flex flex-wrap items-center gap-1.5 py-[7px] font-geist text-caption"
|
||||
>
|
||||
<span className="rounded-full bg-[color:var(--m-ic)] px-2 py-0.5 font-semibold text-m-ink">{t('journey.share.followers', { count: followers.count })}</span>
|
||||
{followers.pending > 0 && (
|
||||
<span className="rounded-full bg-[color:var(--m-ic)] px-2 py-0.5 text-m-muted">{t('journey.share.followersPending', { count: followers.pending })}</span>
|
||||
)}
|
||||
</button>
|
||||
{access.followersOpen && followers.subscribers.map(sub => (
|
||||
<div key={sub.id} className="flex items-center gap-2">
|
||||
<span className={`min-w-0 flex-1 truncate font-geist text-caption ${sub.confirmed ? 'text-m-ink' : 'text-m-muted'}`}>{sub.email}</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('journey.share.removeFollower')}
|
||||
onClick={() => void access.removeFollower(sub.id)}
|
||||
className="flex h-10 w-10 flex-none items-center justify-center text-m-muted"
|
||||
>
|
||||
<X size={14} strokeWidth={2.2} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Password and end date of the link (#2553), one row each. */
|
||||
function MShareAccess({ access }: { access: ShareAccess }) {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<div className="flex flex-col gap-[6px]">
|
||||
<div className="flex items-center gap-[11px] rounded-[14px] bg-[color:var(--m-ic)] px-3 py-[10px]">
|
||||
<Lock size={16} strokeWidth={2} className="flex-none text-m-muted" />
|
||||
<div className="min-w-0 flex-1 text-body font-semibold text-m-ink">{t('common.password')}</div>
|
||||
{access.hasPassword && (
|
||||
<button type="button" onClick={() => void access.removePassword()} className="px-1 font-geist text-caption font-semibold text-[color:var(--m-st-danger)]">
|
||||
{t('common.remove')}
|
||||
</button>
|
||||
)}
|
||||
<button type="button" onClick={() => access.setPasswordOpen(true)} className="rounded-full bg-m-sheetop px-3 py-1.5 font-geist text-caption font-semibold text-m-ink">
|
||||
{access.hasPassword ? t('common.change') : t('journey.share.passwordSet')}
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex items-center gap-[11px] rounded-[14px] bg-[color:var(--m-ic)] px-3 py-[10px]">
|
||||
<CalendarClock size={16} strokeWidth={2} className="flex-none text-m-muted" />
|
||||
<div className="min-w-0 flex-1 text-body font-semibold text-m-ink">{t('journey.share.expires')}</div>
|
||||
{!access.expiry && <span className="font-geist text-caption text-m-muted">{t('journey.share.expiresNever')}</span>}
|
||||
<input
|
||||
type="date"
|
||||
value={access.expiry}
|
||||
min={access.minExpiry}
|
||||
onChange={e => access.setExpiry(e.target.value)}
|
||||
aria-label={t('journey.share.expires')}
|
||||
className="bg-transparent font-geist text-caption text-m-ink outline-none"
|
||||
/>
|
||||
{access.expiry && (
|
||||
<button type="button" aria-label={t('journey.share.expiresNever')} onClick={() => access.setExpiry('')} className="flex h-8 w-8 flex-none items-center justify-center text-m-muted">
|
||||
<X size={14} strokeWidth={2.2} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{access.passwordOpen && <JourneySharePasswordDialog onSave={access.savePassword} onClose={() => access.setPasswordOpen(false)} />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** What the shared map shows besides the entries (JRN-04), only while the map is shared. */
|
||||
function MShareMapExtras({ link, onToggle }: { link: JourneyShareLink; onToggle: (key: JourneyShareMapExtra) => unknown }) {
|
||||
const { t } = useTranslation()
|
||||
|
||||
@@ -32,6 +32,7 @@ import { AddTripDialog } from '../components/Journey/JourneyDetailPageAddTripDia
|
||||
import { JourneySettingsDialog } from '../components/Journey/JourneyDetailPageSettingsDialog'
|
||||
import HelpAnchor from '../components/Help/HelpAnchor'
|
||||
import JourneyDayJump from '../components/Journey/JourneyDayJump'
|
||||
import { MemberEntryComments } from '../components/Journey/JourneyEntryComments'
|
||||
|
||||
export default function JourneyDetailPage() {
|
||||
// ViewportRoute in App.tsx picks the branch now, so the phone screen is a
|
||||
@@ -53,7 +54,7 @@ export function JourneyDetailPageDesktop({ journeyId, embedded = false }: Journe
|
||||
// Page = wiring container: load + live sync, view state, dialogs, the
|
||||
// scroll-synced map and the map/trip-date derivations live in the hook.
|
||||
const {
|
||||
id, navigate, toast, t, locale,
|
||||
id, navigate, toast, t, locale, comments,
|
||||
openStudio, prefetchStudio,
|
||||
current, loading,
|
||||
canEditEntries, canEditJourney, myRole,
|
||||
@@ -69,7 +70,7 @@ export function JourneyDetailPageDesktop({ journeyId, embedded = false }: Journe
|
||||
galleryUploadProgress, setGalleryUploadProgress,
|
||||
activeLocationId, handleMarkerClick, handleLocationClick,
|
||||
mapEntries, sidebarMapItems, tripDates, isMobile, tracks, mapPhotos, openMapPhotos, mapLayers, entryTitleOf,
|
||||
recordings, canTakeOverRecording, recordingNeedsConnection, dayImport, recordingPrep,
|
||||
recordings, canTakeOverRecording, recordingNeedsConnection, dayImport, recordingPrep, gpxImport, canImportGpx,
|
||||
feedEdge, scrollFeedTo,
|
||||
loadJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto,
|
||||
addPickedProviderPhotos, addEntryProviderPhotos, writeAboutPlace,
|
||||
@@ -211,6 +212,7 @@ export function JourneyDetailPageDesktop({ journeyId, embedded = false }: Journe
|
||||
<MobileEntryView
|
||||
entry={viewingEntry}
|
||||
readOnly={!canEditEntries}
|
||||
comments={<MemberEntryComments entryId={viewingEntry.id} thread={comments} />}
|
||||
onClose={() => setViewingEntry(null)}
|
||||
onEdit={() => { setViewingEntry(null); setEditingEntry(viewingEntry); }}
|
||||
onDelete={() => { setViewingEntry(null); setDeleteTarget(viewingEntry); }}
|
||||
@@ -508,11 +510,18 @@ export function JourneyDetailPageDesktop({ journeyId, embedded = false }: Journe
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-[0.07em]" style={{ background: 'var(--vg-surf2)', color: 'var(--vg-ink3)' }}><MapPin size={12} /> {entries.length} {t('journey.synced.places', { count: entries.length })}</span>
|
||||
<JourneyDayRecordingButton
|
||||
day={recordings.byDate.get(date)}
|
||||
day={recordings.bySource.dawarich.get(date)}
|
||||
canEdit={canEditEntries}
|
||||
canTakeOver={canTakeOverRecording}
|
||||
needsConnection={recordingNeedsConnection}
|
||||
onOpen={() => recordings.open(date)}
|
||||
gpx={{
|
||||
day: recordings.bySource.gpx.get(date),
|
||||
canImport: canImportGpx,
|
||||
busy: gpxImport.busy,
|
||||
onImport: file => void gpxImport.importDayFile(file, date),
|
||||
onRemove: () => void gpxImport.removeDay(date),
|
||||
}}
|
||||
/>
|
||||
<JourneyDayImportButton
|
||||
pending={stays.length}
|
||||
@@ -601,6 +610,7 @@ export function JourneyDetailPageDesktop({ journeyId, embedded = false }: Journe
|
||||
<EntryCard
|
||||
entry={entry}
|
||||
readOnly={!canEditEntries}
|
||||
comments={<MemberEntryComments entryId={entry.id} thread={comments} />}
|
||||
onEdit={() => setEditingEntry(entry)}
|
||||
onDelete={() => setDeleteTarget(entry)}
|
||||
onPhotoClick={(photos, idx) => setLightbox({ photos: photos.map(p => ({ id: p.id, src: photoUrl(p, 'original'), thumbSrc: photoUrl(p, 'thumbnail'), caption: p.caption, provider: p.provider, asset_id: p.asset_id, owner_id: p.owner_id, mediaType: p.media_type })), index: idx })}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { BellOff, BellRing, CircleAlert, Loader2 } from 'lucide-react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useTranslation } from '../i18n';
|
||||
import { useJourneyFollowPage } from './journeyFollow/useJourneyFollowPage';
|
||||
|
||||
/**
|
||||
* Where a follower's mail links land (#1669): the page confirms the address or
|
||||
* ends the subscription, then says so in one card.
|
||||
*/
|
||||
export default function JourneyFollowPage() {
|
||||
const { t } = useTranslation();
|
||||
const { state } = useJourneyFollowPage();
|
||||
|
||||
let icon = <Loader2 size={20} className="animate-spin" />;
|
||||
let title = t('common.loading');
|
||||
let text = '';
|
||||
if (state.status === 'confirmed') {
|
||||
icon = <BellRing size={20} />;
|
||||
title = t('journey.follow.confirmedTitle');
|
||||
text = t('journey.follow.confirmedText', { title: state.title });
|
||||
} else if (state.status === 'unsubscribed') {
|
||||
icon = <BellOff size={20} />;
|
||||
title = t('journey.follow.unsubscribedTitle');
|
||||
text = t('journey.follow.unsubscribedText');
|
||||
} else if (state.status === 'invalid' || state.status === 'failed') {
|
||||
icon = <CircleAlert size={20} />;
|
||||
title = t(state.status === 'invalid' ? 'journey.follow.invalidTitle' : 'common.errorTitle');
|
||||
text = t(state.status === 'invalid' ? 'journey.follow.invalidText' : 'journey.follow.failed');
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-surface-secondary px-4">
|
||||
<div className="w-full max-w-sm rounded-[28px] border border-edge-faint bg-surface-card p-7 text-center shadow-sm">
|
||||
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-2xl bg-surface-secondary text-content-muted">
|
||||
{icon}
|
||||
</div>
|
||||
<h1 className="text-subtitle font-bold text-content">{title}</h1>
|
||||
{text && <p className="mt-1.5 text-body text-content-muted">{text}</p>}
|
||||
{state.status === 'confirmed' && (
|
||||
<Link
|
||||
to={`/public/journey/${state.link}`}
|
||||
className="mt-5 inline-flex w-full items-center justify-center rounded-xl bg-accent py-2.5 text-body font-semibold text-accent-text transition-colors hover:bg-accent-hover"
|
||||
>
|
||||
{t('common.open')}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -32,6 +32,9 @@ import { useTranslation } from '../i18n';
|
||||
import { formatLocationName } from '../utils/formatters';
|
||||
import { posterlessVideo } from './journeyDetail/JourneyDetailPage.helpers';
|
||||
import { useJourneyPublic } from './journeyPublic/useJourneyPublic';
|
||||
import { GuestEntryComments } from '../components/Journey/JourneyEntryComments';
|
||||
import { JourneyPublicExpired, JourneyPublicPasswordCard } from './journeyPublic/JourneyPublicGate';
|
||||
import { JourneyPublicFollow } from './journeyPublic/JourneyPublicFollow';
|
||||
|
||||
const MOOD_CONFIG: Record<string, { icon: typeof Smile; label: string; bg: string; text: string }> = {
|
||||
amazing: {
|
||||
@@ -116,6 +119,9 @@ export default function JourneyPublicPage() {
|
||||
data,
|
||||
loading,
|
||||
error,
|
||||
access,
|
||||
unlock,
|
||||
social,
|
||||
isMobile,
|
||||
locale,
|
||||
view,
|
||||
@@ -151,6 +157,8 @@ export default function JourneyPublicPage() {
|
||||
} = useJourneyPublic();
|
||||
|
||||
if (loading) return <SharedLoading />;
|
||||
if (access === 'locked') return <JourneyPublicPasswordCard onUnlock={unlock} />;
|
||||
if (access === 'expired') return <JourneyPublicExpired />;
|
||||
|
||||
if (error || !data) {
|
||||
return (
|
||||
@@ -549,6 +557,12 @@ export default function JourneyPublicPage() {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{social.commentsOpen && (
|
||||
<div className="mt-3 border-t border-zinc-100 pt-3 dark:border-zinc-800">
|
||||
<GuestEntryComments entryId={entry.id} thread={social} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -619,6 +633,7 @@ export default function JourneyPublicPage() {
|
||||
<SharedHero
|
||||
trip={{ title: journey.title, description: journey.subtitle, cover_image: journey.cover_image, start_date: firstDate, end_date: lastDate }}
|
||||
stats={heroStats}
|
||||
action={social.canSubscribe ? <JourneyPublicFollow onSubscribe={social.subscribe} /> : undefined}
|
||||
/>
|
||||
{!floatingSwitch && (
|
||||
<SharedTabBar tabs={availableViews.map(v => ({ id: v.id, label: v.label, icon: v.icon }))} active={view} onChange={id => setView(id as typeof view)} />
|
||||
@@ -777,6 +792,7 @@ export default function JourneyPublicPage() {
|
||||
publicPhotoUrl={(photoId, size = 'original') =>
|
||||
`/api/public/journey/${token}/photos/${photoId}/${size}`
|
||||
}
|
||||
comments={social.commentsOpen ? <GuestEntryComments entryId={viewingEntry.id} thread={social} /> : undefined}
|
||||
onClose={() => setViewingEntry(null)}
|
||||
onEdit={() => { }}
|
||||
onDelete={() => { }}
|
||||
|
||||
@@ -21,6 +21,7 @@ import type { DawarichSuggestion, DawarichSuggestionTarget, JourneyMapPlace } fr
|
||||
import { useDawarichJournalTrail } from '../../hooks/useDawarichJournalTrail'
|
||||
import { useJourneyDetailLayers } from './useJourneyDetailLayers'
|
||||
import { useProviderPhotoAdds } from './useProviderPhotoAdds'
|
||||
import { useJourneyComments } from '../../components/Journey/useJourneyComments'
|
||||
|
||||
|
||||
/**
|
||||
@@ -540,7 +541,7 @@ export function useJourneyDetail({ journeyId, embedded = false }: JourneyDetailO
|
||||
|
||||
const {
|
||||
recordingPrep, recordings, canTakeOverRecording, recordingNeedsConnection, mapTracks, mapLayers, entryTitleOf,
|
||||
dayImport, dayImportDates,
|
||||
dayImport, dayImportDates, gpxImport, canImportGpx,
|
||||
} = useJourneyDetailLayers({
|
||||
journey: current, loaded: journeyLoaded, canEditEntries, loadJourney: refreshJourney, dawarich, dawarichByDate, dawarichTrail,
|
||||
tripDates, sidebarMapItems, photoCount: mapPhotos.length, showTripTracks,
|
||||
@@ -574,8 +575,11 @@ export function useJourneyDetail({ journeyId, embedded = false }: JourneyDetailO
|
||||
void import('../JourneyStudioPage')
|
||||
}, [])
|
||||
|
||||
// #1702: the threads under the entries, read once the journey is here.
|
||||
const comments = useJourneyComments(journeyLoaded && current ? current.id : null)
|
||||
|
||||
return {
|
||||
id, navigate, toast, t, locale, embedded, notFound,
|
||||
id, navigate, toast, t, locale, embedded, notFound, comments,
|
||||
openStudio, prefetchStudio,
|
||||
current, loading,
|
||||
canEditEntries, canEditJourney, myRole,
|
||||
@@ -592,7 +596,7 @@ export function useJourneyDetail({ journeyId, embedded = false }: JourneyDetailO
|
||||
galleryUploadProgress, setGalleryUploadProgress,
|
||||
activeLocationId, handleMarkerClick, handleLocationClick,
|
||||
mapEntries, sidebarMapItems, tripDates, isMobile, tracks: mapTracks, dawarichTrail, mapLayers, entryTitleOf,
|
||||
recordings, canTakeOverRecording, recordingNeedsConnection, dayImport, dayImportDates, recordingPrep,
|
||||
recordings, canTakeOverRecording, recordingNeedsConnection, dayImport, dayImportDates, recordingPrep, gpxImport, canImportGpx,
|
||||
mapPhotos, openMapPhotos,
|
||||
feedEdge, scrollFeedTo,
|
||||
// The views reload after their own changes; such a read never rejects.
|
||||
|
||||
@@ -41,7 +41,7 @@ export function useJourneyDetailRecordings({
|
||||
);
|
||||
const recordings = useJourneyRecordings(journey, colorOfDay);
|
||||
// #3085: a GPX file is a source of its own, open to whoever may edit, with or without Dawarich.
|
||||
const gpxImport = useJourneyGpxImport(journeyId, recordings.keptMany);
|
||||
const gpxImport = useJourneyGpxImport(journeyId, recordings.keptMany, recordings.removed);
|
||||
|
||||
const mapTracks = useMemo(() => {
|
||||
if (recordings.tracks.length === 0 && liveTracks.length === 0) return tripTracks;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { useParams, useSearchParams } from 'react-router-dom';
|
||||
import { useJourneyFollow } from './useJourneyFollow';
|
||||
|
||||
/**
|
||||
* The follower page's state: which mail link was opened (`/public/journey-follow/
|
||||
* confirm` or `/unsubscribe`) and what posting its token came to. An unknown
|
||||
* action reads as an unknown link.
|
||||
*/
|
||||
export function useJourneyFollowPage() {
|
||||
const { action } = useParams();
|
||||
const [params] = useSearchParams();
|
||||
const known = action === 'confirm' || action === 'unsubscribe' ? action : null;
|
||||
const state = useJourneyFollow(known ?? 'confirm', known ? params.get('token') : null);
|
||||
return { action: known, state };
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import { BellPlus, MailCheck } from 'lucide-react';
|
||||
import { useId, useState, type FormEvent } from 'react';
|
||||
import {
|
||||
DialogButton,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogShell,
|
||||
DialogTile,
|
||||
FooterSpacer,
|
||||
NEUTRAL_TINT,
|
||||
fs,
|
||||
} from '../../components/shared/DialogShell';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { GLASS } from '../sharedTrip/SharedChrome';
|
||||
import type { PublicSocialOutcome } from './journeyPublicModel';
|
||||
|
||||
const OUTCOME_KEYS: Record<Exclude<PublicSocialOutcome, 'ok'>, string> = {
|
||||
closed: 'journey.follow.closed',
|
||||
gone: 'journey.public.notFoundMessage',
|
||||
locked: 'journey.comments.locked',
|
||||
rate_limited: 'common.tooManyAttempts',
|
||||
invalid: 'journey.follow.invalid',
|
||||
failed: 'journey.follow.failed',
|
||||
};
|
||||
|
||||
/**
|
||||
* "Follow" on a shared journey (#1669): one glass pill in the hero, and a small
|
||||
* dialog that takes an address. The server answers the same for an address that
|
||||
* already follows, so the dialog always ends on "check your inbox".
|
||||
*/
|
||||
export function JourneyPublicFollow({
|
||||
onSubscribe,
|
||||
}: {
|
||||
onSubscribe: (email: string, locale: string) => Promise<PublicSocialOutcome>;
|
||||
}) {
|
||||
const { t, locale } = useTranslation();
|
||||
const labelId = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [email, setEmail] = useState('');
|
||||
const [trap, setTrap] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [sent, setSent] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const close = () => {
|
||||
setOpen(false);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (busy || sent || !email.trim()) return;
|
||||
// Only a bot fills the field people never see: it is told all went well.
|
||||
if (trap) {
|
||||
setSent(true);
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const outcome = await onSubscribe(email.trim(), locale || 'en');
|
||||
setBusy(false);
|
||||
if (outcome === 'ok') setSent(true);
|
||||
else setError(t(OUTCOME_KEYS[outcome]));
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(true)}
|
||||
className={`${GLASS} hover:bg-white/25`}
|
||||
style={fs(12, 'body')}
|
||||
>
|
||||
<BellPlus size={13} strokeWidth={2} aria-hidden />
|
||||
{t('journey.follow.title')}
|
||||
</button>
|
||||
{open && (
|
||||
<DialogShell
|
||||
onClose={close}
|
||||
labelledBy={labelId}
|
||||
width="narrow"
|
||||
onSubmit={(e) => void submit(e)}
|
||||
header={
|
||||
<DialogHeader
|
||||
tile={<DialogTile>{sent ? <MailCheck size={18} /> : <BellPlus size={18} />}</DialogTile>}
|
||||
tint={NEUTRAL_TINT}
|
||||
labelId={labelId}
|
||||
onClose={close}
|
||||
title={sent ? t('journey.follow.sentTitle') : t('journey.follow.title')}
|
||||
sub={sent ? t('journey.follow.sentText') : t('journey.follow.text')}
|
||||
subWraps
|
||||
/>
|
||||
}
|
||||
footer={
|
||||
<DialogFooter>
|
||||
<FooterSpacer />
|
||||
{sent ? (
|
||||
<DialogButton variant="primary" onClick={close}>
|
||||
{t('common.close')}
|
||||
</DialogButton>
|
||||
) : (
|
||||
<DialogButton variant="primary" type="submit" disabled={busy || !email.trim()}>
|
||||
{t('journey.follow.title')}
|
||||
</DialogButton>
|
||||
)}
|
||||
</DialogFooter>
|
||||
}
|
||||
>
|
||||
{!sent && (
|
||||
<div className="flex flex-col gap-2 px-6 py-5">
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
autoFocus
|
||||
autoComplete="email"
|
||||
placeholder={t('common.email')}
|
||||
aria-label={t('common.email')}
|
||||
className="w-full rounded-xl border border-edge bg-surface px-3.5 py-2.5 text-body text-content outline-none placeholder:text-content-faint focus:border-content-faint"
|
||||
/>
|
||||
{/* Left empty by people: the field sits off screen and out of the tab order. */}
|
||||
<input
|
||||
value={trap}
|
||||
onChange={(e) => setTrap(e.target.value)}
|
||||
name="website"
|
||||
tabIndex={-1}
|
||||
autoComplete="off"
|
||||
aria-hidden="true"
|
||||
className="absolute -start-[9999px] h-px w-px opacity-0"
|
||||
/>
|
||||
{error && (
|
||||
<p role="alert" className="text-caption text-danger">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<p className="text-caption text-content-faint">{t('journey.follow.privacy')}</p>
|
||||
</div>
|
||||
)}
|
||||
</DialogShell>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { Clock, Lock } from 'lucide-react';
|
||||
import { useState, type FormEvent, type ReactNode } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import type { PublicUnlockOutcome } from './journeyPublicModel';
|
||||
|
||||
const OUTCOME_KEYS: Record<Exclude<PublicUnlockOutcome, 'ok' | 'expired'>, string> = {
|
||||
wrong: 'journey.public.passwordWrong',
|
||||
rate_limited: 'common.tooManyAttempts',
|
||||
failed: 'journey.public.passwordFailed',
|
||||
};
|
||||
|
||||
function GateFrame({
|
||||
icon,
|
||||
title,
|
||||
text,
|
||||
children,
|
||||
}: {
|
||||
icon: ReactNode;
|
||||
title: string;
|
||||
text: string;
|
||||
children?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-surface-secondary px-4">
|
||||
<div className="w-full max-w-sm rounded-[28px] border border-edge-faint bg-surface-card p-7 text-center shadow-sm">
|
||||
<div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-2xl bg-surface-secondary text-content-muted">
|
||||
{icon}
|
||||
</div>
|
||||
<h1 className="text-subtitle font-bold text-content">{title}</h1>
|
||||
<p className="mt-1.5 text-body text-content-muted">{text}</p>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** A shared journey behind a password (#2553): one field, and why it did not open. */
|
||||
export function JourneyPublicPasswordCard({
|
||||
onUnlock,
|
||||
}: {
|
||||
onUnlock: (password: string) => Promise<PublicUnlockOutcome>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const [password, setPassword] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!password || busy) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const outcome = await onUnlock(password);
|
||||
setBusy(false);
|
||||
if (outcome === 'ok' || outcome === 'expired') return;
|
||||
setError(t(OUTCOME_KEYS[outcome]));
|
||||
};
|
||||
|
||||
return (
|
||||
<GateFrame icon={<Lock size={20} />} title={t('journey.public.lockedTitle')} text={t('journey.public.lockedText')}>
|
||||
<form onSubmit={(e) => void submit(e)} className="mt-5 flex flex-col gap-2.5">
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoFocus
|
||||
autoComplete="current-password"
|
||||
placeholder={t('common.password')}
|
||||
aria-label={t('common.password')}
|
||||
className="w-full rounded-xl border border-edge bg-surface px-3.5 py-2.5 text-body text-content outline-none placeholder:text-content-faint focus:border-content-faint"
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!password || busy}
|
||||
className="w-full rounded-xl bg-accent py-2.5 text-body font-semibold text-accent-text transition-colors hover:bg-accent-hover disabled:opacity-50"
|
||||
>
|
||||
{t('journey.public.unlock')}
|
||||
</button>
|
||||
{error && (
|
||||
<p role="alert" className="text-caption text-danger">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
</GateFrame>
|
||||
);
|
||||
}
|
||||
|
||||
/** A shared journey whose owner let the link run out. */
|
||||
export function JourneyPublicExpired() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<GateFrame
|
||||
icon={<Clock size={20} />}
|
||||
title={t('journey.public.expiredTitle')}
|
||||
text={t('journey.public.expiredText')}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -11,9 +11,16 @@ import {
|
||||
groupByDate, publicLinkAccessOf, unlockOutcomeOf,
|
||||
type PublicEntry, type PublicGalleryPhoto, type PublicLinkAccess, type PublicUnlockOutcome,
|
||||
} from './journeyPublicModel'
|
||||
import { useJourneyPublicSocial } from './useJourneyPublicSocial'
|
||||
import { useJourneyMapLayers } from '../../components/Journey/useJourneyMapLayers'
|
||||
import { journeyOpenAtEntryId } from '../../components/Journey/journeyOpenAt'
|
||||
import { localIsoDate } from '../../utils/localDate'
|
||||
import { journeySocialRepo } from '../../repo/journeySocialRepo'
|
||||
|
||||
type PublicJourneyRead = { token: string; revision: number } & (
|
||||
| { status: 'open'; data: Awaited<ReturnType<typeof journeyApi.getPublicJourney>> }
|
||||
| { status: 'locked' | 'expired' | 'error' }
|
||||
)
|
||||
|
||||
/**
|
||||
* Public-journey (read-only share) data hook — owns the token fetch, the
|
||||
@@ -26,14 +33,14 @@ import { localIsoDate } from '../../utils/localDate'
|
||||
*/
|
||||
export function useJourneyPublic() {
|
||||
const { token } = useParams()
|
||||
const [data, setData] = useState<any>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState(false)
|
||||
// #2553: a link with a password answers 401 until this browser unlocked it,
|
||||
// one past its date 410; the page shows a password card or a "gone" note.
|
||||
const [access, setAccess] = useState<PublicLinkAccess>('open')
|
||||
// Bumped by a successful unlock, so the read runs again with the new cookie.
|
||||
const [response, setResponse] = useState<PublicJourneyRead | null>(null)
|
||||
const [reloadKey, setReloadKey] = useState(0)
|
||||
// React can keep the page mounted when the visitor follows a different link.
|
||||
const current = response && response.token === token && response.revision === reloadKey ? response : null
|
||||
const data = current?.status === 'open' ? current.data : null
|
||||
const loading = !!token && !current
|
||||
const error = !token || current?.status === 'error'
|
||||
const access: PublicLinkAccess = current?.status === 'locked' || current?.status === 'expired' ? current.status : 'open'
|
||||
const isMobile = useIsMobile()
|
||||
const [view, setView] = useState<'timeline' | 'gallery' | 'map'>('timeline')
|
||||
const [lightbox, setLightbox] = useState<{ photos: { id: string; src: string; thumbSrc?: string; caption?: string | null; mediaType?: string | null }[]; index: number } | null>(null)
|
||||
@@ -58,17 +65,13 @@ export function useJourneyPublic() {
|
||||
journeyApi.getPublicJourney(token)
|
||||
.then(d => {
|
||||
if (cancelled) return
|
||||
setData(d)
|
||||
setAccess('open')
|
||||
setResponse({ token, revision: reloadKey, status: 'open', data: d })
|
||||
void journeySocialRepo.recordPublicView(token)
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (cancelled) return
|
||||
const refused = publicLinkAccessOf(err)
|
||||
if (refused) setAccess(refused)
|
||||
else setError(true)
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
setResponse({ token, revision: reloadKey, status: refused ?? 'error' })
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
@@ -83,16 +86,18 @@ export function useJourneyPublic() {
|
||||
const unlock = useCallback(async (password: string): Promise<PublicUnlockOutcome> => {
|
||||
if (!token) return 'failed'
|
||||
try {
|
||||
await journeyApi.unlockPublicJourney(token, password)
|
||||
await journeySocialRepo.unlockPublicJourney(token, password)
|
||||
} catch (err) {
|
||||
const outcome = unlockOutcomeOf(err)
|
||||
if (outcome === 'expired') setAccess('expired')
|
||||
if (outcome === 'expired') setResponse({ token, revision: reloadKey, status: 'expired' })
|
||||
return outcome
|
||||
}
|
||||
setLoading(true)
|
||||
setReloadKey(n => n + 1)
|
||||
return 'ok'
|
||||
}, [token])
|
||||
}, [token, reloadKey])
|
||||
|
||||
// #1702, #1669: what a reader may do besides reading, as the owner allows it.
|
||||
const social = useJourneyPublicSocial(token, data?.interaction)
|
||||
|
||||
const entries = (data?.entries || []) as PublicEntry[]
|
||||
const gallery = (data?.gallery || []) as PublicGalleryPhoto[]
|
||||
@@ -212,7 +217,7 @@ export function useJourneyPublic() {
|
||||
}, [desktopTwoColumn, view])
|
||||
|
||||
return {
|
||||
token, data, loading, error, access, unlock, isMobile, locale,
|
||||
token, data, loading, error, access, unlock, social, isMobile, locale,
|
||||
view, setView, lightbox, setLightbox, showLangPicker, setShowLangPicker,
|
||||
mapRef, feedRef, activeEntryId, setActiveEntryId, viewingEntry, setViewingEntry, handleMarkerClick,
|
||||
perms, journey, stats,
|
||||
|
||||
@@ -20,7 +20,7 @@ export const PAGE_WIDTH = 'mx-auto w-full max-w-[1280px] px-4 sm:px-6'
|
||||
// photo is; without a cover the same dark ground keeps the hero one piece.
|
||||
const HERO_GROUND = 'linear-gradient(135deg, #0b1020 0%, #1e293b 55%, #334155 100%)' // theme-lint-disable: the hero's own ground under white type
|
||||
const HERO_SCRIM = 'linear-gradient(180deg, rgba(0,0,0,0.08) 0%, rgba(0,0,0,0.28) 45%, rgba(0,0,0,0.74) 100%)' // theme-lint-disable: a scrim over a photo
|
||||
const GLASS = 'inline-flex items-center gap-1.5 rounded-full border border-white/20 bg-white/15 px-3 py-1 font-semibold text-white backdrop-blur-md' // theme-lint-disable: glass over a photo
|
||||
export const GLASS = 'inline-flex items-center gap-1.5 rounded-full border border-white/20 bg-white/15 px-3 py-1 font-semibold text-white backdrop-blur-md' // theme-lint-disable: glass over a photo
|
||||
|
||||
interface TopBarProps {
|
||||
title: string
|
||||
@@ -62,10 +62,12 @@ export interface HeroStat {
|
||||
interface HeroProps {
|
||||
trip: { title: string; description?: string | null; cover_image?: string | null; start_date?: string | null; end_date?: string | null }
|
||||
stats: HeroStat[]
|
||||
/** One quiet action beside the stats, such as following a shared journey (#1669). */
|
||||
action?: ReactNode
|
||||
}
|
||||
|
||||
/** The trip as a postcard: its cover, its dates, its name, what the owner wrote about it, and how big it is. */
|
||||
export function SharedHero({ trip, stats }: HeroProps) {
|
||||
export function SharedHero({ trip, stats, action }: HeroProps) {
|
||||
const { locale } = useTranslation()
|
||||
const cover = coverSrc(trip.cover_image)
|
||||
const dates = formatDateRange(trip.start_date, trip.end_date, locale)
|
||||
@@ -84,7 +86,7 @@ export function SharedHero({ trip, stats }: HeroProps) {
|
||||
{trip.description && (
|
||||
<p className="max-w-2xl whitespace-pre-line text-white/80 [overflow-wrap:anywhere]" style={fs(14.5, 'body')}>{trip.description}</p> // theme-lint-disable: white type over a photo
|
||||
)}
|
||||
{stats.length > 0 && (
|
||||
{(stats.length > 0 || action) && (
|
||||
<div className="mt-1 flex flex-wrap gap-2">
|
||||
{stats.map(s => (
|
||||
<span key={s.key} className={GLASS} style={fs(12, 'body')}>
|
||||
@@ -92,6 +94,7 @@ export function SharedHero({ trip, stats }: HeroProps) {
|
||||
<span className="font-medium text-white/80">{s.label}</span>
|
||||
</span>
|
||||
))}
|
||||
{action}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -57,6 +57,18 @@ export const journeySocialRepo = {
|
||||
return journeyPublicCommentsResponseSchema.parse(await journeySocialApi.publicComments(token, signal));
|
||||
},
|
||||
|
||||
async recordPublicView(token: string): Promise<void> {
|
||||
try {
|
||||
await journeySocialApi.recordPublicView(token);
|
||||
} catch {
|
||||
// The owner’s view count is best effort and does not prevent opening the journey.
|
||||
}
|
||||
},
|
||||
|
||||
async unlockPublicJourney(token: string, password: string): Promise<void> {
|
||||
await journeySocialApi.unlockPublicJourney(token, password);
|
||||
},
|
||||
|
||||
async addPublicComment(token: string, entryId: number, body: JourneyPublicCommentCreateRequest): Promise<void> {
|
||||
await journeySocialApi.addPublicComment(token, entryId, body);
|
||||
},
|
||||
|
||||
@@ -2,6 +2,7 @@ import { http, HttpResponse } from 'msw';
|
||||
import { buildTrip, buildDay, buildPlace } from '../../factories';
|
||||
|
||||
export const sharedHandlers = [
|
||||
http.post('/api/public/journey/:token/view', () => HttpResponse.json({ success: true })),
|
||||
http.get('/api/shared/:token', ({ params }) => {
|
||||
const { token } = params;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user