node.dart 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import 'dart:collection';
  2. import 'package:flowy_editor/document/path.dart';
  3. typedef Attributes = Map<String, dynamic>;
  4. class Node extends LinkedListEntry<Node> {
  5. Node? parent;
  6. final String type;
  7. final LinkedList<Node> children;
  8. final Attributes attributes;
  9. Node({
  10. required this.type,
  11. required this.children,
  12. required this.attributes,
  13. this.parent,
  14. });
  15. factory Node.fromJson(Map<String, Object> json) {
  16. assert(json['type'] is String);
  17. final jType = json['type'] as String;
  18. final jChildren = json['children'] as List?;
  19. final jAttributes = json['attributes'] != null
  20. ? Attributes.from(json['attributes'] as Map)
  21. : Attributes.from({});
  22. final LinkedList<Node> children = LinkedList();
  23. if (jChildren != null) {
  24. children.addAll(
  25. jChildren.map(
  26. (jChild) => Node.fromJson(
  27. Map<String, Object>.from(jChild),
  28. ),
  29. ),
  30. );
  31. }
  32. final node = Node(
  33. type: jType,
  34. children: children,
  35. attributes: jAttributes,
  36. );
  37. for (final child in children) {
  38. child.parent = node;
  39. }
  40. return node;
  41. }
  42. void updateAttributes(Attributes attributes) {
  43. for (final attribute in attributes.entries) {
  44. this.attributes[attribute.key] = attribute.value;
  45. }
  46. }
  47. Node? childAtIndex(int index) {
  48. if (children.length <= index) {
  49. return null;
  50. }
  51. return children.elementAt(index);
  52. }
  53. Node? childAtPath(Path path) {
  54. if (path.isEmpty) {
  55. return this;
  56. }
  57. return childAtIndex(path.first)?.childAtPath(path.sublist(1));
  58. }
  59. @override
  60. void insertAfter(Node entry) {
  61. entry.parent = parent;
  62. super.insertAfter(entry);
  63. }
  64. @override
  65. void insertBefore(Node entry) {
  66. entry.parent = parent;
  67. super.insertBefore(entry);
  68. }
  69. @override
  70. void unlink() {
  71. parent = null;
  72. super.unlink();
  73. }
  74. Map<String, Object> toJson() {
  75. var map = <String, Object>{
  76. 'type': type,
  77. };
  78. if (children.isNotEmpty) {
  79. map['children'] = children.map((node) => node.toJson());
  80. }
  81. if (attributes.isNotEmpty) {
  82. map['attributes'] = attributes;
  83. }
  84. return map;
  85. }
  86. }