duration-input-react 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rafael Cotta
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,117 @@
1
+ # duration-input-react
2
+
3
+ [![npm](https://img.shields.io/npm/v/duration-input-react)](https://www.npmjs.com/package/duration-input-react)
4
+ [![npm downloads](https://img.shields.io/npm/dw/duration-input-react)](https://www.npmjs.com/package/duration-input-react)
5
+ [![License](https://img.shields.io/npm/l/duration-input-react)](./LICENSE)
6
+ [![Repo](https://img.shields.io/badge/github-rcotta%2Fduration--input-181717?logo=github)](https://github.com/rcotta/duration-input)
7
+ [![Issues](https://img.shields.io/github/issues/rcotta/duration-input)](https://github.com/rcotta/duration-input/issues)
8
+
9
+ Controlled React + TypeScript input for duration intervals.
10
+
11
+ This component was created to handle time period inputs (durations), not clock time inputs (time of day).
12
+
13
+ ## Repository
14
+
15
+ https://github.com/rcotta/duration-input
16
+
17
+ ## Features
18
+
19
+ - Single `<input />` with dynamic `:` mask
20
+ - Modes: `ss`, `mm`, `hh`, `mm:ss`, `hh:mm`, `hh:mm:ss`
21
+ - Controlled value as total seconds (`number`)
22
+ - Numeric, segment-aware editing
23
+ - Dynamic leading-segment width from configured max (`max*`)
24
+ - Better mobile behavior via `beforeinput` + `onChange` fallback
25
+ - Built-in clamping/validation per mode
26
+
27
+ ## Installation
28
+
29
+ ```bash
30
+ npm install duration-input-react
31
+ ```
32
+
33
+ ## Exports
34
+
35
+ ```ts
36
+ import { DurationInput } from 'duration-input-react';
37
+ import type { DurationInputProps, DurationMode } from 'duration-input-react';
38
+ ```
39
+
40
+ ## API
41
+
42
+ ```ts
43
+ type DurationInputProps = Omit<
44
+ React.InputHTMLAttributes<HTMLInputElement>,
45
+ 'value' | 'onChange' | 'type'
46
+ > & {
47
+ value: number; // total seconds
48
+ onChange: (seconds: number) => void;
49
+ mode: 'ss' | 'mm' | 'hh' | 'mm:ss' | 'hh:mm' | 'hh:mm:ss';
50
+
51
+ maxHours?: number;
52
+ maxMinutes?: number;
53
+ maxSeconds?: number;
54
+ };
55
+ ```
56
+
57
+ ## Validation rules
58
+
59
+ - `hh`: clamps with `maxHours` when provided; otherwise unbounded
60
+ - `mm`/`mm:ss`: clamps with `maxMinutes` when provided
61
+ - `hh:mm`/`hh:mm:ss`: minutes clamp to `0..59`
62
+ - `ss`: clamps with `maxSeconds` when provided
63
+ - Modes with segmented seconds (`mm:ss`, `hh:mm:ss`) clamp seconds to `0..59`
64
+
65
+ ## Editing behavior
66
+
67
+ - `Ctrl+A` + `Backspace/Delete` clears and moves caret to start
68
+ - `Backspace` at end shifts digits right (helpful on mobile)
69
+ - `onChange` only fires when total seconds actually changes
70
+
71
+ ## Usage
72
+
73
+ ```tsx
74
+ import { useState } from 'react';
75
+ import { DurationInput } from 'duration-input-react';
76
+
77
+ export function Example() {
78
+ const [seconds, setSeconds] = useState(0);
79
+
80
+ return (
81
+ <DurationInput
82
+ value={seconds}
83
+ onChange={setSeconds}
84
+ mode="hh:mm:ss"
85
+ maxHours={99}
86
+ aria-label="Duration"
87
+ name="duration"
88
+ />
89
+ );
90
+ }
91
+ ```
92
+
93
+ ## Demo
94
+
95
+ The project contains a local demo app with PT-BR and EN pages.
96
+
97
+ ```bash
98
+ cd demo
99
+ npm install
100
+ npm run dev
101
+ ```
102
+
103
+ Pages:
104
+ - PT-BR: `http://localhost:5173/index.html`
105
+ - EN: `http://localhost:5173/en.html`
106
+
107
+ ## Development
108
+
109
+ ```bash
110
+ cd demo
111
+ npm test
112
+ npm run build
113
+ ```
114
+
115
+ ## License
116
+
117
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,412 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ DurationInput: () => DurationInput
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+
27
+ // src/components/ui/DurationInput.tsx
28
+ var import_react = require("react");
29
+
30
+ // src/components/ui/duration-input.utils.ts
31
+ var EMPTY_VALUES = { hh: 0, mm: 0, ss: 0 };
32
+ var NAVIGATION_KEYS = /* @__PURE__ */ new Set(["ArrowLeft", "ArrowRight", "Tab", "Home", "End"]);
33
+ var EDIT_SHORTCUT_KEYS = /* @__PURE__ */ new Set(["a", "c", "v", "x", "z", "y"]);
34
+ function assertNever(value) {
35
+ throw new Error(`Unsupported duration mode: ${String(value)}`);
36
+ }
37
+ function getModeSegments(mode) {
38
+ switch (mode) {
39
+ case "hh:mm:ss":
40
+ return ["hh", "mm", "ss"];
41
+ case "hh:mm":
42
+ return ["hh", "mm"];
43
+ case "mm:ss":
44
+ return ["mm", "ss"];
45
+ case "hh":
46
+ return ["hh"];
47
+ case "mm":
48
+ return ["mm"];
49
+ case "ss":
50
+ return ["ss"];
51
+ default:
52
+ return assertNever(mode);
53
+ }
54
+ }
55
+ function clamp(n, min, max) {
56
+ if (!Number.isFinite(n) || Number.isNaN(n)) return min;
57
+ if (n < min) return min;
58
+ if (max !== void 0 && n > max) return max;
59
+ return n;
60
+ }
61
+ function applyModeValidation(mode, values, limits) {
62
+ const normalized = { ...values };
63
+ if (mode.includes("hh")) {
64
+ normalized.hh = clamp(normalized.hh, 0, limits.maxHours);
65
+ }
66
+ if (mode === "mm" || mode === "mm:ss") {
67
+ normalized.mm = clamp(normalized.mm, 0, limits.maxMinutes);
68
+ } else if (mode.includes("mm")) {
69
+ normalized.mm = clamp(normalized.mm, 0, 59);
70
+ }
71
+ if (mode === "ss") {
72
+ normalized.ss = clamp(normalized.ss, 0, limits.maxSeconds);
73
+ } else if (mode.includes("ss")) {
74
+ normalized.ss = clamp(normalized.ss, 0, 59);
75
+ }
76
+ return normalized;
77
+ }
78
+ function secondsToSegments(mode, totalSeconds, limits) {
79
+ const safeSeconds = Math.max(0, Math.floor(Number.isFinite(totalSeconds) ? totalSeconds : 0));
80
+ const values = {
81
+ hh: Math.floor(safeSeconds / 3600),
82
+ mm: Math.floor(safeSeconds % 3600 / 60),
83
+ ss: safeSeconds % 60
84
+ };
85
+ if (mode === "hh") {
86
+ values.hh = Math.floor(safeSeconds / 3600);
87
+ values.mm = 0;
88
+ values.ss = 0;
89
+ }
90
+ if (mode === "mm") {
91
+ values.hh = 0;
92
+ values.mm = Math.floor(safeSeconds / 60);
93
+ values.ss = 0;
94
+ }
95
+ if (mode === "ss") {
96
+ values.hh = 0;
97
+ values.mm = 0;
98
+ values.ss = safeSeconds;
99
+ }
100
+ if (mode === "mm:ss") {
101
+ values.hh = 0;
102
+ values.mm = Math.floor(safeSeconds / 60);
103
+ values.ss = safeSeconds % 60;
104
+ }
105
+ return applyModeValidation(mode, values, limits);
106
+ }
107
+ function segmentsToSeconds(mode, values) {
108
+ const hh = mode.includes("hh") ? values.hh : 0;
109
+ const mm = mode.includes("mm") ? values.mm : 0;
110
+ const ss = mode.includes("ss") ? values.ss : 0;
111
+ const total = hh * 3600 + mm * 60 + ss;
112
+ return Number.isFinite(total) && !Number.isNaN(total) ? total : 0;
113
+ }
114
+ function getDigitsForLimit(limit) {
115
+ if (limit === void 0 || !Number.isFinite(limit) || Number.isNaN(limit)) return 2;
116
+ return Math.max(2, String(Math.max(0, Math.floor(limit))).length);
117
+ }
118
+ function getSegmentWidths(mode, limits) {
119
+ const widths = { hh: 2, mm: 2, ss: 2 };
120
+ if (mode === "hh" || mode === "hh:mm" || mode === "hh:mm:ss") {
121
+ widths.hh = getDigitsForLimit(limits.maxHours);
122
+ }
123
+ if (mode === "mm" || mode === "mm:ss") {
124
+ widths.mm = getDigitsForLimit(limits.maxMinutes);
125
+ }
126
+ if (mode === "ss") {
127
+ widths.ss = getDigitsForLimit(limits.maxSeconds);
128
+ }
129
+ return widths;
130
+ }
131
+ function getDisplayWidth(value, minWidth) {
132
+ return Math.max(minWidth, String(Math.max(0, value)).length);
133
+ }
134
+ function formatDisplay(mode, values, widths) {
135
+ return getModeSegments(mode).map((key) => String(values[key]).padStart(getDisplayWidth(values[key], widths[key]), "0")).join(":");
136
+ }
137
+ function parseRawInput(raw, mode) {
138
+ const segments = getModeSegments(mode);
139
+ const parsed = { ...EMPTY_VALUES };
140
+ const cleaned = raw.trim();
141
+ if (!cleaned) return parsed;
142
+ if (cleaned.includes(":")) {
143
+ const parts = cleaned.split(":").slice(0, segments.length);
144
+ segments.forEach((segment, index) => {
145
+ const digits2 = (parts[index] ?? "").replace(/\D/g, "");
146
+ parsed[segment] = digits2 ? Number.parseInt(digits2, 10) : 0;
147
+ });
148
+ return parsed;
149
+ }
150
+ const digits = cleaned.replace(/\D/g, "");
151
+ if (!digits) return parsed;
152
+ if (segments.length === 1) {
153
+ parsed[segments[0]] = Number.parseInt(digits, 10);
154
+ return parsed;
155
+ }
156
+ let end = digits.length;
157
+ for (let idx = segments.length - 1; idx >= 0; idx -= 1) {
158
+ const key = segments[idx];
159
+ if (idx === 0) {
160
+ const chunk2 = digits.slice(0, end);
161
+ parsed[key] = chunk2 ? Number.parseInt(chunk2, 10) : 0;
162
+ break;
163
+ }
164
+ const start = Math.max(0, end - 2);
165
+ const chunk = digits.slice(start, end);
166
+ parsed[key] = chunk ? Number.parseInt(chunk, 10) : 0;
167
+ end = start;
168
+ }
169
+ return parsed;
170
+ }
171
+ function normalizeRaw(mode, raw, limits, widths) {
172
+ const parsed = parseRawInput(raw, mode);
173
+ const values = applyModeValidation(mode, parsed, limits);
174
+ return {
175
+ values,
176
+ display: formatDisplay(mode, values, widths),
177
+ seconds: segmentsToSeconds(mode, values)
178
+ };
179
+ }
180
+ function getRanges(display, mode) {
181
+ const keys = getModeSegments(mode);
182
+ const parts = display.split(":");
183
+ let offset = 0;
184
+ return keys.map((key, index) => {
185
+ const part = parts[index] ?? "";
186
+ const start = offset;
187
+ const end = start + part.length;
188
+ offset = end + 1;
189
+ return { key, start, end };
190
+ });
191
+ }
192
+ function findRangeAtPosition(ranges, pos) {
193
+ for (const range of ranges) {
194
+ if (pos >= range.start && pos <= range.end) return range;
195
+ }
196
+ return null;
197
+ }
198
+ function isEditingShortcut(event) {
199
+ if (!(event.ctrlKey || event.metaKey)) return false;
200
+ return EDIT_SHORTCUT_KEYS.has(event.key.toLowerCase());
201
+ }
202
+ function replaceSelection(display, start, end, value) {
203
+ return `${display.slice(0, start)}${value}${display.slice(end)}`;
204
+ }
205
+
206
+ // src/components/ui/DurationInput.tsx
207
+ var import_jsx_runtime = require("react/jsx-runtime");
208
+ function DurationInput({
209
+ value,
210
+ onChange,
211
+ mode,
212
+ maxHours,
213
+ maxMinutes,
214
+ maxSeconds,
215
+ disabled = false,
216
+ inputMode = "numeric",
217
+ ...inputProps
218
+ }) {
219
+ const inputRef = (0, import_react.useRef)(null);
220
+ const pendingCaretRef = (0, import_react.useRef)(null);
221
+ const limits = (0, import_react.useMemo)(() => ({ maxHours, maxMinutes, maxSeconds }), [maxHours, maxMinutes, maxSeconds]);
222
+ const widths = (0, import_react.useMemo)(() => getSegmentWidths(mode, limits), [mode, limits]);
223
+ const externalDisplay = (0, import_react.useMemo)(() => {
224
+ const values = secondsToSegments(mode, value, limits);
225
+ return formatDisplay(mode, values, widths);
226
+ }, [mode, value, limits, widths]);
227
+ const [isEditing, setIsEditing] = (0, import_react.useState)(false);
228
+ const [draftDisplay, setDraftDisplay] = (0, import_react.useState)(externalDisplay);
229
+ const activeDisplay = isEditing ? draftDisplay : externalDisplay;
230
+ (0, import_react.useEffect)(() => {
231
+ if (pendingCaretRef.current === null || !inputRef.current) return;
232
+ const caret = pendingCaretRef.current;
233
+ inputRef.current.setSelectionRange(caret, caret);
234
+ pendingCaretRef.current = null;
235
+ }, [draftDisplay]);
236
+ const commitNormalized = (normalized, nextCaret) => {
237
+ if (nextCaret !== void 0) {
238
+ pendingCaretRef.current = Math.min(nextCaret, normalized.display.length);
239
+ }
240
+ if (normalized.display !== draftDisplay) {
241
+ setDraftDisplay(normalized.display);
242
+ }
243
+ if (normalized.seconds !== value) {
244
+ onChange(normalized.seconds);
245
+ }
246
+ };
247
+ const applyRaw = (raw, nextCaret) => {
248
+ const normalized = normalizeRaw(mode, raw, limits, widths);
249
+ commitNormalized(normalized, nextCaret);
250
+ };
251
+ const moveCaret = (nextCaret) => {
252
+ const input = inputRef.current;
253
+ if (!input) return;
254
+ const boundedCaret = Math.min(nextCaret, activeDisplay.length);
255
+ input.setSelectionRange(boundedCaret, boundedCaret);
256
+ };
257
+ const applyDisplayEdit = (nextDisplay, nextCaret) => {
258
+ const boundedCaret = Math.min(nextCaret, nextDisplay.length);
259
+ if (nextDisplay === activeDisplay) {
260
+ moveCaret(boundedCaret);
261
+ return;
262
+ }
263
+ applyRaw(nextDisplay, boundedCaret);
264
+ };
265
+ const applyDeleteShiftAtEnd = () => {
266
+ const digits = activeDisplay.replace(/\D/g, "");
267
+ const shiftedDigits = digits.slice(0, -1);
268
+ const normalized = normalizeRaw(mode, shiftedDigits, limits, widths);
269
+ commitNormalized(normalized, normalized.display.length);
270
+ };
271
+ const handleDeleteKey = (key, cursor, selectionEnd) => {
272
+ const hasSelection = selectionEnd !== cursor;
273
+ const selectedAll = hasSelection && cursor === 0 && selectionEnd === activeDisplay.length;
274
+ if (selectedAll) {
275
+ applyRaw("", 0);
276
+ return true;
277
+ }
278
+ if (!hasSelection && key === "Backspace" && cursor === activeDisplay.length) {
279
+ applyDeleteShiftAtEnd();
280
+ return true;
281
+ }
282
+ const leftIsColon = key === "Backspace" && cursor > 0 && activeDisplay[cursor - 1] === ":";
283
+ const currentIsColon = activeDisplay[cursor] === ":";
284
+ if (leftIsColon || currentIsColon) {
285
+ const nextCursor = key === "Backspace" ? Math.max(0, cursor - 1) : Math.min(activeDisplay.length, cursor + 1);
286
+ moveCaret(nextCursor);
287
+ return true;
288
+ }
289
+ return false;
290
+ };
291
+ const handleDigitInsertion = (digit, cursor, selectionEnd) => {
292
+ const ranges = getRanges(activeDisplay, mode);
293
+ const targetRange = findRangeAtPosition(ranges, cursor);
294
+ if (!targetRange) return;
295
+ const segments = getModeSegments(mode);
296
+ const leadingSegment = segments[0];
297
+ const isLeadingSegment = targetRange.key === leadingSegment;
298
+ const hasSelection = selectionEnd !== cursor;
299
+ if (hasSelection) {
300
+ const nextDisplay2 = replaceSelection(activeDisplay, cursor, selectionEnd, digit);
301
+ applyDisplayEdit(nextDisplay2, cursor + 1);
302
+ return;
303
+ }
304
+ if (isLeadingSegment && cursor >= targetRange.end) {
305
+ const insertIndex = targetRange.end;
306
+ const nextDisplay2 = replaceSelection(activeDisplay, insertIndex, insertIndex, digit);
307
+ applyDisplayEdit(nextDisplay2, insertIndex + 1);
308
+ return;
309
+ }
310
+ let writeIndex = cursor;
311
+ if (activeDisplay[writeIndex] === ":") writeIndex += 1;
312
+ if (writeIndex >= activeDisplay.length) return;
313
+ const nextDisplay = replaceSelection(activeDisplay, writeIndex, writeIndex + 1, digit);
314
+ const localPos = writeIndex - targetRange.start;
315
+ const segmentLength = targetRange.end - targetRange.start;
316
+ let nextCaret = writeIndex + 1;
317
+ const reachedSegmentEnd = localPos >= segmentLength - 1;
318
+ if (reachedSegmentEnd && !isLeadingSegment) {
319
+ const afterSegment = targetRange.end + 1;
320
+ nextCaret = nextDisplay[afterSegment] === ":" ? afterSegment + 1 : afterSegment;
321
+ }
322
+ if (nextCaret < nextDisplay.length && nextDisplay[nextCaret] === ":") {
323
+ nextCaret += 1;
324
+ }
325
+ applyDisplayEdit(nextDisplay, nextCaret);
326
+ };
327
+ const handleBeforeInput = (event) => {
328
+ const input = inputRef.current;
329
+ if (!input) return;
330
+ const native = event.nativeEvent;
331
+ if (native.isComposing) return;
332
+ const cursor = input.selectionStart ?? 0;
333
+ const selectionEnd = input.selectionEnd ?? cursor;
334
+ if (native.inputType === "insertText") {
335
+ const text = native.data ?? "";
336
+ if (!text) return;
337
+ event.preventDefault();
338
+ if (/^\d$/.test(text)) {
339
+ handleDigitInsertion(text, cursor, selectionEnd);
340
+ }
341
+ return;
342
+ }
343
+ if (native.inputType === "deleteContentBackward") {
344
+ event.preventDefault();
345
+ handleDeleteKey("Backspace", cursor, selectionEnd);
346
+ return;
347
+ }
348
+ if (native.inputType === "deleteContentForward") {
349
+ event.preventDefault();
350
+ handleDeleteKey("Delete", cursor, selectionEnd);
351
+ }
352
+ };
353
+ const handleKeyDown = (event) => {
354
+ const input = inputRef.current;
355
+ if (!input) return;
356
+ if (event.altKey) {
357
+ return;
358
+ }
359
+ if (event.ctrlKey || event.metaKey) {
360
+ if (isEditingShortcut(event)) return;
361
+ if (event.key.length === 1) {
362
+ event.preventDefault();
363
+ }
364
+ return;
365
+ }
366
+ if (NAVIGATION_KEYS.has(event.key)) {
367
+ return;
368
+ }
369
+ const cursor = input.selectionStart ?? 0;
370
+ const selectionEnd = input.selectionEnd ?? cursor;
371
+ if (event.key === "Backspace" || event.key === "Delete") {
372
+ const handled = handleDeleteKey(event.key, cursor, selectionEnd);
373
+ if (handled) event.preventDefault();
374
+ return;
375
+ }
376
+ if (!/^\d$/.test(event.key)) {
377
+ if (event.key.length === 1) event.preventDefault();
378
+ return;
379
+ }
380
+ event.preventDefault();
381
+ handleDigitInsertion(event.key, cursor, selectionEnd);
382
+ };
383
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
384
+ "input",
385
+ {
386
+ ...inputProps,
387
+ ref: inputRef,
388
+ type: "text",
389
+ inputMode,
390
+ value: activeDisplay,
391
+ disabled,
392
+ onFocus: () => {
393
+ setIsEditing(true);
394
+ setDraftDisplay(externalDisplay);
395
+ },
396
+ onBlur: () => {
397
+ const normalized = normalizeRaw(mode, draftDisplay, limits, widths);
398
+ commitNormalized(normalized);
399
+ setIsEditing(false);
400
+ },
401
+ onBeforeInput: handleBeforeInput,
402
+ onKeyDown: handleKeyDown,
403
+ onChange: (event) => {
404
+ applyRaw(event.target.value);
405
+ }
406
+ }
407
+ );
408
+ }
409
+ // Annotate the CommonJS export names for ESM import in node:
410
+ 0 && (module.exports = {
411
+ DurationInput
412
+ });
@@ -0,0 +1,16 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { InputHTMLAttributes } from 'react';
3
+
4
+ type DurationMode = 'ss' | 'mm' | 'hh' | 'mm:ss' | 'hh:mm' | 'hh:mm:ss';
5
+
6
+ type DurationInputProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'value' | 'onChange' | 'type'> & {
7
+ value: number;
8
+ onChange: (seconds: number) => void;
9
+ mode: DurationMode;
10
+ maxHours?: number;
11
+ maxMinutes?: number;
12
+ maxSeconds?: number;
13
+ };
14
+ declare function DurationInput({ value, onChange, mode, maxHours, maxMinutes, maxSeconds, disabled, inputMode, ...inputProps }: DurationInputProps): react_jsx_runtime.JSX.Element;
15
+
16
+ export { DurationInput, type DurationInputProps, type DurationMode };
@@ -0,0 +1,16 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+ import { InputHTMLAttributes } from 'react';
3
+
4
+ type DurationMode = 'ss' | 'mm' | 'hh' | 'mm:ss' | 'hh:mm' | 'hh:mm:ss';
5
+
6
+ type DurationInputProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'value' | 'onChange' | 'type'> & {
7
+ value: number;
8
+ onChange: (seconds: number) => void;
9
+ mode: DurationMode;
10
+ maxHours?: number;
11
+ maxMinutes?: number;
12
+ maxSeconds?: number;
13
+ };
14
+ declare function DurationInput({ value, onChange, mode, maxHours, maxMinutes, maxSeconds, disabled, inputMode, ...inputProps }: DurationInputProps): react_jsx_runtime.JSX.Element;
15
+
16
+ export { DurationInput, type DurationInputProps, type DurationMode };
package/dist/index.js ADDED
@@ -0,0 +1,385 @@
1
+ // src/components/ui/DurationInput.tsx
2
+ import { useEffect, useMemo, useRef, useState } from "react";
3
+
4
+ // src/components/ui/duration-input.utils.ts
5
+ var EMPTY_VALUES = { hh: 0, mm: 0, ss: 0 };
6
+ var NAVIGATION_KEYS = /* @__PURE__ */ new Set(["ArrowLeft", "ArrowRight", "Tab", "Home", "End"]);
7
+ var EDIT_SHORTCUT_KEYS = /* @__PURE__ */ new Set(["a", "c", "v", "x", "z", "y"]);
8
+ function assertNever(value) {
9
+ throw new Error(`Unsupported duration mode: ${String(value)}`);
10
+ }
11
+ function getModeSegments(mode) {
12
+ switch (mode) {
13
+ case "hh:mm:ss":
14
+ return ["hh", "mm", "ss"];
15
+ case "hh:mm":
16
+ return ["hh", "mm"];
17
+ case "mm:ss":
18
+ return ["mm", "ss"];
19
+ case "hh":
20
+ return ["hh"];
21
+ case "mm":
22
+ return ["mm"];
23
+ case "ss":
24
+ return ["ss"];
25
+ default:
26
+ return assertNever(mode);
27
+ }
28
+ }
29
+ function clamp(n, min, max) {
30
+ if (!Number.isFinite(n) || Number.isNaN(n)) return min;
31
+ if (n < min) return min;
32
+ if (max !== void 0 && n > max) return max;
33
+ return n;
34
+ }
35
+ function applyModeValidation(mode, values, limits) {
36
+ const normalized = { ...values };
37
+ if (mode.includes("hh")) {
38
+ normalized.hh = clamp(normalized.hh, 0, limits.maxHours);
39
+ }
40
+ if (mode === "mm" || mode === "mm:ss") {
41
+ normalized.mm = clamp(normalized.mm, 0, limits.maxMinutes);
42
+ } else if (mode.includes("mm")) {
43
+ normalized.mm = clamp(normalized.mm, 0, 59);
44
+ }
45
+ if (mode === "ss") {
46
+ normalized.ss = clamp(normalized.ss, 0, limits.maxSeconds);
47
+ } else if (mode.includes("ss")) {
48
+ normalized.ss = clamp(normalized.ss, 0, 59);
49
+ }
50
+ return normalized;
51
+ }
52
+ function secondsToSegments(mode, totalSeconds, limits) {
53
+ const safeSeconds = Math.max(0, Math.floor(Number.isFinite(totalSeconds) ? totalSeconds : 0));
54
+ const values = {
55
+ hh: Math.floor(safeSeconds / 3600),
56
+ mm: Math.floor(safeSeconds % 3600 / 60),
57
+ ss: safeSeconds % 60
58
+ };
59
+ if (mode === "hh") {
60
+ values.hh = Math.floor(safeSeconds / 3600);
61
+ values.mm = 0;
62
+ values.ss = 0;
63
+ }
64
+ if (mode === "mm") {
65
+ values.hh = 0;
66
+ values.mm = Math.floor(safeSeconds / 60);
67
+ values.ss = 0;
68
+ }
69
+ if (mode === "ss") {
70
+ values.hh = 0;
71
+ values.mm = 0;
72
+ values.ss = safeSeconds;
73
+ }
74
+ if (mode === "mm:ss") {
75
+ values.hh = 0;
76
+ values.mm = Math.floor(safeSeconds / 60);
77
+ values.ss = safeSeconds % 60;
78
+ }
79
+ return applyModeValidation(mode, values, limits);
80
+ }
81
+ function segmentsToSeconds(mode, values) {
82
+ const hh = mode.includes("hh") ? values.hh : 0;
83
+ const mm = mode.includes("mm") ? values.mm : 0;
84
+ const ss = mode.includes("ss") ? values.ss : 0;
85
+ const total = hh * 3600 + mm * 60 + ss;
86
+ return Number.isFinite(total) && !Number.isNaN(total) ? total : 0;
87
+ }
88
+ function getDigitsForLimit(limit) {
89
+ if (limit === void 0 || !Number.isFinite(limit) || Number.isNaN(limit)) return 2;
90
+ return Math.max(2, String(Math.max(0, Math.floor(limit))).length);
91
+ }
92
+ function getSegmentWidths(mode, limits) {
93
+ const widths = { hh: 2, mm: 2, ss: 2 };
94
+ if (mode === "hh" || mode === "hh:mm" || mode === "hh:mm:ss") {
95
+ widths.hh = getDigitsForLimit(limits.maxHours);
96
+ }
97
+ if (mode === "mm" || mode === "mm:ss") {
98
+ widths.mm = getDigitsForLimit(limits.maxMinutes);
99
+ }
100
+ if (mode === "ss") {
101
+ widths.ss = getDigitsForLimit(limits.maxSeconds);
102
+ }
103
+ return widths;
104
+ }
105
+ function getDisplayWidth(value, minWidth) {
106
+ return Math.max(minWidth, String(Math.max(0, value)).length);
107
+ }
108
+ function formatDisplay(mode, values, widths) {
109
+ return getModeSegments(mode).map((key) => String(values[key]).padStart(getDisplayWidth(values[key], widths[key]), "0")).join(":");
110
+ }
111
+ function parseRawInput(raw, mode) {
112
+ const segments = getModeSegments(mode);
113
+ const parsed = { ...EMPTY_VALUES };
114
+ const cleaned = raw.trim();
115
+ if (!cleaned) return parsed;
116
+ if (cleaned.includes(":")) {
117
+ const parts = cleaned.split(":").slice(0, segments.length);
118
+ segments.forEach((segment, index) => {
119
+ const digits2 = (parts[index] ?? "").replace(/\D/g, "");
120
+ parsed[segment] = digits2 ? Number.parseInt(digits2, 10) : 0;
121
+ });
122
+ return parsed;
123
+ }
124
+ const digits = cleaned.replace(/\D/g, "");
125
+ if (!digits) return parsed;
126
+ if (segments.length === 1) {
127
+ parsed[segments[0]] = Number.parseInt(digits, 10);
128
+ return parsed;
129
+ }
130
+ let end = digits.length;
131
+ for (let idx = segments.length - 1; idx >= 0; idx -= 1) {
132
+ const key = segments[idx];
133
+ if (idx === 0) {
134
+ const chunk2 = digits.slice(0, end);
135
+ parsed[key] = chunk2 ? Number.parseInt(chunk2, 10) : 0;
136
+ break;
137
+ }
138
+ const start = Math.max(0, end - 2);
139
+ const chunk = digits.slice(start, end);
140
+ parsed[key] = chunk ? Number.parseInt(chunk, 10) : 0;
141
+ end = start;
142
+ }
143
+ return parsed;
144
+ }
145
+ function normalizeRaw(mode, raw, limits, widths) {
146
+ const parsed = parseRawInput(raw, mode);
147
+ const values = applyModeValidation(mode, parsed, limits);
148
+ return {
149
+ values,
150
+ display: formatDisplay(mode, values, widths),
151
+ seconds: segmentsToSeconds(mode, values)
152
+ };
153
+ }
154
+ function getRanges(display, mode) {
155
+ const keys = getModeSegments(mode);
156
+ const parts = display.split(":");
157
+ let offset = 0;
158
+ return keys.map((key, index) => {
159
+ const part = parts[index] ?? "";
160
+ const start = offset;
161
+ const end = start + part.length;
162
+ offset = end + 1;
163
+ return { key, start, end };
164
+ });
165
+ }
166
+ function findRangeAtPosition(ranges, pos) {
167
+ for (const range of ranges) {
168
+ if (pos >= range.start && pos <= range.end) return range;
169
+ }
170
+ return null;
171
+ }
172
+ function isEditingShortcut(event) {
173
+ if (!(event.ctrlKey || event.metaKey)) return false;
174
+ return EDIT_SHORTCUT_KEYS.has(event.key.toLowerCase());
175
+ }
176
+ function replaceSelection(display, start, end, value) {
177
+ return `${display.slice(0, start)}${value}${display.slice(end)}`;
178
+ }
179
+
180
+ // src/components/ui/DurationInput.tsx
181
+ import { jsx } from "react/jsx-runtime";
182
+ function DurationInput({
183
+ value,
184
+ onChange,
185
+ mode,
186
+ maxHours,
187
+ maxMinutes,
188
+ maxSeconds,
189
+ disabled = false,
190
+ inputMode = "numeric",
191
+ ...inputProps
192
+ }) {
193
+ const inputRef = useRef(null);
194
+ const pendingCaretRef = useRef(null);
195
+ const limits = useMemo(() => ({ maxHours, maxMinutes, maxSeconds }), [maxHours, maxMinutes, maxSeconds]);
196
+ const widths = useMemo(() => getSegmentWidths(mode, limits), [mode, limits]);
197
+ const externalDisplay = useMemo(() => {
198
+ const values = secondsToSegments(mode, value, limits);
199
+ return formatDisplay(mode, values, widths);
200
+ }, [mode, value, limits, widths]);
201
+ const [isEditing, setIsEditing] = useState(false);
202
+ const [draftDisplay, setDraftDisplay] = useState(externalDisplay);
203
+ const activeDisplay = isEditing ? draftDisplay : externalDisplay;
204
+ useEffect(() => {
205
+ if (pendingCaretRef.current === null || !inputRef.current) return;
206
+ const caret = pendingCaretRef.current;
207
+ inputRef.current.setSelectionRange(caret, caret);
208
+ pendingCaretRef.current = null;
209
+ }, [draftDisplay]);
210
+ const commitNormalized = (normalized, nextCaret) => {
211
+ if (nextCaret !== void 0) {
212
+ pendingCaretRef.current = Math.min(nextCaret, normalized.display.length);
213
+ }
214
+ if (normalized.display !== draftDisplay) {
215
+ setDraftDisplay(normalized.display);
216
+ }
217
+ if (normalized.seconds !== value) {
218
+ onChange(normalized.seconds);
219
+ }
220
+ };
221
+ const applyRaw = (raw, nextCaret) => {
222
+ const normalized = normalizeRaw(mode, raw, limits, widths);
223
+ commitNormalized(normalized, nextCaret);
224
+ };
225
+ const moveCaret = (nextCaret) => {
226
+ const input = inputRef.current;
227
+ if (!input) return;
228
+ const boundedCaret = Math.min(nextCaret, activeDisplay.length);
229
+ input.setSelectionRange(boundedCaret, boundedCaret);
230
+ };
231
+ const applyDisplayEdit = (nextDisplay, nextCaret) => {
232
+ const boundedCaret = Math.min(nextCaret, nextDisplay.length);
233
+ if (nextDisplay === activeDisplay) {
234
+ moveCaret(boundedCaret);
235
+ return;
236
+ }
237
+ applyRaw(nextDisplay, boundedCaret);
238
+ };
239
+ const applyDeleteShiftAtEnd = () => {
240
+ const digits = activeDisplay.replace(/\D/g, "");
241
+ const shiftedDigits = digits.slice(0, -1);
242
+ const normalized = normalizeRaw(mode, shiftedDigits, limits, widths);
243
+ commitNormalized(normalized, normalized.display.length);
244
+ };
245
+ const handleDeleteKey = (key, cursor, selectionEnd) => {
246
+ const hasSelection = selectionEnd !== cursor;
247
+ const selectedAll = hasSelection && cursor === 0 && selectionEnd === activeDisplay.length;
248
+ if (selectedAll) {
249
+ applyRaw("", 0);
250
+ return true;
251
+ }
252
+ if (!hasSelection && key === "Backspace" && cursor === activeDisplay.length) {
253
+ applyDeleteShiftAtEnd();
254
+ return true;
255
+ }
256
+ const leftIsColon = key === "Backspace" && cursor > 0 && activeDisplay[cursor - 1] === ":";
257
+ const currentIsColon = activeDisplay[cursor] === ":";
258
+ if (leftIsColon || currentIsColon) {
259
+ const nextCursor = key === "Backspace" ? Math.max(0, cursor - 1) : Math.min(activeDisplay.length, cursor + 1);
260
+ moveCaret(nextCursor);
261
+ return true;
262
+ }
263
+ return false;
264
+ };
265
+ const handleDigitInsertion = (digit, cursor, selectionEnd) => {
266
+ const ranges = getRanges(activeDisplay, mode);
267
+ const targetRange = findRangeAtPosition(ranges, cursor);
268
+ if (!targetRange) return;
269
+ const segments = getModeSegments(mode);
270
+ const leadingSegment = segments[0];
271
+ const isLeadingSegment = targetRange.key === leadingSegment;
272
+ const hasSelection = selectionEnd !== cursor;
273
+ if (hasSelection) {
274
+ const nextDisplay2 = replaceSelection(activeDisplay, cursor, selectionEnd, digit);
275
+ applyDisplayEdit(nextDisplay2, cursor + 1);
276
+ return;
277
+ }
278
+ if (isLeadingSegment && cursor >= targetRange.end) {
279
+ const insertIndex = targetRange.end;
280
+ const nextDisplay2 = replaceSelection(activeDisplay, insertIndex, insertIndex, digit);
281
+ applyDisplayEdit(nextDisplay2, insertIndex + 1);
282
+ return;
283
+ }
284
+ let writeIndex = cursor;
285
+ if (activeDisplay[writeIndex] === ":") writeIndex += 1;
286
+ if (writeIndex >= activeDisplay.length) return;
287
+ const nextDisplay = replaceSelection(activeDisplay, writeIndex, writeIndex + 1, digit);
288
+ const localPos = writeIndex - targetRange.start;
289
+ const segmentLength = targetRange.end - targetRange.start;
290
+ let nextCaret = writeIndex + 1;
291
+ const reachedSegmentEnd = localPos >= segmentLength - 1;
292
+ if (reachedSegmentEnd && !isLeadingSegment) {
293
+ const afterSegment = targetRange.end + 1;
294
+ nextCaret = nextDisplay[afterSegment] === ":" ? afterSegment + 1 : afterSegment;
295
+ }
296
+ if (nextCaret < nextDisplay.length && nextDisplay[nextCaret] === ":") {
297
+ nextCaret += 1;
298
+ }
299
+ applyDisplayEdit(nextDisplay, nextCaret);
300
+ };
301
+ const handleBeforeInput = (event) => {
302
+ const input = inputRef.current;
303
+ if (!input) return;
304
+ const native = event.nativeEvent;
305
+ if (native.isComposing) return;
306
+ const cursor = input.selectionStart ?? 0;
307
+ const selectionEnd = input.selectionEnd ?? cursor;
308
+ if (native.inputType === "insertText") {
309
+ const text = native.data ?? "";
310
+ if (!text) return;
311
+ event.preventDefault();
312
+ if (/^\d$/.test(text)) {
313
+ handleDigitInsertion(text, cursor, selectionEnd);
314
+ }
315
+ return;
316
+ }
317
+ if (native.inputType === "deleteContentBackward") {
318
+ event.preventDefault();
319
+ handleDeleteKey("Backspace", cursor, selectionEnd);
320
+ return;
321
+ }
322
+ if (native.inputType === "deleteContentForward") {
323
+ event.preventDefault();
324
+ handleDeleteKey("Delete", cursor, selectionEnd);
325
+ }
326
+ };
327
+ const handleKeyDown = (event) => {
328
+ const input = inputRef.current;
329
+ if (!input) return;
330
+ if (event.altKey) {
331
+ return;
332
+ }
333
+ if (event.ctrlKey || event.metaKey) {
334
+ if (isEditingShortcut(event)) return;
335
+ if (event.key.length === 1) {
336
+ event.preventDefault();
337
+ }
338
+ return;
339
+ }
340
+ if (NAVIGATION_KEYS.has(event.key)) {
341
+ return;
342
+ }
343
+ const cursor = input.selectionStart ?? 0;
344
+ const selectionEnd = input.selectionEnd ?? cursor;
345
+ if (event.key === "Backspace" || event.key === "Delete") {
346
+ const handled = handleDeleteKey(event.key, cursor, selectionEnd);
347
+ if (handled) event.preventDefault();
348
+ return;
349
+ }
350
+ if (!/^\d$/.test(event.key)) {
351
+ if (event.key.length === 1) event.preventDefault();
352
+ return;
353
+ }
354
+ event.preventDefault();
355
+ handleDigitInsertion(event.key, cursor, selectionEnd);
356
+ };
357
+ return /* @__PURE__ */ jsx(
358
+ "input",
359
+ {
360
+ ...inputProps,
361
+ ref: inputRef,
362
+ type: "text",
363
+ inputMode,
364
+ value: activeDisplay,
365
+ disabled,
366
+ onFocus: () => {
367
+ setIsEditing(true);
368
+ setDraftDisplay(externalDisplay);
369
+ },
370
+ onBlur: () => {
371
+ const normalized = normalizeRaw(mode, draftDisplay, limits, widths);
372
+ commitNormalized(normalized);
373
+ setIsEditing(false);
374
+ },
375
+ onBeforeInput: handleBeforeInput,
376
+ onKeyDown: handleKeyDown,
377
+ onChange: (event) => {
378
+ applyRaw(event.target.value);
379
+ }
380
+ }
381
+ );
382
+ }
383
+ export {
384
+ DurationInput
385
+ };
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "duration-input-react",
3
+ "version": "0.1.0",
4
+ "description": "Controlled React input for duration intervals",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/index.js",
14
+ "require": "./dist/index.cjs"
15
+ }
16
+ },
17
+ "files": [
18
+ "dist",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "sideEffects": false,
23
+ "keywords": [
24
+ "react",
25
+ "duration",
26
+ "time",
27
+ "input",
28
+ "typescript"
29
+ ],
30
+ "engines": {
31
+ "node": ">=18"
32
+ },
33
+ "scripts": {
34
+ "clean": "rimraf dist",
35
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
36
+ "typecheck": "tsc --noEmit",
37
+ "prepublishOnly": "npm run build"
38
+ },
39
+ "peerDependencies": {
40
+ "react": ">=18"
41
+ },
42
+ "devDependencies": {
43
+ "@types/react": "^18.3.12",
44
+ "rimraf": "^6.1.1",
45
+ "tsup": "^8.3.5",
46
+ "typescript": "^5.6.3"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }