-
-
Notifications
You must be signed in to change notification settings - Fork 889
/
Copy pathhtml_parser.dart
1887 lines (1801 loc) · 59.9 KB
/
html_parser.dart
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
import 'dart:convert';
import 'image_properties.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:html/dom.dart' as dom;
import 'package:html/parser.dart' as parser;
typedef CustomRender = Widget Function(dom.Node node, List<Widget> children);
typedef CustomTextStyle = TextStyle Function(
dom.Node node,
TextStyle baseStyle,
);
typedef CustomEdgeInsets = EdgeInsets Function(dom.Node node);
typedef OnLinkTap = void Function(String url);
typedef OnImageTap = void Function();
const OFFSET_TAGS_FONT_SIZE_FACTOR =
0.7; //The ratio of the parent font for each of the offset tags: sup or sub
class LinkTextSpan extends TextSpan {
// Beware!
//
// This class is only safe because the TapGestureRecognizer is not
// given a deadline and therefore never allocates any resources.
//
// In any other situation -- setting a deadline, using any of the less trivial
// recognizers, etc -- you would have to manage the gesture recognizer's
// lifetime and call dispose() when the TextSpan was no longer being rendered.
//
// Since TextSpan itself is @immutable, this means that you would have to
// manage the recognizer from outside the TextSpan, e.g. in the State of a
// stateful widget that then hands the recognizer to the TextSpan.
final String url;
LinkTextSpan(
{TextStyle style,
this.url,
String text,
OnLinkTap onLinkTap,
List<TextSpan> children})
: super(
style: style,
text: text,
children: children ?? <TextSpan>[],
recognizer: TapGestureRecognizer()
..onTap = () {
onLinkTap(url);
});
}
class LinkBlock extends Container {
// final String url;
// final EdgeInsets padding;
// final EdgeInsets margin;
// final OnLinkTap onLinkTap;
final List<Widget> children;
LinkBlock({
String url,
EdgeInsets padding,
EdgeInsets margin,
OnLinkTap onLinkTap,
this.children,
}) : super(
padding: padding,
margin: margin,
child: GestureDetector(
onTap: () {
onLinkTap(url);
},
child: Column(
children: children,
)));
}
class BlockText extends StatelessWidget {
final RichText child;
final EdgeInsets padding;
final EdgeInsets margin;
final String leadingChar;
final Decoration decoration;
BlockText(
{@required this.child,
this.padding,
this.margin,
this.leadingChar = '',
this.decoration});
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: this.padding,
margin: this.margin,
decoration: this.decoration,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
leadingChar.isNotEmpty ? Text(leadingChar) : Container(),
Expanded(child: child),
],
));
}
}
class ParseContext {
List<Widget> rootWidgetList; // the widgetList accumulator
dynamic parentElement; // the parent spans accumulator
int indentLevel = 0;
int listCount = 0;
String listChar = '•';
String blockType; // blockType can be 'p', 'div', 'ul', 'ol', 'blockquote'
bool condenseWhitespace = true;
bool spansOnly = false;
bool inBlock = false;
TextStyle childStyle;
ParseContext(
{this.rootWidgetList,
this.parentElement,
this.indentLevel = 0,
this.listCount = 0,
this.listChar = '•',
this.blockType,
this.condenseWhitespace = true,
this.spansOnly = false,
this.inBlock = false,
this.childStyle}) {
childStyle = childStyle ?? TextStyle();
}
ParseContext.fromContext(ParseContext parseContext) {
rootWidgetList = parseContext.rootWidgetList;
parentElement = parseContext.parentElement;
indentLevel = parseContext.indentLevel;
listCount = parseContext.listCount;
listChar = parseContext.listChar;
blockType = parseContext.blockType;
condenseWhitespace = parseContext.condenseWhitespace;
spansOnly = parseContext.spansOnly;
inBlock = parseContext.inBlock;
childStyle = parseContext.childStyle ?? TextStyle();
}
}
class HtmlRichTextParser extends StatelessWidget {
HtmlRichTextParser({
@required this.width,
this.onLinkTap,
this.renderNewlines = false,
this.html,
this.customTextStyle,
this.customEdgeInsets,
this.onImageError,
this.linkStyle = const TextStyle(
decoration: TextDecoration.underline,
color: Colors.blueAccent,
decorationColor: Colors.blueAccent,
),
this.imageProperties,
this.onImageTap,
this.showImages = true,
});
final double indentSize = 10.0;
final double width;
final onLinkTap;
final bool renderNewlines;
final String html;
final CustomTextStyle customTextStyle;
final CustomEdgeInsets customEdgeInsets;
final ImageErrorListener onImageError;
final TextStyle linkStyle;
final ImageProperties imageProperties;
final OnImageTap onImageTap;
final bool showImages;
// style elements set a default style
// for all child nodes
// treat ol, ul, and blockquote like style elements also
static const _supportedStyleElements = [
"b",
"i",
"address",
"cite",
"var",
"em",
"strong",
"kbd",
"samp",
"tt",
"code",
"ins",
"u",
"small",
"abbr",
"acronym",
"mark",
"ol",
"ul",
"blockquote",
"del",
"s",
"strike",
"ruby",
"rp",
"rt",
"bdi",
"data",
"time",
"span",
"big",
];
// specialty elements require unique handling
// eg. the "a" tag can contain a block of text or an image
// sometimes "a" will be rendered with a textspan and recognizer
// sometimes "a" will be rendered with a clickable Block
static const _supportedSpecialtyElements = [
"a",
"br",
"table",
"tbody",
"caption",
"td",
"tfoot",
"th",
"thead",
"tr",
"q",
];
// block elements are always rendered with a new
// block-level widget, if a block level element
// is found inside another block level element,
// we simply treat it as a new block level element
static const _supportedBlockElements = [
"article",
"aside",
"body",
"center",
"dd",
"dfn",
"div",
"dl",
"dt",
"figcaption",
"figure",
"footer",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"header",
"hr",
"img",
"li",
"main",
"nav",
"noscript",
"p",
"pre",
"section",
];
static get _supportedElements => List()
..addAll(_supportedStyleElements)
..addAll(_supportedSpecialtyElements)
..addAll(_supportedBlockElements);
// this function is called recursively for each child
// however, the first time it is called, we make sure
// to ignore the node itself, so we only pay attention
// to the children
bool _hasBlockChild(dom.Node node, {bool ignoreSelf = true}) {
bool retval = false;
if (node is dom.Element) {
if (_supportedBlockElements.contains(node.localName) && !ignoreSelf)
return true;
node.nodes.forEach((dom.Node node) {
if (_hasBlockChild(node, ignoreSelf: false)) retval = true;
});
}
return retval;
}
// Parses an html string and returns a list of RichText widgets that represent the body of your html document.
@override
Widget build(BuildContext context) {
String data = html;
if (renderNewlines) {
data = data.replaceAll("\n", "<br />");
}
dom.Document document = parser.parse(data);
dom.Node body = document.body;
List<Widget> widgetList = new List<Widget>();
ParseContext parseContext = ParseContext(
rootWidgetList: widgetList,
childStyle: DefaultTextStyle.of(context).style,
);
// don't ignore the top level "body"
_parseNode(body, parseContext, context);
// filter out empty widgets
List<Widget> children = [];
widgetList.forEach((dynamic w) {
if (w is BlockText) {
if (w.child.text == null) return;
if ((w.child.text.text == null || w.child.text.text.isEmpty) &&
(w.child.text.children == null || w.child.text.children.isEmpty))
return;
} else if (w is LinkBlock) {
if (w.children.isEmpty) return;
} else if (w is LinkTextSpan) {
if (w.text.isEmpty && w.children.isEmpty) return;
}
children.add(w);
});
return Column(
children: children,
);
}
// THE WORKHORSE FUNCTION!!
// call the function with the current node and a ParseContext
// the ParseContext is used to do a number of things
// first, since we call this function recursively, the parseContext holds references to
// all the data that is relevant to a particular iteration and its child iterations
// it holds information about whether to indent the text, whether we are in a list, etc.
//
// secondly, it holds the 'global' widgetList that accumulates all the block-level widgets
//
// thirdly, it holds a reference to the most recent "parent" so that this iteration of the
// function can add child nodes to the parent if it should
//
// each iteration creates a new parseContext as a copy of the previous one if it needs to
void _parseNode(
dom.Node node, ParseContext parseContext, BuildContext buildContext) {
// TEXT ONLY NODES
// a text only node is a child of a tag with no inner html
if (node is dom.Text) {
// WHITESPACE CONSIDERATIONS ---
// truly empty nodes should just be ignored
if (node.text.trim() == "" && node.text.indexOf(" ") == -1) {
return;
}
// we might want to preserve internal whitespace
// empty strings of whitespace might be significant or not, condense it by default
String finalText = node.text;
if (parseContext.condenseWhitespace) {
finalText = condenseHtmlWhitespace(node.text);
// if this is part of a string of spans, we will preserve leading
// and trailing whitespace unless the previous character is whitespace
if (parseContext.parentElement == null)
finalText = finalText.trimLeft();
else if (parseContext.parentElement is TextSpan ||
parseContext.parentElement is LinkTextSpan) {
String lastString = parseContext.parentElement.text ?? '';
if (!parseContext.parentElement.children.isEmpty) {
lastString = parseContext.parentElement.children.last.text ?? '';
}
if (lastString.endsWith(' ') || lastString.endsWith('\n')) {
finalText = finalText.trimLeft();
}
}
}
// if the finalText is actually empty, just return (unless it's just a space)
if (finalText.trim().isEmpty && finalText != " ") return;
// NOW WE HAVE OUR TRULY FINAL TEXT
// debugPrint("Plain Text Node: '$finalText'");
// create a span by default
TextSpan span = TextSpan(
text: finalText,
children: <TextSpan>[],
style: parseContext.childStyle);
// in this class, a ParentElement must be a BlockText, LinkTextSpan, Row, Column, TextSpan
// the parseContext might actually be a block level style element, so we
// need to honor the indent and styling specified by that block style.
// e.g. ol, ul, blockquote
bool treatLikeBlock =
['blockquote', 'ul', 'ol'].indexOf(parseContext.blockType) != -1;
// if there is no parentElement, contain the span in a BlockText
if (parseContext.parentElement == null) {
// if this is inside a context that should be treated like a block
// but the context is not actually a block, create a block
// and append it to the root widget tree
if (treatLikeBlock) {
Decoration decoration;
if (parseContext.blockType == 'blockquote') {
decoration = BoxDecoration(
border:
Border(left: BorderSide(color: Colors.black38, width: 2.0)),
);
parseContext.childStyle = parseContext.childStyle.merge(TextStyle(
fontStyle: FontStyle.italic,
));
}
BlockText blockText = BlockText(
margin: EdgeInsets.only(
top: 8.0,
bottom: 8.0,
left: parseContext.indentLevel * indentSize),
padding: EdgeInsets.all(2.0),
decoration: decoration,
child: RichText(
textAlign: TextAlign.left,
text: span,
),
);
parseContext.rootWidgetList.add(blockText);
} else {
parseContext.rootWidgetList
.add(BlockText(child: RichText(text: span)));
}
// this allows future items to be added as children of this item
parseContext.parentElement = span;
// if the parent is a LinkTextSpan, keep the main attributes of that span going.
} else if (parseContext.parentElement is LinkTextSpan) {
// add this node to the parent as another LinkTextSpan
parseContext.parentElement.children.add(LinkTextSpan(
style:
parseContext.parentElement.style.merge(parseContext.childStyle),
url: parseContext.parentElement.url,
text: finalText,
onLinkTap: onLinkTap,
));
// if the parent is a normal span, just add this to that list
} else if (!(parseContext.parentElement.children is List<Widget>)) {
parseContext.parentElement.children.add(span);
} else {
// Doing nothing... we shouldn't ever get here
}
return;
}
// OTHER ELEMENT NODES
else if (node is dom.Element) {
if (!_supportedElements.contains(node.localName)) {
return;
}
// make a copy of the current context so that we can modify
// pieces of it for the next iteration of this function
ParseContext nextContext = new ParseContext.fromContext(parseContext);
// handle style elements
if (_supportedStyleElements.contains(node.localName)) {
TextStyle childStyle = parseContext.childStyle ?? TextStyle();
switch (node.localName) {
//"b","i","em","strong","code","u","small","abbr","acronym"
case "b":
case "strong":
childStyle =
childStyle.merge(TextStyle(fontWeight: FontWeight.bold));
break;
case "i":
case "address":
case "cite":
case "var":
case "em":
childStyle =
childStyle.merge(TextStyle(fontStyle: FontStyle.italic));
break;
case "kbd":
case "samp":
case "tt":
case "code":
childStyle = childStyle.merge(TextStyle(fontFamily: 'monospace'));
break;
case "ins":
case "u":
childStyle = childStyle
.merge(TextStyle(decoration: TextDecoration.underline));
break;
case "abbr":
case "acronym":
childStyle = childStyle.merge(TextStyle(
decoration: TextDecoration.underline,
decorationStyle: TextDecorationStyle.dotted,
));
break;
case "big":
childStyle = childStyle.merge(TextStyle(fontSize: 20.0));
break;
case "small":
childStyle = childStyle.merge(TextStyle(fontSize: 10.0));
break;
case "mark":
childStyle = childStyle.merge(
TextStyle(backgroundColor: Colors.yellow, color: Colors.black));
break;
case "del":
case "s":
case "strike":
childStyle = childStyle
.merge(TextStyle(decoration: TextDecoration.lineThrough));
break;
case "ol":
nextContext.indentLevel += 1;
nextContext.listChar = '#';
nextContext.listCount = 0;
nextContext.blockType = 'ol';
break;
case "ul":
nextContext.indentLevel += 1;
nextContext.listChar = '•';
nextContext.listCount = 0;
nextContext.blockType = 'ul';
break;
case "blockquote":
nextContext.indentLevel += 1;
nextContext.blockType = 'blockquote';
break;
case "ruby":
case "rt":
case "rp":
case "bdi":
case "data":
case "time":
case "span":
//No additional styles
break;
}
if (customTextStyle != null) {
final TextStyle customStyle = customTextStyle(node, childStyle);
if (customStyle != null) {
childStyle = customStyle;
}
}
nextContext.childStyle = childStyle;
}
// handle specialty elements
else if (_supportedSpecialtyElements.contains(node.localName)) {
// should support "a","br","table","tbody","thead","tfoot","th","tr","td"
switch (node.localName) {
case "a":
// if this item has block children, we create
// a container and gesture recognizer for the entire
// element, otherwise, we create a LinkTextSpan
String url = node.attributes['href'] ?? null;
if (_hasBlockChild(node)) {
LinkBlock linkContainer = LinkBlock(
url: url,
margin: EdgeInsets.only(
left: parseContext.indentLevel * indentSize),
onLinkTap: onLinkTap,
children: <Widget>[],
);
nextContext.parentElement = linkContainer;
nextContext.rootWidgetList.add(linkContainer);
} else {
TextStyle _linkStyle = parseContext.childStyle.merge(linkStyle);
LinkTextSpan span = LinkTextSpan(
style: _linkStyle,
url: url,
onLinkTap: onLinkTap,
children: <TextSpan>[],
);
if (parseContext.parentElement is TextSpan) {
nextContext.parentElement.children.add(span);
} else {
// start a new block element for this link and its text
BlockText blockElement = BlockText(
margin: EdgeInsets.only(
left: parseContext.indentLevel * indentSize, top: 10.0),
child: RichText(text: span),
);
parseContext.rootWidgetList.add(blockElement);
nextContext.inBlock = true;
}
nextContext.childStyle = linkStyle;
nextContext.parentElement = span;
}
break;
case "br":
if (parseContext.parentElement != null &&
parseContext.parentElement is TextSpan) {
parseContext.parentElement.children
.add(TextSpan(text: '\n', children: []));
}
break;
case "table":
// new block, so clear out the parent element
parseContext.parentElement = null;
nextContext.parentElement = Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[],
);
nextContext.rootWidgetList.add(Container(
margin: EdgeInsets.symmetric(vertical: 12.0),
child: nextContext.parentElement));
break;
// we don't handle tbody, thead, or tfoot elements separately for now
case "tbody":
case "thead":
case "tfoot":
break;
case "td":
case "th":
int colspan = 1;
if (node.attributes['colspan'] != null) {
colspan = int.tryParse(node.attributes['colspan']);
}
nextContext.childStyle = nextContext.childStyle.merge(TextStyle(
fontWeight: (node.localName == 'th')
? FontWeight.bold
: FontWeight.normal));
RichText text =
RichText(text: TextSpan(text: '', children: <TextSpan>[]));
Expanded cell = Expanded(
flex: colspan,
child: Container(padding: EdgeInsets.all(1.0), child: text),
);
nextContext.parentElement.children.add(cell);
nextContext.parentElement = text.text;
break;
case "tr":
Row row = Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[],
);
nextContext.parentElement.children.add(row);
nextContext.parentElement = row;
break;
// treat captions like a row with one expanded cell
case "caption":
// create the row
Row row = Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[],
);
// create an expanded cell
RichText text = RichText(
textAlign: TextAlign.center,
textScaleFactor: 1.2,
text: TextSpan(text: '', children: <TextSpan>[]));
Expanded cell = Expanded(
child: Container(padding: EdgeInsets.all(2.0), child: text),
);
row.children.add(cell);
nextContext.parentElement.children.add(row);
nextContext.parentElement = text.text;
break;
case "q":
if (parseContext.parentElement != null &&
parseContext.parentElement is TextSpan) {
parseContext.parentElement.children
.add(TextSpan(text: '"', children: []));
TextSpan content = TextSpan(text: '', children: []);
parseContext.parentElement.children.add(content);
parseContext.parentElement.children
.add(TextSpan(text: '"', children: []));
nextContext.parentElement = content;
}
break;
}
}
// handle block elements
else if (_supportedBlockElements.contains(node.localName)) {
// block elements only show up at the "root" widget level
// so if we have a block element, reset the parentElement to null
parseContext.parentElement = null;
TextAlign textAlign = TextAlign.left;
EdgeInsets _customEdgeInsets;
if (customEdgeInsets != null) {
_customEdgeInsets = customEdgeInsets(node);
}
switch (node.localName) {
case "hr":
parseContext.rootWidgetList
.add(Divider(height: 1.0, color: Colors.black38));
break;
case "img":
if (showImages) {
if (node.attributes['src'] != null) {
if (node.attributes['src'].startsWith("data:image") &&
node.attributes['src'].contains("base64,")) {
precacheImage(
MemoryImage(
base64.decode(
node.attributes['src'].split("base64,")[1].trim(),
),
),
buildContext,
onError: onImageError,
);
parseContext.rootWidgetList.add(GestureDetector(
child: Image.memory(
base64.decode(
node.attributes['src'].split("base64,")[1].trim()),
width: imageProperties?.width ??
((node.attributes['width'] != null)
? double.parse(node.attributes['width'])
: null),
height: imageProperties?.height ??
((node.attributes['height'] != null)
? double.parse(node.attributes['height'])
: null),
scale: imageProperties?.scale ?? 1.0,
matchTextDirection:
imageProperties?.matchTextDirection ?? false,
centerSlice: imageProperties?.centerSlice,
filterQuality:
imageProperties?.filterQuality ?? FilterQuality.low,
alignment: imageProperties?.alignment ?? Alignment.center,
colorBlendMode: imageProperties?.colorBlendMode,
fit: imageProperties?.fit,
color: imageProperties?.color,
repeat: imageProperties?.repeat ?? ImageRepeat.noRepeat,
semanticLabel: imageProperties?.semanticLabel,
excludeFromSemantics:
(imageProperties?.semanticLabel == null)
? true
: false,
),
onTap: onImageTap,
));
} else {
precacheImage(
NetworkImage(node.attributes['src']),
buildContext,
onError: onImageError,
);
parseContext.rootWidgetList.add(GestureDetector(
child: Image.network(
node.attributes['src'],
width: imageProperties?.width ??
((node.attributes['width'] != null)
? double.parse(node.attributes['width'])
: null),
height: imageProperties?.height ??
((node.attributes['height'] != null)
? double.parse(node.attributes['height'])
: null),
scale: imageProperties?.scale ?? 1.0,
matchTextDirection:
imageProperties?.matchTextDirection ?? false,
centerSlice: imageProperties?.centerSlice,
filterQuality:
imageProperties?.filterQuality ?? FilterQuality.low,
alignment: imageProperties?.alignment ?? Alignment.center,
colorBlendMode: imageProperties?.colorBlendMode,
fit: imageProperties?.fit,
color: imageProperties?.color,
repeat: imageProperties?.repeat ?? ImageRepeat.noRepeat,
semanticLabel: imageProperties?.semanticLabel,
excludeFromSemantics:
(imageProperties?.semanticLabel == null)
? true
: false,
),
onTap: onImageTap,
));
}
if (node.attributes['alt'] != null) {
parseContext.rootWidgetList.add(BlockText(
margin:
EdgeInsets.symmetric(horizontal: 0.0, vertical: 10.0),
padding: EdgeInsets.all(0.0),
child: RichText(
textAlign: TextAlign.center,
text: TextSpan(
text: node.attributes['alt'],
style: nextContext.childStyle,
children: <TextSpan>[],
))));
}
}
}
break;
case "li":
String leadingChar = parseContext.listChar;
if (parseContext.blockType == 'ol') {
// nextContext will handle nodes under this 'li'
// but we want to increment the count at this level
parseContext.listCount += 1;
leadingChar = parseContext.listCount.toString() + '.';
}
BlockText blockText = BlockText(
margin: EdgeInsets.only(
left: parseContext.indentLevel * indentSize, top: 3.0),
child: RichText(
text: TextSpan(
text: '',
style: nextContext.childStyle,
children: <TextSpan>[],
),
),
leadingChar: '$leadingChar ',
);
parseContext.rootWidgetList.add(blockText);
nextContext.parentElement = blockText.child.text;
nextContext.spansOnly = true;
nextContext.inBlock = true;
break;
case "h1":
nextContext.childStyle = nextContext.childStyle.merge(
TextStyle(fontSize: 26.0, fontWeight: FontWeight.bold),
);
continue myDefault;
case "h2":
nextContext.childStyle = nextContext.childStyle.merge(
TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),
);
continue myDefault;
case "h3":
nextContext.childStyle = nextContext.childStyle.merge(
TextStyle(fontSize: 22.0, fontWeight: FontWeight.bold),
);
continue myDefault;
case "h4":
nextContext.childStyle = nextContext.childStyle.merge(
TextStyle(fontSize: 20.0, fontWeight: FontWeight.w100),
);
continue myDefault;
case "h5":
nextContext.childStyle = nextContext.childStyle.merge(
TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
);
continue myDefault;
case "h6":
nextContext.childStyle = nextContext.childStyle.merge(
TextStyle(fontSize: 18.0, fontWeight: FontWeight.w100),
);
continue myDefault;
case "pre":
nextContext.condenseWhitespace = false;
continue myDefault;
case "center":
textAlign = TextAlign.center;
// no break here
continue myDefault;
myDefault:
default:
Decoration decoration;
if (parseContext.blockType == 'blockquote') {
decoration = BoxDecoration(
border:
Border(left: BorderSide(color: Colors.black38, width: 2.0)),
);
nextContext.childStyle = nextContext.childStyle.merge(TextStyle(
fontStyle: FontStyle.italic,
));
}
BlockText blockText = BlockText(
margin: node.localName != 'body'
? _customEdgeInsets ??
EdgeInsets.only(
top: 8.0,
bottom: 8.0,
left: parseContext.indentLevel * indentSize)
: EdgeInsets.zero,
padding: EdgeInsets.all(2.0),
decoration: decoration,
child: RichText(
textAlign: textAlign,
text: TextSpan(
text: '',
style: nextContext.childStyle,
children: <TextSpan>[],
),
),
);
parseContext.rootWidgetList.add(blockText);
nextContext.parentElement = blockText.child.text;
nextContext.spansOnly = true;
nextContext.inBlock = true;
}
}
node.nodes.forEach((dom.Node childNode) {
_parseNode(childNode, nextContext, buildContext);
});
}
}
Paint _getPaint(Color color) {
Paint paint = new Paint();
paint.color = color;
return paint;
}
String condenseHtmlWhitespace(String stringToTrim) {
stringToTrim = stringToTrim.replaceAll("\n", " ");
while (stringToTrim.indexOf(" ") != -1) {
stringToTrim = stringToTrim.replaceAll(" ", " ");
}
return stringToTrim;
}
bool _isNotFirstBreakTag(dom.Node node) {
int index = node.parentNode.nodes.indexOf(node);
if (index == 0) {
if (node.parentNode == null) {
return false;
}
return _isNotFirstBreakTag(node.parentNode);
} else if (node.parentNode.nodes[index - 1] is dom.Element) {
if ((node.parentNode.nodes[index - 1] as dom.Element).localName == "br") {
return true;
}
return false;
} else if (node.parentNode.nodes[index - 1] is dom.Text) {
if ((node.parentNode.nodes[index - 1] as dom.Text).text.trim() == "") {
return _isNotFirstBreakTag(node.parentNode.nodes[index - 1]);
} else {
return false;
}
}
return false;
}
}
class HtmlOldParser extends StatelessWidget {
HtmlOldParser({
@required this.width,
this.onLinkTap,
this.renderNewlines = false,
this.customRender,
this.blockSpacing,
this.html,
this.onImageError,
this.linkStyle = const TextStyle(
decoration: TextDecoration.underline,
color: Colors.blueAccent,
decorationColor: Colors.blueAccent),
this.showImages = true,
});
final double width;
final OnLinkTap onLinkTap;
final bool renderNewlines;
final CustomRender customRender;
final double blockSpacing;
final String html;
final ImageErrorListener onImageError;
final TextStyle linkStyle;
final bool showImages;
static const _supportedElements = [
"a",
"abbr",
"acronym",
"address",
"article",
"aside",
"b",
"bdi",
"bdo",
"big",
"blockquote",
"body",
"br",
"caption",
"cite",
"center",
"code",
"data",
"dd",
"del",