Create

General

Code Block

Copy page View as Markdown Open in ChatGPT Open in Claude

Displays code with syntax highlighting, line numbers, marked lines and words, and copy and download buttons.

Usage#

app.component.ts
import { WDS_CODE_BLOCK } from '@wds/angular/code-block';

Colors come from a highlighter registered once: 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 &lt;) 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.

delay.ts
      export function delayMinutes(planned: Date, actual: Date): number {
        const diff = actual.getTime() - planned.getTime();
        return Math.max(0, Math.round(diff / 60_000));
      }
    

Pinned copy button#

A copy button placed directly in the block floats in the top corner of the code and shows on hover (always on touch screens).

      const departures = await api.get('/stations/krk/departures', {
        params: { limit: 20, from: new Date().toISOString() },
      });
    

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.

train-label.ts
      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}`;
      }
    

Highlighted lines and words#

highlighted-lines takes ranges such as 2-4,7; highlighted-words marks words wherever they appear.

client.ts
      export const client = createClient({
        baseUrl: 'https://api.example.com',
        retries: 3,
        timeoutMs: 8000,
        headers: { Accept: 'application/json' },
      });
    

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);
      }
    

Errors and warnings#

error-lines, warning-lines and info-lines color the lines; the header can sum them up with badges.

platform.ts 1 error 1 warning
      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.
      }
    

Terminal output#

plain skips the highlighter. wds-code-block-wrap-toggle switches wrap, so long lines wrap instead of scrolling sideways.

Terminal
      $ 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
    

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.

stations.json
      [
        { "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 }
      ]
    

Download#

wds-code-block-download-button saves the code as a file named filename.

compose.yaml
      services:
        api:
          image: ghcr.io/acme/timetable-api:1.4.0
          environment:
            DATABASE_URL: postgres://timetable@db/timetable
          ports:
            - "8080:8080"
    

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);
      

Themes#

light-theme and dark-theme pick the highlighter themes for the light and dark color scheme (default github-light and github-dark).

speed.ts
      export const averageSpeed = (km: number, minutes: number) =>
        Math.round((km / minutes) * 60);
    

API References#

wds-code-block#

Code block: code with line numbers, highlighted lines and words, diff marks and line levels. The code comes from code or from a <pre> inside the element (escape < as &lt;); 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

AttributeTypeDefaultDescription
codestring''The code. Empty: the text of a <pre> inside the element.
languagestring''Language for highlighting and for wds-code-block-language, e.g. ts, html, bash.
plainbooleanfalseShows the code without colors; the highlighter is not called.
line-numbers.lineNumbersbooleanfalseShows line numbers.
start-line.startLinenumber1Number of the first line. Line ranges (highlighted-lines and the rest) still count from 1.
wrapbooleanfalseWraps long lines instead of scrolling sideways.
max-lines.maxLinesnumber0Shows this many lines and hides the rest until the block is expanded (wds-code-block-expand-button). 0: all lines.
expandedbooleanfalseA block with max-lines shows all lines.
variantWdsCodeBlockVariant'default'default: border and card background. ghost: no border and background, for a block inside another surface.
labelstring''Accessible name of the code area. Empty: built-in text (codeBlock.label).
highlighted-lines.highlightedLinesstring''Lines with a background and a bar, e.g. 2-4,7.
highlighted-words.highlightedWordsstring[][]Words marked wherever they appear (separated by spaces or commas).
focused-lines.focusedLinesstring''Lines in focus: the rest is dimmed until the pointer is over the block, e.g. 3-5.
diff-added.diffAddedstring''Added lines (green, +), e.g. 4-7.
diff-removed.diffRemovedstring''Removed lines (red, -), e.g. 3.
error-lines.errorLinesstring''Lines with an error.
warning-lines.warningLinesstring''Lines with a warning.
info-lines.infoLinesstring''Lines with a note.
light-theme.lightThemestring'github-light'Highlighter theme for the light color scheme.
dark-theme.darkThemestring'github-dark'Highlighter theme for the dark color scheme.

Properties

PropertyDescription
linesWdsCodeBlockLine[] | nullLines highlighted ahead of time (e.g. on the server); they replace the highlighter.

Events

EventDescription
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

SlotDescription
(default)wds-code-block-header, wds-code-block-copy-button, wds-code-block-expand-button; a <pre> with the code.

CSS parts (::part)

PartDescription
viewportThe scrolling area with the code.

CSS custom properties

PropertyDescription
--wds-code-block-paddingHorizontal padding of the code (default 12px).
--wds-code-block-padding-blockTop and bottom padding of the code (default --wds-code-block-padding).
--wds-code-block-gutter-gapSpace between the line numbers and the code (default 10px).
--wds-code-block-font-sizeFont size of the code (default 13px).
--wds-code-block-line-heightHeight of a line (default 24px).
--wds-code-block-max-heightLargest height of the code area before it scrolls (default none).
--wds-code-block-backgroundBackground of the block (default --wds-card).
--wds-code-block-highlightBackground of highlighted lines.
--wds-code-block-addColor of added lines and the + mark.
--wds-code-block-removeColor of removed lines and the - mark.
--wds-code-block-warningColor of warning lines.
--wds-code-block-infoColor of info lines.

wds-code-block-header#

Top row of 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

SlotDescription
(default)wds-code-block-title, wds-code-block-language, buttons and other content.

wds-code-block-title#

Title in wds-code-block-header, usually a file name. Long text is cut with an ellipsis.

Slots

SlotDescription
(default)The title, optionally with an icon.

wds-code-block-language#

Language badge in 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

SlotDescription
(default)Own text instead of the language name.

wds-code-block-copy-button#

Copies the code of the block. In 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

AttributeTypeDefaultDescription
valuestring''Text to copy. Empty: the code of the block.
variantWdsButtonVariant'ghost'Button style.
sizeWdsButtonSize | ''''Button size. Empty: sm in the header, default over the code.
always-visible.alwaysVisiblebooleanfalseA button floating over the code stays visible, also without hover.
labelstring''Accessible name. Empty: built-in text (codeBlock.copy).

Events

EventDescription
wds-copyCustomEvent<WdsCodeBlockCopyDetail>The text was copied.

wds-code-block-download-button#

Saves the code of the block as a file named filename.

Attributes

AttributeTypeDefaultDescription
filenamestring'code.txt'Name of the saved file.
labelstring''Accessible name. Empty: built-in text (codeBlock.download).

wds-code-block-wrap-toggle#

Switches line wrapping of the block (wrap). A toggle button: aria-pressed tells whether lines wrap.

Slots

SlotDescription
(default)Own text instead of the built-in one (codeBlock.wrap).

wds-code-block-expand-button#

„Show more” / „Show less” at the bottom of a block with max-lines. A collapsed block fades out under it. Hidden when the block has no more lines than max-lines.

Accessibility#

Screen reader#

The code area is a 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.

Line numbers and the + / - diff marks are drawn by CSS: screen readers skip them and they are not copied with the text.

Line colors (diff, levels, highlights) are not announced. Say what changed or what is wrong in the text around the block, e.g. with badges in the header.

Copy, download and expand buttons are named by 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#

KeyFunction
TabMoves focus to the buttons in the header and to the code area.
ArrowLeftArrowRightArrowUpArrowDownScrolls the focused code area.
EnterSpaceActivates the focused button.
Footer