duration-input-react
v0.1.1
Published
Controlled React input for duration intervals
Maintainers
Readme
duration-input-react
Controlled React + TypeScript input for duration intervals.
This component was created to handle time period inputs (durations), not clock time inputs (time of day).
Repository
https://github.com/rcotta/duration-input
Features
- Single
<input />with dynamic:mask - Modes:
ss,mm,hh,mm:ss,hh:mm,hh:mm:ss - Controlled value as total seconds (
number) - Accepts standard input props like
className,id,name,aria-* - Numeric, segment-aware editing
- Dynamic leading-segment width from configured max (
max*) - Better mobile behavior via
beforeinput+onChangefallback - Built-in clamping/validation per mode
Installation
npm install duration-input-reactExports
import { DurationInput } from 'duration-input-react';
import type { DurationInputProps, DurationMode } from 'duration-input-react';API
type DurationInputProps = Omit<
React.InputHTMLAttributes<HTMLInputElement>,
'value' | 'onChange' | 'type'
> & {
value: number; // total seconds
onChange: (seconds: number) => void;
mode: 'ss' | 'mm' | 'hh' | 'mm:ss' | 'hh:mm' | 'hh:mm:ss';
maxHours?: number;
maxMinutes?: number;
maxSeconds?: number;
};Styling
Use className or inline styles like any standard input:
<DurationInput
value={seconds}
onChange={setSeconds}
mode="hh:mm:ss"
className="duration-field"
/>.duration-field {
width: 220px;
max-width: 100%;
padding: 10px 12px;
}Validation rules
hh: clamps withmaxHourswhen provided; otherwise unboundedmm/mm:ss: clamps withmaxMinuteswhen providedhh:mm/hh:mm:ss: minutes clamp to0..59ss: clamps withmaxSecondswhen provided- Modes with segmented seconds (
mm:ss,hh:mm:ss) clamp seconds to0..59
Editing behavior
Ctrl+A+Backspace/Deleteclears and moves caret to startBackspaceat end shifts digits right (helpful on mobile)onChangeonly fires when total seconds actually changes
Usage
import { useState } from 'react';
import { DurationInput } from 'duration-input-react';
export function Example() {
const [seconds, setSeconds] = useState(0);
return (
<DurationInput
value={seconds}
onChange={setSeconds}
mode="hh:mm:ss"
maxHours={99}
aria-label="Duration"
name="duration"
/>
);
}Demo
The project contains a local demo app with PT-BR and EN pages.
cd demo
npm install
npm run devPages:
- PT-BR:
http://localhost:5173/index.html - EN:
http://localhost:5173/en.html
Development
cd demo
npm test
npm run buildLicense
MIT
