import SwiftUI

// A vertical TextField treats Return as editing, not form submission. Handle
// unmodified Return explicitly on Mac, leaving Shift+Return and other modified
// keys to the native text field. iOS keeps its software-keyboard behavior.
@MainActor
enum SybilReturnKeySubmission {
    static func handle(
        phase: KeyPress.Phases,
        modifiers: EventModifiers,
        submit: () -> Void
    ) -> KeyPress.Result {
        guard modifiers.intersection([.shift, .command, .control, .option]).isEmpty else {
            return .ignored
        }
        if phase == .down {
            submit()
        }
        // Consume autorepeat without submitting or inserting a newline.
        return .handled
    }
}

extension View {
    @ViewBuilder
    func submitOnMacReturn(_ submit: @escaping () -> Void) -> some View {
        #if targetEnvironment(macCatalyst)
        onKeyPress(keys: [.return, KeyEquivalent("\u{3}")], phases: [.down, .repeat]) { press in
            SybilReturnKeySubmission.handle(phase: press.phase, modifiers: press.modifiers, submit: submit)
        }
        #else
        self
        #endif
    }
}
