kyle-n / HighlightedTextEditor

A SwiftUI view for dynamically highlighting user input
MIT License
726 stars 69 forks source link

Custom actions on fx pressing Enter #70

Closed lmunck closed 1 year ago

lmunck commented 1 year ago

I love the project, but in the App I'm using this for, I have multiple text fields, and would like to switch focus from one to the next when pressing Enter. I can obviously just fork and add the feature, but I was thinking this was a generic enough requirement that I either missed that it was already there or that it might be worth adding to the project.

To illustrate the request, here is what I have made as a workaround for now:

.onTextChange {                                    
                                    if $0.contains("\n") {

                                    var str = $0

                                    while let pos = str.firstIndex(of: "\n") {
                                        str.remove(at: pos)
                                    }

                                    if str.isEmpty {
                                        markdownContent.remove(at: index)
                                    } else {
                                        markdownContent[index].markdown = str
                                    }

                                    nextItem()
                                }
                            } 
kyle-n commented 1 year ago

Oof, that is not a fun workaround.

In order to fix this, I'd have to add an onKeyPress modifier to HLTE. I'm not going to do that because Apple is actually adding onKeyPress in iOS 17 / macOS 14.

I recommend using Apple's modifier if possible. If your app supports an older version of iOS or macOS, I recommend forking HLTE and adding a textView function.

public func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
    if let event: NSEvent = NSApp.currentEvent {
        if event.modifierFlags.intersection(.deviceIndependentFlagsMask) == [.command] && event.keyCode == 36 {
            print("caught [⌘ + ⏎]")
        }
        return true
    }
    return false
}