Skip to content

Instantly share code, notes, and snippets.

@granicz
Created December 30, 2017 00:55
Show Gist options
  • Save granicz/eeaf2140a3f1fbccc9ebb4af9deadaa1 to your computer and use it in GitHub Desktop.
Save granicz/eeaf2140a3f1fbccc9ebb4af9deadaa1 to your computer and use it in GitHub Desktop.
Serving SPAs - barebones version
namespace CSSPA0
open WebSharper
open WebSharper.Sitelets
open WebSharper.UI
open WebSharper.UI.Server
open WebSharper.UI.Html
type SPA =
| [<EndPoint "/cities">] Cities
| [<EndPoint "/cities">] City of string
type EndPoint =
| [<EndPoint "/">] Home
| [<EndPoint "/spa">] SPA of SPA
[<JavaScript>]
module Client =
open WebSharper.UI.Client
let store =
[
"Budapest", "awesome"
"Paris", "famous"
"San Francisco", "expensive"
"London", "cosmopolitan"
"Singapore", "crowded"
]
let Main () =
let router = Router.Infer<EndPoint>()
let location =
router
|> Router.Slice (function | SPA spa -> Some spa | _ -> None) EndPoint.SPA
|> Router.Install SPA.Cities
location.View.Doc(function
| SPA.Cities ->
Doc.Concat [
ul [] (
store |> List.map (fun (city, _) ->
a [attr.href <| router.Link (EndPoint.SPA (SPA.City city))] [
li [] [text city]
] :> Doc)
)
]
| SPA.City city ->
let message =
match List.tryFind (fun (cty, _) -> city=cty) store with
| None ->
p [] [text "I don't know your city :("]
| Some (_, adjective) ->
p [] [text <| "Your city is " + adjective + "!"]
Doc.Concat [
h1 [] [text city]
message
p [] [
text "Click "
a [attr.href (router.Link (EndPoint.SPA SPA.Cities))] [text "here"]
text " to go back."
]
]
)
module Site =
let HomePage (ctx: Context<EndPoint>) =
Content.Page(
Title = "Home",
Body = [
p [] [
text "There is nothing here, go to the "
a [attr.href <| ctx.Link (EndPoint.SPA SPA.Cities)] [text "Cities page"]
]
]
)
let CitiesPage ctx =
Content.Page(
Title = "Cities",
Body = [
div [] [client <@ Client.Main () @> ]
]
)
[<Website>]
let Main =
Application.MultiPage (fun ctx endpoint ->
match endpoint with
| EndPoint.Home ->
HomePage ctx
| EndPoint.SPA SPA.Cities
| EndPoint.SPA (SPA.City _) ->
CitiesPage ctx
)
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="System.ValueTuple" version="4.3.0" targetFramework="net461" />
<package id="WebSharper" version="4.1.0.171" targetFramework="net461" />
<package id="WebSharper.FSharp" version="4.1.0.171" targetFramework="net461" />
<package id="WebSharper.UI" version="4.1.0.34" targetFramework="net461" />
</packages>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment