OLD | NEW |
1 // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file | 1 // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file |
2 // for details. All rights reserved. Use of this source code is governed by a | 2 // for details. All rights reserved. Use of this source code is governed by a |
3 // BSD-style license that can be found in the LICENSE file. | 3 // BSD-style license that can be found in the LICENSE file. |
4 | 4 |
5 String renderToHtml(List<Node> nodes) => new HtmlRenderer().render(nodes); | 5 String renderToHtml(List<Node> nodes) => new HtmlRenderer().render(nodes); |
6 | 6 |
7 /// Translates a parsed AST to HTML. | 7 /// Translates a parsed AST to HTML. |
8 class HtmlRenderer implements NodeVisitor { | 8 class HtmlRenderer implements NodeVisitor { |
9 static const _BLOCK_TAGS = const RegExp( | 9 static const _BLOCK_TAGS = const RegExp( |
10 'blockquote|h1|h2|h3|h4|h5|h6|hr|p|pre'); | 10 'blockquote|h1|h2|h3|h4|h5|h6|hr|p|pre'); |
11 | 11 |
12 StringBuffer buffer; | 12 StringBuffer buffer; |
13 | 13 |
14 HtmlRenderer(); | 14 HtmlRenderer(); |
15 | 15 |
16 String render(List<Node> nodes) { | 16 String render(List<Node> nodes) { |
17 buffer = new StringBuffer(); | 17 buffer = new StringBuffer(); |
18 | 18 |
19 for (final node in nodes) node.accept(this); | 19 for (final node in nodes) node.accept(this); |
20 | 20 |
21 return buffer.toString(); | 21 return buffer.toString(); |
22 } | 22 } |
23 | 23 |
24 void visitText(Text text) { | 24 void visitText(Text text) { |
25 buffer.add(text.text); | 25 buffer.add(text.text); |
26 } | 26 } |
27 | 27 |
28 bool visitElementBefore(Element element) { | 28 bool visitElementBefore(Element element) { |
29 // Hackish. Separate block-level elements with newlines. | 29 // Hackish. Separate block-level elements with newlines. |
30 if (!buffer.isEmpty() && | 30 if (!buffer.isEmpty && |
31 _BLOCK_TAGS.firstMatch(element.tag) != null) { | 31 _BLOCK_TAGS.firstMatch(element.tag) != null) { |
32 buffer.add('\n'); | 32 buffer.add('\n'); |
33 } | 33 } |
34 | 34 |
35 buffer.add('<${element.tag}'); | 35 buffer.add('<${element.tag}'); |
36 | 36 |
37 for (final name in element.attributes.getKeys()) { | 37 for (final name in element.attributes.getKeys()) { |
38 buffer.add(' $name="${element.attributes[name]}"'); | 38 buffer.add(' $name="${element.attributes[name]}"'); |
39 } | 39 } |
40 | 40 |
41 if (element.isEmpty) { | 41 if (element.isEmpty) { |
42 // Empty element like <hr/>. | 42 // Empty element like <hr/>. |
43 buffer.add(' />'); | 43 buffer.add(' />'); |
44 return false; | 44 return false; |
45 } else { | 45 } else { |
46 buffer.add('>'); | 46 buffer.add('>'); |
47 return true; | 47 return true; |
48 } | 48 } |
49 } | 49 } |
50 | 50 |
51 void visitElementAfter(Element element) { | 51 void visitElementAfter(Element element) { |
52 buffer.add('</${element.tag}>'); | 52 buffer.add('</${element.tag}>'); |
53 } | 53 } |
54 } | 54 } |
OLD | NEW |