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