Today’s post will be the last one associated with DSP 2017. Almost 3 months have passed since the beginning of the blogging contest and here we are, 21 posts later! I will continue to blog after the contest ends, but probably not as frequently as of now.
What is D3.js?
The D3 extension for WebSharper
Quick analysis of the F# code
- The F# file contains 142 lines of logic (around 100 lines of pure logic, the rest being helper / integration code around D3.js).
This contrasts with F# / C# comparisons where F# is most of the time much shorter.
Here is the core logic that I wrote to port the example (the full example is available on my GitHub repo under ZoomableMap.fs):
- Due to the sequential nature of F# (every element must be defined before being used) I had to define the onClicked function at the top of the file. This forced me to add a unique svg-group Id to the SVG group element:
let svgGroup = svg.Append("g").Attr("id", "svg-group")
so I can retrieve it later in the onClicked function:
let svgG = D3.Select("#svg-group") svgG.SelectAll("path") .Classed("active", fun (_, i) -> currentStateIndex <> noStateSelectedIndex && currentStateIndex = i) |> ignore svgG.Transition() .Duration(750) .Attr("transform", SvgTransform.Translate(dimensions.Width / 2., dimensions.Height / 2.) + SvgTransform.Scale(k) + SvgTransform.Translate(-x, -y)) |> ignore
// F# let states : obj = topojson.feature(map, map?objects?``states``)?features let borders = topojson.mesh(map, map?objects?``states``, fun (a, b) -> a !==. b)
How to get quickly started with D3 under WebSharper
I actually spent a few hours trying to figure out how to properly set up a WebSharper project for my experiment. The instructions below will help you get started quickly and effortlessly!
- Create a new project using the UI.Next Single-Page Application template:
- Add the WebSharper.Html package to the project using the following NuGet command:
- Do the same with the WebSharper.D3 package:
- Edit the index.html file and add the following script to it:
With that configured, you should be able to run your D3 samples without problems. Once again, the full sources are available on my GitHub repo.