Files
TREK/client/src/components/Journey/JourneyEntryComments.tsx
T

338 lines
13 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. */
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;
mobile?: 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,
mobile = false,
}: Props) {
const { t, locale } = useTranslation();
const [expanded, setExpanded] = useState<boolean | null>(null);
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 open = expanded ?? Boolean(defaultOpen || (mobile && comments.length));
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 | undefined) =>
iso ? new Date(iso).toLocaleDateString(locale || undefined, { day: 'numeric', month: 'short' }) : '';
const toggle = (
<button
type="button"
aria-expanded={open}
onClick={(e) => {
e.stopPropagation();
setExpanded(!open);
}}
className={
mobile
? 'flex min-h-11 w-full items-center gap-2 rounded-xl bg-m-sheetop px-3 text-start text-control font-medium text-m-ink'
: '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 && !mobile && 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={
mobile
? 'flex flex-none items-center gap-0.5'
: '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 ${mobile ? 'size-11' : 'size-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 ${mobile ? 'size-11' : 'size-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-w-0 flex-1 resize-none rounded-xl border px-3 py-2 text-body outline-none [field-sizing:content] ${
mobile
? 'min-h-11 border-m-rowbr bg-m-sheetop text-m-ink placeholder:text-m-muted'
: 'min-h-[38px] border-edge bg-surface text-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 flex-none items-center justify-center rounded-full transition-opacity disabled:opacity-40 ${
mobile
? 'size-11 bg-m-act text-m-actfg'
: 'size-[38px] bg-accent text-accent-text hover:bg-accent-hover'
}`}
>
<SendHorizontal size={15} />
</button>
</Tooltip>
</div>
{message && <p className="text-caption text-danger">{message}</p>}
{publicHint && !guest && (
<p className={`text-caption ${mobile ? 'font-normal text-m-muted' : '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,
mobile,
}: {
entryId: number;
thread: MemberThreadState;
defaultOpen?: boolean;
mobile?: 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}
mobile={mobile}
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>;
}
/** 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();
const messages = {
closed: t('journey.comments.closed'),
gone: t('journey.public.notFoundMessage'),
locked: t('journey.comments.locked'),
rate_limited: t('common.tooManyAttempts'),
invalid: t('journey.comments.invalid'),
failed: t('journey.comments.failed'),
};
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 : messages[outcome];
}}
/>
);
}