fix(journey): keep draft edits and share screens scoped to their source

Preserve typed titles until submit, require a valid photo preview, and clear entry and photo overlays when following another public share link. Keep committed drafts successful if realtime delivery fails.
This commit is contained in:
Maurice
2026-11-30 17:03:05 +01:00
parent 07fdcbcbee
commit 21b8da53cf
11 changed files with 113 additions and 27 deletions
@@ -31,11 +31,15 @@ export default function JourneyFromPhotosDialog({
const { t } = useTranslation();
const labelId = useId();
const state = useJourneyEntriesFromPhotos({ journeyId, onCreated, onClose });
const close = () => {
if (!state.busy) onClose();
};
const allOn = state.clusters.length > 0 && state.selectedCount === state.clusters.length;
return (
<DialogShell
onClose={onClose}
onClose={close}
blocked={state.busy}
labelledBy={labelId}
width="detail"
header={
@@ -47,7 +51,7 @@ export default function JourneyFromPhotosDialog({
}
tint={NEUTRAL_TINT}
labelId={labelId}
onClose={onClose}
onClose={close}
title={t('journey.fromPhotos.title')}
sub={t('journey.fromPhotos.text')}
subWraps
@@ -56,12 +60,14 @@ export default function JourneyFromPhotosDialog({
footer={
<DialogFooter>
{state.clusters.length > 1 && (
<DialogButton onClick={() => state.selectAll(!allOn)}>
<DialogButton disabled={state.busy} onClick={() => state.selectAll(!allOn)}>
{allOn ? t('common.deselectAll') : t('common.selectAll')}
</DialogButton>
)}
<FooterSpacer />
<DialogButton onClick={onClose}>{t('common.cancel')}</DialogButton>
<DialogButton disabled={state.busy} onClick={close}>
{t('common.cancel')}
</DialogButton>
<DialogButton variant="primary" disabled={!state.canSubmit} onClick={state.submit}>
{t('journey.fromPhotos.create', { count: state.selectedCount })}
</DialogButton>
@@ -59,8 +59,9 @@ describe('choosing gallery photo drafts', () => {
expect(screen.getByText('Unavailable')).toBeVisible();
fireEvent.click(screen.getByRole('button', { name: 'common.errorRetry' }));
expect(retry).toHaveBeenCalledOnce();
rerender(<JourneyFromPhotosList coverOf={coverOf} state={draftState()} />);
rerender(<JourneyFromPhotosList coverOf={coverOf} state={draftState({ withoutCaptureTime: 4 })} />);
expect(screen.getByText('journey.fromPhotos.empty')).toBeVisible();
expect(screen.getByText('journey.fromPhotos.withoutTime')).toBeVisible();
});
it('renders a group, can change its selection and title, and explains missing capture data', () => {
@@ -48,7 +48,7 @@ export default function JourneyFromPhotosList({
);
}
if (state.error && state.clusters.length === 0) {
if (state.error) {
return (
<div className="flex flex-col items-center gap-3 py-6 text-center">
<p className="text-body text-content-muted">{state.error}</p>
@@ -63,12 +63,23 @@ export default function JourneyFromPhotosList({
);
}
const skippedPhotos = state.withoutCaptureTime > 0 && (
<p className="px-1 pt-1 text-caption text-content-faint">
{t('journey.fromPhotos.withoutTime', { count: state.withoutCaptureTime })}
</p>
);
if (state.clusters.length === 0) {
return <p className="py-6 text-center text-body text-content-muted">{t('journey.fromPhotos.empty')}</p>;
return (
<div className="py-6 text-center">
<p className="text-body text-content-muted">{t('journey.fromPhotos.empty')}</p>
{skippedPhotos}
</div>
);
}
return (
<div className="flex flex-col gap-2">
<div className="flex flex-col gap-2" aria-busy={state.loading || state.busy}>
{state.clusters.map((cluster) => {
const on = state.isSelected(cluster);
return (
@@ -82,7 +93,8 @@ export default function JourneyFromPhotosList({
type="button"
role="checkbox"
aria-checked={on}
aria-label={state.titleOf(cluster)}
aria-label={state.titleOf(cluster).trim() || cluster.suggestedTitle}
disabled={state.busy}
onClick={() => state.toggle(cluster)}
className={`flex h-6 w-6 flex-none items-center justify-center rounded-full border transition-colors ${
on ? 'border-accent bg-accent text-accent-text' : 'border-edge text-transparent'
@@ -94,8 +106,10 @@ export default function JourneyFromPhotosList({
<div className="min-w-0 flex-1">
<input
value={state.titleOf(cluster)}
placeholder={cluster.suggestedTitle}
onChange={(e) => state.rename(cluster, e.target.value)}
disabled={!on}
disabled={!on || state.busy}
maxLength={255}
aria-label={t('common.title')}
className="-mx-1.5 w-[calc(100%+12px)] truncate rounded-lg bg-transparent px-1.5 py-0.5 text-body font-semibold text-content outline-none hover:bg-surface-secondary focus:bg-surface-secondary disabled:hover:bg-transparent"
/>
@@ -120,11 +134,7 @@ export default function JourneyFromPhotosList({
</div>
);
})}
{state.withoutCaptureTime > 0 && (
<p className="px-1 pt-1 text-caption text-content-faint">
{t('journey.fromPhotos.withoutTime', { count: state.withoutCaptureTime })}
</p>
)}
{skippedPhotos}
</div>
);
}
@@ -82,8 +82,11 @@ describe('useJourneyEntriesFromPhotos', () => {
const { result, onCreated, onClose } = setup();
await waitFor(() => expect(result.current.selectedCount).toBe(2));
act(() => result.current.rename(VENICE, 'San Marco'));
expect(result.current.titleOf(VENICE)).toBe('San Marco');
act(() => result.current.rename(VENICE, ''));
expect(result.current.titleOf(VENICE)).toBe('');
act(() => result.current.rename(VENICE, 'San '));
expect(result.current.titleOf(VENICE)).toBe('San ');
act(() => result.current.rename(VENICE, 'San Marco '));
await act(async () => result.current.submit());
expect(repo.create).toHaveBeenCalledWith(
@@ -157,7 +160,9 @@ describe('useJourneyEntriesFromPhotos', () => {
act(() => result.current.selectAll(true));
expect(result.current.selectedCount).toBe(2);
repo.preview.mockRejectedValueOnce(new Error('offline again'));
act(() => result.current.setMaxGapMinutes(60));
expect(result.current.canSubmit).toBe(false);
await waitFor(() =>
expect(repo.preview).toHaveBeenLastCalledWith(
7,
@@ -165,5 +170,9 @@ describe('useJourneyEntriesFromPhotos', () => {
expect.any(AbortSignal)
)
);
await waitFor(() => expect(result.current.error).toBeTruthy());
expect(result.current.canSubmit).toBe(false);
await act(async () => result.current.submit());
expect(repo.create).not.toHaveBeenCalled();
});
});
@@ -10,7 +10,6 @@ import {
clusterKey,
renameCluster,
requestOf,
titleOf,
toggleCluster,
type FromPhotosChoice,
} from './journeyEntriesFromPhotosModel';
@@ -99,7 +98,8 @@ export function useJourneyEntriesFromPhotos({ journeyId, onCreated, onClose }: J
const [maxGapMinutes, setMaxGapMinutes] = useState<number | undefined>(undefined);
const [busy, setBusy] = useState(false);
const state = usePreview(journeyId, maxGapMinutes, timezone, locale);
const { preview, choice, update, reload } = state;
const { preview, choice, update, reload, loading, failed } = state;
const canUsePreview = !loading && !failed;
const clusters = useMemo<JourneyEntriesFromPhotosCluster[]>(() => preview?.clusters ?? [], [preview]);
const request = useMemo(
() => (choice ? requestOf(clusters, choice, { timezone, lang: locale }) : null),
@@ -107,7 +107,7 @@ export function useJourneyEntriesFromPhotos({ journeyId, onCreated, onClose }: J
);
const submit = useCallback(async () => {
if (!request || busy) return;
if (!request || busy || !canUsePreview) return;
setBusy(true);
try {
const result = await journeyEntriesFromPhotosRepo.create(journeyId, request);
@@ -126,7 +126,7 @@ export function useJourneyEntriesFromPhotos({ journeyId, onCreated, onClose }: J
} finally {
setBusy(false);
}
}, [request, busy, journeyId, toast, t, onCreated, onClose, reload]);
}, [request, busy, canUsePreview, journeyId, toast, t, onCreated, onClose, reload]);
return {
clusters,
@@ -140,14 +140,15 @@ export function useJourneyEntriesFromPhotos({ journeyId, onCreated, onClose }: J
error: state.failed ? t('journey.fromPhotos.previewFailed') : null,
retry: reload,
isSelected: (cluster: JourneyEntriesFromPhotosCluster) => !!choice?.selected.has(clusterKey(cluster)),
titleOf: (cluster: JourneyEntriesFromPhotosCluster) => (choice ? titleOf(choice, cluster) : cluster.suggestedTitle),
titleOf: (cluster: JourneyEntriesFromPhotosCluster) =>
choice?.titles[clusterKey(cluster)] ?? cluster.suggestedTitle,
selectedCount: request?.groups.length ?? 0,
toggle: (cluster: JourneyEntriesFromPhotosCluster) => update((c) => toggleCluster(c, clusterKey(cluster))),
selectAll: (on: boolean) => update((c) => chooseAll(c, clusters, on)),
rename: (cluster: JourneyEntriesFromPhotosCluster, title: string) =>
update((c) => renameCluster(c, clusterKey(cluster), title)),
busy,
canSubmit: !!request && !busy,
canSubmit: !!request && !busy && canUsePreview,
submit: () => void submit(),
};
}
@@ -20,15 +20,18 @@ export default function MJourneyFromPhotosSheet({
}) {
const { t } = useTranslation();
const state = useJourneyEntriesFromPhotos({ journeyId, onCreated, onClose });
const close = () => {
if (!state.busy) onClose();
};
const allOn = state.clusters.length > 0 && state.selectedCount === state.clusters.length;
return (
<MSheet open onClose={onClose} variant="bottom" material="glass" ariaLabel={t('journey.fromPhotos.title')}>
<MSheet open onClose={close} variant="bottom" material="glass" ariaLabel={t('journey.fromPhotos.title')}>
<div className="flex max-h-[86dvh] min-h-0 flex-col">
<FormSheetHeader
icon={Images}
title={t('journey.fromPhotos.title')}
subtitle={t('journey.fromPhotos.text')}
onClose={onClose}
onClose={close}
closeLabel={t('common.close')}
/>
<div className="min-h-0 flex-1 overflow-y-auto px-[14px] pb-3">
@@ -39,6 +42,7 @@ export default function MJourneyFromPhotosSheet({
<button
type="button"
onClick={() => state.selectAll(!allOn)}
disabled={state.busy}
className={`${SHEET_SECONDARY} whitespace-nowrap`}
>
{allOn ? t('common.deselectAll') : t('common.selectAll')}
+24 -1
View File
@@ -10,9 +10,11 @@ import userEvent from '@testing-library/user-event';
// ── Mocks ────────────────────────────────────────────────────────────────────
const publicRoute = vi.hoisted(() => ({ token: 'test-share-token' }));
vi.mock('react-router', async () => {
const actual = await vi.importActual('react-router');
return { ...actual, useParams: () => ({ token: 'test-share-token' }) };
return { ...actual, useParams: () => publicRoute };
});
vi.mock('react-leaflet', () => ({
@@ -150,6 +152,7 @@ beforeEach(() => {
resetAllStores();
vi.clearAllMocks();
mockIsMobile.value = false;
publicRoute.token = 'test-share-token';
});
// ── Tests ────────────────────────────────────────────────────────────────────
@@ -434,6 +437,26 @@ describe('JourneyPublicPage', () => {
});
});
it('closes an open entry when the reader navigates to another shared journey', async () => {
mockIsMobile.value = true;
setupSuccess();
server.use(http.get('/api/public/journey/next-share', () => HttpResponse.json({
...mockJourneyData,
journey: { ...mockJourneyData.journey, title: 'Next journey' },
entries: [],
})));
const { rerender } = render(<JourneyPublicPage />);
fireEvent.click(await screen.findByText('Open Entry'));
expect(await screen.findByText('The most famous crossing in the world.')).toBeInTheDocument();
publicRoute.token = 'next-share';
rerender(<JourneyPublicPage />);
expect(await screen.findByRole('heading', { level: 1, name: 'Next journey' })).toBeInTheDocument();
expect(screen.queryByText('The most famous crossing in the world.')).not.toBeInTheDocument();
});
// FE-PAGE-PUBLICJOURNEY-016
it('FE-PAGE-PUBLICJOURNEY-016: language picker opens and switches language', async () => {
const user = userEvent.setup();
+6
View File
@@ -28,6 +28,7 @@ import MobileMapTimeline from '../components/Journey/MobileMapTimeline';
import PhotoLightbox from '../components/Journey/PhotoLightbox';
import EmptyState from '../components/shared/EmptyState';
import { PAGE_WIDTH, SharedFooter, SharedHero, SharedLoading, SharedTabBar, SharedTopBar } from './sharedTrip/SharedChrome';
import { useParams } from 'react-router';
import { useTranslation } from '../i18n';
import { formatLocationName } from '../utils/formatters';
import { posterlessVideo } from './journeyDetail/JourneyDetailPage.helpers';
@@ -111,6 +112,11 @@ function formatDate(d: string, locale?: string): { weekday: string; month: strin
}
export default function JourneyPublicPage() {
const { token } = useParams();
return <JourneyPublicContent key={token} />;
}
function JourneyPublicContent() {
const { t } = useTranslation();
// Page = wiring container: the share fetch, view state and all timeline/map
// derivations live in the hook; the render helpers below stay next to the JSX.
@@ -61,6 +61,16 @@ function buildHook(over: Record<string, unknown> = {}): Record<string, unknown>
data: { journey: { title: 'Japan 2026' } },
loading: false,
error: false,
access: 'open',
unlock: vi.fn(),
social: {
commentsOpen: false,
canSubscribe: false,
comments: [],
byEntry: new Map(),
addComment: vi.fn(),
subscribe: vi.fn(),
},
isMobile: false,
locale: 'en',
view: 'timeline',
@@ -274,7 +274,12 @@ export class JourneyEntriesFromPhotosService {
});
for (const { entry } of done.written) {
await this.journeys.broadcastJourneyEvent(journeyId, 'journey:entry:created', { entry }, socketId);
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 }) => ({
@@ -387,6 +387,17 @@ describe('JourneyEntriesFromPhotosService.create', () => {
expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled();
});
it('returns a committed draft even if the realtime notification fails', async () => {
const { owner, journey } = await fixture();
const photoId = await galleryPhoto(journey.id, owner.id, '2026-05-14T07:00:00Z');
vi.spyOn(t.get(JourneyDomainService), 'broadcastJourneyEvent').mockRejectedValueOnce(new Error('realtime offline'));
const result = await svc.create(owner.id, journey.id, { groups: [{ photoIds: [photoId] }] });
expect(result.entries).toEqual([expect.objectContaining({ photoCount: 1 })]);
expect(await linksOf(result.entries[0]?.id ?? 0)).toEqual([photoId]);
});
it('JRNPHOTOS-SVC-008: only an editor may create; a viewer and a stranger write nothing', async () => {
const { viewer, outsider, journey, owner } = await fixture();
const a = await galleryPhoto(journey.id, owner.id, '2026-05-14T07:00:00Z');