LexiFi / ocaml-vdom

Elm architecture and (V)DOM for OCaml
MIT License
197 stars 13 forks source link

onkeydown event not working #36

Open aryx opened 3 years ago

aryx commented 3 years ago

For context, I try to port the elm-playground library to OCaml using ocaml-vdom. I manage to get a few examples working but I am currently stuck with the way the keyboard is handled in ocaml-vdom vs Elm.

I would like to generate a msg `Keydown each time the user press a key anyway in the page, but it does not work. Here is the smallest program showing the problem:

open Vdom

type model = string

let update _ = function
  | `Click -> 
      "Click:"
  | `Keydown s -> 
      "Keydown:" ^ s

let init = "EMPTY"

let view s =
  div
    ~a:[
    onkeydown (fun evt -> `Keydown (Printf.sprintf "%d" evt.which));
    autofocus;
  ]
    [
      div [text (Printf.sprintf "Content: %s" s)];
      div [input [] ~a:[onclick (fun _ -> `Click); type_button; value "Update"]]
    ]

let app = simple_app ~init ~view ~update ()

open Js_browser

let run () = Vdom_blit.run app |> Vdom_blit.dom |> Element.append_child (Document.body document)
let () = Window.set_onload window run
aryx commented 3 years ago

If I type a key in the page, nothing changes. However, if I click on the button, and then I type a key anywhere, then the event gets triggered.

aryx commented 3 years ago

Note that Elm provides not only an event for keydown but also for keyup (which are useful to implememt games with elm-playground).

aryx commented 3 years ago

Any help? Is this project dead? Should I switch to another OCaml library (e.g., Brr by daniel buenzli?)

alainfrisch commented 3 years ago

If no element under the div has the focus, the KeyDown event won't trigger. You might want to use a Custom elements to attach a global handler.

aryx commented 3 years ago

Is there any code doing that I could imitate? I'm not very familiar with those custom elements.

aryx commented 10 months ago

Is this issue fixed in the vdom 0.3 version? https://discuss.ocaml.org/t/ann-vdom-0-3-functional-ui-applications-now-with-custom-event-handlers/13298