From 36da9593f30040463c955244069d2670ed454bfe Mon Sep 17 00:00:00 2001 From: Sabrina Tardio <44158575+SabrinaTardio@users.noreply.github.com> Date: Fri, 24 May 2024 14:08:33 +0200 Subject: [PATCH] Scroll address bar to caret when using arrows (#2799) Task/Issue URL: https://app.asana.com/0/1177771139624306/1207043866291151/f **Description**: When using arrows in the address bar it will scroll to the caret position --- .../View/AddressBarTextEditor.swift | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/DuckDuckGo/NavigationBar/View/AddressBarTextEditor.swift b/DuckDuckGo/NavigationBar/View/AddressBarTextEditor.swift index bf5c1c6c7f..c235f193d1 100644 --- a/DuckDuckGo/NavigationBar/View/AddressBarTextEditor.swift +++ b/DuckDuckGo/NavigationBar/View/AddressBarTextEditor.swift @@ -292,12 +292,14 @@ final class AddressBarTextEditor: NSTextView { guard let index = nextWordSelectionIndex(backwards: false) else { return } self.selectedRange = NSRange(location: index, length: 0) + scrollToCaret() } override func moveWordLeft(_ sender: Any?) { guard let index = nextWordSelectionIndex(backwards: true) else { return } self.selectedRange = NSRange(location: index, length: 0) + scrollToCaret() } override func moveWordRightAndModifySelection(_ sender: Any?) { @@ -311,6 +313,7 @@ final class AddressBarTextEditor: NSTextView { let range = NSRange(location: selectedRange.location, length: index - selectedRange.location) self.setSelectedRange(range, affinity: .downstream, stillSelecting: false) + self.scrollToSelectionEnd() } override func moveWordLeftAndModifySelection(_ sender: Any?) { @@ -324,6 +327,7 @@ final class AddressBarTextEditor: NSTextView { let range = NSRange(location: index, length: selectedRange.upperBound - index) self.setSelectedRange(range, affinity: .upstream, stillSelecting: false) + self.scrollToSelectionStart() } override func deleteForward(_ sender: Any?) { @@ -422,6 +426,22 @@ final class AddressBarTextEditor: NSTextView { breakUndoCoalescing() } + private func scrollToCaret() { + guard let layoutManager = layoutManager, let textContainer = textContainer else { return } + let caretRect = layoutManager.boundingRect(forGlyphRange: selectedRange(), in: textContainer) + scrollToVisible(caretRect) + } + + private func scrollToSelectionStart() { + let startRange = NSRange(location: selectedRange().location, length: 0) + self.scrollRangeToVisible(startRange) + } + + private func scrollToSelectionEnd() { + let endRange = NSRange(location: selectedRange.location + selectedRange.length, length: 0) + self.scrollRangeToVisible(endRange) + } + } final class AddressBarTextFieldCell: NSTextFieldCell {