Building a feature-rich React TypeScript textbox with the specified functionalities involves careful planning and leveraging lightweight libraries where necessary. Below is a comprehensive guide to help you implement each feature effectively:
1. Project Setup
Technologies & Libraries:
- React & TypeScript: Core framework and language.
- React Hooks: For state and side-effect management.
react-contenteditable: Simplifies working with contenteditable elements.
downshift: Lightweight library for autocomplete dropdowns.
marked or markdown-it: For Markdown parsing and rendering.
- CSS Modules or Styled Components: For scoped and maintainable styling.
Installation:
npx create-react-app rich-textbox --template typescript
cd rich-textbox
npm install react-contenteditable downshift marked
2. Component Structure
Create a RichTextbox component with the following structure:
// RichTextbox.tsx
import React, { useState, useRef, KeyboardEvent } from 'react';
import ContentEditable from 'react-contenteditable';
import Downshift from 'downshift';
import marked from 'marked';
import styles from './RichTextbox.module.css';
const commands = ['/h1', '/h2', '/h3', '/link', '/bold', '/italic'];
const RichTextbox: React.FC = () => {
// State to manage content and command input
const [html, setHtml] = useState<string>('');
const [markdown, setMarkdown] = useState<string>('');
const [command, setCommand] = useState<string | null>(null);
const contentEditableRef = useRef<ContentEditable>(null);
// Handlers and rendering logic will go here
return (
<div className={styles.container}>
{/* ContentEditable and Downshift components */}
</div>
);
};
export default RichTextbox;
3. Handling contenteditable
Use react-contenteditable to handle the textbox, allowing inline editing and real-time styling.
<ContentEditable
innerRef={contentEditableRef}
html={html}
disabled={false}
onChange={handleChange}
onKeyDown={handleKeyDown}
className={styles.textbox}
data-placeholder="Type here..."
/>
Change Handler:
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newHtml = e.target.value;
setHtml(newHtml);
setMarkdown(marked.parse(newHtml));
const cursorPosition = getCaretPosition(contentEditableRef.current?.props.innerRef.current);
const textBeforeCursor = getTextBeforeCursor(newHtml, cursorPosition);
const match = textBeforeCursor.match(/\/(\w*)$/);
if (match) {
setCommand(match[1]);
} else {
setCommand(null);
}
};
Utility Functions:
Implement functions like getCaretPosition and getTextBeforeCursor to manage cursor positions and extract current command input.
4. Implementing Slash Commands with Autocomplete
Use downshift to create an accessible dropdown for command suggestions.
<Downshift
onSelect={selection => handleCommandSelect(selection)}
inputValue={command || ''}
items={commands.filter(cmd => cmd.startsWith(`/${command || ''}`))}
>
{({
getMenuProps,
getInputProps,
getItemProps,
isOpen,
highlightedIndex,
}) => (
isOpen && (
<ul {...getMenuProps()} className={styles.dropdown}>
{commands.filter(cmd => cmd.startsWith(`/${command || ''}`)).map((item, index) => (
<li
{...getItemProps({ key: item, index, item })}
className={highlightedIndex === index ? styles.highlighted : ''}
>
{item}
</li>
))}
</ul>
)
)}
</Downshift>
Command Selection Handler:
const handleCommandSelect = (selection: string) => {
if (!selection) return;
// Replace the command text with corresponding Markdown or HTML
const updatedHtml = applyCommand(html, selection);
setHtml(updatedHtml);
setMarkdown(marked.parse(updatedHtml));
setCommand(null);
};
Applying Commands:
const applyCommand = (currentHtml: string, command: string): string => {
// Logic to transform the currentHtml based on the command
// For example, /h1 converts the current line to <h1>...</h1>
// This is a simplified example:
switch (command) {
case '/h1':
return currentHtml.replace(/\/h1$/, '# ');
case '/h2':
return currentHtml.replace(/\/h2$/, '## ');
case '/h3':
return currentHtml.replace(/\/h3$/, '### ');
case '/bold':
return currentHtml.replace(/\/bold$/, '**bold** ');
case '/italic':
return currentHtml.replace(/\/italic$/, '_italic_ ');
// Add more cases as needed
default:
return currentHtml;
}
};
5. Keyboard & Mouse Support
Ensure users can navigate the dropdown using arrow keys and select with Enter or mouse clicks.
- Downshift inherently manages keyboard navigation, selection via Enter, and mouse interactions.
- Ensure
handleKeyDown handles Escape to close the dropdown and other relevant keys.
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
setCommand(null);
}
// Add more key handling as needed
};
6. Per-Line Commands
To support commands on each line independently:
- Parsing Lines: Split the HTML content into lines and manage command state per line.
- Command Detection: When the cursor is on a new line, detect if a
/ is typed and activate the dropdown accordingly.
Example Approach:
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newHtml = e.target.value;
setHtml(newHtml);
setMarkdown(marked.parse(newHtml));
const cursorPosition = getCaretPosition(contentEditableRef.current?.props.innerRef.current);
const textBeforeCursor = getTextBeforeCursor(newHtml, cursorPosition);
const lines = textBeforeCursor.split('\n');
const currentLine = lines[lines.length - 1];
const match = currentLine.match(/\/(\w*)$/);
if (match) {
setCommand(match[1]);
} else {
setCommand(null);
}
};
7. Native Markdown Support with WYSIWYG Inline Editing
Real-Time Rendering:
- Use
marked to convert Markdown to HTML and display it within the contenteditable element.
- Update the
html state as the user types to reflect real-time changes.
Example:
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newMarkdown = e.target.value;
setMarkdown(newMarkdown);
setHtml(marked.parse(newMarkdown));
// Handle commands as before
};
Ensuring WYSIWYG Experience:
- Style the
contenteditable element to display HTML elements (like <b>, <i>, <h1>, etc.) appropriately.
- Consider sanitizing HTML to prevent XSS attacks using libraries like
dompurify.
npm install dompurify
import DOMPurify from 'dompurify';
// In handleChange
setHtml(DOMPurify.sanitize(marked.parse(newMarkdown)));
8. Styling & Performance
Minimal Styling:
- Focus on supporting bullet lists, headings (H1, H2, H3), bold, and italic text.
- Use CSS to style these elements within the
contenteditable area.
Example CSS:
/* RichTextbox.module.css */
.container {
position: relative;
width: 100%;
max-width: 600px;
margin: auto;
}
.textbox {
width: 100%;
min-height: 200px;
border: 1px solid #ccc;
padding: 10px;
overflow: auto;
outline: none;
}
.dropdown {
position: absolute;
top: 100%;
left: 0;
background: white;
border: 1px solid #ddd;
width: 100%;
max-height: 150px;
overflow-y: auto;
z-index: 1000;
}
.dropdown li {
padding: 8px 12px;
cursor: pointer;
}
.dropdown li:hover,
.highlighted {
background-color: #f0f0f0;
}
Performance Optimization:
- Debounce Input Handling: Prevent excessive re-renders by debouncing the
handleChange function.
- Memoize Components: Use
React.memo for components like dropdown items to avoid unnecessary updates.
- Efficient State Management: Keep state updates minimal and localized.
Debounce Example:
import { useCallback } from 'react';
import debounce from 'lodash.debounce';
const debouncedHandleChange = useCallback(
debounce((e: React.ChangeEvent<HTMLInputElement>) => {
// handle change logic
}, 300),
[]
);
9. CSS Styling and Accessibility
Accessible Dropdown:
- Ensure the dropdown menu is navigable via keyboard (handled by
downshift).
- Use ARIA attributes for better screen reader support.
Example ARIA Attributes:
<ul {...getMenuProps()} role="listbox" className={styles.dropdown}>
{items.map((item, index) => (
<li
{...getItemProps({ key: item, index, item })}
role="option"
aria-selected={highlightedIndex === index}
className={highlightedIndex === index ? styles.highlighted : ''}
>
{item}
</li>
))}
</ul>
Screen Reader Labels:
- Use
aria-label or aria-labelledby for the contenteditable element.
<ContentEditable
// ...other props
aria-label="Rich text editor with slash commands"
/>
Focus Management:
- Manage focus transitions when the dropdown opens/closes to ensure seamless keyboard navigation.
10. Final Integration and Testing
- Integrate All Parts: Combine the contenteditable, command detection, dropdown, and markdown rendering seamlessly.
- Testing: Ensure all features work as expected across different browsers and devices.
- Test keyboard navigation, mouse interactions, and accessibility features.
- Validate Markdown rendering and command application.
- Performance Profiling: Use React DevTools and browser performance tools to identify and optimize any bottlenecks.
Complete Example
Here’s a simplified version integrating the key parts mentioned above.
// RichTextbox.tsx
import React, { useState, useRef, KeyboardEvent, useCallback } from 'react';
import ContentEditable from 'react-contenteditable';
import Downshift from 'downshift';
import marked from 'marked';
import DOMPurify from 'dompurify';
import styles from './RichTextbox.module.css';
import debounce from 'lodash.debounce';
const commands = ['/h1', '/h2', '/h3', '/link', '/bold', '/italic'];
const RichTextbox: React.FC = () => {
const [html, setHtml] = useState<string>('');
const [markdown, setMarkdown] = useState<string>('');
const [command, setCommand] = useState<string | null>(null);
const contentEditableRef = useRef<HTMLDivElement>(null);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newHtml = e.target.value;
setHtml(newHtml);
const cleanHtml = DOMPurify.sanitize(marked.parse(newHtml));
setHtml(cleanHtml);
setMarkdown(marked.parse(newHtml));
const cursorPosition = getCaretPosition(contentEditableRef.current);
const textBeforeCursor = getTextBeforeCursor(cleanHtml, cursorPosition);
const match = textBeforeCursor.match(/\/(\w*)$/);
if (match) {
setCommand(match[1]);
} else {
setCommand(null);
}
};
const debouncedHandleChange = useCallback(debounce(handleChange, 100), []);
const handleCommandSelect = (selection: string) => {
if (!selection) return;
let updatedHtml = html;
switch (selection) {
case '/h1':
updatedHtml = updatedHtml.replace(/\/h1$/, '# ');
break;
case '/h2':
updatedHtml = updatedHtml.replace(/\/h2$/, '## ');
break;
case '/h3':
updatedHtml = updatedHtml.replace(/\/h3$/, '### ');
break;
case '/bold':
updatedHtml = updatedHtml.replace(/\/bold$/, '**bold** ');
break;
case '/italic':
updatedHtml = updatedHtml.replace(/\/italic$/, '_italic_ ');
break;
// Add more commands as needed
default:
break;
}
setHtml(updatedHtml);
setMarkdown(marked.parse(updatedHtml));
setCommand(null);
};
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
setCommand(null);
}
};
return (
<div className={styles.container}>
<Downshift
onSelect={handleCommandSelect}
inputValue={command || ''}
items={commands.filter(cmd => cmd.startsWith(`/${command || ''}`))}
isOpen={Boolean(command)}
>
{({
getMenuProps,
getItemProps,
isOpen,
highlightedIndex,
}) => (
<>
<ContentEditable
innerRef={contentEditableRef}
html={html}
disabled={false}
onChange={debouncedHandleChange}
onKeyDown={handleKeyDown}
className={styles.textbox}
data-placeholder="Type here..."
aria-label="Rich text editor with slash commands"
/>
{isOpen && (
<ul {...getMenuProps()} className={styles.dropdown} role="listbox">
{commands
.filter(cmd => cmd.startsWith(`/${command || ''}`))
.map((item, index) => (
<li
{...getItemProps({ key: item, index, item })}
role="option"
aria-selected={highlightedIndex === index}
className={highlightedIndex === index ? styles.highlighted : ''}
>
{item}
</li>
))}
</ul>
)}
</>
)}
</Downshift>
</div>
);
};
// Utility functions (simplified for brevity)
const getCaretPosition = (element: HTMLDivElement | null): number => {
if (!element) return 0;
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) return 0;
const range = selection.getRangeAt(0);
const preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
return preCaretRange.toString().length;
};
const getTextBeforeCursor = (html: string, position: number): string => {
return html.substring(0, position);
};
export default RichTextbox;
Conclusion
By following this structured approach, you can build a robust React TypeScript textbox with slash commands, autocomplete, per-line command support, native Markdown handling, real-time WYSIWYG editing, and accessible, responsive UI. Leveraging lightweight libraries like react-contenteditable, downshift, and marked helps maintain performance and simplicity without the overhead of heavier solutions like Slate.js.
Additional Recommendations
- Testing: Implement unit and integration tests using tools like Jest and React Testing Library to ensure all functionalities work correctly.
- Accessibility Audits: Use tools like Lighthouse or aXe to audit and improve accessibility.
- Responsive Design: Ensure the component is responsive across different screen sizes by testing and refining CSS as needed.
- Further Enhancements: Depending on requirements, consider adding more Markdown features or extending command functionalities.