WYSIWYG Editor Development for CMS
You build a custom WYSIWYG editor when no ready-made tool covers your project's specifics: non-standard blocks, strict HTML output requirements, deep CMS backend integration. This is serious engineering—from data model design to drag-and-drop block reordering. Minimum MVP takes 3–4 weeks, full editor with custom blocks and history—8–12 weeks.
Choosing Base Technology
Building a browser contenteditable-editor from scratch in 2024 is a bad idea. Browser quirks, IME input, text selection—all solved in ready engines. Real choice is between:
- ProseMirror — low-level, maximum flexibility, steep learning curve. Foundation for Tiptap, Atlassian Editor, NY Times editor
- Slate.js — React-native, JSON-tree data model, good for structured content
- Lexical (Meta) — performant, good concurrent mode support, actively maintained
For block editors (like Notion) — separate story: blocks are independent, type-switched, no nested rich text. Build on custom architecture without browser contenteditable.
Data Model
Editor must work with clearly defined content schema. Two approaches:
Flat JSON (Editor.js-style):
{
"blocks": [
{ "id": "abc123", "type": "header", "data": { "text": "Heading", "level": 2 } },
{ "id": "def456", "type": "paragraph", "data": { "text": "Paragraph text" } },
{ "id": "ghi789", "type": "image", "data": { "url": "/uploads/photo.jpg", "caption": "Caption" } }
],
"version": "2.28.0"
}
Tree (ProseMirror/Tiptap-style):
{
"type": "doc",
"content": [
{
"type": "heading",
"attrs": { "level": 2 },
"content": [{ "type": "text", "text": "Heading" }]
},
{
"type": "paragraph",
"content": [
{ "type": "text", "text": "Normal " },
{ "type": "text", "marks": [{ "type": "bold" }], "text": "bold" },
{ "type": "text", "text": " text" }
]
}
]
}
Flat JSON is simpler for storage and APIs. Tree is better for complex formatting and transformations.
In PostgreSQL, store in jsonb:
ALTER TABLE pages ADD COLUMN content jsonb NOT NULL DEFAULT '{}';
CREATE INDEX idx_pages_content_gin ON pages USING GIN (content);
GIN index enables full-text search in editor content via jsonb_path_query.
Block Architecture
Each block type is separate React component with two modes: display and edit.
interface BlockPlugin<T = Record<string, unknown>> {
type: string;
label: string;
icon: React.ReactNode;
defaultData: T;
render: (data: T, ctx: RenderContext) => React.ReactNode;
edit: (data: T, onChange: (data: T) => void) => React.ReactNode;
validate?: (data: T) => ValidationError[];
toHTML?: (data: T) => string;
}
// Block registration
const registry = new BlockRegistry();
registry.register(ParagraphBlock);
registry.register(HeadingBlock);
registry.register(ImageBlock);
registry.register(VideoEmbedBlock);
registry.register(CodeBlock);
registry.register(TableBlock);
registry.register(CalloutBlock);
Block registry allows adding new types without core editor changes—plugin architecture.
Toolbar and Formatting
For rich text blocks, toolbar should appear contextually—on text selection. Fixed toolbar is excessive and intrusive.
const FloatingToolbar: React.FC = () => {
const { selection, commands } = useEditorState();
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!selection || selection.collapsed) {
ref.current!.style.display = 'none';
return;
}
const rect = getSelectionBoundingRect();
ref.current!.style.display = 'flex';
ref.current!.style.top = `${rect.top - 44}px`;
ref.current!.style.left = `${rect.left + rect.width / 2}px`;
ref.current!.style.transform = 'translateX(-50%)';
}, [selection]);
return (
<div ref={ref} className="floating-toolbar">
<ToolbarButton icon={<Bold />} action={() => commands.toggleMark('bold')} />
<ToolbarButton icon={<Italic />} action={() => commands.toggleMark('italic')} />
<ToolbarButton icon={<Link />} action={() => commands.setLink()} />
</div>
);
};
Slash Commands
De facto standard for block editors — typing / triggers block insertion menu. Implementation:
const useSlashMenu = (editor: Editor) => {
const [query, setQuery] = useState('');
const [visible, setVisible] = useState(false);
editor.on('keydown', (e) => {
if (e.key === '/') {
setVisible(true);
setQuery('');
}
});
editor.on('keyup', () => {
if (visible) {
const currentText = editor.getCurrentLineText();
if (currentText.startsWith('/')) {
setQuery(currentText.slice(1));
} else {
setVisible(false);
}
}
});
const filteredBlocks = registry.all().filter(b =>
b.label.toLowerCase().includes(query.toLowerCase())
);
return { visible, filteredBlocks, setVisible };
};
Drag-and-Drop Block Reordering
Blocks should be draggable. Library @dnd-kit/core is best for React:
import { DndContext, closestCenter, DragEndEvent } from '@dnd-kit/core';
import { SortableContext, verticalListSortingStrategy, arrayMove } from '@dnd-kit/sortable';
const BlockEditor: React.FC = ({ blocks, onChange }) => {
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (over && active.id !== over.id) {
const oldIndex = blocks.findIndex(b => b.id === active.id);
const newIndex = blocks.findIndex(b => b.id === over.id);
onChange(arrayMove(blocks, oldIndex, newIndex));
}
};
return (
<DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={blocks.map(b => b.id)} strategy={verticalListSortingStrategy}>
{blocks.map(block => (
<SortableBlock key={block.id} block={block} />
))}
</SortableContext>
</DndContext>
);
};
Change History (Undo/Redo)
Command pattern + history stack:
class EditorHistory {
private undoStack: EditorState[] = [];
private redoStack: EditorState[] = [];
private maxSize = 100;
push(state: EditorState) {
this.undoStack.push(structuredClone(state));
if (this.undoStack.length > this.maxSize) {
this.undoStack.shift();
}
this.redoStack = []; // Reset redo on new action
}
undo(current: EditorState): EditorState | null {
if (this.undoStack.length === 0) return null;
this.redoStack.push(structuredClone(current));
return this.undoStack.pop()!;
}
redo(current: EditorState): EditorState | null {
if (this.redoStack.length === 0) return null;
this.undoStack.push(structuredClone(current));
return this.redoStack.pop()!;
}
}
For large documents, structuredClone is expensive—use immutable data structures (Immer, immutable.js) or delta patches.
Autosave
Editor should save changes without user intervention:
const useAutoSave = (content: BlockData[], pageId: number) => {
const lastSaved = useRef<string>('');
const timerRef = useRef<ReturnType<typeof setTimeout>>();
useEffect(() => {
const serialized = JSON.stringify(content);
if (serialized === lastSaved.current) return;
clearTimeout(timerRef.current);
timerRef.current = setTimeout(async () => {
await api.patch(`/pages/${pageId}`, { content });
lastSaved.current = serialized;
setStatus('saved');
}, 2000); // 2 seconds debounce
return () => clearTimeout(timerRef.current);
}, [content, pageId]);
};
Save status is displayed in header: "Saved", "Saving...", "Unsaved changes".
Frontend Rendering
Editor's JSON content needs rendering on public site. Two options: SSR-render via React components or server-side HTML generation.
// PHP block renderer (Laravel)
class BlockRenderer
{
protected array $renderers = [];
public function register(string $type, callable $renderer): void
{
$this->renderers[$type] = $renderer;
}
public function render(array $blocks): string
{
return collect($blocks)
->map(fn($block) => ($this->renderers[$block['type']] ?? fn() => '')($block['data']))
->implode("\n");
}
}
// Renderer registration
$renderer->register('paragraph', fn($data) =>
'<p>' . e($data['text']) . '</p>'
);
$renderer->register('image', fn($data) =>
'<figure><img src="' . e($data['url']) . '" alt="' . e($data['caption']) . '">
<figcaption>' . e($data['caption']) . '</figcaption></figure>'
);
Working with Media
Editor integrates with CMS media library. Inserting image opens modal with uploaded files—no page transition. Upload via drag-and-drop directly into block:
const handleImageDrop = async (file: File) => {
const formData = new FormData();
formData.append('file', file);
const { data } = await api.post('/media', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (e) => setProgress(e.loaded / e.total! * 100),
});
insertBlock({ type: 'image', data: { url: data.url, caption: '' } });
};
Performance with Large Documents
For articles with dozens of images and hundreds of blocks, use virtualization:
- Render only visible blocks + 5–10 block buffer above/below viewport
-
react-windowor@tanstack/virtual— ready solutions - Blocks outside viewport replaced with placeholder preserving height
Custom editor development is justified when project has specific requirements ready solutions don't cover without extensive override.







