Designing with D3 and Ranvier
How separating visualization math from view ownership gives us one reactive chart architecture from the browser to native WebCore and Clef.
If you have ever built a data-heavy application, you probably know the moment when a clean UI architecture starts to fray. Forms, tables, and summary cards fit comfortably inside whatever reactive view layer the team chose. Then someone asks for an interactive forecast chart, and the integration gets more complicated. You hand an empty container to a charting widget, write the code to push updates across the boundary, and make sure the numbers in the table and the curve on the screen still agree after a filter change or a network refresh.
We ran into that design question while planning the next set of views for Beancounter, our financial-planning application at Braidpoint. We’re standardizing our JavaScript work on Fickl and Ranvier: Fickl compiles our F# to JavaScript, and Ranvier provides the reactive interface. Beancounter uses that foundation with a Cloudflare Workers backend. When someone extends a projection or adjusts a growth assumption, the summary table and trend line should be two readings of the same model. Dragging the window wider should give the chart more room without touching the forecast, and editing a scenario title should not cause the chart to recalculate its coordinates.
Bringing D3 into that picture turns out to be a natural fit once you look past how it is often introduced. Many tutorials focus on D3’s DOM manipulation, but its modules also offer scales that map data values to chart coordinates, shape generators that turn points into SVG paths, and array utilities that calculate bounds and ticks. We can use those pieces without asking D3 to manage the SVG elements. Ranvier owns the state and the view while D3 supplies the geometry.
That separation matters beyond the browser. Ranvier supports F# compiled to JavaScript through Fickl, server rendering of HTML and SVG, and an experimental .NET NativeAOT desktop backend that drives WebCore with native UI logic. The same geometry boundary also supports a future Clef implementation using Farscape bindings and native incremental computation. For the product context, see Designing Web and Native UI with Ranvier on the Braidpoint blog.
Splitting the Work Between Ranvier and D3
d3-selection can create, update, and remove SVG nodes. If both D3 and Ranvier modify the same subtree, either can overwrite an attribute or remove a node still used by the other. The integration needs one owner for each node.
In the planned Beancounter integration, D3 calculates geometry while Ranvier owns the reactive state, derived computations, and SVG nodes through disposal.
flowchart LR
DATA["Accepted observations and<br/>forecast assumptions"] --> STATE["Ranvier state"]
SIZE["Viewport / container size"] --> GEOM["Derived chart geometry<br/>(planned D3 scales and paths)"]
STATE --> TOTALS["Derived summary figures"]
STATE --> GEOM
TOTALS --> TABLE["Forecast table<br/>and variance cards"]
GEOM --> SVG["Ranvier-owned SVG<br/>paths, axes, and labels"]
The forecast table and chart geometry both read the same accepted Ranvier state. That removes one common source of disagreement: a separate dataset held by the chart. There is still work to do to keep the display consistent. We need to accept updates as a single snapshot, ignore out-of-order responses, and flush the affected view bindings before presenting the result.
The container dimensions take a different route through the graph. When the user resizes a pane, the scale ranges and SVG attributes should update, but the forecast, summary table, and celld network layer have no reason to run again.
That selective invalidation connects to the reactive model we’ve been developing across the framework (see Native Reactivity in Clef and Building User Interfaces with the Fidelity Framework). Tracked computations record dependencies from their reactive reads. Ranvier also provides fixed-dependency bindSignal and bindMemo bindings; a memo can transform a value before it is bound. A chart header that reads only the scenario name need not update when numerical data changes. A closed drawer can dispose its visual observers so they no longer demand geometry updates, while a background service continues updating the projection.
When an assumption changes and celld has a request in flight, Ranvier can retain the last accepted dataset while a separate request-status signal tracks a pending or failed refresh. The view can dim the series or show a notice without removing the chart or losing keyboard focus. That gives someone working through a forecast a stable point of comparison while new results are on their way.
Scales, Paths, and Stateful Helpers
Suppose we have an accepted series of regularly spaced budget periods, with missing observations retained as { value: null } placeholders. This JavaScript helper uses D3’s d3-scale and d3-shape packages to produce an SVG path for a width by height drawing box in SVG user units:
import { scaleLinear } from "d3-scale";
import { line } from "d3-shape";
function buildSeriesPath(points, width, height, floor, ceiling) {
if (
!Array.isArray(points) ||
points.length === 0 ||
!Number.isFinite(width) || width <= 0 ||
!Number.isFinite(height) || height <= 0 ||
!Number.isFinite(floor) ||
!Number.isFinite(ceiling) || ceiling <= floor
) {
return "";
}
const lastSlot = Math.max(points.length - 1, 1);
const x = scaleLinear([0, lastSlot], [0, width]);
const y = scaleLinear([floor, ceiling], [height, 0]);
const shape = line()
.defined(p => p !== null && p !== undefined && Number.isFinite(p.value))
.x((_, i) => x(i))
.y(p => y(p.value));
return shape(points) ?? "";
}Even this small example raises a few questions that matter when the data changes or the chart encounters an unusual input:
- Spacing and gaps. The example uses the array index for
x, so adjacent entries are evenly spaced. That works for a regular fiscal grid as long as missing periods keep their placeholders. D3’s.defined()predicate can break the path at a missing entry, but it cannot detect a period that has been left out of the array. For irregular dates, scale the timestamps to represent elapsed time and decide separately where missing observations should break the line. - The vertical domain. An explicit
[floor, ceiling]lets the chart show negative values as well as zero-based budgets. The finite checks keep invalid dimensions and domain bounds out of the scales. D3’s linear scale extrapolates by default, so values outside that domain project beyond the drawing box. We can expand the domain or clip the graphic with an SVGclipPath; clamping is another choice, but it flattens out-of-range values onto the edge. - Stateful helpers. A D3 scale is a callable function object. Its
.domain,.range, and.clampsetters change its configuration and return the scale for chaining; a line generator works similarly. Constructing them inside the derived calculation keeps one reactive reader from changing a scale used by another. - Isolated points. With one observation, the example uses an
xdomain of[0, 1]and puts the point at the left edge. D3 itself maps a collapsed finite domain to the range midpoint. Either way, a single point—or a point separated from its neighbors by gaps—can produce a line segment that is invisible with a plain SVG stroke. When those observations matter, the view can render explicit<circle>markers alongside the path. - Ticks and labels. We can calculate tick records and let Ranvier render them as SVG instead of asking
d3-axisto modify the elements. Use the samecountwithy.ticks(count)andy.tickFormat(count, spec); the optional format specifier belongs totickFormat. The count is a hint, and unless the specifier sets its own precision, D3 uses it to choose suitable label precision.
So how does that path get into the view? Ranvier can read derived geometry without handing a DOM element to JavaScript. Ranvier.View.Sugar provides SVG elements such as svg, path, circle, and clipPath, and their attributes can read reactive values. We can keep the geometry in a memo and let the view use it for the path, ticks, and point markers. The SVG element definitions and template documentation show the available building blocks.
Here’s the path portion of that idea as a Ranvier.View template:
open Ranvier
open Ranvier.View
open Ranvier.View.Sugar
type ChartPoint = { X: float; Y: float }
type TickMark = { Position: float; Label: string }
type ChartGeometry = {
PathData: string
IsolatedPoints: ChartPoint list
XTicks: TickMark list
YTicks: TickMark list
}
type Chart = { Geometry: Memo<ChartGeometry> }
let forecast =
Component.template
(fun _ (chart: Chart) -> chart)
(svg () {
path (Attrs.attribute ("d", fun (chart: Chart) -> Some chart.Geometry.Value.PathData)) { () }
})The template reads PathData from the memo and uses it for the SVG path’s d attribute. It doesn’t call D3 yet, and the tick marks and isolated points still need their own elements, but it shows where the calculated geometry meets the view. Ranvier retains ownership of the SVG throughout.
Owning those elements also gives us a place to build accessibility into the chart. We can add SVG <title> and <desc> metadata, provide keyboard-navigable point summaries, and pair the graphic with a table based on the same accepted data. The component can follow the application’s color palette, high-contrast theme, and reduced-motion preferences.
Xantham and the Browser Toolchain Today
Fickl and Ranvier give us the browser application; D3 adds the visualization calculations. To call D3’s scale, shape, and array modules from F# without maintaining untyped shims, our plan uses Xantham, the TypeScript declaration analyzer maintained by Shayan Habibi and detailed in our TypeScript binding architecture notes.
D3’s TypeScript declarations (@types/d3-scale, @types/d3-shape, and @types/d3-array) exercise several binding-generation requirements:
- Callable interfaces. A D3
ScaleLinear<Range, Output>is simultaneously a function you invoke to project a domain number and an object carrying configuration and inspection methods (.domain,.range,.invert,.ticks,.nice). - Fluent method chaining and generic parameters. Ordinary configuration setters such as
.domain,.range, and.clamppreserve the existing scale type, while specific builder overloads (such as datum-type helpers or interpolator selection) narrow or transform generic parameters along a chain. - Method overloads for getters versus setters. Calling
scale.domain()with no arguments reads the current array, whilescale.domain([0, 100])configures it and returns the scale.
Xantham queries the TypeScript compiler’s semantic model, so it can examine these callable objects, overloaded methods, and generic relationships when generating F# bindings. It also reports how faithfully each signature maps to F#, including cases where a type must be widened or handled outside the generated binding (mapping notes). That gives us a way to bring D3’s API into our Fickl and Ranvier application with the binding’s compromises visible to the developer. Those same structural patterns also inform the bindings planned for Clef’s JavaScript target.
An interactive browser view that imports d3-scale and d3-shape still ships those JavaScript packages as runtime dependencies. Pin package versions and measure the resulting bundle; importing individual modules can limit the dependency surface, although the actual bundle size also depends on tree shaking. For a static report, Ranvier.View can render HTML and SVG on the server without client-side JavaScript unless the page opts into hydration. A plain .NET process needs a JavaScript host or process to execute D3; alternatively, a server-rendered chart can use geometry calculated by a shared F# or Clef module. D3’s modules can also run in suitable server-side JavaScript environments.
Browser, Server, and Native Execution
If the browser were the only place we wanted to run this chart, JavaScript bindings would be enough to pursue. Ranvier’s server and native paths make the geometry boundary more interesting: they let us retain the same approach to the view while choosing an implementation suited to each environment. That is also useful for our shared UI architecture.
The experimental Ranvier.View.WebCore backend supports an F# Ranvier application compiled with .NET NativeAOT and mounted against a native WebCore document. Input events arrive from the native host, reactive state updates in native code, and WebCore handles CSS layout and SVG painting. The documented experimental targets are Windows x64 and ARM64, Linux x64, and macOS 26 on arm64. Ranvier’s native WebCore packages also include JavaScriptCore, but the native UI path does not require JavaScript to execute its application logic.
flowchart TB
MODEL["Authored Ranvier state and view"]
MODEL --> BROWSER["Browser path<br/>F# → Fickl → JavaScript"]
MODEL --> SSR["Server path<br/>Ranvier.View HTML / SVG render"]
MODEL --> AOT["Experimental desktop path<br/>.NET NativeAOT → WebCore"]
D3JS["D3 math packages<br/>(planned Xantham bindings)"] -.-> BROWSER
BROWSER --> DOM["Browser DOM and SVG"]
SSR --> MARKUP["Static or hydrated markup"]
AOT --> WIN["Native window via WebCore"]
The desktop path also brings deployment choices into view. In our WREN Stack experiments, the WrenHello application binary was roughly 77 kB alongside separately supplied platform libraries. A WebCore deployment has its own native libraries to account for, so the application binary alone does not tell us the size of the complete package. Ranvier’s publishing notes show how those pieces add up for a native build.
The same boundary is relevant to the planned Clef implementation:
- Native host bindings via Farscape. On our Clef roadmap, Farscape generates typed
[<FidelityExtern>]bindings directly from C and C++ headers for WebView, WebCore, and host windowing libraries. Combined with Clef’s intrinsicIncremental<'T>andObservable<'T>primitives, a Clef application will be able to drive a WebCore document with deterministic, arena-backed lifetimes and no garbage collector in the UI loop. - Geometry on native and server paths. Xantham bindings are intended to let browser builds call D3’s JavaScript modules; Clef’s JavaScript and WebAssembly paths can also interoperate at the browser boundary. The native UI backend does not automatically load D3 even though the WebCore packages include JavaScriptCore. Executing those modules would require a supported JavaScript host and module integration. A Clef geometry implementation provides another path for native and server rendering behind the same view boundary.
- Dimensional types for domain and display coordinates. Financial series carry domain units such as currency, headcount, days, or rates. SVG paths and ticks use
viewBoxuser coordinates, while layout and display APIs may report CSS or device pixels. A scale typed fromfloat<'Domain>tofloat<svg_u>, with explicit transforms into distinct pixel units, could make accidental mixing of these quantities a compile-time error.
Proving Out the Integration
The design gives us a useful direction, but the browser bindings, the Ranvier.View.WebCore path, and a future Clef geometry implementation each run in a different environment. We need to exercise each path before we can rely on the same behavior across them.
For Beancounter, that means checking the interactions that prompted this design in the first place. When an assumption changes, do the forecast table and SVG path render from the same accepted snapshot? Does a resize update the geometry without triggering a network request? When the view is removed, are its reactive readers and resize observers released?
As the native geometry implementation develops, we can give it and the browser version the same series and viewport dimensions and compare the results. There is a detail to account for here: D3’s line generator defaults to three fractional digits when it writes an SVG path, so equivalent geometry may still produce different strings. Comparing parsed commands and coordinates within an explicit tolerance, and checking tick positions and labels separately, gives us a more useful measure. We can reserve exact string comparisons for cases where both implementations share the same serialization contract.
That gives us a practical way to bring D3 into the Fickl and Ranvier stack today while keeping the chart’s state, behavior, and presentation connected as we carry the design to native targets.