Calendar

Range Picker

A range in two clicks: if the second date lands before the first, the ends swap instead of raising an error.

  • calendar
  • range
  • booking
  • dates

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/calendar-002?lang=en

март 2026 г.
пнвтсрчтптсбвс
10 мар. 17 мар.7 ночей
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 "calendar-002" (Range Picker) 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/calendar-002.json

Registry item: https://vibeui.ru/r/calendar-002.json
Installs to: components/vibeui/calendar-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 range in two clicks: if the second date lands before the first, the ends swap instead of raising an error.

A range calendar: the first click sets the start, the second the end, the ends normalise, the band between them is solid and nights are counted. Zero dependencies, one file.

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

<Calendar002 defaultFrom="2026-03-10" defaultTo="2026-03-17" onChange={setRange} />

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-calendar-002-* palette — do not swap it for your theme tokens
- swapping the ends instead of erroring: "from the 17th to the 10th" is how people think
- the highlight on the cell rather than the button — otherwise the band breaks between days
- the rounded range ends: without them the band looks cut off
- counting nights rather than days: bookings count nights, and the off-by-one matters
- the "pick the second date" hint between clicks

## 6. You may change
- defaultFrom and defaultTo
- locale — the label language
- the onChange handler
- the accent through the accent prop

## 7. Rules
- Minimum and maximum range lengths are not enforced: add the check in onChange.
- Blocked dates inside the range are unknown to the component — a booking flow needs that added.
- Dates are compared as ISO strings: the format must be YYYY-MM-DD or the ordering breaks.
- 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/calendar-002.json
https://vibeui.ru/r/calendar-002.json

Компонент самодостаточен: один файл, без зависимостей, собственная палитра в локальных переменных --vibeui-calendar-002-*. Клиентский: "use client". Подсветка диапазона живёт на ячейке таблицы, а не на кнопке дня: только так полоса между границами получается сплошной. Порядок дат нормализуется сравнением строк ISO — они сравниваются лексикографически. Внизу считается число ночей.

Component source

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

"use client"

import { useMemo, useState } from "react"
import type { ComponentPropsWithoutRef, CSSProperties } from "react"

export type Calendar002Props = Omit<
  ComponentPropsWithoutRef<"div">,
  "children" | "onChange"
> & {
  defaultFrom?: string
  defaultTo?: string
  locale?: string
  onChange?: (range: { from: string; to: string }) => void
  accent?: string
}

// Идея компонента: выбор диапазона в один заход. Первый клик ставит начало,
// второй — конец, и если он раньше начала, границы меняются местами вместо
// ошибки: человек так и думает — «с этого по то», а не «сначала меньшую».
// Подсветка идёт по всей строке между границами, а не точками по дням.
const STYLES = `
:where([data-vibeui-block="calendar-002"]){
--vibeui-calendar-002-bg:oklch(1 0 0);
--vibeui-calendar-002-fg:oklch(0.24 0.014 265);
--vibeui-calendar-002-muted:oklch(0.6 0.014 265);
--vibeui-calendar-002-border:oklch(0.91 0.006 265);
--vibeui-calendar-002-accent:oklch(0.55 0.17 265);
--vibeui-calendar-002-range:color-mix(in oklab,var(--vibeui-calendar-002-accent) 12%,oklch(1 0 0));
--vibeui-calendar-002-font:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
}
[data-vibeui-block="calendar-002"]{
display:flex;flex-direction:column;gap:0.625rem;
width:100%;max-width:19rem;box-sizing:border-box;padding:0.875rem;
background:var(--vibeui-calendar-002-bg);
border:1px solid var(--vibeui-calendar-002-border);border-radius:0.875rem;
color:var(--vibeui-calendar-002-fg);font-family:var(--vibeui-calendar-002-font);
}
[data-vibeui-block="calendar-002"] [data-part="head"]{display:flex;align-items:center;justify-content:space-between;gap:0.5rem}
[data-vibeui-block="calendar-002"] [data-part="title"]{font-size:0.875rem;font-weight:650}
/* Заглавная только первая буква: capitalize поднимает и «г.» в «январь 2026 г.». */
[data-vibeui-block="calendar-002"] [data-part="title"]::first-letter{text-transform:uppercase}
[data-vibeui-block="calendar-002"] [data-part="nav"]{display:flex;gap:0.25rem}
[data-vibeui-block="calendar-002"] [data-part="nav"] button{
appearance:none;cursor:pointer;
display:inline-flex;align-items:center;justify-content:center;
width:1.75rem;height:1.75rem;padding:0;
border:1px solid var(--vibeui-calendar-002-border);border-radius:0.5rem;
background:transparent;color:inherit;
}
[data-vibeui-block="calendar-002"] [data-part="nav"] button:focus-visible{outline:2px solid var(--vibeui-calendar-002-accent);outline-offset:2px}
[data-vibeui-block="calendar-002"] [data-part="arrow"]{
width:0.375rem;height:0.375rem;
border-left:1.5px solid currentColor;border-bottom:1.5px solid currentColor;
transform:rotate(45deg) translate(0.0625rem,-0.0625rem);
}
[data-vibeui-block="calendar-002"] [data-part="arrow"][data-dir="next"]{transform:rotate(-135deg) translate(0.0625rem,-0.0625rem)}
[data-vibeui-block="calendar-002"] table{width:100%;border-collapse:collapse;table-layout:fixed}
[data-vibeui-block="calendar-002"] th{padding:0.25rem 0;font-size:0.6875rem;font-weight:600;color:var(--vibeui-calendar-002-muted);text-transform:capitalize}
/* Подсветка диапазона живёт на ячейке, а не на кнопке: только так полоса
   между днями получается сплошной. */
[data-vibeui-block="calendar-002"] td{padding:0;text-align:center}
[data-vibeui-block="calendar-002"] td[data-in="true"]{background:var(--vibeui-calendar-002-range)}
[data-vibeui-block="calendar-002"] td[data-edge="from"]{border-radius:0.5rem 0 0 0.5rem}
[data-vibeui-block="calendar-002"] td[data-edge="to"]{border-radius:0 0.5rem 0.5rem 0}
[data-vibeui-block="calendar-002"] td[data-edge="single"]{border-radius:0.5rem}
[data-vibeui-block="calendar-002"] td button{
appearance:none;cursor:pointer;
display:inline-flex;align-items:center;justify-content:center;
width:2rem;height:2rem;padding:0;border:0;border-radius:0.5rem;
background:transparent;color:inherit;
font:inherit;font-size:0.8125rem;font-variant-numeric:tabular-nums;
}
[data-vibeui-block="calendar-002"] td button:hover{box-shadow:inset 0 0 0 1px var(--vibeui-calendar-002-border)}
[data-vibeui-block="calendar-002"] td button:focus-visible{outline:2px solid var(--vibeui-calendar-002-accent);outline-offset:-2px}
[data-vibeui-block="calendar-002"] td button[data-outside="true"]{color:var(--vibeui-calendar-002-muted);opacity:.55}
[data-vibeui-block="calendar-002"] td button[data-edge="true"]{
background:var(--vibeui-calendar-002-accent);color:oklch(0.99 0.01 265);font-weight:650;opacity:1;
}
[data-vibeui-block="calendar-002"] [data-part="summary"]{
display:flex;align-items:center;justify-content:space-between;gap:0.5rem;
font-size:0.75rem;color:var(--vibeui-calendar-002-muted);
}
[data-vibeui-block="calendar-002"] [data-part="nights"]{color:var(--vibeui-calendar-002-fg);font-weight:600}
@media (prefers-reduced-motion:reduce){[data-vibeui-block="calendar-002"] *{animation:none!important;transition:none!important}}
`

const DAY = 86400000

function iso(date: Date) {
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`
}

function mondayIndex(date: Date) {
  return (date.getDay() + 6) % 7
}

function buildGrid(year: number, month: number) {
  const first = new Date(year, month, 1)
  const start = new Date(first.getTime() - mondayIndex(first) * DAY)
  return Array.from(
    { length: 42 },
    (_, index) => new Date(start.getTime() + index * DAY),
  )
}

/**
 * Выбор диапазона: два клика, автоперестановка границ и счёт ночей.
 * Один файл, ноль зависимостей, собственная палитра.
 */
export function Calendar002({
  defaultFrom = "2026-03-10",
  defaultTo = "2026-03-17",
  locale = "ru-RU",
  onChange,
  accent,
  className,
  style,
  ...props
}: Calendar002Props) {
  const [range, setRange] = useState({ from: defaultFrom, to: defaultTo })
  const [pending, setPending] = useState<string | null>(null)
  const [cursor, setCursor] = useState(() => {
    const [year, month] = defaultFrom.split("-").map(Number)
    return { year, month: month - 1 }
  })

  const days = useMemo(
    () => buildGrid(cursor.year, cursor.month),
    [cursor.month, cursor.year],
  )

  const titles = useMemo(() => {
    const week = new Intl.DateTimeFormat(locale, { weekday: "short" })
    const month = new Intl.DateTimeFormat(locale, {
      month: "long",
      year: "numeric",
    })
    return {
      weekdays: days.slice(0, 7).map((date) => week.format(date)),
      month: month.format(new Date(cursor.year, cursor.month, 1)),
      day: new Intl.DateTimeFormat(locale, { day: "numeric", month: "short" }),
      full: new Intl.DateTimeFormat(locale, { dateStyle: "long" }),
    }
  }, [cursor.month, cursor.year, days, locale])

  const palette = {
    ...(accent ? { "--vibeui-calendar-002-accent": accent } : null),
    ...style,
  } as CSSProperties

  const pick = (value: string) => {
    if (!pending) {
      setPending(value)
      return
    }
    // Границы наоборот — не ошибка, а обычный ход мысли: меняем местами.
    const next =
      value < pending
        ? { from: value, to: pending }
        : { from: pending, to: value }
    setRange(next)
    setPending(null)
    onChange?.(next)
  }

  const from = pending ?? range.from
  const to = pending ? pending : range.to
  const nights = Math.round(
    (new Date(`${range.to}T00:00:00`).getTime() -
      new Date(`${range.from}T00:00:00`).getTime()) /
      DAY,
  )

  return (
    <>
      <style href="vibeui-calendar-002" precedence="medium">
        {STYLES}
      </style>
      <div
        {...props}
        data-vibeui-block="calendar-002"
        className={className}
        style={palette}
      >
        <div data-part="head">
          <span data-part="title">{titles.month}</span>
          <span data-part="nav">
            <button
              type="button"
              aria-label="Предыдущий месяц"
              onClick={() => {
                const next = new Date(cursor.year, cursor.month - 1, 1)
                setCursor({ year: next.getFullYear(), month: next.getMonth() })
              }}
            >
              <span data-part="arrow" aria-hidden="true" />
            </button>
            <button
              type="button"
              aria-label="Следующий месяц"
              onClick={() => {
                const next = new Date(cursor.year, cursor.month + 1, 1)
                setCursor({ year: next.getFullYear(), month: next.getMonth() })
              }}
            >
              <span data-part="arrow" data-dir="next" aria-hidden="true" />
            </button>
          </span>
        </div>
        <table>
          <thead>
            <tr>
              {titles.weekdays.map((day) => (
                <th key={day} scope="col">
                  {day}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {Array.from({ length: 6 }, (_, row) => (
              <tr key={row}>
                {days.slice(row * 7, row * 7 + 7).map((date) => {
                  const value = iso(date)
                  const inRange = value >= from && value <= to
                  const edge =
                    from === to && value === from
                      ? "single"
                      : value === from
                        ? "from"
                        : value === to
                          ? "to"
                          : undefined

                  return (
                    <td key={value} data-in={inRange} data-edge={edge}>
                      <button
                        type="button"
                        aria-label={titles.full.format(date)}
                        aria-pressed={value === from || value === to}
                        data-edge={value === from || value === to}
                        data-outside={date.getMonth() !== cursor.month}
                        onClick={() => pick(value)}
                      >
                        {date.getDate()}
                      </button>
                    </td>
                  )
                })}
              </tr>
            ))}
          </tbody>
        </table>
        <div data-part="summary">
          <span>
            {titles.day.format(new Date(`${range.from}T00:00:00`))} —{" "}
            {titles.day.format(new Date(`${range.to}T00:00:00`))}
          </span>
          <span data-part="nights">
            {pending ? "Выберите вторую дату" : `${nights} ночей`}
          </span>
        </div>
      </div>
    </>
  )
}