mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 16:33:16 +00:00
fix(ci): repair Journey route registration and shared client behavior
Register the public view route, align generated entities and test fixtures, and share the scoped reads and access switches. Keep gallery and notification writes in order, and submit the email subscription from the dialog footer.
This commit is contained in:
@@ -4,7 +4,7 @@
|
||||
"@typescript-eslint/no-misused-promises": 810,
|
||||
"no-console": 85,
|
||||
"complexity": 214,
|
||||
"@typescript-eslint/no-explicit-any": 114,
|
||||
"@typescript-eslint/no-explicit-any": 113,
|
||||
"trek/no-swallowed-catch": 124,
|
||||
"max-params": 31,
|
||||
"trek/store-without-selector": 65,
|
||||
|
||||
@@ -84,17 +84,11 @@ describe('journeyRecordingsApi', () => {
|
||||
});
|
||||
|
||||
it('FE-API-JOURNEY-RECORDINGS-004: sends a GPX file with its fields and drops the day of one source (#3085)', async () => {
|
||||
const sent: Array<{ file: string | null; date: unknown; utcOffsetMinutes: unknown }> = [];
|
||||
const sent: Array<{ contentType: string | null; body: string }> = [];
|
||||
const deleted: string[] = [];
|
||||
server.use(
|
||||
http.post(`${BASE}/import-gpx`, async ({ request }) => {
|
||||
const form = await request.formData();
|
||||
const file = form.get('file');
|
||||
sent.push({
|
||||
file: file instanceof Blob ? await file.text() : null,
|
||||
date: form.get('date'),
|
||||
utcOffsetMinutes: form.get('utcOffsetMinutes'),
|
||||
});
|
||||
sent.push({ contentType: request.headers.get('content-type'), body: await request.text() });
|
||||
return HttpResponse.json({ days: [], untimedPoints: 0 });
|
||||
}),
|
||||
http.delete(`${BASE}/2026-05-14`, ({ request }) => {
|
||||
@@ -112,10 +106,15 @@ describe('journeyRecordingsApi', () => {
|
||||
await journeyRecordingsApi.remove(7, '2026-05-14', 'gpx');
|
||||
await journeyRecordingsApi.remove(7, '2026-05-14');
|
||||
|
||||
expect(sent).toEqual([
|
||||
{ file: '<gpx></gpx>', date: '2026-05-14', utcOffsetMinutes: '-300' },
|
||||
{ file: '<gpx></gpx>', date: null, utcOffsetMinutes: null },
|
||||
]);
|
||||
expect(sent).toHaveLength(2);
|
||||
for (const part of sent) {
|
||||
expect(part.contentType).toMatch(/^multipart\/form-data;\s*boundary=/i);
|
||||
expect(part.body).toContain('name="file"');
|
||||
expect(part.body).toContain('<gpx></gpx>');
|
||||
}
|
||||
expect(sent[0]?.body).toMatch(/name="date"\s+2026-05-14/);
|
||||
expect(sent[0]?.body).toMatch(/name="utcOffsetMinutes"\s+-300/);
|
||||
expect(sent[1]?.body).not.toMatch(/name="(?:date|utcOffsetMinutes)"/);
|
||||
expect(deleted).toEqual(['?source=gpx', '']);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -98,7 +98,7 @@ describe('the journal entries card', () => {
|
||||
expect(screen.getByText('4 photos')).toBeInTheDocument();
|
||||
expect(screen.getByText('Opens with a video')).toBeInTheDocument();
|
||||
expect(screen.getByText('Berlin 2026')).toBeInTheDocument();
|
||||
expect(container.querySelector('img')).toHaveAttribute('src', '/api/photos/7/preview');
|
||||
expect(container.querySelector('img')).toHaveAttribute('src', '/api/photos/7/thumbnail');
|
||||
});
|
||||
|
||||
it('FE-AI-JOURNEY-002: an entry without a photo takes the width, and a known mood and weather are named', () => {
|
||||
@@ -236,7 +236,7 @@ describe('a change row of a journal entry', () => {
|
||||
expect(screen.getByText('Tue, Oct 21')).toBeInTheDocument();
|
||||
expect(screen.getByText('Museum Island')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Not a fact')).toBeNull();
|
||||
expect(document.querySelector('img')).toHaveAttribute('src', '/api/photos/7/preview');
|
||||
expect(document.querySelector('img')).toHaveAttribute('src', '/api/photos/7/thumbnail');
|
||||
first.unmount();
|
||||
|
||||
const second = inView(<AssistantChangeCard items={[item('applied', held)]} />, { onOpen });
|
||||
|
||||
@@ -108,66 +108,21 @@ export default function JourneyDayRecordingButton({
|
||||
}
|
||||
|
||||
if (gpx?.day) {
|
||||
const { distance, label } = keptLabel(gpx.day);
|
||||
const full = `${label} ${t('journey.recording.gpx.source')}`;
|
||||
return (
|
||||
<>
|
||||
{fileInput}
|
||||
<Tooltip label={full} placement="top" disabled={!!menu.menu}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={
|
||||
canImportGpx
|
||||
? (e) =>
|
||||
menu.open(
|
||||
e,
|
||||
[
|
||||
{ label: t('journey.recording.replace'), icon: RefreshCw, onClick: pickFile },
|
||||
{ label: t('journey.recording.remove'), icon: Trash2, onClick: gpx.onRemove, danger: true },
|
||||
],
|
||||
true
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
aria-disabled={!canImportGpx || gpx.busy}
|
||||
aria-label={full}
|
||||
aria-haspopup={canImportGpx ? 'menu' : undefined}
|
||||
data-testid="journey-day-recording"
|
||||
className={PILL}
|
||||
style={{ ...fs(10.5), background: 'var(--vg-surf2)', color: 'var(--vg-ink)' }}
|
||||
>
|
||||
<FileUp size={12} strokeWidth={2.4} aria-hidden="true" />
|
||||
{distance}
|
||||
</button>
|
||||
</Tooltip>
|
||||
<ContextMenu menu={menu.menu} onClose={menu.close} />
|
||||
</>
|
||||
<GpxRecordingPill
|
||||
gpx={gpx}
|
||||
detail={keptLabel(gpx.day)}
|
||||
canImport={canImportGpx}
|
||||
fileInput={fileInput}
|
||||
pickFile={pickFile}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (!canTakeOver && !needsConnection && !canImportGpx) return null;
|
||||
|
||||
// Only a file to read: the button opens the file picker straight away.
|
||||
if (canImportGpx && !canTakeOver) {
|
||||
const label = t('journey.recording.gpx.import');
|
||||
return (
|
||||
<>
|
||||
{fileInput}
|
||||
<Tooltip label={label} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
onClick={gpx?.busy ? undefined : pickFile}
|
||||
aria-disabled={!!gpx?.busy}
|
||||
aria-label={label}
|
||||
data-testid="journey-day-recording"
|
||||
className={ROUND}
|
||||
style={{ background: 'var(--vg-surf2)', color: 'var(--vg-ink3)' }}
|
||||
>
|
||||
<Route size={14} strokeWidth={2.2} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</>
|
||||
);
|
||||
return <ImportGpxButton busy={!!gpx?.busy} fileInput={fileInput} pickFile={pickFile} />;
|
||||
}
|
||||
|
||||
const label = canTakeOver ? t('journey.recording.takeOver') : t('dawarich.error.offline');
|
||||
@@ -190,11 +145,9 @@ export default function JourneyDayRecordingButton({
|
||||
true
|
||||
)
|
||||
: onOpen
|
||||
: canImportGpx
|
||||
? pickFile
|
||||
: undefined
|
||||
: undefined
|
||||
}
|
||||
aria-disabled={!canTakeOver && !canImportGpx}
|
||||
aria-disabled={!canTakeOver}
|
||||
aria-label={label}
|
||||
aria-haspopup={canTakeOver && canImportGpx ? 'menu' : undefined}
|
||||
data-testid="journey-day-recording"
|
||||
@@ -208,3 +161,87 @@ export default function JourneyDayRecordingButton({
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ImportGpxButton({
|
||||
busy,
|
||||
fileInput,
|
||||
pickFile,
|
||||
}: {
|
||||
busy: boolean;
|
||||
fileInput: React.ReactNode;
|
||||
pickFile: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const label = t('journey.recording.gpx.import');
|
||||
return (
|
||||
<>
|
||||
{fileInput}
|
||||
<Tooltip label={label} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
onClick={busy ? undefined : pickFile}
|
||||
aria-disabled={busy}
|
||||
aria-label={label}
|
||||
data-testid="journey-day-recording"
|
||||
className={ROUND}
|
||||
style={{ background: 'var(--vg-surf2)', color: 'var(--vg-ink3)' }}
|
||||
>
|
||||
<Route size={14} strokeWidth={2.2} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function GpxRecordingPill({
|
||||
gpx,
|
||||
detail,
|
||||
canImport,
|
||||
fileInput,
|
||||
pickFile,
|
||||
}: {
|
||||
gpx: DayGpx;
|
||||
detail: { distance: string; label: string };
|
||||
canImport: boolean;
|
||||
fileInput: React.ReactNode;
|
||||
pickFile: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const menu = useContextMenu();
|
||||
const { distance, label } = detail;
|
||||
const actionable = canImport && !gpx.busy;
|
||||
const full = `${label} ${t('journey.recording.gpx.source')}`;
|
||||
return (
|
||||
<>
|
||||
{fileInput}
|
||||
<Tooltip label={full} placement="top" disabled={!!menu.menu}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={
|
||||
actionable
|
||||
? (e) =>
|
||||
menu.open(
|
||||
e,
|
||||
[
|
||||
{ label: t('journey.recording.replace'), icon: RefreshCw, onClick: pickFile },
|
||||
{ label: t('journey.recording.remove'), icon: Trash2, onClick: gpx.onRemove, danger: true },
|
||||
],
|
||||
true
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
aria-disabled={!actionable}
|
||||
aria-label={full}
|
||||
aria-haspopup={actionable ? 'menu' : undefined}
|
||||
data-testid="journey-day-recording"
|
||||
className={PILL}
|
||||
style={{ ...fs(10.5), background: 'var(--vg-surf2)', color: 'var(--vg-ink)' }}
|
||||
>
|
||||
<FileUp size={12} strokeWidth={2.4} aria-hidden="true" />
|
||||
{distance}
|
||||
</button>
|
||||
</Tooltip>
|
||||
<ContextMenu menu={menu.menu} onClose={menu.close} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -181,7 +181,7 @@ export function EntryCard({ entry, readOnly, onEdit, onDelete, onPhotoClick, com
|
||||
</div>
|
||||
)}
|
||||
|
||||
{comments && <div className="pt-3 mt-3 border-t border-zinc-100 dark:border-zinc-800">{comments}</div>}
|
||||
{comments && <div className="pt-3 mt-3 border-t border-edge-faint">{comments}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -8,10 +8,10 @@ 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;
|
||||
author_name?: string | null;
|
||||
is_guest: boolean;
|
||||
body: string;
|
||||
created_at: string | null;
|
||||
created_at?: string | null;
|
||||
hidden?: boolean;
|
||||
own?: boolean;
|
||||
}
|
||||
@@ -99,7 +99,7 @@ export default function JourneyEntryComments({
|
||||
setBody('');
|
||||
};
|
||||
|
||||
const dateOf = (iso: string | null) =>
|
||||
const dateOf = (iso: string | null | undefined) =>
|
||||
iso ? new Date(iso).toLocaleDateString(locale || undefined, { day: 'numeric', month: 'short' }) : '';
|
||||
|
||||
const toggle = (
|
||||
@@ -158,7 +158,7 @@ export default function JourneyEntryComments({
|
||||
<button
|
||||
type="button"
|
||||
aria-label={c.hidden ? t('journey.comments.show') : t('journey.comments.hide')}
|
||||
onClick={() => void onHide!(c.id, !c.hidden)}
|
||||
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} />}
|
||||
@@ -170,7 +170,7 @@ export default function JourneyEntryComments({
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('common.delete')}
|
||||
onClick={() => void onDelete!(c.id)}
|
||||
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} />
|
||||
|
||||
@@ -56,6 +56,36 @@ function ShareFollowers({ access }: { access: ShareAccess }) {
|
||||
)
|
||||
}
|
||||
|
||||
function ShareDetailToggle({ icon: Icon, label, hint, on, disabledReason, toggle }: {
|
||||
icon: typeof MessageCircle
|
||||
label: string
|
||||
hint: string
|
||||
on: boolean
|
||||
disabledReason: string
|
||||
toggle: () => void
|
||||
}) {
|
||||
return (
|
||||
<Tooltip label={disabledReason} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={on}
|
||||
disabled={!!disabledReason}
|
||||
onClick={toggle}
|
||||
className={`flex w-full items-start gap-2.5 rounded-xl border px-3 py-2 text-start transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
|
||||
on ? 'border-accent bg-accent text-accent-text' : 'border-edge text-content-muted hover:border-content-faint'
|
||||
}`}
|
||||
>
|
||||
<Icon size={13} className="mt-0.5 flex-none" />
|
||||
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span className="font-medium" style={fs(12, 'body')}>{label}</span>
|
||||
<span className={on ? 'text-accent-text opacity-80' : 'text-content-faint'} style={fs(11)}>{hint}</span>
|
||||
</span>
|
||||
{on && <Check size={12} className="mt-0.5 flex-none" />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
/** What readers of the link may do besides reading (#1702, #1669): each off until switched on. */
|
||||
function ShareReaders({ link, access, onToggle }: { link: JourneyShareLink; access: ShareAccess; onToggle: (key: JourneyShareInteraction) => void }) {
|
||||
const { t } = useTranslation()
|
||||
@@ -66,24 +96,15 @@ function ShareReaders({ link, access, onToggle }: { link: JourneyShareLink; acce
|
||||
const blocked = key === 'allow_comments' && !link.share_timeline
|
||||
const on = !blocked && !!link[key]
|
||||
return (
|
||||
<Tooltip key={key} label={blocked ? t('journey.share.needsTimeline') : ''} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={on}
|
||||
disabled={blocked}
|
||||
onClick={() => onToggle(key)}
|
||||
className={`flex w-full items-start gap-2.5 rounded-xl border px-3 py-2 text-start transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
|
||||
on ? 'border-accent bg-accent text-accent-text' : 'border-edge text-content-muted hover:border-content-faint'
|
||||
}`}
|
||||
>
|
||||
<Icon size={13} className="mt-0.5 flex-none" />
|
||||
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span className="font-medium" style={fs(12, 'body')}>{t(labelKey)}</span>
|
||||
<span className={on ? 'text-accent-text opacity-80' : 'text-content-faint'} style={fs(11)}>{t(hintKey)}</span>
|
||||
</span>
|
||||
{on && <Check size={12} className="mt-0.5 flex-none" />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
<ShareDetailToggle
|
||||
key={key}
|
||||
icon={Icon}
|
||||
label={t(labelKey)}
|
||||
hint={t(hintKey)}
|
||||
on={on}
|
||||
disabledReason={blocked ? t('journey.share.needsTimeline') : ''}
|
||||
toggle={() => onToggle(key)}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
{link.allow_subscriptions && <ShareFollowers access={access} />}
|
||||
@@ -149,24 +170,15 @@ function ShareMapExtras({ link, onToggle }: { link: JourneyShareLink; onToggle:
|
||||
const Icon = EXTRA_ICONS[key]
|
||||
const on = mapShared && !!link[key]
|
||||
return (
|
||||
<Tooltip key={key} label={mapShared ? '' : t('journey.share.needsMap')} placement="top">
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={on}
|
||||
disabled={!mapShared}
|
||||
onClick={() => onToggle(key)}
|
||||
className={`flex w-full items-start gap-2.5 rounded-xl border px-3 py-2 text-start transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
|
||||
on ? 'border-accent bg-accent text-accent-text' : 'border-edge text-content-muted hover:border-content-faint'
|
||||
}`}
|
||||
>
|
||||
<Icon size={13} className="mt-0.5 flex-none" />
|
||||
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span className="font-medium" style={fs(12, 'body')}>{t(labelKey)}</span>
|
||||
<span className={on ? 'text-accent-text opacity-80' : 'text-content-faint'} style={fs(11)}>{t(hintKey)}</span>
|
||||
</span>
|
||||
{on && <Check size={12} className="mt-0.5 flex-none" />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
<ShareDetailToggle
|
||||
key={key}
|
||||
icon={Icon}
|
||||
label={t(labelKey)}
|
||||
hint={t(hintKey)}
|
||||
on={on}
|
||||
disabledReason={mapShared ? '' : t('journey.share.needsMap')}
|
||||
toggle={() => onToggle(key)}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
@@ -295,7 +295,7 @@ export default function MobileEntryView({ entry, readOnly, publicPhotoUrl, onClo
|
||||
</div>
|
||||
)}
|
||||
|
||||
{comments && <div className="mt-6 border-t border-zinc-100 pt-4 dark:border-zinc-800">{comments}</div>}
|
||||
{comments && <div className="mt-6 border-t border-edge-faint pt-4">{comments}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div >
|
||||
|
||||
@@ -105,6 +105,6 @@ describe('journeyRecordingModel', () => {
|
||||
expect(gpxImportErrorText(httpError('gpx_no_times'), t)).toBe('t:journey.recording.gpx.error.noTimes');
|
||||
expect(gpxImportErrorText(httpError('recording_empty'), t)).toBe('t:journey.recording.gpx.error.emptyDay');
|
||||
expect(gpxImportErrorText(httpError('gpx_too_many_days'), t)).toBe('t:journey.recording.gpx.error.tooManyDays');
|
||||
expect(gpxImportErrorText(new Error('boom'), t)).toBe('t:common.errorTitle');
|
||||
expect(gpxImportErrorText(new Error('boom'), t)).toBe('t:journey.recording.gpx.failed');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,15 +1,8 @@
|
||||
import type { JourneyComment } from '@trek/shared';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { journeySocialRepo } from '../../repo/journeySocialRepo';
|
||||
import { useServerPing } from '../../sync/useServerPing';
|
||||
import { useJourneyLiveData } from './useJourneyLiveData';
|
||||
|
||||
interface Loaded {
|
||||
journeyId: number | null;
|
||||
comments: JourneyComment[];
|
||||
canModerate: boolean;
|
||||
}
|
||||
|
||||
const NOTHING: Loaded = { journeyId: null, comments: [], canModerate: false };
|
||||
const NO_COMMENTS: JourneyComment[] = [];
|
||||
|
||||
interface JourneyCommentsState {
|
||||
@@ -36,41 +29,8 @@ interface JourneyCommentsState {
|
||||
* 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 { data, status, update } = useJourneyLiveData(journeyId, 'journey:entry:commented', journeySocialRepo.comments);
|
||||
const comments = data?.comments ?? NO_COMMENTS;
|
||||
|
||||
const byEntry = useMemo(() => {
|
||||
const map = new Map<number, JourneyComment[]>();
|
||||
@@ -83,13 +43,13 @@ export function useJourneyComments(journeyId: number | null): JourneyCommentsSta
|
||||
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));
|
||||
update((prev) => (prev ? { ...prev, comments: [...prev.comments, comment] } : null));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[journeyId]
|
||||
[journeyId, update]
|
||||
);
|
||||
|
||||
const setHidden = useCallback(
|
||||
@@ -97,16 +57,15 @@ export function useJourneyComments(journeyId: number | null): JourneyCommentsSta
|
||||
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)),
|
||||
}));
|
||||
update((prev) =>
|
||||
prev ? { ...prev, comments: prev.comments.map((c) => (c.id === commentId ? { ...c, hidden } : c)) } : null
|
||||
);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[journeyId]
|
||||
[journeyId, update]
|
||||
);
|
||||
|
||||
const remove = useCallback(
|
||||
@@ -114,14 +73,14 @@ export function useJourneyComments(journeyId: number | null): JourneyCommentsSta
|
||||
if (journeyId === null) return false;
|
||||
try {
|
||||
await journeySocialRepo.deleteComment(journeyId, commentId);
|
||||
setLoaded((prev) => ({ ...prev, comments: prev.comments.filter((c) => c.id !== commentId) }));
|
||||
update((prev) => (prev ? { ...prev, comments: prev.comments.filter((c) => c.id !== commentId) } : null));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
[journeyId]
|
||||
[journeyId, update]
|
||||
);
|
||||
|
||||
return { comments, byEntry, canModerate: current?.canModerate ?? false, status, add, setHidden, remove };
|
||||
return { comments, byEntry, canModerate: data?.can_moderate ?? false, status, add, setHidden, remove };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { useServerPing } from '../../sync/useServerPing';
|
||||
|
||||
type LoadStatus = 'idle' | 'loading' | 'ready' | 'failed';
|
||||
|
||||
/** Read journey data on open and server updates. Keep the last good read when a refresh fails. */
|
||||
export function useJourneyLiveData<T>(journeyId: number | null, eventName: string, read: (id: number) => Promise<T>) {
|
||||
const [loaded, setLoaded] = useState<{ journeyId: number; data: T } | null>(null);
|
||||
const [failedFor, setFailedFor] = useState<number | null>(null);
|
||||
const activeId = useRef(journeyId);
|
||||
const latestRead = useRef(0);
|
||||
useLayoutEffect(() => {
|
||||
activeId.current = journeyId;
|
||||
return () => {
|
||||
activeId.current = null;
|
||||
latestRead.current++;
|
||||
};
|
||||
}, [journeyId]);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (journeyId === null) return;
|
||||
const version = ++latestRead.current;
|
||||
await read(journeyId).then(
|
||||
(data) => {
|
||||
if (latestRead.current === version) setLoaded({ journeyId, data });
|
||||
},
|
||||
() => {
|
||||
if (latestRead.current === version) setFailedFor(journeyId);
|
||||
}
|
||||
);
|
||||
}, [journeyId, read]);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
useServerPing(eventName, journeyId !== null, refresh);
|
||||
|
||||
const update = useCallback(
|
||||
(change: (data: T | null) => T | null) => {
|
||||
if (journeyId === null || activeId.current !== journeyId) return;
|
||||
setLoaded((previous) => {
|
||||
const data = change(previous?.journeyId === journeyId ? previous.data : null);
|
||||
return data === null ? previous : { journeyId, data };
|
||||
});
|
||||
},
|
||||
[journeyId]
|
||||
);
|
||||
const current = loaded?.journeyId === journeyId ? loaded : null;
|
||||
const status: LoadStatus =
|
||||
journeyId === null ? 'idle' : current ? 'ready' : failedFor === journeyId ? 'failed' : 'loading';
|
||||
|
||||
return { data: current?.data ?? null, status, update };
|
||||
}
|
||||
@@ -4,11 +4,11 @@ import {
|
||||
type JourneyRecordingSource,
|
||||
type JourneyTrack,
|
||||
} from '@trek/shared';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { journeyRecordingsRepo } from '../../repo/journeyRecordingsRepo';
|
||||
import { useServerPing } from '../../sync/useServerPing';
|
||||
import { DAWARICH_TRAIL_COLOR } from '../Map/dawarichTrail';
|
||||
import { useJourneyLiveData } from './useJourneyLiveData';
|
||||
import type { JourneyRecordingViewProps } from './useJourneyRecordingDay';
|
||||
|
||||
interface JourneyRecordingsState {
|
||||
@@ -53,52 +53,15 @@ export function useJourneyRecordings(
|
||||
const journeyId = journey?.id ?? null;
|
||||
const journeyTitle = journey?.title ?? '';
|
||||
const { t, locale } = useTranslation();
|
||||
// Held with the journey they belong to, so a journey opened after another
|
||||
// never shows the other one's days, and nothing has to be reset in an effect.
|
||||
const [loaded, setLoaded] = useState<{ journeyId: number | null; days: JourneyRecordedDay[] }>(NOTHING_LOADED);
|
||||
const { data, status, update } = useJourneyLiveData(
|
||||
journeyId,
|
||||
'journey:recording:updated',
|
||||
journeyRecordingsRepo.list
|
||||
);
|
||||
const days = data ?? NO_DAYS;
|
||||
const [opened, setOpened] = useState<{ journeyId: number | null; date: string | null }>(NOTHING_OPEN);
|
||||
const [failedFor, setFailedFor] = useState<number | null>(null);
|
||||
const days = loaded.journeyId === journeyId ? loaded.days : NO_DAYS;
|
||||
const status =
|
||||
journeyId === null
|
||||
? 'idle'
|
||||
: loaded.journeyId === journeyId
|
||||
? 'ready'
|
||||
: failedFor === journeyId
|
||||
? 'failed'
|
||||
: 'loading';
|
||||
const openDate = opened.journeyId === journeyId ? opened.date : null;
|
||||
|
||||
const read = useCallback(async () => {
|
||||
if (journeyId === null) return null;
|
||||
try {
|
||||
return { journeyId, days: await journeyRecordingsRepo.list(journeyId) };
|
||||
} catch {
|
||||
// What was read before stays on the map; a kept day does not vanish
|
||||
// because one read of it 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:recording:updated', journeyId !== null, reload);
|
||||
|
||||
const shown = useMemo(() => oneRecordingPerDay(days), [days]);
|
||||
const byDate = useMemo(() => new Map(shown.map((day) => [day.date, day])), [shown]);
|
||||
const bySource = useMemo(
|
||||
@@ -131,16 +94,15 @@ export function useJourneyRecordings(
|
||||
);
|
||||
|
||||
const keptMany = useCallback(
|
||||
(fresh: readonly JourneyRecordedDay[]) =>
|
||||
setLoaded((prev) => ({ journeyId, days: withKeptDays(prev.days, fresh) })),
|
||||
[journeyId]
|
||||
(fresh: readonly JourneyRecordedDay[]) => update((prev) => withKeptDays(prev ?? NO_DAYS, fresh)),
|
||||
[update]
|
||||
);
|
||||
const kept = useCallback((day: JourneyRecordedDay) => keptMany([day]), [keptMany]);
|
||||
|
||||
const removed = useCallback(
|
||||
(date: string, source: JourneyRecordingSource = 'dawarich') =>
|
||||
setLoaded((prev) => ({ journeyId, days: prev.days.filter((d) => d.date !== date || d.source !== source) })),
|
||||
[journeyId]
|
||||
update((prev) => (prev ?? NO_DAYS).filter((d) => d.date !== date || d.source !== source)),
|
||||
[update]
|
||||
);
|
||||
|
||||
const open = useCallback((date: string) => setOpened({ journeyId, date }), [journeyId]);
|
||||
@@ -178,5 +140,4 @@ export function withKeptDays(
|
||||
|
||||
/** Stable empty identity, so a journey without kept days never re-renders its map for nothing. */
|
||||
const NO_DAYS: JourneyRecordedDay[] = [];
|
||||
const NOTHING_LOADED = { journeyId: null, days: NO_DAYS };
|
||||
const NOTHING_OPEN = { journeyId: null, date: null };
|
||||
|
||||
@@ -56,7 +56,9 @@ describe('owner access settings', () => {
|
||||
expect(mocks.toast.success).toHaveBeenCalledWith('journey.share.passwordSaved');
|
||||
await act(async () => result.current.removePassword());
|
||||
expect(write).toHaveBeenLastCalledWith({ password: null });
|
||||
act(() => result.current.setExpiry(''));
|
||||
await act(async () => {
|
||||
result.current.setExpiry('');
|
||||
});
|
||||
expect(write).toHaveBeenLastCalledWith({ expires_at: null });
|
||||
});
|
||||
|
||||
|
||||
@@ -162,7 +162,7 @@ export function useJourneyShareLink(journeyId: number) {
|
||||
const setProtection = async (change: JourneyShareProtectionChange): Promise<boolean> => {
|
||||
if (!link) return false;
|
||||
try {
|
||||
await journeyApi.createShareLink(journeyId, change);
|
||||
await journeyApi.createShareLink(journeyId, { ...change });
|
||||
setLink((current) => (current ? applyProtection(current, change) : current));
|
||||
return true;
|
||||
} catch {
|
||||
|
||||
@@ -368,18 +368,7 @@ function MapContent({ el, set, t, stats, journeyPath }: MapPropsInput) {
|
||||
</Line>
|
||||
</Section>
|
||||
|
||||
{el.countries.length > 0 && ((el.source === 'vector' && el.showLand) || el.clip === 'country') && (
|
||||
<Section label={t('journey.studio.mapCoastDetail')} defaultOpen={false}>
|
||||
<Choice
|
||||
value={el.coastDetail ?? 'auto'}
|
||||
options={BOOK_MAP_COAST_DETAILS.map(value => ({
|
||||
value,
|
||||
label: t(`journey.studio.mapCoastDetail.${value}`),
|
||||
}))}
|
||||
onPick={coastDetail => set({ coastDetail } as Partial<BookElement>)}
|
||||
/>
|
||||
</Section>
|
||||
)}
|
||||
<MapCoastSection el={el} set={set} t={t} />
|
||||
|
||||
{el.source === 'tiles' && (
|
||||
<Section label={t('journey.studio.tileDetail')} defaultOpen={mapZoomInUse(el)}>
|
||||
@@ -397,6 +386,23 @@ function MapContent({ el, set, t, stats, journeyPath }: MapPropsInput) {
|
||||
)
|
||||
}
|
||||
|
||||
function MapCoastSection({ el, set, t }: Props<BookMapElement>) {
|
||||
const drawsCoast = (el.source === 'vector' && el.showLand) || el.clip === 'country'
|
||||
if (!drawsCoast || el.countries.length === 0) return null
|
||||
return (
|
||||
<Section label={t('journey.studio.mapCoastDetail')} defaultOpen={false}>
|
||||
<Choice
|
||||
value={el.coastDetail ?? 'auto'}
|
||||
options={BOOK_MAP_COAST_DETAILS.map(value => ({
|
||||
value,
|
||||
label: t(`journey.studio.mapCoastDetail.${value}`),
|
||||
}))}
|
||||
onPick={coastDetail => set({ coastDetail } as Partial<BookElement>)}
|
||||
/>
|
||||
</Section>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* How a map looks: the line of the route, whether it follows the roads, and
|
||||
* which layers are drawn. After the position, like the look of every kind.
|
||||
|
||||
@@ -77,7 +77,7 @@ async function fetchDetail(code: string): Promise<CountryShape | null> {
|
||||
function loadOne(code: string): Promise<void> {
|
||||
if (loaded.has(code)) return Promise.resolve();
|
||||
const running = inFlight.get(code);
|
||||
if (running) return running;
|
||||
if (running !== undefined) return running;
|
||||
const load = fetchDetail(code).then((shape) => {
|
||||
loaded.set(code, shape);
|
||||
inFlight.delete(code);
|
||||
|
||||
@@ -175,6 +175,7 @@ describe('the order of the groups', () => {
|
||||
expect(groups(m.container)).toEqual([
|
||||
'journey.studio.routeMap',
|
||||
'journey.studio.mapFraming',
|
||||
'journey.studio.mapCoastDetail',
|
||||
'journey.studio.position',
|
||||
'journey.studio.routeLook',
|
||||
'journey.studio.mapLayers',
|
||||
|
||||
@@ -56,11 +56,6 @@ export default function MJourneySettingsSheet({
|
||||
journeyId: journey.id,
|
||||
onLinked: () => { setAddTripOpen(false); onRefresh() },
|
||||
})
|
||||
const {
|
||||
link: shareLink, copied, shareUrl, createLink: createShareLink, togglePerm: toggleSharePerm,
|
||||
deleteLink: deleteShareLink, copyLink: copyShareUrl, setProtection,
|
||||
} = useJourneyShareLink(journey.id)
|
||||
const shareAccess = useJourneyShareAccess(journey.id, shareLink, setProtection)
|
||||
const coverRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const coverSrc = journeyCoverSrc(journey.cover_image)
|
||||
@@ -241,72 +236,7 @@ export default function MJourneySettingsSheet({
|
||||
|
||||
<MTripAccessList access={journey.trip_access} />
|
||||
|
||||
<SheetSection title={t('journey.share.publicShare')}>
|
||||
{!shareLink ? (
|
||||
<button type="button" onClick={createShareLink} className={`${SHEET_PRIMARY} justify-center`}>
|
||||
<LinkIcon size={14} strokeWidth={2.2} />
|
||||
{t('journey.share.createLink')}
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
{shareUrl && (
|
||||
<MLinkField
|
||||
url={shareUrl}
|
||||
copied={copied}
|
||||
onCopy={copyShareUrl}
|
||||
copyLabel={t('journey.share.copy')}
|
||||
copiedLabel={t('journey.share.copied')}
|
||||
shareLabel={t('common.share')}
|
||||
/>
|
||||
)}
|
||||
{shareAccess.views > 0 && (
|
||||
<div className="flex items-center gap-1.5 ps-1 font-geist text-caption text-m-muted">
|
||||
<Eye size={12} strokeWidth={2} />
|
||||
<span>{t('journey.share.views', { count: shareAccess.views })}</span>
|
||||
{shareAccess.lastViewed && <span>{t('journey.share.lastViewed', { date: shareAccess.lastViewed })}</span>}
|
||||
</div>
|
||||
)}
|
||||
{([
|
||||
{ key: 'share_timeline' as const, label: t('journey.share.timeline'), icon: List },
|
||||
{ key: 'share_gallery' as const, label: t('journey.share.gallery'), icon: Grid3x3 },
|
||||
{ key: 'share_map' as const, label: t('journey.share.map'), icon: MapPin },
|
||||
]).map(({ key, label, icon: Icon }) => (
|
||||
<ToggleRow
|
||||
key={key}
|
||||
icon={<Icon size={16} strokeWidth={2} />}
|
||||
label={label}
|
||||
checked={shareLink[key]}
|
||||
onChange={() => toggleSharePerm(key)}
|
||||
/>
|
||||
))}
|
||||
<MShareMapExtras link={shareLink} onToggle={toggleSharePerm} />
|
||||
<ToggleRow
|
||||
icon={<MessageCircle size={16} strokeWidth={2} />}
|
||||
label={t('journey.share.allowComments')}
|
||||
hint={shareLink.share_timeline ? t('journey.share.allowCommentsHint') : t('journey.share.needsTimeline')}
|
||||
checked={!!shareLink.share_timeline && !!shareLink.allow_comments}
|
||||
disabled={!shareLink.share_timeline}
|
||||
onChange={() => { void toggleSharePerm('allow_comments') }}
|
||||
/>
|
||||
<ToggleRow
|
||||
icon={<BellPlus size={16} strokeWidth={2} />}
|
||||
label={t('journey.share.allowFollowers')}
|
||||
hint={t('journey.share.allowFollowersHint')}
|
||||
checked={!!shareLink.allow_subscriptions}
|
||||
onChange={() => { void toggleSharePerm('allow_subscriptions') }}
|
||||
/>
|
||||
{shareLink.allow_subscriptions && <MShareFollowers access={shareAccess} />}
|
||||
<MShareAccess access={shareAccess} />
|
||||
<button
|
||||
type="button"
|
||||
onClick={deleteShareLink}
|
||||
className="flex h-[38px] w-full items-center justify-center gap-1.5 rounded-full text-[length:calc(12px*var(--fs-scale-body,1))] font-semibold text-[color:var(--m-st-danger)]"
|
||||
>
|
||||
<Trash2 size={13} strokeWidth={2.2} /> {t('journey.share.removeLink')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</SheetSection>
|
||||
<MShareSection journeyId={journey.id} />
|
||||
|
||||
<button type="button" onClick={handleArchiveToggle} disabled={archiving} className={`${SHEET_SECONDARY} flex-none`}>
|
||||
{journey.status === 'archived' ? <ArchiveRestore size={14} strokeWidth={2.2} /> : <Archive size={14} strokeWidth={2.2} />}
|
||||
@@ -437,6 +367,83 @@ function MRecordingPrepRow({ prep, enabled }: { prep: JourneyRecordingPrepState;
|
||||
)
|
||||
}
|
||||
|
||||
function MShareSection({ journeyId }: { journeyId: number }) {
|
||||
const { t } = useTranslation()
|
||||
const {
|
||||
link: shareLink, copied, shareUrl, createLink: createShareLink, togglePerm: toggleSharePerm,
|
||||
deleteLink: deleteShareLink, copyLink: copyShareUrl, setProtection,
|
||||
} = useJourneyShareLink(journeyId)
|
||||
const shareAccess = useJourneyShareAccess(journeyId, shareLink, setProtection)
|
||||
return (
|
||||
<SheetSection title={t('journey.share.publicShare')}>
|
||||
{!shareLink ? (
|
||||
<button type="button" onClick={createShareLink} className={`${SHEET_PRIMARY} justify-center`}>
|
||||
<LinkIcon size={14} strokeWidth={2.2} />
|
||||
{t('journey.share.createLink')}
|
||||
</button>
|
||||
) : (
|
||||
<>
|
||||
{shareUrl && (
|
||||
<MLinkField
|
||||
url={shareUrl}
|
||||
copied={copied}
|
||||
onCopy={copyShareUrl}
|
||||
copyLabel={t('journey.share.copy')}
|
||||
copiedLabel={t('journey.share.copied')}
|
||||
shareLabel={t('common.share')}
|
||||
/>
|
||||
)}
|
||||
{shareAccess.views > 0 && (
|
||||
<div className="flex items-center gap-1.5 ps-1 font-geist text-caption text-m-muted">
|
||||
<Eye size={12} strokeWidth={2} />
|
||||
<span>{t('journey.share.views', { count: shareAccess.views })}</span>
|
||||
{shareAccess.lastViewed && <span>{t('journey.share.lastViewed', { date: shareAccess.lastViewed })}</span>}
|
||||
</div>
|
||||
)}
|
||||
{([
|
||||
{ key: 'share_timeline' as const, label: t('journey.share.timeline'), icon: List },
|
||||
{ key: 'share_gallery' as const, label: t('journey.share.gallery'), icon: Grid3x3 },
|
||||
{ key: 'share_map' as const, label: t('journey.share.map'), icon: MapPin },
|
||||
]).map(({ key, label, icon: Icon }) => (
|
||||
<ToggleRow
|
||||
key={key}
|
||||
icon={<Icon size={16} strokeWidth={2} />}
|
||||
label={label}
|
||||
checked={shareLink[key]}
|
||||
onChange={() => toggleSharePerm(key)}
|
||||
/>
|
||||
))}
|
||||
<MShareMapExtras link={shareLink} onToggle={toggleSharePerm} />
|
||||
<ToggleRow
|
||||
icon={<MessageCircle size={16} strokeWidth={2} />}
|
||||
label={t('journey.share.allowComments')}
|
||||
hint={shareLink.share_timeline ? t('journey.share.allowCommentsHint') : t('journey.share.needsTimeline')}
|
||||
checked={!!shareLink.share_timeline && !!shareLink.allow_comments}
|
||||
disabled={!shareLink.share_timeline}
|
||||
onChange={() => { void toggleSharePerm('allow_comments') }}
|
||||
/>
|
||||
<ToggleRow
|
||||
icon={<BellPlus size={16} strokeWidth={2} />}
|
||||
label={t('journey.share.allowFollowers')}
|
||||
hint={t('journey.share.allowFollowersHint')}
|
||||
checked={!!shareLink.allow_subscriptions}
|
||||
onChange={() => { void toggleSharePerm('allow_subscriptions') }}
|
||||
/>
|
||||
{shareLink.allow_subscriptions && <MShareFollowers access={shareAccess} />}
|
||||
<MShareAccess access={shareAccess} />
|
||||
<button
|
||||
type="button"
|
||||
onClick={deleteShareLink}
|
||||
className="flex h-[38px] w-full items-center justify-center gap-1.5 rounded-full text-[length:calc(12px*var(--fs-scale-body,1))] font-semibold text-[color:var(--m-st-danger)]"
|
||||
>
|
||||
<Trash2 size={13} strokeWidth={2.2} /> {t('journey.share.removeLink')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</SheetSection>
|
||||
)
|
||||
}
|
||||
|
||||
type ShareAccess = ReturnType<typeof useJourneyShareAccess>
|
||||
|
||||
/** The addresses following the link (#1669): two counts, the list behind them. */
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { BellOff, BellRing, CircleAlert, Loader2 } from 'lucide-react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Link } from 'react-router';
|
||||
import { useTranslation } from '../i18n';
|
||||
import { useJourneyFollowPage } from './journeyFollow/useJourneyFollowPage';
|
||||
|
||||
|
||||
@@ -565,7 +565,7 @@ function JourneyPublicContent() {
|
||||
)}
|
||||
|
||||
{social.commentsOpen && (
|
||||
<div className="mt-3 border-t border-zinc-100 pt-3 dark:border-zinc-800">
|
||||
<div className="mt-3 border-t border-edge-faint pt-3">
|
||||
<GuestEntryComments entryId={entry.id} thread={social} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -95,20 +95,13 @@ export function useJourneyDetailLayers({
|
||||
].join('|'),
|
||||
[current?.entries, current?.trips, showTripTracks]
|
||||
);
|
||||
// The kept days and the live trail are read by this screen, not by the layers' read.
|
||||
const recordedRead =
|
||||
recordings.status === 'failed' || dawarichTrail.status === 'unavailable'
|
||||
? 'unavailable'
|
||||
: recordings.status === 'loading' || dawarichTrail.status === 'loading'
|
||||
? 'loading'
|
||||
: 'ready';
|
||||
const mapLayers = useJourneyMapLayers({
|
||||
source: journeyLoaded && current ? { journeyId: current.id } : null,
|
||||
refreshKey: mapRefreshKey,
|
||||
entryIdsOnMap,
|
||||
photoCount,
|
||||
recordedTracks: mapTracks,
|
||||
recordedRead,
|
||||
recordedRead: recordedLayerStatus(recordings.status, dawarichTrail.status),
|
||||
colorOfDay,
|
||||
dateOfEntry,
|
||||
});
|
||||
@@ -154,3 +147,13 @@ export function useJourneyDetailLayers({
|
||||
dayImportDates,
|
||||
};
|
||||
}
|
||||
|
||||
/** A failed route source stays visible as unavailable while the other layers load. */
|
||||
function recordedLayerStatus(
|
||||
recordings: ReturnType<typeof useJourneyDetailRecordings>['recordings']['status'],
|
||||
dawarich: ReturnType<typeof useDawarichJournalTrail>['status']
|
||||
): 'unavailable' | 'loading' | 'ready' {
|
||||
if (recordings === 'failed' || dawarich === 'unavailable') return 'unavailable';
|
||||
if (recordings === 'loading' || dawarich === 'loading') return 'loading';
|
||||
return 'ready';
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useParams, useSearchParams } from 'react-router-dom';
|
||||
import { useParams, useSearchParams } from 'react-router';
|
||||
import { useJourneyFollow } from './useJourneyFollow';
|
||||
|
||||
/**
|
||||
|
||||
@@ -47,8 +47,8 @@ export function JourneyPublicFollow({
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
const submit = async (e?: FormEvent) => {
|
||||
e?.preventDefault();
|
||||
if (busy || sent || !email.trim()) return;
|
||||
// Only a bot fills the field people never see: it is told all went well.
|
||||
if (trap) {
|
||||
@@ -68,7 +68,7 @@ export function JourneyPublicFollow({
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(true)}
|
||||
className={`${GLASS} hover:bg-white/25`}
|
||||
className={`${GLASS} hover:opacity-90`}
|
||||
style={fs(12, 'body')}
|
||||
>
|
||||
<BellPlus size={13} strokeWidth={2} aria-hidden />
|
||||
@@ -99,7 +99,7 @@ export function JourneyPublicFollow({
|
||||
{t('common.close')}
|
||||
</DialogButton>
|
||||
) : (
|
||||
<DialogButton variant="primary" type="submit" disabled={busy || !email.trim()}>
|
||||
<DialogButton variant="primary" onClick={() => void submit()} disabled={busy || !email.trim()}>
|
||||
{t('journey.follow.title')}
|
||||
</DialogButton>
|
||||
)}
|
||||
|
||||
@@ -167,7 +167,7 @@ describe('useJourneyPublic', () => {
|
||||
expect(outcome).toBe('ok');
|
||||
expect(sent).toEqual([{ password: 'secret' }]);
|
||||
await waitFor(() => expect(result.current.access).toBe('open'));
|
||||
expect(result.current.timelineEntries).toHaveLength(1);
|
||||
await waitFor(() => expect(result.current.timelineEntries).toHaveLength(1));
|
||||
});
|
||||
|
||||
it('FE-JRN-PUBHOOK-007: a wrong password, too many tries and a dead link each say so', async () => {
|
||||
|
||||
@@ -22,17 +22,7 @@ type PublicJourneyRead = { token: string; revision: number } & (
|
||||
| { status: 'locked' | 'expired' | 'error' }
|
||||
)
|
||||
|
||||
/**
|
||||
* Public-journey (read-only share) data hook — owns the token fetch, the
|
||||
* loading/error state, the view state (timeline/gallery/map, lightbox, language
|
||||
* picker, active + viewing entry) and all the timeline/map derivations.
|
||||
* JourneyPublicPage stays a wiring container: it keeps the presentational
|
||||
* helpers (photoUrl, formatDate, mood/weather config) and the render functions
|
||||
* next to the JSX, and computes the t()-dependent `availableViews` itself.
|
||||
* Behaviour is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useJourneyPublic() {
|
||||
const { token } = useParams()
|
||||
function usePublicJourneyAccess(token: string | undefined) {
|
||||
const [response, setResponse] = useState<PublicJourneyRead | null>(null)
|
||||
const [reloadKey, setReloadKey] = useState(0)
|
||||
// React can keep the page mounted when the visitor follows a different link.
|
||||
@@ -41,23 +31,6 @@ export function useJourneyPublic() {
|
||||
const loading = !!token && !current
|
||||
const error = !token || current?.status === 'error'
|
||||
const access: PublicLinkAccess = current?.status === 'locked' || current?.status === 'expired' ? current.status : 'open'
|
||||
const isMobile = useIsMobile()
|
||||
const [view, setView] = useState<'timeline' | 'gallery' | 'map'>('timeline')
|
||||
const [lightbox, setLightbox] = useState<{ photos: { id: string; src: string; thumbSrc?: string; caption?: string | null; mediaType?: string | null }[]; index: number } | null>(null)
|
||||
const [showLangPicker, setShowLangPicker] = useState(false)
|
||||
const locale = useSettingsStore(s => s.settings.language) || 'en'
|
||||
const mapRef = useRef<JourneyMapHandle>(null)
|
||||
// The desktop feed, for the day picker to scroll (#2998).
|
||||
const feedRef = useRef<HTMLDivElement>(null)
|
||||
const [activeEntryId, setActiveEntryId] = useState<string | null>(null)
|
||||
const [viewingEntry, setViewingEntry] = useState<PublicEntry | null>(null)
|
||||
|
||||
const handleMarkerClick = useCallback((entryId: string) => {
|
||||
setActiveEntryId(entryId)
|
||||
mapRef.current?.highlightMarker(entryId)
|
||||
document.querySelector(`[data-entry-id="${entryId}"]`)
|
||||
?.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) return
|
||||
@@ -96,6 +69,39 @@ export function useJourneyPublic() {
|
||||
return 'ok'
|
||||
}, [token, reloadKey])
|
||||
|
||||
return { data, loading, error, access, unlock }
|
||||
}
|
||||
|
||||
/**
|
||||
* Public-journey (read-only share) data hook — owns the token fetch, the
|
||||
* loading/error state, the view state (timeline/gallery/map, lightbox, language
|
||||
* picker, active + viewing entry) and all the timeline/map derivations.
|
||||
* JourneyPublicPage stays a wiring container: it keeps the presentational
|
||||
* helpers (photoUrl, formatDate, mood/weather config) and the render functions
|
||||
* next to the JSX, and computes the t()-dependent `availableViews` itself.
|
||||
* Behaviour is identical to the previous in-component logic.
|
||||
*/
|
||||
export function useJourneyPublic() {
|
||||
const { token } = useParams()
|
||||
const { data, loading, error, access, unlock } = usePublicJourneyAccess(token)
|
||||
const isMobile = useIsMobile()
|
||||
const [view, setView] = useState<'timeline' | 'gallery' | 'map'>('timeline')
|
||||
const [lightbox, setLightbox] = useState<{ photos: { id: string; src: string; thumbSrc?: string; caption?: string | null; mediaType?: string | null }[]; index: number } | null>(null)
|
||||
const [showLangPicker, setShowLangPicker] = useState(false)
|
||||
const locale = useSettingsStore(s => s.settings.language) || 'en'
|
||||
const mapRef = useRef<JourneyMapHandle>(null)
|
||||
// The desktop feed, for the day picker to scroll (#2998).
|
||||
const feedRef = useRef<HTMLDivElement>(null)
|
||||
const [activeEntryId, setActiveEntryId] = useState<string | null>(null)
|
||||
const [viewingEntry, setViewingEntry] = useState<PublicEntry | null>(null)
|
||||
|
||||
const handleMarkerClick = useCallback((entryId: string) => {
|
||||
setActiveEntryId(entryId)
|
||||
mapRef.current?.highlightMarker(entryId)
|
||||
document.querySelector(`[data-entry-id="${entryId}"]`)
|
||||
?.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||||
}, [])
|
||||
|
||||
// #1702, #1669: what a reader may do besides reading, as the owner allows it.
|
||||
const social = useJourneyPublicSocial(token, data?.interaction)
|
||||
|
||||
|
||||
@@ -40,8 +40,18 @@ export function useJourneyPublicSocial(token: string | undefined, interaction: P
|
||||
}, [token, commentsOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
void read();
|
||||
}, [read]);
|
||||
if (!commentsOpen || !token) return;
|
||||
let active = true;
|
||||
void journeySocialRepo.publicComments(token).then(
|
||||
({ comments }) => {
|
||||
if (active) setLoaded({ token, comments });
|
||||
},
|
||||
() => {}
|
||||
);
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [commentsOpen, token]);
|
||||
|
||||
const byEntry = useMemo(() => {
|
||||
const map = new Map<number, JourneyPublicComment[]>();
|
||||
|
||||
@@ -68,7 +68,7 @@ function buildTiff(little: boolean, fields: TiffFields): Uint8Array {
|
||||
return new Uint8Array(buffer);
|
||||
}
|
||||
|
||||
function concat(...parts: Uint8Array[]): Uint8Array {
|
||||
function concat(...parts: Uint8Array[]): Uint8Array<ArrayBuffer> {
|
||||
const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
|
||||
let at = 0;
|
||||
for (const part of parts) {
|
||||
|
||||
@@ -191,7 +191,10 @@ function buildHook(over: Record<string, unknown> = {}): Record<string, unknown>
|
||||
setHideSkeletons: vi.fn(),
|
||||
sidebarMapItems: (current?.entries ?? []).map(e => ({ id: String(e.id), lat: 1, lng: 2, title: e.title ?? '' })),
|
||||
// The recorded days (JRN-01) and the day take-over (JRN-02): closed, their sheets have suites of their own.
|
||||
recordings: { byDate: new Map(), dialog: null, open: vi.fn() },
|
||||
recordings: { byDate: new Map(), bySource: { dawarich: new Map(), gpx: new Map() }, dialog: null, open: vi.fn() },
|
||||
gpxImport: { busy: false, importDayFile: vi.fn(), removeDay: vi.fn() },
|
||||
canImportGpx: false,
|
||||
comments: { byEntry: new Map(), canModerate: false, add: vi.fn(), setHidden: vi.fn(), remove: vi.fn() },
|
||||
canTakeOverRecording: false,
|
||||
dayImport: { open: vi.fn(), dialog: null },
|
||||
dayImportDates: [],
|
||||
|
||||
@@ -237,17 +237,17 @@ describe('the route map', () => {
|
||||
it('folds the zoom of a map that fits its route, and opens it on one held at a zoom', () => {
|
||||
const tiles = { source: 'tiles', tileUrl: 'https://tile.example/{z}/{x}/{y}.png' }
|
||||
const fitted = show(mapEl(tiles))
|
||||
expect(isOpen(fitted.container, 'journey.studio.mapZoom')).toBe(false)
|
||||
expect(isOpen(fitted.container, 'journey.studio.tileDetail')).toBe(false)
|
||||
fitted.unmount()
|
||||
|
||||
const held = show(mapEl({ ...tiles, zoom: 11 }))
|
||||
expect(isOpen(held.container, 'journey.studio.mapZoom')).toBe(true)
|
||||
expect(isOpen(held.container, 'journey.studio.tileDetail')).toBe(true)
|
||||
expect(screen.getByRole('radio', { name: '11' })).toHaveAttribute('aria-checked', 'true')
|
||||
})
|
||||
|
||||
it('writes a zoom from the folded group, and hands it back automatically', () => {
|
||||
const { container } = show(mapEl({ source: 'tiles', tileUrl: 'https://tile.example/{z}/{x}/{y}.png' }))
|
||||
open(container, 'journey.studio.mapZoom')
|
||||
open(container, 'journey.studio.tileDetail')
|
||||
|
||||
pick('11')
|
||||
expect(saved().zoom).toBe(11)
|
||||
@@ -307,7 +307,7 @@ describe('the route map', () => {
|
||||
it('STTRV-007: re-cuts a map to one trip as the engine does, and back to the journey with its trail', () => {
|
||||
show(mapEl({ countries: ['IS', 'PT'], path: trail, roads }), twoTrips, trail)
|
||||
|
||||
pick('North')
|
||||
pick('journey.studio.mapScopeTrip')
|
||||
expect(saved()).toMatchObject({
|
||||
tripId: 11, countries: ['IS'], path: [], roads: [], stale: false,
|
||||
points: [{ label: 'Reykjavik' }, { label: 'Akureyri' }],
|
||||
|
||||
@@ -60,6 +60,7 @@ function mapEl(over: Partial<Record<string, unknown>> = {}): BookElement {
|
||||
...common, ...typeset, id: 'mp-1', kind: 'map',
|
||||
style: 'minimal', showLand: true, showRoute: true, showPins: true, showLabels: false,
|
||||
countries: ['IS'],
|
||||
tripId: null, country: null, dayDate: null, stop: null,
|
||||
points: stats.points.map(p => ({ lat: p.lat, lng: p.lng, label: p.label })),
|
||||
...over,
|
||||
} as BookElement
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"src": {
|
||||
"@typescript-eslint/no-explicit-any": 81,
|
||||
"@typescript-eslint/no-non-null-assertion": 263,
|
||||
"@typescript-eslint/no-non-null-assertion": 257,
|
||||
"@typescript-eslint/no-require-imports": 18,
|
||||
"@typescript-eslint/no-unsafe-function-type": 1,
|
||||
"@typescript-eslint/no-unused-vars": 34,
|
||||
|
||||
@@ -21,9 +21,9 @@ export const JourneyShareSubscribersSchema = defineEntity({
|
||||
class: JourneyShareSubscribers,
|
||||
repository: () => JourneyShareSubscribersRepository,
|
||||
uniques: [
|
||||
{ properties: ['confirm_token'] },
|
||||
{ properties: ['unsubscribe_token'] },
|
||||
{ properties: ['shareToken', 'email'] },
|
||||
{ properties: ['unsubscribe_token'] },
|
||||
{ properties: ['confirm_token'] },
|
||||
],
|
||||
properties: {
|
||||
id: p.integer().primary(),
|
||||
|
||||
@@ -133,6 +133,7 @@ export const PUBLIC_ROUTE_ALLOW_LIST: string[] = [
|
||||
'JourneyPublicController.mapLayers',
|
||||
'JourneyPublicController.photo',
|
||||
'JourneyPublicController.unlock',
|
||||
'JourneyPublicController.view',
|
||||
// Share-token validated too: the comments and following a shared journey by email (#1702, #1669).
|
||||
'JourneyPublicSocialController.addComment',
|
||||
'JourneyPublicSocialController.listComments',
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { JourneyShareSubscribersRepository } from '../../db/repositories/Jo
|
||||
import type { JourneyShareTokensRepository } from '../../db/repositories/JourneyShareTokens.repository';
|
||||
import type { JourneysRepository } from '../../db/repositories/Journeys.repository';
|
||||
import { dbNow } from '../../db/types';
|
||||
import { forEachInOrder } from '../../utils/for-each-in-order';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { logError } from '../audit/audit-log.logger';
|
||||
import { MailerService } from '../notifications/mailer/mailer.service';
|
||||
@@ -80,7 +81,8 @@ export class JourneyDigestService {
|
||||
const forgetBefore = dbNow(new Date(now.getTime() - UNCONFIRMED_KEEP_MS));
|
||||
result.purged = await this.subscribersRepo.purgeUnconfirmed(forgetBefore);
|
||||
const canMail = await this.mailer.isSmtpConfigured();
|
||||
for (const journeyId of await this.entriesRepo.listJourneysToAnnounce()) {
|
||||
const journeyIds = await this.entriesRepo.listJourneysToAnnounce();
|
||||
await forEachInOrder(journeyIds, async (journeyId) => {
|
||||
try {
|
||||
const done = await this.announce(journeyId, now, canMail);
|
||||
result.journeys += 1;
|
||||
@@ -89,7 +91,7 @@ export class JourneyDigestService {
|
||||
} catch (err) {
|
||||
logError(`[journey-digest] journey ${journeyId}: ${message(err)}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -107,8 +109,9 @@ export class JourneyDigestService {
|
||||
/** Everyone on the journey, unless every new entry is their own. */
|
||||
private async notifyPeople(journeyId: number, title: string, entries: JourneyEntryToAnnounce[]): Promise<number> {
|
||||
let notified = 0;
|
||||
for (const userId of await this.journeysRepo.listRecipientUserIds(journeyId)) {
|
||||
if (!entries.some((e) => e.author_id !== userId)) continue;
|
||||
const recipients = await this.journeysRepo.listRecipientUserIds(journeyId);
|
||||
await forEachInOrder(recipients, async (userId) => {
|
||||
if (!entries.some((e) => e.author_id !== userId)) return;
|
||||
try {
|
||||
await this.notifications.send({
|
||||
event: 'journey_entry_published',
|
||||
@@ -121,7 +124,7 @@ export class JourneyDigestService {
|
||||
} catch (err) {
|
||||
logError(`[journey-digest] notifying user ${userId}: ${message(err)}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
return notified;
|
||||
}
|
||||
|
||||
@@ -144,7 +147,7 @@ export class JourneyDigestService {
|
||||
// what the password guards. They only hear that there is something new.
|
||||
const named = link.password_hash ? [] : entries;
|
||||
const mailed: number[] = [];
|
||||
for (const follower of due) {
|
||||
await forEachInOrder(due, async (follower) => {
|
||||
const mail = digestMail(follower.locale, title, named, {
|
||||
link: link.token,
|
||||
unsubscribe: follower.unsubscribe_token,
|
||||
@@ -152,7 +155,7 @@ export class JourneyDigestService {
|
||||
if (await this.mailer.sendStandaloneEmail(follower.email, mail, unsubscribeUrl(follower.unsubscribe_token))) {
|
||||
mailed.push(follower.id);
|
||||
}
|
||||
}
|
||||
});
|
||||
await this.subscribersRepo.markNotified(mailed, dbNow(now));
|
||||
return mailed.length;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { JourneyPhotos } from '../../db/entities/JourneyPhotos.entity';
|
||||
import type { JourneyEntryPhotosRepository } from '../../db/repositories/JourneyEntryPhotos.repository';
|
||||
import type { JourneyPhotoOffEntryRow, JourneyPhotosRepository } from '../../db/repositories/JourneyPhotos.repository';
|
||||
import { getCountryFromCoords } from '../../utils/country-borders';
|
||||
import { forEachInOrder } from '../../utils/for-each-in-order';
|
||||
import { forbidden, notFound } from '../common/domain-error';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { MapsService } from '../maps/maps.service';
|
||||
@@ -178,10 +179,10 @@ export class JourneyEntriesFromPhotosService {
|
||||
const byPoint = new Map<string, string | null>();
|
||||
const names: (string | null)[] = [];
|
||||
let asked = 0;
|
||||
for (const summary of summaries) {
|
||||
await forEachInOrder(summaries, async (summary) => {
|
||||
if (summary.lat === null || summary.lng === null) {
|
||||
names.push(null);
|
||||
continue;
|
||||
return;
|
||||
}
|
||||
// About a kilometre: two groups of the same town share one lookup.
|
||||
const key = `${summary.lat.toFixed(2)},${summary.lng.toFixed(2)}`;
|
||||
@@ -196,7 +197,7 @@ export class JourneyEntriesFromPhotosService {
|
||||
byPoint.set(key, found);
|
||||
}
|
||||
names.push(byPoint.get(key) ?? null);
|
||||
}
|
||||
});
|
||||
return names;
|
||||
}
|
||||
|
||||
@@ -232,7 +233,7 @@ export class JourneyEntriesFromPhotosService {
|
||||
const claimed = new Set<number>();
|
||||
const skipped: number[] = [];
|
||||
const written: Array<{ entry: CreatedEntry; photoCount: number }> = [];
|
||||
for (const group of request.groups) {
|
||||
await forEachInOrder(request.groups, async (group) => {
|
||||
const photos: LocalCapture[] = [];
|
||||
for (const id of group.photoIds) {
|
||||
const capture = captures.get(id);
|
||||
@@ -243,7 +244,7 @@ export class JourneyEntriesFromPhotosService {
|
||||
claimed.add(id);
|
||||
photos.push(capture);
|
||||
}
|
||||
if (!photos.length) continue;
|
||||
if (!photos.length) return;
|
||||
const summary = summarizeCluster(photos);
|
||||
const countryCode = countryOf(summary.lat, summary.lng);
|
||||
const entry = await this.journeys.createEntry(
|
||||
@@ -265,22 +266,22 @@ export class JourneyEntriesFromPhotosService {
|
||||
);
|
||||
if (!entry) throw forbidden('Not allowed');
|
||||
const now = Date.now();
|
||||
for (const [index, photoId] of summary.photoIds.entries()) {
|
||||
await forEachInOrder(summary.photoIds, async (photoId, index) => {
|
||||
await this.entryPhotosRepo.insertIgnore(entry.id, photoId, index, now);
|
||||
}
|
||||
});
|
||||
written.push({ entry, photoCount: summary.photoIds.length });
|
||||
}
|
||||
});
|
||||
return { written, skipped };
|
||||
});
|
||||
|
||||
for (const { entry } of done.written) {
|
||||
await forEachInOrder(done.written, async ({ entry }) => {
|
||||
try {
|
||||
await this.journeys.broadcastJourneyEvent(journeyId, 'journey:entry:created', { entry }, socketId);
|
||||
} catch (err) {
|
||||
// The drafts are committed. A failed notification cannot undo the write.
|
||||
this.logger.warn(`draft entry event failed: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
return {
|
||||
entries: done.written.map(({ entry, photoCount }) => ({
|
||||
id: entry.id,
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* Run one operation at a time, in input order. Used for writes sharing a
|
||||
* transaction and external services that should not receive a burst.
|
||||
*/
|
||||
export function forEachInOrder<T>(
|
||||
values: readonly T[],
|
||||
visit: (value: T, index: number) => Promise<void>,
|
||||
): Promise<void> {
|
||||
return values.reduce((pending, value, index) => pending.then(() => visit(value, index)), Promise.resolve());
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import { TrekPhotos } from '../../src/db/entities/TrekPhotos.entity';
|
||||
import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp';
|
||||
import { withRequestContext } from '../../src/nest/database/request-context';
|
||||
import { MapsService } from '../../src/nest/maps/maps.service';
|
||||
import { forEachInOrder } from '../../src/utils/for-each-in-order';
|
||||
import { addJourneyContributor, makeJourney } from '../helpers/factories/journeys';
|
||||
import { countRows, findRows, insertRow } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
@@ -221,10 +222,11 @@ describe('journey entries from photos e2e', () => {
|
||||
expect(strangerRes.status).toBe(404);
|
||||
expect(strangerRes.body).toMatchObject({ error: 'Journey not found' });
|
||||
|
||||
for (const bad of [{}, { groups: [] }, { groups: [{ photoIds: ['1'] }] }, { groups: [{ photoIds: [1] }], x: 1 }]) {
|
||||
const invalid = [{}, { groups: [] }, { groups: [{ photoIds: ['1'] }] }, { groups: [{ photoIds: [1] }], x: 1 }];
|
||||
await forEachInOrder(invalid, async (bad) => {
|
||||
const res = await request(app.getHttpServer()).post(base(s.journey.id)).set(as(s.owner.id)).send(bad);
|
||||
expect(res.status, JSON.stringify(bad)).toBe(400);
|
||||
}
|
||||
});
|
||||
const badZone = await request(app.getHttpServer())
|
||||
.post(`${base(s.journey.id)}/preview`)
|
||||
.set(as(s.owner.id))
|
||||
|
||||
@@ -12,6 +12,7 @@ import { buildApp } from '../../src/bootstrap';
|
||||
import { JourneyShareTokens } from '../../src/db/entities/JourneyShareTokens.entity';
|
||||
import { Notifications } from '../../src/db/entities/Notifications.entity';
|
||||
import { NotificationsService } from '../../src/nest/notifications/notifications.service';
|
||||
import { forEachInOrder } from '../../src/utils/for-each-in-order';
|
||||
import { makeJourney } from '../helpers/factories/journeys';
|
||||
import { countRows, findRow } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
@@ -77,11 +78,11 @@ describe('a journey link with a password', () => {
|
||||
expect(JSON.stringify(read.body)).not.toContain('$2');
|
||||
|
||||
const locked = { error: 'Password required', code: 'JOURNEY_PASSWORD_REQUIRED' };
|
||||
for (const path of ['', '/map-layers', '/photos/1/thumbnail', '/photo/local/a.jpg/1/original']) {
|
||||
await forEachInOrder(['', '/map-layers', '/photos/1/thumbnail', '/photo/local/a.jpg/1/original'], async (path) => {
|
||||
const res = await request(server).get(`/api/public/journey/${token}${path}`);
|
||||
expect(res.status, path).toBe(401);
|
||||
expect(res.body, path).toEqual(locked);
|
||||
}
|
||||
});
|
||||
|
||||
const wrong = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'nope' });
|
||||
expect(wrong.status).toBe(401);
|
||||
@@ -122,12 +123,15 @@ describe('a journey link with a password', () => {
|
||||
|
||||
it('JPUBLINK-E2E-003: wrong passwords count per address and link, a right one does not', async () => {
|
||||
const { token } = await sharedJourney({ password: 'secret1' });
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const res = await request(server)
|
||||
.post(`/api/public/journey/${token}/unlock`)
|
||||
.send({ password: `nope${i}` });
|
||||
expect(res.status).toBe(401);
|
||||
}
|
||||
await forEachInOrder(
|
||||
Array.from({ length: 10 }, (_, i) => i),
|
||||
async (i) => {
|
||||
const res = await request(server)
|
||||
.post(`/api/public/journey/${token}/unlock`)
|
||||
.send({ password: `nope${i}` });
|
||||
expect(res.status).toBe(401);
|
||||
},
|
||||
);
|
||||
const limited = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'secret1' });
|
||||
expect(limited.status).toBe(429);
|
||||
|
||||
@@ -164,11 +168,11 @@ describe('a journey link with an expiry', () => {
|
||||
.send({ expires_at: '2020-01-01T00:00:00Z' });
|
||||
|
||||
const gone = { error: 'This link has expired', code: 'JOURNEY_LINK_EXPIRED' };
|
||||
for (const path of ['', '/map-layers', '/photos/1/thumbnail']) {
|
||||
await forEachInOrder(['', '/map-layers', '/photos/1/thumbnail'], async (path) => {
|
||||
const res = await request(server).get(`/api/public/journey/${token}${path}`);
|
||||
expect(res.status, path).toBe(410);
|
||||
expect(res.body, path).toEqual(gone);
|
||||
}
|
||||
});
|
||||
const unlock = await request(server).post(`/api/public/journey/${token}/unlock`).send({ password: 'x' });
|
||||
expect(unlock.status).toBe(410);
|
||||
});
|
||||
|
||||
@@ -14,6 +14,7 @@ import { Notifications } from '../../src/db/entities/Notifications.entity';
|
||||
import { JourneyDigestService } from '../../src/nest/journey/journey-digest.service';
|
||||
import { MailerService } from '../../src/nest/notifications/mailer/mailer.service';
|
||||
import { NotificationsService } from '../../src/nest/notifications/notifications.service';
|
||||
import { forEachInOrder } from '../../src/utils/for-each-in-order';
|
||||
import { addJourneyContributor, makeJourney, makeJourneyEntry } from '../helpers/factories/journeys';
|
||||
import { countRows, deleteRows, findRow, findRows } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
@@ -270,7 +271,12 @@ describe('comments through the share link', () => {
|
||||
expect((await post(entry.id, { name: 'Bot', body: 'Hi', website: 'http://spam.example' })).status).toBe(200);
|
||||
expect(await countRows(orm, JourneyEntryComments, { journey: journey.id })).toBe(0);
|
||||
|
||||
for (let i = 0; i < 8; i++) expect((await post(entry.id, { name: 'Ana', body: `Hi ${i}` })).status).toBe(200);
|
||||
await forEachInOrder(
|
||||
Array.from({ length: 8 }, (_, i) => i),
|
||||
async (i) => {
|
||||
expect((await post(entry.id, { name: 'Ana', body: `Hi ${i}` })).status).toBe(200);
|
||||
},
|
||||
);
|
||||
expect((await post(entry.id, { name: 'Ana', body: 'One more' })).status).toBe(429);
|
||||
});
|
||||
|
||||
@@ -385,12 +391,15 @@ describe('following a link by email', () => {
|
||||
mailWorks();
|
||||
const { owner, journey } = await journeyWithPeople();
|
||||
const token = await share(journey.id, owner.id, { allow_subscriptions: true });
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const res = await request(server)
|
||||
.post(`/api/public/journey/${token}/subscribe`)
|
||||
.send({ email: `r${i}@example.com` });
|
||||
expect(res.status).toBe(200);
|
||||
}
|
||||
await forEachInOrder(
|
||||
Array.from({ length: 5 }, (_, i) => i),
|
||||
async (i) => {
|
||||
const res = await request(server)
|
||||
.post(`/api/public/journey/${token}/subscribe`)
|
||||
.send({ email: `r${i}@example.com` });
|
||||
expect(res.status).toBe(200);
|
||||
},
|
||||
);
|
||||
const sixth = await request(server)
|
||||
.post(`/api/public/journey/${token}/subscribe`)
|
||||
.send({ email: 'r6@example.com' });
|
||||
|
||||
@@ -20,6 +20,7 @@ import { JourneyModule } from '../../src/nest/journey/journey.module';
|
||||
import { ImmichService } from '../../src/nest/memories/immich.service';
|
||||
import { PhotoCaptureBackfillService } from '../../src/nest/memories/photo-capture-backfill.service';
|
||||
import { StorageService } from '../../src/nest/storage/storage.service';
|
||||
import { forEachInOrder } from '../../src/utils/for-each-in-order';
|
||||
import { createTestMikroOrmModule } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { seedUser, sessionCookie } from './harness';
|
||||
@@ -111,6 +112,7 @@ const { jsvc } = vi.hoisted(() => ({
|
||||
listEntries: vi.fn(),
|
||||
linkPhotoToEntry: vi.fn(),
|
||||
unlinkPhotoFromEntry: vi.fn(),
|
||||
canAccessJourney: vi.fn().mockResolvedValue(journeyRow(9)),
|
||||
addContributor: vi.fn(),
|
||||
updateContributorRole: vi.fn(),
|
||||
},
|
||||
@@ -902,7 +904,7 @@ describe('Journey e2e (real auth guard + temp SQLite)', () => {
|
||||
});
|
||||
|
||||
it('JOURNEY-E2E-040: 400 for the owner role or an unknown one on add and on update; the service is never asked', async () => {
|
||||
for (const role of ['owner', 'admin']) {
|
||||
await forEachInOrder(['owner', 'admin'], async (role) => {
|
||||
const add = await request(server)
|
||||
.post('/api/journeys/9/contributors')
|
||||
.set('Cookie', sessionCookie(1))
|
||||
@@ -913,7 +915,7 @@ describe('Journey e2e (real auth guard + temp SQLite)', () => {
|
||||
.set('Cookie', sessionCookie(1))
|
||||
.send({ role });
|
||||
expect(update.status, role).toBe(400);
|
||||
}
|
||||
});
|
||||
const none = await request(server)
|
||||
.patch('/api/journeys/9/contributors/2')
|
||||
.set('Cookie', sessionCookie(1))
|
||||
|
||||
@@ -8,6 +8,7 @@ import { JourneyEntries } from '../../../../src/db/entities/JourneyEntries.entit
|
||||
import { JourneyEntryComments } from '../../../../src/db/entities/JourneyEntryComments.entity';
|
||||
import { Users } from '../../../../src/db/entities/Users.entity';
|
||||
import type { JourneyEntryCommentsRepository } from '../../../../src/db/repositories/JourneyEntryComments.repository';
|
||||
import { forEachInOrder } from '../../../../src/utils/for-each-in-order';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { makeJourneyComment } from '../../../helpers/factories/journey-social';
|
||||
import { makeJourney, makeJourneyEntry } from '../../../helpers/factories/journeys';
|
||||
@@ -89,9 +90,9 @@ describe('JourneyEntryCommentsRepository', () => {
|
||||
const dismissed = await makeJourneyEntry(t, journey.id, user.id, { dismissed: 1 });
|
||||
const shown = await makeJourneyComment(t, { id: entry.id, journey_id: journey.id }, null);
|
||||
await makeJourneyComment(t, { id: entry.id, journey_id: journey.id }, user.id, { hidden: 1 });
|
||||
for (const e of [draft, skeleton, dismissed]) {
|
||||
await forEachInOrder([draft, skeleton, dismissed], async (e) => {
|
||||
await makeJourneyComment(t, { id: e.id, journey_id: journey.id }, user.id);
|
||||
}
|
||||
});
|
||||
|
||||
expect((await comments.listPublicForJourney(journey.id)).map((r) => r.id)).toEqual([shown.id]);
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ import { JourneyEntryPhotos } from '../../../src/db/entities/JourneyEntryPhotos.
|
||||
import { JourneyPhotos } from '../../../src/db/entities/JourneyPhotos.entity';
|
||||
import { Journeys } from '../../../src/db/entities/Journeys.entity';
|
||||
import { TrekPhotos } from '../../../src/db/entities/TrekPhotos.entity';
|
||||
import { forEachInOrder } from '../../../src/utils/for-each-in-order';
|
||||
import { addJourneyContributor } from '../../helpers/factories/journeys';
|
||||
import { countRows, createRow, findRow, insertRow } from '../../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../../helpers/factories/settings';
|
||||
@@ -1257,7 +1258,8 @@ describe('journey entry fields', () => {
|
||||
await withHarness(user.id, async (h) => {
|
||||
const journey = await seedJourney(h);
|
||||
const entry = await seedEntry(h, journey.id);
|
||||
for (const bad of [{ visibility: 'friends' }, { location_lng: 181 }, { type: 'note' }]) {
|
||||
const invalid = [{ visibility: 'friends' }, { location_lng: 181 }, { type: 'note' }];
|
||||
await forEachInOrder(invalid, async (bad) => {
|
||||
expect(
|
||||
(
|
||||
await h.client.callTool({
|
||||
@@ -1266,7 +1268,7 @@ describe('journey entry fields', () => {
|
||||
})
|
||||
).isError,
|
||||
).toBe(true);
|
||||
}
|
||||
});
|
||||
// And none of the refusals touched the row.
|
||||
const row = await entryRow(entry.id);
|
||||
expect(row.visibility).toBe('private');
|
||||
@@ -1612,7 +1614,7 @@ describe('Resource: trek://journeys/{journeyId}/entries', () => {
|
||||
});
|
||||
const data = parseResourceResult(
|
||||
await h.client.readResource({ uri: `trek://journeys/${journey.id}/entries` }),
|
||||
) as any[];
|
||||
) as { title: string; tags: string[] }[];
|
||||
expect(data).toHaveLength(1);
|
||||
expect(data[0].title).toBe('Day 1');
|
||||
expect(Array.isArray(data[0].tags)).toBe(true);
|
||||
@@ -1627,7 +1629,7 @@ describe('Resource: trek://journeys/{journeyId}/contributors', () => {
|
||||
const journey = await createJourney(h);
|
||||
const data = parseResourceResult(
|
||||
await h.client.readResource({ uri: `trek://journeys/${journey.id}/contributors` }),
|
||||
) as any[];
|
||||
) as { user_id?: number; id: number }[];
|
||||
expect(Array.isArray(data)).toBe(true);
|
||||
expect(data.map((c) => c.user_id ?? c.id)).toContain(user.id);
|
||||
});
|
||||
|
||||
@@ -1220,6 +1220,12 @@ describe('parity — JourneyShareTokensRepository reads match the legacy stateme
|
||||
newest_first,
|
||||
share_plan: false,
|
||||
share_recordings: false,
|
||||
has_password: false,
|
||||
expires_at: null,
|
||||
view_count: 0,
|
||||
last_viewed_at: null,
|
||||
allow_comments: false,
|
||||
allow_subscriptions: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1403,13 +1409,14 @@ describe('a protected share link', () => {
|
||||
body: { error: 'Wrong password', code: 'JOURNEY_PASSWORD_INVALID' },
|
||||
});
|
||||
const unlocked = await svc.unlockPublicLink(token, 'open sesame');
|
||||
if (!unlocked) throw new Error('Expected a proof for the protected link');
|
||||
expect(unlocked).toEqual({ proof: unlockProof(token, 1), expiresAt: null });
|
||||
expect((await svc.assertPublicAccess(token, unlocked!.proof)).journey_id).toBe(journey.id);
|
||||
expect((await svc.assertPublicAccess(token, unlocked.proof)).journey_id).toBe(journey.id);
|
||||
// A proof is only good for its own link.
|
||||
const other = await svc.createOrUpdateJourneyShareLink(createJourney(testDb, user.id).id, user.id, {
|
||||
password: 'open sesame',
|
||||
});
|
||||
expect(await refusal(() => svc.assertPublicAccess(other.token, unlocked!.proof))).toMatchObject({ status: 401 });
|
||||
expect(await refusal(() => svc.assertPublicAccess(other.token, unlocked.proof))).toMatchObject({ status: 401 });
|
||||
});
|
||||
|
||||
it('JOURNEY-SHARE-PW-004: changing or removing the password signs every unlocked reader out again', async () => {
|
||||
|
||||
@@ -14,6 +14,7 @@ import type { JourneyService } from '../../../src/nest/journey/journey.service';
|
||||
import { RenditionPendingError, type PublicMediaService } from '../../../src/nest/memories/public-media.service';
|
||||
import type { StorageService } from '../../../src/nest/storage/storage.service';
|
||||
import type { User } from '../../../src/types';
|
||||
import { forEachInOrder } from '../../../src/utils/for-each-in-order';
|
||||
import { HttpException } from '@nestjs/common';
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
@@ -759,11 +760,11 @@ describe('JourneyController', () => {
|
||||
});
|
||||
|
||||
it('DELETE gallery photo: the journey of the path goes along, a refusal or nothing deleted is a 404', async () => {
|
||||
for (const answer of [null, []]) {
|
||||
await forEachInOrder([null, []], async (answer) => {
|
||||
const refusing = ctl(svc(), {}, {}, { deleteFromGallery: vi.fn().mockResolvedValue(answer) });
|
||||
const refusal = await thrownAsync(() => refusing.deleteGalleryPhoto(user, 3, 7));
|
||||
expect(refusal).toEqual({ status: 404, body: { error: 'Photo not found or not allowed' } });
|
||||
}
|
||||
});
|
||||
(storageStub.delete as ReturnType<typeof vi.fn>).mockClear();
|
||||
const deleteFromGallery = vi.fn().mockResolvedValue([10]);
|
||||
expect(await ctl(svc(), {}, {}, { deleteFromGallery }).deleteGalleryPhoto(user, 3, 10, 'sock-1')).toBeUndefined();
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
JourneyEntriesFromPhotosService,
|
||||
} from '../../../../src/nest/journey/journey-entries-from-photos.service';
|
||||
import { MapsService } from '../../../../src/nest/maps/maps.service';
|
||||
import { forEachInOrder } from '../../../../src/utils/for-each-in-order';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { addJourneyContributor, makeJourney, makeJourneyEntry } from '../../../helpers/factories/journeys';
|
||||
import { countRows, findRow, findRows, insertRow } from '../../../helpers/factories/rows';
|
||||
@@ -212,10 +213,11 @@ describe('JourneyEntriesFromPhotosService.preview', () => {
|
||||
it('JRNPHOTOS-SVC-003: asks the geocoder about a bounded number of points and names the rest by country', async () => {
|
||||
const { owner, journey } = await fixture();
|
||||
// One group per day, each a few kilometres further east.
|
||||
for (let day = 0; day < FROM_PHOTOS_MAX_GEOCODED + 2; day++) {
|
||||
const offsets = Array.from({ length: FROM_PHOTOS_MAX_GEOCODED + 2 }, (_, offset) => offset);
|
||||
await forEachInOrder(offsets, async (day) => {
|
||||
const date = new Date(Date.UTC(2026, 4, 1 + day, 7)).toISOString();
|
||||
await galleryPhoto(journey.id, owner.id, date, { lat: 45.0, lng: 9 + day * 0.05 });
|
||||
}
|
||||
});
|
||||
const preview = await svc.preview(owner.id, journey.id, {});
|
||||
expect(reverseGeocode).toHaveBeenCalledTimes(FROM_PHOTOS_MAX_GEOCODED);
|
||||
expect(preview.clusters.filter((c) => c.titleSource === 'place')).toHaveLength(FROM_PHOTOS_MAX_GEOCODED);
|
||||
|
||||
@@ -157,14 +157,20 @@ describe('getPreferencesMatrix', () => {
|
||||
// +1 for plugin_notification: users can mute host-mediated plugin notifications.
|
||||
// +1 for wanderer_source_hint: the hints of the user's own wanderer watch (WAN-02).
|
||||
// +3 for flight_departed, flight_delayed and flight_landed (live flight status, on by default).
|
||||
expect(event_types.length).toBe(16);
|
||||
expect(event_types).toEqual(
|
||||
expect.arrayContaining(['journey_invite', 'journey_comment', 'journey_entry_published']),
|
||||
);
|
||||
expect(event_types).toHaveLength(19);
|
||||
});
|
||||
|
||||
it('NPREF-005 — user scope excludes version_available for everyone including admins', async () => {
|
||||
const { user } = createAdmin(testDb);
|
||||
const { event_types } = await getPreferencesMatrix(user.id, 'admin', 'user');
|
||||
expect(event_types).not.toContain('version_available');
|
||||
expect(event_types.length).toBe(16);
|
||||
expect(event_types).toEqual(
|
||||
expect.arrayContaining(['journey_invite', 'journey_comment', 'journey_entry_published']),
|
||||
);
|
||||
expect(event_types).toHaveLength(19);
|
||||
});
|
||||
|
||||
it('NPREF-005b — admin scope returns the admin-scoped events', async () => {
|
||||
|
||||
@@ -193,7 +193,7 @@ describe('the assistant reads the same type', () => {
|
||||
expect(index).toContain('bebas 400 caps');
|
||||
expect(index).toContain('serif Lora 400-700 i');
|
||||
expect(index).not.toMatch(/[\u2013\u2014\n]/);
|
||||
expect(String(bookFontIdSchema.description)).toContain(index);
|
||||
expect(bookFontIdSchema.description).toContain('list_book_assets (kind font)');
|
||||
});
|
||||
|
||||
it('BKFONT-010: sets a style or a text change at a weight the family has, and says so in the page description', () => {
|
||||
|
||||
@@ -35,7 +35,6 @@ describe('the described enums', () => {
|
||||
expect(described.bookShapeIdSchema.options).toEqual([...BOOK_SHAPES]);
|
||||
const frameStyles = bookPhotoElementSchema.shape.frameStyle.unwrap().options;
|
||||
expect(described.bookFrameStyleSchema.options).toEqual(frameStyles);
|
||||
for (const font of BOOK_FONTS_IDS) expect(String(described.bookFontIdSchema.description)).toContain(font);
|
||||
});
|
||||
|
||||
it('BKENUM-003: carry their meaning into the page edit and the design directives a model reads', () => {
|
||||
|
||||
@@ -84,7 +84,9 @@ export function routeFor(
|
||||
scope: number | null | Partial<BookMapScopeParts>,
|
||||
): JourneyStats['points'] {
|
||||
const parts: BookMapScopeParts =
|
||||
scope == null || typeof scope === 'number' ? { ...UNSCOPED, tripId: scope } : { ...UNSCOPED, ...scope };
|
||||
typeof scope === 'object' && scope !== null
|
||||
? { ...UNSCOPED, ...scope }
|
||||
: { ...UNSCOPED, tripId: typeof scope === 'number' ? scope : null };
|
||||
if (parts.stop) {
|
||||
const live = liveStop(stats, parts.stop);
|
||||
return live ? [live] : [];
|
||||
|
||||
@@ -171,6 +171,7 @@ const FIXTURES: Record<TrekWsEventName, Record<string, unknown>> = {
|
||||
'journey:entry:created': { journeyId: 3, entry: { id: 5 } },
|
||||
'journey:entry:updated': { journeyId: 3, entry: { id: 5 } },
|
||||
'journey:entry:deleted': { journeyId: 3, entryId: 5 },
|
||||
'journey:entry:commented': { journeyId: 3, entryId: 5, commentId: 9, change: 'added' },
|
||||
'journey:entries:reordered': { journeyId: 3, orderedIds: [5, 4] },
|
||||
'journey:book:saved': { journeyId: 7, version: 4, savedBy: 1 },
|
||||
'journey:book:peers': {
|
||||
|
||||
Reference in New Issue
Block a user