Last active
September 9, 2018 05:34
-
-
Save aratama/38d982c70609c14e357ceea501604a36 to your computer and use it in GitHub Desktop.
Elm 0.19 SPA Routing Paractice Swing :)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main exposing (Model, Msg(..), init, main, update, view) | |
import Browser exposing (UrlRequest(..)) | |
import Browser.Navigation exposing (Key, load, pushUrl) | |
import Html exposing (Html, a, div, h1, img, p, text) | |
import Html.Attributes exposing (href, src) | |
import Url as Url exposing (Url) | |
import Url.Parser exposing (Parser, map, oneOf, parse, s, top) | |
---- MODEL ---- | |
type alias Model = | |
{ key : Key, route : Route } | |
type Route | |
= NotFound | |
| Top | |
| PageA | |
| PageB | |
init : () -> Url -> Key -> ( Model, Cmd Msg ) | |
init flags url key = | |
( { key = key, route = parseUrl url }, Cmd.none ) | |
routing : Parser (Route -> a) a | |
routing = | |
oneOf | |
[ map PageA (s "a") | |
, map PageB (s "b") | |
, map Top top | |
] | |
parseUrl : Url -> Route | |
parseUrl url = | |
Maybe.withDefault NotFound (parse routing url) | |
---- UPDATE ---- | |
type Msg | |
= UrlRequest UrlRequest | |
| UrlChanged Url | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update msg model = | |
case msg of | |
UrlRequest urlRequest -> | |
case urlRequest of | |
Internal url -> | |
( model | |
, pushUrl model.key (Url.toString url) | |
) | |
External url -> | |
( model | |
, load url | |
) | |
UrlChanged url -> | |
( { model | route = parseUrl url } | |
, Cmd.none | |
) | |
---- VIEW ---- | |
view : Model -> Browser.Document Msg | |
view model = | |
{ title = "Rabbitania" | |
, body = | |
case model.route of | |
NotFound -> | |
[ h1 [] [ text "Page Not Found" ] | |
, a [ href "/" ] [ text "Go back home" ] | |
] | |
Top -> | |
[ h1 [] [ text "Top" ] | |
, p [] [ a [ href "/a" ] [ text "Go tp Page A" ] ] | |
, p [] [ a [ href "/b" ] [ text "Go tp Page B" ] ] | |
] | |
PageA -> | |
[ h1 [] [ text "Page A" ] | |
, a [ href "/" ] [ text "Go back home" ] | |
] | |
PageB -> | |
[ h1 [] [ text "Page B" ] | |
, a [ href "/" ] [ text "Go back home" ] | |
] | |
} | |
---- PROGRAM ---- | |
main : Program () Model Msg | |
main = | |
Browser.application | |
{ view = view | |
, init = init | |
, update = update | |
, subscriptions = always Sub.none | |
, onUrlRequest = UrlRequest | |
, onUrlChange = UrlChanged | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment