# Copy Button

Copies a string to the clipboard. The copy icon turns into an animated check mark and a live region says Copied.

- Category: Buttons
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/copy-button.json
- CLI: `npx markasui@latest add copy-button`

## When to use

Copying a command, API key, link, or ID that the user will paste somewhere else.

- Show the copied value next to the button so users know what they copy
- Give icon-only buttons a specific copyLabel such as Copy command
- Use the ghost or secondary variant inside code blocks and inputs

## Code

### Blade

Save at `resources/views/components/markas/copy-button.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'text' => '',
    'variant' => 'primary',
    'size' => 'md',
    'copyLabel' => 'Copy',
    'copiedLabel' => 'Copied',
])

@php
    $wrapper = 'contents';
    $base = 'group inline-flex items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none';
    $variants = [
        'primary' => 'bg-primary text-on-primary hover:bg-primary-strong',
        'secondary' => 'border border-line bg-surface text-ink hover:bg-subtle',
        'ghost' => 'text-ink hover:bg-subtle',
        'danger' => 'bg-danger text-on-primary hover:bg-danger/90',
    ];
    $sizes = [
        'sm' => 'h-8 rounded-md px-3 text-sm',
        'md' => 'h-10 rounded-lg px-4 text-sm',
        'lg' => 'h-12 rounded-lg px-6 text-base',
    ];
    $iconSizes = [
        'sm' => 'size-8 rounded-md text-sm',
        'md' => 'size-10 rounded-lg text-sm',
        'lg' => 'size-12 rounded-lg text-base',
    ];
    $iconStack = 'grid size-4 shrink-0 place-items-center';
    $copyIcon = 'col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]:scale-50 group-data-[state=copied]:opacity-0 motion-reduce:transition-none';
    $checkIcon = 'col-start-1 row-start-1 size-4 scale-50 opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]:scale-100 group-data-[state=copied]:opacity-100 motion-reduce:transition-none';
    $checkPath = '[stroke-dasharray:24] [stroke-dashoffset:24] transition-[stroke-dashoffset] delay-100 duration-300 ease-out group-data-[state=copied]:[stroke-dashoffset:0] motion-reduce:transition-none';
    $srOnly = 'sr-only';

    $hasLabel = $slot->isNotEmpty();
@endphp

{{-- Clipboard blocked or unavailable: the button stays idle so the check mark never lies. --}}
<span
    class="{{ $wrapper }}"
    x-data="{
        copied: false,
        timer: null,
        async copy() {
            try {
                await navigator.clipboard.writeText(@js((string) $text));
            } catch {
                return;
            }
            this.copied = true;
            clearTimeout(this.timer);
            this.timer = setTimeout(() => (this.copied = false), 2000);
        },
        destroy() {
            clearTimeout(this.timer);
        },
    }"
>
    <button
        data-state="idle"
        x-bind:data-state="copied ? 'copied' : 'idle'"
        x-on:click="copy()"
        {{ $attributes->merge(['type' => 'button'])->class([$base, $variants[$variant], $hasLabel ? $sizes[$size] : $iconSizes[$size]]) }}
    >
        <span class="{{ $iconStack }}" aria-hidden="true">
            <svg class="{{ $copyIcon }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="12" height="12" rx="2" /><path d="M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1" /></svg>
            <svg class="{{ $checkIcon }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path class="{{ $checkPath }}" d="m4 12 5 5L20 6" /></svg>
        </span>
        @if ($hasLabel)
            {{ $slot }}
        @else
            <span class="{{ $srOnly }}">{{ $copyLabel }}</span>
        @endif
    </button>
    <span role="status" class="{{ $srOnly }}" x-text="copied ? @js($copiedLabel) : ''"></span>
</span>
```

```blade
<x-markas.copy-button text="pnpm dlx markasui add button" variant="ghost" size="sm" copy-label="Copy command" />
<x-markas.copy-button text="sk_live_51Hx9aT2" variant="secondary">Copy key</x-markas.copy-button>
```

### React

Save at `src/components/markas/CopyButton.tsx`. No extra dependencies.

```tsx
"use client";

import {
  useEffect,
  useRef,
  useState,
  type ComponentProps,
  type MouseEvent,
} from "react";

const wrapper = "contents";
const base =
  "group inline-flex items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const variants = {
  primary: "bg-primary text-on-primary hover:bg-primary-strong",
  secondary: "border border-line bg-surface text-ink hover:bg-subtle",
  ghost: "text-ink hover:bg-subtle",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const sizes = {
  sm: "h-8 rounded-md px-3 text-sm",
  md: "h-10 rounded-lg px-4 text-sm",
  lg: "h-12 rounded-lg px-6 text-base",
};
const iconSizes = {
  sm: "size-8 rounded-md text-sm",
  md: "size-10 rounded-lg text-sm",
  lg: "size-12 rounded-lg text-base",
};
const iconStack = "grid size-4 shrink-0 place-items-center";
const copyIcon =
  "col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]:scale-50 group-data-[state=copied]:opacity-0 motion-reduce:transition-none";
const checkIcon =
  "col-start-1 row-start-1 size-4 scale-50 opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]:scale-100 group-data-[state=copied]:opacity-100 motion-reduce:transition-none";
const checkPath =
  "[stroke-dasharray:24] [stroke-dashoffset:24] transition-[stroke-dashoffset] delay-100 duration-300 ease-out group-data-[state=copied]:[stroke-dashoffset:0] motion-reduce:transition-none";
const srOnly = "sr-only";

/** How long the check mark stays before the button returns to idle. */
const RESET_DELAY = 2000;

const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

export type CopyButtonProps = ComponentProps<"button"> & {
  /** Text written to the clipboard. */
  text: string;
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
  copyLabel?: string;
  copiedLabel?: string;
};

export function CopyButton({
  text,
  variant = "primary",
  size = "md",
  copyLabel = "Copy",
  copiedLabel = "Copied",
  type = "button",
  className,
  children,
  onClick,
  ...props
}: CopyButtonProps) {
  const [copied, setCopied] = useState(false);
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
  useEffect(() => () => clearTimeout(timer.current), []);

  const handleClick = async (event: MouseEvent<HTMLButtonElement>) => {
    onClick?.(event);
    if (event.defaultPrevented) return;
    try {
      await navigator.clipboard.writeText(text);
    } catch {
      // Clipboard blocked or unavailable: stay idle so the check mark never lies.
      return;
    }
    setCopied(true);
    clearTimeout(timer.current);
    timer.current = setTimeout(() => setCopied(false), RESET_DELAY);
  };

  return (
    <span className={wrapper}>
      <button
        type={type}
        data-state={copied ? "copied" : "idle"}
        onClick={handleClick}
        className={cx(
          base,
          variants[variant],
          children ? sizes[size] : iconSizes[size],
          className,
        )}
        {...props}
      >
        <span className={iconStack} aria-hidden="true">
          <svg
            className={copyIcon}
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <rect x="9" y="9" width="12" height="12" rx="2" />
            <path d="M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1" />
          </svg>
          <svg
            className={checkIcon}
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path className={checkPath} d="m4 12 5 5L20 6" />
          </svg>
        </span>
        {children ?? <span className={srOnly}>{copyLabel}</span>}
      </button>
      <span role="status" className={srOnly}>
        {copied ? copiedLabel : ""}
      </span>
    </span>
  );
}
```

```tsx
import { CopyButton } from "@/components/markas/CopyButton";

<CopyButton text="pnpm dlx markasui add button" variant="ghost" size="sm" copyLabel="Copy command" />
<CopyButton text="sk_live_51Hx9aT2" variant="secondary">Copy key</CopyButton>
```

### Vue

Save at `src/components/markas/CopyButton.vue`. No extra dependencies.

```vue
<script setup lang="ts">
import { onBeforeUnmount, ref } from "vue";

defineOptions({ inheritAttrs: false });

const variants = {
  primary: "bg-primary text-on-primary hover:bg-primary-strong",
  secondary: "border border-line bg-surface text-ink hover:bg-subtle",
  ghost: "text-ink hover:bg-subtle",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const sizes = {
  sm: "h-8 rounded-md px-3 text-sm",
  md: "h-10 rounded-lg px-4 text-sm",
  lg: "h-12 rounded-lg px-6 text-base",
};
const iconSizes = {
  sm: "size-8 rounded-md text-sm",
  md: "size-10 rounded-lg text-sm",
  lg: "size-12 rounded-lg text-base",
};

const props = withDefaults(
  defineProps<{
    /** Text written to the clipboard. */
    text: string;
    variant?: keyof typeof variants;
    size?: keyof typeof sizes;
    copyLabel?: string;
    copiedLabel?: string;
  }>(),
  {
    variant: "primary",
    size: "md",
    copyLabel: "Copy",
    copiedLabel: "Copied",
  },
);
const emit = defineEmits<{ click: [event: MouseEvent] }>();

const wrapper = "contents";
const base =
  "group inline-flex items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const iconStack = "grid size-4 shrink-0 place-items-center";
const copyIcon =
  "col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]:scale-50 group-data-[state=copied]:opacity-0 motion-reduce:transition-none";
const checkIcon =
  "col-start-1 row-start-1 size-4 scale-50 opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]:scale-100 group-data-[state=copied]:opacity-100 motion-reduce:transition-none";
const checkPath =
  "[stroke-dasharray:24] [stroke-dashoffset:24] transition-[stroke-dashoffset] delay-100 duration-300 ease-out group-data-[state=copied]:[stroke-dashoffset:0] motion-reduce:transition-none";
const srOnly = "sr-only";

/** How long the check mark stays before the button returns to idle. */
const RESET_DELAY = 2000;

const copied = ref(false);
let timer: ReturnType<typeof setTimeout> | undefined;
onBeforeUnmount(() => clearTimeout(timer));

async function copy(event: MouseEvent) {
  emit("click", event);
  if (event.defaultPrevented) return;
  try {
    await navigator.clipboard.writeText(props.text);
  } catch {
    // Clipboard blocked or unavailable: stay idle so the check mark never lies.
    return;
  }
  copied.value = true;
  clearTimeout(timer);
  timer = setTimeout(() => (copied.value = false), RESET_DELAY);
}
</script>

<template>
  <span :class="wrapper">
    <button
      type="button"
      :data-state="copied ? 'copied' : 'idle'"
      :class="[
        base,
        variants[props.variant],
        $slots.default ? sizes[props.size] : iconSizes[props.size],
      ]"
      v-bind="$attrs"
      @click="copy"
    >
      <span :class="iconStack" aria-hidden="true">
        <svg
          :class="copyIcon"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
        >
          <rect x="9" y="9" width="12" height="12" rx="2" />
          <path d="M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1" />
        </svg>
        <svg
          :class="checkIcon"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
        >
          <path :class="checkPath" d="m4 12 5 5L20 6" />
        </svg>
      </span>
      <slot>
        <span :class="srOnly">{{ props.copyLabel }}</span>
      </slot>
    </button>
    <span role="status" :class="srOnly">{{
      copied ? props.copiedLabel : ""
    }}</span>
  </span>
</template>
```

```vue
<script setup lang="ts">
import CopyButton from "@/components/markas/CopyButton.vue";
</script>

<template>
  <CopyButton
    text="pnpm dlx markasui add button"
    variant="ghost"
    size="sm"
    copy-label="Copy command"
  />
  <CopyButton text="sk_live_51Hx9aT2" variant="secondary">Copy key</CopyButton>
</template>
```

### Svelte

Save at `src/lib/components/markas/CopyButton.svelte`. No extra dependencies.

```svelte
<script lang="ts">
  import { onDestroy, type Snippet } from "svelte";
  import type { HTMLButtonAttributes } from "svelte/elements";

  const wrapper = "contents";
  const base =
    "group inline-flex items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
  const variants = {
    primary: "bg-primary text-on-primary hover:bg-primary-strong",
    secondary: "border border-line bg-surface text-ink hover:bg-subtle",
    ghost: "text-ink hover:bg-subtle",
    danger: "bg-danger text-on-primary hover:bg-danger/90",
  };
  const sizes = {
    sm: "h-8 rounded-md px-3 text-sm",
    md: "h-10 rounded-lg px-4 text-sm",
    lg: "h-12 rounded-lg px-6 text-base",
  };
  const iconSizes = {
    sm: "size-8 rounded-md text-sm",
    md: "size-10 rounded-lg text-sm",
    lg: "size-12 rounded-lg text-base",
  };
  const iconStack = "grid size-4 shrink-0 place-items-center";
  const copyIcon =
    "col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]:scale-50 group-data-[state=copied]:opacity-0 motion-reduce:transition-none";
  const checkIcon =
    "col-start-1 row-start-1 size-4 scale-50 opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]:scale-100 group-data-[state=copied]:opacity-100 motion-reduce:transition-none";
  const checkPath =
    "[stroke-dasharray:24] [stroke-dashoffset:24] transition-[stroke-dashoffset] delay-100 duration-300 ease-out group-data-[state=copied]:[stroke-dashoffset:0] motion-reduce:transition-none";
  const srOnly = "sr-only";

  /** How long the check mark stays before the button returns to idle. */
  const RESET_DELAY = 2000;

  type Props = HTMLButtonAttributes & {
    /** Text written to the clipboard. */
    text: string;
    variant?: keyof typeof variants;
    size?: keyof typeof sizes;
    copyLabel?: string;
    copiedLabel?: string;
    children?: Snippet;
  };

  let {
    text,
    variant = "primary",
    size = "md",
    copyLabel = "Copy",
    copiedLabel = "Copied",
    type = "button",
    class: className,
    children,
    onclick,
    ...rest
  }: Props = $props();

  let copied = $state(false);
  let timer: ReturnType<typeof setTimeout> | undefined;
  onDestroy(() => clearTimeout(timer));

  async function copy(
    event: MouseEvent & { currentTarget: EventTarget & HTMLButtonElement },
  ) {
    onclick?.(event);
    if (event.defaultPrevented) return;
    try {
      await navigator.clipboard.writeText(text);
    } catch {
      // Clipboard blocked or unavailable: stay idle so the check mark never lies.
      return;
    }
    copied = true;
    clearTimeout(timer);
    timer = setTimeout(() => (copied = false), RESET_DELAY);
  }
</script>

<span class={wrapper}>
  <button
    {type}
    data-state={copied ? "copied" : "idle"}
    onclick={copy}
    class={[
      base,
      variants[variant],
      children ? sizes[size] : iconSizes[size],
      className,
    ]}
    {...rest}
  >
    <span class={iconStack} aria-hidden="true">
      <svg
        class={copyIcon}
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
      >
        <rect x="9" y="9" width="12" height="12" rx="2" />
        <path d="M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1" />
      </svg>
      <svg
        class={checkIcon}
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        stroke-linecap="round"
        stroke-linejoin="round"
      >
        <path class={checkPath} d="m4 12 5 5L20 6" />
      </svg>
    </span>
    {#if children}{@render children()}{:else}<span class={srOnly}
        >{copyLabel}</span
      >{/if}
  </button>
  <span role="status" class={srOnly}>{copied ? copiedLabel : ""}</span>
</span>
```

```svelte
<script lang="ts">
  import CopyButton from "$lib/components/markas/CopyButton.svelte";
</script>

<CopyButton
  text="pnpm dlx markasui add button"
  variant="ghost"
  size="sm"
  copyLabel="Copy command"
/>
<CopyButton text="sk_live_51Hx9aT2" variant="secondary">Copy key</CopyButton>
```

### Astro

Save at `src/components/markas/CopyButton.astro`. No extra dependencies.

```astro
---
import type { HTMLAttributes } from "astro/types";

const wrapper = "contents";
const base =
  "group inline-flex items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const variants = {
  primary: "bg-primary text-on-primary hover:bg-primary-strong",
  secondary: "border border-line bg-surface text-ink hover:bg-subtle",
  ghost: "text-ink hover:bg-subtle",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const sizes = {
  sm: "h-8 rounded-md px-3 text-sm",
  md: "h-10 rounded-lg px-4 text-sm",
  lg: "h-12 rounded-lg px-6 text-base",
};
const iconSizes = {
  sm: "size-8 rounded-md text-sm",
  md: "size-10 rounded-lg text-sm",
  lg: "size-12 rounded-lg text-base",
};
const iconStack = "grid size-4 shrink-0 place-items-center";
const copyIcon =
  "col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]:scale-50 group-data-[state=copied]:opacity-0 motion-reduce:transition-none";
const checkIcon =
  "col-start-1 row-start-1 size-4 scale-50 opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]:scale-100 group-data-[state=copied]:opacity-100 motion-reduce:transition-none";
const checkPath =
  "[stroke-dasharray:24] [stroke-dashoffset:24] transition-[stroke-dashoffset] delay-100 duration-300 ease-out group-data-[state=copied]:[stroke-dashoffset:0] motion-reduce:transition-none";
const srOnly = "sr-only";

type Props = HTMLAttributes<"button"> & {
  /** Text written to the clipboard. */
  text: string;
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
  copyLabel?: string;
  copiedLabel?: string;
};

const {
  text,
  variant = "primary",
  size = "md",
  copyLabel = "Copy",
  copiedLabel = "Copied",
  type = "button",
  class: className,
  ...rest
} = Astro.props;
const hasLabel = Astro.slots.has("default");
---

<span class={wrapper}>
  <button
    type={type}
    data-state="idle"
    data-markas-copy-button={text}
    data-copied-label={copiedLabel}
    class:list={[
      base,
      variants[variant],
      hasLabel ? sizes[size] : iconSizes[size],
      className,
    ]}
    {...rest}
  >
    <span class={iconStack} aria-hidden="true">
      <svg
        class={copyIcon}
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
      >
        <rect x="9" y="9" width="12" height="12" rx="2"></rect>
        <path d="M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"></path>
      </svg>
      <svg
        class={checkIcon}
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        stroke-linecap="round"
        stroke-linejoin="round"
      >
        <path class={checkPath} d="m4 12 5 5L20 6"></path>
      </svg>
    </span>
    {hasLabel ? <slot /> : <span class={srOnly}>{copyLabel}</span>}
  </button>
  <span role="status" class={srOnly}></span>
</span>

<script>
  /** How long the check mark stays before the button returns to idle. */
  const RESET_DELAY = 2000;
  const timers = new WeakMap<HTMLElement, ReturnType<typeof setTimeout>>();

  const setState = (button: HTMLElement, copied: boolean) => {
    button.dataset.state = copied ? "copied" : "idle";
    const status = button.nextElementSibling;
    if (status) status.textContent = copied ? (button.dataset.copiedLabel ?? "") : "";
  };

  // One listener per page serves every copy button. It runs after the user's own click
  // listeners, so preventDefault() there skips the copy.
  document.addEventListener("click", async (event) => {
    const button = (event.target as Element).closest<HTMLElement>(
      "[data-markas-copy-button]",
    );
    if (!button || event.defaultPrevented) return;
    try {
      await navigator.clipboard.writeText(button.dataset.markasCopyButton ?? "");
    } catch {
      // Clipboard blocked or unavailable: stay idle so the check mark never lies.
      return;
    }
    setState(button, true);
    clearTimeout(timers.get(button));
    timers.set(button, setTimeout(() => setState(button, false), RESET_DELAY));
  });
</script>
```

```astro
---
import CopyButton from "@/components/markas/CopyButton.astro";
---

<CopyButton text="pnpm dlx markasui add button" variant="ghost" size="sm" copyLabel="Copy command" />
<CopyButton text="sk_live_51Hx9aT2" variant="secondary">Copy key</CopyButton>
```

### Angular

Save at `src/app/markas/copy-button.component.ts`. No extra dependencies.

```ts
import {
  afterNextRender,
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  DestroyRef,
  type ElementRef,
  inject,
  input,
  signal,
  viewChild,
} from "@angular/core";

const wrapper = "contents";
const base =
  "group inline-flex items-center justify-center gap-2 font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const variants = {
  primary: "bg-primary text-on-primary hover:bg-primary-strong",
  secondary: "border border-line bg-surface text-ink hover:bg-subtle",
  ghost: "text-ink hover:bg-subtle",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const sizes = {
  sm: "h-8 rounded-md px-3 text-sm",
  md: "h-10 rounded-lg px-4 text-sm",
  lg: "h-12 rounded-lg px-6 text-base",
};
const iconSizes = {
  sm: "size-8 rounded-md text-sm",
  md: "size-10 rounded-lg text-sm",
  lg: "size-12 rounded-lg text-base",
};
const iconStack = "grid size-4 shrink-0 place-items-center";
const copyIcon =
  "col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]:scale-50 group-data-[state=copied]:opacity-0 motion-reduce:transition-none";
const checkIcon =
  "col-start-1 row-start-1 size-4 scale-50 opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=copied]:scale-100 group-data-[state=copied]:opacity-100 motion-reduce:transition-none";
const checkPath =
  "[stroke-dasharray:24] [stroke-dashoffset:24] transition-[stroke-dashoffset] delay-100 duration-300 ease-out group-data-[state=copied]:[stroke-dashoffset:0] motion-reduce:transition-none";
const srOnly = "sr-only";

/** How long the check mark stays before the button returns to idle. */
const RESET_DELAY = 2000;

export type CopyButtonVariant = keyof typeof variants;
export type CopyButtonSize = keyof typeof sizes;

/**
 * Host stays out of layout (display: contents). id, aria-label, title, and class move to the
 * button. Without projected content the button is square and named by copyLabel.
 */
@Component({
  selector: "markas-copy-button",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: "contents",
    "[attr.id]": "null",
    "[attr.aria-label]": "null",
    "[attr.title]": "null",
  },
  template: `
    <span [class]="wrapper">
      <button
        [attr.type]="type()"
        [attr.id]="id() ?? null"
        [attr.aria-label]="ariaLabel() ?? null"
        [attr.title]="title() ?? null"
        [disabled]="disabled()"
        [attr.data-state]="copied() ? 'copied' : 'idle'"
        [class]="classes()"
        (click)="copy()"
      >
        <span [class]="iconStack" aria-hidden="true">
          <svg
            [class]="copyIcon"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
          >
            <rect x="9" y="9" width="12" height="12" rx="2" />
            <path
              d="M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"
            />
          </svg>
          <svg
            [class]="checkIcon"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
          >
            <path [class]="checkPath" d="m4 12 5 5L20 6" />
          </svg>
        </span>
        <ng-content
          ><span #fallback [class]="srOnly">{{ copyLabel() }}</span></ng-content
        >
      </button>
      <span role="status" [class]="srOnly">{{
        copied() ? copiedLabel() : ""
      }}</span>
    </span>
  `,
})
export class CopyButton {
  /** Text written to the clipboard. */
  readonly text = input.required<string>();
  readonly variant = input<CopyButtonVariant>("primary");
  readonly size = input<CopyButtonSize>("md");
  readonly copyLabel = input("Copy");
  readonly copiedLabel = input("Copied");
  readonly type = input<"button" | "submit" | "reset">("button");
  readonly disabled = input(false, { transform: booleanAttribute });
  readonly id = input<string>();
  readonly title = input<string>();
  readonly ariaLabel = input<string | undefined>(undefined, {
    alias: "aria-label",
  });
  readonly userClass = input("", { alias: "class" });

  protected readonly wrapper = wrapper;
  protected readonly iconStack = iconStack;
  protected readonly copyIcon = copyIcon;
  protected readonly checkIcon = checkIcon;
  protected readonly checkPath = checkPath;
  protected readonly srOnly = srOnly;
  protected readonly copied = signal(false);
  private readonly hasLabel = signal(true);
  protected readonly classes = computed(() =>
    [
      base,
      variants[this.variant()],
      this.hasLabel() ? sizes[this.size()] : iconSizes[this.size()],
      this.userClass(),
    ]
      .filter(Boolean)
      .join(" "),
  );
  private readonly fallback = viewChild<ElementRef<HTMLElement>>("fallback");
  private timer: ReturnType<typeof setTimeout> | undefined;

  constructor() {
    // Projected content is only known after the first render.
    afterNextRender(() => this.hasLabel.set(!this.fallback()));
    inject(DestroyRef).onDestroy(() => clearTimeout(this.timer));
  }

  protected async copy() {
    try {
      await navigator.clipboard.writeText(this.text());
    } catch {
      // Clipboard blocked or unavailable: stay idle so the check mark never lies.
      return;
    }
    this.copied.set(true);
    clearTimeout(this.timer);
    this.timer = setTimeout(() => this.copied.set(false), RESET_DELAY);
  }
}
```

```ts
import { Component } from "@angular/core";
import { CopyButton } from "./markas/copy-button.component";

@Component({
  selector: "app-install",
  imports: [CopyButton],
  template: `
    <markas-copy-button
      text="pnpm dlx markasui add button"
      variant="ghost"
      size="sm"
      copyLabel="Copy command"
    />
    <markas-copy-button text="sk_live_51Hx9aT2" variant="secondary">
      Copy key
    </markas-copy-button>
  `,
})
export class Install {}
```

Angular moves `id`, `aria-label`, `title`, and `class` from `markas-copy-button` to the inner button.

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `text` | `string` | - | Text written to the clipboard. |
| `variant` | `'primary' \| 'secondary' \| 'ghost' \| 'danger'` | primary | Visual style, the same set as Button. |
| `size` | `'sm' \| 'md' \| 'lg'` | md | Height 32, 40, or 48px. Without a label the button is square. |
| `copyLabel` | `string` | Copy | Hidden name of an icon-only button. |
| `copiedLabel` | `string` | Copied | Announced by the live region after a successful copy. |

## Accessibility

- A native button element, so Enter and Space work and focus shows a 2px primary outline.
- A visually hidden role=status region announces copiedLabel after the copy succeeds.
- Without a label the button is named by copyLabel, and both icons are aria-hidden.
- With prefers-reduced-motion the icon swaps without scaling or drawing.

## Notes

- Uses `navigator.clipboard.writeText`, which needs a secure context (https or localhost). If the browser blocks the clipboard, the button stays idle.
- The check mark shows for 2 seconds, then the button returns to idle.
- Without a label the button is square and named by `copyLabel`. Blade needs Alpine.js.
