noredink-ui/styleguide-app/Routes.elm

111 lines
2.5 KiB
Elm
Raw Normal View History

2022-05-20 22:20:12 +03:00
module Routes exposing (Route(..), fromLocation, toString, viewBreadCrumbs)
2018-02-13 00:32:38 +03:00
2022-05-20 22:20:12 +03:00
import Accessibility.Styled as Html exposing (Html)
import Category
2022-05-20 22:20:12 +03:00
import Html.Styled.Attributes as Attributes
import Nri.Ui.BreadCrumbs.V1 as BreadCrumbs exposing (BreadCrumbs)
2018-12-05 21:56:04 +03:00
import Parser exposing ((|.), (|=), Parser)
import Url exposing (Url)
2018-02-13 00:32:38 +03:00
type Route
= Doodad String
| Category Category.Category
2018-02-13 00:32:38 +03:00
| All
toString : Route -> String
toString route_ =
case route_ of
Doodad exampleName ->
"#/doodad/" ++ exampleName
Category c ->
"#/category/" ++ Debug.toString c
All ->
"#/"
2018-12-05 21:56:04 +03:00
route : Parser Route
2018-02-13 00:32:38 +03:00
route =
2018-12-05 21:56:04 +03:00
Parser.oneOf
[ Parser.succeed Category
|. Parser.token "/category/"
2018-12-08 01:16:00 +03:00
|= (restOfPath |> Parser.andThen category)
2018-12-05 21:56:04 +03:00
, Parser.succeed Doodad
|. Parser.token "/doodad/"
2018-12-08 01:16:00 +03:00
|= restOfPath
2018-12-05 21:56:04 +03:00
, Parser.succeed All
2018-02-13 00:32:38 +03:00
]
2018-12-08 01:16:00 +03:00
restOfPath : Parser String
restOfPath =
Parser.getChompedString (Parser.chompWhile (always True))
2018-12-05 21:56:04 +03:00
category : String -> Parser Category.Category
2018-12-05 21:56:04 +03:00
category string =
case Category.fromString string of
2018-12-05 21:56:04 +03:00
Ok c ->
Parser.succeed c
Err e ->
Parser.problem e
2018-02-13 00:32:38 +03:00
fromLocation : Url -> Route
2018-02-13 00:32:38 +03:00
fromLocation location =
location.fragment
|> Maybe.withDefault ""
|> Parser.run route
2018-12-05 21:56:04 +03:00
|> Result.withDefault All
2022-05-20 22:20:12 +03:00
viewBreadCrumbs : Route -> Html msg
viewBreadCrumbs currentRoute =
breadCrumbs currentRoute
|> Maybe.map
(BreadCrumbs.view
{ aTagAttributes = \r -> [ Attributes.href ("/" ++ toString r) ]
, isCurrentRoute = (==) currentRoute
}
)
|> Maybe.withDefault (Html.text "")
breadCrumbs : Route -> Maybe (BreadCrumbs Route)
breadCrumbs route_ =
case route_ of
All ->
Just allBreadCrumb
Category category_ ->
Just (categoryCrumb category_)
Doodad _ ->
Nothing
allBreadCrumb : BreadCrumbs Route
allBreadCrumb =
BreadCrumbs.init
{ icon = Nothing
, iconStyle = BreadCrumbs.Default
, id = "breadcrumbs__all"
, text = "All"
, route = All
}
categoryCrumb : Category.Category -> BreadCrumbs Route
categoryCrumb category_ =
BreadCrumbs.after allBreadCrumb
{ icon = Nothing
, iconStyle = BreadCrumbs.Default
, id = "breadcrumbs__" ++ Category.forId category_
, text = Category.forDisplay category_
, route = Category category_
}