charmbracelet / huh

Build terminal forms and prompts 🤷🏻‍♀️
MIT License
3.72k stars 94 forks source link

Windows: Tab/Enter keys not handled correctly #286

Open seanamos opened 2 weeks ago

seanamos commented 2 weeks ago

Describe the bug I am unable to get input fields to work correctly on Windows. Every tab/enter press results in a space character being added to the field.

Tracing this down, it seems to be that the KeyMsg on Windows contains either the \t or \r runes respectively. The message is then sent to the textinput bubble which sanitizes the tab or carriage return to a `. Only after this, doeshuh.Input.Updatehandle the key, but at this point, ` has already been inserted into the field.

Testing on Mac, the tab and enter KeyMsg do not have any runes in them. Haven't tested on Linux yet.

To Reproduce Add input field to a form group. Press Tab/Enter on windows. Observe space character is inserted into the field.

Expected behavior No extra characters are inserted into the field.

Desktop (please complete the following information):

seanamos commented 2 weeks ago

To work around this, I implemented this hack:

//go:build windows

package winhax

import (
    "slices"

    tea "github.com/charmbracelet/bubbletea"
)

var (
    cleanKeyTypes = []tea.KeyType{
        tea.KeyTab,
        tea.KeyShiftTab,
        tea.KeyEnter,
    }
)

// Some keys on Windows carry runes with them (\t, \r, etc.).
//
// This removes those runes from the keypress.
func CleanKeys(msg tea.Msg) tea.Msg {
    switch msg := msg.(type) {
    case tea.KeyMsg:
        if slices.Contains(cleanKeyTypes, msg.Type) {
            msg.Runes = []rune{}
            return msg
        }
    }

    return msg
}