Files
TREK/client/src/components/Journey/JourneyEntryComments.tsx
T
Maurice ede109dce8 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.
2026-11-30 16:56:18 +01:00

313 lines
12 KiB
TypeScript

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]);
}}
/>
);
}