Skip to content

armgit / umami

Public Imported from GitHub
0

Umami is a privacy-first web and product analytics platform. Traffic, campaigns, behavior, conversions, and revenue in one place. No cookies, no surveillance, self-hosted or in the cloud.

2.9 KB
Raw Blame
'use client';
import { Row, TextField } from '@umami/react-zen';
import { type ClipboardEvent, type KeyboardEvent, useRef } from 'react';

interface OtpInputProps {
  value: string;
  onChange: (value: string) => void;
  onComplete?: (value: string) => void;
  disabled?: boolean;
}

const LENGTH = 6;

const focusInput = (el: HTMLDivElement | null) => el?.querySelector('input')?.focus();

export function OtpInput({ value, onChange, onComplete, disabled }: OtpInputProps) {
  const digits = Array.from({ length: LENGTH }, (_, i) => value?.[i] ?? '');
  const refs = useRef<(HTMLDivElement | null)[]>([]);

  const update = (index: number, char: string) => {
    const next = digits.slice();
    next[index] = char;
    const newVal = next.join('');
    onChange(newVal);
    if (newVal.length === LENGTH) {
      onComplete?.(newVal);
    }
  };

  const applyPastedValue = (digitsStr: string) => {
    const pasted = digitsStr.replace(/\D/g, '').slice(0, LENGTH);
    const next = Array.from({ length: LENGTH }, (_, i) => pasted[i] ?? '');
    const newVal = next.join('');
    onChange(newVal);
    if (newVal.length === LENGTH) {
      onComplete?.(newVal);
      focusInput(refs.current[LENGTH - 1]);
    } else {
      focusInput(refs.current[pasted.length]);
    }
  };

  const handleInput = (index: number, raw: string) => {
    const digitsOnly = raw.replace(/\D/g, '');

    if (digitsOnly.length > 1) {
      applyPastedValue(digitsOnly);
      return;
    }

    const char = digitsOnly;
    if (!char) return;
    update(index, char);
    if (index < LENGTH - 1) {
      focusInput(refs.current[index + 1]);
    }
  };

  const handleKeyDown = (
    index: number,
    e: KeyboardEvent<HTMLInputElement & HTMLTextAreaElement>,
  ) => {
    if (e.key === 'Backspace') {
      if (digits[index]) {
        update(index, '');
      } else if (index > 0) {
        update(index - 1, '');
        focusInput(refs.current[index - 1]);
      }
    } else if (e.key === 'ArrowLeft' && index > 0) {
      focusInput(refs.current[index - 1]);
    } else if (e.key === 'ArrowRight' && index < LENGTH - 1) {
      focusInput(refs.current[index + 1]);
    }
  };

  const handlePaste = (e: ClipboardEvent<HTMLInputElement & HTMLTextAreaElement>) => {
    e.preventDefault();
    applyPastedValue(e.clipboardData.getData('text'));
  };

  return (
    <Row gap="2">
      {digits.map((digit, i) => (
        <div
          key={i}
          ref={el => {
            refs.current[i] = el;
          }}
        >
          <TextField
            value={digit}
            onChange={char => handleInput(i, char)}
            onKeyDown={e => handleKeyDown(i, e)}
            onPaste={handlePaste}
            isDisabled={disabled}
            inputMode="numeric"
            maxLength={1}
            autoComplete="one-time-code"
            aria-label={`Digit ${i + 1}`}
            placeholder="0"
            style={{ width: 32 }}
          />
        </div>
      ))}
    </Row>
  );
}