Skip to content

Code block ​

A titled block of code with a copy button and optional line numbers.

Installation ​

bash
npx bootcn add code-block
bash
pnpm dlx bootcn add code-block
bash
yarn dlx bootcn add code-block
bash
bunx --bun bootcn add code-block

The CLI also installs the design tokens and these components: none. It prints the <link> and <script> tags to add to your layout.

Usage ​

Escape the code on the server (htmlspecialchars in PHP). For line numbers, add bootcn-code-block--numbered and wrap each line in <span class="bootcn-code-block__line">. Keep the code's own line breaks (or &#10;) and do not let a formatter indent the inside of <pre>. For syntax colours, put the output of a highlighter such as Prism or Shiki inside <code>; the block only provides the frame.

JavaScript API ​

  • data-bootcn-code-block on the <figure>, a button with data-bootcn-code-block-copy, and a live region marked data-bootcn-code-block-status.
  • The copy button copies the text of the <code> element (line numbers are CSS counters, so they are never copied), shows a check for two seconds and announces "Copied to the clipboard."
  • Event bootcn:code-block:copy (bubbles), detail.text.
  • Bootcn.codeBlock.init() / destroy().

Accessibility ​

  • The <pre> is focusable (tabindex="0") so keyboard users can scroll long lines.
  • The copy button has an accessible name ("Copy code") and the result is announced in a live region.
  • The title is a <figcaption>, so the code is named by it.

Dependencies ​

  • Bootstrap 5.3+ CSS.
  • themes/tokens/tokens.css.

Source ​

The exact files the CLI installs (code-block@1.0.0). View on GitHub · Report an issue

html
<figure class="bootcn-code-block" data-bootcn-code-block>
  <figcaption class="bootcn-code-block__header">
    <span class="bootcn-code-block__title">Terminal</span>
    <button
      type="button"
      class="bootcn-code-block__copy"
      aria-label="Copy code"
      data-bootcn-code-block-copy
    >
      <svg
        class="bootcn-icon bootcn-code-block__copy-icon"
        width="16"
        height="16"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
        focusable="false"
      >
        <rect x="8" y="8" width="13" height="13" rx="2" />
        <path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3" />
      </svg>
      <svg
        class="bootcn-icon bootcn-code-block__done-icon"
        width="16"
        height="16"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
        focusable="false"
      >
        <path d="M20 6 9 17l-5-5" />
      </svg>
    </button>
  </figcaption>
  <pre class="bootcn-code-block__pre" tabindex="0"><code>npx bootcn add dialog</code></pre>
  <span class="visually-hidden" role="status" data-bootcn-code-block-status></span>
</figure>

<figure class="bootcn-code-block bootcn-code-block--numbered mt-4" data-bootcn-code-block>
  <figcaption class="bootcn-code-block__header">
    <span class="bootcn-code-block__title">components/ui/hello.php</span>
    <button
      type="button"
      class="bootcn-code-block__copy"
      aria-label="Copy code"
      data-bootcn-code-block-copy
    >
      <svg
        class="bootcn-icon bootcn-code-block__copy-icon"
        width="16"
        height="16"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
        focusable="false"
      >
        <rect x="8" y="8" width="13" height="13" rx="2" />
        <path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3" />
      </svg>
      <svg
        class="bootcn-icon bootcn-code-block__done-icon"
        width="16"
        height="16"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
        focusable="false"
      >
        <path d="M20 6 9 17l-5-5" />
      </svg>
    </button>
  </figcaption>
  <pre
    class="bootcn-code-block__pre"
    tabindex="0"
  ><code class="language-php"><span class="bootcn-code-block__line">&lt;?php</span>&#10;<span class="bootcn-code-block__line">$name = htmlspecialchars($_GET['name'] ?? 'world');</span>&#10;<span class="bootcn-code-block__line">?&gt;</span>&#10;<span class="bootcn-code-block__line">&lt;button type="button" class="btn bootcn-button bootcn-button--default"&gt;</span>&#10;<span class="bootcn-code-block__line">  Hello, &lt;?= $name ?&gt;</span>&#10;<span class="bootcn-code-block__line">&lt;/button&gt;</span></code></pre>
  <span class="visually-hidden" role="status" data-bootcn-code-block-status></span>
</figure>
css
.bootcn-code-block {
  width: 36rem;
  max-width: 100%;
  margin: 0;
  overflow: hidden;
  border: var(--bootcn-border-width) solid var(--bootcn-border-color);
  border-radius: var(--bootcn-radius-lg);
  background-color: var(--bootcn-muted);
}

.bootcn-code-block__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 0.5rem;
  min-height: 2.5rem;
  margin: 0;
  padding: 0.25rem 0.25rem 0.25rem 1rem;
  border-bottom: var(--bootcn-border-width) solid var(--bootcn-border-color);
  color: var(--bootcn-muted-foreground);
  font-size: 0.8125rem;
}

.bootcn-code-block__title {
  overflow: hidden;
  font-family: var(--bs-font-monospace);
  text-overflow: ellipsis;
  white-space: nowrap;
}

.bootcn-code-block__copy {
  display: inline-flex;
  flex: none;
  align-items: center;
  justify-content: center;
  width: 2rem;
  height: 2rem;
  border: 0;
  border-radius: var(--bootcn-radius);
  background: transparent;
  color: var(--bootcn-muted-foreground);
}

.bootcn-code-block__copy:hover {
  background-color: var(--bootcn-accent);
  color: var(--bootcn-foreground);
}

.bootcn-code-block__copy:focus-visible {
  outline: 0;
  box-shadow: var(--bootcn-focus-ring);
}

.bootcn-code-block__done-icon,
.bootcn-code-block__copy.is-copied .bootcn-code-block__copy-icon {
  display: none;
}

.bootcn-code-block__copy.is-copied .bootcn-code-block__done-icon {
  display: inline-block;
}

.bootcn-code-block__pre {
  margin: 0;
  padding: 1rem;
  overflow: auto;
  background-color: var(--bootcn-background);
  color: var(--bootcn-foreground);
  font-size: 0.8125rem;
  line-height: 1.7;
  tab-size: 2;
}

.bootcn-code-block__pre:focus-visible {
  outline: 0;
  box-shadow: inset 0 0 0 var(--bootcn-focus-ring-width) var(--bootcn-focus-ring-color);
}

.bootcn-code-block__pre code {
  color: inherit;
  font-size: inherit;
}

/* Line numbers: one .bootcn-code-block__line per line. */
.bootcn-code-block--numbered .bootcn-code-block__pre code {
  counter-reset: bootcn-line;
}

.bootcn-code-block--numbered .bootcn-code-block__line::before {
  display: inline-block;
  width: 2rem;
  margin-right: 1rem;
  color: var(--bootcn-muted-foreground);
  text-align: right;
  content: counter(bootcn-line);
  counter-increment: bootcn-line;
  user-select: none;
}
js
(function () {
  'use strict';

  const ns = (window.Bootcn = window.Bootcn || {});
  if (ns.codeBlock) return; // already loaded: idempotent

  const ROOT = '[data-bootcn-code-block]';
  const timers = new WeakMap();
  let listening = false;

  // Clipboard API, else a hidden textarea and execCommand (older browsers,
  // pages without clipboard permission).
  function writeClipboard(text) {
    if (navigator.clipboard && window.isSecureContext) {
      return navigator.clipboard.writeText(text).then(
        function () {
          return true;
        },
        function () {
          return legacyCopy(text);
        },
      );
    }
    return Promise.resolve(legacyCopy(text));
  }

  function legacyCopy(text) {
    const area = document.createElement('textarea');
    area.value = text;
    area.setAttribute('readonly', '');
    area.style.position = 'fixed';
    area.style.opacity = '0';
    document.body.appendChild(area);
    const active = document.activeElement;
    area.select();
    let ok;
    try {
      ok = document.execCommand('copy');
    } catch {
      ok = false;
    }
    area.remove();
    if (active && active.focus) active.focus();
    return ok;
  }

  // Announces text in a live region, even when it is the same as last time.
  function announce(region, text) {
    if (!region) return;
    region.textContent = '';
    setTimeout(function () {
      region.textContent = text;
    }, 50);
  }

  function copy(button) {
    const root = button.closest(ROOT);
    const code = root && root.querySelector('code');
    if (!code) return;
    const text = code.textContent;
    writeClipboard(text).then(function (ok) {
      if (!ok) return;
      button.classList.add('is-copied');
      clearTimeout(timers.get(button));
      timers.set(
        button,
        setTimeout(function () {
          button.classList.remove('is-copied');
        }, 2000),
      );
      announce(root.querySelector('[data-bootcn-code-block-status]'), 'Copied to the clipboard.');
      root.dispatchEvent(
        new CustomEvent('bootcn:code-block:copy', { bubbles: true, detail: { text: text } }),
      );
    });
  }

  function onClick(event) {
    const button =
      event.target.closest && event.target.closest(ROOT + ' [data-bootcn-code-block-copy]');
    if (button) copy(button);
  }

  function init() {
    if (listening) return;
    document.addEventListener('click', onClick);
    listening = true;
  }

  function destroy() {
    if (!listening) return;
    document.removeEventListener('click', onClick);
    listening = false;
  }

  ns.codeBlock = { init: init, destroy: destroy };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();

Released under the MIT License. Not affiliated with Bootstrap or shadcn/ui.