node.dart 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import 'dart:collection';
  2. class Node extends LinkedListEntry<Node> {
  3. Node? parent;
  4. final String type;
  5. final LinkedList<Node> children;
  6. final Map<String, Object> attributes;
  7. Node({
  8. required this.type,
  9. required this.children,
  10. required this.attributes,
  11. this.parent,
  12. });
  13. factory Node.fromJson(Map<String, Object> json) {
  14. assert(json['type'] is String);
  15. final jType = json['type'] as String;
  16. final jChildren = json['children'] as List?;
  17. final jAttributes = json['attributes'] != null
  18. ? Map<String, Object>.from(json['attributes'] as Map)
  19. : <String, Object>{};
  20. final LinkedList<Node> children = LinkedList();
  21. if (jChildren != null) {
  22. children.addAll(
  23. jChildren.map(
  24. (jnode) => Node.fromJson(
  25. Map<String, Object>.from(jnode),
  26. ),
  27. ),
  28. );
  29. }
  30. return Node(
  31. type: jType,
  32. children: children,
  33. attributes: jAttributes,
  34. );
  35. }
  36. Map<String, Object> toJson() {
  37. var map = <String, Object>{
  38. 'type': type,
  39. };
  40. if (children.isNotEmpty) {
  41. map['children'] = children.map((node) => node.toJson());
  42. }
  43. if (attributes.isNotEmpty) {
  44. map['attributes'] = attributes;
  45. }
  46. return map;
  47. }
  48. }