digitojs 1.2.2 → 1.2.4

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/src/cdn.ts DELETED
@@ -1,24 +0,0 @@
1
- /**
2
- * CDN entry point for Digito.
3
- *
4
- * Exposes all public browser-facing APIs as a single window.Digito global.
5
- * This file is the entrypoint for dist/digito.min.js only — it is not
6
- * part of the npm package exports.
7
- *
8
- * Usage after loading the CDN script:
9
- * const { initDigito, createDigito, filterChar, filterString, createTimer } = window.Digito
10
- */
11
-
12
- // Vanilla adapter
13
- export { initDigito } from './adapters/vanilla'
14
-
15
- // Core state machine + utilities
16
- export {
17
- createDigito,
18
- createTimer,
19
- formatCountdown,
20
- filterChar,
21
- filterString,
22
- triggerHapticFeedback,
23
- triggerSoundFeedback,
24
- } from './core'
@@ -1,44 +0,0 @@
1
- /**
2
- * digito/core/feedback
3
- * ─────────────────────────────────────────────────────────────────────────────
4
- * Optional sensory feedback utilities — exported so consumers can call them
5
- * in their own event handlers without reimplementing the Web Audio / vibration
6
- * boilerplate ("bring your own feedback" pattern).
7
- *
8
- * Used internally by the core machine when `haptic` / `sound` options are set.
9
- *
10
- * @author Olawale Balo — Product Designer + Design Engineer
11
- * @license MIT
12
- */
13
-
14
- /**
15
- * Trigger a short haptic pulse via `navigator.vibrate`.
16
- * Silently no-ops in environments that don't support the Vibration API
17
- * (e.g. desktop browsers, Safari, Node.js).
18
- */
19
- export function triggerHapticFeedback(): void {
20
- try { navigator?.vibrate?.(10) } catch { /* not supported — fail silently */ }
21
- }
22
-
23
- /**
24
- * Play a brief 880 Hz tone via the Web Audio API.
25
- * The AudioContext is closed immediately after the tone ends to prevent
26
- * Chrome's ~6-concurrent-context limit from being reached across calls.
27
- * Silently no-ops where Web Audio is unavailable.
28
- */
29
- export function triggerSoundFeedback(): void {
30
- try {
31
- const audioCtx = new AudioContext()
32
- const oscillator = audioCtx.createOscillator()
33
- const gainNode = audioCtx.createGain()
34
- oscillator.connect(gainNode)
35
- gainNode.connect(audioCtx.destination)
36
- oscillator.frequency.value = 880
37
- gainNode.gain.setValueAtTime(0.08, audioCtx.currentTime)
38
- gainNode.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + 0.08)
39
- oscillator.start()
40
- oscillator.stop(audioCtx.currentTime + 0.08)
41
- // Close the context after the tone ends — prevents AudioContext instance leak
42
- oscillator.onended = () => { audioCtx.close().catch(() => { /* ignore */ }) }
43
- } catch { /* Web Audio not available — fail silently */ }
44
- }
@@ -1,48 +0,0 @@
1
- /**
2
- * digito/core/filter
3
- * ─────────────────────────────────────────────────────────────────────────────
4
- * Character filtering utilities — exported for use by all adapters.
5
- *
6
- * @author Olawale Balo — Product Designer + Design Engineer
7
- * @license MIT
8
- */
9
-
10
- import type { InputType } from './types.js'
11
-
12
- /**
13
- * Returns `char` if it is valid for `type` (and optional `pattern`), otherwise `''`.
14
- * Single character input only — multi-char strings always return `''`.
15
- *
16
- * When `pattern` is provided it takes precedence over `type` for validation.
17
- */
18
- export function filterChar(char: string, type: InputType, pattern?: RegExp): string {
19
- if (!char || char.length !== 1) return ''
20
- if (pattern !== undefined) {
21
- // A pattern with the /g flag has stateful lastIndex. Reset it before every
22
- // test so the same pattern can be reused safely across multiple characters
23
- // without alternating between matches.
24
- if (pattern.global) pattern.lastIndex = 0
25
- return pattern.test(char) ? char : ''
26
- }
27
- switch (type) {
28
- case 'numeric': return /^[0-9]$/.test(char) ? char : ''
29
- case 'alphabet': return /^[a-zA-Z]$/.test(char) ? char : ''
30
- case 'alphanumeric': return /^[a-zA-Z0-9]$/.test(char) ? char : ''
31
- case 'any': return char
32
- default: return ''
33
- }
34
- }
35
-
36
- /**
37
- * Filters every character in `str` using `filterChar`.
38
- * Used to sanitize pasted strings and controlled-value inputs before distribution.
39
- *
40
- * When `pattern` is provided it takes precedence over `type` for each character.
41
- */
42
- export function filterString(str: string, type: InputType, pattern?: RegExp): string {
43
- // Array.from iterates over Unicode code points, not UTF-16 code units.
44
- // str.split('') would split emoji and other supplementary-plane characters
45
- // into surrogate pairs (two strings of length 1 each), causing filterChar
46
- // to accept broken half-surrogates into slots for type:'any'.
47
- return Array.from(str).filter(c => filterChar(c, type, pattern) !== '').join('')
48
- }
package/src/core/index.ts DELETED
@@ -1,16 +0,0 @@
1
- /**
2
- * digito/core
3
- * ─────────────────────────────────────────────────────────────────────────────
4
- * Pure OTP state machine — zero DOM, zero framework, zero side effects.
5
- * All adapters (vanilla, React, Vue, Svelte, Alpine, Web Components) import
6
- * from here. Nothing else is shared between them.
7
- *
8
- * @author Olawale Balo — Product Designer + Design Engineer
9
- * @license MIT
10
- */
11
-
12
- export type { InputType, DigitoState, DigitoOptions, TimerOptions, TimerControls, StateListener } from './types.js'
13
- export { filterChar, filterString } from './filter.js'
14
- export { createTimer, formatCountdown } from './timer.js'
15
- export { triggerHapticFeedback, triggerSoundFeedback } from './feedback.js'
16
- export { createDigito } from './machine.js'
@@ -1,405 +0,0 @@
1
- /**
2
- * digito/core/machine
3
- * ─────────────────────────────────────────────────────────────────────────────
4
- * Pure OTP state machine — zero DOM, zero framework, zero side effects.
5
- * All adapters import `createDigito` from here (via core/index.ts).
6
- *
7
- * Subscription system: pass a listener to `subscribe()` to be notified after
8
- * every state mutation. Compatible with XState / Zustand-style patterns:
9
- *
10
- * const otp = createDigito({ length: 6 })
11
- * const unsub = otp.subscribe(state => console.log(state))
12
- * // ... later:
13
- * unsub()
14
- *
15
- * @author Olawale Balo — Product Designer + Design Engineer
16
- * @license MIT
17
- */
18
-
19
- import type { DigitoOptions, DigitoState, StateListener, InputType } from './types.js'
20
- import { filterChar, filterString } from './filter.js'
21
- import { triggerHapticFeedback, triggerSoundFeedback } from './feedback.js'
22
-
23
-
24
- // ─────────────────────────────────────────────────────────────────────────────
25
- // INTERNAL HELPERS
26
- // ─────────────────────────────────────────────────────────────────────────────
27
-
28
- /** Returns `true` when every slot contains exactly one character. */
29
- function allSlotsFilled(slotValues: string[]): boolean {
30
- return slotValues.every(v => v.length === 1)
31
- }
32
-
33
- /** Clamp `index` to the inclusive range `[min, max]`. */
34
- function clampIndex(index: number, min: number, max: number): number {
35
- return Math.max(min, Math.min(max, index))
36
- }
37
-
38
- /** Join all slot values into a single string (the OTP code). */
39
- function joinSlots(slotValues: string[]): string {
40
- return slotValues.join('')
41
- }
42
-
43
-
44
- // ─────────────────────────────────────────────────────────────────────────────
45
- // FACTORY
46
- // ─────────────────────────────────────────────────────────────────────────────
47
-
48
- /**
49
- * Creates a pure OTP state machine.
50
- * Returns action functions, a `state` getter, a `subscribe` method, and a
51
- * `getState` snapshot helper — no DOM, no side effects.
52
- */
53
- export function createDigito(options: DigitoOptions = {}) {
54
- // Security: guard against invalid length values.
55
- // Negative numbers would throw a RangeError from Array(); zero would produce
56
- // a permanently-incomplete input with no slots. Clamp to a safe minimum of 1.
57
- const rawLength = options.length ?? 6
58
- // Guard against NaN (e.g. parseInt('', 10) from a missing data-attribute).
59
- // NaN would propagate through Math.floor and crash Array() with RangeError.
60
- const length = isNaN(rawLength) ? 6 : Math.max(1, Math.floor(rawLength))
61
-
62
- const {
63
- type = 'numeric' as InputType,
64
- pattern,
65
- onComplete,
66
- onInvalidChar,
67
- haptic = true,
68
- sound = false,
69
- pasteTransformer,
70
- } = options
71
-
72
- // `disabled` is mutable so setDisabled() can toggle it at runtime without
73
- // requiring the instance to be recreated. Adapters that pass disabled at
74
- // construction time still work — the initial value is honoured.
75
- let disabled = options.disabled ?? false
76
- // `readOnly` allows focus/navigation while blocking all slot mutations.
77
- let readOnly = options.readOnly ?? false
78
-
79
- let state: DigitoState = {
80
- slotValues: Array(length).fill('') as string[],
81
- activeSlot: 0,
82
- hasError: false,
83
- isComplete: false,
84
- timerSeconds: options.timer ?? 0,
85
- isDisabled: options.disabled ?? false,
86
- isReadOnly: options.readOnly ?? false,
87
- }
88
-
89
- // ── Subscription set ──────────────────────────────────────────────────────
90
- const listeners = new Set<StateListener>()
91
-
92
- function applyState(patch: Partial<DigitoState>): DigitoState {
93
- state = { ...state, ...patch }
94
- // Notify all subscribers with a deep copy of slotValues so they cannot
95
- // mutate the live array. A simple { ...state } is a shallow copy — the
96
- // slotValues array reference would be shared, letting a subscriber silently
97
- // corrupt internal state.
98
- if (listeners.size > 0) {
99
- const snapshot = { ...state, slotValues: [...state.slotValues] }
100
- listeners.forEach(fn => fn(snapshot))
101
- }
102
- return state
103
- }
104
-
105
- /**
106
- * Handle for the pending onComplete timeout.
107
- * Stored so resetState() can cancel it if the user clears the input
108
- * within the 10ms defer window (e.g. rapid type-then-delete).
109
- */
110
- let completeTimeoutId: ReturnType<typeof setTimeout> | null = null
111
-
112
- /** Fire onComplete after a short delay so DOM sync can finish first. */
113
- function notifyCompleteIfReady(slotValues: string[]): void {
114
- if (!allSlotsFilled(slotValues) || !onComplete) return
115
- if (haptic) triggerHapticFeedback()
116
- if (sound) triggerSoundFeedback()
117
- const code = joinSlots(slotValues)
118
- if (completeTimeoutId !== null) clearTimeout(completeTimeoutId)
119
- completeTimeoutId = setTimeout(() => {
120
- completeTimeoutId = null
121
- onComplete(code)
122
- }, 10)
123
- }
124
-
125
- /**
126
- * Cancel any pending onComplete callback without clearing slot state.
127
- * Use this after a programmatic fill (e.g. controlled-value sync in adapters)
128
- * to prevent a parent-driven pre-fill from triggering onComplete as if the
129
- * user had typed the code.
130
- */
131
- function cancelPendingComplete(): void {
132
- if (completeTimeoutId !== null) {
133
- clearTimeout(completeTimeoutId)
134
- completeTimeoutId = null
135
- }
136
- }
137
-
138
-
139
- // ── Actions ────────────────────────────────────────────────────────────────
140
-
141
- /**
142
- * Process a single character typed into `slotIndex`.
143
- * Invalid characters leave the slot unchanged and keep focus in place.
144
- * Out-of-bounds indices are silently ignored to prevent sparse-array corruption.
145
- */
146
- function inputChar(slotIndex: number, char: string): DigitoState {
147
- if (disabled || readOnly) return state
148
- if (slotIndex < 0 || slotIndex >= length) return state
149
- const validChar = filterChar(char, type, pattern)
150
- if (!validChar) {
151
- // Fire onInvalidChar for single rejected characters (not empty/multi-char)
152
- if (char.length === 1) onInvalidChar?.(char, slotIndex)
153
- // Only notify subscribers if focus actually needs to move. Firing applyState
154
- // when activeSlot is already slotIndex causes a spurious state notification
155
- // on every invalid keystroke, which can trigger expensive re-renders.
156
- if (state.activeSlot !== slotIndex) {
157
- return applyState({ activeSlot: slotIndex })
158
- }
159
- return state
160
- }
161
-
162
- const slotValues = [...state.slotValues]
163
- slotValues[slotIndex] = validChar
164
-
165
- const nextSlot = slotIndex < length - 1 ? slotIndex + 1 : length - 1
166
-
167
- const newState = applyState({
168
- slotValues,
169
- activeSlot: nextSlot,
170
- hasError: false,
171
- isComplete: allSlotsFilled(slotValues),
172
- })
173
-
174
- notifyCompleteIfReady(slotValues)
175
- return newState
176
- }
177
-
178
- /**
179
- * Handle backspace at `slotIndex`.
180
- * Clears the current slot if filled, otherwise clears the previous slot and moves back.
181
- */
182
- function deleteChar(slotIndex: number): DigitoState {
183
- if (disabled || readOnly) return state
184
- if (slotIndex < 0 || slotIndex >= length) return state
185
- const slotValues = [...state.slotValues]
186
-
187
- if (slotValues[slotIndex]) {
188
- slotValues[slotIndex] = ''
189
- return applyState({ slotValues, activeSlot: slotIndex, isComplete: false })
190
- }
191
-
192
- const prevSlot = clampIndex(slotIndex - 1, 0, length - 1)
193
- slotValues[prevSlot] = ''
194
- return applyState({ slotValues, activeSlot: prevSlot, isComplete: false })
195
- }
196
-
197
- /** Move focus one slot to the left, clamped to slot 0. */
198
- function moveFocusLeft(slotIndex: number): DigitoState {
199
- return applyState({ activeSlot: clampIndex(slotIndex - 1, 0, length - 1) })
200
- }
201
-
202
- /** Move focus one slot to the right, clamped to the last slot. */
203
- function moveFocusRight(slotIndex: number): DigitoState {
204
- return applyState({ activeSlot: clampIndex(slotIndex + 1, 0, length - 1) })
205
- }
206
-
207
- /**
208
- * Smart paste — distributes valid characters from `cursorSlot` forward,
209
- * wrapping around to slot 0 if the string is longer than the remaining slots.
210
- *
211
- * Examples (length = 6, type = numeric):
212
- * paste(0, '123456') → fills all slots
213
- * paste(5, '847291') → slot5='8', slot0='4', slot1='7', slot2='2', slot3='9', slot4='1'
214
- * paste(0, '84AB91') → filtered='8491', fills slots 0–3, slots 4–5 unchanged
215
- */
216
- function pasteString(cursorSlot: number, rawText: string): DigitoState {
217
- if (disabled || readOnly) return state
218
-
219
- let transformed: string
220
- try {
221
- transformed = pasteTransformer ? pasteTransformer(rawText) : rawText
222
- } catch (err) {
223
- console.warn('[digito] pasteTransformer threw — using raw paste text.', err)
224
- transformed = rawText
225
- }
226
-
227
- // Report each rejected character so adapters can provide inline feedback.
228
- // Tracks the effective write cursor so the reported slot index matches where
229
- // the character would have landed if it had been valid.
230
- if (onInvalidChar && transformed) {
231
- let slotCursor = cursorSlot
232
- for (const char of Array.from(transformed)) {
233
- if (filterChar(char, type, pattern)) {
234
- slotCursor = (slotCursor + 1) % length
235
- } else {
236
- onInvalidChar(char, slotCursor)
237
- }
238
- }
239
- }
240
-
241
- const validChars = filterString(transformed, type, pattern)
242
- if (!validChars) return state
243
-
244
- const slotValues = [...state.slotValues]
245
- let writeSlot = cursorSlot
246
-
247
- for (let i = 0; i < validChars.length && i < length; i++) {
248
- slotValues[writeSlot] = validChars[i]
249
- writeSlot = (writeSlot + 1) % length
250
- }
251
-
252
- const charsWritten = Math.min(validChars.length, length)
253
- const nextActiveSlot = charsWritten >= length
254
- ? length - 1
255
- : (cursorSlot + charsWritten) % length
256
-
257
- const newState = applyState({
258
- slotValues,
259
- activeSlot: nextActiveSlot,
260
- hasError: false,
261
- isComplete: allSlotsFilled(slotValues),
262
- })
263
-
264
- notifyCompleteIfReady(slotValues)
265
- return newState
266
- }
267
-
268
- /**
269
- * Clear the slot at slotIndex without moving focus.
270
- * Used by the Delete key — differs from deleteChar (backspace) which steps the cursor back.
271
- * Returns early when the slot is already empty, the field is disabled, or readOnly.
272
- */
273
- function clearSlot(slotIndex: number): DigitoState {
274
- if (disabled || readOnly) return state
275
- if (slotIndex < 0 || slotIndex >= length) return state
276
- if (!state.slotValues[slotIndex]) return state
277
- const slotValues = [...state.slotValues]
278
- slotValues[slotIndex] = ''
279
- return applyState({ slotValues, activeSlot: slotIndex, isComplete: false })
280
- }
281
-
282
- /** Set or clear the error state. Triggers haptic feedback when setting. */
283
- function setError(isError: boolean): DigitoState {
284
- if (isError && haptic) triggerHapticFeedback()
285
- return applyState({ hasError: isError })
286
- }
287
-
288
- /** Clear all slots and reset to initial state. Cancels any pending onComplete callback. */
289
- function resetState(): DigitoState {
290
- if (completeTimeoutId !== null) {
291
- clearTimeout(completeTimeoutId)
292
- completeTimeoutId = null
293
- }
294
- return applyState({
295
- slotValues: Array(length).fill('') as string[],
296
- activeSlot: 0,
297
- hasError: false,
298
- isComplete: false,
299
- timerSeconds: options.timer ?? 0,
300
- })
301
- }
302
-
303
- /** Move focus to a specific slot index. */
304
- function moveFocusTo(slotIndex: number): DigitoState {
305
- return applyState({ activeSlot: clampIndex(slotIndex, 0, length - 1) })
306
- }
307
-
308
- /**
309
- * Reactively enable or disable the input.
310
- * When `true`, inputChar / deleteChar / pasteString are silently ignored.
311
- * Navigation (moveFocusLeft/Right/To) is always allowed regardless of state.
312
- *
313
- * Prefer this over passing `disabled` at construction time whenever you need
314
- * to toggle disabled at runtime (e.g. during async verification).
315
- */
316
- function setDisabled(value: boolean): void {
317
- disabled = value
318
- applyState({ isDisabled: value })
319
- }
320
-
321
- /**
322
- * Toggle readOnly at runtime. When `true`, all slot mutations are blocked
323
- * but navigation and focus remain fully functional.
324
- */
325
- function setReadOnly(value: boolean): void {
326
- readOnly = value
327
- applyState({ isReadOnly: value })
328
- }
329
-
330
- /**
331
- * Subscribe to state changes. The listener is called after every mutation
332
- * with a shallow copy of the new state.
333
- *
334
- * @returns An unsubscribe function — call it to stop receiving updates.
335
- *
336
- * @example
337
- * ```ts
338
- * const otp = createDigito({ length: 6 })
339
- * const unsub = otp.subscribe(state => console.log(state.slotValues))
340
- * // Later:
341
- * unsub()
342
- * ```
343
- */
344
- function subscribe(listener: StateListener): () => void {
345
- listeners.add(listener)
346
- return () => { listeners.delete(listener) }
347
- }
348
-
349
- return {
350
- /** Current state snapshot. */
351
- get state() { return state },
352
-
353
- // Input actions
354
- inputChar,
355
- deleteChar,
356
- clearSlot,
357
- moveFocusLeft,
358
- moveFocusRight,
359
- pasteString,
360
-
361
- // State control
362
- setError,
363
- resetState,
364
- moveFocusTo,
365
-
366
- /**
367
- * Cancel any pending onComplete callback without resetting slot state.
368
- * Intended for adapter-layer controlled-value syncs where a programmatic
369
- * fill should not be treated as a user completing the code.
370
- */
371
- cancelPendingComplete,
372
-
373
- /**
374
- * Toggle the disabled state at runtime.
375
- * Affects inputChar, deleteChar, and pasteString only.
376
- * Navigation actions are always allowed.
377
- */
378
- setDisabled,
379
-
380
- /** Toggle readOnly at runtime. Blocks mutations, preserves navigation. */
381
- setReadOnly,
382
-
383
- /** Returns the current joined code string. */
384
- getCode: () => joinSlots(state.slotValues),
385
- /**
386
- * Returns a copy of the current state with a cloned slotValues array.
387
- * Mutations to the returned object (including its slotValues array) will
388
- * not affect live state.
389
- */
390
- getSnapshot: (): DigitoState => ({ ...state, slotValues: [...state.slotValues] }),
391
-
392
- /**
393
- * Subscribe to state changes. Returns an unsubscribe function.
394
- * Compatible with XState / Zustand-style patterns.
395
- */
396
- subscribe,
397
-
398
- /**
399
- * Returns a copy of the current state with a cloned slotValues array.
400
- * Equivalent to `digito.getSnapshot()` — provided for ergonomic parity
401
- * with state-management libraries that expose a `getState()` method.
402
- */
403
- getState: (): DigitoState => ({ ...state, slotValues: [...state.slotValues] }),
404
- }
405
- }
package/src/core/timer.ts DELETED
@@ -1,90 +0,0 @@
1
- /**
2
- * digito/core/timer
3
- * ─────────────────────────────────────────────────────────────────────────────
4
- * Standalone countdown timer — re-exported from core for use by adapters and
5
- * developers who want to drive their own timer UI.
6
- *
7
- * @author Olawale Balo — Product Designer + Design Engineer
8
- * @license MIT
9
- */
10
-
11
- import type { TimerOptions, TimerControls } from './types.js'
12
-
13
- /**
14
- * Create a 1-second countdown timer.
15
- *
16
- * Lifecycle notes:
17
- * - `start()` is idempotent — it stops any running interval before starting a
18
- * new one, so calling it twice never produces double-ticking.
19
- * - If `totalSeconds <= 0`, `onExpire` fires synchronously on `start()` and no
20
- * interval is created (avoids decrementing to -1 and passing invalid values).
21
- * - `reset()` stops and restores remaining seconds without restarting.
22
- * - `restart()` is shorthand for `reset()` followed immediately by `start()`.
23
- * Used by the vanilla adapter's "Resend" button to reset the countdown.
24
- */
25
- export function createTimer(options: TimerOptions): TimerControls {
26
- const { totalSeconds, onTick, onExpire } = options
27
-
28
- let remainingSeconds = totalSeconds
29
- let intervalId: ReturnType<typeof setInterval> | null = null
30
-
31
- /** Stop the running interval. No-op if already stopped. */
32
- function stop(): void {
33
- if (intervalId !== null) {
34
- clearInterval(intervalId)
35
- intervalId = null
36
- }
37
- }
38
-
39
- /** Stop the interval and restore `remainingSeconds` to `totalSeconds`. Does not restart. */
40
- function reset(): void {
41
- stop()
42
- remainingSeconds = totalSeconds
43
- }
44
-
45
- /**
46
- * Start ticking. Stops any existing interval first to prevent double-ticking.
47
- * If `totalSeconds <= 0`, fires `onExpire` immediately without creating an interval.
48
- */
49
- function start(): void {
50
- stop()
51
- // Guard: if totalSeconds is zero or negative, fire onExpire immediately
52
- // without starting an interval. Without this, the first tick would decrement
53
- // to -1 and pass an invalid value to onTick before calling onExpire.
54
- if (totalSeconds <= 0) {
55
- onExpire?.()
56
- return
57
- }
58
- intervalId = setInterval(() => {
59
- remainingSeconds -= 1
60
- onTick?.(remainingSeconds)
61
- if (remainingSeconds <= 0) {
62
- stop()
63
- onExpire?.()
64
- }
65
- }, 1000)
66
- }
67
-
68
- /** Reset to `totalSeconds` and immediately start ticking. */
69
- function restart(): void {
70
- reset()
71
- start()
72
- }
73
-
74
- return { start, stop, reset, restart }
75
- }
76
-
77
- /**
78
- * Format a second count as a `m:ss` countdown string (e.g. `"1:05"`, `"0:30"`).
79
- * Used by the vanilla, alpine, and web-component adapters for their built-in timer UI.
80
- *
81
- * @example formatCountdown(65) → "1:05"
82
- * @example formatCountdown(9) → "0:09"
83
- */
84
- export function formatCountdown(totalSeconds: number): string {
85
- const minutes = Math.floor(totalSeconds / 60)
86
- const seconds = totalSeconds % 60
87
- return minutes > 0
88
- ? `${minutes}:${String(seconds).padStart(2, '0')}`
89
- : `0:${String(seconds).padStart(2, '0')}`
90
- }