-
Notifications
You must be signed in to change notification settings - Fork 370
/
Copy pathbootstrap-markdown.js
1595 lines (1373 loc) · 50.2 KB
/
bootstrap-markdown.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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ===================================================
* bootstrap-markdown.js v2.10.0
* http://github.com/toopay/bootstrap-markdown
* ===================================================
* Copyright 2013-2016 Taufan Aditya
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================== */
(function(factory) {
if (typeof define === "function" && define.amd) {
// RequireJS
define(["jquery"], factory);
} else if (typeof exports === 'object') {
// Backbone.js
factory(require('jquery'));
} else {
// jQuery plugin
factory(jQuery);
}
}(function($) {
"use strict";
/* MARKDOWN CLASS DEFINITION
* ========================== */
var Markdown = function(element, options) {
// @TODO : remove this BC on next major release
// @see : https://github.com/toopay/bootstrap-markdown/issues/109
var opts = ['autofocus', 'savable', 'hideable', 'width',
'height', 'resize', 'iconlibrary', 'language',
'footer', 'fullscreen', 'hiddenButtons', 'disabledButtons'
];
$.each(opts, function(_, opt) {
if (typeof $(element).data(opt) !== 'undefined') {
options = typeof options == 'object' ? options : {};
options[opt] = $(element).data(opt);
}
});
// End BC
// Class Properties
this.$ns = 'bootstrap-markdown';
this.$element = $(element);
this.$editable = {
el: null,
type: null,
attrKeys: [],
attrValues: [],
content: null
};
this.$options = $.extend(true, {}, $.fn.markdown.defaults, options, this.$element.data('options'));
this.$oldContent = null;
this.$isPreview = false;
this.$isFullscreen = false;
this.$editor = null;
this.$textarea = null;
this.$handler = [];
this.$callback = [];
this.$nextTab = [];
this.showEditor();
};
Markdown.prototype = {
constructor: Markdown,
__alterButtons: function(name, alter) {
var handler = this.$handler,
isAll = (name == 'all'),
that = this;
$.each(handler, function(k, v) {
var halt = true;
if (isAll) {
halt = false;
} else {
halt = v.indexOf(name) < 0;
}
if (halt === false) {
alter(that.$editor.find('button[data-handler="' + v + '"]'));
}
});
},
__buildButtons: function(buttonsArray, container) {
var i,
ns = this.$ns,
handler = this.$handler,
callback = this.$callback;
for (i = 0; i < buttonsArray.length; i++) {
// Build each group container
var y, btnGroups = buttonsArray[i];
for (y = 0; y < btnGroups.length; y++) {
// Build each button group
var z,
buttons = btnGroups[y].data,
btnGroupContainer = $('<div/>', {
'class': 'btn-group'
});
for (z = 0; z < buttons.length; z++) {
var button = buttons[z],
buttonContainer, buttonIconContainer,
buttonHandler = ns + '-' + button.name,
buttonIcon = this.__getIcon(button),
btnText = button.btnText ? button.btnText : '',
btnClass = button.btnClass ? button.btnClass : 'btn',
tabIndex = button.tabIndex ? button.tabIndex : '-1',
hotkey = typeof button.hotkey !== 'undefined' ? button.hotkey : '',
hotkeyCaption = typeof jQuery.hotkeys !== 'undefined' && hotkey !== '' ? ' (' + hotkey + ')' : '';
// Construct the button object
buttonContainer = $('<button></button>');
buttonContainer.text(' ' + this.__localize(btnText)).addClass('btn-default btn-sm').addClass(btnClass);
if (btnClass.match(/btn\-(primary|success|info|warning|danger|link)/)) {
buttonContainer.removeClass('btn-default');
}
buttonContainer.attr({
'type': 'button',
'title': this.__localize(button.title) + hotkeyCaption,
'tabindex': tabIndex,
'data-provider': ns,
'data-handler': buttonHandler,
'data-hotkey': hotkey
});
if (button.toggle === true) {
buttonContainer.attr('data-toggle', 'button');
}
buttonIconContainer = $('<span/>');
buttonIconContainer.addClass(buttonIcon);
buttonIconContainer.prependTo(buttonContainer);
// Attach the button object
btnGroupContainer.append(buttonContainer);
// Register handler and callback
handler.push(buttonHandler);
callback.push(button.callback);
}
// Attach the button group into container DOM
container.append(btnGroupContainer);
}
}
return container;
},
__setListener: function() {
// Set size and resizable Properties
var hasRows = typeof this.$textarea.attr('rows') !== 'undefined',
maxRows = this.$textarea.val().split("\n").length > 5 ? this.$textarea.val().split("\n").length : '5',
rowsVal = hasRows ? this.$textarea.attr('rows') : maxRows;
this.$textarea.attr('rows', rowsVal);
if (this.$options.resize) {
this.$textarea.css('resize', this.$options.resize);
}
// Re-attach markdown data
this.$textarea.data('markdown', this);
},
__setEventListeners: function() {
this.$textarea.on({
'focus': $.proxy(this.focus, this),
'keyup': $.proxy(this.keyup, this),
'change': $.proxy(this.change, this),
'select': $.proxy(this.select, this)
});
if (this.eventSupported('keydown')) {
this.$textarea.on('keydown', $.proxy(this.keydown, this));
}
if (this.eventSupported('keypress')) {
this.$textarea.on('keypress', $.proxy(this.keypress, this));
}
},
__handle: function(e) {
var target = $(e.currentTarget),
handler = this.$handler,
callback = this.$callback,
handlerName = target.attr('data-handler'),
callbackIndex = handler.indexOf(handlerName),
callbackHandler = callback[callbackIndex];
// Trigger the focusin
$(e.currentTarget).focus();
callbackHandler(this);
// Trigger onChange for each button handle
this.change(this);
// Unless it was the save handler,
// focusin the textarea
if (handlerName.indexOf('cmdSave') < 0) {
this.$textarea.focus();
}
e.preventDefault();
},
__localize: function(string) {
var messages = $.fn.markdown.messages,
language = this.$options.language;
if (
typeof messages !== 'undefined' &&
typeof messages[language] !== 'undefined' &&
typeof messages[language][string] !== 'undefined'
) {
return messages[language][string];
}
return string;
},
__getIcon: function(src) {
if(typeof src == 'object'){
var customIcon = this.$options.customIcons[src.name];
return typeof customIcon == 'undefined' ? src.icon[this.$options.iconlibrary] : customIcon;
} else {
return src;
}
},
setFullscreen: function(mode) {
var $editor = this.$editor,
$textarea = this.$textarea;
if (mode === true) {
$editor.addClass('md-fullscreen-mode');
$('body').addClass('md-nooverflow');
this.$options.onFullscreen(this);
} else {
$editor.removeClass('md-fullscreen-mode');
$('body').removeClass('md-nooverflow');
this.$options.onFullscreenExit(this);
if (this.$isPreview === true)
this.hidePreview().showPreview();
}
this.$isFullscreen = mode;
$textarea.focus();
},
showEditor: function() {
var instance = this,
textarea,
ns = this.$ns,
container = this.$element,
originalHeigth = container.css('height'),
originalWidth = container.css('width'),
editable = this.$editable,
handler = this.$handler,
callback = this.$callback,
options = this.$options,
editor = $('<div/>', {
'class': 'md-editor',
click: function() {
instance.focus();
}
});
// Prepare the editor
if (this.$editor === null) {
// Create the panel
var editorHeader = $('<div/>', {
'class': 'md-header btn-toolbar'
});
// Merge the main & additional button groups together
var allBtnGroups = [];
if (options.buttons.length > 0) allBtnGroups = allBtnGroups.concat(options.buttons[0]);
if (options.additionalButtons.length > 0) {
// iterate the additional button groups
$.each(options.additionalButtons[0], function(idx, buttonGroup) {
// see if the group name of the additional group matches an existing group
var matchingGroups = $.grep(allBtnGroups, function(allButtonGroup, allIdx) {
return allButtonGroup.name === buttonGroup.name;
});
// if it matches add the additional buttons to that group, if not just add it to the all buttons group
if (matchingGroups.length > 0) {
matchingGroups[0].data = matchingGroups[0].data.concat(buttonGroup.data);
} else {
allBtnGroups.push(options.additionalButtons[0][idx]);
}
});
}
// Reduce and/or reorder the button groups
if (options.reorderButtonGroups.length > 0) {
allBtnGroups = allBtnGroups
.filter(function(btnGroup) {
return options.reorderButtonGroups.indexOf(btnGroup.name) > -1;
})
.sort(function(a, b) {
if (options.reorderButtonGroups.indexOf(a.name) < options.reorderButtonGroups.indexOf(b.name)) return -1;
if (options.reorderButtonGroups.indexOf(a.name) > options.reorderButtonGroups.indexOf(b.name)) return 1;
return 0;
});
}
// Build the buttons
if (allBtnGroups.length > 0) {
editorHeader = this.__buildButtons([allBtnGroups], editorHeader);
}
if (options.fullscreen.enable) {
editorHeader.append('<div class="md-controls"><a class="md-control md-control-fullscreen" href="#"><span class="' + this.__getIcon(options.fullscreen.icons.fullscreenOn) + '"></span></a></div>').on('click', '.md-control-fullscreen', function(e) {
e.preventDefault();
instance.setFullscreen(true);
});
}
editor.append(editorHeader);
// Wrap the textarea
if (container.is('textarea')) {
container.before(editor);
textarea = container;
textarea.addClass('md-input');
editor.append(textarea);
} else {
var rawContent = (typeof toMarkdown == 'function') ? toMarkdown(container.html()) : container.html(),
currentContent = $.trim(rawContent);
// This is some arbitrary content that could be edited
textarea = $('<textarea/>', {
'class': 'md-input',
'val': currentContent
});
editor.append(textarea);
// Save the editable
editable.el = container;
editable.type = container.prop('tagName').toLowerCase();
editable.content = container.html();
$(container[0].attributes).each(function() {
editable.attrKeys.push(this.nodeName);
editable.attrValues.push(this.nodeValue);
});
// Set editor to block the original container
container.replaceWith(editor);
}
var editorFooter = $('<div/>', {
'class': 'md-footer'
}),
createFooter = false,
footer = '';
// Create the footer if savable
if (options.savable) {
createFooter = true;
var saveHandler = 'cmdSave';
// Register handler and callback
handler.push(saveHandler);
callback.push(options.onSave);
editorFooter.append('<button class="btn btn-success" data-provider="' +
ns +
'" data-handler="' +
saveHandler +
'"><i class="icon icon-white icon-ok"></i> ' +
this.__localize('Save') +
'</button>');
}
footer = typeof options.footer === 'function' ? options.footer(this) : options.footer;
if ($.trim(footer) !== '') {
createFooter = true;
editorFooter.append(footer);
}
if (createFooter) editor.append(editorFooter);
// Set width
if (options.width && options.width !== 'inherit') {
if (jQuery.isNumeric(options.width)) {
editor.css('display', 'table');
textarea.css('width', options.width + 'px');
} else {
editor.addClass(options.width);
}
}
// Set height
if (options.height && options.height !== 'inherit') {
if (jQuery.isNumeric(options.height)) {
var height = options.height;
if (editorHeader) height = Math.max(0, height - editorHeader.outerHeight());
if (editorFooter) height = Math.max(0, height - editorFooter.outerHeight());
textarea.css('height', height + 'px');
} else {
editor.addClass(options.height);
}
}
// Reference
this.$editor = editor;
this.$textarea = textarea;
this.$editable = editable;
this.$oldContent = this.getContent();
this.__setListener();
this.__setEventListeners();
// Set editor attributes, data short-hand API and listener
this.$editor.attr('id', (new Date()).getTime());
this.$editor.on('click', '[data-provider="bootstrap-markdown"]', $.proxy(this.__handle, this));
if (this.$element.is(':disabled') || this.$element.is('[readonly]')) {
this.$editor.addClass('md-editor-disabled');
this.disableButtons('all');
}
if (this.eventSupported('keydown') && typeof jQuery.hotkeys === 'object') {
editorHeader.find('[data-provider="bootstrap-markdown"]').each(function() {
var $button = $(this),
hotkey = $button.attr('data-hotkey');
if (hotkey.toLowerCase() !== '') {
textarea.bind('keydown', hotkey, function() {
$button.trigger('click');
return false;
});
}
});
}
if (options.initialstate === 'preview') {
this.showPreview();
} else if (options.initialstate === 'fullscreen' && options.fullscreen.enable) {
this.setFullscreen(true);
}
} else {
this.$editor.show();
}
if (options.autofocus) {
this.$textarea.focus();
this.$editor.addClass('active');
}
if (options.fullscreen.enable && options.fullscreen !== false) {
this.$editor.append('<div class="md-fullscreen-controls">' +
'<a href="#" class="exit-fullscreen" title="Exit fullscreen"><span class="' + this.__getIcon(options.fullscreen.icons.fullscreenOff) + '">' +
'</span></a>' +
'</div>');
this.$editor.on('click', '.exit-fullscreen', function(e) {
e.preventDefault();
instance.setFullscreen(false);
});
}
// hide hidden buttons from options
this.hideButtons(options.hiddenButtons);
// disable disabled buttons from options
this.disableButtons(options.disabledButtons);
// enable dropZone if available and configured
if (options.dropZoneOptions) {
if (this.$editor.dropzone) {
if(!options.dropZoneOptions.init) {
options.dropZoneOptions.init = function() {
var caretPos = 0;
this.on('drop', function(e) {
caretPos = textarea.prop('selectionStart');
});
this.on('success', function(file, path) {
var text = textarea.val();
textarea.val(text.substring(0, caretPos) + '\n\n' + text.substring(caretPos));
});
this.on('error', function(file, error, xhr) {
console.log('Error:', error);
});
};
}
this.$editor.addClass('dropzone');
this.$editor.dropzone(options.dropZoneOptions);
} else {
console.log('dropZoneOptions was configured, but DropZone was not detected.');
}
}
// enable data-uris via drag and drop
if (options.enableDropDataUri === true) {
this.$editor.on('drop', function(e) {
var caretPos = textarea.prop('selectionStart');
e.stopPropagation();
e.preventDefault();
$.each(e.originalEvent.dataTransfer.files, function(index, file){
var fileReader = new FileReader();
fileReader.onload = (function(file) {
var type = file.type.split('/')[0];
return function(e) {
var text = textarea.val();
if (type === 'image')
textarea.val(text.substring(0, caretPos) + '\n<img src="'+ e.target.result +'" />\n' + text.substring(caretPos) );
else
textarea.val(text.substring(0, caretPos) + '\n<a href="'+ e.target.result +'">Download ' + file.name + '</a>\n' + text.substring(caretPos) );
};
})(file);
fileReader.readAsDataURL(file);
});
});
}
// Trigger the onShow hook
options.onShow(this);
return this;
},
parseContent: function(val) {
var content;
// parse with supported markdown parser
val = val || this.$textarea.val();
if (this.$options.parser) {
content = this.$options.parser(val);
} else if (typeof markdown == 'object') {
content = markdown.toHTML(val);
} else if (typeof marked == 'function') {
content = marked(val);
} else {
content = val;
}
return content;
},
showPreview: function() {
var options = this.$options,
container = this.$textarea,
afterContainer = container.next(),
replacementContainer = $('<div/>', {
'class': 'md-preview',
'data-provider': 'markdown-preview'
}),
content,
callbackContent;
if (this.$isPreview === true) {
// Avoid sequenced element creation on misused scenario
// @see https://github.com/toopay/bootstrap-markdown/issues/170
return this;
}
// Give flag that tells the editor to enter preview mode
this.$isPreview = true;
// Disable all buttons
this.disableButtons('all').enableButtons('cmdPreview');
// Try to get the content from callback
callbackContent = options.onPreview(this, replacementContainer);
// Set the content based on the callback content if string, otherwise parse value from textarea
content = typeof callbackContent == 'string' ? callbackContent : this.parseContent();
// Build preview element
replacementContainer.html(content);
if (afterContainer && afterContainer.attr('class') == 'md-footer') {
// If there is footer element, insert the preview container before it
replacementContainer.insertBefore(afterContainer);
} else {
// Otherwise, just append it after textarea
container.parent().append(replacementContainer);
}
// Set the preview element dimensions
replacementContainer.css({
"width": container.outerWidth() + 'px',
"min-height": container.outerHeight() + 'px',
"height": "auto"
});
if (this.$options.resize) {
replacementContainer.css('resize', this.$options.resize);
}
// Hide the last-active textarea
container.hide();
// Attach the editor instances
replacementContainer.data('markdown', this);
if (this.$element.is(':disabled') || this.$element.is('[readonly]')) {
this.$editor.addClass('md-editor-disabled');
this.disableButtons('all');
}
return this;
},
hidePreview: function() {
// Give flag that tells the editor to quit preview mode
this.$isPreview = false;
// Obtain the preview container
var container = this.$editor.find('div[data-provider="markdown-preview"]');
// Remove the preview container
container.remove();
// Enable all buttons
this.enableButtons('all');
// Disable configured disabled buttons
this.disableButtons(this.$options.disabledButtons);
// Perform any callbacks
this.$options.onPreviewEnd(this);
// Back to the editor
this.$textarea.show();
this.__setListener();
return this;
},
isDirty: function() {
return this.$oldContent != this.getContent();
},
getContent: function() {
return this.$textarea.val();
},
setContent: function(content) {
this.$textarea.val(content);
return this;
},
findSelection: function(chunk) {
var content = this.getContent(),
startChunkPosition;
if (startChunkPosition = content.indexOf(chunk), startChunkPosition >= 0 && chunk.length > 0) {
var oldSelection = this.getSelection(),
selection;
this.setSelection(startChunkPosition, startChunkPosition + chunk.length);
selection = this.getSelection();
this.setSelection(oldSelection.start, oldSelection.end);
return selection;
} else {
return null;
}
},
getSelection: function() {
var e = this.$textarea[0];
return (
('selectionStart' in e && function() {
var l = e.selectionEnd - e.selectionStart;
return {
start: e.selectionStart,
end: e.selectionEnd,
length: l,
text: e.value.substr(e.selectionStart, l)
};
}) ||
/* browser not supported */
function() {
return null;
}
)();
},
setSelection: function(start, end) {
var e = this.$textarea[0];
return (
('selectionStart' in e && function() {
e.selectionStart = start;
e.selectionEnd = end;
return;
}) ||
/* browser not supported */
function() {
return null;
}
)();
},
replaceSelection: function(text) {
var e = this.$textarea[0];
return (
('selectionStart' in e && function() {
e.value = e.value.substr(0, e.selectionStart) + text + e.value.substr(e.selectionEnd, e.value.length);
// Set cursor to the last replacement end
e.selectionStart = e.value.length;
return this;
}) ||
/* browser not supported */
function() {
e.value += text;
return jQuery(e);
}
)();
},
getNextTab: function() {
// Shift the nextTab
if (this.$nextTab.length === 0) {
return null;
} else {
var nextTab, tab = this.$nextTab.shift();
if (typeof tab == 'function') {
nextTab = tab();
} else if (typeof tab == 'object' && tab.length > 0) {
nextTab = tab;
}
return nextTab;
}
},
setNextTab: function(start, end) {
// Push new selection into nextTab collections
if (typeof start == 'string') {
var that = this;
this.$nextTab.push(function() {
return that.findSelection(start);
});
} else if (typeof start == 'number' && typeof end == 'number') {
var oldSelection = this.getSelection();
this.setSelection(start, end);
this.$nextTab.push(this.getSelection());
this.setSelection(oldSelection.start, oldSelection.end);
}
return;
},
__parseButtonNameParam: function(names) {
return typeof names == 'string' ?
names.split(' ') :
names;
},
enableButtons: function(name) {
var buttons = this.__parseButtonNameParam(name),
that = this;
$.each(buttons, function(i, v) {
that.__alterButtons(buttons[i], function(el) {
el.removeAttr('disabled');
});
});
return this;
},
disableButtons: function(name) {
var buttons = this.__parseButtonNameParam(name),
that = this;
$.each(buttons, function(i, v) {
that.__alterButtons(buttons[i], function(el) {
el.attr('disabled', 'disabled');
});
});
return this;
},
hideButtons: function(name) {
var buttons = this.__parseButtonNameParam(name),
that = this;
$.each(buttons, function(i, v) {
that.__alterButtons(buttons[i], function(el) {
el.addClass('hidden');
});
});
return this;
},
showButtons: function(name) {
var buttons = this.__parseButtonNameParam(name),
that = this;
$.each(buttons, function(i, v) {
that.__alterButtons(buttons[i], function(el) {
el.removeClass('hidden');
});
});
return this;
},
eventSupported: function(eventName) {
var isSupported = eventName in this.$element;
if (!isSupported) {
this.$element.setAttribute(eventName, 'return;');
isSupported = typeof this.$element[eventName] === 'function';
}
return isSupported;
},
keyup: function(e) {
var blocked = false;
switch (e.keyCode) {
case 40: // down arrow
case 38: // up arrow
case 16: // shift
case 17: // ctrl
case 18: // alt
break;
case 9: // tab
var nextTab;
if (nextTab = this.getNextTab(), nextTab !== null) {
// Get the nextTab if exists
var that = this;
setTimeout(function() {
that.setSelection(nextTab.start, nextTab.end);
}, 500);
blocked = true;
} else {
// The next tab's memory contains nothing...
// check the cursor position to determine tab action
var cursor = this.getSelection();
if (cursor.start == cursor.end && cursor.end == this.getContent().length) {
// The cursor has reached the end of the content
blocked = false;
} else {
// Put the cursor to the end
this.setSelection(this.getContent().length, this.getContent().length);
blocked = true;
}
}
break;
case 13: // enter
blocked = false;
var chars = this.getContent().split('');
var enterIndex = this.getSelection().start;
var priorNewlineIndex = -1; // initial line break at before index 0
// traverse backwards through chars to check if last line break was num/bullet item
for (var i = enterIndex - 2; i >= 0; i--) {
if (chars[i] === '\n') {
priorNewlineIndex = i;
break;
}
}
if (chars.slice(priorNewlineIndex + 1, priorNewlineIndex + 4).join('') == '---') {
break;
}
var charFollowingLastLineBreak = chars[priorNewlineIndex + 1];
if (charFollowingLastLineBreak === '-') {
var line = chars.slice(priorNewlineIndex + 2, enterIndex).join('');
var allWhitespace = /^[\W]*$/.test(line);
if (allWhitespace) {
// If we hit enter on a empty line, we probably want to close the bullet list
var linesDeleted = line.length + 2;
this.setSelection(priorNewlineIndex, enterIndex);
this.replaceSelection("\n\n");
this.setSelection(enterIndex + 2 - linesDeleted, enterIndex + 2 - linesDeleted); // Put the cursor into new line
} else {
this.addBullet(enterIndex);
}
} else if ($.isNumeric(charFollowingLastLineBreak)) {
var numBullet = this.getBulletNumber(priorNewlineIndex + 1);
if (numBullet) {
var line = chars.slice(priorNewlineIndex + 1, enterIndex).join('');
var allWhitespace = (new RegExp('^' + numBullet + '\\.[\\W]*$')).test(line);
if (allWhitespace) {
// If we hit enter on a empty line, we probably want to close the numbered bullet list
var linesDeleted = line.length;
this.setSelection(priorNewlineIndex, enterIndex);
this.replaceSelection("\n\n");
this.setSelection(enterIndex + 1 - linesDeleted, enterIndex + 1 - linesDeleted); // Put the cursor into new line
} else {
this.addNumberedBullet(enterIndex, numBullet);
}
}
}
break;
case 27: // escape
if (this.$isFullscreen) this.setFullscreen(false);
blocked = false;
break;
default:
blocked = false;
}
if (blocked) {
e.stopPropagation();
e.preventDefault();
}
this.$options.onChange(this);
},
insertContent: function(index, content) {
var firstHalf = this.getContent().slice(0, index);
var secondHalf = this.getContent().slice(index + 1);
this.setContent(firstHalf.concat(content).concat(secondHalf));
},
addBullet: function(index) {
this.insertContent(index, '- \n');
this.setSelection(index + 2, index + 2); // Put the cursor after the bullet
},
addNumberedBullet: function(index, num) {
var numBullet = (num + 1) + '. \n';
this.insertContent(index, numBullet);
var prefixLength = (num + 1).toString().length + 2;
this.setSelection(index + prefixLength, index + prefixLength); // Put the cursor after the number
},
getBulletNumber: function(startIndex) {
var bulletNum = this.getContent().slice(startIndex).split('.')[0];
return $.isNumeric(bulletNum) ? parseInt(bulletNum) : null;
},
change: function(e) {
this.$options.onChange(this);
return this;
},
select: function(e) {
this.$options.onSelect(this);
return this;
},
focus: function(e) {
var options = this.$options,
isHideable = options.hideable,
editor = this.$editor;
editor.addClass('active');
// Blur other markdown(s)
$(document).find('.md-editor').each(function() {
if ($(this).attr('id') !== editor.attr('id')) {
var attachedMarkdown;
if (attachedMarkdown = $(this).find('textarea').data('markdown'),
attachedMarkdown === null) {
attachedMarkdown = $(this).find('div[data-provider="markdown-preview"]').data('markdown');
}
if (attachedMarkdown) {
attachedMarkdown.blur();
}
}
});
// Trigger the onFocus hook
options.onFocus(this);
return this;
},
blur: function(e) {
var options = this.$options,
isHideable = options.hideable,
editor = this.$editor,
editable = this.$editable;
if (editor.hasClass('active') || this.$element.parent().length === 0) {
editor.removeClass('active');
if (isHideable) {
// Check for editable elements
if (editable.el !== null) {
// Build the original element
var oldElement = $('<' + editable.type + '/>'),
content = this.getContent(),
currentContent = this.parseContent(content);