# @rtif-sdk/react

Headless React bindings for the RTIF editor. One host component, three hooks,
zero UI opinions — toolbars and menus are yours to render.

```bash
npm install @rtif-sdk/react @rtif-sdk/web @rtif-sdk/engine @rtif-sdk/core react react-dom
```

## 30 seconds

```tsx
import { useEditor, EditorContent, useCommand } from '@rtif-sdk/react';
import type { EditorHandle } from '@rtif-sdk/react';

function ToolbarButton({ editor, command, label }: {
  editor: EditorHandle; command: string; label: string;
}) {
  const { exec, canExec, isActive } = useCommand(editor, command);
  return (
    <button
      disabled={!canExec}
      aria-pressed={isActive}
      style={{ fontWeight: isActive ? 'bold' : 'normal' }}
      onMouseDown={(e) => e.preventDefault()} // keep editor focus
      onClick={() => exec()}
    >
      {label}
    </button>
  );
}

export function MyEditor() {
  const editor = useEditor({ placeholder: 'Write something…' });
  return (
    <div>
      <ToolbarButton editor={editor} command="bold.toggle" label="B" />
      <ToolbarButton editor={editor} command="italic.toggle" label="I" />
      <ToolbarButton editor={editor} command="history.undo" label="↶" />
      <EditorContent editor={editor} className="my-editor" />
    </div>
  );
}
```

That `ToolbarButton` is the whole toolbar story — there are no toolbar
components in this package, by design. `useCommand` gives you live
`canExec`/`isActive` for any registered `${feature}.${command}` name.

## Headless usage

`useEditor` returns a **stable handle** (same identity every render). The
editor itself is created when `<EditorContent>` mounts; before that,
`handle.editor` and `handle.getState()` are `null` and `exec`/`focus` throw a
`[NOT_MOUNTED]` error.

Subscribe to any derived slice of state with `useEditorState` — your component
re-renders only when the selected value changes (`Object.is` by default; pass
a custom `isEqual` for object-returning selectors):

```tsx
import { useEditorState } from '@rtif-sdk/react';

function WordCount({ editor }: { editor: EditorHandle }) {
  const words = useEditorState(editor, (s) =>
    s.doc.blocks.flatMap((b) => b.spans).map((sp) => sp.text).join(' ')
      .split(/\s+/).filter(Boolean).length
  );
  return <span>{words ?? 0} words</span>; // null until mounted
}
```

Skip prop drilling with the context pair:

```tsx
import { EditorProvider, useEditorContext } from '@rtif-sdk/react';

<EditorProvider editor={editor}>
  <Toolbar />          {/* calls useEditorContext() inside */}
  <EditorContent editor={editor} />
</EditorProvider>
```

Need the raw machinery? `editor.editor` (once mounted) is the full
`@rtif-sdk/web` `Editor` — `editor.editor.engine.dispatch(...)`, undo, pending
marks, everything. Types come from `@rtif-sdk/core` / `@rtif-sdk/web` directly; this
package re-exports nothing from lower layers.

## SSR

Safe by construction: nothing touches the DOM at module scope or during
render. `renderToString` emits the plain host `<div>`; hooks return their
server snapshots (`null` / `false`). The editor is created in a browser-only
effect after hydration.

## Config is create-time only

The object passed to `useEditor` is read **once**, when the handle is first
created — like a `useRef` initial value. Changing `doc`, `features`,
`readOnly`, etc. on a later render does nothing. To apply a new config, mount
a fresh handle (e.g. give the editor component a new React `key`).

The one exception is `onChange`: it always sees the latest render's closure.
It fires after every state change (edits, selection, focus). Don't `exec`
synchronously inside it — the engine forbids re-entrant dispatch; queue
follow-up edits with `queueMicrotask`.

## Mentions / hashtag autocomplete

Pair `createMentionsFeature` (from `@rtif-sdk/web`) with the headless
`useMentions` hook: you supply an async `MentionSource` wrapping your API —
the hook owns debounce, abort of superseded searches, and stale-response
dropping. Render the result with the unstyled `MentionsPopup` (customize rows
via `renderItem`/`renderLoading`/`renderEmpty`) or build your own dropdown
from the returned `MentionsApi`.

```tsx
const TRIGGERS = { '@': { mark: 'mention' }, '#': { mark: 'hashtag' } };
const source: MentionSource = {
  async search(query, signal) {
    const res = await fetch(`/api/search?s=${query.sigil}&q=${query.query}`, { signal });
    return res.json(); // [{ value, label, data? }]
  },
};

function MyEditor() {
  const editor = useEditor({
    features: [...defaultFeatures(), createMentionsFeature({ triggers: TRIGGERS })],
  });
  const containerRef = useRef<HTMLDivElement | null>(null);
  const mentions = useMentions(editor, containerRef, { triggers: TRIGGERS, source });
  return (
    <div ref={containerRef} style={{ position: 'relative' }}
         onKeyDownCapture={mentions.onKeyDownCapture}>
      <EditorContent editor={editor} />
      <MentionsPopup mentions={mentions} />
    </div>
  );
}
```

Customization points: `toItem` (map your search results to `{ value, label,
data? }`), `onPick` (replace insertion wholesale), `detect` (replace trigger
detection), `command` (a differently-named feature), popup render props
(`renderItem` / `renderLoading` / `renderEmpty` / `renderError`, plus `getKey`
for stable row keys), and per-trigger `text` / `markValue` / `view` on the
feature side. Failed searches surface on `mentions.error` (aborts never do);
the popup position re-anchors on scroll and resize while open. Inserted
tokens self-heal: partial edits strip the mark rather than leave a
stale-looking token (token integrity — see the `@rtif-sdk/web` README). See
`examples/react` in the repo for a complete app.

## Media uploads

`useMediaUpload(editor, options)` wraps `@rtif-sdk/web`'s upload pipeline and
tracks per-block state, so you can render spinners, errors, and a retry button.
Options mirror the web `MediaUploadOptions`, except `accept` is an HTML
`accept` **string** (picker filter + file gate, e.g. `'image/*,.pdf'`) and the
hook supplies `onStatusChange` for you. Three input paths share one pipeline:
the editor's own paste/drop, a toolbar `openPicker()`, and an optional
`getDropZoneProps()` target.

```tsx
import { useEditor, EditorContent, useMediaUpload } from '@rtif-sdk/react';
import { defaultFeatures, createImageFeature } from '@rtif-sdk/web';

function MediaEditor() {
  const editor = useEditor({ features: [...defaultFeatures(), createImageFeature()] });

  const media = useMediaUpload(editor, {
    accept: 'image/*',
    onUpload: async (file) => ({ src: await upload(file) }), // MediaResult: has `src`
  });

  return (
    <div {...media.getDropZoneProps()} data-dragging={media.isDragging}>
      <button onMouseDown={(e) => e.preventDefault()} onClick={() => media.openPicker()}>
        Insert image
      </button>
      <EditorContent editor={editor} />
      {media.uploads.map((u) => (
        <div key={u.blockId} data-status={u.status}>
          {u.file.name} — {u.status}
          {u.status === 'error' && <button onClick={() => media.retry(u.blockId)}>Retry</button>}
        </div>
      ))}
    </div>
  );
}
```

**No wiring needed.** `useMediaUpload` registers its handler with the editor on
mount (via `editor.setMediaHandler`), so the toolbar picker, drag-drop, and file
paste all work just by calling the hook — you don't pass anything to `useEditor`.
Set `enabled: false` to make the hook inert (a shared wrapper that toggles media
per editor). `MediaUploadApi` also returns the underlying `handler`,
`openPicker()`, `getDropZoneProps()`, `isDragging`, `uploads` (a readonly
`MediaUploadState[]` with `blockId`/`file`/`status`/`error?`), and
`retry(blockId)`. See [`docs/guides/media-attachments.md`](../../docs/guides/media-attachments.md)
for the full recipe (placeholder vs await, custom block types, security).

## API

| Export | What |
|---|---|
| `useEditor(config)` | Create a stable `EditorHandle` |
| `EditorContent` | Host component: `editor`, `className?`, `style?` |
| `useEditorState(editor, selector, isEqual?)` | Live derived state, `null` pre-mount |
| `useCommand(editor, command)` | `{ exec, canExec, isActive }`, live |
| `useMentions(editor, containerRef, options)` | Headless mention autocomplete (`MentionsApi`) |
| `useMediaUpload(editor, options)` | Headless media uploads + per-block status (`MediaUploadApi`) |
| `MentionsPopup` | Optional unstyled dropdown over `MentionsApi` |
| `EditorProvider` / `useEditorContext` | Share the handle without prop drilling |
| `UseEditorConfig`, `EditorHandle`, `MentionSource`, … | The types above |
