Skip to main content

createCopy

Reactive clipboard primitive with duration-based status, ClipboardItem support, and an execCommand fallback.

View as Markdown

createCopy writes strings or ClipboardItem values to the clipboard and tracks the result as reactive state. It writes through the Clipboard API, falls back to document.execCommand('copy') when that API is missing or the write fails, and holds a copied or failed status for a set delay before returning to idle. For a ready-made button, use CopyButton.

Import#

import { createCopy } from 'moraine/utils'

Features#

  • Writes strings with navigator.clipboard.writeText and ClipboardItem values with navigator.clipboard.write. It falls back to document.execCommand('copy') when the matching method is missing or the write throws.
  • Accepts a string, ClipboardItem, ClipboardItem[], a Promise of any of these, or a function returning them.
  • In the fallback path, extracts plain text from a ClipboardItem, or serializes the data with JSON.stringify when no text type is present.
  • Exposes isCopied(), isError(), and status() ('idle' | 'copied' | 'failed'). Both active states reset to idle after resetDelay milliseconds.
  • A newer copy() call supersedes an earlier pending one. The superseded call resolves to false and sets no state.
  • Resolves copy() to false without touching the clipboard on the server, after the owner disposes, or when there is no source (neither the argument nor options.value).

Signature#

function createCopy(options?: CreateCopyOptions): CreateCopyReturn

interface CreateCopyOptions {
  /**
   * Document owning the element that triggers the copy. Used for the execCommand
   * fallback so it targets the same document as the invoking element.
   */
  ownerDocument?: Accessor<Document | undefined>

  /**
   * Default source value to copy if none is provided to copy().
   */
  value?: CopySource

  /**
   * Delay in milliseconds before the 'copied' or 'failed' status returns to 'idle'.
   * @default 2000
   */
  resetDelay?: number | (() => number | undefined)

  /**
   * Callback invoked when a copy succeeds.
   */
  onCopySuccess?: (data: CopyData) => void

  /**
   * Callback invoked when a copy fails.
   */
  onCopyError?: (error: unknown) => void

  /**
   * Callback invoked when the copy status changes.
   */
  onStatusChange?: (details: { isCopied: boolean; status: CopyStatus }) => void
}

interface CreateCopyReturn {
  /** Whether the last copy succeeded and its duration is still active. */
  isCopied: Accessor<boolean>
  /** Whether the last copy failed and its duration is still active. */
  isError: Accessor<boolean>
  status: Accessor<'idle' | 'copied' | 'failed'>
  /** Copies `data`, or `options.value` when omitted. Resolves to whether the copy succeeded. */
  copy: (data?: CopySource) => Promise<boolean>
  /** Returns to `idle`, clears the error, and cancels the pending reset timer. */
  reset: () => void
  /** The last error when a copy failed. */
  error: Accessor<unknown>
  /** Whether the Clipboard API or `execCommand` is available. `false` on the server. */
  isSupported: Accessor<boolean>
}

type CopyData = string | ClipboardItem | ClipboardItem[]
type CopySource = CopyData | Promise<CopyData> | (() => CopyData | Promise<CopyData>)

Usage Example#

src/ClipboardSnippet.tsx
import { createCopy } from 'moraine/utils'

export function ClipboardSnippet() {
  const clipboard = createCopy({
    resetDelay: 2000,
  })

  return (
    <div class="flex gap-2 items-center">
      <code class="px-2 py-1 bg-muted rounded text-xs font-mono">pnpm add moraine</code>
      <button
        type="button"
        onClick={() => clipboard.copy('pnpm add moraine')}
        class="text-xs px-2 py-1 rounded border"
      >
        {clipboard.isCopied() ? 'Copied!' : 'Copy'}
      </button>
    </div>
  )
}

Fallback Mechanics#

When navigator.clipboard is missing or its write call throws, createCopy falls back to document.execCommand('copy'):

  1. For a string, it adds a visually hidden read-only <textarea>, selects the content, and runs the command.
  2. For a ClipboardItem or ClipboardItem[], it looks for a text/plain or text/* type, reads it through item.getType(type) and blob.text(), then runs the command on that text. If no text type is found or reading fails, it runs the command on JSON.stringify(data).