-
Notifications
You must be signed in to change notification settings - Fork 24
/
core.js
525 lines (465 loc) · 16.2 KB
/
core.js
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import config from './config.js'
import error from './util/error.js'
import * as parser from './parser.js'
import * as block from './block.js'
import * as content from './content.js'
import * as clipboard from './clipboard.js'
import Dispatcher from './dispatcher.js'
import Cursor from './cursor.js'
import highlightSupport from './highlight-support.js'
import MonitoredHighlighting from './monitored-highlighting.js'
import createDefaultEvents from './create-default-events.js'
import {textNodesUnder, getTextNodeAndRelativeOffset} from './util/element.js'
import {binaryCursorSearch} from './util/binary_search.js'
import {domArray, createRange, nodeContainsRange} from './util/dom.js'
/**
* The Core module provides the Editable class that defines the Editable.JS
* API and is the main entry point for Editable.JS.
* It also provides the cursor module for cross-browser cursors, and the dom
* submodule.
*
* @module core
*/
/**
* Constructor for the Editable.JS API that is externally visible.
*
* @param {Object} configuration for this editable instance.
* window: The window where to attach the editable events.
* defaultBehavior: {Boolean} Load default-behavior.js.
* mouseMoveSelectionChanges: {Boolean} Whether to get cursor and selection events on mousemove.
* browserSpellcheck: {Boolean} Set the spellcheck attribute on editable elements
*
* @class Editable
*/
export class Editable {
constructor (instanceConfig) {
const defaultInstanceConfig = {
window: window,
defaultBehavior: true,
mouseMoveSelectionChanges: false,
browserSpellcheck: true
}
this.config = Object.assign(defaultInstanceConfig, instanceConfig)
this.win = this.config.window
this.editableSelector = `.${config.editableClass}`
this.dispatcher = new Dispatcher(this)
if (this.config.defaultBehavior === true) {
this.dispatcher.on(createDefaultEvents(this))
}
}
/**
* @returns the default Editable configs from config.js
*/
static getGlobalConfig () {
return config
}
/**
* Set configuration options that affect all editable
* instances.
*
* @param {Object} global configuration options (defaults are defined in config.js)
* log: {Boolean}
* logErrors: {Boolean}
* editableClass: {String} e.g. 'js-editable'
* editableDisabledClass: {String} e.g. 'js-editable-disabled'
* pastingAttribute: {String} default: e.g. 'data-editable-is-pasting'
* boldTag: e.g. '<strong>'
* italicTag: e.g. '<em>'
*/
static globalConfig (globalConfig) {
Object.assign(config, globalConfig)
clipboard.updateConfig(config)
}
/**
* Adds the Editable.JS API to the given target elements.
* Opposite of {{#crossLink "Editable/remove"}}{{/crossLink}}.
* Calls dispatcher.setup to setup all event listeners.
*
* @method add
* @param {HTMLElement|Array(HTMLElement)|String} target A HTMLElement, an
* array of HTMLElement or a query selector representing the target where
* the API should be added on.
* @param {normalize, plainText} options Block specific configuration
* @chainable
*/
add (target, options) {
this.enable(target, options)
// TODO check css whitespace settings
return this
}
/**
* Removes the Editable.JS API from the given target elements.
* Opposite of {{#crossLink "Editable/add"}}{{/crossLink}}.
*
* @method remove
* @param {HTMLElement|Array(HTMLElement)|String} target A HTMLElement, an
* array of HTMLElement or a query selector representing the target where
* the API should be removed from.
* @chainable
*/
remove (target) {
const targets = domArray(target, this.win.document)
this.disable(targets)
for (const element of targets) {
element.classList.remove(config.editableDisabledClass)
}
return this
}
/**
* Removes the Editable.JS API from the given target elements.
* The target elements are marked as disabled.
*
* @method disable
* @param { HTMLElement | undefined } elem editable root element(s)
* If no param is specified all editables are disabled.
* @chainable
*/
disable (target) {
const targets = domArray(target || `.${config.editableClass}`, this.win.document)
for (const element of targets) {
block.disable(element)
}
return this
}
/**
* Adds the Editable.JS API to the given target elements.
*
* @method enable
* @param { HTMLElement | undefined } target editable root element(s)
* If no param is specified all editables marked as disabled are enabled.
* @param {boolean} normalize normalizes target content (legacy param)
* @param {boolean} options.normalize normalizes target content
* @param {boolean} options.plainText prevents text formatting for block
* @chainable
*/
enable (target, options) {
const {
normalize = typeof options === 'boolean' ? options : false,
plainText = false
} = options ?? {}
const shouldSpellcheck = this.config.browserSpellcheck
const targets = domArray(target || `.${config.editableDisabledClass}`, this.win.document)
for (const element of targets) {
block.init(element, {normalize, plainText, shouldSpellcheck})
this.dispatcher.notify('init', element)
}
return this
}
/**
* Temporarily disable an editable.
* Can be used to prevent text selection while dragging an element
* for example.
*
* @method suspend
* @param { HTMLElement | undefined } target
*/
suspend (target) {
const targets = domArray(target || `.${config.editableClass}`, this.win.document)
for (const element of targets) {
element.removeAttribute('contenteditable')
}
this.dispatcher.suspend()
return this
}
/**
* Reverse the effects of suspend()
*
* @method continue
* @param { HTMLElement | undefined } target
*/
continue (target) {
const targets = domArray(target || `.${config.editableClass}`, this.win.document)
for (const element of targets) {
element.setAttribute('contenteditable', true)
}
this.dispatcher.continue()
return this
}
/**
* Set the cursor inside of an editable block.
*
* @method createCursor
* @param { HTMLElement } element
* @param { 'beginning' | 'end' | 'before' | 'after' } position
*/
createCursor (element, position = 'beginning') {
const host = Cursor.findHost(element, this.editableSelector)
if (!host) return undefined
const range = createRange()
if (position === 'beginning' || position === 'end') {
range.selectNodeContents(element)
range.collapse(position === 'beginning')
} else if (element !== host) {
if (position === 'before') {
range.setStartBefore(element)
range.setEndBefore(element)
} else if (position === 'after') {
range.setStartAfter(element)
range.setEndAfter(element)
}
} else {
error('EditableJS: cannot create cursor outside of an editable block.')
}
return new Cursor(host, range)
}
createCursorAtCharacterOffset ({element, offset}) {
const textNodes = textNodesUnder(element)
const {node, relativeOffset} = getTextNodeAndRelativeOffset({textNodes, absOffset: offset})
const newRange = createRange()
newRange.setStart(node, relativeOffset)
newRange.collapse(true)
const host = Cursor.findHost(element, this.editableSelector)
const nextCursor = new Cursor(host, newRange)
nextCursor.setVisibleSelection()
return nextCursor
}
createCursorAtBeginning (element) {
return this.createCursor(element, 'beginning')
}
createCursorAtEnd (element) {
return this.createCursor(element, 'end')
}
createCursorBefore (element) {
return this.createCursor(element, 'before')
}
createCursorAfter (element) {
return this.createCursor(element, 'after')
}
/**
* Extract the content from an editable host or document fragment.
* This method will remove all internal elements and ui-elements.
*
* @param {DOM node or Document Fragment} The innerHTML of this element or fragment will be extracted.
* @returns {String} The cleaned innerHTML.
*/
getContent (element) {
return content.extractContent(element)
}
/**
* @param {String | DocumentFragment} content to append.
* @returns {Cursor} A new Cursor object just before the inserted content.
*/
appendTo (inputElement, contentToAppend) {
const element = content.adoptElement(inputElement, this.win.document)
const cursor = this.createCursor(element, 'end')
// TODO create content in the right window
cursor.insertAfter(typeof contentToAppend === 'string'
? content.createFragmentFromString(contentToAppend)
: contentToAppend
)
return cursor
}
/**
* @param {String | DocumentFragment} content to prepend
* @returns {Cursor} A new Cursor object just after the inserted content.
*/
prependTo (inputElement, contentToPrepend) {
const element = content.adoptElement(inputElement, this.win.document)
const cursor = this.createCursor(element, 'beginning')
// TODO create content in the right window
cursor.insertBefore(typeof contentToPrepend === 'string'
? content.createFragmentFromString(contentToPrepend)
: contentToPrepend
)
return cursor
}
/**
* Get the current selection.
* Only returns something if the selection is within an editable element.
* If you pass an editable host as param it only returns something if the selection is inside this
* very editable element.
*
* @param {DOMNode} Optional. An editable host where the selection needs to be contained.
* @returns A Cursor or Selection object or undefined.
*/
getSelection (editableHost) {
const selection = this.dispatcher.selectionWatcher.getFreshSelection()
if (!editableHost || !selection) return selection
const range = selection.range
// Check if the selection is inside the editableHost
if (editableHost?.isConnected && nodeContainsRange(editableHost, range)) {
return selection
}
}
/**
* Enable spellchecking
*
* @chainable
*/
setupHighlighting (hightlightingConfig) {
this.highlighting = new MonitoredHighlighting(this, hightlightingConfig)
return this
}
// For backwards compatibility
setupSpellcheck (conf) {
let marker
if (conf.markerNode) {
marker = conf.markerNode.outerHTML
}
this.setupHighlighting({
throttle: conf.throttle,
spellcheck: {
marker: marker,
spellcheckService: conf.spellcheckService
}
})
this.spellcheck = {
checkSpelling: (elem) => {
this.highlighting.highlight(elem)
}
}
}
/**
* Highlight text within an editable.
*
* By default highlights all occurrences of `text`.
* Pass it a `textRange` object to highlight a
* specific text portion.
*
* The markup used for the highlighting will be removed
* from the final content.
*
*
* @param {Object} options
* @param {DOMNode} options.editableHost
* @param {String} options.text
* @param {String} options.highlightId Added to the highlight markups in the property `data-word-id`
* @param {Object} [options.textRange] An optional range which gets used to set the markers.
* @param {Number} options.textRange.start
* @param {Number} options.textRange.end
* @param {Boolean} options.raiseEvents do throw change events
* @return {Number} The text-based start offset of the newly applied highlight or `-1` if the range was considered invalid.
*/
highlight ({editableHost, text, highlightId, textRange, raiseEvents, type = 'comment'}) {
if (!textRange) {
return highlightSupport.highlightText(editableHost, text, highlightId, type, raiseEvents ? this.dispatcher : undefined)
}
if (typeof textRange.start !== 'number' || typeof textRange.end !== 'number') {
error(
'Error in Editable.highlight: You passed a textRange object with invalid keys. Expected shape: { start: Number, end: Number }'
)
return -1
}
if (textRange.start === textRange.end) {
error(
'Error in Editable.highlight: You passed a textRange object with equal start and end offsets, which is considered a cursor and therefore unfit to create a highlight.'
)
return -1
}
return highlightSupport.highlightRange(editableHost, text, highlightId, textRange.start, textRange.end, raiseEvents ? this.dispatcher : undefined, type)
}
/**
* Extracts positions of all DOMNodes that match `[data-word-id]` and the `[data-highlight]`
*
* Returns an object where the keys represent a highlight id and the value
* a text range object of shape:
* ```
* { start: number, end: number, text: string}
* ```
*
* @param {Object} options
* @param {DOMNode} options.editableHost
* @param {String} [options.type]
* @return {Object} ranges
*/
getHighlightPositions ({editableHost, type}) {
return highlightSupport.extractHighlightedRanges(
editableHost,
type
)
}
removeHighlight ({editableHost, highlightId, raiseEvents}) {
highlightSupport.removeHighlight(editableHost, highlightId, raiseEvents ? this.dispatcher : undefined)
}
decorateHighlight ({editableHost, highlightId, addCssClass, removeCssClass}) {
highlightSupport.updateHighlight(editableHost, highlightId, addCssClass, removeCssClass)
}
/**
* Subscribe a callback function to a custom event fired by the API.
*
* @param {String} event The name of the event.
* @param {Function} handler The callback to execute in response to the
* event.
*
* @chainable
*/
on (event, handler) {
// TODO throw error if event is not one of EVENTS
// TODO throw error if handler is not a function
this.dispatcher.on(event, handler)
return this
}
/**
* Unsubscribe a callback function from a custom event fired by the API.
* Opposite of {{#crossLink "Editable/on"}}{{/crossLink}}.
*
* @param {String} event The name of the event.
* @param {Function} handler The callback to remove from the
* event or the special value false to remove all callbacks.
*
* @chainable
*/
off (...args) {
this.dispatcher.off.apply(this.dispatcher, args)
return this
}
/**
* Unsubscribe all callbacks and event listeners.
*
* @chainable
*/
unload () {
this.dispatcher.unload()
return this
}
/**
* Takes coordinates and uses its left value to find out how to offset a character in a string to
* closely match the coordinates.left value.
* Takes conditions for the result being on the first line, used when navigating to a paragraph from
* the above paragraph and being on the last line, used when navigating to a paragraph from the below
* paragraph.
*
* Internally this sets up the methods used for a binary cursor search and calls this.
*
* @param {DomNode} element
* - the editable hostDOM Node to which the cursor jumps
* @param {object} coordinates
* - The bounding rect of the preceding cursor to be matched
* @param {boolean} requiredOnFirstLine
* - set to true if you want to require the cursor to be on the first line of the paragraph
* @param {boolean} requiredOnLastLine
* - set to true if you want to require the cursor to be on the last line of the paragraph
*
* @return {Object}
* - object with boolean `wasFound` indicating if the binary search found an offset and `offset` to indicate the actual character offset
*/
findClosestCursorOffset ({
element,
origCoordinates,
requiredOnFirstLine = false,
requiredOnLastLine = false
}) {
const positionX = this.dispatcher.switchContext
? this.dispatcher.switchContext.positionX
: origCoordinates.left
return binaryCursorSearch({
host: element,
requiredOnFirstLine,
requiredOnLastLine,
positionX
})
}
}
// Expose modules and editable
Editable.parser = parser
Editable.content = content
// Set up callback functions for several events.
;['focus', 'blur', 'flow', 'selection', 'cursor', 'newline',
'insert', 'split', 'merge', 'empty', 'change', 'switch',
'move', 'clipboard', 'paste', 'spellcheckUpdated', 'selectToBoundary'
].forEach((name) => {
// Generate a callback function to subscribe to an event.
Editable.prototype[name] = function (handler) {
return this.on(name, handler)
}
})