Skip to content

Image Viewer

Layout and contentSince 0.13.0

Shows photos, scans, and screenshots inline or in a gallery lightbox (a modal dialog). Users zoom by wheel, pinch, buttons, and keys; pan by dragging or with arrow keys; rotate in 90 degree steps; switch between fit and actual size; move between images with previous and next or the thumbnail strip; and, with croppable, crop to an aspect ratio preset. The crop produces a canvas and a Blob (aui-crop) for the application to upload. Every image needs alt text, and image URLs are limited to safe schemes.

  • Zoom every wayWheel, pinch, buttons, and + / - keys, around the pointer; fit and actual size with 0 and 1.
  • Pan and rotateDrag or arrow keys to pan a zoomed image; R rotates in 90 degree steps.
  • Gallery or lightboxInline viewer or a modal lightbox that restores focus, with a thumbnail strip and "2 of 5".
  • Crop to a BlobAspect ratio presets, a crop area you move and resize by pointer or keyboard, and a canvas plus Blob out.
  • Safe by defaultAlt text required; only https, blob, raster data, and same-origin image URLs; CSP-safe transforms.

Use it for

  • Inspecting scanned documents, receipts, or ID photos that need zoom and rotation.
  • A gallery of attachments opened from a list or a file manager.
  • Cropping an uploaded photo (profile pictures, document scans) before saving it.

Use something else for

  • A single decorative image in content: use a plain img.
  • A slideshow of marketing content: use Carousel.
  • Editing images beyond crop and rotation (filters, drawing).
Anatomy
<div class="aui-image-viewer aui-image-viewer--inline" role="region" aria-label="Receipts"> (lightbox: <dialog class="aui-image-viewer aui-image-viewer--lightbox">)
<div class="aui-image-viewer__header">
<span class="aui-image-viewer__counter">2 of 5</span>
<div class="aui-image-viewer__toolbar" role="toolbar" aria-label="Image tools" aria-controls="stage">
<button class="aui-button aui-image-viewer__tool--previous" aria-label="Previous image">...</button>
... next, zoom out, <span class="aui-image-viewer__zoom">100%</span>, zoom in, fit or actual size,
rotate left, rotate right, crop, <a download> download, close (lightbox)
</div>
</div>
<div class="aui-image-viewer__stage" role="group" tabindex="0" aria-label="Image 2 of 5: Hotel invoice" aria-describedby="help">
<div class="aui-image-viewer__canvas"><img class="aui-image-viewer__image" alt="Hotel invoice"></div>
<div class="aui-image-viewer__status">Loading image</div>
<div class="aui-image-viewer__crop" role="group" tabindex="0" aria-label="Crop area, 640 by 480 pixels">4 handles</div>
<span class="aui-image-viewer__help">keyboard help (visually hidden)</span>
</div>
<p class="aui-image-viewer__caption">Hotel, two nights</p>
<div class="aui-image-viewer__crop-bar">aspect presets (aria-pressed), Apply crop, Cancel</div>
<div class="aui-image-viewer__thumbs" role="group" aria-label="Images">
<button class="aui-image-viewer__thumb" aria-label="Taxi receipt" aria-current="true"><img alt=""></button> ...
</div>
</div>

Use the bar above each frame to switch theme, density, direction, and locale.

Image Viewer in the Document center showcase

Section titled “Image Viewer in the Document center showcase”

The part of the Document center showcase that uses Image Viewer. Change its options, use it with the keyboard, and watch the event log; the link in the frame opens the full showcase. The bar above the frame switches theme, density, direction, and locale.

Showcase source
// Documents showcase: a document center over a simulated provider. The File Manager
// browses folders (list or grid, sort, multi-select, rename, new folder, delete, move by drag or
// cut and paste, uploads with progress); opening a photo shows it in the Image Viewer (zoom,
// rotate, crop to a Blob); opening a text or code file shows it in the Code Viewer with a diff
// against its previous version; every change is added to the Timeline of document activity; and
// a Tour walks through the page.
import { instant, type Instant } from '@absoluteui/core';
import { CodeViewer, type CodeLanguage } from '@absoluteui/components/code-viewer';
import {
FileManager,
type FileEntry,
type FileManagerCreateFolderDetail,
type FileManagerDeleteDetail,
type FileManagerErrorDetail,
type FileManagerMoveDetail,
type FileManagerOpenDetail,
type FileManagerProvider,
type FileManagerRenameDetail,
type FileManagerUploadDetail,
} from '@absoluteui/components/file-manager';
import { ImageViewer, type ImageViewerImage } from '@absoluteui/components/image-viewer';
import { Timeline, type TimelineActionDetail, type TimelineItem, type TimelineTone } from '@absoluteui/components/timeline';
import { Tour } from '@absoluteui/components/tour';
import { action, choice, createShowcase, hostIn, section, status, toggle, wait } from './kit.js';
const sc = createShowcase({
title: 'Document center',
description: 'Browse company documents, preview photos and files, compare versions, follow the activity, and take the guided tour.',
simulated: true,
});
// Simulated storage: entries, text contents with a previous version, and generated photos.
const HOUR = 3_600_000;
const now = Date.now();
const ago = (hours: number): Instant => instant(now - hours * HOUR);
function photo(color: string, label: string): string {
const canvas = document.createElement('canvas');
canvas.width = 640;
canvas.height = 400;
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.fillStyle = color;
ctx.fillRect(0, 0, 640, 400);
ctx.fillStyle = '#f8fafc';
ctx.beginPath();
ctx.arc(320, 170, 80, 0, Math.PI * 2);
ctx.fill();
ctx.fillRect(190, 270, 260, 90);
ctx.fillStyle = '#0f172a';
ctx.font = '600 28px sans-serif';
ctx.textAlign = 'center';
ctx.fillText(label, 320, 325);
}
return canvas.toDataURL('image/png');
}
interface Stored {
entry: FileEntry;
text?: string;
previous?: string;
url?: string;
}
const store = new Map<string, Stored>();
let nextId = 1;
function put(entry: Omit<FileEntry, 'id'> & { id?: string }, extra: Omit<Stored, 'entry'> = {}): FileEntry {
const id = entry.id ?? `f${String(nextId++)}`;
const full: FileEntry = { ...entry, id };
store.set(id, { entry: full, ...extra });
return full;
}
const policyBefore = '{\n "policy": "Annual leave",\n "annualDays": 25,\n "carryOverDays": 5,\n "approval": "manager"\n}\n';
const policyAfter = '{\n "policy": "Annual leave",\n "annualDays": 26,\n "carryOverDays": 5,\n "halfDays": true,\n "approval": ["manager", "hr"]\n}\n';
const exportBefore = "export async function exportEmployees(limit = 100): Promise<string> {\n const response = await fetch(`/api/employees?limit=${String(limit)}`);\n return JSON.stringify(await response.json());\n}\n";
const exportAfter = "/** Export employees as indented JSON; business days only (see the payroll calendar). */\nexport async function exportEmployees(limit = 100, signal?: AbortSignal): Promise<string> {\n const response = await fetch(`/api/employees?limit=${String(limit)}`, { signal });\n if (!response.ok) throw new Error(`Export failed: ${String(response.status)}`);\n return JSON.stringify(await response.json(), null, 2);\n}\n";
const handbook = '# Employee handbook\n\nWelcome to the company. Read the **leave policy** first.\n\n## Working hours\n\n- Core hours: 10:00 to 16:00\n- Public holidays follow the `business calendar`\n';
const handbookBefore = '# Employee handbook\n\nWelcome to the company.\n\n## Working hours\n\n- Core hours: 10:00 to 15:00\n';
put({ id: 'policies', name: 'Policies', kind: 'folder', parentId: null, hasChildren: true, modified: ago(30) });
put({ id: 'photos', name: 'Badge photos', kind: 'folder', parentId: null, hasChildren: false, modified: ago(50) });
put({ id: 'scripts', name: 'Scripts', kind: 'folder', parentId: null, hasChildren: false, modified: ago(70) });
put({ id: 'archive', name: 'Archive', kind: 'folder', parentId: null, hasChildren: false, modified: ago(900) });
put({ name: 'Employee handbook.md', kind: 'file', parentId: null, size: 18_240, mimeType: 'text/markdown', modified: ago(5) }, { text: handbook, previous: handbookBefore });
put({ id: 'leave-policy', name: 'leave-policy.json', kind: 'file', parentId: 'policies', size: 1_204, mimeType: 'application/json', modified: ago(2) }, { text: policyAfter, previous: policyBefore });
put({ name: 'travel-policy.md', kind: 'file', parentId: 'policies', size: 9_870, mimeType: 'text/markdown', modified: ago(120) }, { text: '# Travel policy\n\nBook economy for flights under six hours.\n' });
put({ id: 'remote', name: 'Remote work', kind: 'folder', parentId: 'policies', hasChildren: false, modified: ago(200) });
put({ name: 'export-employees.ts', kind: 'file', parentId: 'scripts', size: 2_310, mimeType: 'text/typescript', modified: ago(26) }, { text: exportAfter, previous: exportBefore });
put({ name: 'monthly-report.sql', kind: 'file', parentId: 'scripts', size: 640, mimeType: 'application/sql', modified: ago(300) }, { text: "SELECT department, COUNT(*) AS headcount\nFROM employees\nWHERE status = 'active'\nGROUP BY department\nORDER BY headcount DESC;\n" });
const PEOPLE: readonly [string, string][] = [
['Ada Lovelace', '#1d4ed8'],
['Grace Hopper', '#15803d'],
['Alan Turing', '#b45309'],
['Katherine Johnson', '#7c3aed'],
];
for (const [index, [person, color]] of PEOPLE.entries()) {
put({ name: `${person}.png`, kind: 'file', parentId: 'photos', size: 48_000 + index * 3_100, mimeType: 'image/png', modified: ago(48 + index) }, { url: photo(color, person) });
}
const children = (parentId: string | null): FileEntry[] => [...store.values()].map((s) => s.entry).filter((e) => e.parentId === parentId);
const latency = (): number => 180 + Math.round(Math.random() * 220);
function stored(id: string): Stored {
const s = store.get(id);
if (!s) throw new Error('The file no longer exists.');
return s;
}
function withChildren(id: string | null): void {
if (id === null) return;
const s = store.get(id);
if (s) s.entry = { ...s.entry, hasChildren: children(id).some((e) => e.kind === 'folder') };
}
const provider: FileManagerProvider = {
async list(folderId, { signal }) {
await wait(latency(), signal);
return children(folderId);
},
async createFolder(parentId, name, { signal }) {
await wait(latency(), signal);
const entry = put({ name, kind: 'folder', parentId, hasChildren: false, modified: instant(Date.now()) });
withChildren(parentId);
return entry;
},
async rename(entry, name, { signal }) {
await wait(latency(), signal);
const s = stored(entry.id);
s.entry = { ...s.entry, name, modified: instant(Date.now()) };
return s.entry;
},
async move(entries, targetFolderId, { signal }) {
await wait(latency(), signal);
const sources = new Set(entries.map((e) => e.parentId));
const moved = entries.map((e) => {
const s = stored(e.id);
s.entry = { ...s.entry, parentId: targetFolderId };
return s.entry;
});
for (const id of [...sources, targetFolderId]) withChildren(id);
return moved;
},
async delete(entries, { signal }) {
await wait(latency(), signal);
const remove = (id: string): void => {
for (const child of children(id)) remove(child.id);
store.delete(id);
};
for (const e of entries) remove(e.id);
for (const e of entries) withChildren(e.parentId);
},
async upload(folderId, file, { signal, onProgress }) {
// Simulated transfer: ten steps; names starting with "fail" are rejected by the "server".
for (let step = 1; step <= 10; step++) {
await wait(120, signal);
onProgress(Math.round((file.size * step) / 10), file.size);
}
if (file.name.toLowerCase().startsWith('fail')) throw new Error('The server rejected the file.');
const text = /\.(?:ts|js|json|md|txt|sql|css|html|sh)$/i.test(file.name) ? await file.text() : undefined;
return put({ name: file.name, kind: 'file', parentId: folderId, size: file.size, mimeType: file.type, modified: instant(Date.now()) }, text === undefined ? {} : { text });
},
async getUrl(entry, { signal }) {
await wait(120, signal);
const url = stored(entry.id).url;
if (url === undefined) throw new Error('This file has no preview.');
return url;
},
async read(entry, { signal }) {
await wait(120, signal);
return stored(entry.id).text ?? '';
},
};
// Activity timeline: seeded history plus live entries from the File Manager.
const activity: TimelineItem[] = [
{ id: 'a1', title: 'Leave policy updated', description: '26 annual days, half days allowed, HR approval added.', tone: 'success', status: 'Published', time: ago(2), avatar: { name: 'Grace Hopper' }, actions: [{ id: 'compare', label: 'Compare versions' }] },
{ id: 'a2', title: 'Handbook edited', description: 'Core hours extended to 16:00.', tone: 'info', time: ago(5), avatar: { name: 'Ada Lovelace' }, actions: [{ id: 'compare', label: 'Compare versions' }] },
{ id: 'a3', title: 'Export script reviewed', tone: 'neutral', time: ago(26), avatar: { name: 'Alan Turing' } },
{ id: 'a4', title: 'Badge photos uploaded', description: 'Four photos for new starters.', tone: 'success', time: ago(48), avatar: { name: 'Katherine Johnson' } },
{ id: 'a5', title: 'Virus scan blocked an upload', description: 'invoice.pdf.exe was quarantined.', tone: 'error', status: 'Blocked', time: ago(52) },
];
let olderPages = 2;
let activityId = 100;
// Layout: files, then the two previews, then activity.
const filesSection = section(sc, 'Files', ['file-manager', 'tour']);
const fm = FileManager.create(hostIn(filesSection), {
label: 'Company documents',
root: { id: null, label: 'Documents' },
provider,
height: '30rem',
maxFileSize: 5_000_000,
});
const fmStatus = status(filesSection);
fmStatus.textContent = 'Open a photo or a file (Enter or double click) to preview it.';
sc.listen(fm.host, ['aui-navigate', 'aui-change', 'aui-open', 'aui-create-folder', 'aui-rename', 'aui-move', 'aui-delete', 'aui-upload', 'aui-error'], 'file-manager');
// The tour walks every section, so every section lists it.
const previewSection = section(sc, 'Photos', ['image-viewer', 'tour']);
const images = (): ImageViewerImage[] =>
children('photos')
.filter((e) => e.mimeType?.startsWith('image/') === true)
.map((e) => ({ src: stored(e.id).url ?? '', alt: `Badge photo of ${e.name.replace(/\.png$/, '')}`, caption: e.name, downloadName: e.name }))
.filter((i) => i.src !== '');
const viewer = ImageViewer.create(hostIn(previewSection), { label: 'Badge photos', images: images(), croppable: true, aspectRatios: [{ label: 'Badge (1:1)', value: 1 }, { label: '4:3', value: 4 / 3 }, { label: 'Free', value: null }] });
sc.listen(viewer.host, ['aui-change', 'aui-zoom', 'aui-rotate', 'aui-crop', 'aui-error'], 'image-viewer');
const LANGUAGES: Readonly<Record<string, CodeLanguage>> = { json: 'json', ts: 'typescript', js: 'javascript', md: 'markdown', sql: 'sql', css: 'css', html: 'html', sh: 'bash' };
const languageOf = (name: string): CodeLanguage => LANGUAGES[name.split('.').pop()?.toLowerCase() ?? ''] ?? 'plain';
let diffMode: 'unified' | 'split' = 'unified';
let showDiff = true;
let current = stored('leave-policy');
const codeSection = section(sc, 'File preview', ['code-viewer', 'tour']);
const code = CodeViewer.create(hostIn(codeSection), { label: 'File preview', filename: current.entry.name, language: 'json', diff: { original: policyBefore, modified: policyAfter, mode: diffMode, originalLabel: 'Previous version', modifiedLabel: 'Current version' } });
sc.listen(code.host, ['aui-copy', 'aui-change'], 'code-viewer');
function showCode(s: Stored): void {
current = s;
const text = s.text ?? '';
const language = languageOf(s.entry.name);
if (showDiff && s.previous !== undefined) code.update({ filename: s.entry.name, language, code: '', diff: { original: s.previous, modified: text, mode: diffMode, originalLabel: 'Previous version', modifiedLabel: 'Current version' } });
else code.update({ filename: s.entry.name, language, diff: null, code: text });
}
fm.host.addEventListener('aui-open', (event) => {
const { entry } = (event as CustomEvent<FileManagerOpenDetail>).detail;
const s = store.get(entry.id);
if (!s) return;
// The page shows previews inline instead of the File Manager's dialog, unless the preview
// section is hidden (the File Manager's focus view on a component page).
const inline = s.url !== undefined ? !previewSection.hidden : s.text !== undefined && !codeSection.hidden;
if (!inline) return;
event.preventDefault();
if (s.url !== undefined) {
const list = images();
viewer.update({ images: list, index: Math.max(0, list.findIndex((i) => i.caption === entry.name)) });
fmStatus.textContent = `Showing ${entry.name} in the image viewer.`;
viewer.host.scrollIntoView({ block: 'nearest' });
} else if (s.text !== undefined) {
showCode(s);
fmStatus.textContent = s.previous === undefined ? `Showing ${entry.name}.` : `Showing the changes to ${entry.name}.`;
code.host.scrollIntoView({ block: 'nearest' });
}
});
const activitySection = section(sc, 'Activity', ['timeline', 'tour']);
const timeline = Timeline.create(hostIn(activitySection), {
label: 'Document activity',
items: activity,
initialVisible: 4,
hasMore: true,
loadMore: async ({ signal }) => {
await wait(500, signal);
olderPages--;
const base = 24 * (6 + (2 - olderPages) * 3);
return [
{ id: `old-${String(olderPages)}-1`, title: 'Contract template replaced', tone: 'info', time: ago(base), avatar: { name: 'Ada Lovelace' } },
{ id: `old-${String(olderPages)}-2`, title: 'Archive folder cleaned up', tone: 'warning', description: '12 files older than seven years removed.', time: ago(base + 30) },
];
},
});
sc.listen(timeline.host, ['aui-action', 'aui-toggle', 'aui-load-more', 'aui-load-error'], 'timeline');
timeline.host.addEventListener('aui-load-more', () => {
if (olderPages <= 0) timeline.update({ hasMore: false });
});
timeline.host.addEventListener('aui-action', (event) => {
const { item } = (event as CustomEvent<TimelineActionDetail>).detail;
const target = item.id === 'a2' ? [...store.values()].find((s) => s.entry.name === 'Employee handbook.md') : stored('leave-policy');
if (target) {
showDiff = true;
showCode(target);
code.host.scrollIntoView({ block: 'nearest' });
}
});
function record(title: string, tone: TimelineTone, description?: string): void {
activity.unshift({ id: `live-${String(activityId++)}`, title, tone, time: instant(Date.now()), avatar: { name: 'You' }, ...(description === undefined ? {} : { description }) });
timeline.update({ items: [...activity] });
}
const names = (list: readonly FileEntry[]): string => list.map((e) => e.name).join(', ');
fm.host.addEventListener('aui-create-folder', (e) => {
record('Folder created', 'success', (e as CustomEvent<FileManagerCreateFolderDetail>).detail.entry.name);
});
fm.host.addEventListener('aui-rename', (e) => {
const d = (e as CustomEvent<FileManagerRenameDetail>).detail;
record('Renamed', 'info', `${d.previousName} to ${d.entry.name}`);
});
fm.host.addEventListener('aui-move', (e) => {
record('Moved', 'info', names((e as CustomEvent<FileManagerMoveDetail>).detail.entries));
});
fm.host.addEventListener('aui-delete', (e) => {
record('Deleted', 'warning', names((e as CustomEvent<FileManagerDeleteDetail>).detail.entries));
});
fm.host.addEventListener('aui-upload', (e) => {
record('Uploaded', 'success', (e as CustomEvent<FileManagerUploadDetail>).detail.entry.name);
});
fm.host.addEventListener('aui-error', (e) => {
const d = (e as CustomEvent<FileManagerErrorDetail>).detail;
record(`Failed: ${d.operation}`, 'error', d.error instanceof Error ? d.error.message : undefined);
});
// Guided tour of the page.
const tour = Tour.create(hostIn(filesSection), {
dots: true,
steps: [
{ id: 'welcome', title: 'Welcome to the document center', content: 'A short tour: files, previews, and activity. Press Escape to leave at any time.' },
{ id: 'toolbar', title: 'File actions', content: 'Create folders, upload, rename, delete, cut and paste, sort, and switch between list and grid.', target: () => fm.host.querySelector('[role="toolbar"]'), placement: 'bottom-start' },
{ id: 'folders', title: 'Folders', content: 'Browse the folder tree; drop files on a folder to move them.', target: () => fm.host.querySelector('.aui-file-manager__folders'), placement: 'right' },
{ id: 'photos', title: 'Photo viewer', content: 'Zoom, rotate, and crop badge photos to a square.', target: () => viewer.host, placement: 'top' },
{ id: 'code', title: 'Compare versions', content: 'See what changed in a file, unified or side by side.', target: () => code.host, placement: 'top' },
{ id: 'activity', title: 'Activity', content: 'Every change you make is added here, grouped by day.', target: () => timeline.host, placement: 'top' },
],
});
sc.listen(tour.host, ['aui-start', 'aui-step-change', 'aui-step-missing', 'aui-finish', 'aui-skip'], 'tour');
// Options.
action(sc, 'Start tour', () => {
void tour.start();
}, ['tour']);
choice(sc, 'View', [{ value: 'list', label: 'List' }, { value: 'grid', label: 'Grid' }], 'list', (view) => {
fm.update({ view });
}, ['file-manager']);
toggle(sc, 'Folder pane', true, (checked) => {
fm.update({ showFolderPane: checked });
}, ['file-manager']);
toggle(sc, 'Read-only', false, (checked) => {
fm.update({ readOnly: checked });
}, ['file-manager']);
toggle(sc, 'Show changes', true, (checked) => {
showDiff = checked;
showCode(current);
}, ['code-viewer']);
choice(sc, 'Diff layout', [{ value: 'unified', label: 'Unified' }, { value: 'split', label: 'Side by side' }], 'unified', (mode) => {
diffMode = mode;
showCode(current);
}, ['code-viewer']);
choice(sc, 'Timeline layout', [{ value: 'start', label: 'Start' }, { value: 'alternate', label: 'Alternate' }], 'start', (layout) => {
timeline.update({ layout });
}, ['timeline']);
choice(sc, 'Times', [{ value: 'relative', label: 'Relative' }, { value: 'absolute', label: 'Absolute' }], 'relative', (timeFormat) => {
timeline.update({ timeFormat });
}, ['timeline']);
timeline.update({ timeFormat: 'relative' });
import { ImageViewer, type ImageViewerChangeDetail } from '@absoluteui/components/image-viewer';
const host = document.createElement('div');
document.body.append(host);
const viewer = ImageViewer.create(host, {
label: 'Expense receipts',
images: [
{ src: '/images/receipts-taxi.png', alt: 'Taxi receipt, 42 euros, 3 March', caption: 'Taxi to the airport' },
{ src: '/images/receipts-hotel.png', alt: 'Hotel invoice, two nights', downloadName: 'hotel-invoice.jpg' },
],
});
host.addEventListener('aui-change', (event) => {
host.dataset.shown = String((event as CustomEvent<ImageViewerChangeDetail>).detail.index);
});
viewer.zoomIn();
import { ImageViewer, type ImageViewerCropDetail } from '@absoluteui/components/image-viewer';
const trigger = document.createElement('button');
trigger.textContent = 'Edit photo';
const host = document.createElement('div');
document.body.append(trigger, host);
const viewer = ImageViewer.create(host, {
label: 'Profile photo',
mode: 'lightbox',
croppable: true,
images: [{ src: '/images/people-ada.png', alt: 'Ada Lovelace smiling' }],
crossOrigin: 'anonymous',
cropType: 'image/jpeg',
cropQuality: 0.9,
});
trigger.addEventListener('click', () => {
viewer.open(0);
});
host.addEventListener('aui-crop', (event) => {
const { blob, rect } = (event as CustomEvent<ImageViewerCropDetail>).detail;
host.dataset.size = `${String(rect.width)}x${String(rect.height)} ${String(blob.size)} bytes`;
viewer.close();
});
Terminal window
npm install @absoluteui/components @absoluteui/core @absoluteui/theme

Registry setup, the theme stylesheet, and the Content Security Policy are covered in Installation.

import { ImageViewer } from '@absoluteui/components/image-viewer';
import '@absoluteui/components/button/style.css';
import '@absoluteui/components/image-viewer/style.css';
import { ImageViewer } from '@absoluteui/components/image-viewer';
import '@absoluteui/components/button/style.css';
import '@absoluteui/components/image-viewer/style.css';
const host = document.querySelector<HTMLElement>('#gallery');
const open = document.querySelector<HTMLButtonElement>('#open-gallery');
if (host && open) {
const viewer = ImageViewer.create(host, {
label: 'Office photos',
mode: 'lightbox',
images: [
{ src: '/images/office-lobby.png', alt: 'Lobby with reception desk', caption: 'Lobby' },
{ src: '/images/office-kitchen.png', alt: 'Shared kitchen with long table', caption: 'Kitchen' },
],
});
open.addEventListener('click', () => {
viewer.open(0);
});
}
More usage
import { ImageViewer } from '@absoluteui/components/image-viewer';
const host = document.querySelector<HTMLElement>('#scan');
if (host) {
const viewer = ImageViewer.create(host, {
label: 'Passport scan',
croppable: true,
aspectRatios: [{ label: 'Photo page', value: 125 / 88 }, { label: 'Free', value: null }],
images: [{ src: '/files/passport.jpg', alt: 'Passport photo page of Ada Lovelace' }],
});
host.addEventListener('aui-crop', () => {
viewer.fit();
});
}

Using Angular? See Image Viewer for Angular.

ImageViewer.create(host: HTMLElement, options: ImageViewerOptions): ImageViewer

Global configuration key: imageViewer (see Configuration).

Option Type Default Description
label string Accessible name of the viewer (region or dialog). Required.
images readonly ImageViewerImage[] One or more images { src, alt, decorative?, caption?, thumbnail?, width?, height?, downloadName? }. Required.
mode 'inline' | 'lightbox' "inline" inline renders into the host; lightbox renders a modal dialog opened with open(). Set at creation only.
index number "0" Shown image.
loop boolean "false" Previous and next wrap around.
croppable boolean "false" Show the Crop tool.
aspectRatios readonly ImageViewerAspectRatio[] "Free, 1:1, 4:3, 16:9, 3:2" Crop presets { label, value: width / height | null }.
cropType 'image/png' | 'image/jpeg' | 'image/webp' "image/png" Blob type of the crop output.
cropQuality number Quality from 0 to 1 for JPEG and WebP output.
crossOrigin 'anonymous' | 'use-credentials' | null "null" CORS mode of the image request; needed to crop cross-origin images.
wheelZoom 'auto' | 'ctrl' | 'always' "auto" When the wheel zooms: auto is Ctrl (or a pinch gesture) inline and always in the lightbox.
icons Partial<ImageViewerIcons> Tool and error icons.
zoomStep number "1.25" Zoom factor of one step, 1.05 to 4. Globally configurable.
minZoom number "0.1" Smallest zoom, 0.01 to 1 (fit may go lower for very large images). Globally configurable.
maxZoom number "8" Largest zoom, 1 to 32. Globally configurable.
showThumbnails boolean "true" Show the thumbnail strip for two or more images. Globally configurable.
locale string "en-US" Locale of the counter, zoom level, and messages. Globally configurable. Inherited from common configuration.
Property Type Description
host HTMLElement The host element.
options Readonly<ImageViewerOptions> Current options.
index number Index of the shown image.
zoom number Current zoom (1 = actual size).
fitted boolean Whether the image is fitted to the view.
rotation number Rotation in degrees clockwise (0, 90, 180, 270).
cropping boolean Whether crop mode is active.
cropRect ImageViewerCropRect | null Crop rectangle in natural pixels of the rotated image.
isOpen boolean Lightbox: whether the dialog is open (inline: always true).
dialog HTMLDialogElement | null The lightbox dialog (null inline).
Method Description
open(index?: number): void Lightbox: open the dialog (optionally at an image). Inline: show that image.
close(): void Lightbox: close and restore focus.
show(index: number): void Show an image (clamped), fitted and unrotated.
next(): void Next image.
previous(): void Previous image.
zoomIn(): void Zoom in by one step.
zoomOut(): void Zoom out by one step.
setZoom(zoom: number): void Set the zoom, clamped to the zoom range.
fit(): void Fit the image to the view.
actualSize(): void Zoom to 100%.
rotate(degrees?: number): void Rotate by a multiple of 90 degrees (default 90, clockwise).
startCrop(aspect?: number | null): void Enter crop mode with an aspect ratio (default: the first preset).
cancelCrop(): void Leave crop mode without output.
crop(): Promise<ImageViewerCropDetail> Crop to the crop rectangle; resolves with the canvas and Blob and emits aui-crop.
update(options: Partial<ImageViewerOptions>): void Merge and apply options (mode is create-only).
destroy(): void Close, remove rendering, buttons, and listeners.
Event Detail Bubbles Cancelable Description
aui-change ImageViewerChangeDetail Yes No The shown image changed: { index, image }.
aui-zoom ImageViewerZoomDetail Yes No The zoom changed: { zoom, fit }.
aui-rotate ImageViewerRotateDetail Yes No The image was rotated: { rotation, index }.
aui-crop ImageViewerCropDetail Yes No A crop was applied: { blob, canvas, rect, rotation, index, image }.
aui-error ImageViewerErrorDetail Yes No An image failed to load, or a crop was refused (tainted canvas): { index, image, reason, message }.
aui-open ImageViewerOpenDetail Yes No Lightbox opened: { index }.
aui-close ImageViewerOpenDetail Yes No Lightbox closed: { index }.

All rules live in the aui.components cascade layer, so application styles override them without specificity battles.

Class Purpose
aui-image-viewer The viewer (host inline, dialog in the lightbox).
aui-image-viewer--inline | --lightbox Mode.
aui-image-viewer--zoomed | --cropping Zoomed past fit; crop mode.
aui-image-viewer-host Host of a lightbox viewer (left empty).
aui-image-viewer__header Counter and toolbar.
aui-image-viewer__counter ‘2 of 5’.
aui-image-viewer__toolbar Tools (role=toolbar).
aui-image-viewer__tool--<name> One tool: previous, next, zoomOut, zoomIn, fitToggle, rotateLeft, rotateRight, crop, download, close.
aui-image-viewer__zoom Zoom percentage.
aui-image-viewer__stage Focusable image area; height from –aui-image-viewer-height inline.
aui-image-viewer__canvas Transformed wrapper of the image.
aui-image-viewer__image The img.
aui-image-viewer__status Loading and error state (–error).
aui-image-viewer__crop Crop area with four handles (__handle–nw|ne|sw|se).
aui-image-viewer__caption Caption.
aui-image-viewer__crop-bar Aspect presets (__aspect) and apply / cancel (__apply, __cancel).
aui-image-viewer__thumbs Thumbnail strip (__thumb buttons).
Slot Default icon
previous chevron-left
next chevron-right
zoomIn zoom-in
zoomOut zoom-out
fit minimize
actualSize maximize
rotate rotate (mirrored for rotate left)
crop crop
download download
close close
error image-off

Tokens this stylesheet reads (verified in CI). Override them in a theme or with the Theme Designer.

--aui-border-width | --aui-border-width-strong | --aui-color-backdrop | --aui-color-border | --aui-color-focus-ring | --aui-color-primary | --aui-color-surface | --aui-color-surface-sunken | --aui-color-text | --aui-color-text-muted | --aui-duration-fast | --aui-easing-standard | --aui-focus-ring-offset | --aui-focus-ring-width | --aui-font-family-sans | --aui-font-size-md | --aui-font-size-sm | --aui-icon-size-xl | --aui-line-height-normal | --aui-radius-md | --aui-radius-sm | --aui-space-1 | --aui-space-2 | --aui-space-3 | --aui-space-4

TypeScript definitions
interface ImageViewerConfig { zoomStep: number; minZoom: number; maxZoom: number; showThumbnails: boolean }
interface ImageViewerImage {
src: string;
alt: string;
decorative?: boolean;
caption?: string;
thumbnail?: string;
width?: number;
height?: number;
downloadName?: string;
}
interface ImageViewerAspectRatio { label: string; value: number | null }
type ImageViewerMode = 'inline' | 'lightbox';
type ImageViewerCropType = 'image/png' | 'image/jpeg' | 'image/webp';
interface ImageViewerOptions extends Partial<ImageViewerConfig> {
label: string;
images: readonly ImageViewerImage[];
mode?: ImageViewerMode;
index?: number;
loop?: boolean;
croppable?: boolean;
aspectRatios?: readonly ImageViewerAspectRatio[];
cropType?: ImageViewerCropType;
cropQuality?: number;
crossOrigin?: 'anonymous' | 'use-credentials' | null;
wheelZoom?: 'auto' | 'ctrl' | 'always';
locale?: string;
icons?: Partial<ImageViewerIcons>;
}
interface ImageViewerChangeDetail { index: number; image: ImageViewerImage }
interface ImageViewerZoomDetail { zoom: number; fit: boolean }
interface ImageViewerRotateDetail { rotation: number; index: number }
interface ImageViewerCropRect { x: number; y: number; width: number; height: number }
interface ImageViewerCropDetail { blob: Blob; canvas: HTMLCanvasElement; rect: ImageViewerCropRect; rotation: number; index: number; image: ImageViewerImage }
interface ImageViewerErrorDetail { index: number; image: ImageViewerImage; reason: 'load' | 'crop'; message: string }
interface ImageViewerOpenDetail { index: number }
function isSafeImageUrl(src: string, doc: Document): boolean;

Pattern: Inline: a labelled region with a toolbar (WAI-ARIA APG Toolbar), a focusable image stage, and thumbnail buttons with aria-current. Lightbox: the same content in a modal dialog (APG Dialog) that restores focus when it closes.

Checked on every docs build: the showcase passes axe (WCAG 2.2 A and AA rules) in the default, dark, and high-contrast themes and right to left; the playground loads without errors and passes axe before and after every on/off option is switched, with no Content Security Policy violations.

Key Context Action
+ / = Stage Zoom in.
- Stage Zoom out.
0 Stage Fit the image to the view.
1 Stage Actual size (100%).
R / Shift+R Stage Rotate clockwise / counter-clockwise.
ArrowLeft / ArrowRight Stage Previous / next image (mirrored in RTL); pans when zoomed in.
ArrowUp / ArrowDown Stage, zoomed in Pan.
Home / End Stage First / last image.
ArrowLeft / ArrowRight / Home / End Toolbar or thumbnails Move between tools or thumbnails.
Enter / Space Tool or thumbnail Activate the tool or show the image.
Arrow keys Crop area Move the crop area.
Shift+Arrow keys Crop area Resize the crop area (keeps the aspect ratio).
Enter Crop area Apply the crop.
Escape Crop mode / lightbox Cancel the crop; otherwise close the lightbox.
Element Role
host (inline) or dialog (lightbox) region or dialog, named by label
toolbar toolbar (roving tabindex)
stage group, named ‘Image 2 of 5: alt text’, described by the keyboard help
image img with the image’s alt text
thumbnails group of buttons named by alt text; the current one has aria-current=true
crop area group, named with its size, described by the crop keyboard help
Attribute Element Value
aria-label host or dialog label option
aria-controls toolbar the stage id
aria-describedby stage and crop area visually hidden keyboard help
aria-disabled unavailable tools true (they stay focusable in the toolbar)
aria-current current thumbnail true
aria-pressed aspect ratio buttons true for the active preset

The lightbox moves focus to the stage when it opens and returns it to the previously focused element when it closes. Starting a crop focuses the crop area; applying or cancelling returns focus to the stage.

Criterion Level Note
1.1.1 Non-text Content A
1.3.1 Info and Relationships A
1.4.3 Contrast (Minimum) AA
1.4.11 Non-text Contrast AA
2.1.1 Keyboard A
2.4.3 Focus Order A
2.4.7 Focus Visible AA
2.5.1 Pointer Gestures A
2.5.7 Dragging Movements AA
4.1.2 Name, Role, Value A
4.1.3 Status Messages AA

Automated test results: Accessibility and compliance.

  • Every image needs alt text; decorative images are announced as ‘Image n’.
  • Image changes, zoom steps, rotation, crop size changes, and load errors are announced politely.
  • Pinch and drag have single-pointer alternatives (buttons, keys, double click) for WCAG 2.5.1 and 2.5.7.
  • Manual screen-reader verification (NVDA, JAWS, VoiceOver) is pending.
Import cost Minified gzip brotli CSS brotli
@absoluteui/components/image-viewer 70.7 kB 22.9 kB 20.4 kB 1.4 kB

Measured at build time, including every AbsoluteUI module the component pulls in. No third-party runtime dependencies.

Budget (enforced in CI) Limit
ImageViewer.create with 500 images (thumbnails lazy-loaded) < 30 ms in headless Chromium
Lightbox open and fit < 16 ms (one frame) in headless Chromium
Zoom or pan step One style update of custom properties; no layout of the image

Tested scale: 500 images per viewer; images up to 8,000 by 8,000 pixels (crop canvases are limited by the browser’s canvas size).

Zoom, pan, and rotation update five custom properties on one wrapper (a compositor transform); the image is never re-laid out. Thumbnails load lazily. The crop draws once into a canvas sized to the crop rectangle.

Measured run times: Performance.

States

Inline; lightbox open or closed; loading, loaded, or load error; fitted or zoomed; rotated; cropping; a single image (no counter, navigation, or thumbnails) or a gallery.

State transitions
From Trigger To
closed (lightbox) open() open; focus on the stage; aui-open
open (lightbox) Escape, Close tool, close() closed; focus restored; aui-close
loading image loads loaded (fitted)
loading image fails error state; aui-error (load)
fitted zoom in, wheel, pinch, 1, double click zoomed; aui-zoom
zoomed 0, Fit tool, double click fitted; aui-zoom
any image previous, next, thumbnail, show() another image (fitted, unrotated); aui-change
loaded Crop tool, startCrop() cropping (fitted; zoom, pan, rotation, and navigation paused)
cropping Apply, Enter, crop() loaded; aui-crop, or aui-error (crop) when the canvas is tainted
cropping Cancel, Escape, cancelCrop() loaded
Accessibility notes
  • Alt text is required for every image; set decorative: true only for images that add nothing (they are announced as “Image n”).
  • Image changes, zoom steps, rotation, crop size changes, and load errors are announced politely.
  • Pinch and drag have single-pointer and keyboard alternatives (buttons, keys, double click) for WCAG 2.5.1 and 2.5.7.
  • The lightbox returns focus to the element that opened it.
  • The e2e axe run covers three themes; manual screen-reader verification is pending.
Responsive behavior

The stage fills the available inline size; inline, its height is --aui-image-viewer-height (default 24rem), and the lightbox fills the viewport. The toolbar and crop bar wrap, the thumbnail strip scrolls horizontally, and fit is recomputed when the stage resizes.

Right-to-left

The header, toolbar, crop bar, and thumbnails follow the writing direction; the previous and next chevrons are mirrored, and ArrowLeft shows the next image in RTL when the image is not zoomed. Image transforms (pan, rotation) are physical.

Theming

The counter, caption, status text, crop outline, current thumbnail ring, and focus indicator are in the contrast gate in every theme. Forced colors draw the crop area and the current thumbnail in Highlight. Under reduced motion (or animation: 'none'), zoom and pan apply without transition.

Global configuration
configureAbsoluteUI({ components: { imageViewer: { zoomStep: 1.5, maxZoom: 4, showThumbnails: false } } });
Component configuration

Instance zoomStep, minZoom, maxZoom, and showThumbnails override configuration; locale falls back to the common configuration.

Icons

icons: previous (chevron-left), next (chevron-right), zoomIn (zoom-in), zoomOut (zoom-out), fit (minimize), actualSize (maximize), rotate (rotate, mirrored for rotate left), crop (crop), download (download), close (close), and error (image-off). Any registered IconRef works.

Security

Image and thumbnail URLs are limited to https:, blob:, raster data:image URLs (png, jpeg, gif, webp, avif, bmp), and URLs on the document’s own origin (relative URLs, or http: on a local development origin). javascript:, file:, cross-origin http:, and data:image/svg+xml URLs throw IMAGE_VIEWER_OPTIONS. Alt text and captions are set as text. Transforms are custom properties set through the CSSOM (style.setProperty), never style attributes, so the component runs under a strict CSP. A cross-origin image can only be cropped when it is served with CORS headers and crossOrigin is set; otherwise the canvas is tainted, crop() rejects, and aui-error reports reason: 'crop'.

Data handling

No persistence, telemetry, or network access beyond loading the given images. The crop output (canvas and Blob) stays in memory for the application.

Supported data scale

500 images per viewer; images up to 8,000 by 8,000 pixels (crop canvases are limited by the browser’s maximum canvas size).

Edge cases
  • With one image, the counter, previous, next, and thumbnails are hidden.
  • An image smaller than the stage is fitted at 100% (fit never upscales).
  • width and height reserve the image size before it loads; without them the stage shows “Loading image”.
  • A failed image shows the error state with its alt text; zoom, rotation, and crop are unavailable for it.
  • Rotating keeps fit when the image was fitted; crop rectangles are in pixels of the rotated image.
  • While cropping, zoom, pan, rotation, and navigation are paused.
Errors
Code Category Cause
IMAGE_VIEWER_OPTIONS configuration Blank label, no images, an unsafe or missing src or thumbnail, missing alt text on a non-decorative image, an invalid index, aspect ratio, crop type or quality, cross-origin mode, wheel mode, minZoom above maxZoom, changing mode after creation, or an invalid setZoom, rotate, or startCrop argument.
IMAGE_VIEWER_NOT_CROPPING runtime crop() outside crop mode.
IMAGE_VIEWER_CROP runtime The canvas could not produce a Blob (a cross-origin image without CORS).
CFG_INVALID_VALUE / CFG_UNKNOWN_OPTION configuration Invalid or unknown configuration.
ICON_UNKNOWN configuration An icon names an icon that is not registered.

Invalid options throw before the host is modified; an invalid update() leaves the previous state intact.

Known limitations
  • Rotation is in steps of 90 degrees.
  • Crop rectangles are axis aligned.
  • The download link uses the download attribute, which browsers ignore for cross-origin URLs.
  • Manual screen-reader verification is pending.
Unsupported scenarios
  • SVG images and other script-capable formats.
  • Image editing beyond crop and rotation (filters, drawing, perspective correction).