Browse Source

feat: implement text replacement in singe selection

Lucas.Xu 2 years ago
parent
commit
575e01c909

+ 13 - 0
frontend/app_flowy/packages/flowy_editor/lib/operation/transaction_builder.dart

@@ -75,6 +75,19 @@ class TransactionBuilder {
         Selection.collapsed(Position(path: node.path, offset: index));
   }
 
+  replaceText(TextNode node, int index, int length, String content) {
+    textEdit(
+      node,
+      () => Delta().retain(index).delete(length).insert(content),
+    );
+    afterSelection = Selection.collapsed(
+      Position(
+        path: node.path,
+        offset: index + content.length,
+      ),
+    );
+  }
+
   add(Operation op) {
     final Operation? last = operations.isEmpty ? null : operations.last;
     if (last != null) {

+ 20 - 0
frontend/app_flowy/packages/flowy_editor/lib/service/input_service.dart

@@ -97,6 +97,7 @@ class _FlowyInputState extends State<FlowyInput>
         _applyInsert(delta);
       } else if (delta is TextEditingDeltaDeletion) {
       } else if (delta is TextEditingDeltaReplacement) {
+        _applyReplacement(delta);
       } else if (delta is TextEditingDeltaNonTextUpdate) {
         // We don't need to care the [TextEditingDeltaNonTextUpdate].
         // Do nothing.
@@ -125,6 +126,25 @@ class _FlowyInputState extends State<FlowyInput>
     }
   }
 
+  void _applyReplacement(TextEditingDeltaReplacement delta) {
+    final selectionService = _editorState.service.selectionService;
+    final currentSelection = selectionService.currentSelection;
+    if (currentSelection == null) {
+      return;
+    }
+    if (currentSelection.isSingle) {
+      final textNode =
+          selectionService.currentSelectedNodes.value.first as TextNode;
+      final length = delta.replacedRange.end - delta.replacedRange.start;
+      TransactionBuilder(_editorState)
+        ..replaceText(
+            textNode, delta.replacedRange.start, length, delta.replacementText)
+        ..commit();
+    } else {
+      // TODO: implement
+    }
+  }
+
   @override
   void close() {
     _textInputConnection?.close();