Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions Sources/Runestone/TextView/Appearance/DefaultTheme.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
10 changes: 8 additions & 2 deletions Sources/Runestone/TextView/Appearance/Theme.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
30 changes: 30 additions & 0 deletions Sources/Runestone/TextView/Core/LayoutManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
42 changes: 42 additions & 0 deletions Sources/Runestone/TextView/Core/TextInputView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down Expand Up @@ -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? {
Expand Down Expand Up @@ -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.
Expand Down
24 changes: 24 additions & 0 deletions Sources/Runestone/TextView/Core/TextView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
84 changes: 74 additions & 10 deletions Sources/Runestone/TextView/Highlight/HighlightService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,28 @@ 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()
}
}
}

private var highlightedRangeFragmentsPerLine: [DocumentLineNodeID: [HighlightedRangeFragment]] = [:]
private var highlightedRangeFragmentsPerLineFragment: [LineFragmentID: [HighlightedRangeFragment]] = [:]
private var selectedSearchResultRange: NSRange?

init(lineManager: LineManager) {
self.lineManager = lineManager
Expand All @@ -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()
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -85,6 +148,7 @@ private extension HighlightService {
containsStart: containsStart,
containsEnd: containsEnd,
color: lineHighlightedRangeFragment.color,
foregroundColor: lineHighlightedRangeFragment.foregroundColor,
cornerRadius: lineHighlightedRangeFragment.cornerRadius)
}
}
Expand Down
32 changes: 30 additions & 2 deletions Sources/Runestone/TextView/Highlight/HighlightedRange.swift
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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
}
}

Expand Down
Loading
Loading