### Install and Run Demo Source: https://github.com/eaeao/summernote-react/blob/main/demo/README.md Navigate to the demo directory, install dependencies, and start the development server to view the live application. ```bash cd demo yarn install yarn dev # http://localhost:5173 ``` -------------------------------- ### Install with yarn Source: https://github.com/eaeao/summernote-react/blob/main/docs/README.md Install the package using yarn. ```bash yarn add @eaeao/summernote-react ``` -------------------------------- ### Install with npm Source: https://github.com/eaeao/summernote-react/blob/main/docs/README.md Install the package using npm. ```bash npm install @eaeao/summernote-react ``` -------------------------------- ### Complete Custom Plugin Example Source: https://github.com/eaeao/summernote-react/blob/main/docs/reference-api.md An example demonstrating how to create a custom plugin with a command and a toolbar button using `definePlugin`, `useChrome`, and `useCommand`. ```APIDOC ## A complete custom plugin ### Description This example shows a full implementation of a custom plugin named 'star' that adds a button to the toolbar. Clicking the button inserts a star character ('★') into the editor content. It demonstrates the use of `definePlugin`, custom commands, custom buttons, and the `useChrome` and `useCommand` hooks. ### Code Example ```tsx import { definePlugin, useChrome, useCommand, SummernoteEditor } from '@eaeao/summernote-react'; function StarButton(): JSX.Element { const { options } = useChrome(); const cmd = useCommand(); return ( ); } export const starPlugin = definePlugin({ name: 'star', commands: { insertStar: (core): boolean => { const sel = window.getSelection(); if (!sel || sel.rangeCount === 0) return false; const range = sel.getRangeAt(0); if (!core.ownsRange(range)) return false; // guard: must be inside this editor range.deleteContents(); range.insertNode(document.createTextNode('★')); range.collapse(false); return true; // changed → undo step + onChange }, }, buttons: { star: StarButton }, }); // usage: // ``` ### Usage To use the plugin, import it and include it in the `plugins` array of the `` component. Then, reference the button name (e.g., 'star') in the `toolbar` configuration. ``` -------------------------------- ### Install and Run Demo Locally Source: https://github.com/eaeao/summernote-react/blob/main/README.md Instructions to set up and run the demo application locally using yarn. ```bash cd demo && yarn install && yarn dev # http://localhost:5173 ``` -------------------------------- ### Tooltip with Shortcut Example Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Demonstrates how tooltips are generated for buttons, including the optional display of keyboard shortcuts. This example shows the tooltip for the link dialog. ```javascript tooltip (a lang string + optional shortcut). this.button strips tooltip if options.tooltip is false. Lite renders tooltips via TooltipUI keyed on container; bs3/4/5 rely on Bootstrap $.tooltip and data-original-title. ``` -------------------------------- ### Install Summernote React Source: https://github.com/eaeao/summernote-react/blob/main/docs/getting-started.md Install the @eaeao/summernote-react package using npm or yarn. Ensure react and react-dom are installed as peer dependencies. ```bash npm install @eaeao/summernote-react # or yarn add @eaeao/summernote-react ``` ```bash npm install react react-dom ``` -------------------------------- ### Minimal Editor Example Source: https://github.com/eaeao/summernote-react/blob/main/docs/README.md A basic example demonstrating how to use the SummernoteEditor component with controlled state. Ensure you import the necessary CSS styles. ```tsx import { useState } from 'react'; import { SummernoteEditor } from '@eaeao/summernote-react'; // CSS is not auto-injected — import the base skin + icon webfont yourself. import '@eaeao/summernote-react/styles.css'; import '@eaeao/summernote-react/icons.css'; export function Editor() { const [html, setHtml] = useState('

Hello Summernote

'); return ; } ``` -------------------------------- ### Button Factory Initialization Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Demonstrates the initialization process for a button using the `ui.button` factory, including tooltip, content, and dropdown toggle setup. ```javascript // Example usage within the Summernote context (conceptual) const buttonOptions = { tooltip: 'Bold', contents: 'B', data: { toggle: 'dropdown' }, container: editorOptions.container // Inherited from editor options }; const $buttonNode = ui.button(buttonOptions); // Subsequent logic would handle rendering and event binding based on buttonOptions ``` -------------------------------- ### Complete Custom Plugin Example Source: https://github.com/eaeao/summernote-react/blob/main/docs/reference-api.md A full example demonstrating how to create a custom plugin with a button that inserts a star character into the editor. It includes the button component, plugin definition, and usage in SummernoteEditor. ```tsx import { definePlugin, useChrome, useCommand, SummernoteEditor } from '@eaeao/summernote-react'; function StarButton(): JSX.Element { const { options } = useChrome(); const cmd = useCommand(); return ( ); } export const starPlugin = definePlugin({ name: 'star', commands: { insertStar: (core): boolean => { const sel = window.getSelection(); if (!sel || sel.rangeCount === 0) return false; const range = sel.getRangeAt(0); if (!core.ownsRange(range)) return false; // guard: must be inside this editor range.deleteContents(); range.insertNode(document.createTextNode('★')); range.collapse(false); return true; // changed → undo step + onChange }, }, buttons: { star: StarButton }, }); // usage: ; ``` -------------------------------- ### Install summernote-react Source: https://github.com/eaeao/summernote-react/blob/main/SKILL.md Install the summernote-react package. React and ReactDOM versions 18 or higher are required as peer dependencies. ```bash npm install @eaeao/summernote-react # react/react-dom >= 18 are peer deps ``` -------------------------------- ### Initialize Summernote Editor Source: https://github.com/eaeao/summernote-react/blob/main/docs/getting-started.md Basic setup for a fully functional Summernote editor with default toolbar and features. Imports required CSS and JS. ```tsx import { SummernoteEditor } from '@eaeao/summernote-react'; import '@eaeao/summernote-react/styles.css'; import '@eaeao/summernote-react/icons.css'; export function Example() { return ; } ``` -------------------------------- ### Command Dispatch Example Source: https://github.com/eaeao/summernote-react/blob/main/docs/reference-component.md Illustrates how to dispatch editor commands, such as inserting text, using the imperative `command` method. This is the equivalent of legacy jQuery Summernote calls. ```text In legacy summernote you would call `$('#x').summernote('insertText', 'hi')`. Here the equivalent is `ref.current?.command('insertText', 'hi')` — there is no string-dispatch `'module.method'` syntax; every command is a flat name passed to `command()`. ``` -------------------------------- ### Ad-hoc Localization Example Source: https://github.com/eaeao/summernote-react/blob/main/docs/examples.md You can provide an ad-hoc partial locale object. Missing keys will fall back to English. ```tsx ``` -------------------------------- ### Development Commands for Summernote React Source: https://github.com/eaeao/summernote-react/blob/main/README.md Run these commands in your project to manage development tasks. Ensure dependencies are installed, code quality is checked, tests are executed, and the project is built. ```bash yarn install ``` ```bash yarn verify # jQuery-ban + zero-dep gates + typecheck ``` ```bash yarn test # full suite, both engines (heavy — see docs/STATUS.md) ``` ```bash yarn build # dual ESM + CJS + .d.ts ``` -------------------------------- ### Headless Editor with useSummernote Source: https://github.com/eaeao/summernote-react/blob/main/docs/reference-api.md Example of creating a custom toolbar and editable area using the `useSummernote` hook. The `state` object dynamically updates button classes and disabled states. ```tsx import { useSummernote } from '@eaeao/summernote-react'; import '@eaeao/summernote-react/styles.css'; function Headless() { const { editableRef, core, state } = useSummernote({ historyLimit: 100 }); return (
); } ``` -------------------------------- ### Korean Localization Example Source: https://github.com/eaeao/summernote-react/blob/main/docs/examples.md Pass the 'ko-KR' locale to the lang prop for Korean localization. The locales are exported from the library. ```tsx import { SummernoteEditor, locales } from '@eaeao/summernote-react'; export function KoreanEditor() { return ; } ``` -------------------------------- ### createEditorCore Function Example Source: https://github.com/eaeao/summernote-react/blob/main/docs/reference-api.md Demonstrates mounting the Summernote editor core directly onto an HTML element without React. This is useful for integrating into existing non-React applications or specific parts of a React app. ```typescript import { createEditorCore } from '@eaeao/summernote-react'; const el = document.querySelector('#editable') as HTMLElement; const core = createEditorCore(el, { value: '

Hi

', onChange: (html) => console.log(html), }); core.command('bold'); core.command('insertText', 'Hello'); const html = core.getHTML(); core.destroy(); ``` -------------------------------- ### Define and Use a Custom Plugin in Summernote React Source: https://github.com/eaeao/summernote-react/blob/main/docs/examples.md This example shows how to define a custom plugin with a command to insert a star character and a button to trigger it. Ensure the plugin is included in the `plugins` array and the button is referenced in the `toolbar` configuration. ```tsx import { definePlugin, useChrome, useCommand, SummernoteEditor, } from '@eaeao/summernote-react'; function StarButton(): JSX.Element { const { options } = useChrome(); const cmd = useCommand(); return ( ); } const starPlugin = definePlugin({ name: 'star', commands: { insertStar: (core): boolean => { const sel = window.getSelection(); if (!sel || sel.rangeCount === 0) return false; const range = sel.getRangeAt(0); if (!core.ownsRange(range)) return false; // guard: must be inside this editor range.deleteContents(); range.insertNode(document.createTextNode('★')); range.collapse(false); return true; // changed → one undo step + onChange }, }, buttons: { star: StarButton }, }); export function PluginEditor() { return ( ); } ``` -------------------------------- ### Initialize and Show Help Dialog Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Sets up an event listener for when the dialog is shown, triggers a 'dialog.shown' event, and then displays the dialog. The dialog resolves immediately upon being shown. ```javascript ui.onDialogShown(this.$dialog, () => { context.triggerEvent('dialog.shown'); // onDialogShown callback + summernote.dialog.shown deferred.resolve(); // resolves immediately on shown }); ui.showDialog(this.$dialog); ``` -------------------------------- ### Context Initialization Order Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Critical initialization steps within the Context, including generating unique IDs, setting default containers, registering custom buttons, and initializing modules in a specific order. ```javascript options.id = func.uniqueId($.now()) options.container = options.container || layoutInfo.editor // Register custom buttons // Instantiate modules, then initialize each module ``` -------------------------------- ### Get Dialog Body Element Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Retrieves the body element of a dialog. ```javascript getDialogBody($dialog) { return $dialog.find('.note-modal-body'); } ``` -------------------------------- ### Apply Editor Themes and Import Styles Source: https://github.com/eaeao/summernote-react/blob/main/docs/reference-options.md Use the `theme` prop to select a UI skin for the editor instance. Ensure you import the base styles, icon webfont, and optionally a theme-specific CSS file. ```typescript theme?: 'lite' | 'bs3' | 'bs4' | 'bs5' // default 'lite' ``` ```tsx import '@eaeao/summernote-react/styles.css'; // base skin (required) import '@eaeao/summernote-react/icons.css'; // icon webfont (required) import '@eaeao/summernote-react/themes/bs5.css'; // optional: Bootstrap-5 skin ; ``` -------------------------------- ### Help Button Configuration Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Configuration for a help button, including its icon, tooltip, and click handler. Does not have a keyboard shortcut. ```javascript { 'help': createInvokeHandler('helpDialog.show') } ``` -------------------------------- ### Generate Shortcut List - JavaScript Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Generates an HTML string for the shortcut list in the HelpDialog. It maps key combinations to command names, fetching descriptions from language memos. Preserves the iteration order from the source keyMap. ```javascript const keyMap = this.options.keyMap[env.isMac ? 'mac' : 'pc']; return Object.keys(keyMap).map((key) => { const command = keyMap[key]; // e.g. 'undo' const $row = $('
'); $row.append($('').css({ 'width': 180, 'margin-right': 10 })) .append($('').html(this.context.memo('help.' + command) || command)); return $row.html(); }).join(''); ``` -------------------------------- ### Initialize AirPopover Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md This snippet shows the core steps involved in initializing the AirPopover, including creating its DOM, finding the content slot, building buttons, and setting up event listeners for hiding behavior. ```javascript this.$popover = this.ui.popover({ className: 'note-air-popover' }).render().appendTo(this.options.container) const $content = this.$popover.find('.popover-content,.note-popover-content') this.context.invoke('buttons.build', $content, this.options.popover.air) this.$popover.on('mousedown', () => { this.hidable = false; }) this.$popover.on('mouseup', () => { this.hidable = true; }) ``` -------------------------------- ### Initialization and Event Bindings Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Details on how the editor is initialized and the DOM events it binds to. ```APIDOC ## initialize() ### Description Initializes the editor by setting attributes, initial content, and binding various DOM events to handle user interactions and trigger Summernote events. ### Method `initialize()` ### Parameters None ### Response None ``` -------------------------------- ### Font Names Configuration Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Specifies the list of available font names for the editor. Some fonts may bypass installation checks. ```javascript ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Helvetica Neue', 'Helvetica', 'Impact', 'Lucida Grande', 'Tahoma', 'Times New Roman', 'Verdana'] ``` -------------------------------- ### Destructuring Locale Example Source: https://github.com/eaeao/summernote-react/blob/main/docs/examples.md Destructure a specific locale from the locales map for better tree-shaking. This avoids importing unused locales. ```tsx import { SummernoteEditor, locales } from '@eaeao/summernote-react'; const koKR = locales['ko-KR']; ; ``` -------------------------------- ### YouTube Video Node Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Generates an iframe for YouTube videos, including handling start times specified in various formats. ```html ``` -------------------------------- ### Configuring SummernoteEditor Options Source: https://github.com/eaeao/summernote-react/blob/main/docs/reference-options.md Example of how to pass custom options to the SummernoteEditor component, overriding default values for historyLimit, shortcuts, and isMac. ```tsx ``` -------------------------------- ### Custom Summernote React Toolbar Configuration Source: https://github.com/eaeao/summernote-react/blob/main/docs/reference-options.md Example of a custom toolbar configuration for Summernote React. This allows for a personalized set of editing tools. ```tsx ``` -------------------------------- ### Initialize Toolbar and Handle Scroll Events Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Initializes the toolbar, optionally relocating it and binding scroll/resize events for sticky behavior. The toolbar is hidden if no buttons are configured. ```javascript initialize() { options.toolbar = options.toolbar || []; if (options.toolbar.length === 0) { $toolbar.hide(); } else { context.invoke('buttons.build', $toolbar, options.toolbar); } if (options.toolbarContainer) { $toolbar.appendTo(options.toolbarContainer); } changeContainer(false); $note.on('summernote.keyup summernote.mouseup summernote.change', () => { invoke('buttons.updateCurrentStyle'); }); invoke('buttons.updateCurrentStyle'); if (options.followingToolbar) { $window.on('scroll resize', this.followScroll); } } ``` -------------------------------- ### Emoji Dialog Plugin Example Source: https://github.com/eaeao/summernote-react/blob/main/docs/reference-api.md Implements a dialog-style button to insert emojis. It captures the selection before opening the modal and restores it before inserting the emoji. ```tsx import { useState } from 'react'; import { definePlugin, Modal, useChrome, useCommand } from '@eaeao/summernote-react'; function EmojiButton() { const { core, options } = useChrome(); const cmd = useCommand(); const [open, setOpen] = useState(false); const openDialog = () => { core?.saveRange(); // capture selection before the modal steals focus setOpen(true); }; const pick = (emoji: string) => { core?.restoreRange(); cmd('insertEmoji', emoji); setOpen(false); core?.focus(); }; return ( <> {open && ( setOpen(false)}> {['😀', '🎉', '🚀', '★'].map((e) => ( ))} )} ); } export const emojiPlugin = definePlugin({ name: 'emoji', commands: { insertEmoji: (core, emoji): boolean => { const sel = window.getSelection(); if (!sel || sel.rangeCount === 0) return false; const range = sel.getRangeAt(0); if (!core.ownsRange(range)) return false; range.deleteContents(); range.insertNode(document.createTextNode(String(emoji))); range.collapse(false); return true; }, }, buttons: { emoji: EmojiButton }, }); ``` -------------------------------- ### TooltipUI Show Method Logic Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Illustrates the core logic within the TooltipUI's show method, including offset calculations, title and placement retrieval, DOM manipulation, and positioning. ```javascript // 1. offset = $node.offset(); subtract the target's offset (targetOffset = $(target).offset()) so coordinates are **relative to the target container** (the container must be positioned). // 2. title = options.title || $node.attr('title') || $node.data('title'). // 3. placement = options.placement || $node.data('placement'). // 4. add placement class to tooltip; set .note-tooltip-content **text** = title (text, not HTML — XSS-safe); append tooltip to options.target. // 5. measure node W/H and tooltip W/H (outer), then position: // - **bottom**: top = offset.top + nodeHeight, left = offset.left + (nodeWidth/2 - tooltipWidth/2). // - **top**: top = offset.top - tooltipHeight, same left centering. // - **left**: top = offset.top + (nodeHeight/2 - tooltipHeight/2), left = offset.left - tooltipWidth. // - **right**: top = same vertical centering, left = offset.left + nodeWidth. // 6. add class `in` (CSS reveals/animates the tooltip). ``` -------------------------------- ### Uncontrolled Summernote Editor Example Source: https://github.com/eaeao/summernote-react/blob/main/docs/concepts.md Use this mode when the editor should manage its own content internally after initialization. Pass an initial default value using `defaultValue`. ```tsx ``` -------------------------------- ### Image Popover Buttons Configuration Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Defines buttons for resizing and floating images, and removing media. All use `createInvokeHandler`. Resize arguments must be strings. ```javascript { 'resizeFull': createInvokeHandler('editor.resize', '1'), 'resizeHalf': createInvokeHandler('editor.resize', '0.5'), 'resizeQuarter': createInvokeHandler('editor.resize', '0.25'), 'resizeNone': createInvokeHandler('editor.resize', '0') } ``` ```javascript { 'floatLeft': createInvokeHandler('editor.floatMe', 'left'), 'floatRight': createInvokeHandler('editor.floatMe', 'right'), 'floatNone': createInvokeHandler('editor.floatMe', 'none') } ``` ```javascript { 'removeMedia': createInvokeHandler('editor.removeMedia') } ``` -------------------------------- ### createLayout($note) Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Builds the editor's structural layout based on editor options (like airMode and toolbar position) and inserts it into the DOM. ```APIDOC ## createLayout($note) ### Description Builds the editor skeleton, choosing the structure based on options like `airMode` and `toolbarPosition`. The editor DOM is inserted immediately after the original element (`$note`). ### Parameters - **$note** (jQuery object) - The original element to which the editor will be attached. ### Returns A `layoutInfo` object containing references to the note, editor, toolbar, editing area, editable area, codable area, and status bar. ``` -------------------------------- ### Uncontrolled Editor with Imperative Ref Source: https://github.com/eaeao/summernote-react/blob/main/docs/README.md Example of using the SummernoteEditor in an uncontrolled manner with an imperative ref to access its methods like getCode(), command(), and undo(). ```tsx import { useRef } from 'react'; import { SummernoteEditor, type SummernoteEditorHandle } from '@eaeao/summernote-react'; function Demo() { const ref = useRef(null); return ( <> ); } ``` -------------------------------- ### Initialize Image Popover Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Initializes the popover by rendering it and appending it to the specified container. It then builds the popover buttons based on the configuration. ```javascript this.$popover = ui.popover({ className: 'note-image-popover' }).render().appendTo(options.container); ``` -------------------------------- ### Integrating Multiple Plugins in Summernote React Source: https://github.com/eaeao/summernote-react/blob/main/docs/reference-api.md Demonstrates how to include the hello, specialchars, and databasic plugins in the Summernote editor and configure their appearance in the toolbar. ```tsx import { SummernoteEditor, helloPlugin, specialcharsPlugin, databasicPlugin } from '@eaeao/summernote-react'; ; ``` -------------------------------- ### Get Popover Content Element Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Retrieves the content element within a popover. Note: There might be an inconsistency with the 'popover' factory's generated class name. ```javascript getPopoverContent($popover) { return $popover.find('.note-popover-content'); } ``` -------------------------------- ### Fullscreen Button Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Sets up the fullscreen button, including its class name for styling, icon, and tooltip. It toggles the fullscreen mode. ```javascript button.fullscreen - `className: 'btn-fullscreen note-codeview-keep'`, icon `icons.arrowsAlt`, tooltip `lang.options.fullscreen` (no shortcut). - `click: createInvokeHandler('fullscreen.toggle')`. ``` -------------------------------- ### Show Help Dialog and Restore Selection Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Saves the current editor selection, opens the help dialog, and restores the selection once the dialog is shown. This method does not handle failures as the help dialog has no explicit reject path. ```javascript context.invoke('editor.saveRange'); this.showHelpDialog().then(() => { context.invoke('editor.restoreRange'); }); ``` -------------------------------- ### Get or Set Editor Code Source: https://github.com/eaeao/summernote-react/blob/main/docs/migrating.md Retrieve the HTML content or set it using jQuery. In React, use ref.current?.getCode() or setCode(html), or manage with controlled component props. ```javascript $('.x').summernote('code') ``` ```javascript ref.current?.getCode() ``` ```javascript setCode(html) ``` ```javascript controlled value / onChange ``` -------------------------------- ### Button Factory Logic Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Illustrates the core logic for creating and rendering toolbar buttons, including tooltip handling and UI integration. ```javascript this.button(o) .tooltip(options.tooltip) .container(options.container) .render(); ``` -------------------------------- ### UI Icon Generation Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Generates an icon element using a provided class name. If the class name starts with '<', it's returned directly. Otherwise, a default tag (usually 'i') is used. ```javascript ui.icon(className, tag='i') → '' ``` -------------------------------- ### Summernote Initialization Options Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Handles merging of options, language packs, and icons during Summernote initialization. Tooltip behavior is determined by touch support. ```javascript options = $.extend({}, $.summernote.options, userOptions) options.langInfo = $.extend(true, {}, lang['en-US'], lang[options.lang]) options.icons = $.extend(true, {}, defaultIcons, options.icons) options.tooltip = !env.isSupportTouch ``` -------------------------------- ### Initialize Handle Overlay DOM Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Builds the DOM for the image selection handle overlay. This includes the background, corner controls, and an optional info div. It's prepended to the editing area. ```javascript this.$handle = $( '
{infoDiv}
', ).prependTo(this.$editingArea); ``` -------------------------------- ### Get Link Info Command Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Use `getLinkInfo` to retrieve details about the anchor element at the current range, including its text and URL. It focuses the editor if necessary and expands the range to encompass the anchor. ```javascript getLinkInfo() → {range, text, url, isNewWindow?} ``` -------------------------------- ### Render Icon with Class Name Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Renders an icon element. If the `iconClassName` starts with '<', it's treated as pre-existing markup and returned directly. Otherwise, it creates an element (defaulting to 'i') with the provided class name. ```javascript icon(iconClassName, tagName) { if (iconClassName.startsWith('<')) { return iconClassName; } const tagName = tagName || 'i'; return `<${tagName} class="${iconClassName}">`; } ``` -------------------------------- ### Configure CodeMirror Tern Integration Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md If Tern integration is configured in CodeMirror options, this code sets up the Tern server and binds cursor activity to update argument hints. ```javascript server = new CodeMirror.TernServer(options.codemirror.tern); cmEditor.ternServer = server; cmEditor.on('cursorActivity', function(cm) { server.updateArgHints(cm); }); ``` -------------------------------- ### PeerTube Embed Code Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Generates an iframe for PeerTube embeds. Note the preserved bugs for parity, including unsanitized host and incorrect 'end' parameter referencing YouTube's 'start' variable. ```html ``` -------------------------------- ### Custom Summernote React Toolbar Source: https://github.com/eaeao/summernote-react/blob/main/docs/examples.md Define a custom toolbar by passing an array of group and item name tuples to the `toolbar` prop. This example shows a reduced set of common formatting and insertion tools. ```tsx import { SummernoteEditor } from '@eaeao/summernote-react'; export function CustomToolbarEditor() { return ( ); } ``` -------------------------------- ### Using Imperative Ref and Command API Source: https://github.com/eaeao/summernote-react/blob/main/AGENTS.md This snippet demonstrates how to initialize Summernote React with a ref and use it to get/set HTML, dispatch commands, and manage focus. Note that commands like 'bold' or 'insertText' require an active editor selection. ```tsx import { useRef } from 'react'; import { SummernoteEditor, type SummernoteEditorHandle } from '@eaeao/summernote-react'; const ref = useRef(null); ; // ref.current?.getCode() get HTML // ref.current?.setCode(html) set HTML // ref.current?.command('bold') dispatch a command (returns boolean) // ref.current?.command('insertText', 'hi') // ref.current?.focus() / undo() / redo() // ref.current?.core the raw EditorCore (escape hatch) ``` -------------------------------- ### Create Editor Layout (Bottom Toolbar) Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Builds the editor's skeleton structure with the toolbar positioned at the bottom. It returns a layout information object. ```javascript createLayout($note) { // ... logic for toolbarPosition === 'bottom' ... return { note: $note, editor: $editor, toolbar: '.note-toolbar', editingArea: '.note-editing-area', editable: '.note-editable', codable: '.note-codable', statusbar: '.note-statusbar' }; } ``` -------------------------------- ### Setup CSS Imports for Summernote React Source: https://github.com/eaeao/summernote-react/blob/main/docs/examples.md Import the necessary CSS files for the Summernote React editor. The base styles and icon webfont are always required. Optional Bootstrap themes can also be imported. ```tsx import { SummernoteEditor } from '@eaeao/summernote-react'; import '@eaeao/summernote-react/styles.css'; // base / lite skin (required) import '@eaeao/summernote-react/icons.css'; // shared icon webfont (required) // optional, only if you use a Bootstrap theme: // import '@eaeao/summernote-react/themes/bs3.css'; // import '@eaeao/summernote-react/themes/bs4.css'; // import '@eaeao/summernote-react/themes/bs5.css'; ``` -------------------------------- ### UI Button Markup and Wiring Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Shows the basic HTML structure for a button and how various attributes and callbacks are wired for different functionalities like tooltips and dropdowns. ```html ``` -------------------------------- ### Controlled Summernote Editor Example Source: https://github.com/eaeao/summernote-react/blob/main/docs/concepts.md Use this mode when you want to manage the editor's content externally using React state. Pass the current value via the `value` prop and update it using the `onChange` callback. ```tsx const [html, setHtml] = React.useState('

Hello

'); ; ``` -------------------------------- ### Get or Set HTML Content in React Summernote Source: https://github.com/eaeao/summernote-react/blob/main/AGENTS.md Retrieve the current HTML content using `getCode()` or set it with `setCode(html)`. Alternatively, manage content in a controlled manner using the `value` and `onChange` props, which is the recommended approach. ```javascript getCode() / setCode(html) ``` ```javascript controlled `value`/`onChange` ``` -------------------------------- ### Generate Native-Style Commands in Constructor Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md These commands are generated in a loop from an array of command names. Each command is a method that executes a specific document command, with before and after hooks. ```javascript this[cmd] = (value) => { beforeCommand(); document.execCommand(cmd, false, value); afterCommand(true); } ``` -------------------------------- ### Insert Image Command Implementation Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Details the `editor.insertImage(src, param)` command, including image preloading, width clamping, and event handling. ```javascript editor.insertImage(src, param) → insertImage(src, param): - `param` here is the URL string path: only `src` is passed (`param` undefined). - Uses `createImage(src)` (async helper): creates a hidden `` appended to `document.body`, resolves on `load`, rejects on `error`/`abort`. The port must asynchronously preload to learn natural dimensions. - On resolve: - `beforeCommand()` (snapshot/before.command + focus). - Since `param` is not a function and not a string here → `$image.css('width', Math.min($editable.width(), $image.width()))`. **Inserted images are clamped to the editable's width** (never wider than the editor). - `$image.show()`, insert at `getLastRange().insertNode($image[0])`, set selection after the image (`range.createFromNodeAfter($image[0]).select()`), `afterCommand()` (records undo + fires `change`). - On failure: `context.triggerEvent('image.upload.error', e)`. ``` -------------------------------- ### Create Editor Layout (Air Mode) Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Builds the editor's skeleton structure for air mode. This configuration omits the toolbar and status bar. It returns a layout information object. ```javascript createLayout($note) { // ... logic for airMode ... return { note: $note, editor: $editor, toolbar: null, // No toolbar in air mode editingArea: '.note-editing-area', editable: '.note-editable', codable: '.note-codable', statusbar: null // No statusbar in air mode }; } ``` -------------------------------- ### Picture Button Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Sets up the picture button with its icon and tooltip. It triggers the image dialog upon click. ```javascript button.picture - icon `icons.picture`, tooltip `lang.image.image` (no shortcut). - `click: createInvokeHandler('imageDialog.show')`. ``` -------------------------------- ### Media / link Commands Source: https://github.com/eaeao/summernote-react/blob/main/docs/reference-commands.md Commands for managing media and links within the editor. ```APIDOC ## createLink ### Description Create or update an anchor element (``). Rejects empty or unsafe URLs (e.g., `javascript:`, `vbscript:`, `data:`). If `newWindow` is set to `true`, it also sets `target="_blank"` and `rel="noopener noreferrer"`. This command edits an existing anchor in place. ### Method Not specified (assumed to be a function call) ### Parameters - **url** (string) - Required - The URL for the link. - **text** (string) - Optional - The display text for the link. - **newWindow** (boolean) - Optional - If true, opens the link in a new tab. ## unlink ### Description Unwrap the enclosing anchor element. ### Method Not specified (assumed to be a function call) ### Parameters None ## insertImage ### Description Insert an image using its source URL. Optionally, a filename can be provided. ### Method Not specified (assumed to be a function call) ### Parameters - **src** (string) - Required - The URL of the image. - **filename** (string) - Optional - The filename for the image. ## insertVideo ### Description Insert a video by parsing a provider URL into an embed node. ### Method Not specified (assumed to be a function call) ### Parameters - **url** (string) - Required - The URL of the video provider. ## insertHorizontalRule ### Description Insert a horizontal rule (`
`). ### Method Not specified (assumed to be a function call) ### Parameters None ## insertNode ### Description Insert an arbitrary DOM node, typically used for custom embeds. The caret is placed after the inserted node. ### Method Not specified (assumed to be a function call) ### Parameters - **node** (Node) - Required - The DOM node to insert. ## resizeImage ### Description Set the width of an image. The width is specified as a percentage of the original size. An empty string or 'none' will remove the width. ### Method Not specified (assumed to be a function call) ### Parameters - **img** (HTMLImageElement) - Required - The image element to resize. - **value** (string | number) - Required - The width value (e.g., '50%', 0.5, '', 'none'). ## floatImage ### Description Set the CSS `float` property for an image. The default value is 'none'. ### Method Not specified (assumed to be a function call) ### Parameters - **img** (HTMLImageElement) - Required - The image element to float. - **value** (string) - Optional - The CSS float value (e.g., 'left', 'right', 'none'). ## removeMedia ### Description Remove the specified image node from the editor. ### Method Not specified (assumed to be a function call) ### Parameters - **img** (HTMLImageElement) - Required - The image element to remove. ``` -------------------------------- ### Resize Media Command Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Adjust the width of a media element using `resize` with a fractional value representing a percentage. A value of '0' clears the width. ```javascript resize(value) ``` -------------------------------- ### Invoke Handler Creation Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Demonstrates the creation of event handlers for invoking editor commands, with or without a static value. ```javascript context.createInvokeHandler(namespace, value?) ``` ```javascript (e) => { e.preventDefault(); invoke(ns, value || $(e.target).closest('[data-value]').data('value'), $target); } ``` -------------------------------- ### Format Block Command Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Wraps the current selection in a specified HTML tag. It supports custom callbacks and provides an internal handler for the execCommand. ```javascript formatBlock(tagName, $target?) { if (options.callbacks.onApplyCustomStyle) { options.callbacks.onApplyCustomStyle($target, context, this.onFormatBlock); } else { this.onFormatBlock(tagName, $target); } } ``` ```javascript onFormatBlock(tagName, $target?) { document.execCommand('FormatBlock', false, isMSIE ? '<' + tagName + '>' : tagName); if ($target) { const $current = $target.closest(tagName); if ($current.length) { $current.removeClass('note-para note-heading') .addClass($target[0].className); } } } ``` -------------------------------- ### ui(editorOptions) Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Initializes the UI components for the Summernote editor based on provided options. It returns an object containing references to various editor elements and helper functions for UI manipulation. ```APIDOC ## ui(editorOptions) ### Description Initializes the UI components for the Summernote editor. Returns an object exposing factories and helpers for interacting with the editor's UI elements. ### Parameters - **editorOptions** (object) - Configuration options for the editor. ### Returns An object containing: - Pass-throughs: `editor`, `toolbar`, `editingArea`, `codable`, `editable`, `statusbar`, `airEditor`, `airEditable`, `buttonGroup`, `dropdown`, `dropdownCheck`, `dropdownButton`, `dropdownButtonContents`, `dropdownCheckButton`, `paragraphDropdownButton`, `tableDropdownButton`, `colorDropdownButton`, `palette`, `dialog`, `videoDialog`, `imageDialog`, `linkDialog`, `popover`, `checkbox`, `icon`. - `options`: The resolved editor options. - `button(options)`: A wrapper for the base button factory that injects a default tooltip container. ``` -------------------------------- ### Sizing and Destruction Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Configuration for editor sizing and the method for destroying the editor instance. ```APIDOC ## Sizing Configuration ### Description Configures the editor's dimensions based on `options.width`, `options.height`, `options.maxHeight`, and `options.minHeight`. ### Parameters - **options.width** - Sets the outer width of the editor. - **options.height** - Sets the outer height of the editable area. - **options.maxHeight** - Sets the maximum CSS height for the editable area. - **options.minHeight** - Sets the minimum CSS height for the editable area. ### Response None ``` ```APIDOC ## destroy() ### Description Cleans up the editor instance by removing all event bindings from the editable element. ### Method `destroy()` ### Parameters None ### Response None ``` -------------------------------- ### Invoke Editor Commands in Summernote React Source: https://github.com/eaeao/summernote-react/blob/main/docs/CHROME-SPECS.md Demonstrates the sequence of editor commands invoked by the video dialog's `show()` method. Includes saving and restoring selection ranges, and inserting a node. ```javascript context.invoke('editor.getSelectedText') context.invoke('editor.saveRange') this.showVideoDialog(text).then((url) => { this.ui.hideDialog(this.$dialog) context.invoke('editor.restoreRange') const $node = this.createVideoNode(url) if ($node) { context.invoke('editor.insertNode', $node) } }).fail(() => { context.invoke('editor.restoreRange') }) ```