elm / virtual-dom

The foundation of HTML and SVG in Elm.
https://package.elm-lang.org/packages/elm/virtual-dom/latest
BSD 3-Clause "New" or "Revised" License
209 stars 80 forks source link

lazy can cause loss of user's input focus #184

Open z5h opened 1 year ago

z5h commented 1 year ago

VDOM diffing follows the logic as outlined in its comment:

// Bail if you run into different types of nodes. Implies that the // structure has changed significantly and it's not worth a diff.

This means it will bail if it runs into a thunk/node diff, even if the thunk would generate the same output as the node.
If follows that conditional use of lazy can trigger DOM node deletion/creation even for nodes that do not change, and this will cause a loss of user's input focus if a text input is recreated.

Below is an example where lazy is used to render input only when it contains an "s", and every time that condition changes the user's input focus will be lost.

SSCCE

module Main exposing (main)

import Browser
import Html exposing (Html, input)
import Html.Attributes exposing (value)
import Html.Events exposing (onInput)
import Html.Lazy

type alias Model =
    String

initialModel : Model
initialModel =
    "Don't delete the \"s\""

type Msg
    = InputChanged String

update : Msg -> Model -> Model
update msg model =
    case msg of
        InputChanged s ->
            s

view : Model -> Html Msg
view model =
    if String.contains "s" model then
        Html.Lazy.lazy viewInput model

    else
        viewInput model

viewInput : String -> Html Msg
viewInput s =
    input [ value s, onInput InputChanged ] []

main : Program () Model Msg
main =
    Browser.sandbox
        { init = initialModel
        , view = view
        , update = update
        }
lydell commented 1 year ago

Linking the Discourse thread for extra context: https://discourse.elm-lang.org/t/elm-virtual-dom-bug/8732