-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
toolbar.js
683 lines (566 loc) · 27.5 KB
/
toolbar.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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
(function () {
'use strict';
var Toolbar = MediumEditor.Extension.extend({
name: 'toolbar',
/* Toolbar Options */
/* align: ['left'|'center'|'right']
* When the __static__ option is true, this aligns the static toolbar
* relative to the medium-editor element.
*/
align: 'center',
/* allowMultiParagraphSelection: [boolean]
* enables/disables whether the toolbar should be displayed when
* selecting multiple paragraphs/block elements
*/
allowMultiParagraphSelection: true,
/* buttons: [Array]
* the names of the set of buttons to display on the toolbar.
*/
buttons: ['bold', 'italic', 'underline', 'anchor', 'h2', 'h3', 'quote'],
/* diffLeft: [Number]
* value in pixels to be added to the X axis positioning of the toolbar.
*/
diffLeft: 0,
/* diffTop: [Number]
* value in pixels to be added to the Y axis positioning of the toolbar.
*/
diffTop: -10,
/* firstButtonClass: [string]
* CSS class added to the first button in the toolbar.
*/
firstButtonClass: 'medium-editor-button-first',
/* lastButtonClass: [string]
* CSS class added to the last button in the toolbar.
*/
lastButtonClass: 'medium-editor-button-last',
/* standardizeSelectionStart: [boolean]
* enables/disables standardizing how the beginning of a range is decided
* between browsers whenever the selected text is analyzed for updating toolbar buttons status.
*/
standardizeSelectionStart: false,
/* static: [boolean]
* enable/disable the toolbar always displaying in the same location
* relative to the medium-editor element.
*/
static: false,
/* sticky: [boolean]
* When the __static__ option is true, this enables/disables the toolbar
* "sticking" to the viewport and staying visible on the screen while
* the page scrolls.
*/
sticky: false,
/* stickyTopOffset: [Number]
* Value in pixel of the top offset above the toolbar
*/
stickyTopOffset: 0,
/* updateOnEmptySelection: [boolean]
* When the __static__ option is true, this enables/disables updating
* the state of the toolbar buttons even when the selection is collapsed
* (there is no selection, just a cursor).
*/
updateOnEmptySelection: false,
/* relativeContainer: [node]
* appending the toolbar to a given node instead of body
*/
relativeContainer: null,
init: function () {
MediumEditor.Extension.prototype.init.apply(this, arguments);
this.initThrottledMethods();
if (!this.relativeContainer) {
this.getEditorOption('elementsContainer').appendChild(this.getToolbarElement());
} else {
this.relativeContainer.appendChild(this.getToolbarElement());
}
},
// Helper method to execute method for every extension, but ignoring the toolbar extension
forEachExtension: function (iterator, context) {
return this.base.extensions.forEach(function (command) {
if (command === this) {
return;
}
return iterator.apply(context || this, arguments);
}, this);
},
// Toolbar creation/deletion
createToolbar: function () {
var toolbar = this.document.createElement('div');
toolbar.id = 'medium-editor-toolbar-' + this.getEditorId();
toolbar.className = 'medium-editor-toolbar';
if (this.static) {
toolbar.className += ' static-toolbar';
} else if (this.relativeContainer) {
toolbar.className += ' medium-editor-relative-toolbar';
} else {
toolbar.className += ' medium-editor-stalker-toolbar';
}
toolbar.appendChild(this.createToolbarButtons());
// Add any forms that extensions may have
this.forEachExtension(function (extension) {
if (extension.hasForm) {
toolbar.appendChild(extension.getForm());
}
});
this.attachEventHandlers();
return toolbar;
},
createToolbarButtons: function () {
var ul = this.document.createElement('ul'),
li,
btn,
buttons,
extension,
buttonName,
buttonOpts;
ul.id = 'medium-editor-toolbar-actions' + this.getEditorId();
ul.className = 'medium-editor-toolbar-actions';
ul.style.display = 'block';
this.buttons.forEach(function (button) {
if (typeof button === 'string') {
buttonName = button;
buttonOpts = null;
} else {
buttonName = button.name;
buttonOpts = button;
}
// If the button already exists as an extension, it'll be returned
// othwerise it'll create the default built-in button
extension = this.base.addBuiltInExtension(buttonName, buttonOpts);
if (extension && typeof extension.getButton === 'function') {
btn = extension.getButton(this.base);
li = this.document.createElement('li');
if (MediumEditor.util.isElement(btn)) {
li.appendChild(btn);
} else {
li.innerHTML = btn;
}
ul.appendChild(li);
}
}, this);
buttons = ul.querySelectorAll('button');
if (buttons.length > 0) {
buttons[0].classList.add(this.firstButtonClass);
buttons[buttons.length - 1].classList.add(this.lastButtonClass);
}
return ul;
},
destroy: function () {
if (this.toolbar) {
if (this.toolbar.parentNode) {
this.toolbar.parentNode.removeChild(this.toolbar);
}
delete this.toolbar;
}
},
// Toolbar accessors
getInteractionElements: function () {
return this.getToolbarElement();
},
getToolbarElement: function () {
if (!this.toolbar) {
this.toolbar = this.createToolbar();
}
return this.toolbar;
},
getToolbarActionsElement: function () {
return this.getToolbarElement().querySelector('.medium-editor-toolbar-actions');
},
// Toolbar event handlers
initThrottledMethods: function () {
// throttledPositionToolbar is throttled because:
// - It will be called when the browser is resizing, which can fire many times very quickly
// - For some event (like resize) a slight lag in UI responsiveness is OK and provides performance benefits
this.throttledPositionToolbar = MediumEditor.util.throttle(function () {
if (this.base.isActive) {
this.positionToolbarIfShown();
}
}.bind(this));
},
attachEventHandlers: function () {
// MediumEditor custom events for when user beings and ends interaction with a contenteditable and its elements
this.subscribe('blur', this.handleBlur.bind(this));
this.subscribe('focus', this.handleFocus.bind(this));
// Updating the state of the toolbar as things change
this.subscribe('editableClick', this.handleEditableClick.bind(this));
this.subscribe('editableKeyup', this.handleEditableKeyup.bind(this));
// Handle mouseup on document for updating the selection in the toolbar
this.on(this.document.documentElement, 'mouseup', this.handleDocumentMouseup.bind(this));
// Add a scroll event for sticky toolbar
if (this.static && this.sticky) {
// On scroll (capture), re-position the toolbar
this.on(this.window, 'scroll', this.handleWindowScroll.bind(this), true);
}
// On resize, re-position the toolbar
this.on(this.window, 'resize', this.handleWindowResize.bind(this));
},
handleWindowScroll: function () {
this.positionToolbarIfShown();
},
handleWindowResize: function () {
this.throttledPositionToolbar();
},
handleDocumentMouseup: function (event) {
// Do not trigger checkState when mouseup fires over the toolbar
if (event &&
event.target &&
MediumEditor.util.isDescendant(this.getToolbarElement(), event.target)) {
return false;
}
this.checkState();
},
handleEditableClick: function () {
// Delay the call to checkState to handle bug where selection is empty
// immediately after clicking inside a pre-existing selection
setTimeout(function () {
this.checkState();
}.bind(this), 0);
},
handleEditableKeyup: function () {
this.checkState();
},
handleBlur: function () {
// Kill any previously delayed calls to hide the toolbar
clearTimeout(this.hideTimeout);
// Blur may fire even if we have a selection, so we want to prevent any delayed showToolbar
// calls from happening in this specific case
clearTimeout(this.delayShowTimeout);
// Delay the call to hideToolbar to handle bug with multiple editors on the page at once
this.hideTimeout = setTimeout(function () {
this.hideToolbar();
}.bind(this), 1);
},
handleFocus: function () {
this.checkState();
},
// Hiding/showing toolbar
isDisplayed: function () {
return this.getToolbarElement().classList.contains('medium-editor-toolbar-active');
},
showToolbar: function () {
clearTimeout(this.hideTimeout);
if (!this.isDisplayed()) {
this.getToolbarElement().classList.add('medium-editor-toolbar-active');
this.trigger('showToolbar', {}, this.base.getFocusedElement());
}
},
hideToolbar: function () {
if (this.isDisplayed()) {
this.getToolbarElement().classList.remove('medium-editor-toolbar-active');
this.trigger('hideToolbar', {}, this.base.getFocusedElement());
}
},
isToolbarDefaultActionsDisplayed: function () {
return this.getToolbarActionsElement().style.display === 'block';
},
hideToolbarDefaultActions: function () {
if (this.isToolbarDefaultActionsDisplayed()) {
this.getToolbarActionsElement().style.display = 'none';
}
},
showToolbarDefaultActions: function () {
this.hideExtensionForms();
if (!this.isToolbarDefaultActionsDisplayed()) {
this.getToolbarActionsElement().style.display = 'block';
}
// Using setTimeout + options.delay because:
// We will actually be displaying the toolbar, which should be controlled by options.delay
this.delayShowTimeout = this.base.delay(function () {
this.showToolbar();
}.bind(this));
},
hideExtensionForms: function () {
// Hide all extension forms
this.forEachExtension(function (extension) {
if (extension.hasForm && extension.isDisplayed()) {
extension.hideForm();
}
});
},
// Responding to changes in user selection
// Checks for existance of multiple block elements in the current selection
multipleBlockElementsSelected: function () {
var regexEmptyHTMLTags = /<[^\/>][^>]*><\/[^>]+>/gim, // http://stackoverflow.com/questions/3129738/remove-empty-tags-using-regex
regexBlockElements = new RegExp('<(' + MediumEditor.util.blockContainerElementNames.join('|') + ')[^>]*>', 'g'),
selectionHTML = MediumEditor.selection.getSelectionHtml(this.document).replace(regexEmptyHTMLTags, ''), // Filter out empty blocks from selection
hasMultiParagraphs = selectionHTML.match(regexBlockElements); // Find how many block elements are within the html
return !!hasMultiParagraphs && hasMultiParagraphs.length > 1;
},
modifySelection: function () {
var selection = this.window.getSelection(),
selectionRange = selection.getRangeAt(0);
/*
* In firefox, there are cases (ie doubleclick of a word) where the selectionRange start
* will be at the very end of an element. In other browsers, the selectionRange start
* would instead be at the very beginning of an element that actually has content.
* example:
* <span>foo</span><span>bar</span>
*
* If the text 'bar' is selected, most browsers will have the selectionRange start at the beginning
* of the 'bar' span. However, there are cases where firefox will have the selectionRange start
* at the end of the 'foo' span. The contenteditable behavior will be ok, but if there are any
* properties on the 'bar' span, they won't be reflected accurately in the toolbar
* (ie 'Bold' button wouldn't be active)
*
* So, for cases where the selectionRange start is at the end of an element/node, find the next
* adjacent text node that actually has content in it, and move the selectionRange start there.
*/
if (this.standardizeSelectionStart &&
selectionRange.startContainer.nodeValue &&
(selectionRange.startOffset === selectionRange.startContainer.nodeValue.length)) {
var adjacentNode = MediumEditor.util.findAdjacentTextNodeWithContent(MediumEditor.selection.getSelectionElement(this.window), selectionRange.startContainer, this.document);
if (adjacentNode) {
var offset = 0;
while (adjacentNode.nodeValue.substr(offset, 1).trim().length === 0) {
offset = offset + 1;
}
selectionRange = MediumEditor.selection.select(this.document, adjacentNode, offset,
selectionRange.endContainer, selectionRange.endOffset);
}
}
},
checkState: function () {
if (this.base.preventSelectionUpdates) {
return;
}
// If no editable has focus OR selection is inside contenteditable = false
// hide toolbar
if (!this.base.getFocusedElement() ||
MediumEditor.selection.selectionInContentEditableFalse(this.window)) {
return this.hideToolbar();
}
// If there's no selection element, selection element doesn't belong to this editor
// or toolbar is disabled for this selection element
// hide toolbar
var selectionElement = MediumEditor.selection.getSelectionElement(this.window);
if (!selectionElement ||
this.getEditorElements().indexOf(selectionElement) === -1 ||
selectionElement.getAttribute('data-disable-toolbar')) {
return this.hideToolbar();
}
// Now we know there's a focused editable with a selection
// If the updateOnEmptySelection option is true, show the toolbar
if (this.updateOnEmptySelection && this.static) {
return this.showAndUpdateToolbar();
}
// If we don't have a 'valid' selection -> hide toolbar
if (!MediumEditor.selection.selectionContainsContent(this.document) ||
(this.allowMultiParagraphSelection === false && this.multipleBlockElementsSelected())) {
return this.hideToolbar();
}
this.showAndUpdateToolbar();
},
// Updating the toolbar
showAndUpdateToolbar: function () {
this.modifySelection();
this.setToolbarButtonStates();
this.trigger('positionToolbar', {}, this.base.getFocusedElement());
this.showToolbarDefaultActions();
this.setToolbarPosition();
},
setToolbarButtonStates: function () {
this.forEachExtension(function (extension) {
if (typeof extension.isActive === 'function' &&
typeof extension.setInactive === 'function') {
extension.setInactive();
}
});
this.checkActiveButtons();
},
checkActiveButtons: function () {
var manualStateChecks = [],
queryState = null,
selectionRange = MediumEditor.selection.getSelectionRange(this.document),
parentNode,
updateExtensionState = function (extension) {
if (typeof extension.checkState === 'function') {
extension.checkState(parentNode);
} else if (typeof extension.isActive === 'function' &&
typeof extension.isAlreadyApplied === 'function' &&
typeof extension.setActive === 'function') {
if (!extension.isActive() && extension.isAlreadyApplied(parentNode)) {
extension.setActive();
}
}
};
if (!selectionRange) {
return;
}
// Loop through all extensions
this.forEachExtension(function (extension) {
// For those extensions where we can use document.queryCommandState(), do so
if (typeof extension.queryCommandState === 'function') {
queryState = extension.queryCommandState();
// If queryCommandState returns a valid value, we can trust the browser
// and don't need to do our manual checks
if (queryState !== null) {
if (queryState && typeof extension.setActive === 'function') {
extension.setActive();
}
return;
}
}
// We can't use queryCommandState for this extension, so add to manualStateChecks
manualStateChecks.push(extension);
});
parentNode = MediumEditor.selection.getSelectedParentElement(selectionRange);
// Make sure the selection parent isn't outside of the contenteditable
if (!this.getEditorElements().some(function (element) {
return MediumEditor.util.isDescendant(element, parentNode, true);
})) {
return;
}
// Climb up the DOM and do manual checks for whether a certain extension is currently enabled for this node
while (parentNode) {
manualStateChecks.forEach(updateExtensionState);
// we can abort the search upwards if we leave the contentEditable element
if (MediumEditor.util.isMediumEditorElement(parentNode)) {
break;
}
parentNode = parentNode.parentNode;
}
},
// Positioning toolbar
positionToolbarIfShown: function () {
if (this.isDisplayed()) {
this.setToolbarPosition();
}
},
setToolbarPosition: function () {
var container = this.base.getFocusedElement(),
selection = this.window.getSelection();
// If there isn't a valid selection, bail
if (!container) {
return this;
}
if (this.static || !selection.isCollapsed) {
this.showToolbar();
// we don't need any absolute positioning if relativeContainer is set
if (!this.relativeContainer) {
if (this.static) {
this.positionStaticToolbar(container);
} else {
this.positionToolbar(selection);
}
}
this.trigger('positionedToolbar', {}, this.base.getFocusedElement());
}
},
positionStaticToolbar: function (container) {
// position the toolbar at left 0, so we can get the real width of the toolbar
this.getToolbarElement().style.left = '0';
// document.documentElement for IE 9
var scrollTop = (this.document.documentElement && this.document.documentElement.scrollTop) || this.document.body.scrollTop,
windowWidth = this.window.innerWidth,
toolbarElement = this.getToolbarElement(),
containerRect = container.getBoundingClientRect(),
containerTop = containerRect.top + scrollTop,
containerCenter = (containerRect.left + (containerRect.width / 2)),
toolbarHeight = toolbarElement.offsetHeight,
toolbarWidth = toolbarElement.offsetWidth,
halfOffsetWidth = toolbarWidth / 2,
targetLeft;
if (this.sticky) {
// If it's beyond the height of the editor, position it at the bottom of the editor
if (scrollTop > (containerTop + container.offsetHeight - toolbarHeight - this.stickyTopOffset)) {
toolbarElement.style.top = (containerTop + container.offsetHeight - toolbarHeight) + 'px';
toolbarElement.classList.remove('medium-editor-sticky-toolbar');
// Stick the toolbar to the top of the window
} else if (scrollTop > (containerTop - toolbarHeight - this.stickyTopOffset)) {
toolbarElement.classList.add('medium-editor-sticky-toolbar');
toolbarElement.style.top = this.stickyTopOffset + 'px';
// Normal static toolbar position
} else {
toolbarElement.classList.remove('medium-editor-sticky-toolbar');
toolbarElement.style.top = containerTop - toolbarHeight + 'px';
}
} else {
toolbarElement.style.top = containerTop - toolbarHeight + 'px';
}
switch (this.align) {
case 'left':
targetLeft = containerRect.left;
break;
case 'right':
targetLeft = containerRect.right - toolbarWidth;
break;
case 'center':
targetLeft = containerCenter - halfOffsetWidth;
break;
}
if (targetLeft < 0) {
targetLeft = 0;
} else if ((targetLeft + toolbarWidth) > windowWidth) {
targetLeft = (windowWidth - Math.ceil(toolbarWidth) - 1);
}
toolbarElement.style.left = targetLeft + 'px';
},
positionToolbar: function (selection) {
// position the toolbar at left 0, so we can get the real width of the toolbar
this.getToolbarElement().style.left = '0';
this.getToolbarElement().style.right = 'initial';
var range = selection.getRangeAt(0),
boundary = range.getBoundingClientRect();
// Handle selections with just images
if (!boundary || ((boundary.height === 0 && boundary.width === 0) && range.startContainer === range.endContainer)) {
// If there's a nested image, use that for the bounding rectangle
if (range.startContainer.nodeType === 1 && range.startContainer.querySelector('img')) {
boundary = range.startContainer.querySelector('img').getBoundingClientRect();
} else {
boundary = range.startContainer.getBoundingClientRect();
}
}
var containerWidth = this.window.innerWidth,
toolbarElement = this.getToolbarElement(),
toolbarHeight = toolbarElement.offsetHeight,
toolbarWidth = toolbarElement.offsetWidth,
halfOffsetWidth = toolbarWidth / 2,
buttonHeight = 50,
defaultLeft = this.diffLeft - halfOffsetWidth,
elementsContainer = this.getEditorOption('elementsContainer'),
elementsContainerAbsolute = ['absolute', 'fixed'].indexOf(window.getComputedStyle(elementsContainer).getPropertyValue('position')) > -1,
positions = {},
relativeBoundary = {},
middleBoundary, elementsContainerBoundary;
// If container element is absolute / fixed, recalculate boundaries to be relative to the container
if (elementsContainerAbsolute) {
elementsContainerBoundary = elementsContainer.getBoundingClientRect();
['top', 'left'].forEach(function (key) {
relativeBoundary[key] = boundary[key] - elementsContainerBoundary[key];
});
relativeBoundary.width = boundary.width;
relativeBoundary.height = boundary.height;
boundary = relativeBoundary;
containerWidth = elementsContainerBoundary.width;
// Adjust top position according to container scroll position
positions.top = elementsContainer.scrollTop;
} else {
// Adjust top position according to window scroll position
positions.top = this.window.pageYOffset;
}
middleBoundary = boundary.left + boundary.width / 2;
positions.top += boundary.top - toolbarHeight;
if (boundary.top < buttonHeight) {
toolbarElement.classList.add('medium-toolbar-arrow-over');
toolbarElement.classList.remove('medium-toolbar-arrow-under');
positions.top += buttonHeight + boundary.height - this.diffTop;
} else {
toolbarElement.classList.add('medium-toolbar-arrow-under');
toolbarElement.classList.remove('medium-toolbar-arrow-over');
positions.top += this.diffTop;
}
if (middleBoundary < halfOffsetWidth) {
positions.left = defaultLeft + halfOffsetWidth;
positions.right = 'initial';
} else if ((containerWidth - middleBoundary) < halfOffsetWidth) {
positions.left = 'auto';
positions.right = 0;
} else {
positions.left = defaultLeft + middleBoundary;
positions.right = 'initial';
}
['top', 'left', 'right'].forEach(function (key) {
toolbarElement.style[key] = positions[key] + (isNaN(positions[key]) ? '' : 'px');
});
}
});
MediumEditor.extensions.toolbar = Toolbar;
}());