release: v0.19.0

Release v0.19.0. See the `## [0.19.0] — 2026-09-29` section of
[CHANGELOG.md](https://github.com/ralksta/immich-folio/blob/dev/CHANGELOG.md)
for the full list.

Highlights: client proofing links (#683), custom content pages (#738),
asset picker search (#740), concurrent-edit detection (#742), env-locked
settings (#739), an accessibility baseline (#741), three security fixes
with advisories (#737, #755, #759), and a pre-release quality pass
(#780–#797).

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: ralksta <ralksta@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Ralf <rohlenbo79@gmail.com>
Co-authored-by: Paul Thies <110185070+ImScheinox@users.noreply.github.com>
Co-authored-by: lancetm714 <108419425+lancetm714@users.noreply.github.com>
Co-authored-by: Lance Martin <lancetaylor95@gmail.com>
This commit is contained in:
Ralksta
2026-09-29 22:50:30 +02:00
committed by GitHub
parent 5f251923f0
commit ad8b09700b
297 changed files with 19398 additions and 1800 deletions

View File

@@ -11,14 +11,16 @@ import { albumMetaDetail } from '@/lib/albumMeta';
import { AlbumNav } from '@/components/AlbumNav';
import { StructuredData } from '@/components/StructuredData';
import type { AlbumNavPair } from '@/lib/albumNav';
import type { ProofSessionInit } from '@/components/ProofingContext';
interface AlbumDetailViewProps {
album: ImmichAlbum;
images: PhotoItem[];
layout: GridConfig['layout'];
gridStyle: React.CSSProperties;
backLinkHref: string;
backLinkLabel: string;
/** Omitted on a client proofing link, which has nowhere to go back to. */
backLinkHref?: string;
backLinkLabel?: string;
subtitle?: string;
heroImageUrl?: string;
heroBlurDataURL?: string;
@@ -31,6 +33,12 @@ interface AlbumDetailViewProps {
proofing?: boolean;
/** Offer the "send by email" button in the proofing modal. */
allowMailto?: boolean;
/**
* `encodeEmail()` of where the proofing dialog's "email to photographer"
* goes, when one is configured (#736). Encoded, like every address the site
* renders, so the plain form stays out of the HTML and the RSC payload.
*/
encodedMailto?: string;
/**
* The ZIP endpoint for this album, when it offers downloads (#475). Renders a
* "download album" link in the header and lets the proofing modal offer a
@@ -41,6 +49,10 @@ interface AlbumDetailViewProps {
nav?: AlbumNavPair;
/** JSON-LD for this album, or null when no site URL is configured (#472). */
structuredData?: Record<string, unknown> | null;
/** A client proofing link's session; see PhotoGrid. */
proofSession?: ProofSessionInit;
/** Rendered under the title — the proofing link's greeting and notes. */
intro?: React.ReactNode;
}
export function AlbumDetailView({
@@ -58,9 +70,12 @@ export function AlbumDetailView({
showGear = true,
proofing,
allowMailto,
encodedMailto,
downloadArchiveUrl,
nav,
structuredData,
proofSession,
intro,
}: AlbumDetailViewProps) {
const metaDetail = albumMetaDetail(album, showGear);
const t = getServerDictionary();
@@ -86,7 +101,7 @@ export function AlbumDetailView({
)}
<div className={`album-header${heroImageUrl ? ' album-header--has-hero' : ''}`}>
<div className="album-header__main">
<BackLink href={backLinkHref} label={backLinkLabel} />
{backLinkHref && <BackLink href={backLinkHref} label={backLinkLabel ?? ''} />}
<h1 className="album-header__title">{album.albumName}</h1>
{subtitle && (
<p className="subpage-subtitle" style={{ textAlign: 'left', marginLeft: 0 }}>
@@ -94,6 +109,7 @@ export function AlbumDetailView({
</p>
)}
{album.description && <p className="album-header__description">{album.description}</p>}
{intro}
{downloadArchiveUrl && (
<a className="album-header__download" href={downloadArchiveUrl}>
<svg
@@ -127,8 +143,10 @@ export function AlbumDetailView({
showExifPanel={showExifPanel}
proofing={proofing}
allowMailto={allowMailto}
encodedMailto={encodedMailto}
downloadArchiveUrl={downloadArchiveUrl}
albumName={album.albumName}
proofSession={proofSession}
/>
{nav && <AlbumNav {...nav} />}
</>

View File

@@ -2,17 +2,32 @@
import { useState, useMemo } from 'react';
import Image from 'next/image';
import dynamic from 'next/dynamic';
import { Lightbox, type LightboxWatermark } from '@/components/Lightbox';
import { ProofingProvider, useProofing } from '@/components/ProofingContext';
import { ProofingModal } from '@/components/ProofingModal';
import { useProofing } from '@/components/useProofing';
import { ProofingProvider, ProofingModal } from '@/components/ProofingLazy';
import { FadeIn } from '@/components/FadeIn';
import { LeafletMap, escapeHtml } from '@/components/LeafletMap';
import { escapeHtml } from '@/lib/escapeHtml';
import type { ParsedEssay, EssayBlock } from '@/lib/essay';
import { renderInlineMarkdown } from '@/lib/essay';
import { essayPhotoSequence } from '@/lib/essaySequence';
import type { PhotoItem } from './PhotoGrid';
import './essay.css';
import { useDictionary } from '@/components/I18nProvider';
import { formatJournalDate } from '@/lib/journalDate';
/**
* The map block is the only thing in an essay that needs Leaflet, and most
* essays have none. Imported statically, LeafletMap put its wrapper and
* Leaflet's stylesheet (render-blocking CSS) on every album, subpage and
* journal page. The map only ever drew on the client — Leaflet itself was
* already imported inside an effect — so the server renders the same empty
* container it rendered before, and the wrapper arrives with the map.
*/
const LeafletMap = dynamic(() => import('@/components/LeafletMap').then((m) => m.LeafletMap), {
ssr: false,
loading: () => <div className="essay-map" />,
});
interface EssayViewProps {
essay: ParsedEssay;
@@ -28,6 +43,8 @@ interface EssayViewProps {
proofing?: boolean;
/** Offer the "send by email" button in the proofing modal. */
allowMailto?: boolean;
/** `encodeEmail()` of the proofing recipient, when one is configured (#736). */
encodedMailto?: string;
}
function EssayViewContent({
@@ -389,6 +406,9 @@ function EssayViewContent({
}
};
// The story's photos that are selected, not the whole stored set (see PhotoGrid).
const selectedCount = proofing ? proofing.getSelectedTokens().length : 0;
return (
<div className="essay-container">
<header className="essay-header">
@@ -396,7 +416,9 @@ function EssayViewContent({
{displaySubtitle && <p className="essay-header__subtitle">{displaySubtitle}</p>}
{(essay.frontmatter.author || essay.frontmatter.date) && (
<div className="essay-header__meta">
{[essay.frontmatter.author, essay.frontmatter.date].filter(Boolean).join(' • ')}
{[essay.frontmatter.author, formatJournalDate(essay.frontmatter.date, t.dateLocale)]
.filter(Boolean)
.join(' • ')}
</div>
)}
</header>
@@ -429,9 +451,9 @@ function EssayViewContent({
</figure>
)}
<main>{essay.blocks.map(renderBlock)}</main>
<div>{essay.blocks.map(renderBlock)}</div>
{proofing && proofing.favorites.size > 0 && (
{proofing && selectedCount > 0 && (
<div
className="proofing-sticky-bar"
style={{
@@ -454,7 +476,7 @@ function EssayViewContent({
{/* A count, not the album grid's filter toggle: a story's layout is
authored, so there is nothing for "show favourites" to narrow. */}
<span style={{ fontSize: '0.85rem', fontWeight: 500, padding: '6px 4px' }}>
{t.proofing.selected(proofing.favorites.size)}
{t.proofing.selected(selectedCount)}
</span>
<button
type="button"
@@ -513,6 +535,7 @@ export function EssayView(props: EssayViewProps) {
// default key with every album (and story) on the site.
albumName={props.title || props.essay.frontmatter.title}
allowMailto={props.allowMailto ?? true}
encodedMailto={props.encodedMailto}
>
<EssayViewContent {...props} />
</ProofingProvider>

View File

@@ -15,8 +15,9 @@ import { useState, useCallback, useEffect, useMemo } from 'react';
import Image from 'next/image';
import { Lightbox, type LightboxWatermark } from '@/components/Lightbox';
import { FadeIn } from '@/components/FadeIn';
import { ProofingProvider, useProofing } from '@/components/ProofingContext';
import { ProofingModal } from '@/components/ProofingModal';
import type { ProofSessionInit } from '@/components/ProofingContext';
import { useProofing } from '@/components/useProofing';
import { ProofingProvider, ProofingModal, ProofSessionControls } from '@/components/ProofingLazy';
import { useDictionary } from '@/components/I18nProvider';
import { parsePhotoHash, parsePhotoQuery, buildPhotoQuery } from '@/lib/photoHash';
@@ -60,6 +61,12 @@ interface PhotoGridProps {
proofing?: boolean;
/** Offer the "send by email" button in the proofing modal. */
allowMailto?: boolean;
/**
* `encodeEmail()` of where the proofing dialog's "email to photographer"
* goes, when one is configured (#736). Lets the modal address the compose;
* without it the button is hidden.
*/
encodedMailto?: string;
/**
* The ZIP endpoint for this album, when it offers downloads. Lets the
* proofing modal offer a "download selected" action (#475).
@@ -71,6 +78,11 @@ interface PhotoGridProps {
* selection made in one album leaks into the next.
*/
albumName?: string;
/**
* A client proofing link's session (/proof/<token>). Turns proofing on and
* keeps the selection on the server instead of in the browser.
*/
proofSession?: ProofSessionInit;
}
function PhotoGridInner({
@@ -124,6 +136,33 @@ function PhotoGridInner({
}
}, [lightboxIndex, displayedAssets]);
// ── The photo on screen can leave the list ─────────────────────
// With "selected only" on, un-hearting the photo in the viewer drops it from
// `displayedAssets`. The viewer keeps its position, which now shows the next
// favourite; past the end it steps back to the last one, and with nothing
// left it closes. `shownIndex` keeps this render valid (it used to hand the
// viewer an index past the end, and the page crashed); the effect settles
// the state and the URL.
const shownIndex =
lightboxIndex === null || displayedAssets.length === 0
? null
: Math.min(lightboxIndex, displayedAssets.length - 1);
useEffect(() => {
if (lightboxIndex === null || lightboxIndex < displayedAssets.length) return;
if (displayedAssets.length > 0) {
// eslint-disable-next-line react-hooks/set-state-in-effect
setLightboxIndex(displayedAssets.length - 1);
return;
}
setLightboxIndex(null);
window.history.replaceState(
null,
'',
window.location.pathname + buildPhotoQuery(window.location.search, null),
);
}, [lightboxIndex, displayedAssets.length]);
// ── Listen for browser back/forward ────────────────────────────
useEffect(() => {
const handlePopState = () => {
@@ -204,6 +243,7 @@ function PhotoGridInner({
}}
role="button"
tabIndex={0}
data-lightbox-index={index}
aria-label={t.lightbox.openPhoto(index + 1)}
aria-haspopup="dialog"
style={{
@@ -285,13 +325,38 @@ function PhotoGridInner({
});
}, [displayedAssets, layout, openLightbox, proofing, t]);
// Photos of this album that are selected. Not `favorites.size`: the stored set
// can also hold a photo since removed, or a favourite from another album whose
// name slugs the same way (they share `folio_fav_<name>`).
const selectedCount = proofing ? proofing.getSelectedTokens().length : 0;
return (
<>
<div className={`photo-grid photo-grid--${layout}`} style={gridStyle}>
{gridItems}
</div>
{proofing?.isFilterActive && displayedAssets.length === 0 ? (
// Un-hearting the last favourite with the filter on left a blank page
// between the header and the footer. Say why, and offer the way back
// here as well as in the bar in the corner.
<div className="empty-state" role="status">
<p className="empty-state__text">{t.proofing.filterEmpty}</p>
<div className="empty-state__actions">
<button
type="button"
className="empty-state__button"
onClick={() => proofing.setIsFilterActive(false)}
>
{t.proofing.showAll}
</button>
</div>
</div>
) : (
<div className={`photo-grid photo-grid--${layout}`} style={gridStyle} data-lightbox-group>
{gridItems}
</div>
)}
{proofing && proofing.favorites.size > 0 && (
{/* Kept while the filter is on: un-hearting the last favourite there
empties the grid, and the bar holds the only way back to all photos. */}
{proofing && !proofing.session && (selectedCount > 0 || proofing.isFilterActive) && (
<div
className="proofing-sticky-bar"
style={{
@@ -327,9 +392,7 @@ function PhotoGridInner({
cursor: 'pointer',
}}
>
{proofing.isFilterActive
? t.proofing.showAll
: t.proofing.selected(proofing.favorites.size)}
{proofing.isFilterActive ? t.proofing.showAll : t.proofing.selected(selectedCount)}
</button>
<button
type="button"
@@ -349,12 +412,13 @@ function PhotoGridInner({
</div>
)}
{proofing && <ProofingModal />}
{proofing && !proofing.session && <ProofingModal />}
{proofing?.session && <ProofSessionControls />}
{lightboxIndex !== null && (
{shownIndex !== null && (
<Lightbox
assets={displayedAssets}
currentIndex={lightboxIndex}
currentIndex={shownIndex}
onClose={closeLightbox}
onNext={goNext}
onPrev={goPrev}
@@ -372,7 +436,7 @@ export function PhotoGrid(props: PhotoGridProps) {
// Without the provider useProofing() returns null, and every proofing control
// (hearts in the grid and in the lightbox, selection bar, modal) drops out on
// its own.
if (!props.proofing) {
if (!props.proofing && !props.proofSession) {
return <PhotoGridInner {...props} />;
}
@@ -381,7 +445,9 @@ export function PhotoGrid(props: PhotoGridProps) {
albumTokens={albumTokens}
albumName={props.albumName}
allowMailto={props.allowMailto ?? true}
encodedMailto={props.encodedMailto}
downloadArchiveUrl={props.downloadArchiveUrl}
session={props.proofSession}
>
<PhotoGridInner {...props} />
</ProofingProvider>

View File

@@ -0,0 +1,85 @@
// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, cleanup, fireEvent, within } from '@testing-library/react';
import { PhotoGrid, type PhotoItem } from '../PhotoGrid';
/**
* With "show selected" on, the lightbox walks the favourites only. Un-hearting
* the photo on screen takes it out of that list while the viewer is open: on
* the last favourite the index pointed past the end and the viewer crashed the
* page (`current` undefined), and on the only one the list was empty.
*/
vi.mock('next/image', () => ({
// eslint-disable-next-line @next/next/no-img-element
default: ({ alt }: { alt?: string }) => <img alt={alt ?? ''} />,
}));
vi.mock('@/components/FadeIn', () => ({
FadeIn: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
const photo = (id: string): PhotoItem => ({
id,
type: 'image',
thumbUrl: `/t/${id}`,
previewUrl: `/p/${id}`,
exifUrl: `/e/${id}`,
aspectRatio: 1.5,
});
const ASSETS = [photo('a1'), photo('a2'), photo('a3')];
let store: Map<string, string>;
beforeEach(() => {
// Node 26 defines its own global localStorage (undefined without
// --localstorage-file), which shadows jsdom's; give the test a working one.
store = new Map<string, string>();
vi.stubGlobal('localStorage', {
getItem: (k: string) => store.get(k) ?? null,
setItem: (k: string, v: string) => void store.set(k, String(v)),
removeItem: (k: string) => void store.delete(k),
clear: () => store.clear(),
});
window.history.replaceState(null, '', '/wedding');
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
async function openFilteredLightboxOn(n: number) {
render(<PhotoGrid assets={ASSETS} proofing albumName="Wedding" />);
fireEvent.click(await screen.findByText(/❤️ \d Selected/));
fireEvent.click(screen.getByLabelText(`View photo ${n}`));
return screen.getByRole('dialog');
}
const shownPhoto = (dialog: HTMLElement) =>
dialog.querySelector('img')?.getAttribute('src')?.split('?')[0];
describe('un-hearting inside the filtered lightbox', () => {
it('moves to the previous favourite when the last one is removed', async () => {
store.set('folio_fav_wedding', JSON.stringify(['a1', 'a3']));
const dialog = await openFilteredLightboxOn(2);
expect(shownPhoto(dialog)).toBe('/p/a3');
fireEvent.click(within(dialog).getByLabelText('Remove from favorites'));
const after = screen.getByRole('dialog');
expect(shownPhoto(after)).toBe('/p/a1');
expect(within(after).getByText('1 / 1')).toBeTruthy();
expect(new URLSearchParams(window.location.search).get('photo')).toBe('a1');
});
it('closes the viewer when the only favourite is removed', async () => {
store.set('folio_fav_wedding', JSON.stringify(['a2']));
const dialog = await openFilteredLightboxOn(1);
fireEvent.click(within(dialog).getByLabelText('Remove from favorites'));
expect(screen.queryByRole('dialog')).toBeNull();
expect(new URLSearchParams(window.location.search).get('photo')).toBeNull();
});
});

View File

@@ -0,0 +1,61 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import type { JournalBlock } from '@/lib/journal';
const getAlbumAssetsRaw = vi.fn();
vi.mock('@/lib/immich', () => ({
immich: {
get getAlbumAssetsRaw() {
return getAlbumAssetsRaw;
},
},
}));
import { loadAlbumBlocks } from '../essayPayload';
const album = (albumId: string) => ({ type: 'album', albumId, line: 0 }) as unknown as JournalBlock;
const photo = { type: 'photo', line: 0 } as unknown as JournalBlock;
describe('loadAlbumBlocks', () => {
beforeEach(() => {
getAlbumAssetsRaw.mockReset();
});
// It used to await each album before asking for the next, so a page with
// three album blocks waited for three Immich round trips in a row.
it('asks for every album before any answer arrives', async () => {
const pending: Array<() => void> = [];
getAlbumAssetsRaw.mockImplementation(
(id: string) =>
new Promise((resolve) => pending.push(() => resolve([{ id: `${id}-asset` }]))),
);
const result = loadAlbumBlocks([album('a'), photo, album('b'), album('c')], () => {});
await Promise.resolve();
expect(getAlbumAssetsRaw).toHaveBeenCalledTimes(3);
pending.forEach((resolve) => resolve());
expect([...(await result).keys()]).toEqual(['a', 'b', 'c']);
});
it('loads an album named by two blocks once', async () => {
getAlbumAssetsRaw.mockResolvedValue([]);
await loadAlbumBlocks([album('a'), album('a')], () => {});
expect(getAlbumAssetsRaw).toHaveBeenCalledTimes(1);
});
it('leaves out an album that fails and reports it, keeping the rest', async () => {
const failure = new Error('immich down');
getAlbumAssetsRaw.mockImplementation(async (id: string) => {
if (id === 'b') throw failure;
return [{ id: `${id}-asset` }];
});
const onError = vi.fn();
const result = await loadAlbumBlocks([album('a'), album('b'), album('c')], onError);
expect([...result.keys()]).toEqual(['a', 'c']);
expect(onError).toHaveBeenCalledWith('b', failure);
});
});

View File

@@ -0,0 +1,161 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import type { Metadata } from 'next';
/**
* generateMetadata runs for any URL a visitor types. It used to start from
* `title = slug` and keep that whenever nothing matched, so an unknown path,
* an offline subpage or a locked album put the requested slug in the
* `<title>` and in a validly signed share-card URL. Every branch that finds
* nothing — or finds it locked — now answers with a dictionary title and no
* card of its own.
*/
vi.mock('next/navigation', () => ({
notFound: () => {
throw new Error('NEXT_NOT_FOUND');
},
}));
vi.mock('next/headers', () => ({
cookies: async () => ({ get: () => undefined }),
}));
vi.mock('@/lib/admin/auth', () => ({ isAdminAuthenticated: async () => false }));
vi.mock('@/lib/i18n/server', async () => {
const { getDictionary } = await import('@/lib/i18n');
return { getServerDictionary: () => getDictionary('en') };
});
vi.mock('@/lib/ogImage', () => ({
ogImageUrl: (title: string, subtitle = '') =>
`/api/og?title=${encodeURIComponent(title)}&subtitle=${encodeURIComponent(subtitle)}&sig=x`,
}));
vi.mock('../contentPage', () => ({
contentPageMetadata: vi.fn(async () => null),
renderContentPage: vi.fn(async () => null),
}));
const locked = vi.hoisted(() => ({ keys: new Set<string>() }));
vi.mock('@/lib/auth', () => ({
isProtected: (key: string) => locked.keys.has(key),
isAuthenticated: () => false,
withoutLockedAlbums: <T>(albums: T[]) => albums,
}));
const immich = vi.hoisted(() => ({
isSubpageSlug: vi.fn((slug: string) => slug === 'travel' || slug === 'solo'),
getSubpageAlbums: vi.fn(),
getAlbumBySlug: vi.fn(),
}));
vi.mock('@/lib/immich', () => ({ immich }));
const ICELAND = {
id: 'album-1',
albumName: 'Iceland',
slug: 'iceland',
assets: [{ id: 'a1', type: 'IMAGE' }],
albumThumbnailAssetId: null,
};
import { generateMetadata } from '../page';
import { getDictionary } from '@/lib/i18n';
const en = getDictionary('en');
const meta = (path: string[]) =>
generateMetadata({ params: Promise.resolve({ path }), searchParams: Promise.resolve({}) });
/** Every string the metadata would put in the page head or a share URL. */
function emitted(m: Metadata): string {
return JSON.stringify(m);
}
beforeEach(() => {
vi.clearAllMocks();
locked.keys.clear();
immich.getAlbumBySlug.mockImplementation(async (slug: string) =>
slug === 'iceland' ? ICELAND : null,
);
immich.getSubpageAlbums.mockImplementation(async (slug: string) => {
if (slug === 'travel') {
return {
subpage: { slug: 'travel', name: 'travel', title: 'Travel', albumIds: ['album-1', 'b'] },
albums: [ICELAND, { ...ICELAND, id: 'b', slug: 'norway', albumName: 'Norway' }],
};
}
if (slug === 'solo') {
return { subpage: { slug: 'solo', name: 'solo', albumIds: ['album-1'] }, albums: [ICELAND] };
}
return null;
});
});
describe('page metadata never echoes the requested path', () => {
it.each([
['an unknown slug', ['unknown-visitor-text']],
['an unknown album under a real subpage', ['travel', 'nope']],
['a three-segment path', ['iceland', 'x', 'y']],
])('gives %s the generic not-found title and no card', async (_, path) => {
const m = await meta(path);
expect(m.title).toBe(en.error.notFoundTitle);
expect(m.openGraph).toBeUndefined();
expect(m.twitter).toBeUndefined();
for (const segment of path) expect(emitted(m)).not.toContain(encodeURIComponent(segment));
});
it('drops the layout robots tag on a not-found path, leaving only Next’s noindex', async () => {
const m = await meta(['nope']);
expect(m.robots).toBeNull();
});
it('treats an offline subpage like any unknown slug', async () => {
// isSubpageSlug is false for `enabled: false`, and no album has the slug.
const m = await meta(['dubai']);
expect(m.title).toBe(en.error.notFoundTitle);
expect(emitted(m)).not.toContain('dubai');
});
it('gives a locked standalone album the generic protected title', async () => {
locked.keys.add('album-1');
const m = await meta(['iceland']);
expect(m.title).toBe(en.password.protectedPage);
expect(emitted(m)).not.toContain('iceland');
expect(emitted(m)).not.toContain('Iceland');
expect(m.openGraph).toBeUndefined();
});
it('gives a locked multi-album subpage the protected title, not its slug', async () => {
locked.keys.add('travel');
const m = await meta(['travel']);
expect(m.title).toBe(en.password.protectedPage);
expect(emitted(m)).not.toContain('travel');
});
it('gives an album under a locked subpage the protected title', async () => {
locked.keys.add('travel');
const m = await meta(['travel', 'iceland']);
expect(m.title).toBe(en.password.protectedPage);
expect(emitted(m)).not.toContain('Iceland');
});
it('gives a locked album on a single-album subpage the protected title', async () => {
locked.keys.add('album-1');
const m = await meta(['solo']);
expect(m.title).toBe(en.password.protectedPage);
expect(emitted(m)).not.toContain('solo');
});
it('still describes published content by its own name', async () => {
const album = await meta(['iceland']);
expect(album.title).toBe('Iceland');
expect(emitted(album)).toContain(encodeURIComponent('Iceland'));
const subpage = await meta(['travel']);
expect(subpage.title).toBe('Travel');
const nested = await meta(['travel', 'iceland']);
expect(nested.title).toBe('Iceland');
});
});

View File

@@ -0,0 +1,78 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
/**
* The catch-all answers one segment (subpage, content page, standalone album)
* and two (subpage/album). A third segment used to fall through to the
* one-segment branch, which only reads `path[0]`: `/travel/iceland/anything`
* rendered the Travel subpage and `/iceland/x/y` the Iceland album, each with
* a 200, under an endless supply of URLs.
*/
const NOT_FOUND = new Error('NEXT_NOT_FOUND');
vi.mock('next/navigation', () => ({
notFound: () => {
throw NOT_FOUND;
},
}));
vi.mock('next/headers', () => ({
cookies: async () => ({ get: () => undefined }),
}));
vi.mock('@/lib/admin/auth', () => ({ isAdminAuthenticated: async () => false }));
const immich = vi.hoisted(() => ({
isSubpageSlug: vi.fn((slug: string) => slug === 'travel'),
getSubpageAlbums: vi.fn(),
getAlbumBySlug: vi.fn(),
getStandaloneAlbums: vi.fn(async () => []),
getSubpages: vi.fn(async () => []),
getAssetInfo: vi.fn(async () => null),
}));
vi.mock('@/lib/immich', () => ({ immich }));
const ALBUM = {
id: 'album-1',
albumName: 'Iceland',
slug: 'iceland',
assets: [],
albumThumbnailAssetId: null,
};
import PathPage, { generateMetadata } from '../page';
import { getServerDictionary } from '@/lib/i18n/server';
const call = (path: string[]) => ({
params: Promise.resolve({ path }),
searchParams: Promise.resolve({}),
});
beforeEach(() => {
vi.clearAllMocks();
immich.getAlbumBySlug.mockResolvedValue(ALBUM);
immich.getSubpageAlbums.mockResolvedValue({
subpage: { slug: 'travel', name: 'Travel', albumIds: ['album-1', 'album-2'] },
albums: [ALBUM, { ...ALBUM, id: 'album-2', slug: 'norway', albumName: 'Norway' }],
});
});
describe('catch-all path depth', () => {
it.each([[['iceland', 'x', 'y']], [['travel', 'iceland', 'extra']], [['travel', 'a', 'b', 'c']]])(
'answers %j with a 404',
async (path) => {
await expect(PathPage(call(path))).rejects.toBe(NOT_FOUND);
expect(immich.getAlbumBySlug).not.toHaveBeenCalled();
expect(immich.getSubpageAlbums).not.toHaveBeenCalled();
},
);
it('gives a three-segment path no album metadata, only the not-found title', async () => {
const meta = await generateMetadata(call(['iceland', 'x', 'y']));
expect(meta.title).toBe(getServerDictionary().error.notFoundTitle);
expect(immich.getAlbumBySlug).not.toHaveBeenCalled();
});
it('still renders one and two segments', async () => {
await expect(PathPage(call(['iceland']))).resolves.toBeTruthy();
await expect(PathPage(call(['travel', 'iceland']))).resolves.toBeTruthy();
});
});

View File

@@ -0,0 +1,121 @@
// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, cleanup, fireEvent, within } from '@testing-library/react';
import { PhotoGrid, type PhotoItem } from '../PhotoGrid';
import { EssayView } from '../EssayView';
import { parseEssayMarkdown } from '@/lib/essay';
import { encodeEmail } from '@/lib/emailObfuscation';
/**
* The anonymous proofing selection lives under `folio_fav_<albumName>`, so it
* can hold tokens this grid does not show: a photo since removed from the
* album, or a favourite from another album whose name slugs the same way.
* Every count the visitor sees must be the photos of *this* album that are
* selected — the modal's download button already counted that way, while the
* bar, the title and the email subject counted the whole stored set.
*/
vi.mock('next/image', () => ({
// eslint-disable-next-line @next/next/no-img-element
default: ({ alt }: { alt?: string }) => <img alt={alt ?? ''} />,
}));
vi.mock('@/components/Lightbox', () => ({ Lightbox: () => null }));
vi.mock('@/components/LeafletMap', () => ({
LeafletMap: () => null,
escapeHtml: (s: string) => s,
}));
vi.mock('@/components/FadeIn', () => ({
FadeIn: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
const photo = (id: string): PhotoItem => ({
id,
type: 'image',
thumbUrl: `/t/${id}`,
previewUrl: `/p/${id}`,
exifUrl: `/e/${id}`,
aspectRatio: 1.5,
});
const ASSETS = [photo('a1'), photo('a2'), photo('a3')];
let store: Map<string, string>;
beforeEach(() => {
// Node 26 defines its own global localStorage (undefined without
// --localstorage-file), which shadows jsdom's; give the test a working one.
store = new Map<string, string>();
vi.stubGlobal('localStorage', {
getItem: (k: string) => store.get(k) ?? null,
setItem: (k: string, v: string) => void store.set(k, String(v)),
removeItem: (k: string) => void store.delete(k),
clear: () => store.clear(),
});
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
describe('proofing counts in the album grid', () => {
it('counts only this album’s photos, not stale or foreign favourites', async () => {
// One photo of this album, one removed photo, one from a same-named album.
store.set('folio_fav_wedding', JSON.stringify(['a2', 'gone', 'other-album']));
render(<PhotoGrid assets={ASSETS} proofing albumName="Wedding" />);
expect(await screen.findByText('❤️ 1 Selected')).toBeTruthy();
fireEvent.click(screen.getByText('Share & Export'));
expect(screen.getByText('❤️ Selection (1)')).toBeTruthy();
expect(screen.getByText(/You have selected 1 photo\./)).toBeTruthy();
});
it('shows no selection bar when only foreign favourites are stored', () => {
store.set('folio_fav_wedding', JSON.stringify(['gone', 'other-album']));
render(<PhotoGrid assets={ASSETS} proofing albumName="Wedding" />);
// `render` flushes the hydration effect, so the stored set is loaded here.
expect(screen.queryByText(/Selected/)).toBeNull();
expect(screen.queryByText('Share & Export')).toBeNull();
});
it('keeps "Show All" reachable after the last favourite is removed in the filter', async () => {
store.set('folio_fav_wedding', JSON.stringify(['a1']));
render(<PhotoGrid assets={ASSETS} proofing albumName="Wedding" />);
fireEvent.click(await screen.findByText('❤️ 1 Selected'));
// Filtered to the one favourite; un-heart it and the grid is empty.
fireEvent.click(screen.getByLabelText('Remove favorite'));
expect(screen.queryByLabelText('Add favorite')).toBeNull();
// The empty state offers "Show All" too; this is about the bar's own.
const bar = document.querySelector<HTMLElement>('.proofing-sticky-bar')!;
fireEvent.click(within(bar).getByText('Show All'));
expect(screen.getAllByLabelText('Add favorite')).toHaveLength(3);
});
it('puts the album count into the email subject', async () => {
store.set('folio_fav_wedding', JSON.stringify(['a1', 'gone']));
render(
<PhotoGrid
assets={ASSETS}
proofing
albumName="Wedding"
allowMailto
encodedMailto={encodeEmail('hello@example.com')}
/>,
);
fireEvent.click(await screen.findByText('Share & Export'));
const location = { href: 'http://localhost/wedding' };
vi.stubGlobal('location', location);
fireEvent.click(screen.getByText('✉️ Send Email to Photographer'));
expect(decodeURIComponent(location.href)).toMatch(/Photo Selection \(1 items?\)/);
});
});
describe('proofing counts in an essay', () => {
it('counts only the essay’s photos', async () => {
store.set('folio_fav_story', JSON.stringify(['a3', 'gone']));
const essay = parseEssayMarkdown('---\ntitle: Story\n---\n\n![a1, a3](caption)\n');
render(<EssayView essay={essay} assets={ASSETS} title="Story" proofing />);
expect(await screen.findByText('❤️ 1 Selected')).toBeTruthy();
});
});

View File

@@ -0,0 +1,77 @@
// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, cleanup, fireEvent, within } from '@testing-library/react';
import { PhotoGrid, type PhotoItem } from '../PhotoGrid';
/**
* With "show selected" on, un-hearting the last favourite emptied the grid and
* left nothing between the album header and the footer — no word on why, and
* the only way back a small pill in the corner.
*/
vi.mock('next/image', () => ({
// eslint-disable-next-line @next/next/no-img-element
default: ({ alt }: { alt?: string }) => <img alt={alt ?? ''} />,
}));
vi.mock('@/components/FadeIn', () => ({
FadeIn: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
const photo = (id: string): PhotoItem => ({
id,
type: 'image',
thumbUrl: `/t/${id}`,
previewUrl: `/p/${id}`,
exifUrl: `/e/${id}`,
aspectRatio: 1.5,
});
const ASSETS = [photo('a1'), photo('a2'), photo('a3')];
let store: Map<string, string>;
beforeEach(() => {
// Node 26 defines its own global localStorage (undefined without
// --localstorage-file), which shadows jsdom's; give the test a working one.
store = new Map<string, string>();
vi.stubGlobal('localStorage', {
getItem: (k: string) => store.get(k) ?? null,
setItem: (k: string, v: string) => void store.set(k, String(v)),
removeItem: (k: string) => void store.delete(k),
clear: () => store.clear(),
});
window.history.replaceState(null, '', '/wedding');
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
describe('favourites filter with nothing left', () => {
it('says nothing is selected and offers the way back to all photos', async () => {
store.set('folio_fav_wedding', JSON.stringify(['a2']));
render(<PhotoGrid assets={ASSETS} proofing albumName="Wedding" />);
fireEvent.click(await screen.findByText('❤️ 1 Selected'));
expect(screen.getAllByLabelText(/^View photo/)).toHaveLength(1);
fireEvent.click(screen.getByLabelText('Remove favorite'));
const empty = screen.getByRole('status');
expect(within(empty).getByText('No photos selected.')).toBeTruthy();
expect(screen.queryAllByLabelText(/^View photo/)).toHaveLength(0);
fireEvent.click(within(empty).getByRole('button', { name: 'Show All' }));
expect(screen.getAllByLabelText(/^View photo/)).toHaveLength(3);
expect(screen.queryByText('No photos selected.')).toBeNull();
});
it('shows no empty state while the filter still has photos', async () => {
store.set('folio_fav_wedding', JSON.stringify(['a1', 'a2']));
render(<PhotoGrid assets={ASSETS} proofing albumName="Wedding" />);
fireEvent.click(await screen.findByText('❤️ 2 Selected'));
expect(screen.getAllByLabelText(/^View photo/)).toHaveLength(2);
expect(screen.queryByText('No photos selected.')).toBeNull();
});
});

View File

@@ -0,0 +1,126 @@
// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, cleanup, fireEvent } from '@testing-library/react';
import { renderToReadableStream } from 'react-dom/server';
import type { ReactNode } from 'react';
import { PhotoGrid, type PhotoItem } from '../PhotoGrid';
import { EssayView } from '../EssayView';
import { parseEssayMarkdown } from '@/lib/essay';
/**
* Proofing is off on most album pages, but its provider, modal and session
* controls used to be imported statically by the grid and the essay, so every
* album, essay and journal page shipped them (~5 KB gzip). They now load
* through `next/dynamic` only where proofing is on.
*
* The mocks below pass every module through unchanged and only note that it
* was loaded: a page without proofing must not load any of them, and a page
* with proofing must still render the hearts — on the server too, so they are
* in the HTML before the chunk arrives.
*/
const loaded = vi.hoisted(() => new Set<string>());
vi.mock('@/components/ProofingContext', async (importOriginal) => {
loaded.add('ProofingContext');
return importOriginal();
});
vi.mock('@/components/ProofingModal', async (importOriginal) => {
loaded.add('ProofingModal');
return importOriginal();
});
vi.mock('@/components/ProofSessionControls', async (importOriginal) => {
loaded.add('ProofSessionControls');
return importOriginal();
});
// The build aliases `next/dynamic` to the App Router implementation in app/;
// the bare package resolves to the Pages Router one.
vi.mock('next/dynamic', async () => ({
default: (await import('next/dist/shared/lib/app-dynamic')).default,
}));
vi.mock('next/image', () => ({
// eslint-disable-next-line @next/next/no-img-element
default: ({ alt }: { alt?: string }) => <img alt={alt ?? ''} />,
}));
vi.mock('@/components/LeafletMap', () => ({
LeafletMap: () => null,
escapeHtml: (s: string) => s,
}));
vi.mock('@/components/FadeIn', () => ({
FadeIn: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
const photo = (id: string): PhotoItem => ({
id,
type: 'image',
thumbUrl: `/t/${id}`,
previewUrl: `/p/${id}`,
exifUrl: `/e/${id}`,
aspectRatio: 1.5,
});
const ASSETS = [photo('a1'), photo('a2'), photo('a3')];
const ESSAY = parseEssayMarkdown('---\ntitle: Story\n---\n\n![a1, a3](caption)\n');
async function serverHtml(node: ReactNode): Promise<string> {
const stream = await renderToReadableStream(node);
await stream.allReady;
return new Response(stream).text();
}
const hearts = (html: string) => html.match(/aria-label="Add favorite"/g)?.length ?? 0;
beforeEach(() => {
// Node defines its own global localStorage (undefined without
// --localstorage-file), which shadows jsdom's; give the test a working one.
const store = new Map<string, string>();
vi.stubGlobal('localStorage', {
getItem: (k: string) => store.get(k) ?? null,
setItem: (k: string, v: string) => void store.set(k, String(v)),
removeItem: (k: string) => void store.delete(k),
clear: () => store.clear(),
});
});
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
// Runs first: the set records loads for the whole file.
describe('proofing off', () => {
it('loads neither the provider nor the modal nor the session controls', async () => {
const grid = render(<PhotoGrid assets={ASSETS} albumName="Wedding" />);
const essay = render(<EssayView essay={ESSAY} assets={ASSETS} title="Story" />);
expect(grid.container.querySelectorAll('img')).toHaveLength(3);
expect(essay.container.querySelectorAll('img')).toHaveLength(2);
expect(screen.queryByLabelText('Add favorite')).toBeNull();
await serverHtml(<PhotoGrid assets={ASSETS} albumName="Wedding" />);
expect([...loaded]).toEqual([]);
});
});
describe('proofing on', () => {
it('renders the hearts on the server', async () => {
const html = await serverHtml(<PhotoGrid assets={ASSETS} proofing albumName="Wedding" />);
expect(hearts(html)).toBe(3);
const essay = await serverHtml(
<EssayView essay={ESSAY} assets={ASSETS} title="Story" proofing />,
);
expect(hearts(essay)).toBe(2);
});
it('shares one context between the grid and the lazily loaded provider and modal', async () => {
render(<PhotoGrid assets={ASSETS} proofing albumName="Wedding" />);
const [first] = await screen.findAllByLabelText('Add favorite');
fireEvent.click(first);
// The heart, the selection bar and the modal all read the same state.
expect(screen.getAllByLabelText('Remove favorite')).toHaveLength(1);
fireEvent.click(await screen.findByText('Share & Export'));
expect(await screen.findByText(/You have selected 1 photo\./)).toBeTruthy();
expect(loaded).toContain('ProofingContext');
expect(loaded).toContain('ProofingModal');
});
});

View File

@@ -0,0 +1,31 @@
import { describe, it, expect } from 'vitest';
import fs from 'fs';
import path from 'path';
/**
* The page renders albums and essays from several branches — subpage album,
* essay, single-album subpage, standalone album — and each one passes the
* proofing props by hand. The dialog hides its email button without a
* recipient (#736), so a branch that forwards `allowMailto` but forgets
* `encodedMailto` silently loses the button on that kind of page. #746 missed
* two of the four; this keeps the next branch from doing the same.
*/
const source = fs.readFileSync(path.join(__dirname, '..', 'page.tsx'), 'utf8');
/** Every `<AlbumDetailView … />` and `<EssayView … />` element in the page. */
const elements = source.match(/<(AlbumDetailView|EssayView)\b[\s\S]*?\/>/g) ?? [];
describe('proofing email wiring in the catch-all page', () => {
it('finds the album and essay views', () => {
expect(elements.length).toBeGreaterThanOrEqual(4);
});
it('passes the recipient wherever it passes the email switch', () => {
const missing = elements
.filter((el) => el.includes('allowMailto='))
.filter((el) => !el.includes('encodedMailto='))
.map((el) => el.split('\n').slice(0, 3).join(' ').trim());
expect(missing).toEqual([]);
});
});

View File

@@ -0,0 +1,108 @@
/**
* Content pages at `/<slug>` (#722): content/pages/<slug>.md rendered through
* the journal's EssayView, without a date, reading time or journal index.
*
* Draft and password behave as on a journal entry: a draft is a 404 for
* everyone but a signed-in admin, and a password shows the gate until the
* `lb_auth_page_<slug>` cookie is set. The site password is enforced before
* any of this runs, in proxy.ts.
*/
import type { Metadata } from 'next';
import { cookies } from 'next/headers';
import { readPage, type PageRecord } from '@/lib/admin/pages-service';
import { isAdminAuthenticated } from '@/lib/admin/auth';
import { isAuthenticated } from '@/lib/auth';
import { getConfig } from '@/lib/config';
import { getServerDictionary } from '@/lib/i18n/server';
import { ogImageUrl } from '@/lib/ogImage';
import PasswordGate from '@/components/PasswordGate';
import { EssayView } from './EssayView';
import { buildEssayPayload } from './essayPayload';
type Access = 'open' | 'draft' | 'locked';
async function accessFor(page: PageRecord): Promise<Access> {
const { draft, password } = page.parsed.frontmatter;
if (draft && !(await isAdminAuthenticated())) return 'draft';
if (password) {
const cookieStore = await cookies();
if (!isAuthenticated(page.slug, (name) => cookieStore.get(name)?.value, 'page')) {
return 'locked';
}
}
return 'open';
}
/**
* Metadata for `/<slug>` when it is a page, or null when it is not.
*
* A draft is described as not found, and a locked page by a generic
* title only: generateMetadata runs ahead of the page's own gate, so the real
* title and description must not reach the `<head>` (GHSA-fvgv-97g3-wjr7).
*/
export async function contentPageMetadata(slug: string): Promise<Metadata | null> {
const page = await readPage(slug).catch(() => null);
if (!page) return null;
const access = await accessFor(page);
const t = getServerDictionary();
// A draft answers 404 to everyone but an admin, so it gets the not-found
// title, and no robots tag that would contradict Next's own noindex.
if (access === 'draft') return { title: t.error.notFoundTitle, robots: null };
if (access === 'locked') {
return { title: t.password.protectedPage, robots: { index: false } };
}
const { title: rawTitle, description } = page.parsed.frontmatter;
const title = rawTitle || slug;
const ogImage = ogImageUrl(title);
return {
title,
...(description ? { description } : {}),
openGraph: { title, ...(description ? { description } : {}), images: [ogImage] },
twitter: {
card: 'summary_large_image',
title,
...(description ? { description } : {}),
images: [ogImage],
},
};
}
/**
* The rendered page, `'not-found'` for a draft a visitor may not see, or null
* when no page has this slug (the caller then tries a standalone album).
*/
export async function renderContentPage(
slug: string,
): Promise<React.ReactElement | 'not-found' | null> {
const page = await readPage(slug).catch(() => null);
if (!page) return null;
const access = await accessFor(page);
if (access === 'draft') return 'not-found';
const { frontmatter, blocks } = page.parsed;
if (access === 'locked') {
return <PasswordGate slug={slug} title={frontmatter.title || slug} type="page" />;
}
// No map block in v1 (#722): it is dropped before any of its photos are
// fetched, so a hand-written `::map` cannot publish positions either.
const { essay, images } = await buildEssayPayload(blocks, {
logTag: 'page',
slug,
allowMap: false,
});
return (
<div className="content-page" style={{ paddingTop: '2rem' }}>
<EssayView
// Only the title crosses to the client: the frontmatter also holds
// the password, stored hashed but still not the visitor's business.
essay={{ ...essay, frontmatter: { title: frontmatter.title } }}
assets={images}
title={frontmatter.title}
watermark={getConfig().watermark}
/>
</div>
);
}

View File

@@ -0,0 +1,197 @@
/**
* Turn a parsed block-markdown document into what `EssayView` renders: the
* blocks with every asset id replaced by its token, and the photo items those
* tokens resolve to. Shared by journal entries and content pages (#722).
*
* Server only — it talks to Immich and encrypts asset ids.
*/
import {
collectAssetIds,
mapBlockAssetIds,
type JournalBlock,
type MapPin,
type ParsedJournal,
} from '@/lib/journal';
import { entryMapPins } from '@/lib/journalMap';
import { expandAlbumBlocks } from '@/lib/journalAlbum';
import { getConfig } from '@/lib/config';
import { immich, type ImmichAsset } from '@/lib/immich';
import {
imageUrl,
videoUrl,
exifUrl,
assetPlaceholder,
assetAspectRatio,
assetCaption,
assetExifSummary,
} from '@/lib/urls';
import { encodeAssetId } from '@/lib/tokens';
import type { PhotoItem } from './PhotoGrid';
export interface EssayPayload {
/** Blocks and cover carry tokens, never raw asset ids. Frontmatter is left empty. */
essay: ParsedJournal;
images: PhotoItem[];
}
interface EssayPayloadOptions {
/** Prefix for log lines, e.g. `journal` or `page`. */
logTag: string;
slug: string;
/** Map blocks are dropped when false, whatever the site's map setting. */
allowMap: boolean;
/** Raw asset id of a cover photo, shown in the lightbox sequence. */
coverAssetId?: string;
}
/**
* The assets of every album an album block names, keyed by album id, loaded
* concurrently. An album that fails is reported and left out, so its block
* drops rather than the page.
*/
export async function loadAlbumBlocks(
blocks: readonly JournalBlock[],
onError: (albumId: string, error: unknown) => void,
): Promise<Map<string, ImmichAsset[]>> {
const albumIds = [
...new Set(blocks.flatMap((b) => (b.type === 'album' && b.albumId ? [b.albumId] : []))),
];
const loaded = await Promise.all(
albumIds.map(async (albumId) => {
try {
return [albumId, await immich.getAlbumAssetsRaw(albumId)] as const;
} catch (error) {
onError(albumId, error);
return null;
}
}),
);
return new Map(loaded.filter((entry) => entry !== null));
}
export async function buildEssayPayload(
authoredBlocks: JournalBlock[],
{ logTag, slug, allowMap, coverAssetId }: EssayPayloadOptions,
): Promise<EssayPayload & { coverToken?: string }> {
const config = getConfig();
const mapAllowed = allowMap && config.map;
const sourceBlocks = allowMap ? authoredBlocks : authoredBlocks.filter((b) => b.type !== 'map');
const referencedAssetIds = [
...new Set([...(coverAssetId ? [coverAssetId] : []), ...collectAssetIds(sourceBlocks)]),
];
const fetchedAssets = (
await Promise.all(
referencedAssetIds.map((assetId) => immich.getAssetInfo(assetId).catch(() => null)),
)
).filter((a): a is ImmichAsset => a !== null);
// Album blocks become photo blocks here. The raw fetch bypasses the album
// allowlist on purpose: an entry may already show any single photo by id,
// and the author's pick is the gate for a whole album just the same. An
// album Immich cannot deliver drops its block rather than the page.
// All albums at once, not one round trip after the other.
const albumAssetsById = await loadAlbumBlocks(sourceBlocks, (albumId, error) => {
// eslint-disable-next-line no-console
console.warn(`[${logTag}] ${slug}: album ${albumId} could not be loaded:`, error);
});
const { blocks } = expandAlbumBlocks(
sourceBlocks,
(albumId) => albumAssetsById.get(albumId),
config.albumManualOrders,
);
const knownIds = new Set(fetchedAssets.map((a) => a.id));
const rawAssets = [...fetchedAssets];
for (const list of albumAssetsById.values()) {
for (const asset of list) {
if (knownIds.has(asset.id)) continue;
knownIds.add(asset.id);
rawAssets.push(asset);
}
}
// EssayView drops photo blocks it cannot resolve, which is right for visitors
// but leaves no trace of *why* a photo vanished. Legacy positional references
// ("1", "2") are the usual cause: they only resolved against a subpage album.
if (fetchedAssets.length < referencedAssetIds.length) {
const resolved = new Set(fetchedAssets.map((a) => a.id));
const missing = referencedAssetIds.filter((id) => !resolved.has(id));
// eslint-disable-next-line no-console
console.warn(
`[${logTag}] ${slug}: ${missing.length} photo reference(s) could not be resolved and will not render: ${missing.join(', ')}`,
);
}
/*
* EssayView resolves a block's photo through PhotoItem.id, and those ids are
* encrypted tokens — while the blocks coming out of the Markdown carry raw
* asset UUIDs. Translating here also keeps raw UUIDs out of the client
* payload. Unresolvable references collapse to an empty string, which
* EssayView skips.
*/
const tokenByAssetId = new Map(rawAssets.map((a) => [a.id, encodeAssetId(a.id)]));
const toToken = (assetId: string) => tokenByAssetId.get(assetId) ?? '';
// A map block's pins are computed here, from the photos fetched above and
// under each photo's `location:` precision, and only when the site
// publishes a map at all. The client gets pins only — never the items,
// which carry raw asset ids.
const entryPhotoIds = collectAssetIds(blocks.filter((b) => b.type !== 'map'));
const pinsByBlock = new Map<JournalBlock, MapPin[]>();
if (mapAllowed) {
for (const block of blocks) {
if (block.type === 'map') {
pinsByBlock.set(block, await entryMapPins(block.items, rawAssets, entryPhotoIds));
}
}
}
// Photos that only anchor a map pin are fetched for their EXIF but are not
// part of the story, so they stay out of the lightbox sequence.
const shownAssetIds = new Set([...entryPhotoIds, ...(coverAssetId ? [coverAssetId] : [])]);
const essay: ParsedJournal = {
frontmatter: {},
blocks: blocks.flatMap((block): JournalBlock[] => {
if (block.type === 'map') {
const pins = pinsByBlock.get(block);
return pins
? [{ type: 'map', caption: block.caption, line: block.line, items: [], pins }]
: [];
}
return [mapBlockAssetIds(block, toToken)];
}),
referencedAssetIds: rawAssets.map((a) => encodeAssetId(a.id)),
};
const images: PhotoItem[] = rawAssets
.filter((a) => shownAssetIds.has(a.id) && (a.type === 'IMAGE' || a.type === 'VIDEO'))
.map((a) => {
const ph = assetPlaceholder(a);
const exif =
config.exif.onHover && config.exif.camera && a.type === 'IMAGE'
? assetExifSummary(a)
: undefined;
const caption = assetCaption(a, config.exif.caption);
const isVideo = a.type === 'VIDEO';
return {
id: encodeAssetId(a.id),
type: isVideo ? 'video' : 'image',
thumbUrl: imageUrl(a.id, 'preview'),
previewUrl: imageUrl(a.id, 'preview'),
...(isVideo ? { videoUrl: videoUrl(a.id) } : {}),
exifUrl: exifUrl(a.id),
...(ph ? { blurDataURL: ph.blurDataURL, dominantColor: ph.dominantColor } : {}),
...(exif ?? {}),
...(caption ? { caption } : {}),
aspectRatio: assetAspectRatio(a),
};
});
return {
essay,
images,
...(coverAssetId ? { coverToken: toToken(coverAssetId) || undefined } : {}),
};
}

View File

@@ -3,30 +3,25 @@
*
* Single segment:
* - If slug matches a subpage → render subpage album grid
* - If slug matches a content page (content/pages/<slug>.md) → render it
* - If slug matches a standalone album → render album detail
*
* Two segments:
* - Treat as subpage-slug/album-slug → render album detail
* with back-link to the subpage
*
* Three or more segments: 404.
*/
import { cookies } from 'next/headers';
import type { Metadata } from 'next';
import { immich, type ImmichAsset } from '@/lib/immich';
import { notFound } from 'next/navigation';
import type { PhotoItem } from './PhotoGrid';
import {
imageUrl,
exifUrl,
videoUrl,
assetPlaceholder,
assetCaption,
assetExifSummary,
downloadUrl,
archiveUrl,
assetAspectRatio,
} from '@/lib/urls';
import { toPhotoItems } from './photoItems';
import { imageUrl, assetPlaceholder, archiveUrl } from '@/lib/urls';
import { ogImageUrl } from '@/lib/ogImage';
import { encodeAssetId, decodeAssetId } from '@/lib/tokens';
import { encodeEmail } from '@/lib/emailObfuscation';
import {
buildCoverGridVars,
getConfig,
@@ -52,6 +47,8 @@ import { mapBlockAssetIds } from '@/lib/journal';
import { strictestPrecision, type LocationPrecision } from '@/lib/mapPrecision';
import { resolveEssayFile, generatedEssayCaption } from '@/lib/essaySource';
import { getServerDictionary } from '@/lib/i18n/server';
import { contentPageMetadata, renderContentPage } from './contentPage';
import { loadAlbumBlocks } from './essayPayload';
// Render at request time — requires live Immich connection
export const dynamic = 'force-dynamic';
@@ -75,13 +72,32 @@ async function isLocked(key: string, type: 'subpage' | 'album'): Promise<boolean
return !isAuthenticated(key, getCookie, type);
}
/**
* Metadata for a path that names nothing this site publishes. The title is
* the dictionary's, never the requested slug: generateMetadata runs for any
* URL a visitor types, and echoing it would put their text in the `<title>`
* and, through a signed share card, in an image served from this domain.
* Leaving `openGraph` out keeps the root layout's site card. `robots: null`
* drops the layout's `index, follow`, which would otherwise contradict the
* `noindex` Next adds to every not-found response.
*/
function notFoundMetadata(): Metadata {
return { title: getServerDictionary().error.notFoundTitle, robots: null };
}
/** Metadata for a path behind a password this request has not given. */
function lockedMetadata(): Metadata {
return { title: getServerDictionary().password.protectedPage, robots: { index: false } };
}
export async function generateMetadata({ params, searchParams }: PathPageProps): Promise<Metadata> {
// Next hands catch-all segments over percent-encoded, so a non-ASCII slug
// ("/家族相册") would never match a stored one. Decode once, here, and every
// comparison downstream works on the same form (#522).
const { path: rawPath } = await params;
const path = rawPath?.map(normalizeSlug);
if (!path || path.length === 0) return {};
// Deeper paths are a 404 (see the page below); they name nothing to describe.
if (!path || path.length === 0 || path.length > 2) return notFoundMetadata();
// A shared photo link's whole point is that it reaches the server — unlike
// the #photo-N hash it replaces, a `photo` query param is visible here, so
@@ -92,45 +108,51 @@ export async function generateMetadata({ params, searchParams }: PathPageProps):
const photoAssetId = photoToken ? decodeAssetId(photoToken) : null;
let photoAsset: ImmichAsset | undefined;
// Each branch follows the page body's order of gates and 404s, and takes
// the title only from site-authored text (an album or subpage name). A
// branch that finds nothing, or finds it locked, returns early, so the
// requested slug never becomes a title or share-card text.
const slug = path[0];
let title = slug;
let title: string;
let subtitle = '';
let description: string | undefined = undefined;
const photoCount = (assets: ImmichAsset[]) =>
getServerDictionary().common.photos(
assets.filter((a) => a.type === 'IMAGE' || a.type === 'VIDEO').length,
);
if (path.length === 1 && immich.isSubpageSlug(slug)) {
const subpageLocked = await isLocked(slug, 'subpage');
if (await isLocked(slug, 'subpage')) return lockedMetadata();
const result = await immich.getSubpageAlbums(slug);
if (result) {
if (!subpageLocked && result.subpage.subtitle) {
description = result.subpage.subtitle;
}
if (result.albums.length === 1) {
const album = await immich.getAlbumBySlug(result.albums[0].slug, slug);
if (album && !subpageLocked && !(await isLocked(album.id, 'album'))) {
title = album.albumName;
const count = album.assets.filter((a) => a.type === 'IMAGE' || a.type === 'VIDEO').length;
subtitle = `${count} photo${count === 1 ? '' : 's'}`;
if (photoAssetId) photoAsset = album.assets.find((a) => a.id === photoAssetId);
}
} else if (!subpageLocked) {
title = result.subpage.title || result.subpage.name;
}
if (!result || result.albums.length === 0) return notFoundMetadata();
if (result.subpage.subtitle) description = result.subpage.subtitle;
if (result.albums.length === 1) {
const album = await immich.getAlbumBySlug(result.albums[0].slug, slug);
if (!album) return notFoundMetadata();
if (await isLocked(album.id, 'album')) return lockedMetadata();
title = album.albumName;
subtitle = photoCount(album.assets);
if (photoAssetId) photoAsset = album.assets.find((a) => a.id === photoAssetId);
} else {
title = result.subpage.title || result.subpage.name;
}
} else if (path.length === 2) {
if (await isLocked(slug, 'subpage')) return lockedMetadata();
const album = await immich.getAlbumBySlug(path[1], slug);
if (album && !(await isLocked(slug, 'subpage')) && !(await isLocked(album.id, 'album'))) {
title = album.albumName;
const count = album.assets.filter((a) => a.type === 'IMAGE' || a.type === 'VIDEO').length;
subtitle = `${count} photo${count === 1 ? '' : 's'}`;
if (photoAssetId) photoAsset = album.assets.find((a) => a.id === photoAssetId);
}
if (!album) return notFoundMetadata();
if (await isLocked(album.id, 'album')) return lockedMetadata();
title = album.albumName;
subtitle = photoCount(album.assets);
if (photoAssetId) photoAsset = album.assets.find((a) => a.id === photoAssetId);
} else {
const pageMeta = await contentPageMetadata(slug);
if (pageMeta) return pageMeta;
const album = await immich.getAlbumBySlug(slug);
if (album && !(await isLocked(album.id, 'album'))) {
title = album.albumName;
const count = album.assets.filter((a) => a.type === 'IMAGE' || a.type === 'VIDEO').length;
subtitle = `${count} photo${count === 1 ? '' : 's'}`;
if (photoAssetId) photoAsset = album.assets.find((a) => a.id === photoAssetId);
}
if (!album) return notFoundMetadata();
if (await isLocked(album.id, 'album')) return lockedMetadata();
title = album.albumName;
subtitle = photoCount(album.assets);
if (photoAssetId) photoAsset = album.assets.find((a) => a.id === photoAssetId);
}
// The title stays the album's — it's still the context a reader wants —
@@ -140,9 +162,7 @@ export async function generateMetadata({ params, searchParams }: PathPageProps):
photoAsset?.exifInfo?.description?.trim() ||
description ||
(subtitle ? `${title} — ${subtitle}` : undefined);
const ogImage = photoAsset
? imageUrl(photoAsset.id, 'preview')
: `/api/og?title=${encodeURIComponent(title)}${subtitle ? `&subtitle=${encodeURIComponent(subtitle)}` : ''}`;
const ogImage = photoAsset ? imageUrl(photoAsset.id, 'preview') : ogImageUrl(title, subtitle);
return {
title,
@@ -161,44 +181,6 @@ export async function generateMetadata({ params, searchParams }: PathPageProps):
};
}
/** Map Immich assets to PhotoItem props for the grid/lightbox. */
/**
* `showExif` covers the hover overlay only, and that overlay carries camera,
* lens and focal length — so it follows the `camera` group, not the panel.
*
* `showCaption` follows the `caption` group and decides whether the Immich
* description becomes alt text; see `assetCaption`.
*/
function toPhotoItems(
assets: ImmichAsset[],
showExif: boolean,
showCaption: boolean,
/** The album offering downloads, or undefined when it does not. */
downloadAlbumId?: string,
): PhotoItem[] {
return assets
.filter((a) => a.type === 'IMAGE' || a.type === 'VIDEO')
.map((a) => {
const ph = assetPlaceholder(a);
const exif = showExif && a.type === 'IMAGE' ? assetExifSummary(a) : undefined;
const caption = assetCaption(a, showCaption);
const isVideo = a.type === 'VIDEO';
return {
id: encodeAssetId(a.id),
type: isVideo ? 'video' : 'image',
thumbUrl: imageUrl(a.id, 'preview'),
previewUrl: imageUrl(a.id, 'preview'),
...(isVideo ? { videoUrl: videoUrl(a.id) } : {}),
exifUrl: exifUrl(a.id),
...(ph ? { blurDataURL: ph.blurDataURL, dominantColor: ph.dominantColor } : {}),
...(exif ?? {}),
...(caption ? { caption } : {}),
...(downloadAlbumId ? { downloadUrl: downloadUrl(downloadAlbumId, a.id) } : {}),
aspectRatio: assetAspectRatio(a),
};
});
}
/**
* JSON-LD for an album page. Null unless a site URL is configured — structured
* data is a set of claims about absolute URLs, and there is nothing truthful to
@@ -242,7 +224,8 @@ async function gateIfProtected(
let title = titleOverride || key;
if (!titleOverride && type === 'subpage') {
const subpageData = await immich.getSubpageAlbums(key);
title = subpageData?.subpage.name ?? key;
const sp = subpageData?.subpage;
title = sp ? sp.title || sp.name : key;
}
return <PasswordGate slug={key} title={title} type={type} />;
@@ -280,6 +263,12 @@ export default async function PathPage({ params, searchParams }: PathPageProps)
const config = getConfig();
// The proofing dialog's "email to photographer" needs a recipient: the
// configured `proofing.email`, else the footer contact email (#736). Encoded
// here so the plain address stays out of the HTML and the RSC payload, like
// every other address the site renders.
const encodedMailto = config.proofing.email ? encodeEmail(config.proofing.email) : undefined;
// Build grid CSS custom properties, optionally merging subpage overrides
const buildGridStyle = (overrides?: Partial<GridConfig>): React.CSSProperties => {
const g = { ...config.grid, ...overrides };
@@ -322,7 +311,10 @@ export default async function PathPage({ params, searchParams }: PathPageProps)
return { ...spGrid, ...albumGrid };
};
if (!path || path.length === 0) {
// One segment or two: nothing on this site lives deeper. A third segment
// used to fall through to the one-segment branch below, which reads only
// `path[0]`, so `/travel/iceland/anything` rendered the Travel subpage.
if (!path || path.length === 0 || path.length > 2) {
notFound();
}
@@ -351,7 +343,9 @@ export default async function PathPage({ params, searchParams }: PathPageProps)
// Look up subpage config for grid overrides and back link
const subpageData = await immich.getSubpageAlbums(subpageSlug, forceFresh);
const spGrid = subpageData?.subpage.grid;
const subpageName = subpageData?.subpage.name ?? subpageSlug;
const subpageName = subpageData
? subpageData.subpage.title || subpageData.subpage.name
: subpageSlug;
const images = toPhotoItems(
album.assets,
@@ -385,6 +379,7 @@ export default async function PathPage({ params, searchParams }: PathPageProps)
showGear={config.exif.camera}
proofing={proofingFor(subpageData?.subpage)}
allowMailto={config.proofing.allowMailto}
encodedMailto={encodedMailto}
downloadArchiveUrl={config.albumDownloads[album.id] ? archiveUrl(album.id) : undefined}
{...heroData}
/>
@@ -435,7 +430,15 @@ export default async function PathPage({ params, searchParams }: PathPageProps)
getCookie: (name) => cookieStore.get(name)?.value,
});
if (file.status === 'locked') {
return <PasswordGate slug={result.subpage.essayFile} title={file.title} type="journal" />;
// The subpage's own title, which the nav already shows — not the
// borrowed entry's, which the journal index hides while it is locked.
return (
<PasswordGate
slug={result.subpage.essayFile}
title={result.subpage.title || result.subpage.name}
type="journal"
/>
);
}
if (file.status === 'open') essayParsed = file.parsed;
}
@@ -453,16 +456,10 @@ export default async function PathPage({ params, searchParams }: PathPageProps)
// does, from a raw fetch, and add those photos to the page's assets.
// Their ids are encoded here because this path hands EssayView tokens.
if (essayParsed?.blocks.some((b) => b.type === 'album')) {
const byAlbum = new Map<string, typeof allAssets>();
for (const b of essayParsed.blocks) {
if (b.type !== 'album' || !b.albumId || byAlbum.has(b.albumId)) continue;
try {
byAlbum.set(b.albumId, await immich.getAlbumAssetsRaw(b.albumId));
} catch (error) {
// eslint-disable-next-line no-console
console.warn(`[essay] ${slug}: album ${b.albumId} could not be loaded:`, error);
}
}
const byAlbum = await loadAlbumBlocks(essayParsed.blocks, (albumId, error) => {
// eslint-disable-next-line no-console
console.warn(`[essay] ${slug}: album ${albumId} could not be loaded:`, error);
});
const expanded = expandAlbumBlocks(
essayParsed.blocks,
(id) => byAlbum.get(id),
@@ -551,6 +548,7 @@ export default async function PathPage({ params, searchParams }: PathPageProps)
watermark={config.watermark}
proofing={essayProofing}
allowMailto={config.proofing.allowMailto}
encodedMailto={encodedMailto}
/>
);
}
@@ -599,6 +597,7 @@ export default async function PathPage({ params, searchParams }: PathPageProps)
showGear={config.exif.camera}
proofing={proofingFor(result.subpage)}
allowMailto={config.proofing.allowMailto}
encodedMailto={encodedMailto}
downloadArchiveUrl={config.albumDownloads[album.id] ? archiveUrl(album.id) : undefined}
{...heroData}
/>
@@ -653,12 +652,22 @@ export default async function PathPage({ params, searchParams }: PathPageProps)
gridStyle={buildCoverGridStyle(result.subpage.coverGrid)}
{...(subpageIndex >= 0 ? { index: subpageIndex + 1 } : {})}
{...(nextSubpage
? { nextSubpage: { slug: nextSubpage.slug, name: nextSubpage.name } }
? {
nextSubpage: { slug: nextSubpage.slug, name: nextSubpage.title || nextSubpage.name },
}
: {})}
/>
);
}
// A content page (#722). The admin refuses a page slug that collides with a
// subpage or an album, so the order here only matters for a hand-edited file.
if (path.length === 1) {
const page = await renderContentPage(slug);
if (page === 'not-found') notFound();
if (page) return page;
}
// Otherwise treat as a standalone album slug
const album = await immich.getAlbumBySlug(slug, undefined, forceFresh);
if (!album) {
@@ -701,6 +710,7 @@ export default async function PathPage({ params, searchParams }: PathPageProps)
showGear={config.exif.camera}
proofing={proofingFor()}
allowMailto={config.proofing.allowMailto}
encodedMailto={encodedMailto}
downloadArchiveUrl={config.albumDownloads[album.id] ? archiveUrl(album.id) : undefined}
{...heroData}
/>

View File

@@ -0,0 +1,57 @@
/**
* Immich assets → the PhotoItem props the grid and lightbox render.
*
* Shared by the album routes and the client proofing page, so both render a
* photo exactly the same way.
*/
import type { ImmichAsset } from '@/lib/immich';
import { encodeAssetId } from '@/lib/tokens';
import {
assetAspectRatio,
assetCaption,
assetExifSummary,
assetPlaceholder,
downloadUrl,
exifUrl,
imageUrl,
videoUrl,
} from '@/lib/urls';
import type { PhotoItem } from './PhotoGrid';
/**
* `showExif` covers the hover overlay only, and that overlay carries camera,
* lens and focal length — so it follows the `camera` group, not the panel.
*
* `showCaption` follows the `caption` group and decides whether the Immich
* description becomes alt text; see `assetCaption`.
*/
export function toPhotoItems(
assets: ImmichAsset[],
showExif: boolean,
showCaption: boolean,
/** The album offering downloads, or undefined when it does not. */
downloadAlbumId?: string,
): PhotoItem[] {
return assets
.filter((a) => a.type === 'IMAGE' || a.type === 'VIDEO')
.map((a) => {
const ph = assetPlaceholder(a);
const exif = showExif && a.type === 'IMAGE' ? assetExifSummary(a) : undefined;
const caption = assetCaption(a, showCaption);
const isVideo = a.type === 'VIDEO';
return {
id: encodeAssetId(a.id),
type: isVideo ? 'video' : 'image',
thumbUrl: imageUrl(a.id, 'preview'),
previewUrl: imageUrl(a.id, 'preview'),
...(isVideo ? { videoUrl: videoUrl(a.id) } : {}),
exifUrl: exifUrl(a.id),
...(ph ? { blurDataURL: ph.blurDataURL, dominantColor: ph.dominantColor } : {}),
...(exif ?? {}),
...(caption ? { caption } : {}),
...(downloadAlbumId ? { downloadUrl: downloadUrl(downloadAlbumId, a.id) } : {}),
aspectRatio: assetAspectRatio(a),
};
});
}