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
+47
View File
@@ -0,0 +1,47 @@
// FE-API-JOURNEY-SOCIAL-001
//
// #1702, #1669: every call pins its method and path and hands back what the server answered.
import { http, HttpResponse } from 'msw';
import { describe, expect, it } from 'vitest';
import { server } from '../../tests/helpers/msw/server';
import { journeySocialApi } from './journeySocial';
describe('journeySocialApi', () => {
it('FE-API-JOURNEY-SOCIAL-001: calls the comment, follower and link routes', async () => {
const seen: string[] = [];
const record =
(body: unknown) =>
({ request }: { request: Request }) => {
seen.push(`${request.method} ${new URL(request.url).pathname}`);
return HttpResponse.json(body);
};
const ok = { success: true };
server.use(
http.get('/api/journeys/7/comments', record({ comments: [], can_moderate: false })),
http.post('/api/journeys/7/entries/2/comments', record({ comment: { id: 1 } })),
http.patch('/api/journeys/7/comments/1', record(ok)),
http.delete('/api/journeys/7/comments/1', record(ok)),
http.get('/api/journeys/7/share-link/subscribers', record({ count: 0, pending: 0, subscribers: [] })),
http.delete('/api/journeys/7/share-link/subscribers/4', record(ok)),
http.get('/api/public/journey/:token/comments', record({ comments: [] })),
http.post('/api/public/journey/:token/entries/2/comments', record(ok)),
http.post('/api/public/journey/:token/subscribe', record(ok)),
http.post('/api/public/journey-subscriptions/confirm', record({ title: 'Azores', link: 'tok' })),
http.post('/api/public/journey-subscriptions/unsubscribe', record(ok))
);
expect(await journeySocialApi.comments(7)).toEqual({ comments: [], can_moderate: false });
expect(await journeySocialApi.addComment(7, 2, 'Hi')).toEqual({ comment: { id: 1 } });
expect(await journeySocialApi.setCommentHidden(7, 1, true)).toEqual(ok);
expect(await journeySocialApi.deleteComment(7, 1)).toEqual(ok);
expect(await journeySocialApi.subscribers(7)).toEqual({ count: 0, pending: 0, subscribers: [] });
expect(await journeySocialApi.removeSubscriber(7, 4)).toEqual(ok);
expect(await journeySocialApi.publicComments('a/b')).toEqual({ comments: [] });
expect(await journeySocialApi.addPublicComment('tok', 2, { name: 'Bo', body: 'Hi' })).toEqual(ok);
expect(await journeySocialApi.subscribe('tok', { email: 'bo@example.com' })).toEqual(ok);
expect(await journeySocialApi.confirmSubscription('c')).toEqual({ title: 'Azores', link: 'tok' });
expect(await journeySocialApi.unsubscribe('u')).toEqual(ok);
expect(seen).toContain('GET /api/public/journey/a%2Fb/comments');
expect(seen).toHaveLength(11);
});
});
+49
View File
@@ -0,0 +1,49 @@
import type {
JourneyCommentCreateResponse,
JourneyCommentsResponse,
JourneyPublicCommentCreateRequest,
JourneyPublicCommentsResponse,
JourneyPublicSubscribeRequest,
JourneyShareSubscribersResponse,
JourneySubscriptionConfirmResponse,
} from '@trek/shared';
import apiClient from './client';
const pub = (token: string) => `/public/journey/${encodeURIComponent(token)}`;
/**
* The social side of a journey (#1702, #1669): its comments for the people on
* it, the followers of its share link for its owner, and what a reader of the
* link may do besides reading (comment, follow by email, confirm and stop
* following from the mail's links).
*/
export const journeySocialApi = {
comments: (journeyId: number, signal?: AbortSignal): Promise<JourneyCommentsResponse> =>
apiClient.get(`/journeys/${journeyId}/comments`, { signal }).then((r) => r.data),
addComment: (journeyId: number, entryId: number, body: string): Promise<JourneyCommentCreateResponse> =>
apiClient.post(`/journeys/${journeyId}/entries/${entryId}/comments`, { body }).then((r) => r.data),
setCommentHidden: (journeyId: number, commentId: number, hidden: boolean): Promise<{ success: true }> =>
apiClient.patch(`/journeys/${journeyId}/comments/${commentId}`, { hidden }).then((r) => r.data),
deleteComment: (journeyId: number, commentId: number): Promise<{ success: true }> =>
apiClient.delete(`/journeys/${journeyId}/comments/${commentId}`).then((r) => r.data),
subscribers: (journeyId: number, signal?: AbortSignal): Promise<JourneyShareSubscribersResponse> =>
apiClient.get(`/journeys/${journeyId}/share-link/subscribers`, { signal }).then((r) => r.data),
removeSubscriber: (journeyId: number, subscriberId: number): Promise<{ success: true }> =>
apiClient.delete(`/journeys/${journeyId}/share-link/subscribers/${subscriberId}`).then((r) => r.data),
publicComments: (token: string, signal?: AbortSignal): Promise<JourneyPublicCommentsResponse> =>
apiClient.get(`${pub(token)}/comments`, { signal }).then((r) => r.data),
addPublicComment: (
token: string,
entryId: number,
body: JourneyPublicCommentCreateRequest
): Promise<{ success: true }> =>
apiClient.post(`${pub(token)}/entries/${entryId}/comments`, body).then((r) => r.data),
subscribe: (token: string, body: JourneyPublicSubscribeRequest): Promise<{ success: true }> =>
apiClient.post(`${pub(token)}/subscribe`, body).then((r) => r.data),
confirmSubscription: (mailToken: string): Promise<JourneySubscriptionConfirmResponse> =>
apiClient.post('/public/journey-subscriptions/confirm', { token: mailToken }).then((r) => r.data),
unsubscribe: (mailToken: string): Promise<{ success: true }> =>
apiClient.post('/public/journey-subscriptions/unsubscribe', { token: mailToken }).then((r) => r.data),
};
@@ -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 };
}
@@ -0,0 +1,44 @@
// FE-JRN-FOLLOW-001 to FE-JRN-FOLLOW-003
//
// #1669: the page a follower's mail link opens posts its token once and says what came of it.
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { renderHook, waitFor } from '../../../tests/helpers/render';
import { followFailureOf, useJourneyFollow } from './useJourneyFollow';
const repo = vi.hoisted(() => ({ confirmSubscription: vi.fn(), unsubscribe: vi.fn() }));
vi.mock('../../repo/journeySocialRepo', () => ({ journeySocialRepo: repo }));
beforeEach(() => {
repo.confirmSubscription.mockReset();
repo.unsubscribe.mockReset();
});
describe('useJourneyFollow', () => {
it('FE-JRN-FOLLOW-001: confirms once and names the journey to open', async () => {
repo.confirmSubscription.mockResolvedValue({ title: 'Azores', link: 'tok' });
const { result } = renderHook(() => useJourneyFollow('confirm', 'c-token'));
expect(result.current).toEqual({ status: 'working' });
await waitFor(() => expect(result.current).toEqual({ status: 'confirmed', title: 'Azores', link: 'tok' }));
expect(repo.confirmSubscription).toHaveBeenCalledTimes(1);
expect(repo.confirmSubscription).toHaveBeenCalledWith('c-token');
});
it('FE-JRN-FOLLOW-002: unsubscribes, and a link without a token is invalid without asking', async () => {
repo.unsubscribe.mockResolvedValue(undefined);
const { result } = renderHook(() => useJourneyFollow('unsubscribe', 'u-token'));
await waitFor(() => expect(result.current).toEqual({ status: 'unsubscribed' }));
const empty = renderHook(() => useJourneyFollow('confirm', null));
expect(empty.result.current).toEqual({ status: 'invalid' });
expect(repo.confirmSubscription).not.toHaveBeenCalled();
});
it('FE-JRN-FOLLOW-003: an unknown token is invalid, anything else a failure', async () => {
repo.confirmSubscription.mockRejectedValue({ response: { status: 404 } });
const { result } = renderHook(() => useJourneyFollow('confirm', 'gone-token'));
await waitFor(() => expect(result.current).toEqual({ status: 'invalid' }));
expect(followFailureOf({ response: { status: 400 } })).toEqual({ status: 'invalid' });
expect(followFailureOf({ response: { status: 500 } })).toEqual({ status: 'failed' });
expect(followFailureOf(new Error('network'))).toEqual({ status: 'failed' });
});
});
@@ -0,0 +1,59 @@
import { useEffect, useState } from 'react';
import { journeySocialRepo } from '../../repo/journeySocialRepo';
/** The two links in a follower's mails (#1669). */
type JourneyFollowAction = 'confirm' | 'unsubscribe';
type JourneyFollowState =
| { status: 'working' }
/** The address follows the journey now; `link` is its share token, to open it. */
| { status: 'confirmed'; title: string; link: string }
| { status: 'unsubscribed' }
/** No token, or one the server does not know (a confirmation link of an address removed since). */
| { status: 'invalid' }
| { status: 'failed' };
const WORKING: JourneyFollowState = { status: 'working' };
/** What the answer of a mail link means for the page. */
export function followFailureOf(err: unknown): JourneyFollowState {
const status = (err as { response?: { status?: number } } | null)?.response?.status;
return status === 404 || status === 400 ? { status: 'invalid' } : { status: 'failed' };
}
/**
* The page a follower's mail link opens (`/journey-follow/confirm?token=` or
* `/journey-follow/unsubscribe?token=`): it posts the token once and says
* what came of it. The page does the write, never the link itself, so a mail
* scanner that fetches the link changes nothing.
*/
export function useJourneyFollow(action: JourneyFollowAction, token: string | null): JourneyFollowState {
const [answered, setAnswered] = useState<{ key: string; state: JourneyFollowState } | null>(null);
const key = `${action}:${token ?? ''}`;
useEffect(() => {
if (!token) return;
let cancelled = false;
const run = async (): Promise<JourneyFollowState> => {
try {
if (action === 'confirm') {
const journey = await journeySocialRepo.confirmSubscription(token);
return { status: 'confirmed', title: journey.title, link: journey.link };
}
await journeySocialRepo.unsubscribe(token);
return { status: 'unsubscribed' };
} catch (err) {
return followFailureOf(err);
}
};
void run().then((state) => {
if (!cancelled) setAnswered({ key: `${action}:${token}`, state });
});
return () => {
cancelled = true;
};
}, [action, token]);
if (!token) return { status: 'invalid' };
return answered?.key === key ? answered.state : WORKING;
}
@@ -89,6 +89,23 @@ export function unlockOutcomeOf(err: unknown): Exclude<PublicUnlockOutcome, 'ok'
return 'failed';
}
/**
* What a reader's comment or follow request came to (#1702, #1669): taken,
* closed by the owner or the instance (403), the link gone or locked again,
* too many tries, a value the contract refused (400), or anything else.
*/
export type PublicSocialOutcome = 'ok' | 'closed' | 'gone' | 'locked' | 'rate_limited' | 'invalid' | 'failed';
export function publicSocialOutcomeOf(err: unknown): Exclude<PublicSocialOutcome, 'ok'> {
const { status } = failureOf(err);
if (status === 403) return 'closed';
if (status === 404 || status === 410) return 'gone';
if (status === 401) return 'locked';
if (status === 429) return 'rate_limited';
if (status === 400) return 'invalid';
return 'failed';
}
export function groupByDate(entries: PublicEntry[]): Map<string, PublicEntry[]> {
const groups = new Map<string, PublicEntry[]>();
for (const e of entries) {
@@ -0,0 +1,83 @@
// FE-JRN-PUBLIC-SOCIAL-001 to FE-JRN-PUBLIC-SOCIAL-004
//
// #1702, #1669: what a reader of a shared journey may do besides reading,
// and what each try came to.
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { act, renderHook, waitFor } from '../../../tests/helpers/render';
import { publicSocialOutcomeOf } from './journeyPublicModel';
import { useJourneyPublicSocial } from './useJourneyPublicSocial';
const repo = vi.hoisted(() => ({ publicComments: vi.fn(), addPublicComment: vi.fn(), subscribe: vi.fn() }));
vi.mock('../../repo/journeySocialRepo', () => ({ journeySocialRepo: repo }));
const COMMENT = { id: 1, entry_id: 10, author_name: 'Bo', is_guest: true, body: 'Hi', created_at: null };
beforeEach(() => {
for (const fn of Object.values(repo)) fn.mockReset();
});
describe('useJourneyPublicSocial', () => {
it('FE-JRN-PUBLIC-SOCIAL-001: reads the comments only while they are open, grouped by entry', async () => {
repo.publicComments.mockResolvedValue({ comments: [COMMENT] });
const closed = renderHook(() => useJourneyPublicSocial('tok', { comments: false, subscribe: false }));
expect(closed.result.current.commentsOpen).toBe(false);
expect(repo.publicComments).not.toHaveBeenCalled();
const { result } = renderHook(() => useJourneyPublicSocial('tok', { comments: true, subscribe: false }));
await waitFor(() => expect(result.current.comments).toHaveLength(1));
expect(result.current.byEntry.get(10)).toEqual([COMMENT]);
expect(result.current.canSubscribe).toBe(false);
});
it('FE-JRN-PUBLIC-SOCIAL-002: a comment is sent, the thread read again, and refusals come back as outcomes', async () => {
repo.publicComments.mockResolvedValue({ comments: [] });
repo.addPublicComment.mockResolvedValue(undefined);
const { result } = renderHook(() => useJourneyPublicSocial('tok', { comments: true, subscribe: false }));
await waitFor(() => expect(repo.publicComments).toHaveBeenCalledTimes(1));
let outcome: string | undefined;
await act(async () => {
outcome = await result.current.addComment(10, 'Bo', 'Hi');
});
expect(outcome).toBe('ok');
expect(repo.addPublicComment).toHaveBeenCalledWith('tok', 10, { name: 'Bo', body: 'Hi' });
expect(repo.publicComments).toHaveBeenCalledTimes(2);
expect(await result.current.addComment(10, ' ', 'Hi')).toBe('invalid');
repo.addPublicComment.mockRejectedValue({ response: { status: 429 } });
await act(async () => {
outcome = await result.current.addComment(10, 'Bo', 'Again');
});
expect(outcome).toBe('rate_limited');
});
it('FE-JRN-PUBLIC-SOCIAL-003: following sends the address with the page language', async () => {
repo.subscribe.mockResolvedValue(undefined);
const { result } = renderHook(() => useJourneyPublicSocial('tok', { comments: false, subscribe: true }));
expect(result.current.canSubscribe).toBe(true);
expect(await result.current.subscribe('bo@example.com', 'de')).toBe('ok');
expect(repo.subscribe).toHaveBeenCalledWith('tok', { email: 'bo@example.com', locale: 'de' });
expect(await result.current.subscribe('', 'de')).toBe('invalid');
repo.subscribe.mockRejectedValue({ response: { status: 403 } });
expect(await result.current.subscribe('bo@example.com', 'de')).toBe('closed');
const off = renderHook(() => useJourneyPublicSocial('tok', undefined));
expect(await off.result.current.subscribe('bo@example.com', 'de')).toBe('closed');
expect(await off.result.current.addComment(10, 'Bo', 'Hi')).toBe('closed');
});
it('FE-JRN-PUBLIC-SOCIAL-004: every refusal has its outcome', () => {
const of = (status?: number) =>
publicSocialOutcomeOf(status === undefined ? new Error('x') : { response: { status } });
expect([of(403), of(404), of(410), of(401), of(429), of(400), of(500), of()]).toEqual([
'closed',
'gone',
'gone',
'locked',
'rate_limited',
'invalid',
'failed',
'failed',
]);
});
});
@@ -0,0 +1,89 @@
import type { JourneyPublicComment } from '@trek/shared';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { journeySocialRepo } from '../../repo/journeySocialRepo';
import { publicSocialOutcomeOf, type PublicSocialOutcome } from './journeyPublicModel';
/** What a reader may do on the shared page, as its payload says (`interaction`). */
interface PublicInteraction {
comments: boolean;
subscribe: boolean;
}
const NO_COMMENTS: JourneyPublicComment[] = [];
/**
* What a reader of a shared journey may do besides reading (#1702, #1669),
* for the public page on every screen size: read the comments under the
* entries and leave one signed with a name, while the owner allows it, and
* leave an address to follow the link by email, while the owner allows it and
* the instance can send mail. Each write resolves what it came to, so the page
* can say "thanks", "try again later" or "this link is closed" without
* reading an error itself. The field the page leaves empty for people
* (`website`) is never sent from here.
*/
export function useJourneyPublicSocial(token: string | undefined, interaction: PublicInteraction | undefined) {
const commentsOpen = !!token && !!interaction?.comments;
const [loaded, setLoaded] = useState<{ token: string | null; comments: JourneyPublicComment[] }>({
token: null,
comments: NO_COMMENTS,
});
const comments = commentsOpen && loaded.token === token ? loaded.comments : NO_COMMENTS;
const read = useCallback(async () => {
if (!token || !commentsOpen) return;
try {
const answer = await journeySocialRepo.publicComments(token);
setLoaded({ token, comments: answer.comments });
} catch {
// The page still reads without comments; the next write reads again.
}
}, [token, commentsOpen]);
useEffect(() => {
void read();
}, [read]);
const byEntry = useMemo(() => {
const map = new Map<number, JourneyPublicComment[]>();
for (const comment of comments) map.set(comment.entry_id, [...(map.get(comment.entry_id) ?? []), comment]);
return map;
}, [comments]);
const addComment = useCallback(
async (entryId: number, name: string, body: string): Promise<PublicSocialOutcome> => {
if (!token || !commentsOpen) return 'closed';
if (!name.trim() || !body.trim()) return 'invalid';
try {
await journeySocialRepo.addPublicComment(token, entryId, { name, body });
await read();
return 'ok';
} catch (err) {
return publicSocialOutcomeOf(err);
}
},
[token, commentsOpen, read]
);
const subscribe = useCallback(
async (email: string, locale: string): Promise<PublicSocialOutcome> => {
if (!token || !interaction?.subscribe) return 'closed';
if (!email.trim()) return 'invalid';
try {
await journeySocialRepo.subscribe(token, { email, locale });
return 'ok';
} catch (err) {
return publicSocialOutcomeOf(err);
}
},
[token, interaction?.subscribe]
);
return {
commentsOpen,
canSubscribe: !!token && !!interaction?.subscribe,
comments,
byEntry,
addComment,
subscribe,
};
}
+87
View File
@@ -0,0 +1,87 @@
import type { JourneyComment } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { journeySocialApi } from '../api/journeySocial';
import { journeySocialRepo } from './journeySocialRepo';
import { OnlineOnlyError } from './onlineOnly';
// FE-REPO-JOURNEY-SOCIAL-001 to FE-REPO-JOURNEY-SOCIAL-004
const network = vi.hoisted(() => ({ offline: false }));
vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: () => network.offline }));
const COMMENT: JourneyComment = {
id: 1,
entry_id: 2,
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,
};
beforeEach(() => {
network.offline = false;
vi.restoreAllMocks();
});
describe('journeySocialRepo', () => {
it('FE-REPO-JOURNEY-SOCIAL-001: the journey comments and followers need a connection', async () => {
network.offline = true;
const comments = vi.spyOn(journeySocialApi, 'comments');
await expect(journeySocialRepo.comments(7)).rejects.toBeInstanceOf(OnlineOnlyError);
await expect(journeySocialRepo.addComment(7, 2, 'x')).rejects.toBeInstanceOf(OnlineOnlyError);
await expect(journeySocialRepo.setCommentHidden(7, 1, true)).rejects.toBeInstanceOf(OnlineOnlyError);
await expect(journeySocialRepo.deleteComment(7, 1)).rejects.toBeInstanceOf(OnlineOnlyError);
await expect(journeySocialRepo.subscribers(7)).rejects.toBeInstanceOf(OnlineOnlyError);
await expect(journeySocialRepo.removeSubscriber(7, 1)).rejects.toBeInstanceOf(OnlineOnlyError);
expect(comments).not.toHaveBeenCalled();
});
it('FE-REPO-JOURNEY-SOCIAL-002: reads and writes the comments, parsed against the contract', async () => {
vi.spyOn(journeySocialApi, 'comments').mockResolvedValue({ comments: [COMMENT], can_moderate: true });
vi.spyOn(journeySocialApi, 'addComment').mockResolvedValue({ comment: COMMENT });
const hide = vi.spyOn(journeySocialApi, 'setCommentHidden').mockResolvedValue({ success: true });
const del = vi.spyOn(journeySocialApi, 'deleteComment').mockResolvedValue({ success: true });
expect(await journeySocialRepo.comments(7)).toEqual({ comments: [COMMENT], can_moderate: true });
expect(await journeySocialRepo.addComment(7, 2, 'Lovely')).toEqual(COMMENT);
await journeySocialRepo.setCommentHidden(7, 1, true);
await journeySocialRepo.deleteComment(7, 1);
expect(hide).toHaveBeenCalledWith(7, 1, true);
expect(del).toHaveBeenCalledWith(7, 1);
vi.spyOn(journeySocialApi, 'comments').mockResolvedValue({ comments: [{ id: 'x' }], can_moderate: true } as never);
await expect(journeySocialRepo.comments(7)).rejects.toThrow();
});
it('FE-REPO-JOURNEY-SOCIAL-003: the owner reads and removes the followers', async () => {
const list = { count: 1, pending: 0, subscribers: [] };
vi.spyOn(journeySocialApi, 'subscribers').mockResolvedValue(list);
const remove = vi.spyOn(journeySocialApi, 'removeSubscriber').mockResolvedValue({ success: true });
expect(await journeySocialRepo.subscribers(7)).toEqual(list);
await journeySocialRepo.removeSubscriber(7, 4);
expect(remove).toHaveBeenCalledWith(7, 4);
});
it('FE-REPO-JOURNEY-SOCIAL-004: the reader of a link comments, follows, confirms and stops following', async () => {
// The shared page keeps no offline copy: these go out and the answer says whether they landed.
network.offline = true;
const publicComment = { id: 1, entry_id: 2, author_name: 'Bo', is_guest: true, body: 'Hi', created_at: null };
vi.spyOn(journeySocialApi, 'publicComments').mockResolvedValue({ comments: [publicComment] });
const add = vi.spyOn(journeySocialApi, 'addPublicComment').mockResolvedValue({ success: true });
const follow = vi.spyOn(journeySocialApi, 'subscribe').mockResolvedValue({ success: true });
vi.spyOn(journeySocialApi, 'confirmSubscription').mockResolvedValue({ title: 'Azores', link: 'tok' });
const stop = vi.spyOn(journeySocialApi, 'unsubscribe').mockResolvedValue({ success: true });
expect(await journeySocialRepo.publicComments('tok')).toEqual({ comments: [publicComment] });
await journeySocialRepo.addPublicComment('tok', 2, { name: 'Bo', body: 'Hi' });
await journeySocialRepo.subscribe('tok', { email: 'bo@example.com', locale: 'de' });
expect(await journeySocialRepo.confirmSubscription('c'.repeat(32))).toEqual({ title: 'Azores', link: 'tok' });
await journeySocialRepo.unsubscribe('u'.repeat(32));
expect(add).toHaveBeenCalledWith('tok', 2, { name: 'Bo', body: 'Hi' });
expect(follow).toHaveBeenCalledWith('tok', { email: 'bo@example.com', locale: 'de' });
expect(stop).toHaveBeenCalledWith('u'.repeat(32));
});
});
+75
View File
@@ -0,0 +1,75 @@
import {
journeyCommentCreateResponseSchema,
journeyCommentsResponseSchema,
journeyPublicCommentsResponseSchema,
journeyShareSubscribersResponseSchema,
journeySubscriptionConfirmResponseSchema,
type JourneyComment,
type JourneyCommentsResponse,
type JourneyPublicCommentCreateRequest,
type JourneyPublicCommentsResponse,
type JourneyPublicSubscribeRequest,
type JourneyShareSubscribersResponse,
type JourneySubscriptionConfirmResponse,
} from '@trek/shared';
import { journeySocialApi } from '../api/journeySocial';
import { requireOnline } from './onlineOnly';
/**
* The social side of a journey (#1702, #1669), online only on purpose like the
* journey itself: comments are a conversation, read when the journey is open
* and written while the server can pass them on, and the share link is a page
* on the network anyway. Answers are parsed against the shared contract.
*/
export const journeySocialRepo = {
async comments(journeyId: number, signal?: AbortSignal): Promise<JourneyCommentsResponse> {
requireOnline();
return journeyCommentsResponseSchema.parse(await journeySocialApi.comments(journeyId, signal));
},
async addComment(journeyId: number, entryId: number, body: string): Promise<JourneyComment> {
requireOnline();
return journeyCommentCreateResponseSchema.parse(await journeySocialApi.addComment(journeyId, entryId, body))
.comment;
},
async setCommentHidden(journeyId: number, commentId: number, hidden: boolean): Promise<void> {
requireOnline();
await journeySocialApi.setCommentHidden(journeyId, commentId, hidden);
},
async deleteComment(journeyId: number, commentId: number): Promise<void> {
requireOnline();
await journeySocialApi.deleteComment(journeyId, commentId);
},
async subscribers(journeyId: number, signal?: AbortSignal): Promise<JourneyShareSubscribersResponse> {
requireOnline();
return journeyShareSubscribersResponseSchema.parse(await journeySocialApi.subscribers(journeyId, signal));
},
async removeSubscriber(journeyId: number, subscriberId: number): Promise<void> {
requireOnline();
await journeySocialApi.removeSubscriber(journeyId, subscriberId);
},
async publicComments(token: string, signal?: AbortSignal): Promise<JourneyPublicCommentsResponse> {
return journeyPublicCommentsResponseSchema.parse(await journeySocialApi.publicComments(token, signal));
},
async addPublicComment(token: string, entryId: number, body: JourneyPublicCommentCreateRequest): Promise<void> {
await journeySocialApi.addPublicComment(token, entryId, body);
},
async subscribe(token: string, body: JourneyPublicSubscribeRequest): Promise<void> {
await journeySocialApi.subscribe(token, body);
},
async confirmSubscription(mailToken: string): Promise<JourneySubscriptionConfirmResponse> {
return journeySubscriptionConfirmResponseSchema.parse(await journeySocialApi.confirmSubscription(mailToken));
},
async unsubscribe(mailToken: string): Promise<void> {
await journeySocialApi.unsubscribe(mailToken);
},
};