### Install mui-tiptap with yarn Source: https://github.com/sjdemartini/mui-tiptap/blob/main/README.md Use this command to install the mui-tiptap package using yarn. ```shell yarn add mui-tiptap ``` -------------------------------- ### Install MUI Tiptap and Dependencies Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/README.md Install the necessary packages for MUI Tiptap, Material UI, and Tiptap core. ```bash npm install mui-tiptap @mui/material @tiptap/core @tiptap/react @tiptap/starter-kit ``` -------------------------------- ### Complete RichTextEditor Example with Menu Controls Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/MenuControls.md This example demonstrates a full RichTextEditor setup, including various menu controls within a MenuControlsContainer. Ensure all necessary extensions and components are imported. ```typescript import { RichTextEditor, MenuControlsContainer, MenuSelectHeading, MenuDivider, MenuButtonBold, MenuButtonItalic, MenuButtonUnderline, MenuSelectFontSize, MenuButtonTextColor, MenuButtonUndo, MenuButtonRedo, } from "mui-tiptap"; import StarterKit from "@tiptap/starter-kit"; import { TextStyle } from "@tiptap/extension-text-style"; import { Color } from "@tiptap/extension-color"; import { FontSize } from "mui-tiptap"; function MyEditor() { return ( ( )} /> ); } ``` -------------------------------- ### Basic RichTextEditor Example Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/RichTextEditor.md Demonstrates a basic RichTextEditor setup with common formatting controls like bold, italic, and headings. Ensure `StarterKit` and necessary menu components are imported. ```typescript import { RichTextEditor, MenuButtonBold, MenuButtonItalic, MenuControlsContainer, MenuSelectHeading, MenuDivider } from "mui-tiptap"; import StarterKit from "@tiptap/starter-kit"; import { useRef } from "react"; function BasicEditor() { const rteRef = useRef(null); return ( ( )} /> ); } ``` -------------------------------- ### Install mui-tiptap with npm Source: https://github.com/sjdemartini/mui-tiptap/blob/main/README.md Use this command to install the mui-tiptap package using npm. ```shell npm install mui-tiptap ``` -------------------------------- ### Example Menu Bar Configuration Source: https://github.com/sjdemartini/mui-tiptap/blob/main/README.md An example of how to define menu controls for a RichTextEditor or RichTextField. ```APIDOC ## Example Menu Bar Configuration ### Description Demonstrates a typical setup for defining editor controls. ### Code Example ```tsx {/* Add more controls of your choosing here */} ``` ``` -------------------------------- ### Basic Rich Text Editor Setup Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/INDEX.md Demonstrates the basic setup of the RichTextEditor component with essential extensions and a simple bold button. ```typescript import { RichTextEditor, MenuControlsContainer, MenuButtonBold } from "mui-tiptap"; import StarterKit from "@tiptap/starter-kit"; export default function App() { return ( ( )} /> ); } ``` -------------------------------- ### RichTextEditorProvider Usage Example Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/RichTextEditorProvider.md An example demonstrating how to use the RichTextEditorProvider with the useEditor hook and other mui-tiptap components. ```APIDOC ## Usage Examples ### With useEditor Hook ```typescript import { useEditor } from "@tiptap/react"; import { RichTextEditorProvider, RichTextField, MenuButtonBold } from "mui-tiptap"; import StarterKit from "@tiptap/starter-kit"; function MyEditor() { const editor = useEditor({ extensions: [StarterKit], content: "

Hello

", shouldRerenderOnTransaction: true, }); return ( } /> ); } ``` ``` -------------------------------- ### Complete Utility Functions Example Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/Utilities.md Demonstrates the usage of various mui-tiptap utility functions including formatting URLs, inserting images, color conversion, slugification, truncation, and shortcut key descriptions. This example shows practical application in an editor context. ```typescript import { insertImages, formatHref, colorToHex, slugify, truncateMiddle, isMac, getShortcutKeysDescription, } from "mui-tiptap"; function MyEditor() { const handleAddLink = () => { const url = prompt("Enter URL:"); if (url) { const formatted = formatHref(url); editor.commands.setLink({ href: formatted }); } }; const handleAddImage = async (files: File[]) => { const urls = await uploadFiles(files); insertImages({ images: urls.map(src => ({ src })), editor }); return urls; }; return ( <> ); } ``` -------------------------------- ### Basic Rich Text Editor Example Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/README.md A simple example demonstrating how to use the RichTextEditor component with basic extensions and content. ```typescript import { RichTextEditor } from "mui-tiptap"; import StarterKit from "@tiptap/starter-kit"; export default function App() { return ( ( )} /> ); } ``` -------------------------------- ### Install mui-tiptap peer dependencies with npm Source: https://github.com/sjdemartini/mui-tiptap/blob/main/README.md Install necessary peer dependencies for mui-tiptap if they are not automatically handled or already present in your project. ```shell npm install @mui/material @mui/icons-material @emotion/react @emotion/styled @tiptap/react @tiptap/extension-heading @tiptap/extension-image @tiptap/extension-table @tiptap/pm @tiptap/core ``` -------------------------------- ### Install mui-tiptap peer dependencies with yarn Source: https://github.com/sjdemartini/mui-tiptap/blob/main/README.md Install necessary peer dependencies for mui-tiptap using yarn if they are not automatically handled or already present in your project. ```shell yarn add @mui/material @mui/icons-material @emotion/react @emotion/styled @tiptap/react @tiptap/extension-heading @tiptap/extension-image @tiptap/extension-table @tiptap/pm @tiptap/core ``` -------------------------------- ### MenuButton Usage Example Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/MenuControls.md Example of using the MenuButton component for a bold text formatting button. It includes tooltip, shortcut keys, icon, click handler, and selection state. ```typescript editor.commands.toggleBold()} selected={editor.isActive("bold")} /> ``` -------------------------------- ### Basic RichTextContent Usage Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/RichTextContent.md Demonstrates the basic setup for RichTextContent within a RichTextEditorProvider. Ensure the editor instance is passed to the provider. ```typescript import { RichTextContent } from "mui-tiptap"; import { useEditor } from "@tiptap/react"; import StarterKit from "@tiptap/starter-kit"; function MyEditor() { const editor = useEditor({ extensions: [StarterKit], content: "

Hello

", shouldRerenderOnTransaction: true, }); return ( ); } ``` -------------------------------- ### ControlledBubbleMenu Usage Example Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/BubbleMenus.md Demonstrates how to use the ControlledBubbleMenu component. It requires a Tiptap editor instance and manages its open state. Configure placement and fallback placements for optimal positioning. ```typescript import { ControlledBubbleMenu } from "mui-tiptap"; import { useState } from "react"; function MyCustomMenu() { const editor = useRichTextEditorContext(); const [isOpen, setIsOpen] = useState(false); return ( setIsOpen(false)} > ); } ``` -------------------------------- ### LinkBubbleMenu Localization Example Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/BubbleMenus.md Shows how to override default text labels for buttons and input fields within the LinkBubbleMenu for localization purposes. This example uses Chinese labels. ```typescript ``` -------------------------------- ### Create SVG Icon Source: https://github.com/sjdemartini/mui-tiptap/blob/main/CONTRIBUTING.md Example of creating a new SVG icon component using `createSvgIcon` from `@mui/material`. Pass the SVG path data as an argument. ```tsx import { createSvgIcon } from "@mui/material"; // Your SVG path data const pathData = "M10 20v-6h4v6h5v-8h3L11 3 2 12h3v8z"; const MyIcon = createSvgIcon(pathData, "MyIcon"); export default MyIcon; ``` -------------------------------- ### Security Example for ResizableImage Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/configuration.md Implement a security measure for the ResizableImage extension by whitelisting specific domains for image sources. This prevents the insertion of images from untrusted origins. ```typescript // Whitelist specific domains const allowedDomains = ["cdn.example.com", "images.example.com"]; ResizableImage.configure({ isAllowedImgSrc: (src) => { if (!src) return false; try { const url = new URL(src); return allowedDomains.includes(url.hostname); } catch { return false; } }, }) ``` -------------------------------- ### Rendering Content from Different Sources Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/RichTextReadOnly.md This example demonstrates how to fetch content from different sources (API, Markdown, or direct HTML) and render it using the RichTextReadOnly component. It utilizes React's `useState` and `useEffect` hooks to manage and update the content. ```typescript function ContentRenderer({ source, id }) { const [content, setContent] = useState(""); useEffect(() => { if (source === "api") { fetch(`/api/posts/${id}`).then(r => r.json()).then(d => setContent(d.html)); } else if (source === "markdown") { markdownToHtml(id).then(setContent); } else { setContent(id); // Direct HTML } }, [source, id]); return ( ); } ``` -------------------------------- ### Basic Usage with useEditor Hook Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/RichTextEditorProvider.md Demonstrates how to initialize a Tiptap editor using the useEditor hook and provide it to the RichTextEditorProvider. This setup makes the editor instance available to child components like RichTextField. ```typescript import { useEditor } from "@tiptap/react"; import { RichTextEditorProvider, RichTextField, MenuButtonBold } from "mui-tiptap"; import StarterKit from "@tiptap/starter-kit"; function MyEditor() { const editor = useEditor({ extensions: [StarterKit], content: "

Hello

", shouldRerenderOnTransaction: true, }); return ( } /> ); } ``` -------------------------------- ### Full Featured Rich Text Editor Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/INDEX.md Illustrates a comprehensive setup for the RichTextEditor, including a wide array of extensions and menu controls for a feature-rich editing experience. ```typescript ( )> {() => ( <> )} ``` -------------------------------- ### Import MUI Tiptap Utilities Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/INDEX.md Import utility functions for common tasks like inserting images, formatting links, converting colors, slugifying text, and checking the operating system. ```typescript import { insertImages, formatHref, colorToHex, slugify, isMac, } from "mui-tiptap"; ``` -------------------------------- ### Get Attributes for Each Selected Item Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/Utilities.md Get attributes for all selected marks and nodes, organized by type. This is useful for determining the overall state of the selection to control UI elements. ```typescript const attrs = getAttributesForEachSelected(); // { // bold: [{}], // mark applied to selection // link: [{ href: "..." }], // heading: [{ level: 2 }], // } ``` -------------------------------- ### Style Customization with MUI Conventions Source: https://github.com/sjdemartini/mui-tiptap/blob/main/README.md Explains how to customize mui-tiptap component styles using standard MUI practices. ```APIDOC ## Style Customization ### Description Override styles in several different ways, following standard [MUI conventions](https://mui.com/material-ui/customization/how-to-customize/). ### Methods 1. **`sx` Prop**: Use the [`sx` prop](https://mui.com/system/getting-started/the-sx-prop/) with any mui-tiptap component. ```tsx ``` 2. **Class Names**: Use `className` and/or `classes` props. `className` applies a class to the root, and `classes` allows passing class names for various slots and states. ```css .custom-border { border-color: #222; } .custom-content { background-color: #eee; } ``` ```tsx // or ``` 3. **Theme Overrides**: Use theme overrides (https://mui.com/material-ui/customization/theme-components/). ```ts import { createTheme } from "@mui/material/styles"; const theme = createTheme({ components: { // Override the behavior for the mui-tiptap `FieldContainer` "MuiTiptap-FieldContainer": { defaultProps: { // If no `variant` value is set, use "standard" variant: "standard", }, styleOverrides: { // Apply this background color to the `root` slot root: { backgroundColor: "#222" }, // Apply this border style to the `notchedOutline` slot notchedOutline: { borderStyle: "dashed" }, }, variants: [ // When the `disabled` prop is `true`, show a red outline { props: { disabled: true }, style: { outline: "1px solid red" }, }, ], }, }, }); ``` 4. **Utility Class Names**: Apply styles based on utility class names of mui-tiptap components. Import helper objects from mui-tiptap to avoid hard-coding. ```ts import { richTextFieldClasses } from "mui-tiptap"; // Example usage: // Accessing the content class: richTextFieldClasses.content ``` ``` -------------------------------- ### Basic RichTextReadOnly Usage Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/RichTextReadOnly.md Demonstrates the basic usage of RichTextReadOnly with extensions and HTML content. Ensure necessary extensions like StarterKit are imported. ```typescript import { RichTextReadOnly } from "mui-tiptap"; import StarterKit from "@tiptap/starter-kit"; function DisplayContent() { return ( ); } ``` -------------------------------- ### truncateMiddle Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/Utilities.md Truncates a string by removing characters from the middle, preserving the start and end, and inserting '...'. ```APIDOC ## truncateMiddle ### Description Truncate a long string by removing characters from the middle, keeping start and end. ### Signature ```typescript function truncateMiddle(text: string, maxLength: number): string ``` ### Parameters #### Path Parameters - **text** (string) - Required - Text to truncate. - **maxLength** (number) - Required - Maximum length of result. ### Returns Truncated string with "..." in the middle ### Usage Examples ```typescript truncateMiddle("Hello World", 8); // "He...rld" truncateMiddle("short", 10); // "short" (unchanged) truncateMiddle("VeryLongFileName", 10); // "Very...ame" ``` ### Use Case Display long URLs or file names in UI without taking up too much space. ``` -------------------------------- ### Get Attributes for Marks Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/Utilities.md Retrieve attributes for all selected marks of a specific type. The editor instance can be optionally provided. ```typescript const links = getAttributesForMarks("link"); // [{ href: "https://example.com" }, { href: "..." }] const colors = getAttributesForMarks("color"); // [{ color: "#ff0000" }, { color: "#00ff00" }] ``` -------------------------------- ### Import MUI Tiptap Menu Controls Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/INDEX.md Import components for building custom menu controls, including containers, dividers, and specific buttons like Bold and heading/font size selectors. ```typescript import { MenuControlsContainer, MenuDivider, MenuButtonBold, MenuSelectHeading, MenuSelectFontSize, } from "mui-tiptap"; ``` -------------------------------- ### Import MUI Tiptap Bubble Menus Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/INDEX.md Import components for creating contextual bubble menus, such as those for links, tables, or custom controlled menus. ```typescript import { LinkBubbleMenu, TableBubbleMenu, ControlledBubbleMenu, } from "mui-tiptap"; ``` -------------------------------- ### Get Attributes for Nodes Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/Utilities.md Retrieve attributes for all selected nodes of a specific type. Provide the editor instance if not automatically fetched from context. ```typescript const headingAttrs = getAttributesForNodes("heading", { editor }); // If selection spans multiple h2 tags: // [{ level: 2 }, { level: 2 }] const imageAttrs = getAttributesForNodes("image"); // [{ src: "url1", alt: "..." }, { src: "url2", alt: "..." }] ``` -------------------------------- ### Import MUI Tiptap Extensions Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/INDEX.md Import specific extensions such as FontSize, HeadingWithAnchor, ResizableImage, TableImproved, and LinkBubbleMenuHandler to customize editor behavior. ```typescript import { FontSize, HeadingWithAnchor, ResizableImage, TableImproved, LinkBubbleMenuHandler, } from "mui-tiptap"; ``` -------------------------------- ### Automatic RichTextEditorProvider Provision Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/RichTextEditorProvider.md The RichTextEditor component automatically includes RichTextEditorProvider, simplifying setup. Use this when you don't need manual control over the editor. ```typescript // This automatically includes RichTextEditorProvider: } /> // Only use RichTextEditorProvider directly when: // 1. Using useEditor() hook manually // 2. Want more control over editor instantiation // 3. Building custom editor layouts ``` -------------------------------- ### Get Platform Modifier Shortcut Key Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/Utilities.md Retrieves the appropriate modifier key name ('Cmd' for Mac, 'Ctrl' for others) for displaying shortcuts. ```typescript const modKey = getModShortcutKey(); console.log(`${modKey}+B for bold`); // "Cmd+B" on Mac, "Ctrl+B" elsewhere ``` -------------------------------- ### Import Multiple MUI Tiptap Components Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/INDEX.md Import several core components like RichTextEditor, RichTextField, RichTextEditorProvider, and RichTextContent together for flexible UI composition. ```typescript import { RichTextEditor, RichTextField, RichTextEditorProvider, RichTextContent, } from "mui-tiptap"; ``` -------------------------------- ### Import Menu Control Components Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/MenuControls.md Import the necessary components for menu controls from the mui-tiptap library. ```typescript import { MenuButton*, MenuSelect*, MenuControlsContainer } from "mui-tiptap" ``` -------------------------------- ### useDebouncedFocus Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/ContextAndHooks.md Get a debounced version of the editor's focus state. This is useful for UI elements that should only update after the focus state has stabilized, preventing flashing. ```APIDOC ## useDebouncedFocus ### Description Get a debounced version of the editor's focus state. Useful to avoid UI "flashing" when focus is briefly lost (e.g., when clicking menu buttons). ### Signature ```typescript function useDebouncedFocus(options?: UseDebouncedFocusOptions): boolean ``` ### Type Definition ```typescript type UseDebouncedFocusOptions = { editor?: Editor | null; debounceMs?: number; } ``` ### Parameters #### Query Parameters - **editor** (Editor | null) - Optional - Tiptap editor. If not provided, fetched from context via `useRichTextEditorContext()`. - **debounceMs** (number) - Optional - Default: 200 - Debounce delay in milliseconds. Focus state changes wait this long before updating. ### Returns `boolean` — `true` if editor is focused (debounced), `false` otherwise. ### Usage Example ```typescript function StyledField() { const editor = useRichTextEditorContext(); const isFieldFocused = useDebouncedFocus({ editor, debounceMs: 150 }); return ( ); } ``` ``` -------------------------------- ### Core Components Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/INDEX.md These are the main components provided by mui-tiptap for building rich text editing experiences. ```APIDOC ## RichTextEditor ### Description An all-in-one rich text editor component. ### Use Case Provides the quickest way to add a fully functional rich text editor to your application. ``` ```APIDOC ## RichTextField ### Description A rich text editor field that includes built-in controls. ### Use Case Offers a flexible layout for integrating an editor with its associated controls. ``` ```APIDOC ## RichTextReadOnly ### Description A display-only renderer for rich text content. ### Use Case Used to show editor content without any editing controls, ideal for previewing or displaying formatted text. ``` ```APIDOC ## RichTextContent ### Description This component renders only the content area of the rich text editor. ### Use Case Suitable for custom editor layouts where you need to manage the controls separately. ``` ```APIDOC ## RichTextEditorProvider ### Description A context provider for setting up the rich text editor manually. ### Use Case Essential for more advanced or custom editor configurations that require explicit context setup. ``` -------------------------------- ### Configure Tiptap Editor Instance Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/configuration.md Configure the underlying Tiptap editor via `useEditor()` options, including extensions, initial content, autofocus, editability, event handlers, and Prosemirror editor properties. ```typescript const editor = useEditor({ // Extensions extensions: [StarterKit], // Initial content content: "

Start here

", // Autofocus autofocus: "end", // or true, false, "start" // Editable editable: true, // Re-render on transaction shouldRerenderOnTransaction: true, // Event handlers onInit: ({ editor }) => console.log("ready"), onUpdate: ({ editor }) => saveContent(editor.getHTML()), onSelectionUpdate: ({ editor }) => updateControls(), onTransaction: ({ editor, transaction }) => {}, onFocus: ({ editor }) => {}, onBlur: ({ editor }) => {}, onDestroy: () => {}, // Element element: document.getElementById("editor"), // Inline inlineContent: false, // Editor props (Prosemirror) editorProps: { attributes: { class: "my-editor", }, handleDrop: (view, event, slice) => { // Handle drag-drop return false; }, handlePaste: (view, event, slice) => { // Handle paste return false; }, }, }); ``` -------------------------------- ### Applying Custom Classes to RichTextContent Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/RichTextContent.md Attaches custom CSS classes to the RichTextContent component for styling via external stylesheets or CSS-in-JS solutions. This example uses makeStyles from Material-UI. ```typescript const useStyles = makeStyles((theme) => ({ editor: { minHeight: "300px", backgroundColor: theme.palette.mode === "dark" ? "#1e1e1e" : "#fff", padding: theme.spacing(2), borderRadius: theme.shape.borderRadius, border: `1px solid ${theme.palette.divider}`, "& .ProseMirror": { outline: "none", }, "& a": { color: theme.palette.primary.main, textDecoration: "underline", }, }, })); function MyEditor() { const classes = useStyles(); return ( ); } ``` -------------------------------- ### Insert Images with mui-tiptap Utility Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/Extensions.md Employ the `insertImages` utility from mui-tiptap to efficiently insert multiple images into the editor at a specified position or the current selection. ```typescript import { insertImages, type ImageNodeAttributes } from "mui-tiptap"; insertImages({ images: [ { src: "https://example.com/image.jpg", alt: "An image" }, ], editor, position: undefined, // defaults to current selection }); ``` -------------------------------- ### Import RichTextEditorProvider Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/RichTextEditorProvider.md Import the RichTextEditorProvider component from the mui-tiptap library. ```typescript import { RichTextEditorProvider } from "mui-tiptap" ``` -------------------------------- ### Theming RichTextField Overrides Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/RichTextField.md Customize the default appearance of RichTextField components across your application by using theme overrides. This example shows how to change the background color for the outlined variant. ```typescript const theme = createTheme({ components: { "MuiTiptap-RichTextField": { styleOverrides: { outlined: { backgroundColor: "#f0f0f0", }, }, }, }, }); ``` -------------------------------- ### Get Image Background Color Styles Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/Utilities.md Obtain CSS object styles for images that adapt to the current MUI theme. This utility helps in applying theme-consistent background colors to images. ```typescript import { getImageBackgroundColorStyles } from "mui-tiptap"; import { useTheme } from "@mui/material/styles"; function ImageWithBackground() { const theme = useTheme(); const imageStyles = getImageBackgroundColorStyles(theme); return Example; } ``` -------------------------------- ### Use FontSize Commands Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/Extensions.md Demonstrates how to use the setFontSize and unsetFontSize commands to manage text font size in the editor. Font size values must be valid CSS font-size strings. ```typescript editor.commands.setFontSize("16px"); editor.commands.setFontSize("1.2em"); editor.commands.setFontSize("large"); editor.commands.unsetFontSize(); ``` -------------------------------- ### Import RichTextContent Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/RichTextContent.md Import the RichTextContent component from the mui-tiptap library. ```typescript import { RichTextContent } from "mui-tiptap" ``` -------------------------------- ### Get MUI Theme-Aware Editor Styles Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/Utilities.md Use this function to obtain CSS object styles for the editor content area that are aware of the MUI theme. It requires the current MUI theme object as input. ```typescript import { getEditorStyles } from "mui-tiptap"; import { useTheme } from "@mui/material/styles"; function CustomContent() { const theme = useTheme(); const editorStyles = getEditorStyles(theme); return
Editor content
; } ``` -------------------------------- ### Access Editor Instance with useRichTextEditorContext Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/ContextAndHooks.md Use this hook to get the Tiptap Editor instance within the RichTextEditorProvider tree. It returns null if the editor is not yet initialized and throws an error if used outside the provider. ```typescript function MyControlComponent() { const editor = useRichTextEditorContext(); if (!editor || editor.isDestroyed) { return null; } return ( ); } ``` -------------------------------- ### Get Debounced Editor Focus State with useDebouncedFocus Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/ContextAndHooks.md Obtain a debounced version of the editor's focus state. This is useful for preventing UI flickering when the focus briefly changes, such as during menu interactions. Customize the debounce delay with the debounceMs option. ```typescript function StyledField() { const editor = useRichTextEditorContext(); const isFieldFocused = useDebouncedFocus({ editor, debounceMs: 150 }); return ( ); } ``` -------------------------------- ### Keyboard Shortcuts for Custom Commands Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/ContextAndHooks.md Defines custom keyboard shortcuts to trigger editor commands. This example shows how to insert a horizontal rule with Cmd+Alt+H (preventing default behavior) and insert content with Ctrl+.. The `useKeyDown` hook is used for defining these shortcuts. ```typescript function CustomShortcuts() { const editor = useRichTextEditorContext(); // Cmd+Alt+H for horizontal rule useKeyDown(["mod", "alt", "h"], () => { editor?.commands.setHorizontalRule(); }, { prevent: true }); // Ctrl+. for custom insertion useKeyDown(["control", "."], () => { editor?.commands.insertContent("..."); }); return ; } ``` -------------------------------- ### FontSize Extension Source: https://github.com/sjdemartini/mui-tiptap/blob/main/README.md Allows setting text font size. Requires `@tiptap/extension-text-style` and its `TextStyle` mark. ```APIDOC #### `FontSize` Sets text font size. This extension requires the [`@tiptap/extension-text-style`](https://tiptap.dev/api/marks/text-style) package to be installed and its `TextStyle` mark to be included in your `extensions`. Can be controlled with the [`MenuSelectFontSize` component](#controls-components). ##### Commands - `setFontSize()`: Set the text font size (using [a valid CSS `font-size` property](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size)). ex: `"12px"`, `"2em"`, `"small"` - `unsetFontSize()`: Remove any previously set font size, reverting to the default size for the given mark. ``` -------------------------------- ### Truncate String from Middle Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/Utilities.md Use `truncateMiddle` to shorten a string by removing characters from the center, ensuring the start and end remain visible. This is ideal for displaying long strings like file names or URLs in limited UI space. If the string is shorter than `maxLength`, it remains unchanged. ```typescript truncateMiddle("Hello World", 8); // "He...rld" truncateMiddle("short", 10); // "short" (unchanged) truncateMiddle("VeryLongFileName", 10); // "Very...ame" ``` -------------------------------- ### Import MUI Tiptap Class Names Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/INDEX.md Import specific class names for styling the RichTextField and RichTextContent components. ```typescript import { richTextFieldClasses, richTextContentClasses } from "mui-tiptap"; ``` -------------------------------- ### Import MUI Tiptap Hooks Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/INDEX.md Import utility hooks to interact with the RichTextEditor context, manage focus, handle editable updates, or capture key down events. ```typescript import { useRichTextEditorContext, useDebouncedFocus, useEditorOnEditableUpdate, useKeyDown, } from "mui-tiptap"; ``` -------------------------------- ### Run Local Checks Source: https://github.com/sjdemartini/mui-tiptap/blob/main/CONTRIBUTING.md Execute these commands to ensure code quality and formatting before submitting a pull request. Some commands can auto-fix issues. ```bash pnpm run type:check pnpm run format:check # Fix with `pnpm run format` pnpm run lint:check # Auto-fix with `pnpm run lint` pnpm run spell:check pnpm run md-link:check ``` -------------------------------- ### Initialize RichTextEditor component Source: https://github.com/sjdemartini/mui-tiptap/blob/main/README.md Basic usage of the all-in-one RichTextEditor component with a ref, initial content, and extensions. ```jsx ``` -------------------------------- ### Configure ControlledBubbleMenu Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/configuration.md Configure the ControlledBubbleMenu by providing the editor instance and open state. Options for positioning, portal behavior, and styling of the paper element are available. ```typescript ``` -------------------------------- ### Basic RichTextEditor Usage Source: https://github.com/sjdemartini/mui-tiptap/blob/main/README.md Renders a rich text editor with basic formatting controls. Ensure Tiptap extensions are correctly imported and passed to the `extensions` prop. The `renderControls` prop allows for custom menu bar configurations. ```tsx import Button from "@mui/material/Button"; import StarterKit from "@tiptap/starter-kit"; import { MenuButtonBold, MenuButtonItalic, MenuControlsContainer, MenuDivider, MenuSelectHeading, RichTextEditor, type RichTextEditorRef, } from "mui-tiptap"; import { useRef } from "react"; function App() { const rteRef = useRef(null); return (
( {/* Add more controls of your choosing here */} )} />
); } ``` -------------------------------- ### Image Upload Button Source: https://github.com/sjdemartini/mui-tiptap/blob/main/README.md Use MenuButtonImageUpload to handle image uploads. Implement the onUploadFiles prop to manage the file upload process and return the server-accessible URLs of the uploaded images. ```typescript onUploadFiles: async (files) => { // Example: upload files and return URLs const urls = await uploadFiles(files); return urls; } ``` -------------------------------- ### Basic Editor with LinkBubbleMenu Usage Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/BubbleMenus.md Demonstrates how to integrate the LinkBubbleMenu into a RichTextEditor, including necessary extensions and rendering controls. Ensure LinkBubbleMenuHandler is included in extensions. ```typescript import { RichTextEditor, LinkBubbleMenu, MenuButtonEditLink } from "mui-tiptap"; import { Link } from "@tiptap/extension-link"; import StarterKit from "@tiptap/starter-kit"; function EditorWithLinks() { return ( ( )}> {() => ( )} ); } ``` -------------------------------- ### Configure ResizableImage Extension Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/Extensions.md Configure the ResizableImage extension with options to restrict allowed image sources and optionally provide a custom component for rendering. ```typescript const editor = useEditor({ extensions: [ ResizableImage.configure({ // Optional: restrict which image URLs are allowed isAllowedImgSrc: (src) => { // Only allow images from your own domain return src?.startsWith("https://mycdn.example.com") ?? false; }, // Optional: render a custom component as a sibling to the image ChildComponent: MyCustomImageComponent, // Inherited from Image extension inline: false, allowBase64: true, }), ], }) ``` -------------------------------- ### getShortcutKeysDescription Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/Utilities.md Converts an array of shortcut key identifiers into a human-readable string, accounting for platform-specific modifier keys. ```APIDOC ## getShortcutKeysDescription ### Description Convert an array of shortcut key names to a human-readable description. ### Signature ```typescript function getShortcutKeysDescription(shortcutKeys: string[]): string ``` ### Parameters #### Query Parameters - **shortcutKeys** (string[]) - Required - Array where "mod" is replaced with Cmd/Ctrl per platform ### Usage ```typescript getShortcutKeysDescription(["mod", "b"]); // "Cmd+B" (Mac) or "Ctrl+B" getShortcutKeysDescription(["mod", "shift", "k"]); // "Cmd+Shift+K" or "Ctrl+Shift+K" getShortcutKeysDescription(["Enter"]); // "Enter" ``` ``` -------------------------------- ### Menu Controls Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/INDEX.md Individual controls and containers for building custom menu bars and toolbars. ```APIDOC ## Text Formatting Buttons ### Description Provides buttons for common text formatting options. ### Components - `MenuButtonBold`: Apply bold formatting. - `MenuButtonItalic`: Apply italic formatting. - `MenuButtonUnderline`: Apply underline formatting. - `MenuButtonStrikethrough`: Apply strikethrough formatting. - `MenuButtonCode`: Apply inline code formatting. - `MenuButtonCodeBlock`: Insert a code block. - `MenuButtonSubscript` / `MenuButtonSuperscript`: Apply subscript or superscript formatting. ``` ```APIDOC ## Containers & Dividers ### Description Components for organizing and separating menu controls. ### Components - `MenuControlsContainer`: Groups multiple controls together. - `MenuDivider`: Adds a visual separator between controls. - `MenuBar`: Represents the main control bar. ``` ```APIDOC ## Heading & Style Selection ### Description Controls for selecting heading levels, font sizes, families, and text alignment. ### Components - `MenuSelectHeading`: Dropdown to choose heading levels (H1, H2, etc.). - `MenuSelectFontSize`: Dropdown to select font size. - `MenuSelectFontFamily`: Dropdown to select font family. - `MenuSelectTextAlign`: Options for text alignment (left, center, right, justify). ``` ```APIDOC ## Blocks & Lists ### Description Controls for creating and managing block elements and lists. ### Components - `MenuButtonBulletedList`: Insert a bulleted list. - `MenuButtonOrderedList`: Insert a numbered list. - `MenuButtonTaskList`: Insert a task list. - `MenuButtonIndent` / `MenuButtonUnindent`: Adjust list indentation. - `MenuButtonBlockquote`: Insert a blockquote. - `MenuButtonHorizontalRule`: Insert a horizontal line. ``` ```APIDOC ## Colors ### Description Controls for applying text and highlight colors. ### Components - `MenuButtonTextColor`: Button to set the text color. - `MenuButtonHighlightColor`: Button to set the background highlight color. - `MenuButtonHighlightToggle`: Toggles the highlight color on/off. ``` ```APIDOC ## Images & Tables ### Description Controls for inserting and managing images and tables. ### Components - `MenuButtonAddImage`: Button to insert an image. - `MenuButtonImageUpload`: Button to trigger image upload. - `MenuButtonAddTable`: Button to insert a table. ``` ```APIDOC ## Links & History ### Description Controls for managing links and undo/redo actions. ### Components - `MenuButtonEditLink`: Button to create or edit links. - `MenuButtonUndo` / `MenuButtonRedo`: Undo or redo the last action. - `MenuButtonRemoveFormatting`: Clears all formatting from the selection. ``` -------------------------------- ### Configure MenuSelect components Source: https://github.com/sjdemartini/mui-tiptap/blob/main/README.md Customize labels, options, and accessibility attributes for font, size, heading, and alignment selects. ```tsx ``` ```tsx ``` ```tsx ``` ```tsx ``` -------------------------------- ### Version Release Command Source: https://github.com/sjdemartini/mui-tiptap/blob/main/CONTRIBUTING.md Use this npm command to update the package version and create a git tag. Choose the appropriate version type (major, minor, patch, etc.) based on semver conventions. ```bash npm version ``` -------------------------------- ### useKeyDown Source: https://github.com/sjdemartini/mui-tiptap/blob/main/_autodocs/api-reference/ContextAndHooks.md Listen for specific keyboard events on the editor. This hook allows you to easily bind key combinations to specific actions within the editor. ```APIDOC ## useKeyDown ### Description Listen for specific keyboard events on the editor. ### Signature ```typescript function useKeyDown( keyOrKeys: string | string[], callback: (event: KeyboardEvent) => void, options?: UseKeyDownOptions ): void ``` ### Type Definition ```typescript type UseKeyDownOptions = { editor?: Editor | null; prevent?: boolean; } ``` ### Parameters #### Query Parameters - **keyOrKeys** (string | string[]) - Required - Key name(s) to listen for (e.g., "Enter", "ArrowDown", or ["mod", "s"] for Cmd+S). - **callback** ((event: KeyboardEvent) => void) - Required - Function called when key is pressed. - **editor** (Editor | null) - Optional - Default: from context - Editor instance. Auto-fetched from context if not provided. - **prevent** (boolean) - Optional - Default: false - If true, call `preventDefault()` on the event. ### Key Name Format - Standard keys: "Enter", "Escape", "ArrowUp", "ArrowDown", " " (space), etc. - Modifiers: "Shift", "Control", "Alt", "Meta" - Special: Use "mod" to represent Cmd (Mac) or Ctrl (Windows/Linux) - Array syntax: `["mod", "shift", "s"]` for Cmd+Shift+S (Mac) or Ctrl+Shift+S (Windows) ### Usage ```typescript function SaveShortcut() { const editor = useRichTextEditorContext(); useKeyDown(["mod", "s"], (event) => { event.preventDefault(); console.log("Save editor content"); // Save editor.getHTML() }); return ; } ``` ### Multiple Keys ```typescript // Listen for any of several keys useKeyDown(["Enter", "Tab"], (event) => { console.log("User pressed Enter or Tab"); }); ``` ```