Incorrect View Functon Return Type in elm - elm

I am making a program that changes the rendered text on the screen to be whatever the user inputs in a text box. I think I have the model and the update part of the elm architecture correct, but I really don't understand the view portion.
I'm just having trouble wrapping my head around the square bracket view functions.
Anyway, I am getting this error.
This div call produces:
Html #(Model -> Model)#
But the type annotation on view says it should be:
Html #Msg#Elm
But I am not sure how to change my view function to return Html Msg and I am kinda confused between the difference between that and a string.
Thank you everyone!
Here is my code ...
module Main exposing (..)
import Browser
import Html exposing (Html, div, text, input, Attribute)
import Html.Attributes exposing (..)
import Html.Events exposing (onInput)
main =
Browser.sandbox { init = init, update = update, view = view }
type alias Model = String
init : Model
init = "Hello, World!"
type alias Msg = String
update : Msg -> Model -> Model
update msg model =
msg
view : Model -> Html Msg
view model =
div []
[ input [ placeholder "Input new string", value model, onInput update ] []
, div [] [ text model ]
]

You're passing the update function as an argument to onInput. Your probably meant to pass it a Msg, which the runtime will then pass to the update function.
Since your Msg type is an alias for String, you can use onInput identity

Related

Elm and VSCode: Formatter messes up spacing

So I started learning Elm today. I use VSCode as my editor.
I followed the docs for the set up and installed elm as well as el-format via npm install -g elm elm-format. I also installed the VSCode Elm extension.
Next, in my settings.json I set:
"[elm]": {
"editor.formatOnSave": true
},
Then I went on with the tutorial. In it the code is formatted like this:
import Browser
import Html exposing (Html, Attribute, div, input, text)
import Html.Attributes exposing (..)
import Html.Events exposing (onInput)
-- MAIN
main =
Browser.sandbox { init = init, update = update, view = view }
-- MODEL
type alias Model =
{ content : String
}
init : Model
init =
{ content = "" }
-- UPDATE
type Msg
= Change String
update : Msg -> Model -> Model
update msg model =
case msg of
Change newContent ->
{ model | content = newContent }
-- VIEW
view : Model -> Html Msg
view model =
div []
[ input [ placeholder "Text to reverse", value model.content, onInput Change ] []
, div [] [ text (String.reverse model.content) ]
]
But when I hit safe, it formats the code like this:
module Main exposing (Model, Msg(..), init, main, update, view)
import Browser
import Html exposing (Attribute, Html, div, input, text)
import Html.Attributes exposing (..)
import Html.Events exposing (onInput)
-- MAIN
main =
Browser.sandbox { init = init, update = update, view = view }
-- MODEL
type alias Model =
{ content : String
}
init : Model
init =
{ content = "" }
-- UPDATE
type Msg
= Change String
update : Msg -> Model -> Model
update msg model =
case msg of
Change newContent ->
{ model | content = newContent }
-- VIEW
view : Model -> Html Msg
view model =
div []
[ input [ placeholder "Text to reverse", value model.content, onInput Change ] []
, div [] [ text (String.reverse model.content) ]
]
So it adds extra lines, and extra module Main exposing ... and doubles the number of spaces. I tried setting spaces to 2 again using the footer in VSCode, but that didn't help.
My questions are:
Is it okay that saving adds the extra module Main ...?
Is having 2 spaces best practice / community standard, or 4?
If it is 2 (like it is in the tutorial's default code) how can I get my formatter to respect that?
If it is not, why has the tutorial the non-standard indentation?
First of all, this question is both too broad and primarily opinion-based and will probably be closed because of that. It would have been more suited for the forums I think.
That said, I'm going to try to answer it as best as I can anyway, since it's here:
Yes? Most modules won't be very useful without exposing something and it's good practice to be explicit about what's being exposed.
elm-format is the community standard, so 4 it is.
You can't. This is by design. It has also been discussed to death in various fora. Here's one issue discussing it
You'd have to ask Evan about that. It might be related to formatting for the web, or just Evan being lazy.

Elm - How to use HTML events?

The Elm getting started guide doesn't seem to use the standard Elm HTML events and I'm not sure how to use them. For example, onBlur:
view model =
div []
[ div []
input [ type_ "text", onInput MsgA ] []
, input [ type_ "text", onBlur MsgB ] []
]
This fails in the compiler because now I am returning type Html (String -> Msg) on line 3 but Html (Msg) in line two.
Why are these two events incompatible? Is there any way to use both at the same time? Additionally, the docs don't make it clear enough for someone like me to understand how to use onBlur.
onBlur has a different type signature than onInput.
onInput : (String -> msg) -> Attribute msg
onBlur : msg -> Attribute msg
That means whatever Msg you use for onInput has to take a single string parameter. Likewise, the Msg used in onBlur cannot take a parameter. If you redefined MsgA and MsgB to the following, it would compile:
type Msg
= MsgA String
| MsgB
Edit
If you wanted your blur handler to be able to accept the target value, you can roll your own like this:
import Html.Events exposing (on, targetValue)
import Json.Decode as Json
onBlurWithTargetValue : (String -> msg) -> Attribute msg
onBlurWithTargetValue tagger =
on "blur" (Json.map tagger targetValue)

Elm no data except isTrusted in JSON events

I wrote a simple program based on time example, to test what data are in events. It decodes JSON to value then encodes it back to JSON, then show it in SVG text element. And the only thing I get is {"isTrusted":true}.
Why that happens? How do I get another data of event? I'm using Firefox 49 and online compiler:
import Html exposing (Html)
import Svg exposing (..)
import Svg.Attributes exposing (..)
import Svg.Events exposing(on)
import Json.Decode as Json
import Json.Encode exposing (encode)
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model = String
init : (Model, Cmd Msg)
init =
("No event", Cmd.none)
-- UPDATE
type Msg
= Event String
update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
Event event ->
(event, Cmd.none)
subscriptions model = Sub.none
stringifyEvent: Json.Encode.Value -> Msg
stringifyEvent x =
Event (encode 2 x)
-- VIEW
view : Model -> Svg Msg
view model =
svg [ viewBox "0 0 300 300", width "300px", on "mousedown" (Json.map stringifyEvent Json.value) ] [
text_ [x "0", y "30"] [text model]
]
When I try in console
svgElement.addEventListener('click', function(e) {console.log(e)})
It works with all the attributes.
I do not know a way to achieve your goal.
But I can give you an answer why it does the way you described.
If you look at the source code, you'll find that Elm runtime uses
JSON.stringify() for converting Value to String.
And guess what...
svgElement.addEventListener('click', function(e) {console.log(JSON.stringify(e))})
will give you {"isTrusted":true} when you click...

What does a function with 2 values on the right side mean? (Model -> Html msg)

I have encountered that in the guide:
viewValidation : Model -> Html msg
viewValidation model =
let
(color, message) =
if model.password == model.passwordAgain then
("green", "OK")
else
("red", "Passwords do not match!")
in
div [ style [("color", color)] ] [ text message ]
So this is a function, which takes the Model.
Html msg usually looks to me like we are calling the function Html with the argument msg.
msg doesn't seem to play any role in any other part of the viewValidation function, though. So what does it mean and what is it for in this case?
Html Msg is just a type parameter, as List Int is. While List Int denotes a list that contains element of type Int, similarly Html Msg describes some HTML that can treat/emit messages of type Msg.
For example, if you have a button inside your HTML, it could look like this:
button [ onClick DoSomething ] [ text "caption" ]
Where DoSomething is a case of the Msg type.
Don't mix the type definition with the normal execution of code. Html is not a function, it is a type that takes a parameter to define a type for a view function.
Html msg is the most general definition you can have as msg is a variable itself, so this returns Html that is independent of the msg type you are currently using. This could either be because it creates no event messages, or because the view function takes messages as parameters.
As the comments established Html () would be a very narrow type that is constrained to return nothing.
The most common case though will be a view function returning Html Msg - i.e. Html with messages based on user interactions.
As Elm encourages componentization, you also need keep Html.map in mind. It's type signature is Html.map : (a -> b) -> Html a -> Html b. In the context of components this is more easily read as
Html.map : (Child.Msg -> Parent.Msg) -> Html Child.Msg -> Html Parent.Msg
Note that when you define your messages in your parent component, you will have something like:
type Msg = ChildMsg Child.Msg
which means that ChildMsg has type signature:
ChildMsg : Child.Msg -> Parent.Msg
So my view functions have a lot of
parentView model =
-- childView model.child |> Html.map ChildMsg
Html.map ChildMsg (childView model.child)

How to debounce elm signals?

Im using start-app to shape my application. Html.Events supports creating custom events with custom Signal.message. But how to send that message is abstracted behind the Html library. Also there is a library called which implements debouncing (http://package.elm-lang.org/packages/Apanatshka/elm-signal-extra/5.7.0/Signal-Time#settledAfter).
SearchBar.elm:
module PhotosApp.SearchBar (view) where
import Html exposing (input, div, button, text, Html)
import Html.Events exposing (on, onClick, targetValue)
import Html.Attributes exposing (value, type')
import Effects exposing (Effects, Never)
import PhotosApp.Actions as Actions
onTextChange : Signal.Address a -> (String -> a) -> Html.Attribute
onTextChange address contentToValue =
on "input" targetValue (\str -> Signal.message address (contentToValue str))
view : Signal.Address Actions.Action -> String -> Html
view address model =
div []
[ input [ type' "text", value model, onTextChange address Actions.Search] []
, button [ onClick address Actions.Clear ] [text "Clear"]
]
You can set up debouncing from an HTML attribute by going through a proxy mailbox before tying into #Apanatshka's settledAfter function.
(Note that since you're using StartApp, we don't have direct access to the main Address and therefore I've had to compromise a few of these functions by ignoring the address passed into view. You could get something more generalized by not using StartApp, but this should hopefully get you started)
Since event attributes cannot create tasks directly, we have to use an intermediate proxy mailbox. We can set that up like this:
debounceProxy : Signal.Mailbox Action
debounceProxy =
Signal.mailbox NoOp
Note that the above function expects a NoOp Action, common in Elm architecture, which just means the update function makes no changes to the model.
Now we need to set up another Signal which listens to the proxy mailbox, then passes the signal through the settledAfter function. We can define this signal like this:
debounce : Signal Action
debounce =
settledAfter (500 * Time.millisecond) debounceProxy.signal
We can now change the onTextChange function to point at the proxy mailbox. Notice that I've taken out the first Address parameter since it's being ignored (see my earlier comment about conforming to StartApp):
onTextChange : (String -> Action) -> Html.Attribute
onTextChange contentToValue =
on "input" targetValue (\str -> Signal.message debounceProxy.address (contentToValue str))
Lastly, you have to tie in the debounce signal into StartApp's inputs parameter, which means your call to start will look something like this:
app = StartApp.start
{ init = init
, update = update
, view = view
, inputs = [ debounce ]
}
I've pasted the full working example at a gist here.