From 4bccbe254b60dd32549c25a8b17342b4b3015baa Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Sat, 14 Nov 2020 11:47:20 -0500 Subject: [PATCH] Add text formatting key commands --- .../Screens/Compose/MainComposeTextView.swift | 42 +++++++++++++++++-- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/Tusker/Screens/Compose/MainComposeTextView.swift b/Tusker/Screens/Compose/MainComposeTextView.swift index 75988099..b32784d9 100644 --- a/Tusker/Screens/Compose/MainComposeTextView.swift +++ b/Tusker/Screens/Compose/MainComposeTextView.swift @@ -59,7 +59,7 @@ struct MainComposeWrappedTextView: UIViewRepresentable { @State var visibilityButton: UIBarButtonItem? func makeUIView(context: Context) -> UITextView { - let textView = UITextView() + let textView = WrappedTextView() textView.delegate = context.coordinator textView.isEditable = true textView.backgroundColor = .clear @@ -171,6 +171,35 @@ struct MainComposeWrappedTextView: UIViewRepresentable { return Coordinator(text: $text, uiState: uiState, didChange: textDidChange) } + class WrappedTextView: UITextView { + private let formattingActions = [#selector(toggleBoldface(_:)), #selector(toggleItalics(_:))] + + override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { + if formattingActions.contains(action) { + return Preferences.shared.statusContentType != .plain + } + + return super.canPerformAction(action, withSender: sender) + } + + override func toggleBoldface(_ sender: Any?) { + (delegate as! Coordinator).applyFormat(.bold) + } + + override func toggleItalics(_ sender: Any?) { + (delegate as! Coordinator).applyFormat(.italics) + } + + override func validate(_ command: UICommand) { + super.validate(command) + + if formattingActions.contains(command.action), + Preferences.shared.statusContentType != .plain { + command.attributes.remove(.disabled) + } + } + } + class Coordinator: NSObject, UITextViewDelegate, ComposeAutocompleteHandler, ComposeTextViewCaretScrolling { weak var textView: UITextView? var text: Binding @@ -192,9 +221,16 @@ struct MainComposeWrappedTextView: UIViewRepresentable { } @objc func formatButtonPressed(_ sender: UIBarButtonItem) { - guard let textView = textView, textView.isFirstResponder else { return } let format = StatusFormat.allCases[sender.tag] - guard let insertionResult = format.insertionResult else { return } + applyFormat(format) + } + + func applyFormat(_ format: StatusFormat) { + guard let textView = textView, + textView.isFirstResponder, + let insertionResult = format.insertionResult else { + return + } let currentSelectedRange = textView.selectedRange if currentSelectedRange.length == 0 {