General
Code Block
Usage#
import { WDS_CODE_BLOCK } from '@wds/angular/code-block';import '@wds/core/code-block/shiki' registers one built on Shiki (install shiki; grammars and themes load on demand). Without it the code is plain text. Write the code in a <pre> inside the block (escape < as <) or pass it in code.
Examples#
Default#
line-numbers numbers the lines; the header holds a title, the language of the block and a copy button.
export function delayMinutes(planned: Date, actual: Date): number {
const diff = actual.getTime() - planned.getTime();
return Math.max(0, Math.round(diff / 60_000));
}
import { Component } from '@angular/core';
import { WdsCodeBlockComponent, WdsCodeBlockCopyButtonComponent, WdsCodeBlockHeaderComponent, WdsCodeBlockLanguageComponent, WdsCodeBlockTitleComponent } from '@wds/angular/code-block';
@Component({
selector: 'app-code-block-default-demo',
imports: [WdsCodeBlockComponent, WdsCodeBlockHeaderComponent, WdsCodeBlockTitleComponent, WdsCodeBlockLanguageComponent, WdsCodeBlockCopyButtonComponent],
template: `
<div class="w-full max-w-2xl">
<wds-code-block language="ts" line-numbers>
<wds-code-block-header>
<wds-code-block-title>delay.ts</wds-code-block-title>
<wds-code-block-language></wds-code-block-language>
<wds-code-block-copy-button class="ms-auto"></wds-code-block-copy-button>
</wds-code-block-header>
<pre>
export function delayMinutes(planned: Date, actual: Date): number {{ '{' }}
const diff = actual.getTime() - planned.getTime();
return Math.max(0, Math.round(diff / 60_000));
{{ '}' }}
</pre>
</wds-code-block>
</div>
`,
})
export class CodeBlockDefaultDemo {}Pinned copy button#
const departures = await api.get('/stations/krk/departures', {
params: { limit: 20, from: new Date().toISOString() },
});
import { Component } from '@angular/core';
import { WdsCodeBlockComponent, WdsCodeBlockCopyButtonComponent } from '@wds/angular/code-block';
@Component({
selector: 'app-code-block-pinned-copy-demo',
imports: [WdsCodeBlockComponent, WdsCodeBlockCopyButtonComponent],
template: `
<div class="w-full max-w-2xl">
<wds-code-block language="ts">
<wds-code-block-copy-button></wds-code-block-copy-button>
<pre>
const departures = await api.get('/stations/krk/departures', {{ '{' }}
params: {{ '{' }} limit: 20, from: new Date().toISOString() {{ '}' }},
{{ '}' }});
</pre>
</wds-code-block>
</div>
`,
})
export class CodeBlockPinnedCopyDemo {}Diff#
diff-removed and diff-added take line ranges; the lines get a red or green background and a - or + mark that is not copied.
export function trainLabel(train: Train): string {
return train.number;
const prefix = train.category === 'IC' ? 'IC' : 'R';
const name = train.name ? ` ${train.name}` : '';
return `${prefix} ${train.number}${name}`;
}
import { Component } from '@angular/core';
import { WdsCodeBlockComponent, WdsCodeBlockCopyButtonComponent, WdsCodeBlockHeaderComponent, WdsCodeBlockTitleComponent } from '@wds/angular/code-block';
@Component({
selector: 'app-code-block-diff-demo',
imports: [WdsCodeBlockComponent, WdsCodeBlockHeaderComponent, WdsCodeBlockTitleComponent, WdsCodeBlockCopyButtonComponent],
template: `
<div class="w-full max-w-2xl">
<wds-code-block language="ts" line-numbers diff-removed="2" diff-added="3-5">
<wds-code-block-header>
<wds-code-block-title>train-label.ts</wds-code-block-title>
<wds-code-block-copy-button class="ms-auto"></wds-code-block-copy-button>
</wds-code-block-header>
<pre>
export function trainLabel(train: Train): string {{ '{' }}
return train.number;
const prefix = train.category === 'IC' ? 'IC' : 'R';
const name = train.name ? \` \${{ '{' }}train.name{{ '}' }}\` : '';
return \`\${{ '{' }}prefix{{ '}' }} \${{ '{' }}train.number{{ '}' }}\${{ '{' }}name{{ '}' }}\`;
{{ '}' }}
</pre>
</wds-code-block>
</div>
`,
})
export class CodeBlockDiffDemo {}Highlighted lines and words#
highlighted-lines takes ranges such as 2-4,7; highlighted-words marks words wherever they appear.
export const client = createClient({
baseUrl: 'https://api.example.com',
retries: 3,
timeoutMs: 8000,
headers: { Accept: 'application/json' },
});
import { Component } from '@angular/core';
import { WdsCodeBlockComponent, WdsCodeBlockCopyButtonComponent, WdsCodeBlockHeaderComponent, WdsCodeBlockTitleComponent } from '@wds/angular/code-block';
@Component({
selector: 'app-code-block-highlight-demo',
imports: [WdsCodeBlockComponent, WdsCodeBlockHeaderComponent, WdsCodeBlockTitleComponent, WdsCodeBlockCopyButtonComponent],
template: `
<div class="w-full max-w-2xl">
<wds-code-block language="ts" line-numbers highlighted-lines="2-4" highlighted-words="retries timeoutMs">
<wds-code-block-header>
<wds-code-block-title>client.ts</wds-code-block-title>
<wds-code-block-copy-button class="ms-auto"></wds-code-block-copy-button>
</wds-code-block-header>
<pre>
export const client = createClient({{ '{' }}
baseUrl: 'https://api.example.com',
retries: 3,
timeoutMs: 8000,
headers: {{ '{' }} Accept: 'application/json' {{ '}' }},
{{ '}' }});
</pre>
</wds-code-block>
</div>
`,
})
export class CodeBlockHighlightDemo {}Focused lines#
focused-lines dims the other lines until the pointer is over the block or the code area has keyboard focus.
export async function cancelTrain(id: string, reason: string) {
const train = await trains.find(id);
if (train.status === 'departed') throw new Error('Train already departed');
await trains.update(id, { status: 'cancelled', reason });
await notify.passengers(train, reason);
}
import { Component } from '@angular/core';
import { WdsCodeBlockComponent } from '@wds/angular/code-block';
@Component({
selector: 'app-code-block-focus-demo',
imports: [WdsCodeBlockComponent],
template: `
<div class="w-full max-w-2xl">
<wds-code-block language="ts" line-numbers focused-lines="3-4">
<pre>
export async function cancelTrain(id: string, reason: string) {{ '{' }}
const train = await trains.find(id);
if (train.status === 'departed') throw new Error('Train already departed');
await trains.update(id, {{ '{' }} status: 'cancelled', reason {{ '}' }});
await notify.passengers(train, reason);
{{ '}' }}
</pre>
</wds-code-block>
</div>
`,
})
export class CodeBlockFocusDemo {}Errors and warnings#
error-lines, warning-lines and info-lines color the lines; the header can sum them up with badges.
export function assignPlatform(train: Train, station: Station) {
const free = station.platforms.filter((p) => p.free);
return free[0].number;
const any = station.platforms as any;
// Platforms are refreshed every 30 seconds.
}
import { Component } from '@angular/core';
import { WdsCodeBlockComponent, WdsCodeBlockHeaderComponent, WdsCodeBlockTitleComponent } from '@wds/angular/code-block';
import { WdsBadgeComponent } from '@wds/angular/badge';
@Component({
selector: 'app-code-block-levels-demo',
imports: [WdsCodeBlockComponent, WdsCodeBlockHeaderComponent, WdsCodeBlockTitleComponent, WdsBadgeComponent],
template: `
<div class="w-full max-w-2xl">
<wds-code-block language="ts" line-numbers error-lines="3" warning-lines="4" info-lines="5">
<wds-code-block-header>
<wds-code-block-title>platform.ts</wds-code-block-title>
<wds-badge variant="destructive" class="ms-auto">1 error</wds-badge>
<wds-badge variant="secondary">1 warning</wds-badge>
</wds-code-block-header>
<pre>
export function assignPlatform(train: Train, station: Station) {{ '{' }}
const free = station.platforms.filter((p) => p.free);
return free[0].number;
const any = station.platforms as any;
// Platforms are refreshed every 30 seconds.
{{ '}' }}
</pre>
</wds-code-block>
</div>
`,
})
export class CodeBlockLevelsDemo {}Terminal output#
plain skips the highlighter. wds-code-block-wrap-toggle switches wrap, so long lines wrap instead of scrolling sideways.
$ pnpm build --filter @acme/timetable --filter @acme/timetable-api --filter @acme/timetable-worker
✓ @acme/timetable built in 4.1s
✓ @acme/timetable-api built in 2.7s
✓ @acme/timetable-worker built in 1.9s
import { Component } from '@angular/core';
import { WdsCodeBlockComponent, WdsCodeBlockCopyButtonComponent, WdsCodeBlockHeaderComponent, WdsCodeBlockTitleComponent, WdsCodeBlockWrapToggleComponent } from '@wds/angular/code-block';
@Component({
selector: 'app-code-block-terminal-demo',
imports: [WdsCodeBlockComponent, WdsCodeBlockHeaderComponent, WdsCodeBlockTitleComponent, WdsCodeBlockWrapToggleComponent, WdsCodeBlockCopyButtonComponent],
template: `
<div class="w-full max-w-2xl">
<wds-code-block language="bash" plain label="Build output">
<wds-code-block-header>
<wds-code-block-title>Terminal</wds-code-block-title>
<div class="ms-auto flex items-center gap-1">
<wds-code-block-wrap-toggle></wds-code-block-wrap-toggle>
<wds-code-block-copy-button></wds-code-block-copy-button>
</div>
</wds-code-block-header>
<pre>
$ pnpm build --filter @acme/timetable --filter @acme/timetable-api --filter @acme/timetable-worker
✓ @acme/timetable built in 4.1s
✓ @acme/timetable-api built in 2.7s
✓ @acme/timetable-worker built in 1.9s
</pre>
</wds-code-block>
</div>
`,
})
export class CodeBlockTerminalDemo {}Long file#
max-lines shows that many lines and wds-code-block-expand-button reveals the rest. start-line changes the first number; ranges still count from 1.
[
{ "code": "KRK", "name": "Kraków Główny", "platforms": 5 },
{ "code": "WAW", "name": "Warszawa Centralna", "platforms": 4 },
{ "code": "GDA", "name": "Gdańsk Główny", "platforms": 4 },
{ "code": "POZ", "name": "Poznań Główny", "platforms": 6 },
{ "code": "WRO", "name": "Wrocław Główny", "platforms": 5 },
{ "code": "KAT", "name": "Katowice", "platforms": 4 },
{ "code": "LOD", "name": "Łódź Fabryczna", "platforms": 4 },
{ "code": "SZC", "name": "Szczecin Główny", "platforms": 3 },
{ "code": "LUB", "name": "Lublin Główny", "platforms": 3 }
]
import { Component } from '@angular/core';
import { WdsCodeBlockComponent, WdsCodeBlockCopyButtonComponent, WdsCodeBlockExpandButtonComponent, WdsCodeBlockHeaderComponent, WdsCodeBlockTitleComponent } from '@wds/angular/code-block';
@Component({
selector: 'app-code-block-expand-demo',
imports: [WdsCodeBlockComponent, WdsCodeBlockHeaderComponent, WdsCodeBlockTitleComponent, WdsCodeBlockCopyButtonComponent, WdsCodeBlockExpandButtonComponent],
template: `
<div class="w-full max-w-2xl">
<wds-code-block language="json" line-numbers start-line="40" max-lines="6">
<wds-code-block-header>
<wds-code-block-title>stations.json</wds-code-block-title>
<wds-code-block-copy-button class="ms-auto"></wds-code-block-copy-button>
</wds-code-block-header>
<pre>
[
{{ '{' }} "code": "KRK", "name": "Kraków Główny", "platforms": 5 {{ '}' }},
{{ '{' }} "code": "WAW", "name": "Warszawa Centralna", "platforms": 4 {{ '}' }},
{{ '{' }} "code": "GDA", "name": "Gdańsk Główny", "platforms": 4 {{ '}' }},
{{ '{' }} "code": "POZ", "name": "Poznań Główny", "platforms": 6 {{ '}' }},
{{ '{' }} "code": "WRO", "name": "Wrocław Główny", "platforms": 5 {{ '}' }},
{{ '{' }} "code": "KAT", "name": "Katowice", "platforms": 4 {{ '}' }},
{{ '{' }} "code": "LOD", "name": "Łódź Fabryczna", "platforms": 4 {{ '}' }},
{{ '{' }} "code": "SZC", "name": "Szczecin Główny", "platforms": 3 {{ '}' }},
{{ '{' }} "code": "LUB", "name": "Lublin Główny", "platforms": 3 {{ '}' }}
]
</pre>
<wds-code-block-expand-button></wds-code-block-expand-button>
</wds-code-block>
</div>
`,
})
export class CodeBlockExpandDemo {}Download#
wds-code-block-download-button saves the code as a file named filename.
services:
api:
image: ghcr.io/acme/timetable-api:1.4.0
environment:
DATABASE_URL: postgres://timetable@db/timetable
ports:
- "8080:8080"
import { Component } from '@angular/core';
import { WdsCodeBlockComponent, WdsCodeBlockCopyButtonComponent, WdsCodeBlockDownloadButtonComponent, WdsCodeBlockHeaderComponent, WdsCodeBlockLanguageComponent, WdsCodeBlockTitleComponent } from '@wds/angular/code-block';
@Component({
selector: 'app-code-block-download-demo',
imports: [WdsCodeBlockComponent, WdsCodeBlockHeaderComponent, WdsCodeBlockTitleComponent, WdsCodeBlockLanguageComponent, WdsCodeBlockDownloadButtonComponent, WdsCodeBlockCopyButtonComponent],
template: `
<div class="w-full max-w-2xl">
<wds-code-block language="yaml" line-numbers>
<wds-code-block-header>
<wds-code-block-title>compose.yaml</wds-code-block-title>
<wds-code-block-language></wds-code-block-language>
<div class="ms-auto flex items-center gap-1">
<wds-code-block-download-button filename="compose.yaml"></wds-code-block-download-button>
<wds-code-block-copy-button></wds-code-block-copy-button>
</div>
</wds-code-block-header>
<pre>
services:
api:
image: ghcr.io/acme/timetable-api:1.4.0
environment:
DATABASE_URL: postgres://timetable@db/timetable
ports:
- "8080:8080"
</pre>
</wds-code-block>
</div>
`,
})
export class CodeBlockDownloadDemo {}Ghost#
variant="ghost" drops the border and background, for blocks inside another surface.
let seats = 0;
for (const car of train.cars) {
seats += car.seats;
}
const seats = train.cars.reduce((sum, car) => sum + car.seats, 0);
import { Component } from '@angular/core';
import { WdsCardComponent } from '@wds/angular/card';
import { WdsCodeBlockComponent } from '@wds/angular/code-block';
@Component({
selector: 'app-code-block-ghost-demo',
imports: [WdsCardComponent, WdsCodeBlockComponent],
template: `
<wds-card class="w-full max-w-2xl" heading="Before and after" description="The loop becomes a single reduce.">
<div class="grid gap-4">
<wds-code-block variant="ghost" language="ts" class="rounded-lg bg-muted/50">
<pre>
let seats = 0;
for (const car of train.cars) {{ '{' }}
seats += car.seats;
{{ '}' }}
</pre>
</wds-code-block>
<wds-code-block variant="ghost" language="ts" class="rounded-lg bg-muted/50">
<pre>
const seats = train.cars.reduce((sum, car) => sum + car.seats, 0);
</pre>
</wds-code-block>
</div>
</wds-card>
`,
})
export class CodeBlockGhostDemo {}Themes#
light-theme and dark-theme pick the highlighter themes for the light and dark color scheme (default github-light and github-dark).
export const averageSpeed = (km: number, minutes: number) =>
Math.round((km / minutes) * 60);
import { Component } from '@angular/core';
import { WdsCodeBlockComponent, WdsCodeBlockHeaderComponent, WdsCodeBlockLanguageComponent, WdsCodeBlockTitleComponent } from '@wds/angular/code-block';
@Component({
selector: 'app-code-block-themes-demo',
imports: [WdsCodeBlockComponent, WdsCodeBlockHeaderComponent, WdsCodeBlockTitleComponent, WdsCodeBlockLanguageComponent],
template: `
<div class="w-full max-w-2xl">
<wds-code-block language="ts" line-numbers light-theme="vitesse-light" dark-theme="vitesse-dark">
<wds-code-block-header>
<wds-code-block-title>speed.ts</wds-code-block-title>
<wds-code-block-language></wds-code-block-language>
</wds-code-block-header>
<pre>
export const averageSpeed = (km: number, minutes: number) =>
Math.round((km / minutes) * 60);
</pre>
</wds-code-block>
</div>
`,
})
export class CodeBlockThemesDemo {}API References#
wds-code-block#
code or from a <pre> inside the element (escape < as <); a common indent is removed.
Colors come from the registered highlighter: import '@wds/core/code-block/shiki' registers one built on
Shiki (an optional dependency), and lines takes lines highlighted ahead of time (e.g. on the server).
Without a highlighter, for an unknown language or with plain the code is plain text.
Child elements are chrome: wds-code-block-header with a title, language and buttons, a copy button pinned
over the code, wds-code-block-expand-button under a block with max-lines. The code itself is drawn by the block.
Attributes
| Attribute | Type | Default | Description |
|---|---|---|---|
| code | string | '' | <pre> inside the element. |
| language | string | '' | wds-code-block-language, e.g. ts, html, bash. |
| plain | boolean | false | |
| line-numbers.lineNumbers | boolean | false | |
| start-line.startLine | number | 1 | highlighted-lines and the rest) still count from 1. |
| wrap | boolean | false | |
| max-lines.maxLines | number | 0 | wds-code-block-expand-button). 0: all lines. |
| expanded | boolean | false | max-lines shows all lines. |
| variant | WdsCodeBlockVariant | 'default' | default: border and card background. ghost: no border and background, for a block inside another surface. |
| label | string | '' | codeBlock.label). |
| highlighted-lines.highlightedLines | string | '' | 2-4,7. |
| highlighted-words.highlightedWords | string[] | [] | |
| focused-lines.focusedLines | string | '' | 3-5. |
| diff-added.diffAdded | string | '' | +), e.g. 4-7. |
| diff-removed.diffRemoved | string | '' | -), e.g. 3. |
| error-lines.errorLines | string | '' | |
| warning-lines.warningLines | string | '' | |
| info-lines.infoLines | string | '' | |
| light-theme.lightTheme | string | 'github-light' | |
| dark-theme.darkTheme | string | 'github-dark' |
Properties
| Property | Description |
|---|---|
| linesWdsCodeBlockLine[] | null |
Events
| Event | Description |
|---|---|
| wds-wrap-changeCustomEvent<WdsCodeBlockWrapChangeDetail> | wds-code-block-wrap-toggle switched line wrapping. |
| wds-expand-changeCustomEvent<WdsCodeBlockExpandChangeDetail> | wds-code-block-expand-button expanded or collapsed the block. |
Slots
| Slot | Description |
|---|---|
| (default) | wds-code-block-header, wds-code-block-copy-button, wds-code-block-expand-button; a <pre> with the code. |
CSS parts (::part)
| Part | Description |
|---|---|
| viewport |
CSS custom properties
| Property | Description |
|---|---|
| --wds-code-block-padding | |
| --wds-code-block-padding-block | --wds-code-block-padding). |
| --wds-code-block-gutter-gap | |
| --wds-code-block-font-size | |
| --wds-code-block-line-height | |
| --wds-code-block-max-height | |
| --wds-code-block-background | --wds-card). |
| --wds-code-block-highlight | |
| --wds-code-block-add | + mark. |
| --wds-code-block-remove | - mark. |
| --wds-code-block-warning | |
| --wds-code-block-info |
wds-code-block-header#
wds-code-block with a bottom border: a title, the language and buttons.
A copy button inside the header stands in the row instead of floating over the code.
Slots
| Slot | Description |
|---|---|
| (default) | wds-code-block-title, wds-code-block-language, buttons and other content. |
wds-code-block-title#
wds-code-block-header, usually a file name. Long text is cut with an ellipsis.
Slots
| Slot | Description |
|---|---|
| (default) |
wds-code-block-language#
wds-code-block-header: the language of the block after aliases (ts → typescript).
Text inside replaces it. Hidden when the block has no language.
Slots
| Slot | Description |
|---|---|
| (default) |
wds-code-block-copy-button#
wds-code-block-header it stands in the row; placed directly in the block it
floats in the top corner of the code and shows on hover (always on touch screens or with always-visible).
After copying the icon turns into a check mark for 2 seconds.
Attributes
| Attribute | Type | Default | Description |
|---|---|---|---|
| value | string | '' | |
| variant | WdsButtonVariant | 'ghost' | |
| size | WdsButtonSize | '' | '' | sm in the header, default over the code. |
| always-visible.alwaysVisible | boolean | false | |
| label | string | '' | codeBlock.copy). |
Events
| Event | Description |
|---|---|
| wds-copyCustomEvent<WdsCodeBlockCopyDetail> |
wds-code-block-download-button#
filename.
Attributes
| Attribute | Type | Default | Description |
|---|---|---|---|
| filename | string | 'code.txt' | |
| label | string | '' | codeBlock.download). |
wds-code-block-wrap-toggle#
wrap). A toggle button: aria-pressed tells whether lines wrap.
Slots
| Slot | Description |
|---|---|
| (default) | codeBlock.wrap). |
wds-code-block-expand-button#
max-lines. A collapsed block fades out under it.
Hidden when the block has no more lines than max-lines.
Accessibility#
Screen reader#
region named by label (default Code) and is in the tab sequence, so a keyboard user can scroll it. Give blocks on one page different labels when they hold different code.
+ / - diff marks are drawn by CSS: screen readers skip them and they are not copied with the text.
codeBlock.copy, codeBlock.download and codeBlock.showMore; after copying the name of the copy button changes to Copied. The wrap toggle reports its state with aria-pressed, the expand button with aria-expanded.
Keyboard support#
| Key | Function |
|---|---|