# Animated Date Input for UI SDK (/docs/components/date-input)

One highlight glides between day, month and year as you move through the segments.

```tsx title="example.tsx"
import * as React from "react"

import { DateInput } from "@/components/keyframery/date-input"

const today = new Date()
const iso = (date: Date) =>
  `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`

/* A passport has to stay valid for six months after the trip. */
const sixMonthsOut = iso(new Date(today.getFullYear(), today.getMonth() + 6, today.getDate()))

export default function DateInputDemo() {
  const [expiry, setExpiry] = React.useState<string | null>("2031-08-09")
  const expiresTooSoon = expiry !== null && expiry < sixMonthsOut

  return (
    <div className="w-[340px]">
      <h3 className="text-[15px] font-semibold tracking-tight">Passenger 1</h3>
      <p className="mt-1 text-[13px] text-muted-foreground">As shown on the passport</p>

      <div
        className="mt-5 grid grid-cols-2 gap-x-3 gap-y-1.5"
        /* A scripted click does not focus an input by itself; this lets the self-playing loop in. */
        onClick={(event) => event.target instanceof HTMLInputElement && event.target.focus()}
      >
        <span id="dob" className="text-[13px] font-medium">
          Date of birth
        </span>
        <span id="expiry" className="text-[13px] font-medium">
          Passport expires
        </span>
        <DateInput aria-labelledby="dob" defaultValue="1991-04-23" max={iso(today)} className="w-full" />
        <DateInput
          aria-labelledby="expiry"
          value={expiry}
          onValueChange={setExpiry}
          min={sixMonthsOut}
          className="w-full"
        />
        <span />
        <span
          className={
            "text-[12px] " + (expiresTooSoon ? "text-destructive" : "text-muted-foreground")
          }
        >
          {expiresTooSoon ? "Must last 6 more months" : "Valid for this trip"}
        </span>
      </div>
    </div>
  )
}
```

## Installation [#installation]

```bash
npx shadcn@latest add @keyframery/date-input
```

This adds `components/keyframery/date-input.tsx` and its primitive, `components/keyframery/primitives/date-input.tsx`, to your project, and installs `@ui-sdk/react`. The motion tokens are added to your global CSS the first time you install a component.

## Usage [#usage]

```tsx
import { DateInput, DateInputSegment } from "@/components/keyframery/date-input"
```

The parts and props are the same as UI SDK's Date Input. For every prop, see the [UI SDK date input reference](https://ui-sdk.dev/docs/components/date-input).

**Next.js with cacheComponents**

The date input reads today's date while it renders. With `cacheComponents` turned on, render it inside `<Suspense>` after `await connection()`. [See the fix](/docs/troubleshooting#nextjs-stops-with-unstable-value-datenow).

## What moves [#what-moves]

| Move      | What you see                                                               |
| --------- | -------------------------------------------------------------------------- |
| **Glide** | One highlight glides between day, month and year as you move through them. |

Timing and springiness follow the [motion style](/docs/motion-styles) you set, so this component moves like the rest of your app.

## Swap the import [#swap-the-import]

Already using UI SDK's date input with your own styles? Keep your markup and change one line. The primitive adds motion and nothing else.

```tsx
// Before
import { … } from "@ui-sdk/react/date-input"

// After: same parts, same props, now animated
import { … } from "@/components/keyframery/primitives/date-input"
```

## Parts [#parts]

The finished component exports 2 parts:

`DateInput`, `DateInputSegment`

## Accessibility [#accessibility]

Keyboard, focus and screen-reader behaviour come from UI SDK and are not changed. With reduced motion turned on, nothing in the date input moves: changes happen at once or with a short fade. More in [Accessibility](/docs/accessibility).

## Source [#source]

The code that lands in your project. It is yours to change.

**components/keyframery/date-input.tsx**

```tsx
"use client"

/* Styled date input: the animated primitive plus the Keyframery look. */

import * as React from "react"

import {
  DateInput as DateInputPrimitive,
  DateInputSegment as DateInputSegmentPrimitive,
  createDateInputController,
} from "@/components/keyframery/primitives/date-input"
import { cn } from "@/lib/utils"

/* The field look, as in Input: one hairline variable that hover, focus and invalid change. */
const fieldBox =
  "rounded-[10px] bg-background text-[13px] " +
  "[--field-line:rgb(0_0_0/0.09)] dark:[--field-line:rgb(255_255_255/0.1)] " +
  "shadow-[0_0_0_1px_var(--field-line),0_1px_2px_rgb(0_0_0/0.05)] dark:shadow-[0_0_0_1px_var(--field-line)] " +
  "transition-[box-shadow,background-color] duration-[calc(150ms*var(--kf-speed,1))] ease-house motion-reduce:transition-none! " +
  "hover:[--field-line:rgb(0_0_0/0.16)] dark:hover:[--field-line:rgb(255_255_255/0.18)]"

/* The field. The ring follows whichever segment has focus; invalid wins over focus. */
function DateInput({
  className,
  children,
  ...props
}: React.ComponentProps<typeof DateInputPrimitive>) {
  return (
    <DateInputPrimitive
      className={cn(
        fieldBox,
        "inline-flex h-9 w-fit min-w-0 cursor-text items-center px-2 text-foreground tabular-nums",
        "has-[input:focus-visible]:ring-[3px] has-[input:focus-visible]:ring-ring/25 has-[input:focus-visible]:[--field-line:var(--ring)] dark:has-[input:focus-visible]:[--field-line:var(--ring)]",
        "data-invalid:ring-destructive/25! data-invalid:[--field-line:var(--destructive)]!",
        "data-readonly:bg-muted/50",
        /* The highlight the primitive glides under the focused segment. */
        "before:rounded-[6px] before:bg-accent",
        "data-disabled:cursor-not-allowed data-disabled:bg-muted data-disabled:text-muted-foreground data-disabled:[--field-line:rgb(0_0_0/0.06)] dark:data-disabled:[--field-line:rgb(255_255_255/0.06)]",
        className,
      )}
      {...props}
    >
      {children ??
        ((state) =>
          state.segments.map((segment) => (
            <DateInputSegment key={segment.key} segment={segment} />
          )))}
    </DateInputPrimitive>
  )
}

/* A segment sizes to its text. The one with focus sits on the accent tile the primitive glides
   between segments, and an empty one shows its placeholder in a quieter colour. */
function DateInputSegment({
  className,
  ...props
}: React.ComponentProps<typeof DateInputSegmentPrimitive>) {
  return (
    <DateInputSegmentPrimitive
      className={cn(
        "h-6 rounded-[6px] bg-transparent px-[3px] text-center text-[13px] leading-none font-medium text-foreground tabular-nums outline-none",
        "[field-sizing:content] caret-transparent selection:bg-transparent",
        /* Room for the full number even while empty, so the field keeps its width. */
        "data-[type=day]:min-w-[calc(2ch+6px)] data-[type=month]:min-w-[calc(2ch+6px)] data-[type=hour]:min-w-[calc(2ch+6px)] data-[type=minute]:min-w-[calc(2ch+6px)] data-[type=second]:min-w-[calc(2ch+6px)]",
        "data-[type=year]:min-w-[calc(4ch+6px)] data-[type=dayPeriod]:min-w-[calc(2.2em+6px)]",
        "transition-colors duration-[calc(150ms*var(--kf-speed,1))] motion-reduce:transition-none! focus:text-accent-foreground",
        "placeholder:text-muted-foreground/70 data-empty:text-muted-foreground/70",
        "data-[type=literal]:flex data-[type=literal]:items-center data-[type=literal]:px-px data-[type=literal]:font-normal data-[type=literal]:text-muted-foreground/70",
        "data-[type=dayPeriod]:ml-1 data-[type=dayPeriod]:uppercase",
        "data-invalid:not-data-[type=literal]:text-destructive",
        "data-disabled:pointer-events-none data-disabled:text-muted-foreground",
        className,
      )}
      {...props}
    />
  )
}

export { DateInput, DateInputSegment, createDateInputController }
```

**components/keyframery/primitives/date-input.tsx**

```tsx
"use client"

/* Animated drop-in for `@ui-sdk/react/date-input`: same parts, same props. Swap the import and keep your code.
   This file adds motion only. Colours, radii, shadows and spacing stay yours.

   Glide: one highlight sits under the segment with focus and glides to the next segment as focus
   moves, typed or tabbed. It is the root's `before:`; give it your own colour and radius with
   `before:` classes on DateInput. */

import { DateInput as DateInputRoot, DateInputSegment as DateInputSegmentPart } from "@ui-sdk/react/date-input"
import * as React from "react"

import { cn } from "@/lib/utils"

export * from "@ui-sdk/react/date-input"

function DateInput({ className, children, ...props }: React.ComponentProps<typeof DateInputRoot>) {
  return (
    <DateInputRoot
      className={cn(
        "relative isolate [anchor-scope:--kf-seg,--kf-seg-rest]",
        "before:pointer-events-none before:absolute before:-z-10 before:opacity-0 before:content-[''] before:[position-anchor:--kf-seg]",
        "before:bg-[color-mix(in_oklch,currentColor_9%,transparent)]",
        "before:top-[anchor(--kf-seg_top,anchor(--kf-seg-rest_top))] before:right-[anchor(--kf-seg_right,anchor(--kf-seg-rest_right))]",
        "before:bottom-[anchor(--kf-seg_bottom,anchor(--kf-seg-rest_bottom))] before:left-[anchor(--kf-seg_left,anchor(--kf-seg-rest_left))]",
        "before:[transition:top_calc(280ms*var(--kf-speed,1))_var(--ease-spring),right_calc(280ms*var(--kf-speed,1))_var(--ease-spring),bottom_calc(280ms*var(--kf-speed,1))_var(--ease-spring),left_calc(280ms*var(--kf-speed,1))_var(--ease-spring),opacity_calc(160ms*var(--kf-speed,1))_var(--ease-house)]",
        "has-[input:focus]:before:opacity-100 motion-reduce:before:[transition:none]!",
        className,
      )}
      {...props}
    >
      {children ??
        ((state) =>
          state.segments.map((segment) => <DateInputSegment key={segment.key} segment={segment} />))}
    </DateInputRoot>
  )
}

/* The segment with focus names itself as the highlight's anchor. The first segment is a resting
   anchor: focus passes through "nothing focused" for a moment as it moves between segments, and
   without somewhere to rest the highlight would jump instead of gliding. */
function DateInputSegment({ className, ...props }: React.ComponentProps<typeof DateInputSegmentPart>) {
  return <DateInputSegmentPart className={cn(
        "first:[anchor-name:--kf-seg-rest] focus:[anchor-name:--kf-seg] first:focus:[anchor-name:--kf-seg,--kf-seg-rest]",
        className,
      )} {...props} />
}

export { DateInput, DateInputSegment }
```

## Questions

### How does the animated Date Input for UI SDK move?

Glide: One highlight glides between day, month and year as you move through them.

### Do I need Motion or Framer Motion for the animated Date Input?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### Can I keep my own styling and only take the motion?

Yes. Import from `@/components/keyframery/primitives/date-input` instead. It has the same parts and props as `@ui-sdk/react/date-input` and adds motion only.

### What happens to the Date Input when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
