### Install via npm Source: https://richtexteditor.com/docs/quick-start Use npm to install the package or scaffold a new project with a specific framework. ```bash npm install @richscripts/richtexteditor # or scaffold a complete working example app: npm create @richscripts/richtexteditor my-app -- --react # also: --vue, --angular ``` -------------------------------- ### Install Structured Content Bridge Source: https://richtexteditor.com/docs/structured-content Load the bridge scripts after the core editor bundle and initialize the bridge before creating the editor instance. ```html ``` -------------------------------- ### editor.selectDoc(bStart) Source: https://richtexteditor.com/docs/jsapi_selectdoc Selects the document within the editor. The bStart parameter is a boolean that determines if the range collapses to the start or end. ```APIDOC ## editor.selectDoc(bStart) ### Description Selects the document. The bStart is a boolean value. ### Syntax `editor.selectDoc(bStart)` ### Parameters - **bStart** (boolean) - Optional - True collapses the Range to its start, false to its end. If omitted, it defaults to false. ### Example usage ```javascript var editor1 = new RichTextEditor("#div_editor1"); var img=editor1.document.createElement("IMG"); img.src="/images/editor-image.png"; editor1.insertElement(img); editor1.selectDoc(img) ``` ``` -------------------------------- ### editor.collapse(bStart) Source: https://richtexteditor.com/docs/jsapi_collapse Collapses the current selection to a single point. The bStart parameter determines whether the range collapses to its start or end. ```APIDOC ## editor.collapse(bStart) ### Description Collapses the current selection to a single point. ### Syntax `editor.collapse(bStart)` ### Parameters - **bStart** (boolean) - Optional - True collapses the Range to its start, false to its end. If omitted, it defaults to false. ### Example usage ```javascript var editor1 = new RichTextEditor("#div_editor1"); editor1.setHTMLCode("hello world"); editor1.selectDoc(); editor1.execCommand("forecolor","red"); editor1.collapse(false); ``` ``` -------------------------------- ### Integrate CRDT in Vanilla JS Source: https://richtexteditor.com/docs/crdt-internals Setup the RichTextEditor with Yjs and WebsocketProvider using the CRDT engine. ```html ``` -------------------------------- ### Get and Set Editor Content Source: https://richtexteditor.com/docs/initialization Use setHTMLCode and getHTMLCode to manipulate or retrieve the editor's content. ```javascript //Setting the editor data editor1.setHTMLCode("

Hello World

Click the button below to show this HTML code

"); function btnShowHTMLCode() { // Getting the editor data alert(editor1.getHTMLCode()) } ``` -------------------------------- ### Attach selectionchange event listener Source: https://richtexteditor.com/docs/event_selectionchange Registers a callback function to execute when the editor selection changes. This example updates the document title with the current plain text character count. ```javascript editor1.attachEvent("change", function () { var textCount = editor1.getPlainText().trim().length; document.title = "textCount:" + textCount; }); ``` -------------------------------- ### Initialize AI Toolkit with Editor Source: https://richtexteditor.com/docs/ai-toolkit Load the required CSS and JS files, then initialize the editor with the AI toolkit persistence key. ```html
``` -------------------------------- ### GET /richtextbox/health Source: https://richtexteditor.com/docs/operations Retrieves the health status of the RichTextBox service, including dependency reachability and license status. ```APIDOC ## GET /richtextbox/health ### Description Surfaces the reachability status of configured RichTextBox dependencies alongside the current license status. ### Method GET ### Endpoint /richtextbox/health ``` -------------------------------- ### Initialize the editor Source: https://richtexteditor.com/docs/quick-start Include the required CSS and JS files, then initialize the editor on a target HTML element. ```html
Hello RichTextEditor
``` -------------------------------- ### Configure skin and toolbar Source: https://richtexteditor.com/docs/configuration Initializes the editor with a specific skin and toolbar configuration. ```javascript ``` -------------------------------- ### Initialize Editor Instance Source: https://richtexteditor.com/docs/initialization Instantiate the editor by passing a selector to the new() method. ```javascript //Then call new() method to replace the matched element with RichTextEditor. var editor1 = new RichTextEditor("#div_editor1"); ``` -------------------------------- ### Configure one-off mode prompts via dictionary Source: https://richtexteditor.com/docs/operations Use the SystemPromptOverridesByMode dictionary within the service configuration for quick mode-specific prompt adjustments. ```csharp services.AddRichTextBoxOpenAiResolver(opts => { opts.ApiKey = "sk-..."; opts.SystemPromptOverridesByMode["proofread"] = "You are a hyper-pedantic copy-editor for legal documents."; }); ``` -------------------------------- ### Retrieve Editor HTML Content Source: https://richtexteditor.com/docs/jsapi_gethtmlcode Demonstrates initializing the editor, setting initial content, and displaying the current HTML via an alert. ```javascript var editor1 = new RichTextEditor("#div_editor1"); editor1.setHTMLCode("

Hello World

Click the button below to show this HTML code

"); function btnShowHTMLCode() { alert(editor1.getHTMLCode()) } ``` -------------------------------- ### Initialize and Set Content with JavaScript Source: https://richtexteditor.com/docs/get-the-html-content-of-rte Create an editor instance on a target element and use setHTMLCode to programmatically update the editor content. ```html
``` ```javascript //Initialize Richtexteditor for the matched element var editor1 = new RichTextEditor("#div_editor1"); //Setting Content with Javascript editor1.setHTMLCode("Use inline HTML or setHTMLCode to set the default content."); ``` -------------------------------- ### Configure the toolbar Source: https://richtexteditor.com/docs/quick-start Customize the editor appearance and functionality by passing a configuration object during initialization. ```javascript var editor = new RichTextEditor("#div_editor1", { toolbar: "basic", // "basic" | "full" | "mobile" | "custom" height: "500px", showStatistics: true, // word / character count in the bottom bar showFloatTextToolBar: true }); ``` ```javascript var editor = new RichTextEditor("#div_editor1", { toolbar: "custom", toolbar_custom: "{bold,italic,underline}|" + "{insertorderedlist,insertunorderedlist}|" + "{insertlink,insertimage}|" + "{aiassist,aichat}|" + "{undo,redo}" }); ``` -------------------------------- ### Register AI Provider in Program.cs Source: https://richtexteditor.com/docs/ai-providers-streaming Register the RichTextBox services and configure an OpenAI provider using dependency injection. ```csharp using RichTextBox.AiResolvers; builder.Services.AddRichTextBox(); builder.Services.AddRichTextBoxOpenAiResolver(opts => { opts.ApiKey = builder.Configuration["OpenAI:ApiKey"]; opts.Model = "gpt-4o-mini"; }); ``` -------------------------------- ### Enable Mobile Toolbar via CSS and HTML Source: https://richtexteditor.com/docs/mobile-toolbar Include the mobile stylesheet and apply the 'rte-mobile' class to the editor container. ```html
``` -------------------------------- ### Configure Persistence and Remote Ledger Source: https://richtexteditor.com/docs/ai-toolkit Set persistence keys and URLs to enable cross-session synchronization of AI review suggestions. ```javascript new RichTextEditor("#editor", { aiToolkitPersistenceKey: "doc-42-review", // localStorage scope aiToolkitSuggestionLedgerUrl: "/api/ai/ledger", // optional GET/POST for cross-session sync aiToolkitReviewLogUrl: "/api/ai/review-log", // optional activity feed endpoint aiToolkitReviewSyncInterval: 15000 // ms between sync polls (default 15s) }); ``` -------------------------------- ### Import editor modules Source: https://richtexteditor.com/docs/quick-start Import the necessary styles and scripts into your build pipeline, or use the framework-specific component wrappers. ```javascript // Side-effect import attaches `RichTextEditor` to `window`. import "@richscripts/richtexteditor/richtexteditor/rte.js"; import "@richscripts/richtexteditor/richtexteditor/plugins/all_plugins.js"; // Or via the typed React wrapper (Vue / Angular wrappers shipped too): import { RichTextEditorComponent } from "@richscripts/richtexteditor/react"; ``` -------------------------------- ### Enable Dictation via JavaScript Configuration Source: https://richtexteditor.com/docs/dictation Configure the editor instance to enable dictation features during initialization. ```javascript var cfg = { dictationEnabled: true, dictationLang: "en-US", // BCP-47 dictationContinuous: true, dictationInterimResults: true, dictationAutoPunctuation: true }; new RichTextEditor("#editor", cfg); ``` -------------------------------- ### Execute fullscreen command Source: https://richtexteditor.com/docs/jsapi_execcommand Triggers the fullscreen mode for the specified editor instance. ```javascript var editor1 = new RichTextEditor("#div_editor1"); editor1.execCommand("fullscreenenter"); ``` -------------------------------- ### Configure toolbar using editor.toolbar Source: https://richtexteditor.com/docs/configuration Sets the editor toolbar style to basic using a configuration object. ```javascript ``` -------------------------------- ### Configure Slash Commands Source: https://richtexteditor.com/docs/collaboration-review Enable slash commands and AI toolkit integration. ```javascript { slashCommandEnabled: true, // default when this plugin is loaded slashCommandIncludeAi: true // pull aiToolkitActions into the menu } ``` -------------------------------- ### Implement Custom AI Resolver Source: https://richtexteditor.com/docs/ai-providers-streaming Create a custom provider by implementing IRichTextBoxAiResolver and registering it in the service container. ```csharp public sealed class MyBedrockResolver : IRichTextBoxAiResolver { public async ValueTask ResolveAsync( RichTextBoxAiRequest request, CancellationToken cancellationToken = default) { // ...call Bedrock, map response to RichTextBoxAiResponseBuilder... } } builder.Services.AddRichTextBox(); builder.Services.AddSingleton(); ``` -------------------------------- ### Configure OpenTelemetry tracing Source: https://richtexteditor.com/docs/operations Subscribe to the RichTextBox ActivitySource within the OpenTelemetry tracer provider configuration to enable distributed tracing. ```csharp builder.Services.AddOpenTelemetry().WithTracing(t => t .AddSource(RichTextBoxDiagnostics.SourceName) // "RichTextBox.AspNetCore" .AddAspNetCoreInstrumentation() .AddOtlpExporter()); ``` -------------------------------- ### Insert root paragraphs using JavaScript Source: https://richtexteditor.com/docs/jsapi_insertrootparagraph Demonstrates how to iterate and insert multiple paragraph elements into the editor instance. ```javascript var editor1 = new RichTextEditor("#div_editor1"); for(var i=1;i<10;i++) { editor1.selectDoc(false); var p=editor1.insertRootParagraph("P"); p.innerText="paragraph "+i; } ``` -------------------------------- ### RichTextEditor Initialization and Content Management Source: https://richtexteditor.com/docs/api-basics Methods for creating an editor instance, setting its initial HTML content, and retrieving the current content. ```APIDOC ## RichTextEditor Initialization ### Description Initializes a new RichTextEditor instance on a specified DOM element. ### Constructor `new RichTextEditor(selector)` - **selector** (string) - The CSS selector for the target element. --- ## setHTMLCode ### Description Sets the HTML content of the editor. ### Method `editor.setHTMLCode(html)` - **html** (string) - The HTML string to be set as the editor content. --- ## getHTMLCode ### Description Retrieves the current HTML content from the editor. ### Method `editor.getHTMLCode()` ### Returns - **string** - The current HTML content of the editor. ``` -------------------------------- ### Create a toolbar dropdown Source: https://richtexteditor.com/docs/jsapi_createtoolbardropdown Initializes a new dropdown component with custom fillinput and fillpanel functions, then inserts it into the DOM before the editor container. ```javascript var editor1 = new RichTextEditor("#div_editor1"); var option={} option.fillinput=function(span){span.innerText='select..'} option.fillpanel=function(panel){panel.style.width='80px';panel.innerHTML='
a
b
'} var dropdown=editor1.createToolbarDropDown(option,"mycmd"); editor1.container.parentNode.insertBefore(dropdown,editor1.container); ``` -------------------------------- ### Retrieve and use selection from RichTextEditor Source: https://richtexteditor.com/docs/jsapi_getselection Demonstrates initializing an editor, setting content, selecting the document, and retrieving the selection object to calculate its bounding rectangle. ```javascript var editor1 = new RichTextEditor("#div_editor1"); editor1.setHTMLCode("hello world"); editor1.selectDoc(); var sel=editor1.getSelection() console.log(sel) var rect=sel.getRangeAt(0).getBoundingClientRect(); alert("width : "+rect.width); ``` -------------------------------- ### Configure Track Changes Source: https://richtexteditor.com/docs/collaboration-review Enable track changes and set the current user identity. ```javascript { trackChangesEnabled: true, currentUser: { id: "maya", name: "Maya Patel", color: "#9333ea" } } ``` -------------------------------- ### Implement custom file upload handler Source: https://richtexteditor.com/docs/uploadfiles This template demonstrates how to create a UI for file uploads and use XMLHttpRequest to send files to a server-side handler. ```javascript var uploadhandlerpath = "/imageupload.ashx"; function rte_file_upload_handler(file, callback, optionalIndex, optionalFiles) { function append(parent, tagname, csstext) { var tag = parent.ownerDocument.createElement(tagname); if (csstext) tag.style.cssText = csstext; parent.appendChild(tag); return tag; } var uploadcancelled = false; var dialogouter = append(document.body, "div", "display:flex;align-items:center;justify-content:center;z-index:999999;position:fixed;left:0px;top:0px;width:100%;height:100%;background-color:rgba(128,128,128,0.5)"); var dialoginner = append(dialogouter, "div", "background-color:white;border:solid 1px gray;border-radius:15px;padding:15px;min-width:200px;box-shadow:2px 2px 6px #7777"); var line1 = append(dialoginner, "div", "text-align:center;font-size:1.2em;margin:0.5em;"); line1.innerText = "Uploading..."; var totalsize = file.size; var sentsize = 0; if (optionalFiles && optionalFiles.length > 1) { totalsize = 0; for (var i = 0; i < optionalFiles.length; i++) { totalsize += optionalFiles[i].size; if (i < optionalIndex) sentsize = totalsize; } console.log(totalsize, optionalIndex, optionalFiles) line1.innerText = "Uploading..." + (optionalIndex + 1) + "/" + optionalFiles.length; } var line2 = append(dialoginner, "div", "text-align:center;font-size:1.0em;margin:0.5em;"); line2.innerText = "0%"; var progressbar = append(dialoginner, "div", "border:solid 1px gray;margin:0.5em;"); var progressbg = append(progressbar, "div", "height:12px"); var line3 = append(dialoginner, "div", "text-align:center;font-size:1.0em;margin:0.5em;"); var btn = append(line3, "button"); btn.className = "btn btn-primary"; btn.innerText = "cancel"; btn.onclick = function () { uploadcancelled = true; xh.abort(); } var xh = new XMLHttpRequest(); xh.open("POST", uploadhandlerpath + "?name=" + encodeURIComponent(file.name) + "&type=" + encodeURIComponent(file.type) + "&size=" + file.size, true); xh.onload = xh.onabort = xh.onerror = function (pe) { console.log(pe); console.log(xh); dialogouter.parentNode.removeChild(dialogouter); if (pe.type == "load") { if (xh.status != 200) { console.log("uploaderror", pe); if (xh.responseText.startsWith("ERROR:")) { callback(null, "http-error-" + xh.responseText.substring(6)); } else { callback(null, "http-error-" + xh.status); } } else if (xh.responseText.startsWith("READY:")) { console.log("File uploaded to " + xh.responseText.substring(6)); callback(xh.responseText.substring(6)); } else { callback(null, "http-error-" + xh.responseText); } } else if (uploadcancelled) { console.log("uploadcancelled", pe); callback(null, "cancelled"); } else { console.log("uploaderror", pe); callback(null, pe.type); } } xh.upload.onprogress = function (pe) { console.log(pe); //pe.total var percent = Math.floor(100 * (sentsize + pe.loaded) / totalsize); line2.innerText = percent + "%"; progressbg.style.cssText = "background-color:green;width:" + (percent * progressbar.offsetWidth / 100) + "px;height:12px;"; } xh.send(file); } ``` -------------------------------- ### Include CSS and JavaScript assets Source: https://richtexteditor.com/docs/install_div Add the required stylesheet and script files to your HTML document to enable the editor functionality. ```html ``` -------------------------------- ### Create and insert a toolbar button Source: https://richtexteditor.com/docs/jsapi_createtoolbarbutton Creates a button for a specific command and inserts it into the DOM before the editor container. ```javascript var editor1 = new RichTextEditor("#div_editor1"); var btn=editor1.createToolbarButton("bold"); btn.style.width="32px" btn.style.height="32px" editor1.container.parentNode.insertBefore(btn,editor1.container); ``` -------------------------------- ### Configure RichTextBox Health Probes Source: https://richtexteditor.com/docs/operations Enables health probes for AI resolvers and storage backends, with configurable timeouts and cache TTL to prevent excessive load. ```csharp builder.Services.AddRichTextBox(opts => { opts.AiResolverHealthProbeEnabled = true; opts.AiResolverHealthProbeTimeout = TimeSpan.FromSeconds(3); opts.AiResolverHealthProbeCacheTtl = TimeSpan.FromSeconds(30); opts.IdempotencyStoreHealthProbeEnabled = true; opts.UploadStoreHealthProbeEnabled = true; }); ``` -------------------------------- ### Set an image for a command Source: https://richtexteditor.com/docs/jsapi_setimageforcommand Associates a custom element with a specific editor command, such as 'bold'. ```javascript var editor1 = new RichTextEditor("#div_editor1"); var btn=document.createElement("span"); btn.style.cssText="width:32px;height:32px;display:inline-block;border:solid 1px darkgreen"; editor1.container.parentNode.insertBefore(btn,editor1.container); editor1.setImageForCommand(btn,"bold"); ``` -------------------------------- ### Configure Buffering AI Cost Sink Source: https://richtexteditor.com/docs/operations Wraps an existing cost sink with buffering to reduce the frequency of external billing calls for high-traffic tenants. ```csharp builder.Services.AddBufferingAiCostSink( flushInterval: TimeSpan.FromSeconds(30), maxBatchSize: 500); ``` -------------------------------- ### Configure AI Rate Limiting Source: https://richtexteditor.com/docs/operations Adjust the token bucket settings for AI calls to prevent quota exhaustion. Set the limit to 0 to disable rate limiting. ```csharp builder.Services.AddRichTextBox(opts => { opts.AiRateLimit = 30; // calls per window opts.AiRateLimitWindow = TimeSpan.FromMinutes(1); // window length }); ``` ```csharp builder.Services.AddSingleton(); builder.Services.AddRichTextBox(); ``` -------------------------------- ### Attach Yjs Collaboration Source: https://richtexteditor.com/docs/collaboration-review Initialize Yjs and attach it to the editor for concurrent editing. ```javascript import * as Y from "yjs"; import { WebsocketProvider } from "y-websocket"; const ydoc = new Y.Doc(); const provider = new WebsocketProvider("wss://collab.example.com", docId, ydoc); editor.collab.attach({ doc: ydoc, provider: provider, user: { id: "alice", name: "Alice", color: "#2563eb" }, textSync: true // opt-in concurrent typing via shared Y.Text }); ``` -------------------------------- ### Dictation Configuration Options Source: https://richtexteditor.com/docs/dictation Configuration settings used when initializing the RichTextEditor to enable and customize dictation. ```APIDOC ### Options - **dictationEnabled** (boolean) - Default: false - Enables the dictation plugin. - **dictationLang** (string) - Default: navigator.language - BCP-47 language tag (e.g., "en-US"). - **dictationContinuous** (boolean) - Default: true - If true, continues listening; if false, stops after one utterance. - **dictationInterimResults** (boolean) - Default: true - Shows a preview of the speech being processed. - **dictationAutoPunctuation** (boolean) - Default: true - Automatically capitalizes chunks and adds periods. ``` -------------------------------- ### Client-side Streaming Request Source: https://richtexteditor.com/docs/ai-providers-streaming Initiate a streaming AI request from the client using the editor toolkit. ```javascript var stream = editor.aiToolkit.streamRequest({ url: "/richtextbox/ai/stream", body: { mode: "rewrite", selectionText: "..." }, onDelta: function (chunk, full) { /* render progressively */ }, onResponse: function (payload) { /* final structured result */ }, onDone: function (fullText) { }, onError: function (err) { } }); // stream.abort() — cancel mid-response // stream.promise — resolves with the concatenated full text ``` -------------------------------- ### editor.createToolbarButton(cmdname) Source: https://richtexteditor.com/docs/jsapi_createtoolbarbutton Creates a button in the toolbar associated with a specific command name. Returns the created HTMLElement. ```APIDOC ## editor.createToolbarButton(cmdname) ### Description Creates a button in the toolbar with default styles based on the provided command name. ### Syntax `editor.createToolbarButton(cmdname)` ### Parameters - **cmdname** (String) - The name of the command to associate with the button. ### Return Value - **Type**: HTMLElement - **Description**: The created toolbar button element. ### Example Usage ```javascript var editor1 = new RichTextEditor("#div_editor1"); var btn = editor1.createToolbarButton("bold"); btn.style.width = "32px"; btn.style.height = "32px"; editor1.container.parentNode.insertBefore(btn, editor1.container); ``` ``` -------------------------------- ### editor.createToolbarDropDown(option, cmdname) Source: https://richtexteditor.com/docs/jsapi_createtoolbardropdown Creates a dropdown element for the toolbar with custom fill logic for the input and panel areas. ```APIDOC ## editor.createToolbarDropDown ### Description Creates a dropDown in the toolbar with default styles. The method accepts an options object to define the content of the input and the dropdown panel, and a command name. ### Syntax `editor.createToolbarDropDown(option, cmdname)` ### Parameters - **option** (object) - Required - An object containing `fillinput` and `fillpanel` functions to define the dropdown behavior. - **cmdname** (string) - Required - The name of the command associated with the dropdown. ### Return Value - **HTMLElement** - The created toolbar dropdown element. ### Example Usage ```javascript var editor1 = new RichTextEditor("#div_editor1"); var option={}; option.fillinput=function(span){span.innerText='select..'}; option.fillpanel=function(panel){panel.style.width='80px';panel.innerHTML='
a
b
'}; var dropdown=editor1.createToolbarDropDown(option,"mycmd"); editor1.container.parentNode.insertBefore(dropdown,editor1.container); ``` ``` -------------------------------- ### Define a custom toolbar configuration Source: https://richtexteditor.com/docs/toolbar-items-reference Use these identifiers to construct a custom toolbar string, which can then be assigned to the config.toolbar property. ```javascript config.toolbar = "mycustom"; config.toolbar_mycustom = "{bold,italic,underline}|{forecolor,backcolor}|{insertlink,insertimage}|undo,redo"; ``` -------------------------------- ### Override system prompts with PromptTemplateProviderBase Source: https://richtexteditor.com/docs/operations Inherit from PromptTemplateProviderBase to modify system prompts for specific modes while retaining base functionality. ```csharp public sealed class FormalTonePromptProvider : PromptTemplateProviderBase { public override string BuildSystemPrompt(RichTextBoxAiRequest request, string? operatorSuffix) => base.BuildSystemPrompt(request, operatorSuffix) + "\n\nAlways reply in formal British English; avoid contractions."; } ``` -------------------------------- ### Insert an image element using insertByTagName Source: https://richtexteditor.com/docs/jsapi_insertbytagname Demonstrates how to insert an IMG element and set its source attribute. ```javascript var editor1 = new RichTextEditor("#div_editor1"); var img=editor1.insertByTagName("IMG"); img.src="/images/editor-image.png"; ``` -------------------------------- ### Initialize the editor instance Source: https://richtexteditor.com/docs/install_textarea Replace the specified textarea element with a new RichTextEditor instance using its ID. ```javascript ``` -------------------------------- ### new RichTextEditor(elementOrQuery, config) Source: https://richtexteditor.com/docs/initialization Initializes a new RichTextEditor instance by replacing a specified HTML element. ```APIDOC ## new RichTextEditor(elementOrQuery, config) ### Description Creates a new RichTextEditor instance. The editor replaces the target element (div or textarea) and loads its content as the initial document. ### Parameters - **elementOrQuery** (string|object) - Required - An element object, or a CSS selector string (e.g., "#id", ".classname"). - **config** (object) - Optional - Configuration options to initialize the editor. ### Usage Example ```javascript var editor1 = new RichTextEditor("#div_editor1"); ``` ``` -------------------------------- ### Initialize Richtexteditor instance Source: https://richtexteditor.com/docs/install_div Replace the target DIV with an active editor instance using the RichTextEditor constructor. ```javascript ``` -------------------------------- ### Configure Idempotency Settings Source: https://richtexteditor.com/docs/operations Sets the TTL and pruning interval for idempotency keys to manage cached request bodies. ```csharp builder.Services.AddRichTextBox(opts => { opts.IdempotencyTtl = TimeSpan.FromHours(1); opts.IdempotencyPruneInterval = TimeSpan.FromMinutes(5); }); ``` -------------------------------- ### Initialize and manipulate RichTextEditor content Source: https://richtexteditor.com/docs/api-basics Initializes a new editor instance and demonstrates basic HTML content retrieval and setting. ```javascript var editor1 = new RichTextEditor("#div_editor1"); editor1.setHTMLCode("

Hello world

"); var html = editor1.getHTMLCode(); ``` -------------------------------- ### Execute forecolor command Source: https://richtexteditor.com/docs/jsapi_execcommand Applies a specific color to the selected text within the editor. ```javascript var editor2 = new RichTextEditor("#div_editor1"); editor2.execCommand("forecolor","red"); ``` -------------------------------- ### Register AI security policies Source: https://richtexteditor.com/docs/operations Inject custom IRichTextBoxAiPolicy implementations to handle prompt injection screening or other security requirements. ```csharp builder.Services.AddSingleton(); builder.Services.AddSingleton(); ``` -------------------------------- ### Enable Dictation via ASP.NET Core Tag Helper Source: https://richtexteditor.com/docs/dictation Use the richtextbox tag helper to enable dictation settings directly in Razor views. ```html ``` -------------------------------- ### Configure Revision History Source: https://richtexteditor.com/docs/collaboration-review Set revision history settings including snapshot frequency and storage URL. ```javascript { revisionHistoryEnabled: true, revisionHistoryMaxEntries: 50, revisionHistoryAutoSnapshotMs: 10000, revisionHistoryUrl: "/api/revisions" // optional } ``` -------------------------------- ### Perform Markdown and HTML Operations Source: https://richtexteditor.com/docs/structured-content Utilize global helpers to convert between Markdown and document models, render HTML, and validate structured content. ```javascript var restored = RichTextEditor.fromMarkdown("## Hello\n\nMarkdown works too"); var html = RichTextEditor.renderHTML(restored); var validation = RichTextEditor.validateStructuredContent(restored); var markdown = RichTextEditor.toMarkdown(restored); ``` -------------------------------- ### AI Resolver Configuration Options Source: https://richtexteditor.com/docs/ai-providers-streaming The configuration class used for defining provider settings such as API keys, models, and timeouts. ```csharp public class AiResolverOptions { public string ApiKey { get; set; } // required public string? Model { get; set; } // provider-specific default public string? BaseUrl { get; set; } // for proxies / Ollama / Groq public int MaxTokens { get; set; } = 1024; public double Temperature { get; set; } = 0.4; public string? SystemSuffix { get; set; } // appended to every mode's system prompt public TimeSpan Timeout { get; set; } = 60s; } ``` -------------------------------- ### Handle exec_command_newdoc event Source: https://richtexteditor.com/docs/event_exec_command Attaches a listener to the exec_command_newdoc event to override the default behavior and set custom HTML content. ```javascript editor1.attachEvent("exec_command_newdoc", function (state, cmd, value) { state.returnValue = true;//handled, don't execute default action this.setHTMLCode("

NewDoc...

"); }); ``` -------------------------------- ### Commit Bookmark Usage Source: https://richtexteditor.com/docs/jsapi_commitbookmark Creates undo points before and after modifying the editor content. ```javascript var editor1 = new RichTextEditor("#div_editor1"); editor1.commitBookmark(); editor1.setHTMLCode("hello world"); editor1.commitBookmark(); ``` -------------------------------- ### Configure HTTP Retry Policy Source: https://richtexteditor.com/docs/operations Set retry attempts and delay parameters for transient provider failures like 429 or 503 errors. ```csharp services.AddRichTextBoxOpenAiResolver(opts => { opts.ApiKey = builder.Configuration["OpenAI:ApiKey"]; opts.MaxRetryAttempts = 2; // 0 to disable opts.RetryBaseDelay = TimeSpan.FromMilliseconds(500); }); ``` -------------------------------- ### Initialize CRDT mode Source: https://richtexteditor.com/docs/crdt-internals Activates the per-paragraph Yjs binding by attaching the document and provider to the editor instance. ```javascript editor.collab.attach({ doc, provider, textSync: "crdt" }) ``` -------------------------------- ### Surround selection with a tag Source: https://richtexteditor.com/docs/jsapi_surroundbytagname Wraps the selected content within the editor in the specified HTML tag. ```javascript var editor1 = new RichTextEditor("#div_editor1"); editor1.setHTMLCode("hello world"); editor1.selectDoc(); editor1.surroundByTagName("blockquote"); ``` -------------------------------- ### editor.commitBookmark() Source: https://richtexteditor.com/docs/jsapi_commitbookmark Creates a bookmark for the undo record to allow for state restoration. ```APIDOC ## editor.commitBookmark() ### Description Creates a bookmark for the undo record. This allows the editor to track states for undo/redo operations. ### Syntax `editor.commitBookmark()` ### Example usage ```javascript var editor1 = new RichTextEditor("#div_editor1"); editor1.commitBookmark(); editor1.setHTMLCode("hello world"); editor1.commitBookmark(); ``` ``` -------------------------------- ### Set Preview CSS Text Source: https://richtexteditor.com/docs/jsapi_setpreviewcsstext Applies custom CSS styles to the editor's preview area by passing a string of CSS rules. ```javascript var editor1 = new RichTextEditor("#div_editor1"); editor1.setPreviewCssText("body{background-color:gray"); ``` -------------------------------- ### Define target DIV element Source: https://richtexteditor.com/docs/install_div Create a container element with a unique ID to hold the initial content for the editor. ```html

Initial Document Content

``` -------------------------------- ### Retrieve plain text content from RichTextEditor Source: https://richtexteditor.com/docs/jsapi_getplaintext Initializes an editor instance and displays its plain text content via an alert when a button is clicked. ```javascript var editor1 = new RichTextEditor("#div_editor1"); editor1.setHTMLCode("

Hello World

Click the button below to show this text code

"); function btnShowText() { alert(editor1.getText()) } ``` -------------------------------- ### Configure aiToolkitResolver Source: https://richtexteditor.com/docs/ai-toolkit The primary extension point for handling AI requests within the editor. The resolver must return a result object, a string, or a Promise. ```javascript var editor = new RichTextEditor("#editor", { toolbar: "full", aiToolkitResolver: async function (request) { var reply = await fetch("/api/ai", { method: "POST", body: JSON.stringify({ mode: request.mode, text: request.source, language: request.language }) }).then(function (r) { return r.json(); }); return { result: reply.text, // string: the AI output reason: reply.explanation, // string: why this change operations: [{ // structured plan (optional) type: "preview-suggestion", text: reply.text, reason: reply.explanation }] }; } }); ``` -------------------------------- ### Client-side DOCX Export Helper Source: https://richtexteditor.com/docs/ai-providers-streaming Trigger a document export from the client using the editor toolkit. ```javascript editor.aiToolkit.exportDocx({ url: "/richtextbox/export/docx", fileName: "report.docx", title: "Quarterly report" }); ``` -------------------------------- ### Insert an image element into the editor Source: https://richtexteditor.com/docs/jsapi_insertelement Creates an image element using the editor's document and inserts it into the editor instance. ```javascript var editor1 = new RichTextEditor("#div_editor1"); var img=editor1.document.createElement("IMG"); img.src="/images/editor-image.png"; editor1.insertElement(img); ``` -------------------------------- ### Create a custom dialog with RichTextEditor Source: https://richtexteditor.com/docs/jsapi_createdialog Initializes a new dialog instance and appends custom content to it. The dialog is automatically closed after a 2-second timeout. ```javascript var editor1 = new RichTextEditor("#div_editor1"); var dlg=editor1.createDialog("Hello","myclass"); var panel=dlg.appendChild(document.createElement("div")); panel.innerText="My Dialog Content"; setTimeout(function(){ dlg.close() },2000); ``` -------------------------------- ### editor.surroundByTagName(tagname) Source: https://richtexteditor.com/docs/jsapi_surroundbytagname Wraps the selected content in the editor with the specified HTML tag and returns the newly created element. ```APIDOC ## editor.surroundByTagName(tagname) ### Description Get the content of selection and place it into an element. Then insert this new element. ### Syntax `editor.surroundByTagName(tagname)` ### Parameters - **tagname** (String) - Required - The tagname of the elements you want to insert. ### Return Value - **HTMLElement** - The HtmlElement that was just inserted. ### Example ```javascript var editor1 = new RichTextEditor("#div_editor1"); editor1.setHTMLCode("hello world"); editor1.selectDoc(); editor1.surroundByTagName("blockquote"); ``` ``` -------------------------------- ### editor.aiToolkit Programmatic API Source: https://richtexteditor.com/docs/ai-toolkit Methods to programmatically control AI dialogs, panels, and actions. ```APIDOC ## Programmatic API ### Dialogs - `editor.aiToolkit.openDialog({ presetMode: string, autoRun: boolean })` - Opens the Ask AI dialog. ### Quick Actions - `editor.aiToolkit.runQuickAction(mode: string, options?: object)` - Executes an action without a dialog. ### Panels - `editor.aiToolkit.openChatPanel(options?: object)` - `editor.aiToolkit.closeChatPanel()` - `editor.aiToolkit.toggleChatPanel()` - `editor.aiToolkit.openReviewPanel(options?: object)` - `editor.aiToolkit.closeReviewPanel()` - `editor.aiToolkit.toggleReviewPanel()` ### Utilities - `editor.aiToolkit.resolveAction(mode: string, context: object)` - Resolves an action without rendering. - `editor.aiToolkit.setResolver(resolver: function)` - Swaps the resolver at runtime. - `editor.aiToolkit.registerOperationHandler(type: string, handler: function)` - Registers a custom operation type. ``` -------------------------------- ### editor.setImageForCommand(element, cmdname) Source: https://richtexteditor.com/docs/jsapi_setimageforcommand Adds an image (svg or png) for a specified command name to the provided element. ```APIDOC ## editor.setImageForCommand ### Description Adds an image (svg or png) for a specified command name to the element. For details, please refer to the plugin example. ### Syntax `editor.setImageForCommand(element, cmdname)` ### Parameters - **element** (HTMLElement) - The HTML element to which the image will be applied. - **cmdname** (String) - The name of the command to associate with the element. ### Return Value - **HTMLElement** - The specified HTML Element. - **String** - The name of the command. ### Example Usage ```javascript var editor1 = new RichTextEditor("#div_editor1"); var btn = document.createElement("span"); btn.style.cssText = "width:32px;height:32px;display:inline-block;border:solid 1px darkgreen"; editor1.container.parentNode.insertBefore(btn, editor1.container); editor1.setImageForCommand(btn, "bold"); ``` ``` -------------------------------- ### Apply Mobile Toolbar Site-wide Source: https://richtexteditor.com/docs/mobile-toolbar Apply the 'rte-mobile' class to the body element to enable mobile mode for all editors on the page. ```html ... ``` -------------------------------- ### editor.surroundElement(element) Source: https://richtexteditor.com/docs/jsapi_surroundelement Creates an element using editor.document, places the content of the current selection into that element, and inserts it into the document. ```APIDOC ## editor.surroundElement(element) ### Description Creates an element using editor.document, places the content of the current selection into the element, and then inserts this new element into the document. ### Syntax `editor.surroundElement(element)` ### Parameters - **element** (HTMLElement) - Required - The new element to insert. ### Example Usage ```javascript var editor1 = new RichTextEditor("#div_editor1"); editor1.setHTMLCode("hello world"); editor1.selectDoc(); var element = editor1.document.createElement("BLOCKQUOTE"); editor1.surroundElement(element); ``` ``` -------------------------------- ### Set focus on RichTextEditor instance Source: https://richtexteditor.com/docs/jsapi_focus Initializes a new editor instance and sets the focus to it. ```javascript var editor1 = new RichTextEditor("#div_editor1"); editor1.focus(); ``` -------------------------------- ### Select Document in RichTextEditor Source: https://richtexteditor.com/docs/jsapi_selectdoc Demonstrates inserting an image element into the editor and subsequently selecting the document. ```javascript var editor1 = new RichTextEditor("#div_editor1"); var img=editor1.document.createElement("IMG"); img.src="/images/editor-image.png"; editor1.insertElement(img); editor1.selectDoc(img) ``` -------------------------------- ### editor.mentions.register Source: https://richtexteditor.com/docs/collaboration-review Registers a trigger-character framework for mentions or custom prefixes. ```APIDOC ## editor.mentions.register({ trigger, insertClass, search, renderItem, renderInsert }) Registers a new mention trigger (e.g., '@', '#'). ### Parameters - **trigger** (string) - The character that triggers the mention menu. - **insertClass** (string) - CSS class for the inserted mention pill. - **search** (function) - Async function to fetch data based on query. - **renderItem** (function) - Function to render the item in the menu. - **renderInsert** (function) - Function to render the item in the editor. ``` -------------------------------- ### POST /richtextbox/export/docx Source: https://richtexteditor.com/docs/ai-providers-streaming Converts HTML content into a downloadable DOCX file. ```APIDOC ## POST /richtextbox/export/docx ### Description Converts provided HTML content into a binary DOCX file stream. ### Method POST ### Endpoint /richtextbox/export/docx ### Request Body - **html** (string) - Required - The HTML content to convert. - **title** (string) - Optional - The document title. - **fileName** (string) - Optional - The desired filename for the exported DOCX. ### Response #### Success Response (200) - **Content-Type** (header) - application/vnd.openxmlformats-officedocument.wordprocessingml.document - **Body** (binary) - The generated DOCX file stream. ``` -------------------------------- ### Manage Editor JSON Content Source: https://richtexteditor.com/docs/structured-content Use getJSON to retrieve the current document model and setJSON to restore content from a node-based structure. ```javascript var documentModel = editor.getJSON(); editor.setJSON({ type: "doc", version: 2, format: "richtexteditor-json", content: [ { type: "paragraph", content: [{ type: "text", text: "Restored from JSON" }] } ] }); ``` -------------------------------- ### editor.slashCommands Source: https://richtexteditor.com/docs/collaboration-review Methods to manage slash commands within the editor. ```APIDOC ## editor.slashCommands.register({ id, label, keywords, run }) Registers a new slash command. ## editor.slashCommands.remove(id) Removes a registered slash command by ID. ## editor.slashCommands.list() Returns a list of registered slash commands. ## editor.slashCommands.open() / .close() Opens or closes the slash command menu. ``` -------------------------------- ### window.RichTextEditorCrdt.htmlToYFragment(options) Source: https://richtexteditor.com/docs/crdt-internals Migrates legacy HTML content into a Yjs fragment for CRDT-based synchronization. ```APIDOC ## window.RichTextEditorCrdt.htmlToYFragment(options) ### Description Converts a legacy HTML string into a Yjs fragment structure to initialize a new CRDT-enabled document. ### Parameters - **ydoc** (Y.Doc) - Required - The target Yjs document. - **html** (string) - Required - The legacy HTML content string. - **parserDocument** (Document) - Required - The browser document object used for parsing. ``` -------------------------------- ### editor.setHTMLCode(html) Source: https://richtexteditor.com/docs/initialization Sets the HTML content of the editor. ```APIDOC ## editor.setHTMLCode(html) ### Description Updates the editor content with the provided HTML string. ### Parameters - **html** (string) - Required - The HTML content to set in the editor. ``` -------------------------------- ### editor.collab.attach Source: https://richtexteditor.com/docs/collaboration-review Attaches a Yjs document and provider to the editor for real-time collaboration. ```APIDOC ## editor.collab.attach({ doc, provider, user, textSync }) ### Parameters - **doc** (Y.Doc) - The Yjs document instance. - **provider** (Object) - The Yjs provider (e.g., WebsocketProvider). - **user** (Object) - User metadata (id, name, color). - **textSync** (boolean) - Whether to enable concurrent typing via shared Y.Text. ``` -------------------------------- ### editor.getJSON() Source: https://richtexteditor.com/docs/structured-content Retrieves the current editor content as a semantic document tree including compatibility fields. ```APIDOC ## editor.getJSON() ### Description Returns a semantic document tree representing the current editor content, including necessary compatibility fields. ### Returns - **documentModel** (Object) - The semantic representation of the editor content. ``` -------------------------------- ### Configure Threaded Comments Source: https://richtexteditor.com/docs/collaboration-review Enable threaded comments and set the current user identity. ```javascript { commentsEnabled: true, currentUser: { id: "alice", name: "Alice Lee", color: "#2563eb" } } ``` -------------------------------- ### editor.focus() Source: https://richtexteditor.com/docs/jsapi_focus The focus method attempts to set the focus of the editor content window. ```APIDOC ## editor.focus() ### Description Attempts to set the focus of the editor content window. ### Syntax `editor.focus()` ### Example usage ```javascript var editor1 = new RichTextEditor("#div_editor1"); editor1.focus(); ``` ``` -------------------------------- ### Submit content via API Source: https://richtexteditor.com/docs/quick-start Manually retrieve the editor content for dynamic form submissions using fetch. ```javascript document.getElementById("save").addEventListener("click", function () { fetch("/api/save", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ html: editor.getHTMLCode() }) }); }); ``` -------------------------------- ### Read and write content Source: https://richtexteditor.com/docs/quick-start Use the editor API to programmatically retrieve or update the content in HTML, plain text, or JSON formats. ```javascript // Get the current HTML var html = editor.getHTMLCode(); // Replace the editor's content editor.setHTMLCode("

New content

"); // Get plain text (no markup) var text = editor.getPlainText(); // Get a structured-content JSON document (lossless round-trip with setJSON()) var json = editor.getJSON(); editor.setJSON(json); ``` -------------------------------- ### editor.aiToolkit.registerDialogMode Source: https://richtexteditor.com/docs/ai-toolkit Registers a new mode in the AI action dropdown menu. ```APIDOC ## editor.aiToolkit.registerDialogMode(mode) ### Description Registers a new dialog mode that appears in the AI Action dropdown menu. ### Parameters - **id** (string) - Required - Unique identifier for the mode. - **title** (string) - Required - Display title for the mode. - **description** (string) - Required - Brief description of the mode's purpose. ``` -------------------------------- ### Toggle read-only state with editor.getReadOnly() Source: https://richtexteditor.com/docs/jsapi_getreadonly Demonstrates how to retrieve the current read-only status and toggle it using the setReadOnly method. ```javascript var editor1 = new RichTextEditor("#div_editor1"); var toggleBtn=document.getElementById("btn_toggle"); toggleBtn.onclick=function(){ editor1.setReadOnly( ! editor1.getReadOnly() ); } ```