OLD | NEW |
| (Empty) |
1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file | |
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. | |
4 | |
5 library json_view_element; | |
6 | |
7 import 'package:polymer/polymer.dart'; | |
8 import 'observatory_element.dart'; | |
9 import 'package:observatory/service.dart'; | |
10 | |
11 class JsonPrettyPrinter { | |
12 String prettyPrint(ServiceMap map) { | |
13 _buffer.clear(); | |
14 _buffer.write('{\n'); | |
15 _printMap(map, 0); | |
16 _buffer.write('}\n'); | |
17 return _buffer.toString(); | |
18 } | |
19 | |
20 void _printMap(ObservableMap map, int depth) { | |
21 if (_seen.contains(map)) { | |
22 return; | |
23 } | |
24 _seen.add(map); | |
25 for (var k in map.keys) { | |
26 var v = map[k]; | |
27 if (v is Map) { | |
28 _writeIndent(depth); | |
29 _buffer.write('"$k": {\n'); | |
30 _printMap(v, depth + 1); | |
31 _writeIndent(depth); | |
32 _buffer.write('}\n'); | |
33 } else if (v is List) { | |
34 _writeIndent(depth); | |
35 _buffer.write('"$k": [\n'); | |
36 _printList(v, depth + 1); | |
37 _writeIndent(depth); | |
38 _buffer.write(']\n'); | |
39 } else { | |
40 _writeIndent(depth); | |
41 _buffer.write('"$k": $v'); | |
42 _buffer.write('\n'); | |
43 } | |
44 } | |
45 _seen.remove(map); | |
46 } | |
47 | |
48 void _printList(ObservableList list, int depth) { | |
49 if (_seen.contains(list)) { | |
50 return; | |
51 } | |
52 _seen.add(list); | |
53 for (var v in list) { | |
54 if (v is Map) { | |
55 _writeIndent(depth); | |
56 _buffer.write('{\n'); | |
57 _printMap(v, depth + 1); | |
58 _writeIndent(depth); | |
59 _buffer.write('}\n'); | |
60 } else if (v is List) { | |
61 _writeIndent(depth); | |
62 _buffer.write('[\n'); | |
63 _printList(v, depth + 1); | |
64 _writeIndent(depth); | |
65 _buffer.write(']\n'); | |
66 } else { | |
67 _writeIndent(depth); | |
68 _buffer.write(v); | |
69 _buffer.write('\n'); | |
70 } | |
71 } | |
72 _seen.remove(list); | |
73 } | |
74 | |
75 void _writeIndent(int depth) { | |
76 const tab = ' '; // 2 spaces. | |
77 _buffer.write(tab * depth); | |
78 } | |
79 | |
80 final _buffer = new StringBuffer(); | |
81 final _seen = new Set(); | |
82 } | |
83 | |
84 | |
85 @CustomTag('json-view') | |
86 class JsonViewElement extends ObservatoryElement { | |
87 @published ServiceMap map; | |
88 @observable String mapAsString; | |
89 JsonViewElement.created() : super.created(); | |
90 | |
91 void mapChanged(oldValue) { | |
92 var jpp = new JsonPrettyPrinter(); | |
93 mapAsString = jpp.prettyPrint(map); | |
94 } | |
95 } | |
OLD | NEW |