Site
Code block
The site's tabs of code: a #262626 panel with a 56px head of tabs (a White line sliding under the chosen one) and a copy button whose label turns to Copied, over code in White with its punctuation and comments muted, scrolling across. Code and the copy button also stand alone.
Install
React apps get the React files; every other stack gets the web component.
npx spyglass-ds add code-block<script type="module" src="/spyglass-ds/elements/code-block.js"></script>Usage
Requests and setup steps on product, docs and resource pages (tabs of { id, label, code, language }); Code alone inside a response panel or a card; CopyButton beside a URL or a key.
Never
- Colored syntax highlighting: only the muted gray and White
- Code that wraps: it scrolls across and fades at its edges
- A White copy button: it is quiet
Props
The web component takes the same as attributes or properties (<spyglass-code-block>); title is heading there.
<CodeBlock>
| Prop | Type | Default |
|---|---|---|
tabs | CodeTab[] The tabs: { id, label, code, language }. One tab still shows its label. | codeTabsExample |
label | string The tab list's accessible name. | 'Code' |
copy | { label: string; copiedLabel: string; name: string } | { label: 'Copy', copiedLabel: 'Copied', name: 'Copy code' } |
onCopy | (text: string) => void | |
className | string |
<Code>
| Prop | Type | Default |
|---|---|---|
source | string | |
language | string shell, ts, python or json (json keeps `#` as text). | 'shell' |
className | string |
<CopyButton>
| Prop | Type | Default |
|---|---|---|
text | string | |
label | string | 'Copy' |
copiedLabel | string | 'Copied' |
name | string Its accessible name. | 'Copy code' |
selectId | string The element whose text is selected when copying is refused. | |
onCopy | (text: string) => void | |
className | string |
Examples
The same example in React and as web components; both render identically.
import { CodeBlock } from '@/react/components/site/CodeBlock'
// The same request in three languages; the copy button copies the shown tab.
export default function Tabs() {
return <CodeBlock label="Request" className="w-full max-w-160" />
}<!-- The same request in three languages; the copy button copies the shown tab. -->
<spyglass-code-block label="Request" class="w-full max-w-160"></spyglass-code-block>import { CodeBlock } from '@/react/components/site/CodeBlock'
// One tab: setup commands, with comments muted.
export default function Single() {
return <CodeBlock label="Setup" tabs={[{ id: 'shell', label: 'Terminal', language: 'shell', code: '# The CLI\nnpm install -g @acme/cli\n# The MCP server\nhttps://mcp.acme.com/mcp' }]} className="w-full max-w-160" />
}<!-- One tab: setup commands, with comments muted. -->
<spyglass-code-block id="single" label="Setup" class="w-full max-w-160"></spyglass-code-block>
<script type="module">
document.getElementById('single').tabs = [{ id: 'shell', label: 'Terminal', language: 'shell', code: '# The CLI\nnpm install -g @acme/cli\n# The MCP server\nhttps://mcp.acme.com/mcp' }]
</script>import { CopyButton } from '@/react/components/site/CopyButton'
// The copy button on its own, beside a URL on a #262626 field.
export default function Copy() {
return (
<div className="flex min-h-control-lg w-full max-w-120 items-center gap-2 rounded-control bg-surface-raised p-1 ps-4">
<code id="mcp-url" className="min-w-0 flex-1 truncate type-code text-fg">https://mcp.acme.com/mcp</code>
<CopyButton text="https://mcp.acme.com/mcp" name="Copy the URL" selectId="mcp-url" />
</div>
)
}<!-- The copy button on its own, beside a URL on a #262626 field. -->
<div class="flex min-h-control-lg w-full max-w-120 items-center gap-2 rounded-control bg-surface-raised p-1 ps-4">
<code id="mcp-url" class="min-w-0 flex-1 truncate type-code text-fg">https://mcp.acme.com/mcp</code>
<spyglass-copy-button text="https://mcp.acme.com/mcp" name="Copy the URL" select-id="mcp-url"></spyglass-copy-button>
</div>Source
'use client'
import { useId, useLayoutEffect, useRef, useState, type KeyboardEvent } from 'react'
import { Code } from '@/react/components/site/Code'
import { CopyButton } from '@/react/components/site/CopyButton'
import { codeTabsExample, type CodeTab } from '@/lib/code'
import { cn } from '@/react/lib/cn'
// The site's tabs of code (sections/Connect CodeTabs, Code, CopyButton): a #262626 panel with an 8px corner; a 56px
// head with the tabs (14/20 Medium in the muted gray, White when chosen, the soft gray under the pointer; a 2px White
// line under the chosen one that slides to the next) and the copy button for the shown tab, over a hairline; under it
// the code, 16px in (24 from 768), scrolling across and fading at its edges. Arrows, Home and End move between tabs.
export interface CodeBlockProps {
/** The tabs: { id, label, code, language }. One tab still shows its label. */
tabs?: CodeTab[]
/** The tab list's accessible name. */
label?: string
copy?: { label: string; copiedLabel: string; name: string }
onCopy?: (text: string) => void
className?: string
}
export function CodeBlock({ tabs = codeTabsExample, label = 'Code', copy = { label: 'Copy', copiedLabel: 'Copied', name: 'Copy code' }, onCopy, className }: CodeBlockProps) {
const [active, setActive] = useState(0)
const [line, setLine] = useState<{ x: number; w: number } | null>(null)
const id = useId()
const listRef = useRef<HTMLDivElement>(null)
const buttons = useRef<(HTMLButtonElement | null)[]>([])
// The line moves by transform only: a 100px bar placed and scaled to the chosen tab's label.
useLayoutEffect(() => {
const list = listRef.current
if (!list) return
const measure = () => {
const tab = buttons.current[active]
if (!tab || !tab.offsetWidth) return
const pad = parseFloat(getComputedStyle(tab).paddingLeft)
setLine({ x: tab.offsetLeft + pad, w: tab.offsetWidth - 2 * pad })
}
measure()
const observer = new ResizeObserver(measure)
observer.observe(list)
return () => observer.disconnect()
}, [active])
const select = (index: number) => {
setActive(index)
const tab = buttons.current[index]
const list = listRef.current
if (!tab || !list) return
const t = tab.getBoundingClientRect()
const l = list.getBoundingClientRect()
if (t.left < l.left) list.scrollLeft += t.left - l.left
else if (t.right > l.right) list.scrollLeft += t.right - l.right
}
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
const last = tabs.length - 1
const next = e.key === 'ArrowRight' ? (active === last ? 0 : active + 1) : e.key === 'ArrowLeft' ? (active === 0 ? last : active - 1) : e.key === 'Home' ? 0 : e.key === 'End' ? last : -1
if (next < 0) return
e.preventDefault()
select(next)
buttons.current[next]?.focus()
}
if (!tabs.length) return null
const shown = tabs[active] ?? tabs[0]
return (
<div data-ds="code-block" className={cn('min-w-0 rounded-control bg-surface-raised text-fg', className)}>
<div className="relative flex h-control-lg items-center justify-between gap-2 px-1 after:absolute after:inset-x-0 after:bottom-0 after:h-px after:bg-edge-surface md:px-2">
<div ref={listRef} role="tablist" aria-label={label} onKeyDown={onKeyDown} className="fade-x relative isolate flex h-full min-w-0 overflow-x-auto [scrollbar-width:none]">
{line ? <span aria-hidden="true" className="pointer-events-none absolute bottom-0 left-0 z-0 h-0.5 w-25 origin-left bg-fg transition-transform duration-160 ease-loop motion-reduce:transition-none" style={{ transform: `translateX(${line.x}px) scaleX(${line.w / 100})` }} /> : null}
{tabs.map((tab, i) => (
<button
key={tab.id}
ref={(node) => { buttons.current[i] = node }}
type="button"
role="tab"
id={`${id}-tab-${tab.id}`}
aria-selected={i === active}
aria-controls={`${id}-panel-${tab.id}`}
tabIndex={i === active ? 0 : -1}
onClick={() => select(i)}
className="relative z-1 h-full flex-none cursor-pointer rounded-ds-sm px-3 type-ui-strong text-fg-muted transition-[color] duration-160 ease-out outline-offset-[calc(-1*var(--ds-border-focus))] hover:not-aria-selected:text-fg-soft active:text-fg aria-selected:text-fg md:px-4"
>
{tab.label}
</button>
))}
</div>
<CopyButton key={shown.id} text={shown.code} label={copy.label} copiedLabel={copy.copiedLabel} name={copy.name} selectId={`${id}-panel-${shown.id}`} onCopy={onCopy} />
</div>
<div className="grid grid-cols-[minmax(0,1fr)]">
{tabs.map((tab, i) => (
<div
key={tab.id}
role="tabpanel"
id={`${id}-panel-${tab.id}`}
aria-labelledby={`${id}-tab-${tab.id}`}
tabIndex={i === active ? 0 : -1}
inert={i !== active}
className={cn('fade-x min-w-0 overflow-x-auto rounded-b-control p-4 outline-offset-[calc(-1*var(--ds-border-focus))] [grid-area:1/1] [scrollbar-color:var(--ds-color-edge-strong)_transparent] [scrollbar-width:thin] md:p-6', i === active ? 'visible' : 'invisible')}
>
<Code source={tab.code} language={tab.language} />
</div>
))}
</div>
</div>
)
}
export default CodeBlockimport { codeRuns } from '@/lib/code'
import { cn } from '@/react/lib/cn'
// The site's code (sections/Connect Code): mono 14/20 in White, as wide as its longest line, with comments,
// punctuation and string quotes in the muted gray. Put it in something that scrolls across.
export interface CodeProps {
source: string
/** shell, ts, python or json (json keeps `#` as text). */
language?: string
className?: string
}
export function Code({ source, language = 'shell', className }: CodeProps) {
return (
<pre data-ds="code" className={cn('m-0 w-max type-code text-fg [tab-size:2]', className)}>
<code>{codeRuns(source, language).map((r, i) => (r.dim ? <span key={i} className="text-fg-muted">{r.text}</span> : r.text))}</code>
</pre>
)
}
export default Code'use client'
import { useEffect, useRef, useState } from 'react'
import { copyText } from '@/lib/code'
import { cn } from '@/react/lib/cn'
// The site's copy button (sections/Connect CopyButton): a quiet 40px button with a 4px corner, its label in the soft
// gray (White under the pointer); a press puts `text` on the clipboard and the label crosses over to "Copied" (up and
// out, up and in, 160ms) for 2s. If the clipboard is refused, the text in `selectId` is selected instead.
export interface CopyButtonProps {
text: string
label?: string
copiedLabel?: string
/** Its accessible name. */
name?: string
/** The element whose text is selected when copying is refused. */
selectId?: string
onCopy?: (text: string) => void
className?: string
}
export const COPY_BUTTON =
'ds-copy relative inline-flex h-control-md min-w-20 flex-none cursor-pointer items-center justify-center rounded-ds-sm bg-action-secondary px-4 type-ui-strong whitespace-nowrap text-fg-soft shadow-[inset_0_0_0_var(--ds-border-hairline)_var(--ds-color-action-secondary-edge)] transition-[background-color,color] duration-160 ease-out select-none before:absolute before:-inset-y-2 before:inset-x-0 hover:bg-action-secondary-hover hover:text-fg data-copied:text-fg'
export function CopyButton({ text, label = 'Copy', copiedLabel = 'Copied', name = 'Copy code', selectId, onCopy, className }: CopyButtonProps) {
const [copied, setCopied] = useState(false)
const timer = useRef<number | undefined>(undefined)
useEffect(() => () => window.clearTimeout(timer.current), [])
const copy = async () => {
const ok = await copyText(text)
if (!ok) {
const target = selectId ? document.getElementById(selectId) : null
if (target) window.getSelection()?.selectAllChildren(target)
return
}
setCopied(true)
onCopy?.(text)
window.clearTimeout(timer.current)
timer.current = window.setTimeout(() => setCopied(false), 2000)
}
return (
<span data-ds="copy-button" className="contents">
<style href="ds-copy-button" precedence="ds">{css}</style>
<button type="button" aria-label={name} data-copied={copied || undefined} className={cn(COPY_BUTTON, className)} onClick={copy}>
<span aria-hidden="true" className="grid justify-items-center">
<span className="ds-copy-idle [grid-area:1/1]">{label}</span>
<span className="ds-copy-done [grid-area:1/1]">{copiedLabel}</span>
</span>
</button>
<span role="status" className="sr-only">{copied ? copiedLabel : ''}</span>
</span>
)
}
export default CopyButton
const css = `
.ds-copy-idle, .ds-copy-done { transition: opacity var(--ds-duration-micro) var(--ds-easing-out), transform var(--ds-duration-micro) var(--ds-easing-out); }
.ds-copy-done { opacity: 0; transform: translateY(var(--ds-space-xs)); }
.ds-copy[data-copied] .ds-copy-idle { opacity: 0; transform: translateY(calc(-1 * var(--ds-space-xs))); }
.ds-copy[data-copied] .ds-copy-done { opacity: 1; transform: none; }
@media (prefers-reduced-motion: reduce) {
.ds-copy-done, .ds-copy[data-copied] .ds-copy-idle { transform: none; }
}
`// The site's code display (sections/Connect Code, CopyButton): source split into runs, with comments, punctuation and
// string quotes in the muted gray and everything else White; and a copy that falls back to a hidden textarea. Both
// flavors read it.
export interface CodeRun { text: string; dim?: boolean }
const TOKEN = /(#.*$)|("(?:[^"\\]|\\.)*")|(https?:\/\/[^\s"']+)|([{}[\]():,=\\.'])/gm
/** The runs of `source`; JSON keeps `#` as text. */
export function codeRuns(source: string, language = 'shell'): CodeRun[] {
const out: CodeRun[] = []
let last = 0
for (const match of source.matchAll(TOKEN)) {
const [text, comment, string, url, mark] = match
const at = match.index ?? 0
if (comment && language === 'json') continue
if (at > last) out.push({ text: source.slice(last, at) })
if (comment || mark) out.push({ text, dim: true })
else if (url) out.push({ text })
else if (string) out.push({ text: '"', dim: true }, { text: string.slice(1, -1) }, { text: '"', dim: true })
last = at + text.length
}
if (last < source.length) out.push({ text: source.slice(last) })
return out
}
/** Puts `text` on the clipboard; true when it worked. */
export async function copyText(text: string): Promise<boolean> {
try {
await navigator.clipboard.writeText(text)
return true
} catch {}
const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null
const area = document.createElement('textarea')
area.value = text
area.setAttribute('readonly', '')
area.style.cssText = 'position:fixed;opacity:0;pointer-events:none'
document.body.append(area)
area.focus({ preventScroll: true })
area.select()
let ok = false
try {
ok = document.execCommand('copy')
} catch {}
area.remove()
previous?.focus({ preventScroll: true })
return ok
}
export interface CodeTab { id: string; label: string; code: string; language?: string }
export const codeTabsExample: CodeTab[] = [
{ id: 'curl', label: 'cURL', language: 'shell', code: '# Search the ads of a brand\ncurl "https://api.acme.com/v1/search" \\\n -H "Authorization: Bearer $ACME_KEY" \\\n -d \'{"query": "skincare launches", "limit": 20}\'' },
{ id: 'ts', label: 'TypeScript', language: 'ts', code: 'const res = await fetch("https://api.acme.com/v1/search", {\n method: "POST",\n headers: { Authorization: `Bearer ${key}` },\n body: JSON.stringify({ query: "skincare launches", limit: 20 }),\n})' },
{ id: 'py', label: 'Python', language: 'python', code: 'import requests\n\nres = requests.post(\n "https://api.acme.com/v1/search",\n headers={"Authorization": f"Bearer {key}"},\n json={"query": "skincare launches", "limit": 20},\n)' },
]// Joins class names, skipping falsy ones: cn('a', on && 'b', ['c', undefined]). It does not merge conflicting
// utilities (no tailwind-merge), as Vue's class binding does not: the library's classes are written not to compete,
// and a className from the caller is appended after them, as Vue appends a fallthrough class.
export type ClassValue = string | false | null | undefined | 0 | ClassValue[]
export function cn(...values: ClassValue[]): string {
const out: string[] = []
for (const v of values) {
if (!v) continue
if (Array.isArray(v)) {
const s = cn(...v)
if (s) out.push(s)
}
else out.push(v)
}
return out.join(' ')
}import { html, nothing } from 'lit'
import { keyed } from 'lit/directives/keyed.js'
import { DsElement, define, HostLayoutController, uid } from '@/elements/lib/element'
import { codeTabsExample, type CodeTab } from '@/lib/code'
import '@/elements/components/site/code'
import '@/elements/components/site/copy-button'
import styles from 'virtual:tw'
// CodeBlock.tsx as <spyglass-code-block>: tabs of code on a #262626 panel, the White line sliding under the chosen tab,
// the copy button for the shown tab, the code scrolling across and fading at its edges. Arrows, Home and End move
// between tabs. `tabs` (JSON: { id, label, code, language }), `label`, `copy` (JSON: { label, copiedLabel, name });
// the copy button's `copy` event bubbles out.
/** @summary Tabs of code with a copy button. */
export class CodeBlock extends DsElement {
static styles = [DsElement.styles, styles]
protected readonly layout = new HostLayoutController(this, () => this.renderRoot.querySelector<HTMLElement>('[data-ds="code-block"]'))
static properties = { tabs: { type: Array }, label: {}, copy: { type: Object }, active: { state: true }, line: { state: true } }
tabs: CodeTab[] = codeTabsExample
/** The tab list's accessible name. */
label = 'Code'
copy = { label: 'Copy', copiedLabel: 'Copied', name: 'Copy code' }
private active = 0
private line: { x: number; w: number } | null = null
private blockId = uid('code')
private observer?: ResizeObserver
private get list() { return this.renderRoot.querySelector<HTMLElement>('[role="tablist"]') }
private get buttons() { return [...this.renderRoot.querySelectorAll<HTMLButtonElement>('[role="tab"]')] }
private measure = () => {
const tab = this.buttons[this.active]
if (!tab || !tab.offsetWidth) return
const pad = parseFloat(getComputedStyle(tab).paddingLeft)
const next = { x: tab.offsetLeft + pad, w: tab.offsetWidth - 2 * pad }
if (next.x !== this.line?.x || next.w !== this.line?.w) this.line = next
}
protected firstUpdated(changed: Map<string, unknown>) {
super.firstUpdated(changed as never)
this.observer = new ResizeObserver(this.measure)
if (this.list) this.observer.observe(this.list)
}
protected updated(changed: Map<string, unknown>) {
super.updated(changed as never)
if (changed.has('active') || changed.has('tabs')) this.measure()
}
disconnectedCallback() {
super.disconnectedCallback()
this.observer?.disconnect()
}
private select(index: number) {
this.active = index
const tab = this.buttons[index]
const list = this.list
if (!tab || !list) return
const t = tab.getBoundingClientRect()
const l = list.getBoundingClientRect()
if (t.left < l.left) list.scrollLeft += t.left - l.left
else if (t.right > l.right) list.scrollLeft += t.right - l.right
}
private onKeyDown(e: KeyboardEvent) {
const last = (this.tabs ?? []).length - 1
const a = this.active
const next = e.key === 'ArrowRight' ? (a === last ? 0 : a + 1) : e.key === 'ArrowLeft' ? (a === 0 ? last : a - 1) : e.key === 'Home' ? 0 : e.key === 'End' ? last : -1
if (next < 0) return
e.preventDefault()
this.select(next)
this.updateComplete.then(() => this.buttons[next]?.focus())
}
render() {
const tabs = this.tabs ?? []
if (!tabs.length) return nothing
const shown = tabs[this.active] ?? tabs[0]
const id = this.blockId
const copy = this.copy ?? { label: 'Copy', copiedLabel: 'Copied', name: 'Copy code' }
return html`<div data-ds="code-block" class="min-w-0 rounded-control bg-surface-raised text-fg"><div class="relative flex h-control-lg items-center justify-between gap-2 px-1 after:absolute after:inset-x-0 after:bottom-0 after:h-px after:bg-edge-surface md:px-2"><div role="tablist" aria-label=${this.label} @keydown=${this.onKeyDown} class="fade-x relative isolate flex h-full min-w-0 overflow-x-auto [scrollbar-width:none]">${this.line ? html`<span aria-hidden="true" class="pointer-events-none absolute bottom-0 left-0 z-0 h-0.5 w-25 origin-left bg-fg transition-transform duration-160 ease-loop motion-reduce:transition-none" style=${`transform: translateX(${this.line.x}px) scaleX(${this.line.w / 100})`}></span>` : nothing}${tabs.map((tab, i) => html`<button type="button" role="tab" id=${`${id}-tab-${tab.id}`} aria-selected=${String(i === this.active)} aria-controls=${`${id}-panel-${tab.id}`} tabindex=${i === this.active ? 0 : -1} @click=${() => this.select(i)} class="relative z-1 h-full flex-none cursor-pointer rounded-ds-sm px-3 type-ui-strong text-fg-muted transition-[color] duration-160 ease-out outline-offset-[calc(-1*var(--ds-border-focus))] hover:not-aria-selected:text-fg-soft active:text-fg aria-selected:text-fg md:px-4">${tab.label}</button>`)}</div>${keyed(shown.id, html`<spyglass-copy-button .text=${shown.code} .label=${copy.label} .copiedLabel=${copy.copiedLabel} .name=${copy.name} select-id=${`${id}-panel-${shown.id}`}></spyglass-copy-button>`)}</div><div class="grid grid-cols-[minmax(0,1fr)]">${tabs.map((tab, i) => html`<div role="tabpanel" id=${`${id}-panel-${tab.id}`} aria-labelledby=${`${id}-tab-${tab.id}`} tabindex=${i === this.active ? 0 : -1} ?inert=${i !== this.active} class=${`fade-x min-w-0 overflow-x-auto rounded-b-control p-4 outline-offset-[calc(-1*var(--ds-border-focus))] [grid-area:1/1] [scrollbar-color:var(--ds-color-edge-strong)_transparent] [scrollbar-width:thin] md:p-6 ${i === this.active ? 'visible' : 'invisible'}`}><spyglass-code .source=${tab.code} .language=${tab.language ?? 'shell'}></spyglass-code></div>`)}</div></div>`
}
}
define('code-block', CodeBlock)import { html } from 'lit'
import { DsElement, define, HostLayoutController } from '@/elements/lib/element'
import { codeRuns } from '@/lib/code'
import styles from 'virtual:tw'
// Code.tsx as <spyglass-code>: mono 14/20 in White, as wide as its longest line, comments, punctuation and string
// quotes in the muted gray. `source` and `language` (shell, ts, python or json).
/** @summary Source code with the site's muted punctuation. */
export class Code extends DsElement {
static styles = [DsElement.styles, styles]
protected readonly layout = new HostLayoutController(this, () => this.renderRoot.querySelector<HTMLElement>('[data-ds="code"]'))
static properties = { source: {}, language: {} }
source = ''
/** shell, ts, python or json (json keeps `#` as text). */
language = 'shell'
render() {
return html`<pre data-ds="code" class="m-0 w-max type-code text-fg [tab-size:2]"><code>${codeRuns(this.source ?? '', this.language).map((r) => (r.dim ? html`<span class="text-fg-muted">${r.text}</span>` : r.text))}</code></pre>`
}
}
define('code', Code)import { html } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { DsElement, define, HostLayoutController } from '@/elements/lib/element'
import { copyText } from '@/lib/code'
import styles from 'virtual:tw'
// CopyButton.tsx as <spyglass-copy-button>: the quiet 40px copy button whose label crosses over to "Copied" for 2s.
// `text`, `label`, `copied-label`, `name` (its accessible name), `select-id` (selected when copying is refused, looked up
// in the same document or shadow root); fires `copy` with detail.text.
export const COPY_BUTTON =
'ds-copy relative inline-flex h-control-md min-w-20 flex-none cursor-pointer items-center justify-center rounded-ds-sm bg-action-secondary px-4 type-ui-strong whitespace-nowrap text-fg-soft shadow-[inset_0_0_0_var(--ds-border-hairline)_var(--ds-color-action-secondary-edge)] transition-[background-color,color] duration-160 ease-out select-none before:absolute before:-inset-y-2 before:inset-x-0 hover:bg-action-secondary-hover hover:text-fg data-copied:text-fg'
/**
* @summary A quiet button that copies text and says so.
* @fires copy - After copying; detail.text.
*/
export class CopyButton extends DsElement {
static styles = [DsElement.styles, styles]
protected readonly layout = new HostLayoutController(this, () => this.renderRoot.querySelector<HTMLElement>('button'))
static properties = { text: {}, label: {}, copiedLabel: { attribute: 'copied-label' }, name: {}, selectId: { attribute: 'select-id' }, copied: { state: true } }
text = ''
label = 'Copy'
copiedLabel = 'Copied'
/** Its accessible name. */
name = 'Copy code'
selectId?: string
private copied = false
private timer = 0
disconnectedCallback() {
super.disconnectedCallback()
clearTimeout(this.timer)
}
private async copy() {
const ok = await copyText(this.text)
if (!ok) {
const root = this.getRootNode() as Document | ShadowRoot
const target = this.selectId ? root.getElementById?.(this.selectId) : null
if (target) window.getSelection()?.selectAllChildren(target)
return
}
this.copied = true
this.emit('copy', { text: this.text })
clearTimeout(this.timer)
this.timer = window.setTimeout(() => (this.copied = false), 2000)
}
render() {
return html`<span data-ds="copy-button" class="contents"><button type="button" aria-label=${this.name} data-copied=${ifDefined(this.copied ? '' : undefined)} class=${COPY_BUTTON} @click=${this.copy}><span aria-hidden="true" class="grid justify-items-center"><span class="ds-copy-idle [grid-area:1/1]">${this.label}</span><span class="ds-copy-done [grid-area:1/1]">${this.copiedLabel}</span></span></button><span role="status" class="sr-only">${this.copied ? this.copiedLabel : ''}</span></span>`
}
}
define('copy-button', CopyButton).ds-copy-idle, .ds-copy-done { transition: opacity var(--ds-duration-micro) var(--ds-easing-out), transform var(--ds-duration-micro) var(--ds-easing-out); }
.ds-copy-done { opacity: 0; transform: translateY(var(--ds-space-xs)); }
.ds-copy[data-copied] .ds-copy-idle { opacity: 0; transform: translateY(calc(-1 * var(--ds-space-xs))); }
.ds-copy[data-copied] .ds-copy-done { opacity: 1; transform: none; }
@media (prefers-reduced-motion: reduce) {
.ds-copy-done, .ds-copy[data-copied] .ds-copy-idle { transform: none; }
}Reference: Site sections/Connect (Code.tsx, CodeTabs.tsx, CopyButton.tsx, Connect.module.css .panel, .tab, .tabLine, .codePanel, .pre, .copy): --surface panel, --radius-m; head --control-l, 4px in (8 from 768), --line-surface hairline; tabs 14/20 Medium --text-3, 12px in (16 from 768), a --stroke White line on the sliding pill; .btn--quiet .btn--s copy at 80px or wider, --radius-s, labels crossing 4px over --dur-fast; panels 16px in (24 from 768), mono --small-size.