Elmでマウスの右クリックを検知するにはどうすれば?と思って調べた際のメモ。
mpizenberg/elm-pointer-events を使うのが楽そう。
左クリックor右クリックをボタンのテキストに表示するサンプルコード
module Main exposing (main)
import Browser
import Html exposing (Html, button, div, text)
import Html.Events.Extra.Mouse as Mouse
type alias Model = { buttonText : String }
type Msg = LeftClick | RightClick
initialModel : Model
initialModel =
{ buttonText = "Clicked: -" }
update : Msg -> Model -> Model
update msg model =
case msg of
LeftClick ->
{ model | buttonText = "Clicked: Left" }
RightClick ->
{ model | buttonText = "Clicked: Right" }
view : Model -> Html Msg
view model =
div []
[ button
[ Mouse.onClick (\_ -> LeftClick)
, Mouse.onContextMenu (\_ -> RightClick)
]
[ text model.buttonText ]
]
main : Program () Model Msg
main =
Browser.sandbox
{ init = initialModel
, view = view
, update = update
}
2022.12.10 追記
@ababup1192 さんから Html.Events.custom
でいけますよとのこと。
折角なので実装してみましょう。
Html.Events.custom版
module Main exposing (main)
import Browser
import Html exposing (Attribute, Html, button, div, text)
import Html.Events as Events
import Json.Decode as JD
-- (略)
view : Model -> Html Msg
view model =
div []
[ button
[ Events.onClick LeftClick
, Events.custom "contextmenu" <|
JD.succeed
{ message = RightClick
, stopPropagation = True
, preventDefault = True
}
]
[ text model.buttonText ]
]
-- (略)
OK👍