Not Found: "Navigation.Parser" and "Navigation.makeParser" - elm

I have the following errors that I am struggling to resolve based on the latest version of elm-lang/Navigation:
-- NAMING ERROR ------------------------------------------------------- Home.elm
Cannot find variable Navigation.makeParser.
231| Navigation.makeParser parse
^^^^^^^^^^^^^^^^^^^^^ Navigation does not expose makeParser.
-- NAMING ERROR ------------------------------------------------------- Home.elm
Cannot find type Navigation.Parser.
229| urlParser : Navigation.Parser Route
^^^^^^^^^^^^^^^^^ Navigation does not expose Parser.
Note:
It looks like Parser and makePaser were removed from Navigation in version 2.1.0.
Is there an updated example of how to do navigation leveraging the urlParser function?
I have the following:
import Navigation exposing (..)
main : Program Never
main =
Navigation.program urlParser
{ model = model
, update = update
, urlUpdate = urlUpdate
, view = view
}
...
-- NAVIGATION
parse : Navigation.Location -> Route
parse { pathname } =
let
one =
Debug.log "path" pathname
in
case pathname of
"index.html" ->
HomeRoute
_ ->
NotFound
urlParser : Navigation.Parser Route
urlParser =
Navigation.makeParser parse

The Parser concept was removed during the Elm 0.18 to simplify the API. Now you just need to supply a function that takes a Location and returns a Msg as the first parameter to program function.
That function could simply be a Msg constructor that takes a Location argument, as shown in the example from the examples directory (here is live example on ellie-app.com)
type Msg
= UrlChange Navigation.Location
Your update function would then handle the UrlChange Msg and act accordingly. You can still use Location parsing packages like evancz/url-parser.

Related

How do I add dynamic content in the HTML part of my Elm file without getting a "Type mismatch error"?

I have an Elm file with some HTML content in a function called view.
Part of the HTML content is dynamically generated via a map function that extracts data from a record.
Below is the code from that file.
module PhotoGroove exposing (main)
import Html exposing (div,h1,img,text)
import Html.Attributes exposing (..)
--model
initialModel : { photos : List { url : String }, selectedPhoto : String }
initialModel =
{ photos =
[ { url = "1.jpeg" }
, { url = "2.jpeg" }
, { url = "3.jpeg" }
]
, selectedPhoto = "1.jpeg"
}
--view
urlPrefix : String
urlPrefix = "http://elm-in-action.com/"
viewThumbnail : String -> { a | url : String } -> Html.Html msg
viewThumbnail selectedPhoto thumb =
if selectedPhoto == thumb.url
then img [src (urlPrefix ++ thumb.url), class "selected"] []
else img [src (urlPrefix ++ thumb.url)] []
view : List { a | url : String } -> Html.Html msg
view model =
div [class "context"]
[h1 [] [text "Photo Groove"]
,div [id "tumbnail"] (List.map viewThumbnail model) -- error message on "model"
]
--main
main = view initialModel -- error message on "initialModel"
However, I got error messages on the words "model" and "initialModel".
Below is the error message for "model":
TYPE MISMATCH - The 2nd argument to `div` is not what I expect:
29| ,div [id "tumbnail"] (List.map viewThumbnail model)
#^^^^^^^^^^^^^^^^^^^^^^^^^^^^#
This `map` call produces:
List #({ a | url : String } -> Html.Html msg)#
But `div` needs the 2nd argument to be:
List #(Html.Html msg)#
#Hint#: I always figure out the argument types from left to right. If an argument
is acceptable, I assume it is “correct” and move on. So the problem may actually
be in one of the previous arguments!
And for initialModel:
TYPE MISMATCH - The 1st argument to `view` is not what I expect:
35| main = view initialModel
#^^^^^^^^^^^^#
This `initialModel` value is a:
#{ photos : List { url : String }, selectedPhoto : String }#
But `view` needs the 1st argument to be:
#List { a | url : String }#
I got that I need to somehow convert the objects directly into HTML msg types, but I don't know how.
I even tried to change the type for view, but that did not work either.
How do I fix this problem?
This is a great example of Elm's type system (or a good static type system in general) helping you figure out logical errors in your code.
The problems here are all due to your view function, and in particular with faulty assumptions it makes about what is in your model.
You are trying to map a function over the model argument, which assumes model is a list - but it isn't, it's a record containing both a list of all photos and a string identifying the selected photo. That makes logical sense as a model to use in this situation, so rather than changing the model type (which would otherwise be a sensible option) I would suggest changing view so that it works with your actual model type.
Another problem, which is highlighted in the first of the 2 error messages you quote, is that viewThumbnail can't be mapped over a list of photos anyway because it actually takes 2 arguments, the first of which isn't a list. You do want to use this function to produce the list of images in view's output - but you also need to provide it with the selectedPhoto, which of course comes from the other field in your model that you've ignored so far.
So the only changes needed to your original code to get this to compile are:
change the type signature of view to actually match your model's type. (This is what the second of the two error messages is about). It should be view : { photos : List { url : String }, selectedPhoto : String } -> Html.Html msg (You probably want to make a type alias for this model type, at least if you expand this app to any much greater size.)
inside the function body,
change this
List.map viewThumbnail model
to
List.map (\photo -> viewThumbnail model.selectedPhoto photo) model.photos
Hopefully you can see what the above is doing - the \ is for an anonymous function, that takes one of the photos and calls viewThumbnail with that as second argument and model.selectedPhoto always as the first argument.
And note finally that you can simplify the above by taking advantage of Elm's built-in function currying, to just
List.map (viewThumbnail model.selectedPhoto) model.photos
which I and probably most others familiar with functional programming find much cleaner and easy to read.

What is the 'msg' in 'HTML msg' in Elm actually?

I'm teaching myself elm and see (of course) many references to Html msg--
I understand that this is a 'parameterised type', that is, that (as I understand it), the constructor of the type Html takes a parameter -- much as List Char does.
OK. But then in following along in some tutorials, I see they quickly change the msg to be a custom type, often something like this (I'm doing this from memory, so please forgive me):
Html Msg
where Msg might be defined as
type Msg =
Something | SomethingElse
I also see that here -- https://discourse.elm-lang.org/t/html-msg-vs-html-msg/2758 -- they say
The lower case msg is called a type variable. The upper case Msg is called a concrete type - its something your application has defined.
That answers my question part way, but could someone elaborate on what this means exactly? Because when I see something like List String, I understand what String is in this context, but I don't understand what msg means in Html msg.
Also, are we not changing the type of the return value of the function? That is, if the Elm runtime is expecting view to return a certain type, and that type is Html msg, if we change the return type to Html Whatever, why does that work? (For instance, we can't change a function's return value from List String to List Number arbitrarily, right?)
Coming from a background in OOP and typed languages like C, TypeScript, etc, I would think that any Msg would need to somehow be related to msg, that is 'extend' it in some way to allow polymorphism. Obviously I'm looking at this the wrong way, and any explanation would be appreciated!
tl;dr: as long as every function agrees on the type of msg, and model, they can be anything you want.
Just like the type parameter of List, msg can be anything. There is no restriction. To demonstrate, here's the classic increment/decrement example with the msg being just an Int:
-- These type aliases aren't needed, but makes it easier to distinguish
-- their roles in later type signatures
type alias Model = Int
type alias Msg = Int
update : Msg -> Model -> Model
update msg model =
model + msg
view : Model -> Html Msg
view model =
div []
[ button [ onClick 1 ] [ text "+1" ]
, div [] [ text <| String.fromInt model.count ]
, button [ onClick (-1) ] [ text "-1" ]
]
main : Program () Model Msg
main =
Browser.sandbox { init = 0, view = view, update = update }
So how does that work? The key is in the Browser.sandbox function, as that's what connects everything together. Its type signature is:
sandbox :
{ init : model
, view : model -> Html msg
, update : msg -> model -> model
}
-> Program () model msg
where model and msg are type variables. Both of these can be replaced with any concrete type, as long as it matches up with the constraints given in this signature, which is that they must be the same across the init, view and update functions. Otherwise we'll get a type error here. If, for example, update requires a String instead of an Int, we'll get the error:
This argument is a record of type:
{ init : Model, update : String -> Model -> Model, view : Model -> Html Msg
}
But `sandbox` needs the 1st argument to be:
{ init : Model
, update : String -> Model -> Model
, view : Model -> Html String
}
It doesn't really know which is right or wrong, of course, just that there's a mismatch. But in an effort to be helpful it assumes String is right and expects view to return Html String instead.
I hope that sufficiently answers your question. If not, comment and subscribe!
Short and Simple Explanation:
I have an xmas function like this:
wrapPresents : presents -> String
But what is the type, presents? It can be anything that you want! You can substitute it with your own 'concrete type'. presents is just a place holder!
wrapPresents : Boxes -> String
Now we have the "type" - we know that the first parameter must be a Box type.
wrapPresents boxes = "All the boxes are now wrapped!"
Summary: msg (lowercase) is simply a placeholder

Intercepting 401 for any response in Elm

I'm building an application in Elm where most API calls are protected; i.e. the user needs to be logged in for the API call to work. If the user is not logged in, they will receive a 401 Unauthorized response. I want the application to redirect to the login page if any response is a 401.
Currently, I only have this redirect set up for a single API call. Here is a stripped-down version of the code to give an idea of how it's set up:
-- Util/Api.elm
type alias Data data =
{ data : data
}
-- Resources/Expense.elm
getExpenses : (Progress (Api.Data (List Expense)) -> msg) -> Sub msg
getExpenses msg =
(dataDecoder expenseListDecoder)
|> Http.get expensesEndpoint
|> Progress.track expensesEndpoint msg
-- Main/Msg.elm
type Msg
= ExpenseListMsg ExpenseListMsg
| RedirectToLogin
-- Main/Update.elm
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
ExpenseListMsg msg ->
ExpenseList.Update.update msg model
GoTo path ->
model ! [ Navigation.newUrl path ]
RedirectToLogin ->
model ! [ Navigation.load "path/to/login" ]
-- ExpenseList/Msg.elm
type ExpenseListMsg
= GetExpensesProgress (Progress (Api.Data (List Expense)))
| SetLoading
-- ExpenseList/Update.elm
update : ExpenseListMsg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
SetLoading ->
{ model | expenses = setExpensesLoading model.expenses } ! []
GetExpensesProgress (Done { data }) ->
{ model | expenses = addExpenses model.expenses data } ! []
GetExpensesProgress (Fail (BadStatus { status })) ->
case status.code of
401 ->
model ! [ msgToCmd RedirectToLogin ]
_ ->
model ! []
GetExpensesProgress (Fail error) ->
model ! []
GetExpensesProgress progress ->
{ model | expenses = setExpensesLoading model.expenses } ! []
Essentially, I want to move the logic around 401 responses from ExpenseList/Update.elm up to Main/Update.elm so that I can use it for any request I want.
I attempted a number of things, but nothing quite worked with Elm's type system. For example, one thing I wanted to do was try to do a nested pattern match with missing specificity in the middle, e.g.:
-- Main/Update.elm
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
ApiCall (messageType (msg (Fail (BadStatus { status })))) ->
case status of ->
. . .
. . .
I was hoping something like this would work and would match a message that looked like: ApiCall (ExpenseListMsg (GetExpensesProgress (Fail (BadStatus)))). Unfortunately, it's not proper Elm syntax, so my code didn't compile.
How can I write something that will allow me to mark an API call as protected and catch 401 errors at the top level in Main.Update.update?
Currently, the API call is encapsulated by the ExpenseList/Update module. This encapsulation is what makes the API call results unavailable to the Main module. The interaction works like this: Main -> FeatureModule -> API
Because the API is what provides the information needed to determine whether the app should redirect to the login page, and you want the Main module to perform the redirect, the Main module needs access to the API. Hence, the encapsulation needs to go. Instead, you can:
Have an API module which provides the low-level API functionality by producing Tasks. Unlike producing Cmds, this allows the caller, such as the Main module to decide how to handle the result of the Task, which can be acquired by converting the Task to a Cmd and giving it to the Elm runtime for execution.
Have the ExpenseList.Update module use the API module to create Tasks.
With this arrangement:
The Main module sends high-level commands to a feature module, which then uses the API module to produce the low-level instructions, which are then provided to the Main module.
The Main module doesn't need to care what those low-level instructions are, it simply converts the Task to a Cmd and waits for the result.
When the result comes back it's in a low-level format (ex. Success/Fail). At this point the Main module can jump in and handle the redirect on a 401 error. Otherwise, it can pass the result to a feature module so it may handle the result.

How to use scalajs-bundler with client only app

In another question I was advised to use ScalaJS bundler to import NPM dependencies.
I would like to use some Javascript NPM packages in a simple client-only web application. There is an example called static which shows this.
My changes to the example:
Add into build.sbt:
npmDependencies in Compile += "esprima" -> "3.1.3"
Add into Main.scala:
import Esprima._
import JsonToString._
val code = "answer = 42"
val tokens = tokenize(code)
val tokensStr = tokens.json
Change in Main.scala: "This is bold" into s"This is bold $tokensStr"
Facade (a bit simplified, for full a version see GitHub):
import scala.scalajs.js
import scala.scalajs.js.annotation.JSName
#JSName("esprima")
#js.native
object Esprima extends js.Object {
def tokenize(input: String, config: js.Any = js.native, delegate: String => String = js.native): js.Array[js.Any] = js.native
def parse(input: String, config: js.Any = js.native): js.Dynamic = js.native
}
When running the html generated with fastOptJS::webpack the error is:
Uncaught TypeError: Cannot read property 'tokenize' of undefined
Inspecting the static-fastopt-bundle.js shows esprima is used, but its js is not bundled.
What other steps are needed to add dependencies into a client-only web page?
As described in this part of the documentation, you have to use #JSImport in your facade definition:
#JSImport("esprima", JSImport.Namespace)
For reference, #JSName defines a facade bound to a global name, while #JSImport defines a facade bound to a required JavaScript module.

Elm: Update a command coming from nested module

In my Elm app, there is a parent and a child. I would like the child to send an HTTP command and then the parent would update it on the fly by adding the backend config that the child model doesn't have.
The way I see it is:
The child sends the HTTP command (update function)
The command is transferred to the parent (update function)
The parent adds the config to command (is this possible??)
The command is finally executed with all the required parameters
I would like to implement HTTP actions in children modules so my app remains modular while keeping the config in one place.
Any help is welcome. Maybe a different approach can solve my problem too!
Keep all the configuration details in a module that handles the Http Requests. For example, you can have this code in Requests.elm
import Http
import Task
url = "http://ip.jsontest.com/"
getIP : (String -> msg) -> Cmd msg
getIP tagger =
Http.getString url
|> Task.perform (\e -> tagger (toString e)) tagger
and then in the Component code have something like
update msg model =
case msg of
GetIP -> model ! [Requests.getIP ShowIP]
ShowIP str -> {model | ipStr = str} ! []
all the configuration details are hidden from the component. Only an API of access is exposed.
LATER EDIT:
Another option would be to define and pass around a dynamic Context. You can manage this context at the top level and just pass the current version around when you update things. It would look like this
In Requests.elm
import Http
import Task
type alias Context =
{ url : String }
getIP : Context -> (String -> msg) -> Cmd msg
getIP ctx tagger =
Http.getString ctx.url
|> Task.perform (\e -> tagger (toString e)) tagger
in Components:
update ctx msg model =
case msg of
GetIP -> model ! [Requests.getIP ctx ShowIP]
ShowIP str -> {model | ipStr = str} ! []