Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(fix: #28) Update scrollToVisible Loop #29

Merged
merged 1 commit into from
May 16, 2024
Merged
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
20 changes: 15 additions & 5 deletions Sources/CodeEditTextView/TextView/TextView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -522,19 +522,29 @@ public class TextView: NSView, NSTextContent {

/// Scrolls the upmost selection to the visible rect if `scrollView` is not `nil`.
public func scrollSelectionToVisible() {
guard let scrollView,
let selection = selectionManager.textSelections
.sorted(by: { $0.boundingRect.origin.y < $1.boundingRect.origin.y }).first else {
guard let scrollView else {
return
}

// There's a bit of a chicken-and-the-egg issue going on here. We need to know the rect to scroll to, but we
// can't know the exact rect to make visible without laying out the text. Then, once text is laid out the
// selection rect may be different again. To solve this, we loop until the frame doesn't change after a layout
// pass and scroll to that rect.

var lastFrame: CGRect = .zero
while lastFrame != selection.boundingRect {
while let selection = selectionManager
.textSelections
.sorted(by: { $0.boundingRect.origin.y < $1.boundingRect.origin.y })
.first,
lastFrame != selection.boundingRect {
lastFrame = selection.boundingRect
layoutManager.layoutLines()
selectionManager.updateSelectionViews()
selectionManager.drawSelections(in: visibleRect)
}
scrollView.contentView.scrollToVisible(lastFrame)
if lastFrame != .zero {
scrollView.contentView.scrollToVisible(lastFrame)
}
}

deinit {
Expand Down
Loading