$ show github/clipboard-copy-element
This repository provides a custom HTML element, `<clipboard-copy>`, that copies text or element content to the clipboard when clicked. Implemented as a web component extending `HTMLElement`, it supports multiple data sources: the `value` attribute, a `for` attribute that references another element by ID (including inputs, textareas, and anchor hrefs), or element text content. The element ensures accessibility by automatically adding `role="button"` and `tabindex="0"` if not present, and handles keyboard events (Enter/Space) for activation. Internally, it uses the modern `navigator.clipboard.writeText()` API when available, falling back to `document.execCommand('copy')` via a temporary hidden node. It also normalizes Unicode whitespace characters (e.g., non-breaking spaces, zero-width joiners) to plain spaces or strips them, ensuring the copied text matches visual expectations. A `clipboard-copy` custom event is dispatched on success, allowing external handlers to provide feedback. The source code is written in TypeScript, is well-structured with clear separation of concerns (clipboard logic in `clipboard.ts`, element definition in `clipboard-copy-element.ts`, and a side-effect module for registration), and includes a comprehensive test suite covering element creation, clipboard operations, shadow DOM contexts, and edge cases like disabled state and Unicode normalization. The project follows GitHub's engineering standards (eslint, prettier, CI via GitHub Actions) and is published as an npm package under `@github/clipboard-copy-element`.
The LLM identified 1 files worth highlighting for reuse:
Provides two exported functions, `copyText` and `copyNode`, that handle all clipboard writing logic. `copyText` normalizes Unicode whitespace (replacing separator chars with spaces, stripping zero-width and invisible format chars), then writes to the clipboard using the modern `navigator.clipboard.writeText` API, falling back to `document.execCommand('copy')` via a temporary hidden `<pre>` element. `copyNode` extracts text from an element's `textContent` and delegates to `copyText`. This module is fully isolated (no dependencies on the rest of the component) and could be extracted and reused in any web project that needs robust clipboard copying with cross-browser fallback and Unicode normalization.