Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elm check whether ctrl key pressed onClick

Tags:

elm

Using elm-html, how can I check whether the ctrl key is pressed at the time of the click?

Is "control key down" some state I'd need to maintain elsewhere, perhaps using the Keyboard module? If so, how would that fit into elm-html?

I've adapted the code below from one of the well-known elm examples:

import Keyboard
import Html exposing (..)
import Html.Attributes exposing (style)
import Html.Events exposing (onClick)
import Signal exposing(Signal, Mailbox)


type alias Model =
  { count: Int
  , ctrl : Bool
}

initialModel : Model
initialModel = { count = 0, ctrl = False}

type Action = Increment | Decrement | NoOp

update : Action -> Model -> Model
update action model =
  case action of
    Increment ->
      { model | count = model.count + 1 }
    Decrement ->
      { model | count = model.count - 1 }
    NoOp ->
      model


view : Signal.Address Action -> Model -> Html
view address model =
  div []
    [ button [ onClick address Decrement ] [ text "-" ]
    , div [] [ text (toString model) ]
    , button [ onClick address Increment ] [ text "+" ]
    ]


actions : Mailbox Action
actions =
  Signal.mailbox NoOp

model : Signal Model
model =
  Signal.foldp update initialModel actions.signal -- Keyboard.ctrl ?

main =
  Signal.map (view actions.address) model

How can I update the value of the model's "ctrl" field?

like image 529
tenuej Avatar asked Sep 05 '25 03:09

tenuej


1 Answers

You first need an Action capable of setting the value of whether CTRL is pressed:

type Action = Increment | Decrement | SetCtrl Bool | NoOp

Your case statement in the update function needs to handle that new action:

SetCtrl bool -> { model | ctrl = bool }

And now you need a port that can map the Keyboard.ctrl boolean to a task which sends a signal with the new Action:

port ctrlToAction : Signal (Task.Task Effects.Never ())
port ctrlToAction =
  Signal.map (Signal.send actions.address << SetCtrl) Keyboard.ctrl
like image 148
Chad Gilbert Avatar answered Sep 07 '25 22:09

Chad Gilbert