{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "code-snippet",
  "type": "registry:ui",
  "title": "<ui-code-snippet>",
  "description": "Carbon `CodeSnippet`. `type=\"single\"`: one 40px line that scrolls sideways, read-only textbox, copy button at the end. `type=\"multi\"`: a block collapsed to at most `max-collapsed-rows` (15 × 16px) with a \"Show more\" / \"Show less\" button when longer, copy button top-right, optional `wrap-text`. `type=\"inline\"`: a `<code>` chip that is itself the copy button (or plain with `hide-copy-button`). The copied text is `text`, else the slotted content. Copied from @purpurabog/ui 2.3.0; the package is the maintained source, this copy is yours to change. Icons from the Carbon Design System (Apache-2.0, © IBM Corp.; see THIRD-PARTY-NOTICES.md in the package).",
  "dependencies": [
    "lit@^3.3.0"
  ],
  "registryDependencies": [
    "@kanok-ui/copy-button",
    "@kanok-ui/core-code-snippet",
    "@kanok-ui/shared-align",
    "@kanok-ui/shared-element",
    "@kanok-ui/shared-events",
    "@kanok-ui/shared-field",
    "@kanok-ui/shared-localize",
    "@kanok-ui/shared-skeleton",
    "@kanok-ui/tooltip",
    "@kanok-ui/tokens"
  ],
  "files": [
    {
      "path": "src/primitives/code-snippet/code-snippet-skeleton.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/code-snippet/code-snippet-skeleton.ts",
      "content": "import { html, css } from 'lit';\nimport { customElement, property } from 'lit/decorators.js';\nimport { skeletonStyles, UiSkeletonElement } from '../shared/skeleton.ts';\n\n/**\n * Carbon `CodeSnippetSkeleton` (`cds-code-snippet-skeleton`): a layer box, 56px tall with one 16px bar (`single`),\n * or 98px with three lines at 100 / 85 / 95% (`multi`). Hidden from assistive tech.\n *\n * @csspart base - The box\n * @csspart line - Each bar\n */\n@customElement('ui-code-snippet-skeleton')\nexport class UiCodeSnippetSkeleton extends UiSkeletonElement {\n    static override readonly styles = [\n        skeletonStyles,\n        css`\n            :host {\n                display: block;\n                max-inline-size: 768px;\n            }\n\n            .box {\n                box-sizing: border-box;\n                block-size: 56px;\n                padding: 20px 40px 0 var(--ui-space-md);\n                background-color: var(--ui-surface-1);\n            }\n\n            .bone {\n                display: block;\n                block-size: 16px;\n            }\n\n            :host([type='multi']) .box {\n                display: flex;\n                flex-direction: column;\n                gap: var(--ui-space-xs);\n                block-size: 98px;\n                padding: var(--ui-space-md);\n            }\n\n            :host([type='multi']) .bone:nth-child(2) {\n                inline-size: 85%;\n            }\n\n            :host([type='multi']) .bone:nth-child(3) {\n                inline-size: 95%;\n            }\n        `,\n    ];\n\n    @property({ reflect: true }) type: 'single' | 'multi' = 'single';\n\n    override render() {\n        const lines = this.type === 'multi' ? 3 : 1;\n        const line = html`<span class=\"bone\" part=\"line\"></span>`;\n        return html`<div class=\"box\" part=\"base\">${Array.from({ length: lines }, () => line)}</div>`;\n    }\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-code-snippet-skeleton': UiCodeSnippetSkeleton;\n    }\n}\n"
    },
    {
      "path": "src/primitives/code-snippet/code-snippet.ts",
      "type": "registry:ui",
      "target": "components/ui/primitives/code-snippet/code-snippet.ts",
      "content": "import { LitElement, html, css, nothing } from 'lit';\nimport { customElement, property, query, state } from 'lit/decorators.js';\nimport { classMap } from 'lit/directives/class-map.js';\nimport { ifDefined } from 'lit/directives/if-defined.js';\nimport { styleMap } from 'lit/directives/style-map.js';\nimport { srOnlyStyles } from '../shared/field.ts';\nimport type { TooltipPlacement, UiTooltip } from '../tooltip/tooltip.ts';\nimport { copyToClipboard } from '../copy-button/copy-button.ts'; // also defines <ui-copy-button>\nimport '../tooltip/tooltip.ts';\nimport { LocalizeController } from '../shared/localize.ts';\nimport type { ExpandedDetail, CopyDetail } from '../shared/events.ts';\nimport { WithAlign } from '../shared/align.ts';\nimport { UiElement } from '../shared/element.ts';\nimport { snippetCanExpand, snippetCopyText, snippetHeights, snippetShouldCollapse, type SnippetRows } from '../../core/code-snippet.ts';\n\nexport type CodeSnippetType = 'single' | 'multi' | 'inline';\n\nconst chevron = html`<svg class=\"chevron\" viewBox=\"0 0 16 16\" aria-hidden=\"true\"><path d=\"M8 11 3 6l.7-.7L8 9.6l4.3-4.3.7.7z\" /></svg>`;\n\n/**\n * Carbon `CodeSnippet`. `type=\"single\"`: one 40px line that scrolls sideways, read-only textbox,\n * copy button at the end. `type=\"multi\"`: a block collapsed to at most `max-collapsed-rows`\n * (15 × 16px) with a \"Show more\" / \"Show less\" button when longer, copy button top-right,\n * optional `wrap-text`. `type=\"inline\"`: a `<code>` chip that is itself the copy button\n * (or plain with `hide-copy-button`). The copied text is `text`, else the slotted content.\n *\n * As in `<pre>`, one line break directly after the opening tag is dropped.\n *\n * @slot - The code\n * @fires ui-copy - detail: { text }; cancelable\n * @fires ui-toggle - detail: { expanded } when \"Show more / less\" is used\n * @csspart container - Scrolling container (single) / `<pre>` wrapper (multi)\n * @csspart code - The `<code>` element\n * @csspart copy-button - The `<ui-copy-button>` (single / multi)\n * @csspart expand-button - The \"Show more / less\" button (multi)\n * @attr align - Carbon's name for `placement` (same values)\n * @cssprop --ui-code-background - Fill of the snippet (default `--ui-surface-1`; Kanok: a light grey on its white surfaces)\n * @cssprop --ui-code-radius - Corners of the single and multi-line snippets (default 0; Kanok: 8px; the inline chip keeps its 4px)\n * @cssprop --ui-focus-offset - `outline-offset` of its focus ring (default -2px: inside; Kanok: 2px outside)\n */\n@customElement('ui-code-snippet')\nexport class UiCodeSnippet extends WithAlign(UiElement) {\n    /** `el.focus()` lands on the control inside. */\n    static override readonly shadowRootOptions: ShadowRootInit = { ...LitElement.shadowRootOptions, delegatesFocus: true };\n\n    static override readonly styles = [srOnlyStyles, css`\n        :host {\n            display: block;\n            position: relative;\n            inline-size: 100%;\n            max-inline-size: 768px;\n            font-family: var(--ui-font-family);\n        }\n\n        :host([type='inline']) {\n            display: inline;\n            inline-size: auto;\n            max-inline-size: none;\n        }\n\n        code,\n        pre {\n            margin: 0;\n            font: var(--ui-font-code);\n            letter-spacing: var(--ui-tracking-code);\n            color: var(--ui-ink);\n        }\n\n        pre {\n            white-space: pre;\n        }\n\n        /* ---- single ---- */\n        .single {\n            display: flex;\n            align-items: center;\n            box-sizing: border-box;\n            block-size: 40px;\n            padding-inline-end: 40px;\n            border-radius: var(--ui-code-radius, 0); /* square in Carbon; Kanok 8px */\n            background-color: var(--ui-code-background, var(--ui-surface-1));\n        }\n\n        .single.no-copy {\n            padding: 0;\n        }\n\n        .single .container {\n            position: relative;\n            display: flex;\n            align-items: center;\n            block-size: 100%;\n            inline-size: 100%;\n            overflow-x: auto;\n            padding-inline-start: var(--ui-space-md);\n            outline: none;\n        }\n\n        .single .container:focus-visible {\n            outline: var(--ui-focus-width, 2px) solid var(--ui-focus);\n            outline-offset: -2px;\n            border-radius: var(--ui-code-radius, 0); /* the snippet's own corners (Kanok: 8px) */\n        }\n\n        .single pre {\n            padding-inline-end: var(--ui-space-xs);\n        }\n\n        /* ---- multi ---- */\n        .multi {\n            position: relative;\n            display: flex;\n            box-sizing: border-box;\n            padding: var(--ui-space-md);\n            border-radius: var(--ui-code-radius, 0);\n            background-color: var(--ui-code-background, var(--ui-surface-1));\n        }\n\n        .multi .container {\n            position: relative;\n            order: 1;\n            inline-size: 100%;\n            overflow-y: auto;\n            transition: max-height var(--ui-duration-moderate-01) var(--ui-easing); /* Carbon moderate-01 */\n        }\n\n        .multi pre {\n            padding-inline-end: 40px;\n            outline: none;\n        }\n\n        .multi pre:focus-visible {\n            outline: var(--ui-focus-width, 2px) solid var(--ui-focus);\n            outline-offset: 0;\n            border-radius: var(--ui-link-focus-radius, 0); /* inside the snippet's padding (Kanok: 4px) */\n        }\n\n        .multi.no-copy pre {\n            padding-inline-end: 0;\n        }\n\n        .multi.expanded .container {\n            padding-block-end: var(--ui-space-md);\n        }\n\n        .multi.wrap pre {\n            white-space: pre-wrap;\n            overflow-wrap: break-word;\n        }\n\n        .multi code {\n            display: block;\n            overflow: hidden;\n        }\n\n        .copy-button {\n            position: absolute;\n            inset-block-start: 0;\n            inset-inline-end: 0;\n            z-index: 10;\n        }\n\n        .multi .copy-button {\n            inset-block-start: var(--ui-space-xs);\n            inset-inline-end: var(--ui-space-xs);\n        }\n\n        .expand {\n            position: absolute;\n            z-index: 10;\n            inset-block-end: 0;\n            inset-inline-end: 0;\n            display: inline-flex;\n            align-items: center;\n            block-size: 32px;\n            padding: var(--ui-space-xs) var(--ui-space-md);\n            border: 0;\n            border-end-end-radius: var(--ui-code-radius, 0); /* it sits in the snippet's corner */\n            background-color: var(--ui-code-background, var(--ui-surface-1));\n            color: var(--ui-ink);\n            font: var(--ui-font-body-sm);\n            line-height: 18px; /* body-compact-01 */\n            letter-spacing: var(--ui-tracking-body);\n            cursor: pointer;\n            outline: none;\n            /* Carbon .cds--btn: the fill and the ring change in fast-01 with the entrance easing */\n            transition:\n                background-color var(--ui-duration-fast) var(--ui-easing-entrance),\n                outline var(--ui-duration-fast) var(--ui-easing-entrance);\n        }\n\n        .expand:hover {\n            background-color: var(--ui-ghost-hover);\n        }\n\n        .expand:active {\n            background-color: var(--ui-ghost-active);\n        }\n\n        .expand:focus-visible {\n            outline: var(--ui-focus-width, 2px) solid var(--ui-focus);\n            outline-offset: var(--ui-focus-offset, -2px);\n        }\n\n        .expand .text {\n            position: relative;\n            inset-block-start: -1px;\n        }\n\n        .chevron {\n            width: 16px;\n            height: 16px;\n            margin-inline-start: var(--ui-space-xs);\n            fill: var(--ui-icon-primary);\n            transition: all var(--ui-duration-moderate-01) var(--ui-easing); /* Carbon moderate-01; collapsing */\n        }\n\n        /* opening, Carbon turns it with $transition-expansion (300ms, no token) and the browser's ease */\n        .expanded .chevron {\n            transform: rotate(180deg);\n            transition: transform 300ms;\n        }\n\n        @media (prefers-reduced-motion: reduce) {\n            .expanded .chevron {\n                transition: none;\n            }\n        }\n\n        /* ---- inline ---- */\n        .inline {\n            position: relative;\n            display: inline;\n            box-sizing: border-box;\n            block-size: 20px;\n            min-block-size: 20px;\n            padding: 0;\n            border: 1px solid transparent;\n            border-radius: 4px;\n            background-color: var(--ui-code-background, var(--ui-surface-1));\n            color: var(--ui-ink);\n            font: var(--ui-font-code);\n            letter-spacing: var(--ui-tracking-code);\n            cursor: pointer;\n            outline: none;\n        }\n\n        .inline code {\n            padding: 0 var(--ui-space-xs);\n            white-space: pre;\n        }\n\n        .inline:hover {\n            background-color: var(--ui-ghost-hover);\n        }\n\n        .inline:active {\n            background-color: var(--ui-ghost-active);\n        }\n\n        .inline:focus-visible {\n            border-color: var(--ui-focus);\n        }\n\n        .inline.no-copy {\n            display: inline-block;\n            cursor: auto;\n        }\n\n        .inline.no-copy:hover {\n            background-color: var(--ui-code-background, var(--ui-surface-1));\n        }\n\n        /* ---- disabled ---- */\n        .disabled,\n        .disabled .expand,\n        .disabled .inline {\n            color: var(--ui-ink-disabled);\n            cursor: not-allowed;\n        }\n\n        .disabled code,\n        .disabled pre {\n            color: var(--ui-ink-disabled);\n        }\n\n        .disabled .expand:hover,\n        .disabled .inline:hover {\n            background-color: var(--ui-code-background, var(--ui-surface-1));\n        }\n\n        .disabled .chevron {\n            fill: var(--ui-icon-disabled);\n        }\n\n        @media (forced-colors: active) {\n            .single,\n            .multi,\n            .inline {\n                outline: 1px solid CanvasText;\n            }\n        }\n    `];\n\n    @property({ reflect: true }) type: CodeSnippetType = 'single';\n\n\n    private readonly localize = new LocalizeController(this);\n\n    /** Text to copy instead of the slotted content. */\n    @property() text = '';\n\n    /** Accessible name of the read-only textbox (single / multi); inline: the copy button's tooltip and description (the button is named by its code, WCAG 2.5.3). */\n    @property() label = '';\n\n    /** Tooltip of the copy button (single / multi). */\n    @property({ attribute: 'copy-label' }) copyLabel = '';\n\n    @property() feedback = '';\n\n    @property({ type: Number, attribute: 'feedback-timeout' }) feedbackTimeout = 2000;\n\n    @property() placement: TooltipPlacement = 'bottom';\n\n    @property({ type: Boolean, attribute: 'hide-copy-button' }) hideCopyButton = false;\n\n    @property({ type: Boolean, attribute: 'wrap-text' }) wrapText = false;\n\n    @property({ type: Boolean, reflect: true }) disabled = false;\n\n    @property({ type: Boolean, reflect: true }) expanded = false;\n\n    @property({ attribute: 'show-more-text' }) showMoreText = '';\n\n    @property({ attribute: 'show-less-text' }) showLessText = '';\n\n    /** Rows (16px) visible while collapsed; 0 = no limit. */\n    @property({ type: Number, attribute: 'max-collapsed-rows' }) maxCollapsedRows = 15;\n\n    /** Rows visible while expanded; 0 = no limit. */\n    @property({ type: Number, attribute: 'max-expanded-rows' }) maxExpandedRows = 0;\n\n    @property({ type: Number, attribute: 'min-collapsed-rows' }) minCollapsedRows = 3;\n\n    @property({ type: Number, attribute: 'min-expanded-rows' }) minExpandedRows = 16;\n\n    @state() private canExpand = false;\n\n    @state() private copied = false;\n\n    @query('code') private readonly codeEl!: HTMLElement | null;\n\n    @query('ui-tooltip') private readonly inlineTooltip!: UiTooltip | null;\n\n    private observer?: ResizeObserver;\n    private timer?: number;\n\n    override connectedCallback() {\n        super.connectedCallback();\n        this.observer ??= new ResizeObserver(() => this.measure());\n        if (this.hasUpdated && this.codeEl) this.observer.observe(this.codeEl); // moved: observe again\n    }\n\n    override disconnectedCallback() {\n        super.disconnectedCallback();\n        this.observer?.disconnect();\n        clearTimeout(this.timer);\n    }\n\n    protected override firstUpdated() {\n        if (this.codeEl) this.observer?.observe(this.codeEl);\n    }\n\n    protected override updated(changed: Map<string, unknown>) {\n        if (changed.has('type') && this.codeEl) {\n            this.observer?.disconnect();\n            this.observer?.observe(this.codeEl);\n        }\n        if (changed.has('expanded') && changed.get('expanded') !== undefined) {\n            this.dispatchEvent(new CustomEvent('ui-toggle', { detail: { expanded: this.expanded }, bubbles: true, composed: true }));\n        }\n    }\n\n    /** What gets copied: `text`, else the slotted code. */\n    get copyText() {\n        return snippetCopyText(this.text, this.textContent ?? '');\n    }\n\n    /** Carbon: the Show more / less button appears when the code is taller than the collapsed limit. */\n    private measure() {\n        if (this.type !== 'multi' || !this.codeEl) {\n            this.canExpand = false;\n            return;\n        }\n        const height = this.codeEl.getBoundingClientRect().height;\n        this.canExpand = snippetCanExpand(height, this.rows);\n        if (this.expanded && snippetShouldCollapse(height, this.rows)) this.expanded = false;\n    }\n\n    private get rows(): SnippetRows {\n        return { maxCollapsedRows: this.maxCollapsedRows, maxExpandedRows: this.maxExpandedRows, minCollapsedRows: this.minCollapsedRows, minExpandedRows: this.minExpandedRows };\n    }\n\n    /** Like `<pre>`: drop one line break right after the opening tag. */\n    private onSlotChange() {\n        const first = this.firstChild;\n        if (first?.nodeType === Node.TEXT_NODE && first.textContent?.startsWith('\\n')) first.textContent = first.textContent.slice(1);\n        this.measure();\n        this.requestUpdate();\n    }\n\n    private containerStyle() {\n        if (this.type !== 'multi') return {};\n        const { max, min } = snippetHeights(this.expanded, this.rows);\n        return { maxHeight: max === undefined ? null : `${max}px`, minHeight: min === undefined ? null : `${min}px` };\n    }\n\n    private async copyInline() {\n        if (this.disabled) return;\n        const event = new CustomEvent('ui-copy', { detail: { text: this.copyText }, bubbles: true, composed: true, cancelable: true });\n        if (this.dispatchEvent(event) && !(await copyToClipboard(this.copyText))) return; // no \"Copied!\" when the copy failed\n        const tooltip = this.inlineTooltip;\n        if (!tooltip) return;\n        clearTimeout(this.timer);\n        this.copied = true;\n        tooltip.pinned = true;\n        tooltip.open = true;\n        this.timer = globalThis.setTimeout(() => {\n            this.copied = false;\n            tooltip.pinned = false;\n            tooltip.open = false;\n        }, this.feedbackTimeout);\n    }\n\n    private renderInline() {\n        const code = html`<code part=\"code\"><slot @slotchange=${this.onSlotChange}></slot></code>`;\n        if (this.hideCopyButton) return html`<span class=\"inline no-copy ${classMap({ disabled: this.disabled })}\">${code}</span>`;\n        return html`<ui-tooltip small text=${this.copied ? (this.feedback || this.localize.t.copy.copied) : (this.label || this.localize.t.copy.copy)} placement=${this.placement}>\n            <button class=\"inline ${classMap({ disabled: this.disabled })}\" type=\"button\" aria-disabled=${ifDefined(this.disabled ? 'true' : undefined)} @click=${this.copyInline}>${code}</button>\n        </ui-tooltip><span class=\"sr-only\" role=\"status\">${this.copied ? (this.feedback || this.localize.t.copy.copied) : ''}</span>`;\n    }\n\n    private renderCopyButton(size: 'sm' | 'md') {\n        if (this.hideCopyButton) return nothing;\n        return html`<ui-copy-button\n            class=\"copy-button\"\n            part=\"copy-button\"\n            size=${size}\n            .text=${this.copyText}\n            label=${this.copyLabel || this.localize.t.copy.copy}\n            feedback=${this.feedback || this.localize.t.copy.copied}\n            feedback-timeout=${this.feedbackTimeout}\n            placement=${this.placement}\n            ?disabled=${this.disabled}\n        ></ui-copy-button>`;\n    }\n\n    private renderSingle() {\n        const focusable = !this.disabled;\n        return html`<div class=\"single ${classMap({ 'no-copy': this.hideCopyButton, disabled: this.disabled })}\">\n            <div class=\"container\" part=\"container\" role=\"textbox\" tabindex=${ifDefined(focusable ? 0 : undefined)} aria-label=${this.label || this.localize.t.copy.copy} aria-readonly=\"true\">\n                <pre><code part=\"code\"><slot @slotchange=${this.onSlotChange}></slot></code></pre>\n            </div>\n            ${this.renderCopyButton('md')}\n        </div>`;\n    }\n\n    private renderExpandButton() {\n        if (!this.canExpand) return nothing;\n        const expandText = this.expanded ? (this.showLessText || this.localize.t.copy.showLess) : (this.showMoreText || this.localize.t.copy.showMore);\n        return html`<button class=\"expand\" part=\"expand-button\" type=\"button\" aria-expanded=${this.expanded ? 'true' : 'false'} ?disabled=${this.disabled} @click=${() => (this.expanded = !this.expanded)}>\n            <span class=\"text\">${expandText}</span>${chevron}\n        </button>`;\n    }\n\n    private renderMulti() {\n        const focusable = !this.disabled;\n        return html`<div class=\"multi ${classMap({ 'no-copy': this.hideCopyButton, expanded: this.expanded, wrap: this.wrapText, disabled: this.disabled })}\">\n            <div class=\"container\" part=\"container\" style=${styleMap(this.containerStyle())}>\n                <pre role=\"textbox\" tabindex=${ifDefined(focusable ? 0 : undefined)} aria-label=${this.label || this.localize.t.copy.copy} aria-readonly=\"true\" aria-multiline=\"true\"><code part=\"code\"><slot @slotchange=${this.onSlotChange}></slot></code></pre>\n            </div>\n            ${this.renderCopyButton('sm')}\n            ${this.renderExpandButton()}\n        </div>`;\n    }\n\n    override render() {\n        if (this.type === 'inline') return this.renderInline();\n        if (this.type === 'multi') return this.renderMulti();\n        return this.renderSingle();\n    }\n}\n\nexport interface UiCodeSnippetEventMap extends HTMLElementEventMap {\n    'ui-toggle': CustomEvent<ExpandedDetail>;\n    'ui-copy': CustomEvent<CopyDetail>;\n}\n\n/** Typed listeners for UiCodeSnippet's events (declaration merging with the class). */\nexport interface UiCodeSnippet {\n    addEventListener<K extends keyof UiCodeSnippetEventMap>(type: K, listener: (this: UiCodeSnippet, event: UiCodeSnippetEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void;\n    addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;\n    removeEventListener<K extends keyof UiCodeSnippetEventMap>(type: K, listener: (this: UiCodeSnippet, event: UiCodeSnippetEventMap[K]) => unknown, options?: boolean | EventListenerOptions): void;\n    removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;\n}\n\ndeclare global {\n    interface HTMLElementTagNameMap {\n        'ui-code-snippet': UiCodeSnippet;\n    }\n}\n"
    }
  ]
}
