### Complete TinyMDE Editor and CommandBar Example
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-commandbar.md
A full example showing the initialization of a TinyMDE Editor with custom inline grammar and a CommandBar with various default and custom commands, including event listener setup.
```javascript
// Create editor
const editor = new TinyMDE.Editor({
element: 'editor-container',
placeholder: 'Write your markdown...',
customInlineGrammar: {
highlight: {
regexp: /^(==)([^=]+)(==)/,
replacement: '$2'
}
}
});
// Create custom toolbar with default and custom commands
const commandBar = new TinyMDE.CommandBar({
element: 'toolbar',
editor: editor,
commands: [
'bold',
'italic',
'strikethrough',
'|',
'code',
'|',
'h1',
'h2',
'h3',
'|',
'ul',
'ol',
'blockquote',
'|',
{
name: 'highlight',
title: 'Highlight (Alt+H)',
innerHTML: '🎨',
hotkey: 'Alt-H',
action: (editor) => {
editor.wrapSelection('==', '==');
}
},
'|',
'insertLink',
'insertImage',
'|',
'undo',
'redo'
]
});
// Listen for changes
editor.addEventListener('change', (event) => {
console.log('Document changed');
// Save to server, etc.
});
```
--------------------------------
### Start Development Server
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/CLAUDE.md
Starts the development server with live reloading for rapid development.
```bash
npm run dev
```
--------------------------------
### Customized TinyMDE Command Bar Setup
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/docs/index.md
Initializes a TinyMDE editor and a custom command bar. This example demonstrates how to specify a subset of commands, customize existing ones, and add new commands with custom actions.
```html
```
--------------------------------
### Custom Command Hotkey Examples
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/configuration.md
Examples demonstrating various formats for defining hotkeys for commands.
```javascript
hotkey: 'Mod-B' // Ctrl+B / Cmd+B
hotkey: 'Mod-Shift-K' // Ctrl+Shift+K / Cmd+Shift+K
hotkey: 'Alt-I' // Alt+I
hotkey: 'Mod2-Shift-5'// Option+Shift+5 / Alt+Shift+5
```
--------------------------------
### Install TinyMDE
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/REFERENCE.md
Install the tiny-markdown-editor package using npm.
```bash
npm install tiny-markdown-editor
```
--------------------------------
### Hotkey Syntax Examples
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-commandbar.md
Examples demonstrating the string format for specifying hotkeys with modifier keys and a specific key.
```javascript
hotkey: 'Mod-B' // Ctrl+B on Windows, Cmd+B on Mac
```
```javascript
hotkey: 'Mod-Shift-K' // Ctrl+Shift+K on Windows, Cmd+Shift+K on Mac
```
```javascript
hotkey: 'Alt-I' // Alt+I on Windows
```
```javascript
hotkey: 'Mod2-Shift-5' // Alt+Shift+5 on Windows, Option+Shift+5 on Mac
```
--------------------------------
### Create a Simple TinyMDE Editor
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/README.md
Instantiate a basic TinyMDE editor as a child of a specified HTML element. This example shows the minimal setup for a standalone editor.
```html
```
--------------------------------
### Custom Command Action Example
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/configuration.md
Example of defining a custom command with a specific action function.
```javascript
{
name: 'uppercase',
action: (editor) => {
const content = editor.getContent();
editor.setContent(content.toUpperCase());
}
}
```
--------------------------------
### Complete TinyMDE Editor Configuration Example
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/configuration.md
This comprehensive example demonstrates how to initialize the TinyMDE Editor and CommandBar with various configurations, including custom inline grammar, custom commands, and inline styling. It also includes event listeners for content changes and selection events.
```javascript
// Create editor with full configuration
const editor = new TinyMDE.Editor({
element: 'editor-container',
placeholder: 'Write your markdown...',
customInlineGrammar: {
highlight: {
regexp: /^(==)([^=]+)(==)/,
replacement: '$2'
}
}
});
// Create command bar with custom commands
const commandBar = new TinyMDE.CommandBar({
element: 'toolbar',
editor: editor,
commands: [
'bold',
'italic',
'strikethrough',
'|',
'code',
'|',
'h1',
'h2',
'|',
'ul',
'ol',
'blockquote',
'|',
{
name: 'highlight',
title: 'Highlight',
innerHTML: '🎨',
hotkey: 'Mod-Shift-H',
action: (editor) => {
editor.wrapSelection('==', '==');
},
enabled: (editor) => {
return editor.isInlineFormattingAllowed() ? false : null;
}
},
'|',
'insertLink',
'insertImage',
'|',
'undo',
'redo'
]
});
// Style the editor
const style = document.createElement('style');
style.textContent = `
.TinyMDE {
border: 1px solid #ddd;
padding: 12px;
min-height: 300px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
font-size: 14px;
line-height: 1.6;
}
.TMCommandBar {
display: flex;
gap: 4px;
padding: 8px;
background: #f5f5f5;
border-bottom: 1px solid #ddd;
flex-wrap: wrap;
}
.TMCommandButton {
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid #ccc;
background: white;
cursor: pointer;
border-radius: 4px;
}
.TMCommandButton:hover:not(.TMCommandButton_Disabled) {
background: #e8e8e8;
}
.TMCommandButton_Active {
background: #0066cc;
color: white;
}
.TMCommandButton_Disabled {
opacity: 0.5;
cursor: not-allowed;
}
.TMCommandDivider {
width: 1px;
background: #ddd;
margin: 0 4px;
}
.TMStrong { font-weight: bold; }
.TMEm { font-style: italic; }
.TMCode { background: #f4f4f4; padding: 2px 6px; }
.TMStrikethrough { text-decoration: line-through; }
.highlight { background-color: yellow; padding: 2px 6px; }
`;
document.head.appendChild(style);
// Listen for changes
editor.addEventListener('change', (event) => {
console.log('Content updated:', event.content.length, 'characters');
});
editor.addEventListener('selection', (event) => {
console.log('Selection:', event.focus, event.anchor);
});
```
--------------------------------
### Complete TinyMDE Editor Setup
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/REFERENCE.md
Demonstrates a full HTML page setup for the TinyMDE editor, including custom inline grammar for highlighting and a custom command bar. This is useful for a complete, standalone integration.
```html
```
--------------------------------
### Install Dependencies and Build TinyMDE
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/README.md
Install project dependencies using npm and build the TinyMDE project. This command generates the necessary distribution and library files.
```bash
npm install
# You may need to run npm install --force
npm run build
```
--------------------------------
### Basic Editor and CommandBar Setup
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/index-reference.md
Initialize the TinyMDE editor and its associated command bar. The command bar requires an instance of the editor to function.
```javascript
// Create editor
const editor = new TinyMDE.Editor({
element: 'editor-container',
placeholder: 'Write markdown...'
});
// Create toolbar
const commandBar = new TinyMDE.CommandBar({
element: 'toolbar',
editor: editor
});
// Listen for changes
editor.addEventListener('change', (event) => {
console.log(event.content);
});
```
--------------------------------
### Custom Command Definition Example
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/types.md
Example of defining a custom toolbar command with a name, title, icon, hotkey, action, and custom enabled logic.
```javascript
const customCmd: CommandDefinition = {
name: 'myCmd',
title: 'My Command',
innerHTML: '✨',
hotkey: 'Mod-Shift-M',
action: (editor) => {
editor.paste('✨ Magic! ✨');
},
enabled: (editor) => {
return editor.isInlineFormattingAllowed() ? false : null;
}
};
```
--------------------------------
### Example CSS for CommandBar Styling
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-commandbar.md
Provides example CSS rules for styling the CommandBar, its buttons (active, inactive, disabled states), and dividers to customize the toolbar's appearance.
```css
.TMCommandBar {
display: flex;
gap: 4px;
padding: 8px;
background: #f5f5f5;
border-bottom: 1px solid #ddd;
}
.TMCommandButton {
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid #ccc;
background: white;
cursor: pointer;
border-radius: 4px;
}
.TMCommandButton_Active {
background: #0066cc;
color: white;
}
.TMCommandButton_Inactive {
background: white;
}
.TMCommandButton_Disabled {
opacity: 0.5;
cursor: not-allowed;
}
.TMCommandDivider {
width: 1px;
background: #ddd;
margin: 0 4px;
}
```
--------------------------------
### Custom Command Action Example
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/types.md
Example of a custom command action that converts the editor's content to uppercase.
```javascript
const myCommand: CommandAction = (editor) => {
const content = editor.getContent();
editor.setContent(content.toUpperCase());
};
```
--------------------------------
### Basic TinyMDE Editor Setup
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/REFERENCE.md
Basic HTML and JavaScript setup for embedding the TinyMDE editor. Ensure the script and CSS files are linked correctly.
```html
```
--------------------------------
### Custom Command innerHTML Example
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/configuration.md
Example of setting custom HTML content for a command button, such as an emoji or SVG.
```javascript
{
name: 'myCommand',
innerHTML: '✨', // Emoji
// Or SVG
innerHTML: ''
}
```
--------------------------------
### Install TinyMDE from NPM
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/README.md
Install the TinyMDE package using npm. This is suitable for projects using bundlers like Webpack or Rollup.
```bash
npm install --save tiny-markdown-editor
```
--------------------------------
### Basic TinyMDE Editor and Command Bar Setup
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/docs/index.md
Initializes a TinyMDE editor and its associated command bar, linking them to specific HTML elements. This is suitable for a standard editor interface.
```html
```
--------------------------------
### Custom Inline Grammar Example
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/types.md
Example of defining custom inline grammar rules for highlighting and mentions. These rules are passed to the editor's constructor.
```javascript
const customGrammar = {
highlight: {
regexp: /^(==)([^=]+)(==)/,
replacement: '$2'
},
mention: {
regexp: /^(@[a-zA-Z0-9_]+)/,
replacement: '$1'
}
};
const editor = new TinyMDE.Editor({
element: 'editor',
customInlineGrammar: customGrammar
});
```
--------------------------------
### Clone TinyMDE Repository
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/README.md
Clone the TinyMDE repository from GitHub to start building the project. This is the first step in the build process.
```bash
git clone git@github.com:jefago/tiny-markdown-editor.git
```
--------------------------------
### Example of Merging Custom Inline Grammar
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/grammar.md
Demonstrates how to define and merge custom inline grammar rules, such as a 'highlight' rule, with the existing grammar.
```javascript
const customRules = {
highlight: {
regexp: /^(==)([^=]+)(==)/,
replacement: '$2'
}
};
const merged = createMergedInlineGrammar(customRules);
// merged now contains all built-in rules plus the custom highlight rule
```
--------------------------------
### Custom Command Enabled Logic Example
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/types.md
Example of a custom CommandEnabled function that checks if inline formatting is allowed and disables the command at the beginning of the document.
```javascript
const isHighlightAllowed: CommandEnabled = (editor, focus, anchor) => {
if (!editor.isInlineFormattingAllowed()) return null;
if (focus?.row === 0 && focus?.col < 10) return null; // Disabled at start
return false; // Available but not active
};
```
--------------------------------
### CSS for Placeholder Styling
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/configuration.md
Example CSS to style the placeholder text using the `data-placeholder` attribute on the editor div when it's empty.
```css
.TinyMDE.TinyMDE_empty::before {
content: attr(data-placeholder);
color: #999;
}
```
--------------------------------
### TinyMDE Editor Setup Without Command Bar
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/docs/index.md
Initializes a TinyMDE editor without a command bar, useful for simpler interfaces or when commands are managed externally. Requires only an element for the editor.
```html
```
--------------------------------
### Configure Minimum Release Age for Dependencies
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/CLAUDE.md
Sets a minimum age for installing package versions to mitigate supply-chain attacks. Requires npm 11.10+.
```ini
min-release-age=7
```
--------------------------------
### Handle File Drop in Editor
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/types.md
Listens for the 'drop' event to process dropped files. This example iterates through the DataTransfer items to identify and log the names of dropped files.
```javascript
editor.addEventListener('drop', (event) => {
for (let i = 0; i < event.dataTransfer.items.length; i++) {
if (event.dataTransfer.items[i].kind === 'file') {
const file = event.dataTransfer.items[i].getAsFile();
console.log('Dropped file:', file.name);
}
}
});
```
--------------------------------
### Initialize TinyMDE Editor
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/src/html/demo.html
Initializes a TinyMDE editor instance attached to a textarea element. This is the basic setup for using the editor.
```javascript
// Create editor element, initialized to a textarea
tinyMDE = new TinyMDE.Editor({textarea: 'txt'});
```
--------------------------------
### Example of HTML Escaping
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/grammar.md
Shows how to use the htmlescape function to convert special HTML characters into their entity equivalents for safe display.
```javascript
const safe = htmlescape('5 < 10 && 10 > 5');
// Returns: '5 < 10 && 10 > 5'
```
--------------------------------
### Position Object Example
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/REFERENCE.md
Represents a zero-based position within the editor content, defined by a row and column. Used for cursor and selection management.
```javascript
const pos = {row: 0, col: 5}; // First line, 6th character
```
--------------------------------
### getSelection()
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-editor.md
Gets the current cursor position or selection range. It can return either the focus (end) or anchor (start) of the selection.
```APIDOC
## getSelection()
### Description
Gets the current cursor position or selection. It can return either the focus (end) or anchor (start) of the selection.
### Method
```typescript
public getSelection(getAnchor: boolean = false): Position | null
```
### Parameters
#### Query Parameters
- **getAnchor** (boolean) - Optional - If true, returns anchor (start); if false, returns focus (end). Defaults to false.
### Returns
- **Position | null**: Current cursor/selection position or null if not in editor
### Example
```javascript
const focus = editor.getSelection(); // Get cursor end position
const anchor = editor.getSelection(true); // Get selection start position
console.log(focus); // {row: 2, col: 15}
```
```
--------------------------------
### Get Cursor Position or Selection
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-editor.md
Retrieves the current cursor's focus (end) or anchor (start) position within the editor. Returns null if the editor is not focused.
```typescript
public getSelection(getAnchor: boolean = false): Position | null
```
```javascript
const focus = editor.getSelection(); // Get cursor end position
const anchor = editor.getSelection(true); // Get selection start position
console.log(focus); // {row: 2, col: 15}
```
--------------------------------
### Initialize CommandBar
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/README.md
Set up the optional toolbar for the markdown editor. It can be configured with a predefined list of commands.
```typescript
const commandBar = new CommandBar({
element: 'toolbar',
editor: editor,
commands: ['bold', 'italic', '|', 'h1', 'h2', ...]
});
```
--------------------------------
### Import and Initialize TinyMDE via NPM
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/README.md
Import the TinyMDE package and initialize a new editor instance. Ensure you also include the CSS for styling.
```javascript
const TinyMDE = require('tiny-markdown-editor');
var tinyMDE = new TinyMDE.Editor({element: 'editor'});
```
--------------------------------
### CommandBar Initialization with Custom Command List
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/configuration.md
Initializes the CommandBar with a specific subset of built-in commands.
```javascript
new TinyMDE.CommandBar({
element: 'toolbar',
editor: editor,
commands: [
'bold',
'italic',
'|',
'code',
'|',
'h1',
'h2',
'h3'
]
});
```
--------------------------------
### Custom CommandBar with Custom Actions
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-commandbar.md
Demonstrates creating a CommandBar with custom commands, including a 'myCustom' command that wraps selection and an 'insertDate' command that pastes the current date.
```javascript
const commandBar = new TinyMDE.CommandBar({
element: 'toolbar',
editor: editor,
commands: [
'bold',
'italic',
'|',
{
name: 'myCustom',
title: 'My Custom Button',
innerHTML: '🎨',
hotkey: 'Mod-Shift-X',
action: (editor) => {
editor.wrapSelection('', '');
}
},
{
name: 'insertDate',
title: 'Insert Date',
innerHTML: '📅',
action: (editor) => {
const date = new Date().toLocaleDateString();
editor.paste(date);
},
enabled: (editor) => {
// Only enable if not in code block
return editor.isInlineFormattingAllowed() ? false : null;
}
}
]
});
```
--------------------------------
### CommandBar Initialization with Custom Commands
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/configuration.md
Initializes the CommandBar with both built-in and custom-defined commands, including custom actions and hotkeys.
```javascript
new TinyMDE.CommandBar({
element: 'toolbar',
editor: editor,
commands: [
'bold',
'italic',
'|',
{
name: 'highlight',
title: 'Highlight Text',
innerHTML: '🎨',
hotkey: 'Mod-Shift-H',
action: (editor) => {
editor.wrapSelection('==', '==');
}
},
{
name: 'insertDate',
title: 'Insert Current Date',
innerHTML: '📅',
action: (editor) => {
const today = new Date().toLocaleDateString();
editor.paste(today);
}
}
]
});
```
--------------------------------
### CommandBar Initialization with Editor Instance
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/configuration.md
Initializes the CommandBar and associates it with an existing Editor instance.
```javascript
const editor = new TinyMDE.Editor({element: 'editor'});
const commandBar = new TinyMDE.CommandBar({
element: 'toolbar',
editor: editor
});
```
--------------------------------
### Mention Username Rule
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/grammar.md
Defines a grammar rule to identify and format mentions starting with '@'. This is useful for user tagging features.
```javascript
const mention: GrammarRule = {
regexp: /^(@[a-zA-Z0-9_]+)/,
replacement: '$1'
};
```
--------------------------------
### CommandBar Initialization with Element
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/configuration.md
Initializes the CommandBar, specifying the container element by ID.
```javascript
new TinyMDE.CommandBar({
element: 'toolbar',
editor: editor
});
```
--------------------------------
### Pre-publish Build and Test Pipeline
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/CLAUDE.md
Runs the full build, test, and transpilation process required before publishing the package.
```bash
npm run prepublishOnly
```
--------------------------------
### Initialize Editor
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/README.md
Instantiate the core markdown editor with basic configuration. Supports custom inline grammar for extended markdown support.
```typescript
const editor = new Editor({
element: 'editor-container',
placeholder: 'Write markdown...',
customInlineGrammar: {/* custom rules */}
});
```
--------------------------------
### Build Production Assets
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/CLAUDE.md
Compiles and minifies JavaScript, CSS, and HTML for production deployment.
```bash
npm run build
```
--------------------------------
### Selection Management Operations
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/index-reference.md
Methods for getting the current cursor/selection position and setting a new selection. Position is defined by row and column.
```javascript
// Selection
const pos = editor.getSelection();
editor.setSelection({row: 0, col: 5});
```
--------------------------------
### HTMLBlockRule Interface
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/types.md
Defines the rules for detecting HTML blocks within markdown, including start and end patterns and paragraph interruption behavior.
```typescript
export interface HTMLBlockRule {
start: RegExp;
end: RegExp | false;
paraInterrupt: boolean;
}
```
--------------------------------
### Initialize CommandBar with Custom Commands
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-commandbar.md
Instantiate a CommandBar, linking it to an editor instance and specifying a custom array of commands to display. The 'element' parameter targets the DOM where the toolbar will be rendered.
```javascript
const editor = new TinyMDE.Editor({element: 'editor'});
const commandBar = new TinyMDE.CommandBar({
element: 'toolbar',
editor: editor,
commands: ['bold', 'italic', '|', 'h1', 'h2', '|', 'ul', 'ol']
});
```
--------------------------------
### Connect Editor Instance to CommandBar
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-commandbar.md
Demonstrates how to programmatically link an existing TinyMDE Editor instance to a CommandBar instance after both have been created. This is useful when the editor and toolbar are initialized separately or at different times.
```javascript
const editor = new TinyMDE.Editor({element: 'editor'});
const commandBar = new TinyMDE.CommandBar({element: 'toolbar'});
commandBar.setEditor(editor); // Connect editor to toolbar
```
--------------------------------
### CommandBar Constructor
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-commandbar.md
Initializes a new instance of the CommandBar class. It accepts a configuration object to customize its appearance and behavior, including the target DOM element, the associated editor instance, and the list of commands to display.
```APIDOC
## Constructor CommandBar
### Description
Initializes a new instance of the CommandBar class with provided configuration.
### Signature
```typescript
constructor(props: CommandBarProps)
```
### Parameters
#### props (CommandBarProps) - Required
Configuration object for command bar initialization.
##### CommandBarProps Interface
- **element** (string | HTMLElement) - Optional - DOM element (ID or reference) where toolbar will be created. Defaults to `document.body`.
- **editor** (Editor) - Optional - Editor instance to control.
- **commands** (Array) - Optional - List of commands to display as buttons. Defaults to a predefined array of commands.
### Example
```javascript
const editor = new TinyMDE.Editor({element: 'editor'});
const commandBar = new TinyMDE.CommandBar({
element: 'toolbar',
editor: editor,
commands: ['bold', 'italic', '|', 'h1', 'h2', '|', 'ul', 'ol']
});
```
```
--------------------------------
### Get Editor Content
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-editor.md
Retrieves the current markdown content from the editor as a string. This is useful for saving the editor's state or processing the content.
```typescript
const markdown = editor.getContent();
console.log(markdown); // '# New Content\n\nWith **bold** text'
```
--------------------------------
### Create TinyMDE Editor with Command Bar
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/README.md
Instantiate both the TinyMDE editor and its associated CommandBar. This requires separate HTML elements for the editor and the toolbar.
```html
```
--------------------------------
### Replace Selection with Text
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-editor.md
Replaces a specified range of text within the editor with new content. Define the start and end positions of the text to be replaced.
```typescript
editor.paste('replacement', {row: 0, col: 5}, {row: 0, col: 10});
```
--------------------------------
### getCommandState()
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-editor.md
Gets the state of all formatting commands at the current or a specified selection. Returns an object indicating whether commands are active, inactive but applicable, or not applicable.
```APIDOC
## getCommandState()
### Description
Gets the state of all formatting commands at the current or a specified selection. Returns an object indicating whether commands are active, inactive but applicable, or not applicable.
### Method
```typescript
public getCommandState(focus: Position | null = null, anchor: Position | null = null): Record
```
### Parameters
#### Query Parameters
- **focus** (Position) - Optional - Cursor position (defaults to current)
- **anchor** (Position) - Optional - Selection start (defaults to current)
### Returns
- **Record**: Command state object where:
- `true` = command is active
- `false` = command is inactive but applicable
- `null` = command not applicable at this position
### Example
```javascript
const state = editor.getCommandState();
console.log(state.bold); // true if cursor in bold text
console.log(state.h1); // true if on heading 1 line
console.log(state.code); // false if can apply code formatting
```
```
--------------------------------
### CommandBar Class Initialization
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/REFERENCE.md
Initialize the optional TinyMDE CommandBar (toolbar) component. It can be linked to an existing editor instance.
```typescript
const commandBar = new CommandBar(props: CommandBarProps);
```
--------------------------------
### Custom Grammar Rule for User Mentions
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/README.md
Defines a custom grammar rule for user mentions starting with '@'. The regexp captures the username, and the replacement wraps it in a span with the TMMention class for styling.
```javascript
mention: {
regexp: /^(@[a-zA-Z0-9_]+)/,
replacement: '$1'
}
```
--------------------------------
### Import TinyMDE Editor and CommandBar via NPM
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/REFERENCE.md
Shows how to import the Editor and CommandBar classes when using TinyMDE as an NPM module. This is suitable for projects managed with npm or yarn.
```javascript
const { Editor, CommandBar } = require('tiny-markdown-editor');
const editor = new Editor({element: 'editor'});
const commandBar = new CommandBar({element: 'toolbar', editor});
```
--------------------------------
### HTML Block Grammar Rules
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/grammar.md
An array of rules used to detect HTML blocks within markdown. Each rule defines start and end patterns for different types of HTML constructs.
```typescript
export const htmlBlockGrammar: HTMLBlockRule[]
```
--------------------------------
### Editor Constructor
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-editor.md
Initializes a new instance of the Editor class. It accepts an optional configuration object to set up the editor's appearance and initial content.
```APIDOC
## Editor Constructor
### Description
Initializes a new instance of the Editor class. It accepts an optional configuration object to set up the editor's appearance and initial content.
### Signature
```typescript
constructor(props: EditorProps = {})
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **props** (EditorProps) - Optional - Configuration object for editor initialization. Defaults to `{}`.
**EditorProps interface**
- **element** (string | HTMLElement) - Optional - DOM element (ID or reference) where editor will be created.
- **editor** (string | HTMLElement) - Optional - Existing DOM div element to use as editor container.
- **content** (string) - Optional - Initial markdown content.
- **textarea** (string | HTMLTextAreaElement) - Optional - Textarea element (ID or reference) to link with editor.
- **placeholder** (string) - Optional - Placeholder text when editor is empty.
- **customInlineGrammar** (Record) - Optional - Custom inline formatting rules.
### Request Example
```javascript
// Create editor in a div element
const editor = new TinyMDE.Editor({
element: 'editor-container',
content: '# Hello World\n\nStart editing...',
placeholder: 'Write your markdown here'
});
// Create editor linked to textarea
const editor = new TinyMDE.Editor({
textarea: 'my-textarea',
placeholder: 'Edit markdown'
});
```
### Response
None
```
--------------------------------
### CommandBar Methods
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/README.md
Methods for associating a CommandBar instance with an Editor instance.
```typescript
// Methods
commandBar.setEditor(editor);
```
--------------------------------
### Extend Markdown with Custom Inline Grammar
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/REFERENCE.md
Customize the editor's markdown parsing by defining custom inline grammar rules. Each rule requires a regular expression and a replacement string. The regexp must start with '^'.
```javascript
const editor = new TinyMDE.Editor({
element: 'editor',
customInlineGrammar: {
highlight: {
regexp: /^(==)([^=]+)(==)/,
replacement: '$2'
},
mention: {
regexp: /^(@[a-zA-Z0-9_]+)/,
replacement: '$1'
}
}
});
```
--------------------------------
### Get Formatting Command State
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-editor.md
Retrieves the current formatting state (e.g., bold, italic, heading level) for the active selection or a specified range. Returns true if active, false if inactive but applicable, and null if not applicable.
```typescript
public getCommandState(focus: Position | null = null, anchor: Position | null = null): Record
```
```javascript
const state = editor.getCommandState();
console.log(state.bold); // true if cursor in bold text
console.log(state.h1); // true if on heading 1 line
console.log(state.code); // false if can apply code formatting
```
--------------------------------
### CommandBarProps
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/types.md
Configuration object for the CommandBar constructor, specifying the container element, the associated editor instance, and the array of commands to be displayed.
```APIDOC
## Interface CommandBarProps
### Description
Configuration object for CommandBar constructor.
### Properties
- **element** (string | HTMLElement) - no - `document.body` - Container for toolbar
- **editor** (Editor) - no - — - Editor instance to control
- **commands** (Array) - no - default array - Command definitions
```
--------------------------------
### CommandBar HTML Structure
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-commandbar.md
Illustrates the basic HTML structure generated by the CommandBar, including buttons and dividers, which can be styled using CSS.
```html
```
--------------------------------
### Initialize TinyMDE with Custom Inline Grammar
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/README.md
Initialize the TinyMDE editor with custom inline grammar rules to enable custom formatting syntax alongside standard Markdown.
```javascript
const customGrammar = {
highlight: {
regexp: /^(==)([^=]+)(==)/,
replacement: '$1$2$3'
},
mention: {
regexp: /^(@[a-zA-Z0-9_]+)/,
replacement: '$1'
}
};
const editor = new TinyMDE.Editor({
element: 'editor',
customInlineGrammar: customGrammar
});
```
--------------------------------
### Import TinyMDE Package
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/index-reference.md
Import the Editor and CommandBar classes from the 'tiny-markdown-editor' package. Alternatively, use require for CommonJS environments.
```typescript
// Full package (Editor + CommandBar)
import { Editor, CommandBar } from 'tiny-markdown-editor';
// Or from NPM after installation
const TinyMDE = require('tiny-markdown-editor');
const { Editor, CommandBar } = TinyMDE;
```
--------------------------------
### CommandBarProps Interface
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/REFERENCE.md
Configuration options for the CommandBar component.
```APIDOC
## CommandBarProps Interface
### Description
Configuration options for the CommandBar component.
### Properties
- `element?: string | HTMLElement`: Toolbar container element.
- `editor?: Editor`: The Editor instance to control.
- `commands?: (string | CommandDefinition)[]`: A list of commands to display in the toolbar.
```
--------------------------------
### TinyMDE Editor with Toolbar
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/REFERENCE.md
Integrate the TinyMDE editor with its optional CommandBar (toolbar). The CommandBar requires an editor instance to function.
```html
```
--------------------------------
### Set Initial Editor Content
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/configuration.md
Initialize the editor with specific markdown content. This option overrides any content from a textarea or default placeholder.
```javascript
new TinyMDE.Editor({
element: 'editor',
content: '# Welcome\n\nStart typing...'
});
```
--------------------------------
### CommandBarProps Interface
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/types.md
Configuration object for the CommandBar constructor, specifying the element, editor instance, and commands to be included.
```typescript
export interface CommandBarProps {
element?: string | HTMLElement;
editor?: Editor;
commands?: (string | CommandDefinition)[];
}
```
--------------------------------
### Wrap Selection to Create Link
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-editor.md
Wraps the selected text with markdown syntax for creating a link. The prefix is '[' and the suffix is ']()', ready for the URL to be added.
```typescript
editor.wrapSelection('[', ']()');
```
--------------------------------
### Include TinyMDE via Self-Hosted Files
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/README.md
Include local copies of the TinyMDE JavaScript and CSS files. Download or build the distribution files and link them in your HTML.
```html
```
--------------------------------
### setEditor Method
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-commandbar.md
Links an editor instance to the CommandBar, enabling the toolbar to control the editor's content and state.
```APIDOC
## Method: setEditor()
### Description
Links an editor instance to this command bar, allowing the toolbar to interact with the editor.
### Signature
```typescript
public setEditor(editor: Editor): void
```
### Parameters
#### editor (Editor) - Required
The editor instance to control.
### Example
```javascript
const editor = new TinyMDE.Editor({element: 'editor'});
const commandBar = new TinyMDE.CommandBar({element: 'toolbar'});
commandBar.setEditor(editor); // Connect editor to toolbar
```
```
--------------------------------
### Import TinyMDE via Global Script Tag
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/REFERENCE.md
Illustrates how to include TinyMDE using global script tags in an HTML file. This method is useful for simpler projects or when not using a module bundler.
```html
```
--------------------------------
### Set Editor Selection with Position
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/types.md
Demonstrates how to set the editor's selection using a Position object. Ensure the Position object is correctly formatted with zero-based row and column numbers.
```javascript
const pos = {row: 0, col: 5}; // First line, 6th character
editor.setSelection(pos);
```
--------------------------------
### CommandBar Class
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/REFERENCE.md
Optional toolbar for buttons and keyboard shortcuts. It can be linked to an Editor instance to control its state.
```APIDOC
## CommandBar Class
### Description
Optional toolbar for buttons and keyboard shortcuts. It can be linked to an Editor instance to control its state.
### Constructor
```typescript
new CommandBar(props: CommandBarProps)
```
### Methods
- `setEditor(editor: Editor)`: Link this CommandBar to an Editor instance.
### Properties
- `e: HTMLDivElement | null`: Toolbar DOM element.
- `editor: Editor | null`: Linked editor instance.
- `commands: Record`: All available commands.
- `state: Record`: Current state of commands.
```
--------------------------------
### Initialize Editor with Element ID
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-editor.md
Creates a new TinyMDE editor instance within a specified DOM element. Use this when you have a div with a specific ID to host the editor.
```javascript
const editor = new TinyMDE.Editor({
element: 'editor-container',
content: '# Hello World\n\nStart editing...',
placeholder: 'Write your markdown here'
});
```
--------------------------------
### Run Individual Jest Test
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/CLAUDE.md
Executes a specific Jest test file. Replace 'jest/commandbar.test.js' with the desired test file path.
```bash
npm run test jest/commandbar.test.js
```
--------------------------------
### Handle File Drops
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/REFERENCE.md
Implement the 'drop' event listener to process files that are dropped into the editor. Iterate through the dropped files for custom handling.
```javascript
editor.addEventListener('drop', (event) => {
for (let file of event.dataTransfer.files) {
// Handle dropped file
}
});
```
--------------------------------
### CommandBar Class Methods
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/README.md
The CommandBar class provides an optional toolbar for the editor, enabling users to apply formatting and execute commands via buttons and keyboard shortcuts.
```APIDOC
## CommandBar Class
### Description
Optional toolbar with buttons and keyboard shortcuts for the markdown editor.
### Methods
- **`setEditor(editor: Editor)`**: Associates the CommandBar with a specific Editor instance.
- **`addCommand(command: CommandDefinition)`**: Adds a custom command to the CommandBar.
- **`removeCommand(commandName: string)`**: Removes a command from the CommandBar.
- **`updateButtonStates()`**: Refreshes the visual state of toolbar buttons based on the editor's current state.
```
--------------------------------
### Command Definition
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-commandbar.md
Defines the structure for custom commands that can be added to the CommandBar. This includes specifying the action, appearance, tooltip, keyboard shortcut, and enablement condition for each command.
```APIDOC
### Interface: CommandDefinition
#### Description
Defines the structure for custom commands.
#### Fields
- **name** (string) - Required - Unique command identifier.
- **action** (string | CommandAction) - Optional - Action to perform or command name.
- **innerHTML** (string) - Optional - HTML content of button (icon/text).
- **title** (string) - Optional - Tooltip text on hover.
- **hotkey** (string) - Optional - Keyboard shortcut.
- **enabled** (CommandEnabled) - Optional - Function to determine if applicable.
#### Type Aliases
- **CommandAction**: `(editor: Editor) => void`
- **CommandEnabled**: `(editor: Editor, focus?: Position, anchor?: Position) => boolean | null`
```
--------------------------------
### CommandDefinition Interface
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/REFERENCE.md
Defines a command for the CommandBar, including its appearance, action, and hotkey.
```APIDOC
## CommandDefinition Interface
### Description
Defines a command for the CommandBar, including its appearance, action, and hotkey.
### Properties
- `name: string`: Unique identifier for the command.
- `action?: string | CommandAction`: Built-in command name or a custom action function.
- `innerHTML?: string`: HTML content for the button (e.g., icon or text).
- `title?: string`: Tooltip text for the button.
- `hotkey?: string`: Keyboard shortcut for the command.
- `enabled?: CommandEnabled`: A function to determine if the command is currently enabled.
```
--------------------------------
### CommandBarProps Interface
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/REFERENCE.md
Defines the properties for configuring the TinyMDE CommandBar. Options include specifying the toolbar container, the associated editor, and the list of commands to display.
```typescript
interface CommandBarProps {
element?: string | HTMLElement; // Toolbar container
editor?: Editor; // Editor to control
commands?: (string | CommandDefinition)[]; // Button list
}
```
--------------------------------
### Define Custom Command Structure
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-commandbar.md
Illustrates the structure of a custom CommandDefinition object, which allows for detailed configuration of command buttons beyond simple string names. This includes setting HTML content, tooltips, keyboard shortcuts, and conditional enabling logic.
```typescript
interface CommandDefinition {
name: string;
action?: string | CommandAction;
innerHTML?: string;
title?: string;
hotkey?: string;
enabled?: CommandEnabled;
}
type CommandAction = (editor: Editor) => void;
type CommandEnabled = (editor: Editor, focus?: Position, anchor?: Position) => boolean | null;
```
--------------------------------
### wrapSelection()
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/api-reference-editor.md
Wraps the current or specified selection with prefix and suffix strings, useful for applying formatting.
```APIDOC
## wrapSelection()
### Description
Wraps the current or specified selection with prefix and suffix strings, useful for applying formatting.
### Signature
```typescript
public wrapSelection(pre: string, post: string, focus: Position | null = null, anchor: Position | null = null): void
```
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **pre** (string) - Required - String to insert before selection.
- **post** (string) - Required - String to insert after selection.
- **focus** (Position) - Optional - End position of selection (defaults to current).
- **anchor** (Position) - Optional - Start position of selection (defaults to current).
**Position interface**
```typescript
interface Position {
row: number; // Zero-based line number
col: number; // Zero-based column number
}
```
### Request Example
```javascript
// Bold the current selection
editor.wrapSelection('**', '**');
// Create a link
editor.wrapSelection('[', ']()');
// Create inline code
editor.wrapSelection('`', '`');
```
### Response
#### Success Response (void)
This method does not return a value.
#### Response Example
None
```
--------------------------------
### Define Custom Hotkeys
Source: https://github.com/jefago/tiny-markdown-editor/blob/main/_autodocs/REFERENCE.md
Create custom keyboard shortcuts for editor actions by defining a CommandDefinition object. Specify the command name, hotkey combination, and the action to perform.
```javascript
{
name: 'myCommand',
hotkey: 'Mod-Shift-X', // Cross-platform: Ctrl/Cmd + Shift + X
action: (editor) => {
// Custom action
}
}
```