(
inputEl: HTMLInputElement,
options: DateInputBehaviorOptions = {}
)
| 68 | } |
| 69 | |
| 70 | export function attachDateInputBehavior( |
| 71 | inputEl: HTMLInputElement, |
| 72 | options: DateInputBehaviorOptions = {} |
| 73 | ): () => void { |
| 74 | let digitBuffer = ""; |
| 75 | let lastDigitAt = 0; |
| 76 | const now = options.now ?? (() => Date.now()); |
| 77 | const resetMs = options.typeBufferResetMs ?? DEFAULT_TYPE_BUFFER_RESET_MS; |
| 78 | |
| 79 | const handleKeydown = (event: KeyboardEvent) => { |
| 80 | if (!isPlainDigitKey(event)) return; |
| 81 | |
| 82 | const eventTime = now(); |
| 83 | if (eventTime - lastDigitAt > resetMs) { |
| 84 | digitBuffer = ""; |
| 85 | } |
| 86 | |
| 87 | lastDigitAt = eventTime; |
| 88 | digitBuffer = `${digitBuffer}${event.key}`.slice(-8); |
| 89 | |
| 90 | const normalized = normalizeDateEntryValue(digitBuffer); |
| 91 | if (!normalized) return; |
| 92 | |
| 93 | event.preventDefault(); |
| 94 | digitBuffer = ""; |
| 95 | commitDateInputValue(inputEl, normalized, options); |
| 96 | }; |
| 97 | |
| 98 | const handlePaste = (event: ClipboardEvent) => { |
| 99 | const pastedText = event.clipboardData?.getData("text") ?? ""; |
| 100 | const normalized = normalizeDateEntryValue(pastedText); |
| 101 | if (!normalized) return; |
| 102 | |
| 103 | event.preventDefault(); |
| 104 | digitBuffer = ""; |
| 105 | commitDateInputValue(inputEl, normalized, options); |
| 106 | }; |
| 107 | |
| 108 | const handleInput = () => { |
| 109 | const normalized = normalizeDateEntryValue(inputEl.value); |
| 110 | if (!normalized || normalized === inputEl.value) return; |
| 111 | |
| 112 | digitBuffer = ""; |
| 113 | commitDateInputValue(inputEl, normalized, options); |
| 114 | }; |
| 115 | |
| 116 | inputEl.addEventListener("keydown", handleKeydown); |
| 117 | inputEl.addEventListener("paste", handlePaste); |
| 118 | inputEl.addEventListener("input", handleInput); |
| 119 | |
| 120 | return () => { |
| 121 | inputEl.removeEventListener("keydown", handleKeydown); |
| 122 | inputEl.removeEventListener("paste", handlePaste); |
| 123 | inputEl.removeEventListener("input", handleInput); |
| 124 | }; |
| 125 | } |
no test coverage detected