Skip to content

Instantly share code, notes, and snippets.

@justinmimbs
Created June 12, 2017 12:28
Show Gist options
  • Save justinmimbs/caef35d7975d76fd0ea57d8fbf797abf to your computer and use it in GitHub Desktop.
Save justinmimbs/caef35d7975d76fd0ea57d8fbf797abf to your computer and use it in GitHub Desktop.
module Main exposing (..)
import Html exposing (Html)
import Html.Attributes
import Html.Events
import Json.Decode as Decode exposing (Decoder)
{-
(Chrome only)
While the input has focus, press the Enter key.
This replaces the input element, as expected. When the removed input fires
a blur event, we expect it to send a Blur message through the Close tagger.
Instead the Blur message is sent through the Open tagger.
-}
main : Program Never Model Msg
main =
Html.beginnerProgram
{ model = True
, update = update
, view = view
}
type alias Model =
Bool
type Msg
= Open String
| Close EventType
type EventType
= Keydown
| Blur
update : Msg -> Model -> Model
update msg isEditing =
case msg |> Debug.log "msg" of
Open value ->
let
_ =
-- We can throw an exception if value is not a string.
String.toUpper value
in
True
_ ->
False
view : Model -> Html Msg
view isEditing =
if isEditing then
-- The problem does not occur when the nodes have a different number of
-- taggers, so adding, e.g., `|> Html.map identity` to one of the cases
-- below will prevent the problem.
viewEditor "editor" |> Html.map Close
else
viewReader "reader" |> Html.map Open
viewReader : String -> Html String
viewReader value =
Html.div
[ Html.Events.onClick value
]
[ Html.text value
]
viewEditor : String -> Html EventType
viewEditor value =
Html.input
[ Html.Events.on "keydown" decodeKeydown
, Html.Events.onBlur Blur
, Html.Attributes.autofocus True
, Html.Attributes.value value
]
[]
decodeKeydown : Decoder EventType
decodeKeydown =
Decode.field "key" Decode.string
|> Decode.andThen
(\key ->
if key == "Enter" then
Decode.succeed Keydown
else
Decode.fail ""
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment