Component
Codeblock actions
Published on
Description
Write a plain <pre><code> block and mark it up as <pre is="ds-codeblock-actions">. The component prepends a button that writes the text content of the nested <code> element to the clipboard. Without JavaScript the block still renders as preformatted text, only the button is missing, so nothing is lost.
Use it for anything a reader is expected to paste elsewhere: install commands, configuration snippets, tokens, identifiers. It pairs with the Codeblock component, which wraps its highlighted code in this same element.
Add a bare data-filename for the download variant. A second control joins the copy button in the corner and saves the block as a file. Use it when the block is long enough that pasting is the wrong verb: a config file, a certificate, a manifest.
The contents come from the markup already there, the text of the nested <code>, saved as code.txt. Give data-filename a value to name the file something else.
Neither control implements its own behaviour: the component builds a ds-copy and ds-download button and points each at the nested <code> with data-elem="code", which resolves within the block itself, so the clipboard and file handling live in one place and a block that changes after load still copies what it shows.
Example
Accessibility
- The control is a native
<button type="button">, so it is reachable by keyboard and activated with Enter or Space. - The icon is
aria-hidden="true"andfocusable="false"; the accessible name comes from a visually hidden label. - That label is an
aria-live="polite"region that switches fromCopy
toCopied
for two seconds, so success is announced rather than shown only in colour. - The button is prepended in the DOM so it is announced before the code it copies, and moved to the inline end corner visually with
order. - Both controls are prepended ahead of the value, so they are announced before it; the inline end floats then paint copy in the corner with download beside it.
- Text and line breaks are preserved by
<pre>, so what is announced matches what is copied.
References
Related
- Codeblock — for code samples that also need syntax highlighting
- Icon — used for the button glyph
- Inline format — for short code references within a sentence
Variables
data-icon— sprite for both controls, defaults to/img/icons.svg#copy; the fragment is swapped per control, so#downloadis read from the same filedata-i18n-copy— idle label, defaults toCopydata-i18n-copied— confirmation label, defaults toCopieddata-filename— present, renders the download control; its value names the file, defaults tocode.txtdata-i18n-download— download label, defaults toDownload