# Input OTP

Input kode sekali pakai yang dipecah menjadi kotak satu digit, dengan maju otomatis, dukungan tempel, dan satu input tersembunyi untuk submit form.

- Kategori: Form
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/input-otp.json
- CLI: `npx markasui@latest add input-otp`

## Kapan dipakai

Kode verifikasi lewat SMS atau email, autentikasi dua faktor, dan PIN angka pendek.

- Isi name agar kode gabungan ikut terkirim bersama form
- Pakai onComplete atau markas-complete untuk submit otomatis saat kode lengkap
- Terjemahkan digitLabel bersama label untuk situs berbahasa selain Inggris

## Kode

### Blade

Simpan di `resources/views/components/markas/input-otp.blade.php`. Dependensi: alpinejs.

```blade
@props([
    'length' => 6,
    'label' => null,
    'name' => null,
    'value' => '',
    'digitLabel' => 'Digit {index} of {length}',
])

@php
    // wire:model.live without its own timing gets the 150 ms debounce Livewire gives text inputs, so a burst of changes sends one request, not one per change.
    $liveModel = fn (string $key) => preg_match('/^wire:model(\.[\w-]+)*\.live(\.|$)/', $key) && ! preg_match('/\.(debounce|throttle|blur|change|lazy|enter)(\.|$)/', $key);
    $attributes = new \Illuminate\View\ComponentAttributeBag(collect($attributes->getAttributes())->mapWithKeys(fn ($bound, $key) => [$liveModel($key) ? $key.'.debounce.150ms' : $key => $bound])->all());

    $root = 'm-0 min-w-0 border-0 p-0';
    $legend = 'mb-1.5 p-0 text-sm font-medium text-ink';
    $group = 'flex gap-2';
    $box = 'h-12 w-10 rounded-md border border-line bg-surface text-center text-lg font-medium text-ink transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 motion-reduce:transition-none';

    $length = max(1, (int) $length);
    // Pecah nilai menjadi tepat $length karakter; posisi kosong berisi ''.
    $chars = array_map(fn (int $index) => mb_substr((string) $value, $index, 1), range(0, $length - 1));
@endphp

<fieldset
    x-data="{
        chars: @js($chars),
        {{-- Bound value for wire:model and x-model (x-modelable). --}}
        value: @js(implode('', $chars)),
        init() {
            this.$watch('value', (next) => {
                const text = String(next ?? '');
                if (text !== this.joined) this.chars = this.chars.map((_, index) => text[index] ?? '');
            });
        },
        get joined() {
            return this.chars.join('');
        },
        focusBox(index) {
            const target = this.$refs.group.children[index];
            if (target) target.focus();
        },
        update(next) {
            const previous = this.joined;
            this.chars = next;
            const value = next.join('');
            if (value === previous) return;
            this.value = value;
            this.$dispatch('markas-change', value);
            if (next.every(Boolean)) this.$dispatch('markas-complete', value);
        },
        {{-- Isi kotak mulai dari start dengan digit berurutan, lalu fokus ke kotak sesudahnya. --}}
        fill(start, digits) {
            this.update(this.chars.map((char, index) =>
                index >= start && index < start + digits.length ? (digits[index - start] ?? char) : char));
            this.focusBox(Math.min(start + digits.length, this.chars.length - 1));
        },
        setChar(index, char) {
            this.update(this.chars.map((current, i) => (i === index ? char : current)));
        },
        onInput(index, event) {
            const digits = event.target.value.replace(/\D/g, '');
            if (digits === '') this.setChar(index, '');
            else this.fill(index, digits);
            {{-- Alpine tidak menimpa DOM kalau nilai reaktifnya tidak berubah, jadi samakan manual. --}}
            event.target.value = this.chars[index] ?? '';
        },
        onKeydown(index, event) {
            const last = this.chars.length - 1;
            const move = { ArrowLeft: index - 1, ArrowRight: index + 1, Home: 0, End: last }[event.key];
            if (move !== undefined) {
                event.preventDefault();
                return this.focusBox(move);
            }
            if (event.key === 'Delete') {
                event.preventDefault();
                return this.setChar(index, '');
            }
            if (event.key !== 'Backspace') return;
            event.preventDefault();
            if (this.chars[index] || index === 0) return this.setChar(index, '');
            this.setChar(index - 1, '');
            this.focusBox(index - 1);
        },
        onPaste(index, event) {
            event.preventDefault();
            const digits = (event.clipboardData?.getData('text') ?? '').replace(/\D/g, '').slice(0, this.chars.length);
            if (digits === '') return;
            this.fill(digits.length >= this.chars.length ? 0 : index, digits);
        },
    }"
    x-modelable="value"
    {{ $attributes->class([$root]) }}
>
    @if ($label)
        <legend class="{{ $legend }}">{{ $label }}</legend>
    @endif
    <div x-ref="group" class="{{ $group }}">
        @foreach ($chars as $index => $char)
            <input
                type="text"
                inputmode="numeric"
                autocomplete="{{ $index === 0 ? 'one-time-code' : 'off' }}"
                aria-label="{{ str_replace(['{index}', '{length}'], [$index + 1, $length], $digitLabel) }}"
                value="{{ $char }}"
                :value="chars[{{ $index }}]"
                @input="onInput({{ $index }}, $event)"
                @keydown="onKeydown({{ $index }}, $event)"
                @paste="onPaste({{ $index }}, $event)"
                @focus="$event.target.select()"
                class="{{ $box }}"
            />
        @endforeach
    </div>
    @if ($name)
        <input type="hidden" name="{{ $name }}" value="{{ implode('', $chars) }}" :value="joined" />
    @endif
</fieldset>
```

```blade
<x-markas.input-otp
    name="code"
    label="Kode verifikasi"
    digit-label="Digit {index} dari {length}"
    x-on:markas-complete="$el.closest('form').requestSubmit()"
/>
```

Butuh Alpine.js. Setiap perubahan memancarkan `markas-change` dan kode yang lengkap memancarkan `markas-complete`, keduanya membawa kode di `$event.detail`. Isi kode awal lewat `value`.

### Livewire

```blade
<x-markas.input-otp label="Code" wire:model.live="code" x-on:markas-complete="$wire.verify()" />
```

`wire:model` terhubung ke kode gabungan sebagai satu string. Dengarkan `markas-complete` untuk verifikasi setelah semua kotak terisi.

### React

Simpan di `src/components/markas/InputOTP.tsx`. Tanpa dependensi tambahan.

```tsx
"use client";

import {
  useRef,
  useState,
  type ClipboardEvent,
  type ComponentProps,
  type FocusEvent,
  type FormEvent,
  type KeyboardEvent,
} from "react";

const root = "m-0 min-w-0 border-0 p-0";
const legend = "mb-1.5 p-0 text-sm font-medium text-ink";
const group = "flex gap-2";
const box =
  "h-12 w-10 rounded-md border border-line bg-surface text-center text-lg font-medium text-ink transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 motion-reduce:transition-none";
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

const NON_DIGIT = /\D/g;

/** Pecah nilai menjadi tepat `length` karakter; posisi kosong berisi "". */
const toChars = (value: string, length: number) =>
  Array.from({ length }, (_, index) => value[index] ?? "");

const formatDigitLabel = (template: string, index: number, length: number) =>
  template
    .replace("{index}", String(index + 1))
    .replace("{length}", String(length));

export type InputOTPProps = Omit<
  ComponentProps<"fieldset">,
  "defaultValue" | "name"
> & {
  length?: number;
  label?: string;
  name?: string;
  value?: string;
  defaultValue?: string;
  digitLabel?: string;
  onValueChange?: (value: string) => void;
  onComplete?: (value: string) => void;
};

export function InputOTP({
  length = 6,
  label,
  name,
  value,
  defaultValue = "",
  digitLabel = "Digit {index} of {length}",
  onValueChange,
  onComplete,
  className,
  ...props
}: InputOTPProps) {
  const groupRef = useRef<HTMLDivElement>(null);
  const [internal, setInternal] = useState(() =>
    toChars(value ?? defaultValue, length),
  );
  // Nilai terkontrol dari luar menang, kecuali sama dengan isi kotak saat ini (menjaga posisi kotak kosong).
  const chars =
    value !== undefined && value !== internal.join("")
      ? toChars(value, length)
      : internal;
  const joined = chars.join("");

  const focusBox = (index: number) => {
    const target = groupRef.current?.children[index];
    if (target instanceof HTMLInputElement) target.focus();
  };

  const update = (next: string[]) => {
    const nextValue = next.join("");
    setInternal(next);
    if (nextValue === joined) return;
    onValueChange?.(nextValue);
    if (next.every(Boolean)) onComplete?.(nextValue);
  };

  /** Isi kotak mulai dari `start` dengan digit berurutan, lalu fokus ke kotak sesudahnya. */
  const fill = (start: number, digits: string) => {
    const next = chars.map((char, index) =>
      index >= start && index < start + digits.length
        ? (digits[index - start] ?? char)
        : char,
    );
    update(next);
    focusBox(Math.min(start + digits.length, length - 1));
  };

  const setChar = (index: number, char: string) =>
    update(chars.map((current, i) => (i === index ? char : current)));

  const handleInput = (index: number, event: FormEvent<HTMLInputElement>) => {
    const digits = event.currentTarget.value.replace(NON_DIGIT, "");
    if (digits === "") return setChar(index, "");
    fill(index, digits);
  };

  const handleKeyDown = (
    index: number,
    event: KeyboardEvent<HTMLInputElement>,
  ) => {
    const moves: Record<string, number | undefined> = {
      ArrowLeft: index - 1,
      ArrowRight: index + 1,
      Home: 0,
      End: length - 1,
    };
    const move = moves[event.key];
    if (move !== undefined) {
      event.preventDefault();
      return focusBox(move);
    }
    if (event.key === "Delete") {
      event.preventDefault();
      return setChar(index, "");
    }
    if (event.key !== "Backspace") return;
    event.preventDefault();
    if (chars[index] || index === 0) return setChar(index, "");
    setChar(index - 1, "");
    focusBox(index - 1);
  };

  const handlePaste = (
    index: number,
    event: ClipboardEvent<HTMLInputElement>,
  ) => {
    event.preventDefault();
    const digits = event.clipboardData
      .getData("text")
      .replace(NON_DIGIT, "")
      .slice(0, length);
    if (digits === "") return;
    fill(digits.length >= length ? 0 : index, digits);
  };

  const selectContent = (event: FocusEvent<HTMLInputElement>) =>
    event.currentTarget.select();

  return (
    <fieldset className={cx(root, className)} {...props}>
      {label && <legend className={legend}>{label}</legend>}
      <div ref={groupRef} className={group}>
        {chars.map((char, index) => (
          <input
            key={index}
            type="text"
            inputMode="numeric"
            autoComplete={index === 0 ? "one-time-code" : "off"}
            aria-label={formatDigitLabel(digitLabel, index, length)}
            value={char}
            className={box}
            onInput={(event) => handleInput(index, event)}
            onKeyDown={(event) => handleKeyDown(index, event)}
            onPaste={(event) => handlePaste(index, event)}
            onFocus={selectContent}
          />
        ))}
      </div>
      {name && <input type="hidden" name={name} value={joined} />}
    </fieldset>
  );
}
```

```tsx
import { useState } from "react";
import { InputOTP } from "@/components/markas/InputOTP";

const [code, setCode] = useState("");

<InputOTP
  name="code"
  label="Kode verifikasi"
  digitLabel="Digit {index} dari {length}"
  value={code}
  onValueChange={setCode}
  onComplete={(value) => verify(value)}
/>;
```

### Vue

Simpan di `src/components/markas/InputOTP.vue`. Tanpa dependensi tambahan.

```vue
<script setup lang="ts">
import { computed, ref, useTemplateRef, watch } from "vue";

const props = withDefaults(
  defineProps<{
    length?: number;
    label?: string;
    name?: string;
    digitLabel?: string;
  }>(),
  {
    length: 6,
    label: undefined,
    name: undefined,
    digitLabel: "Digit {index} of {length}",
  },
);
const model = defineModel<string>({ default: "" });
const emit = defineEmits<{ complete: [value: string] }>();

const root = "m-0 min-w-0 border-0 p-0";
const legend = "mb-1.5 p-0 text-sm font-medium text-ink";
const group = "flex gap-2";
const box =
  "h-12 w-10 rounded-md border border-line bg-surface text-center text-lg font-medium text-ink transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 motion-reduce:transition-none";

const NON_DIGIT = /\D/g;

/** Pecah nilai menjadi tepat `length` karakter; posisi kosong berisi "". */
const toChars = (value: string, length: number) =>
  Array.from({ length }, (_, index) => value[index] ?? "");

const formatDigitLabel = (template: string, index: number, length: number) =>
  template
    .replace("{index}", String(index + 1))
    .replace("{length}", String(length));

const groupEl = useTemplateRef<HTMLDivElement>("digits");
const chars = ref(toChars(model.value, props.length));
const joined = computed(() => chars.value.join(""));

// Nilai dari luar menang, kecuali sama dengan isi kotak saat ini (menjaga posisi kotak kosong).
watch([model, () => props.length], ([value, length]) => {
  if (value !== joined.value || chars.value.length !== length)
    chars.value = toChars(value, length);
});

function focusBox(index: number) {
  const target = groupEl.value?.children[index];
  if (target instanceof HTMLInputElement) target.focus();
}

function update(next: string[]) {
  const previous = joined.value;
  chars.value = next;
  const nextValue = next.join("");
  if (nextValue === previous) return;
  model.value = nextValue;
  if (next.every(Boolean)) emit("complete", nextValue);
}

/** Isi kotak mulai dari `start` dengan digit berurutan, lalu fokus ke kotak sesudahnya. */
function fill(start: number, digits: string) {
  update(
    chars.value.map((char, index) =>
      index >= start && index < start + digits.length
        ? (digits[index - start] ?? char)
        : char,
    ),
  );
  focusBox(Math.min(start + digits.length, props.length - 1));
}

const setChar = (index: number, char: string) =>
  update(chars.value.map((current, i) => (i === index ? char : current)));

function onInput(index: number, event: Event) {
  const target = event.target as HTMLInputElement;
  const digits = target.value.replace(NON_DIGIT, "");
  if (digits === "") setChar(index, "");
  else fill(index, digits);
  // Vue tidak menimpa DOM kalau nilai reaktifnya tidak berubah, jadi samakan manual.
  target.value = chars.value[index] ?? "";
}

function onKeydown(index: number, event: KeyboardEvent) {
  const moves: Record<string, number | undefined> = {
    ArrowLeft: index - 1,
    ArrowRight: index + 1,
    Home: 0,
    End: props.length - 1,
  };
  const move = moves[event.key];
  if (move !== undefined) {
    event.preventDefault();
    return focusBox(move);
  }
  if (event.key === "Delete") {
    event.preventDefault();
    return setChar(index, "");
  }
  if (event.key !== "Backspace") return;
  event.preventDefault();
  if (chars.value[index] || index === 0) return setChar(index, "");
  setChar(index - 1, "");
  focusBox(index - 1);
}

function onPaste(index: number, event: ClipboardEvent) {
  event.preventDefault();
  const digits = (event.clipboardData?.getData("text") ?? "")
    .replace(NON_DIGIT, "")
    .slice(0, props.length);
  if (digits === "") return;
  fill(digits.length >= props.length ? 0 : index, digits);
}

const selectContent = (event: FocusEvent) =>
  (event.target as HTMLInputElement).select();
</script>

<template>
  <fieldset :class="root">
    <legend v-if="props.label" :class="legend">{{ props.label }}</legend>
    <div ref="digits" :class="group">
      <input
        v-for="(char, index) in chars"
        :key="index"
        type="text"
        inputmode="numeric"
        :autocomplete="index === 0 ? 'one-time-code' : 'off'"
        :aria-label="formatDigitLabel(props.digitLabel, index, props.length)"
        :value="char"
        :class="box"
        @input="onInput(index, $event)"
        @keydown="onKeydown(index, $event)"
        @paste="onPaste(index, $event)"
        @focus="selectContent"
      />
    </div>
    <input v-if="props.name" type="hidden" :name="props.name" :value="joined" />
  </fieldset>
</template>
```

```vue
<script setup lang="ts">
import { ref } from "vue";
import InputOTP from "@/components/markas/InputOTP.vue";

const code = ref("");
</script>

<template>
  <InputOTP
    v-model="code"
    name="code"
    label="Kode verifikasi"
    digit-label="Digit {index} dari {length}"
    @complete="(value) => verify(value)"
  />
</template>
```

### Svelte

Simpan di `src/lib/components/markas/InputOTP.svelte`. Tanpa dependensi tambahan.

```svelte
<script lang="ts">
  import { untrack } from "svelte";
  import type { HTMLFieldsetAttributes } from "svelte/elements";

  const root = "m-0 min-w-0 border-0 p-0";
  const legend = "mb-1.5 p-0 text-sm font-medium text-ink";
  const group = "flex gap-2";
  const box =
    "h-12 w-10 rounded-md border border-line bg-surface text-center text-lg font-medium text-ink transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 motion-reduce:transition-none";

  const NON_DIGIT = /\D/g;

  /** Split the value into exactly `length` characters; empty positions hold "". */
  const toChars = (value: string, length: number) =>
    Array.from({ length }, (_, index) => value[index] ?? "");

  const formatDigitLabel = (template: string, index: number, length: number) =>
    template
      .replace("{index}", String(index + 1))
      .replace("{length}", String(length));

  type Props = Omit<HTMLFieldsetAttributes, "name"> & {
    length?: number;
    label?: string;
    name?: string;
    value?: string;
    /** aria-label of each box. {index} and {length} are replaced with numbers. */
    digitLabel?: string;
    oncomplete?: (value: string) => void;
  };

  let {
    length = 6,
    label,
    name,
    value = $bindable(""),
    digitLabel = "Digit {index} of {length}",
    oncomplete,
    class: className,
    ...rest
  }: Props = $props();

  let groupEl = $state<HTMLDivElement>();
  let chars = $state(untrack(() => toChars(value, length)));
  const joined = $derived(chars.join(""));

  // An outside value wins, unless it equals the boxes (keeps empty positions in place).
  $effect.pre(() => {
    const next = value;
    const size = length;
    untrack(() => {
      if (next !== joined || chars.length !== size) chars = toChars(next, size);
    });
  });

  function focusBox(index: number) {
    const target = groupEl?.children[index];
    if (target instanceof HTMLInputElement) target.focus();
  }

  function update(next: string[]) {
    const previous = joined;
    chars = next;
    const nextValue = next.join("");
    if (nextValue === previous) return;
    value = nextValue;
    if (next.every(Boolean)) oncomplete?.(nextValue);
  }

  /** Fill boxes from `start` with consecutive digits, then focus the box after them. */
  function fill(start: number, digits: string) {
    update(
      chars.map((char, index) =>
        index >= start && index < start + digits.length
          ? (digits[index - start] ?? char)
          : char,
      ),
    );
    focusBox(Math.min(start + digits.length, length - 1));
  }

  const setChar = (index: number, char: string) =>
    update(chars.map((current, i) => (i === index ? char : current)));

  function handleInput(
    index: number,
    event: Event & { currentTarget: HTMLInputElement },
  ) {
    const target = event.currentTarget;
    const digits = target.value.replace(NON_DIGIT, "");
    if (digits === "") setChar(index, "");
    else fill(index, digits);
    // Svelte skips the DOM write when the state did not change, so sync it by hand.
    target.value = chars[index] ?? "";
  }

  function handleKeydown(index: number, event: KeyboardEvent) {
    const moves: Record<string, number | undefined> = {
      ArrowLeft: index - 1,
      ArrowRight: index + 1,
      Home: 0,
      End: length - 1,
    };
    const move = moves[event.key];
    if (move !== undefined) {
      event.preventDefault();
      return focusBox(move);
    }
    if (event.key === "Delete") {
      event.preventDefault();
      return setChar(index, "");
    }
    if (event.key !== "Backspace") return;
    event.preventDefault();
    if (chars[index] || index === 0) return setChar(index, "");
    setChar(index - 1, "");
    focusBox(index - 1);
  }

  function handlePaste(index: number, event: ClipboardEvent) {
    event.preventDefault();
    const digits = (event.clipboardData?.getData("text") ?? "")
      .replace(NON_DIGIT, "")
      .slice(0, length);
    if (digits === "") return;
    fill(digits.length >= length ? 0 : index, digits);
  }
</script>

<fieldset class={[root, className]} {...rest}>
  {#if label}
    <legend class={legend}>{label}</legend>
  {/if}
  <div bind:this={groupEl} class={group}>
    {#each chars as char, index (index)}
      <input
        type="text"
        inputmode="numeric"
        autocomplete={index === 0 ? "one-time-code" : "off"}
        aria-label={formatDigitLabel(digitLabel, index, length)}
        value={char}
        class={box}
        oninput={(event) => handleInput(index, event)}
        onkeydown={(event) => handleKeydown(index, event)}
        onpaste={(event) => handlePaste(index, event)}
        onfocus={(event) => event.currentTarget.select()}
      />
    {/each}
  </div>
  {#if name}
    <input type="hidden" {name} value={joined} />
  {/if}
</fieldset>
```

```svelte
<script lang="ts">
  import InputOTP from "$lib/components/markas/InputOTP.svelte";

  let kode = $state("");
</script>

<InputOTP
  bind:value={kode}
  name="code"
  label="Kode verifikasi"
  digitLabel="Digit {index} dari {length}"
  oncomplete={(value) => verify(value)}
/>
```

### Astro

Simpan di `src/components/markas/InputOTP.astro`. Tanpa dependensi tambahan.

```astro
---
import type { HTMLAttributes } from "astro/types";

const root = "m-0 min-w-0 border-0 p-0";
const legend = "mb-1.5 p-0 text-sm font-medium text-ink";
const group = "flex gap-2";
const box =
  "h-12 w-10 rounded-md border border-line bg-surface text-center text-lg font-medium text-ink transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 motion-reduce:transition-none";

type Props = Omit<HTMLAttributes<"fieldset">, "name"> & {
  length?: number;
  label?: string;
  name?: string;
  value?: string;
  /** aria-label of each box. {index} and {length} are replaced with numbers. */
  digitLabel?: string;
};

const {
  length: rawLength = 6,
  label,
  name,
  value = "",
  digitLabel = "Digit {index} of {length}",
  class: className,
  ...rest
} = Astro.props;
const length = Math.max(1, Math.trunc(Number(rawLength)));
// Split the value into exactly `length` characters; empty positions hold "".
const chars = Array.from({ length }, (_, index) => value[index] ?? "");
const formatDigitLabel = (index: number) =>
  digitLabel
    .replace("{index}", String(index + 1))
    .replace("{length}", String(length));
---

<fieldset data-markas-otp class:list={[root, className]} {...rest}>
  {label && <legend class={legend}>{label}</legend>}
  <div class={group}>
    {
      chars.map((char, index) => (
        <input
          type="text"
          inputmode="numeric"
          autocomplete={index === 0 ? "one-time-code" : "off"}
          aria-label={formatDigitLabel(index)}
          value={char}
          class={box}
        />
      ))
    }
  </div>
  {name && <input type="hidden" name={name} value={chars.join("")} />}
</fieldset>

<script>
  // One set of listeners per page serves every OTP field, including markup added later.
  // The last committed character of each box is remembered, so a raw edit can be compared
  // and undone (digits only), like the controlled boxes in React and Vue.
  const NON_DIGIT = /\D/g;
  const committed = new WeakMap<HTMLInputElement, string>();

  type Field = { root: HTMLFieldSetElement; boxes: HTMLInputElement[] };

  function fieldOf(target: EventTarget | null): [Field, number] | null {
    if (!(target instanceof HTMLInputElement) || target.type !== "text")
      return null;
    const root = target.closest<HTMLFieldSetElement>("[data-markas-otp]");
    if (!root) return null;
    const boxes = [
      ...root.querySelectorAll<HTMLInputElement>('input[type="text"]'),
    ];
    return [{ root, boxes }, boxes.indexOf(target)];
  }

  const charsOf = ({ boxes }: Field) =>
    boxes.map((box) => committed.get(box) ?? box.defaultValue);

  function update(field: Field, next: string[]) {
    const previous = charsOf(field).join("");
    field.boxes.forEach((box, index) => {
      box.value = next[index] ?? "";
      committed.set(box, box.value);
    });
    const value = next.join("");
    if (value === previous) return;
    const hidden = field.root.querySelector<HTMLInputElement>(
      'input[type="hidden"]',
    );
    if (hidden) hidden.value = value;
    field.root.dispatchEvent(
      new CustomEvent("markas-change", { detail: value, bubbles: true }),
    );
    if (next.every(Boolean))
      field.root.dispatchEvent(
        new CustomEvent("markas-complete", { detail: value, bubbles: true }),
      );
  }

  const setChar = (field: Field, index: number, char: string) =>
    update(
      field,
      charsOf(field).map((current, i) => (i === index ? char : current)),
    );

  /** Fill boxes from `start` with consecutive digits, then focus the box after them. */
  function fill(field: Field, start: number, digits: string) {
    update(
      field,
      charsOf(field).map((char, index) =>
        index >= start && index < start + digits.length
          ? (digits[index - start] ?? char)
          : char,
      ),
    );
    field.boxes[
      Math.min(start + digits.length, field.boxes.length - 1)
    ]?.focus();
  }

  document.addEventListener("input", (event) => {
    const found = fieldOf(event.target);
    if (!found) return;
    const [field, index] = found;
    const digits = field.boxes[index]!.value.replace(NON_DIGIT, "");
    if (digits === "") setChar(field, index, "");
    else fill(field, index, digits);
  });

  document.addEventListener("keydown", (event) => {
    const found = fieldOf(event.target);
    if (!found) return;
    const [field, index] = found;
    const moves: Record<string, number | undefined> = {
      ArrowLeft: index - 1,
      ArrowRight: index + 1,
      Home: 0,
      End: field.boxes.length - 1,
    };
    const move = moves[event.key];
    if (move !== undefined) {
      event.preventDefault();
      field.boxes[move]?.focus();
      return;
    }
    if (event.key === "Delete") {
      event.preventDefault();
      return setChar(field, index, "");
    }
    if (event.key !== "Backspace") return;
    event.preventDefault();
    if (charsOf(field)[index] || index === 0)
      return setChar(field, index, "");
    setChar(field, index - 1, "");
    field.boxes[index - 1]?.focus();
  });

  document.addEventListener("paste", (event) => {
    const found = fieldOf(event.target);
    if (!found) return;
    const [field, index] = found;
    event.preventDefault();
    const digits = (event.clipboardData?.getData("text") ?? "")
      .replace(NON_DIGIT, "")
      .slice(0, field.boxes.length);
    if (digits === "") return;
    fill(field, digits.length >= field.boxes.length ? 0 : index, digits);
  });

  document.addEventListener("focusin", (event) => {
    if (fieldOf(event.target)) (event.target as HTMLInputElement).select();
  });
</script>
```

```astro
---
import InputOTP from "@/components/markas/InputOTP.astro";
---

<InputOTP
  name="code"
  label="Kode verifikasi"
  digitLabel="Digit {index} dari {length}"
/>

<script>
  document.addEventListener("markas-complete", (event) => {
    verify((event as CustomEvent<string>).detail);
  });
</script>
```

Satu script kecil per halaman melayani semua kolom. Seperti Blade, fieldset memancarkan event `markas-change` dan `markas-complete` dengan kode di `detail`.

### Angular

Simpan di `src/app/markas/input-otp.component.ts`. Tanpa dependensi tambahan.

```ts
import {
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  type ElementRef,
  input,
  linkedSignal,
  model,
  numberAttribute,
  output,
  viewChild,
} from "@angular/core";

const root = "m-0 min-w-0 border-0 p-0";
const legend = "mb-1.5 p-0 text-sm font-medium text-ink";
const group = "flex gap-2";
const box =
  "h-12 w-10 rounded-md border border-line bg-surface text-center text-lg font-medium text-ink transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:cursor-not-allowed disabled:opacity-50 motion-reduce:transition-none";

const NON_DIGIT = /\D/g;

/** Split the value into exactly `length` characters; empty positions hold "". */
const toChars = (value: string, length: number) =>
  Array.from({ length }, (_, index) => value[index] ?? "");

const formatDigitLabel = (template: string, index: number, length: number) =>
  template
    .replace("{index}", String(index + 1))
    .replace("{length}", String(length));

/**
 * Host stays out of layout (display: contents). id and class move to the fieldset, so the
 * host id is cleared. `disabled` disables the fieldset and with it every box.
 */
@Component({
  selector: "markas-input-otp",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: "contents", "[attr.id]": "null", "[attr.name]": "null" },
  template: `
    <fieldset
      [class]="rootClass()"
      [disabled]="disabled()"
      [attr.id]="id() ?? null"
    >
      @if (label()) {
        <legend [class]="legend">{{ label() }}</legend>
      }
      <div #groupEl [class]="group">
        @for (char of chars(); track $index) {
          <input
            #boxEl
            type="text"
            inputmode="numeric"
            [attr.autocomplete]="$index === 0 ? 'one-time-code' : 'off'"
            [attr.aria-label]="digitLabels()[$index]"
            [value]="char"
            [class]="box"
            (input)="handleInput($index, boxEl)"
            (keydown)="handleKeydown($index, $event)"
            (paste)="handlePaste($index, $event)"
            (focus)="boxEl.select()"
          />
        }
      </div>
      @if (name()) {
        <input type="hidden" [attr.name]="name()" [value]="joined()" />
      }
    </fieldset>
  `,
})
export class InputOTP {
  readonly length = input(6, { transform: numberAttribute });
  readonly label = input<string>();
  readonly name = input<string>();
  readonly id = input<string>();
  readonly disabled = input(false, { transform: booleanAttribute });
  /** aria-label of each box. {index} and {length} are replaced with numbers. */
  readonly digitLabel = input("Digit {index} of {length}");
  readonly userClass = input("", { alias: "class" });
  /** The joined code. Two-way bindable with [(value)]. */
  readonly value = model("");
  /** Emits the full code once every box is filled. */
  readonly complete = output<string>();

  protected readonly legend = legend;
  protected readonly group = group;
  protected readonly box = box;
  protected readonly rootClass = computed(() =>
    [root, this.userClass()].filter(Boolean).join(" "),
  );
  /** An outside value wins, unless it equals the boxes (keeps empty positions in place). */
  protected readonly chars = linkedSignal<
    { value: string; length: number },
    string[]
  >({
    source: () => ({ value: this.value(), length: this.length() }),
    computation: (source, previous) =>
      previous &&
      previous.value.length === source.length &&
      previous.value.join("") === source.value
        ? previous.value
        : toChars(source.value, source.length),
  });
  protected readonly joined = computed(() => this.chars().join(""));
  protected readonly digitLabels = computed(() =>
    Array.from({ length: this.length() }, (_, index) =>
      formatDigitLabel(this.digitLabel(), index, this.length()),
    ),
  );
  private readonly groupRef =
    viewChild.required<ElementRef<HTMLDivElement>>("groupEl");

  private focusBox(index: number) {
    const target = this.groupRef().nativeElement.children[index];
    if (target instanceof HTMLInputElement) target.focus();
  }

  private update(next: string[]) {
    const previous = this.joined();
    this.chars.set(next);
    const nextValue = next.join("");
    if (nextValue === previous) return;
    this.value.set(nextValue);
    if (next.every(Boolean)) this.complete.emit(nextValue);
  }

  /** Fill boxes from `start` with consecutive digits, then focus the box after them. */
  private fill(start: number, digits: string) {
    this.update(
      this.chars().map((char, index) =>
        index >= start && index < start + digits.length
          ? (digits[index - start] ?? char)
          : char,
      ),
    );
    this.focusBox(Math.min(start + digits.length, this.length() - 1));
  }

  private setChar(index: number, char: string) {
    this.update(
      this.chars().map((current, i) => (i === index ? char : current)),
    );
  }

  protected handleInput(index: number, target: HTMLInputElement) {
    const digits = target.value.replace(NON_DIGIT, "");
    if (digits === "") this.setChar(index, "");
    else this.fill(index, digits);
    // Angular skips the DOM write when the bound value did not change, so sync it by hand.
    target.value = this.chars()[index] ?? "";
  }

  protected handleKeydown(index: number, event: KeyboardEvent) {
    const moves: Record<string, number | undefined> = {
      ArrowLeft: index - 1,
      ArrowRight: index + 1,
      Home: 0,
      End: this.length() - 1,
    };
    const move = moves[event.key];
    if (move !== undefined) {
      event.preventDefault();
      return this.focusBox(move);
    }
    if (event.key === "Delete") {
      event.preventDefault();
      return this.setChar(index, "");
    }
    if (event.key !== "Backspace") return;
    event.preventDefault();
    if (this.chars()[index] || index === 0) return this.setChar(index, "");
    this.setChar(index - 1, "");
    this.focusBox(index - 1);
  }

  protected handlePaste(index: number, event: ClipboardEvent) {
    event.preventDefault();
    const digits = (event.clipboardData?.getData("text") ?? "")
      .replace(NON_DIGIT, "")
      .slice(0, this.length());
    if (digits === "") return;
    this.fill(digits.length >= this.length() ? 0 : index, digits);
  }
}
```

```ts
import { Component, signal } from "@angular/core";
import { InputOTP } from "./markas/input-otp.component";

@Component({
  selector: "app-verifikasi",
  imports: [InputOTP],
  template: `
    <markas-input-otp
      [(value)]="kode"
      name="code"
      label="Kode verifikasi"
      digitLabel="Digit {index} dari {length}"
      (complete)="verify($event)"
    />
  `,
})
export class Verifikasi {
  readonly kode = signal("");

  verify(kode: string) {
    // Kirim kode ke API.
  }
}
```

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `length` | `number` | 6 | Jumlah kotak digit. |
| `label` | `string` | - | Label grup, dirender sebagai legend fieldset. |
| `name` | `string` | - | Nama input tersembunyi yang berisi kode lengkap untuk submit form. |
| `value / defaultValue / v-model / bind:value` | `string` | "" | Kode. React menerima value dengan onValueChange atau defaultValue; Vue memakai v-model; Svelte bind:value; Angular value atau [(value)]; Blade dan Astro memakai value. |
| `onValueChange / markas-change` | `(value: string) => void` | - | Dipanggil setiap perubahan dengan kode gabungan (React). Blade dan Astro memancarkan event markas-change. |
| `onComplete / @complete / markas-complete` | `(value: string) => void` | - | Dipanggil sekali saat semua kotak terisi, dengan kode lengkap. Blade dan Astro memancarkan event markas-complete. |
| `oncomplete` | `(value: string) => void` | - | Khusus Svelte. Dipanggil sekali saat semua kotak terisi, dengan kode lengkap. |
| `complete` | `output<string>` | - | Khusus Angular. Memancarkan kode lengkap saat semua kotak terisi. |
| `digitLabel` | `string` | Digit {index} of {length} | aria-label tiap kotak. {index} dan {length} diganti angka. Isi misalnya "Digit {index} dari {length}". |

## Aksesibilitas

- Kotak berada di fieldset dengan legend dari prop label, dan tiap kotak punya aria-label seperti "Digit 1 of 6".
- Mengetik digit memindah fokus ke kotak berikutnya; Backspace mengosongkan lalu mundur; panah kiri, panah kanan, Home, dan End berpindah kotak.
- Menempel kode mengisi semua kotak. Kotak pertama memakai autocomplete=one-time-code agar ponsel bisa menyarankan kode SMS.
- Kotak memakai inputmode=numeric untuk keyboard angka dan hanya menerima digit.

## Catatan

- Kotak hanya menerima digit. Menempel kode lengkap mengisi semua kotak, walaupun ada spasi atau tanda hubung.
- `name` dipasang di satu input tersembunyi berisi kode gabungan, jadi submit form biasa mengirim `code=123456`.
- Atribut tambahan dan `class` jatuh ke `<fieldset>`. `disabled` menonaktifkan semua kotak.
- Label kotak bawaan berbahasa Inggris ("Digit {index} of {length}"). Terjemahkan lewat `digitLabel`.
