denwa-react-shared
Version:
101 lines (82 loc) • 2.96 kB
Markdown
name: text-editor
description: >
Implement rich text editing using BaseTextEditor (Slate.js).
Covers content synchronization (JSON and HTML) and toolbar configuration.
type: framework
library: denwa-react-shared
framework: react
library_version: "1.0.88"
requires:
- session-auth
sources:
- "Denwa799/react-shared:src/shared/ui/text-editor/text-editor.tsx"
# Slate Rich Text Editor
`BaseTextEditor` provides a rich text editing experience based on Slate.js. It handles serialization to HTML and synchronization with external form state through debounced handlers.
## Setup
```tsx
import { BaseTextEditor, BaseTextEditorRefMethods } from 'denwa-react-shared';
const MyForm = () => {
const editorRef = useRef<BaseTextEditorRefMethods>(null);
return (
<BaseTextEditor
boldText="Жирный"
italicText="Курсив"
underlineText="Подчеркнутый"
// ... more labels
onSetContent={(jsonString, lang) => setFieldValue('content', jsonString)}
onSetHtml={(htmlString, lang) => setFieldValue('contentHtml', htmlString)}
onErrorMessage={(msg) => alert(msg)}
/>
);
};
```
## Core Patterns
### Content Initialization
To set the editor value (e.g. when loading an existing entity), use the `setValue` method on the ref. It expects the serialized JSON string found in the database.
```tsx
useEffect(() => {
if (data?.content) {
editorRef.current?.setValue(data.content);
}
}, [data]);
```
### Syncing JSON and HTML
The editor emits events for both the raw Slate JSON structure (for editing) and the rendered HTML (for display/SEO). Always provide both `onSetContent` and `onSetHtml`.
```tsx
<BaseTextEditor
onSetContent={(json) => updateJson(json)}
onSetHtml={(html) => updateHtml(html)}
/>
```
## Common Mistakes
### HIGH Passing raw HTML to setValue
Wrong:
```tsx
editorRef.current?.setValue("<p>Hello world</p>");
```
Correct:
```tsx
editorRef.current?.setValue(JSON.stringify([{ type: 'paragraph', children: [{ text: 'Hello world' }] }]));
```
`setValue` expects a serialized JSON string representing the Slate document structure. Passing raw HTML will cause parsing errors or an empty editor.
Source: src/shared/ui/text-editor/text-editor.tsx:113
### MEDIUM Missing synchronization handlers
Wrong:
```tsx
<BaseTextEditor onSetHtml={(html) => setHtml(html)} />
// Missing onSetContent
```
Correct:
```tsx
<BaseTextEditor
onSetContent={(json) => setJson(json)}
onSetHtml={(html) => setHtml(html)}
/>
```
Failing to provide `onSetContent` prevents the application from saving the internal editor state, making future edits impossible even if the HTML is saved.
Source: src/shared/ui/text-editor/text-editor.tsx:83
### MEDIUM Ignoring the debounce
The editor uses a 1-second debounce (`TIME.seconds.seconds1`) before firing sync events. Do not expect immediate state updates on every keystroke.
Source: src/shared/ui/text-editor/text-editor.tsx:86