forked from mfrye/textAngular
-
Notifications
You must be signed in to change notification settings - Fork 0
/
textAngular.js
1341 lines (1287 loc) · 55.5 KB
/
textAngular.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
/*
textAngular
Author : Austin Anderson
License : 2013 MIT
Version 1.2.0
See README.md or https://github.com/fraywing/textAngular/wiki for requirements and use.
*/
(function(){ // encapsulate all variables so they don't become global vars
"Use Strict";
var textAngular = angular.module("textAngular", ['ngSanitize', 'colorpicker.module', 'ui.bootstrap.dropdownToggle']); //This makes ngSanitize required
// Here we set up the global display defaults, to set your own use a angular $provider#decorator.
textAngular.value('taOptions', {
toolbar: [
['blockFormat', 'pre', 'quote', 'fontName', 'fontSize', 'bold', 'italics', 'underline', 'strikeThrough', 'fontColor', 'backgroundColor', 'alignment', 'ul', 'ol', 'outdent', 'indent'],
['insertImage', 'insertLink', 'unlink', 'insertHorizontalRule'],
['redo', 'undo', 'clear', 'html']
],
classes: {
focussed: "focussed",
toolbar: "btn-toolbar",
toolbarGroup: "btn-group",
toolbarButton: "btn btn-default",
toolbarButtonActive: "active",
disabled: "disabled",
textEditor: 'form-control',
htmlEditor: 'form-control'
},
setup: {
// wysiwyg mode
textEditorSetup: function($element){ /* Do some processing here */ },
// raw html
htmlEditorSetup: function($element){ /* Do some processing here */ }
}
});
// setup the global contstant functions for setting up the toolbar
// all tool definitions
var taTools = {};
/*
A tool definition is an object with the following key/value parameters:
action: [function(deferred, restoreSelection)]
a function that is executed on clicking on the button - this will allways be executed using ng-click and will
overwrite any ng-click value in the display attribute.
The function is passed a deferred object ($q.defer()), if this is wanted to be used `return false;` from the action and
manually call `deferred.resolve();` elsewhere to notify the editor that the action has finished.
restoreSelection is only defined if the rangy library is included and it can be called as `restoreSelection()` to restore the users
selection in the WYSIWYG editor.
display: [string]?
Optional, an HTML element to be displayed as the buton. The `scope` of the button is the tool definition object with some additional functions
If set this will cause buttontext and iconclass to be ignored
buttontext: [string]?
if this is defined it will replace the contents of the element contained in the `display` element
iconclass: [string]?
if this is defined an icon (<i>) will be appended to the `display` element with this string as it's class
activestate: [function(commonElement)]?
this function is called on every caret movement, if it returns true then the class taOptions.classes.toolbarButtonActive
will be applied to the `display` element, else the class will be removed
If the rangy library is loaded commonElement will be an angular.element object that contains ALL of the selection.
disabled: [function()]?
if this function returns true then the tool will have the class taOptions.classes.disabled applied to it, else it will be removed
Other functions available on the scope are:
name: [string]
the name of the tool, this is the first parameter passed into taRegisterTool
isDisabled: [function()]
returns true if the tool is disabled, false if it isn't
displayActiveToolClass: [function(boolean)]
returns true if the tool is 'active' in the currently focussed toolbar
*/
// name and toolDefinition to add into the tools available to be added on the toolbar
function registerTextAngularTool(name, toolDefinition){
if(!name || name === '' || taTools.hasOwnProperty(name)) throw('textAngular Error: A unique name is required for a Tool Definition');
if(
(toolDefinition.display && (toolDefinition.display === '' || angular.element(toolDefinition.display).length === 0)) ||
(!toolDefinition.display && !toolDefinition.buttontext && !toolDefinition.iconclass)
)
throw('textAngular Error: Tool Definition for "' + name + '" does not have a valid display/iconclass/buttontext value');
taTools[name] = toolDefinition;
}
textAngular.constant('taRegisterTool', registerTextAngularTool);
textAngular.value('taTools', taTools);
// configure initial textAngular tools here via taRegisterTool
textAngular.config(['taRegisterTool', function(taRegisterTool){
// clear taTools variable. Just catches testing and any other time that this config may run multiple times...
angular.forEach(taTools, function(value, key){ delete taTools[key]; });
taRegisterTool("html", {
buttontext: 'Toggle HTML',
action: function(){
this.$editor().switchView();
},
activeState: function(){
return this.$editor().showHtml;
}
});
// add the Header tools
// convenience functions so that the loop works correctly
var _retActiveStateFunction = function(q){
return function(){ return this.$editor().queryFormatBlockState(q); };
};
var headerAction = function(){
return this.$editor().wrapSelection("formatBlock", "<" + this.name.toUpperCase() +">");
};
angular.forEach(['h1','h2','h3','h4','h5','h6'], function(h){
taRegisterTool(h.toLowerCase(), {
buttontext: h.toUpperCase(),
action: headerAction,
activeState: _retActiveStateFunction(h.toLowerCase())
});
});
taRegisterTool('p', {
buttontext: 'P',
action: function(){
return this.$editor().wrapSelection("formatBlock", "<P>");
},
activeState: function(){
return this.$editor().queryFormatBlockState('p'); }
});
taRegisterTool('blockFormat', {
display: "<span class='bar-btn-dropdown dropdown'>" +
"<button class='btn btn-default dropdown-toggle' type='button' ng-disabled='showHtml()'><span>{{active}} </span></button>" +
"<ul class='dropdown-menu'><li ng-repeat='o in options'><button class='checked-dropdown' type='button' ng-click='action(o.html)'><i ng-if='o.active' class='fa fa-check'></i>{{o.name}}</button></li></ul></span>",
action: function(html) {
if (html !== '') {
this.$editor().wrapSelection('formatBlock', html);
}
},
options: [
{name: 'Header 1 (h1)', code: 'h1', html: '<H1>'},
{name: 'Header 2 (h2)', code: 'h2', html: '<H2>'},
{name: 'Header 3 (h3)', code: 'h3', html: '<H3>'},
{name: 'Header 4 (h4)', code: 'h4', html: '<H4>'},
{name: 'Header 5 (h5)', code: 'h5', html: '<H5>'},
{name: 'Header 6 (h6)', code: 'h6', html: '<H6>'},
{name: 'Paragraph (p)', code: 'p', html: '<P>'}
],
active: 'Format Text',
setActive: function(html) {
angular.forEach(this.options, function(option) {
if (html === option.html) {
this.active = option.name;
option['active'] = true;
} else {
option['active'] = false;
}
});
},
getActive: function() {
var format = document.queryCommandValue('formatBlock');
selected = '';
angular.forEach(this.options, function(option) {
if (option.code === format) {
selected = option.html;
}
});
return selected;
}
});
taRegisterTool('pre', {
buttontext: 'pre',
action: function(){
return this.$editor().wrapSelection("formatBlock", "<PRE>");
},
activeState: function(){ return this.$editor().queryFormatBlockState('pre'); }
});
taRegisterTool('ul', {
iconclass: 'fa fa-list-ul',
action: function(){
return this.$editor().wrapSelection("insertUnorderedList", null);
},
activeState: function(){ return document.queryCommandState('insertUnorderedList'); }
});
taRegisterTool('ol', {
iconclass: 'fa fa-list-ol',
action: function(){
return this.$editor().wrapSelection("insertOrderedList", null);
},
activeState: function(){ return document.queryCommandState('insertOrderedList'); }
});
taRegisterTool('quote', {
iconclass: 'fa fa-quote-right',
action: function(){
return this.$editor().wrapSelection("formatBlock", "<BLOCKQUOTE>");
},
activeState: function(){ return this.$editor().queryFormatBlockState('blockquote'); }
});
taRegisterTool('indent', {
iconclass: 'fa fa-indent',
action: function(){
return this.$editor().wrapSelection("indent", null);
}
});
taRegisterTool('outdent', {
iconclass: 'fa fa-outdent',
action: function(){
return this.$editor().wrapSelection("outdent", null);
}
});
taRegisterTool('fontName', {
display: "<span class='bar-btn-dropdown dropdown'>" +
"<button class='btn btn-default dropdown-toggle' type='button' ng-disabled='showHtml()'><span>{{active}} </span></button>" +
"<ul class='dropdown-menu'><li ng-repeat='o in options'><button class='checked-dropdown' style='font-family: {{o.css}}' type='button' ng-click='action(o.css)'><i ng-if='o.active' class='fa fa-check'></i>{{o.name}}</button></li></ul></span>",
action: function(font) {
if (font !== '') {
this.$editor().wrapSelection('fontName', font);
}
},
options: [
{name: 'Sans-Serif', css: 'Arial, Helvetica, sans-serif'},
{name: 'Serif', css: "'times new roman', serif"},
{name: 'Wide', css: "'arial black', sans-serif"},
{name: 'Narrow', css: "'arial narrow', sans-serif"},
{name: 'Comic Sans MS', css: "'comic sans ms', sans-serif"},
{name: 'Courier New', css: "'courier new', monospace"},
{name: 'Garamond', css: 'garamond, serif'},
{name: 'Georgia', css: 'georgia, serif'},
{name: 'Tahoma', css: 'tahoma, sans-serif'},
{name: 'Trebuchet MS', css: "'trebuchet ms', sans-serif"},
{name: "Helvetica", css: "'Helvetica Neue', Helvetica, Arial, sans-serif"},
{name: 'Verdana', css: 'verdana, sans-serif'},
{name: 'Proxima Nova', css: 'proxima_nova_rgregular'}
],
active: 'Font Family',
setActive: function(font) {
angular.forEach(this.options, function(option) {
if (font === option.css) {
this.active = option.name;
option['active'] = true;
} else {
option['active'] = false;
}
});
},
getActive: function() {
var font = document.queryCommandValue('fontName');
if (font === '') {
return 'Arial, Helvetica, sans-serif';
} else {
return font;
}
}
});
taRegisterTool('fontSize', {
display: "<span class='bar-btn-dropdown dropdown'>" +
"<button class='btn btn-default dropdown-toggle' type='button' ng-disabled='showHtml()'><i class='fa fa-font'></i><i class='fa fa-caret-down'></i></button>" +
"<ul class='dropdown-menu'><li ng-repeat='o in options'><button class='checked-dropdown' style='font-size: {{o.css}}' type='button' ng-click='action(o.value)'><i ng-if='o.active' class='fa fa-check'></i> {{o.name}}</button></li></ul>" +
"</span>",
action: function(size) {
if (size !== '') {
return this.$editor().wrapSelection('fontSize', size);
}
},
options: [
{name: 'Extra Small', css: 'xx-small', value: '1'},
{name: 'Small', css: 'x-small', value: '2'},
{name: 'Medium', css: 'small', value: '3'},
{name: 'Large', css: 'medium', value: '4'},
{name: 'Extra Large', css: 'large', value: '5'},
{name: 'Huge', css: 'x-large', value: '6'}
],
setActive: function(font) {
// Convert to string if not already
if (typeof font !== 'string') { font = String(font) };
angular.forEach(this.options, function(option) {
option['active'] = font === option.value ? true : false;
});
},
getActive: function() {
var font = document.queryCommandValue('fontSize');
if (font === '') {
return 3;
} else {
return font;
}
}
});
taRegisterTool('undo', {
iconclass: 'fa fa-undo',
action: function(){
return this.$editor().wrapSelection("undo", null);
}
});
taRegisterTool('redo', {
iconclass: 'fa fa-repeat',
action: function(){
return this.$editor().wrapSelection("redo", null);
}
});
taRegisterTool('bold', {
iconclass: 'fa fa-bold',
action: function(){
return this.$editor().wrapSelection("bold", null);
},
activeState: function(){
return document.queryCommandState('bold');
},
commandKeyCode: 98
});
taRegisterTool('italics', {
iconclass: 'fa fa-italic',
action: function(){
return this.$editor().wrapSelection("italic", null);
},
activeState: function(){
return document.queryCommandState('italic');
},
commandKeyCode: 105
});
taRegisterTool('underline', {
iconclass: 'fa fa-underline',
action: function(){
return this.$editor().wrapSelection("underline", null);
},
activeState: function(){
return document.queryCommandState('underline');
},
commandKeyCode: 117
});
taRegisterTool('strikeThrough', {
iconclass: 'fa fa-strikethrough',
action: function(){
return this.$editor().wrapSelection("strikeThrough", null);
},
activeState: function(){
return document.queryCommandState('strikeThrough');
}
});
taRegisterTool('alignment', {
display: "<span class='bar-btn-dropdown dropdown'>" +
"<button class='btn btn-default dropdown-toggle' type='button' ng-disabled='showHtml()'><span><i class='fa fa-align-left'></i></span></button>" +
"<ul class='dropdown-menu inline-opts'><li ng-repeat='o in options'><button type='button' ng-click='action(o.command)'><i class='fa fa-align-{{o.icon}}'></i></button></li></ul></span>",
action: function(alignment) {
if (alignment !== '') {
return this.$editor().wrapSelection(alignment, null);
}
},
options: [
{icon: 'left', command: 'justifyLeft'},
{icon: 'center', command: 'justifyCenter'},
{icon: 'right', command: 'justifyRight'}
],
active: 'left',
setActive: function(alignment) {
angular.forEach(this.options, function(option) {
if (alignment === option.command) {
this.active = option.icon;
}
});
},
getActive: function() {
if (document.queryCommandValue('justifyLeft') && !document.queryCommandState('justifyRight') && !document.queryCommandState('justifyCenter')) {
return 'justifyLeft';
} else if (document.queryCommandState('justifyRight')) {
return 'justifyRight';
} else if (document.queryCommandState('justifyCenter')) {
return 'justifyCenter';
} else {
return 'justifyLeft';
}
}
});
taRegisterTool('justifyLeft', {
iconclass: 'fa fa-align-left',
action: function(){
return this.$editor().wrapSelection("justifyLeft", null);
},
activeState: function(commonElement){
var result = false;
if(commonElement) result = commonElement.css('text-align') === 'left' || commonElement.attr('align') === 'left' ||
(commonElement.css('text-align') !== 'right' && commonElement.css('text-align') !== 'center' && !document.queryCommandState('justifyRight') && !document.queryCommandState('justifyCenter'));
result = result || document.queryCommandState('justifyLeft');
return result;
}
});
taRegisterTool('justifyRight', {
iconclass: 'fa fa-align-right',
action: function(){
return this.$editor().wrapSelection("justifyRight", null);
},
activeState: function(commonElement){
var result = false;
if(commonElement) result = commonElement.css('text-align') === 'right';
result = result || document.queryCommandState('justifyRight');
return result;
}
});
taRegisterTool('justifyCenter', {
iconclass: 'fa fa-align-center',
action: function(){
return this.$editor().wrapSelection("justifyCenter", null);
},
activeState: function(commonElement){
var result = false;
if(commonElement) result = commonElement.css('text-align') === 'center';
result = result || document.queryCommandState('justifyCenter');
return result;
}
});
taRegisterTool('insertHorizontalRule', {
iconclass: 'fa fa-minus',
action: function(){
return this.$editor().wrapSelection("insertHorizontalRule", null);
}
});
taRegisterTool('fontColor', {
display: "<span class='bar-btn-dropdown'><button type='button' colorpicker colorpicker-text-editor='true' colorpicker-parent='true' class='btn btn-default' ng-disabled='showHtml()'> <i class='fa fa-magic'></i><i class='fa fa-caret-down'></i></button></span>",
action: function(color) {
if (color !== '') {
return this.$editor().wrapSelection('foreColor', color);
}
}
});
taRegisterTool('backgroundColor', {
display: "<span class='bar-btn-dropdown'><button type='button' colorpicker colorpicker-text-editor='true' colorpicker-parent='true' class='btn btn-default' ng-disabled='showHtml()'> <i class='fa fa-magic'></i><i class='fa fa-caret-down'></i></button></span>",
action: function(color) {
if (color !== '') {
return this.$editor().wrapSelection('backColor', color);
}
}
});
taRegisterTool('clear', {
iconclass: 'fa fa-ban',
action: function(deferred, restoreSelection){
this.$editor().wrapSelection("removeFormat", null);
var _ranges = [];
// if rangy, do better removal. Else just change everything to a <p> tag - this don't work so well on lists
if(this.$window.rangy && this.$window.rangy.getSelection &&
(_ranges = this.$window.rangy.getSelection().getAllRanges()).length === 1
){
var possibleNodes = angular.element(_ranges[0].commonAncestorContainer);
// remove lists
var removeListElements = function(list){
list = angular.element(list);
var prevElement = list;
angular.forEach(list.children(), function(liElem){
var newElem = angular.element('<p></p>');
newElem.html(angular.element(liElem).html());
prevElement.after(newElem);
prevElement = newElem;
});
list.remove();
};
angular.forEach(possibleNodes.find("ul"), removeListElements);
angular.forEach(possibleNodes.find("ol"), removeListElements);
// clear out all class attributes. These do not seem to be cleared via removeFormat
var $editor = this.$editor();
var recursiveRemoveClass = function(node){
node = angular.element(node);
if(node[0] !== $editor.displayElements.text[0]) node.removeAttr('class');
angular.forEach(node.children(), recursiveRemoveClass);
};
angular.forEach(possibleNodes, recursiveRemoveClass);
// check if in list. If not in list then use formatBlock option
if(possibleNodes[0].tagName.toLowerCase() !== 'li' &&
possibleNodes[0].tagName.toLowerCase() !== 'ol' &&
possibleNodes[0].tagName.toLowerCase() !== 'ul') this.$editor().wrapSelection("formatBlock", "<p>");
}else this.$editor().wrapSelection("formatBlock", "<p>");
restoreSelection();
}
});
taRegisterTool('insertImage', {
iconclass: 'fa fa-picture-o',
action: function(){
var imageLink;
imageLink = prompt("Please enter an image URL to insert", 'http://');
if(imageLink !== '' && imageLink !== 'http://'){
return this.$editor().wrapSelection('insertImage', imageLink);
}
}
});
taRegisterTool('insertLink', {
iconclass: 'fa fa-link',
action: function(){
var urlLink;
urlLink = prompt("Please enter an URL to insert", 'http://');
if(urlLink !== '' && urlLink !== 'http://'){
return this.$editor().wrapSelection('createLink', urlLink);
}
},
activeState: function(commonElement){
if(commonElement) return commonElement[0].tagName === 'A';
return false;
}
});
taRegisterTool('unlink', {
iconclass: 'fa fa-unlink',
action: function(){
return this.$editor().wrapSelection('unlink', null);
},
activeState: function(commonElement){
if(commonElement) return commonElement[0].tagName === 'A';
return false;
}
});
}]);
textAngular.directive("textAngular", [
'$compile', '$timeout', 'taOptions', 'taSanitize', 'textAngularManager', '$window',
function($compile, $timeout, taOptions, taSanitize, textAngularManager, $window){
return {
require: '?ngModel',
scope: {},
restrict: "EA",
link: function(scope, element, attrs, ngModel){
// all these vars should not be accessable outside this directive
var _keydown, _keyup, _keypress, _mouseup, _focusin, _focusout,
_originalContents, _toolbars,
_serial = Math.floor(Math.random() * 10000000000000000),
_name = (attrs.name) ? attrs.name : 'textAngularEditor' + _serial;
// get the settings from the defaults and add our specific functions that need to be on the scope
angular.extend(scope, angular.copy(taOptions), {
// wraps the selection in the provided tag / execCommand function. Should only be called in WYSIWYG mode.
wrapSelection: function(command, opt){
// catch errors like FF erroring when you try to force an undo with nothing done
try{
document.execCommand(command, false, opt);
}catch(e){}
// refocus on the shown display element, this fixes a display bug when using :focus styles to outline the box.
// You still have focus on the text/html input it just doesn't show up
scope.displayElements.text[0].focus();
},
showHtml: false
});
// setup the options from the optional attributes
if(attrs.taFocussedClass) scope.classes.focussed = attrs.taFocussedClass;
if(attrs.taTextEditorClass) scope.classes.textEditor = attrs.taTextEditorClass;
if(attrs.taHtmlEditorClass) scope.classes.htmlEditor = attrs.taHtmlEditorClass;
// optional setup functions
if(attrs.taTextEditorSetup) scope.setup.textEditorSetup = scope.$parent.$eval(attrs.taTextEditorSetup);
if(attrs.taHtmlEditorSetup) scope.setup.htmlEditorSetup = scope.$parent.$eval(attrs.taHtmlEditorSetup);
_originalContents = element[0].innerHTML;
// clear the original content
element[0].innerHTML = '';
// Setup the HTML elements as variable references for use later
scope.displayElements = {
// we still need the hidden input even with a textarea as the textarea may have invalid/old input in it,
// wheras the input will ALLWAYS have the correct value.
forminput: angular.element("<input type='hidden' tabindex='-1' style='display: none;'>"),
html: angular.element("<textarea></textarea>"),
text: angular.element("<div></div>")
};
// allow for insertion of custom directives on the textarea and div
scope.setup.htmlEditorSetup(scope.displayElements.html);
scope.setup.textEditorSetup(scope.displayElements.text);
scope.displayElements.html.attr({
'id': 'taHtmlElement',
'ng-show': 'showHtml',
'ta-bind': 'ta-bind',
'ng-model': 'html'
});
scope.displayElements.text.attr({
'id': 'taTextElement',
'contentEditable': 'true',
'ng-hide': 'showHtml',
'ta-bind': 'ta-bind',
'ng-model': 'html'
});
// add the main elements to the origional element
element.append(scope.displayElements.text);
element.append(scope.displayElements.html);
scope.displayElements.forminput.attr('name', _name);
element.append(scope.displayElements.forminput);
if(attrs.tabindex){
element.removeAttr('tabindex');
scope.displayElements.text.attr('tabindex', attrs.tabindex);
scope.displayElements.html.attr('tabindex', attrs.tabindex);
}
if (attrs.placeholder) {
scope.displayElements.text.attr('placeholder', attrs.placeholder);
scope.displayElements.html.attr('placeholder', attrs.placeholder);
}
if(attrs.taDisabled){
scope.displayElements.text.attr('ta-readonly', 'disabled');
scope.displayElements.html.attr('ta-readonly', 'disabled');
scope.disabled = scope.$parent.$eval(attrs.taDisabled);
scope.$parent.$watch(attrs.taDisabled, function(newVal){
scope.disabled = newVal;
if(scope.disabled){
element.addClass(scope.classes.disabled);
}else{
element.removeClass(scope.classes.disabled);
}
});
}
// compile the scope with the text and html elements only - if we do this with the main element it causes a compile loop
$compile(scope.displayElements.text)(scope);
$compile(scope.displayElements.html)(scope);
// add the classes manually last
element.addClass("ta-root");
scope.displayElements.text.addClass("ta-text ta-editor " + scope.classes.textEditor);
scope.displayElements.html.addClass("ta-html ta-editor " + scope.classes.textEditor);
// used in the toolbar actions
scope._actionRunning = false;
var _savedSelection = false;
scope.startAction = function(){
scope._actionRunning = true;
// if rangy library is loaded return a function to reload the current selection
if($window.rangy && $window.rangy.saveSelection){
_savedSelection = $window.rangy.saveSelection();
return function(){
if(_savedSelection) $window.rangy.restoreSelection(_savedSelection);
};
}
};
scope.endAction = function(){
scope._actionRunning = false;
if(_savedSelection) $window.rangy.removeMarkers(_savedSelection);
_savedSelection = false;
scope.updateSelectedStyles();
// only update if in text or WYSIWYG mode
if(!scope.showHtml) scope.updateTaBindtaTextElement();
};
// note that focusout > focusin is called everytime we click a button - except bad support: http://www.quirksmode.org/dom/events/blurfocus.html
// cascades to displayElements.text and displayElements.html automatically.
_focusin = function(){
element.addClass(scope.classes.focussed);
_toolbars.focus();
};
scope.displayElements.html.on('focus', _focusin);
scope.displayElements.text.on('focus', _focusin);
_focusout = function(e){
// if we are NOT runnig an action and have NOT focussed again on the text etc then fire the blur events
if(!scope._actionRunning && document.activeElement !== scope.displayElements.html[0] && document.activeElement !== scope.displayElements.text[0]){
element.removeClass(scope.classes.focussed);
_toolbars.unfocus();
// to prevent multiple apply error defer to next seems to work.
$timeout(function(){ element.triggerHandler('blur'); }, 0);
}
e.preventDefault();
return false;
};
scope.displayElements.html.on('blur', _focusout);
scope.displayElements.text.on('blur', _focusout);
// Setup the default toolbar tools, this way allows the user to add new tools like plugins.
// This is on the editor for future proofing if we find a better way to do this.
scope.queryFormatBlockState = function(command){
return command.toLowerCase() === document.queryCommandValue('formatBlock').toLowerCase();
};
scope.switchView = function(){
scope.showHtml = !scope.showHtml;
//Show the HTML view
if(scope.showHtml){
//defer until the element is visible
$timeout(function(){
// [0] dereferences the DOM object from the angular.element
return scope.displayElements.html[0].focus();
}, 100);
}else{
//Show the WYSIWYG view
//defer until the element is visible
$timeout(function(){
// [0] dereferences the DOM object from the angular.element
return scope.displayElements.text[0].focus();
}, 100);
}
};
// changes to the model variable from outside the html/text inputs
// if no ngModel, then the only input is from inside text-angular
if(attrs.ngModel){
var _firstRun = true;
ngModel.$render = function(){
if(_firstRun){
// we need this firstRun to set the originalContents otherwise it gets overrided by the setting of ngModel to undefined from NaN
_firstRun = false;
// if view value is null or undefined initially and there was original content, set to the original content
var _initialValue = scope.$parent.$eval(attrs.ngModel);
if((_initialValue === undefined || _initialValue === null) && (_originalContents && _originalContents !== '')){
// on passing through to taBind it will be sanitised
ngModel.$setViewValue(_originalContents);
}
}
scope.displayElements.forminput.val(ngModel.$viewValue);
// if the editors aren't focused they need to be updated, otherwise they are doing the updating
if(document.activeElement !== scope.displayElements.html[0] && document.activeElement !== scope.displayElements.text[0]){
// catch model being null or undefined
scope.html = ngModel.$viewValue || '';
}
};
}else{
// if no ngModel then update from the contents of the origional html.
scope.displayElements.forminput.val(_originalContents);
scope.html = _originalContents;
}
scope.$watch('html', function(newValue, oldValue){
if(newValue !== oldValue){
if(attrs.ngModel) ngModel.$setViewValue(newValue);
scope.displayElements.forminput.val(newValue);
}
});
if(attrs.taTargetToolbars) _toolbars = textAngularManager.registerEditor(_name, scope, attrs.taTargetToolbars.split(','));
else{
var _toolbar = angular.element('<div text-angular-toolbar name="textAngularToolbar' + _serial + '">');
// passthrough init of toolbar options
if(attrs.taToolbar) _toolbar.attr('ta-toolbar', attrs.taToolbar);
if(attrs.taToolbarClass) _toolbar.attr('ta-toolbar-class', attrs.taToolbarClass);
if(attrs.taToolbarGroupClass) _toolbar.attr('ta-toolbar-group-class', attrs.taToolbarGroupClass);
if(attrs.taToolbarButtonClass) _toolbar.attr('ta-toolbar-button-class', attrs.taToolbarButtonClass);
if(attrs.taToolbarActiveButtonClass) _toolbar.attr('ta-toolbar-active-button-class', attrs.taToolbarActiveButtonClass);
if(attrs.taFocussedClass) _toolbar.attr('ta-focussed-class', attrs.taFocussedClass);
element.prepend(_toolbar);
$compile(_toolbar)(scope.$parent);
_toolbars = textAngularManager.registerEditor(_name, scope, ['textAngularToolbar' + _serial]);
}
scope.$on('$destroy', function(){
textAngularManager.unregisterEditor(_name);
});
// the following is for applying the active states to the tools that support it
scope._bUpdateSelectedStyles = false;
// loop through all the tools polling their activeState function if it exists
scope.updateSelectedStyles = function(){
var _ranges;
// test if rangy exists and if the common element ISN'T the root ta-text node
if($window.rangy && $window.rangy.getSelection &&
(_ranges = $window.rangy.getSelection().getAllRanges()).length === 1 &&
_ranges[0].commonAncestorContainer.parentNode !== scope.displayElements.text[0]
){
_toolbars.updateSelectedStyles(angular.element(_ranges[0].commonAncestorContainer.parentNode));
}else _toolbars.updateSelectedStyles();
// used to update the active state when a key is held down, ie the left arrow
if(scope._bUpdateSelectedStyles) $timeout(scope.updateSelectedStyles, 200);
};
// start updating on keydown
_keydown = function(){
if(!scope._bUpdateSelectedStyles){
scope._bUpdateSelectedStyles = true;
scope.$apply(function(){
scope.updateSelectedStyles();
});
}
};
scope.displayElements.html.on('keydown', _keydown);
scope.displayElements.text.on('keydown', _keydown);
// stop updating on key up and update the display/model
_keyup = function(){
scope._bUpdateSelectedStyles = false;
};
scope.displayElements.html.on('keyup', _keyup);
scope.displayElements.text.on('keyup', _keyup);
// stop updating on key up and update the display/model
_keypress = function(event){
scope.$apply(function(){
if(_toolbars.sendKeyCommand(event)){
if(!scope._bUpdateSelectedStyles){
scope.updateSelectedStyles();
}
event.preventDefault();
return false;
}
});
};
scope.displayElements.html.on('keypress', _keypress);
scope.displayElements.text.on('keypress', _keypress);
// update the toolbar active states when we click somewhere in the text/html boxed
_mouseup = function(){
// ensure only one execution of updateSelectedStyles()
scope._bUpdateSelectedStyles = false;
scope.$apply(function(){
scope.updateSelectedStyles();
});
};
scope.displayElements.html.on('mouseup', _mouseup);
scope.displayElements.text.on('mouseup', _mouseup);
}
};
}
]).directive('taBind', ['taSanitize', '$timeout', 'taFixChrome', function(taSanitize, $timeout, taFixChrome){
// Uses for this are textarea or input with ng-model and ta-bind='text'
// OR any non-form element with contenteditable="contenteditable" ta-bind="html|text" ng-model
return {
require: 'ngModel',
scope: {},
link: function(scope, element, attrs, ngModel){
// the option to use taBind on an input or textarea is required as it will sanitize all input into it correctly.
var _isContentEditable = element.attr('contenteditable') !== undefined && element.attr('contenteditable');
var _isInputFriendly = _isContentEditable || element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input';
var _isReadonly = false;
// in here we are undoing the converts used elsewhere to prevent the < > and & being displayed when they shouldn't in the code.
var _compileHtml = function(){
if(_isContentEditable) return element[0].innerHTML;
if(_isInputFriendly) return element.val();
throw ('textAngular Error: attempting to update non-editable taBind');
};
//used for updating when inserting wrapped elements
scope.$parent['updateTaBind' + (attrs.id || '')] = function(){
if(!_isReadonly) ngModel.$setViewValue(_compileHtml());
};
//this code is used to update the models when data is entered/deleted
if(_isInputFriendly){
element.on('paste cut', function(){
// timeout to next is needed as otherwise the paste/cut event has not finished actually changing the display
if(!_isReadonly) $timeout(function(){
ngModel.$setViewValue(_compileHtml());
}, 0);
});
if(!_isContentEditable){
// if a textarea or input just add in change and blur handlers, everything else is done by angulars input directive
element.on('change blur', function(){
if(!_isReadonly) ngModel.$setViewValue(_compileHtml());
});
}else{
// all the code specific to contenteditable divs
element.on('keyup', function(){
if(!_isReadonly) ngModel.$setViewValue(_compileHtml());
});
element.on('blur', function(){
var val = _compileHtml();
if(val === '' && element.attr("placeholder")) element.addClass('placeholder-text');
if(!_isReadonly) ngModel.$setViewValue(_compileHtml());
ngModel.$render();
});
// if is not a contenteditable the default placeholder logic can work - ie the HTML value itself
if (element.attr("placeholder")) {
// we start off not focussed on this element
element.addClass('placeholder-text');
element.on('focus', function(){
element.removeClass('placeholder-text');
ngModel.$render();
});
}
}
}
// catch DOM XSS via taSanitize
// Sanitizing both ways is identical
var _sanitize = function(unsafe){
return (ngModel.$oldViewValue = taSanitize(taFixChrome(unsafe), ngModel.$oldViewValue));
};
// parsers trigger from the above keyup function or any other time that the viewValue is updated and parses it for storage in the ngModel
ngModel.$parsers.push(_sanitize);
// because textAngular is bi-directional (which is awesome) we need to also sanitize values going in from the server
ngModel.$formatters.push(_sanitize);
// changes to the model variable from outside the html/text inputs
ngModel.$render = function(){
// if the editor isn't focused it needs to be updated, otherwise it's receiving user input
if(document.activeElement !== element[0]){
// catch model being null or undefined
var val = ngModel.$viewValue || '';
if(_isContentEditable){
// WYSIWYG Mode
if (val === '' && element.attr('placeholder') && element.hasClass('placeholder-text'))
element[0].innerHTML = element.attr('placeholder');
else element[0].innerHTML = val;
// if in WYSIWYG and readOnly we kill the use of links by clicking
if(!_isReadonly) element.find('a').on('click', function(e){
e.preventDefault();
return false;
});
}else if(element[0].tagName.toLowerCase() !== 'textarea' && element[0].tagName.toLowerCase() !== 'input'){
// make sure the end user can SEE the html code as a display.
element[0].innerHTML = val;
}else{
// only for input and textarea inputs
element.val(val);
}
}
};
if(attrs.taReadonly){
//set initial value
_isReadonly = scope.$parent.$eval(attrs.taReadonly);
if(_isReadonly){
// we changed to readOnly mode (taReadonly='true')
if(element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input'){
element.attr('disabled', 'disabled');
}
if(element.attr('contenteditable') !== undefined && element.attr('contenteditable')){
element.removeAttr('contenteditable');
}
}else{
// we changed to NOT readOnly mode (taReadonly='false')
if(element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input'){
element.removeAttr('disabled');
}else if(_isContentEditable){
element.attr('contenteditable', 'true');
}
}
// taReadonly only has an effect if the taBind element is an input or textarea or has contenteditable='true' on it.
// Otherwise it is readonly by default
scope.$parent.$watch(attrs.taReadonly, function(newVal, oldVal){
if(oldVal === newVal) return;
if(newVal){
// we changed to readOnly mode (taReadonly='true')
if(element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input'){
element.attr('disabled', 'disabled');
}
if(element.attr('contenteditable') !== undefined && element.attr('contenteditable')){
element.removeAttr('contenteditable');
}
}else{
// we changed to NOT readOnly mode (taReadonly='false')
if(element[0].tagName.toLowerCase() === 'textarea' || element[0].tagName.toLowerCase() === 'input'){
element.removeAttr('disabled');
}else if(_isContentEditable){
element.attr('contenteditable', 'true');
}
}
_isReadonly = newVal;
});
}
}
};
}]).factory('taFixChrome', function(){
// get whaterever rubbish is inserted in chrome
// should be passed an html string, returns an html string
var taFixChrome = function(html){
// default wrapper is a span so find all of them
var $html = angular.element('<div>' + html + '</div>');
var spans = angular.element($html).find('span');
for(var s = 0; s < spans.length; s++){
var span = angular.element(spans[s]);
// chrome specific string that gets inserted into the style attribute, other parts may vary. Second part is specific ONLY to hitting backspace in Headers
if(span.attr('style') && span.attr('style').match(/line-height: 1.428571429;|color: inherit; line-height: 1.1;/i)){
span.attr('style', span.attr('style').replace(/( |)font-family: inherit;|( |)line-height: 1.428571429;|( |)line-height:1.1;|( |)color: inherit;/ig, ''));
if(!span.attr('style') || span.attr('style') === ''){
if(span.next().length > 0 && span.next()[0].tagName === 'BR') span.next().remove();
span.replaceWith(span[0].innerHTML);
}
}
}
// regex to replace ONLY offending styles - these can be inserted into various other tags on delete
var result = $html[0].innerHTML.replace(/style="[^"]*?(line-height: 1.428571429;|color: inherit; line-height: 1.1;)[^"]*"/ig, '');
// only replace when something has changed, else we get focus problems on inserting lists
if(result !== $html[0].innerHTML) $html[0].innerHTML = result;
return $html[0].innerHTML;
};
return taFixChrome;
}).factory('taSanitize', ['$sanitize', function taSanitizeFactory($sanitize){
// recursive function that returns an array of angular.elements that have the passed attribute set on them
function getByAttribute(element, attribute){
var resultingElements = [];
var childNodes = element.children();
if(childNodes.length){
angular.forEach(childNodes, function(child){
resultingElements = resultingElements.concat(getByAttribute(angular.element(child), attribute));
});
}
if(element.attr(attribute)) resultingElements.push(element);
return resultingElements;
}
return function taSanitize(unsafe, oldsafe){
// unsafe and oldsafe should be valid HTML strings
// any exceptions (lets say, color for example) should be made here but with great care
// setup unsafe element for modification
var unsafeElement = angular.element('<div>' + unsafe + '</div>');
// replace all align='...' tags with text-align attributes
angular.forEach(getByAttribute(unsafeElement, 'align'), function(element){
element.css('text-align', element.attr('align'));
element.removeAttr('align');
});
// get the html string back
unsafe = unsafeElement[0].innerHTML;
var safe;
try {
safe = $sanitize(unsafe);
} catch (e){
safe = oldsafe || '';
}
return safe;
};
}]).directive('textAngularToolbar', [
'$compile', 'textAngularManager', 'taOptions', 'taTools', 'taToolExecuteAction', '$window',
function($compile, textAngularManager, taOptions, taTools, taToolExecuteAction, $window){
return {
scope: {
name: '@' // a name IS required
},