### Local Development Setup and Run Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Provides instructions for cloning the repository, installing dependencies, and starting the development server for local Lobe Editor development. ```bash $ git clone https://github.com/lobehub/lobe-editor.git $ cd lobe-editor $ pnpm install $ pnpm run dev ``` -------------------------------- ### Basic Upload Plugin Setup Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/upload/index.md Demonstrates how to initialize the Upload plugin and obtain the IUploadService from the kernel. ```typescript const uploadPlugin = new UploadPlugin(kernel); // The plugin automatically registers the upload service const uploadService = kernel.requireService(IUploadService); ``` -------------------------------- ### Basic Plugin Setup Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/link-highlight/index.md Shows the basic setup for integrating the ReactLinkHighlightPlugin into a React editor. Ensure the plugin is placed before ReactPlainText. ```typescript import { ReactEditor, ReactEditorContent, ReactPlainText, ReactLinkHighlightPlugin } from '@lobehub/editor'; export default () => { return ( {/* Plugin must be placed before ReactPlainText */} ); }; ``` -------------------------------- ### Basic Editor Usage Source: https://github.com/lobehub/lobe-editor/blob/master/src/react/Editor/index.md Demonstrates the basic setup and usage of the Editor component. ```tsx import { Editor } from '@lobehub/editor/react'; export default () => { return ; }; ``` -------------------------------- ### Basic Setup with Custom Renderer Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/math/index.md Demonstrates how to register the Math plugin with a custom renderer and theme. ```typescript import { MathPlugin, ReactMathPlugin } from '@lobehub/editor'; // Register the plugin with custom renderer const mathPlugin = new MathPlugin(kernel, { decorator: (node, editor) => { return ; }, theme: { mathInline: 'custom-inline-math', mathBlock: 'custom-block-math' } }); // Use in React ``` -------------------------------- ### EditorProvider Complete Configuration Example Source: https://github.com/lobehub/lobe-editor/blob/master/src/react/EditorProvider/index.md This example demonstrates a comprehensive configuration for EditorProvider, including theme settings and a detailed nested structure for locale translations across various categories like file, table, image, and link. ```typescript import { Editor, EditorProvider } from '@lobehub/editor/react'; const globalConfig = { theme: { primaryColor: '#1677ff', borderRadius: 6, }, locale: { // File-related - supports nested structure file: { error: 'File upload failed: {{message}}', uploading: 'Uploading file...', }, // Table-related table: { delete: 'Delete table', deleteColumn: 'Delete column', deleteRow: 'Delete row', insertColumnLeft: 'Insert {{count}} column(s) to the left', insertColumnRight: 'Insert {{count}} column(s) to the right', insertRowAbove: 'Insert {{count}} row(s) above', insertRowBelow: 'Insert {{count}} row(s) below', }, // Image-related image: { broken: 'Image failed to load', }, // Link-related link: { edit: 'Edit Link', open: 'Open Link', placeholder: 'Enter link URL', unlink: 'Unlink', }, }, }; ``` -------------------------------- ### Basic Mention Setup Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/mention/index.md Register the mention plugin with custom decorator, markdown writer, and theme. ```typescript const mentionPlugin = new MentionPlugin(kernel, { decorator: (node, editor) => , markdownWriter: (node) => `[@${node.label}](${node.getId()})`, theme: { mention: 'custom-mention-class' } }); ``` -------------------------------- ### Basic Editor Setup with React Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Demonstrates the basic setup of the LobeHub Editor using React components and essential plugins. Handles content changes by retrieving markdown and JSON formats. ```tsx import { INSERT_HEADING_COMMAND, ReactCodeblockPlugin, ReactImagePlugin, ReactLinkPlugin, ReactListPlugin, } from '@lobehub/editor'; import { Editor, useEditor } from '@lobehub/editor/react'; export default function MyEditor() { const editor = useEditor(); return ( { editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h1' }); }, }, // More slash commands... ], }} onChange={(editor) => { // Handle content changes const markdown = editor.getDocument('markdown'); const json = editor.getDocument('json'); }} /> ); } ``` -------------------------------- ### Install LobeHub Editor with Bun Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Install the @lobehub/editor package using the Bun package manager. ```bash $ bun add @lobehub/editor ``` -------------------------------- ### Complete Editor Event Handling Example Source: https://github.com/lobehub/lobe-editor/blob/master/src/react/Editor/index.md A comprehensive example demonstrating the integration of multiple event handlers including focus, composition, keyboard, and context menu events for robust editor interaction. ```typescript import { Editor } from '@lobehub/editor/react'; import { useState } from 'react'; function MyEditor() { const [isComposing, setIsComposing] = useState(false); const [isFocused, setIsFocused] = useState(false); return ( setIsFocused(true)} onBlur={() => setIsFocused(false)} onCompositionStart={() => setIsComposing(true)} onCompositionEnd={() => setIsComposing(false)} onKeyDown={(e) => { // Handle special key combinations if (e.ctrlKey && e.key === 's') { e.preventDefault(); // Save content } }} onPressEnter={(e) => { if (e.ctrlKey) { // Submit on Ctrl+Enter handleSubmit(); } }} onContextMenu={(e) => { e.preventDefault(); // Show custom context menu }} onChange={(editor) => { // Handle content changes console.log('Content changed'); }} /> ); } ``` -------------------------------- ### Basic Editor Usage Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/common/index.md Demonstrates the basic setup and usage of the ReactEditor component. ```typescript import { ReactEditor, ReactEditorContent, ReactPlainText, } from '@lobehub/react-editor'; import React from 'react'; const App = () => { return ( ); }; export default App; ``` -------------------------------- ### Install LobeHub Editor with PNPM Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Install the @lobehub/editor package using the PNPM package manager. ```bash $ pnpm add @lobehub/editor ``` -------------------------------- ### Basic Image Plugin Setup Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/image/index.md Configure the ImagePlugin with custom themes, maximum width, and enable captions and resizing. ```typescript const imagePlugin = new ImagePlugin(kernel, { theme: { image: 'custom-image', imageCaption: 'custom-caption', imageResizer: 'custom-resizer', }, maxWidth: 1000, captionsEnabled: true, resizeEnabled: true, }); ``` -------------------------------- ### Transformer Registration Examples: Bold, Heading, Link Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/markdown/index.md Provides examples for registering transformers for bold text, headings (h1-h6), and markdown links. ```typescript // Bold text transformer const boldTransformer: TextFormatTransformer = { format: ['bold'], tag: '**', type: 'text-format', }; // Heading transformer const headingTransformer: ElementTransformer = { regExp: /^(#{1,6})\s(.+)$/, replace: (parentNode, children, match) => { const level = match[1].length as 1 | 2 | 3 | 4 | 5 | 6; const headingNode = $createHeadingNode(`h${level}`); headingNode.append($createTextNode(match[2])); parentNode.replace(headingNode); return true; }, trigger: 'enter', type: 'element', }; // Link transformer const linkTransformer: TextMatchTransformer = { regExp: /!\[([^\]]+)\]\(([^)]+)\)/, replace: (textNode, match) => { const linkNode = $createLinkNode(match[2]); linkNode.append($createTextNode(match[1])); textNode.replace(linkNode); }, type: 'text-match', }; ``` -------------------------------- ### Basic Slash Command Setup Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/slash/index.md Configure basic slash commands with predefined items. Use this for static command lists. ```typescript const slashPlugin = new SlashPlugin(kernel, { slashOptions: [{ trigger: '/', items: [ { key: 'heading', title: 'Heading', icon: }, { key: 'list', title: 'List', icon: } ] }], triggerOpen: (context) => showSlashMenu(context), triggerClose: () => hideSlashMenu() }); ``` -------------------------------- ### Basic Code Plugin Setup Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/code/index.md Illustrates how to register the CodePlugin and use the ReactCodePlugin wrapper within the Editor component. ```typescript import { CodePlugin, ReactCodePlugin } from '@lobehub/editor'; // Register the plugin const codePlugin = new CodePlugin(kernel, { theme: 'custom-code-class' }); // Use in React ``` -------------------------------- ### Basic HR Plugin Setup Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/hr/index.md Initialize the HRPlugin with custom theme configurations, default style, and options for custom styling and responsiveness. ```typescript const hrPlugin = new HRPlugin(kernel, { theme: { hr: 'custom-hr', hrSolid: 'hr-solid', hrDashed: 'hr-dashed', }, defaultStyle: 'solid', allowCustom: true, responsive: true, }); ``` -------------------------------- ### Basic Link Plugin Setup Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/link/index.md Demonstrates how to initialize the LinkPlugin with custom theme settings, enable auto-detection, validate on type, set a default target, and specify allowed protocols. ```typescript const linkPlugin = new LinkPlugin(kernel, { theme: { link: 'custom-link', linkHover: 'custom-link-hover', linkInvalid: 'custom-link-invalid', }, autoDetect: true, validateOnType: true, defaultTarget: '_blank', allowedProtocols: ['http', 'https', 'mailto'], }); ``` -------------------------------- ### Basic ChatInput Usage Source: https://github.com/lobehub/lobe-editor/blob/master/src/react/ChatInput/index.md Demonstrates the basic setup of the ChatInput component. This snippet shows how to render the component with its default configuration. ```tsx import { ChatInput } from '@lobehub/editor/react'; export default () => ( {/* Content goes here */} ); ``` -------------------------------- ### Basic Codeblock Plugin Setup Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/codeblock/index.md Initializes the Codeblock plugin with a specified Shiki theme and a custom CSS class for code styling. Requires the kernel instance. ```typescript const codeblockPlugin = new CodeblockPlugin(kernel, { shikiTheme: 'github-dark', theme: { code: 'custom-code-style' }, }); ``` -------------------------------- ### Basic List Plugin Setup Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/list/index.md Initializes the List plugin with custom theme settings, maximum nesting level, and enables markdown and auto-indentation features. ```typescript const listPlugin = new ListPlugin(kernel, { theme: { list: 'custom-list', listItem: 'custom-list-item', nestedListItem: 'custom-nested-item', }, maxNestingLevel: 5, enableMarkdown: true, autoIndent: true, }); ``` -------------------------------- ### Markdown Serialization Example Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/link-highlight/index.md Shows how link highlights are serialized into markdown format using angle brackets. ```typescript // Link highlight is serialized as: ; // Angle bracket-wrapped URL // Also works with other URL formats: ``` -------------------------------- ### SlashOptions Configuration Example Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/slash/index.md Illustrates the configuration options for defining slash commands, including trigger characters, items, matching fields, and custom trigger functions. ```typescript interface SlashOptions { trigger?: string; items?: ISlashOption[] | Function; maxLength?: number; matchingFields?: string[]; matchingStrategy?: 'startsWith' | 'fuzzy'; triggerFn?: (text: string) => Match; } ``` -------------------------------- ### Image Plugin Internationalization Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/image/index.md Example translations for image-related UI text within the plugin. ```typescript // Example translations { "image.insert": "Insert Image", "image.upload": "Upload Image", "image.caption": "Image Caption", "image.altText": "Alternative Text", "image.resize": "Resize Image", "image.delete": "Delete Image", "image.loading": "Loading image...", "image.error": "Failed to load image" } ``` -------------------------------- ### Custom CSS for Link Highlight Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/link-highlight/index.md Provides example CSS rules for styling the link highlight component using a custom class. ```css .my-custom-link-highlight-style { color: #0066cc; background: rgba(0, 102, 204, 0.1); border: 1px solid #0066cc; border-radius: 4px; padding: 2px 6px; font-family: 'Monaco', 'Consolas', monospace; text-decoration: none; transition: all 0.2s ease; } .my-custom-link-highlight-style:hover { background: rgba(0, 102, 204, 0.2); border-color: #0052a3; } ``` -------------------------------- ### Auto-link Detection Configuration Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/link/index.md Shows how to configure the AutoLinkPlugin with custom matchers. This example uses a regex to find URLs within text and prepares them for linking. ```typescript // Enable auto-link detection const autoLinkPlugin = new AutoLinkPlugin({ matchers: [ (text: string) => { const matches = text.match(URL_PATTERN); return ( matches?.map((match) => ({ index: text.indexOf(match), length: match.length, text: match, url: match, })) || [] ); }, ], }); ``` -------------------------------- ### CodeNode API Examples Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/code/index.md Demonstrates creating a new code node with initial content, checking if a node is an inline code node, and verifying if the current selection is within an inline code block. ```typescript // Create a new code node const codeNode = $createCodeNode('console.log("Hello")'); // Check if a node is a code node if ($isCodeInlineNode(node)) { // Handle code node logic } // Check if current selection is in code if ($isSelectionInCodeInline(editor)) { // Selection is within inline code } ``` -------------------------------- ### Get Editor Instance and Plugin Configuration Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Demonstrates how to obtain the editor instance using a custom hook and configure a React plugin with a file upload handler. ```tsx // Get editor instance const editor = useEditor(); // Helper for plugin configuration const PluginWithConfig = Editor.withProps(ReactFilePlugin, { handleUpload: async (file) => ({ url: 'uploaded-url' }), }); ``` -------------------------------- ### i18n String Resolution Example Source: https://github.com/lobehub/lobe-editor/blob/master/docs/superpowers/specs/2026-05-28-extract-codemirror-ui-components-design.md Demonstrates how user-visible strings are resolved using the 'labels' prop, with English defaults provided directly in the code. This approach avoids dependency on a global translation context. ```typescript const text = labels?.copy ?? 'Copy'; ``` -------------------------------- ### Headless Editor Setup and Block Extraction Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/content-blocks/index.md Configure and use the headless editor for server-side or worker-based block extraction. Image and File plugins are configured with no-op callbacks. ```typescript import { CONTENT_BLOCKS_DATA_TYPE, type ContentBlock, ContentBlocksPlugin, FilePlugin, ImagePlugin, } from '@lobehub/editor'; import { DEFAULT_HEADLESS_EDITOR_PLUGINS, createHeadlessEditor } from '@lobehub/editor/headless'; const headless = createHeadlessEditor({ additionalPlugins: [ [ImagePlugin, { renderImage: () => null, handleUpload: async () => ({ url: '' }) }], [FilePlugin, { decorator: () => null, handleUpload: async () => ({ url: '' }) }], ContentBlocksPlugin, ], plugins: DEFAULT_HEADLESS_EDITOR_PLUGINS, }); headless.hydrate({ content: editorJson, type: 'json' }); const blocks = headless.kernel.getDocument(CONTENT_BLOCKS_DATA_TYPE) as unknown as ContentBlock[]; headless.destroy(); ``` -------------------------------- ### Configuring Content Blocks Plugin with Silent Drop Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/content-blocks/index.md Example of registering the ContentBlocksPlugin with options to disable placeholders for unuploaded media, causing them to be dropped silently. ```typescript const kernel = Editor.createEditor().registerPlugins([ CommonPlugin, MarkdownPlugin, ImagePlugin, FilePlugin, [ContentBlocksPlugin, { defaultOptions: { emitPlaceholderForUnuploaded: false } }], ]); ``` -------------------------------- ### Editor Kernel API Example Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Directly interact with the Lobe Editor kernel for advanced use cases. This includes creating an editor instance, registering plugins, manipulating content, and dispatching commands. ```typescript import { IEditor, createEditor } from '@lobehub/editor'; // Create editor instance const editor: IEditor = createEditor(); // Register plugins editor.registerPlugin(SomePlugin, { config: 'value' }); // Interact with content editor.setDocument('text', 'Hello world'); const content = editor.getDocument('json'); // Listen to events editor.on('content-changed', (newContent) => { console.log('Content updated:', newContent); }); // Execute commands editor.dispatchCommand(INSERT_HEADING_COMMAND, { tag: 'h2' }); ``` -------------------------------- ### File Plugin Initialization Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/file/index.md Demonstrates how to initialize the File plugin with custom theme settings, maximum file size, allowed file types, and a custom upload handler. ```typescript const filePlugin = new FilePlugin(kernel, { theme: { file: 'custom-file', fileName: 'custom-file-name', fileStatus: 'custom-status', }, maxFileSize: 10 * 1024 * 1024, // 10MB allowedTypes: ['.pdf', '.doc', '.docx', '.txt'], uploadHandler: async (file) => { const formData = new FormData(); formData.append('file', file); const response = await fetch('/api/upload', { method: 'POST', body: formData, }); return response.json(); }, }); ``` -------------------------------- ### Basic Table Plugin Initialization Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/table/index.md Demonstrates how to initialize the Table Plugin with custom theming and options for including headers and allowing resizing. ```typescript const tablePlugin = new TablePlugin(kernel, { theme: { table: 'custom-table', tableCell: 'custom-cell', tableCellHeader: 'custom-header', }, includeHeaders: true, allowResize: true, }); ``` -------------------------------- ### Get HR Style Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/hr/index.md Retrieve the current styling of a HorizontalRuleNode using the getHRStyle utility function. ```typescript getHRStyle(node: HorizontalRuleNode): HRStyle ``` -------------------------------- ### ImageNode Methods Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/image/index.md Provides methods to get and set image source, alternative text, dimensions, and caption visibility. ```typescript getSrc(): string setSrc(src: string): void getAltText(): string setAltText(alt: string): void getWidth(): number | 'inherit' setWidth(width: number | 'inherit'): void getHeight(): number | 'inherit' setHeight(height: number | 'inherit'): void getShowCaption(): boolean setShowCaption(show: boolean): void getCaptionEditor(): LexicalEditor ``` -------------------------------- ### Click to Open Links Configuration Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/link-highlight/index.md Illustrates that no additional configuration is needed for the default behavior of clicking highlighted links to open them in a new window. ```typescript // Click a highlighted link - it opens automatically // No additional configuration needed ``` -------------------------------- ### Get List Item Depth Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/list/index.md Returns the current nesting depth of a given ListItemNode. Depth is 0 for top-level items. ```typescript import { ListItemNode } from '@lobehub/editor-plugins'; // ... const item: ListItemNode = ...; // Get your ListItemNode const depth = getListItemDepth(item); ``` -------------------------------- ### Get Link URL Utility Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/link/index.md Retrieves the URL from a Lexical `LinkNode`. Ensure the node is a link node before calling this function. ```typescript getLinkUrl(node: LinkNode): string ``` -------------------------------- ### Enable Upload Service Debugging Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Enable detailed tracing for the upload service. ```bash DEBUG=lobe-editor:service:upload ``` -------------------------------- ### Creating Custom Plugins Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Demonstrates how to create custom plugins for the Lobe Editor by implementing the `IEditorPlugin` interface. ```APIDOC ## Creating Custom Plugins ### Description Shows the structure for creating custom plugins using the `IEditorPlugin` interface, including initialization and cleanup. ### Usage ```typescript import { IEditorKernel, IEditorPlugin } from '@lobehub/editor'; class MyCustomPlugin implements IEditorPlugin { constructor(private config: MyPluginConfig) {} initialize(kernel: IEditorKernel) { // Register nodes, commands, transforms, etc. kernel.registerNode(MyCustomNode); kernel.registerCommand(MY_COMMAND, this.handleCommand); } destroy() { // Cleanup } } ``` ``` -------------------------------- ### Table Plugin Translations Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/table/index.md Provides example translations for table-related UI elements. These can be used to internationalize the table plugin's text. ```typescript // Example translations { "table.insert": "Insert Table", "table.delete": "Delete Table", "table.addRow": "Add Row", "table.addColumn": "Add Column", "table.deleteRow": "Delete Row", "table.deleteColumn": "Delete Column" } ``` -------------------------------- ### File Plugin i18n Translations Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/file/index.md Provides example translation keys and values for internationalizing file-related text within the Lobe Editor. ```typescript // Example translations { "file.insert": "Insert File", "file.upload": "Upload File", "file.download": "Download File", "file.remove": "Remove File", "file.retry": "Retry Upload", "file.pending": "Uploading...", "file.uploaded": "Upload Complete", "file.error": "Upload Failed", "file.sizeLimit": "File size exceeds limit", "file.typeNotAllowed": "File type not allowed" } ``` -------------------------------- ### Enable Mention System Debugging Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Enable detailed tracing for the mention system plugin. ```bash DEBUG=lobe-editor:plugin:mention ``` -------------------------------- ### Retrieve Markdown Content from Editor Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/markdown/index.md Shows how to get the processed markdown content from the editor instance, which automatically applies all registered writers. ```typescript // Get markdown output const editor = kernel.getEditor(); const markdownContent = editor.getDocument('markdown'); // The markdown data source automatically processes all registered writers console.log(markdownContent); // Clean markdown text output ``` -------------------------------- ### Using Link and Link Highlight Plugins Together Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/link-highlight/index.md Configure multiple link plugins within the same editor. Ensure hotkeys are managed to prevent conflicts, and understand the priority for link insertion and toolbar behavior. ```typescript import { ReactEditor, ReactPlainText, ReactLinkPlugin, ReactLinkHighlightPlugin } from '@lobehub/editor'; function MyEditor() { return ( {/* Standard Link plugin - disable hotkey to avoid conflict */} {/* LinkHighlight plugin - uses Cmd+K hotkey */} ); } ``` -------------------------------- ### Get List Items Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/list/index.md Retrieves an array of all ListItemNode instances directly contained within a given ListNode. Does not include nested items. ```typescript import { ListNode, ListItemNode } from '@lobehub/editor-plugins'; // ... const list: ListNode = ...; // Get your ListNode const items: ListItemNode[] = getListItems(list); ``` -------------------------------- ### Custom Image Component Example Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/image/index.md A React component for rendering custom image nodes, handling loading and error states, and displaying captions. ```typescript const CustomImageComponent = ({ node, editor }) => { const [isLoading, setIsLoading] = useState(true); const [hasError, setHasError] = useState(false); return (
{node.getAltText()} setIsLoading(false)} onError={() => setHasError(true)} style={{ width: node.getWidth(), height: node.getHeight(), maxWidth: node.getMaxWidth() }} /> {node.getShowCaption() && (
)}
); }; ``` -------------------------------- ### Enable Image Handling Debugging Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Enable detailed tracing for the image handling plugin. ```bash DEBUG=lobe-editor:plugin:image ``` -------------------------------- ### Basic Table Usage Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/table/index.md Demonstrates the basic integration and usage of the Table plugin within the editor. ```typescript import { ReactTablePlugin } from "@lobehub/editor-plugins"; // ... editor setup { console.log('Table created:', table); }} /> ``` -------------------------------- ### Programmatic Link Highlight Insertion Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/link-highlight/index.md Demonstrates how to programmatically insert a link highlight node using editor commands and direct node creation. ```typescript import { $createLinkHighlightNode, INSERT_LINK_HIGHLIGHT_COMMAND } from '@lobehub/editor'; // Insert link highlight via command const insertLinkHighlight = () => { editor.dispatchCommand(INSERT_LINK_HIGHLIGHT_COMMAND, undefined); }; // Create link highlight node directly editor.update(() => { const linkHighlightNode = $createLinkHighlightNode('https://example.com'); $insertNodes([linkHighlightNode]); }); ``` -------------------------------- ### Get Parent List Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/list/index.md Finds and returns the immediate parent ListNode for a given ListItemNode. Returns null if the item is not part of a list or is a top-level item. ```typescript import { ListItemNode, ListNode } from '@lobehub/editor-plugins'; // ... const item: ListItemNode = ...; // Get your ListItemNode const parentList: ListNode | null = getParentList(item); ``` -------------------------------- ### Lobe Editor Initialization Source: https://github.com/lobehub/lobe-editor/blob/master/docs/index.md This snippet shows the basic initialization of the Lobe Editor component. It's a starting point for integrating the editor into your React application. ```typescript import { EditorState, LexicalComposer } from '@lexical/react'; import * as React from 'react'; import { InitialConfigType } from './config'; import Editor from './Editor'; export interface EditorProps { className?: string; initialEditorState?: EditorState; initialConfig?: InitialConfigType; } export default function LobeEditor({ className, initialEditorState, initialConfig }: EditorProps) { return ( ); } ``` -------------------------------- ### Enable All Plugin Debugging Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Enable detailed tracing for all plugins. Use this to debug issues across multiple plugins. ```bash DEBUG=lobe-editor:plugin:* ``` -------------------------------- ### Enable All Service Debugging Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Enable detailed tracing for all services. Use this to debug issues across multiple services. ```bash DEBUG=lobe-editor:service:* ``` -------------------------------- ### Link Plugin Internationalization Translations Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/link/index.md Provides example translations for various link-related UI elements and messages. These are used to internationalize the link plugin's interface. ```typescript // Example translations { "link.insert": "Insert Link", "link.edit": "Edit Link", "link.remove": "Remove Link", "link.url": "URL", "link.title": "Link Title", "link.target": "Link Target", "link.openNewWindow": "Open in New Window", "link.invalidUrl": "Invalid URL format", "link.preview": "Link Preview" } ``` -------------------------------- ### Basic Debug Configuration Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Shows how to configure debug logging for LobeHub Editor using environment variables, including enabling all logs or specific components. ```bash # Enable all LobeHub Editor debug output DEBUG=lobe-editor:* # Enable only important logs (recommended for development) DEBUG=lobe-editor:*:info,lobe-editor:*:warn,lobe-editor:*:error # Enable specific components DEBUG=lobe-editor:kernel,lobe-editor:plugin:* ``` -------------------------------- ### Initialize Markdown Plugin with Default Options Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/markdown/index.md Initializes the Markdown plugin with default settings, enabling paste markdown functionality. ```typescript // With default options (paste markdown enabled) const markdownPlugin = new MarkdownPlugin(kernel); // The plugin automatically registers the markdown service const markdownService = kernel.requireService(IMarkdownShortCutService); ``` -------------------------------- ### Get Drag Selection Utility Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/upload/index.md A utility function to determine the text selection range from a drag event, supporting different browser implementations for caret range detection. ```typescript // Get drag selection utility (included in plugin) function getDragSelection(event: DragEvent): Range | null | undefined { let range; const domSelection = getDOMSelectionFromTarget(event.target); if (document.caretRangeFromPoint) { range = document.caretRangeFromPoint(event.clientX, event.clientY); } else if (event.rangeParent && domSelection !== null) { domSelection.collapse(event.rangeParent, event.rangeOffset || 0); range = domSelection.getRangeAt(0); } return range; } ``` -------------------------------- ### Recommended Link Plugin Configurations Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/link-highlight/index.md Choose the optimal configuration for Link and LinkHighlight plugins based on your application's needs, such as chat interfaces requiring auto-highlighting or document editors needing manual link creation. ```typescript // For chat/messaging interfaces (auto-highlight URLs): // For documents (manual link creation with custom text): // For both (LinkHighlight gets hotkey, Link disabled): ``` -------------------------------- ### Table Utility Functions Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/table/index.md Provides essential utility functions for interacting with and manipulating table nodes, including checking node type, getting dimensions, and inserting/deleting rows/columns. ```typescript // Check if node is a table isTableNode(node: LexicalNode): boolean // Get table dimensions getTableDimensions(tableNode: TableNode): { rows: number, cols: number } // Insert row/column insertTableRow(tableNode: TableNode, index: number): void insertTableColumn(tableNode: TableNode, index: number): void // Delete row/column deleteTableRow(tableNode: TableNode, index: number): void deleteTableColumn(tableNode: TableNode, index: number): void ``` -------------------------------- ### Programmatic Table Creation and Row Insertion Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/table/index.md Shows how to programmatically insert a table with specified dimensions and headers, and how to add a new row to an existing table. ```typescript // Create a 3x4 table with headers editor.dispatchCommand(INSERT_TABLE_COMMAND, { rows: 3, columns: 4, includeHeaders: true, }); // Add row to existing table const tableNode = getSelectedTableNode(); if (tableNode) { insertTableRow(tableNode, 1); } ``` -------------------------------- ### Extracting URL from Link Highlight Node Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/link-highlight/index.md Retrieve the URL associated with a LinkHighlightNode within the editor. This is useful for accessing link data programmatically, for example, when a user interacts with a link. ```typescript editor.update(() => { const selection = $getSelection(); if ($isRangeSelection(selection)) { const node = selection.anchor.getNode(); const linkHighlight = getLinkHighlightNode(node); if (linkHighlight) { const url = linkHighlight.getURL(); console.log('Current link:', url); } } }); ``` -------------------------------- ### Handle IME Composition Events Source: https://github.com/lobehub/lobe-editor/blob/master/src/react/Editor/index.md Utilize onCompositionStart and onCompositionEnd for proper handling of Input Method Editor (IME) input, crucial for languages like Chinese, Japanese, and Korean. ```typescript const [isComposing, setIsComposing] = useState(false); const handleCompositionStart = (e: CompositionEvent) => { setIsComposing(true); console.log('Composition started'); }; const handleCompositionEnd = (e: CompositionEvent) => { setIsComposing(false); console.log('Composition ended:', e.data); }; ``` -------------------------------- ### Custom File Component Example Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/file/index.md Defines a custom React component for rendering file attachments, including download and retry actions based on the file's upload status. ```typescript const CustomFileComponent = ({ node, editor }) => { const handleDownload = () => { const url = node.getFileUrl(); if (url) { window.open(url, '_blank'); } }; const handleRetry = async () => { node.setStatus('pending'); try { const result = await retryUpload(node.getName()); node.setFileUrl(result.url); node.setStatus('uploaded'); } catch (error) { node.setStatus('error'); node.setMessage(error.message); } }; return (
{node.getName()} {formatFileSize(node.getSize() || 0)}
{node.getStatus() === 'uploaded' && ( )} {node.getStatus() === 'error' && ( )}
); }; ``` -------------------------------- ### Enable Info Level Tracing Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Enable general information logging for all categories, displayed as Console.log (blue). ```bash DEBUG=lobe-editor:*:info ``` -------------------------------- ### Table Navigation Functions Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/table/index.md Offers functions for navigating and selecting cells within tables, including moving to a specific cell, getting the current cell position, and selecting a range of cells. ```typescript // Navigate to cell navigateToTableCell( tableNode: TableNode, rowIndex: number, colIndex: number ): void // Get current cell position getCurrentTableCell(): { row: number, col: number } | null // Select table range selectTableRange( tableNode: TableNode, startRow: number, startCol: number, endRow: number, endCol: number ): void ``` -------------------------------- ### SendButton Basic Usage Source: https://github.com/lobehub/lobe-editor/blob/master/src/react/SendButton/index.md Demonstrates the basic implementation of the SendButton component. This snippet shows how to render the button in its default state. ```tsx import { SendButton } from '@lobehub/ui'; export default () => ( { console.log('send button clicked'); }} /> ); ``` -------------------------------- ### FileNode Methods Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/file/index.md Provides methods to get and set file properties such as name, URL, size, and upload status. Also includes a method to update file data from a JSON object. ```typescript // Get/set file name getName(): string setName(name: string): void // Get/set file URL getFileUrl(): string | undefined setFileUrl(url: string): void // Get/set file size getSize(): number | undefined setSize(size: number): void // Get/set upload status getStatus(): 'pending' | 'uploaded' | 'error' setStatus(status: 'pending' | 'uploaded' | 'error'): void // Get/set status message getMessage(): string | undefined setMessage(message: string): void // Update file data updateFromJSON(data: SerializedFileNode): FileNode ``` -------------------------------- ### Create Editor Kernel Instance Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Shows how to create a new instance of the Lobe Editor kernel. ```typescript const editor = createEditor(); ``` -------------------------------- ### Basic ChatInputActionBar Usage Source: https://github.com/lobehub/lobe-editor/blob/master/src/react/ChatInputActionBar/index.md Demonstrates the basic structure of a ChatInputActionBar. Use the `left` and `right` props to place content in the respective areas. ```tsx import { ChatInputActionBar } from '@lobehub/editor/react'; import { Icon } from '@lobehub/ui'; import { Mic, Send } from 'lucide-react'; export default () => ( } // Example icon for the left area right={} // Example icon for the right area /> ); ``` -------------------------------- ### Enable Kernel Debugging Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Enable detailed tracing for core editor functionality. ```bash DEBUG=lobe-editor:kernel ``` -------------------------------- ### Programmatic Math Insertion Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/math/index.md Demonstrates how to programmatically insert various math expressions into the editor. ```typescript // Insert various math expressions const insertMath = (expression: string) => { editor.dispatchCommand(INSERT_MATH_COMMAND, { code: expression, }); }; // Examples insertMath('\frac{1}{2}'); // Fraction insertMath('\sum_{i=1}^{n} i'); // Summation insertMath('\int_0^\infty e^{-x} dx'); // Integral insertMath('\begin{matrix} a & b \\ c & d \end{matrix}'); // Matrix ``` -------------------------------- ### Custom Matching Configurations Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/slash/index.md Configure different matching strategies and fields for slash commands. Supports 'startsWith', 'fuzzy', and custom fields for matching. ```typescript // Use startsWith matching with key field (default behavior) const startsWithMatching = { trigger: '/', matchingStrategy: 'startsWith', // Default strategy matchingFields: ['key'], // Default field items: [ { key: 'heading1', title: 'Heading 1' }, { key: 'heading2', title: 'Heading 2' }, { key: 'list', title: 'List' }, ], }; // Typing 'h' will match 'heading1' and 'heading2' // Use custom fields for matching const customFieldMatching = { trigger: '@', matchingStrategy: 'startsWith', matchingFields: ['title', 'description'], // Match by title and description items: [ { key: 'user1', title: 'John Doe', description: 'Developer' }, { key: 'user2', title: 'Jane Smith', description: 'Designer' }, ], }; // Typing 'john' or 'dev' will match the first item // Use fuzzy matching for more flexible search const fuzzyMatching = { trigger: '#', matchingStrategy: 'fuzzy', matchingFields: ['key', 'title'], items: [ { key: 'react-component', title: 'React Component' }, { key: 'vue-template', title: 'Vue Template' }, ], }; // Typing 'comp' will match 'react-component' even with characters in between ``` -------------------------------- ### createEditor(): IEditor Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Factory function to create a new instance of the editor kernel. ```APIDOC ## `createEditor(): IEditor` ### Description Create a new editor kernel instance. ### Method `createEditor` ### Returns An instance of `IEditor`. ### Request Example ```typescript const editor = createEditor(); ``` ``` -------------------------------- ### Enable Markdown Processing Debugging Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Enable detailed tracing for the markdown processing service. ```bash DEBUG=lobe-editor:service:markdown ``` -------------------------------- ### CodeblockPluginOptions Configuration Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/codeblock/index.md Configuration options for initializing the Codeblock plugin, including theme and color customization. ```APIDOC ## CodeblockPluginOptions ### Description These are the options available when initializing the `CodeblockPlugin`. They allow for extensive customization of the syntax highlighting and overall appearance of code blocks. ### Properties - **shikiTheme** (string | { dark: string, light: string }) - Optional - Specifies the Shiki theme to use. Can be a theme name string (e.g., 'github-dark') or an object defining separate themes for light and dark modes. - **colorReplacements** ({ current?: AllColorReplacements }) - Optional - Allows for custom color schemes. The `current` property is an object where keys are token types and values are CSS color strings. - **theme** ({ code?: string }) - Optional - Provides CSS theme configuration, specifically for the code element's styling. ``` -------------------------------- ### AllColorReplacements Interface Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/codeblock/index.md Defines the structure for custom color replacements for syntax highlighting tokens. ```APIDOC ## AllColorReplacements Interface ### Description This interface defines the structure for specifying custom color replacements for various syntax highlighting token types. It allows you to override the default colors provided by the Shiki highlighter. ### Structure ```typescript interface AllColorReplacements { [tokenType: string]: string; // CSS color values } ``` ### Usage Provide an object where keys are the token types (e.g., 'string', 'keyword', 'comment', 'variable') and values are valid CSS color strings (e.g., '#ff0000', 'rgb(255, 0, 0)'). **Example:** ```typescript { string: '#22863a', keyword: '#d73a49', comment: '#6a737d', } ``` ``` -------------------------------- ### EditorProvider Basic Usage Source: https://github.com/lobehub/lobe-editor/blob/master/src/react/EditorProvider/index.md This snippet demonstrates the basic usage of the EditorProvider component. It wraps child components to provide global editor configurations. ```tsx import { EditorProvider } from '@lobehub/editor/react'; export default () => ( {/* Your editor components */} ); ``` -------------------------------- ### Available Commands Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Lists common commands that can be dispatched to control editor behavior, such as content insertion and text formatting. ```APIDOC ## Available Commands ### Description Common commands you can dispatch to manipulate editor content and formatting. ### Commands #### Content Insertion - `INSERT_HEADING_COMMAND` - `INSERT_LINK_COMMAND` - `INSERT_IMAGE_COMMAND` - `INSERT_TABLE_COMMAND` - `INSERT_MENTION_COMMAND` - `INSERT_FILE_COMMAND` - `INSERT_HORIZONTAL_RULE_COMMAND` #### Text Formatting - `FORMAT_TEXT_COMMAND` - `CLEAR_FORMAT_COMMAND` ``` -------------------------------- ### ChatInputActions Basic Usage Source: https://github.com/lobehub/lobe-editor/blob/master/src/react/ChatInputActions/index.md Demonstrates the basic integration of the ChatInputActions component. This snippet shows how to render the component with its default configuration. ```tsx import { ChatInputActions } from '@lobehub/editor/react'; export default () => ( { console.log(action); }} /> ); ``` -------------------------------- ### Create Custom Plugin Source: https://github.com/lobehub/lobe-editor/blob/master/README.md Illustrates how to create a custom plugin for the Lobe Editor by implementing the IEditorPlugin interface, including initialization and cleanup logic. ```typescript import { IEditorKernel, IEditorPlugin } from '@lobehub/editor'; class MyCustomPlugin implements IEditorPlugin { constructor(private config: MyPluginConfig) {} initialize(kernel: IEditorKernel) { // Register nodes, commands, transforms, etc. kernel.registerNode(MyCustomNode); kernel.registerCommand(MY_COMMAND, this.handleCommand); } destroy() { // Cleanup } } ``` -------------------------------- ### Basic Usage of CodeLanguageSelect Source: https://github.com/lobehub/lobe-editor/blob/master/src/react/CodeLanguageSelect/index.md Demonstrates the basic implementation of the CodeLanguageSelect component. This component automatically populates language options based on Shiki's supported languages. ```typescript import CodeLanguageSelect from '@lobehub/editor/react'; export default () => ( ); ``` -------------------------------- ### Basic Usage of ReactListPlugin Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/list/index.md Demonstrates the basic integration of the ReactListPlugin component. This snippet shows how to include the plugin in your React application to enable list editing features. ```typescript import { ReactListPlugin } from '@lobehub/editor-plugins'; // ... inside your editor component ``` -------------------------------- ### Programmatic File Insertion Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/file/index.md Shows how to programmatically insert files into the editor, both as already uploaded files and as pending uploads with status messages. ```typescript // Insert uploaded file editor.dispatchCommand(INSERT_FILE_COMMAND, { name: 'report.pdf', fileUrl: '/uploads/report.pdf', size: 2048000, status: 'uploaded', }); // Insert pending upload editor.dispatchCommand(INSERT_FILE_COMMAND, { name: 'document.docx', size: 1024000, status: 'pending', message: 'Uploading...', }); ``` -------------------------------- ### Integrating Click Handlers for Link Highlights Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/link-highlight/index.md Register a command to handle clicks on LinkHighlightNodes, allowing custom actions like opening the URL in a new window. This enhances user interaction with highlighted links. ```typescript // Add click handler to open links editor.registerCommand( CLICK_COMMAND, (event) => { const node = $getNearestNodeFromDOMNode(event.target); if ($isLinkHighlightNode(node)) { const url = node.getURL(); window.open(url, '_blank'); return true; } return false; }, COMMAND_PRIORITY_LOW, ); ``` -------------------------------- ### Basic Usage of ReactLinkHighlightPlugin Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/link-highlight/index.md Integrate the `ReactLinkHighlightPlugin` before `ReactPlainText` to ensure proper registration during content loading. ```typescript import { ReactLinkHighlightPlugin } from '@lobehub/editor'; // ... editor configuration ``` -------------------------------- ### FileTheme Configuration Source: https://github.com/lobehub/lobe-editor/blob/master/src/plugins/file/index.md Defines the CSS theme configuration for styling file elements within the editor. This allows for customization of the appearance of file names, sizes, statuses, and actions. ```APIDOC ## FileTheme ### Description CSS theme configuration for file styling. ### Properties - **file** (string) - Optional - **fileName** (string) - Optional - **fileSize** (string) - Optional - **fileStatus** (string) - Optional - **filePending** (string) - Optional - **fileUploaded** (string) - Optional - **fileError** (string) - Optional - **fileActions** (string) - Optional ```