Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
z5h opened this issue Oct 28, 2022 · 1 comment
Open

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

z5h opened this issue Oct 28, 2022 · 1 comment

Comments

@z5h
Copy link

z5h commented Oct 28, 2022

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
Copy link

lydell commented Oct 28, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants