Search code examples
elm

how to detect shift-enter in Elm?


I've adapted the onentercode from the todomvc example to create onShiftEnter, but it does not work. Apparently, shiftKey is not passed to Elm. So, how can I detect shift-Enter ?

onShiftEnter : Msg -> Attribute Msg
onShiftEnter msg =
  let
    tagger (code, shift) =
      if code == 13 && shift then msg else NoOp
  in
    on "keydown" 
       (Json.Decode.map tagger 
          ( Json.Decode.tuple2 (,)
              (Json.Decode.at ["keyCode"] Json.Decode.int)
              (Json.Decode.at ["shiftKey"] Json.Decode.bool)
          )
       )

Solution

  • use Json.Decoder.object2 instead. Json.Decoder.tuple2 is used for decoding arrays.

    import Json.Decode as Json exposing ((:=))
    
    onShiftEnter : Msg -> Attribute Msg
    onShiftEnter msg =
      let
        tagger (code, shift) =
          if code == 13 && shift then msg else NoOp
        keyExtractor =
          Json.object2 (,)
            ("keyCode" := Json.int)
            ("shiftKey" := Json.bool)
      in
        on "keydown" <| Json.map tagger keyExtractor