-
-
Save nutsmuggler/c1d50e04c894324b1f0cd9b6a1502cfb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HighlightTextViewController: UIViewController { | |
var textView = UITextView() | |
let theme: Theme = MaterialLightTheme() | |
lazy var highlighter: TextViewHighlighter = { | |
let abcLanguage = Language(language: tree_sitter_abc()) | |
let url = Bundle.main.url(forResource: "highlights", withExtension: "scm") | |
let query = try! abcLanguage.query(contentsOf: url!) | |
let attrProvider: TextViewSystemInterface.AttributeProvider = { token in | |
// print(token) | |
// TODO extract and add fonts etc | |
var attrs: [NSAttributedString.Key: Any] = [:] | |
if let foregroundColor = self.theme.textColor(for: token.name) { | |
attrs[.foregroundColor] = foregroundColor | |
} | |
return attrs | |
} | |
return try! TextViewHighlighter(textView: textView, | |
language: abcLanguage, | |
highlightQuery: query, | |
attributeProvider: attrProvider) | |
}() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
_ = highlighter.textView | |
textView.isEditable = true | |
textView.font = UIFont.systemFont(ofSize: 20) | |
textView.backgroundColor = theme.backgroundColor | |
view.addSubview(textView) | |
textView.translatesAutoresizingMaskIntoConstraints = false | |
NSLayoutConstraint.activate([ | |
textView.topAnchor.constraint(equalTo: view.topAnchor), | |
textView.bottomAnchor.constraint(equalTo: view.bottomAnchor), | |
textView.leadingAnchor.constraint(equalTo: view.leadingAnchor), | |
textView.trailingAnchor.constraint(equalTo: view.trailingAnchor) | |
]) | |
} | |
func invalidateHighlighter() { | |
DispatchQueue.main.async { | |
print(self.textView.text) | |
self.highlighter.invalidate() | |
} | |
} | |
override func viewDidAppear(_ animated: Bool) { | |
super.viewDidAppear(animated) | |
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { | |
let text = self.textView.text | |
self.textView.text = "jsk" | |
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { | |
self.textView.text = text | |
self.highlighter.invalidate() | |
} | |
} | |
} | |
} | |
struct HighlightingTextView: UIViewControllerRepresentable { | |
@Binding var text: String | |
func makeUIViewController(context: Context) -> HighlightTextViewController { | |
let viewController = HighlightTextViewController() | |
viewController.textView.text = text | |
viewController.invalidateHighlighter() | |
return viewController | |
} | |
func updateUIViewController(_ uiViewController: HighlightTextViewController, context: Context) { | |
uiViewController.textView.text = text | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment