Skip to content

Share Text Storage Delegates #92

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

Merged
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
4 changes: 4 additions & 0 deletions Sources/CodeEditTextView/TextView/TextView+SetText.swift
Original file line number Diff line number Diff line change
@@ -20,6 +20,10 @@ extension TextView {
public func setTextStorage(_ textStorage: NSTextStorage) {
self.textStorage = textStorage

if let storageDelegate = textStorage.delegate as? MultiStorageDelegate {
self.storageDelegate = storageDelegate
}

subviews.forEach { view in
view.removeFromSuperview()
}
6 changes: 5 additions & 1 deletion Sources/CodeEditTextView/TextView/TextView.swift
Original file line number Diff line number Diff line change
@@ -320,7 +320,11 @@ public class TextView: NSView, NSTextContent {
super.init(frame: .zero)

self.emphasisManager = EmphasisManager(textView: self)
self.storageDelegate = MultiStorageDelegate()
if let storageDelegate = textStorage.delegate as? MultiStorageDelegate {
self.storageDelegate = storageDelegate
} else {
self.storageDelegate = MultiStorageDelegate()
}

wantsLayer = true
postsFrameChangedNotifications = true
24 changes: 24 additions & 0 deletions Tests/CodeEditTextViewTests/TextViewTests.swift
Original file line number Diff line number Diff line change
@@ -40,4 +40,28 @@ struct TextViewTests {
// available in test module
textView.layoutManager.lineStorage.validateInternalState()
}

@Test
func sharedTextStorage() {
let storage = NSTextStorage(string: "Hello world")

let textView1 = TextView(string: "")
textView1.frame = NSRect(x: 0, y: 0, width: 100, height: 100)
textView1.layoutSubtreeIfNeeded()
textView1.setTextStorage(storage)

let textView2 = TextView(string: "")
textView2.frame = NSRect(x: 0, y: 0, width: 100, height: 100)
textView2.layoutSubtreeIfNeeded()
textView2.setTextStorage(storage)

// Expect both text views to receive edited events from the storage
#expect(textView1.layoutManager.lineCount == 1)
#expect(textView2.layoutManager.lineCount == 1)

storage.replaceCharacters(in: NSRange(location: 11, length: 0), with: "\nMore Lines\n")

#expect(textView1.layoutManager.lineCount == 3)
#expect(textView2.layoutManager.lineCount == 3)
}
}