WYSIWYG Editor Development for CMS

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1212
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    852
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_bitrix-bitrix-24-1c_fixper_448_0.png
    Website development for FIXPER company
    815

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-window or @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.