0
# Commands
1
2
Programmatic formatting and editing commands for bold, italic, colors, and other rich text operations.
3
4
## Capabilities
5
6
### Execute Command
7
8
Execute formatting and editing commands programmatically.
9
10
```javascript { .api }
11
/**
12
* Execute editing commands (bold, italic, fontSize, etc.)
13
* @param name - Command name (e.g., 'bold', 'fontSize', 'foreColor')
14
* @param value - Optional command value (e.g., font size, color)
15
*/
16
do(name: string, value?: any): void;
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
// Text formatting commands
23
editor.cmd.do('bold'); // Toggle bold
24
editor.cmd.do('italic'); // Toggle italic
25
editor.cmd.do('underline'); // Toggle underline
26
editor.cmd.do('strikeThrough'); // Toggle strikethrough
27
28
// Commands with values
29
editor.cmd.do('fontSize', '18px'); // Set font size
30
editor.cmd.do('fontName', 'Arial'); // Set font family
31
editor.cmd.do('foreColor', '#ff0000'); // Set text color
32
editor.cmd.do('backColor', '#ffff00'); // Set background color
33
34
// Insert content
35
editor.cmd.do('insertHTML', '<p>Custom <strong>HTML</strong> content</p>');
36
37
// Text alignment
38
editor.cmd.do('justifyLeft');
39
editor.cmd.do('justifyCenter');
40
editor.cmd.do('justifyRight');
41
42
// Lists
43
editor.cmd.do('insertOrderedList'); // Numbered list
44
editor.cmd.do('insertUnorderedList'); // Bulleted list
45
46
// Undo/Redo
47
editor.cmd.do('undo');
48
editor.cmd.do('redo');
49
```
50
51
### Query Command Support
52
53
Check if a command is supported by the browser/editor.
54
55
```javascript { .api }
56
/**
57
* Check if a command is supported
58
* @param name - Command name to check
59
* @returns true if command is supported, false otherwise
60
*/
61
queryCommandSupported(name: string): boolean;
62
```
63
64
**Usage Examples:**
65
66
```javascript
67
// Check command support before using
68
if (editor.cmd.queryCommandSupported('bold')) {
69
editor.cmd.do('bold');
70
} else {
71
console.log('Bold command not supported');
72
}
73
74
// Build dynamic UI based on support
75
const supportedCommands = ['bold', 'italic', 'underline', 'strikeThrough']
76
.filter(cmd => editor.cmd.queryCommandSupported(cmd));
77
78
console.log('Supported formatting commands:', supportedCommands);
79
```
80
81
## Available Commands
82
83
### Text Formatting Commands
84
85
```javascript { .api }
86
// Basic text formatting (no value required)
87
editor.cmd.do('bold'); // Toggle bold text
88
editor.cmd.do('italic'); // Toggle italic text
89
editor.cmd.do('underline'); // Toggle underlined text
90
editor.cmd.do('strikeThrough'); // Toggle strikethrough text
91
```
92
93
### Font Commands
94
95
```javascript { .api }
96
// Font size (value: CSS font-size string)
97
editor.cmd.do('fontSize', '16px');
98
editor.cmd.do('fontSize', '1.2em');
99
editor.cmd.do('fontSize', 'large');
100
101
// Font family (value: font family name)
102
editor.cmd.do('fontName', 'Arial');
103
editor.cmd.do('fontName', '微软雅黑');
104
editor.cmd.do('fontName', 'Helvetica, sans-serif');
105
```
106
107
### Color Commands
108
109
```javascript { .api }
110
// Text color (value: CSS color string)
111
editor.cmd.do('foreColor', '#ff0000'); // Hex color
112
editor.cmd.do('foreColor', 'red'); // Named color
113
editor.cmd.do('foreColor', 'rgb(255, 0, 0)'); // RGB color
114
115
// Background color (value: CSS color string)
116
editor.cmd.do('backColor', '#ffff00'); // Yellow background
117
editor.cmd.do('backColor', 'transparent'); // Clear background
118
```
119
120
### Alignment Commands
121
122
```javascript { .api }
123
// Text alignment (no value required)
124
editor.cmd.do('justifyLeft'); // Align left
125
editor.cmd.do('justifyCenter'); // Align center
126
editor.cmd.do('justifyRight'); // Align right
127
```
128
129
### List Commands
130
131
```javascript { .api }
132
// List creation (no value required)
133
editor.cmd.do('insertOrderedList'); // Create numbered list
134
editor.cmd.do('insertUnorderedList'); // Create bulleted list
135
```
136
137
### Content Insertion Commands
138
139
```javascript { .api }
140
// Insert HTML content (value: HTML string)
141
editor.cmd.do('insertHTML', '<p>New paragraph</p>');
142
editor.cmd.do('insertHTML', '<img src="image.jpg" alt="Image">');
143
editor.cmd.do('insertHTML', '<a href="http://example.com">Link</a>');
144
```
145
146
### History Commands
147
148
```javascript { .api }
149
// Undo/Redo operations (no value required)
150
editor.cmd.do('undo'); // Undo last action
151
editor.cmd.do('redo'); // Redo last undone action
152
```
153
154
### Query Command Value
155
156
Get the current value of a command in the selection.
157
158
```javascript { .api }
159
/**
160
* Get current value of a command
161
* @param name - Command name to query
162
* @returns Current value of the command
163
*/
164
queryCommandValue(name: string): string;
165
```
166
167
**Usage Examples:**
168
169
```javascript
170
// Get current font size
171
const currentFontSize = editor.cmd.queryCommandValue('fontSize');
172
console.log('Current font size:', currentFontSize);
173
174
// Get current font name
175
const currentFont = editor.cmd.queryCommandValue('fontName');
176
console.log('Current font:', currentFont);
177
178
// Get current text color
179
const currentColor = editor.cmd.queryCommandValue('foreColor');
180
console.log('Current text color:', currentColor);
181
```
182
183
### Query Command State
184
185
Check the current state of a toggle command.
186
187
```javascript { .api }
188
/**
189
* Check current state of a toggle command
190
* @param name - Command name to check
191
* @returns true if command is active, false otherwise
192
*/
193
queryCommandState(name: string): boolean;
194
```
195
196
**Usage Examples:**
197
198
```javascript
199
// Check if text is bold
200
const isBold = editor.cmd.queryCommandState('bold');
201
console.log('Text is bold:', isBold);
202
203
// Check if text is italic
204
const isItalic = editor.cmd.queryCommandState('italic');
205
console.log('Text is italic:', isItalic);
206
207
// Update UI button states
208
function updateFormatButtons() {
209
document.getElementById('bold-btn').classList.toggle('active',
210
editor.cmd.queryCommandState('bold'));
211
document.getElementById('italic-btn').classList.toggle('active',
212
editor.cmd.queryCommandState('italic'));
213
document.getElementById('underline-btn').classList.toggle('active',
214
editor.cmd.queryCommandState('underline'));
215
}
216
```
217
218
## Complete Command API Interface
219
220
```javascript { .api }
221
interface CommandAPI {
222
/** Execute a formatting or editing command */
223
do(name: string, value?: any): void;
224
225
/** Check if a command is supported */
226
queryCommandSupported(name: string): boolean;
227
228
/** Get current value of a command */
229
queryCommandValue(name: string): string;
230
231
/** Check current state of a toggle command */
232
queryCommandState(name: string): boolean;
233
}
234
```
235
236
## Advanced Command Usage
237
238
### Conditional Formatting
239
240
```javascript
241
// Apply formatting based on conditions
242
function applyConditionalFormatting(condition, format, value) {
243
if (condition && editor.cmd.queryCommandSupported(format)) {
244
editor.cmd.do(format, value);
245
}
246
}
247
248
// Usage examples
249
const isImportant = true;
250
applyConditionalFormatting(isImportant, 'bold');
251
applyConditionalFormatting(isImportant, 'foreColor', '#ff0000');
252
```
253
254
### Batch Commands
255
256
```javascript
257
// Apply multiple formatting commands
258
function applyBatchFormatting(commands) {
259
commands.forEach(({command, value}) => {
260
if (editor.cmd.queryCommandSupported(command)) {
261
editor.cmd.do(command, value);
262
}
263
});
264
}
265
266
// Usage
267
applyBatchFormatting([
268
{command: 'bold'},
269
{command: 'fontSize', value: '18px'},
270
{command: 'foreColor', value: '#0066cc'}
271
]);
272
```
273
274
### Format Toggle Implementation
275
276
```javascript
277
// Custom toggle for formatting commands
278
function toggleFormat(command) {
279
// Note: Some commands like 'bold' automatically toggle
280
// Others may need custom logic
281
editor.cmd.do(command);
282
}
283
284
// Create UI buttons that toggle formatting
285
const formatButtons = [
286
{name: 'Bold', command: 'bold'},
287
{name: 'Italic', command: 'italic'},
288
{name: 'Underline', command: 'underline'}
289
];
290
291
formatButtons.forEach(btn => {
292
const button = document.createElement('button');
293
button.textContent = btn.name;
294
button.onclick = () => toggleFormat(btn.command);
295
document.getElementById('custom-toolbar').appendChild(button);
296
});
297
```
298
299
### Custom Content Insertion
300
301
```javascript
302
// Helper functions for common content insertion
303
function insertTable(rows = 2, cols = 2) {
304
let tableHtml = '<table border="1"><tbody>';
305
for (let i = 0; i < rows; i++) {
306
tableHtml += '<tr>';
307
for (let j = 0; j < cols; j++) {
308
tableHtml += '<td> </td>';
309
}
310
tableHtml += '</tr>';
311
}
312
tableHtml += '</tbody></table>';
313
314
editor.cmd.do('insertHTML', tableHtml);
315
}
316
317
function insertTimestamp() {
318
const now = new Date().toLocaleString();
319
editor.cmd.do('insertHTML', `<span style="color: #666;">[${now}]</span> `);
320
}
321
322
function insertHorizontalRule() {
323
editor.cmd.do('insertHTML', '<hr>');
324
}
325
```
326
327
### Command Validation
328
329
```javascript
330
// Validate commands before execution
331
function executeCommand(command, value) {
332
// Check if command is supported
333
if (!editor.cmd.queryCommandSupported(command)) {
334
console.warn(`Command '${command}' is not supported`);
335
return false;
336
}
337
338
// Validate values for specific commands
339
if (command === 'fontSize' && value) {
340
const validSizes = ['12px', '14px', '16px', '18px', '24px', '32px'];
341
if (!validSizes.includes(value)) {
342
console.warn(`Invalid font size: ${value}`);
343
return false;
344
}
345
}
346
347
if (command === 'foreColor' && value) {
348
// Basic color validation
349
const colorRegex = /^#[0-9A-F]{6}$/i;
350
if (!colorRegex.test(value) && !CSS.supports('color', value)) {
351
console.warn(`Invalid color: ${value}`);
352
return false;
353
}
354
}
355
356
// Execute the command
357
editor.cmd.do(command, value);
358
return true;
359
}
360
```