Code / react-rte

react-rte

TypeScript · 50 files · main @ 4c32580

Files

  • docs/
  • examples/
  • scripts/
  • src/
  • test/
  • .gitignore
  • .yarnrc.yml
  • CHANGELOG.md
  • LICENSE
  • package.json
  • README.md
  • tailwind.config.ts
  • tsconfig.json
  • tsup.config.ts

README

@sclp/react-rte

A reusable, type-safe rich-text editor package for React, built on Meta's Lexical editor framework.

It stores content as structured Lexical state and can safely accept previously exported Lexical JSON, HTML, Markdown, or plain text data. HTML is parsed into supported Lexical nodes after sanitisation. The package does not use dangerouslySetInnerHTML, innerHTML, outerHTML, or insertAdjacentHTML.

Included

  • Bold, italic, underline, strikethrough, inline code, subscript, and superscript
  • Paragraphs, headings, quotes, and code blocks
  • Font family, font size, foreground color, and highlight color
  • Alignment and indentation
  • Bulleted, numbered, and check lists
  • Links with protocol validation
  • Tables
  • Images by URL, custom picker, upload callback, paste, or drop
  • Horizontal rules
  • Undo and redo
  • Markdown typing shortcuts
  • Optional character limit and read-only mode
  • Controlled and uncontrolled usage
  • Debounced structured change snapshots
  • Safe HTML/Markdown/JSON/text data import
  • JSON, HTML, Markdown, text, Word-compatible .doc, and browser PDF export
  • Imperative, fully typed editor API
  • Exact toolbar item selection, ordering, and grouping
  • Automatic low-specificity fallback styles with Tailwind-friendly overrides

Why Lexical

Lexical is used only as the structured editor engine. Feature packages are imported separately, so the runtime dependency set remains focused instead of dragging an entire office suite into the browser like a doomed procurement project.

All Lexical packages are pinned to 0.48.0 to prevent cross-package incompatibilities. That release is a maintenance and security-hardening release; the package deliberately avoids the immediately following breaking node-API migration until consumers can adopt it intentionally.

Install

corepack enable
yarn add @sclp/react-rte react react-dom

During local development of this source package:

corepack enable
yarn install
yarn check

Basic usage

import { useRef } from 'react';
import {
  RichTextEditor,
  type EditorDocument,
  type RichTextEditorHandle
} from '@sclp/react-rte';
const initialValue: EditorDocument = {
  format: 'markdown',
  data: '# Hello\n\nThis came from **Markdown data**.'
};

export function DocumentEditor() {
  const editorRef = useRef<RichTextEditorHandle>(null);

  return (
    <RichTextEditor
      ref={editorRef}
      defaultValue={initialValue}
      toolbar={{ sticky: true }}
      exportOptions={{ fileName: 'document', documentTitle: 'My document' }}
      onChange={(snapshot) => {
        // Store snapshot.json for a lossless round trip.
        // snapshot.html, snapshot.markdown and snapshot.text are also available.
        console.log(snapshot.json);
      }}
      onImageUpload={async (file) => {
        const result = await uploadToYourStorage(file);
        return {
          src: result.url,
          altText: file.name
        };
      }}
    />
  );
}

Loading exported data

The component accepts data, not files:

const markdown: EditorDocument = {
  format: 'markdown',
  data: '# Imported\n\n- One\n- Two'
};

const html: EditorDocument = {
  format: 'html',
  data: '<h1>Imported</h1><p><strong>Safe structured import</strong></p>'
};

const json: EditorDocument = {
  format: 'lexical-json',
  data: previouslySavedLexicalJson
};

<RichTextEditor value={html} />;

For reliable round trips, store Lexical JSON as the canonical value. Markdown and HTML are interoperability formats and may not preserve every custom-node property.

Lexical JSON is treated as untrusted input by default: known link and image nodes are validated, inline text styles are reduced to the same formatting allow-list used for HTML, and unreasonable nesting or node counts are rejected.

Controlled editor

const [document, setDocument] = useState<EditorDocument>({
  format: 'text',
  data: ''
});

<RichTextEditor
  value={document}
  onChange={(snapshot) => {
    setDocument({ format: 'lexical-json', data: snapshot.json });
  }}
/>;

Local-state fingerprints prevent a controlled parent from needlessly replacing the editor state and moving the caret after every keystroke.

Imperative API

editorRef.current?.focus();
editorRef.current?.clear();
editorRef.current?.setDocument({ format: 'markdown', data: '# Replaced' });

const json = editorRef.current?.getDocument('lexical-json');
const html = editorRef.current?.getDocument('html');
const snapshot = editorRef.current?.getSnapshot();

await editorRef.current?.download('json', { fileName: 'draft' });
await editorRef.current?.download('html', { fileName: 'draft' });
await editorRef.current?.download('md', { fileName: 'draft' });
await editorRef.current?.download('txt', { fileName: 'draft' });
await editorRef.current?.download('doc', { fileName: 'draft' });
await editorRef.current?.download('pdf', { documentTitle: 'Draft' });

Export behavior

FormatBehavior
Lexical JSONLossless structured editor state
HTMLSemantic HTML generated from registered Lexical nodes
MarkdownCommon Markdown plus the included image transformer
Plain textText-only content
Word .docLightweight HTML-based Word document, opened by Microsoft Word and compatible office tools
PDFOpens the browser print dialog with A4 print CSS; users select Save as PDF

True binary .docx generation and silent binary PDF generation are intentionally not runtime dependencies. Add them through an application-specific export adapter when required. That keeps the editor package small and avoids shipping document engines to every user merely because one person might click Export twice a quarter.

Toolbar configuration

Use toolbar.items when you want exact control over what is shown, in what order, and how controls are grouped. A nested array becomes one visual toolbar group and a custom object item renders arbitrary React content.

<RichTextEditor
  toolbar={{
    sticky: true,
    items: [
      ['undo', 'redo'],
      'blockType',
      ['bold', 'italic', 'underline'],
      ['bulletList', 'orderedList'],
      ['link', 'table', 'image'],
      {
        id: 'save',
        render: ({ commands }) => <button onClick={() => commands.export('md')}>Save</button>
      }
    ]
  }}
/>

Available toolbar items are fully typed: undo, redo, blockType, fontFamily, fontSize, bold, italic, underline, strike, subscript, superscript, code, quote, textColor, backgroundColor, align, bulletList, orderedList, checkList, outdent, indent, link, table, insertRowAbove, insertRowBelow, insertColumnLeft, insertColumnRight, deleteRow, deleteColumn, deleteTable, mergeCells, unmergeCells, toggleHeaderRow, toggleHeaderColumn, image, horizontalRule, clearFormatting, and export.

toolbar.features remains available when you intentionally want to disable an editor capability. Merely omitting an item from toolbar.items only hides that control; it does not disable table/list/link rendering or importing.

The table button opens a grid picker. Table row/column/delete/header actions are exposed through the typed command facade and the table context menu.

Set toolbar={false} to provide your own UI while continuing to use the exported commands, nodes, serializers, hooks, and imperative API.

Custom link and image UI

The built-in fallback uses window.prompt for links and image URLs. Production applications can replace that with their own dialogs:

<RichTextEditor
  onRequestLink={async (currentUrl) => openLinkDialog(currentUrl)}
  onRequestImage={async () => openMediaLibrary()}
  onImageUpload={async (file) => uploadImage(file)}
/>

onImageUpload also enables image paste and drag-and-drop upload.

HTML import policy

HTML import is conservative by default and can be tightened for a particular application:

<RichTextEditor
  htmlPolicy={{
    allowedProtocols: ['https:', 'mailto:'],
    allowRelativeUrls: false,
    allowDataImages: false
  }}
/>

The same policy is used by controlled values and the imperative setDocument() method.

Use validateLink and validateImage when the application needs stricter URL rules than the package defaults.

Safety model

  • React never renders imported HTML through a raw HTML injection prop.
  • HTML is parsed into a detached document using DOMParser.
  • Scriptable and embedded tags are removed.
  • Event-handler and srcdoc attributes are removed.
  • href and src protocols are restricted.
  • Inline CSS is reduced to a small formatting allow-list.
  • Only registered Lexical nodes are inserted into editor state.
  • A source check fails if common unsafe HTML injection APIs appear under src/.

The sanitizer is intentionally conservative. For hostile multi-tenant content with organisation-specific security requirements, validate content again on the server before persistence or distribution. Browsers remain inventive little chaos machines.

Styling and Tailwind

The package supports three explicit styling modes:

styleMode="default"   // bundled stylesheet, works without Tailwind
styleMode="tailwind"  // Tailwind-friendly tokens and preset/css exports
styleMode="unstyled"  // no visual styling beyond behavior-critical layout

The default mode is deterministic and uses the exported stylesheet from @sclp/react-rte/styles.css. It scopes everything under .sclp-rte, restores list markers explicitly, and includes table borders, selection states, dialogs, menus, and editor surface styling.

The package does not try to discover or read the host application's Tailwind config at runtime. Tailwind generates CSS at build time, so the editor provides a preset and optional CSS entry instead:

// tailwind.config.ts
import { rteTailwindPreset } from '@sclp/react-rte/tailwind';

export default {
  presets: [rteTailwindPreset]
};

Tailwind v4 consumers can also import the explicit CSS entry:

@import '@sclp/react-rte/tailwind.css';

Parent apps remain responsible for compiling Tailwind. The editor only exposes the preset, CSS tokens, and namespaced classes.

For custom presentation, use classNames and Lexical's theme prop. The unstyled mode avoids the bundled visual layer so design-system consumers can fully compose their own surface.

Extending the package

The package exports:

  • ImageNode, $createImageNode, $isImageNode
  • INSERT_IMAGE_COMMAND
  • RichTextEditorProvider, EditorSurface, EditorToolbar
  • useRichTextEditor, useEditorSelection, useEditorFormatState, useEditorHistoryState, useEditorTableState
  • createEditorExtension
  • rteTailwindPreset
  • RTE_MARKDOWN_TRANSFORMERS
  • setEditorDocument, getEditorDocument, createEditorSnapshot with custom serialization options
  • downloadEditorDocument
  • parseSafeHtml
  • all public TypeScript types

Register additional nodes, plugins, themes, toolbar items, commands, and Markdown transformers through extensions or directly on the provider. Custom transformers are placed before the built-in set, so they can handle application-specific syntax first.

<RichTextEditor
  nodes={[MentionNode]}
  extensions={[
    createEditorExtension({
      id: 'mentions',
      nodes: [MentionNode],
      markdownTransformers: [MENTION_TRANSFORMER]
    })
  ]}
  toolbar={false}
/>

Use useRichTextEditor() inside custom controls to reach the current editor, selection state, commands, and import/export helpers without importing raw Lexical internals.

The existing image node demonstrates JSON, DOM, Markdown, and React rendering integration.

Package architecture

src/
├── editor/
│   ├── EditorSurface.tsx
│   ├── RichTextEditorProvider.tsx
│   └── rte-context.ts
├── hooks/
│   ├── use-editor-format-state.ts
│   ├── use-editor-history-state.ts
│   ├── use-editor-selection.ts
│   ├── use-editor-table-state.ts
│   └── use-rich-text-editor.ts
├── commands/
│   └── editor-commands.ts
├── table/
│   └── TableContextMenu.tsx
├── toolbar/
│   ├── EditorToolbar.tsx
│   ├── TablePicker.tsx
│   └── icons.tsx
├── nodes/ImageNode.tsx
├── plugins/
│   ├── DocumentSyncPlugin.tsx
│   ├── EditablePlugin.tsx
│   ├── EditorBridgePlugin.tsx
│   ├── ImageDropPastePlugin.tsx
│   └── ImagePlugin.tsx
├── styles/
│   ├── tailwind.css
│   └── tailwind-preset.ts
├── utils/
│   ├── export.ts
│   ├── html.ts
│   └── serialization.ts
├── RichTextEditor.tsx
├── tailwind.ts
├── config.ts
├── index.ts
├── styles.css
├── theme.ts
└── types.ts

Scope

This package provides the common word-processing surface expected in application forms, document builders, CMS tools, case notes, contracts, and internal portals. It is not a clone of Microsoft Word's collaboration server, tracked changes engine, mail merge, macros, equations, citations, pagination layout engine, or thirty years of historical sediment.

Those can be added as separate plugins without turning the core editor into an unmaintainable monument to feature creep.