From f351a80fd400e293565fd12da052ef272f594510 Mon Sep 17 00:00:00 2001 From: agata Date: Mon, 9 Sep 2024 10:48:50 -0700 Subject: [PATCH] Fix: Allow backspace at start of document to remove block elements and headers (#2198) --- .../editor/raw_editor/raw_editor_state.dart | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/lib/src/editor/raw_editor/raw_editor_state.dart b/lib/src/editor/raw_editor/raw_editor_state.dart index de9f14828..d6e00ec9e 100644 --- a/lib/src/editor/raw_editor/raw_editor_state.dart +++ b/lib/src/editor/raw_editor/raw_editor_state.dart @@ -761,6 +761,11 @@ class QuillRawEditorState extends EditorState return _handleSpaceKey(event); } + // Handles removing styles when pressing the backspace key at the beginning of the document. + if (event.logicalKey == LogicalKeyboardKey.backspace) { + return _handleBackspaceKey(event); + } + return KeyEventResult.ignored; } @@ -797,6 +802,49 @@ class QuillRawEditorState extends EditorState return KeyEventResult.handled; } + KeyEventResult _handleBackspaceKey(KeyEvent event) { + final child = + controller.document.queryChild(controller.selection.baseOffset); + if (child.node == null) { + return KeyEventResult.ignored; + } + + if (child.node == null) { + return KeyEventResult.ignored; + } + + // Only process when the backspace key is pressed at the beginning of the document. + if (controller.selection.baseOffset != 0) { + return KeyEventResult.ignored; + } + + // Blocks and headers are targeted. + final node = child.node!; + final parent = node.parent; + if (parent == null && (parent is Block || parent is Root)) { + return KeyEventResult.ignored; + } + + // Remove the parent's style. + // Block attributes are removed. + final style = parent!.style; + if (style.isNotEmpty) { + for (final attr in style.values) { + controller.formatSelection(Attribute.clone(attr, null)); + } + } + + // Remove the first child's style. + // Header attributes are removed. + final firstChildStyle = parent.first?.style; + if (firstChildStyle != null) { + for (final attr in firstChildStyle.values) { + controller.formatSelection(Attribute.clone(attr, null)); + } + } + return KeyEventResult.handled; + } + KeyEventResult _handleTabKey(KeyEvent event) { final child = controller.document.queryChild(controller.selection.baseOffset);