Skip to content
Esc
↑↓navigate↵open⌘Jpreview
On this page

Copy Button for Astro

Copy text with an Astro button or bind clipboard behavior to your own button.

bun run build

Installation

bunx --bun shadcn@latest add @gnostic/copy-button
npx shadcn@latest add @gnostic/copy-button
pnpm dlx shadcn@latest add @gnostic/copy-button

Component classes: Default Gnostic.

Complete the Installation guide first. Then copy the component files below.

Install component packages

bun add @data-slot/core

Copy the files

src/components/ui/copy-button/copy-button.astro
---
import type { HTMLAttributes } from "astro/types"
import Check from "@lucide/astro/icons/check"
import Copy from "@lucide/astro/icons/copy"
import { cn } from "cn"
import Button from "../button/button.astro"
import type { CopyButtonProps } from "./types.ts"

type Props = Omit<HTMLAttributes<"button">, "value"> & CopyButtonProps
const {
  class: className,
  value,
  source,
  timeout = 2000,
  variant = "ghost",
  size = "icon",
  "aria-label": label = "Copy to clipboard",
  ...props
} = Astro.props
---

<div data-slot="copy-button" data-timeout={timeout} class="contents">
  <Button
    {...props}
    data-copy-control
    data-copy-href={source}
    data-value={value}
    variant={variant}
    size={size}
    aria-label={label}
    class={cn("shrink-0 group/copy", className)}
  >
    <slot>
      <Copy aria-hidden="true" class="group-data-copied/copy:hidden" />
      <Check aria-hidden="true" class="hidden group-data-copied/copy:block" />
    </slot>
  </Button>
  <span
    aria-live="polite"
    aria-atomic="true"
    class="sr-only"
    data-slot="copy-button-status"
  ></span>
</div>

<script>
  import {
    create,
    type CopyToClipboardController,
  } from "./copy-to-clipboard.ts"

  const controllers: CopyToClipboardController[] = []
  const initialize = () => controllers.push(...create())
  initialize()
  document.addEventListener("astro:page-load", initialize)
  document.addEventListener("astro:before-swap", () => {
    for (const controller of controllers) controller.destroy()
    controllers.length = 0
  })
</script>
src/components/ui/copy-button/copy-to-clipboard.ts
import {
    clearRootBinding,
    getOwnedElements,
    getPart,
    getRoots,
    hasRootBinding,
    reuseRootBinding,
    setRootBinding,
} from '@data-slot/core'

const BINDING_KEY = '@gnostic/copy-button'

/** Browser behavior adapted from Coss useCopyToClipboard. No framework runtime. */
export interface CopyToClipboardOptions {
    /** Read the current value on each copy. Defaults to the button's data-value. */
    value?: string | (() => string)
    /** Copied-state duration in milliseconds. Zero keeps it until reset. @default 2000 */
    timeout?: number
    onCopy?: () => void
    onError?: (error: unknown) => void
    onStateChange?: (state: 'idle' | 'copied' | 'error') => void
}

export interface CopyToClipboardController {
    readonly isCopied: boolean
    copy(value?: string): Promise<boolean>
    reset(): void
    destroy(): void
}

/** Bind one copy-button root. Destroy its controller before removing the root. */
export function createCopyToClipboard(
    root: Element,
    options: CopyToClipboardOptions = {},
): CopyToClipboardController {
    const existing = reuseRootBinding<CopyToClipboardController>(
        root,
        BINDING_KEY,
        '[copy-button] Destroy the existing controller before binding new options.',
    )
    if (existing) return existing
    const button = getOwnedElements<HTMLButtonElement>(
        root,
        root,
        'button[data-copy-control]',
    )[0]
    if (!button)
        throw new Error('Copy Button requires a data-copy-control button.')
    const timeout =
        options.timeout ?? Number(root.getAttribute('data-timeout') ?? 2000)
    if (!Number.isFinite(timeout) || timeout < 0)
        throw new RangeError(
            'Copy timeout must be a finite, non-negative number.',
        )
    const label = button.getAttribute('aria-label')
    const status = getPart(root, 'copy-button-status')
    let timer: ReturnType<typeof setTimeout> | undefined
    let copied = false
    let pending = false
    let destroyed = false
    let generation = 0

    const state = (value: 'idle' | 'copied' | 'error') => {
        copied = value === 'copied'
        button.toggleAttribute('data-copied', copied)
        if (value === 'copied') button.setAttribute('aria-label', 'Copied')
        else if (label === null) button.removeAttribute('aria-label')
        else button.setAttribute('aria-label', label)
        if (status)
            status.textContent =
                value === 'copied'
                    ? 'Copied'
                    : value === 'error'
                      ? 'Copy failed. Select and copy the text.'
                      : ''
        options.onStateChange?.(value)
    }

    const reset = () => {
        generation++
        pending = false
        clearTimeout(timer)
        timer = undefined
        state('idle')
    }

    const copy = async (value?: string): Promise<boolean> => {
        if (
            destroyed ||
            pending ||
            button.matches(':disabled') ||
            button.getAttribute('aria-disabled') === 'true'
        )
            return false
        clearTimeout(timer)
        state('idle')
        pending = true
        const request = ++generation
        try {
            const view = button.ownerDocument.defaultView
            const clipboard = view?.navigator.clipboard
            // A source URL is fetched on click. The page markdown route is one example.
            const href = button.getAttribute('data-copy-href')
            if (href) {
                if (!view?.fetch) throw new Error('Fetch API is unavailable.')
                if (!clipboard?.writeText && !clipboard?.write)
                    throw new Error('Clipboard API is unavailable.')
                const ClipboardItemCtor = view.ClipboardItem
                // Start the clipboard write in the click so the browser keeps the user gesture.
                if (clipboard.write && ClipboardItemCtor) {
                    await clipboard.write([
                        new ClipboardItemCtor({
                            'text/plain': view
                                .fetch(href)
                                .then(async (response) => {
                                    if (!response.ok)
                                        throw new Error(
                                            `Fetching ${href} failed (${response.status}).`,
                                        )
                                    return new Blob([await response.text()], {
                                        type: 'text/plain',
                                    })
                                }),
                        }),
                    ])
                } else {
                    const response = await view.fetch(href)
                    if (!response.ok)
                        throw new Error(
                            `Fetching ${href} failed (${response.status}).`,
                        )
                    const text = await response.text()
                    if (!text) {
                        pending = false
                        return false
                    }
                    if (!clipboard.writeText)
                        throw new Error('Clipboard API is unavailable.')
                    await clipboard.writeText(text)
                }
            } else {
                const text =
                    value ??
                    (typeof options.value === 'function'
                        ? options.value()
                        : options.value) ??
                    button.dataset.value ??
                    ''
                if (!text) {
                    pending = false
                    return false
                }
                if (!clipboard?.writeText)
                    throw new Error('Clipboard API is unavailable.')
                await clipboard.writeText(text)
            }
        } catch (error) {
            if (destroyed || request !== generation) return false
            pending = false
            state('error')
            options.onError?.(error)
            return false
        }
        if (destroyed || request !== generation) return false
        pending = false
        state('copied')
        if (timeout > 0) timer = setTimeout(reset, timeout)
        options.onCopy?.()
        return true
    }
    const click = (event: Event) => {
        if (!event.defaultPrevented) void copy()
    }
    button.addEventListener('click', click)
    const controller: CopyToClipboardController = {
        get isCopied() {
            return copied
        },
        copy,
        reset,
        destroy() {
            if (destroyed) return
            destroyed = true
            button.removeEventListener('click', click)
            clearRootBinding(root, BINDING_KEY, controller)
            reset()
        },
    }
    return setRootBinding(root, BINDING_KEY, controller)
}

/** Bind each unbound copy-button root within the scope. Defaults to the page. */
export function create(
    scope: ParentNode = document,
): CopyToClipboardController[] {
    const controllers: CopyToClipboardController[] = []
    for (const root of getRoots(scope, 'copy-button')) {
        if (!hasRootBinding(root, BINDING_KEY))
            controllers.push(createCopyToClipboard(root))
    }
    return controllers
}
src/components/ui/copy-button/types.ts
import type { ButtonVariantProps } from '../button/button-variants.ts'

/** A button that copies text and confirms a successful clipboard write. */
export interface CopyButtonProps extends ButtonVariantProps {
    /**
     * The exact text to copy.
     * Empty values do nothing.
     * Omit this when `source` is set.
     */
    value?: string
    /**
     * URL whose response text is copied on click.
     * Use a page path with a `.md` extension to copy that page's markdown.
     */
    source?: string
    /** Copied-state duration in milliseconds. Zero keeps it until reset. @default 2000 */
    timeout?: number
}
src/components/ui/copy-button/index.ts
export { default as CopyButton } from './copy-button.astro'
export { createCopyToClipboard, create } from './copy-to-clipboard.ts'
export type { CopyButtonProps } from './types.ts'
export type {
    CopyToClipboardOptions,
    CopyToClipboardController,
} from './copy-to-clipboard.ts'

Usage

---
import { CopyButton } from "@/components/ui/copy-button"
---

<CopyButton value="bun run build" />

The button uses the shared Button styles. Its defaults are variant="ghost" and size="icon". Position it with a caller class or a parent layout. The copied state starts after a successful clipboard write and lasts 2000 ms. Set timeout={0} to keep that state until the controller is reset or destroyed. Empty values do nothing. Whitespace and final newlines are copied exactly.

Examples

Custom content

Use the default slot for other icons or text. The button’s data-copied attribute controls the state. The group/copy marker lets child elements respond to it. Native button attributes, including disabled, pass through.

Optional tooltip

CopyButton has no tooltip by default. Add Tooltip when you want a visible hint on hover or focus. Set data-slot="tooltip-trigger" on CopyButton to use its button as the trigger.

---
import { CopyButton } from "@/components/ui/copy-button"
import { Tooltip, TooltipContent } from "@/components/ui/tooltip"
---

<Tooltip>
  <CopyButton
    value="bun run build"
    aria-label="Copy command"
    data-slot="tooltip-trigger"
  />
  <TooltipContent>Copy command</TooltipContent>
</Tooltip>

Fetch data from a URL

Pass in a URL to the source prop to fetch the data from a URL.

Bind all copy buttons

Import the browser module directly. It has no Astro dependency. Use data-slot="copy-button" for each root and data-copy-control for its button. create() binds all unbound roots on the page and returns their controllers. Pass a container to create(container) to limit the search.

<div data-slot="copy-button" data-timeout="2000">
  <pre>bun run build</pre>
  <button type="button" data-copy-control data-value="bun run build">
    Copy command
  </button>
  <span data-slot="copy-button-status" aria-live="polite"></span>
</div>

<script>
  import {
    create,
    type CopyToClipboardController,
  } from "@/components/ui/copy-button/copy-to-clipboard"

  const controllers: CopyToClipboardController[] = []
  const initialize = () => controllers.push(...create())
  initialize()
  document.addEventListener("astro:page-load", initialize)
  document.addEventListener("astro:before-swap", () => {
    for (const controller of controllers) controller.destroy()
    controllers.length = 0
  })
</script>

CopyButton and CodeBlockCopyButton include this setup and cleanup in their component scripts. No extra setup is needed when you use those components. Repeated calls to create() skip bound roots. For content that your code adds later, call create(container) after insertion. Destroy its controllers before you remove that content.

Bind one root

Use createCopyToClipboard(root, options) when you need a value function or callbacks for one root. The root contains the data-copy-control button and any feedback elements.

import { createCopyToClipboard } from "@/components/ui/copy-button/copy-to-clipboard"

const root = document.querySelector<HTMLElement>('[data-slot="copy-button"]')!
const clipboard = createCopyToClipboard(root, {
    value: () => root.querySelector("pre")?.textContent ?? "",
    timeout: 2000,
    onCopy: () => console.log("Copied"),
    onError: (error) => console.error(error),
})

// Before removing the root or replacing its binding:
// clipboard.destroy()

Use this scoped setup in place of create() for that root. A bound root keeps its existing controller and options until you destroy the controller.

The controller provides copy(value?), reset(), destroy(), and a read-only isCopied property. copy() returns a promise with true after success and false after a failed or skipped write. Without a value option, it reads the button’s data-value on each click. A value function also runs on each copy.

Use onStateChange(state) for custom feedback. States are idle, copied, and error. The controller sets data-copied and updates the button label. It updates the optional copy-button-status slot within the root. It does not replace the button content. It ignores clicks while a write is pending. A new success starts a new timeout. reset() and destroy() ignore any pending result; they cannot cancel a write already sent to the browser.

Call copy() from a user action, such as a click, when you use it directly.

Accessibility and browser support

The component includes an accessible button label and a polite status message. Icon buttons use aria-label for their accessible name. A tooltip is optional and does not replace that label. Failed writes show failure feedback and do not show the check icon. Clipboard access requires HTTPS or localhost and browser permission. The browser module reports an unavailable API through onError.

Design source

Adapted from the Coss CopyButton and useCopyToClipboard source. The Astro port uses native events, the shared Button component, and data-copied for icon changes. It does not require a React hook.

API Reference

CopyButtonProps

PropType
value?string

The exact text to copy. Empty values do nothing. Omit this when `source` is set.

Typestring
source?string

URL whose response text is copied on click. Use a page path with a `.md` extension to copy that page's markdown.

Typestring
timeout?number

Copied-state duration in milliseconds. Zero keeps it until reset.

Typenumber
Default2000
variant?"outline" | "default" | "glass" | "surface" | "destructive-outline" | "destructive" | "ghost" | "link" | "secondary" | null | undefined
Type"outline" | "default" | "glass" | "surface" | "destructive-outline" | "destructive" | "ghost" | "link" | "secondary" | null | undefined
size?"icon" | "icon-xs" | "icon-sm" | "icon-lg" | "icon-xl" | "default" | "lg" | "sm" | "xl" | "xs" | null | undefined
Type"icon" | "icon-xs" | "icon-sm" | "icon-lg" | "icon-xl" | "default" | "lg" | "sm" | "xl" | "xs" | null | undefined

Read the installed source for the complete prop types.

Theme and layout

Copy Button uses the shared Button styles. Use its variant and size props for the control, and place it with a parent layout. Keep the success and error feedback visible when you supply custom content. For a full code sample with copy controls, use Code Block.