# API reference

> Full specification of options, controllers, methods, and companion extensions in TypeFlow.

Canonical documentation: https://staticcanvas.github.io/typeflow/api/


## Package Exports

The `@staticcanvas/typeflow` package provides ESM, CommonJS, and UMD distributions.

| Export Path | Format | Target | Description |
| :--- | :--- | :--- | :--- |
| `@staticcanvas/typeflow` | ESM / CJS / UMD | `dist/typeflow.mjs` | Core typewriter engine and sequence helpers. |
| `@staticcanvas/typeflow/metrics` | ESM / CJS / UMD | `dist/typeflow-metrics.mjs` | Real-time floating performance HUD and diagnostic badge. |
| `@staticcanvas/typeflow/debug` | ESM / CJS / UMD | `dist/typeflow-debug.mjs` | Diagnostic tracing and `@staticcanvas/logcad` integration. |
| `@staticcanvas/typeflow/webaudio` | ESM / CJS / UMD | `dist/typeflow-webaudio.mjs` | Zero-asset procedural Web Audio synthesizer. |
| `@staticcanvas/typeflow/parallel` | ESM / CJS / UMD | `dist/typeflow-parallel.mjs` | Explicit opt-in parallel step orchestration with bounded concurrency. |
| `@staticcanvas/typeflow/keystroke` | ESM / CJS / UMD | `dist/typeflow-keystroke.mjs` | Human typing dynamics, finger travel, and typo simulation. |
| `@staticcanvas/typeflow/extchars` | ESM / CJS / UMD | `dist/typeflow-extchars.mjs` | Extended Unicode glyph sets for decrypt scramble reveals. |
| `@staticcanvas/typeflow/caret` | ESM / CJS / UMD | `dist/typeflow-caret.mjs` | Persistent, editable cursor bound to an element&#39;s text. |
| `jsr:@staticcanvas/typeflow` | ESM | `src/typeflow.js` | JSR package distribution for Deno and Node. |

## `TypeFlowConfig` Options

```typescript
export interface TypeFlowConfig {
  speed?: number;
  delay?: number;
  speedVariance?: number;
  naturalCadence?: boolean;
  granularity?: &#34;grapheme&#34; | &#34;word&#34;;
  direction?: &#34;left&#34; | &#34;right&#34; | &#34;center&#34;;
  typeStyle?: &#34;char&#34; | &#34;word&#34; | &#34;scramble&#34; | &#34;fade-trail&#34; | &#34;word-fade&#34; | &#34;float-in-top&#34; | &#34;float-in-bottom&#34; | &#34;float-in-left&#34; | &#34;float-in-right&#34; | &#34;zoom-in-space&#34;;
  wordOrder?: &#34;left-to-right&#34; | &#34;right-to-left&#34; | &#34;random&#34;;
  wordLayout?: &#34;opacity&#34; | &#34;placeholder&#34;;
  wordFadeDuration?: number;
  wordStagger?: number;
  wordSeed?: string | number;
  wordMotionDistance?: number;
  wordMotionDepth?: number;
  wordMotionScale?: number;
  wordMotionPerspective?: number;
  wordMotionEasing?: string;
  trailFade?: number | boolean;
  trailMinOpacity?: number;
  cursor?: string;
  cursorBlink?: boolean;
  html?: boolean;
  mode?: &#34;replace&#34; | &#34;append&#34;;
  scrambleCharset?: &#34;matrix&#34; | &#34;ascii&#34; | &#34;ascii-extended&#34; | &#34;blocks&#34; | &#34;binary&#34; | &#34;hex&#34; | &#34;braille&#34; | &#34;runic&#34; | &#34;cyber&#34;;
  scrambleGlyphs?: string;
  scrambleRounds?: number;
  scrambleColor?: string;
  scrambleGradient?: string;
  audio?: &#34;mechanical&#34; | &#34;beep&#34; | &#34;synth&#34; | boolean | (() =&gt; void);
  allowedTags?: string[];
  allowedAttributes?: Record&lt;string, string[]&gt;;
  sanitizer?: (html: string) =&gt; string;
  respectReducedMotion?: boolean;
  ariaLive?: &#34;off&#34; | &#34;polite&#34; | &#34;assertive&#34;;
  eraseStyle?: &#34;end&#34; | &#34;start&#34; | &#34;center&#34; | &#34;scramble&#34; | &#34;fade-trail&#34; | &#34;instant&#34; | &#34;fade&#34; | &#34;word-fade&#34; | &#34;float-in-top&#34; | &#34;float-in-bottom&#34; | &#34;float-in-left&#34; | &#34;float-in-right&#34; | &#34;zoom-in-space&#34;;
  duration?: number;
  preserveBaseline?: boolean;
  onStart?: () =&gt; void;
  onComplete?: (text: string) =&gt; void;
  onInterrupt?: () =&gt; void;
}
```

### Options Breakdown

| Property | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| `speed` | `number` | `50` (type) / `25` (erase) | Milliseconds per character / word delay. |
| `delay` | `number` | `0` | Initial delay in ms before animation initiates. |
| `speedVariance` | `number` | `0` | Random jitter (&#43;/- ms) added per unit for natural typing cadence. |
| `naturalCadence`| `boolean`| `false` | Adds natural micro-pauses at punctuation (. , ! ?) and word breaks. |
| `granularity` | `&#34;grapheme&#34; \| &#34;word&#34;` | `&#34;grapheme&#34;` | Unit segmentation mode using `Intl.Segmenter`. |
| `direction` | `&#34;left&#34; \| &#34;right&#34; \| &#34;center&#34;` | `&#34;left&#34;` | Typing reveal direction (LTR, RTL, center-outward). |
| `typeStyle` | `&#34;char&#34; \| &#34;word&#34; \| &#34;scramble&#34; \| &#34;fade-trail&#34; \| &#34;word-fade&#34; \| &#34;float-in-top&#34; \| &#34;float-in-bottom&#34; \| &#34;float-in-left&#34; \| &#34;float-in-right&#34; \| &#34;zoom-in-space&#34;` | `&#34;char&#34;` | Typing reveal presentation style. `word-fade` and the `float-in-*`/`zoom-in-space` spatial styles lay out the final text before transitioning each word. |
| `wordOrder` | `&#34;left-to-right&#34; \| &#34;right-to-left&#34; \| &#34;random&#34;` | `&#34;left-to-right&#34;` | Reveal or erase order for `word-fade` and the spatial word-motion styles; it does not change bidi direction. |
| `wordLayout` | `&#34;opacity&#34; \| &#34;placeholder&#34;` | `&#34;opacity&#34;` | Stable-layout strategy shared by `word-fade` and the spatial word-motion styles. Placeholder mode also hides unrevealed words with `visibility`. |
| `wordFadeDuration` | `number` | `280` | Opacity/transform transition duration for each word in milliseconds. |
| `wordStagger` | `number` | Current `speed` | Delay between consecutive word transitions in milliseconds. |
| `wordSeed` | `string \| number` | `undefined` | Optional deterministic seed when `wordOrder` is `&#34;random&#34;`. |
| `wordMotionDistance` | `number` | `24` | Translate distance in pixels for `float-in-*` styles. |
| `wordMotionDepth` | `number` | `160` | `translateZ` depth in pixels for `zoom-in-space`. |
| `wordMotionScale` | `number` | `0.82` | Starting scale (0-1) for `zoom-in-space`. |
| `wordMotionPerspective` | `number` | `600` | CSS `perspective` in pixels applied to the target element while `zoom-in-space` runs. |
| `wordMotionEasing` | `string` | `&#34;ease&#34;` | CSS timing function for `float-in-*`/`zoom-in-space` transitions. |
| `trailFade` | `number \| boolean` | `undefined` | Length of trailing fade gradient in characters. |
| `trailMinOpacity` | `number` | `0.18` | Lowest opacity used by characters in a trailing fade. |
| `scrambleCharset` | `&#34;matrix&#34; \| &#34;ascii&#34; \| ...` | `undefined` | Built-in scramble glyph charset preset name. |
| `scrambleGlyphs`| `string` | `&#34;!&lt;&gt;-_\\/[]{}—=&#43;*^?#________&#34;` | Character pool used during scramble reveals. |
| `scrambleRounds`| `number` | `2` | Number of glyph iterations per unit. |
| `scrambleColor` | `string` | `undefined` | CSS color applied to the active scramble glyph. |
| `scrambleGradient` | `string` | `undefined` | CSS gradient applied to the active scramble glyph; overrides `scrambleColor`. |
| `audio` | `&#34;mechanical&#34; \| &#34;beep&#34; \| &#34;synth&#34; \| boolean \| fn` | `undefined` | Procedural Web Audio synthesized keystrokes or custom sound callback. |
| `cursor` | `string` | `&#34;\|&#34;` | Cursor glyph string. Set to `&#34;&#34;` to omit cursor. |
| `cursorBlink` | `boolean` | `true` | Enables post-completion cursor blinking effect. |
| `html` | `boolean` | `false` | When `true`, parses input string as structured HTML markup. |
| `mode` | `&#34;replace&#34; \| &#34;append&#34;` | `&#34;replace&#34;` | `&#34;replace&#34;` clears element first; `&#34;append&#34;` preserves initial child nodes. |
| `allowedTags` | `string[]` | `[&#39;b&#39;, &#39;strong&#39;, &#39;i&#39;, &#39;em&#39;, &#39;mark&#39;, &#39;span&#39;, &#39;small&#39;, &#39;sub&#39;, &#39;sup&#39;, &#39;u&#39;, &#39;br&#39;, &#39;a&#39;, &#39;code&#39;, &#39;ul&#39;, &#39;ol&#39;, &#39;li&#39;]` | Allowed HTML tags for sanitization. |
| `allowedAttributes` | `Record&lt;string, string[]&gt;` | Defaults for `a`, `span`, `mark` | Map of tag names to allowed attribute arrays. |
| `sanitizer` | `(html: string) =&gt; string` | `undefined` | Custom HTML sanitization function. |
| `respectReducedMotion` | `boolean` | `true` | Skips animation if user OS has `prefers-reduced-motion: reduce`. |
| `ariaLive` | `&#34;off&#34; \| &#34;polite&#34; \| &#34;assertive&#34;` | `undefined` | Updates the element `aria-live` attribute during typing. |
| `eraseStyle` | `&#34;end&#34; \| &#34;start&#34; \| &#34;center&#34; \| &#34;scramble&#34; \| &#34;fade-trail&#34; \| &#34;instant&#34; \| &#34;fade&#34; \| &#34;word-fade&#34; \| &#34;float-in-top&#34; \| &#34;float-in-bottom&#34; \| &#34;float-in-left&#34; \| &#34;float-in-right&#34; \| &#34;zoom-in-space&#34;` | `&#34;end&#34;` | Erasing animation method. |
| `duration` | `number` | `250` | Fade duration in ms when `eraseStyle: &#39;fade&#39;`. |
| `preserveBaseline` | `boolean` | `true` | Retains initial prefix when erasing an `append` mode element. |
| `onStart` | `() =&gt; void` | `undefined` | Callback invoked right before the first character renders. |
| `onComplete` | `(text: string) =&gt; void` | `undefined` | Callback invoked upon animation completion. |
| `onInterrupt` | `() =&gt; void` | `undefined` | Callback invoked when `.stop()` is triggered early. |

---

## `TypeFlowController`

Returned by `TypeFlow.type()`, `TypeFlow.erase()`, `TypeFlow.morph()`, `TypeFlow.stagger()`, `TypeFlow.sequence()`, and `TypeFlow.rotate()`.

| Property / Method | Type | Description |
| :--- | :--- | :--- |
| `stop()` | `() =&gt; void` | Cancels running timers and halts animation immediately without promise rejection. |
| `promise` | `Promise&lt;TypeFlowResult&gt;` | Resolves with `{ completed: boolean, text: string }`. |

---

## Core Engine Methods

### `TypeFlow.type(target, text, config?)`
Types text or sanitized HTML into the element.

```javascript
const controller = TypeFlow.type(&#39;#msg&#39;, &#39;Hello &lt;strong&gt;World&lt;/strong&gt;&#39;, {
  html: true,
  direction: &#39;center&#39;,
  audio: &#39;mechanical&#39;
});
```

### `TypeFlow.erase(target, config?)`
Erases text from the target using the specified `eraseStyle`.

```javascript
TypeFlow.erase(&#39;#msg&#39;, { eraseStyle: &#39;fade-trail&#39;, speed: 20 });
```

### `TypeFlow.morph(target, nextText, config?)`
Computes the longest common prefix between existing text and `nextText`, erases only the changed suffix, and types the new text.

```javascript
await TypeFlow.type(&#39;#status&#39;, &#39;Connection: Pending&#39;);
await TypeFlow.morph(&#39;#status&#39;, &#39;Connection: Established&#39;);
```

### `TypeFlow.stream(target, config?)`
Creates a streaming chunk consumer for real-time LLM token ingestion.

```javascript
const stream = TypeFlow.stream(&#39;#output&#39;, { speed: 15 });
stream.push(&#39;Processing &#39;);
stream.push(&#39;query results...&#39;);
```

### `TypeFlow.stagger(targets, texts?, config?)`
Staggers typing across multiple DOM elements simultaneously with offset delays.

```javascript
TypeFlow.stagger(&#39;.terminal-line&#39;, [
  &#39;npm install @staticcanvas/typeflow&#39;,
  &#39;npm run build&#39;,
  &#39;Ready.&#39;
], { stagger: 200, speed: 25 });
```

### `TypeFlow.preset(name, overrides?)`
Returns a pre-configured options object for common styles (`&#39;cyberpunk&#39;`, `&#39;terminal&#39;`, `&#39;writer&#39;`, `&#39;matrix&#39;`, `&#39;blocks&#39;`, `&#39;subtle&#39;`).

```javascript
TypeFlow.type(&#39;#terminal&#39;, &#39;INITIALIZING MATRIX&#39;, TypeFlow.preset(&#39;cyberpunk&#39;));
```

### `TypeFlow.fit(target, candidates)`
Measures candidate phrases and locks the container&#39;s inline dimensions to eliminate Cumulative Layout Shift (CLS).

```javascript
TypeFlow.fit(&#39;#rotating&#39;, [&#39;Short&#39;, &#39;A much longer rotating phrase&#39;]);
```

### `TypeFlow.sequence(steps, seqConfig?)`
Orchestrates sequential typing, erasing, pausing, and arbitrary function callbacks.

```javascript
import { TypeFlow, seq } from &#39;@staticcanvas/typeflow&#39;;

TypeFlow.sequence([
  seq.visible(&#39;#output&#39;),
  seq.type(&#39;#output&#39;, &#39;Step 1 complete.&#39;),
  seq.pause(500),
  seq.call(() =&gt; console.log(&#39;Milestone&#39;)),
  seq.erase(&#39;#output&#39;, { eraseStyle: &#39;center&#39; }),
  seq.type(&#39;#output&#39;, &#39;Step 2 starting...&#39;)
], { repeat: 1 });
```

### `TypeFlow.parallel(steps, options?)` — experimental

&gt; This API is opt-in and experimental. Its shape may change before it is
&gt; promoted to the stable API.

Runs ordinary `seq` steps concurrently while preserving input order in the
result array. `concurrency` bounds active children. With `all-settled` (the
default), every step runs; with `fail-fast`, the first error or interrupted
child stops active siblings. The controller promise always resolves, including
errors as `{ status: &#39;rejected&#39;, reason }` entries. Calling `stop()` propagates
to active children and pending waits. A later operation on a repeated target
interrupts the earlier operation, following the normal TypeFlow target rule.

```javascript
import { TypeFlow, seq } from &#39;@staticcanvas/typeflow&#39;;
import { installParallel } from &#39;@staticcanvas/typeflow/parallel&#39;;

// Explicit opt-in: this adds parallel() only for callers importing the extension.
installParallel(TypeFlow, seq);

const group = TypeFlow.parallel([
  seq.type(&#39;#status-a&#39;, &#39;Connected&#39;, { delay: 100 }),
  seq.erase(&#39;#status-b&#39;, { eraseStyle: &#39;fade&#39; }),
  seq.parallel([
    seq.type(&#39;#nested-a&#39;, &#39;Nested A&#39;),
    seq.type(&#39;#nested-b&#39;, &#39;Nested B&#39;)
  ], { concurrency: 1 })
], { concurrency: 2, settlement: &#39;all-settled&#39; });

const { completed, results } = await group.promise;
```

### `TypeFlow.rotate(target, words, config?)`
Cyclically types and erases an array of strings.

```javascript
TypeFlow.rotate(&#39;#rotating&#39;, [&#39;Fast&#39;, &#39;Lightweight&#39;, &#39;Reliable&#39;], {
  holdDuration: 1200,
  pauseBetween: 200,
  repeat: Infinity
});
```

### `TypeFlow.watch(container, selector, callback)`
Observes DOM subtree mutations and automatically invokes a callback whenever matching elements are injected.

```javascript
const watcher = TypeFlow.watch(&#39;#feed&#39;, &#39;.item-title&#39;, (el) =&gt; {
  const text = el.textContent;
  el.textContent = &#39;&#39;;
  TypeFlow.type(el, text, { speed: 20 });
});

// Clean up
watcher.disconnect();
```

---

## Companion Extensions API

### `TypeFlowMetrics` (`@staticcanvas/typeflow/metrics`)
```javascript
import { TypeFlowMetrics } from &#39;@staticcanvas/typeflow/metrics&#39;;

TypeFlowMetrics.mount({ position: &#39;bottom-right&#39;, detailed: false });
const stats = TypeFlowMetrics.getStats();
TypeFlowMetrics.unmount();
```

### `TypeFlowDebug` (`@staticcanvas/typeflow/debug`)
```javascript
import { TypeFlowDebug } from &#39;@staticcanvas/typeflow/debug&#39;;

TypeFlowDebug.enable({ logcad: true, console: true });
TypeFlowDebug.trace(controller, &#39;Target Label&#39;);
const jsonLog = TypeFlowDebug.exportLog();
```

### `TypeFlowWebAudio` (`@staticcanvas/typeflow/webaudio`)
```javascript
import { TypeFlowWebAudio, createKeystrokeAudio } from &#39;@staticcanvas/typeflow/webaudio&#39;;

TypeFlowWebAudio.play(&#39;mechanical-blue&#39;, { pan: 0.1 });
const audioCallback = createKeystrokeAudio(&#39;teletype&#39;);
const controller = TypeFlow.type(&#39;#target&#39;, &#39;Scoped audio&#39;, { audio: audioCallback });
controller.stop(); // also stops and disconnects this callback&#39;s active voices
```

### `TypeFlowKeystroke` (`@staticcanvas/typeflow/keystroke`)
```javascript
import { TypeFlowKeystroke, calculateKeyDistance } from &#39;@staticcanvas/typeflow/keystroke&#39;;

const dist = calculateKeyDistance(&#39;q&#39;, &#39;p&#39;);
const actions = TypeFlowKeystroke.humanize(&#39;Typo injection text&#39;, { errorRate: 0.05 });
```

### `TypeFlowExtChars` (`@staticcanvas/typeflow/extchars`)
```javascript
import { TypeFlowExtChars, getExtendedCharset } from &#39;@staticcanvas/typeflow/extchars&#39;;

const runes = getExtendedCharset(&#39;runic&#39;);
const custom = TypeFlowExtChars.combineCharsets(&#39;hieroglyphs&#39;, &#39;coptic&#39;);
```

