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

feat: key commands for external keyboards #243

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
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
31 changes: 31 additions & 0 deletions Sources/Views/InputTextView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,9 @@ open class InputTextView: UITextView {
}
}

open var registeredCommands: [UIKeyCommand] = []
open var registeredKeyCallbacks: [String: () -> Void] = [:]

/// A weak reference to the InputBarAccessoryView that the InputTextView is contained within
open weak var inputBarAccessoryView: InputBarAccessoryView?

Expand Down Expand Up @@ -231,6 +234,34 @@ open class InputTextView: UITextView {
}
}

// MARK: - Key Command

open override var keyCommands: [UIKeyCommand]? {
return registeredCommands
}

open func observeKeyInput(_ input: String, modifiers: UIKeyModifierFlags, discoverabilityTitle: String?, callback: @escaping (() -> Void)) {
if input == "" {
return
}
let keyCommand = UIKeyCommand(input: input, modifierFlags: modifiers, action: #selector(didDetectKeyCommand(_:)))
keyCommand.discoverabilityTitle = discoverabilityTitle
if #available(iOS 15.0, *) {
keyCommand.wantsPriorityOverSystemBehavior = true
}

let key = "\(input)_\(modifiers)"
registeredCommands.append(keyCommand)
registeredKeyCallbacks[key] = callback
}

@objc private func didDetectKeyCommand(_ keyCommand: UIKeyCommand) {
if keyCommand.input == nil { return }
let key = "\(String(describing: keyCommand.input!))_\(keyCommand.modifierFlags)"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a big fan of this force unwrap - can we figure out better way for the key?

let callback = registeredKeyCallbacks[key]
callback?()
}

// MARK: - Image Paste Support

open override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
Expand Down