# Companion Extensions

> Modular opt-in extensions for performance telemetry, Web Audio, keystroke dynamics, debugging, and extended Unicode charsets.

Canonical documentation: https://staticcanvas.github.io/typeflow/guides/extensions/


TypeFlow keeps its zero-dependency core below a 10.25 KiB gzip budget. Optional capabilities are published as modular companion extensions.

```mermaid
graph LR
    A[&#34;Core Engine: @staticcanvas/typeflow&#34;] --&gt; B[&#34;@staticcanvas/typeflow/metrics&#34;]
    A --&gt; C[&#34;@staticcanvas/typeflow/debug&#34;]
    A --&gt; D[&#34;@staticcanvas/typeflow/webaudio&#34;]
    A --&gt; E[&#34;@staticcanvas/typeflow/keystroke&#34;]
    A --&gt; F[&#34;@staticcanvas/typeflow/extchars&#34;]
    A --&gt; G[&#34;@staticcanvas/typeflow/caret&#34;]
```

---

## 1. Performance Metrics HUD (`@staticcanvas/typeflow/metrics`)

The `TypeFlowMetrics` extension mounts an accessible, zero-CLS floating diagnostic HUD badge in the viewport.

### Installation &amp; Usage

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

// Mount floating badge in the bottom-right corner
const hud = TypeFlowMetrics.mount({
  position: &#39;bottom-right&#39;, // &#39;bottom-right&#39; | &#39;bottom-left&#39; | &#39;top-right&#39; | &#39;top-left&#39;
  detailed: false,          // Starts in compact mode; click to expand diagnostic cards
  updateInterval: 250,      // Polling frequency in ms
});

// Programmatic stats access
const stats = TypeFlowMetrics.getStats();
console.log(&#39;Active animations:&#39;, stats.activeInstances);
console.log(&#39;Lifetime characters typed:&#39;, stats.totalTyped);
```

### Metrics Tracked
- **Frame Rate (FPS)**: Real-time rendering frequency.
- **Active Animations**: Currently running TypeFlow controllers.
- **Lifetime Units**: Total typed and erased units.
- **DOM Mutations**: Count of DOM child / character modifications.
- **Heap Memory**: Current JS Heap memory (in supported browsers).
- **JSON Export**: One-click copy of telemetry data for bug reports.

---

## 2. Telemetry &amp; LogCAD Debugging (`@staticcanvas/typeflow/debug`)

The `TypeFlowDebug` extension connects TypeFlow&#39;s animation lifecycle to `@staticcanvas/logcad` or styled console groups.

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

// Enable debugging
TypeFlowDebug.enable({
  logcad: true,    // Route through @staticcanvas/logcad if available
  console: true,   // Output styled color-coded console logs
  maxHistory: 200, // Retain last 200 events in memory
});

// Trace a controller
const ctrl = TypeFlow.type(&#39;#headline&#39;, &#39;Diagnostics enabled&#39;);
TypeFlowDebug.trace(ctrl, &#39;Hero Headline&#39;);
```

---

## 3. Procedural Web Audio (`@staticcanvas/typeflow/webaudio`)

Synthesizes high-fidelity, zero-asset mechanical switch clicks, vintage teletype strikes, and cyber synths in real time using the native Web Audio API.

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

// Attach directly to TypeFlow&#39;s audio option
TypeFlow.type(&#39;#terminal&#39;, &#39;Connecting to mainframe...&#39;, {
  audio: createKeystrokeAudio(&#39;mechanical-blue&#39;, {
    pan: 0.2,            // Stereo pan (-1.0 to 1.0)
    pitchVariance: 0.06, // Natural ±6% frequency jitter
  }),
  speed: 35,
});
```

### Versioned sound presets

Built-ins are immutable schema-v1 records with separate type and erase action
envelopes. The extension validates oscillator, frequency, gain, duration,
filter, detune, and variance bounds before accepting a custom preset.

- `&#39;mechanical-blue&#39;` / `&#39;clicky&#39;`: Crisp high-transient click with body thud.
- `&#39;mechanical-brown&#39;` / `&#39;tactile&#39;`: Damped tactile bump.
- `&#39;mechanical-red&#39;` / `&#39;mechanical&#39;`: Smooth linear bottom-out.
- `&#39;soft-keyboard&#39;` / `&#39;bubble&#39;`: Filtered, quiet key response.
- `&#39;typewriter&#39;` / `&#39;teletype&#39;`: Electro-mechanical strike.
- `&#39;synth&#39;` / `&#39;cyber-synth&#39;`: Neon oscillator chirp.
- `&#39;terminal-beep&#39;` / `&#39;terminal-8bit&#39;` / `&#39;beep&#39;`: Retro square-wave pulse.
- `&#39;correction&#39;`: Distinct erase/correction feedback.

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

const custom = structuredClone(AUDIO_PRESETS[&#39;soft-keyboard&#39;]);
custom.actions.type[0].frequency.start = 640;

TypeFlowWebAudio.registerAudioPreset(&#39;product-soft&#39;, custom);
TypeFlowWebAudio.play(&#39;product-soft&#39;);
TypeFlowWebAudio.removeAudioPreset(&#39;product-soft&#39;);
```

The `AudioContext` is created only after browser user activation. The shared
master graph is reused and active voices are capped. A callback returned by
`createKeystrokeAudio()` owns a scoped voice set; interrupting its TypeFlow
controller automatically stops and disconnects that set without affecting
other callbacks. `stopAll()` and `destroy()` remain available for global
teardown. Use `action: &#39;erase&#39;` to select a preset&#39;s correction envelope.

---

## 4. Humanized Keystroke Dynamics (`@staticcanvas/typeflow/keystroke`)

Simulates realistic human typing by modeling physical QWERTY finger travel distance, clause thought pauses, fatigue deceleration, and realistic typo injection with auto-correction backspaces.

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

// Calculate physical keyboard distance between keys
const dist = calculateKeyDistance(&#39;q&#39;, &#39;p&#39;); // ~9.0 key units

// Compute dynamic delay for natural rhythm
const delay = TypeFlowKeystroke.getDelay(&#39;a&#39;, &#39;b&#39;, { baseSpeed: 40 });

// Injects realistic adjacent-key typos and automatic backspaces
const actions = TypeFlowKeystroke.humanize(&#39;Fast, resilient, zero dependencies.&#39;, {
  errorRate: 0.04,   // 4% typo probability per character
  hesitationMs: 180, // Pause before realizing mistake
});
```

---

## 5. Extended Unicode Charsets (`@staticcanvas/typeflow/extchars`)

Extends TypeFlow&#39;s scramble reveals with hundreds of specialized glyphs across ancient scripts, mathematics, and cyber glitch presets.

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

// Ancient Egyptian Hieroglyphic reveal
TypeFlow.type(&#39;#sacred-text&#39;, &#39;TEMPLE OF KARNAK&#39;, {
  typeStyle: &#39;scramble&#39;,
  scrambleGlyphs: getExtendedCharset(&#39;hieroglyphs&#39;),
  scrambleRounds: 3,
});

// Combine multiple custom pools
const customPool = TypeFlowExtChars.combineCharsets(&#39;runic&#39;, &#39;katakana&#39;, &#39;mathSymbols&#39;);
```

### Available Extended Presets
- `hieroglyphs`: Egyptian hieroglyphic symbols (`𓀀𓀁𓀂𓀃...`).
- `runic`: Elder &amp; Anglo-Saxon runes (`ᚠᚡᚢᚣᚤ...`).
- `ogham`: Celtic Ogham script (`ᚁᚂᚃᚄᚅ...`).
- `coptic`: Coptic alphabet (`ⲀⲂⲄⲆⲈ...`).
- `katakana`: Cyber Katakana glyphs (`ｱｲｳｴｵ...`).
- `boxDrawing`: Terminal borders &amp; frames (`┌┐└┘├┤┬┴┼...`).
- `mathSymbols`: Calculus &amp; set theory operators (`∀∂∃∅∆∇∈∉...`).
- `braille`: Full Braille patterns (`⠁⠂⠃⠄...`).
- `astronomical`: Planetary &amp; zodiac glyphs (`☉☽☿♀♁♂...`).
- `glitch`: Combining zalgo diacritics.

---

## 6. Interactive Caret (`@staticcanvas/typeflow/caret`)

`TypeFlowCaret` is a persistent, editable cursor bound to an element&#39;s text. Unlike `TypeFlow.type()`/`erase()`, which run once from start to finish, a caret stays around: `jump()`/`move()` reposition it instantly, `deleteChar()`/`deleteWord()` edit at that position, and `insert()` types new text in with the usual character-by-character animation.

```javascript
import { Caret } from &#39;@staticcanvas/typeflow/caret&#39;;

const caret = Caret(&#39;#terminal&#39;, { text: &#39;git commit -m &#34;wip&#34;&#39; });

// Jump to just after &#34;git &#34;, delete the word &#34;commit&#34;, type &#34;push&#34; in its place
caret.jump(4).deleteWord(&#39;forward&#39;).insert(&#39;push&#39;);
// &#34;git push -m &#34;wip&#34;&#34;
```

It&#39;s a standalone, zero-dependency module — it does not import the core engine. If a page-global `TypeFlow` happens to be present, a caret opportunistically calls `TypeFlow.stop()` on its target before editing, so starting a caret edit interrupts any in-flight `type()`/`erase()` cleanly; the reverse (a `TypeFlow.type()` call interrupting an in-flight caret) is not automatic, since the two are otherwise fully decoupled.

### API

| Method | Description |
| :--- | :--- |
| `jump(position)` | Moves the caret to an absolute grapheme index, clamped to the text&#39;s bounds. |
| `move(delta)` | Moves the caret by a relative number of graphemes (positive = right, negative = left). |
| `deleteChar(direction)` | Deletes one grapheme: `&#39;backward&#39;` (Backspace, default) or `&#39;forward&#39;` (Delete). |
| `deleteWord(direction)` | Deletes the whitespace-delimited word adjacent to the caret, consuming the adjoining whitespace with it. |
| `insert(text, config)` | Types `text` at the caret position, shifting following content right. Returns `{ stop, promise }` like `TypeFlow.type()`. |
| `stop()` | Stops an in-flight `insert()`. |
| `destroy()` | Stops any in-flight `insert()` and clears the blink interval. |

`caret.text`, `caret.position`, and `caret.length` expose the current plain text, caret index, and total grapheme count. Every mutating method returns the caret instance, so calls can be chained.

