Allow linking to individual images
Some checks failed
Check & deploy / validate (push) Failing after 11m6s
Check & deploy / deploy (push) Has been skipped

This commit is contained in:
Andras Schmelczer 2026-11-07 09:29:42 +00:00
commit d949e1645e
5 changed files with 287 additions and 15 deletions

View file

@ -61,6 +61,12 @@ Photo order, captions, and alt text live in `src/photo-catalog.json`. Add new so
The generated files under `src/generated/` and `public/static/photos/` are intentionally ignored because they are reproducible from the source images and catalog. The generated files under `src/generated/` and `public/static/photos/` are intentionally ignored because they are reproducible from the source images and catalog.
## Gallery Navigation
Photo selections use `#photo=<id>` links, where the ID comes from the source filename rather than its position or generated asset hash. Selecting a thumbnail or using the arrow, Home, or End keys updates the URL; thumbnails can also be copied or opened in another tab. Reloading or opening a photo link selects that photo with the slideshow paused. Back and Forward restore selections, and automatic slideshow advances replace the current URL without adding history entries. Missing or unknown IDs fall back to the first photo.
The header's Portfolio link returns to `https://schmelczer.dev/`. Without JavaScript, thumbnails still link directly to photo assets.
## Metadata ## Metadata
Source photos should not contain private EXIF/XMP/IPTC metadata. Check with: Source photos should not contain private EXIF/XMP/IPTC metadata. Check with:

View file

@ -1,5 +1,7 @@
import { expect, test } from '@playwright/test'; import { expect, test } from '@playwright/test';
test.use({ contextOptions: { reducedMotion: 'reduce' } });
test('renders the gallery and supports keyboard navigation', async ({ test('renders the gallery and supports keyboard navigation', async ({
page, page,
}) => { }) => {
@ -18,4 +20,201 @@ test('renders the gallery and supports keyboard navigation', async ({
'alt', 'alt',
firstAlt ?? '' firstAlt ?? ''
); );
const selected = page.locator('.thumbnail[aria-current="true"]');
await expect(selected).toBeFocused();
expect(new URL(page.url()).hash).toBe(
`#photo=${await selected.getAttribute('data-photo-id')}`
);
await page.keyboard.press('End');
await expect(page.locator('.thumbnail[data-order="47"]')).toHaveAttribute(
'aria-current',
'true'
);
await page.keyboard.press('ArrowRight');
await expect(page.locator('.thumbnail[data-order="1"]')).toHaveAttribute(
'aria-current',
'true'
);
await page.keyboard.press('ArrowLeft');
await expect(page.locator('.thumbnail[data-order="47"]')).toHaveAttribute(
'aria-current',
'true'
);
await page.keyboard.press('Home');
await expect(page.locator('.thumbnail[data-order="1"]')).toBeFocused();
});
test('keeps a selected photo on reload and in a copied thumbnail link', async ({
page,
context,
}) => {
await page.emulateMedia({ reducedMotion: 'no-preference' });
await page.goto('/?ref=gallery');
const thumbnail = page.locator('.thumbnail[data-order="9"]');
const id = await thumbnail.getAttribute('data-photo-id');
const alt = await thumbnail.locator('img').getAttribute('alt');
const copiedLink = await thumbnail.evaluate(
(link: HTMLAnchorElement) => link.href
);
await thumbnail.click();
expect(page.url()).toBe(copiedLink);
expect(new URL(page.url()).search).toBe('?ref=gallery');
expect(new URL(page.url()).hash).toBe(`#photo=${id}`);
await expect(page.locator('#frame-image')).toHaveAttribute('alt', alt ?? '');
await expect(page.locator('#slideshow-toggle')).toHaveAttribute(
'aria-pressed',
'false'
);
await page.reload();
await expect(page.locator('#frame-image')).toHaveAttribute('alt', alt ?? '');
await expect(page.locator('.thumbnail[aria-current="true"]')).toHaveAttribute(
'data-photo-id',
id ?? ''
);
await expect(page.locator('#slideshow-toggle')).toHaveText('Play');
const sharedPage = await context.newPage();
await sharedPage.emulateMedia({ reducedMotion: 'no-preference' });
await sharedPage.clock.install();
await sharedPage.goto(copiedLink);
await expect(sharedPage.locator('#frame-image')).toHaveAttribute(
'alt',
alt ?? ''
);
await sharedPage.clock.fastForward(14_000);
await expect(sharedPage.locator('#frame-image')).toHaveAttribute(
'alt',
alt ?? ''
);
await expect(sharedPage.locator('#slideshow-toggle')).toHaveAttribute(
'aria-pressed',
'false'
);
await sharedPage.close();
});
test('restores photo selections with Back, Forward, and hash changes', async ({
page,
}) => {
await page.goto('/');
const first = page.locator('.thumbnail[data-order="1"]');
const later = page.locator('.thumbnail[data-order="6"]');
const last = page.locator('.thumbnail[data-order="47"]');
await later.click();
const laterUrl = page.url();
await last.click();
const lastUrl = page.url();
await page.goBack();
await expect(page).toHaveURL(laterUrl);
await expect(later).toHaveAttribute('aria-current', 'true');
await page.goBack();
expect(new URL(page.url()).hash).toBe('');
await expect(first).toHaveAttribute('aria-current', 'true');
await page.goForward();
await expect(later).toHaveAttribute('aria-current', 'true');
await page.goForward();
await expect(page).toHaveURL(lastUrl);
await expect(last).toHaveAttribute('aria-current', 'true');
const firstLink = await first.getAttribute('href');
await page.evaluate((hash) => {
window.location.hash = hash ?? '';
}, firstLink);
await expect(first).toHaveAttribute('aria-current', 'true');
await expect(page.locator('#slideshow-toggle')).toHaveText('Play');
});
test('updates slideshow links without filling browser history and still pauses', async ({
page,
}) => {
await page.emulateMedia({ reducedMotion: 'no-preference' });
await page.clock.install();
await page.goto('/');
const historyLength = await page.evaluate(() => window.history.length);
await page.clock.fastForward(7000);
const selected = page.locator('.thumbnail[aria-current="true"]');
await expect(selected).toHaveAttribute('data-order', '2');
expect(new URL(page.url()).hash).toBe(
`#photo=${await selected.getAttribute('data-photo-id')}`
);
expect(await page.evaluate(() => window.history.length)).toBe(historyLength);
await page.getByRole('button', { name: 'Pause' }).click();
const pausedUrl = page.url();
await page.clock.fastForward(14_000);
await expect(page).toHaveURL(pausedUrl);
await expect(selected).toHaveAttribute('data-order', '2');
await page.getByRole('button', { name: 'Play' }).click();
await page.clock.fastForward(7000);
await expect(selected).toHaveAttribute('data-order', '3');
expect(await page.evaluate(() => window.history.length)).toBe(historyLength);
});
test('falls back to the first photo for unknown or malformed links', async ({
page,
}) => {
for (const hash of [
'#photo=missing-photo',
'#photo=%E0%A4%A',
'#portraits',
]) {
await page.goto(`/${hash}`);
const first = page.locator('.thumbnail[data-order="1"]');
await expect(first).toHaveAttribute('aria-current', 'true');
await expect(page.locator('#frame-image')).toHaveAttribute(
'alt',
(await first.locator('img').getAttribute('alt')) ?? ''
);
await page.locator('.thumbnail[data-order="6"]').click();
await expect(
page.locator('.thumbnail[aria-current="true"]')
).toHaveAttribute('data-order', '6');
}
});
test('keeps the portfolio link and gallery usable on a narrow screen', async ({
page,
}) => {
await page.setViewportSize({ width: 320, height: 568 });
await page.goto('/');
const portfolio = page.getByRole('link', { name: 'Portfolio' });
await expect(portfolio).toBeVisible();
await expect(portfolio).toHaveAttribute('href', 'https://schmelczer.dev/');
await expect(portfolio).toBeInViewport();
await expect(page.locator('#slideshow-toggle')).toBeInViewport();
await portfolio.focus();
await expect(portfolio).toBeFocused();
await page.locator('.thumbnail[data-order="6"]').click();
await expect(page.locator('#frame-image')).toBeVisible();
await expect(
page.locator('#frame-content source[type="image/avif"]')
).toHaveAttribute('srcset', /480w.*960w/);
await expect(
page.locator('#frame-content source[type="image/webp"]')
).toHaveAttribute('sizes', /max-width: 899px/);
expect(
await page.evaluate(
() => document.documentElement.scrollWidth <= window.innerWidth
)
).toBe(true);
});
test('retains asset links and the portfolio link without JavaScript', async ({
browser,
}) => {
const context = await browser.newContext({ javaScriptEnabled: false });
const page = await context.newPage();
await page.goto('http://127.0.0.1:4173/');
await expect(page.locator('.thumbnail').first()).toHaveAttribute(
'href',
/^static\/photos\/.*\.jpg$/
);
await expect(page.locator('#frame-image')).toBeVisible();
await expect(page.getByRole('link', { name: 'Portfolio' })).toBeVisible();
await expect(page.locator('#slideshow-toggle')).toBeHidden();
await context.close();
}); });

View file

@ -80,10 +80,8 @@ img {
min-width: 0; min-width: 0;
min-height: 100dvh; min-height: 100dvh;
display: grid; display: grid;
grid-template-columns: minmax(5rem, 10vmin) minmax(0, 1fr) minmax( grid-template-columns: minmax(5rem, 10vmin) minmax(0, 1fr) minmax(7rem,
7rem, 14vmin);
14vmin
);
position: relative; position: relative;
overflow: hidden; overflow: hidden;
} }
@ -234,18 +232,21 @@ img {
} }
.site-header { .site-header {
display: flex; grid-template-columns: 1fr auto;
flex-direction: row-reverse; gap: var(--space-xs) var(--space-s);
align-items: center;
justify-content: space-around;
padding: var(--space-s); padding: var(--space-s);
} }
.slideshow-toggle { .slideshow-toggle {
position: static; position: static;
grid-column: 2;
grid-row: 2;
justify-self: end;
} }
.site-header h1 { .site-header h1 {
grid-column: 1 / -1;
grid-row: 1;
writing-mode: horizontal-tb; writing-mode: horizontal-tb;
transform: none; transform: none;
font-size: clamp(1.5rem, 7vw, 2rem); font-size: clamp(1.5rem, 7vw, 2rem);
@ -292,4 +293,4 @@ img {
grid-row: 2; grid-row: 2;
padding: var(--space-s); padding: var(--space-s);
} }
} }

View file

@ -27,6 +27,7 @@ const thumbnail = (id: string, order: number, alt: string): string => `
</a>`; </a>`;
const setup = () => { const setup = () => {
window.history.replaceState(null, '', '/');
vi.stubGlobal('matchMedia', () => ({ vi.stubGlobal('matchMedia', () => ({
matches: false, matches: false,
media: '(prefers-reduced-motion: reduce)', media: '(prefers-reduced-motion: reduce)',

View file

@ -12,8 +12,12 @@ type SelectOptions = {
readonly focusThumbnail?: boolean; readonly focusThumbnail?: boolean;
readonly pause?: boolean; readonly pause?: boolean;
readonly source?: string; readonly source?: string;
readonly updateUrl?: boolean;
}; };
const photoHash = (id: string): string =>
`#${new URLSearchParams({ photo: id })}`;
export const requiredElement = <T extends Element>( export const requiredElement = <T extends Element>(
selector: string, selector: string,
constructor: { new (...args: never[]): T } constructor: { new (...args: never[]): T }
@ -95,6 +99,12 @@ export class PhotoGallery {
throw new Error('The gallery needs at least one photo.'); throw new Error('The gallery needs at least one photo.');
} }
// Keep asset links as the no-JavaScript fallback, but let enhanced
// thumbnails be copied or opened in another tab as gallery deep links.
for (const thumbnail of this.thumbnails) {
thumbnail.href = photoHash(thumbnail.dataset.photoId ?? '');
}
// Off-screen holder that warms the next photo's image so advancing to it is // Off-screen holder that warms the next photo's image so advancing to it is
// instant; see preloadNext. // instant; see preloadNext.
this.preloadHolder.className = 'frame-preload'; this.preloadHolder.className = 'frame-preload';
@ -103,12 +113,20 @@ export class PhotoGallery {
this.addEventListeners(); this.addEventListeners();
// The frame for photo 0 is already server-rendered, so just mark the const linkedIndex = this.indexFromUrl();
// selected thumbnail; rebuilding it would discard the in-flight LCP image. if (linkedIndex > 0) {
this.updateSelectedThumbnail(0, false); this.select(linkedIndex, { updateUrl: false });
this.preloadNext(); } else {
// Preserve the server-rendered first photo and its in-flight LCP image.
this.updateSelectedThumbnail(0, false);
this.preloadNext();
}
if (this.options.autoAdvance !== false && !this.reducedMotion.matches) { if (
linkedIndex < 0 &&
this.options.autoAdvance !== false &&
!this.reducedMotion.matches
) {
this.startAutoAdvance(); this.startAutoAdvance();
} else { } else {
this.updateToggle(false); this.updateToggle(false);
@ -116,7 +134,24 @@ export class PhotoGallery {
} }
private addEventListeners(): void { private addEventListeners(): void {
window.addEventListener('hashchange', () => {
this.select(Math.max(0, this.indexFromUrl()), {
pause: true,
updateUrl: false,
});
});
this.options.gallery.addEventListener('click', (event) => { this.options.gallery.addEventListener('click', (event) => {
if (
event.button !== 0 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
) {
return;
}
const thumbnail = (event.target as Element).closest<HTMLAnchorElement>( const thumbnail = (event.target as Element).closest<HTMLAnchorElement>(
'[data-photo-id]' '[data-photo-id]'
); );
@ -193,6 +228,29 @@ export class PhotoGallery {
}); });
} }
private indexFromUrl(): number {
const id = new URLSearchParams(window.location.hash.slice(1)).get('photo');
return this.thumbnails.findIndex(
(thumbnail) => thumbnail.dataset.photoId === id
);
}
private updatePhotoUrl(id: string, recordHistory: boolean): void {
const url = new URL(window.location.href);
url.hash = photoHash(id);
if (url.href === window.location.href) {
return;
}
if (recordHistory) {
window.history.pushState(window.history.state, '', url);
} else {
// The slideshow keeps the current photo shareable without adding a
// history entry every seven seconds.
window.history.replaceState(window.history.state, '', url);
}
}
private selectById(id: string | undefined, options: SelectOptions): void { private selectById(id: string | undefined, options: SelectOptions): void {
const index = this.thumbnails.findIndex( const index = this.thumbnails.findIndex(
(thumbnail) => thumbnail.dataset.photoId === id (thumbnail) => thumbnail.dataset.photoId === id
@ -214,7 +272,7 @@ export class PhotoGallery {
// Auto-advance shows the preloaded figure instantly; a user-initiated jump // Auto-advance shows the preloaded figure instantly; a user-initiated jump
// (which carries a source) may need a download, so it gets the spinner. // (which carries a source) may need a download, so it gets the spinner.
this.showFigure(this.takeFigure(this.selectedIndex, thumbnail), { this.showFigure(this.takeFigure(this.selectedIndex, thumbnail), {
loading: options.source !== undefined, loading: options.source !== undefined || options.updateUrl === false,
}); });
this.updateSelectedThumbnail( this.updateSelectedThumbnail(
this.selectedIndex, this.selectedIndex,
@ -225,6 +283,13 @@ export class PhotoGallery {
this.pauseAutoAdvance(); this.pauseAutoAdvance();
} }
if (options.updateUrl !== false) {
this.updatePhotoUrl(
thumbnail.dataset.photoId ?? '',
options.source !== undefined
);
}
// Only user-initiated selections carry a source; auto-advance stays // Only user-initiated selections carry a source; auto-advance stays
// untracked so the slideshow doesn't flood analytics every few seconds. // untracked so the slideshow doesn't flood analytics every few seconds.
if (options.source) { if (options.source) {