diff --git a/Sources/Runestone/TextView/Appearance/DefaultTheme.swift b/Sources/Runestone/TextView/Appearance/DefaultTheme.swift index 3eedf07a9..00af0dbe2 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: 3, + 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: 5, + 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..fe7ffd2bb 100644 --- a/Sources/Runestone/TextView/Appearance/Theme.swift +++ b/Sources/Runestone/TextView/Appearance/Theme.swift @@ -106,9 +106,15 @@ 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), + cornerRadius: 3, + presentationRole: .foundSearchResult) case .highlighted: - return HighlightedRange(range: foundTextRange, color: .systemYellow) + return HighlightedRange(range: foundTextRange, + color: .systemYellow, + cornerRadius: 5, + presentationRole: .selectedSearchResult) case .normal: return nil @unknown default: diff --git a/Sources/Runestone/TextView/Core/LayoutManager.swift b/Sources/Runestone/TextView/Core/LayoutManager.swift index 65ab6621e..056fd3668 100644 --- a/Sources/Runestone/TextView/Core/LayoutManager.swift +++ b/Sources/Runestone/TextView/Core/LayoutManager.swift @@ -666,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, @@ -856,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 10d5b6d08..05ddf8ae8 100644 --- a/Sources/Runestone/TextView/Core/TextInputView.swift +++ b/Sources/Runestone/TextView/Core/TextInputView.swift @@ -716,9 +716,46 @@ final class TextInputView: UIView, UITextInput { highlightService.highlightedRanges = newValue layoutManager.setNeedsLayout() layoutManager.layoutIfNeeded() + findResultPresentationView.update(highlightedRanges: newValue, + selectionRects: selectionRects(for:)) } } } + var isFindResultPresentationEnabled = false { + didSet { + updateFindResultPresentation() + } + } + var isFindResultPresentationActive: Bool { + get { + isFindResultPresentationRequested + } + set { + isFindResultPresentationRequested = newValue + updateFindResultPresentation() + } + } + private var isFindResultPresentationRequested = false + + private func updateFindResultPresentation() { + let isActive = isFindResultPresentationEnabled && isFindResultPresentationRequested + findResultPresentationView.isActive = isActive + highlightService.isFindResultPresentationActive = isActive + layoutManager.setNeedsLayout() + layoutManager.layoutIfNeeded() + guard isActive else { + return + } + if findResultPresentationView.superview == nil { + addSubview(findResultPresentationView) + } + findResultPresentationView.update(highlightedRanges: highlightedRanges, + selectionRects: selectionRects(for:)) + } + + func selectedResultTextSegments(for range: NSRange) -> [SelectedResultTextSegment] { + layoutManager.selectedResultTextSegments(for: range) + } // MARK: - Contents weak var delegate: TextInputViewDelegate? @@ -880,6 +917,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 +1073,10 @@ final class TextInputView: UIView, UITextInput { checkVisibleSpellingIfNeeded() updateLegacySpellingMenuIfNeeded() writingToolsController?.layoutDidChange() + if findResultPresentationView.isActive { + bringSubviewToFront(findResultPresentationView) + 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. // 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..9cc643597 100644 --- a/Sources/Runestone/TextView/Core/TextView.swift +++ b/Sources/Runestone/TextView/Core/TextView.swift @@ -683,6 +683,30 @@ open class TextView: UIScrollView { highlightNavigationController.highlightedRanges = newValue } } + /// Whether search results may be presented above dimmed editor content. + /// + /// 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 + } + 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/HighlightService.swift b/Sources/Runestone/TextView/Highlight/HighlightService.swift index e9885a080..11b728cd3 100644 --- a/Sources/Runestone/TextView/Highlight/HighlightService.swift +++ b/Sources/Runestone/TextView/Highlight/HighlightService.swift @@ -11,6 +11,20 @@ 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 { + invalidateHighlightedRangeFragments() + } + } + } + } + var isFindResultPresentationActive = false { + didSet { + if isFindResultPresentationActive != oldValue { invalidateHighlightedRangeFragments() } } @@ -18,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 @@ -32,9 +47,49 @@ final class HighlightService { return highlightedLineFragments } } + + func hiddenTextRanges(for lineFragment: LineFragment, inLineRange lineRange: NSRange) -> [NSRange] { + guard isFindResultPresentationActive, let selectedRange = selectedSearchResultRange 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 { + 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) }) { 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 shouldRender(highlightedRange), highlightedRange.range.overlaps(lineRange) else { + return nil + } + return makeHighlightedRangeFragment(for: highlightedRange, in: lineRange) + } + } + } + private func invalidateHighlightedRangeFragments() { highlightedRangeFragmentsPerLine.removeAll() highlightedRangeFragmentsPerLineFragment.removeAll() @@ -43,22 +98,14 @@ 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) 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 +116,22 @@ 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, + foregroundColor: highlightedRange.foregroundColor, + 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 { @@ -85,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 5f1554155..f15e17ba1 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. @@ -8,26 +18,44 @@ 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. + public let presentationRole: HighlightedRangePresentationRole /// Create a new highlighted range. /// - Parameters: /// - 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. - 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, + 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 } } 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.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/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..b71d35cb7 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,15 +289,59 @@ private extension LineFragmentRenderer { } extension LineFragmentRenderer { - func drawText(to context: CGContext) { + 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, + 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) 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 new file mode 100644 index 000000000..8072bdfdd --- /dev/null +++ b/Sources/Runestone/TextView/SearchAndReplace/FindResultPresentationView.swift @@ -0,0 +1,306 @@ +import UIKit + +final class FindResultPresentationView: UIView { + var isActive = false { + didSet { + guard isActive != oldValue else { + return + } + isHidden = !isActive + selectedResultPlateView.isHidden = !isActive + if !isActive { + selectedResultPlateView.layer.removeAnimation(forKey: Self.bounceAnimationKey) + selectedResultPlateView.transform = .identity + selectedRange = nil + currentBounds = .null + currentRanges = [] + cachedPresentations = [] + selectedTextSegmentSignature = [] + } + } + } + let selectedResultPlateView = UIView() + + private weak var sourceView: UIView? + private let dimmingLayer = CAShapeLayer() + private var selectedRange: NSRange? + private var currentBounds = CGRect.null + private var currentRanges: [HighlightedRange] = [] + private var cachedPresentations: [RangePresentation] = [] + private var selectedTextSegmentSignature: [SelectedResultTextSegmentSignature] = [] + + 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) + selectedResultPlateView.isHidden = true + selectedResultPlateView.isUserInteractionEnabled = false + addSubview(selectedResultPlateView) + } + + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + func update(highlightedRanges: [HighlightedRange], + 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 boundsChanged = currentBounds != sourceView.bounds + let rangesChanged = currentRanges != searchRanges + guard boundsChanged || rangesChanged else { + return + } + let geometryChanged = currentBounds.width != sourceView.bounds.width + || currentRanges.map(\.range) != searchRanges.map(\.range) + currentBounds = sourceView.bounds + currentRanges = searchRanges + frame = sourceView.bounds + dimmingLayer.frame = bounds + 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(selectionRects: (UITextRange) -> [UITextSelectionRect]) { + guard let sourceView else { + return + } + let boundsChanged = sourceView.bounds != currentBounds + let geometryChanged = sourceView.bounds.width != currentBounds.width + if boundsChanged { + currentBounds = sourceView.bounds + frame = sourceView.bounds + dimmingLayer.frame = bounds + if geometryChanged { + cachedPresentations = presentations(for: currentRanges, + sourceView: sourceView, + selectionRects: selectionRects) + } + } + 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) + } + } + + private func presentations(for ranges: [HighlightedRange], + sourceView: UIView, + selectionRects: (UITextRange) -> [UITextSelectionRect]) -> [RangePresentation] { + guard let textInput = sourceView as? UITextInput else { + return [] + } + return ranges.compactMap { highlightedRange in + 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() { + let path = UIBezierPath(rect: bounds) + for presentation in cachedPresentations { + for rect in displayRects(for: presentation) where !rect.isEmpty { + path.append(UIBezierPath(roundedRect: rect, + cornerRadius: cornerRadius(for: presentation.range))) + } + } + CATransaction.begin() + CATransaction.setDisableActions(true) + dimmingLayer.path = path.cgPath + CATransaction.commit() + } + + 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 { + selectedResultPlateView.isHidden = true + return + } + let rects = presentation.rects.filter { !$0.isEmpty }.map(selectedDisplayRect(for:)) + guard !rects.isEmpty else { + selectedResultPlateView.isHidden = true + return + } + 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) + } + 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, + foregroundColor: presentation.range.foregroundColor) + textView.frame = segment.frame.offsetBy(dx: -union.minX, dy: -union.minY) + selectedResultPlateView.addSubview(textView) + } + } + animateSelectedResultPlate(animated) + } + + private func animateSelectedResultPlate(_ animated: Bool) { + guard animated else { + return + } + selectedResultPlateView.layer.removeAnimation(forKey: Self.bounceAnimationKey) + selectedResultPlateView.transform = .identity + guard !UIAccessibility.isReduceMotionEnabled else { + return + } + 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] { + 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 + static let bounceAnimationKey = "find-result-bounce" +} + +struct SelectedResultTextSegment { + let frame: CGRect + let horizontalOffset: CGFloat + 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 + private let foregroundColor: UIColor? + + init(segment: SelectedResultTextSegment, foregroundColor: UIColor?) { + self.segment = segment + self.foregroundColor = foregroundColor + 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, foregroundColor: foregroundColor) + } +} + +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/FindResultPerformanceTests.swift b/Tests/RunestoneTests/FindResultPerformanceTests.swift new file mode 100644 index 000000000..3447ab868 --- /dev/null +++ b/Tests/RunestoneTests/FindResultPerformanceTests.swift @@ -0,0 +1,137 @@ +@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 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) + } + 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] { + 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) + } + + 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)] + 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 \(message)") + } +} + +@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() + } + } +} diff --git a/Tests/RunestoneTests/FindResultPresentationViewTests.swift b/Tests/RunestoneTests/FindResultPresentationViewTests.swift new file mode 100644 index 000000000..bfec74d44 --- /dev/null +++ b/Tests/RunestoneTests/FindResultPresentationViewTests.swift @@ -0,0 +1,118 @@ +@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 + var selectedY: CGFloat = 10 + let selectionRects: (UITextRange) -> [UITextSelectionRect] = { _ in + geometryCallCount += 1 + return [TextSelectionRect(rect: CGRect(x: 10, y: selectedY, width: 8, height: 18), + writingDirection: .natural, containsStart: true, containsEnd: true)] + } + + presentationView.update(highlightedRanges: ranges(count: resultCount, selectedIndex: 0), + selectionRects: selectionRects) + 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 + 100, + "Layout must refresh only the selected result, not every match") + } + + 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) + } + + 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(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)", + range: NSRange(location: index, length: 1), + color: index == selectedIndex ? .yellow : .white, + cornerRadius: 3, + presentationRole: index == selectedIndex ? .selectedSearchResult : .foundSearchResult) + } + } +} 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 + } + } + } + } + } diff --git a/Tests/RunestoneTests/UITextSearchingHelperTests.swift b/Tests/RunestoneTests/UITextSearchingHelperTests.swift index 743b3d774..c883f1818 100644 --- a/Tests/RunestoneTests/UITextSearchingHelperTests.swift +++ b/Tests/RunestoneTests/UITextSearchingHelperTests.swift @@ -52,6 +52,44 @@ 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() + textView.isFindResultPresentationEnabled = true + 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 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"