Inputs

Unit Switch Field

A weight field whose unit switch converts the number: 12.5 kg becomes 27.6 lb on a click instead of staying 12.5.

  • number
  • units
  • converter
  • weight

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/number-005?lang=en

Это же значение: 27.6 фунта

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 "number-005" (Unit Switch Field) 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/number-005.json

Registry item: https://vibeui.ru/r/number-005.json
Installs to: components/vibeui/number-005.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 weight field whose unit switch converts the number: 12.5 kg becomes 27.6 lb on a click instead of staying 12.5.

A number field with a unit switch: changing the unit converts the value, and the equivalent in the other unit is always captioned. Zero dependencies, one file.

## 3. How to use it
import { Number005 } from "@/components/vibeui/number-005"

<Number005 label="Parcel weight" defaultValue={12.5} defaultUnit="кг" />

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-number-005-* palette — do not swap it for your theme tokens
- its own light surface: the field gets shown over any background
- the conversion on unit change: keeping 12.5 and relabelling "kg" as "lb" silently corrupts the data
- the single source of truth in kilograms: two independent numbers drift apart after the first manual edit
- the single rounding point: rounding on every switch walks the value away as you toggle back and forth
- aria-pressed on the unit buttons: this is a toggle state, not just a press
- the equivalent line: nobody converts between systems in their head

## 6. You may change
- label — the field caption
- defaultValue — the starting value
- defaultUnit — the unit the field opens in
- the rounding precision inside the round helper
- the accent through the accent prop

## 7. Rules
- The 2.2046226218 factor is a constant: swap it and the button captions for other units.
- Emit kilograms outwards rather than the displayed number, or the receiver cannot tell the unit.
- Rounding to a tenth is a compromise: raise the multiplier in round for pharmacy scales.
- 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/number-005.json
https://vibeui.ru/r/number-005.json

Компонент самодостаточен: один файл, ноль зависимостей, палитра в локальных переменных --vibeui-number-005-*. Клиентский: единица и значение живут в состоянии. Внутри всегда хранятся килограммы, показанное число получается умножением — так щелчки туда-обратно не накапливают ошибку округления. Переключатель сделан двумя кнопками с aria-pressed, а не select'ом: вариантов два, и оба должны быть видны. Под полем всегда подписан эквивалент во второй единице.

Component source

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

"use client"

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

export type Number005Props = Omit<
  ComponentPropsWithoutRef<"div">,
  "children" | "defaultValue" | "onChange"
> & {
  label?: string
  defaultValue?: number
  defaultUnit?: "кг" | "фунты"
  accent?: string
}

// Идея компонента: вес с переключателем единиц, который пересчитывает число,
// а не подменяет подпись. Переключить «кг» на «фунты» и оставить 70 — значит
// молча испортить данные, поэтому 70 кг становятся 154.3 фунта. Внутри
// компонент всегда держит килограммы: одна база и одно место округления
// избавляют от накопления ошибки при щелчках туда-обратно.
const STYLES = `
:where([data-vibeui-block="number-005"]){
--vibeui-number-005-surface:oklch(1 0 0);
--vibeui-number-005-field:oklch(1 0 0);
--vibeui-number-005-shell:oklch(0.9 0.006 265);
--vibeui-number-005-fg:oklch(0.23 0.014 265);
--vibeui-number-005-muted:oklch(0.55 0.014 265);
--vibeui-number-005-border:oklch(0.88 0.008 265);
--vibeui-number-005-switch:oklch(0.96 0.004 265);
--vibeui-number-005-accent:oklch(0.5 0.14 195);
--vibeui-number-005-font:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
}
/* Своя светлая подложка: поле показывают поверх любого фона. */
[data-vibeui-block="number-005"]{
display:flex;flex-direction:column;gap:0.5rem;
width:100%;max-width:18rem;box-sizing:border-box;padding:0.875rem;
background:var(--vibeui-number-005-surface);
border:1px solid var(--vibeui-number-005-shell);border-radius:0.875rem;
font-family:var(--vibeui-number-005-font);color:var(--vibeui-number-005-fg);
}
[data-vibeui-block="number-005"] label{font-size:0.8125rem;font-weight:650}
[data-vibeui-block="number-005"] [data-part="row"]{
display:flex;align-items:center;gap:0.5rem;
padding:0.25rem 0.25rem 0.25rem 0.75rem;box-sizing:border-box;
border:1px solid var(--vibeui-number-005-border);border-radius:0.75rem;
background:var(--vibeui-number-005-field);
}
[data-vibeui-block="number-005"] [data-part="row"]:focus-within{
border-color:var(--vibeui-number-005-accent);
box-shadow:0 0 0 2px oklch(0.5 0.14 195 / 20%);
}
[data-vibeui-block="number-005"] input{
flex:1 1 auto;min-width:0;width:100%;
appearance:none;border:0;background:none;outline:none;
height:2.5rem;color:inherit;
font:inherit;font-size:1.25rem;font-weight:700;
font-variant-numeric:tabular-nums;
}
[data-vibeui-block="number-005"] input::-webkit-outer-spin-button,
[data-vibeui-block="number-005"] input::-webkit-inner-spin-button{appearance:none;margin:0}
/* Переключатель единиц: две кнопки видны сразу, выпадающий список тут лишний. */
[data-vibeui-block="number-005"] [data-part="units"]{
display:flex;flex:none;gap:0.125rem;padding:0.125rem;
border-radius:0.5rem;background:var(--vibeui-number-005-switch);
}
[data-vibeui-block="number-005"] button{
appearance:none;border:0;cursor:pointer;
height:2rem;padding:0 0.625rem;border-radius:0.4375rem;
background:transparent;color:var(--vibeui-number-005-muted);
font:inherit;font-size:0.8125rem;font-weight:650;
transition:background-color .14s ease,color .14s ease;
}
[data-vibeui-block="number-005"] button[aria-pressed="true"]{
background:var(--vibeui-number-005-surface);color:var(--vibeui-number-005-fg);
box-shadow:0 1px 2px oklch(0.2 0.02 265 / 14%);
}
[data-vibeui-block="number-005"] button:focus-visible{outline:2px solid var(--vibeui-number-005-accent);outline-offset:2px}
/* Вторая единица подписана всегда: перевод не приходится держать в голове. */
[data-vibeui-block="number-005"] [data-part="mirror"]{
margin:0;font-size:0.75rem;color:var(--vibeui-number-005-muted);
font-variant-numeric:tabular-nums;
}
[data-vibeui-block="number-005"] [data-part="mirror"] b{color:var(--vibeui-number-005-fg);font-weight:650}
@media (prefers-reduced-motion:reduce){[data-vibeui-block="number-005"] *{animation:none!important;transition:none!important}}
`

const POUNDS_IN_KILOGRAM = 2.2046226218

function round(value: number) {
  return Math.round(value * 10) / 10
}

/**
 * Вес с переключением единиц: смена единицы пересчитывает число.
 * Один файл, ноль зависимостей, собственная палитра.
 */
export function Number005({
  label = "Вес посылки",
  defaultValue = 12.5,
  defaultUnit = "кг",
  accent,
  className,
  style,
  ...props
}: Number005Props) {
  const id = useId()
  const [unit, setUnit] = useState(defaultUnit)
  // База всегда в килограммах: одно место округления, никакого дрейфа.
  const [kilograms, setKilograms] = useState(
    defaultUnit === "кг" ? defaultValue : defaultValue / POUNDS_IN_KILOGRAM,
  )

  const shown = unit === "кг" ? kilograms : kilograms * POUNDS_IN_KILOGRAM
  const mirror =
    unit === "кг"
      ? `${round(kilograms * POUNDS_IN_KILOGRAM)} фунта`
      : `${round(kilograms)} кг`

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

  return (
    <>
      <style href="vibeui-number-005" precedence="medium">
        {STYLES}
      </style>
      <div
        {...props}
        data-vibeui-block="number-005"
        className={className}
        style={palette}
      >
        <label htmlFor={id}>{label}</label>
        <div data-part="row">
          <input
            id={id}
            type="number"
            inputMode="decimal"
            min={0}
            step={0.1}
            value={round(shown)}
            aria-describedby={`${id}-mirror`}
            onChange={(event) => {
              const next = Number(event.target.value)
              if (!Number.isFinite(next)) return
              setKilograms(unit === "кг" ? next : next / POUNDS_IN_KILOGRAM)
            }}
          />
          <div data-part="units" role="group" aria-label="Единица измерения">
            {(["кг", "фунты"] as const).map((option) => (
              <button
                key={option}
                type="button"
                aria-pressed={unit === option}
                onClick={() => setUnit(option)}
              >
                {option === "кг" ? "кг" : "lb"}
              </button>
            ))}
          </div>
        </div>
        <p id={`${id}-mirror`} data-part="mirror" aria-live="polite">
          Это же значение: <b>{mirror}</b>
        </p>
      </div>
    </>
  )
}