Time Range Form
Time range form card: start and end times typed as m:ss with the length worked out large between them, for a sound loop, a clip trim, a meeting slot or a shift, and an optional collapsible section for times that go with it, such as fades. Controlled or uncontrolled.
"use client"
import { useId, useState, type ComponentProps, type ReactNode } from "react"
import { MinusIcon, PlusIcon } from "@phosphor-icons/react"
import { cn } from "cn"
import { Button } from "@/components/ui/button"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible"
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator"
/** A start and an end time, each an `m:ss` string as typed. */
type TimeRange = { start: string; end: string }
// m:ss to seconds; anything else reads as not a time.
function seconds(value: string) {
const match = /^(\d+):([0-5]\d)$/.exec(value.trim())
return match ? Number(match[1]) * 60 + Number(match[2]) : null
}
function clock(total: number) {
return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`
}
type TimeFieldProps = Omit<
ComponentProps<typeof Input>,
"value" | "defaultValue" | "onChange"
> & {
/** The field's label, set small in mono capitals above the input. */
label: ReactNode
/** The time as typed, such as `1:24`, when you control it. */
value?: string
/** The starting time when the field keeps its own value. */
defaultValue?: string
/** Called with the text on every change. */
onValueChange?: (value: string) => void
}
/**
* A labelled text field for an `m:ss` time, in tabular mono figures. Use it
* inside `TimeRangeForm`'s collapsible section for times that go with the
* range, such as fades. Controlled with `value` and `onValueChange`, or
* seeded with `defaultValue`. Other props go to the input.
*/
function TimeField({
label,
value,
defaultValue = "",
onValueChange,
id,
className,
...props
}: TimeFieldProps) {
const fallbackId = useId()
const inputId = id ?? fallbackId
const [uncontrolled, setUncontrolled] = useState(defaultValue)
const text = value ?? uncontrolled
return (
<Field data-slot="time-field" className="gap-2">
<FieldLabel
htmlFor={inputId}
className="font-mono text-xs font-normal text-muted-foreground"
>
{label}
</FieldLabel>
<Input
id={inputId}
value={text}
onChange={(event) => {
if (value === undefined) setUncontrolled(event.target.value)
onValueChange?.(event.target.value)
}}
className={cn(
"border-input bg-transparent font-mono tabular-nums dark:bg-input/30",
className
)}
{...props}
/>
</Field>
)
}
type TimeRangeFormProps = Omit<
ComponentProps<typeof Card>,
"title" | "children" | "defaultValue" | "onChange"
> & {
/** The card's title. */
title: ReactNode
/** A line under the title. */
description?: ReactNode
/** The range, when you control it with `onValueChange`. */
value?: TimeRange
/** The starting range when the form keeps its own value. */
defaultValue?: TimeRange
/** Called with both times after either field changes. */
onValueChange?: (value: TimeRange) => void
/** Every word the form shows or announces. */
labels: {
/** Beside the length worked out from the two times, such as "Loop". */
length: string
/** The start field's label. */
start: string
/** The end field's label. */
end: string
/** The heading over the collapsible section, when there is one. */
more?: string
/** The toggle's accessible name while the section is hidden. */
showMore?: string
/** The toggle's accessible name while the section shows. */
hideMore?: string
}
/**
* Fields that go with the range, shown behind a toggle under it: fade
* times for a loop, a buffer for a booking. Build them from `TimeField`.
* Leave out for no toggle.
*/
children?: ReactNode
/** Shows the collapsible section on first render. */
defaultMoreOpen?: boolean
}
/**
* A card for a span of time: start and end times typed as `m:ss`, with the
* length worked out large between them, for a sound loop, a clip trim, a
* meeting slot or a shift. The length shows a dash until both times read as
* times and the end comes after the start. Anything passed as children sits
* in a collapsible section under the range. Other props go to the Card.
*/
function TimeRangeForm({
title,
description,
value,
defaultValue = { start: "", end: "" },
onValueChange,
labels,
children,
defaultMoreOpen = false,
className,
...props
}: TimeRangeFormProps) {
const [isOpen, setIsOpen] = useState(defaultMoreOpen)
const [uncontrolled, setUncontrolled] = useState(defaultValue)
const range = value ?? uncontrolled
const set = (key: keyof TimeRange) => (next: string) => {
const updated = { ...range, [key]: next }
if (value === undefined) setUncontrolled(updated)
onValueChange?.(updated)
}
const start = seconds(range.start)
const end = seconds(range.end)
const length =
start !== null && end !== null && end > start ? clock(end - start) : "–"
return (
<Card
data-slot="time-range-form"
className={cn("gap-8", className)}
{...props}
>
<CardHeader>
<CardTitle>{title}</CardTitle>
{description != null && (
<CardDescription>{description}</CardDescription>
)}
</CardHeader>
<CardContent className="flex flex-col gap-8">
<span className="flex items-baseline gap-2">
<span className="font-display text-5xl tracking-tight tabular-nums">
{length}
</span>
<span className="font-mono text-xs font-normal text-muted-foreground">
{labels.length}
</span>
</span>
<FieldGroup className="grid grid-cols-2 gap-4">
<TimeField
label={labels.start}
value={range.start}
onValueChange={set("start")}
/>
<TimeField
label={labels.end}
value={range.end}
onValueChange={set("end")}
/>
</FieldGroup>
{children != null && (
<Collapsible
open={isOpen}
onOpenChange={setIsOpen}
className="flex flex-col gap-3"
>
<Separator />
<p className="flex items-center justify-between">
<span className="font-mono text-xs font-normal text-muted-foreground">
{labels.more}
</span>
<CollapsibleTrigger
render={
<Button
variant="ghost"
size="icon-sm"
aria-label={isOpen ? labels.hideMore : labels.showMore}
/>
}
>
{isOpen ? <MinusIcon /> : <PlusIcon />}
</CollapsibleTrigger>
</p>
<CollapsibleContent>
<FieldGroup className="grid grid-cols-2 gap-4 pt-1">
{children}
</FieldGroup>
</CollapsibleContent>
</Collapsible>
)}
</CardContent>
</Card>
)
}
export { TimeField, TimeRangeForm }
import {
ExampleGrid,
ExampleGridItem,
} from "@/components/grid/example-grid"
import { DemoLabel } from "@/components/text/demo-label"
import {
TimeField,
TimeRangeForm,
} from "@/components/time-range-form/time-range-form"
import TimeRangeFormConsole from "@01orbital/core/examples/time-range-form/time-range-form-console"
// The copy: change text here, not in the markup.
const COPY = {
loop: {
title: "Loop points",
description: "Where the bed repeats, and how it fades.",
},
clip: {
title: "Trim clip",
description: "The part of the interview that goes in the reel.",
},
captions: {
closed: "Size default, with fade times behind the toggle",
open: "defaultMoreOpen",
sm: "Size sm",
plain: "No children: start and end only",
console: "Example: Console",
},
} as const
const LOOP_LABELS = {
length: "loop",
start: "Loop in",
end: "Loop out",
more: "Fades",
showMore: "Show fades",
hideMore: "Hide fades",
} as const
const CLIP_LABELS = {
length: "clip",
start: "In",
end: "Out",
} as const
const FADES = {
in: "Fade in",
out: "Fade out",
} as const
const LOOP = { start: "0:00", end: "1:24" }
const CLIP = { start: "4:12", end: "5:03" }
/** Time Range Form for a sound loop with its fades behind the toggle,
* closed and open, at the small size, and as a plain clip trim with no
* toggle, then the example built from it. */
export default function TimeRangeFormDemo() {
return (
<div className="grid w-full gap-10 p-6">
<div className="mx-auto grid w-full max-w-md min-w-0 grid-cols-1 gap-10">
<div className="grid gap-4">
<TimeRangeForm
title={COPY.loop.title}
description={COPY.loop.description}
defaultValue={LOOP}
labels={LOOP_LABELS}
>
<TimeField label={FADES.in} defaultValue="0:02" />
<TimeField label={FADES.out} defaultValue="0:04" />
</TimeRangeForm>
<DemoLabel>{COPY.captions.closed}</DemoLabel>
</div>
<div className="grid gap-4">
<TimeRangeForm
title={COPY.loop.title}
description={COPY.loop.description}
defaultValue={LOOP}
labels={LOOP_LABELS}
defaultMoreOpen
>
<TimeField label={FADES.in} defaultValue="0:02" />
<TimeField label={FADES.out} defaultValue="0:04" />
</TimeRangeForm>
<DemoLabel>{COPY.captions.open}</DemoLabel>
</div>
<div className="grid gap-4">
<TimeRangeForm
size="sm"
title={COPY.loop.title}
description={COPY.loop.description}
defaultValue={LOOP}
labels={LOOP_LABELS}
>
<TimeField label={FADES.in} defaultValue="0:02" />
<TimeField label={FADES.out} defaultValue="0:04" />
</TimeRangeForm>
<DemoLabel>{COPY.captions.sm}</DemoLabel>
</div>
<div className="grid gap-4">
<TimeRangeForm
title={COPY.clip.title}
description={COPY.clip.description}
defaultValue={CLIP}
labels={CLIP_LABELS}
/>
<DemoLabel>{COPY.captions.plain}</DemoLabel>
</div>
</div>
<ExampleGrid cols={1} className="mx-auto w-full max-w-xl">
<ExampleGridItem
name="time-range-form-console"
caption={COPY.captions.console}
>
<TimeRangeFormConsole />
</ExampleGridItem>
</ExampleGrid>
</div>
)
}
import type { ComponentProps } from "react"
import { cn } from "cn"
/**
* A caption under a demo or gallery piece, in medium-weight mono at
* 12px/20px. Long captions wrap with balanced last lines. The caption
* inherits its ground's text color; native paragraph props pass through.
*/
function DemoLabel({ className, ...props }: ComponentProps<"p">) {
return (
<p
data-slot="demo-label"
className={cn("font-mono text-xs/5 font-medium text-pretty", className)}
{...props}
/>
)
}
export { DemoLabel }
import type { ComponentProps, ReactNode } from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
import { DemoLabel } from "@/components/text/demo-label"
const exampleGridVariants = cva("grid grid-cols-1 gap-x-4 gap-y-10", {
variants: {
/**
* The most columns, reached at `lg`: `3` (the default) steps 1, 2, 3;
* `2` steps 1, 2 for pieces too wide for a third; `1` keeps one wide
* column for full-width pieces.
*/
cols: {
1: "",
2: "sm:grid-cols-2",
3: "sm:grid-cols-2 lg:grid-cols-3",
},
},
defaultVariants: { cols: 3 },
})
/**
* A grid of captioned pieces, such as the examples under a demo: one column
* on phones, two from `sm`, three from `lg` (fewer with `cols`). Each
* `ExampleGridItem` spans two rows of a subgrid, so every card in a row is
* the same height and every caption sits on the same line.
*/
function ExampleGrid({
cols,
className,
...props
}: ComponentProps<"ul"> & VariantProps<typeof exampleGridVariants>) {
return (
<ul
role="list"
data-slot="example-grid"
className={cn(exampleGridVariants({ cols }), className)}
{...props}
/>
)
}
type ExampleGridItemProps = ComponentProps<"li"> & {
/** The line under the piece, naming it: "Example: Ceramic study". */
caption: ReactNode
/**
* The piece's registry name, written to `data-example` so a gallery can
* link the card to that piece's own page. Optional.
*/
name?: string
}
/**
* One piece and its caption. The piece fills a frame with the tile radius
* and stretches to the tallest card in its row; a piece with its own
* background fills the frame, a smaller one can center itself inside. The
* frame's one column can shrink below the piece's natural width, so wide
* content (a code block) wraps or scrolls inside the piece instead of being
* cut off at the frame's edge. The frame is positioned and isolated, so a
* piece placed with `absolute` (a bare scene texture) stays inside it.
*/
function ExampleGridItem({
caption,
name,
className,
children,
...props
}: ExampleGridItemProps) {
return (
<li
data-slot="example-grid-item"
data-example={name}
className={cn("row-span-2 grid grid-rows-subgrid gap-3", className)}
{...props}
>
<div
data-slot="example-grid-frame"
className="relative isolate grid grid-cols-[minmax(0,1fr)] overflow-hidden rounded-(--tile-radius)"
>
{children}
</div>
<DemoLabel data-slot="example-grid-caption">{caption}</DemoLabel>
</li>
)
}
export { ExampleGrid, ExampleGridItem }
import { Grain } from "@/components/texture/grain"
import {
TimeField,
TimeRangeForm,
} from "@/components/time-range-form/time-range-form"
// The copy: change text here, not in the markup.
const COPY = {
device: "Field recorder",
format: "48 kHz / 24 bit",
title: "Rain on the greenhouse",
description: "Take 07 · Stereo ambience",
} as const
const RANGE = { start: "0:12", end: "2:48" }
const FADES = { in: "0:03", out: "0:08" } as const
const LABELS = {
length: "loop length",
start: "In point",
end: "Out point",
more: "Crossfades",
showMore: "Show crossfades",
hideMore: "Hide crossfades",
} as const
const FADE_LABELS = { in: "Fade in", out: "Fade out" } as const
/** A TimeRangeForm as an audio console with exposed fades and mono labels. */
export default function TimeRangeFormConsole() {
return (
<div className="relative isolate w-full overflow-hidden bg-background p-5 text-foreground [--font-display:var(--font-hanken-grotesk)]! sm:p-8">
<Grain variant="single" opacity={0.24} />
<div className="relative mb-4 flex justify-between font-mono text-xs text-primary">
<span>{COPY.device}</span>
<span>{COPY.format}</span>
</div>
<TimeRangeForm
title={COPY.title}
description={COPY.description}
defaultValue={RANGE}
defaultMoreOpen
labels={LABELS}
className="relative rounded-lg bg-card shadow-none ring-1 ring-border [&_.tabular-nums]:text-primary"
>
<TimeField label={FADE_LABELS.in} defaultValue={FADES.in} />
<TimeField label={FADE_LABELS.out} defaultValue={FADES.out} />
</TimeRangeForm>
</div>
)
}
import { cn } from "cn"
// Paper grain: an SVG turbulence filter as a data URI.
const PAPER_GRAIN = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='250' height='250' viewBox='0 0 100 100'%3E%3Cfilter id='n' color-interpolation-filters='sRGB'%3E%3CfeTurbulence type='turbulence' baseFrequency='1.4' numOctaves='1' seed='2' stitchTiles='stitch' result='n'/%3E%3CfeComponentTransfer result='g'%3E%3CfeFuncR type='linear' slope='4' intercept='1'/%3E%3CfeFuncG type='linear' slope='4' intercept='1'/%3E%3CfeFuncB type='linear' slope='4' intercept='1'/%3E%3C/feComponentTransfer%3E%3CfeColorMatrix type='saturate' values='0' in='g'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`
// Sandpaper grain: an SVG turbulence filter as a data URI.
const SANDPAPER_GRAIN = `url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='200' viewBox='0 0 100 100'%3E%3Cfilter id='n' color-interpolation-filters='sRGB'%3E%3CfeTurbulence type='turbulence' baseFrequency='2.2' numOctaves='2' seed='5' stitchTiles='stitch' result='n'/%3E%3CfeComponentTransfer result='g'%3E%3CfeFuncR type='linear' slope='2.5' intercept='0.8'/%3E%3CfeFuncG type='linear' slope='2.5' intercept='0.8'/%3E%3CfeFuncB type='linear' slope='2.5' intercept='0.8'/%3E%3C/feComponentTransfer%3E%3CfeColorMatrix type='saturate' values='0' in='g'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`
// Single noise: an SVG turbulence filter as a data URI.
const SINGLE_NOISE = `url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n' color-interpolation-filters='sRGB'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`
// Square grain: an SVG turbulence filter as a data URI.
const SQUARE_GRAIN = `url("data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22%20width=%22200%22%20height=%22200%22%20viewBox=%220%200%20100%20100%22%3E%3Cfilter%20id=%22n%22%20color-interpolation-filters=%22sRGB%22%3E%3CfeTurbulence%20type=%22turbulence%22%20baseFrequency=%222.1%22%20numOctaves=%223%22%20seed=%2211%22%20stitchTiles=%22stitch%22%20result=%22n%22/%3E%3CfeComponentTransfer%20result=%22g%22%3E%3CfeFuncR%20type=%22linear%22%20slope=%225.5%22%20intercept=%221.4%22/%3E%3CfeFuncG%20type=%22linear%22%20slope=%225.5%22%20intercept=%221.4%22/%3E%3CfeFuncB%20type=%22linear%22%20slope=%225.5%22%20intercept=%221.4%22/%3E%3C/feComponentTransfer%3E%3CfeColorMatrix%20type=%22saturate%22%20values=%220%22%20in=%22g%22/%3E%3C/filter%3E%3Crect%20width=%22100%%22%20height=%22100%%22%20filter=%22url(%23n)%22/%3E%3C/svg%3E")`
type Intensity = "fine" | "default" | "rich"
// One scale for every texture; `default` is the unscaled value.
const INTENSITY_MULT: Record<Intensity, number> = {
fine: 0.6,
default: 1,
rich: 1.45,
}
const alpha = (base: number, mult: number) => (base * mult).toFixed(4)
// Four grain treatments; each paints a single texture layer.
// Full-bleed art layer — drop inside a `relative` parent; sits behind content.
/** The texture treatment painted by `Grain`. */
type GrainVariant =
// Stylized paper-look variants — heavier filter chain than plain noise.
"paper" | "sandpaper" | "square" | "single"
type Layer = {
src: string
size: string
opacity: number
blend: "overlay" | "soft-light"
}
const BLEND_CLASS: Record<Layer["blend"], string> = {
overlay: "mix-blend-overlay",
"soft-light": "mix-blend-soft-light",
}
const VARIANT_TEXTURES: Record<GrainVariant, Layer> = {
paper: {
src: PAPER_GRAIN,
size: "250px",
opacity: 0.25,
blend: "overlay",
},
sandpaper: {
src: SANDPAPER_GRAIN,
size: "200px",
opacity: 0.25,
blend: "overlay",
},
square: {
src: SQUARE_GRAIN,
size: "200px",
opacity: 0.8,
blend: "soft-light",
},
single: { src: SINGLE_NOISE, size: "200px", opacity: 0.3, blend: "overlay" },
}
/**
* A decorative grain layer that fills a positioned parent without blocking
* clicks. Choose a texture and adjust its strength with `intensity` or
* `opacity`. `className` and other div props land on the outer layer.
*/
function Grain({
variant = "single",
intensity = "default",
opacity,
isolated = false,
className,
...props
}: React.ComponentProps<"div"> & {
/** The grain treatment: `single` (default), `paper`, `sandpaper` or `square`. */
variant?: GrainVariant
/** Multiplies the texture's opacity: `fine` 0.6×, `default` 1×, `rich` 1.45×. */
intensity?: Intensity
/** The texture opacity, from 0 to 1. Takes precedence over `intensity`. */
opacity?: number
/**
* Adds paint containment when true. This creates a stacking context, so
* the texture stops blending with scene layers outside this element.
*/
isolated?: boolean
}) {
const layer = VARIANT_TEXTURES[variant]
const m =
opacity != null ? opacity / layer.opacity : INTENSITY_MULT[intensity]
return (
<div
data-slot="grain"
data-variant={variant}
aria-hidden="true"
className={cn(
"pointer-events-none absolute inset-0",
isolated && "contain-[paint]",
className
)}
{...props}
>
<div
className={cn("absolute inset-0", BLEND_CLASS[layer.blend])}
style={{
backgroundImage: layer.src,
backgroundSize: layer.size,
opacity: layer.opacity * m,
}}
/>
</div>
)
}
export { Grain }
Installation
npx shadcn@latest add @01orbital/time-range-formUsage
import { TimeRangeForm } from "@/components/time-range-form/time-range-form"Needs props to render
title, labels; see the API reference below.Examples
Consoletime-range-form-console
Audio loop settings example showing the LoopSettingsForm as a console, with the fade in and out controls left exposed and monospace labels.
import { Grain } from "@/components/texture/grain"
import {
TimeField,
TimeRangeForm,
} from "@/components/time-range-form/time-range-form"
// The copy: change text here, not in the markup.
const COPY = {
device: "Field recorder",
format: "48 kHz / 24 bit",
title: "Rain on the greenhouse",
description: "Take 07 · Stereo ambience",
} as const
const RANGE = { start: "0:12", end: "2:48" }
const FADES = { in: "0:03", out: "0:08" } as const
const LABELS = {
length: "loop length",
start: "In point",
end: "Out point",
more: "Crossfades",
showMore: "Show crossfades",
hideMore: "Hide crossfades",
} as const
const FADE_LABELS = { in: "Fade in", out: "Fade out" } as const
/** A TimeRangeForm as an audio console with exposed fades and mono labels. */
export default function TimeRangeFormConsole() {
return (
<div className="relative isolate w-full overflow-hidden bg-background p-5 text-foreground [--font-display:var(--font-hanken-grotesk)]! sm:p-8">
<Grain variant="single" opacity={0.24} />
<div className="relative mb-4 flex justify-between font-mono text-xs text-primary">
<span>{COPY.device}</span>
<span>{COPY.format}</span>
</div>
<TimeRangeForm
title={COPY.title}
description={COPY.description}
defaultValue={RANGE}
defaultMoreOpen
labels={LABELS}
className="relative rounded-lg bg-card shadow-none ring-1 ring-border [&_.tabular-nums]:text-primary"
>
<TimeField label={FADE_LABELS.in} defaultValue={FADES.in} />
<TimeField label={FADE_LABELS.out} defaultValue={FADES.out} />
</TimeRangeForm>
</div>
)
}
import { cn } from "cn"
// Paper grain: an SVG turbulence filter as a data URI.
const PAPER_GRAIN = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='250' height='250' viewBox='0 0 100 100'%3E%3Cfilter id='n' color-interpolation-filters='sRGB'%3E%3CfeTurbulence type='turbulence' baseFrequency='1.4' numOctaves='1' seed='2' stitchTiles='stitch' result='n'/%3E%3CfeComponentTransfer result='g'%3E%3CfeFuncR type='linear' slope='4' intercept='1'/%3E%3CfeFuncG type='linear' slope='4' intercept='1'/%3E%3CfeFuncB type='linear' slope='4' intercept='1'/%3E%3C/feComponentTransfer%3E%3CfeColorMatrix type='saturate' values='0' in='g'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`
// Sandpaper grain: an SVG turbulence filter as a data URI.
const SANDPAPER_GRAIN = `url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='200' viewBox='0 0 100 100'%3E%3Cfilter id='n' color-interpolation-filters='sRGB'%3E%3CfeTurbulence type='turbulence' baseFrequency='2.2' numOctaves='2' seed='5' stitchTiles='stitch' result='n'/%3E%3CfeComponentTransfer result='g'%3E%3CfeFuncR type='linear' slope='2.5' intercept='0.8'/%3E%3CfeFuncG type='linear' slope='2.5' intercept='0.8'/%3E%3CfeFuncB type='linear' slope='2.5' intercept='0.8'/%3E%3C/feComponentTransfer%3E%3CfeColorMatrix type='saturate' values='0' in='g'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`
// Single noise: an SVG turbulence filter as a data URI.
const SINGLE_NOISE = `url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n' color-interpolation-filters='sRGB'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E")`
// Square grain: an SVG turbulence filter as a data URI.
const SQUARE_GRAIN = `url("data:image/svg+xml;charset=utf-8,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22%20width=%22200%22%20height=%22200%22%20viewBox=%220%200%20100%20100%22%3E%3Cfilter%20id=%22n%22%20color-interpolation-filters=%22sRGB%22%3E%3CfeTurbulence%20type=%22turbulence%22%20baseFrequency=%222.1%22%20numOctaves=%223%22%20seed=%2211%22%20stitchTiles=%22stitch%22%20result=%22n%22/%3E%3CfeComponentTransfer%20result=%22g%22%3E%3CfeFuncR%20type=%22linear%22%20slope=%225.5%22%20intercept=%221.4%22/%3E%3CfeFuncG%20type=%22linear%22%20slope=%225.5%22%20intercept=%221.4%22/%3E%3CfeFuncB%20type=%22linear%22%20slope=%225.5%22%20intercept=%221.4%22/%3E%3C/feComponentTransfer%3E%3CfeColorMatrix%20type=%22saturate%22%20values=%220%22%20in=%22g%22/%3E%3C/filter%3E%3Crect%20width=%22100%%22%20height=%22100%%22%20filter=%22url(%23n)%22/%3E%3C/svg%3E")`
type Intensity = "fine" | "default" | "rich"
// One scale for every texture; `default` is the unscaled value.
const INTENSITY_MULT: Record<Intensity, number> = {
fine: 0.6,
default: 1,
rich: 1.45,
}
const alpha = (base: number, mult: number) => (base * mult).toFixed(4)
// Four grain treatments; each paints a single texture layer.
// Full-bleed art layer — drop inside a `relative` parent; sits behind content.
/** The texture treatment painted by `Grain`. */
type GrainVariant =
// Stylized paper-look variants — heavier filter chain than plain noise.
"paper" | "sandpaper" | "square" | "single"
type Layer = {
src: string
size: string
opacity: number
blend: "overlay" | "soft-light"
}
const BLEND_CLASS: Record<Layer["blend"], string> = {
overlay: "mix-blend-overlay",
"soft-light": "mix-blend-soft-light",
}
const VARIANT_TEXTURES: Record<GrainVariant, Layer> = {
paper: {
src: PAPER_GRAIN,
size: "250px",
opacity: 0.25,
blend: "overlay",
},
sandpaper: {
src: SANDPAPER_GRAIN,
size: "200px",
opacity: 0.25,
blend: "overlay",
},
square: {
src: SQUARE_GRAIN,
size: "200px",
opacity: 0.8,
blend: "soft-light",
},
single: { src: SINGLE_NOISE, size: "200px", opacity: 0.3, blend: "overlay" },
}
/**
* A decorative grain layer that fills a positioned parent without blocking
* clicks. Choose a texture and adjust its strength with `intensity` or
* `opacity`. `className` and other div props land on the outer layer.
*/
function Grain({
variant = "single",
intensity = "default",
opacity,
isolated = false,
className,
...props
}: React.ComponentProps<"div"> & {
/** The grain treatment: `single` (default), `paper`, `sandpaper` or `square`. */
variant?: GrainVariant
/** Multiplies the texture's opacity: `fine` 0.6×, `default` 1×, `rich` 1.45×. */
intensity?: Intensity
/** The texture opacity, from 0 to 1. Takes precedence over `intensity`. */
opacity?: number
/**
* Adds paint containment when true. This creates a stacking context, so
* the texture stops blending with scene layers outside this element.
*/
isolated?: boolean
}) {
const layer = VARIANT_TEXTURES[variant]
const m =
opacity != null ? opacity / layer.opacity : INTENSITY_MULT[intensity]
return (
<div
data-slot="grain"
data-variant={variant}
aria-hidden="true"
className={cn(
"pointer-events-none absolute inset-0",
isolated && "contain-[paint]",
className
)}
{...props}
>
<div
className={cn("absolute inset-0", BLEND_CLASS[layer.blend])}
style={{
backgroundImage: layer.src,
backgroundSize: layer.size,
opacity: layer.opacity * m,
}}
/>
</div>
)
}
export { Grain }
"use client"
import { useId, useState, type ComponentProps, type ReactNode } from "react"
import { MinusIcon, PlusIcon } from "@phosphor-icons/react"
import { cn } from "cn"
import { Button } from "@/components/ui/button"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible"
import { Field, FieldGroup, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator"
/** A start and an end time, each an `m:ss` string as typed. */
type TimeRange = { start: string; end: string }
// m:ss to seconds; anything else reads as not a time.
function seconds(value: string) {
const match = /^(\d+):([0-5]\d)$/.exec(value.trim())
return match ? Number(match[1]) * 60 + Number(match[2]) : null
}
function clock(total: number) {
return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`
}
type TimeFieldProps = Omit<
ComponentProps<typeof Input>,
"value" | "defaultValue" | "onChange"
> & {
/** The field's label, set small in mono capitals above the input. */
label: ReactNode
/** The time as typed, such as `1:24`, when you control it. */
value?: string
/** The starting time when the field keeps its own value. */
defaultValue?: string
/** Called with the text on every change. */
onValueChange?: (value: string) => void
}
/**
* A labelled text field for an `m:ss` time, in tabular mono figures. Use it
* inside `TimeRangeForm`'s collapsible section for times that go with the
* range, such as fades. Controlled with `value` and `onValueChange`, or
* seeded with `defaultValue`. Other props go to the input.
*/
function TimeField({
label,
value,
defaultValue = "",
onValueChange,
id,
className,
...props
}: TimeFieldProps) {
const fallbackId = useId()
const inputId = id ?? fallbackId
const [uncontrolled, setUncontrolled] = useState(defaultValue)
const text = value ?? uncontrolled
return (
<Field data-slot="time-field" className="gap-2">
<FieldLabel
htmlFor={inputId}
className="font-mono text-xs font-normal text-muted-foreground"
>
{label}
</FieldLabel>
<Input
id={inputId}
value={text}
onChange={(event) => {
if (value === undefined) setUncontrolled(event.target.value)
onValueChange?.(event.target.value)
}}
className={cn(
"border-input bg-transparent font-mono tabular-nums dark:bg-input/30",
className
)}
{...props}
/>
</Field>
)
}
type TimeRangeFormProps = Omit<
ComponentProps<typeof Card>,
"title" | "children" | "defaultValue" | "onChange"
> & {
/** The card's title. */
title: ReactNode
/** A line under the title. */
description?: ReactNode
/** The range, when you control it with `onValueChange`. */
value?: TimeRange
/** The starting range when the form keeps its own value. */
defaultValue?: TimeRange
/** Called with both times after either field changes. */
onValueChange?: (value: TimeRange) => void
/** Every word the form shows or announces. */
labels: {
/** Beside the length worked out from the two times, such as "Loop". */
length: string
/** The start field's label. */
start: string
/** The end field's label. */
end: string
/** The heading over the collapsible section, when there is one. */
more?: string
/** The toggle's accessible name while the section is hidden. */
showMore?: string
/** The toggle's accessible name while the section shows. */
hideMore?: string
}
/**
* Fields that go with the range, shown behind a toggle under it: fade
* times for a loop, a buffer for a booking. Build them from `TimeField`.
* Leave out for no toggle.
*/
children?: ReactNode
/** Shows the collapsible section on first render. */
defaultMoreOpen?: boolean
}
/**
* A card for a span of time: start and end times typed as `m:ss`, with the
* length worked out large between them, for a sound loop, a clip trim, a
* meeting slot or a shift. The length shows a dash until both times read as
* times and the end comes after the start. Anything passed as children sits
* in a collapsible section under the range. Other props go to the Card.
*/
function TimeRangeForm({
title,
description,
value,
defaultValue = { start: "", end: "" },
onValueChange,
labels,
children,
defaultMoreOpen = false,
className,
...props
}: TimeRangeFormProps) {
const [isOpen, setIsOpen] = useState(defaultMoreOpen)
const [uncontrolled, setUncontrolled] = useState(defaultValue)
const range = value ?? uncontrolled
const set = (key: keyof TimeRange) => (next: string) => {
const updated = { ...range, [key]: next }
if (value === undefined) setUncontrolled(updated)
onValueChange?.(updated)
}
const start = seconds(range.start)
const end = seconds(range.end)
const length =
start !== null && end !== null && end > start ? clock(end - start) : "–"
return (
<Card
data-slot="time-range-form"
className={cn("gap-8", className)}
{...props}
>
<CardHeader>
<CardTitle>{title}</CardTitle>
{description != null && (
<CardDescription>{description}</CardDescription>
)}
</CardHeader>
<CardContent className="flex flex-col gap-8">
<span className="flex items-baseline gap-2">
<span className="font-display text-5xl tracking-tight tabular-nums">
{length}
</span>
<span className="font-mono text-xs font-normal text-muted-foreground">
{labels.length}
</span>
</span>
<FieldGroup className="grid grid-cols-2 gap-4">
<TimeField
label={labels.start}
value={range.start}
onValueChange={set("start")}
/>
<TimeField
label={labels.end}
value={range.end}
onValueChange={set("end")}
/>
</FieldGroup>
{children != null && (
<Collapsible
open={isOpen}
onOpenChange={setIsOpen}
className="flex flex-col gap-3"
>
<Separator />
<p className="flex items-center justify-between">
<span className="font-mono text-xs font-normal text-muted-foreground">
{labels.more}
</span>
<CollapsibleTrigger
render={
<Button
variant="ghost"
size="icon-sm"
aria-label={isOpen ? labels.hideMore : labels.showMore}
/>
}
>
{isOpen ? <MinusIcon /> : <PlusIcon />}
</CollapsibleTrigger>
</p>
<CollapsibleContent>
<FieldGroup className="grid grid-cols-2 gap-4 pt-1">
{children}
</FieldGroup>
</CollapsibleContent>
</Collapsible>
)}
</CardContent>
</Card>
)
}
export { TimeField, TimeRangeForm }
npx shadcn@latest add @01orbital/time-range-form-consoleAnatomy
Time Range Form is built from 2 parts. In the example they nest like this:
TimeRangeForm
└─ TimeFieldTimeRangeForm: A card for a span of time: start and end times typed asm:ss, with the length worked out large between them, for a sound loop, a clip trim, a meeting slot or a shift. The length shows a dash until both times read as times and the end comes after the start. Anything passed as children sits in a collapsible section under the range. Other props go to the Card.TimeField: A labelled text field for anm:sstime, in tabular mono figures. Use it insideTimeRangeForm's collapsible section for times that go with the range, such as fades. Controlled withvalueandonValueChange, or seeded withdefaultValue. Other props go to the input.
API reference
TimeRangeForm
A card for a span of time: start and end times typed as m:ss, with the length worked out large between them, for a sound loop, a clip trim, a meeting slot or a shift. The length shows a dash until both times read as times and the end comes after the start. Anything passed as children sits in a collapsible section under the range. Other props go to the Card.
Prop
Type
It also accepts the HTML attributes of the element it renders, and the props of the stock Card it builds on.
TimeField
A labelled text field for an m:ss time, in tabular mono figures. Use it inside TimeRangeForm's collapsible section for times that go with the range, such as fades. Controlled with value and onValueChange, or seeded with defaultValue. Other props go to the input.
Prop
Type
It also accepts the HTML attributes of the element it renders.
Dependencies
npm: @phosphor-icons/react, cn. The CLI installs them for you.
Requires these pieces. The CLI adds each one that is missing and won't replace a file you already have unless you choose to:
The shadcn parts here are their Base UI versions, and this piece uses Base UI's API. A Radix version you already have won't work with it.
Last updated on