mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 17:26:24 +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:
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user