Search code examples
elmelm-signal

Keyboard keyup signal missing


I need Keyboard keyup signal. But the STD library has only keydown which causes "freezes" in my program thanks to very fast changing game state (pause and play). How to solve it?


Solution

  • Look into the elm-signal-extra package: http://package.elm-lang.org/packages/Apanatshka/elm-signal-extra/3.3.1

    Specifically, there is a function Signal.Discrete.whenChangeTo : a -> Signal a -> EventSource (EventSource is a type alias of Signal ())

    The following program will display True on the screen for 500 milliseconds following every time there is a keyup on the Enter key:

    import Text (asText)
    import Keyboard
    import Signal
    import Signal.Discrete (whenChangeTo)
    import Signal.Time (since)
    
    enterKeyUp = whenChangeTo False (Keyboard.isDown 13)
    
    main = Signal.map asText (since 500 enterKeyUp)
    

    Edited:

    I added the since 500 enterKeyUp just as an easy visual to see that the enterKeyUp signal is working. Here's another example that shows how to use it without the 500 ms part. It displays the number of times the enter key has been released:

    import Text (asText)
    import Keyboard
    import Signal
    import Signal.Discrete (whenChangeTo)
    import Signal.Time (since)
    
    enterKeyUp = whenChangeTo False (Keyboard.isDown 13)
    
    count : Signal a -> Signal Int
    count signal = foldp (\_ x -> x + 1) 0 signal
    
    main = Signal.map asText (count enterKeyUp)