-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
Copy pathRichTextEditor.ts
449 lines (395 loc) · 12.5 KB
/
RichTextEditor.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
// The initial version of this RTE was borrowed from https://github.com/jaredreich/pell
// and adapted to the GrapesJS's need
import { isString } from 'underscore';
import RichTextEditorModule from '..';
import EditorModel from '../../editor/model/Editor';
import { getPointerEvent, off, on } from '../../utils/dom';
import { getComponentModel } from '../../utils/mixins';
export interface RichTextEditorAction {
name: string;
icon: string | HTMLElement;
event?: string;
attributes?: Record<string, any>;
result: (rte: RichTextEditor, action: RichTextEditorAction) => void;
update?: (rte: RichTextEditor, action: RichTextEditorAction) => number;
state?: (rte: RichTextEditor, doc: Document) => number;
btn?: HTMLElement;
currentState?: RichTextEditorActionState;
}
export enum RichTextEditorActionState {
ACTIVE = 1,
INACTIVE = 0,
DISABLED = -1,
}
export interface RichTextEditorOptions {
actions?: (RichTextEditorAction | string)[];
classes?: Record<string, string>;
actionbar?: HTMLElement;
actionbarContainer?: HTMLElement;
styleWithCSS?: boolean;
module?: RichTextEditorModule;
}
type EffectOptions = {
event?: Event;
};
const RTE_KEY = '_rte';
const btnState = {
ACTIVE: 1,
INACTIVE: 0,
DISABLED: -1,
};
const isValidTag = (rte: RichTextEditor, tagName = 'A') => {
const { anchorNode, focusNode } = rte.selection() || {};
const parentAnchor = anchorNode?.parentNode;
const parentFocus = focusNode?.parentNode;
return parentAnchor?.nodeName == tagName || parentFocus?.nodeName == tagName;
};
const customElAttr = 'data-selectme';
const defActions: Record<string, RichTextEditorAction> = {
bold: {
name: 'bold',
icon: '<b>B</b>',
attributes: { title: 'Bold' },
result: rte => rte.exec('bold'),
},
italic: {
name: 'italic',
icon: '<i>I</i>',
attributes: { title: 'Italic' },
result: rte => rte.exec('italic'),
},
underline: {
name: 'underline',
icon: '<u>U</u>',
attributes: { title: 'Underline' },
result: rte => rte.exec('underline'),
},
strikethrough: {
name: 'strikethrough',
icon: '<s>S</s>',
attributes: { title: 'Strike-through' },
result: rte => rte.exec('strikeThrough'),
},
link: {
icon: `<svg viewBox="0 0 24 24">
<path fill="currentColor" d="M3.9,12C3.9,10.29 5.29,8.9 7,8.9H11V7H7A5,5 0 0,0 2,12A5,5 0 0,0 7,17H11V15.1H7C5.29,15.1 3.9,13.71 3.9,12M8,13H16V11H8V13M17,7H13V8.9H17C18.71,8.9 20.1,10.29 20.1,12C20.1,13.71 18.71,15.1 17,15.1H13V17H17A5,5 0 0,0 22,12A5,5 0 0,0 17,7Z" />
</svg>`,
name: 'link',
attributes: {
style: 'font-size:1.4rem;padding:0 4px 2px;',
title: 'Link',
},
state: rte => {
return rte && rte.selection() && isValidTag(rte) ? btnState.ACTIVE : btnState.INACTIVE;
},
result: rte => {
if (isValidTag(rte)) {
rte.exec('unlink');
} else {
rte.insertHTML(`<a href="" ${customElAttr}>${rte.selection()}</a>`, {
select: true,
});
}
},
},
wrap: {
name: 'wrap',
icon: `<svg viewBox="0 0 24 24">
<path fill="currentColor" d="M20.71,4.63L19.37,3.29C19,2.9 18.35,2.9 17.96,3.29L9,12.25L11.75,15L20.71,6.04C21.1,5.65 21.1,5 20.71,4.63M7,14A3,3 0 0,0 4,17C4,18.31 2.84,19 2,19C2.92,20.22 4.5,21 6,21A4,4 0 0,0 10,17A3,3 0 0,0 7,14Z" />
</svg>`,
attributes: { title: 'Wrap for style' },
state: rte => {
return rte?.selection() && isValidTag(rte, 'SPAN') ? btnState.DISABLED : btnState.INACTIVE;
},
result: rte => {
!isValidTag(rte, 'SPAN') &&
rte.insertHTML(`<span ${customElAttr}>${rte.selection()}</span>`, {
select: true,
});
},
},
};
export default class RichTextEditor {
em: EditorModel;
settings: RichTextEditorOptions;
classes!: Record<string, string>;
actionbar?: HTMLElement;
actions!: RichTextEditorAction[];
el!: HTMLElement;
doc!: Document;
enabled?: boolean;
getContent?: () => string;
constructor(em: EditorModel, el: HTMLElement & { _rte?: RichTextEditor }, settings: RichTextEditorOptions = {}) {
this.em = em;
this.settings = settings;
if (el[RTE_KEY]) {
return el[RTE_KEY]!;
}
el[RTE_KEY] = this;
this.setEl(el);
this.updateActiveActions = this.updateActiveActions.bind(this);
this.__onKeydown = this.__onKeydown.bind(this);
this.__onPaste = this.__onPaste.bind(this);
const acts = (settings.actions || []).map(action => {
let result = action;
if (isString(action)) {
result = { ...defActions[action] };
} else if (defActions[action.name]) {
result = { ...defActions[action.name], ...action };
}
return result as RichTextEditorAction;
});
const actions = acts.length ? acts : Object.keys(defActions).map(a => defActions[a]);
settings.classes = {
actionbar: 'actionbar',
button: 'action',
active: 'active',
disabled: 'disabled',
inactive: 'inactive',
...settings.classes,
};
const classes = settings.classes;
let actionbar = settings.actionbar;
this.actionbar = actionbar!;
this.classes = classes;
this.actions = actions;
if (!actionbar) {
if (!this.isCustom(settings.module)) {
const actionbarCont = settings.actionbarContainer;
actionbar = document.createElement('div');
actionbar.className = classes.actionbar;
actionbarCont?.appendChild(actionbar);
this.actionbar = actionbar;
}
actions.forEach(action => this.addAction(action));
}
settings.styleWithCSS && this.exec('styleWithCSS');
return this;
}
isCustom(module?: RichTextEditorModule) {
const rte = module || this.em.RichTextEditor;
return !!(rte?.config.custom || rte?.customRte);
}
destroy() {}
setEl(el: HTMLElement) {
this.el = el;
this.doc = el.ownerDocument;
}
updateActiveActions() {
const actions = this.getActions();
actions.forEach(action => {
const { update, btn } = action;
const { active, inactive, disabled } = this.classes;
const state = action.state;
const name = action.name;
const doc = this.doc;
let currentState = RichTextEditorActionState.INACTIVE;
if (btn) {
btn.className = btn.className.replace(active, '').trim();
btn.className = btn.className.replace(inactive, '').trim();
btn.className = btn.className.replace(disabled, '').trim();
}
// if there is a state function, which depicts the state,
// i.e. `active`, `disabled`, then call it
if (state) {
const newState = state(this, doc);
currentState = newState;
if (btn) {
switch (newState) {
case btnState.ACTIVE:
btn.className += ` ${active}`;
break;
case btnState.INACTIVE:
btn.className += ` ${inactive}`;
break;
case btnState.DISABLED:
btn.className += ` ${disabled}`;
break;
}
}
} else {
// otherwise default to checking if the name command is supported & enabled
if (doc.queryCommandSupported(name) && doc.queryCommandState(name)) {
btn && (btn.className += ` ${active}`);
currentState = RichTextEditorActionState.ACTIVE;
}
}
action.currentState = currentState;
update?.(this, action);
});
actions.length && this.em.RichTextEditor.__dbdTrgCustom();
}
enable(opts: EffectOptions) {
if (this.enabled) return this;
return this.__toggleEffects(true, opts);
}
disable() {
return this.__toggleEffects(false);
}
__toggleEffects(enable = false, opts: EffectOptions = {}) {
const method = enable ? on : off;
const { el, doc } = this;
const actionbar = this.actionbarEl();
actionbar && (actionbar.style.display = enable ? '' : 'none');
el.contentEditable = `${!!enable}`;
method(el, 'mouseup keyup', this.updateActiveActions);
method(doc, 'keydown', this.__onKeydown);
method(doc, 'paste', this.__onPaste);
this.enabled = enable;
if (enable) {
const { event } = opts;
this.syncActions();
this.updateActiveActions();
if (event) {
let range = null;
if (doc.caretRangeFromPoint) {
const poiner = getPointerEvent(event);
range = doc.caretRangeFromPoint(poiner.clientX, poiner.clientY);
// @ts-ignore
} else if (event.rangeParent) {
range = doc.createRange();
// @ts-ignore
range.setStart(event.rangeParent, event.rangeOffset);
}
const sel = doc.getSelection();
sel?.removeAllRanges();
range && sel?.addRange(range);
}
el.focus();
}
return this;
}
__onKeydown(event: Event) {
const ev = event as KeyboardEvent;
const { doc } = this;
const cmdList = ['insertOrderedList', 'insertUnorderedList'];
if (ev.key === 'Enter' && !cmdList.some(cmd => doc.queryCommandState(cmd))) {
doc.execCommand('insertLineBreak');
ev.preventDefault();
}
}
__onPaste(ev: Event) {
// @ts-ignore
const clipboardData = ev.clipboardData || window.clipboardData;
const text = clipboardData.getData('text');
const textHtml = clipboardData.getData('text/html');
// Replace \n with <br> in case of plain text
if (text && !textHtml) {
ev.preventDefault();
const html = text.replace(/(?:\r\n|\r|\n)/g, '<br/>');
this.doc.execCommand('insertHTML', false, html);
}
}
/**
* Sync actions with the current RTE
*/
syncActions() {
this.getActions().forEach(action => {
if (this.actionbar) {
if (!action.state || (action.state && action.state(this, this.doc) >= 0)) {
const event = action.event || 'click';
const { btn } = action;
if (btn) {
(btn as any)[`on${event}`] = () => {
action.result(this, action);
this.updateActiveActions();
};
}
}
}
});
}
/**
* Add new action to the actionbar
* @param {Object} action
* @param {Object} [opts={}]
*/
addAction(action: RichTextEditorAction, opts: { sync?: boolean } = {}) {
const { sync } = opts;
const actionbar = this.actionbarEl();
if (actionbar) {
const { icon, attributes: attr = {} } = action;
const btn = document.createElement('span');
btn.className = this.classes.button;
action.btn = btn;
for (let key in attr) {
btn.setAttribute(key, attr[key]);
}
if (typeof icon == 'string') {
btn.innerHTML = icon;
} else {
btn.appendChild(icon);
}
actionbar.appendChild(btn);
}
if (sync) {
this.actions.push(action);
this.syncActions();
}
}
/**
* Get the array of current actions
* @return {Array}
*/
getActions() {
return this.actions;
}
/**
* Returns the Selection instance
* @return {Selection}
*/
selection() {
return this.doc.getSelection();
}
/**
* Wrapper around [execCommand](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand) to allow
* you to perform operations like `insertText`
* @param {string} command Command name
* @param {any} [value=null Command's arguments
*/
exec(command: string, value?: string) {
this.doc.execCommand(command, false, value);
}
/**
* Get the actionbar element
* @return {HTMLElement}
*/
actionbarEl() {
return this.actionbar;
}
/**
* Set custom HTML to the selection, useful as the default 'insertHTML' command
* doesn't work in the same way on all browsers
* @param {string} value HTML string
*/
insertHTML(value: string | HTMLElement, { select }: { select?: boolean } = {}) {
const { em, doc, el } = this;
const sel = doc.getSelection();
if (sel && sel.rangeCount) {
const model = getComponentModel(el) || em.getSelected();
const node = doc.createElement('div');
const range = sel.getRangeAt(0);
range.deleteContents();
if (isString(value)) {
node.innerHTML = value;
} else if (value) {
node.appendChild(value);
}
Array.prototype.slice.call(node.childNodes).forEach(nd => {
range.insertNode(nd);
});
sel.removeAllRanges();
sel.addRange(range);
el.focus();
if (select && model) {
model.once('rte:disable', () => {
const toSel = model.find(`[${customElAttr}]`)[0];
if (!toSel) return;
em.setSelected(toSel);
toSel.removeAttributes(customElAttr);
});
model.trigger('disable');
}
}
}
}