Code Viewer
Introduction
Section titled “Introduction”Displays read-only code with line numbers, syntax highlighting, highlighted lines, a wrap toggle, and a copy button, or a diff of two texts in a unified or side-by-side view. Highlighting covers TypeScript, JavaScript, JSON, HTML, CSS, SQL, Bash, and Markdown through a small tokenizer in the repository that produces text nodes with classes (never HTML). The diff is computed in the repository with Myers’ algorithm. Files above 400 rows are virtualized, so a 10,000-line file stays fast.
- Eight languagesTypeScript, JavaScript, JSON, HTML, CSS, SQL, Bash, and Markdown, highlighted by an in-repo tokenizer that only creates text nodes.
- Diff built inUnified or side-by-side views from a Myers line diff, with Added and Removed spoken, not just colored.
- 10,000 linesLarge files are virtualized; only the rows in view are in the DOM, and wrapped rows are measured as they render.
- Copy and wrapOne-click copy with an announced result, a wrap toggle, highlighted lines, and pinned line numbers.
- Themed tokensEvery token color is a theme token that passes the contrast gate on code, added, removed, and highlighted lines.
Use it for
- Showing source code, configuration, JSON exports, or SQL to read and copy.
- Reviewing changes between two versions of a text, such as a policy or a configuration file.
- Documentation and support pages with copyable snippets.
Use something else for
- Editing code: use a text area or a dedicated editor.
- Short inline code in a sentence: use the Typography Code element.
- Rich formatted documents: use Prose or the Rich Text Editor.
Anatomy
<div class="aui-code-viewer aui-code-viewer--numbers"> <div class="aui-code-viewer__toolbar"> <div class="aui-code-viewer__meta"> <span class="aui-code-viewer__filename">leave.ts</span> <span class="aui-code-viewer__language">TypeScript</span> <span class="aui-code-viewer__stats" hidden></span> (diff counts) </div> <div class="aui-code-viewer__actions"> <div class="aui-code-viewer__modes" role="group" aria-label="Diff view" hidden> <button aria-pressed="true">Unified</button><button aria-pressed="false">Side by side</button> </div> <button class="aui-button" aria-pressed="false">Wrap lines</button> <button class="aui-button" aria-label="Copy code">Copy</button> </div> </div> <div class="aui-code-viewer__viewport" role="region" aria-label="Leave request handler" tabindex="0" aria-describedby="...-summary"> <div class="aui-code-viewer__head" aria-hidden="true" hidden></div> (side-by-side headings) <div class="aui-code-viewer__canvas" dir="ltr"> <div class="aui-code-viewer__row aui-code-viewer__line"> <span class="aui-code-viewer__num" aria-hidden="true">1</span> <span class="aui-code-viewer__code"><span class="aui-code-viewer__t aui-code-viewer__t--keyword">export</span> ...</span> </div> </div> </div> <span class="aui-visually-hidden aui-code-viewer__summary">4 lines, TypeScript</span></div>Live example
Section titled “Live example”Use the bar above each frame to switch theme, density, direction, and locale.
Code Viewer in the Document center showcase
Section titled “Code Viewer in the Document center showcase”The part of the Document center showcase that uses Code 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' });Highlighted TypeScript with line highlights
Section titled “Highlighted TypeScript with line highlights”import { CodeViewer, type CodeViewerCopyDetail } from '@absoluteui/components/code-viewer';
const host = document.createElement('div');document.body.append(host);CodeViewer.create(host, { label: 'Leave request handler', filename: 'leave.ts', language: 'typescript', code: "export async function requestLeave(days: number): Promise<void> {\n if (days <= 0) throw new Error('days must be positive');\n await submit({ days });\n}\n", highlightLines: [2],});host.addEventListener('aui-copy', (event) => { host.dataset.copied = String((event as CustomEvent<CodeViewerCopyDetail>).detail.text.length);});Side-by-side diff of two JSON exports
Section titled “Side-by-side diff of two JSON exports”import { CodeViewer, type CodeViewerChangeDetail } from '@absoluteui/components/code-viewer';
const host = document.createElement('div');document.body.append(host);const viewer = CodeViewer.create(host, { label: 'Policy changes', language: 'json', diff: { original: '{\n "annualLeave": 20,\n "carryOver": 5\n}', modified: '{\n "annualLeave": 22,\n "carryOver": 5,\n "sabbatical": true\n}', mode: 'split', },});host.addEventListener('aui-change', (event) => { host.dataset.mode = (event as CustomEvent<CodeViewerChangeDetail>).detail.mode ?? '';});viewer.scrollToLine(3);Compute a line diff without rendering
Section titled “Compute a line diff without rendering”import { diffLines } from '@absoluteui/components/code-viewer';
const changes = diffLines('a\nb\nc', 'a\nx\nc');const summary = changes.filter((line) => line.op !== 'equal').map((line) => `${line.op} ${line.text}`);document.body.dataset.changes = summary.join(', ');Install and start
Section titled “Install and start”npm install @absoluteui/components @absoluteui/core @absoluteui/themeRegistry setup, the theme stylesheet, and the Content Security Policy are covered in Installation.
import { CodeViewer } from '@absoluteui/components/code-viewer';import '@absoluteui/components/button/style.css';import '@absoluteui/components/code-viewer/style.css';First use
Section titled “First use”import { CodeViewer } from '@absoluteui/components/code-viewer';import '@absoluteui/components/button/style.css';import '@absoluteui/components/code-viewer/style.css';
const host = document.querySelector<HTMLElement>('#policy-diff');if (host) { CodeViewer.create(host, { label: 'Leave policy changes', language: 'markdown', diff: { original: '# Leave\n20 days per year', modified: '# Leave\n22 days per year\nCarry over 5 days', mode: 'unified' }, });}More usage
import { CodeViewer } from '@absoluteui/components/code-viewer';
const host = document.querySelector<HTMLElement>('#export');if (host) { const viewer = CodeViewer.create(host, { label: 'Employee export', language: 'json', code: JSON.stringify({ id: 42, name: 'Ada' }, null, 2) }); viewer.update({ highlightLines: [3] });}Using Angular? See Code Viewer for Angular.
API reference
Section titled “API reference”Factory
Section titled “Factory”CodeViewer.create(host: HTMLElement, options: CodeViewerOptions): CodeViewerGlobal configuration key: codeViewer (see Configuration).
Options
Section titled “Options”| Option | Type | Default | Description |
|---|---|---|---|
label |
string |
Accessible name of the code region. Required. | |
code |
string |
"''" |
Source text (ignored when diff is set). |
diff |
CodeViewerDiff | null |
"null" |
Show a diff: { original, modified, mode?: ‘unified’ | ‘split’, originalLabel?, modifiedLabel?, ignoreWhitespace? }. |
language |
CodeLanguage |
"plain" |
‘typescript’ | ‘javascript’ | ‘json’ | ‘html’ | ‘css’ | ‘sql’ | ‘bash’ | ‘markdown’ | ‘plain’. |
filename |
string |
File name shown in the toolbar. | |
startLine |
number |
"1" |
Number of the first line (code view). |
highlightLines |
readonly CodeViewerLineRange[] |
"[]" |
Line numbers or [from, to] ranges to highlight (modified line numbers in a diff). |
toolbar |
boolean |
"true" |
Show the toolbar (file name, language, actions). |
copyable |
boolean |
"true" |
Show the copy button. |
wrapToggle |
boolean |
"true" |
Show the wrap toggle. |
maxHeight |
string | null |
"30rem" |
Maximum block size of the scroll area (CSS length), or null to grow with the content (no virtualization). |
icons |
Partial<CodeViewerIcons> |
Toolbar icons: copy, copied, unified, split. | |
lineNumbers |
boolean |
"true" |
Show line numbers. Globally configurable. |
wrap |
boolean |
"false" |
Wrap long lines (the side-by-side diff always wraps). Globally configurable. |
tabSize |
number |
"2" |
Width of a tab character in spaces (1 to 16). Globally configurable. |
locale |
string |
"en-US" |
Locale of messages and counts. Globally configurable. Inherited from common configuration. |
density |
'compact' | 'comfortable' | 'spacious' |
"comfortable" |
Line and toolbar spacing. Globally configurable. Inherited from common configuration. |
Properties
Section titled “Properties”| Property | Type | Description |
|---|---|---|
host |
HTMLElement |
The host element. |
options |
Readonly<CodeViewerOptions> |
Current options. |
wrap |
boolean |
Whether long lines wrap. |
mode |
CodeViewerDiffMode | null |
The diff mode, or null for plain code. |
diff |
DiffLine[] | null |
The computed diff lines (null outside diff mode). |
text |
string |
The text the copy button writes (the code, or the modified text of a diff). |
rowCount |
number |
Total number of rows. |
renderedRowCount |
number |
Rows currently in the DOM (all rows unless virtualized). |
Methods
Section titled “Methods”| Method | Description |
|---|---|
update(options: Partial<CodeViewerOptions>): void |
Merge and apply options. |
scrollToLine(line: number, align?: 'auto' | 'start' | 'center' | 'end'): void |
Scroll a displayed line number (modified side in a diff) into view. |
copy(): Promise<boolean> |
Copy the text to the clipboard; resolves false when the clipboard refused. |
destroy(): void |
Remove rendering, buttons, observers, and listeners. |
Events
Section titled “Events”| Event | Detail | Bubbles | Cancelable | Description |
|---|---|---|---|---|
aui-copy |
CodeViewerCopyDetail |
Yes | No | The text was written to the clipboard: { text }. |
aui-change |
CodeViewerChangeDetail |
Yes | No | The user toggled wrapping or the diff mode: { wrap, mode, reason }. |
CSS classes
Section titled “CSS classes”All rules live in the aui.components cascade layer, so application styles override them without specificity battles.
| Class | Purpose |
|---|---|
aui-code-viewer |
Host. |
aui-code-viewer--wrap | --diff | --split | --virtual | --grow | --numbers |
State modifiers. |
aui-code-viewer--compact | --comfortable | --spacious |
Density. |
aui-code-viewer__toolbar |
Toolbar with file name, language, diff counts, and actions. |
aui-code-viewer__viewport |
Scrollable, focusable region (role=region). |
aui-code-viewer__row |
One row (a line, or a pair of lines side by side). |
aui-code-viewer__line |
A line; with –insert, –delete, or –highlight. |
aui-code-viewer__num |
Line number (aria-hidden). |
aui-code-viewer__code |
Line text (left to right). |
aui-code-viewer__t--<type> |
Token: keyword, string, number, comment, function, type, tag, attr, variable, punctuation, heading, emphasis, link, code. |
Icon slots
Section titled “Icon slots”| Slot | Default icon |
|---|---|
copy |
copy (icon set) |
copied |
check (icon set) |
unified |
layout-list (icon set) |
split |
layout-columns (icon set) |
Design tokens
Section titled “Design tokens”Tokens this stylesheet reads (verified in CI). Override them in a theme or with the Theme Designer.
--aui-border-width | --aui-color-border | --aui-color-error-fg | --aui-color-error-subtle | --aui-color-focus-ring | --aui-color-info-fg | --aui-color-link | --aui-color-success-fg | --aui-color-success-subtle | --aui-color-surface | --aui-color-surface-sunken | --aui-color-text | --aui-color-text-muted | --aui-color-warning-fg | --aui-color-warning-subtle | --aui-focus-ring-offset | --aui-focus-ring-width | --aui-font-family-mono | --aui-font-family-sans | --aui-font-size-sm | --aui-font-weight-semibold | --aui-line-height-normal | --aui-radius-md | --aui-space-1 | --aui-space-2 | --aui-space-3 | --aui-space-4
TypeScript definitions
type CodeLanguage = 'typescript' | 'javascript' | 'json' | 'html' | 'css' | 'sql' | 'bash' | 'markdown' | 'plain';type CodeViewerDiffMode = 'unified' | 'split';type CodeViewerLineRange = number | readonly [number, number];interface CodeViewerConfig { lineNumbers: boolean; wrap: boolean; tabSize: number }interface CodeViewerDiff { original: string; modified: string; mode?: CodeViewerDiffMode; originalLabel?: string; modifiedLabel?: string; ignoreWhitespace?: boolean }interface CodeViewerIcons { copy: IconRef; copied: IconRef; unified: IconRef; split: IconRef }interface CodeViewerOptions extends Partial<CodeViewerConfig> { label: string; code?: string; diff?: CodeViewerDiff | null; language?: CodeLanguage; filename?: string; startLine?: number; highlightLines?: readonly CodeViewerLineRange[]; toolbar?: boolean; copyable?: boolean; wrapToggle?: boolean; maxHeight?: string | null; locale?: string; density?: Density; icons?: Partial<CodeViewerIcons>;}interface CodeViewerCopyDetail { text: string }interface CodeViewerChangeDetail { wrap: boolean; mode: CodeViewerDiffMode | null; reason: 'wrap' | 'mode' }type DiffOp = 'equal' | 'insert' | 'delete';interface DiffLine { op: DiffOp; text: string; originalLine: number | null; modifiedLine: number | null }interface DiffOptions { maxEdits?: number; ignoreWhitespace?: boolean }function diffLines(original: string, modified: string, options?: DiffOptions): DiffLine[];Accessibility and performance
Section titled “Accessibility and performance”Accessibility
Section titled “Accessibility”Pattern: A focusable, named scroll region (role=region) containing the code as text; toolbar actions are native toggle and push buttons.
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.
Keyboard
Section titled “Keyboard”| Key | Context | Action |
|---|---|---|
| Tab | Code Viewer | Toolbar buttons, then the code region. |
| Arrow keys / Page Up / Page Down / Home / End | Code region | Scroll the code (native scrolling of the focused region). |
| Enter / Space | Toolbar button | Toggle wrapping, switch the diff mode, or copy. |
| Element | Role |
|---|---|
| viewport | region (named by label, described by the line count and language or the diff counts) |
| diff mode buttons | group of toggle buttons (aria-pressed) |
| wrap | toggle button (aria-pressed) |
| copy | button |
ARIA attributes
Section titled “ARIA attributes”| Attribute | Element | Value |
|---|---|---|
aria-label |
viewport | the label option |
aria-describedby |
viewport | visually hidden summary: ‘120 lines, TypeScript’ or ‘3 added, 2 removed, JSON’ |
aria-hidden |
line numbers, diff markers, side-by-side headings | true (the line text carries the meaning) |
aria-pressed |
wrap and diff mode buttons | true | false |
The region is focusable (tabindex=0) so keyboard users can scroll it; toggling options keeps focus on the button.
WCAG 2.2 success criteria addressed
Section titled “WCAG 2.2 success criteria addressed”| Criterion | Level | Note |
|---|---|---|
| 1.3.1 Info and Relationships | A | |
| 1.4.1 Use of Color | A | |
| 1.4.3 Contrast (Minimum) | AA | |
| 1.4.10 Reflow | AA | |
| 1.4.11 Non-text Contrast | AA | |
| 2.1.1 Keyboard | A | |
| 2.4.7 Focus Visible | AA | |
| 4.1.2 Name, Role, Value | A | |
| 4.1.3 Status Messages | AA |
Automated test results: Accessibility and compliance.
Notes and known caveats
Section titled “Notes and known caveats”- Added and removed lines start with visually hidden ‘Added:’ and ‘Removed:’ text, and highlighted lines with ‘Highlighted:’, so changes are not conveyed by color alone.
- Copy results and option changes are announced in a polite live region; a refused clipboard is announced assertively.
- Line numbers are hidden from assistive technology and excluded from text selection.
- Manual screen-reader verification (NVDA, JAWS, VoiceOver) is pending.
- In virtualized files, only the rows in view are in the accessibility tree; screen-reader users read them by scrolling the region.
Performance
Section titled “Performance”| Import cost | Minified | gzip | brotli | CSS brotli |
|---|---|---|---|---|
@absoluteui/components/code-viewer |
62.6 kB | 21.3 kB | 18.9 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 |
|---|---|
| CodeViewer.create with a 10,000-line TypeScript file (tokenize and first render) | < 400 ms in headless Chromium |
| diffLines over two 10,000-line texts with a few changes | < 50 ms |
| Rendered rows above 400 lines | visible rows + 2 x 20 overscan |
Tested scale: 10,000 lines (code and diff); up to 100,000 lines. The diff search is capped at 2,000 edits, beyond which the changed middle is shown as one deletion and one insertion.
Tokenizing is linear in the text length (about 150 ms for 10,000 TypeScript lines). The diff trims the common prefix and suffix and runs Myers’ algorithm on the rest, capped at 2,000 edits. Above 400 rows, only visible rows plus 20 overscan rows on each side are rendered on the shared windowing engine; wrapped rows are measured as they render.
Measured run times: Performance.
Details
Section titled “Details”States
Code or diff (unified, side by side); wrapped or not; with or without line numbers and toolbar; highlighted lines; virtualized above 400 rows; densities.
State transitions
| From | Trigger | To |
|---|---|---|
| not wrapped | Wrap lines button | wrapped; aui-change with reason: 'wrap' |
| unified | Side by side button | side by side; aui-change with reason: 'mode' |
| idle | Copy button | copied (check icon for 2 seconds); aui-copy |
| any | update(options) |
new content or options (no event) |
Accessibility notes
- Changes are never conveyed by color alone: the text prefixes and the
+/-markers carry them. - Copy results and option changes are announced politely; a refused clipboard is announced assertively.
- Line numbers are excluded from text selection, so selected code copies cleanly.
- In virtualized files only the rows in view are in the accessibility tree.
- The e2e axe run covers three themes; manual screen-reader verification is pending.
Responsive behavior
Fills its container. Long lines scroll horizontally with pinned line numbers, or wrap; the toolbar wraps on narrow containers. The side-by-side view always wraps its two columns.
Right-to-left
The toolbar mirrors with the page direction. The code canvas is always dir="ltr", as source code is written left to right.
Theming
All colors come from component tokens over role tokens and pass the contrast gate in every theme. Forced colors render tokens in CanvasText, line numbers in GrayText, and changed and highlighted lines with a Highlight bar.
Global configuration
configureAbsoluteUI({ components: { codeViewer: { lineNumbers: true, wrap: false, tabSize: 4 } } });Component configuration
Instance lineNumbers, wrap, tabSize, locale, and density override configuration.
Icons
icons.copy (default copy), icons.copied (check), icons.unified (layout-list), and icons.split (layout-columns), all from the icon set; any IconRef works.
Security
Code is never parsed as HTML: the tokenizer returns data and the viewer creates text nodes, so markup in the code is shown, not executed. The copy button writes plain text with the asynchronous Clipboard API.
Data handling
No persistence, network access, or telemetry.
Supported data scale
10,000 lines tested; up to 100,000 lines.
Edge cases
- Empty code renders one empty line.
\r\nand\rline endings are normalized; a single trailing newline does not add a line.- Highlighted lines that do not exist are ignored; in a diff, deleted lines are never highlighted.
- When the edit distance exceeds 2,000, the changed middle shows as one deletion followed by one insertion.
scrollToLinewith a line that is not shown does nothing.
Errors
| Code | Category | Cause |
|---|---|---|
CODE_VIEWER_OPTIONS |
configuration | Blank label, non-string code, an invalid diff object, an unknown language, a negative or fractional start line, invalid highlight ranges, non-boolean toolbar flags, or an invalid maxHeight. |
CFG_INVALID_VALUE / CFG_UNKNOWN_OPTION |
configuration | Invalid or unknown configuration. |
ICON_UNKNOWN |
configuration | An icon name that is not registered. |
Invalid options throw before the host is modified; an invalid update() leaves the previous state intact.
Known limitations
- A fixed set of languages; scripts and styles embedded in HTML are plain text; JavaScript regular expression literals are not highlighted.
- The side-by-side view always wraps.
- Manual screen-reader verification is pending.
Unsupported scenarios
- Editing, folding, search inside the code, and word-level diff highlighting.
(c) 2026 Kasadara Technology Solutions Pvt Ltd. AbsoluteUI is free to use under the AbsoluteUI Free Use License; it is not open source.