elm-lang / mouse

Track global mouse clicks and movements, helpful for dragging.

Home Page:http://package.elm-lang.org/packages/elm-lang/mouse/latest

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Custom decoder

MazeChaZer opened this issue · comments

I would like the get the clientX/clientY coordiantes instead of pageX/pageY. Is this possible?

Someone answered here but it's a bit old. Here's how I wrote a custom decoder to get pageX, pageY, and which button was pressed. It think you just need to change the "pageX" to "clientX".

I confess I'm not sure how to put this in a subscription (that is, how you would use it with this library) - can anyone fill in the blanks on that?

type alias MouseEvent = {pos: Mouse.Position, button: Int}
type Msg =  SomeMsg MouseEvent

decodeClickEvent : (MouseEvent -> a) -> JSD.Decoder a
decodeClickEvent fn =
  let toA : Int -> Int -> Int -> a
      toA px py button =
        fn {pos= {x=px, y=py}, button = button}
  in JSDP.decode toA
      |> JSDP.required "pageX" JSD.int
      |> JSDP.required "pageY" JSD.int
      |> JSDP.required "button" JSD.int

In your HTML, instead of using Events.mouseDown, you use

    Html.Events.on "mousedown" (decodeClickEvent (SomeMsg))

@pbiggar Thanks for your input

I think the problem is, that this library doesn't allow you to pass your own JSON decoder, there is one fixed decoder which extracts the values for pageX and pageY.

It would be great if it was possible to pass your own decoders to the subscription.

That would be useful for me too. I don't see any way to get mouse event attributes from a subscription otherwise.

Custom decoder needed here as well. For the time being, I'm just working about this problem by copying the Mouse module into our project and redefining the internal position decoder to suit our needs.

+1000 on this.

A custom decoder would allow to implement an "onClickOutside" subscription, by checking all the element ids from the event.target to document.
This would be a similar approach to that used by https://github.com/Pomax/react-onclickoutside

You can modify the Mouse module to expose all mouse event properties and listen to any type of event. Demo

This is possible with the new elm/browser package, in the Browser.Events module.