summaryrefslogtreecommitdiff
path: root/src/html2bbcode.js
blob: 7399d71c5cf69684af3ae53ac376238204e0408e (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214

(function (name, definition) {
    if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
      module.exports = definition();
    } else if (typeof define === 'function' && typeof define.amd === 'object') {
      define(definition);
    } else {
      this[name] = definition();
    }
  })('html2bbcode', function (html2bbcode) {
  
    'use strict';
  
    html2bbcode = { version: '1.2.3' };
  
    //function HTMLAttribute()
  
    function HTMLTag() {
      this.name = '';
      this.length = 0;
      //this.attr = null;
      //this.content = null;
    }
  
    HTMLTag.duptags = ['div', 'span'];
    HTMLTag.headingtags = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
    HTMLTag.selfendtags = ['!doctype', 'meta', 'link','img', 'br'];
    HTMLTag.newlinetags = ['div', 'p', 'br', 'li', 'tr'].concat(HTMLTag.headingtags);
    HTMLTag.noemptytags = ['head', 'style', 'script',
      'span', 'a', 'font', 'color', 'size', 'face',
      'strong', 'b', 'em', 'i', 'del', 's', 'ins', 'u'];
    HTMLTag.noemptyattrtags = ['img'];
  
    HTMLTag.prototype.findquoteend = function (script, start, multiline) {
      var end = -1;
      var i = start ? start : 0;
      var len = script.length;
      var d = script[i] === '\"';
  
      i++;
      while (i < len) {
        if (script[i] === '\\') {
          i++;
          switch (script[i]) {
            case 'u':
              // \uXXXX
              i += 5;
              break;
            case 'x':
              // \xXX
              i += 3;
              break;
            default:
              // \n ...
              i++;
              break;
          }
        } else if ((d && script[i] === '\"') || (!d && script[i] === '\'')) {
          end = i;
          break;
        } else if (script[i] === '\n' && !multiline) {
          // not allow change line
          break;
        } else {
          i++;
        }
      }
  
      return end;
    };
  
    HTMLTag.prototype.findscriptend = function (script, start) {
      var end = -1;
      var i = start ? start : 0;
      var len = script.length;
      var freg = /(['"]|<\s*?\/\s*?script\s*?>)/ig;
  
      while (i < len) {
        if (script[i] === '\"' || script[i] === '\'') {
          var qi = this.findquoteend(script, i, true);
          if (qi === -1) {
            break;
          }
          i = qi + 1;
        } else {
          freg.lastIndex = i;
          var m = freg.exec(script);
          if (!m || m.length <= 0) {
            break;
          } else if (m[0][0] === '<') {
            //script here
            end = freg.lastIndex - m[0].length;
            break;
          }
          // quote
          i = freg.lastIndex - 1;
          //console.log(i, script.substr(i, 5));
          continue;
        }
      }
      return end;
    };
  
    HTMLTag.prototype.quote = function (quotation) {
      // convert string type
      if (quotation[0] === '\'') {
        var s = '"';
        var i = 1;
        var len = quotation.length - 1; // last is \'
        var start = i;
        while (i < len) {
          if (quotation[i] === '\\') {
            i++;
            switch (quotation[i]) {
              case 'u':
                // \uXXXX
                i += 5;
                break;
              case 'x':
                // \xXX
                i += 3;
                break;
              default:
                // \n ...
                i++;
                break;
            }
          } else if (quotation[i] === '\"') {
            s += quotation.substr(start, i - start);
            s += '\\"';
            i++;
            start = i;
            break;
          } else {
            i++;
          }
        }
        if (start < len) {
          s += quotation.substr(start, len - start);
        }
        s += '"';
        return s;
      } else {
        return quotation;
      }
    };
  
    HTMLTag.prototype.parseStyle = function (style) {
      var ss = style.split(';');
      var r_style = {};
      var count = 0;
      for (var i = 0; i < ss.length; i++) {
        var s = ss[i].split(':');
        if (s.length >= 2) {
          count++;
          var val;
          if (s.length > 2) {
            // eg. url(http://example.com)
            val = s.slice(1).join(':').trim();
          } else {
            val = s[1].trim();
          }
          if (val[0] === '\'' && val[val.length - 1] === '\'') {
            try {
              val = JSON.parse(this.quote(val));
            } catch (err) {
            }
          }
          r_style[s[0].trim().toLowerCase()] = val;
        }
      }
      if (count > 0) {
        return r_style;
      } else {
        return undefined;
      }
    };
  
    HTMLTag.prototype.parseAttributes = function (attr) {
      attr = attr.trim();
      var blank = /\s/;
      var i = 0;
      var len = attr.length;
      var start = i;
      var lastkey = null;
      var invalue = false;
      var r_attr = {};
      var add_attr = function (k, v) {
        if (typeof v === 'undefined') {
          v = null;
        }
        k = k.trim().toLowerCase();
        r_attr[k] = v;
      };
      while (i < len) {
        if (attr[i] === '=') {
          // TODO: check lastkey, currently drop previous lastkey
          lastkey = attr.substr(start, i - start);
          invalue = false;
        } else if (blank.test(attr[i])) {
          if (lastkey && invalue) {
            add_attr(lastkey, attr.substr(start, i - start));
            invalue = false;
            lastkey = null;
          } else if (i - start > 0) {
            lastkey = attr.substr(start, i - start);
            add_attr(lastkey);
            lastkey = null;
          }
          start = i + 1;
        } else if (lastkey && !invalue) {
          start = i;
          if (attr[i] === '"' || attr[i] === '\'') {
            var b = attr[i] === '\'';
            i = this.findquoteend(attr, i);
            if (i === -1) {
              break;
            }
            var v = attr.substr(start, i + 1 - start);
            if (b) {
              v = this.quote(v);
            }
            try {
              v = JSON.parse(v);
            } catch (e) {
            }
            add_attr(lastkey, v);
            lastkey = null;
            start = i + 1;
          } else {
            invalue = true;
          }
        }
        i++;
      }
      if (start < len) {
        var d = attr.substr(start);
        if (lastkey) {
          add_attr(lastkey, d);
        } else {
          add_attr(d);
        }
        lastkey = null;
      }
      var count = 0;
      for (var k in r_attr) {
        count++;
      }
      if (count > 0) {
        if (r_attr.style) {
          r_attr.style = this.parseStyle(r_attr.style);
        }
        this.attr = r_attr;
      }
    };
  
    HTMLTag.prototype.parse = function (html) {
      var i = 0;
      if (html[i] !== '<') {
        throw new Error('not a tag');
      }
      var len = html.length;
      var blank = /\s/;
      //var htmltagq = /[<>]/;
      // strip tagname head blank
      while (i < len) {
        if (html[i] === '<') {
          i++;
        } else if (html[i] === '>') {
          // drop this empty tag
          this.length = i + 1;
          return this;
        } else if (blank.test(html[i])) {
          i++;
        } else {
          break;
        }
      }
      if (i >= len) {
        // drop this
        this.length = len;
        return this;
      }
  
      // name
      var start = i;
      var tagheadend = false;
      while (i < len && !blank.test(html[i])) {
        if (html[i] === '>') {
          tagheadend = true;
          break;
        } else if (html[i] === '/') {
          break;
        }
        i++;
      }
      if (i >= len) {
        // drop this
        this.length = i;
        return this;
      }
      this.name = html.substr(start, i - start).trim().toLowerCase();
      if (this.name.length > 0 && this.name[0] === '/') {
        this.length = i;
        this.name = this.name.substr(1);
        this.selfend = true;
        return this;
      }
      if (HTMLTag.selfendtags.indexOf(this.name) >= 0) {
        this.selfend = true;
      }
  
      // attr
      if (!tagheadend) {
        start = i;
        while (i < len && html[i] !== '>') {
          i++;
        }
        if (i >= len) {
          // drop this
          this.length = i;
          return this;
        } else if (i - start > 0) {
          var sattr = html.substr(start, i - start).trim();
          var attrlen = sattr.length;
          if (attrlen > 0 && sattr[attrlen - 1] === '/') {
            this.selfend = true;
            sattr = sattr.substr(0, attrlen - 1);
          }
          this.parseAttributes(sattr);
        }
      }
      i++; // skip '>'
  
      if (this.selfend) {
        this.length = i;
        return this;
      }
  
      // content
      var that = this;
      var add_content = function (html) {
        var hstack = new HTMLStack().parse(html);
        if (that.content) {
          that.content.append(hstack);
        } else {
          that.content = hstack;
        }
        return hstack.length;
      };
  
      if (this.name === 'script') {
        var script_len = this.findscriptend(html.substr(i));
        if (script_len < 0) {
          this.length = len;
          return this;
        }
  
        this.content = new HTMLStack();
        var script = html.substr(i, script_len);
        this.content.length = script_len;
        this.content.stack = [ script ];
  
        i += script_len;
        // script tag end
        start = html.indexOf('>', i);
        if (start < 0) {
          // no possible
          this.length = len;
          return this;
        }
  
        this.length = start + 1;
        return this;
      }
  
      var j = 0;
      while (i < len) {
        // loop to tag end
        j++;
        start = i;
  
        while (i < len && blank.test(html[i])) {
          i++;
        }
  
        while (i < len && html[i] !== '<') {
          i++;
        }
  
        var i_tagend = i;
        i++;
        while (i < len && blank.test(html[i])) {
          i++;
        }
  
        if (i >= len) {
          // drop this
          this.content = new HTMLStack().parse(html.substr(start));
          this.length = len;
          return this;
        } else {
          if (i < len && html[i] === '/') {
            i++;
            while (i < len && blank.test(html[i])) {
              i++;
            }
            if (i >= len) {
              // drop this
              i += add_content(html.substr(start));
              this.length = len;
              return this;
            } else {
              var t_start = i;
              var t_tagheadend = false;
              while (i < len && !blank.test(html[i])) {
                if (html[i] === '>') {
                  t_tagheadend = true;
                  break;
                }
                i++;
              }
              if (i > t_start) {
                if (!t_tagheadend) {
                  while (i < len && html[i] !== '>') {
                    i++;
                  }
                }
                var ename = html.substr(t_start, i - t_start).trim().toLowerCase();
                i++; //skip '>'
                // force stop current tag
                /*if (ename === this.name)*/ {
                  // end of tag
                  this.length = i;
                  if (i_tagend > start) {
                    // add content
                    add_content(html.substr(start, i_tagend - start));
                  }
                  return this;
                }
              }
            }
          }
        }
  
        i = start + add_content(html.substr(start));
      }
  
      this.length = i;
      return this;
    };
  
    function HTMLStack() {
      this.stack = [];
      this.length = 0;
    }
  
    HTMLStack.prototype.parse = function (html) {
      // check first...
      if (!html) {
        return this;
      }
  
      var i = 0;
      var len = html.length;
      var lasttagend = 0;
      var blank = /\s/;
      var that = this;
      var push_plaintext = function (start, end) {
        if (start < end) {
          that.push(html.substr(start, end - start));
        }
      };
      while (i < len) {
        switch (html[i]) {
          case '<':
            push_plaintext(lasttagend, i);
  
            // check end & drop
            var t_i = i + 1;
            while (t_i < len && blank.test(html[t_i])) {
              t_i++;
            }
            if (t_i < len && html[t_i] === '/') {
              return this;
            }
  
            var tag = new HTMLTag().parse(html.substr(i));
            this.push(tag);
            i += tag.length;
            lasttagend = i;
            break;
          case '>':
            // TODO: drop the >
            i++;
            break;
          default:
            i++;
            break;
        }
      }
      push_plaintext(lasttagend, len);
      return this;
    };
  
    HTMLStack.prototype.push = function (data) {
      this.length += data.length;
      this.stack.push(data);
    };
  
    HTMLStack.prototype.pop = function () {
      return this.stack.pop();
    };
  
    HTMLStack.prototype.append = function (hstack) {
      this.stack = this.stack.concat(hstack.stack);
      this.length += hstack.length;
    };
  
    (function () {
      var dupRegex = new RegExp(
        '<\\s*?(' + HTMLTag.duptags.join('|') + ')\\s*?>\\s*?'
        + '<\\s*?\\1\\s*?>'
        + '(((?!<\\s*?\\1\\s*?>)[\\S\\s])*?)'
        + '<\\s*?/\\s*?\\1\\s*?>\\s*?'
        + '<\\s*?/\\s*?\\1\\s*?>', 'ig');
      var nlsRegex = new RegExp(
        '(<\\s*?(' + HTMLTag.newlinetags.join('|') + ')(\\s[^>]*?)?>)\\s+', 'ig');
      var nleRegex = new RegExp(
        '\\s+(<\\s*?/\\s*?(' + HTMLTag.newlinetags.join('|') + ')\\s*?>)', 'ig');
      var empRegex = new RegExp(
        '<\\s*?(' + HTMLTag.noemptytags.join('|') + ')(\\s[^>]*?)?>'
        + '<\\s*?/\\s*?\\1\\s*?>', 'ig');
      HTMLStack.minify = function (html) {
        var preRegex = /<pre(\s.*?)?>/ig;
        var endPreRegex = /<\/pre>/ig;
        var emptyRegex = /\s{2,}/g;
        var m, newHtml = '', preMarkIndex = -1;
        html = html.replace(empRegex, '');
        html = html.replace(nlsRegex, '$1');
        html = html.replace(nleRegex, '$1');
        while (m = preRegex.exec(html)) {
          if (preMarkIndex < 0) {
            preMarkIndex = 0;
          }
          newHtml += html.substr(preMarkIndex, preRegex.lastIndex - preMarkIndex).replace(emptyRegex, ' ');
          preMarkIndex = preRegex.lastIndex;
          endPreRegex.lastIndex = preRegex.lastIndex;
          if (m = endPreRegex.exec(html)) {
            preRegex.lastIndex = endPreRegex.lastIndex;
            // no replace for pre content
            newHtml += html.substr(preMarkIndex, m.index - preMarkIndex);
            preMarkIndex = m.index;
          }
        }
        if (preMarkIndex >= 0) {
          html = newHtml + html.substr(preMarkIndex).replace(emptyRegex, ' ');
        } else {
          html = html.replace(emptyRegex, ' ');
        }
        while (dupRegex.test(html)) {
          html = html.replace(dupRegex, '<$1>$2</$1>');
        }
        return html;
      };
    })();
  
    var escapeMap = {
      '&': 'amp',
      '<': 'lt',
      '>': 'gt',
      '"': 'quot',
      "'": '#x27',
      '`': '#x60'
    };
    var unescapeMap = {
      'nbsp': ' ',
      'amp': '&',
      'lt': '<',
      'gt': '>',
      'quot': '"'
    };
  
    HTMLStack.unescape = function (str, nonbsp) {
      var src = '&([a-zA-Z]+?|#[xX][\\da-fA-F]+?|#\\d+?);';
      var testRegexp = new RegExp(src);
      var escaper = function (match, m1) {
        m1 = m1.toLowerCase();
        if (nonbsp && m1 === 'nbsp') {
          return '&nbsp;';
        }
        var m = unescapeMap[m1];
        if (m) {
          return m;
        } else if (m1[0] === '#') {
          var code = 0;
          if (m1[1] == 'x') {
            code = parseInt(m1.substr(2), 16);
          } else {
            code = parseInt(m1.substr(1));
          }
          if (code) {
            return String.fromCharCode(code);
          }
        }
        return '';
      };
      if (testRegexp.test(str)) {
        var replaceRegexp = new RegExp(src, 'g');
        str = str.replace(replaceRegexp, escaper);
      }
      return str;
    };
  
    HTMLStack.prototype.decode = function (nonbsp) {
      for (var i = 0; i < this.stack.length; i++) {
        var s = this.stack[i];
        if (typeof s === 'string') {
          this.stack[i] = HTMLStack.unescape(s, nonbsp);
        } else if (s instanceof HTMLTag && s.content) {
          s.content.decode(nonbsp);
        }
      }
      return this;
    };
  
    HTMLStack.prototype.dedup = function () {
      for (var i = 0; i < this.stack.length; i++) {
        var s = this.stack[i];
        if (s instanceof HTMLTag && s.content) {
          if (HTMLTag.duptags.indexOf(s.name) >= 0 && !s.attr && s.content.stack.length === 1) {
            var ts = s.content.stack[0];
            if (ts.name === s.name) {
              this.stack[i] = ts;
              i--;
              continue;
            }
          }
          s.content.dedup();
        }
      }
      return this;
    };
  
    HTMLStack.prototype.strip = function (parent, afternewline) {
  
      if (!afternewline) {
        afternewline = (parent && !afternewline) ? (HTMLTag.newlinetags.indexOf(parent.name) >= 0) : true;
      }
  
      var blanks = /^\s*$/;
      var k = 0;
      var stag = true;
      // first recursive
      for (var i = 0; i < this.stack.length; i++) {
        var s = this.stack[i];
        if (s instanceof HTMLTag) {
          stag = true;
          if (s.content) {
            //check if is after newline
            var anl;
            if (k <= 0) {
              anl = afternewline;
            } else {
              anl = false;
              // fine previous one
              for (var j = i - 1; j >= 0; j--) {
                var ts = this.stack[j];
                if (ts instanceof HTMLTag) {
                  anl = (HTMLTag.newlinetags.indexOf(ts.name) >= 0);
                  //anl = true;
                  break;
                } else if (typeof ts === 'string' && blanks.test(ts)) {
                  //continue;
                } else {
                  break;
                }
              }
            }
            s.content.strip(s, anl);
          }
        } else if (typeof s === 'string' && blanks.test(s)) {
          if (stag) {
            continue;
          }
        }
        k++;
      }
  
      stag = true;
      var new_stack = [];
      var new_len = 0;
      for (var i = 0; i < this.stack.length; i++) {
        var s = this.stack[i];
        if (typeof s === 'string' && blanks.test(s) && afternewline) {
          if (stag) {
            continue;
          }
          afternewline = false;
        } else if (s instanceof HTMLTag) {
          stag = true;
          if (HTMLTag.noemptyattrtags.indexOf(s.name) >= 0) {
            // strip like <img src="" />
            if (!s.attr) {
              continue;
            }
            var exists = false;
            for (var k1 in s.attr) {
              if (s.attr[k1]) {
                exists = true;
                break;
              }
            }
            if (!exists) {
              continue;
            }
          }
          if (HTMLTag.noemptytags.indexOf(s.name) >= 0 && !s.content) {
            // null span
            continue;
          } else if (HTMLTag.newlinetags.indexOf(s.name) >= 0) {
            afternewline = true;
          /*} else if (s.name === 'span' && afternewline) {*/
            // keep newline flag
          } else {
            afternewline = false;
          }
        } else {
          // not full empty string
          if (afternewline) {
            // removehead space after newline
            s = s.replace(/^\s+/g, '');
            if (!s) {
              // empty string
              continue;
            }
          }
          s = s.replace(/\s+/g, ' ');
          stag = false;
          afternewline = false;
        }
        new_len++;
        new_stack.push(s);
      }
  
      // check last one is empty string
      var s = new_stack[new_len - 1];
      if (typeof s === 'string') {
        if (new_len >= 2 && blanks.test(s)) {
          // remove last empty string
          new_stack.splice(new_len - 1, 1);
          new_len--;
        } else if (/\S\s+$/.test(s)) {
          // space follow with a non-space string
          new_stack[new_len - 1] = s.replace(/\s+$/, '');
        }
      }
  
      if (new_len <= 0 && parent) {
        delete parent.content;
        return;
      }
  
      this.stack = new_stack;
      return this;
    };
  
    HTMLStack.prototype.showtree = function (tab, depth) {
      if (!tab) tab = '';
      if (!depth) depth = 0;
  
      for (var i = 0; i < this.stack.length; i++) {
        var d = this.stack[i];
        if (d instanceof HTMLTag) {
          console.log(tab, d.name, d.attr ? JSON.stringify(d.attr) : '');
          if (d.content) {
            d.content.showtree(tab + '--', depth + 1);
          }
        } else if (typeof d === 'string') {
          console.log(tab, JSON.stringify(d));
        }
      }
    };
  
    function BBCode() {
      this.s = '';
      this.weaknewline = true;
      this.stack = [];
    }
  
    BBCode.maps = {
      'a': { section: 'url', attr: 'href' },
      'img': { section: 'img', data: 'src', empty: true },
      'em': { section: 'i' },
      'i': { section: 'i' },
      'strong': { section: 'b' },
      'b': { section: 'b' },
      'del': { section: 's' },
      's': { section: 's' },
      'ins': { section: 'u' },
      'u': { section: 'u' },
      'center': { section: 'center' },
      'ul': { section: 'ul' },  // may need to treat as 'list'
      'ol': { section: 'ol' },  // may need to treat as 'list'
      'li': { section: 'li', newline: 1 },
      'blockquote': { section: 'quote' },
      'code': { section: 'b' },
      'font': { extend: ['color', 'face', 'size'] },
      'span': { extend: ['color', 'face', 'size'] },
      'color': { section: 'color', attr: 'color' },
      'size': { section: 'size', attr: 'size' },
      'face': { section: 'font', attr: 'face' },
      // new line tags
      'h1': { section: 'h1', newline: 1 },
      'h2': { section: 'h2', newline: 1 },
      'h3': { section: 'h3', newline: 1 },
      'h4': { section: 'h4', newline: 1 },
      'h5': { section: 'h5', newline: 1 },
      'h6': { section: 'h6', newline: 1 },
      'p': { newline: 1 },
      'br': { newline: 2, empty: true },
      'table': { section: 'table', newline: 1 },
      'tr': { section: 'tr', newline: 1 },
      'th': { section: 'td', newline: 1 },
      'td': { section: 'td', newline: 1 },
      'pre': { section: 'code', newline: 1 },
      'div': { newline: 0 },
      // ignore tags
      '!doctype': { ignore: true },
      'head': { ignore: true },
      'style': { ignore: true },
      'script': { ignore: true },
      'meta': { ignore: true },
      'link': { ignore: true },
    };
  
    BBCode.prototype.open = function (section, attr, data) {
      if (!section) {
        return;
      }
      if (section instanceof Array) {
        this.stack = this.stack.concat(section);
      } else {
        this.stack.push({
          section: section,
          attr: attr,
          data: data
        });
      }
    };
  
    BBCode.prototype.append = function (str) {
      this.solidify();
      this._append(str);
    };
  
    BBCode.prototype._append = function (str) {
      if (str) {
        this.s += str;
        this.weaknewline = false;
      }
    };
  
    BBCode.prototype.solidify = function () {
      // write back stack
      var i;
      for (i = 0; i < this.stack.length; i++) {
        var st = this.stack[i];
        var section = st.section;
        var attr = st.attr;
        var data = st.data;
  
        var s = '[' + section;
        if (typeof attr === 'string') {
          s += '=' + attr;
        } else {
          for (var k in attr) {
            s += ' ' + k + '=' + attr[k];
          }
        }
        s += ']';
        if (data) {
          s += data;
        }
  
        this._append(s);
      }
      if (i > 0) {
        this.stack = [];
      }
    };
  
    BBCode.prototype.close = function (section) {
      if (!section) {
        return;
      }
      this.solidify();
      this._append('[/' + section + ']');
    };
  
    BBCode.prototype.rollback = function () {
      this.stack = [];
    };
  
    BBCode.prototype.newline = function (n) {
      if (n === 2) {
        // br
        this.append('\n');
        this.weaknewline = true;
      } else if (n === 1) {
        // div, p
        if (!this.weaknewline) {
          this.append('\n');
          this.weaknewline = true;
        }
      } else if (!this.weaknewline) {
        this.append('\n');
        this.weaknewline = true;
      }
    };
  
    BBCode.prototype.toString = function () {
      return this.s;
    };
  
    // opts: transsize, imagescale
    function HTML2BBCode(opts) {
      this.opts = opts ? opts : {};
    }
  
    HTML2BBCode.prototype.color = function (c) {
      if (!c) return;
      var c1Regex = /rgba?\s*?\(\s*?(\d{1,3})\s*?,\s*?(\d{1,3})\s*?,\s*?(\d{1,3})\s*?.*?\)/i;
      if (c1Regex.test(c)) {
        var pad2 = function (s) {
          if (s.length < 2) {
            s = '0' + s;
          }
          return s;
        }
        c = c.replace(c1Regex, function (match, r, g, b) {
          r = pad2(parseInt(r).toString(16));
          g = pad2(parseInt(g).toString(16));
          b = pad2(parseInt(b).toString(16));
          return '#' + r + g + b;
        });
      }
      return c;
    };
  
    HTML2BBCode.prototype.size = function (size) {
      if (!size) return;
  
      var px2size = [0, 12, 14, 16, 18, 24, 32, 48];
      var name2size = [null, 'smaller', 'small', 'medium', 'large',
        'x-large', 'xx-large', '-webkit-xxx-large'];
  
      if (/^\d+$/.test(size)) {
        return size;
      } else if (/^\d+?px$/.test(size)) {
        size = parseInt(size);
        if (!size || size < 0) {
          return;
        }
        if (this.opts.transsize) {
          for (var i = px2size.length; i >= 0; i--) {
            if (i === 0) {
              // smallest
              return '1';
            }
            if (size >= px2size[i]) {
              return i.toString();
            }
          }
        } else {
          return size.toString();
        }
      } else {
        var ns = name2size.indexOf(size);
        if (ns > 0) {
          if (this.opts.transsize) {
            return ns.toString();
          } else {
            return px2size[ns].toString();
          }
        }
  
        // TODO: support other type
        return;
      }
  
      return size ? size.toString() : undefined;
    };
  
    HTML2BBCode.prototype.px = function (px) {
      if (!px) return;
      px = parseInt(px);
      return px ? px.toString() : undefined;
    };
  
    HTML2BBCode.prototype.convertStyle = function (htag, sec) {
      if (!sec) {
        return;
      }
      var bbs = [];
      var that = this;
      var opts = this.opts;
      var addbb = function (sec) {
        if (!sec || sec.ignore ||
          !(sec.section || (sec.extend && sec.extend.length > 0))) {
          return;
        }
        var tsec = { section: sec.section };
        if (sec.attr) {
          if (htag.attr) {
            switch (sec.section) {
              case 'size':
                tsec.attr = that.size(htag.attr[sec.attr]);
                break;
              case 'color':
                tsec.attr = that.color(htag.attr[sec.attr]);
                break;
              default:
                tsec.attr = htag.attr[sec.attr];
                break;
            }
            if (htag.attr.style) {
              var ra;
              switch (sec.section) {
                case 'size':
                  ra = htag.attr.style['font-size'];
                  if (ra) ra = that.size(ra);
                  break;
                case 'color':
                  ra = htag.attr.style['color'];
                  if (ra) ra = that.color(ra);
                  break;
                case 'font':
                  ra = htag.attr.style['font-family'];
                  break;
              }
              if (ra) {
                tsec.attr = ra;
              }
            }
            if (!tsec.attr) {
              return;
            }
          } else {
            return;
          }
        } else if (sec.section === 'img' && opts.imagescale) {
          // image attr
          var w, h;
          if (htag.attr) {
            w = that.px(htag.attr['width']);
            h = that.px(htag.attr['height']);
            if (htag.attr.style) {
              var w1, h1;
              w1 = that.px(htag.attr.style['width']);
              h1 = that.px(htag.attr.style['height']);
              if (w1) w = w1;
              if (h1) h = h1;
            }
            if (w && h) {
              tsec.attr = w + 'x' + h;
            } else if (w || h) {
              if (w) {
                tsec.attr = { width: w };
              } else {
                tsec.attr = { height: h };
              }
            }
          }
        }
        if (sec.data) {
          tsec.data = htag.attr[sec.data];
        }
        bbs.push(tsec);
      };
      // check font-weight & text-align
      if (htag.attr && htag.attr.style) {
        if (htag.name !== 'b' && htag.name !== 'strong') {
          var att = htag.attr.style['font-weight'];
          if (att === 'bold' || (/^\d+$/.test(att) && parseInt(att) >= 700)) {
            addbb(BBCode.maps['b']);
          }
        }
        if (htag.name !== 'center') {
          var att = htag.attr.style['text-align'];
          if (att === 'center' && !opts.noalign) {
            addbb(BBCode.maps['center']);
          }
        }
        if (htag.name !== 'em' && htag.name !== 'i') {
          var att = htag.attr.style['font-style'];
          if (att === 'italic' || att === 'oblique') {
            // italic style
            addbb(BBCode.maps['i']);
          }
        }
      }
      if (sec.section === 'list'
          || sec.section === 'ul' || sec.section === 'ol'
          || sec.section === 'li') {
        if (opts.nolist) {
          return [];
        }
      } else if (sec.section === 'center') {
        if (opts.noalign) {
          return [];
        }
      } else if (/^h\d+$/.test(sec.section)) {
        // HTML Headings
        if (opts.noheadings) {
          // 18.5 -> 19
          var headings2size = [ null, '32px', '24px', '19px', '16px', '14px', '12px' ];
          var m = sec.section.match(/^h(\d+)$/);
          var hi = parseInt(m[1]);
          if (hi <= 0) {
            return [];
          } else if (hi >= headings2size.length) {
            hi = headings2size.length;
          }
          bbs.push({ section: 'size', attr: that.size(headings2size[hi]) });
          return bbs;
        }
      }
  
      if ('extend' in sec) {
        for (var i = 0; i < sec.extend.length; i++) {
          var tag = sec.extend[i];
          addbb(BBCode.maps[tag]);
        }
      } else {
        addbb(sec);
      }
      return bbs;
    };
  
    HTML2BBCode.prototype.convert = function (hstack) {
      var bbcode = new BBCode();
      if (!hstack) {
        return bbcode;
      }
      var that = this;
      var recursive = function (hs, anl) {
        for (var i = 0; i < hs.length; i++) {
          var s = hs[i];
          if (s instanceof HTMLTag) {
            if (s.name in BBCode.maps) {
              var fnewline = 0;
              var sec = BBCode.maps[s.name];
              if (sec.ignore) {
                continue;
              }
              if ('newline' in sec) {
                fnewline = sec.newline;
                bbcode.newline(sec.newline);
              }
              if (!s.content && !sec.empty) {
                // drop this
                continue;
              }
              var bbs = that.convertStyle(s, sec);
              bbcode.open(bbs);
  
              if (s.content) {
                recursive(s.content.stack, fnewline);
              }
              for (var j = bbs.length - 1; j >= 0; j--) {
                bbcode.close(bbs[j].section);
              }
              if (fnewline) {
                // weak new line
                bbcode.newline();
              }
            } else if (s.content) {
              // drop section
              recursive(s.content.stack);
            }
          } else if (typeof s === 'string') {
            // force space
            //s = s.replace(/&nbsp;/gi, ' ');
            bbcode.append(s);
          }
        }
      };
      recursive(hstack.stack);
      return bbcode;
    };
  
    HTML2BBCode.prototype.parse = function (html) {
      return new HTMLStack().parse(html)
        .strip().dedup().decode();
    };
  
    HTML2BBCode.prototype.feed = function (html) {
      var hstack = this.parse(html);
      if (this.opts.debug) {
        hstack.showtree();
      }
      var bbcode = this.convert(hstack);
      return bbcode;
    };
  
    return {
      HTMLTag: HTMLTag,
      HTMLStack: HTMLStack,
      BBCode: BBCode,
      HTML2BBCode: HTML2BBCode
    };
  
  });