Design WYSIWYG Rich Text Editor – Frontend System Design

In this exploration, we are tasked with designing a WYSIWYG (What You See Is What You Get) text editor, a fundamental tool allowing users to edit and create content in a format that closely mirrors its appearance when published. This editor will provide both basic and advanced editing capabilities, catering to a wide range of user needs. MDN’s contenteditable reference is the starting point for most rich text editor implementations.
Clarifying Questions
Before diving into the design, it’s essential to clarify several aspects to ensure the editor meets user expectations and technical feasibility. The following questions will guide our design process:
- Supported Content Types: What range of content types (text, images, videos, GIFs, tables, etc.) should the editor support?
- Media Handling: How will the editor manage media uploads, including size limitations and storage?
- Collaborative Editing: Is collaborative editing required, and how will simultaneous changes be managed?
- Customizability: To what extent should the editor allow custom styles or plugins?
- Export Options: In which formats can users export their content?
- Mentions and Tags: Should the editor support user mentions and tags, and how are they integrated?
- Accessibility: What are the accessibility considerations to ensure the editor is usable by everyone?
- Performance: What performance benchmarks should the editor achieve, especially with large documents or rich media?
- Cross-Browser Compatibility: Which browsers and their versions must be supported?
- Mobile Experience: How will the editor adapt to mobile devices, and are there specific features or considerations for mobile users?
Requirements
Functional Requirements
The WYSIWYG text editor should offer a comprehensive set of features that enable users to create rich content effortlessly. Key functional requirements include:
- Block Style Elements: Support for various block-style elements such as headings, block quotes, lists, figures, and pre-formatted text.
- Inline Style Elements: Capabilities to edit text inline with styles like bold, italic, underline, and text color adjustments.
- Advanced Content: Ability to insert and manage advanced content like images, videos, GIFs, tables, and hyperlinks.
- Interactivity: Features such as mentioning users with the “@” symbol, adding tags, and creating links.
- Editing Features: Standard editing features including undo/redo capabilities, text alignment, and bulleting.
Non-Functional Requirements
To ensure a seamless and accessible user experience, the editor must also meet the following non-functional criteria:
- Cross-Browser Compatibility: The editor should work consistently across major browsers without significant differences in functionality or appearance.
- Accessibility: Adherence to web accessibility standards to ensure the editor is usable by individuals with varying abilities.
- Performance: The editor should remain responsive and efficient, even with complex documents or on lower-end devices.
- Technical Implementation Options: Consideration of various implementation strategies, including:
- Text Area Element: Basic but limited to text-only content, suitable for simpler use cases.
- Controlled Content Editable: Utilizes the
contenteditableattribute for rich text editing with good cross-browser support but requires customization for consistent behavior. - Manual DOM Elements: Offers the highest level of customizability at the cost of reimplementing many native browser features.
Choosing the right technical approach will depend on the specific needs and priorities of the editor, balancing customizability with development complexity and user experience.
High-Level Architecture

The high-level architecture for a WYSIWYG rich text editor can be segmented into several key components, each responsible for distinct aspects of the editor’s functionality. The architecture diagram outlines the separation of concerns and depicts how user interactions are processed and rendered.
Server and GraphQL (GQL) Layer The server forms the backbone of the rich text editor, interacting with the database and file storage systems to save and retrieve content. GraphQL sits as an intermediary between the server and client, providing a flexible API layer that allows the client to request exactly the data it needs. This can include not just the text content but also metadata, such as user permissions, versioning information, and linked multimedia resources.
Model The Model represents the data structure and business logic of the editor. It stores the document state, including text, formatting attributes, and any embedded media. This state can be serialized for storage and transmitted to the server. The Model also exposes methods to manipulate the editor’s content programmatically, enabling operations like insertions, deletions, and formatting changes.
Controller The Controller mediates interactions between the View and the Model. It handles user input, processes commands, and mediates the rendering of the content. The Controller receives events from the View, interprets them, and makes corresponding state changes to the Model. It ensures that the user’s intentions, as expressed through interactions with the View, are accurately reflected in the editor’s data model.
Views The Views are the visual representation of the Model’s data. The Input Field View is the primary interface where users type and format their content. It listens for input events and requests the necessary updates from the Controller. The Popover View serves as an auxiliary interface for additional features like link editing or media insertion, providing a contextual UI that appears in response to specific user actions.
Interactors Interactors (Field Interactor and Popover Interactor) are the conduits through which the Views communicate with the Controller. They listen for user actions, such as keystrokes, mouse clicks, or touch events, and translate them into operations on the Model via the Controller. The Interactors are also responsible for reflecting the state of the Model back onto the Views, ensuring the UI remains in sync with the underlying data.
Data Model
The data model for the editor is a crucial aspect that dictates how text changes are processed and stored. Here is an interface that illustrates the structure and types of the editor’s properties, ensuring a controlled and predictable state.
interface MessageInputProps {
// Interactions
onChange?: (currentTextJSON: string) => void;
onSelect?: (selectedObject: any) => void;
onBlur?: (event: Event) => void;
autoFocus: boolean;
onFetchResults: (page: number, size: number, type: string) => void;
// Styling
placeholder: string;
resultsRender: JSX.Element;
styling: StyleObject;
className: string;
// Network-related
debounceInterval: number;
showEmptyResults: boolean;
cacheTTL: number;
cacheType: 'in network' | 'apollo' | 'local' | 'session' | 'none';
networkTimeoutDuration: number; // in milliseconds
networkRetries: int;
}
Implementation Options
| Option | Pros | Cons |
|---|---|---|
| Use text area input field |
|
|
| Use contentEditable |
|
|
| External Library (Lexical/Draft.js) |
|
|
Why Option 3 is the Best Choice
Considering the needs for a robust, feature-rich, and user-friendly WYSIWYG editor, Option 3, utilizing an external library like Lexical or Draft.js, emerges as the best choice. While this option may introduce a dependency on external code and potentially increase the overall code size, the advantages it offers far outweigh these drawbacks.
Lexical and Draft.js are battle-tested libraries that provide a wide array of features out-of-the-box, including rich text capabilities and support for modern web interactions like @mentions and hashtags. Furthermore, these libraries are designed with accessibility in mind, ensuring that the editor is usable for all individuals, regardless of their abilities.
The extensive APIs offered by these libraries simplify the implementation of complex editing features, while their compatibility across different platforms and browsers ensures a consistent user experience. Although customization might be somewhat limited compared to building a solution from scratch, the trade-off is a more reliable and maintainable codebase that leverages the collective knowledge and expertise of the developer community.
Optimizing a WYSIWYG Rich Text Editor
Debouncing User Input
To enhance performance and reduce unnecessary load, user input can be debounced. This technique involves waiting for a certain amount of idle time before processing input, thereby limiting the rate at which events like keystrokes trigger updates in the editor state or re-rendering of the component.
Implementing debouncing ensures that the system is not overwhelmed by the high frequency of user actions, which is particularly beneficial when these actions lead to complex processing tasks or network requests, like fetching suggestions for @mentions or updating the live preview of the content.
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = function() {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
// Usage with a function that updates the editor state
const debouncedUpdate = debounce(updateEditorState, 250);
Caching Strategy
Caching is a crucial optimization strategy for a WYSIWYG editor. It allows us to store previously retrieved or computed data, such as user input, images, or document snapshots, so that future requests for the same data can be served faster.
The editor can implement a caching layer that stores the state of the editor or parts of it in memory. It can also persist data locally on the client’s machine using browser caching mechanisms like LocalStorage, IndexedDB, or Service Workers, which is particularly useful for offline capabilities and to quickly restore the state when the user returns to the editor.
// Example of a simple in-memory cache implementation
class EditorCache {
constructor() {
this.cache = {};
}
get(key) {
return this.cache[key];
}
set(key, value) {
this.cache[key] = value;
}
}
const cache = new EditorCache();
// Store and retrieve the editor state
cache.set('editorState', editorState);
const cachedState = cache.get('editorState');
The caching strategy also involves setting a Time To Live (TTL) for cached items and implementing an eviction policy, such as Least Recently Used (LRU), to manage memory efficiently.
Conclusion: Building a Rich Text Editor
In crafting an efficient WYSIWYG rich text editor, the careful application of debouncing and caching strategies is essential. Debouncing smooths out the event-driven nature of user interactions, providing a performant and responsive editing experience without overloading the system with rapid-fire updates. Meanwhile, caching harnesses the ability to swiftly recall and reuse previously accessed data, accelerating load times and fostering a seamless user experience, even in offline scenarios.
These optimization techniques, when applied judiciously, ensure that the editor not only meets the functional requirements of modern web applications but does so with an eye towards scalability, resilience, and user satisfaction. The balance between real-time responsiveness and system performance is delicate, and with these strategies, we tip the scales in favor of an editor that is both powerful and a pleasure to use.
