Code Block

Copy With Timer

A code block with copy where the "Copied" label rolls back on its own: a bar under the button shows how long is left before it returns.

  • code
  • copy
  • clipboard
  • feedback

Preview

1440pxHost theme

Use it with AI

  1. 1. Copy the link.
  2. 2. Write to your agent in your own words and drop the link into the sentence.
  3. 3. The agent opens the link and installs the component from the registry.

put this in the header: https://vibeui.ru/c/codeblock-002?lang=en

app/page.tsx
import { Button } from "@/components/ui/button"

export default function Page() {
  return <Button size="lg">Продолжить</Button>
}
Show the full instructions

What the link says, spelled out. Use it when your agent cannot open links — paste this text instead.

# Install and place "codeblock-002" (Copy With Timer) from VibeUI

## 1. Install first — do not skip, do not recreate
Run this exact command before writing any code:
npx shadcn@latest add https://vibeui.ru/r/codeblock-002.json

Registry item: https://vibeui.ru/r/codeblock-002.json
Installs to: components/vibeui/codeblock-002.tsx (the exact path follows this project's components.json aliases).
npm dependencies: none.
Registry dependencies: none.

Install it from the registry. Do not recreate it from the description,
do not substitute a similar component from another library, and do not
rewrite it to match the project's existing style.

## 2. What it is
A code block with copy where the "Copied" label rolls back on its own: a bar under the button shows how long is left before it returns.

A code block with a copy button in the corner: after a click the label changes and a thin bar underneath shows the rollback to the original state. One file, zero dependencies.

## 3. How to use it
import { Codeblock002 } from "@/components/vibeui/codeblock-002"

<Codeblock002
  title="app/page.tsx"
  label="Copy"
  resetDelay={2000}
/>

Read the installed file for the full prop list.

## 4. Where to place it
This is a small inline component. Put it exactly where the user asked,
inside the existing markup. Do not create a new page, section or
wrapper for it. If a similar control already sits in that spot,
replace it instead of adding a second one.

Placement: ___
(The user fills this line in. If it is still blank, ask where to put it
instead of guessing.)

## 5. Keep exactly as installed
- the local --vibeui-codeblock-002-* palette — do not swap it for your theme tokens
- the rollback bar: without it "Copied" looks like a stuck state and people click again
- one source of duration for the timer and the animation — otherwise the bar lies about the return
- the silence when the clipboard is refused: a false "Copied" is worse than no answer
- clearing the timer on unmount, otherwise state updates land on a dead component
- the dark surface and the button contrast: it sits on top of the code and has to stay readable

## 6. You may change
- the code of the block and the heading through title
- the button captions through label and doneLabel
- the rollback duration through resetDelay
- the button position and the block radius

## 7. Rules
- navigator.clipboard needs a secure context: over http the button stays silent.
- A resetDelay under 500 ms reads as a flicker — nobody manages to see the label.
- The button covers the top right corner of the code: a short first line looks better than a long one.
- Do not lift the CSS variables into globals.css: the component has to stay a single file.

## 8. Verify
- it renders with no console errors;
- it looks like the preview on the VibeUI page you copied this from;
- if it does not, you changed something listed in section 5 — put it back.

For developers

npx shadcn@latest add https://vibeui.ru/r/codeblock-002.json
https://vibeui.ru/r/codeblock-002.json

Компонент самодостаточен: один файл, без зависимостей, собственная палитра в локальных переменных --vibeui-codeblock-002-*. Клиентский: директива "use client" нужна для navigator.clipboard и таймера отката. Длительность отката из пропса resetDelay уходит одновременно в setTimeout и в CSS-переменную, по которой считается длительность анимации полосы, поэтому индикатор и состояние всегда согласованы. Таймер снимается в useEffect при размонтировании, иначе setState прилетел бы в мёртвый компонент.

Component source

The same file your agent installs. Here in case you would rather copy it by hand.

"use client"

import { useEffect, useRef, useState } from "react"
import type { ComponentPropsWithoutRef, CSSProperties } from "react"

export type Codeblock002Props = Omit<
  ComponentPropsWithoutRef<"figure">,
  "children" | "title"
> & {
  title?: string
  code?: string
  label?: string
  doneLabel?: string
  resetDelay?: number
}

// Идея компонента: кнопка копирования, которая честно показывает, сколько
// ещё продержится подпись «Скопировано». Под подписью бежит полоса отката —
// пользователь видит, что состояние временное, и не жмёт кнопку повторно.
const STYLES = `
:where([data-vibeui-block="codeblock-002"]){
--vibeui-codeblock-002-bg:oklch(0.19 0.008 265);
--vibeui-codeblock-002-fg:oklch(0.94 0.005 265);
--vibeui-codeblock-002-muted:oklch(0.67 0.012 265);
--vibeui-codeblock-002-border:oklch(1 0 0 / 13%);
--vibeui-codeblock-002-chip:oklch(1 0 0 / 9%);
--vibeui-codeblock-002-chip-hover:oklch(1 0 0 / 16%);
--vibeui-codeblock-002-ok:oklch(0.82 0.14 152);
--vibeui-codeblock-002-mono:ui-monospace,SFMono-Regular,Menlo,Consolas,"Liberation Mono",monospace;
--vibeui-codeblock-002-font:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
}
[data-vibeui-block="codeblock-002"]{
position:relative;display:block;
width:100%;max-width:32rem;box-sizing:border-box;margin:0;
border:1px solid var(--vibeui-codeblock-002-border);border-radius:0.875rem;
background:var(--vibeui-codeblock-002-bg);color:var(--vibeui-codeblock-002-fg);
font-family:var(--vibeui-codeblock-002-font);
}
[data-vibeui-block="codeblock-002"] figcaption{
padding:0.625rem 0.875rem 0;
font-size:0.75rem;color:var(--vibeui-codeblock-002-muted);
}
[data-vibeui-block="codeblock-002"] pre{
margin:0;padding:0.5rem 0.875rem 0.875rem;overflow-x:auto;
}
[data-vibeui-block="codeblock-002"] code{
display:block;
font-family:var(--vibeui-codeblock-002-mono);
font-size:0.8125rem;line-height:1.65;white-space:pre;
}
[data-vibeui-block="codeblock-002"] [data-part="copy"]{
position:absolute;top:0.5rem;right:0.5rem;
appearance:none;border:0;cursor:pointer;overflow:hidden;
display:inline-flex;align-items:center;gap:0.375rem;
height:1.875rem;padding:0 0.6875rem;border-radius:0.5rem;
background:var(--vibeui-codeblock-002-chip);color:var(--vibeui-codeblock-002-fg);
font:inherit;font-size:0.75rem;font-weight:650;
transition:background-color .16s ease,color .16s ease;
}
[data-vibeui-block="codeblock-002"] [data-part="copy"]:hover{background:var(--vibeui-codeblock-002-chip-hover)}
[data-vibeui-block="codeblock-002"] [data-part="copy"]:focus-visible{outline:2px solid var(--vibeui-codeblock-002-ok);outline-offset:2px}
[data-vibeui-block="codeblock-002"] [data-part="copy"][data-done="true"]{color:var(--vibeui-codeblock-002-ok)}
/* Полоса отката: видно, что подпись сменится сама, а не залипла. */
[data-vibeui-block="codeblock-002"] [data-part="timer"]{
position:absolute;left:0;bottom:0;width:100%;height:2px;
transform-origin:left center;transform:scaleX(0);
background:var(--vibeui-codeblock-002-ok);
}
[data-vibeui-block="codeblock-002"] [data-part="copy"][data-done="true"] [data-part="timer"]{
animation:vibeui-codeblock-002-drain var(--vibeui-codeblock-002-delay,2000ms) linear forwards;
}
[data-vibeui-block="codeblock-002"] [data-part="tick"]{width:0.75rem;height:0.75rem;flex:none}
@keyframes vibeui-codeblock-002-drain{from{transform:scaleX(1)}to{transform:scaleX(0)}}
@media (prefers-reduced-motion:reduce){[data-vibeui-block="codeblock-002"] *{animation:none!important;transition:none!important}}
`

const CODE = `import { Button } from "@/components/ui/button"

export default function Page() {
  return <Button size="lg">Продолжить</Button>
}`

/** Блок кода с кнопкой копирования и видимым откатом подписи. */
export function Codeblock002({
  title = "app/page.tsx",
  code = CODE,
  label = "Копировать",
  doneLabel = "Скопировано",
  resetDelay = 2000,
  className,
  style,
  ...props
}: Codeblock002Props) {
  const [done, setDone] = useState(false)
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null)

  useEffect(
    () => () => {
      if (timer.current) clearTimeout(timer.current)
    },
    [],
  )

  const copy = async () => {
    try {
      await navigator.clipboard.writeText(code)
    } catch {
      // Буфер недоступен: молчим, ложное «скопировано» хуже отсутствия ответа.
      return
    }
    setDone(true)
    if (timer.current) clearTimeout(timer.current)
    timer.current = setTimeout(() => setDone(false), resetDelay)
  }

  const palette = {
    "--vibeui-codeblock-002-delay": `${resetDelay}ms`,
    ...style,
  } as CSSProperties

  return (
    <>
      <style href="vibeui-codeblock-002" precedence="medium">
        {STYLES}
      </style>
      <figure
        {...props}
        data-vibeui-block="codeblock-002"
        className={className}
        style={palette}
      >
        <figcaption>{title}</figcaption>
        <button
          type="button"
          data-part="copy"
          data-done={done}
          onClick={copy}
          aria-label={done ? doneLabel : `${label}: ${title}`}
        >
          {done ? (
            <svg data-part="tick" viewBox="0 0 12 12" aria-hidden="true">
              <path
                d="M2 6.5 4.6 9 10 3"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.8"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>
          ) : null}
          <span aria-live="polite">{done ? doneLabel : label}</span>
          <span data-part="timer" aria-hidden="true" />
        </button>
        <pre>
          <code>{code}</code>
        </pre>
      </figure>
    </>
  )
}