|
module Main exposing (..) |
|
|
|
import Browser exposing (Document) |
|
import Browser.Navigation as Navigation |
|
import Html exposing (Html, a, button, div, li, text, ul) |
|
import Html.Attributes exposing (href) |
|
import Html.Events exposing (onClick) |
|
import Url |
|
import Url.Parser as Parser exposing ((</>), Parser, s) |
|
|
|
|
|
type alias Model = |
|
{ navigation : Navigation } |
|
|
|
|
|
type alias Navigation = |
|
{ key : Navigation.Key |
|
, page : Page |
|
} |
|
|
|
|
|
initialModel : Url.Url -> Navigation.Key -> Model |
|
initialModel url key = |
|
{ navigation = |
|
{ key = key |
|
, page = |
|
case fromUrl url of |
|
Nothing -> |
|
NotFound |
|
|
|
Just a -> |
|
a |
|
} |
|
} |
|
|
|
|
|
parser : Parser (Page -> b) b |
|
parser = |
|
Parser.oneOf |
|
[ Parser.map Home Parser.top |
|
, Parser.map About (s "about") |
|
] |
|
|
|
|
|
fromUrl : Url.Url -> Maybe Page |
|
fromUrl url = |
|
-- Treat fragment as path for convenience |
|
{ url | path = Maybe.withDefault "" url.fragment, fragment = Nothing } |
|
|> Parser.parse parser |
|
|
|
|
|
type Page |
|
= Home |
|
| About |
|
| NotFound |
|
|
|
|
|
type alias Flags = |
|
() |
|
|
|
|
|
init : Flags -> Url.Url -> Navigation.Key -> ( Model, Cmd Msg ) |
|
init flags url key = |
|
( initialModel url key, Cmd.none ) |
|
|
|
|
|
|
|
-- UPDATE |
|
|
|
|
|
type Msg |
|
= UrlRequested Browser.UrlRequest |
|
| UrlChange Url.Url |
|
|
|
|
|
update : Msg -> Model -> ( Model, Cmd Msg ) |
|
update msg model = |
|
case Debug.log "" msg of |
|
UrlRequested urlRequest -> |
|
case urlRequest of |
|
Browser.Internal url -> |
|
( model, Navigation.pushUrl model.navigation.key (Url.toString url) ) |
|
|
|
Browser.External href -> |
|
( model, Navigation.load href ) |
|
|
|
UrlChange url -> |
|
let |
|
navigation = |
|
model.navigation |
|
in |
|
( { model |
|
| navigation = |
|
{ navigation |
|
| page = |
|
case fromUrl url of |
|
Nothing -> |
|
NotFound |
|
|
|
Just a -> |
|
a |
|
} |
|
} |
|
, Cmd.none |
|
) |
|
|
|
|
|
|
|
-- VIEW |
|
|
|
|
|
view : Model -> Document Msg |
|
view model = |
|
{ title = "hello title" |
|
, body = [ bodyView model ] |
|
} |
|
|
|
|
|
bodyView : Model -> Html Msg |
|
bodyView model = |
|
div [] |
|
[ text "hello world" |
|
, ul [] |
|
[ li [] [ a [ href "#/" ] [ text "Home" ] ] |
|
, li [] [ a [ href "#/about" ] [ text "About" ] ] |
|
] |
|
, div [] |
|
[ case model.navigation.page of |
|
NotFound -> |
|
text "Page not Found" |
|
|
|
Home -> |
|
text "Home page" |
|
|
|
About -> |
|
text "About page" |
|
] |
|
] |
|
|
|
|
|
|
|
-- SUBSCRIPTIONS |
|
|
|
|
|
subscriptions : Model -> Sub Msg |
|
subscriptions model = |
|
Sub.none |
|
|
|
|
|
|
|
-- INIT |
|
|
|
|
|
main : Program Flags Model Msg |
|
main = |
|
Browser.application |
|
{ init = init |
|
, update = update |
|
, view = view |
|
, subscriptions = subscriptions |
|
, onUrlRequest = UrlRequested |
|
, onUrlChange = UrlChange |
|
} |