### Local Development Setup and Run Source: https://github.com/opentiny/tiny-editor/blob/main/CONTRIBUTING.md Installs project dependencies and starts the local development server for the TinyEditor project. Ensure you have cloned the repository and associated the upstream remote. ```shell # Clone your personal repository git clone git@github.com:username/tiny-editor.git cd tiny-editor # Associate the upstream repository git remote add upstream git@github.com:opentiny/tiny-editor.git # Install dependencies pnpm i # Start the local project pnpm dev ``` -------------------------------- ### Set up TinyEditor Development Environment Source: https://github.com/opentiny/tiny-editor/blob/main/README.md Clones the TinyEditor repository, installs dependencies using pnpm, and starts the development server. This is for contributing to or modifying the editor. ```shell git clone git@github.com:opentiny/tiny-editor.git cd tiny-editor pnpm i pnpm dev ``` -------------------------------- ### Initialize TinyEditor with HTML and JavaScript (npm) Source: https://github.com/opentiny/tiny-editor/blob/main/packages/docs/fluent-editor/docs/quick-start.md Demonstrates how to set up the HTML structure and initialize TinyEditor using JavaScript after installation via npm. Assumes the necessary CSS is imported separately. ```html

Hello TinyEditor!

``` ```css @import '@opentiny/fluent-editor/style.css'; ``` ```javascript import FluentEditor from '@opentiny/fluent-editor' // 执行初始化时,请确保能获取到 DOM 元素,如果是在 Vue 项目中,需要在 onMounted 事件中执行。 const editor = new FluentEditor('#editor', { theme: 'snow', }) ``` -------------------------------- ### Initialize TinyEditor with CDN Source: https://github.com/opentiny/tiny-editor/blob/main/packages/docs/fluent-editor/docs/quick-start.md Shows how to use TinyEditor via CDN by including script tags in your HTML. This method is useful for quick setup without a build process. ```html
``` -------------------------------- ### JavaScript: Basic Editor Initialization Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Initializes a basic instance of the Tiny-Editor using JavaScript. This snippet demonstrates the fundamental setup required to get the editor running on a web page. It assumes the necessary editor library is already included. ```javascript var editor = new Tiny.Editor({ selector: '#myeditor', plugins: 'link image code', toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | code' }); ``` -------------------------------- ### Install Quill-Toolbar-Tip via npm Source: https://github.com/opentiny/tiny-editor/blob/main/packages/docs/fluent-editor/docs/modules/toolbar-tip.md This command installs the Quill-Toolbar-Tip package using npm. This package provides the functionality for custom toolbar tooltips in the FluentEditor. Ensure you have Node.js and npm installed. ```bash npm install quill-toolbar-tip ``` -------------------------------- ### Basic Vue.js App Setup (Vite) Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This snippet shows a basic Vue.js application setup using Vite. It demonstrates the core structure of a Vue component and how to render it within an app. No external dependencies are required beyond Vue.js itself. ```javascript import { createApp } from "vue" import App from "./App.vue" createApp(App).mount('#app') ``` ```html Vite App
``` ```javascript ``` -------------------------------- ### Vue Component: Modal Dialog Example Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Demonstrates the implementation of a modal dialog component. This example shows how to control the modal's visibility, add content, and handle confirmation/cancellation actions. ```html ``` -------------------------------- ### Install TinyEditor with npm Source: https://github.com/opentiny/tiny-editor/blob/main/README.md Installs the TinyEditor package using npm. This is the first step to integrating TinyEditor into your project. ```shell npm i @opentiny/fluent-editor ``` -------------------------------- ### JavaScript: Inserting and Retrieving Content Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Provides examples for programmatically inserting content into the editor and retrieving the current content. Essential for managing editor state. ```javascript // Set content editor.setContent('

Hello, Tiny-Editor!

'); // Get content const currentContent = editor.getContent(); console.log(currentContent); ``` -------------------------------- ### Vue Component: Basic Button Example Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Demonstrates the basic usage of a button component in Vue.js. This snippet shows how to import, register, and render a button with customizable text and event handling. ```html ``` -------------------------------- ### Handling Tiny Editor Events (JavaScript) Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This example demonstrates how to bind event handlers to the tiny-editor instance. This allows you to react to user actions like content changes or focus shifts. Ensure the editor instance is available. ```javascript tinymce.init({ selector: '#my-editor', // ... other configurations setup: function(editor) { editor.on('init', function() { console.log('Editor is ready!'); }); editor.on('Change', function() { console.log('Content changed!'); }); editor.on('Focus', function() { console.log('Editor focused!'); }); } }); ``` -------------------------------- ### Array Operations in Python Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Provides examples of fundamental array (list) operations in Python, such as creating, accessing, modifying, and iterating through elements. These are essential for data management within the editor. ```python # Create a list my_list = [1, 2, 3, 4, 5] # Access an element first_element = my_list[0] # Modify an element my_list[2] = 10 # Iterate through the list for item in my_list: print(item) # Append an element my_list.append(6) print(my_list) ``` -------------------------------- ### Content Management in Tiny Editor (JavaScript) Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Demonstrates how to get and set the content of the tiny-editor instance. This is crucial for loading existing content or saving user-generated text. It relies on the editor instance created previously. ```javascript // Get content const content = editor.getContent(); console.log(content); // Set content editor.setContent('

This is new content!

'); ``` -------------------------------- ### Add Contributor to List Source: https://github.com/opentiny/tiny-editor/blob/main/CONTRIBUTING.md Command to add a user to the contributor list using the all-contributors bot. This should be used in issues or pull requests to recognize contributions. ```shell @all-contributors please add @ for ``` -------------------------------- ### TypeScript: Editor Configuration and Initialization Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This TypeScript snippet outlines a potential configuration object and initialization function for the Tiny-Editor. It uses types to define the expected structure of configuration options, promoting type safety and clarity in editor setup. Dependencies include standard TypeScript features. ```typescript interface TinyEditorConfig { selector: string; plugins?: string[]; toolbar?: string; height?: number; } function initializeTinyEditor(config: TinyEditorConfig): void { const element = document.querySelector(config.selector); if (!element) { console.error(`Element with selector "${config.selector}" not found.`); return; } // Placeholder for actual editor initialization logic console.log('Initializing Tiny-Editor with config:', config); // Example: element.innerHTML = '
'; } const editorConfig: TinyEditorConfig = { selector: '#my-editor-instance', plugins: ['link', 'image'], toolbar: 'bold italic | link image', height: 400 }; initializeTinyEditor(editorConfig); ``` -------------------------------- ### Use Default English Tooltips with FluentEditor Source: https://github.com/opentiny/tiny-editor/blob/main/packages/docs/fluent-editor/docs/modules/toolbar-tip.md This TypeScript code snippet demonstrates how to register and use the QuillToolbarTip module with FluentEditor, utilizing the default English tooltip texts. It imports necessary components, registers the module, and configures the editor with default options. Ensure `@opentiny/fluent-editor` and `quill-toolbar-tip` are installed. ```typescript import FluentEditor from '@opentiny/fluent-editor' import QuillToolbarTip, { defaultToolbarTip } from 'quill-toolbar-tip' import 'quill-toolbar-tip/dist/index.css' FluentEditor.register( { [`modules/${QuillToolbarTip.moduleName}`]: QuillToolbarTip, }, true, ) const QuillToolbarTipOption = { tipTextMap: defaultToolbarTip['en-US'], } const editor = new FluentEditor('#editor', { theme: 'snow', modules: { toolbar: [ ['bold', 'italic'], [{ list: 'ordered' }, { list: 'bullet' }], [{ script: 'sub' }, { script: 'super' }], [{ color: [] }, { background: [] }], ], [QuillToolbarTip.moduleName]: QuillToolbarTipOption, }, }) ``` -------------------------------- ### Initialize Tiny-Editor with Enhanced Table Module (JavaScript) Source: https://context7.com/opentiny/tiny-editor/llms.txt Shows how to initialize the Tiny-Editor with the enhanced table module, enabling features like drag-to-resize and cell operations. This includes configuration for table insertion buttons, custom text labels, and enabling keyboard shortcuts for table manipulation. The example also demonstrates programmatic table insertion. ```javascript import TinyEditor, { generateTableUpShortKeyMenu } from '@opentiny/fluent-editor' const editor = new TinyEditor('#editor', { theme: 'snow', modules: { toolbar: [ [{ 'table-up': 'TD' }], // Table insertion button ['bold', 'italic'] ], 'table-up': { fullWidth: true, texts: { customBtnText: 'Custom Table', confirmText: 'Insert', cancelText: 'Cancel', rowText: 'Rows', colText: 'Columns', fullCheckboxText: 'Full Width' } }, 'shortcut-key': { 'table-up': generateTableUpShortKeyMenu() // Enable table shortcuts } } }) // Programmatically insert table editor.focus() const range = editor.getSelection(true) editor.insertEmbed(range.index, 'table-up', { rows: 3, cols: 4, fullWidth: false }) // Table keyboard shortcuts (when enabled): // - Tab: Move to next cell // - Shift+Tab: Move to previous cell // - Ctrl+M: Insert row below // - Ctrl+Shift+M: Insert column right // - Ctrl+Alt+M: Delete current row // - Context menu: Right-click for operations (merge, split, delete, etc.) ``` -------------------------------- ### Basic File Upload in Vue Source: https://github.com/opentiny/tiny-editor/blob/main/packages/docs/fluent-editor/docs/demo/file-upload.md Demonstrates the default file upload behavior in Tiny Editor, which automatically handles video and image formats, treating others as generic files. This example uses a Vue.js component. ```Vue ``` -------------------------------- ### Initialize Tiny-Editor with AI Module (JavaScript) Source: https://context7.com/opentiny/tiny-editor/llms.txt Demonstrates how to initialize the Tiny-Editor with the AI module enabled. It includes configuration for API keys, models, character limits, and predefined operation and result menus. This setup allows for AI-powered content generation and editing directly within the editor. ```javascript import TinyEditor from '@opentiny/fluent-editor' const editor = new TinyEditor('#editor', { theme: 'snow', modules: { toolbar: [ ['ai'], // Add AI button to toolbar ['bold', 'italic'] ], ai: { host: 'https://api.openai.com/v1', apiKey: 'your-api-key-here', model: 'gpt-4', textNumber: 5000, // Character limit // Predefined operation menu items operationMenuList: [ { id: 'improve', title: 'Improve Writing', prompt: 'Improve the following text while keeping the same meaning:' }, { id: 'summarize', title: 'Summarize', prompt: 'Summarize the following text in 2-3 sentences:' }, { id: 'expand', title: 'Expand', prompt: 'Expand the following text with more details:' }, { id: 'tone', title: 'Change Tone', submenu: [ { id: 'professional', title: 'Professional', prompt: 'Rewrite in professional tone:' }, { id: 'casual', title: 'Casual', prompt: 'Rewrite in casual tone:' }, { id: 'friendly', title: 'Friendly', prompt: 'Rewrite in friendly tone:' } ] } ], // Result action buttons resultMenuList: [ { id: 'insert', title: 'Insert Below', icon: 'insert-icon' }, { id: 'replace', title: 'Replace Selection', icon: 'replace-icon' }, { id: 'copy', title: 'Copy', icon: 'copy-icon' } ] } } }) // Trigger AI generation programmatically const aiModule = editor.getModule('ai') const selectedText = editor.getText(0, 100) // Custom AI request async function generateWithAI(prompt, selectedText) { const response = await fetch(`${aiModule.host}/chat/completions`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${aiModule.apiKey}` }, body: JSON.stringify({ model: aiModule.model, messages: [ { role: 'system', content: 'You are a helpful writing assistant.' }, { role: 'user', content: `${prompt}\n\n${selectedText}` } ], stream: true }) }) return response.body } ``` -------------------------------- ### Customize Toolbar Tooltip Texts in FluentEditor Source: https://github.com/opentiny/tiny-editor/blob/main/packages/docs/fluent-editor/docs/modules/toolbar-tip.md This TypeScript code illustrates how to customize the tooltip texts for the FluentEditor toolbar by providing a custom `tipTextMap`. It shows how to map specific toolbar formats (like 'bold', 'italic', 'color', 'background') to custom strings or functions for dynamic text generation. Ensure `quill-toolbar-tip` and `@opentiny/fluent-editor` are installed. ```typescript import QuillToolbarTip from 'quill-toolbar-tip' import 'quill-toolbar-tip/dist/index.css' FluentEditor.register( { [`modules/${QuillToolbarTip.moduleName}`]: QuillToolbarTip, }, true, ) const QuillToolbarTipOption = { tipTextMap: { bold: 'Bold', italic: 'Italic', color: { onShow(target, value) { return `Font Color${value ? `: ${value}` : ''}` }, }, background: { onShow(target, value) { return `Background Color${value ? `: ${value}` : ''}` }, }, }, } const editor = new FluentEditor('#editor', { theme: 'snow', modules: { toolbar: [ ['bold', 'italic'], [{ list: 'ordered' }, { list: 'bullet' }], [{ script: 'sub' }, { script: 'super' }], [{ color: [] }, { background: [] }], ], [QuillToolbarTip.moduleName]: QuillToolbarTipOption, }, }) ``` -------------------------------- ### Registering Custom Formats and Modules in TinyEditor Source: https://context7.com/opentiny/tiny-editor/llms.txt Extends TinyEditor with custom blots (formats) and modules. This example demonstrates registering a custom 'highlight' inline format and a 'wordcount' module. Dependencies include '@opentiny/fluent-editor' and 'quill'. ```javascript import TinyEditor, { Parchment } from '@opentiny/fluent-editor' import Quill from 'quill' // Define custom inline format const Inline = Quill.import('blots/inline') class HighlightBlot extends Inline { static blotName = 'highlight' static tagName = 'mark' static className = 'highlight' static create(value) { const node = super.create() node.setAttribute('data-color', value) node.style.backgroundColor = value return node } static formats(node) { return node.getAttribute('data-color') } } // Define custom module class WordCountModule { constructor(quill, options) { this.quill = quill this.container = document.querySelector(options.container) quill.on('text-change', () => { const text = quill.getText() const words = text.trim().split(/\s+/).length this.container.innerText = `Words: ${words}` }) } } // Register custom components TinyEditor.register({ 'formats/highlight': HighlightBlot, 'modules/wordcount': WordCountModule }) // Use custom components const editor = new TinyEditor('#editor', { theme: 'snow', modules: { toolbar: [ [{ 'highlight': ['yellow', 'green', 'pink'] }], ['bold', 'italic'] ], wordcount: { container: '#word-count' } } }) // Apply custom format programmatically const range = editor.getSelection() if (range) { editor.formatText(range.index, range.length, 'highlight', 'yellow') } ``` -------------------------------- ### JavaScript: Editor Events Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Demonstrates how to bind event listeners to the Tiny-Editor to react to user interactions. This example shows how to log a message whenever the editor's content changes. Custom event handling can be implemented for various editor actions. ```javascript editor.on('change', function(e) { console.log('Editor content changed!'); }); ``` -------------------------------- ### Vue Component: Input Field with Validation Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Illustrates an input field component with built-in validation logic. This example shows how to bind input values, define validation rules, and display error messages. ```html ``` -------------------------------- ### JavaScript: Editor Content Manipulation Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Demonstrates how to get and set the content of the Tiny-Editor using JavaScript. This is useful for loading existing data or saving the editor's current state. It assumes an editor instance has already been created. ```javascript const editorInstance = tinymce.get('myeditor'); // Get content const content = editorInstance.getContent(); console.log(content); // Set content editorInstance.setContent('

This is new content!

'); ``` -------------------------------- ### Get Editor Module Instance Source: https://github.com/opentiny/tiny-editor/blob/main/packages/docs/fluent-editor/docs/api/fluent-editor-instance.md Retrieves an instance of a specific module within the TinyEditor (Quill) instance. The 'name' parameter should be the module name, not the full path (e.g., 'toolbar' instead of 'modules/toolbar'). ```typescript class Quill { getModule(name: string): any } const toolbar = quill.getModule('toolbar') const i18n = quill.getModule('i18n') ``` -------------------------------- ### TypeScript: Editor Content Manipulation Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Demonstrates how to get and set the content of the Tiny-Editor using TypeScript. This is useful for loading existing data or saving the editor's current state. It assumes an editor instance has already been created. ```typescript const editorInstance = new Editor({ selector: "#myeditor" }); // Get content const content = editorInstance.getContent(); console.log(content); // Set content editorInstance.setContent('

This is new content!

'); ``` -------------------------------- ### Get Editor Contents as Delta Source: https://github.com/opentiny/tiny-editor/blob/main/packages/docs/fluent-editor/docs/api/fluent-editor-instance.md Fetches the Delta data representing the editor's content. Optional 'index' and 'length' parameters can be provided to retrieve a specific portion of the content. If omitted, the entire content is returned. ```typescript class Quill { getContents(index: number = 0, length: number = remaining): Delta } const delta = editor.getContents() ``` -------------------------------- ### Configure Character Counter Module (JavaScript) Source: https://context7.com/opentiny/tiny-editor/llms.txt Shows how to integrate and configure the Character Counter module for TinyEditor, enabling character or word counting with customizable templates and limits. It also demonstrates accessing the counter module programmatically to get the current content length. ```javascript import TinyEditor from '@opentiny/fluent-editor' const editor = new TinyEditor('#editor', { theme: 'snow', modules: { toolbar: true, counter: { unit: 'char', // 'char' or 'word' format: 'text', // 'text' or 'html' count: 500, // Maximum count template: '{{count}} / {{totalCount}} {{countUnit}}', errorTemplate: 'Exceeded limit by {{restCount}} {{countUnit}}' } } }) // Custom template function const editorWithCustomCounter = new TinyEditor('#editor2', { modules: { counter: { unit: 'word', count: 200, template: (count, restCount) => { return `Words: ${count}, Remaining: ${restCount}` }, errorTemplate: (count, restCount) => { return `Over limit! Remove ${Math.abs(restCount)} words` } } } }) // Access counter programmatically const counterModule = editor.getModule('counter') const currentLength = counterModule.getContentLength('text') ``` -------------------------------- ### JavaScript: Getting Plain Text Content from Tiny-Editor Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This JavaScript code demonstrates how to retrieve the plain text representation of the content currently in the Tiny-Editor. The `getText` method is called on the editor instance, returning a string stripped of all HTML formatting. This is useful for tasks like character counting or simple text storage. ```javascript // Assuming 'editor' is an instance of TinyEditor function getPlainText(editorInstance) { const plainText = editorInstance.getText(); console.log('Plain text content:', plainText); return plainText; } // Example usage: // const currentText = getPlainText(editor); ``` -------------------------------- ### Configure Emoji Picker in Tiny-Editor (JavaScript) Source: https://context7.com/opentiny/tiny-editor/llms.txt This snippet shows how to enable and configure the emoji picker module in Tiny-Editor using JavaScript. It covers options for theme, locale, emoji set, positioning of UI elements, and categories. It also includes examples of programmatically opening/closing the picker and inserting emojis. ```javascript import TinyEditor from '@opentiny/fluent-editor' const editor = new TinyEditor('#editor', { theme: 'snow', modules: { toolbar: [ ['emoji'], // Add emoji button to toolbar ['bold', 'italic'] ], emoji: { theme: 'light', // 'light' or 'dark' locale: 'en', // Language for emoji search set: 'native', // 'native', 'apple', 'google', 'twitter', 'facebook' skinTonePosition: 'none', // 'none', 'search', 'preview' previewPosition: 'bottom', // 'top', 'bottom', 'none' searchPosition: 'sticky', // 'sticky', 'static', 'none' categories: [ 'frequent', 'people', 'nature', 'foods', 'activity', 'places', 'objects', 'symbols', 'flags' ], maxFrequentRows: 2, perLine: 8, navPosition: 'top', // 'top', 'bottom', 'none' noCountryFlags: false, dynamicWidth: false } } }) // Programmatically open/close emoji picker const emojiModule = editor.getModule('emoji') emojiModule.openDialog() emojiModule.closeDialog() // Insert emoji programmatically const range = editor.getSelection(true) editor.insertText(range.index, '😀', 'user') editor.setSelection(range.index + 2) ``` -------------------------------- ### JavaScript: Basic Editor Initialization and Configuration Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Demonstrates how to initialize and configure the Tiny-Editor using JavaScript. Covers essential options for setting up the editor instance. ```javascript const editor = new TinyEditor({ selector: '#myeditor', plugins: 'lists link image', // Example plugins toolbar: 'undo redo | bold italic | link image' }); ``` -------------------------------- ### Tiny Editor Configuration and Initialization (JavaScript) Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This snippet shows how to configure and initialize the tiny-editor. It demonstrates setting up basic options and creating an instance of the editor. Dependencies include the core tiny-editor library. ```javascript const editor = new TinyEditor({ selector: '#my-editor', plugins: 'lists link image charmap print preview anchor', toolbar: 'undo redo | formatselect | bold italic | alignleft aligncenter alignright | bullist numlist outdent indent | link image', height: 500 }); ``` -------------------------------- ### Configuration Loading and Management in JavaScript Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This snippet deals with loading and managing configuration settings for the tiny-editor. This could involve reading settings from a file, an object, or a remote source. It ensures the editor behaves according to specified parameters. ```javascript function loadConfiguration(configPath) { // Implementation for loading configuration console.log('Loading configuration from:', configPath); return {}; // Placeholder for configuration object } ``` -------------------------------- ### Initialize Basic TinyEditor and Manage Content (JavaScript) Source: https://context7.com/opentiny/tiny-editor/llms.txt Demonstrates how to initialize a basic TinyEditor instance with a toolbar, set and retrieve editor content in various formats (HTML, plain text, Delta), and listen for text change events. Requires the '@opentiny/fluent-editor' package and its CSS. ```javascript import TinyEditor from '@opentiny/fluent-editor' import '@opentiny/fluent-editor/style.css' // Create editor from HTML element const editor = new TinyEditor('#editor', { theme: 'snow', placeholder: 'Start typing...', modules: { toolbar: [ ['bold', 'italic', 'underline', 'strike'], ['blockquote', 'code-block'], [{ 'header': 1 }, { 'header': 2 }], [{ 'list': 'ordered' }, { 'list': 'bullet' }], [{ 'indent': '-1' }, { 'indent': '+1' }], ['link', 'image', 'video'], ['clean'] ] } }) // Get editor content const content = editor.root.innerHTML const text = editor.getText() const delta = editor.getContents() // Set editor content editor.setText('Hello World') editor.setContents([{ insert: 'Hello ' }, { insert: 'World', attributes: { bold: true } }]) // Listen to text changes editor.on('text-change', (delta, oldDelta, source) => { console.log('Text changed:', delta) console.log('Current length:', editor.getLength()) }) ``` -------------------------------- ### JavaScript: Rich Text Editor Initialization with Options Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This JavaScript code demonstrates the initialization of the Tiny-Editor with various configuration options. It shows how to set the placeholder text, enable or disable specific features like spell checking and auto-saving, and define the initial content of the editor. This is crucial for customizing the editor's behavior and appearance. ```javascript const editorOptions = { placeholder: 'Enter your text here...', spellcheck: true, autoSave: { enable: true, interval: 5000 // Save every 5 seconds }, initialContent: '

This is the initial content.

', // Other configuration options can be added here }; // Assuming TinyEditor is a globally available class or imported module const editor = new TinyEditor(editorOptions); editor.render('#editor-container'); // Render the editor into a specific DOM element ``` -------------------------------- ### JavaScript: Configuration Options for Tiny Editor Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This JavaScript snippet shows how to configure the Tiny Editor instance. It defines a configuration object that can be passed during initialization to customize behavior, appearance, and features. This allows for flexible integration into different applications. Input is a JavaScript object, output is a configured editor instance. ```JavaScript const editorConfig = { theme: 'dark', plugins: [ 'bold', 'italic', 'underline', 'lists', 'link' ], toolbar: 'bold italic | alignleft aligncenter | bullist numlist | link', height: 300, menubar: false }; // Assuming tinymce is loaded and available tinymce.init({ selector: '#my-editor', ...editorConfig }); ``` -------------------------------- ### Configure Tiny-Editor Initialization Options (JavaScript) Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This JavaScript code shows various initialization options for the Tiny-Editor. It covers settings related to plugins, toolbar configuration, theme, height, and other general editor behaviors. ```javascript tinymce.init({ selector: 'textarea', plugins: 'anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount checklist mediaembed casechange export formatpainter pagebreak', toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline | link image media table mergetags | align lineheight | checklist numlist bullist indent outdent | emoticons charmap | removeformat', height: 400, width: 800, menubar: 'file edit view insert format tools table', // Other configuration options... }); ``` -------------------------------- ### JavaScript: Getting Editor Content Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Retrieves the current content of the Tiny-Editor instance. This function is typically used when a user submits a form or when saving the editor's state. It returns the HTML content as a string. ```javascript var content = editor.getContent(); console.log(content); ``` -------------------------------- ### Configuration Loading Function Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This function is responsible for loading configuration settings, potentially from a file or environment variables. It returns a configuration object used to initialize the editor. Error handling for missing or invalid configurations is crucial. ```javascript import fs from 'fs'; function loadConfig(configPath = './config.json') { try { const configData = fs.readFileSync(configPath, 'utf-8'); return JSON.parse(configData); } catch (error) { console.error(`Error loading configuration from ${configPath}:`, error); // Return default configuration or throw an error return { theme: 'light', plugins: [] }; } } const editorConfig = loadConfig(); console.log('Loaded Config:', editorConfig); ``` -------------------------------- ### JavaScript: Basic Editor Initialization Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Initializes a basic instance of the Tiny-Editor using JavaScript. This is a fundamental step for integrating the editor into an application. It requires the 'tiny-editor' package. ```javascript const editor = tinymce.init({ selector: "#myeditor", plugins: "lists link image", toolbar: "undo redo | bold italic | alignleft aligncenter alignright | code", height: 400 }); ``` -------------------------------- ### TypeScript: Basic Editor Initialization Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Initializes a basic instance of the Tiny-Editor using TypeScript. This is a fundamental step for integrating the editor into an application. It requires the 'tiny-editor' package. ```typescript import Editor from "@opentiny/tiny-editor"; const editor = new Editor({ selector: "#myeditor", plugins: "lists link image", toolbar: "undo redo | bold italic | alignleft aligncenter alignright | code", height: 400 }); ``` -------------------------------- ### Tiny Editor Plugin Integration (JavaScript) Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Illustrates how to add and configure plugins for the tiny-editor. Plugins extend the editor's functionality, such as adding image upload or link features. Ensure the plugin JavaScript files are correctly included. ```javascript tinymce.init({ selector: '#my-editor', plugins: 'code visualblocks visualaid fullscreen image link media table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help', toolbar: 'formatselect | bold italic strikethrough forecolor backcolor | link image media | alignleft aligncenter alignright alignjustify | numlist bullist outdent indent | removeformat | help', menubar: 'file edit view insert format tools table', // ... other configurations }); ``` -------------------------------- ### Basic Data Structure Operations in Go Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Demonstrates fundamental operations on slices (Go's dynamic arrays) and maps (key-value pairs) in Go. These are building blocks for managing data within the editor's backend logic. ```go package main import "fmt" func main() { // Slice operations smySlice := []int{1, 2, 3, 4, 5} fmt.Println("Slice:", mySlice) fmt.Println("First element:", mySlice[0]) smySlice = append(mySlice, 6) fmt.Println("Appended slice:", mySlice) // Map operations myMap := make(map[string]int) myMap["apple"] = 1 myMap["banana"] = 2 fmt.Println("Map:", myMap) fmt.Println("Value for apple:", myMap["apple"]) delete(myMap, "banana") fmt.Println("Map after delete:", myMap) } ``` -------------------------------- ### Handle Text Input and Formatting in Tiny-Editor (JavaScript) Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This snippet demonstrates how to handle text input and apply basic formatting within the Tiny-Editor using JavaScript. It captures user input, processes it, and updates the editor's content. Dependencies include the editor's core API. ```javascript function handleTextInput(event) { const inputText = event.target.value; // Process inputText and apply formatting applyFormatting(inputText); updateEditorContent(inputText); } ``` -------------------------------- ### Initialize TinyEditor Instance Source: https://github.com/opentiny/tiny-editor/blob/main/packages/docs/fluent-editor/docs/api/fluent-editor-instance.md Initializes a TinyEditor rich text editor instance and provides the editor object. The editor is based on Quill, so its instance object inherits all variables and methods from the Quill instance. ```typescript import FluentEditor from '@opentiny/fluent-editor' // TinyEditor 实例对象 const editor = new FluentEditor(container, options) ``` -------------------------------- ### String Searching and Slicing in Python Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Illustrates how to perform string searching (finding substrings) and slicing (extracting parts of strings) in Python. This is useful for text analysis and manipulation within the editor's context. ```python text = "This is a sample string for demonstration." # Find the starting index of a substring index = text.find("sample") print(f"'sample' found at index: {index}") # Slice the string to get a portion substring = text[10:20] print(f"Substring from index 10 to 20: '{substring}'") # Check if a string starts or ends with a substring starts_with_this = text.startswith("This") ends_with_tion = text.endswith("demonstration.") print(f"Starts with 'This': {starts_with_this}") print(f"Ends with 'demonstration.': {ends_with_tion}") ``` -------------------------------- ### Initialize TinyEditor Source: https://github.com/opentiny/tiny-editor/blob/main/packages/docs/fluent-editor/docs/api/options.md Demonstrates the basic initialization of the TinyEditor rich text editor. It requires a container element (CSS selector or DOM object) and an options object for customization. ```typescript import FluentEditor from '@opentiny/fluent-editor' const editor = new FluentEditor(container, options) ``` -------------------------------- ### Dynamically Generate Tooltip Text for Script Formats Source: https://github.com/opentiny/tiny-editor/blob/main/packages/docs/fluent-editor/docs/modules/toolbar-tip.md This JavaScript code demonstrates how to dynamically generate tooltip text for the 'script' format (subscript/superscript) in FluentEditor using the `onShow` function within `tipTextMap`. This approach allows for context-aware tooltip messages based on the script type. Note that if `onShow` is used, the string or `msg`/`content` values are ignored. ```javascript const QuillToolbarTipOption = { tipTextMap: { script: { onShow(target, value) { const text = { sub: 'Subscript', super: 'Superscript', } return text[value] || null }, }, }, } ``` -------------------------------- ### Event Bus or Pub/Sub Implementation in JavaScript Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This snippet likely implements an event bus or publish/subscribe mechanism. This pattern is useful for decoupling different parts of the application, allowing components to communicate without direct dependencies. It facilitates asynchronous event handling. ```javascript class EventBus { constructor() { this.listeners = {}; } on(event, callback) { if (!this.listeners[event]) { this.listeners[event] = []; } this.listeners[event].push(callback); } emit(event, data) { if (this.listeners[event]) { this.listeners[event].forEach(callback => callback(data)); } } } ``` -------------------------------- ### Handle Image Uploads in Tiny-Editor (JavaScript) Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This JavaScript code snippet demonstrates the process of handling image uploads within the Tiny-Editor. It includes logic for selecting an image file, uploading it to a server, and inserting the image URL into the editor content. ```javascript function handleImageUpload(file) { const formData = new FormData(); formData.append('image', file); fetch('/upload-image', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { insertImageIntoEditor(data.imageUrl); }) .catch(error => { console.error('Image upload failed:', error); }); } ``` -------------------------------- ### Markdown Parsing and Rendering Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This snippet demonstrates how to parse Markdown text and render it into HTML. It typically involves a Markdown parsing library. The output is an HTML string, and it's generally safe for direct DOM insertion if properly sanitized. ```javascript import MarkdownIt from 'markdown-it'; const md = new MarkdownIt(); const markdownText = '# Hello, Tiny Editor!\n\nThis is a **bold** text. And *italic* text.'; const htmlResult = md.render(markdownText); console.log(htmlResult); // Output:

Hello, Tiny Editor!

This is a bold text. And italic text.

``` -------------------------------- ### Syntax Highlighting Utility Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground A utility function for applying syntax highlighting to code blocks within the editor. This function takes a language identifier and the code string as input and returns the highlighted HTML. It may rely on external libraries like highlight.js. ```javascript import hljs from 'highlight.js'; function highlightCode(code, language) { if (language && hljs.getLanguage(language)) { return hljs.highlight(code, { language: language }).value; } else { return code; } } const javascriptCode = 'function greet() { console.log("Hello!"); }'; const highlightedJs = highlightCode(javascriptCode, 'javascript'); console.log(highlightedJs); // Output: function greet() { console.log("Hello!"); } ``` -------------------------------- ### String Manipulation and Parsing with JavaScript Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground Demonstrates common string manipulation and parsing techniques in JavaScript, useful for handling text data within the editor. This snippet focuses on basic string operations and regular expression matching. ```javascript function parseString(str) { // Example: Remove leading/trailing whitespace const trimmedStr = str.trim(); // Example: Replace occurrences of a substring const replacedStr = trimmedStr.replace(/old/g, 'new'); // Example: Split string into an array const parts = replacedStr.split('-'); return { trimmedStr, replacedStr, parts }; } const inputText = " some old text example "; const result = parseString(inputText); console.log(result); ``` -------------------------------- ### JavaScript: Toolbar Button Configuration for Tiny-Editor Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This snippet outlines the configuration for toolbar buttons in the Tiny-Editor. It defines an array of button objects, each with a type, name, and optional configuration. This allows for customization of the editor's user interface and available formatting options. Dependencies include the editor's internal component system. ```javascript const toolbarConfig = [ { type: 'button', name: 'bold' }, { type: 'button', name: 'italic' }, { type: 'button', name: 'underline' }, { type: 'separator' }, { type: 'dropdown', name: 'fontSize', options: ['12px', '16px', '20px'] }, { type: 'button', name: 'insertImage' }, { type: 'button', name: 'insertLink' } ]; // Example of how this might be used to initialize the editor: // const editor = new TinyEditor({ // toolbar: toolbarConfig, // // other configurations... // }); ``` -------------------------------- ### CSS: Styling for Tiny Editor Components Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This snippet provides CSS rules for styling components within the Tiny Editor. It covers basic layout, typography, and interactive element styling. These styles are essential for the visual presentation and user experience of the editor. No specific JavaScript dependencies are required, but they complement editor functionality. ```CSS .tiny-editor-toolbar { background-color: #f0f0f0; padding: 10px; border-bottom: 1px solid #ccc; } .tiny-editor-button { background-color: #fff; border: 1px solid #ddd; padding: 5px 10px; margin-right: 5px; cursor: pointer; } .tiny-editor-button:hover { background-color: #e0e0e0; } ``` -------------------------------- ### JavaScript: Basic DOM Manipulation for Tiny-Editor Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This snippet demonstrates fundamental JavaScript DOM manipulation techniques likely used within the Tiny-Editor for element creation and modification. It assumes a browser environment and does not include external dependencies. ```javascript function createEditorElement(tagName, attributes = {}) { const element = document.createElement(tagName); for (const key in attributes) { element.setAttribute(key, attributes[key]); } return element; } function appendContent(parentElement, content) { if (typeof content === 'string') { parentElement.textContent = content; } else { parentElement.appendChild(content); } } const editorContainer = createEditorElement('div', { id: 'tiny-editor' }); const toolbar = createEditorElement('div', { class: 'toolbar' }); const contentArea = createEditorElement('div', { contenteditable: true, class: 'content' }); appendContent(toolbar, createEditorElement('button', { class: 'bold-btn' }, 'B')); appendContent(editorContainer, toolbar); appendContent(editorContainer, contentArea); document.body.appendChild(editorContainer); ``` -------------------------------- ### Initialize TinyEditor in JavaScript Source: https://github.com/opentiny/tiny-editor/blob/main/README.md Initializes the TinyEditor instance by targeting an HTML element and configuring its theme. It requires importing the editor and its styles. ```javascript import TinyEditor from '@opentiny/fluent-editor' const editor = new TinyEditor('#editor', { theme: 'snow', }) ``` -------------------------------- ### Import TinyEditor CSS Styles Source: https://github.com/opentiny/tiny-editor/blob/main/README.md Imports the necessary CSS styles for TinyEditor to render correctly. This should be done before initializing the editor. ```css @import '@opentiny/fluent-editor/style.css'; ``` -------------------------------- ### Initialize TinyEditor with HTML and JavaScript Source: https://github.com/opentiny/tiny-editor/blob/main/README.zh-CN.md Demonstrates how to set up a basic HTML structure for the editor and then initialize TinyEditor using JavaScript. It includes importing the editor, defining the HTML container, and creating a new editor instance with theme configuration. ```html

Hello TinyEditor!

``` ```css @import '@opentiny/fluent-editor/style.css'; ``` ```javascript import TinyEditor from '@opentiny/fluent-editor' const editor = new TinyEditor('#editor', { theme: 'snow', }) ``` -------------------------------- ### Loading Editor State and Data in JavaScript Source: https://github.com/opentiny/tiny-editor/wiki/Fluent-Editor-Playground This snippet is responsible for loading previously saved editor state and data. This allows users to resume editing from where they left off. It would typically involve retrieving stored data and reconstructing the editor's state. ```javascript function loadEditorState() { // Implementation for loading editor state console.log('Loading editor state...'); // ... retrieval and reconstruction logic ... return {}; // Placeholder for loaded state } ```