# API

`ja-ime-utils` exports the core and DOM APIs. Use `ja-ime-utils/core` for the state machine in TypeScript projects without the `DOM` lib. `ja-ime-utils/dom` exports the adapter and its types.

## Decisions

| Function | Result |
| --- | --- |
| `isImeComposing(event?, state?)` | True when `event.isComposing` or `state.isComposing` is true. For value-writing actions, also wait until `state.isSettling` is false, or use `onStableInput`. |
| `shouldHandleEnter(event, state?, options?)` | True for `key === 'Enter'` when the current event and state permit the application's shortcut. Use it on `keydown`. Feed the event to the controller before evaluating the shortcut. |
| `shouldSubmit(event, state?, options?)` | True when `defaultPrevented` is false and the field shows no active composition, IME Enter press, or disallowed Enter repeat. Call it in the form's `submit` listener, before calling `preventDefault()`. |

`EnterOptions.modifiers` defaults to the unmodified key. The object form (`{ shiftKey: true }`, for example) requires an exact match and treats omitted `altKey`, `ctrlKey`, `metaKey`, and `shiftKey` as false. Use `'any'` to accept any combination. `allowRepeat` defaults to `false`. A repeat of an IME Enter remains guarded even with `allowRepeat: true`.

`EnterOptions.legacyKeyCode229` defaults to `false`. When enabled, `keyCode === 229` can indicate that an Enter with `isComposing: false` belongs to a composition that just ended. The event must occur before the controller flushes that end. The controller uses `code` when present to track a physical Enter press or release, including numpad Enter. The shortcut itself requires `key === 'Enter'`.

`SubmitOptions.allowRepeat` defaults to `false` and governs native or application-driven form submissions observed while an Enter repeat is held. `blockWhileSettling` defaults to `false`. An app can enable it to guard all submissions during the short settling window, including an explicit click in that window. Apply the predicate to the state of the field or fields relevant to the form action. A submit event can lack a reliably identifiable originating key. A button used by implicit submission can be the same `submitter` as an explicit click.

## `createImeController(options?)`

Create one controller per field. The controller is synchronous and has no scheduler. Pass events as structural `ImeEvent` objects. `input`, `compositionstart` and `compositionend` accept the field value observed when handling the event. Without a value, the controller can still track composition and keyboard signals.

```ts
import { createImeController, shouldHandleEnter } from 'ja-ime-utils/core'

const enter = { legacyKeyCode229: true }
const ime = createImeController({ enter })
ime.handleEvent({ type: 'compositionstart', value: '' })
const key = { type: 'keydown', key: 'Enter', isComposing: true } as const
const allowShortcut = shouldHandleEnter(key, ime.handleEvent(key), enter)
ime.handleEvent({ type: 'compositionend', data: '日本', value: '日本' })
ime.handleEvent({ type: 'keyup', key: 'Enter' })
ime.flushComposition('日本')
```

| Method | Behavior |
| --- | --- |
| `getState()` | Returns a read-only snapshot. `isComposing` is an observed session, `isSettling` means an observed end is pending, `isImeEnterDown` tracks an IME-associated Enter press, and `isEnterRepeat` tracks a repeated Enter. |
| `handleEvent(event)` | Handles `compositionstart`, `compositionupdate`, `compositionend`, `input`, `keydown`, `keyup` or `blur` and returns the latest snapshot. Use after the associated DOM mutation for `input`. |
| `flushComposition(value?)` | Delivers a pending composition end once. Call after giving the event source time to deliver its trailing input. Omit the value to use the last observed value in the pending composition. |
| `subscribe(listener)` | Immediately returns an unsubscribe function. The listener runs synchronously when the snapshot changes. Read the initial snapshot separately. |
| `reset()` | Clears observed state, a pending end and deduplication history. The controller remains usable. |
| `destroy()` | Clears state, handlers and subscriptions. A destroyed controller stays idle. |

### Notifications

- `onCompositionEnd(result)` reports the observed end of a tracked session, after processing its related trailing input. The result contains `startValue`, `value`, `data` and `outcome`. The `'committed'` inference requires nonempty `data` and a final value that differs from the observed starting value. The `'canceled'` inference requires empty `data` and a return to the starting value. Other combinations, including a replacement with the same text or a missing starting value, are `'unknown'`.
- `onCompositionCommit(result)` follows `onCompositionEnd` for an inferred `'committed'` result. Treat both as observations, since a different edit can already have updated the field. Use `onStableInput` for edits, validation or normalization.
- `onStableInput(result)` receives `source: 'input'` with a value and `inputType`, or `source: 'composition'` with a value and `composition` result. A changed value is reported regardless of the inferred outcome. Returning to the observed baseline does not require reprocessing. When the start value is unavailable, the controller uses its last stable value as the processing baseline if it has one.
- `deduplicateInput: true` suppresses stable notifications whose string equals the last stable string. It defaults to `false`, allowing ordinary same-value inputs to be treated as distinct events. Composition-generated events are coalesced independently. An equal-value trailing input with a composition marker can also be ignored until the next edit, composition start, blur or reset.

Duplicate starts or ends do not restart the current sequence. A `compositionupdate` without a start can establish composition with an unknown initial value. A positive `input.isComposing` can establish a fallback when no composition lifecycle is observed, and an ordinary input can clear that fallback. An unpaired `compositionend` is ignored. `blur` clears an active session if no end was observed and releases Enter state. A pending end is kept across blur. A new composition can supersede a pending one before it is reported, so the consumer cannot accidentally write the previous value into an active session.

During settlement, a composition-marked input, a plain `Event('input')` without an `inputType`, or `insertText` carrying the same data as the end can belong to the end. When a clearly separate input arrives first, the previous composition end can still be reported, but the stable callback receives only the current field value. A final edit delivered in a later task after the adapter has settled can produce another stable notification. Different edits with identical observable metadata can be ambiguous.

## `attachImeController(field, options?)`

Accepts a `textarea` or an `input` of type `text`, `search`, `email`, `url`, `tel`, or `password`. Other fields throw `TypeError`. Use one attachment per element. A repeated call returns the same controller and keeps the original options. Call `destroy()` before reattaching with new options.

The adapter accepts all `ImeControllerOptions` and adds `onEnter(event: KeyboardEvent)`. The event is native and the callback runs synchronously after the controller observes the key. The application may cancel the accepted shortcut to replace its default behavior. The adapter itself never cancels the event, changes the field value or selection, or registers a form, document, or window listener. It does not listen to `beforeinput` because a pending or canceled edit cannot establish a stable value.

The adapter schedules a pending end via `setTimeout(..., 0)` to allow trailing input and reads the live value when it runs. This is a next-task coalescing boundary, not a millisecond-duration guarantee. If the node is disconnected at that point, the adapter discards the pending work. The returned handle has `getState`, `subscribe`, `reset`, and `destroy`. Destroy it during unmount to remove its listeners and timer.

Callbacks run in the event handler or timer that delivers them. Frameworks can consume their results through a native element ref. See the [integration examples](../examples/README.md).
