This document discusses how to structure an Elm single page application (SPA) to divide it into page modules and handle browser navigation. It recommends dividing the main model into separate models for each page module. The update function delegates messages to each module using Cmd.map. Browser location is managed using the Browser.Navigation module to enable back/forward navigation and bookmarking by parsing the URL on initialization and when the URL changes.
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
Elm SPA navigation
1. Dividing a SPA
Navigation and the URL
Elm SPA Navigation
1
Per Lundholm Crisp
2. Problem statement
Demo
Divide an application into page modules
Handle browser location
Per Lundholm 2
Agenda
3. How can I structure my Elm app so that:
– Each page has Model, Messages, Update and View?
– Browser’s location bar is updated
• Backandforwardworks
• Bookmarkingpossible
But an Elm app has only one source of truth
– OneModel
– OneUpdate
– OneView
Per Lundholm 3
Problem statement
4. Book collection
Pages
– Homepage
– Listing page
• Listsbooks
– Details page
• Detailsabouta selectedbook
Per Lundholm 4
Example Application
8. TheModel can only beone, the Main model
– TheMain modelcontainsthe Routermodel
– The Routermodel containsthe page’smodels.
Per Lundholm 8
Dividing the Model
type alias Model =
{ navKey : Browser.Navigation.Key
, url : Url
, sharedState : SharedState.SharedState
, routerModel : Routing.Router.Model
}
type alias Model =
{ route : Routing.Helpers.Route
, homeModel : Pages.Home.Model
, listingModel : Pages.Listing.Model
, detailsModel : Pages.Details.Model
}
type DetailsModel
= Initial
| NotFound
| Loaded Data.Book
type alias Model =
{ details : DetailsModel
}
Main.elm Router.elm
Details.elm
9. The update function takes amessage and a model and returns a new
model plus a command
– update: Msg -> Model -> ( Model, Cmd Msg )
We need to delegate the job
– Main to Router to Page
– But how? Main shouldn’t know about page’sMsg!
– Answer: Cmd.map
Per Lundholm 9
Delegating the update
12. How do we get Urls like:
We use Browser.Navigation of elm/browser!
Step 1. Declare messages for Url changes
Per Lundholm 12
Managing Browser Location
13. Step 2: Handle the messages
– Main
– Router
Per Lundholm 13
15. Step 4: Enable bookmarking by parsing atinit
– Main
– Router init
Per Lundholm 15
16. Divide app into modules for each page
– Delegate update to pages and use Cmd.map
With elm/browser package handle browser location so that
– Back and forward works
– Bookmarking possible
Per Lundholm 16
Summary
17. Source code for the demo
– https://github.com/perty/elm-navigation-test
Ossi Hanhinen’sShared state
– https://github.com/ohanhi/elm-shared-state
Elm’s Browser Navigation
– https://package.elm-lang.org/packages/elm/browser/latest/Browser-Navigation
Per Lundholm 17
Source
Notas do Editor
Nivå på talet
Vem är jag
Vad gör jag nu
You start with Main
Model, Message, View, Update
Easy no navigation
Then?