Browse Source

feat: compute string indexes

Vincent Chan 2 years ago
parent
commit
bee1a04329

+ 15 - 0
frontend/app_flowy/packages/flowy_editor/lib/src/document/text_delta.dart

@@ -260,6 +260,7 @@ TextOperation? _textOperationFromJson(Map<String, dynamic> json) {
 class Delta extends Iterable<TextOperation> {
   final List<TextOperation> _operations;
   String? _rawString;
+  List<int>? _runeIndexes;
 
   factory Delta.fromJson(List<dynamic> list) {
     final operations = <TextOperation>[];
@@ -477,9 +478,23 @@ class Delta extends Iterable<TextOperation> {
   String toRawString() {
     _rawString ??=
         _operations.whereType<TextInsert>().map((op) => op.content).join();
+    _runeIndexes ??= stringIndexes(_rawString!);
     return _rawString!;
   }
 
   @override
   Iterator<TextOperation> get iterator => _operations.iterator;
 }
+
+List<int> stringIndexes(String content) {
+  final indexes = List<int>.filled(content.length, 0);
+  final iterator = content.runes.iterator;
+
+  while (iterator.moveNext()) {
+    for (var i = 0; i < iterator.currentSize; i++) {
+      indexes[iterator.rawIndex + i] = iterator.rawIndex;
+    }
+  }
+
+  return indexes;
+}

+ 5 - 0
frontend/app_flowy/packages/flowy_editor/test/delta_test.dart

@@ -279,4 +279,9 @@ void main() {
       expect(delta, expected);
     });
   });
+  test("stringIndexes", () {
+    final indexes = stringIndexes('😊');
+    expect(indexes[0], 0);
+    expect(indexes[1], 0);
+  });
 }