package toffee
Build not checkedInstall
dune-project
Dependency
Authors
Maintainers
Sources
sha256=ab48bc02082f9c1deea0769a13c2935df529536630745ec3a3d718f59656109b
sha512=c0f3c490e13ca60217d9d59c9bfdf3ada12e1565f04fe2a623e7c94298d519393eabe404e2317726712bf5e7fa860780a07494e77994ac05032e71f535c56910
doc/CHANGES.html
Changelog
[0.2.0] - 2026-11-04
0.2.0 changes most of the API of all three packages, and some programs that still compile will behave differently. Before you upgrade from 0.1, read Migrating from 0.1: it lists every renamed and removed API, with code before and after. Note that Matrix, and so Mosaic, no longer runs on Windows in this release.
Each package below starts with what is new. Then come the changes the compiler won't catch, then the breaking changes and why we made them.
Mosaic
The biggest change is that your model now owns all interactive state. In 0.1, widgets kept their own: an input held its text, a tree its open nodes, a scroll box its offset, and the view only passed starting values. Nothing kept the two in step. A value the app forgot to pass back drifted away from the model, and a value forced from the view undid what the user had just typed. Both of our own editing examples had that bug. Now a widget shows the state you give it and proposes changes through on_change, and your update decides what to keep:
(* in the view; model.name is an Editor.t *)
input ~state:model.name ~on_change:(fun e -> Name_edited e) ()
(* in update *)
| Name_edited e -> ({ model with name = e }, Cmd.none)Widget | The state it takes |
|---|---|
|
|
|
|
|
|
| their value |
| the selected item, as a value of your own type |
Focus works the same way. Your model says which element is focused with ?focused. A click, or Tab, asks for focus through ?on_focus_request. Tab and Shift+Tab walk the elements in the order they appear, so you no longer keep a list of them by hand.
Mosaic is also much faster on the thing we care about most, long transcripts. With keyed lists and memo, a frame costs as much as what changed in it. In our benchmark, a keystroke under a 20,000-block transcript takes about 0.3 ms, the same as under 5,000 blocks.
Also new
- Widgets draw with a theme instead of fixed colors.
Mosaic.Themenames roles such asPlain,Muted,AccentandBorder, andthemedrestyles a subtree. The default theme uses the terminal's own palette, so widgets stay readable on light terminals, where 0.1's white text did not. - You can select and copy text anywhere in the view: drag, double- or triple-click, extend with Shift and the arrow keys, then press Ctrl+C. Each element chooses what a selection takes from it with
?selectable. By default it takes the text. With`Cellsit takes every cell the element draws, borders included, the way a terminal selects. To copy as soon as the user selects, answerSub.on_selectionwithCmd.copy_selection. modaldraws a dialog above the whole view and keeps focus, the mouse and Tab inside it. Escape sends itson_closemessage.- Key, mouse and paste events travel from their target up through its parents, as in the DOM, and a handler can stop them or prevent their default action.
Sub.on_keysbinds shortcuts to messages. - You can run a program under Eio with
Mosaic_eio.run, under Lwt withMosaic_lwt.run, or under any other event loop withMosaic.startandstep. In tests,Mosaic_test.runruns it on an emulated terminal. Cmd.performand the newSub.workerrun on a helper domain, so slow work no longer holds up input.Sub.afterfires once, which is what you want for debouncing.- Syntax highlighting is pluggable.
Code.Highlighterwraps a highlighter that runs synchronously, on a thread or asynchronously. After an edit, Mosaic asks an incremental highlighter only for the lines around the view. See doc/highlighting.md. Cmd.exechands the terminal to an editor or a pager and takes it back afterwards, andCmd.suspendstops the program as Ctrl+Z does. Smaller commands copy to the clipboard, send a desktop notification, ring the bell and switch mouse tracking on or off.- New elements:
button,rich_text,difffor unified and side-by-side patches,picturefor images, andviewport_switch, which picks a subtree by terminal width. Elements also take?on_clickand?on_size. Mosaic.Element.kindturns a widget of your own into an element that the reconciler diffs like the built-in ones.
Changes the compiler won't catch
- Tab and Shift+Tab now move focus. If your program uses Tab for something else, call
Event.Key.prevent_defaultin the handler that uses it, or bind it withSub.on_keys. - A click no longer focuses an element by itself. It sends the element's
?on_focus_requestmessage, and the element is focused once your view says~focused:true. - A widget given no color draws with the theme, in the terminal's own colors. To get 0.1's look back, pass the widget its color arguments, or restyle the roles once with
themedat the root. - Ctrl+C still quits, but now as a default action that a handler can prevent. While text is selected, it copies the selection instead.
- Key, mouse and paste listeners now see events that an element prevented, as DOM listeners do. Check
default_preventedon the event to skip them. Before, a listener could miss a press and have no way to know. - In inline mode, the last frame stays on screen when the program ends, so a summary or a choice stays in the scrollback.
Cmd.keep_frame falseerases it as 0.1 did. - Frames are drawn only when something asks for one. A
canvasthat animates on its own needs~live:true; without it, it moves only when something else redraws. - An exception raised in
Cmd.performnow ends the program, andMosaic.runraises it again once the terminal is restored. In 0.1 it killed only its thread, and the program carried on without the result it was waiting for. Unix.forkraises while background work is running, because OCaml forbids forking once several domains run. UseUnix.create_process.initruns before the terminal is taken, so an exception it raises leaves the terminal alone.- Two subscriptions with the same
~id, a border width that isn't a whole number of cells, and a tab width below 1 now raiseInvalid_argument.
Breaking changes
The compiler will point you to each of these. The migration guide has the full lists and code before and after.
- Stateful widgets take their state as an argument, as shown in the table above, and report changes through
~on_change.select,tab_selectandtabletake items that carry your own values instead of reporting indices, so reordering or filtering the items keeps the selection. See Widget state. - Callbacks that report a widget's own change (
on_change,on_activate,on_submitandon_scroll) return'msginstead of'msg option. The widget has already decided there is a change, so there is nothing left to filter. Raw event callbacks still return'msg option. - Focus is declared with
?focusedand?on_focus_request, which replace?id,?ref,?autofocus,?focusableandCmd.focus. Focus kept by the widgets drifted away from the app, and a storedrefcould outlive its element. Read sizes with?on_size, and mount a renderable of your own withembed. See Focus. Event.Key.datareturns aMatrix.Input.Keystroke.t. In 0.1 one key had a different value in each terminal encoding: Shift+a wasAin one andawith Shift in another. Now it isChar 'A'everywhere, and Ctrl+C isChar 'c'withctrlset.- A mouse release reports
draggedinstead ofis_dragging. It is true only when the pointer left the pressed cell, because some terminals report motion inside a cell and that turned clicks into drags. A press reports itsclicks, for double and triple clicks. Sub.everyandSub.on_ticktake an~id, andSub.everypasses the number of periods that elapsed. In 0.1 a timer that missed periods replayed each of them: a 0.1 s timer sent 100 messages after a 10 s stall.Sub.on_key_all,on_mouse_allandon_paste_allare gone. Pass~phase:CapturetoSub.on_key,on_mouseoron_pasteinstead. Events now follow the DOM's capture-then-bubble order, where 0.1 had a different rule for each kind of event.Mosaic.runtakes aMatrix.configas?config, where it took a Matrix app as?matrix, because Mosaic now runs Matrix's loop itself. Eio programs callMosaic_eio.run, which replaces the forty lines of glue each of them had to copy. See Running a program.?selectabletakes`Off,`Textor`Cellsinstead of a bool, so an element can choose between selecting its text and selecting every cell it draws.falsebecomes`Off, andtruecan usually go, since`Textis the default.Text.set_selectableis gone; callRenderable.set_selectableon the node.- The per-widget selection colors and
code ?on_selectionare gone. Selections draw with the theme'sHighlightrole, andSub.on_selectionhears the selection, which now spans every widget. - The tree-sitter bindings moved to their own package, ocaml-tree-sitter, and
code ?spansandtextarea ?spansbecame?syntax. Every Mosaic install used to compile 36 MB of generated C that Mosaic didn't use. In our measurement, a fresh install went from 90 seconds to 60. Syntax_themeis nowSyntax_style.Markdown.styleis aMarkdown.Style.tvalue built withMarkdown.Style.make, where it was a function. A style function built in the view made every code block highlight again on every refresh.- Durations are in seconds everywhere. A
canvasdraw function takes~dtwhere it took~deltain milliseconds, andSpinner.frame_settakesperiodwhere it tookinterval. We renamed the labels so that code written for milliseconds fails to compile instead of running 1,000 times too slowly. - On a canvas,
?respect_alphagave way to?blendon each write, andCanvas.set_cell ~glyphtoset_uchar ~uchar.
If you build on mosaic.ui directly:
Mosaic_ui.Vnodeis gone; build views withMosaic's elements. There were two vocabularies for one tree, and every label was spelled twice.Mosaic.tis abstract.Mosaic_ui.Edit_bufferbecameMosaic_ui.Editor, an immutable value, so replayed models no longer share editing state.- A widget's
createtakes itsProps.tlast instead of repeating every label:Box.create ~parent (Box.Props.make ~border:true ()). Reconciler.createtakes~deliver,Reconciler.rendertakes~viewport_width, andRenderer.dispatch_keytakes the focus path and anEvent.Key.t. See mosaic.ui.
Fixed
- A text node that had shrunk didn't grow back when it got its room back.
- Flex children next to each other could paint over each other.
scroll_box ~scroll_x:truedidn't scroll horizontally.- Messages sent from
Cmd.performcould be lost. - An empty, focused
inputshowed no cursor.
Matrix
Matrix has a new runtime. In 0.1 you handed Matrix.run a set of callbacks, and it called them from inside its own loop. Now you run the loop. Matrix.run holds the terminal for the length of a function and gives it back however that function ends. Inside it, you ask Matrix.next for the next step and draw with Matrix.draw:
let () =
Matrix.run @@ fun app ->
let rec loop count =
match Matrix.next app with
| Stopped | Event (Key { key = Escape; _ }) -> ()
| Event (Key _) ->
Matrix.request_redraw app;
loop (count + 1)
| Frame ->
Matrix.draw app (fun grid ->
Matrix.Grid.draw_text grid ~x:0 ~y:0
~text:(Printf.sprintf "%d keys" count));
loop count
| Event _ | Timer _ | Posted _ -> loop count
in
loop 0Because the loop is yours, you can also hand it to another event loop. Matrix.step runs one turn without waiting for input, and Matrix.fds and Matrix.deadline tell Eio, Lwt or your own loop what to wait for. Matrix.post sends a message from any thread or domain.
Frames now come only when you ask for one with Matrix.request_redraw, so an idle program doesn't wake up at all. 0.1 drew 30 frames a second whether anything changed or not. A key's frame is drawn in the same turn that read the key: in our benchmark, the median time from a key press to the screen is under 0.4 ms.
Also new
matrix.testruns a program's own loop on an emulated terminal, with a clock that only the test moves. Send input, resize and advance time, then read the screen withMatrix_test.Screen.- Inline mode no longer erases the shell's output when the terminal is resized, when it runs under tmux, or when another process writes. In our tests on five terminal emulators, it lost no lines.
- A key decodes to the same value whichever encoding the terminal uses. Pastes arrive in pieces with no size limit, and the terminal's answers to queries no longer show up as key presses.
Matrix_grid.draw_pictureshows RGBA images, sent as kitty graphics, sixels or half blocks, whichever the terminal supports.Matrix_grid.Linesjoins box-drawing lines where they meet.matrix.cliandmatrix.cli.unixare for command-line programs that don't take over the screen: progress shown below the program's output, task trees with progress bars, prompts and tables. They follow--color,NO_COLOR, pipes and CI.Matrix.query_palettereads the user's palette, so you can pick colors that fit their theme.Matrix.runaccepts the descriptors and environment of any terminal, andMatrix.on_deviceruns one program per remote session, for example one per SSH connection.Matrix.releaselends the terminal to an editor or a shell and takes it back, andMatrix.stop_jobsuspends the program as Ctrl+Z does. TheTerminalmodule adds clipboard, notification and bell commands, andMatrix.set_mouseswitches mouse tracking while the program runs.- We rewrote
matrix.chartsaround figures. Marks such asline,area,bar_yandsparkshare named scales, and axes and legends follow from those scales. A figure's layout also answers zoom, pan and hit tests. - Set
MATRIX_DEBUG=overlayto see frame timings, orMATRIX_DEBUG=frames=DIRto save every frame, in any Matrix or Mosaic program, without rebuilding it. matrix.textfollows Unicode 18.0 and lays out wrapped text, andAnsi.sanitizemakes untrusted text safe to print.Vte.feedreturns the replies the emulated terminal sends back.
Changes the compiler won't catch
- Matrix no longer runs on Windows.
Matrix.run, and soMosaic.run, raisesFailurethere: the new runtime waits on POSIX descriptors and has no Windows path yet.matrix.ptyis POSIX-only too, because its ConPTY backend was unsound. - Frames are drawn only on request. Call
Matrix.request_redrawwhenever your view changes, and again from eachFramewhile something animates. A program that relied on 0.1's 30 frames a second will stop updating its screen. - Ctrl+C is an ordinary key, and Matrix no longer quits on it. To quit, test
Input.Keystroke.is_interruptand return from the run. Mosaic programs still quit on Ctrl+C by default. - SIGINT, SIGTERM, SIGHUP and SIGQUIT restore the terminal and then end the process with the signal's status, so
rundoesn't return. 0.1 exited with a wrong status and replaced handlers the program had installed. Now a handler you install first wins. - The cursor starts hidden in both modes. Show it with
Matrix.set_cursor app ~visible:true. - Output follows the user's color settings.
NO_COLORdrops colors, a 16-color terminal gets 16 colors and a pipe gets no styling at all. Pass~color:`AlwaystoMatrix.configto keep colors whatever the user set. - In inline mode, the last frame stays on screen at exit.
Matrix.keep_frame app falseerases it. - Pictographs such as ❤ and ⚠ take one cell unless a VS16 follows them, as terminals draw them. Matrix counted them as two, which shifted the rest of the row.
- Drawing a space now erases the text under it,
blit_regioncopies colors as they are, and a transparentfill_rectchanges nothing. To tint cells, draw a translucentfill_rect. - Matrix installs no handler for uncaught exceptions. The run restores the terminal and raises the exception again.
Pty.spawn, Screen.resize, Terminal.reset_state and Vte.cursor_pos also behave differently in smaller ways; the guide lists them.
Breaking changes
The migration guide has the full lists.
- The callback runtime is gone.
Matrix.create,attach, theon_*callbacks,close,stop,suspendandresumegive way to the loop shown above,Matrix.StopandMatrix.release. The old runtime ran application code from inside Matrix's loop, and its call order was promised only by a comment. See the runtime. - The options of
createmoved intoMatrix.config, given asrun ~config. - Input events are
Matrix.event.Input.Keyis nowInput.Keystroke,Input.MouseisInput.Mouse_report, andInput.ParserisInput.Decoder. A paste arrives asPaste_start,Paste_dataandPaste_end: 0.1 cut a paste off after 5 seconds of silence and typed the rest as keys.Input.Keymapmoved to Mosaic asMosaic.Shortcut. - Library modules have a prefix:
GridisMatrix_grid,ScreenisMatrix_screen, and so on. The short names clashed with any other library, or file of your own, that had a module with the same name. InsideMatrix, the short names still work. - The
matrix-eiopackage is gone. Any event loop can now wait on the run's descriptors, and Mosaic programs useMosaic_eio.run. matrix.glyphis gone. Measure and segment text withmatrix.text.Ansi.Color.tis abstract, so that a palette color stays a palette color all the way to the terminal. Build colors withColor.of_rgb,Color.indexedor named values such asColor.red.Ansi.rendertakes spans built withAnsi.span. It now sanitizes the text, so a string from elsewhere can't move the cursor or restyle what follows.Terminal.set_raw,restoreandsizemoved toTty, along with everything else that calls the operating system, somatrix.terminalno longer linksunix.Matrix.ImageisMatrix_image, andImage.render grid imgisMatrix_image.draw img grid.Matrix.static_writetakes a grid where it took a string and a row count that you had to get right yourself.- The debug overlay and frame dumps are no longer options of the run. Use
MATRIX_DEBUG, orMatrix.Debug_overlayandMatrix.dump_frame. Matrix_grid.createtakes no pool and no blending flag, and each drawing call says whether it blends. The screen's cursor setters became oneMatrix_screen.set_cursor, andScreen.post_processis gone.Vte.feedreturns the terminal's replies, which used to pile up in a queue that nothing drained.Vte.createtakes a?paletteinstead of default colors.matrix.chartshas the new API described above. A sparkline is afloat listdrawn withspark.
Fixed
- Ctrl+V and Ctrl+O didn't reach the application.
- The runtime used a full CPU core once its input closed.
- A failed setup left the terminal in raw mode.
- A mouse report on the first row of the inline region came in as row -1.
- A combining mark after an ASCII letter was split from the letter.
Toffee
Toffee's layouts match Chromium's more often. We ported fixes from Taffy and checked others against Chromium, for percentages, aspect ratios, absolute positioning, baselines and scroll extents. A row-reverse scroll container can now scroll, for one.
Relayout is also much cheaper, which matters for Mosaic's long transcripts. Each node caches up to 24 measurements, where 0.1 had nine fixed slots that kept evicting each other. With nine, appending a line to a 20,000-line log measured text 500,000 times; with 24, it measures 20,000 times. Rounding skips the subtrees that didn't move, laying out an unchanged tree returns at once, and reading a layout allocates nothing.
Changes the compiler won't catch
- A flex or grid root without a width fills the available width, less its margins, as a block root already did and as browsers do. Before, its children had no width to resolve percentages against. To size it to its content as before, give it a width, or lay it out in
Available_space.max_content. - A root with margins sits at its margins instead of at (0, 0).
- Locations are rounded from absolute positions, as in Taffy and browsers, so boxes at fractional offsets tile without gaps or overlaps. A box under a parent at a fractional position may move by one cell.
- A measure function receives the size of the content box, clamped by the leaf's minimum and maximum sizes, where it received the border box. A padded text was measured at one height and laid out at another, so the line after it drew over it.
- Percentages inside a flex item whose size comes from its content resolve as if that size were unknown, as browsers do.
Breaking changes
- Geometry is unboxed. Measure functions return a
Sizef.t, and the fields ofLayout.tareSizef.t,Pointf.tandRectf.t, records of plain floats. Reading a layout used to allocate a box for every float. The float operations moved into those modules too, andSize.max_concreteisSizef.max. Layout.content_sizeis nowLayout.scrollable_overflow, which can reach before the origin, as CSS defines it. For scroll extents, useLayout.scroll_widthandLayout.scroll_height.- Library modules have a prefix (
Toffee_style,Toffee_treeand so on), for the same reason as Matrix's.Toffee.StyleandToffee.Geometrystill work. Size.equal_optionandAvailable_space.maybe_setare nowSize.equal_withandAvailable_space.set_or_self.- If you write your own layout algorithm or tree, the cache takes the node's
Layout_input.tand its style,Layout_input.thas a new field, outputs carry aScrollable_overflow.t, andROUND_TREEaddsis_rounded. See Toffee in the guide.
Fixed
- A grid's auto rows collapsed when they held scroll containers.
[0.1.0] - 2026-02-26
Mosaic
Terminal UI framework for OCaml built on Matrix and Toffee. Implements The Elm Architecture (TEA) for declarative, composable terminal applications.
- The Elm Architecture – Pure functional Model-View-Update pattern with
init,update,view, andsubscriptions. Commands (Cmd) handle side effects; subscriptions (Sub) handle external events - Flexbox and Grid layout – Powered by Toffee, define complex layouts with familiar CSS properties like
flex_direction,align_items,justify_content, and CSS Grid support - Rich widget library –
box,text,input,textarea,select,tab_select,slider,table,spinner,scroll_box,canvas,code,markdown,tree,progress_bar, andline_number - Rich text – Styled fragments, word/character wrapping, text selection, and full Unicode support
- Syntax highlighting – Tree-sitter-based code highlighting with the
codewidget - Event system – Mouse, keyboard, paste, focus, and resize events with
Sub.on_key,Sub.on_mouse,Sub.on_paste,Sub.on_resize,Sub.on_focus, andSub.on_blur - Canvas drawing – Procedural drawing API with shapes, lines, and braille patterns for charts and visualizations
- Markdown rendering – CommonMark rendering with the
markdownwidget - Dirty tracking and viewport culling – Only re-layouts dirty subtrees; scroll containers cull off-screen children
Matrix
Terminal toolkit for OCaml providing rendering, input, and terminal management.
- Immediate-mode runtime –
Matrix.runwithon_frame,on_render,on_input,on_resizecallbacks, configurable FPS capping, and safe teardown that restores terminal state even on exceptions - Two display modes – Full-screen alternate buffer (
Alt) or inline on primary screen (Primary) with dynamic height and full scrollback - Declarative Image API – Notty-inspired compositional DSL with
hcat,vcat,overlay, padding, cropping, and hit regions for mouse interaction - Full Unicode support – Grapheme cluster handling, emoji, wide characters, and configurable width calculation (wcwidth, Unicode tables)
- Modern terminal protocols – Kitty keyboard (with auto-detection), SGR/X10/URXVT mouse tracking, bracketed paste, focus reporting—all negotiated automatically
- Native alpha blending – RGBA colors with proper alpha compositing for translucent overlays
- Double-buffered diffing – Screen module diffs cell changes between frames to emit minimal ANSI output
- PTY & VTE – Spawn processes in pseudo-terminals and embed terminal output in your UI; cross-platform with Windows ConPTY support
- Automatic capability detection – Two-stage probing (environment heuristics + active queries) detects RGB, Kitty keyboard, sixel, hyperlinks, and Unicode width support without manual configuration
- Hit testing – O(1) spatial indexing maps mouse coordinates to UI element IDs for clickable widgets
- Built-in devtools – Debug overlay for frame timing/FPS, frame dumps to disk for diagnostics
Toffee
CSS layout engine for OCaml, ported from Taffy (Rust).
- CSS Grid Level 1 – Full implementation including
grid-template-columns/rows,grid-auto-flow, named lines/areas,repeat(),minmax(),frunits, and auto-placement - Flexbox – Complete algorithm with
flex-direction,flex-wrap,flex-grow/shrink/basis,align-items/self/content,justify-content,gap, andorder - Block layout – Traditional CSS block formatting context with proper margin collapsing
- Pure OCaml, zero dependencies – No C stubs, no runtime dependencies; works wherever OCaml 5 runs
- Arena storage and layout caching – Nodes stored in a flat arena; layout results cached and invalidated via
mark_dirty - Composable architecture – Use the high-level
Toffeetree API or the lower-leveltoffee.treeandtoffee.computelibraries to plug layout into your own node representation - Custom measure functions – Integrate text shaping, images, or any content with intrinsic sizing via
compute_layout_with_measure