node.dart 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. final node = Node(
  32. type: jType,
  33. children: children,
  34. attributes: jAttributes,
  35. );
  36. for (final child in children) {
  37. child.parent = node;
  38. }
  39. return node;
  40. }
  41. void updateAttributes(Map<String, Object> attributes) {
  42. for (final attribute in attributes.entries) {
  43. this.attributes[attribute.key] = attribute.value;
  44. }
  45. }
  46. Node? childAtIndex(int index) {
  47. if (children.length <= index) {
  48. return null;
  49. }
  50. return children.elementAt(index);
  51. }
  52. Node? childAtPath(Path path) {
  53. if (path.isEmpty) {
  54. return this;
  55. }
  56. return childAtIndex(path.first)?.childAtPath(path.sublist(1));
  57. }
  58. @override
  59. void insertAfter(Node entry) {
  60. entry.parent = parent;
  61. super.insertAfter(entry);
  62. }
  63. @override
  64. void insertBefore(Node entry) {
  65. entry.parent = parent;
  66. super.insertBefore(entry);
  67. }
  68. @override
  69. void unlink() {
  70. parent = null;
  71. super.unlink();
  72. }
  73. Map<String, Object> toJson() {
  74. var map = <String, Object>{
  75. 'type': type,
  76. };
  77. if (children.isNotEmpty) {
  78. map['children'] = children.map((node) => node.toJson());
  79. }
  80. if (attributes.isNotEmpty) {
  81. map['attributes'] = attributes;
  82. }
  83. return map;
  84. }
  85. }