feat(journey): read and write comments and followers in the client hooks

The data side of journey comments and following a link by email (#1702,
#1669), for the views to draw on, online only like the journey itself:

- api/journeySocial and repo/journeySocialRepo, parsed against the shared
  contracts.
- useJourneyComments: a journey's comments grouped by entry, add, hide and
  delete, read again on journey:entry:commented.
- useJourneySubscribers: the owner's list of followers and their removal.
- useJourneyPublicSocial: the comments a share link shows, a reader's
  comment and follow request, each answering what it came to.
- useJourneyFollow: the confirm and unsubscribe pages a follower's mail
  links open, posting the token once.
- useJourneyShareLink switches allow_comments and allow_subscriptions on
  their own, like the map extras.
This commit is contained in:
Maurice
2026-11-30 15:13:17 +01:00
parent 52552133e3
commit f1e64ef686
15 changed files with 979 additions and 3 deletions
@@ -0,0 +1,126 @@
// FE-JRN-COMMENTS-HOOK-001 to FE-JRN-COMMENTS-HOOK-004
//
// #1702: the comments under a journey's entries as both views read them,
// grouped by entry, written through the repo, and read again whenever
// somebody on the journey changes one.
import type { JourneyComment } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { act, renderHook, waitFor } from '../../../tests/helpers/render';
import { useJourneyComments } from './useJourneyComments';
const repo = vi.hoisted(() => ({
comments: vi.fn(),
addComment: vi.fn(),
setCommentHidden: vi.fn(),
deleteComment: vi.fn(),
}));
vi.mock('../../repo/journeySocialRepo', () => ({ journeySocialRepo: repo }));
const pings = vi.hoisted(() => ({ handlers: new Map<string, () => Promise<void>>() }));
vi.mock('../../sync/useServerPing', () => ({
useServerPing: (event: string, enabled: boolean, reload: () => Promise<void>) => {
if (enabled) pings.handlers.set(event, reload);
},
}));
const comment = (over: Partial<JourneyComment> = {}): JourneyComment => ({
id: 1,
entry_id: 10,
user_id: 3,
author_name: 'ana',
avatar_url: null,
is_guest: false,
body: 'Lovely',
hidden: false,
created_at: '2026-11-30T10:00:00Z',
own: true,
...over,
});
beforeEach(() => {
for (const fn of Object.values(repo)) fn.mockReset();
pings.handlers.clear();
});
describe('useJourneyComments', () => {
it('FE-JRN-COMMENTS-HOOK-001: reads the comments and groups them by entry', async () => {
repo.comments.mockResolvedValue({
comments: [comment(), comment({ id: 2, entry_id: 11 }), comment({ id: 3 })],
can_moderate: true,
});
const { result } = renderHook(() => useJourneyComments(7));
await waitFor(() => expect(result.current.status).toBe('ready'));
expect(repo.comments).toHaveBeenCalledWith(7);
expect(result.current.canModerate).toBe(true);
expect(result.current.byEntry.get(10)?.map((c) => c.id)).toEqual([1, 3]);
expect(result.current.byEntry.get(11)?.map((c) => c.id)).toEqual([2]);
});
it('FE-JRN-COMMENTS-HOOK-002: adds, hides and deletes, each shown once the server took it', async () => {
repo.comments.mockResolvedValue({ comments: [comment()], can_moderate: true });
repo.addComment.mockResolvedValue(comment({ id: 5, body: 'New' }));
repo.setCommentHidden.mockResolvedValue(undefined);
repo.deleteComment.mockResolvedValue(undefined);
const { result } = renderHook(() => useJourneyComments(7));
await waitFor(() => expect(result.current.status).toBe('ready'));
let ok: boolean | undefined;
await act(async () => {
ok = await result.current.add(10, 'New');
});
expect(ok).toBe(true);
expect(repo.addComment).toHaveBeenCalledWith(7, 10, 'New');
expect(result.current.comments.map((c) => c.id)).toEqual([1, 5]);
await act(async () => {
await result.current.setHidden(1, true);
});
expect(result.current.comments[0]?.hidden).toBe(true);
await act(async () => {
await result.current.remove(5);
});
expect(result.current.comments.map((c) => c.id)).toEqual([1]);
// An empty comment is not sent at all.
await act(async () => {
ok = await result.current.add(10, ' ');
});
expect(ok).toBe(false);
expect(repo.addComment).toHaveBeenCalledTimes(1);
});
it('FE-JRN-COMMENTS-HOOK-003: a refused write leaves the thread as it was and resolves false', async () => {
repo.comments.mockResolvedValue({ comments: [comment()], can_moderate: false });
repo.addComment.mockRejectedValue(new Error('offline'));
repo.setCommentHidden.mockRejectedValue(new Error('403'));
repo.deleteComment.mockRejectedValue(new Error('403'));
const { result } = renderHook(() => useJourneyComments(7));
await waitFor(() => expect(result.current.status).toBe('ready'));
const outcomes: boolean[] = [];
await act(async () => {
outcomes.push(await result.current.add(10, 'x'));
outcomes.push(await result.current.setHidden(1, true));
outcomes.push(await result.current.remove(1));
});
expect(outcomes).toEqual([false, false, false]);
expect(result.current.comments).toEqual([comment()]);
});
it('FE-JRN-COMMENTS-HOOK-004: reads again on a ping, keeps what it had when a read fails, and idles without a journey', async () => {
repo.comments.mockRejectedValueOnce(new Error('down'));
const { result } = renderHook(() => useJourneyComments(7));
await waitFor(() => expect(result.current.status).toBe('failed'));
repo.comments.mockResolvedValue({ comments: [comment()], can_moderate: false });
await act(async () => {
await pings.handlers.get('journey:entry:commented')?.();
});
expect(result.current.status).toBe('ready');
expect(result.current.comments).toHaveLength(1);
const idle = renderHook(() => useJourneyComments(null));
expect(idle.result.current.status).toBe('idle');
expect(await idle.result.current.add(1, 'x')).toBe(false);
});
});
@@ -0,0 +1,127 @@
import type { JourneyComment } from '@trek/shared';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { journeySocialRepo } from '../../repo/journeySocialRepo';
import { useServerPing } from '../../sync/useServerPing';
interface Loaded {
journeyId: number | null;
comments: JourneyComment[];
canModerate: boolean;
}
const NOTHING: Loaded = { journeyId: null, comments: [], canModerate: false };
const NO_COMMENTS: JourneyComment[] = [];
interface JourneyCommentsState {
/** Every comment the caller may see, oldest first. */
comments: JourneyComment[];
/** The comments under each entry, oldest first. */
byEntry: ReadonlyMap<number, JourneyComment[]>;
/** The caller may hide and delete every comment (an editor of the journey). */
canModerate: boolean;
status: 'idle' | 'loading' | 'ready' | 'failed';
/** Comments under an entry; resolves whether it was saved. */
add: (entryId: number, body: string) => Promise<boolean>;
/** Hide a comment from everyone but the editors, or show it again. */
setHidden: (commentId: number, hidden: boolean) => Promise<boolean>;
remove: (commentId: number) => Promise<boolean>;
}
/**
* The comments under a journey's entries (#1702), for the desktop page and the
* phone screen alike, which draw their own thread under each entry card. Read
* when the journey opens and again whenever somebody on it adds, hides, shows
* or deletes one (`journey:entry:commented`). Online only, like the journey:
* a failed write leaves the thread as it was and resolves false, so the view
* can say so.
*/
export function useJourneyComments(journeyId: number | null): JourneyCommentsState {
const [loaded, setLoaded] = useState<Loaded>(NOTHING);
const [failedFor, setFailedFor] = useState<number | null>(null);
const current = loaded.journeyId === journeyId ? loaded : null;
const comments = current?.comments ?? NO_COMMENTS;
const status = journeyId === null ? 'idle' : current ? 'ready' : failedFor === journeyId ? 'failed' : 'loading';
const read = useCallback(async (): Promise<Loaded | null> => {
if (journeyId === null) return null;
try {
const answer = await journeySocialRepo.comments(journeyId);
return { journeyId, comments: answer.comments, canModerate: answer.can_moderate };
} catch {
// What was read before stays: a thread does not vanish because one read failed.
return null;
}
}, [journeyId]);
useEffect(() => {
let cancelled = false;
void read().then((next) => {
if (cancelled) return;
if (next) setLoaded(next);
else setFailedFor(journeyId);
});
return () => {
cancelled = true;
};
}, [read, journeyId]);
const reload = useCallback(async () => {
const next = await read();
if (next) setLoaded(next);
}, [read]);
useServerPing('journey:entry:commented', journeyId !== null, reload);
const byEntry = useMemo(() => {
const map = new Map<number, JourneyComment[]>();
for (const comment of comments) map.set(comment.entry_id, [...(map.get(comment.entry_id) ?? []), comment]);
return map;
}, [comments]);
const add = useCallback(
async (entryId: number, body: string) => {
if (journeyId === null || !body.trim()) return false;
try {
const comment = await journeySocialRepo.addComment(journeyId, entryId, body);
setLoaded((prev) => (prev.journeyId === journeyId ? { ...prev, comments: [...prev.comments, comment] } : prev));
return true;
} catch {
return false;
}
},
[journeyId]
);
const setHidden = useCallback(
async (commentId: number, hidden: boolean) => {
if (journeyId === null) return false;
try {
await journeySocialRepo.setCommentHidden(journeyId, commentId, hidden);
setLoaded((prev) => ({
...prev,
comments: prev.comments.map((c) => (c.id === commentId ? { ...c, hidden } : c)),
}));
return true;
} catch {
return false;
}
},
[journeyId]
);
const remove = useCallback(
async (commentId: number) => {
if (journeyId === null) return false;
try {
await journeySocialRepo.deleteComment(journeyId, commentId);
setLoaded((prev) => ({ ...prev, comments: prev.comments.filter((c) => c.id !== commentId) }));
return true;
} catch {
return false;
}
},
[journeyId]
);
return { comments, byEntry, canModerate: current?.canModerate ?? false, status, add, setHidden, remove };
}
@@ -135,6 +135,22 @@ describe('useJourneyShareLink', () => {
expect(posted[1]).toEqual({ share_timeline: true, share_gallery: false, share_map: true, share_recordings: true });
});
it('FE-JRN-SHAREHOOK-009b: comments and following by email are switched on their own and start off (#1702, #1669)', async () => {
const { result } = await loaded();
await act(() => result.current.togglePerm('allow_comments'));
expect(posted).toEqual([{ share_timeline: true, share_gallery: false, share_map: true, allow_comments: true }]);
expect(result.current.link?.allow_comments).toBe(true);
expect(result.current.link?.allow_subscriptions).toBeUndefined();
await act(() => result.current.togglePerm('allow_subscriptions'));
expect(posted[1]).toEqual({
share_timeline: true,
share_gallery: false,
share_map: true,
allow_subscriptions: true,
});
});
it('FE-JRN-SHAREHOOK-010: a password and an expiry are saved on their own and only shown once taken (#2553)', async () => {
const { result } = await loaded();
let saved: boolean | undefined;
@@ -20,6 +20,10 @@ export interface JourneyShareLink {
/** Readers who opened the link, each counted once a day, and when the last one did (ISO, UTC). */
view_count?: number;
last_viewed_at?: string | null;
/** #1702: readers without an account may comment under the shared entries (needs the timeline). */
allow_comments?: boolean;
/** #1669: readers may follow the link by email and get a daily mail about new entries. */
allow_subscriptions?: boolean;
}
/**
@@ -33,7 +37,18 @@ interface JourneyShareProtectionChange {
/** What the shared map can show besides the entries, each only while the map itself is shared. */
export type JourneyShareMapExtra = 'share_plan' | 'share_recordings';
export type JourneySharePermission = 'share_timeline' | 'share_gallery' | 'share_map' | JourneyShareMapExtra;
/** What a reader may do besides reading (#1702, #1669); both off on a new link. */
export type JourneyShareInteraction = 'allow_comments' | 'allow_subscriptions';
export type JourneySharePermission =
'share_timeline' | 'share_gallery' | 'share_map' | JourneyShareMapExtra | JourneyShareInteraction;
/** The switches a save sends only when they are the one switched, so a link read before they existed keeps them off. */
const SENT_ONLY_WHEN_SWITCHED: ReadonlySet<JourneySharePermission> = new Set([
'share_plan',
'share_recordings',
'allow_comments',
'allow_subscriptions',
]);
/** The map extras the share switches offer, with what each puts on the shared map. */
export const SHARE_MAP_EXTRAS: { key: JourneyShareMapExtra; labelKey: string; hintKey: string }[] = [
@@ -107,8 +122,8 @@ export function useJourneyShareLink(journeyId: number) {
share_timeline: updated.share_timeline,
share_gallery: updated.share_gallery,
share_map: updated.share_map,
// The map extras go only when switched: a link read before they existed keeps them off.
...(key === 'share_plan' || key === 'share_recordings' ? { [key]: !!updated[key] } : {}),
// The map extras and the reader switches go only when switched: a link read before they existed keeps them off.
...(SENT_ONLY_WHEN_SWITCHED.has(key) ? { [key]: !!updated[key] } : {}),
});
} catch {
setLink(previous);
@@ -0,0 +1,77 @@
// FE-JRN-SUBSCRIBERS-HOOK-001 to FE-JRN-SUBSCRIBERS-HOOK-003
//
// #1669: the addresses following a journey link, as the owner's share section reads them.
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { act, renderHook, waitFor } from '../../../tests/helpers/render';
import { useJourneySubscribers } from './useJourneySubscribers';
const repo = vi.hoisted(() => ({ subscribers: vi.fn(), removeSubscriber: vi.fn() }));
vi.mock('../../repo/journeySocialRepo', () => ({ journeySocialRepo: repo }));
const LIST = {
count: 1,
pending: 1,
subscribers: [
{
id: 1,
email: 'ana@example.com',
confirmed: true,
created_at: null,
confirmed_at: null,
last_notified_at: null,
},
{ id: 2, email: 'bo@example.com', confirmed: false, created_at: null, confirmed_at: null, last_notified_at: null },
],
};
beforeEach(() => {
repo.subscribers.mockReset();
repo.removeSubscriber.mockReset();
});
describe('useJourneySubscribers', () => {
it('FE-JRN-SUBSCRIBERS-HOOK-001: reads nothing until enabled, then the list', async () => {
repo.subscribers.mockResolvedValue(LIST);
const { result, rerender } = renderHook(({ on }) => useJourneySubscribers(7, on), { initialProps: { on: false } });
expect(result.current.status).toBe('idle');
expect(repo.subscribers).not.toHaveBeenCalled();
rerender({ on: true });
await waitFor(() => expect(result.current.status).toBe('ready'));
expect(result.current.count).toBe(1);
expect(result.current.pending).toBe(1);
expect(result.current.subscribers).toHaveLength(2);
});
it('FE-JRN-SUBSCRIBERS-HOOK-002: a removal takes the address and its count off', async () => {
repo.subscribers.mockResolvedValue(LIST);
repo.removeSubscriber.mockResolvedValue(undefined);
const { result } = renderHook(() => useJourneySubscribers(7, true));
await waitFor(() => expect(result.current.status).toBe('ready'));
await act(async () => {
expect(await result.current.remove(1)).toBe(true);
});
expect(repo.removeSubscriber).toHaveBeenCalledWith(7, 1);
expect(result.current).toMatchObject({ count: 0, pending: 1 });
await act(async () => {
await result.current.remove(2);
});
expect(result.current).toMatchObject({ count: 0, pending: 0, subscribers: [] });
});
it('FE-JRN-SUBSCRIBERS-HOOK-003: a failed read says so, a refused removal keeps the list', async () => {
repo.subscribers.mockRejectedValueOnce(new Error('403'));
const failing = renderHook(() => useJourneySubscribers(7, true));
await waitFor(() => expect(failing.result.current.status).toBe('failed'));
repo.subscribers.mockResolvedValue(LIST);
repo.removeSubscriber.mockRejectedValue(new Error('404'));
const { result } = renderHook(() => useJourneySubscribers(8, true));
await waitFor(() => expect(result.current.status).toBe('ready'));
await act(async () => {
expect(await result.current.remove(1)).toBe(false);
});
expect(result.current.subscribers).toHaveLength(2);
});
});
@@ -0,0 +1,65 @@
import type { JourneyShareSubscribersResponse } from '@trek/shared';
import { useCallback, useEffect, useState } from 'react';
import { journeySocialRepo } from '../../repo/journeySocialRepo';
interface Loaded {
journeyId: number | null;
data: JourneyShareSubscribersResponse;
}
const EMPTY: JourneyShareSubscribersResponse = { count: 0, pending: 0, subscribers: [] };
/**
* The addresses following a journey's share link by email (#1669), for its
* owner's share section on the desktop page and the phone sheet. Read only
* while `enabled` (the owner, with following switched on), and removed one by
* one; a removal the server refuses leaves the list as it was and resolves
* false.
*/
export function useJourneySubscribers(journeyId: number, enabled: boolean) {
const [loaded, setLoaded] = useState<Loaded>({ journeyId: null, data: EMPTY });
const [failed, setFailed] = useState(false);
const data = enabled && loaded.journeyId === journeyId ? loaded.data : EMPTY;
const status = !enabled ? 'idle' : loaded.journeyId === journeyId ? 'ready' : failed ? 'failed' : 'loading';
useEffect(() => {
if (!enabled) return;
const controller = new AbortController();
journeySocialRepo
.subscribers(journeyId, controller.signal)
.then((next) => {
setFailed(false);
setLoaded({ journeyId, data: next });
})
.catch(() => {
if (!controller.signal.aborted) setFailed(true);
});
return () => controller.abort();
}, [journeyId, enabled]);
const remove = useCallback(
async (subscriberId: number): Promise<boolean> => {
try {
await journeySocialRepo.removeSubscriber(journeyId, subscriberId);
setLoaded((prev) => {
const gone = prev.data.subscribers.find((s) => s.id === subscriberId);
const subscribers = prev.data.subscribers.filter((s) => s.id !== subscriberId);
return {
...prev,
data: {
subscribers,
count: prev.data.count - (gone?.confirmed ? 1 : 0),
pending: prev.data.pending - (gone && !gone.confirmed ? 1 : 0),
},
};
});
return true;
} catch {
return false;
}
},
[journeyId]
);
return { ...data, status, remove };
}