forked from nodee-apps/angular-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ne-modules-ui.js
17041 lines (14808 loc) · 617 KB
/
ne-modules-ui.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
/**
* NE CONTENT EDITORS
* ***************************************************************************************************************************
*/
angular.module('neContentEditors',[])
.factory('neMarkdown', ['$document','NeRemarked', 'neMarked', function($document, ReMarked, marked){
var md = {}; // markdown instance
var reMarkedOptions = {
link_list:false, // render links as references, create link list as appendix
h1_setext:false, // underline h1 headers
h2_setext:false, // underline h2 headers
h_atx_suf:false, // header suffixes (###)
gfm_code:false, // gfm code blocks (```)
li_bullet:"*", // list item bullet style
hr_char:"-", // hr style
indnt_str:" ", // indentation string
bold_char:"*", // char used for strong
emph_char:"_", // char used for em
gfm_del:true, // ~~strikeout~~ for <del>strikeout</del>
gfm_tbls:true, // markdown-extra tables
tbl_edges:false, // show side edges on tables
hash_lnks:false, // anchors w/hash hrefs as links
br_only:false // avoid using " " as line break indicator
};
var reMarker = new ReMarked(reMarkedOptions);
md.parseHTML = function(htmlString){
return reMarker.render(htmlString || '');
};
var markedOptions = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false
};
marked.setOptions(markedOptions);
md.renderHTML = function(mdString){
return marked(mdString || '');
};
// editor methods
function isAlreadyWrapped(selection, before, after){
var beforeSel = selection.inputValue.substring(selection.start - before.length, selection.start);
var afterSel = selection.inputValue.substring(selection.end, selection.end + after.length);
return (beforeSel===before && afterSel===after);
}
function wrapText(before, after, defaultValue, mode){
mode = mode || 'toggle'; // 'add', 'remove'
return function(selection){
var value = '';
before = before || '';
after = after || '';
if(selection && (selection.end > selection.start) && mode!=='replace'){
if(mode==='remove' || (mode==='toggle' && isAlreadyWrapped(selection, before, after))){
// remove before & after
value = selection.inputValue.substring(0, selection.start - before.length) + selection.value + selection.inputValue.substring(selection.end + after.length, selection.inputValue.length);
selection.select(selection.start - before.length, selection.end - before.length);
}
else {
// add before & after
value = before + selection.value + after;
value = selection.inputValue.substring(0, selection.start) + value + selection.inputValue.substring(selection.end, selection.inputValue.length);
selection.select(selection.start + before.length, selection.end + before.length);
}
}
else if(selection && (defaultValue || defaultValue==='')) {
value = selection.inputValue.substring(0, selection.start) + before + defaultValue + after + selection.inputValue.substring(selection.end, selection.inputValue.length);
selection.select(selection.start + before.length, selection.start + defaultValue.length + before.length);
}
return value;
};
}
md.editor = {
// TODO: undo, redo
//undo: formatDoc('undo'),
//redo: formatDoc('redo'),
bold: wrapText('**','**','bold text'),
italic: wrapText('*','*','italic text'),
strikethrough: wrapText('~~','~~','strikethrough text'),
h1: wrapText('\n# ','','headline 1'),
h2: wrapText('\n## ','','headline 2'),
h3: wrapText('\n### ','','headline 3'),
h4: wrapText('\n#### ','','headline 4'),
h5: wrapText('\n##### ','','headline 5'),
h6: wrapText('\n###### ','','headline 6'),
ol: wrapText('\n1. ','','numbered list'),
ul: wrapText('\n- ','','bulleted list'),
indent: wrapText(' ','','','replace'),
dedent: wrapText(' ','','','remove'),
blocquote: wrapText('\n> ','','blocquote text'),
hr: wrapText('\n\n-----\n\n','','','replace'),
link: function(selection, url, name){ // selection, [url || usePrompt]
if(!(url || url==='')){
url = prompt('Please enter link url','http://');
}
if(url) return wrapText('', '[ ' +(name || 'link text')+ ' ]( ' +url+ ' )' ,'','replace')(selection);
else return '';
},
image: function(selection, url){ // selection, [url || usePrompt]
if(!(url || url==='')){
url = prompt('Please enter image url','http://');
}
if(url) return wrapText('', '![]( ' +url+ ' "")' ,'','replace')(selection);
else return '';
},
table: function(selection, cols, rows){
cols = parseInt(cols, 10);
rows = parseInt(rows, 10);
if(cols>0 && rows>0) return wrapText('', tableMD(cols, rows),'','add')(selection);
else return selection.inputValue;
}
};
function tableMD(cols, rows){
var mdTable = '\n';
for(var r=1;r<rows+3;r++){
for(var c=1;c<cols+1;c++){
if(c===1) mdTable+='\n';
else mdTable+=' | ';
if(r===1) mdTable+='col '+c;
else if(r===2) mdTable+='-----';
else mdTable+='row '+(r-2);
}
}
//return '\n\ncol 1 | col 2 | col 3' +
//'\n----- | ----- | -----' +
//'\nrow 1 | row 1 | row 1' +
//'\nrow 2 | row 2 | row 2' +
//'\nrow 3 | row 3 | row 3\n';
return mdTable+'\n';
}
return md;
}])
.controller('NeMdCtrl', ['$scope', 'neMarkdown', function($scope, markdown){
$scope.editor = markdown.editor;
}])
.controller('NeWsCtrl', ['$scope', 'neWysiwyg', function($scope, wysiwyg){
$scope.editor = wysiwyg.editor;
}])
.factory('neWysiwyg', ['$document', 'neModals', function($document, modals){
function insertNodeAtSelection(selection, insertNode){
// get current selection
var sel = window.getSelection();
// get the first range of the selection
// (there's almost always only one range)
var range = selection.range;
// deselect everything
sel.removeAllRanges();
// remove content of current selection from document
range.deleteContents();
// get location of current selection
var container = range.startContainer;
var pos = range.startOffset;
// make a new range for the new selection
range=document.createRange();
if (container.nodeType===3 && insertNode.nodeType===3) {
// if we insert text in a textnode, do optimized insertion
container.insertData(pos, insertNode.nodeValue);
// put cursor after inserted text
range.setEnd(container, pos+insertNode.length);
range.setStart(container, pos+insertNode.length);
}
else {
var afterNode;
if (container.nodeType===3) {
// when inserting into a textnode
// we create 2 new textnodes
// and put the insertNode in between
var textNode = container;
container = textNode.parentNode;
var text = textNode.nodeValue;
// text before the split
var textBefore = text.substr(0,pos);
// text after the split
var textAfter = text.substr(pos);
var beforeNode = document.createTextNode(textBefore);
afterNode = document.createTextNode(textAfter);
// insert the 3 new nodes before the old one
container.insertBefore(afterNode, textNode);
container.insertBefore(insertNode, afterNode);
container.insertBefore(beforeNode, insertNode);
// remove the old node
container.removeChild(textNode);
}
else {
// else simply insert the node
afterNode = container.childNodes[pos];
container.insertBefore(insertNode, afterNode);
}
range.setEnd(afterNode, 0);
range.setStart(afterNode, 0);
}
sel.addRange(range);
}
function formatDoc(sCmd, sValue){
return function(selection){
$document[0].execCommand(sCmd, false, sValue);
//selection.select(selection.start, selection.end);
return selection.parent.html();
};
}
var colors = ['#ffffff','#ffccc9','#ffce93','#fffc9e','#ffffc7','#9aff99','#96fffb','#cdffff','#cbcefb','#cfcfcf','#fd6864','#fe996b','#fffe65','#fcff2f','#67fd9a','#38fff8','#68fdff','#9698ed','#c0c0c0','#fe0000','#f8a102','#ffcc67','#f8ff00','#34ff34','#68cbd0','#34cdf9','#6665cd','#9b9b9b','#cb0000','#f56b00','#ffcb2f','#ffc702','#32cb00','#00d2cb','#3166ff','#6434fc','#656565','#9a0000','#ce6301','#cd9934','#999903','#009901','#329a9d','#3531ff','#6200c9','#343434','#680100','#963400','#986536','#646809','#036400','#34696d','#00009b','#303498','#000000','#330001','#643403','#663234','#343300','#013300','#003532','#010066','#340096'];
var fontSizes = [
{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'}
];
var editor = {
undo: formatDoc('undo'),
redo: formatDoc('redo'),
bold: formatDoc('bold'),
italic: formatDoc('italic'),
strikethrough: formatDoc('strikeThrough'),
underline: formatDoc('underline'),
quote: formatDoc('quote'),
h1: formatDoc('formatblock','<h1>'),
h2: formatDoc('formatblock','<h2>'),
h3: formatDoc('formatblock','<h3>'),
h4: formatDoc('formatblock','<h4>'),
h5: formatDoc('formatblock','<h5>'),
h6: formatDoc('formatblock','<h6>'),
fontSizes: fontSizes,
fontSize: function(selection, size){
return formatDoc('fontsize', size)(selection);
},
colors: colors,
color: function(selection, color){
return formatDoc('forecolor', color)(selection);
},
bgColor: function(selection, color){
return formatDoc('hilitecolor', color)(selection);
},
justifyLeft: formatDoc('justifyleft'),
justifyCenter: formatDoc('justifycenter'),
justifyRight: formatDoc('justifyright'),
justifyFull: formatDoc('justifyfull'),
ol: formatDoc('insertorderedlist'),
ul: formatDoc('insertunorderedlist'),
indent: formatDoc('indent'),
outdent: formatDoc('outdent'),
unlink: formatDoc('unlink'),
link: function(selection, url, name){ // selection, [url || usePrompt]
if(!(url || url==='')){
url = prompt('Please enter link url','http://');
}
if(url) {
var link = angular.element('<a href="' +url+ '">' +(name || url)+ '</a>');
insertNodeAtSelection(selection, link[0]);
return selection.parent.html();
}
else return '';
},
image: function(selection, url){ // selection, [url || usePrompt]
if(!(url || url==='')){
url = prompt('Please enter image url','http://');
}
if(url) {
var img = angular.element('<img src="' +url+ '">');
insertNodeAtSelection(selection, img[0]);
return selection.parent.html();
}
else return '';
},
table: function(selection, cols, rows){
rows = parseInt(rows,10);
cols = parseInt(cols,10);
var doc = $document[0];
if ((rows > 0) && (cols > 0)) {
var table = doc.createElement('table');
var thead = doc.createElement('thead');
var tbody = doc.createElement('tbody');
var th,tr,td,br;
tr = doc.createElement('tr');
for (var j=0; j < cols; j++) {
th = doc.createElement('th');
th.innerHTML = 'col '+(j+1);
br = doc.createElement('br');
th.appendChild(br);
tr.appendChild(th);
}
thead.appendChild(tr);
for (var i=0; i < rows; i++) {
tr = doc.createElement('tr');
for (var j=0; j < cols; j++) {
td = doc.createElement('td');
td.innerHTML = 'row '+(i+1);
br = doc.createElement('br');
td.appendChild(br);
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(thead);
table.appendChild(tbody);
insertNodeAtSelection(selection, table);
}
return selection.parent.html();
},
hr: formatDoc('inserthorizontalrule')
// TODO:
// blocquote: wrapText('\n> ','','blocquote text'),
};
this.editor = editor;
return this;
}])
.directive('neContenteditable', ['$sce', function($sce) {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
if(!attrs['contenteditable']) element.attr('contenteditable', 'true');
// Specify how UI should be updated
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$apply(read);
});
read(true); // initialize
// Write data to the model
function read(firstTime) {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if(attrs.stripBr && html === '<br>') {
html = '';
}
// set model value from inner html only if value is not already set
if((firstTime && html) || !firstTime) ngModel.$setViewValue(html);
}
}
};
}])
.directive('neSelectionModel', [function(){
return {
restrict:'A',
require:'^ngModel',
scope:{ neSelectionModel:'=' },
link: function(scope, element, attrs, ctrl){
if(element[0].nodeName !== 'TEXTAREA' && attrs.contenteditable!=='true'){
throw new Error('neSelectionModel directive can be used only on <textarea> or contentEditable="true" element');
}
function TextAreaSelection(){
function setSelection(e, start, end){
e.focus();
if(e.setSelectionRange)
e.setSelectionRange(start, end);
else if(e.createTextRange) {
e = e.createTextRange();
e.collapse(true);
e.moveEnd('character', end);
e.moveStart('character', start);
e.select();
}
}
function getSelection(){
var textarea = this;
var selStart = textarea.selectionStart;
var selEnd = textarea.selectionEnd;
scope.$apply(function(){
scope.neSelectionModel = {
parent: angular.element(textarea),
value: textarea.value.substring(selStart, selEnd),
inputValue: textarea.value,
start: selStart,
end: selEnd,
select: function(start, end){
setTimeout(function(){
setSelection(textarea, start, end);
getSelection.call(textarea);
},0);
}
};
});
}
this.setSelection = setSelection;
this.getSelection = getSelection;
}
function closestElement(el, fn) {
while (el) {
if (fn(el)) return el;
el = el.parentNode;
}
}
function ContentEditSelection(element){
function setSelection(e, start, end){
// TODO: implement restore selection on change
//var range = document.createRange();
//range.setStart(e, start);
//range.setEnd(e, end);
////range.collapse(true);
//var sel = window.getSelection();
//sel.removeAllRanges();
//sel.addRange(range);
//e.focus();
// http://stackoverflow.com/questions/16095155/javascript-contenteditable-set-cursor-caret-to-index
// http://stackoverflow.com/questions/1125292/how-to-move-cursor-to-end-of-contenteditable-entity
// or use rangy
}
function getSelection(){
var elm = this;
var doc = closestElement(angular.element(elm)[0], function(elm){ return elm.tagName === 'HTML'; }).parentNode;
var sel = doc.getSelection();
var selStart = sel.getRangeAt(0).startOffset;
var selEnd = sel.getRangeAt(0).endOffset;
var parent = angular.element(elm);
scope.$apply(function(){
scope.neSelectionModel = {
range: sel.getRangeAt(0),
parent: parent,
value: parent.html().substring(selStart, selEnd),
inputValue: parent.html(),
start: selStart,
startElement: sel.getRangeAt(0).startContainer,
end: selEnd,
endElement: sel.getRangeAt(0).endContainer,
select: function(start, end, startElement, endElement){
var startElm = startElement || this.startElement;
var endElm = endElement || this.endElement;
setTimeout(function(){
setSelection(elm, start, end, startElm, endElm);
//getSelection.call(elm);
},0);
}
}
});
}
this.setSelection = setSelection;
this.getSelection = getSelection;
}
var selModel = element[0].nodeName === 'TEXTAREA' ? new TextAreaSelection() : new ContentEditSelection();
element.on('mouseup keyup', selModel.getSelection);
scope.$on('$destroy', function(){
element.unbind('mouseup keyup', selModel.getSelection);
scope.neSelectionModel = null;
});
}
};
}])
.factory('NeRemarked', [function(){
/**
* Copyright (c) 2013, Leon Sorokin
* All rights reserved. (MIT Licensed)
*
* reMarked.js - DOM > markdown
*/
var ReMarked = function(opts) {
var links = [];
var cfg = {
link_list: false, // render links as references, create link list as appendix
// link_near: // cite links immediately after blocks
h1_setext: true, // underline h1 headers
h2_setext: true, // underline h2 headers
h_atx_suf: false, // header suffix (###)
// h_compact: true, // compact headers (except h1)
gfm_code: false, // render code blocks as via ``` delims
li_bullet: "*-+"[0], // list item bullet style
// list_indnt: // indent top-level lists
hr_char: "-_*"[0], // hr style
indnt_str: [" ","\t"," "][0], // indentation string
bold_char: "*_"[0], // char used for strong
emph_char: "*_"[1], // char used for em
gfm_del: true, // ~~strikeout~~ for <del>strikeout</del>
gfm_tbls: true, // markdown-extra tables
tbl_edges: false, // show side edges on tables
hash_lnks: false, // anchors w/hash hrefs as links
br_only: false, // avoid using " " as line break indicator
col_pre: "col ", // column prefix to use when creating missing headers for tables
// comp_style: false, // use getComputedStyle instead of hardcoded tag list to discern block/inline
unsup_tags: { // handling of unsupported tags, defined in terms of desired output style. if not listed, output = outerHTML
// no output
ignore: "script style noscript",
// eg: "<tag>some content</tag>"
inline: "span sup sub i u b center big",
// eg: "\n<tag>\n\tsome content\n</tag>"
// block1: "",
// eg: "\n\n<tag>\n\tsome content\n</tag>"
block2: "div form fieldset dl header footer address article aside figure hgroup section",
// eg: "\n<tag>some content</tag>"
block1c: "dt dd caption legend figcaption output",
// eg: "\n\n<tag>some content</tag>"
block2c: "canvas audio video iframe",
},
tag_remap: { // remap of variants or deprecated tags to internal classes
"i": "em",
"b": "strong"
}
};
extend(cfg, opts);
function extend(a, b) {
if (!b) return a;
for (var i in a) {
if (typeOf(b[i]) == "Object")
extend(a[i], b[i]);
else if (typeof b[i] !== "undefined")
a[i] = b[i];
}
}
function typeOf(val) {
return Object.prototype.toString.call(val).slice(8,-1);
}
function rep(str, num) {
var s = "";
while (num-- > 0)
s += str;
return s;
}
function trim12(str) {
var str = str.replace(/^\s\s*/, ''),
ws = /\s/,
i = str.length;
while (ws.test(str.charAt(--i)));
return str.slice(0, i + 1);
}
function lpad(targ, padStr, len) {
return rep(padStr, len - targ.length) + targ;
}
function rpad(targ, padStr, len) {
return targ + rep(padStr, len - targ.length);
}
function otag(tag, e) {
if (!tag) return "";
var buf = "<" + tag;
for (var attr, i = 0; i < e.attributes.length; i++) {
attr = e.attributes.item(i);
buf += " " + attr.nodeName + '="' + attr.nodeValue + '"';
}
return buf + ">";
}
function ctag(tag) {
if (!tag) return "";
return "</" + tag + ">";
}
function pfxLines(txt, pfx) {
return txt.replace(/^/gm, pfx);
}
function nodeName(e) {
return (e.nodeName == "#text" ? "txt" : e.nodeName).toLowerCase();
}
function wrap(str, opts) {
var pre, suf;
if (opts instanceof Array) {
pre = opts[0];
suf = opts[1];
}
else
pre = suf = opts;
pre = pre instanceof Function ? pre.call(this, str) : pre;
suf = suf instanceof Function ? suf.call(this, str) : suf;
return pre + str + suf;
}
// http://stackoverflow.com/a/3819589/973988
function outerHTML(node) {
// if IE, Chrome take the internal method otherwise build one
return node.outerHTML || (
function(n){
var div = document.createElement('div'), h;
div.appendChild( n.cloneNode(true) );
h = div.innerHTML;
div = null;
return h;
})(node);
}
this.render = function(ctr) {
links = [];
if (typeof ctr == "string") {
var htmlstr = ctr;
ctr = document.createElement("div");
ctr.innerHTML = htmlstr;
}
var s = new lib.tag(ctr, null, 0);
var re = s.rend().replace(/^[\t ]+\n/gm, "\n");
if (cfg.link_list && links.length > 0) {
// hack
re += "\n\n";
var maxlen = 0;
// get longest link href with title, TODO: use getAttribute?
for (var y = 0; y < links.length; y++) {
if (!links[y].e.title) continue;
var len = links[y].e.href.length;
if (len && len > maxlen)
maxlen = len;
}
for (var k = 0; k < links.length; k++) {
var title = links[k].e.title ? rep(" ", (maxlen + 2) - links[k].e.href.length) + '"' + links[k].e.title + '"' : "";
re += " [" + (+k+1) + "]: " + (nodeName(links[k].e) == "a" ? links[k].e.href : links[k].e.src) + title + "\n";
}
}
return re.replace(/^[\t ]+\n/gm, "\n");
};
var lib = {};
lib.tag = klass({
wrap: "",
lnPfx: "", // only block
lnInd: 0, // only block
init: function(e, p, i)
{
this.e = e;
this.p = p;
this.i = i;
this.c = [];
this.tag = nodeName(e);
this.initK();
},
initK: function()
{
var i;
if (this.e.hasChildNodes()) {
// inline elems allowing adjacent whitespace text nodes to be rendered
var inlRe = cfg.unsup_tags.inline, n, name;
// if no thead exists, detect header rows or make fake cols
if (nodeName(this.e) == "table") {
if (this.e.hasChildNodes() && !this.e.tHead) {
var thead = document.createElement("thead");
var tbody0 = this.e.tBodies[0],
row0 = tbody0.rows[0],
cell0 = row0.cells[0];
if (nodeName(cell0) == "th")
thead.appendChild(row0);
else {
var hcell,
i = 0,
len = row0.cells.length,
hrow = thead.insertRow();
while (i++ < len) {
hcell = document.createElement("th");
hcell.textContent = cfg.col_pre + i;
hrow.appendChild(hcell);
}
}
this.e.insertBefore(thead, tbody0);
}
}
for (i in this.e.childNodes) {
if (!/\d+/.test(i)) continue;
n = this.e.childNodes[i];
name = nodeName(n);
// remap of variants
if (name in cfg.tag_remap)
name = cfg.tag_remap[name];
// ignored tags
if (cfg.unsup_tags.ignore.test(name))
continue;
// empty whitespace handling
if (name == "txt" && /^\s+$/.test(n.textContent)) {
// ignore if first or last child (trim)
if (i == 0 || i == this.e.childNodes.length - 1)
continue;
// only ouput when has an adjacent inline elem
var prev = this.e.childNodes[i-1],
next = this.e.childNodes[i+1];
if (prev && !nodeName(prev).match(inlRe) || next && !nodeName(next).match(inlRe))
continue;
}
var wrap = null;
if (!lib[name]) {
var unsup = cfg.unsup_tags;
if (unsup.inline.test(name))
name = "tinl";
else if (unsup.block2.test(name))
name = "tblk";
else if (unsup.block1c.test(name))
name = "ctblk";
else if (unsup.block2c.test(name)) {
name = "ctblk";
wrap = ["\n\n", ""];
}
else
name = "rawhtml";
}
var node = new lib[name](n, this, this.c.length);
if (wrap)
node.wrap = wrap;
if (node instanceof lib.a && n.href || node instanceof lib.img) {
node.lnkid = links.length;
links.push(node);
}
this.c.push(node);
}
}
},
rend: function()
{
return this.rendK().replace(/\n{3,}/gm, "\n\n"); // can screw up pre and code :(
},
rendK: function()
{
var n, buf = "";
for (var i = 0; i < this.c.length; i++) {
n = this.c[i];
buf += (n.bef || "") + n.rend() + (n.aft || "");
}
return buf.replace(/^\n+|\n+$/, "");
}
});
lib.blk = lib.tag.extend({
wrap: ["\n\n", ""],
wrapK: null,
tagr: false,
lnInd: null,
init: function(e, p ,i) {
this.supr(e,p,i);
// kids indented
if (this.lnInd === null) {
if (this.p && this.tagr && this.c[0] instanceof lib.blk)
this.lnInd = 4;
else
this.lnInd = 0;
}
// kids wrapped?
if (this.wrapK === null) {
if (this.tagr && this.c[0] instanceof lib.blk)
this.wrapK = "\n";
else
this.wrapK = "";
}
},
rend: function()
{
return wrap.call(this, (this.tagr ? otag(this.tag, this.e) : "") + wrap.call(this, pfxLines(pfxLines(this.rendK(), this.lnPfx), rep(" ", this.lnInd)), this.wrapK) + (this.tagr ? ctag(this.tag) : ""), this.wrap);
},
rendK: function()
{
var kids = this.supr();
// remove min uniform leading spaces from block children. marked.js's list outdent algo sometimes leaves these
if (this.p instanceof lib.li) {
var repl = null, spcs = kids.match(/^[\t ]+/gm);
if (!spcs) return kids;
for (var i = 0; i < spcs.length; i++) {
if (repl === null || spcs[i][0].length < repl.length)
repl = spcs[i][0];
}
return kids.replace(new RegExp("^" + repl), "");
}
return kids;
}
});
lib.tblk = lib.blk.extend({tagr: true});
lib.cblk = lib.blk.extend({wrap: ["\n", ""]});
lib.ctblk = lib.cblk.extend({tagr: true});
lib.inl = lib.tag.extend({
rend: function()
{
return wrap.call(this, this.rendK(), this.wrap);
}
});
lib.tinl = lib.inl.extend({
tagr: true,
rend: function()
{
return otag(this.tag, this.e) + wrap.call(this, this.rendK(), this.wrap) + ctag(this.tag);
}
});
lib.p = lib.blk.extend({
rendK: function() {
return this.supr().replace(/^\s+/gm, "");
}
});
lib.list = lib.blk.extend({
expn: false,
wrap: [function(){return this.p instanceof lib.li ? "\n" : "\n\n";}, ""]
});
lib.ul = lib.list.extend({});
lib.ol = lib.list.extend({});
lib.li = lib.cblk.extend({
wrap: ["\n", function(kids) {
return this.p.expn || kids.match(/\n{2}/gm) ? "\n" : ""; // || this.kids.match(\n)
}],
wrapK: [function() {
return this.p.tag == "ul" ? cfg.li_bullet + " " : (this.i + 1) + ". ";
}, ""],
rendK: function() {
return this.supr().replace(/\n([^\n])/gm, "\n" + cfg.indnt_str + "$1");
}
});
lib.hr = lib.blk.extend({
wrap: ["\n\n", rep(cfg.hr_char, 3)]
});
lib.h = lib.blk.extend({});
lib.h_setext = lib.h.extend({});
cfg.h1_setext && (lib.h1 = lib.h_setext.extend({
wrapK: ["", function(kids) {
return "\n" + rep("=", kids.length);
}]
}));
cfg.h2_setext && (lib.h2 = lib.h_setext.extend({
wrapK: ["", function(kids) {
return "\n" + rep("-", kids.length);
}]
}));
lib.h_atx = lib.h.extend({
wrapK: [
function(kids) {
return rep("#", this.tag[1]) + " ";
},
function(kids) {
return cfg.h_atx_suf ? " " + rep("#", this.tag[1]) : "";
}
]
});
!cfg.h1_setext && (lib.h1 = lib.h_atx.extend({}));
!cfg.h2_setext && (lib.h2 = lib.h_atx.extend({}));
lib.h3 = lib.h_atx.extend({});
lib.h4 = lib.h_atx.extend({});
lib.h5 = lib.h_atx.extend({});
lib.h6 = lib.h_atx.extend({});
lib.a = lib.inl.extend({
lnkid: null,
rend: function() {
var kids = this.rendK(),
href = this.e.getAttribute("href"),
title = this.e.title ? ' "' + this.e.title + '"' : "";
if (!href || href == kids || href[0] == "#" && !cfg.hash_lnks)
return kids;
if (cfg.link_list)
return "[" + kids + "] [" + (this.lnkid + 1) + "]";
return "[" + kids + "](" + href + title + ")";
}
});
// almost identical to links, maybe merge
lib.img = lib.inl.extend({
lnkid: null,
rend: function() {
var kids = this.e.alt,
src = this.e.getAttribute("src");
if (cfg.link_list)
return "![" + kids + "] [" + (this.lnkid + 1) + "]";
var title = this.e.title ? ' "'+ this.e.title + '"' : "";
return "![" + kids + "](" + src + title + ")";