From 254cacba0c30df528d6929dc6115838d0f4e2207 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20St=C3=B8vring?= Date: Wed, 4 Nov 2026 09:09:32 +0100 Subject: [PATCH 01/13] Present native find results above dimmed text --- .../TextView/Appearance/DefaultTheme.swift | 10 +- .../Runestone/TextView/Appearance/Theme.swift | 8 +- .../TextView/Core/TextInputView.swift | 26 +++ .../Runestone/TextView/Core/TextView.swift | 12 ++ .../TextView/Highlight/HighlightedRange.swift | 26 ++- .../FindResultPresentationView.swift | 170 ++++++++++++++++++ .../UITextSearchingHelper.swift | 8 + .../UITextSearchingHelperTests.swift | 25 +++ 8 files changed, 279 insertions(+), 6 deletions(-) create mode 100644 Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift diff --git a/Sources/Runestone/TextView/Appearance/DefaultTheme.swift b/Sources/Runestone/TextView/Appearance/DefaultTheme.swift index 3eedf07a9..8e64a67b2 100644 --- a/Sources/Runestone/TextView/Appearance/DefaultTheme.swift +++ b/Sources/Runestone/TextView/Appearance/DefaultTheme.swift @@ -77,10 +77,16 @@ public final class DefaultTheme: Runestone.Theme { switch style { case .found: let color = UIColor(themeColorNamed: "search_match_found") - return HighlightedRange(range: foundTextRange, color: color, cornerRadius: 2) + return HighlightedRange(range: foundTextRange, + color: color, + cornerRadius: 2, + presentationRole: .foundSearchResult) case .highlighted: let color = UIColor(themeColorNamed: "search_match_highlighted") - return HighlightedRange(range: foundTextRange, color: color, cornerRadius: 2) + return HighlightedRange(range: foundTextRange, + color: color, + cornerRadius: 2, + presentationRole: .selectedSearchResult) case .normal: return nil @unknown default: diff --git a/Sources/Runestone/TextView/Appearance/Theme.swift b/Sources/Runestone/TextView/Appearance/Theme.swift index cf374f600..37b5ed050 100644 --- a/Sources/Runestone/TextView/Appearance/Theme.swift +++ b/Sources/Runestone/TextView/Appearance/Theme.swift @@ -106,9 +106,13 @@ public extension Theme { func highlightedRange(forFoundTextRange foundTextRange: NSRange, ofStyle style: UITextSearchFoundTextStyle) -> HighlightedRange? { switch style { case .found: - return HighlightedRange(range: foundTextRange, color: .systemYellow.withAlphaComponent(0.2)) + return HighlightedRange(range: foundTextRange, + color: .systemYellow.withAlphaComponent(0.2), + presentationRole: .foundSearchResult) case .highlighted: - return HighlightedRange(range: foundTextRange, color: .systemYellow) + return HighlightedRange(range: foundTextRange, + color: .systemYellow, + presentationRole: .selectedSearchResult) case .normal: return nil @unknown default: diff --git a/Sources/Runestone/TextView/Core/TextInputView.swift b/Sources/Runestone/TextView/Core/TextInputView.swift index 10d5b6d08..29c37ba3f 100644 --- a/Sources/Runestone/TextView/Core/TextInputView.swift +++ b/Sources/Runestone/TextView/Core/TextInputView.swift @@ -716,6 +716,25 @@ final class TextInputView: UIView, UITextInput { highlightService.highlightedRanges = newValue layoutManager.setNeedsLayout() layoutManager.layoutIfNeeded() + findResultPresentationView.update(highlightedRanges: newValue, + viewport: viewport, + selectionRects: selectionRects(for:)) + } + } + } + var isFindResultPresentationActive: Bool { + get { + findResultPresentationView.isActive + } + set { + findResultPresentationView.isActive = newValue + if newValue { + if findResultPresentationView.superview == nil { + addSubview(findResultPresentationView) + } + findResultPresentationView.update(highlightedRanges: highlightedRanges, + viewport: viewport, + selectionRects: selectionRects(for:)) } } } @@ -880,6 +899,7 @@ final class TextInputView: UIView, UITextInput { private let contentSizeService: ContentSizeService private let caretRectService: CaretRectService private let selectionRectService: SelectionRectService + private lazy var findResultPresentationView = FindResultPresentationView(sourceView: self) private let highlightService: HighlightService private let invisibleCharacterConfiguration = InvisibleCharacterConfiguration() private var markedRange: NSRange? { @@ -1035,6 +1055,12 @@ final class TextInputView: UIView, UITextInput { checkVisibleSpellingIfNeeded() updateLegacySpellingMenuIfNeeded() writingToolsController?.layoutDidChange() + if findResultPresentationView.isActive { + bringSubviewToFront(findResultPresentationView) + findResultPresentationView.update(highlightedRanges: highlightedRanges, + viewport: viewport, + selectionRects: selectionRects(for:)) + } // We notify the input delegate about selection changes in layoutSubviews so we have a chance of disabling notifying the input delegate during an editing operation. // We will sometimes disable notifying the input delegate when the user enters Korean text. // This workaround is inspired by a dialog with Alexander Blach (@lextar), developer of Textastic. diff --git a/Sources/Runestone/TextView/Core/TextView.swift b/Sources/Runestone/TextView/Core/TextView.swift index a81e7b9b6..9cf9884a9 100644 --- a/Sources/Runestone/TextView/Core/TextView.swift +++ b/Sources/Runestone/TextView/Core/TextView.swift @@ -683,6 +683,18 @@ open class TextView: UIScrollView { highlightNavigationController.highlightedRanges = newValue } } + /// Whether search results are presented above dimmed editor content. + /// + /// Enable this while a custom find interaction is active. Runestone manages + /// this property automatically for its built-in find interaction. + public var isFindResultPresentationActive: Bool { + get { + textInputView.isFindResultPresentationActive + } + set { + textInputView.isFindResultPresentationActive = newValue + } + } /// Wheter the text view should loop when navigating through highlighted ranges using `selectPreviousHighlightedRange` or `selectNextHighlightedRange` on the text view. public var highlightedRangeLoopingMode: HighlightedRangeLoopingMode { get { diff --git a/Sources/Runestone/TextView/Highlight/HighlightedRange.swift b/Sources/Runestone/TextView/Highlight/HighlightedRange.swift index 5f1554155..25af03d7c 100644 --- a/Sources/Runestone/TextView/Highlight/HighlightedRange.swift +++ b/Sources/Runestone/TextView/Highlight/HighlightedRange.swift @@ -1,5 +1,15 @@ import UIKit +/// The role a highlighted range plays when search results are presented. +public enum HighlightedRangePresentationRole { + /// An ordinary highlight that is unrelated to search presentation. + case standard + /// A search result that is not currently selected. + case foundSearchResult + /// The currently selected search result. + case selectedSearchResult +} + /// Range of text to highlight. public final class HighlightedRange { /// Unique identifier of the highlighted range. @@ -10,6 +20,8 @@ public final class HighlightedRange { public let color: UIColor /// Corner radius of the highlight. public let cornerRadius: CGFloat + /// The role of the range when search results are presented. + public let presentationRole: HighlightedRangePresentationRole /// Create a new highlighted range. /// - Parameters: @@ -17,17 +29,27 @@ public final class HighlightedRange { /// - range: Range in the text to highlight. /// - color: Color to highlight the text with. /// - cornerRadius: Corner radius of the highlight. A value of zero or less means no corner radius. Defaults to 0. - public init(id: String = UUID().uuidString, range: NSRange, color: UIColor, cornerRadius: CGFloat = 0) { + /// - presentationRole: Role of the range in search presentation. Defaults to ``HighlightedRangePresentationRole/standard``. + public init(id: String = UUID().uuidString, + range: NSRange, + color: UIColor, + cornerRadius: CGFloat = 0, + presentationRole: HighlightedRangePresentationRole = .standard) { self.id = id self.range = range self.color = color self.cornerRadius = cornerRadius + self.presentationRole = presentationRole } } extension HighlightedRange: Equatable { public static func == (lhs: HighlightedRange, rhs: HighlightedRange) -> Bool { - lhs.id == rhs.id && lhs.range == rhs.range && lhs.color == rhs.color + lhs.id == rhs.id + && lhs.range == rhs.range + && lhs.color == rhs.color + && lhs.cornerRadius == rhs.cornerRadius + && lhs.presentationRole == rhs.presentationRole } } diff --git a/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift new file mode 100644 index 000000000..f80cdb8e4 --- /dev/null +++ b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift @@ -0,0 +1,170 @@ +import UIKit + +final class FindResultPresentationView: UIView { + var isActive = false { + didSet { + guard isActive != oldValue else { + return + } + isHidden = !isActive + if !isActive { + selectedResultContainer.removeFromSuperview() + selectedRange = nil + currentViewport = .null + currentRanges = [] + } + } + } + + private weak var sourceView: UIView? + private let dimmingLayer = CAShapeLayer() + private let selectedResultContainer = UIView() + private var selectedRange: NSRange? + private var currentViewport = CGRect.null + private var currentRanges: [HighlightedRange] = [] + + init(sourceView: UIView) { + self.sourceView = sourceView + super.init(frame: .zero) + isHidden = true + isUserInteractionEnabled = false + backgroundColor = .clear + dimmingLayer.fillColor = UIColor.black.withAlphaComponent(0.22).cgColor + dimmingLayer.fillRule = .evenOdd + layer.addSublayer(dimmingLayer) + selectedResultContainer.isUserInteractionEnabled = false + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func update(highlightedRanges: [HighlightedRange], + viewport: CGRect, + selectionRects: (UITextRange) -> [UITextSelectionRect]) { + guard isActive, let sourceView else { + return + } + let searchRanges = highlightedRanges.filter { $0.presentationRole != .standard } + let selected = searchRanges.first { $0.presentationRole == .selectedSearchResult } + let shouldAnimate = selectedRange != nil && selected?.range != selectedRange + let needsRebuild = currentViewport != viewport || currentRanges != searchRanges + guard needsRebuild else { + return + } + currentViewport = viewport + currentRanges = searchRanges + frame = viewport + dimmingLayer.frame = bounds + let presentations = presentations(for: searchRanges, + sourceView: sourceView, + viewport: viewport, + selectionRects: selectionRects) + updateDimming(using: presentations) + selectedResultContainer.removeFromSuperview() + selectedResultContainer.subviews.forEach { $0.removeFromSuperview() } + if let selectedPresentation = presentations.first(where: { $0.range.presentationRole == .selectedSearchResult }) { + updateSelectedResult(using: selectedPresentation, sourceView: sourceView, viewport: viewport) + animateSelectedResult(shouldAnimate) + } + selectedRange = selected?.range + } + + private func presentations(for ranges: [HighlightedRange], + sourceView: UIView, + viewport: CGRect, + selectionRects: (UITextRange) -> [UITextSelectionRect]) -> [RangePresentation] { + guard let textInput = sourceView as? UITextInput else { + return [] + } + return ranges.compactMap { highlightedRange in + guard let start = textInput.position(from: textInput.beginningOfDocument, + offset: highlightedRange.range.location), + let end = textInput.position(from: start, offset: highlightedRange.range.length), + let textRange = textInput.textRange(from: start, to: end) else { + return nil + } + let rects = selectionRects(textRange).map { selectionRect in + selectionRect.rect.offsetBy(dx: -viewport.minX, dy: -viewport.minY) + } + return RangePresentation(range: highlightedRange, rects: rects) + } + } + + private func updateDimming(using presentations: [RangePresentation]) { + let path = UIBezierPath(rect: bounds) + for presentation in presentations { + for rect in presentation.rects where !rect.isEmpty && rect.intersects(bounds) { + path.append(UIBezierPath(roundedRect: rect, cornerRadius: presentation.range.cornerRadius)) + } + } + dimmingLayer.path = path.cgPath + } + + private func updateSelectedResult(using presentation: RangePresentation, + sourceView: UIView, + viewport: CGRect) { + let visibleRects = presentation.rects.filter { !$0.isEmpty && $0.intersects(bounds) } + guard !visibleRects.isEmpty else { + return + } + addSubview(selectedResultContainer) + let union = visibleRects.reduce(CGRect.null) { $0.union($1) } + selectedResultContainer.frame = union + let presentationSuperview = superview + removeFromSuperview() + for rect in visibleRects { + addSelectedResultSnapshot(for: rect, + sourceView: sourceView, + viewport: viewport, + cornerRadius: presentation.range.cornerRadius, + union: union) + } + if let presentationSuperview { + presentationSuperview.addSubview(self) + } + } + + private func addSelectedResultSnapshot(for rect: CGRect, + sourceView: UIView, + viewport: CGRect, + cornerRadius: CGFloat, + union: CGRect) { + let sourceRect = rect.offsetBy(dx: viewport.minX, dy: viewport.minY) + guard let snapshot = sourceView.resizableSnapshotView(from: sourceRect, + afterScreenUpdates: true, + withCapInsets: .zero) else { + return + } + let shadowView = UIView(frame: rect.offsetBy(dx: -union.minX, dy: -union.minY)) + shadowView.isUserInteractionEnabled = false + shadowView.layer.shadowColor = UIColor.black.cgColor + shadowView.layer.shadowOpacity = 0.22 + shadowView.layer.shadowRadius = 8 + shadowView.layer.shadowOffset = CGSize(width: 0, height: 3) + shadowView.layer.shadowPath = UIBezierPath(roundedRect: shadowView.bounds, cornerRadius: cornerRadius).cgPath + snapshot.frame = shadowView.bounds + snapshot.layer.cornerRadius = cornerRadius + snapshot.layer.cornerCurve = .continuous + snapshot.clipsToBounds = true + shadowView.addSubview(snapshot) + selectedResultContainer.addSubview(shadowView) + } + + private func animateSelectedResult(_ animated: Bool) { + guard animated, !UIAccessibility.isReduceMotionEnabled else { + selectedResultContainer.transform = .identity + return + } + selectedResultContainer.transform = CGAffineTransform(scaleX: 1.2, y: 1.1) + let animator = UIViewPropertyAnimator(duration: 0.2, dampingRatio: 0.82) { + self.selectedResultContainer.transform = .identity + } + animator.startAnimation() + } +} + +private struct RangePresentation { + let range: HighlightedRange + let rects: [CGRect] +} diff --git a/Sources/Runestone/TextView/SearchAndReplace/UITextSearchingHelper.swift b/Sources/Runestone/TextView/SearchAndReplace/UITextSearchingHelper.swift index 9517ed2eb..14bb0fcc9 100644 --- a/Sources/Runestone/TextView/SearchAndReplace/UITextSearchingHelper.swift +++ b/Sources/Runestone/TextView/SearchAndReplace/UITextSearchingHelper.swift @@ -215,6 +215,14 @@ extension UITextSearchingHelper: UIFindInteractionDelegate { func findInteraction(_ interaction: UIFindInteraction, sessionFor view: UIView) -> UIFindSession? { UITextSearchingFindSession(searchableObject: self) } + + func findInteraction(_ interaction: UIFindInteraction, didBegin session: UIFindSession) { + _textView.isFindResultPresentationActive = true + } + + func findInteraction(_ interaction: UIFindInteraction, didEnd session: UIFindSession) { + _textView.isFindResultPresentationActive = false + } } private extension SearchQuery { diff --git a/Tests/RunestoneTests/UITextSearchingHelperTests.swift b/Tests/RunestoneTests/UITextSearchingHelperTests.swift index 743b3d774..03f5fd2ac 100644 --- a/Tests/RunestoneTests/UITextSearchingHelperTests.swift +++ b/Tests/RunestoneTests/UITextSearchingHelperTests.swift @@ -52,6 +52,31 @@ final class UITextSearchingHelperTests: XCTestCase { wait(for: [applied], timeout: 2) } + func testSearchDecorationPreservesPresentationRole() { + let theme = DefaultTheme() + let range = NSRange(location: 1, length: 2) + + XCTAssertEqual(theme.highlightedRange(forFoundTextRange: range, ofStyle: .found)?.presentationRole, + .foundSearchResult) + XCTAssertEqual(theme.highlightedRange(forFoundTextRange: range, ofStyle: .highlighted)?.presentationRole, + .selectedSearchResult) + XCTAssertEqual(HighlightedRange(range: range, color: .red).presentationRole, .standard) + } + + func testFindSessionControlsResultPresentation() { + let textView = TextView() + let helper = UITextSearchingHelper() + helper.textView = textView + let interaction = UIFindInteraction(sessionDelegate: helper) + let session = UIFindSession() + + helper.findInteraction(interaction, didBegin: session) + XCTAssertTrue(textView.isFindResultPresentationActive) + + helper.findInteraction(interaction, didEnd: session) + XCTAssertFalse(textView.isFindResultPresentationActive) + } + func testDocumentReplacementDiscardsPendingDecorations() { let textView = TextView() textView.text = "abcdef" From 41f5f837d4d6cabd8163f238b2517c75a79d0d0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20St=C3=B8vring?= Date: Wed, 4 Nov 2026 10:12:44 +0100 Subject: [PATCH 02/13] Refine find result rendering and scrolling --- .../TextView/Appearance/DefaultTheme.swift | 4 +- .../Runestone/TextView/Appearance/Theme.swift | 2 + .../TextView/Core/LayoutManager.swift | 5 + .../TextView/Core/TextInputView.swift | 8 +- .../FindResultPresentationView.swift | 166 ++++++++++-------- .../FindResultPresentationViewTests.swift | 67 +++++++ 6 files changed, 167 insertions(+), 85 deletions(-) create mode 100644 Tests/RunestoneTests/FindResultPresentationViewTests.swift diff --git a/Sources/Runestone/TextView/Appearance/DefaultTheme.swift b/Sources/Runestone/TextView/Appearance/DefaultTheme.swift index 8e64a67b2..00af0dbe2 100644 --- a/Sources/Runestone/TextView/Appearance/DefaultTheme.swift +++ b/Sources/Runestone/TextView/Appearance/DefaultTheme.swift @@ -79,13 +79,13 @@ public final class DefaultTheme: Runestone.Theme { let color = UIColor(themeColorNamed: "search_match_found") return HighlightedRange(range: foundTextRange, color: color, - cornerRadius: 2, + cornerRadius: 3, presentationRole: .foundSearchResult) case .highlighted: let color = UIColor(themeColorNamed: "search_match_highlighted") return HighlightedRange(range: foundTextRange, color: color, - cornerRadius: 2, + cornerRadius: 5, presentationRole: .selectedSearchResult) case .normal: return nil diff --git a/Sources/Runestone/TextView/Appearance/Theme.swift b/Sources/Runestone/TextView/Appearance/Theme.swift index 37b5ed050..fe7ffd2bb 100644 --- a/Sources/Runestone/TextView/Appearance/Theme.swift +++ b/Sources/Runestone/TextView/Appearance/Theme.swift @@ -108,10 +108,12 @@ public extension Theme { case .found: return HighlightedRange(range: foundTextRange, color: .systemYellow.withAlphaComponent(0.2), + cornerRadius: 3, presentationRole: .foundSearchResult) case .highlighted: return HighlightedRange(range: foundTextRange, color: .systemYellow, + cornerRadius: 5, presentationRole: .selectedSearchResult) case .normal: return nil diff --git a/Sources/Runestone/TextView/Core/LayoutManager.swift b/Sources/Runestone/TextView/Core/LayoutManager.swift index 65ab6621e..205f68286 100644 --- a/Sources/Runestone/TextView/Core/LayoutManager.swift +++ b/Sources/Runestone/TextView/Core/LayoutManager.swift @@ -293,6 +293,11 @@ final class LayoutManager { private var lineNumberLabelReuseQueue = ViewReuseQueue() private var visibleLineIDs: Set = [] private let linesContainerView = UIView() + func installFindResultPlateView(_ view: UIView) { + if view.superview !== linesContainerView { + linesContainerView.insertSubview(view, at: 0) + } + } var writingToolsHiddenRanges: [NSRange] = [] { didSet { updateWritingToolsMask() } } diff --git a/Sources/Runestone/TextView/Core/TextInputView.swift b/Sources/Runestone/TextView/Core/TextInputView.swift index 29c37ba3f..f10670949 100644 --- a/Sources/Runestone/TextView/Core/TextInputView.swift +++ b/Sources/Runestone/TextView/Core/TextInputView.swift @@ -717,7 +717,6 @@ final class TextInputView: UIView, UITextInput { layoutManager.setNeedsLayout() layoutManager.layoutIfNeeded() findResultPresentationView.update(highlightedRanges: newValue, - viewport: viewport, selectionRects: selectionRects(for:)) } } @@ -732,8 +731,8 @@ final class TextInputView: UIView, UITextInput { if findResultPresentationView.superview == nil { addSubview(findResultPresentationView) } + layoutManager.installFindResultPlateView(findResultPresentationView.selectedResultPlateView) findResultPresentationView.update(highlightedRanges: highlightedRanges, - viewport: viewport, selectionRects: selectionRects(for:)) } } @@ -1057,9 +1056,8 @@ final class TextInputView: UIView, UITextInput { writingToolsController?.layoutDidChange() if findResultPresentationView.isActive { bringSubviewToFront(findResultPresentationView) - findResultPresentationView.update(highlightedRanges: highlightedRanges, - viewport: viewport, - selectionRects: selectionRects(for:)) + findResultPresentationView.updateLayoutIfNeeded(highlightedRanges: highlightedRanges, + selectionRects: selectionRects(for:)) } // We notify the input delegate about selection changes in layoutSubviews so we have a chance of disabling notifying the input delegate during an editing operation. // We will sometimes disable notifying the input delegate when the user enters Korean text. diff --git a/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift index f80cdb8e4..3a2250e1e 100644 --- a/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift +++ b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift @@ -7,21 +7,23 @@ final class FindResultPresentationView: UIView { return } isHidden = !isActive + selectedResultPlateView.isHidden = !isActive if !isActive { - selectedResultContainer.removeFromSuperview() selectedRange = nil - currentViewport = .null + currentBounds = .null currentRanges = [] + cachedPresentations = [] } } } + let selectedResultPlateView = UIView() private weak var sourceView: UIView? private let dimmingLayer = CAShapeLayer() - private let selectedResultContainer = UIView() private var selectedRange: NSRange? - private var currentViewport = CGRect.null + private var currentBounds = CGRect.null private var currentRanges: [HighlightedRange] = [] + private var cachedPresentations: [RangePresentation] = [] init(sourceView: UIView) { self.sourceView = sourceView @@ -32,7 +34,8 @@ final class FindResultPresentationView: UIView { dimmingLayer.fillColor = UIColor.black.withAlphaComponent(0.22).cgColor dimmingLayer.fillRule = .evenOdd layer.addSublayer(dimmingLayer) - selectedResultContainer.isUserInteractionEnabled = false + selectedResultPlateView.isHidden = true + selectedResultPlateView.isUserInteractionEnabled = false } required init?(coder: NSCoder) { @@ -40,7 +43,6 @@ final class FindResultPresentationView: UIView { } func update(highlightedRanges: [HighlightedRange], - viewport: CGRect, selectionRects: (UITextRange) -> [UITextSelectionRect]) { guard isActive, let sourceView else { return @@ -48,31 +50,40 @@ final class FindResultPresentationView: UIView { let searchRanges = highlightedRanges.filter { $0.presentationRole != .standard } let selected = searchRanges.first { $0.presentationRole == .selectedSearchResult } let shouldAnimate = selectedRange != nil && selected?.range != selectedRange - let needsRebuild = currentViewport != viewport || currentRanges != searchRanges - guard needsRebuild else { + let boundsChanged = currentBounds != sourceView.bounds + let rangesChanged = currentRanges != searchRanges + guard boundsChanged || rangesChanged else { return } - currentViewport = viewport + let geometryChanged = boundsChanged || currentRanges.map(\.range) != searchRanges.map(\.range) + currentBounds = sourceView.bounds currentRanges = searchRanges - frame = viewport + frame = sourceView.bounds dimmingLayer.frame = bounds - let presentations = presentations(for: searchRanges, - sourceView: sourceView, - viewport: viewport, - selectionRects: selectionRects) - updateDimming(using: presentations) - selectedResultContainer.removeFromSuperview() - selectedResultContainer.subviews.forEach { $0.removeFromSuperview() } - if let selectedPresentation = presentations.first(where: { $0.range.presentationRole == .selectedSearchResult }) { - updateSelectedResult(using: selectedPresentation, sourceView: sourceView, viewport: viewport) - animateSelectedResult(shouldAnimate) + if geometryChanged { + cachedPresentations = presentations(for: searchRanges, + sourceView: sourceView, + selectionRects: selectionRects) + } else { + cachedPresentations = zip(searchRanges, cachedPresentations).map { range, presentation in + RangePresentation(range: range, rects: presentation.rects) + } } + updateDimming() + updateSelectedResultPlate(animated: shouldAnimate) selectedRange = selected?.range } + func updateLayoutIfNeeded(highlightedRanges: [HighlightedRange], + selectionRects: (UITextRange) -> [UITextSelectionRect]) { + guard sourceView?.bounds != currentBounds else { + return + } + update(highlightedRanges: highlightedRanges, selectionRects: selectionRects) + } + private func presentations(for ranges: [HighlightedRange], sourceView: UIView, - viewport: CGRect, selectionRects: (UITextRange) -> [UITextSelectionRect]) -> [RangePresentation] { guard let textInput = sourceView as? UITextInput else { return [] @@ -84,84 +95,83 @@ final class FindResultPresentationView: UIView { let textRange = textInput.textRange(from: start, to: end) else { return nil } - let rects = selectionRects(textRange).map { selectionRect in - selectionRect.rect.offsetBy(dx: -viewport.minX, dy: -viewport.minY) - } - return RangePresentation(range: highlightedRange, rects: rects) + return RangePresentation(range: highlightedRange, rects: selectionRects(textRange).map(\.rect)) } } - private func updateDimming(using presentations: [RangePresentation]) { + private func updateDimming() { let path = UIBezierPath(rect: bounds) - for presentation in presentations { - for rect in presentation.rects where !rect.isEmpty && rect.intersects(bounds) { - path.append(UIBezierPath(roundedRect: rect, cornerRadius: presentation.range.cornerRadius)) + for presentation in cachedPresentations { + for rect in displayRects(for: presentation) where !rect.isEmpty { + path.append(UIBezierPath(roundedRect: rect, + cornerRadius: cornerRadius(for: presentation.range))) } } dimmingLayer.path = path.cgPath } - private func updateSelectedResult(using presentation: RangePresentation, - sourceView: UIView, - viewport: CGRect) { - let visibleRects = presentation.rects.filter { !$0.isEmpty && $0.intersects(bounds) } - guard !visibleRects.isEmpty else { + private func updateSelectedResultPlate(animated: Bool) { + selectedResultPlateView.subviews.forEach { $0.removeFromSuperview() } + guard let presentation = cachedPresentations.first(where: { presentation in + presentation.range.presentationRole == .selectedSearchResult + }) else { + selectedResultPlateView.isHidden = true return } - addSubview(selectedResultContainer) - let union = visibleRects.reduce(CGRect.null) { $0.union($1) } - selectedResultContainer.frame = union - let presentationSuperview = superview - removeFromSuperview() - for rect in visibleRects { - addSelectedResultSnapshot(for: rect, - sourceView: sourceView, - viewport: viewport, - cornerRadius: presentation.range.cornerRadius, - union: union) - } - if let presentationSuperview { - presentationSuperview.addSubview(self) - } - } - - private func addSelectedResultSnapshot(for rect: CGRect, - sourceView: UIView, - viewport: CGRect, - cornerRadius: CGFloat, - union: CGRect) { - let sourceRect = rect.offsetBy(dx: viewport.minX, dy: viewport.minY) - guard let snapshot = sourceView.resizableSnapshotView(from: sourceRect, - afterScreenUpdates: true, - withCapInsets: .zero) else { + let rects = presentation.rects.filter { !$0.isEmpty }.map(selectedDisplayRect(for:)) + guard !rects.isEmpty else { + selectedResultPlateView.isHidden = true return } - let shadowView = UIView(frame: rect.offsetBy(dx: -union.minX, dy: -union.minY)) - shadowView.isUserInteractionEnabled = false - shadowView.layer.shadowColor = UIColor.black.cgColor - shadowView.layer.shadowOpacity = 0.22 - shadowView.layer.shadowRadius = 8 - shadowView.layer.shadowOffset = CGSize(width: 0, height: 3) - shadowView.layer.shadowPath = UIBezierPath(roundedRect: shadowView.bounds, cornerRadius: cornerRadius).cgPath - snapshot.frame = shadowView.bounds - snapshot.layer.cornerRadius = cornerRadius - snapshot.layer.cornerCurve = .continuous - snapshot.clipsToBounds = true - shadowView.addSubview(snapshot) - selectedResultContainer.addSubview(shadowView) + selectedResultPlateView.isHidden = false + let union = rects.reduce(CGRect.null) { $0.union($1) } + selectedResultPlateView.frame = union + for rect in rects { + let plate = UIView(frame: rect.offsetBy(dx: -union.minX, dy: -union.minY)) + plate.isUserInteractionEnabled = false + plate.backgroundColor = presentation.range.color + plate.layer.cornerRadius = Self.selectedCornerRadius + plate.layer.cornerCurve = .continuous + plate.layer.shadowColor = UIColor.black.cgColor + plate.layer.shadowOpacity = 0.22 + plate.layer.shadowRadius = 8 + plate.layer.shadowOffset = CGSize(width: 0, height: 3) + plate.layer.shadowPath = UIBezierPath(roundedRect: plate.bounds, + cornerRadius: Self.selectedCornerRadius).cgPath + selectedResultPlateView.addSubview(plate) + } + animateSelectedResultPlate(animated) } - private func animateSelectedResult(_ animated: Bool) { + private func animateSelectedResultPlate(_ animated: Bool) { guard animated, !UIAccessibility.isReduceMotionEnabled else { - selectedResultContainer.transform = .identity + selectedResultPlateView.transform = .identity return } - selectedResultContainer.transform = CGAffineTransform(scaleX: 1.2, y: 1.1) - let animator = UIViewPropertyAnimator(duration: 0.2, dampingRatio: 0.82) { - self.selectedResultContainer.transform = .identity + selectedResultPlateView.transform = CGAffineTransform(scaleX: 1.2, y: 1.1) + let animator = UIViewPropertyAnimator(duration: 0.18, dampingRatio: 0.86) { + self.selectedResultPlateView.transform = .identity } animator.startAnimation() } + + private func displayRects(for presentation: RangePresentation) -> [CGRect] { + presentation.range.presentationRole == .selectedSearchResult + ? presentation.rects.map(selectedDisplayRect(for:)) + : presentation.rects + } + + private func selectedDisplayRect(for sourceRect: CGRect) -> CGRect { + sourceRect.insetBy(dx: -Self.selectedHorizontalPadding, dy: -Self.selectedVerticalPadding) + } + + private func cornerRadius(for range: HighlightedRange) -> CGFloat { + range.presentationRole == .selectedSearchResult ? Self.selectedCornerRadius : range.cornerRadius + } + + private static let selectedHorizontalPadding: CGFloat = 4 + private static let selectedVerticalPadding: CGFloat = 3 + private static let selectedCornerRadius: CGFloat = 5 } private struct RangePresentation { diff --git a/Tests/RunestoneTests/FindResultPresentationViewTests.swift b/Tests/RunestoneTests/FindResultPresentationViewTests.swift new file mode 100644 index 000000000..b628bbadd --- /dev/null +++ b/Tests/RunestoneTests/FindResultPresentationViewTests.swift @@ -0,0 +1,67 @@ +@testable import Runestone +import UIKit +import XCTest + +final class FindResultPresentationViewTests: XCTestCase { + func testSelectedResultUsesExpandedRoundedPlateWithShapeShadow() throws { + let sourceView = UITextView(frame: CGRect(x: 0, y: 0, width: 320, height: 480)) + sourceView.text = "match" + let presentationView = FindResultPresentationView(sourceView: sourceView) + presentationView.isActive = true + let sourceRect = CGRect(x: 20, y: 30, width: 42, height: 20) + let range = HighlightedRange(range: NSRange(location: 0, length: 5), + color: .yellow, + cornerRadius: 5, + presentationRole: .selectedSearchResult) + + presentationView.update(highlightedRanges: [range]) { _ in + [TextSelectionRect(rect: sourceRect, writingDirection: .natural, + containsStart: true, containsEnd: true)] + } + + XCTAssertEqual(presentationView.selectedResultPlateView.frame, + sourceRect.insetBy(dx: -4, dy: -3)) + let plate = try XCTUnwrap(presentationView.selectedResultPlateView.subviews.first) + XCTAssertEqual(plate.backgroundColor, .yellow) + XCTAssertEqual(plate.layer.cornerRadius, 5) + XCTAssertEqual(plate.layer.shadowOpacity, 0.22) + XCTAssertNotNil(plate.layer.shadowPath) + } + + func testScrollLayoutAndSelectionChangesReuseCachedGeometryForManyResults() { + let resultCount = 500 + let sourceView = UITextView(frame: CGRect(x: 0, y: 0, width: 320, height: 2_000)) + sourceView.text = String(repeating: "x", count: resultCount) + let presentationView = FindResultPresentationView(sourceView: sourceView) + presentationView.isActive = true + var geometryCallCount = 0 + let selectionRects: (UITextRange) -> [UITextSelectionRect] = { _ in + geometryCallCount += 1 + return [TextSelectionRect(rect: CGRect(x: 10, y: 10, width: 8, height: 18), + writingDirection: .natural, containsStart: true, containsEnd: true)] + } + + presentationView.update(highlightedRanges: ranges(count: resultCount, selectedIndex: 0), + selectionRects: selectionRects) + XCTAssertEqual(geometryCallCount, resultCount) + + for _ in 0 ..< 100 { + presentationView.updateLayoutIfNeeded(highlightedRanges: ranges(count: resultCount, selectedIndex: 0), + selectionRects: selectionRects) + } + presentationView.update(highlightedRanges: ranges(count: resultCount, selectedIndex: 1), + selectionRects: selectionRects) + XCTAssertEqual(geometryCallCount, resultCount, + "Scrolling and moving between existing results must reuse cached text geometry") + } + + private func ranges(count: Int, selectedIndex: Int) -> [HighlightedRange] { + (0 ..< count).map { index in + HighlightedRange(id: "result-\(index)", + range: NSRange(location: index, length: 1), + color: index == selectedIndex ? .yellow : .white, + cornerRadius: 3, + presentationRole: index == selectedIndex ? .selectedSearchResult : .foundSearchResult) + } + } +} From 60c9b33266eca618182a36a6c824b1ffb65fd9a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20St=C3=B8vring?= Date: Wed, 4 Nov 2026 10:43:22 +0100 Subject: [PATCH 03/13] Optimize navigation through large find result sets --- .../TextView/Highlight/HighlightService.swift | 53 ++++++-- .../FindResultPerformanceTests.swift | 128 ++++++++++++++++++ 2 files changed, 171 insertions(+), 10 deletions(-) create mode 100644 Tests/RunestoneTests/FindResultPerformanceTests.swift diff --git a/Sources/Runestone/TextView/Highlight/HighlightService.swift b/Sources/Runestone/TextView/Highlight/HighlightService.swift index e9885a080..3c4b8fc4d 100644 --- a/Sources/Runestone/TextView/Highlight/HighlightService.swift +++ b/Sources/Runestone/TextView/Highlight/HighlightService.swift @@ -11,7 +11,11 @@ final class HighlightService { var highlightedRanges: [HighlightedRange] = [] { didSet { if highlightedRanges != oldValue { - invalidateHighlightedRangeFragments() + if hasUnchangedRangeGeometry(comparedTo: oldValue) { + updateHighlightedRangeFragments(changedFrom: oldValue) + } else { + invalidateHighlightedRangeFragments() + } } } } @@ -35,6 +39,33 @@ final class HighlightService { } private extension HighlightService { + private func hasUnchangedRangeGeometry(comparedTo oldRanges: [HighlightedRange]) -> Bool { + highlightedRanges.count == oldRanges.count + && zip(highlightedRanges, oldRanges).allSatisfy { $0.range == $1.range } + } + + private func updateHighlightedRangeFragments(changedFrom oldRanges: [HighlightedRange]) { + let changedRanges = zip(highlightedRanges, oldRanges).compactMap { newRange, oldRange in + newRange == oldRange ? nil : newRange.range + } + let affectedLines = Dictionary(changedRanges + .flatMap(lineManager.lines(in:)) + .map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) + guard !affectedLines.isEmpty else { + return + } + highlightedRangeFragmentsPerLineFragment.removeAll() + for line in affectedLines.values { + let lineRange = NSRange(location: line.location, length: line.data.totalLength) + highlightedRangeFragmentsPerLine[line.id] = highlightedRanges.compactMap { highlightedRange in + guard highlightedRange.range.length > 0, highlightedRange.range.overlaps(lineRange) else { + return nil + } + return makeHighlightedRangeFragment(for: highlightedRange, in: lineRange) + } + } + } + private func invalidateHighlightedRangeFragments() { highlightedRangeFragmentsPerLine.removeAll() highlightedRangeFragmentsPerLineFragment.removeAll() @@ -50,15 +81,7 @@ private extension HighlightService { guard highlightedRange.range.overlaps(lineRange) else { continue } - let cappedRange = highlightedRange.range.capped(to: lineRange) - let cappedLocalRange = cappedRange.local(to: lineRange) - let containsStart = cappedRange.lowerBound == highlightedRange.range.lowerBound - let containsEnd = cappedRange.upperBound == highlightedRange.range.upperBound - let highlightedRangeFragment = HighlightedRangeFragment(range: cappedLocalRange, - containsStart: containsStart, - containsEnd: containsEnd, - color: highlightedRange.color, - cornerRadius: highlightedRange.cornerRadius) + let highlightedRangeFragment = makeHighlightedRangeFragment(for: highlightedRange, in: lineRange) if let existingHighlightedRangeFragments = result[line.id] { result[line.id] = existingHighlightedRangeFragments + [highlightedRangeFragment] } else { @@ -69,6 +92,16 @@ private extension HighlightService { return result } + private func makeHighlightedRangeFragment(for highlightedRange: HighlightedRange, + in lineRange: NSRange) -> HighlightedRangeFragment { + let cappedRange = highlightedRange.range.capped(to: lineRange) + return HighlightedRangeFragment(range: cappedRange.local(to: lineRange), + containsStart: cappedRange.lowerBound == highlightedRange.range.lowerBound, + containsEnd: cappedRange.upperBound == highlightedRange.range.upperBound, + color: highlightedRange.color, + cornerRadius: highlightedRange.cornerRadius) + } + private func createHighlightedLineFragments(for lineFragment: LineFragment, inLineWithID lineID: DocumentLineNodeID) -> [HighlightedRangeFragment] { guard let lineHighlightedRangeFragments = highlightedRangeFragmentsPerLine[lineID] else { diff --git a/Tests/RunestoneTests/FindResultPerformanceTests.swift b/Tests/RunestoneTests/FindResultPerformanceTests.swift new file mode 100644 index 000000000..ffc9d2403 --- /dev/null +++ b/Tests/RunestoneTests/FindResultPerformanceTests.swift @@ -0,0 +1,128 @@ +@testable import Runestone +import UIKit +import XCTest + +@MainActor +final class FindResultPerformanceTests: XCTestCase { + func testThousandMatchesRemainResponsive() throws { + try XCTSkipUnless(ProcessInfo.processInfo.environment["RUNESTONE_PERFORMANCE"] == "1") + let view = TextView(frame: CGRect(x: 0, y: 0, width: 390, height: 700)) + view.contentInsetAdjustmentBehavior = .never + view.text = (0 ..< 1_000).map { "postId: \($0)" }.joined(separator: "\n") + let controller = UIViewController() + controller.view = view + let window = UIWindow(frame: view.frame) + window.rootViewController = controller + window.makeKeyAndVisible() + defer { window.isHidden = true } + view.layoutIfNeeded() + + let ranges = matches(of: "post", in: view.text) + let applyStart = CACurrentMediaTime() + var highlights = ranges.enumerated().map { index, range in + highlight(range, selected: index == 0) + } + view.isFindResultPresentationActive = true + view.highlightedRanges = highlights + view.layoutIfNeeded() + report(phase: "apply-1000-matches", milliseconds: (CACurrentMediaTime() - applyStart) * 1_000) + + let cycleStart = CACurrentMediaTime() + for selectedIndex in 1 ... 100 { + highlights[selectedIndex - 1] = highlight(ranges[selectedIndex - 1], selected: false) + highlights[selectedIndex] = highlight(ranges[selectedIndex], selected: true) + view.highlightedRanges = highlights + view.scrollRangeToVisible(ranges[selectedIndex]) + } + report(phase: "cycle-100-matches", milliseconds: (CACurrentMediaTime() - cycleStart) * 1_000) + + let finished = expectation(description: "Scroll with 1,000 matches") + let driver = FindResultScrollDriver(view: view) { finished.fulfill() } + driver.start() + wait(for: [finished], timeout: 15) + driver.stop() + report(phase: "scroll-frame-work", samples: driver.work) + report(phase: "scroll-frame-interval", samples: driver.intervals, + extra: ["over25ms": driver.intervals.filter { $0 > 25 }.count, + "over50ms": driver.intervals.filter { $0 > 50 }.count]) + XCTAssertEqual(driver.completedFrames, driver.frameCount) + } + + private func matches(of query: String, in text: String) -> [NSRange] { + let expression = try! NSRegularExpression(pattern: NSRegularExpression.escapedPattern(for: query)) + return expression.matches(in: text, range: NSRange(location: 0, length: text.utf16.count)).map(\.range) + } + + private func highlight(_ range: NSRange, selected: Bool) -> HighlightedRange { + HighlightedRange(range: range, color: selected ? .systemYellow : .systemYellow.withAlphaComponent(0.2), + cornerRadius: selected ? 5 : 3, + presentationRole: selected ? .selectedSearchResult : .foundSearchResult) + } + + private func report(phase: String, milliseconds: Double) { + report(phase: phase, samples: [milliseconds]) + } + + private func report(phase: String, samples: [Double], extra: [String: Any] = [:]) { + let sorted = samples.sorted() + var result = extra + result["phase"] = phase + result["sampleCount"] = samples.count + result["meanMs"] = samples.reduce(0, +) / Double(max(1, samples.count)) + result["maxMs"] = sorted.last ?? 0 + result["p95Ms"] = sorted.isEmpty ? 0 : sorted[min(sorted.count - 1, Int(ceil(Double(sorted.count) * 0.95)) - 1)] + let data = try! JSONSerialization.data(withJSONObject: result, options: [.sortedKeys]) + let attachment = XCTAttachment(data: data, uniformTypeIdentifier: "public.json") + attachment.name = phase + attachment.lifetime = .keepAlways + add(attachment) + print("RUNESTONE_FIND_PERFORMANCE \(String(decoding: data, as: UTF8.self))") + } +} + +@MainActor +private final class FindResultScrollDriver: NSObject { + let frameCount = 180 + private(set) var completedFrames = 0 + private(set) var work: [Double] = [] + private(set) var intervals: [Double] = [] + private let view: TextView + private let completion: () -> Void + private var displayLink: CADisplayLink? + private var previousTimestamp: CFTimeInterval? + + init(view: TextView, completion: @escaping () -> Void) { + self.view = view + self.completion = completion + } + + func start() { + let displayLink = CADisplayLink(target: self, selector: #selector(tick)) + displayLink.preferredFramesPerSecond = 60 + self.displayLink = displayLink + displayLink.add(to: .main, forMode: .common) + } + + func stop() { + displayLink?.invalidate() + displayLink = nil + } + + @objc private func tick() { + let start = CACurrentMediaTime() + if let previousTimestamp { + intervals.append((start - previousTimestamp) * 1_000) + } + previousTimestamp = start + let direction: CGFloat = completedFrames < frameCount / 2 ? 90 : -90 + let maximumOffset = max(0, view.contentSize.height - view.bounds.height) + view.contentOffset.y = min(maximumOffset, max(0, view.contentOffset.y + direction)) + view.layoutIfNeeded() + work.append((CACurrentMediaTime() - start) * 1_000) + completedFrames += 1 + if completedFrames == frameCount { + stop() + completion() + } + } +} From e6ed1390657f6beb6c398cfd1ac1c3a31fc815a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20St=C3=B8vring?= Date: Wed, 4 Nov 2026 10:49:32 +0100 Subject: [PATCH 04/13] Measure large find query matching --- Tests/RunestoneTests/FindResultPerformanceTests.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Tests/RunestoneTests/FindResultPerformanceTests.swift b/Tests/RunestoneTests/FindResultPerformanceTests.swift index ffc9d2403..e0e144938 100644 --- a/Tests/RunestoneTests/FindResultPerformanceTests.swift +++ b/Tests/RunestoneTests/FindResultPerformanceTests.swift @@ -17,7 +17,9 @@ final class FindResultPerformanceTests: XCTestCase { defer { window.isHidden = true } view.layoutIfNeeded() + let searchStart = CACurrentMediaTime() let ranges = matches(of: "post", in: view.text) + report(phase: "search-1000-matches", milliseconds: (CACurrentMediaTime() - searchStart) * 1_000) let applyStart = CACurrentMediaTime() var highlights = ranges.enumerated().map { index, range in highlight(range, selected: index == 0) From e4a14025249494ba3fcd506a64b7a004d1c80713 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20St=C3=B8vring?= Date: Wed, 4 Nov 2026 10:57:40 +0100 Subject: [PATCH 05/13] Fix SwiftLint violations in find benchmark --- .../TextView/Highlight/HighlightService.swift | 2 +- .../RunestoneTests/FindResultPerformanceTests.swift | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/Sources/Runestone/TextView/Highlight/HighlightService.swift b/Sources/Runestone/TextView/Highlight/HighlightService.swift index 3c4b8fc4d..1623cfe65 100644 --- a/Sources/Runestone/TextView/Highlight/HighlightService.swift +++ b/Sources/Runestone/TextView/Highlight/HighlightService.swift @@ -50,7 +50,7 @@ private extension HighlightService { } let affectedLines = Dictionary(changedRanges .flatMap(lineManager.lines(in:)) - .map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first }) + .map { ($0.id, $0) }) { first, _ in first } guard !affectedLines.isEmpty else { return } diff --git a/Tests/RunestoneTests/FindResultPerformanceTests.swift b/Tests/RunestoneTests/FindResultPerformanceTests.swift index e0e144938..3447ab868 100644 --- a/Tests/RunestoneTests/FindResultPerformanceTests.swift +++ b/Tests/RunestoneTests/FindResultPerformanceTests.swift @@ -51,7 +51,10 @@ final class FindResultPerformanceTests: XCTestCase { } private func matches(of query: String, in text: String) -> [NSRange] { - let expression = try! NSRegularExpression(pattern: NSRegularExpression.escapedPattern(for: query)) + guard let expression = try? NSRegularExpression(pattern: NSRegularExpression.escapedPattern(for: query)) else { + XCTFail("Unable to create search expression") + return [] + } return expression.matches(in: text, range: NSRange(location: 0, length: text.utf16.count)).map(\.range) } @@ -73,12 +76,16 @@ final class FindResultPerformanceTests: XCTestCase { result["meanMs"] = samples.reduce(0, +) / Double(max(1, samples.count)) result["maxMs"] = sorted.last ?? 0 result["p95Ms"] = sorted.isEmpty ? 0 : sorted[min(sorted.count - 1, Int(ceil(Double(sorted.count) * 0.95)) - 1)] - let data = try! JSONSerialization.data(withJSONObject: result, options: [.sortedKeys]) + guard let data = try? JSONSerialization.data(withJSONObject: result, options: [.sortedKeys]), + let message = String(bytes: data, encoding: .utf8) else { + XCTFail("Unable to encode performance result") + return + } let attachment = XCTAttachment(data: data, uniformTypeIdentifier: "public.json") attachment.name = phase attachment.lifetime = .keepAlways add(attachment) - print("RUNESTONE_FIND_PERFORMANCE \(String(decoding: data, as: UTF8.self))") + print("RUNESTONE_FIND_PERFORMANCE \(message)") } } From 33807bdbd4d7c087b22b353828459b68c9fa1286 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20St=C3=B8vring?= Date: Wed, 4 Nov 2026 11:14:46 +0100 Subject: [PATCH 06/13] Make find result presentation opt in --- .../TextView/Core/TextInputView.swift | 33 +++++++++++++------ .../Runestone/TextView/Core/TextView.swift | 18 ++++++++-- .../UITextSearchingHelperTests.swift | 13 ++++++++ 3 files changed, 51 insertions(+), 13 deletions(-) diff --git a/Sources/Runestone/TextView/Core/TextInputView.swift b/Sources/Runestone/TextView/Core/TextInputView.swift index f10670949..868f4cda7 100644 --- a/Sources/Runestone/TextView/Core/TextInputView.swift +++ b/Sources/Runestone/TextView/Core/TextInputView.swift @@ -721,21 +721,34 @@ final class TextInputView: UIView, UITextInput { } } } + var isFindResultPresentationEnabled = false { + didSet { + updateFindResultPresentation() + } + } var isFindResultPresentationActive: Bool { get { - findResultPresentationView.isActive + isFindResultPresentationRequested } set { - findResultPresentationView.isActive = newValue - if newValue { - if findResultPresentationView.superview == nil { - addSubview(findResultPresentationView) - } - layoutManager.installFindResultPlateView(findResultPresentationView.selectedResultPlateView) - findResultPresentationView.update(highlightedRanges: highlightedRanges, - selectionRects: selectionRects(for:)) - } + isFindResultPresentationRequested = newValue + updateFindResultPresentation() + } + } + private var isFindResultPresentationRequested = false + + private func updateFindResultPresentation() { + let isActive = isFindResultPresentationEnabled && isFindResultPresentationRequested + findResultPresentationView.isActive = isActive + guard isActive else { + return + } + if findResultPresentationView.superview == nil { + addSubview(findResultPresentationView) } + layoutManager.installFindResultPlateView(findResultPresentationView.selectedResultPlateView) + findResultPresentationView.update(highlightedRanges: highlightedRanges, + selectionRects: selectionRects(for:)) } // MARK: - Contents diff --git a/Sources/Runestone/TextView/Core/TextView.swift b/Sources/Runestone/TextView/Core/TextView.swift index 9cf9884a9..9cc643597 100644 --- a/Sources/Runestone/TextView/Core/TextView.swift +++ b/Sources/Runestone/TextView/Core/TextView.swift @@ -683,10 +683,22 @@ open class TextView: UIScrollView { highlightNavigationController.highlightedRanges = newValue } } - /// Whether search results are presented above dimmed editor content. + /// Whether search results may be presented above dimmed editor content. /// - /// Enable this while a custom find interaction is active. Runestone manages - /// this property automatically for its built-in find interaction. + /// Defaults to `false`. Enable this to use Runestone's dimming and selected-result + /// animation with either the built-in or a custom find interaction. + public var isFindResultPresentationEnabled: Bool { + get { + textInputView.isFindResultPresentationEnabled + } + set { + textInputView.isFindResultPresentationEnabled = newValue + } + } + /// Whether a find interaction currently requests result presentation. + /// + /// Runestone manages this property automatically for its built-in find interaction. + /// Custom find interactions should update it when their session begins and ends. public var isFindResultPresentationActive: Bool { get { textInputView.isFindResultPresentationActive diff --git a/Tests/RunestoneTests/UITextSearchingHelperTests.swift b/Tests/RunestoneTests/UITextSearchingHelperTests.swift index 03f5fd2ac..c883f1818 100644 --- a/Tests/RunestoneTests/UITextSearchingHelperTests.swift +++ b/Tests/RunestoneTests/UITextSearchingHelperTests.swift @@ -65,6 +65,7 @@ final class UITextSearchingHelperTests: XCTestCase { func testFindSessionControlsResultPresentation() { let textView = TextView() + textView.isFindResultPresentationEnabled = true let helper = UITextSearchingHelper() helper.textView = textView let interaction = UIFindInteraction(sessionDelegate: helper) @@ -77,6 +78,18 @@ final class UITextSearchingHelperTests: XCTestCase { XCTAssertFalse(textView.isFindResultPresentationActive) } + func testFindResultPresentationIsOptIn() { + let textView = TextView() + let helper = UITextSearchingHelper() + helper.textView = textView + let interaction = UIFindInteraction(sessionDelegate: helper) + + helper.findInteraction(interaction, didBegin: UIFindSession()) + + XCTAssertTrue(textView.isFindResultPresentationActive) + XCTAssertFalse(textView.isFindResultPresentationEnabled) + } + func testDocumentReplacementDiscardsPendingDecorations() { let textView = TextView() textView.text = "abcdef" From 2954f725035ada6e0122ed8c5cce28c256a4f3ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20St=C3=B8vring?= Date: Wed, 4 Nov 2026 11:21:01 +0100 Subject: [PATCH 07/13] Animate the selected find result plate --- .../FindResultPresentationView.swift | 22 ++++++++++++++----- .../FindResultPresentationViewTests.swift | 22 +++++++++++++++++++ 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift index 3a2250e1e..bb4007ba2 100644 --- a/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift +++ b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift @@ -107,7 +107,10 @@ final class FindResultPresentationView: UIView { cornerRadius: cornerRadius(for: presentation.range))) } } + CATransaction.begin() + CATransaction.setDisableActions(true) dimmingLayer.path = path.cgPath + CATransaction.commit() } private func updateSelectedResultPlate(animated: Bool) { @@ -144,15 +147,21 @@ final class FindResultPresentationView: UIView { } private func animateSelectedResultPlate(_ animated: Bool) { + selectedResultPlateView.layer.removeAnimation(forKey: Self.bounceAnimationKey) + selectedResultPlateView.transform = .identity guard animated, !UIAccessibility.isReduceMotionEnabled else { - selectedResultPlateView.transform = .identity return } - selectedResultPlateView.transform = CGAffineTransform(scaleX: 1.2, y: 1.1) - let animator = UIViewPropertyAnimator(duration: 0.18, dampingRatio: 0.86) { - self.selectedResultPlateView.transform = .identity - } - animator.startAnimation() + let animation = CAKeyframeAnimation(keyPath: "transform.scale") + animation.values = [1, 1.13, 0.985, 1] + animation.keyTimes = [0, 0.38, 0.76, 1] + animation.timingFunctions = [ + CAMediaTimingFunction(name: .easeOut), + CAMediaTimingFunction(name: .easeInEaseOut), + CAMediaTimingFunction(name: .easeOut) + ] + animation.duration = 0.24 + selectedResultPlateView.layer.add(animation, forKey: Self.bounceAnimationKey) } private func displayRects(for presentation: RangePresentation) -> [CGRect] { @@ -172,6 +181,7 @@ final class FindResultPresentationView: UIView { private static let selectedHorizontalPadding: CGFloat = 4 private static let selectedVerticalPadding: CGFloat = 3 private static let selectedCornerRadius: CGFloat = 5 + static let bounceAnimationKey = "find-result-bounce" } private struct RangePresentation { diff --git a/Tests/RunestoneTests/FindResultPresentationViewTests.swift b/Tests/RunestoneTests/FindResultPresentationViewTests.swift index b628bbadd..452380eb1 100644 --- a/Tests/RunestoneTests/FindResultPresentationViewTests.swift +++ b/Tests/RunestoneTests/FindResultPresentationViewTests.swift @@ -55,6 +55,28 @@ final class FindResultPresentationViewTests: XCTestCase { "Scrolling and moving between existing results must reuse cached text geometry") } + func testChangingSelectionAnimatesThePlateItself() { + let sourceView = UITextView(frame: CGRect(x: 0, y: 0, width: 320, height: 480)) + sourceView.text = "xx" + let presentationView = FindResultPresentationView(sourceView: sourceView) + presentationView.isActive = true + let selectionRects: (UITextRange) -> [UITextSelectionRect] = { range in + let x = range.start == sourceView.beginningOfDocument ? 10.0 : 30.0 + return [TextSelectionRect(rect: CGRect(x: x, y: 10, width: 10, height: 18), + writingDirection: .natural, containsStart: true, containsEnd: true)] + } + + presentationView.update(highlightedRanges: ranges(count: 2, selectedIndex: 0), + selectionRects: selectionRects) + presentationView.update(highlightedRanges: ranges(count: 2, selectedIndex: 1), + selectionRects: selectionRects) + + XCTAssertNotNil(presentationView.selectedResultPlateView.layer.animation( + forKey: FindResultPresentationView.bounceAnimationKey + )) + XCTAssertEqual(presentationView.selectedResultPlateView.transform, .identity) + } + private func ranges(count: Int, selectedIndex: Int) -> [HighlightedRange] { (0 ..< count).map { index in HighlightedRange(id: "result-\(index)", From 1e71149ad973b147684e4498dbf6cccd480dc861 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20St=C3=B8vring?= Date: Wed, 4 Nov 2026 11:26:53 +0100 Subject: [PATCH 08/13] Animate the visible find result fill --- .../Runestone/TextView/Core/TextInputView.swift | 3 +++ .../TextView/Highlight/HighlightService.swift | 16 ++++++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/Sources/Runestone/TextView/Core/TextInputView.swift b/Sources/Runestone/TextView/Core/TextInputView.swift index 868f4cda7..d34ca50c7 100644 --- a/Sources/Runestone/TextView/Core/TextInputView.swift +++ b/Sources/Runestone/TextView/Core/TextInputView.swift @@ -740,6 +740,9 @@ final class TextInputView: UIView, UITextInput { private func updateFindResultPresentation() { let isActive = isFindResultPresentationEnabled && isFindResultPresentationRequested findResultPresentationView.isActive = isActive + highlightService.isFindResultPresentationActive = isActive + layoutManager.setNeedsLayout() + layoutManager.layoutIfNeeded() guard isActive else { return } diff --git a/Sources/Runestone/TextView/Highlight/HighlightService.swift b/Sources/Runestone/TextView/Highlight/HighlightService.swift index 1623cfe65..3f05b1f29 100644 --- a/Sources/Runestone/TextView/Highlight/HighlightService.swift +++ b/Sources/Runestone/TextView/Highlight/HighlightService.swift @@ -19,6 +19,13 @@ final class HighlightService { } } } + var isFindResultPresentationActive = false { + didSet { + if isFindResultPresentationActive != oldValue { + invalidateHighlightedRangeFragments() + } + } + } private var highlightedRangeFragmentsPerLine: [DocumentLineNodeID: [HighlightedRangeFragment]] = [:] private var highlightedRangeFragmentsPerLineFragment: [LineFragmentID: [HighlightedRangeFragment]] = [:] @@ -58,7 +65,7 @@ private extension HighlightService { for line in affectedLines.values { let lineRange = NSRange(location: line.location, length: line.data.totalLength) highlightedRangeFragmentsPerLine[line.id] = highlightedRanges.compactMap { highlightedRange in - guard highlightedRange.range.length > 0, highlightedRange.range.overlaps(lineRange) else { + guard shouldRender(highlightedRange), highlightedRange.range.overlaps(lineRange) else { return nil } return makeHighlightedRangeFragment(for: highlightedRange, in: lineRange) @@ -74,7 +81,7 @@ private extension HighlightService { private func createHighlightedRangeFragmentsPerLine() -> [DocumentLineNodeID: [HighlightedRangeFragment]] { var result: [DocumentLineNodeID: [HighlightedRangeFragment]] = [:] - for highlightedRange in highlightedRanges where highlightedRange.range.length > 0 { + for highlightedRange in highlightedRanges where shouldRender(highlightedRange) { let lines = lineManager.lines(in: highlightedRange.range) for line in lines { let lineRange = NSRange(location: line.location, length: line.data.totalLength) @@ -102,6 +109,11 @@ private extension HighlightService { cornerRadius: highlightedRange.cornerRadius) } + private func shouldRender(_ highlightedRange: HighlightedRange) -> Bool { + highlightedRange.range.length > 0 + && (!isFindResultPresentationActive || highlightedRange.presentationRole != .selectedSearchResult) + } + private func createHighlightedLineFragments(for lineFragment: LineFragment, inLineWithID lineID: DocumentLineNodeID) -> [HighlightedRangeFragment] { guard let lineHighlightedRangeFragments = highlightedRangeFragmentsPerLine[lineID] else { From 1f6e6d34e56719cf630b37320f3be8daa77ba604 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20St=C3=B8vring?= Date: Wed, 4 Nov 2026 11:30:37 +0100 Subject: [PATCH 09/13] Keep find bounce alive during scrolling --- .../FindResultPresentationView.swift | 7 ++++- .../FindResultPresentationViewTests.swift | 26 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift index bb4007ba2..4654c0951 100644 --- a/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift +++ b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift @@ -9,6 +9,8 @@ final class FindResultPresentationView: UIView { isHidden = !isActive selectedResultPlateView.isHidden = !isActive if !isActive { + selectedResultPlateView.layer.removeAnimation(forKey: Self.bounceAnimationKey) + selectedResultPlateView.transform = .identity selectedRange = nil currentBounds = .null currentRanges = [] @@ -147,9 +149,12 @@ final class FindResultPresentationView: UIView { } private func animateSelectedResultPlate(_ animated: Bool) { + guard animated else { + return + } selectedResultPlateView.layer.removeAnimation(forKey: Self.bounceAnimationKey) selectedResultPlateView.transform = .identity - guard animated, !UIAccessibility.isReduceMotionEnabled else { + guard !UIAccessibility.isReduceMotionEnabled else { return } let animation = CAKeyframeAnimation(keyPath: "transform.scale") diff --git a/Tests/RunestoneTests/FindResultPresentationViewTests.swift b/Tests/RunestoneTests/FindResultPresentationViewTests.swift index 452380eb1..dedd63d7f 100644 --- a/Tests/RunestoneTests/FindResultPresentationViewTests.swift +++ b/Tests/RunestoneTests/FindResultPresentationViewTests.swift @@ -77,6 +77,32 @@ final class FindResultPresentationViewTests: XCTestCase { XCTAssertEqual(presentationView.selectedResultPlateView.transform, .identity) } + func testFollowUpLayoutDoesNotCancelSelectionAnimation() { + let sourceView = UITextView(frame: CGRect(x: 0, y: 0, width: 320, height: 480)) + sourceView.text = "xx" + let presentationView = FindResultPresentationView(sourceView: sourceView) + presentationView.isActive = true + let selectionRects: (UITextRange) -> [UITextSelectionRect] = { _ in + [TextSelectionRect(rect: CGRect(x: 10, y: 10, width: 10, height: 18), + writingDirection: .natural, containsStart: true, containsEnd: true)] + } + presentationView.update(highlightedRanges: ranges(count: 2, selectedIndex: 0), + selectionRects: selectionRects) + presentationView.update(highlightedRanges: ranges(count: 2, selectedIndex: 1), + selectionRects: selectionRects) + XCTAssertNotNil(presentationView.selectedResultPlateView.layer.animation( + forKey: FindResultPresentationView.bounceAnimationKey + )) + + sourceView.bounds.origin.y = 20 + presentationView.updateLayoutIfNeeded(highlightedRanges: ranges(count: 2, selectedIndex: 1), + selectionRects: selectionRects) + + XCTAssertNotNil(presentationView.selectedResultPlateView.layer.animation( + forKey: FindResultPresentationView.bounceAnimationKey + )) + } + private func ranges(count: Int, selectedIndex: Int) -> [HighlightedRange] { (0 ..< count).map { index in HighlightedRange(id: "result-\(index)", From 962f0bdf27f356927cc403f8750f9a36d38d2818 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20St=C3=B8vring?= Date: Wed, 4 Nov 2026 11:39:05 +0100 Subject: [PATCH 10/13] Render selected find result as one overlay --- .../TextView/Core/LayoutManager.swift | 35 ++++++++++++++--- .../TextView/Core/TextInputView.swift | 5 ++- .../TextView/Highlight/HighlightService.swift | 16 ++++++++ .../LineFragmentController.swift | 11 ++++++ .../LineController/LineFragmentRenderer.swift | 16 +++++++- .../FindResultPresentationView.swift | 38 +++++++++++++++++++ 6 files changed, 114 insertions(+), 7 deletions(-) diff --git a/Sources/Runestone/TextView/Core/LayoutManager.swift b/Sources/Runestone/TextView/Core/LayoutManager.swift index 205f68286..056fd3668 100644 --- a/Sources/Runestone/TextView/Core/LayoutManager.swift +++ b/Sources/Runestone/TextView/Core/LayoutManager.swift @@ -293,11 +293,6 @@ final class LayoutManager { private var lineNumberLabelReuseQueue = ViewReuseQueue() private var visibleLineIDs: Set = [] private let linesContainerView = UIView() - func installFindResultPlateView(_ view: UIView) { - if view.superview !== linesContainerView { - linesContainerView.insertSubview(view, at: 0) - } - } var writingToolsHiddenRanges: [NSRange] = [] { didSet { updateWritingToolsMask() } } @@ -671,6 +666,10 @@ extension LayoutManager { updateSpelling(on: lineFragmentController, lineLocation: line.location) lineFragmentController.highlightedRangeFragments = highlightService.highlightedRangeFragments(for: lineFragment, inLineWithID: line.id) + lineFragmentController.hiddenTextRanges = highlightService.hiddenTextRanges( + for: lineFragment, + inLineRange: NSRange(location: line.location, length: line.data.totalLength) + ) layoutLineFragmentView(for: lineFragmentController, lineLocation: line.location, lineYPosition: lineYPosition, @@ -861,6 +860,32 @@ private extension LayoutManager { // MARK: - Spelling geometry extension LayoutManager { + func selectedResultTextSegments(for range: NSRange) -> [SelectedResultTextSegment] { + lineFragmentViewReuseQueue.visibleViews.values.flatMap { view -> [SelectedResultTextSegment] in + guard let renderer = view.renderer else { + return [] + } + let fragmentRange = renderer.lineFragment.visibleRange + let documentRange = NSRange(location: view.documentLineLocation + fragmentRange.location, + length: fragmentRange.length) + let intersection = NSIntersectionRange(documentRange, range) + guard intersection.length > 0 else { + return [] + } + let localRange = NSRange(location: intersection.location - view.documentLineLocation, + length: intersection.length) + return renderer.spellingUnderlineSegments(in: localRange).map { horizontalRange in + let frame = CGRect(x: view.frame.minX + horizontalRange.lowerBound, + y: view.frame.minY, + width: horizontalRange.upperBound - horizontalRange.lowerBound, + height: view.frame.height) + return SelectedResultTextSegment(frame: frame, + horizontalOffset: horizontalRange.lowerBound, + renderer: renderer) + } + } + } + /// Visible word rectangles in text input coordinates, split at wrapping and bidirectional run boundaries. func spellingRects(for range: NSRange) -> [CGRect] { guard range.location >= 0, range.location <= stringView.string.length, diff --git a/Sources/Runestone/TextView/Core/TextInputView.swift b/Sources/Runestone/TextView/Core/TextInputView.swift index d34ca50c7..b18c3d0e4 100644 --- a/Sources/Runestone/TextView/Core/TextInputView.swift +++ b/Sources/Runestone/TextView/Core/TextInputView.swift @@ -749,11 +749,14 @@ final class TextInputView: UIView, UITextInput { if findResultPresentationView.superview == nil { addSubview(findResultPresentationView) } - layoutManager.installFindResultPlateView(findResultPresentationView.selectedResultPlateView) findResultPresentationView.update(highlightedRanges: highlightedRanges, selectionRects: selectionRects(for:)) } + func selectedResultTextSegments(for range: NSRange) -> [SelectedResultTextSegment] { + layoutManager.selectedResultTextSegments(for: range) + } + // MARK: - Contents weak var delegate: TextInputViewDelegate? var string: NSString { diff --git a/Sources/Runestone/TextView/Highlight/HighlightService.swift b/Sources/Runestone/TextView/Highlight/HighlightService.swift index 3f05b1f29..620a58b45 100644 --- a/Sources/Runestone/TextView/Highlight/HighlightService.swift +++ b/Sources/Runestone/TextView/Highlight/HighlightService.swift @@ -43,6 +43,22 @@ final class HighlightService { return highlightedLineFragments } } + + func hiddenTextRanges(for lineFragment: LineFragment, inLineRange lineRange: NSRange) -> [NSRange] { + guard isFindResultPresentationActive, + let selectedRange = highlightedRanges.first(where: { highlightedRange in + highlightedRange.presentationRole == .selectedSearchResult + })?.range else { + return [] + } + let intersection = NSIntersectionRange(selectedRange, lineRange) + guard intersection.length > 0 else { + return [] + } + let localRange = intersection.local(to: lineRange) + let fragmentIntersection = NSIntersectionRange(localRange, lineFragment.visibleRange) + return fragmentIntersection.length > 0 ? [fragmentIntersection] : [] + } } private extension HighlightService { diff --git a/Sources/Runestone/TextView/LineController/LineFragmentController.swift b/Sources/Runestone/TextView/LineController/LineFragmentController.swift index a0944b3e7..fa9e92138 100644 --- a/Sources/Runestone/TextView/LineController/LineFragmentController.swift +++ b/Sources/Runestone/TextView/LineController/LineFragmentController.swift @@ -65,6 +65,17 @@ final class LineFragmentController { } } } + var hiddenTextRanges: [NSRange] { + get { + renderer.hiddenTextRanges + } + set { + if newValue != renderer.hiddenTextRanges { + renderer.hiddenTextRanges = newValue + lineFragmentView?.setNeedsDisplay() + } + } + } /// Misspelled ranges in coordinates local to the document line. var misspelledRanges: [NSRange] { get { diff --git a/Sources/Runestone/TextView/LineController/LineFragmentRenderer.swift b/Sources/Runestone/TextView/LineController/LineFragmentRenderer.swift index 0eb485178..27d8aa548 100644 --- a/Sources/Runestone/TextView/LineController/LineFragmentRenderer.swift +++ b/Sources/Runestone/TextView/LineController/LineFragmentRenderer.swift @@ -18,6 +18,7 @@ final class LineFragmentRenderer { var markedTextBackgroundColor: UIColor = .systemFill var markedTextBackgroundCornerRadius: CGFloat = 0 var highlightedRangeFragments: [HighlightedRangeFragment] = [] + var hiddenTextRanges: [NSRange] = [] var misspelledRanges: [NSRange] = [] private var showInvisibleCharacters: Bool { @@ -288,8 +289,21 @@ private extension LineFragmentRenderer { } extension LineFragmentRenderer { - func drawText(to context: CGContext) { + func drawText(to context: CGContext, excludingHiddenRanges: Bool = true) { context.saveGState() + if excludingHiddenRanges, !hiddenTextRanges.isEmpty { + let path = UIBezierPath(rect: CGRect(x: -100_000, y: 0, width: 200_000, + height: lineFragment.scaledSize.height)) + for range in hiddenTextRanges { + let startX = CTLineGetOffsetForStringIndex(lineFragment.line, range.lowerBound, nil) + let endX = CTLineGetOffsetForStringIndex(lineFragment.line, range.upperBound, nil) + path.append(UIBezierPath(rect: CGRect(x: min(startX, endX), y: 0, + width: abs(endX - startX), + height: lineFragment.scaledSize.height))) + } + context.addPath(path.cgPath) + context.clip(using: .evenOdd) + } context.textMatrix = .identity context.translateBy(x: 0, y: lineFragment.scaledSize.height) context.scaleBy(x: 1, y: -1) diff --git a/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift index 4654c0951..e8a87c661 100644 --- a/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift +++ b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift @@ -38,6 +38,7 @@ final class FindResultPresentationView: UIView { layer.addSublayer(dimmingLayer) selectedResultPlateView.isHidden = true selectedResultPlateView.isUserInteractionEnabled = false + addSubview(selectedResultPlateView) } required init?(coder: NSCoder) { @@ -145,6 +146,13 @@ final class FindResultPresentationView: UIView { cornerRadius: Self.selectedCornerRadius).cgPath selectedResultPlateView.addSubview(plate) } + if let sourceView = sourceView as? TextInputView { + for segment in sourceView.selectedResultTextSegments(for: presentation.range.range) { + let textView = SelectedResultTextView(segment: segment) + textView.frame = segment.frame.offsetBy(dx: -union.minX, dy: -union.minY) + selectedResultPlateView.addSubview(textView) + } + } animateSelectedResultPlate(animated) } @@ -189,6 +197,36 @@ final class FindResultPresentationView: UIView { static let bounceAnimationKey = "find-result-bounce" } +struct SelectedResultTextSegment { + let frame: CGRect + let horizontalOffset: CGFloat + let renderer: LineFragmentRenderer +} + +private final class SelectedResultTextView: UIView { + private let segment: SelectedResultTextSegment + + init(segment: SelectedResultTextSegment) { + self.segment = segment + super.init(frame: .zero) + backgroundColor = .clear + isUserInteractionEnabled = false + clipsToBounds = true + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func draw(_ rect: CGRect) { + guard let context = UIGraphicsGetCurrentContext() else { + return + } + context.translateBy(x: -segment.horizontalOffset, y: 0) + segment.renderer.drawText(to: context, excludingHiddenRanges: false) + } +} + private struct RangePresentation { let range: HighlightedRange let rects: [CGRect] From c0187d6fe6d64ca769b3e9352a3b335fde1a8d89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20St=C3=B8vring?= Date: Wed, 4 Nov 2026 12:14:28 +0100 Subject: [PATCH 11/13] Keep find presentation responsive while scrolling --- .../TextView/Core/TextInputView.swift | 3 +-- .../TextView/Highlight/HighlightService.swift | 9 ++++---- .../FindResultPresentationView.swift | 22 ++++++++++++++----- .../FindResultPresentationViewTests.swift | 10 ++++----- 4 files changed, 28 insertions(+), 16 deletions(-) diff --git a/Sources/Runestone/TextView/Core/TextInputView.swift b/Sources/Runestone/TextView/Core/TextInputView.swift index b18c3d0e4..05ddf8ae8 100644 --- a/Sources/Runestone/TextView/Core/TextInputView.swift +++ b/Sources/Runestone/TextView/Core/TextInputView.swift @@ -1075,8 +1075,7 @@ final class TextInputView: UIView, UITextInput { writingToolsController?.layoutDidChange() if findResultPresentationView.isActive { bringSubviewToFront(findResultPresentationView) - findResultPresentationView.updateLayoutIfNeeded(highlightedRanges: highlightedRanges, - selectionRects: selectionRects(for:)) + findResultPresentationView.updateLayoutIfNeeded(selectionRects: selectionRects(for:)) } // We notify the input delegate about selection changes in layoutSubviews so we have a chance of disabling notifying the input delegate during an editing operation. // We will sometimes disable notifying the input delegate when the user enters Korean text. diff --git a/Sources/Runestone/TextView/Highlight/HighlightService.swift b/Sources/Runestone/TextView/Highlight/HighlightService.swift index 620a58b45..865e9729d 100644 --- a/Sources/Runestone/TextView/Highlight/HighlightService.swift +++ b/Sources/Runestone/TextView/Highlight/HighlightService.swift @@ -11,6 +11,9 @@ final class HighlightService { var highlightedRanges: [HighlightedRange] = [] { didSet { if highlightedRanges != oldValue { + selectedSearchResultRange = highlightedRanges.first { highlightedRange in + highlightedRange.presentationRole == .selectedSearchResult + }?.range if hasUnchangedRangeGeometry(comparedTo: oldValue) { updateHighlightedRangeFragments(changedFrom: oldValue) } else { @@ -29,6 +32,7 @@ final class HighlightService { private var highlightedRangeFragmentsPerLine: [DocumentLineNodeID: [HighlightedRangeFragment]] = [:] private var highlightedRangeFragmentsPerLineFragment: [LineFragmentID: [HighlightedRangeFragment]] = [:] + private var selectedSearchResultRange: NSRange? init(lineManager: LineManager) { self.lineManager = lineManager @@ -45,10 +49,7 @@ final class HighlightService { } func hiddenTextRanges(for lineFragment: LineFragment, inLineRange lineRange: NSRange) -> [NSRange] { - guard isFindResultPresentationActive, - let selectedRange = highlightedRanges.first(where: { highlightedRange in - highlightedRange.presentationRole == .selectedSearchResult - })?.range else { + guard isFindResultPresentationActive, let selectedRange = selectedSearchResultRange else { return [] } let intersection = NSIntersectionRange(selectedRange, lineRange) diff --git a/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift index e8a87c661..995de6c76 100644 --- a/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift +++ b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift @@ -58,7 +58,8 @@ final class FindResultPresentationView: UIView { guard boundsChanged || rangesChanged else { return } - let geometryChanged = boundsChanged || currentRanges.map(\.range) != searchRanges.map(\.range) + let geometryChanged = currentBounds.width != sourceView.bounds.width + || currentRanges.map(\.range) != searchRanges.map(\.range) currentBounds = sourceView.bounds currentRanges = searchRanges frame = sourceView.bounds @@ -77,12 +78,23 @@ final class FindResultPresentationView: UIView { selectedRange = selected?.range } - func updateLayoutIfNeeded(highlightedRanges: [HighlightedRange], - selectionRects: (UITextRange) -> [UITextSelectionRect]) { - guard sourceView?.bounds != currentBounds else { + func updateLayoutIfNeeded(selectionRects: (UITextRange) -> [UITextSelectionRect]) { + guard let sourceView, sourceView.bounds != currentBounds else { return } - update(highlightedRanges: highlightedRanges, selectionRects: selectionRects) + let geometryChanged = sourceView.bounds.width != currentBounds.width + currentBounds = sourceView.bounds + frame = sourceView.bounds + dimmingLayer.frame = bounds + if geometryChanged { + cachedPresentations = presentations(for: currentRanges, + sourceView: sourceView, + selectionRects: selectionRects) + } + updateDimming() + if geometryChanged || !selectedResultPlateView.subviews.contains(where: { $0 is SelectedResultTextView }) { + updateSelectedResultPlate(animated: false) + } } private func presentations(for ranges: [HighlightedRange], diff --git a/Tests/RunestoneTests/FindResultPresentationViewTests.swift b/Tests/RunestoneTests/FindResultPresentationViewTests.swift index dedd63d7f..2b9687f16 100644 --- a/Tests/RunestoneTests/FindResultPresentationViewTests.swift +++ b/Tests/RunestoneTests/FindResultPresentationViewTests.swift @@ -45,9 +45,10 @@ final class FindResultPresentationViewTests: XCTestCase { selectionRects: selectionRects) XCTAssertEqual(geometryCallCount, resultCount) - for _ in 0 ..< 100 { - presentationView.updateLayoutIfNeeded(highlightedRanges: ranges(count: resultCount, selectedIndex: 0), - selectionRects: selectionRects) + for index in 0 ..< 100 { + sourceView.bounds.origin.y = CGFloat(index) + sourceView.bounds.size.height = 2_000 + CGFloat(index) + presentationView.updateLayoutIfNeeded(selectionRects: selectionRects) } presentationView.update(highlightedRanges: ranges(count: resultCount, selectedIndex: 1), selectionRects: selectionRects) @@ -95,8 +96,7 @@ final class FindResultPresentationViewTests: XCTestCase { )) sourceView.bounds.origin.y = 20 - presentationView.updateLayoutIfNeeded(highlightedRanges: ranges(count: 2, selectedIndex: 1), - selectionRects: selectionRects) + presentationView.updateLayoutIfNeeded(selectionRects: selectionRects) XCTAssertNotNil(presentationView.selectedResultPlateView.layer.animation( forKey: FindResultPresentationView.bounceAnimationKey From 2275720fd18917c25097e3887526f84ecc5b8dbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20St=C3=B8vring?= Date: Wed, 4 Nov 2026 12:34:32 +0100 Subject: [PATCH 12/13] Refresh selected find overlay after layout --- .../FindResultPresentationView.swift | 100 ++++++++++++++---- .../FindResultPresentationViewTests.swift | 9 +- 2 files changed, 85 insertions(+), 24 deletions(-) diff --git a/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift index 995de6c76..54073bcef 100644 --- a/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift +++ b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift @@ -15,6 +15,7 @@ final class FindResultPresentationView: UIView { currentBounds = .null currentRanges = [] cachedPresentations = [] + selectedTextSegmentSignature = [] } } } @@ -26,6 +27,7 @@ final class FindResultPresentationView: UIView { private var currentBounds = CGRect.null private var currentRanges: [HighlightedRange] = [] private var cachedPresentations: [RangePresentation] = [] + private var selectedTextSegmentSignature: [SelectedResultTextSegmentSignature] = [] init(sourceView: UIView) { self.sourceView = sourceView @@ -79,21 +81,46 @@ final class FindResultPresentationView: UIView { } func updateLayoutIfNeeded(selectionRects: (UITextRange) -> [UITextSelectionRect]) { - guard let sourceView, sourceView.bounds != currentBounds else { + guard let sourceView else { return } + let boundsChanged = sourceView.bounds != currentBounds let geometryChanged = sourceView.bounds.width != currentBounds.width - currentBounds = sourceView.bounds - frame = sourceView.bounds - dimmingLayer.frame = bounds - if geometryChanged { - cachedPresentations = presentations(for: currentRanges, - sourceView: sourceView, - selectionRects: selectionRects) + if boundsChanged { + currentBounds = sourceView.bounds + frame = sourceView.bounds + dimmingLayer.frame = bounds + if geometryChanged { + cachedPresentations = presentations(for: currentRanges, + sourceView: sourceView, + selectionRects: selectionRects) + } } - updateDimming() - if geometryChanged || !selectedResultPlateView.subviews.contains(where: { $0 is SelectedResultTextView }) { - updateSelectedResultPlate(animated: false) + guard let selectedIndex = cachedPresentations.firstIndex(where: { presentation in + presentation.range.presentationRole == .selectedSearchResult + }) else { + if boundsChanged { + updateDimming() + } + return + } + let selectedPresentation = cachedPresentations[selectedIndex] + let refreshedPresentation = presentation(for: selectedPresentation.range, + sourceView: sourceView, + selectionRects: selectionRects) + let selectedSegments = (sourceView as? TextInputView)?.selectedResultTextSegments( + for: selectedPresentation.range.range + ) ?? [] + let segmentSignature = selectedSegments.map(SelectedResultTextSegmentSignature.init) + let selectedGeometryChanged = refreshedPresentation?.rects != selectedPresentation.rects + if let refreshedPresentation, selectedGeometryChanged { + cachedPresentations[selectedIndex] = refreshedPresentation + } + if boundsChanged || selectedGeometryChanged { + updateDimming() + } + if geometryChanged || selectedGeometryChanged || segmentSignature != selectedTextSegmentSignature { + updateSelectedResultPlate(animated: false, selectedSegments: selectedSegments) } } @@ -104,14 +131,28 @@ final class FindResultPresentationView: UIView { return [] } return ranges.compactMap { highlightedRange in - guard let start = textInput.position(from: textInput.beginningOfDocument, - offset: highlightedRange.range.location), - let end = textInput.position(from: start, offset: highlightedRange.range.length), - let textRange = textInput.textRange(from: start, to: end) else { - return nil - } - return RangePresentation(range: highlightedRange, rects: selectionRects(textRange).map(\.rect)) + presentation(for: highlightedRange, textInput: textInput, selectionRects: selectionRects) + } + } + + private func presentation(for range: HighlightedRange, + sourceView: UIView, + selectionRects: (UITextRange) -> [UITextSelectionRect]) -> RangePresentation? { + guard let textInput = sourceView as? UITextInput else { + return nil + } + return presentation(for: range, textInput: textInput, selectionRects: selectionRects) + } + + private func presentation(for range: HighlightedRange, + textInput: UITextInput, + selectionRects: (UITextRange) -> [UITextSelectionRect]) -> RangePresentation? { + guard let start = textInput.position(from: textInput.beginningOfDocument, offset: range.range.location), + let end = textInput.position(from: start, offset: range.range.length), + let textRange = textInput.textRange(from: start, to: end) else { + return nil } + return RangePresentation(range: range, rects: selectionRects(textRange).map(\.rect)) } private func updateDimming() { @@ -128,8 +169,9 @@ final class FindResultPresentationView: UIView { CATransaction.commit() } - private func updateSelectedResultPlate(animated: Bool) { + private func updateSelectedResultPlate(animated: Bool, selectedSegments: [SelectedResultTextSegment]? = nil) { selectedResultPlateView.subviews.forEach { $0.removeFromSuperview() } + selectedTextSegmentSignature = [] guard let presentation = cachedPresentations.first(where: { presentation in presentation.range.presentationRole == .selectedSearchResult }) else { @@ -158,8 +200,12 @@ final class FindResultPresentationView: UIView { cornerRadius: Self.selectedCornerRadius).cgPath selectedResultPlateView.addSubview(plate) } - if let sourceView = sourceView as? TextInputView { - for segment in sourceView.selectedResultTextSegments(for: presentation.range.range) { + let segments = selectedSegments + ?? (sourceView as? TextInputView)?.selectedResultTextSegments(for: presentation.range.range) + ?? [] + selectedTextSegmentSignature = segments.map(SelectedResultTextSegmentSignature.init) + if sourceView is TextInputView { + for segment in segments { let textView = SelectedResultTextView(segment: segment) textView.frame = segment.frame.offsetBy(dx: -union.minX, dy: -union.minY) selectedResultPlateView.addSubview(textView) @@ -215,6 +261,18 @@ struct SelectedResultTextSegment { let renderer: LineFragmentRenderer } +private struct SelectedResultTextSegmentSignature: Equatable { + let frame: CGRect + let horizontalOffset: CGFloat + let renderer: ObjectIdentifier + + init(segment: SelectedResultTextSegment) { + frame = segment.frame + horizontalOffset = segment.horizontalOffset + renderer = ObjectIdentifier(segment.renderer) + } +} + private final class SelectedResultTextView: UIView { private let segment: SelectedResultTextSegment diff --git a/Tests/RunestoneTests/FindResultPresentationViewTests.swift b/Tests/RunestoneTests/FindResultPresentationViewTests.swift index 2b9687f16..bfec74d44 100644 --- a/Tests/RunestoneTests/FindResultPresentationViewTests.swift +++ b/Tests/RunestoneTests/FindResultPresentationViewTests.swift @@ -35,9 +35,10 @@ final class FindResultPresentationViewTests: XCTestCase { let presentationView = FindResultPresentationView(sourceView: sourceView) presentationView.isActive = true var geometryCallCount = 0 + var selectedY: CGFloat = 10 let selectionRects: (UITextRange) -> [UITextSelectionRect] = { _ in geometryCallCount += 1 - return [TextSelectionRect(rect: CGRect(x: 10, y: 10, width: 8, height: 18), + return [TextSelectionRect(rect: CGRect(x: 10, y: selectedY, width: 8, height: 18), writingDirection: .natural, containsStart: true, containsEnd: true)] } @@ -46,14 +47,16 @@ final class FindResultPresentationViewTests: XCTestCase { XCTAssertEqual(geometryCallCount, resultCount) for index in 0 ..< 100 { + selectedY = 10 + CGFloat(index) sourceView.bounds.origin.y = CGFloat(index) sourceView.bounds.size.height = 2_000 + CGFloat(index) presentationView.updateLayoutIfNeeded(selectionRects: selectionRects) } + XCTAssertEqual(presentationView.selectedResultPlateView.frame.minY, selectedY - 3) presentationView.update(highlightedRanges: ranges(count: resultCount, selectedIndex: 1), selectionRects: selectionRects) - XCTAssertEqual(geometryCallCount, resultCount, - "Scrolling and moving between existing results must reuse cached text geometry") + XCTAssertEqual(geometryCallCount, resultCount + 100, + "Layout must refresh only the selected result, not every match") } func testChangingSelectionAnimatesThePlateItself() { From 654bd9e4d548d5c41de069cd9ba622e859c9d83c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20St=C3=B8vring?= Date: Wed, 4 Nov 2026 13:03:47 +0100 Subject: [PATCH 13/13] Allow highlights to override text color --- .../TextView/Highlight/HighlightService.swift | 2 + .../TextView/Highlight/HighlightedRange.swift | 6 +++ .../Highlight/HighlightedRangeFragment.swift | 6 ++- .../LineController/LineFragmentRenderer.swift | 35 +++++++++++++++- .../FindResultPresentationView.swift | 9 ++-- .../HighlightBackgroundRenderingTests.swift | 42 +++++++++++++++++++ 6 files changed, 94 insertions(+), 6 deletions(-) diff --git a/Sources/Runestone/TextView/Highlight/HighlightService.swift b/Sources/Runestone/TextView/Highlight/HighlightService.swift index 865e9729d..11b728cd3 100644 --- a/Sources/Runestone/TextView/Highlight/HighlightService.swift +++ b/Sources/Runestone/TextView/Highlight/HighlightService.swift @@ -123,6 +123,7 @@ private extension HighlightService { containsStart: cappedRange.lowerBound == highlightedRange.range.lowerBound, containsEnd: cappedRange.upperBound == highlightedRange.range.upperBound, color: highlightedRange.color, + foregroundColor: highlightedRange.foregroundColor, cornerRadius: highlightedRange.cornerRadius) } @@ -147,6 +148,7 @@ private extension HighlightService { containsStart: containsStart, containsEnd: containsEnd, color: lineHighlightedRangeFragment.color, + foregroundColor: lineHighlightedRangeFragment.foregroundColor, cornerRadius: lineHighlightedRangeFragment.cornerRadius) } } diff --git a/Sources/Runestone/TextView/Highlight/HighlightedRange.swift b/Sources/Runestone/TextView/Highlight/HighlightedRange.swift index 25af03d7c..f15e17ba1 100644 --- a/Sources/Runestone/TextView/Highlight/HighlightedRange.swift +++ b/Sources/Runestone/TextView/Highlight/HighlightedRange.swift @@ -18,6 +18,8 @@ public final class HighlightedRange { public let range: NSRange /// Color to highlight the text with. public let color: UIColor + /// Optional foreground color for text inside the highlight. A value of `nil` preserves syntax colors. + public let foregroundColor: UIColor? /// Corner radius of the highlight. public let cornerRadius: CGFloat /// The role of the range when search results are presented. @@ -28,16 +30,19 @@ public final class HighlightedRange { /// - id: ID of the range. Defaults to a UUID. /// - range: Range in the text to highlight. /// - color: Color to highlight the text with. + /// - foregroundColor: Optional text color inside the highlight. Defaults to `nil`, preserving syntax colors. /// - cornerRadius: Corner radius of the highlight. A value of zero or less means no corner radius. Defaults to 0. /// - presentationRole: Role of the range in search presentation. Defaults to ``HighlightedRangePresentationRole/standard``. public init(id: String = UUID().uuidString, range: NSRange, color: UIColor, + foregroundColor: UIColor? = nil, cornerRadius: CGFloat = 0, presentationRole: HighlightedRangePresentationRole = .standard) { self.id = id self.range = range self.color = color + self.foregroundColor = foregroundColor self.cornerRadius = cornerRadius self.presentationRole = presentationRole } @@ -48,6 +53,7 @@ extension HighlightedRange: Equatable { lhs.id == rhs.id && lhs.range == rhs.range && lhs.color == rhs.color + && lhs.foregroundColor == rhs.foregroundColor && lhs.cornerRadius == rhs.cornerRadius && lhs.presentationRole == rhs.presentationRole } diff --git a/Sources/Runestone/TextView/Highlight/HighlightedRangeFragment.swift b/Sources/Runestone/TextView/Highlight/HighlightedRangeFragment.swift index d72c34502..22cbb33ef 100644 --- a/Sources/Runestone/TextView/Highlight/HighlightedRangeFragment.swift +++ b/Sources/Runestone/TextView/Highlight/HighlightedRangeFragment.swift @@ -5,6 +5,7 @@ final class HighlightedRangeFragment: Equatable { let containsStart: Bool let containsEnd: Bool let color: UIColor + let foregroundColor: UIColor? let cornerRadius: CGFloat var roundedCorners: UIRectCorner { if containsStart && containsEnd { @@ -18,11 +19,13 @@ final class HighlightedRangeFragment: Equatable { } } - init(range: NSRange, containsStart: Bool, containsEnd: Bool, color: UIColor, cornerRadius: CGFloat) { + init(range: NSRange, containsStart: Bool, containsEnd: Bool, color: UIColor, foregroundColor: UIColor? = nil, + cornerRadius: CGFloat) { self.range = range self.containsStart = containsStart self.containsEnd = containsEnd self.color = color + self.foregroundColor = foregroundColor self.cornerRadius = cornerRadius } } @@ -33,6 +36,7 @@ extension HighlightedRangeFragment { && lhs.containsStart == rhs.containsStart && lhs.containsEnd == rhs.containsEnd && lhs.color == rhs.color + && lhs.foregroundColor == rhs.foregroundColor && lhs.cornerRadius == rhs.cornerRadius } } diff --git a/Sources/Runestone/TextView/LineController/LineFragmentRenderer.swift b/Sources/Runestone/TextView/LineController/LineFragmentRenderer.swift index 27d8aa548..b71d35cb7 100644 --- a/Sources/Runestone/TextView/LineController/LineFragmentRenderer.swift +++ b/Sources/Runestone/TextView/LineController/LineFragmentRenderer.swift @@ -289,7 +289,7 @@ private extension LineFragmentRenderer { } extension LineFragmentRenderer { - func drawText(to context: CGContext, excludingHiddenRanges: Bool = true) { + func drawText(to context: CGContext, excludingHiddenRanges: Bool = true, foregroundColor: UIColor? = nil) { context.saveGState() if excludingHiddenRanges, !hiddenTextRanges.isEmpty { let path = UIBezierPath(rect: CGRect(x: -100_000, y: 0, width: 200_000, @@ -309,8 +309,39 @@ extension LineFragmentRenderer { context.scaleBy(x: 1, y: -1) let yPosition = lineFragment.descent + (lineFragment.scaledSize.height - lineFragment.baseSize.height) / 2 context.textPosition = CGPoint(x: 0, y: yPosition) - CTLineDraw(lineFragment.line, context) + if let foregroundColor { + drawLine(to: context, foregroundColor: foregroundColor, baseline: yPosition) + } else { + CTLineDraw(lineFragment.line, context) + drawHighlightedRangeForegrounds(to: context, baseline: yPosition) + } context.restoreGState() } + private func drawHighlightedRangeForegrounds(to context: CGContext, baseline: CGFloat) { + for fragment in highlightedRangeFragments { + guard let foregroundColor = fragment.foregroundColor else { + continue + } + for segment in spellingUnderlineSegments(in: fragment.range) { + context.saveGState() + context.clip(to: CGRect(x: segment.lowerBound, y: 0, + width: segment.upperBound - segment.lowerBound, + height: lineFragment.scaledSize.height)) + drawLine(to: context, foregroundColor: foregroundColor, baseline: baseline) + context.restoreGState() + } + } + } + + private func drawLine(to context: CGContext, foregroundColor: UIColor, baseline: CGFloat) { + context.beginTransparencyLayer(auxiliaryInfo: nil) + context.textPosition = CGPoint(x: 0, y: baseline) + CTLineDraw(lineFragment.line, context) + context.setBlendMode(.sourceIn) + context.setFillColor(foregroundColor.cgColor) + context.fill(CGRect(x: -100_000, y: -100_000, width: 200_000, height: 200_000)) + context.endTransparencyLayer() + } + } diff --git a/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift index 54073bcef..8072bdfdd 100644 --- a/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift +++ b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift @@ -206,7 +206,8 @@ final class FindResultPresentationView: UIView { selectedTextSegmentSignature = segments.map(SelectedResultTextSegmentSignature.init) if sourceView is TextInputView { for segment in segments { - let textView = SelectedResultTextView(segment: segment) + let textView = SelectedResultTextView(segment: segment, + foregroundColor: presentation.range.foregroundColor) textView.frame = segment.frame.offsetBy(dx: -union.minX, dy: -union.minY) selectedResultPlateView.addSubview(textView) } @@ -275,9 +276,11 @@ private struct SelectedResultTextSegmentSignature: Equatable { private final class SelectedResultTextView: UIView { private let segment: SelectedResultTextSegment + private let foregroundColor: UIColor? - init(segment: SelectedResultTextSegment) { + init(segment: SelectedResultTextSegment, foregroundColor: UIColor?) { self.segment = segment + self.foregroundColor = foregroundColor super.init(frame: .zero) backgroundColor = .clear isUserInteractionEnabled = false @@ -293,7 +296,7 @@ private final class SelectedResultTextView: UIView { return } context.translateBy(x: -segment.horizontalOffset, y: 0) - segment.renderer.drawText(to: context, excludingHiddenRanges: false) + segment.renderer.drawText(to: context, excludingHiddenRanges: false, foregroundColor: foregroundColor) } } diff --git a/Tests/RunestoneTests/HighlightBackgroundRenderingTests.swift b/Tests/RunestoneTests/HighlightBackgroundRenderingTests.swift index 57b936540..79ead88ce 100644 --- a/Tests/RunestoneTests/HighlightBackgroundRenderingTests.swift +++ b/Tests/RunestoneTests/HighlightBackgroundRenderingTests.swift @@ -77,6 +77,29 @@ final class HighlightBackgroundRenderingTests: XCTestCase { XCTAssertTrue(hasUnderline, "The spelling underline must paint above the opaque token background.") } + func testHighlightForegroundOverrideRecolorsOnlyConfiguredText() throws { + let sourceColor = UIColor(red: 1, green: 0, blue: 0, alpha: 1) + let overrideColor = UIColor(red: 0, green: 0, blue: 1, alpha: 1) + let attributed = NSAttributedString(string: "abcdef", attributes: [ + .font: UIFont.monospacedSystemFont(ofSize: 24, weight: .regular), + .foregroundColor: sourceColor + ]) + let fragment = try XCTUnwrap(makeFragments(attributed, width: 500).first) + let renderer = LineFragmentRenderer(lineFragment: fragment, invisibleCharacterConfiguration: .init()) + renderer.highlightedRangeFragments = [ + HighlightedRangeFragment(range: NSRange(location: 0, length: 3), containsStart: true, + containsEnd: true, color: .yellow, + foregroundColor: overrideColor, cornerRadius: 0), + HighlightedRangeFragment(range: NSRange(location: 3, length: 3), containsStart: true, + containsEnd: true, color: .yellow, cornerRadius: 0) + ] + + let bitmap = try draw(renderer) + let overrideEnd = Int(CTLineGetOffsetForStringIndex(fragment.line, 3, nil)) + XCTAssertTrue(bitmap.containsDominantColor(overrideColor, inXRange: 0 ..< overrideEnd)) + XCTAssertTrue(bitmap.containsDominantColor(sourceColor, inXRange: overrideEnd ..< bitmap.width)) + } + private func makeFragments(_ string: NSAttributedString, width: CGFloat) -> [LineFragment] { let typesetter = LineTypesetter(lineID: "test") typesetter.constrainingWidth = width @@ -113,4 +136,23 @@ private struct Bitmap { let offset = ((height - 1 - y) * width + x) * 4 return Array(bytes[offset ..< offset + 4]) } + + func containsDominantColor(_ color: UIColor, inXRange xRange: Range) -> Bool { + var targetRed: CGFloat = 0 + var targetGreen: CGFloat = 0 + var targetBlue: CGFloat = 0 + color.getRed(&targetRed, green: &targetGreen, blue: &targetBlue, alpha: nil) + let range = max(0, xRange.lowerBound) ..< min(width, xRange.upperBound) + return range.contains { x in + (0 ..< height).contains { y in + let value = pixel(x: x, y: y) + let target = [targetRed, targetGreen, targetBlue] + let channels = value.prefix(3).map { CGFloat($0) / 255 } + return zip(target, channels).allSatisfy { expected, actual in + expected < 0.1 ? actual < 0.3 : actual > 0.7 + } + } + } + } + }