Bonsai
Bonsai
Bonsai is a UI library for building performant, reactive web applications in OCaml, partly inspired by Elm. It is used to build almost all web applications inside Jane Street, everything from the corporate directory to tools that monitor and interact with our trading systems. A simple Bonsai component with a little interactivity looks like this:
module Dice = struct let faces = [ " ⚀ " ; " ⚁ " ; " ⚂ " ; " ⚃ " ; " ⚄ " ; " ⚅ " ] ;; let component ( graph @ local ) = (* Components are implemented as purely functional state machines. *) let face, set_face = Bonsai. state ( List. hd_exn faces) graph in (* Components are incrementally rendered, only when the relevant parts of the state change. *) let % arr face and set_face in {%html| <div> You rolled a #{face} < button style = " " on_click =% {fun _ -> let index = Random. int ( List. length faces) in set_face ( List. nth_exn faces index)} > Roll the dice < / button > < / div > | } ;; end
Most internal Jane Street web applications are built with Bonsai
Components are implemented as purely functional state machines, and are easily composable. Incrementalization inside the framework means that values don’t get recomputed until necessary. This applies to every value, not just the view.
Why Bonsai?
Other web frameworks tend to lump together state, incrementality, and rendering into a single abstraction, the UI component. By contrast, Bonsai allows you to compose state and incrementality primitives a la carte. The same primitives that prevent re-rendering the entire page during user interaction can also be used to incrementalize an expensive business logic computation on a live-updating dataset. (If you're used to React, imagine if everything used something very similar to hooks, and state was managed outside of the component hierarchy.)
Since state is not associated with explicit components, there is an extensive API for managing the lifecycle and scoping of state as users interact with the page. For instance, if you wanted to embed a collection of stateful UI components inside another UI component (in a tabbed interface, say), Bonsai will handle the state management for you instead of requiring that you manually hoist every internal component's state to the app's top-level model. For more examples of how state is composed, see this composition comparison written by the creator of Bonsai.
... continue reading