node.dart 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import 'dart:collection';
  2. import 'package:flowy_editor/document/path.dart';
  3. class Node extends LinkedListEntry<Node> {
  4. Node? parent;
  5. final String type;
  6. final LinkedList<Node> children;
  7. final Map<String, Object> attributes;
  8. Node({
  9. required this.type,
  10. required this.children,
  11. required this.attributes,
  12. this.parent,
  13. });
  14. factory Node.fromJson(Map<String, Object> json) {
  15. assert(json['type'] is String);
  16. final jType = json['type'] as String;
  17. final jChildren = json['children'] as List?;
  18. final jAttributes = json['attributes'] != null
  19. ? Map<String, Object>.from(json['attributes'] as Map)
  20. : <String, Object>{};
  21. final LinkedList<Node> children = LinkedList();
  22. if (jChildren != null) {
  23. children.addAll(
  24. jChildren.map(
  25. (jnode) => Node.fromJson(
  26. Map<String, Object>.from(jnode),
  27. ),
  28. ),
  29. );
  30. }
  31. return Node(
  32. type: jType,
  33. children: children,
  34. attributes: jAttributes,
  35. );
  36. }
  37. Node? childAtIndex(int index) {
  38. if (children.length <= index) {
  39. return null;
  40. }
  41. return children.elementAt(index);
  42. }
  43. Node? childAtPath(Path path) {
  44. if (path.isEmpty) {
  45. return this;
  46. }
  47. return childAtIndex(path.first)?.childAtPath(path.sublist(1));
  48. }
  49. Map<String, Object> toJson() {
  50. var map = <String, Object>{
  51. 'type': type,
  52. };
  53. if (children.isNotEmpty) {
  54. map['children'] = children.map((node) => node.toJson());
  55. }
  56. if (attributes.isNotEmpty) {
  57. map['attributes'] = attributes;
  58. }
  59. return map;
  60. }
  61. }