Blender's GPU Accelerated UI, Decoupled from it's original codebase. Supports Rust, Python, JS, React, C & C++. Twice as good as GPUI
feat: shadcn style macro
Preetham Pemmasani2a341e41a5a2
diff --git a/AGENTS.md b/AGENTS.mdindex 666a128..c1ca7d9 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,4 +1,5 @@These must be strictly followed:+- Always use DRY principles. Never ever make another function for the same things that can be re-used.- Never regress the perf, unless absolutely necessary- Follow the full Blender's source code. DO NOT Deviate from it.@@ -16,9 +17,17 @@ These must be strictly followed:- errors / validation not at the boundaryThese are recommended:+- In order to prevent memory leaks, and crashes, highly recommended to follow the blender's source code as a base and build upon in rust.If writing Rust:+- STRICTLY DO NOT HAVE Rc<Refcell>. DO IT COMPILE TIME!! It just swaps gc for runtime borrow checks and refcount churn. you won't get real rust perf without a second pass flattening entitices into an arena or ECS with indices.- Please have the clippy lints: all = { level = "warn", priority = -2 }, pedantic = { level = "warn", priority = -2 }, perf = { level = "warn", priority = -1 }, complexity = { level = "warn", priority = -1 }, inline_always = "allow", unseparated_literal_suffix = "allow", similar_names = "allow", missing_panics_doc = "allow", missing_errors_doc = "allow", absolute_paths = "allow", module_name_repetitions = "allow", doc_markdown = "allow", too_many_lines = "allow", unused_self = "allow", cast_possible_truncation = "allow", cast_sign_loss = "allow", cast_precision_loss = "allow", unreadable_literal = "allow", implicit_hasher = "allow", significant_drop_tightening = "warn", redundant_clone = "warn", use_self = "warn", redundant_else = "warn", or_fun_call = "warn", missing_const_for_fn = "warn", derive_partial_eq_without_eq = "warn"- Always NEVER ALLOCATE, try to use the refs, never clone unless necessary. even for strings, use CoW and refs.++After updating any part of the core/component/bindings:++- Update the website+- Update the readme+- Update the docsdiff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex aefb1ea..c159279 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -65,7 +65,7 @@ include `ui/`.)| `gpu/` | The draw surface used by the toolkit (`GPU_*`, `imm*`) behind seam headers + a null backend that *records and forwards*: with a sink installed it emits screen-space primitives (`GPU_backend_sink.h`); without one it discards them. Theme colors reach the GPU layer through function-pointer hooks. | **Builds + tested** || `compat/` | Seam headers carrying upstream API names (`RNA_access.hh`, `BLF_api.hh`, …) with BUI-owned opaque types and stub implementations (`intern/bui_stubs.cc`). | **Builds** || `ui/` | The toolkit sources from `editors/interface`: interface.cc family, widgets, handlers, regions, view2d, views, textbox. Kept for reference and porting work; **not compiled by default** (`-DBUI_BUILD_UI=ON` builds it as `bui_ui`). `kit/` re-ports what it needs in C. | **Compiles + links** (opt-in) |-| `kit/` | Blender's UI as a retained-mode C runtime: node tree, uiLayout-style layout, `interface_handlers.cc` interaction rules, widget drawing ported from `interface_widgets.cc` (widget-base shader parameters rendered by `gpu/` raster), menus, color picker, views, editors; Tk-style pack/grid/place geometry managers, canvas display list, multi-line text area; UI undo/redo, Tab field traversal, vertical multi-drag, panel animation; Blender's file browser; damage-driven rendering; Blender's Dark and Light themes (`kit_theme_presets.c`, generated by `tools/gen_theme.py` from Blender's `Blender_Dark.xml` / `Blender_Light.xml` presets over `userdef_default_theme.c`; `BK_set_theme`); native window hosts for Win32, X11 and Cocoa (`kit_window_win32.c`, `kit_window_x11.c`, `kit_window_cocoa.m`; `kit_window_null.c` elsewhere). The Win32 host is BUI's own; the X11 host follows Blender's GHOST input mapping, and the Cocoa host (experimental: checked by CI, not yet tried by hand on a Mac) is ported from GHOST's Cocoa backend. `kit/intern/blender/` holds Blender files copied in and edited for the kit (each edit marked `BUI:`): `interface_string_search.cc` (menu search with recent searches), `interface_undo.cc` (text-edit undo), `interface_utils.cc` (float display precision). C API: `kit/include/BUI_kit.h`. | **Builds + tested** |+| `kit/` | Blender's UI as a retained-mode C runtime: node tree, uiLayout-style layout, `interface_handlers.cc` interaction rules, widget drawing ported from `interface_widgets.cc` (widget-base shader parameters rendered by `gpu/` raster), menus, color picker, views, editors; Tk-style pack/grid/place geometry managers, canvas display list, multi-line text area; UI undo/redo, Tab field traversal, vertical multi-drag, panel animation; Blender's file browser; damage-driven rendering; Blender's Dark and Light themes (`kit_theme_presets.c`, generated by `tools/gen_theme.py` from Blender's `Blender_Dark.xml` / `Blender_Light.xml` presets over `userdef_default_theme.c`; `BK_set_theme`); native window hosts for Win32, X11 and Cocoa (`kit_window_win32.c`, `kit_window_x11.c`, `kit_window_cocoa.m`; `kit_window_null.c` elsewhere). The Win32 host is BUI's own; the X11 host follows Blender's GHOST input mapping, and the Cocoa host (experimental: checked by CI and tried by hand on an Apple Silicon Mac) is ported from GHOST's Cocoa backend. `kit/intern/blender/` holds Blender files copied in and edited for the kit (each edit marked `BUI:`): `interface_string_search.cc` (menu search with recent searches), `interface_undo.cc` (text-edit undo), `interface_utils.cc` (float display precision). C API: `kit/include/BUI_kit.h`. | **Builds + tested** || `api/` | `bui_c_api.h` — small stable C ABI: version info + sink/viewport plumbing for hosts and bindings. | **Builds + tested** || `bindings/python/` | `buipy` CPython extension (no third-party deps) + `bui` package: `bui.components` (Blender component library), `bui.qtsyntax` / `bui.tksyntax` (Qt / tkinter APIs as thin facades over the kit), `bui.host` (native or Tk windows), `SvgSink` headless renderer, `bui.qt.BuiCanvas` PySide6/PyQt6 widget. | **Builds + tested** || `bindings/imgui/` | Dear ImGui (vendored, 1.93.1 WIP) on BUI: `imgui_impl_bui` platform + renderer backend hosted in a kit `custom` node (input, cursors, clipboard, DPI, damage-driven frames) drawing through `BUI_raster_mesh` and BUI textures; Blender style and Inter font; the C API (`cimgui.h`) and the generator behind the Python and Rust bindings; the Blender-widgets build (`blender/`, `-DBUI_IMGUI_BLENDER_WIDGETS=ON`). Gate: `-DBUI_BUILD_IMGUI` (ON with C++). | **Builds + tested** |diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f4624c4..9d9b3a2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,9 +6,40 @@ All notable changes to **blenderui** (BUI). The format follows## [Unreleased]+### Added+- **shadcn Data Table and virtual list for Rust** (`blenderui::shadcn`): the API of+ shadcn/ui's Data Table (TanStack `ColumnDef`, sorting, column and global filters,+ pagination, row selection, column visibility, controlled and uncontrolled state) as+ `<DataTable columns={..} data={..} />` / `DataTable::new`, with `DataTableColumnHeader`,+ `DataTablePagination`, `DataTableViewOptions` and `DataTableToolbar`, on the painted table;+ cells are typed (text with a number format, checkbox, badge, progress, row actions), so a+ million rows stay O(visible). `VirtualList` and `ChatList` with TanStack Virtual's names+ (`estimate_size`, `overscan`, `get_item_key`, `scroll_to_index`, `scroll_to_offset`,+ `measure_element`, `on_range_change`) over the variable-height list. The logic is in+ `blenderui_table::tanstack` and `blenderui_vlist::rows`.++### Changed+- **macOS:** the docs and the website now say the Cocoa host has been tried by hand on an Apple+ Silicon Mac, by [Krish Kalaria](https://github.com/krishkalaria12) (issue #3, pull request #4).+- **Website:** a video of the variable-height list (downloaded only when played), shadcn pages,+ and a crates.io link in the footer.++## [0.2.0] - 2026-11-05+### Added (latest: summary)The newest work. Details for some items follow in the sections below.+- **Data table and variable-height list for Rust** (new crates `blenderui-table`,+ `blenderui-vlist` and `blenderui-paint`, used by `blenderui`): a virtualized data table+ (a million rows by twenty columns, painted from typed columns, sorting, selection,+ resizable columns) and a chat-grade list with items of different heights (a two-level height+ index, scrolling anchored to an item, opens at the newest message, a file-backed source for+ ten million messages), both on Blender's own virtualization ideas. See the benchmarks in the+ docs.+- **Release pipeline:** one tag publishes the Rust crates (crates.io), the npm packages (trusted+ publishing) and the Python wheels (PyPI, trusted publishing), with a version check first.+- **Text:** glyphs sit on the same baseline in every size, so labels are centered in pills and+ buttons.- **Dear ImGui on BUI** (`bindings/imgui/`): the real Dear ImGui 1.93.1 WIP(vendored, MIT) on a BUI platform + renderer backend (`imgui_impl_bui`),hosted in a kit `custom` node: BUI's windows and input, the software raster,@@ -37,7 +68,8 @@ The newest work. Details for some items follow in the sections below.`BUI_GPU_EGL` picks the EGL platform.- **macOS: a native Cocoa window host** (`kit/intern/kit_window_cocoa.m`),ported from Blender's GHOST Cocoa backend, with Retina scaling. Experimental:- checked by CI but not yet tried by hand on a Mac (see `docs/macos-testing.md`). Python can+ checked by CI and tried by hand on an Apple Silicon Mac by [Krish Kalaria](https://github.com/krishkalaria12) (issue #3,+ pull request #4), which found the fixes listed below (see `docs/macos-testing.md`). Python canfall back to the Tk window with `BUI_HOST=tk`; JavaScript stays headless onmacOS.- **Light theme:** Blender's Dark (default) and Light presets, generated bydiff --git a/README.md b/README.mdindex ac214c2..4e9200c 100644--- a/README.md+++ b/README.md@@ -4,7 +4,7 @@<img alt="BUI Logo" src="https://raw.githubusercontent.com/ppmpreetham/BUI/main/public/Logo.png" width="300"/></picture></p>-+<h1 align="center">BUI</h1>@@ -28,9 +28,6 @@ People spent decades building and optimizing Blender's GUI. It's battery and mem</div>-> [!NOTE]-> This repository is built entirely using LLMs. No human-written code.-This README is a small book. Read it front to back for the whole story, orjump to the chapter you need. Every chapter links to a longer guide in[`docs/`](docs/) or on the [website](https://bui.preetham.top) when there's@@ -126,14 +123,14 @@ What BUI is not:- **Not Blender.** It contains the parts of Blender's UI code it needs andbuilds on its own. You don't need Blender installed, and you don't need toknow Blender to use it.-- **Not a browser.** The Rust and JavaScript sides use HTML and CSS as a *UI- language*, but there's no browser engine, no webview and no network.+- **Not a browser.** The Rust and JavaScript sides use HTML and CSS as a _UI+ language_, but there's no browser engine, no webview and no network.- **Not a re-imagining.** The widget drawing is ported from Blender's`interface_widgets.cc`, and the Dear ImGui support runs the real Dear ImGui.## 2. Why BUI exists-Blender's interface is famous for how it *feels*. You press a number field and+Blender's interface is famous for how it _feels_. You press a number field anddrag: the cursor vanishes, the value glides under your hand, and you never hitthe edge of the screen. You type `2*pi` into a field and it just works. Youtype "ad cu" into a menu and it finds "Add Cube". Millions of artists have@@ -161,16 +158,16 @@ in any language, can have both: Blender's feel, and Blender's efficiency.You can drive BUI many ways, and all of them share the same C runtime, so theyall get the same widgets and interactions:-| You write | You get | Status |-| --- | --- | --- |-| **tkinter** code, even existing programs, unchanged | Blender-styled apps; every tkinter and ttk API | Complete |-| **Qt-style** Python (`QWidget`, layouts, `clicked.connect`) | The common subset of Qt widgets | Partial |-| **Blender components** (`Panel`, `NumberSlider`, `PieMenu`, the node editor ...) | 45 native Blender widgets and editors, from Python; ten of them also from Rust and JavaScript | Complete |-| **Rust**: HTML + CSS + Tailwind, HTML-like markup (`rsx!` / `view!`), hooks, or [gpui](https://www.gpui.rs) / [zopra](https://zopra.preetham.top) syntax | A web-like framework: HTML that looks like a browser's, Blender's look with `styled`, and Blender components (`<NumberSlider>`, `<Button>` ...) | Working |-| **JavaScript / React** on Node.js or Bun: a DOM-like API or JSX | The same engine and components in native windows, over napi-rs; React's hooks backed by signals | Working |-| **Dear ImGui** from C++, C, Python or Rust | The real Dear ImGui on BUI windows in Blender's theme, or a build where ImGui's widgets *are* Blender's widgets | Working |-| **C** (`BUI_kit.h`) | The kit itself: nodes, widgets, windows | Working |-| **MyGo** | MyGo | Not yet (coming soon) |+| You write | You get | Status |+| -------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |+| **tkinter** code, even existing programs, unchanged | Blender-styled apps; every tkinter and ttk API | Complete |+| **Qt-style** Python (`QWidget`, layouts, `clicked.connect`) | The common subset of Qt widgets | Partial |+| **Blender components** (`Panel`, `NumberSlider`, `PieMenu`, the node editor ...) | 45 native Blender widgets and editors, from Python; ten of them also from Rust and JavaScript | Complete |+| **Rust**: HTML + CSS + Tailwind, HTML-like markup (`rsx!` / `view!`), hooks, or [gpui](https://www.gpui.rs) / [zopra](https://zopra.preetham.top) syntax | A web-like framework: HTML that looks like a browser's, Blender's look with `styled`, and Blender components (`<NumberSlider>`, `<Button>` ...) | Working |+| **JavaScript / React** on Node.js or Bun: a DOM-like API or JSX | The same engine and components in native windows, over napi-rs; React's hooks backed by signals | Working |+| **Dear ImGui** from C++, C, Python or Rust | The real Dear ImGui on BUI windows in Blender's theme, or a build where ImGui's widgets _are_ Blender's widgets | Working |+| **C** (`BUI_kit.h`) | The kit itself: nodes, widgets, windows | Working |+| **MyGo** | MyGo | Not yet (coming soon) |Not sure which to pick? If you already have code, use the row that matches it.If you're starting fresh in Python, the Blender components are the friendliest.@@ -393,22 +390,20 @@ target_link_libraries(myapp PRIVATE bui::kit)**Dear ImGui.** Python gets it with `pip install blenderui`(`import blenderui.imgui`). C++ links `bui::imgui`, C links `bui_cimgui`.-Rust uses the `blenderui-imgui` crate, which isn't on crates.io yet, so take it-from git:+Rust uses the [`blenderui-imgui`](https://crates.io/crates/blenderui-imgui) crate:-```toml-[dependencies]-blenderui-imgui = { git = "https://github.com/ppmpreetham/BUI" }+```sh+cargo add blenderui-imgui```**If something goes wrong:**-| Symptom | Fix |-| --- | --- |-| `ImportError: buipy` | You're running from a source checkout without a build. Build first (`cmake --build build`), or set `BUIPY_BUILD_DIR`. The extension must match your Python version. |-| The window never appears | Start the event loop: `mainloop()`, `app.exec()` or `App.run()`. |-| Blurry or tiny UI | Set `BUI_UI_SCALE`, for example `BUI_UI_SCALE=1.25`. |-| `gpu=True` does nothing | Run with `BUI_GPU_DEBUG=1` to see why the GPU device didn't start. Without Direct3D 11 or OpenGL 3.3, BUI stays on the CPU renderer, which draws the same pixels. |+| Symptom | Fix |+| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `ImportError: buipy` | You're running from a source checkout without a build. Build first (`cmake --build build`), or set `BUIPY_BUILD_DIR`. The extension must match your Python version. |+| The window never appears | Start the event loop: `mainloop()`, `app.exec()` or `App.run()`. |+| Blurry or tiny UI | Set `BUI_UI_SCALE`, for example `BUI_UI_SCALE=1.25`. |+| `gpu=True` does nothing | Run with `BUI_GPU_DEBUG=1` to see why the GPU device didn't start. Without Direct3D 11 or OpenGL 3.3, BUI stays on the CPU renderer, which draws the same pixels. |More: [docs/getting-started.md](docs/getting-started.md) and[Install BUI](https://bui.preetham.top/docs/start/installation/) on the website.@@ -659,10 +654,12 @@ import { render, useState, NumberSlider } from "@blender-ui/react"function Counter() {const [count, setCount] = useState(0) // React's hook, holding a signalreturn (- <main styled className="p-6 flex flex-col gap-3"> {/* `styled`: Blender's look */}+ <main styled className="p-6 flex flex-col gap-3">+ {" "}+ {/* `styled`: Blender's look */}<span>Clicks: {count}</span><button onClick={() => setCount((c) => c + 1)}>Add one</button>- <NumberSlider min={0} max={10} /> {/* a Blender component */}+ <NumberSlider min={0} max={10} /> {/* a Blender component */}</main>)}@@ -678,18 +675,18 @@ npx bui build app.jsx # or ship it: app.exe, one 5 MB fileWithout React, `@blender-ui/native` gives you a DOM-like API:```js-const { App, signal } = require('@blender-ui/native')+const { App, signal } = require("@blender-ui/native")const app = new App({ gpu: true })-const win = app.window({ title: 'Hello', width: 360, height: 200 })-win.body.className = 'm-0 p-6 flex flex-col gap-3 bg-[#2b2b2b] text-[#e6e6e6]'+const win = app.window({ title: "Hello", width: 360, height: 200 })+win.body.className = "m-0 p-6 flex flex-col gap-3 bg-[#2b2b2b] text-[#e6e6e6]"const clicks = signal(0)-const label = win.createElement('span')-label.textContent = clicks // follows the signal-const button = win.createElement('button')-button.textContent = 'Add one'-button.addEventListener('click', () => clicks.value++)+const label = win.createElement("span")+label.textContent = clicks // follows the signal+const button = win.createElement("button")+button.textContent = "Add one"+button.addEventListener("click", () => clicks.value++)win.body.appendChild(label)win.body.appendChild(button)```@@ -935,7 +932,7 @@ Blender-widgets build, and every C kit widget.- **Shortcuts on any value:** Backspace resets to the default, `-` negates,Ctrl+Wheel steps, Ctrl+C / Ctrl+V copy and paste, right-click opens Copy,Paste and Reset.-- **Several fields at once.** Drag *down* over a column of number fields to+- **Several fields at once.** Drag _down_ over a column of number fields tocollect them, then sideways to change them together. Drag across checkboxes(or panel headers) to set them all in one stroke.- **Panels** collapse with Blender's animation; Ctrl+click opens one and@@ -960,11 +957,11 @@ popups, and widget drag and drop. More:In Rust and JavaScript you pick the look per element:-| You write | You get |-| --- | --- |-| Plain HTML: `<button>`, `<input type="range">`, `<select>` ... | What a browser draws: black text on white and Chrome's form controls, in the Inter UI font |-| `styled` on any element: `<div styled>`, `div().styled()` | Blender's look for it and everything inside: Blender's theme (dark or light), UI font, Blender widgets |-| **Blender components** (capitalized): `<NumberSlider>`, `<Button>` ... | Blender's widgets and interaction everywhere (drag to scrub, Ctrl+Z, Blender's color picker) |+| You write | You get |+| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |+| Plain HTML: `<button>`, `<input type="range">`, `<select>` ... | What a browser draws: black text on white and Chrome's form controls, in the Inter UI font |+| `styled` on any element: `<div styled>`, `div().styled()` | Blender's look for it and everything inside: Blender's theme (dark or light), UI font, Blender widgets |+| **Blender components** (capitalized): `<NumberSlider>`, `<Button>` ... | Blender's widgets and interaction everywhere (drag to scrub, Ctrl+Z, Blender's color picker) |The components are `Button`, `Checkbox`, `Radio`, `NumberField`, `NumberSlider`,`TextField`, `TextArea`, `ColorSwatch`, `Dropdown` and `ProgressBar`. Each one@@ -1045,13 +1042,13 @@ of 172,800 pixels that differ by more than 3/255, on both backends.Turn the GPU on:-| Where | How |-| --- | --- |-| Python | `bui.set_gpu(True)` before creating windows; tkinter syntax also `tk.Tk(gpu=True)` |-| Rust | `Application::new().gpu(true)`, or `WindowOptions { gpu: Some(true), .. }` |-| JavaScript | `new App({ gpu: true })`, or React's `render(..., { gpu: true })` |-| C | `BUI_gpu_set_default(1)`, or `BK_window_set_gpu(win, 1)` |-| Any app, no code change | `BUI_GPU=1` |+| Where | How |+| ----------------------- | ---------------------------------------------------------------------------------- |+| Python | `bui.set_gpu(True)` before creating windows; tkinter syntax also `tk.Tk(gpu=True)` |+| Rust | `Application::new().gpu(true)`, or `WindowOptions { gpu: Some(true), .. }` |+| JavaScript | `new App({ gpu: true })`, or React's `render(..., { gpu: true })` |+| C | `BUI_gpu_set_default(1)`, or `BK_window_set_gpu(win, 1)` |+| Any app, no code change | `BUI_GPU=1` |`BUI_GPU=1` overrides the app-wide setting in code; `BUI_GPU=0` turns theapp-wide defaults off, but a window that asks for the GPU itself still gets@@ -1092,13 +1089,13 @@ something moves, paced to the display. More:A **window host** puts a kit context in a top-level window and feeds it input.-| Host | Where | Notes |-| --- | --- | --- |-| **Win32** (`kit_window_win32.c`) | Windows | BUI's own host. Per-monitor DPI, vsync-paced animation, clipboard, cursors, window-manager features. |-| **X11** (`kit_window_x11.c`) | Linux; Wayland through XWayland | Input mapping after Blender's GHOST. `Xft.dpi` scaling. libX11 is loaded when the first window opens. |-| **Cocoa** (`kit_window_cocoa.m`) | macOS | **Experimental.** Ported from Blender's GHOST Cocoa code, with Retina scaling. So far it's only been checked by CI, not yet by a person on a real Mac; testing notes in [docs/macos-testing.md](docs/macos-testing.md). |-| **Tk** | Python, anywhere | A stdlib `tkinter` window that shows the kit's frame buffer. `BUI_HOST=tk` forces it; it's also the fallback where no native host works. |-| **Headless** | Everywhere | No window: render into a raster for tests and screenshots, with a virtual clock that steps animations exactly. |+| Host | Where | Notes |+| -------------------------------- | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **Win32** (`kit_window_win32.c`) | Windows | BUI's own host. Per-monitor DPI, vsync-paced animation, clipboard, cursors, window-manager features. |+| **X11** (`kit_window_x11.c`) | Linux; Wayland through XWayland | Input mapping after Blender's GHOST. `Xft.dpi` scaling. libX11 is loaded when the first window opens. |+| **Cocoa** (`kit_window_cocoa.m`) | macOS | **Experimental.** Ported from Blender's GHOST Cocoa code, with Retina scaling. It's checked by CI and has been tried by hand on one Apple Silicon Mac so far; testing notes in [docs/macos-testing.md](docs/macos-testing.md). |+| **Tk** | Python, anywhere | A stdlib `tkinter` window that shows the kit's frame buffer. `BUI_HOST=tk` forces it; it's also the fallback where no native host works. |+| **Headless** | Everywhere | No window: render into a raster for tests and screenshots, with a virtual clock that steps animations exactly. |`BUI_UI_SCALE=1.5` fixes the UI scale instead of following the display (1 isBlender's default, 20 px widgets). More:@@ -1139,14 +1136,14 @@ generated by `tools/gen_theme.py` from Blender's own `Blender_Dark.xml` and`Blender_Light.xml` presets, over Blender 5.x's built-in defaults. Switch atrun time, and every open window relayouts and redraws:-| Where | Light theme |-| --- | --- |-| C | `BK_set_theme("light")`; `BK_theme_name()`, `BK_theme_color("region_bg", rgba)` |-| Python | `blenderui.set_theme("light")` (also switches the Dear ImGui extension); `theme_name()`, `theme_color(key)` |-| Rust | `blenderui::set_theme("light")`, or `Application::new().theme("light")`; `theme_name()`, `theme_color(key)` |-| JavaScript | `new App({ theme: "light" })`, `app.setTheme("light")`, or React's `render(..., { theme: "light" })` |-| Dear ImGui | Its Blender style follows the kit's theme (pick it before the backend starts) |-| Any app, no code change | `BUI_THEME=light` (or `dark`) |+| Where | Light theme |+| ----------------------- | ----------------------------------------------------------------------------------------------------------- |+| C | `BK_set_theme("light")`; `BK_theme_name()`, `BK_theme_color("region_bg", rgba)` |+| Python | `blenderui.set_theme("light")` (also switches the Dear ImGui extension); `theme_name()`, `theme_color(key)` |+| Rust | `blenderui::set_theme("light")`, or `Application::new().theme("light")`; `theme_name()`, `theme_color(key)` |+| JavaScript | `new App({ theme: "light" })`, `app.setTheme("light")`, or React's `render(..., { theme: "light" })` |+| Dear ImGui | Its Blender style follows the kit's theme (pick it before the backend starts) |+| Any app, no code change | `BUI_THEME=light` (or `dark`) |Widgets, panels, the region background, the `styled` HTML sheet and ImGui'sBlender style all follow the theme. Plain HTML keeps a browser's look either@@ -1270,7 +1267,7 @@ transforms, OpenType features, multi-column layout. Guide:Limits: npm packages are prebuilt for Windows x64 only; events reachJavaScript after BUI handled them (no native `preventDefault`), and-`event.target` is the deepest *listening* element. Guide:+`event.target` is the deepest _listening_ element. Guide:[docs/javascript.md](docs/javascript.md); website:[React](https://bui.preetham.top/docs/javascript/react/),[native API](https://bui.preetham.top/docs/javascript/native-api/),@@ -1279,12 +1276,12 @@ JavaScript after BUI handled them (no native `preventDefault`), and## 26. Dear ImGui-| Language | What you use | Built by |-| --- | --- | --- |-| C++ | `imgui.h` + `imgui_impl_bui.h` | CMake target `bui_imgui` (`bui::imgui`) |-| C | `cimgui.h` + `cimgui_impl_bui.h` | CMake target `bui_cimgui` |-| Python | `import blenderui.imgui as imgui` | The `_buiimgui` extension, in the wheel |-| Rust | the `blenderui-imgui` crate (git dependency for now) | Cargo |+| Language | What you use | Built by |+| -------- | ---------------------------------------------------- | --------------------------------------- |+| C++ | `imgui.h` + `imgui_impl_bui.h` | CMake target `bui_imgui` (`bui::imgui`) |+| C | `cimgui.h` + `cimgui_impl_bui.h` | CMake target `bui_cimgui` |+| Python | `import blenderui.imgui as imgui` | The `_buiimgui` extension, in the wheel |+| Rust | the `blenderui-imgui` crate (on crates.io) | Cargo |The C, Python and Rust bindings are generated from `imgui.h`. ImGui isidle-free on BUI: frames run only on input and while something animates.@@ -1317,23 +1314,23 @@ SVG recorder use it. Guide: [INTEGRATION.md](INTEGRATION.md).## 28. Where the docs live-| Guide | What's inside |-| --- | --- |-| [Website](https://bui.preetham.top) | Everything below, as tutorials, concepts and references, with screenshots in dark and light |-| [Getting started](docs/getting-started.md) | Building, environment variables, window hosts, GPU rendering, troubleshooting |-| [tkinter](docs/tkinter.md) | Running tkinter apps on BUI, behavior notes, limitations |-| [Qt syntax](docs/qt.md) | Classes, signals, layouts, painting, coverage |-| [Components](docs/components.md) | The `bui.components` reference |-| [Rust](docs/rust.md) | `rsx!`, hooks, HTML, CSS and Tailwind coverage, effects, animations, events, headless tests |-| [JavaScript and React](docs/javascript.md) | `@blender-ui/native`, `@blender-ui/react`, how changes cross to the UI thread, performance |-| [Dear ImGui](docs/imgui.md) | Dear ImGui on BUI from C++, C, Python and Rust; the Blender-widgets build; coverage |-| [C API](docs/c-api.md) | The C kit (`BUI_kit.h`) |-| [Integration](INTEGRATION.md) | Embedding BUI drawing in C, C++, Qt or PySide hosts |-| [Architecture](ARCHITECTURE.md) | Modules and what was taken from Blender |-| [Syntax coverage](SYNTAX_COVERAGE.md) | The Qt and tkinter surface, exactly |-| [macOS testing](docs/macos-testing.md) | How to try the experimental Cocoa host on a Mac |-| [Publishing](docs/publishing.md) | Releasing to PyPI and crates.io |-| [Changelog](CHANGELOG.md) | What changed |+| Guide | What's inside |+| ------------------------------------------ | ------------------------------------------------------------------------------------------- |+| [Website](https://bui.preetham.top) | Everything below, as tutorials, concepts and references, with screenshots in dark and light |+| [Getting started](docs/getting-started.md) | Building, environment variables, window hosts, GPU rendering, troubleshooting |+| [tkinter](docs/tkinter.md) | Running tkinter apps on BUI, behavior notes, limitations |+| [Qt syntax](docs/qt.md) | Classes, signals, layouts, painting, coverage |+| [Components](docs/components.md) | The `bui.components` reference |+| [Rust](docs/rust.md) | `rsx!`, hooks, HTML, CSS and Tailwind coverage, effects, animations, events, headless tests |+| [JavaScript and React](docs/javascript.md) | `@blender-ui/native`, `@blender-ui/react`, how changes cross to the UI thread, performance |+| [Dear ImGui](docs/imgui.md) | Dear ImGui on BUI from C++, C, Python and Rust; the Blender-widgets build; coverage |+| [C API](docs/c-api.md) | The C kit (`BUI_kit.h`) |+| [Integration](INTEGRATION.md) | Embedding BUI drawing in C, C++, Qt or PySide hosts |+| [Architecture](ARCHITECTURE.md) | Modules and what was taken from Blender |+| [Syntax coverage](SYNTAX_COVERAGE.md) | The Qt and tkinter surface, exactly |+| [macOS testing](docs/macos-testing.md) | How to try the experimental Cocoa host on a Mac |+| [Publishing](docs/publishing.md) | Releasing to PyPI and crates.io |+| [Changelog](CHANGELOG.md) | What changed |---@@ -1361,22 +1358,22 @@ so there the controls are styled divs.Median of 10 launches, from process start until the first frame is on screen,with Python 3.14 and Node 22:-| | Renderer | Start time | CPU used to start | Memory (idle) | Idle CPU per minute |-| --- | --- | ---: | ---: | ---: | ---: |-| Rust (HTML + CSS) | CPU | **38 ms** | **27 ms** | **13 MB** | **0 ms** |-| | GPU | 42 ms | 61 ms | 31 MB | 1.8 ms |-| JavaScript (React, Node.js) | CPU | 94 ms | 100 ms | 48 MB | 68 ms |-| | GPU | 99 ms | 131 ms | 60 MB | 71 ms |-| Blender components (Python) | CPU | 112 ms | 86 ms | 23 MB | 0 ms |-| | GPU | 116 ms | 125 ms | 32 MB | 1.7 ms |-| tkinter syntax (Python) | CPU | 139 ms | 112 ms | 25 MB | 0.2 ms |-| | GPU | 159 ms | 157 ms | 43 MB | 2.4 ms |-| Qt syntax (Python) | CPU | 156 ms | 123 ms | 27 MB | 0 ms |-| | GPU | 161 ms | 160 ms | 36 MB | 1.2 ms |-| **Same gpui code:** blenderui | CPU | **40 ms** | **27 ms** | **15 MB** | **0 ms** |-| blenderui | GPU | 43 ms | 60 ms | 31 MB | 2.1 ms |-| gpui | GPU | 231 ms | 226 ms | 29 MB | 743 ms |-| gpui-fast | GPU | 226 ms | 217 ms | 31 MB | 2.5 ms |+| | Renderer | Start time | CPU used to start | Memory (idle) | Idle CPU per minute |+| ----------------------------- | -------- | ---------: | ----------------: | ------------: | ------------------: |+| Rust (HTML + CSS) | CPU | **38 ms** | **27 ms** | **13 MB** | **0 ms** |+| | GPU | 42 ms | 61 ms | 31 MB | 1.8 ms |+| JavaScript (React, Node.js) | CPU | 94 ms | 100 ms | 48 MB | 68 ms |+| | GPU | 99 ms | 131 ms | 60 MB | 71 ms |+| Blender components (Python) | CPU | 112 ms | 86 ms | 23 MB | 0 ms |+| | GPU | 116 ms | 125 ms | 32 MB | 1.7 ms |+| tkinter syntax (Python) | CPU | 139 ms | 112 ms | 25 MB | 0.2 ms |+| | GPU | 159 ms | 157 ms | 43 MB | 2.4 ms |+| Qt syntax (Python) | CPU | 156 ms | 123 ms | 27 MB | 0 ms |+| | GPU | 161 ms | 160 ms | 36 MB | 1.2 ms |+| **Same gpui code:** blenderui | CPU | **40 ms** | **27 ms** | **15 MB** | **0 ms** |+| blenderui | GPU | 43 ms | 60 ms | 31 MB | 2.1 ms |+| gpui | GPU | 231 ms | 226 ms | 29 MB | 743 ms |+| gpui-fast | GPU | 226 ms | 217 ms | 31 MB | 2.5 ms |On the same code, blenderui shows its first frame about 5× sooner than gpui andgpui-fast, spends about 8× less CPU getting there, and on the CPU renderer uses@@ -1396,11 +1393,11 @@ times include starting the interpreter, and memory doesn't count GPU memory.Python and C, on the full component demo (520×900):-| Frame | Time |-| --- | --- |-| Complete frame (everything redrawn) | ~0.7 ms |+| Frame | Time |+| ----------------------------------------- | -------- |+| Complete frame (everything redrawn) | ~0.7 ms || Hover or number-scrub frame (damage only) | ~0.05 ms |-| Native window: input event → on screen | ~0.06 ms |+| Native window: input event → on screen | ~0.06 ms |Dear ImGui's demo window with every section open (27k triangles, 1280×800) is afull software redraw of about 5–8 ms.@@ -1409,24 +1406,24 @@ Rust, against Zed's [gpui](https://crates.io/crates/gpui) and the faster fork[gpui-fast](https://github.com/longbridge/gpui-fast). The scene is 3000animated cells, and all apps ran in the same session (GPU rows on Direct3D 11):-| | blenderui (GPU) | blenderui (CPU) | gpui-fast | gpui |-| --- | ---: | ---: | ---: | ---: |-| FPS | **59.9** | 57.6 | 31.5 | 19.9 |-| CPU per frame | **11.6 ms** | 22.0 ms | 31.9 ms + GPU | 50.5 ms + GPU |-| RAM | 40 MB | **30 MB** | 65 MB | 77 MB |-| First frame | **~5 ms** | **~5 ms** | ~200 ms | ~220 ms |-| Idle CPU | **0 %** | 0–0.9 % | 0–0.4 % | 0.9–1.4 % |+| | blenderui (GPU) | blenderui (CPU) | gpui-fast | gpui |+| ------------- | --------------: | --------------: | ------------: | ------------: |+| FPS | **59.9** | 57.6 | 31.5 | 19.9 |+| CPU per frame | **11.6 ms** | 22.0 ms | 31.9 ms + GPU | 50.5 ms + GPU |+| RAM | 40 MB | **30 MB** | 65 MB | 77 MB |+| First frame | **~5 ms** | **~5 ms** | ~200 ms | ~220 ms |+| Idle CPU | **0 %** | 0–0.9 % | 0–0.4 % | 0.9–1.4 % |<details><summary>Full results, the GPU renderer, and the method</summary>-| | blenderui (GPU) | blenderui (CPU) | gpui-fast | gpui |-| --- | ---: | ---: | ---: | ---: |-| FPS, 1000 animated cells | **60** | **60** | 49.2 | 36.4 |-| CPU per frame, 1000 / 100 cells | **4.7 / 1.2 ms** | 10.2 / 4.6 ms | 20.5 / 2.7 ms + GPU | 27.7 / 4.7 ms + GPU |-| Uncapped FPS, 100 / 1000 / 3000 cells | **1491 / 309 / 94** | 649 / 202 / 76 | - | - |-| RAM, 1000 / 100 cells | 35 / 28 MB | **24 / 21 MB** | 45 / 47 MB | 47 / 40 MB |-| GPU memory | 19–22 MB | **none** | 19–24 MB | 16–21 MB |+| | blenderui (GPU) | blenderui (CPU) | gpui-fast | gpui |+| ------------------------------------- | ------------------: | --------------: | ------------------: | ------------------: |+| FPS, 1000 animated cells | **60** | **60** | 49.2 | 36.4 |+| CPU per frame, 1000 / 100 cells | **4.7 / 1.2 ms** | 10.2 / 4.6 ms | 20.5 / 2.7 ms + GPU | 27.7 / 4.7 ms + GPU |+| Uncapped FPS, 100 / 1000 / 3000 cells | **1491 / 309 / 94** | 649 / 202 / 76 | - | - |+| RAM, 1000 / 100 cells | 35 / 28 MB | **24 / 21 MB** | 45 / 47 MB | 47 / 40 MB |+| GPU memory | 19–22 MB | **none** | 19–24 MB | 16–21 MB |The GPU renderer is off by default. Turn it on with`Application::new().gpu(true)`, `tk.Tk(gpu=True)`, `bui.set_gpu(True)` or@@ -1452,13 +1449,13 @@ gpui-fast's heavy-scene frame rate varies between sessions on this laptopits first frame is on screen. Each figure is the median of 12 launches after awarm-up launch (`node bench/startup.js`).-| | First frame | Launch to exit | RAM at first frame | What you ship |-| --- | ---: | ---: | ---: | ---: |-| **QuickJS executable** (`bui build`) | **68 ms** | **104 ms** | **19 MB** | **4.9 MB** |-| Bun executable (`bui build --bun`) | 79 ms | 147 ms | 35 MB | 114 MB |-| Bun (`bun app.js`) | 80 ms | 152 ms | 35 MB | Bun + your app |-| Node.js (`node app.js`) | 108 ms | 187 ms | 45 MB | Node + your app |-| Rust (for reference: the benchmark app) | 5 ms | ~92 ms | | 3.5 MB |+| | First frame | Launch to exit | RAM at first frame | What you ship |+| --------------------------------------- | ----------: | -------------: | -----------------: | --------------: |+| **QuickJS executable** (`bui build`) | **68 ms** | **104 ms** | **19 MB** | **4.9 MB** |+| Bun executable (`bui build --bun`) | 79 ms | 147 ms | 35 MB | 114 MB |+| Bun (`bun app.js`) | 80 ms | 152 ms | 35 MB | Bun + your app |+| Node.js (`node app.js`) | 108 ms | 187 ms | 45 MB | Node + your app |+| Rust (for reference: the benchmark app) | 5 ms | ~92 ms | | 3.5 MB |First frame is measured from the runtime's start. Launch to exit is wall timemeasured from outside, including process creation and teardown.@@ -1473,19 +1470,19 @@ counted with the cycle counter as for Rust.- **React with state** re-renders the grid every frame.- **React's production build** is used throughout.-| 3,000 cells | FPS | CPU per frame | RAM |-| --- | ---: | ---: | ---: |-| Rust | 59.6 | **12.0 ms** | **43 MB** |+| 3,000 cells | FPS | CPU per frame | RAM |+| --------------------------------------------------------- | -----------------: | --------------------: | ------------------: |+| Rust | 59.6 | **12.0 ms** | **43 MB** || QuickJS: plain JS / React with signals / React with state | 59.1 / 58.7 / 19.7 | 16.3 / 14.9 / 51.0 ms | **56 / 61 / 67 MB** |-| Bun 1.4: plain JS / React with signals / React with state | 58.8 / 58.4 / 55.8 | 13.1 / 13.3 / 20.8 ms | 80 / 85 / 118 MB |-| Node 22: plain JS / React with signals / React with state | 55.8 / 56.7 / 54.8 | 14.4 / 14.0 / 18.9 ms | 88 / 93 / 121 MB |+| Bun 1.4: plain JS / React with signals / React with state | 58.8 / 58.4 / 55.8 | 13.1 / 13.3 / 20.8 ms | 80 / 85 / 118 MB |+| Node 22: plain JS / React with signals / React with state | 55.8 / 56.7 / 54.8 | 14.4 / 14.0 / 18.9 ms | 88 / 93 / 121 MB |-| 1,000 cells | FPS | CPU per frame | RAM |-| --- | ---: | ---: | ---: |-| Rust | 60 | **4.8 ms** | **32 MB** |+| 1,000 cells | FPS | CPU per frame | RAM |+| --------------------------------------------------------- | -------------: | ------------------: | ------------------: |+| Rust | 60 | **4.8 ms** | **32 MB** || QuickJS: plain JS / React with signals / React with state | 60 / 60 / 56.8 | 6.0 / 5.6 / 17.8 ms | **38 / 40 / 43 MB** |-| Bun: plain JS / React with signals / React with state | 60 / 60 / 60 | 5.2 / 5.2 / 7.5 ms | 58 / 63 / 81 MB |-| Node: plain JS / React with signals / React with state | 60 / 60 / 60 | 5.6 / 5.6 / 6.9 ms | 68 / 71 / 97 MB |+| Bun: plain JS / React with signals / React with state | 60 / 60 / 60 | 5.2 / 5.2 / 7.5 ms | 58 / 63 / 81 MB |+| Node: plain JS / React with signals / React with state | 60 / 60 / 60 | 5.6 / 5.6 / 6.9 ms | 68 / 71 / 97 MB |What this means:@@ -1522,6 +1519,7 @@ py -3 bench/run.py 10 20 # launches per app, seconds of idle measurement**Frame cost: 100, 1,000 and 3,000 animated cells, against gpui andgpui-fast** (`bindings/rust/bench/`, Windows). A 1000×800 window filled with Nrounded, numbered cells, in three modes:+- **anim:** every cell changes every frame, the worst case.- **one:** one cell changes per frame, like a hover or a ticking value.- **idle:** nothing changes.@@ -1572,22 +1570,22 @@ py bindings/python/bench/tk_canvas_bench.py 3000 one # move one## 34. Platforms-| | Windows | Linux | macOS |-| --- | --- | --- | --- |-| Window | Native (Win32) | Native (X11; Wayland through XWayland) | Native (Cocoa), experimental |-| Python (`pip install`) | Works: wheels | Works: wheels (native X11 host) | Works: wheels |-| Rust (`cargo add blenderui`) | Works | Works | Experimental |-| JavaScript / React | Works: prebuilt on npm | Works: build the addon from source (`npm run build`); native X11 windows | Headless (see below) |-| C, C++, Dear ImGui | Works | Works | Experimental |-| Renderer | CPU raster, or GPU (Direct3D 11) | CPU raster, or GPU (OpenGL 3.3) | CPU raster |-| HiDPI | Per-monitor DPI | `Xft.dpi` | Retina (backing scale) |+| | Windows | Linux | macOS |+| ---------------------------- | -------------------------------- | ------------------------------------------------------------------------ | ---------------------------- |+| Window | Native (Win32) | Native (X11; Wayland through XWayland) | Native (Cocoa), experimental |+| Python (`pip install`) | Works: wheels | Works: wheels (native X11 host) | Works: wheels |+| Rust (`cargo add blenderui`) | Works | Works | Experimental |+| JavaScript / React | Works: prebuilt on npm | Works: build the addon from source (`npm run build`); native X11 windows | Headless (see below) |+| C, C++, Dear ImGui | Works | Works | Experimental |+| Renderer | CPU raster, or GPU (Direct3D 11) | CPU raster, or GPU (OpenGL 3.3) | CPU raster |+| HiDPI | Per-monitor DPI | `Xft.dpi` | Retina (backing scale) |**Works** means it works and is tested. **Experimental** means it's written-but not yet tried by hand on real hardware (macOS has only been checked by CI).+but has had little hands-on testing on real hardware (macOS: one Apple Silicon Mac so far, plus CI).**macOS.** The macOS window host is new: it's a port of Blender's Cocoa code-(GHOST). So far it has only been checked by CI, not by a person clicking around-on a real Mac. If you have one, please try it and+(GHOST). So far it has been checked by CI and tried by hand on one Apple Silicon+Mac by [Krish Kalaria](https://github.com/krishkalaria12), who reported issue #3 and fixed it in pull request #4. If you have another one, please try it andtell us what happens: [docs/macos-testing.md](docs/macos-testing.md). Pythoncan still use the stdlib Tk window there (`BUI_HOST=tk`; this needs Python's`tkinter`, for example from python.org or `brew install python-tk`). Node runs@@ -1603,12 +1601,12 @@ and on an NVIDIA GPU.**Packages:**-| Package | Platforms | Notes |-| --- | --- | --- |-| `blenderui` on PyPI | Windows x86_64, Linux x86_64 (manylinux), macOS arm64 and x86_64 | CPython 3.11 to 3.14. No musllinux or 32-bit wheels. |-| `blenderui` on crates.io | Any platform with CMake and a C compiler | Rust 1.88+. `blenderui-imgui` isn't on crates.io yet: use it as a git dependency. |-| `@blender-ui/native`, `@blender-ui/react` on npm | Windows x64 | Node.js 18+ or Bun. Elsewhere, build the addon from source. |-| C and C++ (CMake) | Windows, Linux, macOS | CMake 3.20+, a C11 and C++20 compiler. |+| Package | Platforms | Notes |+| ------------------------------------------------ | ---------------------------------------------------------------- | --------------------------------------------------------------------------------- |+| `blenderui` on PyPI | Windows x86_64, Linux x86_64 (manylinux), macOS arm64 and x86_64 | CPython 3.11 to 3.14. No musllinux or 32-bit wheels. |+| `blenderui` on crates.io | Any platform with CMake and a C compiler | Rust 1.88+. `blenderui-imgui` (Dear ImGui) is on crates.io too. |+| `@blender-ui/native`, `@blender-ui/react` on npm | Windows x64 | Node.js 18+ or Bun. Elsewhere, build the addon from source. |+| C and C++ (CMake) | Windows, Linux, macOS | CMake 3.20+, a C11 and C++20 compiler. |## 35. Environment variables@@ -1617,26 +1615,26 @@ On/off variables look at the first character: `1`, `y`, `Y`, `t` or `T` is on.Where a variable and an app-wide API call set the same thing, the variablewins.-| Variable | What it does |-| --- | --- |-| `BUI_GPU` | `1` draws native windows on the GPU (Direct3D 11 / OpenGL 3.3). Overrides `bui.set_gpu()`, `Application::gpu()`, `BUI_gpu_set_default()`. `0` turns those defaults off; a window that asks for the GPU itself still gets it. |-| `BUI_SLUG` | GPU text: `1` from glyph outlines (Slug, the default), `0` from a per-glyph atlas. |-| `BUI_GPU_DEBUG` | `1` prints why the GPU renderer couldn't start. |-| `BUI_GPU_WARP` | `1` (Windows) creates the Direct3D 11 device on WARP, the software rasterizer. Handy in VMs and CI. |-| `BUI_GPU_EGL` | `default` or `surfaceless` (Linux): the EGL platform for offscreen GPU rendering. |-| `BUI_RASTER_THREADS` | 1 to 8 (Windows): the most threads the software raster uses for big canvases. |-| `BUI_PROFILE` | Prints frame times every 60 frames. **Any** value turns it on, even `0`. |-| `BUI_THEME` | `dark` (default) or `light`: Blender's theme, when the app doesn't set one. |-| `BUI_UI_SCALE` | A fixed UI scale (`1.25`, `1.5` ...) instead of the display's. Clamped to 0.5–4. |-| `BUI_HOST` | `tk` (Python): use the stdlib Tk window even where a native host exists. |-| `BUI_MAC_TK` | `0` (Python on macOS): skip starting a hidden Tk root before the first native window. |-| `BUI_FONT`, `BUI_FONT_DIR` | A font file to replace Inter, and an extra font folder to search first. |-| `BUI_FILEDIALOG` | `native` (or `system`, `tk`), Python: file dialogs use the OS's instead of Blender's File Browser. |-| `BUI_BOOKMARKS` | The File Browser's bookmarks file. |-| `BUIPY_BUILD_DIR` | Running Python from a source checkout: the folder holding the built `buipy` extension. |-| `BUI_NODE_ADDON` | `@blender-ui/native`: load this `.node` addon instead of the bundled one. |-| `BUI_HEADLESS` | `1`: `bui build` apps and `bui run` render off-screen (same as `--headless`). |-| `BUI_SOURCE_DIR`, `BUI_TEXT_GDI` | Build time, Rust: build the C library from this checkout; use GDI text. |+| Variable | What it does |+| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `BUI_GPU` | `1` draws native windows on the GPU (Direct3D 11 / OpenGL 3.3). Overrides `bui.set_gpu()`, `Application::gpu()`, `BUI_gpu_set_default()`. `0` turns those defaults off; a window that asks for the GPU itself still gets it. |+| `BUI_SLUG` | GPU text: `1` from glyph outlines (Slug, the default), `0` from a per-glyph atlas. |+| `BUI_GPU_DEBUG` | `1` prints why the GPU renderer couldn't start. |+| `BUI_GPU_WARP` | `1` (Windows) creates the Direct3D 11 device on WARP, the software rasterizer. Handy in VMs and CI. |+| `BUI_GPU_EGL` | `default` or `surfaceless` (Linux): the EGL platform for offscreen GPU rendering. |+| `BUI_RASTER_THREADS` | 1 to 8 (Windows): the most threads the software raster uses for big canvases. |+| `BUI_PROFILE` | Prints frame times every 60 frames. **Any** value turns it on, even `0`. |+| `BUI_THEME` | `dark` (default) or `light`: Blender's theme, when the app doesn't set one. |+| `BUI_UI_SCALE` | A fixed UI scale (`1.25`, `1.5` ...) instead of the display's. Clamped to 0.5–4. |+| `BUI_HOST` | `tk` (Python): use the stdlib Tk window even where a native host exists. |+| `BUI_MAC_TK` | `0` (Python on macOS): skip starting a hidden Tk root before the first native window. |+| `BUI_FONT`, `BUI_FONT_DIR` | A font file to replace Inter, and an extra font folder to search first. |+| `BUI_FILEDIALOG` | `native` (or `system`, `tk`), Python: file dialogs use the OS's instead of Blender's File Browser. |+| `BUI_BOOKMARKS` | The File Browser's bookmarks file. |+| `BUIPY_BUILD_DIR` | Running Python from a source checkout: the folder holding the built `buipy` extension. |+| `BUI_NODE_ADDON` | `@blender-ui/native`: load this `.node` addon instead of the bundled one. |+| `BUI_HEADLESS` | `1`: `bui build` apps and `bui run` render off-screen (same as `--headless`). |+| `BUI_SOURCE_DIR`, `BUI_TEXT_GDI` | Build time, Rust: build the C library from this checkout; use GDI text. |Every variable, with defaults and where it's read:[Environment variables](https://bui.preetham.top/docs/reference/environment-variables/)@@ -1658,19 +1656,19 @@ python examples/components_demo.pycd bindings/rust && cargo test # Rust: CSS, Tailwind, rsx!, hooks, effects, headless windows```-| Option | Default | What it does |-| --- | --- | --- |-| `BUI_BUILD_TESTS` | `ON` | C test programs and the `ctest` suites |-| `BUI_BUILD_EXAMPLES` | `OFF` | The C examples (`bui_kit_hello`, `bui_svg_demo`, the site screenshot programs) |-| `BUI_BUILD_PYTHON_BINDINGS` | `ON` | The `buipy` extension (and the ImGui extension); skipped without Python's dev files |-| `BUI_BUILD_IMGUI` | `ON` with a C++ compiler | Dear ImGui on BUI, its C API, demo and test |-| `BUI_IMGUI_BLENDER_WIDGETS` | `OFF` | Dear ImGui with Blender's widgets |-| `BUI_BUILD_QT_BACKEND` | `OFF` | The C++ Qt/QPainter render-sink backend (needs Qt 5 or 6) |-| `BUI_BUILD_UI` | `OFF` | Also compile Blender's original `ui/` sources (reference only) |-| `BUI_TEXT_FREETYPE` | `ON` | Render glyphs with FreeType like Blender's BLF; `OFF` uses stb_truetype |-| `BUI_TEXT_GDI` | `OFF` | Windows' GDI text and system fonts |-| `BUI_SLUG` | `ON` | Slug as the GPU's default text method (switchable at run time) |-| `BUI_WARNINGS_AS_ERRORS` | `OFF` | GCC and Clang only: when `OFF` the build adds `-Wno-error`; it never adds `-Werror` or `/WX` itself |+| Option | Default | What it does |+| --------------------------- | ------------------------ | --------------------------------------------------------------------------------------------------- |+| `BUI_BUILD_TESTS` | `ON` | C test programs and the `ctest` suites |+| `BUI_BUILD_EXAMPLES` | `OFF` | The C examples (`bui_kit_hello`, `bui_svg_demo`, the site screenshot programs) |+| `BUI_BUILD_PYTHON_BINDINGS` | `ON` | The `buipy` extension (and the ImGui extension); skipped without Python's dev files |+| `BUI_BUILD_IMGUI` | `ON` with a C++ compiler | Dear ImGui on BUI, its C API, demo and test |+| `BUI_IMGUI_BLENDER_WIDGETS` | `OFF` | Dear ImGui with Blender's widgets |+| `BUI_BUILD_QT_BACKEND` | `OFF` | The C++ Qt/QPainter render-sink backend (needs Qt 5 or 6) |+| `BUI_BUILD_UI` | `OFF` | Also compile Blender's original `ui/` sources (reference only) |+| `BUI_TEXT_FREETYPE` | `ON` | Render glyphs with FreeType like Blender's BLF; `OFF` uses stb_truetype |+| `BUI_TEXT_GDI` | `OFF` | Windows' GDI text and system fonts |+| `BUI_SLUG` | `ON` | Slug as the GPU's default text method (switchable at run time) |+| `BUI_WARNINGS_AS_ERRORS` | `OFF` | GCC and Clang only: when `OFF` the build adds `-Wno-error`; it never adds `-Werror` or `/WX` itself |Rebuild the docs screenshots with `python tools/gen_doc_images.py` (and thewebsite's dark and light shots with `--site`). More:@@ -1678,17 +1676,17 @@ website's dark and light shots with `--site`). More:## 37. Coverage-| API | Coverage | Status |-| --- | --- | --- |-| tkinter and ttk | **7,846 of 7,846** public names; nine real programs behave identically | Complete |-| Qt syntax | **About 220 of 920** public method names on 25 core widget classes (~24%) | Partial |-| Blender components (Python) | **45** components (10 of them also in Rust and JavaScript) | Complete |-| HTML elements (Rust, JavaScript) | **113 of 113** | Complete |-| CSS properties (Rust, JavaScript) | **261 of 745** W3C properties render, **129** more parse, **355** not recognized (mostly drafts, speech, paged media and SVG) | Partial |-| CSS 2.1 screen properties | **90 of 90** | Complete |-| Flexbox / Grid | **12 of 12** / **23 of 23** | Complete |-| Dear ImGui, C | **399 of 399** functions | Complete |-| Dear ImGui, Python and safe Rust | **366 of 399** functions (Rust FFI: 385) | Partial |+| API | Coverage | Status |+| --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | -------- |+| tkinter and ttk | **7,846 of 7,846** public names; nine real programs behave identically | Complete |+| Qt syntax | **About 220 of 920** public method names on 25 core widget classes (~24%) | Partial |+| Blender components (Python) | **45** components (10 of them also in Rust and JavaScript) | Complete |+| HTML elements (Rust, JavaScript) | **113 of 113** | Complete |+| CSS properties (Rust, JavaScript) | **261 of 745** W3C properties render, **129** more parse, **355** not recognized (mostly drafts, speech, paged media and SVG) | Partial |+| CSS 2.1 screen properties | **90 of 90** | Complete |+| Flexbox / Grid | **12 of 12** / **23 of 23** | Complete |+| Dear ImGui, C | **399 of 399** functions | Complete |+| Dear ImGui, Python and safe Rust | **366 of 399** functions (Rust FFI: 385) | Partial |How each was counted: [Coverage](https://bui.preetham.top/docs/reference/coverage/),[SYNTAX_COVERAGE.md](SYNTAX_COVERAGE.md), [docs/rust.md](docs/rust.md#coverage),@@ -1696,44 +1694,44 @@ How each was counted: [Coverage](https://bui.preetham.top/docs/reference/coverag## 38. Repository layout-| Path | Contents |-| --- | --- |-| `kit/` | The C runtime: nodes, input, widget drawing (the `interface_widgets.cc` port), menus, geometry managers, canvas, the File Browser, themes (`kit_theme_presets.c`), the Win32, X11 and Cocoa window hosts; `kit/intern/blender/` holds Blender files copied in (string search, text-edit undo, float precision). API: `kit/include/BUI_kit.h` |-| `gpu/` | Software raster, GPU renderer on Direct3D 11 (`gpu_d3d11.c`, `shaders/`) and OpenGL 3.3 (`gpu_gl.c`), textured meshes, Slug text, text engine (FreeType or stb_truetype + embedded Inter, or GDI) |-| `core/`, `types/` | Blender's `blenlib` subset (including `string_search.cc` and `expr_pylike_eval.cc`) and data types |-| `ui/`, `compat/` | Blender's original interface sources, kept for reference (not compiled by default; `kit/` re-ports them in C), and the seams replacing Blender's application APIs |-| `api/` | Stable C ABI for render-sink hosts |-| `bindings/python/` | The `buipy` extension and the `bui` / `blenderui` packages (tkinter, Qt, components, ImGui) |-| `bindings/rust/` | `blenderui`, `blenderui-sys`, `blenderui-macros`, `blenderui-tailwind`, `blenderui-imgui`, `blenderui-jsview`, `blenderui-node`, `blenderui-qjs`, and the benchmark |-| `bindings/node/`, `bindings/react/` | `@blender-ui/native` and `@blender-ui/react` |-| `bindings/imgui/` | Dear ImGui (vendored), the BUI backend, Blender style, the C API and its generator, the Blender-widgets build |-| `backends/qt/` | C++ Qt/QPainter render-sink backend |-| `bench/` | The start time and battery benchmark |-| `examples/`, `tools/` | Demos, the website's screenshot programs (`examples/site/`), the icon and theme generators, the docs screenshot generator |-| `website/` | The documentation website, [bui.preetham.top](https://bui.preetham.top) |+| Path | Contents |+| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `kit/` | The C runtime: nodes, input, widget drawing (the `interface_widgets.cc` port), menus, geometry managers, canvas, the File Browser, themes (`kit_theme_presets.c`), the Win32, X11 and Cocoa window hosts; `kit/intern/blender/` holds Blender files copied in (string search, text-edit undo, float precision). API: `kit/include/BUI_kit.h` |+| `gpu/` | Software raster, GPU renderer on Direct3D 11 (`gpu_d3d11.c`, `shaders/`) and OpenGL 3.3 (`gpu_gl.c`), textured meshes, Slug text, text engine (FreeType or stb_truetype + embedded Inter, or GDI) |+| `core/`, `types/` | Blender's `blenlib` subset (including `string_search.cc` and `expr_pylike_eval.cc`) and data types |+| `ui/`, `compat/` | Blender's original interface sources, kept for reference (not compiled by default; `kit/` re-ports them in C), and the seams replacing Blender's application APIs |+| `api/` | Stable C ABI for render-sink hosts |+| `bindings/python/` | The `buipy` extension and the `bui` / `blenderui` packages (tkinter, Qt, components, ImGui) |+| `bindings/rust/` | `blenderui`, `blenderui-sys`, `blenderui-macros`, `blenderui-tailwind`, `blenderui-imgui`, `blenderui-jsview`, `blenderui-node`, `blenderui-qjs`, and the benchmark |+| `bindings/node/`, `bindings/react/` | `@blender-ui/native` and `@blender-ui/react` |+| `bindings/imgui/` | Dear ImGui (vendored), the BUI backend, Blender style, the C API and its generator, the Blender-widgets build |+| `backends/qt/` | C++ Qt/QPainter render-sink backend |+| `bench/` | The start time and battery benchmark |+| `examples/`, `tools/` | Demos, the website's screenshot programs (`examples/site/`), the icon and theme generators, the docs screenshot generator |+| `website/` | The documentation website, [bui.preetham.top](https://bui.preetham.top) |## 39. Examples-| File | Shows |-| --- | --- |-| [`examples/tk_unchanged_app.py`](examples/tk_unchanged_app.py) | A plain tkinter app: menus, notebook, form, table, text, canvas |-| [`examples/components_demo.py`](examples/components_demo.py) | Every Blender component in a properties-editor layout |-| [`examples/qt_syntax_demo.py`](examples/qt_syntax_demo.py) | Qt syntax: layouts, form widgets, signals |-| [`examples/tk_syntax_demo.py`](examples/tk_syntax_demo.py) | tkinter syntax laid out like a Blender properties editor |-| [`examples/kit_hello.c`](examples/kit_hello.c) | The C kit: a slider and a button in a native window |-| [`examples/imgui_demo.cpp`](examples/imgui_demo.cpp) | Dear ImGui's demo window on BUI, from C++ |-| [`examples/imgui_demo_c.c`](examples/imgui_demo_c.c) | The same from C (`cimgui.h`) |-| [`examples/imgui_blender_compare.cpp`](examples/imgui_blender_compare.cpp) | ImGui widgets next to BUI's native Blender widgets |-| [`examples/site/`](examples/site/) | The website's screenshot programs: a Render Properties editor and a node editor (Python components), tkinter and ttk dialogs, a Qt material editor, an ImGui inspector (C++ and Python), a C modifier stack, and a JavaScript task list (DOM and React) |-| [`hello.rs`](bindings/rust/blenderui/examples/hello.rs) | Rust: a component, hooks, Tailwind attributes and a Blender slider |-| [`showcase.rs`](bindings/rust/blenderui/examples/showcase.rs) | Rust: HTML, a stylesheet, flex/grid, tables, Blender form widgets |-| [`forms.rs`](bindings/rust/blenderui/examples/forms.rs) | Rust: form controls as plain HTML, inside `styled`, and as Blender components |-| [`site_dashboard.rs`](bindings/rust/blenderui/examples/site_dashboard.rs), [`site_dashboard_builder.rs`](bindings/rust/blenderui/examples/site_dashboard_builder.rs) | Rust: the same dashboard in `rsx!` and in gpui builders |-| [`site_effects.rs`](bindings/rust/blenderui/examples/site_effects.rs), [`site_grid.rs`](bindings/rust/blenderui/examples/site_grid.rs), [`site_animation.rs`](bindings/rust/blenderui/examples/site_animation.rs) | Rust: CSS effects, grid and `@keyframes` |-| [`site_plain_html.rs`](bindings/rust/blenderui/examples/site_plain_html.rs), [`site_styled.rs`](bindings/rust/blenderui/examples/site_styled.rs), [`site_components.rs`](bindings/rust/blenderui/examples/site_components.rs) | Rust: the three looks |-| [`blenderui-imgui` demo](bindings/rust/blenderui-imgui/examples/demo.rs) | Dear ImGui from Rust (`cargo run -p blenderui-imgui --example demo`) |-| [`bindings/node/examples/counter.js`](bindings/node/examples/counter.js) | JavaScript: the DOM-like API |-| [`bindings/react/examples/counter.jsx`](bindings/react/examples/counter.jsx) | React in JSX (`bun examples/counter.jsx`) |+| File | Shows |+| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| [`examples/tk_unchanged_app.py`](examples/tk_unchanged_app.py) | A plain tkinter app: menus, notebook, form, table, text, canvas |+| [`examples/components_demo.py`](examples/components_demo.py) | Every Blender component in a properties-editor layout |+| [`examples/qt_syntax_demo.py`](examples/qt_syntax_demo.py) | Qt syntax: layouts, form widgets, signals |+| [`examples/tk_syntax_demo.py`](examples/tk_syntax_demo.py) | tkinter syntax laid out like a Blender properties editor |+| [`examples/kit_hello.c`](examples/kit_hello.c) | The C kit: a slider and a button in a native window |+| [`examples/imgui_demo.cpp`](examples/imgui_demo.cpp) | Dear ImGui's demo window on BUI, from C++ |+| [`examples/imgui_demo_c.c`](examples/imgui_demo_c.c) | The same from C (`cimgui.h`) |+| [`examples/imgui_blender_compare.cpp`](examples/imgui_blender_compare.cpp) | ImGui widgets next to BUI's native Blender widgets |+| [`examples/site/`](examples/site/) | The website's screenshot programs: a Render Properties editor and a node editor (Python components), tkinter and ttk dialogs, a Qt material editor, an ImGui inspector (C++ and Python), a C modifier stack, and a JavaScript task list (DOM and React) |+| [`hello.rs`](bindings/rust/blenderui/examples/hello.rs) | Rust: a component, hooks, Tailwind attributes and a Blender slider |+| [`showcase.rs`](bindings/rust/blenderui/examples/showcase.rs) | Rust: HTML, a stylesheet, flex/grid, tables, Blender form widgets |+| [`forms.rs`](bindings/rust/blenderui/examples/forms.rs) | Rust: form controls as plain HTML, inside `styled`, and as Blender components |+| [`site_dashboard.rs`](bindings/rust/blenderui/examples/site_dashboard.rs), [`site_dashboard_builder.rs`](bindings/rust/blenderui/examples/site_dashboard_builder.rs) | Rust: the same dashboard in `rsx!` and in gpui builders |+| [`site_effects.rs`](bindings/rust/blenderui/examples/site_effects.rs), [`site_grid.rs`](bindings/rust/blenderui/examples/site_grid.rs), [`site_animation.rs`](bindings/rust/blenderui/examples/site_animation.rs) | Rust: CSS effects, grid and `@keyframes` |+| [`site_plain_html.rs`](bindings/rust/blenderui/examples/site_plain_html.rs), [`site_styled.rs`](bindings/rust/blenderui/examples/site_styled.rs), [`site_components.rs`](bindings/rust/blenderui/examples/site_components.rs) | Rust: the three looks |+| [`blenderui-imgui` demo](bindings/rust/blenderui-imgui/examples/demo.rs) | Dear ImGui from Rust (`cargo run -p blenderui-imgui --example demo`) |+| [`bindings/node/examples/counter.js`](bindings/node/examples/counter.js) | JavaScript: the DOM-like API |+| [`bindings/react/examples/counter.jsx`](bindings/react/examples/counter.jsx) | React in JSX (`bun examples/counter.jsx`) |---@@ -1743,44 +1741,43 @@ How each was counted: [Coverage](https://bui.preetham.top/docs/reference/coverag**Done**-| Area | What works |-| --- | --- |-| C runtime (`kit/`) | Nodes, Tk-style geometry managers, input, Blender widget drawing, damage rendering, undo, animation, text area, canvas, scroll views, Blender's string search, expression evaluator, text-edit undo and float precision, Blender's Dark and Light themes |-| Native windows | Windows (Win32) and Linux (X11; Wayland through XWayland), in C: DPI-aware, frame-paced animation, clipboard, cursors, window-manager features |-| tkinter syntax | **Complete**: every public tkinter and ttk name (7,846 of 7,846) |-| Components | 45 Blender components, including the color ramp, curve and node editors |-| Rust | HTML (113/113 elements), Flexbox 12/12, Grid 23/23, CSS 2.1 90/90, math functions, `var()`, CSS Color 4/5, Selectors 4, `@layer` / `@media` / `@supports` / `@scope` / `@container` / `@font-face` / `@property`, `@keyframes` animations and transitions, filters / blend modes / masks / `clip-path` / 2D transforms / `border-image`, bidi text, background images, `object-fit`, Tailwind v4, `rsx!`, `#[component]` with optional props and `key`, hooks, Blender components, browser-look form controls, headless testing |-| Dear ImGui | The real Dear ImGui 1.93 on BUI (CPU, Direct3D 11, OpenGL), Blender theme and Inter; C++ / C (399/399 functions) / Python and Rust (366–385/399); the Blender-widgets build |-| Rendering | Software raster (parallel, damage-tracked), GPU renderer (Direct3D 11 on Windows, OpenGL 3.3 on Linux), textured meshes, portable text engine (FreeType, as in Blender) |-| JavaScript / React | `@blender-ui/native`: a DOM-like API over napi-rs, with its own UI thread, only changes crossing the boundary, vsync-paced `requestAnimationFrame` and signals. `@blender-ui/react`: a React 19.3 renderer whose hooks (`useState`, `useMemo`, `useEffect` ...) hold signals that update nodes without re-renders. Both on Node.js and Bun, with headless testing. `bui build` makes standalone executables: about 5 MB with the embedded QuickJS runtime, or Bun's with `--bun` ([guide](docs/javascript.md)) |-| Packaging | [`blenderui` on PyPI](https://pypi.org/project/blenderui/), with a CI workflow for wheels on all platforms (Linux wheels with the native X11 host); [`blenderui` on crates.io](https://crates.io/crates/blenderui); [`@blender-ui/react`](https://www.npmjs.com/package/@blender-ui/react) and [`@blender-ui/native`](https://www.npmjs.com/package/@blender-ui/native) on npm |-| Docs | The website, [bui.preetham.top](https://bui.preetham.top) |+| Area | What works |+| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| C runtime (`kit/`) | Nodes, Tk-style geometry managers, input, Blender widget drawing, damage rendering, undo, animation, text area, canvas, scroll views, Blender's string search, expression evaluator, text-edit undo and float precision, Blender's Dark and Light themes |+| Native windows | Windows (Win32) and Linux (X11; Wayland through XWayland), in C: DPI-aware, frame-paced animation, clipboard, cursors, window-manager features |+| tkinter syntax | **Complete**: every public tkinter and ttk name (7,846 of 7,846) |+| Components | 45 Blender components, including the color ramp, curve and node editors |+| Rust | HTML (113/113 elements), Flexbox 12/12, Grid 23/23, CSS 2.1 90/90, math functions, `var()`, CSS Color 4/5, Selectors 4, `@layer` / `@media` / `@supports` / `@scope` / `@container` / `@font-face` / `@property`, `@keyframes` animations and transitions, filters / blend modes / masks / `clip-path` / 2D transforms / `border-image`, bidi text, background images, `object-fit`, Tailwind v4, `rsx!`, `#[component]` with optional props and `key`, hooks, Blender components, browser-look form controls, headless testing |+| Dear ImGui | The real Dear ImGui 1.93 on BUI (CPU, Direct3D 11, OpenGL), Blender theme and Inter; C++ / C (399/399 functions) / Python and Rust (366–385/399); the Blender-widgets build |+| Rendering | Software raster (parallel, damage-tracked), GPU renderer (Direct3D 11 on Windows, OpenGL 3.3 on Linux), textured meshes, portable text engine (FreeType, as in Blender) |+| JavaScript / React | `@blender-ui/native`: a DOM-like API over napi-rs, with its own UI thread, only changes crossing the boundary, vsync-paced `requestAnimationFrame` and signals. `@blender-ui/react`: a React 19.3 renderer whose hooks (`useState`, `useMemo`, `useEffect` ...) hold signals that update nodes without re-renders. Both on Node.js and Bun, with headless testing. `bui build` makes standalone executables: about 5 MB with the embedded QuickJS runtime, or Bun's with `--bun` ([guide](docs/javascript.md)) |+| Packaging | [`blenderui` on PyPI](https://pypi.org/project/blenderui/), with a CI workflow for wheels on all platforms (Linux wheels with the native X11 host); [`blenderui` on crates.io](https://crates.io/crates/blenderui); [`@blender-ui/react`](https://www.npmjs.com/package/@blender-ui/react) and [`@blender-ui/native`](https://www.npmjs.com/package/@blender-ui/native) on npm |+| Docs | The website, [bui.preetham.top](https://bui.preetham.top) |**Partial or in progress**-| Area | What's missing |-| --- | --- |-| Qt syntax (~24%) | Model/view classes, docks, toolbars, splitters, Qt stylesheets ([details](docs/qt.md#coverage)) |-| CSS (261 of 745 W3C properties render, 129 more parse) | 3D transforms, OpenType font features, multi-column layout; hit testing ignores 2D transforms. Most of the remaining W3C list is drafts, speech, print and SVG ([breakdown](docs/rust.md#coverage)) |-| Text | No text wrapping around floats; right-to-left text is reordered (bidi) but not shaped (Arabic joining); no OpenType features; no per-glyph font fallback yet (characters missing from the font show as boxes); no IME |-| Rust components | No async resources (`use_resource`); no generic components |-| Dear ImGui | Python and safe Rust skip the `va_list`, `void*` and C-callback functions (reachable from C and the Rust FFI); with Blender widgets, window title bars, tooltips, plain popups, tables and the color picker keep ImGui's drawing |-| JavaScript / React packages | npm packages are prebuilt for Windows x64 only (on Linux, build the addon from source); events reach JavaScript after BUI handled them (no native `preventDefault`), and `event.target` is the deepest _listening_ element |-| macOS | **Experimental.** The native Cocoa window host is written and checked by CI, but not yet tried by hand on a Mac ([how to help](docs/macos-testing.md)); JavaScript is headless there (Node's UI thread isn't the main thread); no GPU renderer yet |-| crates.io | `blenderui` is published; `blenderui-imgui` isn't yet, so use it as a git dependency |-| Themes | Dark and Light work; loading other Blender theme files doesn't yet |+| Area | What's missing |+| ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Qt syntax (~24%) | Model/view classes, docks, toolbars, splitters, Qt stylesheets ([details](docs/qt.md#coverage)) |+| CSS (261 of 745 W3C properties render, 129 more parse) | 3D transforms, OpenType font features, multi-column layout; hit testing ignores 2D transforms. Most of the remaining W3C list is drafts, speech, print and SVG ([breakdown](docs/rust.md#coverage)) |+| Text | No text wrapping around floats; right-to-left text is reordered (bidi) but not shaped (Arabic joining); no OpenType features; no per-glyph font fallback yet (characters missing from the font show as boxes); no IME |+| Rust components | No async resources (`use_resource`); no generic components |+| Dear ImGui | Python and safe Rust skip the `va_list`, `void*` and C-callback functions (reachable from C and the Rust FFI); with Blender widgets, window title bars, tooltips, plain popups, tables and the color picker keep ImGui's drawing |+| JavaScript / React packages | npm packages are prebuilt for Windows x64 only (on Linux, build the addon from source); events reach JavaScript after BUI handled them (no native `preventDefault`), and `event.target` is the deepest _listening_ element |+| macOS | **Experimental.** The native Cocoa window host is written, checked by CI and tried by hand on one Apple Silicon Mac ([how to help](docs/macos-testing.md)); JavaScript is headless there (Node's UI thread isn't the main thread); no GPU renderer yet |+| Themes | Dark and Light work; loading other Blender theme files doesn't yet |**Planned (coming soon)**-| Target | Plan |-| --- | --- |-| **WebAssembly** | The kit in the browser: the raster blits to `<canvas>`, DOM events feed the kit; `@blender-ui/react` and the DOM-like API on top, unchanged |-| **egui** | BUI panels inside egui, plus a Blender-styled theme |-| **More from Blender's source** | Per-glyph font fallback (BLF), IME, search-as-you-type popups, units in number fields, widget drag and drop |-| **macOS GPU and JavaScript windows** | The GPU renderer on Metal (or the OpenGL backend), and Node windows on the main thread |-| **More GPU backends** | Vulkan / WebGPU drawing the same instance stream as Direct3D 11 and OpenGL |-| **Qt parity** | Measure against PySide6, run the same programs on Qt and BUI, fill in the missing classes, then `install()` so `import PySide6` programs run unchanged |-| **More languages** | MyGo, C#, Go, Zig, Swift, Kotlin and Lua over the same C header; Godot, Unity and Bevy; Flutter |+| Target | Plan |+| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ |+| **WebAssembly** | The kit in the browser: the raster blits to `<canvas>`, DOM events feed the kit; `@blender-ui/react` and the DOM-like API on top, unchanged |+| **egui** | BUI panels inside egui, plus a Blender-styled theme |+| **More from Blender's source** | Per-glyph font fallback (BLF), IME, search-as-you-type popups, units in number fields, widget drag and drop |+| **macOS GPU and JavaScript windows** | The GPU renderer on Metal (or the OpenGL backend), and Node windows on the main thread |+| **More GPU backends** | Vulkan / WebGPU drawing the same instance stream as Direct3D 11 and OpenGL |+| **Qt parity** | Measure against PySide6, run the same programs on Qt and BUI, fill in the missing classes, then `install()` so `import PySide6` programs run unchanged |+| **More languages** | MyGo, C#, Go, Zig, Swift, Kotlin and Lua over the same C header; Godot, Unity and Bevy; Flutter |Our roadmap has no dates on it. Like a good render, it's done when the noisegoes away.@@ -1896,8 +1893,7 @@ now. Read [CONTRIBUTING.md](CONTRIBUTING.md) first, and please follow the[SECURITY.md](SECURITY.md) describes.Releases go to PyPI (`blenderui`, wheels built by CI on a `v*` tag), crates.io-(`blenderui-tailwind`, `blenderui-macros`, `blenderui-sys` and `blenderui`, in-that order) and npm (`@blender-ui/native`, `@blender-ui/react`). The steps are+(the eight Rust crates, in dependency order) and npm (`@blender-ui/native`, `@blender-ui/react`). The steps arein [docs/publishing.md](docs/publishing.md).## 43. License and credits@@ -1906,16 +1902,16 @@ in [docs/publishing.md](docs/publishing.md).**GPL-2.0-or-later**. The SPDX header is kept in every file. Third-party partskeep their own licenses:-| Part | What it does in BUI | License |-| --- | --- | --- |-| [Blender](https://www.blender.org) sources | Widget drawing, interaction rules, theme, icons, `blenlib`, GHOST window code, the File Browser and node editor | GPL-2.0-or-later |-| [Dear ImGui](https://github.com/ocornut/imgui) by Omar Cornut | The immediate-mode GUI that runs on BUI | MIT |-| [Inter](https://rsms.me/inter) by Rasmus Andersson | The embedded UI font, as in Blender (`gpu/extern/Inter-LICENSE.txt`) | SIL Open Font License 1.1 |-| [FreeType](https://freetype.org) 2.13.3 | Glyph loading, hinting and rendering, like Blender's BLF | FreeType License or GPLv2 (dual-licensed) |-| [stb_truetype](https://github.com/nothings/stb) by Sean Barrett | Font metrics and character maps, and the fallback rasterizer | Public domain |-| [NanoSVG](https://github.com/memononen/nanosvg) by Mikko Mononen, as edited by Blender | Rasterizing Blender's SVG icons | Zlib |-| [Slug](https://github.com/EricLengyel/Slug) by Eric Lengyel | The GPU glyph coverage algorithm (shader code "Copyright 2017 by Eric Lengyel") | MIT |-| [Tailwind CSS](https://tailwindcss.com) | The v4 default theme values behind the Tailwind support | MIT |+| Part | What it does in BUI | License |+| -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |+| [Blender](https://www.blender.org) sources | Widget drawing, interaction rules, theme, icons, `blenlib`, GHOST window code, the File Browser and node editor | GPL-2.0-or-later |+| [Dear ImGui](https://github.com/ocornut/imgui) by Omar Cornut | The immediate-mode GUI that runs on BUI | MIT |+| [Inter](https://rsms.me/inter) by Rasmus Andersson | The embedded UI font, as in Blender (`gpu/extern/Inter-LICENSE.txt`) | SIL Open Font License 1.1 |+| [FreeType](https://freetype.org) 2.13.3 | Glyph loading, hinting and rendering, like Blender's BLF | FreeType License or GPLv2 (dual-licensed) |+| [stb_truetype](https://github.com/nothings/stb) by Sean Barrett | Font metrics and character maps, and the fallback rasterizer | Public domain |+| [NanoSVG](https://github.com/memononen/nanosvg) by Mikko Mononen, as edited by Blender | Rasterizing Blender's SVG icons | Zlib |+| [Slug](https://github.com/EricLengyel/Slug) by Eric Lengyel | The GPU glyph coverage algorithm (shader code "Copyright 2017 by Eric Lengyel") | MIT |+| [Tailwind CSS](https://tailwindcss.com) | The v4 default theme values behind the Tailwind support | MIT |The Rust and JavaScript bindings also depend on crates and packages such astaffy, napi-rs, React and QuickJS, each under its own license.diff --git a/bindings/rust/blenderui-paint/src/palette.rs b/bindings/rust/blenderui-paint/src/palette.rsindex af09d73..7fea9e6 100644--- a/bindings/rust/blenderui-paint/src/palette.rs+++ b/bindings/rust/blenderui-paint/src/palette.rs@@ -15,6 +15,8 @@ pub struct Palette {pub sel: Rgba,pub hover: Rgba,pub accent: Rgba,+ /// Destructive actions and errors (Blender's red).+ pub danger: Rgba,}impl Palette {@@ -47,6 +49,7 @@ impl Palette {sel: Rgba { a: sel.a.max(0.85), ..sel },hover: text.opacity(0.07),accent,+ danger: Rgba::new(0.8, 0.2, 0.2, 1.0),}}}diff --git a/bindings/rust/blenderui-table/src/cell.rs b/bindings/rust/blenderui-table/src/cell.rsindex 4cf46ca..f95db56 100644--- a/bindings/rust/blenderui-table/src/cell.rs+++ b/bindings/rust/blenderui-table/src/cell.rs@@ -5,6 +5,7 @@use std::cmp::Ordering;+use crate::column::{BadgeVariant, NumberFormat};use crate::fmt::CellBuf;/// One cell's value.@@ -62,6 +63,44 @@ impl Cell<'_> {}}+ /// The text shown with a number format (a currency sign, grouped+ /// digits): borrowed, or formatted into `buf`. Text is shown as it is.+ #[must_use]+ pub fn text_fmt<'b>(&'b self, buf: &'b mut CellBuf, fmt: &NumberFormat) -> &'b str {+ if fmt.is_plain() || self.kind() != CellKind::Number {+ return self.text(buf);+ }+ let mut digits = CellBuf::new();+ let shown = self.text(&mut digits);+ buf.clear();+ buf.push_formatted(shown, fmt);+ buf.as_str()+ }++ /// Whether the cell counts as "on": a non-zero number, or non-empty text+ /// other than `false` and `0`.+ #[must_use]+ pub fn as_bool(&self) -> bool {+ match *self {+ Cell::Empty => false,+ Cell::Str(s) => !matches!(s, "" | "false" | "0"),+ Cell::I64(v) => v != 0,+ Cell::U64(v) => v != 0,+ Cell::F64(v, _) => v != 0.0,+ }+ }++ /// A numeric cell's value (`None` for text and empty cells).+ #[must_use]+ pub const fn number(&self) -> Option<f64> {+ match *self {+ Cell::I64(v) => Some(v as f64),+ Cell::U64(v) => Some(v as f64),+ Cell::F64(v, _) => Some(v),+ _ => None,+ }+ }+/// An order-preserving `u64` for a numeric cell (`None` for text and/// empty cells): integers keep their order, floats follow `f64::total_cmp`./// Only meaningful between cells of the same variant.@@ -132,6 +171,15 @@ const fn rank(k: CellKind) -> u8 {}}+/// A checkbox's state (the header's select-all box has three).+#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]+pub enum Check {+ #[default]+ Unchecked,+ Indeterminate,+ Checked,+}+/// How a column is sorted.#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]pub enum SortKind {@@ -159,6 +207,19 @@ pub trait CellSource: Sync {SortKind::Cells}+ /// The variant of the [`CellRender::Badge`](crate::CellRender::Badge) cell at (`row`, `col`).+ fn badge(&self, row: usize, col: usize) -> BadgeVariant {+ let _ = (row, col);+ BadgeVariant::default()+ }++ /// The state of the select-all checkbox in the header of column `col`+ /// ([`CellRender::Checkbox`](crate::CellRender::Checkbox)).+ fn header_check(&self, col: usize) -> Check {+ let _ = col;+ Check::Unchecked+ }+/// Order rows `a` and `b` by column `col` (used for [`SortKind::Custom`]).fn compare(&self, col: usize, a: usize, b: usize) -> Ordering {self.cell(a, col).sort_cmp(&self.cell(b, col))diff --git a/bindings/rust/blenderui-table/src/column.rs b/bindings/rust/blenderui-table/src/column.rsindex 04e36e2..8be817f 100644--- a/bindings/rust/blenderui-table/src/column.rs+++ b/bindings/rust/blenderui-table/src/column.rs@@ -47,6 +47,67 @@ impl ColumnSort {}}+/// How a column's cells are drawn. shadcn's `cell: ({ row }) => <JSX/>`+/// becomes one of these typed kinds: the table paints them straight from+/// the cell value, with no element per cell.+#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]+pub enum CellRender {+ /// The cell's text.+ #[default]+ Text,+ /// A checkbox, checked when the cell is a non-zero number. A click+ /// raises [`TableEvent::CheckRow`](crate::TableEvent::CheckRow); the+ /// header shows [`CellSource::header_check`](crate::CellSource::header_check)+ /// and raises [`TableEvent::CheckAll`](crate::TableEvent::CheckAll).+ Checkbox,+ /// The cell's text in a pill, colored by+ /// [`CellSource::badge`](crate::CellSource::badge).+ Badge,+ /// A progress bar: the cell is a number from 0 to 100.+ Progress,+ /// A row-actions button (three dots); a click raises+ /// [`TableEvent::CellAction`](crate::TableEvent::CellAction).+ Actions,+}++/// shadcn's Badge variants.+#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]+pub enum BadgeVariant {+ /// `default`: the accent color.+ Default,+ /// `secondary`: a muted fill.+ #[default]+ Secondary,+ /// `destructive`: red.+ Destructive,+ /// `outline`: a border only.+ Outline,+}++/// How numbers are shown, like `Intl.NumberFormat`: a prefix (a currency+/// sign), a suffix and thousands grouping. Applied to number cells only.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct NumberFormat {+ pub prefix: Text,+ pub suffix: Text,+ /// Group the integer digits in threes (`1,234,567`).+ pub group: bool,+}++impl NumberFormat {+ /// US dollars: `$1,234.50` (with the cell's own decimals).+ #[must_use]+ pub const fn usd() -> Self {+ Self { prefix: Cow::Borrowed("$"), suffix: Cow::Borrowed(""), group: true }+ }++ /// Whether this format changes nothing.+ #[must_use]+ pub fn is_plain(&self) -> bool {+ self.prefix.is_empty() && self.suffix.is_empty() && !self.group+ }+}+/// A pinned column.#[derive(Copy, Clone, Debug, PartialEq, Eq)]pub enum ColumnFixed {@@ -88,6 +149,13 @@ pub struct Column {pub max_width: f32,/// Hidden columns take no space and are never drawn.pub visible: bool,+ /// How the cells are drawn.+ pub render: CellRender,+ /// How numbers are shown.+ pub format: NumberFormat,+ /// A header click raises [`TableEvent::HeaderMenu`](crate::TableEvent::HeaderMenu)+ /// (shadcn's sortable header with a menu) instead of sorting at once.+ pub header_menu: bool,}impl Default for Column {@@ -105,6 +173,9 @@ impl Default for Column {min_width: 20.0,max_width: 1200.0,visible: true,+ render: CellRender::Text,+ format: NumberFormat { prefix: Cow::Borrowed(""), suffix: Cow::Borrowed(""), group: false },+ header_menu: false,}}}@@ -201,6 +272,21 @@ impl Column {self.visible = on;self}+ #[must_use]+ pub const fn render(mut self, render: CellRender) -> Self {+ self.render = render;+ self+ }+ #[must_use]+ pub fn format(mut self, format: NumberFormat) -> Self {+ self.format = format;+ self+ }+ #[must_use]+ pub const fn header_menu(mut self, on: bool) -> Self {+ self.header_menu = on;+ self+ }}/// Order, widths and edges of the columns on screen.diff --git a/bindings/rust/blenderui-table/src/event.rs b/bindings/rust/blenderui-table/src/event.rsindex ea69635..1138247 100644--- a/bindings/rust/blenderui-table/src/event.rs+++ b/bindings/rust/blenderui-table/src/event.rs@@ -38,6 +38,18 @@ pub enum TableEvent {/// A double click on a column's border asks the delegate to fit it/// (source column). Adapters answer it and do not forward it.FitColumn(usize),+ /// A click on a [`CellRender::Checkbox`](crate::CellRender::Checkbox)+ /// cell (source row, source column). The row selection is the+ /// delegate's: the table does not change it.+ CheckRow(usize, usize),+ /// A click on the header of a checkbox column (source column).+ CheckAll(usize),+ /// A click on a [`CellRender::Actions`](crate::CellRender::Actions) cell+ /// (source row, source column).+ CellAction(usize, usize),+ /// A click on the header of a [`Column::header_menu`](crate::Column::header_menu)+ /// column (source column): open its menu.+ HeaderMenu(usize),}/// Rows and columns in view (gpui-component's `TableVisibleRange`). Rows arediff --git a/bindings/rust/blenderui-table/src/fmt.rs b/bindings/rust/blenderui-table/src/fmt.rsindex 29a384e..dc68f38 100644--- a/bindings/rust/blenderui-table/src/fmt.rs+++ b/bindings/rust/blenderui-table/src/fmt.rs@@ -44,6 +44,24 @@ impl CellBuf {}/// Write the decimal digits of `v`.+ /// Append the number text `digits` (as formatted by [`push_f64`](Self::push_f64) and+ /// friends) with `fmt`: the sign first, then the prefix, the integer part+ /// grouped in threes, the rest, then the suffix.+ pub fn push_formatted(&mut self, digits: &str, fmt: &crate::column::NumberFormat) {+ let (sign, rest) = digits.strip_prefix('-').map_or(("", digits), |r| ("-", r));+ let int_len = rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len());+ self.push_bytes(sign.as_bytes());+ self.push_bytes(fmt.prefix.as_bytes());+ for (i, d) in rest[..int_len].bytes().enumerate() {+ if fmt.group && i > 0 && (int_len - i) % 3 == 0 {+ self.push_bytes(b",");+ }+ self.push_bytes(&[d]);+ }+ self.push_bytes(&rest.as_bytes()[int_len..]);+ self.push_bytes(fmt.suffix.as_bytes());+ }+pub fn push_u64(&mut self, mut v: u64) {let mut tmp = [0u8; 20];let mut i = tmp.len();diff --git a/bindings/rust/blenderui-table/src/interact.rs b/bindings/rust/blenderui-table/src/interact.rsindex 8d60f18..4371a01 100644--- a/bindings/rust/blenderui-table/src/interact.rs+++ b/bindings/rust/blenderui-table/src/interact.rs@@ -5,7 +5,7 @@//! clipboard) are queued as [`TableEvent`]s.use crate::cell::CellSource;-use crate::column::ColumnSort;+use crate::column::{CellRender, ColumnSort};use crate::event::TableEvent;use crate::geom::Point;use crate::geometry::Hit;@@ -79,6 +79,14 @@ impl TableModel {fn click_row(&mut self, r: usize, col: Option<usize>, mods: Mods, clicks: usize) {let row = self.mask.get(r);self.right_clicked = None;+ if let Some(v) = col {+ let (render, src) = (self.layout.column(v).render, self.layout.src(v));+ match render {+ CellRender::Checkbox => return self.events.push(TableEvent::CheckRow(row, src)),+ CellRender::Actions => return self.events.push(TableEvent::CellAction(row, src)),+ _ => {}+ }+ }let cell_mode = self.opts.cell_selectable && col.is_some_and(|v| self.layout.column(v).selectable);if cell_mode {let c = self.layout.src(col.unwrap_or(0));@@ -175,7 +183,11 @@ impl TableModel {}let col = self.layout.column(v);let source = self.layout.src(v);- if self.opts.sortable && col.sort.is_some() {+ if col.render == CellRender::Checkbox {+ self.events.push(TableEvent::CheckAll(source));+ } else if col.header_menu {+ self.events.push(TableEvent::HeaderMenu(source));+ } else if self.opts.sortable && col.sort.is_some() {let next = col.sort.map_or(ColumnSort::Ascending, ColumnSort::next);self.sort_by(src, source, next, by_mask);} else if self.opts.col_selectable && col.selectable {diff --git a/bindings/rust/blenderui-table/src/lib.rs b/bindings/rust/blenderui-table/src/lib.rsindex a512a4c..2dc6934 100644--- a/bindings/rust/blenderui-table/src/lib.rs+++ b/bindings/rust/blenderui-table/src/lib.rs@@ -36,6 +36,7 @@ pub mod paint;pub mod selection;pub mod state;pub mod sort;+pub mod tanstack;pub use blenderui_paint::{geom, text_cache};pub mod vec_table;pub mod visible;@@ -45,8 +46,8 @@ mod alloc_probe;#[cfg(test)]mod test_util;-pub use cell::{Cell, CellKind, CellSource, SortKind};-pub use column::{Column, ColumnFixed, ColumnGroup, ColumnLayout, ColumnSort, Text, TextAlign};+pub use cell::{Cell, CellKind, CellSource, Check, SortKind};+pub use column::{BadgeVariant, CellRender, Column, ColumnFixed, ColumnGroup, ColumnLayout, ColumnSort, NumberFormat, Text, TextAlign};pub use event::{Size, TableEvent, TableOptions, TableSelection, TableVisibleRange};pub use fmt::CellBuf;pub use geom::{Point, Rect, Rgba};diff --git a/bindings/rust/blenderui-table/src/model.rs b/bindings/rust/blenderui-table/src/model.rsindex 8199c05..6645a1e 100644--- a/bindings/rust/blenderui-table/src/model.rs+++ b/bindings/rust/blenderui-table/src/model.rs@@ -376,6 +376,21 @@ impl TableModel {}}+ /// Highlight exactly the display rows `rows` (a selection the owner of+ /// the data keeps, like a checkbox column's), without raising events.+ pub fn set_row_highlights(&mut self, rows: impl IntoIterator<Item = usize>) {+ self.sel.clear();+ for r in rows {+ self.sel.add(r..r + 1);+ }+ self.sel.clamp(self.rows());+ }++ /// Show `sorted` as the sort indicator (the owner of the data sorts).+ pub const fn set_sort_indicator(&mut self, sorted: Option<(usize, ColumnSort)>) {+ self.sort = sorted;+ }+/// The active selected row (source index).#[must_use]pub fn selected_row(&self) -> Option<usize> {diff --git a/bindings/rust/blenderui-table/src/paint.rs b/bindings/rust/blenderui-table/src/paint.rsindex 640d9b8..99ca7c2 100644--- a/bindings/rust/blenderui-table/src/paint.rs+++ b/bindings/rust/blenderui-table/src/paint.rs@@ -22,8 +22,8 @@use std::cell::Cell as StdCell;use std::ops::Range;-use crate::cell::CellSource;-use crate::column::{ColumnSort, TextAlign};+use crate::cell::{Cell, CellSource, Check};+use crate::column::{BadgeVariant, CellRender, Column, ColumnSort, TextAlign};use crate::fmt::CellBuf;use crate::geom::{Rect, Rgba};pub use blenderui_paint::{PaintSink, Palette};@@ -94,6 +94,24 @@ pub fn draw_alternating_row_pairs(sink: &mut dyn PaintSink, rows: &Range<usize>,}}+/// A chevron (two lines) of half-width `k` pointing up or down.+fn chevron(sink: &mut dyn PaintSink, cx: f32, cy: f32, k: f32, up: bool, color: Rgba) {+ let d = if up { -k } else { k };+ sink.line((cx - k, cy - d / 2.0), (cx, cy + d / 2.0), color, 1.5);+ sink.line((cx, cy + d / 2.0), (cx + k, cy - d / 2.0), color, 1.5);+}++/// The x of content in a column cell, by the column's alignment. The width of+/// the content is only asked for when the alignment needs it: measuring text+/// is the expensive part, and a left-aligned cell does not need it.+fn aligned(col: &Column, x: f32, w: f32, pad: f32, content_w: impl FnOnce() -> f32) -> f32 {+ match col.align {+ TextAlign::Right => x + w - pad - content_w(),+ TextAlign::Center => x + (w - content_w()) / 2.0,+ TextAlign::Left => x + pad,+ }+}+/// Everything one paint call needs besides the sink.struct Frame<'a, S: CellSource + ?Sized> {t: &'a TableModel,@@ -222,20 +240,25 @@ impl<S: CellSource + ?Sized> Frame<'_, S> {let pad = self.pad();let avail = (w - 2.0 * pad).max(0.0);let selected_cell = t.sel_cell.filter(|&(_, c)| c == source);- let PaintScratch { cell: buf, ell } = scratch;for r in rows.clone() {+ let PaintScratch { cell: buf, ell } = &mut *scratch;let top = t.row_top(g, r);let row = t.mask.get(r);let cell = self.src.cell(row, source);- let text = cell.text(buf);- if !text.is_empty() {- let shown = fit_text(text, avail, self.size, sink, ell);- let tx = match col.align {- TextAlign::Right => x + w - pad - sink.text_width(shown, self.size),- TextAlign::Center => x + (w - sink.text_width(shown, self.size)) / 2.0,- TextAlign::Left => x + pad,- };- sink.text(tx, top + g.row_h / 2.0, shown, self.size, self.pal.text);+ let at = Rect::new(x, top, w, g.row_h);+ match col.render {+ CellRender::Text => {+ let text = cell.text_fmt(buf, &col.format);+ if !text.is_empty() {+ let shown = fit_text(text, avail, self.size, sink, ell);+ let tx = aligned(col, x, w, pad, || sink.text_width(shown, self.size));+ sink.text(tx, top + g.row_h / 2.0, shown, self.size, self.pal.text);+ }+ }+ CellRender::Checkbox => self.draw_checkbox(sink, at, col, if cell.as_bool() { Check::Checked } else { Check::Unchecked }),+ CellRender::Badge => self.draw_badge(sink, at, col, &cell, self.src.badge(row, source), scratch),+ CellRender::Progress => self.draw_progress(sink, at, pad, &cell),+ CellRender::Actions => self.draw_dots(sink, at),}if selected_cell.is_some_and(|(sr, _)| sr == row) {sink.stroke(Rect::new(x, top, w, g.row_h), self.pal.accent, 1.5);@@ -246,6 +269,91 @@ impl<S: CellSource + ?Sized> Frame<'_, S> {}}+ /// The fill of checked boxes, default badges and progress bars: Blender's+ /// selection blue, lifted so it shows on a selected row too.+ fn primary(&self) -> Rgba {+ Rgba { a: 1.0, ..self.pal.sel }.shade(25.0)+ }++ /// A checkbox in a cell or header: Blender-sized (about 60% of the row),+ /// at the column's alignment.+ fn draw_checkbox(&self, sink: &mut dyn PaintSink, at: Rect, col: &Column, state: Check) {+ let s = (at.h * 0.6).round().max(8.0);+ let x = aligned(col, at.x, at.w, self.pad(), || s);+ let b = Rect::new(x, at.y + (at.h - s) / 2.0, s, s);+ let pal = self.pal;+ if state == Check::Unchecked {+ sink.round(b, 3.0, pal.text.opacity(0.5));+ sink.round(Rect::new(b.x + 1.0, b.y + 1.0, s - 2.0, s - 2.0), 2.0, pal.back);+ return;+ }+ let white = Rgba::new(1.0, 1.0, 1.0, 1.0);+ sink.round(b, 3.0, self.primary());+ let w = (s * 0.1).max(1.5);+ if state == Check::Checked {+ let p = |fx: f32, fy: f32| (b.x + s * fx, b.y + s * fy);+ sink.line(p(0.24, 0.52), p(0.42, 0.7), white, w);+ sink.line(p(0.42, 0.7), p(0.76, 0.3), white, w);+ } else {+ sink.line((b.x + s * 0.25, b.y + s * 0.5), (b.x + s * 0.75, b.y + s * 0.5), white, w);+ }+ }++ /// shadcn's Badge: the cell's text in a pill.+ fn draw_badge(&self, sink: &mut dyn PaintSink, at: Rect, col: &Column, cell: &Cell<'_>, variant: BadgeVariant, scratch: &mut PaintScratch) {+ let PaintScratch { cell: buf, ell } = scratch;+ let text = cell.text_fmt(buf, &col.format);+ if text.is_empty() {+ return;+ }+ let pal = self.pal;+ let (pad_x, h) = (self.pad() * 0.9, (at.h * 0.72).round());+ let shown = fit_text(text, (at.w - 2.0 * self.pad() - 2.0 * pad_x).max(0.0), self.size, sink, ell);+ let tw = sink.text_width(shown, self.size);+ let r = Rect::new(aligned(col, at.x, at.w, self.pad(), || tw + 2.0 * pad_x), at.y + (at.h - h) / 2.0, tw + 2.0 * pad_x, h);+ let white = Rgba::new(1.0, 1.0, 1.0, 1.0);+ let ink = match variant {+ BadgeVariant::Default => {+ sink.round(r, h / 2.0, self.primary());+ white+ }+ BadgeVariant::Secondary => {+ sink.round(r, h / 2.0, pal.text.opacity(0.14));+ pal.text+ }+ BadgeVariant::Destructive => {+ sink.round(r, h / 2.0, pal.danger);+ white+ }+ BadgeVariant::Outline => {+ sink.round(r, h / 2.0, pal.text.opacity(0.4));+ sink.round(Rect::new(r.x + 1.0, r.y + 1.0, r.w - 2.0, r.h - 2.0), h / 2.0 - 1.0, pal.back);+ pal.text+ }+ };+ sink.text(r.x + pad_x, at.y + at.h / 2.0, shown, self.size, ink);+ }++ /// shadcn's Progress: a track and a fill, the cell a number 0..=100.+ fn draw_progress(&self, sink: &mut dyn PaintSink, at: Rect, pad: f32, cell: &Cell<'_>) {+ let (w, h) = ((at.w - 2.0 * pad).max(0.0), (at.h * 0.28).round().max(3.0));+ let frac = (cell.number().unwrap_or(0.0) / 100.0).clamp(0.0, 1.0) as f32;+ let y = at.y + (at.h - h) / 2.0;+ sink.round(Rect::new(at.x + pad, y, w, h), h / 2.0, self.pal.text.opacity(0.15));+ if frac > 0.0 {+ sink.round(Rect::new(at.x + pad, y, (w * frac).max(h), h), h / 2.0, self.primary());+ }+ }++ /// The row-actions button: three dots (lucide's `MoreHorizontal`).+ fn draw_dots(&self, sink: &mut dyn PaintSink, at: Rect) {+ let d = (at.h * 0.14).round().max(2.0);+ let (cx, cy) = (at.x + at.w / 2.0, at.y + at.h / 2.0);+ for k in [-1.0f32, 0.0, 1.0] {+ sink.round(Rect::new(cx + k * d * 2.0 - d / 2.0, cy - d / 2.0, d, d), d / 2.0, self.pal.text);+ }+ }+/// Blender's left index column.fn draw_index_column(&self, sink: &mut dyn PaintSink, rows: &Range<usize>, scratch: &mut PaintScratch) {let (g, t) = (&self.g, self.t);@@ -325,7 +433,16 @@ impl<S: CellSource + ?Sized> Frame<'_, S> {let w = t.layout.width(v);let hy = g.groups_h;let pad = self.pad();- let arrow = if col.sort.is_some() && t.opts.sortable { g.unit * 0.7 } else { 0.0 };+ let source = t.layout.src(v);+ if col.render == CellRender::Checkbox {+ self.draw_checkbox(sink, Rect::new(x, hy, w, g.header_h), col, self.src.header_check(source));+ if t.sel_col == Some(source) {+ sink.fill(Rect::new(x, hy, w, g.header_h), pal.accent.opacity(0.25));+ }+ self.vline(sink, x + w, hy, g.header_h);+ return;+ }+ let arrow = if col.header_menu || (col.sort.is_some() && t.opts.sortable) { g.unit * 0.7 } else { 0.0 };let text = fit_text(&col.name, (w - 2.0 * pad - arrow).max(0.0), self.size, sink, &mut scratch.ell);let tx = match col.align {TextAlign::Right => x + w - pad - arrow - sink.text_width(text, self.size),@@ -333,12 +450,19 @@ impl<S: CellSource + ?Sized> Frame<'_, S> {TextAlign::Left => x + pad,};sink.text(tx, hy + g.header_h / 2.0, text, self.size, pal.text);- if let (Some(s @ (ColumnSort::Ascending | ColumnSort::Descending)), true) = (col.sort, t.opts.sortable) {- // a chevron: two lines- let (cx, cy, k) = (x + w - pad - g.unit * 0.25, hy + g.header_h / 2.0, g.unit * 0.15);- let d = if s == ColumnSort::Ascending { -k } else { k };- sink.line((cx - k, cy - d / 2.0), (cx, cy + d / 2.0), pal.text, 1.5);- sink.line((cx, cy + d / 2.0), (cx + k, cy - d / 2.0), pal.text, 1.5);+ let (cy, k) = (hy + g.header_h / 2.0, g.unit * 0.15);+ if col.header_menu {+ // shadcn's DataTableColumnHeader: the icon follows the title (ArrowUp, ArrowDown or ChevronsUpDown)+ let cx = if col.align == TextAlign::Left { (tx + sink.text_width(text, self.size) + pad + k).min(x + w - pad - k) } else { x + w - pad - g.unit * 0.25 };+ let s = col.sort.unwrap_or_default();+ if s == ColumnSort::Default {+ chevron(sink, cx, cy - k * 0.9, k * 0.8, true, pal.dim);+ chevron(sink, cx, cy + k * 0.9, k * 0.8, false, pal.dim);+ } else {+ chevron(sink, cx, cy, k, s == ColumnSort::Ascending, pal.text);+ }+ } else if let (Some(s @ (ColumnSort::Ascending | ColumnSort::Descending)), true) = (col.sort, t.opts.sortable) {+ chevron(sink, x + w - pad - g.unit * 0.25, cy, k, s == ColumnSort::Ascending, pal.text);}if t.sel_col == Some(t.layout.src(v)) {sink.fill(Rect::new(x, hy, w, g.header_h), pal.accent.opacity(0.25));@@ -485,4 +609,103 @@ mod tests {assert_eq!(n, 0, "a steady-state frame allocated");});}++ /// Every cell kind in one table: text with a currency format, a checkbox,+ /// a badge, a progress bar and the actions dots.+ struct Kinds;+ impl CellSource for Kinds {+ fn cell(&self, r: usize, c: usize) -> Cell<'_> {+ match c {+ 0 => Cell::U64((r % 2) as u64),+ 1 => Cell::Str(["paid", "failed"][r % 2]),+ 2 => Cell::F64(1234.5 + r as f64, 2),+ 3 => Cell::U64((r * 7 % 101) as u64),+ _ => Cell::Empty,+ }+ }+ fn badge(&self, r: usize, _: usize) -> BadgeVariant {+ if r.is_multiple_of(2) { BadgeVariant::Default } else { BadgeVariant::Destructive }+ }+ fn header_check(&self, _: usize) -> Check {+ Check::Indeterminate+ }+ }++ fn kinds_model(rows: usize) -> TableModel {+ use crate::column::NumberFormat;+ let mut t = TableModel::new();+ t.set_columns(+ vec![+ Column::new("sel", "").width(40.0_f32).render(CellRender::Checkbox).text_center(),+ Column::new("status", "Status").width(90.0_f32).render(CellRender::Badge),+ Column::new("amount", "Amount").width(110.0_f32).text_right().format(NumberFormat::usd()),+ Column::new("pct", "Done").width(100.0_f32).render(CellRender::Progress),+ Column::new("act", "").width(48.0_f32).render(CellRender::Actions),+ ],+ None,+ );+ t.set_rows(rows, &Kinds);+ t.begin_frame(400.0, 200.0, 20.0, 1.0);+ t+ }++ #[test]+ fn typed_cell_kinds_paint_without_elements() {+ let t = kinds_model(1000);+ let mut rec = Rec::default();+ with_scratch(|s| paint_table(&t, &Kinds, &pal(), "", s, &mut rec));+ assert_eq!(rec.depth, 0);+ assert!(rec.texts.iter().any(|s| s == "paid") && rec.texts.iter().any(|s| s == "failed"), "badge text");+ assert!(rec.texts.iter().any(|s| s == "$1,234.50"), "currency format: {:?}", &rec.texts[..8]);+ assert!(!rec.texts.iter().any(|s| s == "1234.50"));+ }++ #[test]+ fn typed_cell_kinds_do_not_allocate_in_a_steady_frame() {+ use crate::alloc_probe::count_allocs;+ let mut t = kinds_model(1_000_000);+ t.scroll_by(0.0, 5_000_000.0);+ t.begin_frame(400.0, 200.0, 20.0, 1.0);+ struct Null;+ impl PaintSink for Null {+ fn fill(&mut self, _: Rect, _: Rgba) {}+ fn stroke(&mut self, _: Rect, _: Rgba, _: f32) {}+ fn round(&mut self, _: Rect, _: f32, _: Rgba) {}+ fn line(&mut self, _: (f32, f32), _: (f32, f32), _: Rgba, _: f32) {}+ fn text(&mut self, _: f32, _: f32, _: &str, _: f32, _: Rgba) {}+ fn text_width(&mut self, text: &str, size: f32) -> f32 {+ text.len() as f32 * size * 0.5+ }+ fn clipped(&mut self, _: Rect, f: &mut dyn FnMut(&mut dyn PaintSink)) {+ f(self);+ }+ }+ let p = pal();+ with_scratch(|s| {+ for _ in 0..3 {+ paint_table(&t, &Kinds, &p, "", s, &mut Null);+ }+ assert_eq!(count_allocs(|| paint_table(&t, &Kinds, &p, "", s, &mut Null)), 0, "a steady-state frame allocated");+ });+ }++ #[test]+ fn clicks_on_typed_cells_raise_events() {+ use crate::event::TableEvent;+ use crate::input::{Button, Mods};+ let mut t = kinds_model(100);+ let g = t.geo();+ let row = |r: f32| g.top + g.row_h * (r + 0.5);+ // checkbox cell, row 2: neither selects the row nor changes the sort+ t.pointer_down(crate::geom::Point { x: 20.0, y: row(2.0) }, Button::Left, Mods::default(), 1);+ assert_eq!(t.take_events(), vec![TableEvent::CheckRow(2, 0)]);+ assert!(t.selected_rows().next().is_none());+ // the actions cell, row 1 (x past 40 + 90 + 110 + 100)+ t.pointer_down(crate::geom::Point { x: 360.0, y: row(1.0) }, Button::Left, Mods::default(), 1);+ assert_eq!(t.take_events(), vec![TableEvent::CellAction(1, 4)]);+ // the checkbox header: select all+ t.pointer_down(crate::geom::Point { x: 20.0, y: g.groups_h + g.header_h / 2.0 }, Button::Left, Mods::default(), 1);+ t.pointer_up(&Kinds, false);+ assert_eq!(t.take_events(), vec![TableEvent::CheckAll(0)]);+ }}diff --git a/bindings/rust/blenderui-table/src/tanstack/column.rs b/bindings/rust/blenderui-table/src/tanstack/column.rsnew file mode 100644index 0000000..8509632--- /dev/null+++ b/bindings/rust/blenderui-table/src/tanstack/column.rs@@ -0,0 +1,385 @@+//! [`ColumnDef`]: TanStack's column definition.++use std::sync::Arc;++use crate::cell::Cell;+use crate::column::{BadgeVariant, CellRender, NumberFormat, Text, TextAlign};++/// A row type whose fields can be read by name: what makes+/// `ColumnDef::accessor_key("email")` work like TanStack's `accessorKey`+/// (Rust has no reflection, so the type lists its fields once).+///+/// ```+/// use blenderui_table::{Cell, tanstack::Record};+/// struct Payment { id: String, amount: f64 }+/// impl Record for Payment {+/// const FIELDS: &'static [&'static str] = &["id", "amount"];+/// fn field(&self, field: usize) -> Cell<'_> {+/// match field { 0 => Cell::Str(&self.id), _ => Cell::F64(self.amount, 2) }+/// }+/// }+/// ```+pub trait Record: Send + Sync + 'static {+ /// The field names, in the order of [`field`](Self::field)'s index.+ const FIELDS: &'static [&'static str];++ /// The value of field `field` (an index into [`FIELDS`](Self::FIELDS)).+ fn field(&self, field: usize) -> Cell<'_>;+}++/// Picks the badge variant from the cell's text.+pub(crate) type BadgeFn = Arc<dyn Fn(&str) -> BadgeVariant + Send + Sync>;++/// How a column reads its cell from a row.+pub(crate) enum Accessor<T> {+ /// `accessorFn` / `accessorKey`.+ Read(Arc<dyn for<'a> Fn(&'a T) -> Cell<'a> + Send + Sync>),+ /// A display column (`select`, `actions`): no data of its own.+ Display,+ /// `accessorKey` naming a field the row type does not have.+ Missing(Text),+}++impl<T> Clone for Accessor<T> {+ fn clone(&self) -> Self {+ match self {+ Self::Read(f) => Self::Read(Arc::clone(f)),+ Self::Display => Self::Display,+ Self::Missing(k) => Self::Missing(k.clone()),+ }+ }+}++/// A column header: shadcn's `header` string or header component.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Header {+ /// `header: "Email"`.+ Text(Text),+ /// `header: ({ column }) => <DataTableColumnHeader column={column} title="Email" />`:+ /// the title with a sort icon and a menu (Asc, Desc, Hide).+ Menu(Text),+ /// The select-all checkbox (`<Checkbox checked={table.getIsAllPageRowsSelected()} .. />`).+ SelectAll,+}++impl From<&'static str> for Header {+ fn from(s: &'static str) -> Self {+ Self::Text(s.into())+ }+}++impl From<String> for Header {+ fn from(s: String) -> Self {+ Self::Text(s.into())+ }+}++impl Header {+ /// A sortable header with a menu.+ #[must_use]+ pub fn menu(title: impl Into<Text>) -> Self {+ Self::Menu(title.into())+ }++ /// The header's text (empty for the select-all checkbox).+ #[must_use]+ pub fn title(&self) -> &str {+ match self {+ Self::Text(t) | Self::Menu(t) => t,+ Self::SelectAll => "",+ }+ }+}++/// TanStack's `meta`: what the painted table needs to know beyond the+/// definition (alignment, number format, pinning).+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct ColumnMeta {+ pub align: TextAlign,+ pub format: NumberFormat,+ /// Stays at the left edge while the table scrolls sideways.+ pub pinned: bool,+}++impl ColumnMeta {+ /// Right-aligned cells.+ #[must_use]+ pub fn right() -> Self {+ Self { align: TextAlign::Right, ..Self::default() }+ }++ /// Centered cells.+ #[must_use]+ pub fn center() -> Self {+ Self { align: TextAlign::Center, ..Self::default() }+ }++ /// US-dollar numbers (`$1,234.50`).+ #[must_use]+ pub fn usd(mut self) -> Self {+ self.format = NumberFormat::usd();+ self+ }++ /// Any number format.+ #[must_use]+ pub fn format(mut self, format: NumberFormat) -> Self {+ self.format = format;+ self+ }++ /// Pinned to the left edge.+ #[must_use]+ pub const fn pinned(mut self) -> Self {+ self.pinned = true;+ self+ }+}++/// A column definition (TanStack's `ColumnDef<TData>`).+///+/// ```ignore+/// let columns = vec![+/// ColumnDef::select(),+/// ColumnDef::accessor_key("status").header("Status").badge(|s| BadgeVariant::Secondary),+/// ColumnDef::accessor_key("email").header(Header::menu("Email")),+/// ColumnDef::accessor_key("amount").header("Amount").meta(ColumnMeta::right().usd()),+/// ];+/// ```+#[allow(clippy::struct_excessive_bools)]+pub struct ColumnDef<T> {+ /// `id` (defaults to the accessor key).+ pub id: Text,+ pub header: Header,+ /// How the cells are drawn (`cell`).+ pub cell: CellRender,+ /// `enableSorting`.+ pub enable_sorting: bool,+ /// `enableHiding`.+ pub enable_hiding: bool,+ /// `enableColumnFilter`.+ pub enable_column_filter: bool,+ /// `enableGlobalFilter`.+ pub enable_global_filter: bool,+ /// `enableResizing`.+ pub enable_resizing: bool,+ /// `size`, px.+ pub size: f32,+ /// `minSize`, px.+ pub min_size: f32,+ /// `maxSize`, px.+ pub max_size: f32,+ pub meta: ColumnMeta,+ pub(crate) accessor: Accessor<T>,+ pub(crate) badge: Option<BadgeFn>,+}++impl<T> Clone for ColumnDef<T> {+ fn clone(&self) -> Self {+ Self {+ id: self.id.clone(),+ header: self.header.clone(),+ cell: self.cell,+ enable_sorting: self.enable_sorting,+ enable_hiding: self.enable_hiding,+ enable_column_filter: self.enable_column_filter,+ enable_global_filter: self.enable_global_filter,+ enable_resizing: self.enable_resizing,+ size: self.size,+ min_size: self.min_size,+ max_size: self.max_size,+ meta: self.meta.clone(),+ accessor: self.accessor.clone(),+ badge: self.badge.clone(),+ }+ }+}++impl<T> std::fmt::Debug for ColumnDef<T> {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("ColumnDef").field("id", &self.id).field("header", &self.header).field("cell", &self.cell).finish_non_exhaustive()+ }+}++impl<T> ColumnDef<T> {+ fn base(id: Text, accessor: Accessor<T>) -> Self {+ Self {+ header: Header::Text(id.clone()),+ id,+ cell: CellRender::Text,+ enable_sorting: true,+ enable_hiding: true,+ enable_column_filter: true,+ enable_global_filter: true,+ enable_resizing: true,+ size: 150.0,+ min_size: 20.0,+ max_size: 1200.0,+ meta: ColumnMeta::default(),+ accessor,+ badge: None,+ }+ }++ /// `accessorFn` with an `id`: any function of the row.+ #[must_use]+ pub fn accessor_fn(id: impl Into<Text>, f: impl for<'a> Fn(&'a T) -> Cell<'a> + Send + Sync + 'static) -> Self {+ Self::base(id.into(), Accessor::Read(Arc::new(f)))+ }++ /// A display column (`id` only): its cells come from the cell kind, as+ /// shadcn's `select` and `actions` columns do.+ #[must_use]+ pub fn display(id: impl Into<Text>) -> Self {+ let mut c = Self::base(id.into(), Accessor::Display);+ c.enable_sorting = false;+ c.enable_column_filter = false;+ c.enable_global_filter = false;+ c+ }++ /// `id`.+ #[must_use]+ pub fn id(mut self, id: impl Into<Text>) -> Self {+ self.id = id.into();+ self+ }++ /// `header`: a string, or [`Header::menu`] for the sortable header with a menu.+ #[must_use]+ pub fn header(mut self, header: impl Into<Header>) -> Self {+ self.header = header.into();+ self+ }++ /// `cell`: how the cells are drawn.+ #[must_use]+ pub const fn cell(mut self, cell: CellRender) -> Self {+ self.cell = cell;+ self+ }++ /// A [`CellRender::Badge`] column whose variant is chosen from the+ /// cell's text.+ #[must_use]+ pub fn badge(mut self, f: impl Fn(&str) -> BadgeVariant + Send + Sync + 'static) -> Self {+ self.cell = CellRender::Badge;+ self.badge = Some(Arc::new(f));+ self+ }++ #[must_use]+ pub const fn enable_sorting(mut self, on: bool) -> Self {+ self.enable_sorting = on;+ self+ }++ #[must_use]+ pub const fn enable_hiding(mut self, on: bool) -> Self {+ self.enable_hiding = on;+ self+ }++ #[must_use]+ pub const fn enable_column_filter(mut self, on: bool) -> Self {+ self.enable_column_filter = on;+ self+ }++ #[must_use]+ pub const fn enable_global_filter(mut self, on: bool) -> Self {+ self.enable_global_filter = on;+ self+ }++ #[must_use]+ pub const fn enable_resizing(mut self, on: bool) -> Self {+ self.enable_resizing = on;+ self+ }++ /// `size`, px.+ #[must_use]+ pub const fn size(mut self, px: f32) -> Self {+ self.size = px;+ self+ }++ /// `minSize`, px.+ #[must_use]+ pub const fn min_size(mut self, px: f32) -> Self {+ self.min_size = px;+ self+ }++ /// `maxSize`, px.+ #[must_use]+ pub const fn max_size(mut self, px: f32) -> Self {+ self.max_size = px;+ self+ }++ /// `meta`.+ #[must_use]+ pub fn meta(mut self, meta: ColumnMeta) -> Self {+ self.meta = meta;+ self+ }++ /// Whether this column reads data (it is not a display column).+ #[must_use]+ pub const fn has_accessor(&self) -> bool {+ matches!(self.accessor, Accessor::Read(_))+ }++ pub(crate) fn read<'a>(&self, row: &'a T) -> Cell<'a> {+ match &self.accessor {+ Accessor::Read(f) => f(row),+ _ => Cell::Empty,+ }+ }+}++/// shadcn's `select` column: a checkbox per row and a select-all checkbox+/// in the header (`table.getIsAllPageRowsSelected()`).+#[must_use]+pub fn select_column<T>() -> ColumnDef<T> {+ ColumnDef::display("select")+ .header(Header::SelectAll)+ .cell(CellRender::Checkbox)+ .meta(ColumnMeta::center())+ .enable_hiding(false)+ .enable_resizing(false)+ .size(40.0)+ .min_size(40.0)+ .max_size(40.0)+}++/// shadcn's `actions` column: a "more" button per row; a click is reported+/// as a row action.+#[must_use]+pub fn actions_column<T>() -> ColumnDef<T> {+ ColumnDef::display("actions")+ .header("")+ .cell(CellRender::Actions)+ .enable_hiding(false)+ .enable_resizing(false)+ .size(48.0)+ .min_size(48.0)+ .max_size(48.0)+}++impl<T: Record> ColumnDef<T> {+ /// `accessorKey`: the field named `key` ([`Record::FIELDS`]); the `id`+ /// and the header text default to it. An unknown key is reported by+ /// [`Table::new`](super::Table::new), where the columns are validated.+ #[must_use]+ pub fn accessor_key(key: impl Into<Text>) -> Self {+ let key = key.into();+ let accessor = match T::FIELDS.iter().position(|f| *f == key) {+ Some(ix) => Accessor::Read(Arc::new(move |row: &T| row.field(ix))),+ None => Accessor::Missing(key.clone()),+ };+ Self::base(key, accessor)+ }+}diff --git a/bindings/rust/blenderui-table/src/tanstack/mod.rs b/bindings/rust/blenderui-table/src/tanstack/mod.rsnew file mode 100644index 0000000..cd07cba--- /dev/null+++ b/bindings/rust/blenderui-table/src/tanstack/mod.rs@@ -0,0 +1,29 @@+//! TanStack Table v8's model (the engine under shadcn/ui's Data Table) on+//! top of the table core, framework-independent.+//!+//! | TanStack | here |+//! |---|---|+//! | `ColumnDef` (`accessorKey`, `accessorFn`, `id`, `header`, `cell`, `size`, `meta` ...) | [`ColumnDef`] |+//! | `useReactTable` options / table instance | [`TableOptions`] / [`Table`] |+//! | `SortingState`, `ColumnFiltersState`, `VisibilityState`, `RowSelectionState`, `PaginationState` | the types of the same names |+//! | controlled `state` and `onXChange` | [`PartialState`] and [`Change`] |+//! | `getCoreRowModel` / `getFilteredRowModel` / `getSortedRowModel` / `getPaginationRowModel` | [`Table::core_row_model`], [`Table::filtered_row_model`], [`Table::sorted_row_model`], [`Table::row_model`] |+//!+//! The row models are index lists ([`RowMask`](crate::RowMask), Blender's+//! `IndexMask`): sorting, filtering and paging never copy a row, and a+//! sort uses the table core's typed keys. The painted cells come from+//! [`Table`]'s [`CellSource`](crate::CellSource) (the current page), so the+//! table stays O(visible cells) whatever the row count. A shadcn+//! `cell: ({ row }) => <JSX/>` is a [`CellRender`](crate::CellRender): the+//! closest typed equivalent.++mod column;+mod state;+mod table;++pub use column::{actions_column, select_column, ColumnDef, ColumnMeta, Header, Record};+pub use state::{+ Change, ColumnFilter, ColumnFiltersState, PaginationState, PartialState, RowSelectionState, SortingRule, SortingState, TableState,+ VisibilityState,+};+pub use table::{ColumnInfo, Table, TableError, TableOptions};diff --git a/bindings/rust/blenderui-table/src/tanstack/state.rs b/bindings/rust/blenderui-table/src/tanstack/state.rsnew file mode 100644index 0000000..0c63e6a--- /dev/null+++ b/bindings/rust/blenderui-table/src/tanstack/state.rs@@ -0,0 +1,199 @@+//! TanStack's table state: the six pieces shadcn's Data Table uses.++use std::collections::BTreeMap;++use crate::column::Text;++/// One sorted column (`{ id, desc }`).+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct SortingRule {+ pub id: Text,+ pub desc: bool,+}++impl SortingRule {+ pub fn new(id: impl Into<Text>, desc: bool) -> Self {+ Self { id: id.into(), desc }+ }+}++/// `SortingState`: the sorted columns, the first one most significant.+pub type SortingState = Vec<SortingRule>;++/// One column filter (`{ id, value }`).+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct ColumnFilter {+ pub id: Text,+ pub value: String,+}++impl ColumnFilter {+ pub fn new(id: impl Into<Text>, value: impl Into<String>) -> Self {+ Self { id: id.into(), value: value.into() }+ }+}++/// `ColumnFiltersState`.+pub type ColumnFiltersState = Vec<ColumnFilter>;++/// `VisibilityState`: `false` hides a column; a column that is not listed+/// is visible.+pub type VisibilityState = BTreeMap<Text, bool>;++/// `PaginationState`.+#[derive(Copy, Clone, Debug, PartialEq, Eq)]+pub struct PaginationState {+ pub page_index: usize,+ pub page_size: usize,+}++impl Default for PaginationState {+ /// TanStack's default: page 0, ten rows.+ fn default() -> Self {+ Self { page_index: 0, page_size: 10 }+ }+}++/// `RowSelectionState`: the selected rows, by row id (the index of the row+/// in the data), as a bitset: selecting a million rows is 125 KB.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct RowSelectionState {+ words: Vec<u64>,+ count: usize,+}++impl RowSelectionState {+ /// How many rows are selected.+ #[must_use]+ pub const fn count(&self) -> usize {+ self.count+ }++ #[must_use]+ pub const fn is_empty(&self) -> bool {+ self.count == 0+ }++ #[must_use]+ pub fn is_selected(&self, id: usize) -> bool {+ self.words.get(id / 64).is_some_and(|w| w >> (id % 64) & 1 == 1)+ }++ /// Select or deselect row `id`. Returns whether it changed.+ pub fn set(&mut self, id: usize, on: bool) -> bool {+ if self.is_selected(id) == on {+ return false;+ }+ if on {+ if self.words.len() <= id / 64 {+ self.words.resize(id / 64 + 1, 0);+ }+ self.words[id / 64] |= 1 << (id % 64);+ self.count += 1;+ } else {+ self.words[id / 64] &= !(1 << (id % 64));+ self.count -= 1;+ while self.words.last() == Some(&0) {+ self.words.pop();+ }+ }+ true+ }++ /// Deselect everything.+ pub fn clear(&mut self) {+ self.words.clear();+ self.count = 0;+ }++ /// Select rows `0..n`.+ pub fn select_all(&mut self, n: usize) {+ self.clear();+ for id in 0..n {+ self.set(id, true);+ }+ }++ /// Drop selected rows at or after `n` (the data got shorter).+ pub fn clamp(&mut self, n: usize) {+ let ids: Vec<usize> = self.iter().filter(|&i| i >= n).collect();+ for id in ids {+ self.set(id, false);+ }+ }++ /// The selected row ids, ascending.+ pub fn iter(&self) -> impl Iterator<Item = usize> + '_ {+ self.words.iter().enumerate().flat_map(|(w, &bits)| {+ let mut rest = bits;+ std::iter::from_fn(move || {+ (rest != 0).then(|| {+ let b = rest.trailing_zeros() as usize;+ rest &= rest - 1;+ w * 64 + b+ })+ })+ })+ }+}++/// `TableState`: everything a user can change.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct TableState {+ pub sorting: SortingState,+ pub column_filters: ColumnFiltersState,+ pub global_filter: String,+ pub column_visibility: VisibilityState,+ pub row_selection: RowSelectionState,+ pub pagination: PaginationState,+}++/// The state a parent controls (TanStack's `state` option): a field that is+/// `Some` is owned by the parent; the table only reports changes to it+/// ([`Change`]) and shows what the parent passes back.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct PartialState {+ pub sorting: Option<SortingState>,+ pub column_filters: Option<ColumnFiltersState>,+ pub global_filter: Option<String>,+ pub column_visibility: Option<VisibilityState>,+ pub row_selection: Option<RowSelectionState>,+ pub pagination: Option<PaginationState>,+}++/// A state change the user made (the argument of `onSortingChange` and+/// friends). Raised whether or not the field is controlled.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Change {+ Sorting(SortingState),+ ColumnFilters(ColumnFiltersState),+ GlobalFilter(String),+ ColumnVisibility(VisibilityState),+ RowSelection(RowSelectionState),+ Pagination(PaginationState),+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn selection_bits() {+ let mut s = RowSelectionState::default();+ assert!(s.set(3, true) && s.set(130, true) && !s.set(3, true));+ assert_eq!(s.count(), 2);+ assert_eq!(s.iter().collect::<Vec<_>>(), vec![3, 130]);+ assert!(s.set(130, false));+ assert_eq!(s, {+ let mut t = RowSelectionState::default();+ t.set(3, true);+ t+ });+ s.select_all(70);+ assert_eq!(s.count(), 70);+ s.clamp(10);+ assert_eq!(s.count(), 10);+ s.clear();+ assert!(s.is_empty() && !s.is_selected(0));+ }+}diff --git a/bindings/rust/blenderui-table/src/tanstack/table.rs b/bindings/rust/blenderui-table/src/tanstack/table.rsnew file mode 100644index 0000000..015cbac--- /dev/null+++ b/bindings/rust/blenderui-table/src/tanstack/table.rs@@ -0,0 +1,844 @@+//! [`Table`]: TanStack's table instance. It owns the data, the columns and+//! the state, keeps the row models (index lists) up to date, and is the+//! [`CellSource`] of the current page.++use std::cmp::Ordering;+use std::fmt;+use std::sync::Arc;++use super::column::{Accessor, ColumnDef};+use super::state::{+ Change, ColumnFilter, ColumnFiltersState, PaginationState, PartialState, RowSelectionState, SortingRule, SortingState, TableState,+ VisibilityState,+};+use crate::cell::{Cell, CellSource, Check, SortKind};+use crate::column::{BadgeVariant, CellRender, Column, ColumnSort, Text};+use crate::fmt::CellBuf;+use crate::mask::RowMask;+use crate::sort::sorted_by_column;++/// What is wrong with a table's options, found when they are given (the+/// boundary): nothing later has to check again.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum TableError {+ /// An `accessor_key` names a field the row type does not have.+ UnknownKey(Text),+ /// Two columns have the same id.+ DuplicateId(Text),+ /// A page size of zero.+ ZeroPageSize,+ /// More rows than a row id (`u32`) can name.+ TooManyRows(usize),+}++impl fmt::Display for TableError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::UnknownKey(k) => write!(f, "accessor_key({k:?}): the row type has no such field"),+ Self::DuplicateId(i) => write!(f, "two columns have the id {i:?}"),+ Self::ZeroPageSize => f.write_str("the page size must be at least 1"),+ Self::TooManyRows(n) => write!(f, "{n} rows do not fit in a u32 row id"),+ }+ }+}++impl std::error::Error for TableError {}++/// TanStack's table options.+#[allow(clippy::struct_excessive_bools)]+pub struct TableOptions<T> {+ pub columns: Arc<[ColumnDef<T>]>,+ pub data: Arc<[T]>,+ /// `initialState`: where an uncontrolled field starts.+ pub initial_state: TableState,+ /// `state`: the fields the parent controls.+ pub state: PartialState,+ /// `getPaginationRowModel()`: show one page of the rows at a time.+ pub paginate: bool,+ /// `manualSorting`: the data arrives sorted (a server did it).+ pub manual_sorting: bool,+ /// `manualFiltering`: the data arrives filtered.+ pub manual_filtering: bool,+ /// `manualPagination`: the data is one page already; with `page_count`.+ pub manual_pagination: bool,+ /// `pageCount` (with `manual_pagination`).+ pub page_count: Option<usize>,+ /// `autoResetPageIndex`: go back to the first page when the sorting or+ /// filters change.+ pub auto_reset_page_index: bool,+}++impl<T> TableOptions<T> {+ /// Options for `columns` over `data` with TanStack's defaults.+ pub fn new(columns: impl Into<Arc<[ColumnDef<T>]>>, data: impl Into<Arc<[T]>>) -> Self {+ Self {+ columns: columns.into(),+ data: data.into(),+ initial_state: TableState::default(),+ state: PartialState::default(),+ paginate: false,+ manual_sorting: false,+ manual_filtering: false,+ manual_pagination: false,+ page_count: None,+ auto_reset_page_index: true,+ }+ }++ /// Show one page at a time (`getPaginationRowModel`).+ #[must_use]+ pub const fn paginate(mut self, on: bool) -> Self {+ self.paginate = on;+ self+ }++ #[must_use]+ pub fn initial_state(mut self, state: TableState) -> Self {+ self.initial_state = state;+ self+ }++ /// The controlled state.+ #[must_use]+ pub fn state(mut self, state: PartialState) -> Self {+ self.state = state;+ self+ }+}++/// What the UI needs to know about a column (header menus, the view-options+/// dropdown).+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct ColumnInfo {+ pub id: Text,+ pub title: Text,+ pub can_sort: bool,+ pub can_hide: bool,+ pub visible: bool,+ pub sort: ColumnSort,+}++/// Pieces of the row models, in the order they depend on each other.+#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]+enum Stage {+ Filter,+ Sort,+ Page,+ Selection,+}++/// TanStack's table instance over `data`.+pub struct Table<T> {+ columns: Arc<[ColumnDef<T>]>,+ data: Arc<[T]>,+ flags: Flags,+ internal: TableState,+ controlled: PartialState,+ changes: Vec<Change>,+ filtered: RowMask,+ sorted: RowMask,+ page: Vec<u32>,+ filtered_selected: usize,+ dirty: bool,+}++#[derive(Copy, Clone)]+#[allow(clippy::struct_excessive_bools)]+struct Flags {+ paginate: bool,+ manual_sorting: bool,+ manual_filtering: bool,+ manual_pagination: bool,+ page_count: Option<usize>,+ auto_reset_page_index: bool,+}++impl<T: Send + Sync> Table<T> {+ /// A table, or what is wrong with the options.+ pub fn new(opts: TableOptions<T>) -> Result<Self, TableError> {+ let TableOptions { columns, data, initial_state, state, paginate, manual_sorting, manual_filtering, manual_pagination, page_count, auto_reset_page_index } =+ opts;+ validate(&columns, data.len(), initial_state.pagination, &state)?;+ let mut t = Self {+ columns,+ data,+ flags: Flags { paginate, manual_sorting, manual_filtering, manual_pagination, page_count, auto_reset_page_index },+ internal: initial_state,+ controlled: state,+ changes: Vec::new(),+ filtered: RowMask::Identity,+ sorted: RowMask::Identity,+ page: Vec::new(),+ filtered_selected: 0,+ dirty: true,+ };+ t.recompute(Stage::Filter);+ Ok(t)+ }++ /// Take new options (a parent re-rendered): data and columns are+ /// compared by identity (`Arc::ptr_eq`, like TanStack's memoized+ /// references), the controlled state by value. Returns whether anything+ /// the view shows changed.+ pub fn set_options(&mut self, opts: TableOptions<T>) -> Result<bool, TableError> {+ let TableOptions { columns, data, state, paginate, manual_sorting, manual_filtering, manual_pagination, page_count, auto_reset_page_index, initial_state: _ } = opts;+ let pagination = state.pagination.unwrap_or_else(|| *self.pagination());+ validate(&columns, data.len(), pagination, &state)?;+ let flags = Flags { paginate, manual_sorting, manual_filtering, manual_pagination, page_count, auto_reset_page_index };+ let mut from = None;+ let mut note = |s: Stage| from = Some(from.map_or(s, |f: Stage| f.min(s)));+ if !Arc::ptr_eq(&self.columns, &columns) {+ self.columns = columns;+ note(Stage::Filter);+ }+ if !Arc::ptr_eq(&self.data, &data) {+ self.data = data;+ self.internal.row_selection.clamp(self.data.len());+ note(Stage::Filter);+ }+ if state != self.controlled {+ let old = std::mem::replace(&mut self.controlled, state);+ note(if old.column_filters != self.controlled.column_filters || old.global_filter != self.controlled.global_filter {+ Stage::Filter+ } else if old.sorting != self.controlled.sorting {+ Stage::Sort+ } else if old.pagination != self.controlled.pagination {+ Stage::Page+ } else {+ Stage::Selection+ });+ }+ if (flags.paginate, flags.manual_sorting, flags.manual_filtering, flags.manual_pagination, flags.page_count)+ != (self.flags.paginate, self.flags.manual_sorting, self.flags.manual_filtering, self.flags.manual_pagination, self.flags.page_count)+ {+ note(Stage::Filter);+ }+ self.flags = flags;+ Ok(from.is_some_and(|s| {+ self.recompute(s);+ true+ }))+ }++ // -- state ---------------------------------------------------------------------------------------++ /// The state as shown: the controlled fields over the internal ones.+ #[must_use]+ pub fn state(&self) -> TableState {+ TableState {+ sorting: self.sorting().clone(),+ column_filters: self.column_filters().clone(),+ global_filter: self.global_filter().to_owned(),+ column_visibility: self.column_visibility().clone(),+ row_selection: self.row_selection().clone(),+ pagination: *self.pagination(),+ }+ }++ #[must_use]+ pub fn sorting(&self) -> &SortingState {+ self.controlled.sorting.as_ref().unwrap_or(&self.internal.sorting)+ }++ #[must_use]+ pub fn column_filters(&self) -> &ColumnFiltersState {+ self.controlled.column_filters.as_ref().unwrap_or(&self.internal.column_filters)+ }++ #[must_use]+ pub fn global_filter(&self) -> &str {+ self.controlled.global_filter.as_deref().unwrap_or(&self.internal.global_filter)+ }++ #[must_use]+ pub fn column_visibility(&self) -> &VisibilityState {+ self.controlled.column_visibility.as_ref().unwrap_or(&self.internal.column_visibility)+ }++ #[must_use]+ pub fn row_selection(&self) -> &RowSelectionState {+ self.controlled.row_selection.as_ref().unwrap_or(&self.internal.row_selection)+ }++ #[must_use]+ pub fn pagination(&self) -> &PaginationState {+ self.controlled.pagination.as_ref().unwrap_or(&self.internal.pagination)+ }++ /// The changes the user made since the last call, in order (what the+ /// `onXChange` callbacks receive).+ pub fn take_changes(&mut self) -> Vec<Change> {+ std::mem::take(&mut self.changes)+ }++ /// Whether the view needs to redraw; clears the flag.+ pub const fn take_dirty(&mut self) -> bool {+ std::mem::replace(&mut self.dirty, false)+ }++ // -- setters (`setSorting`, `setPageIndex` ...): apply to an uncontrolled field, always report --------++ /// `setSorting`.+ pub fn set_sorting(&mut self, sorting: SortingState) {+ if sorting == *self.sorting() {+ return;+ }+ self.changes.push(Change::Sorting(sorting.clone()));+ if self.controlled.sorting.is_none() {+ self.internal.sorting = sorting;+ self.reset_page_index();+ self.recompute(Stage::Sort);+ }+ }++ /// `setColumnFilters`.+ pub fn set_column_filters(&mut self, filters: ColumnFiltersState) {+ if filters == *self.column_filters() {+ return;+ }+ self.changes.push(Change::ColumnFilters(filters.clone()));+ if self.controlled.column_filters.is_none() {+ self.internal.column_filters = filters;+ self.reset_page_index();+ self.recompute(Stage::Filter);+ }+ }++ /// `setGlobalFilter`.+ pub fn set_global_filter(&mut self, value: impl Into<String>) {+ let value = value.into();+ if value == self.global_filter() {+ return;+ }+ self.changes.push(Change::GlobalFilter(value.clone()));+ if self.controlled.global_filter.is_none() {+ self.internal.global_filter = value;+ self.reset_page_index();+ self.recompute(Stage::Filter);+ }+ }++ /// `setColumnVisibility`.+ pub fn set_column_visibility(&mut self, visibility: VisibilityState) {+ if visibility == *self.column_visibility() {+ return;+ }+ self.changes.push(Change::ColumnVisibility(visibility.clone()));+ if self.controlled.column_visibility.is_none() {+ self.internal.column_visibility = visibility;+ self.dirty = true;+ }+ }++ /// `setRowSelection`.+ pub fn set_row_selection(&mut self, selection: RowSelectionState) {+ if selection == *self.row_selection() {+ return;+ }+ self.changes.push(Change::RowSelection(selection.clone()));+ if self.controlled.row_selection.is_none() {+ self.internal.row_selection = selection;+ self.recompute(Stage::Selection);+ }+ }++ /// `setPagination`.+ pub fn set_pagination(&mut self, pagination: PaginationState) {+ let pagination = PaginationState { page_size: pagination.page_size.max(1), ..pagination };+ if pagination == *self.pagination() {+ return;+ }+ self.changes.push(Change::Pagination(pagination));+ if self.controlled.pagination.is_none() {+ self.internal.pagination = pagination;+ self.recompute(Stage::Page);+ }+ }++ fn reset_page_index(&mut self) {+ if self.flags.auto_reset_page_index && !self.flags.manual_pagination && self.pagination().page_index != 0 {+ self.set_pagination(PaginationState { page_index: 0, ..*self.pagination() });+ }+ }++ // -- columns ----------------------------------------------------------------------------------------++ /// `getAllColumns`.+ #[must_use]+ pub fn column_defs(&self) -> &[ColumnDef<T>] {+ &self.columns+ }++ /// The index of the column `id`.+ #[must_use]+ pub fn column_index(&self, id: &str) -> Option<usize> {+ self.columns.iter().position(|c| c.id == id)+ }++ /// `column.getIsVisible()`.+ #[must_use]+ pub fn column_is_visible(&self, id: &str) -> bool {+ self.column_visibility().get(id).copied().unwrap_or(true)+ }++ /// `column.toggleVisibility(value)`; `None` flips it. Columns with+ /// `enable_hiding` off ignore it.+ pub fn toggle_column_visibility(&mut self, id: &str, visible: Option<bool>) {+ let Some(def) = self.columns.iter().find(|c| c.id == id) else { return };+ if !def.enable_hiding {+ return;+ }+ let want = visible.unwrap_or_else(|| !self.column_is_visible(id));+ let mut v = self.column_visibility().clone();+ v.insert(def.id.clone(), want);+ self.set_column_visibility(v);+ }++ /// `table.toggleAllColumnsVisible(value)`.+ pub fn toggle_all_columns_visible(&mut self, visible: bool) {+ let mut v = self.column_visibility().clone();+ for c in self.columns.iter().filter(|c| c.enable_hiding) {+ v.insert(c.id.clone(), visible);+ }+ self.set_column_visibility(v);+ }++ /// `column.getIsSorted()`.+ #[must_use]+ pub fn column_sort(&self, id: &str) -> ColumnSort {+ self.sorting().iter().find(|r| r.id == id).map_or(ColumnSort::Default, |r| if r.desc { ColumnSort::Descending } else { ColumnSort::Ascending })+ }++ /// `column.toggleSorting(desc)` for one column, replacing other sorting+ /// (`multi` off): `Some(false)` ascending, `Some(true)` descending,+ /// `None` cycles ascending, descending, none (the header click).+ pub fn toggle_column_sorting(&mut self, id: &str, desc: Option<bool>) {+ let Some(def) = self.columns.iter().find(|c| c.id == id) else { return };+ if !def.enable_sorting {+ return;+ }+ let next = match desc {+ Some(d) => ColumnSort::from_desc(d),+ None => self.column_sort(id).next(),+ };+ self.set_column_sort(id, next);+ }++ /// Sort by `id` alone in direction `sort` (`Default` clears the sorting).+ pub fn set_column_sort(&mut self, id: &str, sort: ColumnSort) {+ let Some(def) = self.columns.iter().find(|c| c.id == id) else { return };+ let v: SortingState = match sort {+ ColumnSort::Default => Vec::new(),+ s => vec![SortingRule::new(def.id.clone(), s == ColumnSort::Descending)],+ };+ self.set_sorting(v);+ }++ /// `column.setFilterValue`: an empty value clears the filter.+ pub fn set_column_filter_value(&mut self, id: &str, value: impl Into<String>) {+ let Some(def) = self.columns.iter().find(|c| c.id == id) else { return };+ if !def.enable_column_filter {+ return;+ }+ let value = value.into();+ let mut f: ColumnFiltersState = self.column_filters().iter().filter(|f| f.id != id).cloned().collect();+ if !value.is_empty() {+ f.push(ColumnFilter::new(def.id.clone(), value));+ }+ self.set_column_filters(f);+ }++ /// `column.getFilterValue()`.+ #[must_use]+ pub fn column_filter_value(&self, id: &str) -> Option<&str> {+ self.column_filters().iter().find(|f| f.id == id).map(|f| f.value.as_str())+ }++ /// The columns as the UI lists them.+ #[must_use]+ pub fn column_infos(&self) -> Vec<ColumnInfo> {+ self.columns+ .iter()+ .map(|c| ColumnInfo {+ id: c.id.clone(),+ title: Text::Owned(c.header.title().to_owned()),+ can_sort: c.enable_sorting,+ can_hide: c.enable_hiding,+ visible: self.column_is_visible(&c.id),+ sort: self.column_sort(&c.id),+ })+ .collect()+ }++ /// Column `ix` as the table core draws it: a hidden one is flagged+ /// invisible, so every column keeps its index.+ #[must_use]+ pub fn core_column(&self, ix: usize) -> Column {+ let d = &self.columns[ix];+ let mut c = Column::new(d.id.clone(), Text::Owned(d.header.title().to_owned())).width(d.size).min_width(d.min_size).max_width(d.max_size);+ c.align = d.meta.align;+ c.format = d.meta.format.clone();+ c.render = d.cell;+ c.header_menu = matches!(d.header, super::column::Header::Menu(_)) && d.enable_sorting;+ c.resizable = d.enable_resizing;+ c.movable = false;+ c.selectable = false;+ c.visible = self.column_is_visible(&d.id);+ if d.meta.pinned {+ c = c.fixed_left();+ }+ if d.enable_sorting {+ c.sort = Some(self.column_sort(&d.id));+ }+ c+ }++ /// All columns as the table core draws them.+ #[must_use]+ pub fn core_columns(&self) -> Vec<Column> {+ (0..self.columns.len()).map(|i| self.core_column(i)).collect()+ }++ // -- row models ---------------------------------------------------------------------------------------++ /// `getCoreRowModel`: every row of the data, in order.+ #[must_use]+ pub const fn core_row_model(&self) -> RowMask {+ RowMask::Identity+ }++ /// `getFilteredRowModel`.+ #[must_use]+ pub const fn filtered_row_model(&self) -> &RowMask {+ &self.filtered+ }++ /// `getSortedRowModel`: the filtered rows, sorted.+ #[must_use]+ pub const fn sorted_row_model(&self) -> &RowMask {+ &self.sorted+ }++ /// `getRowModel` (`getPaginationRowModel` when paging): the data rows of the current page.+ #[must_use]+ pub fn row_model(&self) -> &[u32] {+ &self.page+ }++ /// The data row shown at page row `r`.+ #[must_use]+ pub fn data_row(&self, r: usize) -> Option<usize> {+ self.page.get(r).map(|&d| d as usize)+ }++ /// The data (`table.options.data`).+ #[must_use]+ pub fn data(&self) -> &[T] {+ &self.data+ }++ /// `getPrePaginationRowModel().rows.length`: the rows after filtering.+ #[must_use]+ pub fn row_count(&self) -> usize {+ self.sorted.len(self.data.len())+ }++ /// `getCoreRowModel().rows.length`.+ #[must_use]+ pub fn core_row_count(&self) -> usize {+ self.data.len()+ }++ /// `getFilteredRowModel().rows.length`.+ #[must_use]+ pub fn filtered_row_count(&self) -> usize {+ self.filtered.len(self.data.len())+ }++ // -- pagination ---------------------------------------------------------------------------------------++ /// `getPageCount`.+ #[must_use]+ pub fn page_count(&self) -> usize {+ if self.flags.manual_pagination {+ return self.flags.page_count.unwrap_or(1);+ }+ if !self.flags.paginate {+ return 1;+ }+ self.row_count().div_ceil(self.pagination().page_size)+ }++ #[must_use]+ pub fn can_previous_page(&self) -> bool {+ self.pagination().page_index > 0+ }++ #[must_use]+ pub fn can_next_page(&self) -> bool {+ self.pagination().page_index + 1 < self.page_count()+ }++ /// `setPageIndex`, clamped to the pages there are.+ pub fn set_page_index(&mut self, index: usize) {+ let last = self.page_count().saturating_sub(1);+ self.set_pagination(PaginationState { page_index: index.min(last), ..*self.pagination() });+ }++ pub fn first_page(&mut self) {+ self.set_page_index(0);+ }++ pub fn previous_page(&mut self) {+ self.set_page_index(self.pagination().page_index.saturating_sub(1));+ }++ pub fn next_page(&mut self) {+ self.set_page_index(self.pagination().page_index + 1);+ }++ pub fn last_page(&mut self) {+ self.set_page_index(self.page_count().saturating_sub(1));+ }++ /// `setPageSize`: keeps the first row of the page in view.+ pub fn set_page_size(&mut self, size: usize) {+ let size = size.max(1);+ let p = *self.pagination();+ let top = p.page_index * p.page_size;+ self.set_pagination(PaginationState { page_index: top / size, page_size: size });+ }++ // -- selection -----------------------------------------------------------------------------------------++ /// `row.getIsSelected()`.+ #[must_use]+ pub fn is_row_selected(&self, data_row: usize) -> bool {+ self.row_selection().is_selected(data_row)+ }++ /// `row.toggleSelected(value)`; `None` flips it.+ pub fn toggle_row_selected(&mut self, data_row: usize, selected: Option<bool>) {+ if data_row >= self.data.len() {+ return;+ }+ let mut s = self.row_selection().clone();+ s.set(data_row, selected.unwrap_or_else(|| !s.is_selected(data_row)));+ self.set_row_selection(s);+ }++ /// `getFilteredSelectedRowModel().rows.length`.+ #[must_use]+ pub const fn filtered_selected_row_count(&self) -> usize {+ self.filtered_selected+ }++ /// `getIsAllPageRowsSelected`.+ #[must_use]+ pub fn is_all_page_rows_selected(&self) -> bool {+ !self.page.is_empty() && self.page.iter().all(|&r| self.is_row_selected(r as usize))+ }++ /// `getIsSomePageRowsSelected`.+ #[must_use]+ pub fn is_some_page_rows_selected(&self) -> bool {+ !self.is_all_page_rows_selected() && self.page.iter().any(|&r| self.is_row_selected(r as usize))+ }++ /// `toggleAllPageRowsSelected(value)`.+ pub fn toggle_all_page_rows_selected(&mut self, selected: bool) {+ let mut s = self.row_selection().clone();+ for &r in &self.page {+ s.set(r as usize, selected);+ }+ self.set_row_selection(s);+ }++ /// `toggleAllRowsSelected(value)`: every row of the data.+ pub fn toggle_all_rows_selected(&mut self, selected: bool) {+ let mut s = RowSelectionState::default();+ if selected {+ s.select_all(self.data.len());+ }+ self.set_row_selection(s);+ }++ /// `getSelectedRowModel().rows`: the selected rows of the data.+ #[must_use]+ pub fn selected_rows(&self) -> Vec<&T> {+ self.row_selection().iter().filter_map(|i| self.data.get(i)).collect()+ }++ // -- recomputing ----------------------------------------------------------------------------------------++ fn recompute(&mut self, from: Stage) {+ self.dirty = true;+ let n = self.data.len();+ let grid = Grid { columns: &self.columns, data: &self.data };+ if from <= Stage::Filter {+ self.filtered = if self.flags.manual_filtering { RowMask::Identity } else { filter_rows(&grid, self.column_filters(), self.global_filter()) };+ }+ if from <= Stage::Sort {+ self.sorted = if self.flags.manual_sorting { self.filtered.clone() } else { sort_rows(&grid, self.sorting(), &self.filtered) };+ }+ if from <= Stage::Page {+ let total = self.sorted.len(n);+ let (start, end) = if self.flags.paginate && !self.flags.manual_pagination {+ let p = self.pagination();+ let start = p.page_index.saturating_mul(p.page_size).min(total);+ (start, (start + p.page_size).min(total))+ } else {+ (0, total)+ };+ let sorted = &self.sorted;+ self.page.clear();+ self.page.extend((start..end).map(|i| sorted.get(i) as u32));+ }+ // the selected rows among the filtered ones (`getFilteredSelectedRowModel`)+ self.filtered_selected = match &self.filtered {+ RowMask::Identity => self.row_selection().iter().filter(|&i| i < n).count(),+ RowMask::Indices(v) => {+ let sel = self.row_selection();+ v.iter().filter(|&&r| sel.is_selected(r as usize)).count()+ }+ };+ }+}++fn validate<T>(columns: &[ColumnDef<T>], rows: usize, pagination: PaginationState, state: &PartialState) -> Result<(), TableError> {+ if rows > u32::MAX as usize {+ return Err(TableError::TooManyRows(rows));+ }+ if pagination.page_size == 0 || state.pagination.is_some_and(|p| p.page_size == 0) {+ return Err(TableError::ZeroPageSize);+ }+ for (i, c) in columns.iter().enumerate() {+ if let Accessor::Missing(k) = &c.accessor {+ return Err(TableError::UnknownKey(k.clone()));+ }+ if columns[..i].iter().any(|o| o.id == c.id) {+ return Err(TableError::DuplicateId(c.id.clone()));+ }+ }+ Ok(())+}++impl ColumnSort {+ const fn from_desc(desc: bool) -> Self {+ if desc { Self::Descending } else { Self::Ascending }+ }+}++// -- the data rows as a CellSource (what sorting and filtering read) --------------------------------------------++/// The data rows: `cell(row, col)` is the value of data row `row`.+struct Grid<'a, T> {+ columns: &'a [ColumnDef<T>],+ data: &'a [T],+}++impl<T: Send + Sync> CellSource for Grid<'_, T> {+ fn cell(&self, row: usize, col: usize) -> Cell<'_> {+ match (self.data.get(row), self.columns.get(col)) {+ (Some(r), Some(c)) => c.read(r),+ _ => Cell::Empty,+ }+ }++ fn sort_kind(&self, _: usize) -> SortKind {+ SortKind::Cells+ }+}++fn contains_ignore_case(hay: &str, needle_lower: &str) -> bool {+ if needle_lower.is_empty() {+ return true;+ }+ if hay.is_ascii() && needle_lower.is_ascii() {+ let (h, n) = (hay.as_bytes(), needle_lower.as_bytes());+ return h.len() >= n.len() && h.windows(n.len()).any(|w| w.eq_ignore_ascii_case(n));+ }+ hay.to_lowercase().contains(needle_lower)+}++/// The rows passing every column filter and the global filter+/// (`includesString`: case-insensitive contains, on the cell's text).+fn filter_rows<T: Send + Sync>(grid: &Grid<'_, T>, filters: &[ColumnFilter], global: &str) -> RowMask {+ let cols: Vec<(usize, String)> = filters+ .iter()+ .filter_map(|f| grid.columns.iter().position(|c| c.id == f.id && c.enable_column_filter).map(|i| (i, f.value.to_lowercase())))+ .collect();+ let global = global.to_lowercase();+ if cols.is_empty() && global.is_empty() {+ return RowMask::Identity;+ }+ let global_cols: Vec<usize> = if global.is_empty() {+ Vec::new()+ } else {+ grid.columns.iter().enumerate().filter(|(_, c)| c.enable_global_filter && c.has_accessor()).map(|(i, _)| i).collect()+ };+ let text_has = |row: usize, col: usize, needle: &str| {+ let mut buf = CellBuf::new();+ let cell = grid.cell(row, col);+ contains_ignore_case(cell.text(&mut buf), needle)+ };+ RowMask::Identity.filtered(grid.data.len(), |r| {+ cols.iter().all(|(c, v)| text_has(r, *c, v)) && (global.is_empty() || global_cols.iter().any(|&c| text_has(r, c, &global)))+ })+}++/// `base` sorted by every rule: the last rule first, then the earlier ones+/// stably on top, so the first rule is the most significant.+fn sort_rows<T: Send + Sync>(grid: &Grid<'_, T>, rules: &[SortingRule], base: &RowMask) -> RowMask {+ let n = grid.data.len();+ let mut mask: Option<RowMask> = None;+ for r in rules.iter().rev() {+ let Some(col) = grid.columns.iter().position(|c| c.id == r.id && c.enable_sorting) else { continue };+ mask = Some(sorted_by_column(grid, col, mask.as_ref().unwrap_or(base), n, r.desc));+ }+ mask.unwrap_or_else(|| base.clone())+}++// -- the current page as a CellSource (what the table paints) -------------------------------------------------------++impl<T: Send + Sync> CellSource for Table<T> {+ fn cell(&self, row: usize, col: usize) -> Cell<'_> {+ let (Some(&data_row), Some(def)) = (self.page.get(row), self.columns.get(col)) else { return Cell::Empty };+ match def.accessor {+ Accessor::Read(_) => def.read(&self.data[data_row as usize]),+ _ if def.cell == CellRender::Checkbox => Cell::U64(u64::from(self.is_row_selected(data_row as usize))),+ _ => Cell::Empty,+ }+ }++ fn sort_kind(&self, _: usize) -> SortKind {+ SortKind::Cells+ }++ fn compare(&self, _: usize, _: usize, _: usize) -> Ordering {+ Ordering::Equal+ }++ fn badge(&self, row: usize, col: usize) -> BadgeVariant {+ let (Some(def), true) = (self.columns.get(col), row < self.page.len()) else { return BadgeVariant::default() };+ let Some(f) = &def.badge else { return BadgeVariant::default() };+ let mut buf = CellBuf::new();+ let cell = self.cell(row, col);+ f(cell.text(&mut buf))+ }++ fn header_check(&self, col: usize) -> Check {+ if self.columns.get(col).is_none_or(|c| c.cell != CellRender::Checkbox) {+ Check::Unchecked+ } else if self.is_all_page_rows_selected() {+ Check::Checked+ } else if self.is_some_page_rows_selected() {+ Check::Indeterminate+ } else {+ Check::Unchecked+ }+ }+}++#[cfg(test)]+mod tests;diff --git a/bindings/rust/blenderui-table/src/tanstack/table/tests.rs b/bindings/rust/blenderui-table/src/tanstack/table/tests.rsnew file mode 100644index 0000000..424b4f4--- /dev/null+++ b/bindings/rust/blenderui-table/src/tanstack/table/tests.rs@@ -0,0 +1,212 @@+use std::sync::Arc;++use super::*;+use crate::tanstack::{actions_column, select_column, ColumnMeta, Header, Record};++struct Person {+ name: String,+ age: u64,+ city: String,+}++impl Record for Person {+ const FIELDS: &'static [&'static str] = &["name", "age", "city"];+ fn field(&self, field: usize) -> Cell<'_> {+ match field {+ 0 => Cell::Str(&self.name),+ 1 => Cell::U64(self.age),+ _ => Cell::Str(&self.city),+ }+ }+}++fn people(n: usize) -> Arc<[Person]> {+ const CITIES: [&str; 4] = ["Paris", "Oslo", "Lima", "Kyoto"];+ (0..n).map(|i| Person { name: format!("user{:03}", (i * 37) % 1000), age: 20 + (i as u64 * 7) % 50, city: CITIES[i % 4].to_owned() }).collect()+}++fn columns() -> Arc<[ColumnDef<Person>]> {+ vec![+ select_column(),+ ColumnDef::accessor_key("name").header(Header::menu("Name")),+ ColumnDef::accessor_key("age").meta(ColumnMeta::right()),+ ColumnDef::accessor_key("city"),+ actions_column(),+ ]+ .into()+}++fn table(n: usize) -> Table<Person> {+ Table::new(TableOptions::new(columns(), people(n)).paginate(true)).unwrap()+}++fn page_ages(t: &Table<Person>) -> Vec<u64> {+ t.row_model().iter().map(|&r| t.data()[r as usize].age).collect()+}++#[test]+fn options_are_validated_at_the_boundary() {+ let bad: Arc<[ColumnDef<Person>]> = vec![ColumnDef::<Person>::accessor_key("nope")].into();+ assert_eq!(Table::new(TableOptions::new(bad, people(1))).err(), Some(TableError::UnknownKey("nope".into())));+ let dup: Arc<[ColumnDef<Person>]> = vec![ColumnDef::<Person>::accessor_key("age"), ColumnDef::accessor_key("age")].into();+ assert_eq!(Table::new(TableOptions::new(dup, people(1))).err(), Some(TableError::DuplicateId("age".into())));+ let mut o = TableOptions::new(columns(), people(1));+ o.initial_state.pagination.page_size = 0;+ assert_eq!(Table::new(o).err(), Some(TableError::ZeroPageSize));+}++#[test]+fn row_models_follow_tanstack() {+ let mut t = table(95);+ assert_eq!((t.core_row_count(), t.filtered_row_count(), t.row_count()), (95, 95, 95));+ assert_eq!(t.row_model().len(), 10);+ assert_eq!(t.page_count(), 10);+ t.set_column_filter_value("city", "KYO");+ assert_eq!(t.filtered_row_count(), 23); // Kyoto: 23 of 95+ assert_eq!(t.page_count(), 3);+ assert!(t.row_model().iter().all(|&r| t.data()[r as usize].city == "Kyoto"));+ t.set_column_filter_value("city", "");+ assert_eq!(t.filtered_row_count(), 95);+ t.set_global_filter("PARIS");+ assert_eq!(t.row_count(), 24);+ t.set_global_filter("");+ t.set_global_filter("user0");+ assert!(t.row_count() > 0 && t.row_count() < 95);+ assert!(matches!(t.core_row_model(), RowMask::Identity));+}++#[test]+fn sorting_single_multi_and_cycling() {+ let mut t = table(40);+ t.toggle_column_sorting("age", None);+ assert_eq!(t.column_sort("age"), ColumnSort::Ascending);+ assert!(page_ages(&t).windows(2).all(|w| w[0] <= w[1]));+ t.toggle_column_sorting("age", None);+ assert_eq!(t.column_sort("age"), ColumnSort::Descending);+ assert!(page_ages(&t).windows(2).all(|w| w[0] >= w[1]));+ t.toggle_column_sorting("age", None);+ assert_eq!(t.column_sort("age"), ColumnSort::Default);+ assert!(t.sorting().is_empty());+ // city, then age descending inside each city+ t.set_sorting(vec![SortingRule::new("city", false), SortingRule::new("age", true)]);+ t.set_page_size(40);+ let rows: Vec<(&str, u64)> = t.row_model().iter().map(|&r| (t.data()[r as usize].city.as_str(), t.data()[r as usize].age)).collect();+ assert!(rows.windows(2).all(|w| w[0].0 < w[1].0 || (w[0].0 == w[1].0 && w[0].1 >= w[1].1)), "{rows:?}");+ // a column with sorting disabled ignores the toggle+ t.toggle_column_sorting("select", None);+ assert_eq!(t.sorting().len(), 2);+}++#[test]+fn pagination_clamps_and_resets() {+ let mut t = table(95);+ t.next_page();+ t.last_page();+ assert_eq!(t.pagination().page_index, 9);+ assert_eq!(t.row_model().len(), 5);+ assert!(!t.can_next_page() && t.can_previous_page());+ t.next_page();+ assert_eq!(t.pagination().page_index, 9, "clamped");+ t.set_page_size(50);+ assert_eq!((t.pagination().page_index, t.page_count()), (1, 2), "the first row of the page stays in view");+ t.set_column_filter_value("city", "oslo");+ assert_eq!(t.pagination().page_index, 0, "autoResetPageIndex");+ t.first_page();+ t.previous_page();+ assert_eq!(t.pagination().page_index, 0);+ let o = TableOptions::new(columns(), people(0)).paginate(true);+ assert_eq!(Table::new(o).unwrap().page_count(), 0, "no rows, no pages");+}++#[test]+fn selection_across_pages_and_filters() {+ let mut t = table(30);+ assert!(!t.is_all_page_rows_selected() && !t.is_some_page_rows_selected());+ t.toggle_row_selected(3, None);+ assert!(t.is_some_page_rows_selected());+ t.toggle_all_page_rows_selected(true);+ assert!(t.is_all_page_rows_selected());+ assert_eq!(t.row_selection().count(), 10);+ t.next_page();+ assert!(!t.is_some_page_rows_selected(), "selection is by row, not by position");+ t.toggle_all_rows_selected(true);+ assert_eq!((t.filtered_selected_row_count(), t.selected_rows().len()), (30, 30));+ t.set_column_filter_value("city", "paris");+ assert_eq!(t.filtered_selected_row_count(), t.filtered_row_count());+ assert_eq!(t.row_selection().count(), 30, "the selection outlives the filter");+ // the checkbox column reads the selection+ t.set_column_filter_value("city", "");+ t.toggle_all_rows_selected(false);+ t.toggle_row_selected(t.data_row(2).unwrap(), Some(true));+ assert_eq!(t.cell(2, 0), Cell::U64(1));+ assert_eq!(t.cell(1, 0), Cell::U64(0));+ assert_eq!(t.header_check(0), Check::Indeterminate);+ t.toggle_all_page_rows_selected(true);+ assert_eq!(t.header_check(0), Check::Checked);+ assert_eq!(t.header_check(1), Check::Unchecked);+}++#[test]+fn visibility_flags_the_core_columns() {+ let mut t = table(5);+ t.toggle_column_visibility("city", Some(false));+ t.toggle_column_visibility("select", Some(false)); // enable_hiding is off+ let cols = t.core_columns();+ assert_eq!(cols.iter().map(|c| c.visible).collect::<Vec<_>>(), vec![true, true, true, false, true]);+ t.toggle_column_visibility("city", None);+ assert!(t.column_is_visible("city"));+ t.toggle_all_columns_visible(false);+ assert_eq!(t.core_columns().iter().filter(|c| c.visible).count(), 2, "select and actions stay");+ assert!(t.column_infos().iter().any(|c| c.id == "name" && !c.visible && c.can_sort));+}++#[test]+fn controlled_and_uncontrolled_state() {+ // uncontrolled: applied and reported+ let mut t = table(40);+ t.set_page_index(2);+ assert_eq!(t.pagination().page_index, 2);+ assert_eq!(t.take_changes(), vec![Change::Pagination(PaginationState { page_index: 2, page_size: 10 })]);+ // controlled: reported, not applied, until the parent passes it back+ let (cols, data) = (columns(), people(40));+ let controlled = |sorting: SortingState| PartialState {+ sorting: Some(sorting),+ pagination: Some(PaginationState { page_index: 1, page_size: 10 }),+ ..PartialState::default()+ };+ let mut t = Table::new(TableOptions::new(Arc::clone(&cols), Arc::clone(&data)).paginate(true).state(controlled(Vec::new()))).unwrap();+ assert_eq!(t.pagination().page_index, 1);+ t.toggle_column_sorting("age", None);+ assert!(t.sorting().is_empty(), "the parent owns the sorting");+ assert_eq!(t.take_changes(), vec![Change::Sorting(vec![SortingRule::new("age", false)])]);+ let sorted = controlled(vec![SortingRule::new("age", false)]);+ assert!(t.set_options(TableOptions::new(Arc::clone(&cols), Arc::clone(&data)).paginate(true).state(sorted.clone())).unwrap(), "the new controlled value is shown");+ assert_eq!(t.column_sort("age"), ColumnSort::Ascending);+ assert!(page_ages(&t).windows(2).all(|w| w[0] <= w[1]));+ // identical options change nothing+ assert!(!t.set_options(TableOptions::new(cols, data).paginate(true).state(sorted)).unwrap());+}++#[test]+fn page_cells_use_the_core_kinds() {+ let t = table(12);+ let cols = t.core_columns();+ assert_eq!(cols[0].render, CellRender::Checkbox);+ assert!(cols[1].header_menu && !cols[2].header_menu);+ assert_eq!(cols[2].align, crate::column::TextAlign::Right);+ assert_eq!(t.cell(0, 2), Cell::U64(t.data()[0].age));+ assert_eq!(t.cell(0, 4), Cell::Empty);+ assert_eq!(t.cell(99, 1), Cell::Empty);+}++#[test]+fn a_million_rows_sort_and_page_without_copying_rows() {+ let n = 1_000_000;+ let mut t = Table::new(TableOptions::new(columns(), people(n)).paginate(true)).unwrap();+ t.toggle_column_sorting("age", Some(true));+ assert_eq!(t.row_count(), n);+ assert_eq!(t.row_model().len(), 10, "only a page is materialised");+ assert!(page_ages(&t).iter().all(|&a| a == 69));+ t.last_page();+ assert_eq!(t.pagination().page_index, n / 10 - 1);+}diff --git a/bindings/rust/blenderui-vlist/src/estimate.rs b/bindings/rust/blenderui-vlist/src/estimate.rsindex 0792b0e..5f227d4 100644--- a/bindings/rust/blenderui-vlist/src/estimate.rs+++ b/bindings/rust/blenderui-vlist/src/estimate.rs@@ -38,6 +38,15 @@ impl Estimator {Self { pad, line_height, char_width, text_width, calib: 1.0, applied: 1.0, est_sum: 0.0, real_sum: 0.0, samples: 0 }}+ /// An estimator that assumes `one_line_px` for an item of one line of+ /// text (TanStack Virtual's `estimateSize`): what is measured later+ /// still calibrates it.+ #[must_use]+ pub const fn with_item_size(mut self, one_line_px: f64) -> Self {+ self.pad = (one_line_px - self.line_height).max(0.0);+ self+ }+/// The same estimator at another wrap width, keeping what it learned.#[must_use]pub const fn with_text_width(mut self, w: f64) -> Self {diff --git a/bindings/rust/blenderui-vlist/src/lib.rs b/bindings/rust/blenderui-vlist/src/lib.rsindex 14bc16c..a5194f5 100644--- a/bindings/rust/blenderui-vlist/src/lib.rs+++ b/bindings/rust/blenderui-vlist/src/lib.rs@@ -28,6 +28,7 @@ pub mod list;pub mod log;pub mod measure;pub mod paint;+pub mod rows;pub mod scrollbar;pub mod source;pub mod synth;@@ -42,6 +43,7 @@ pub use fx::Fx;pub use index::{HeightIndex, IndexError};pub use measure::{Measurer, TextLayout, TextWidth};pub use paint::ItemPainter;+pub use rows::{CountSource, RowList, RowStyle};pub use source::{ItemSource, Message, Page, Record, VecSource};pub use view::{Align, Budget, ListView, Nav, Options, Placed, Pos};pub use wrap::Lines;diff --git a/bindings/rust/blenderui-vlist/src/rows.rs b/bindings/rust/blenderui-vlist/src/rows.rsnew file mode 100644index 0000000..711df0c--- /dev/null+++ b/bindings/rust/blenderui-vlist/src/rows.rs@@ -0,0 +1,247 @@+//! Plain rows: TanStack Virtual's model. [`CountSource`] is "`count` items,+//! item `i` is whatever `text(i)` writes" (nothing is stored per item), and+//! [`RowStyle`] draws and measures a row of wrapped text. Together they are a+//! [`List`](crate::List) of any length with the same variable-height engine+//! as the chat; the chat's own look is [`ChatStyle`](crate::ChatStyle).++use std::ops::Range;++use blenderui_paint::{PaintSink, Palette, Rect};++use crate::estimate::Estimator;+use crate::list::List;+use crate::measure::Measurer;+use crate::paint::ItemPainter;+use crate::scrollbar::WIDTH as SCROLL_W;+use crate::source::{ItemSource, Page, Record};+use crate::wrap::Lines;++/// Writes the text of item `i` into the buffer.+pub type ItemText = Box<dyn Fn(usize, &mut String)>;++/// Maps an item index to its stable key; keys must ascend with the index.+pub type ItemKey = Box<dyn Fn(usize) -> u64>;++/// `count` items whose text is computed when they are fetched (the visible+/// ones only). The key of item `i` is `i` unless [`with_key`](Self::with_key)+/// says otherwise (TanStack Virtual's `getItemKey`).+pub struct CountSource {+ count: usize,+ text: ItemText,+ key: Option<ItemKey>,+ /// Bytes of text an item is assumed to have, for height estimates.+ avg_bytes: u64,+ version: u64,+}++impl CountSource {+ #[must_use]+ pub fn new(count: usize, text: impl Fn(usize, &mut String) + 'static) -> Self {+ Self { count, text: Box::new(text), key: None, avg_bytes: 80, version: 0 }+ }++ /// `getItemKey`: stable keys that survive reordering of the underlying+ /// data. They must be strictly ascending with the index.+ #[must_use]+ pub fn with_key(mut self, key: impl Fn(usize) -> u64 + 'static) -> Self {+ self.key = Some(Box::new(key));+ self+ }++ /// Replace how item text is computed (a new render's closure).+ pub fn set_text(&mut self, text: impl Fn(usize, &mut String) + 'static) {+ self.text = Box::new(text);+ }++ /// Replace the key function (`None`: the index is the key).+ pub fn set_key(&mut self, key: Option<ItemKey>) {+ self.key = key;+ }++ /// The bytes of text an item is assumed to have before it is measured.+ #[must_use]+ pub const fn with_avg_bytes(mut self, bytes: u64) -> Self {+ self.avg_bytes = bytes;+ self+ }++ /// Change the count; returns the old one. The owner tells the view+ /// ([`crate::ListView::appended`] / [`removed`](crate::ListView::removed)).+ pub const fn set_count(&mut self, count: usize) -> usize {+ self.version += 1;+ std::mem::replace(&mut self.count, count)+ }++ /// Bytes an item is assumed to have (for the view's calls).+ #[must_use]+ pub const fn avg_bytes(&self) -> u64 {+ self.avg_bytes+ }++ fn key_of(&self, i: usize) -> u64 {+ self.key.as_ref().map_or(i as u64, |k| k(i))+ }+}++impl ItemSource for CountSource {+ fn len(&self) -> usize {+ self.count+ }++ fn version(&self) -> u64 {+ self.version+ }++ fn bytes(&self, r: Range<usize>) -> u64 {+ let (a, b) = (r.start.min(self.count), r.end.min(self.count));+ (b - a.min(b)) as u64 * self.avg_bytes+ }++ fn fetch(&self, range: Range<usize>, page: &mut Page) {+ let end = range.end.min(self.count);+ page.reset(range.start);+ for i in range.start..end.max(range.start) {+ // the text is written straight into the page's buffer+ let a = page.text_mut().len();+ (self.text)(i, page.text_mut());+ let b = page.text_mut().len();+ page.push_span(&Record { id: self.key_of(i), time: 0, sender: 0, flags: 0, media_h: 0, text: "" }, a..b);+ }+ }++ fn id_at(&self, i: usize) -> Option<u64> {+ (i < self.count).then(|| self.key_of(i))+ }++ fn index_of(&self, id: u64) -> Option<usize> {+ // keys ascend with the index: a binary search+ let (mut lo, mut hi) = (0usize, self.count);+ while lo < hi {+ let mid = lo + (hi - lo) / 2;+ match self.key_of(mid).cmp(&id) {+ std::cmp::Ordering::Less => lo = mid + 1,+ std::cmp::Ordering::Equal => return Some(mid),+ std::cmp::Ordering::Greater => hi = mid,+ }+ }+ None+ }+}++/// How a plain row measures and paints: wrapped text between two paddings,+/// a hairline under it, a tint when selected.+#[derive(Clone, Debug)]+pub struct RowStyle {+ pub pal: Palette,+ pub font_size: f32,+ pub line_height: f32,+ pub pad_x: f32,+ pub pad_y: f32,+ /// Key of the selected item.+ pub selected: Option<u64>,+}++impl RowStyle {+ #[must_use]+ pub const fn new(pal: Palette) -> Self {+ Self { pal, font_size: 14.0, line_height: 19.0, pad_x: 12.0, pad_y: 8.0, selected: None }+ }+}++impl Measurer for RowStyle {+ fn font_size(&self) -> f32 {+ self.font_size+ }++ fn line_height(&self) -> f32 {+ self.line_height+ }++ fn wrap_width(&self, _: &Record<'_>, list_width: f32) -> f32 {+ (list_width - SCROLL_W - 2.0 * self.pad_x).max(40.0)+ }++ fn chrome(&self, _: &Record<'_>) -> f32 {+ 2.0 * self.pad_y + 1.0+ }++ fn estimator(&self, list_width: f32) -> Estimator {+ let w = f64::from(self.wrap_width(&Record { id: 0, time: 0, sender: 0, flags: 0, media_h: 0, text: "" }, list_width));+ Estimator::new(f64::from(2.0 * self.pad_y + 1.0), f64::from(self.line_height), f64::from(self.font_size) * 0.5, w)+ }+}++impl ItemPainter for RowStyle {+ fn palette(&self) -> &Palette {+ &self.pal+ }++ fn item(&self, sink: &mut dyn PaintSink, r: Rect, rec: &Record<'_>, lines: &Lines) {+ let pal = self.pal;+ if self.selected == Some(rec.id) {+ sink.fill(r, pal.sel.opacity(0.35));+ }+ let mut y = r.y + self.pad_y;+ for i in 0..lines.count() {+ sink.text(self.pad_x, y + self.line_height * 0.5, lines.line(rec.text, i), self.font_size, pal.text);+ y += self.line_height;+ }+ sink.fill(Rect::new(0.0, r.y + r.h - 1.0, r.w - SCROLL_W, 1.0), pal.line);+ }++ fn skeleton(&self, sink: &mut dyn PaintSink, r: Rect, _: Option<&Record<'_>>) {+ let dim = self.pal.dim.opacity(0.18);+ sink.round(Rect::new(self.pad_x, r.y + self.pad_y + 3.0, (r.w - 2.0 * self.pad_x - SCROLL_W).max(20.0) * 0.6, 10.0), 5.0, dim);+ }+}++/// A list of plain rows ([`CountSource`] drawn by [`RowStyle`]).+pub type RowList = List<CountSource, RowStyle>;++#[cfg(test)]+mod tests {+ use super::*;++ fn tw(s: &str, size: f32) -> f32 {+ s.chars().count() as f32 * size * 0.5+ }++ fn rows(n: usize) -> RowList {+ let src = CountSource::new(n, |i, out| {+ use std::fmt::Write;+ let _ = write!(out, "row {i} {}", "x".repeat(i % 7 * 30));+ });+ List::new(src, RowStyle::new(Palette::blender_dark()), 500.0, 300.0, crate::Options::default()).unwrap()+ }++ #[test]+ fn a_count_source_fetches_only_what_is_shown() {+ let mut l = rows(10_000_000);+ let placed = l.layout(&mut tw).to_vec();+ assert_eq!(placed[0].item, 0);+ assert!(placed.len() < 100, "only the viewport is placed: {}", placed.len());+ let mut p = Page::new();+ l.source.fetch(5..8, &mut p);+ assert_eq!(p.record(6).unwrap().text, format!("row 6 {}", "x".repeat(6 * 30)));+ assert_eq!(p.record(7).unwrap().id, 7);+ }++ #[test]+ fn keys_index_and_count_changes() {+ let mut l = rows(1000);+ assert_eq!(l.source.id_at(10), Some(10));+ assert_eq!(l.source.index_of(999), Some(999));+ assert_eq!(l.source.index_of(1000), None);+ l.source = CountSource::new(100, |i, out| out.push_str(&i.to_string())).with_key(|i| i as u64 * 10 + 5);+ assert_eq!(l.source.id_at(3), Some(35));+ assert_eq!(l.source.index_of(35), Some(3));+ assert_eq!(l.source.index_of(36), None);+ let old = l.source.set_count(150);+ assert_eq!((old, l.source.len()), (100, 150));+ assert_eq!(l.source.bytes(0..10), 800);+ l.view.appended(50, 50 * l.source.avg_bytes()).unwrap();+ l.view.jump_to(149, crate::Align::End);+ l.layout(&mut tw);+ assert_eq!(l.view.placed().last().unwrap().item, 149);+ }+}diff --git a/bindings/rust/blenderui-vlist/src/view/frame.rs b/bindings/rust/blenderui-vlist/src/view/frame.rsindex a7325ac..5c3fa54 100644--- a/bindings/rust/blenderui-vlist/src/view/frame.rs+++ b/bindings/rust/blenderui-vlist/src/view/frame.rs@@ -222,7 +222,7 @@ impl ListView {if !wants || self.flinging() {return;}- let ahead = shown.len().max(8);+ let ahead = shown.len().max(self.opts.overscan);let want = if self.last_dir >= 0 { shown.start..(shown.end + ahead).min(page.end) } else { shown.start.saturating_sub(ahead).max(page.start)..shown.end };if self.requested.as_ref() != Some(&want) {if let Some(old) = self.requested.replace(want.clone()) {@@ -235,7 +235,7 @@ impl ListView {/// The source's items changed without the view being told: rebuild the/// index (measured heights are lost), keeping the anchor item.pub(crate) fn resync<S: ItemSource, M: Measurer>(&mut self, src: &S, m: &M) {- let est = m.estimator(self.width.max(1.0));+ let est = super::estimator_for(m, &self.opts, self.width);if let Ok(index) = crate::index::HeightIndex::estimated(src.len(), est, |r| src.bytes(r)) {self.index = index;}diff --git a/bindings/rust/blenderui-vlist/src/view/mod.rs b/bindings/rust/blenderui-vlist/src/view/mod.rsindex c0b1c17..784f406 100644--- a/bindings/rust/blenderui-vlist/src/view/mod.rs+++ b/bindings/rust/blenderui-vlist/src/view/mod.rs@@ -31,6 +31,12 @@ use crate::source::{ItemSource, Page};pub use frame::{Budget, Placed};+/// The measurer's estimator for a list `width` wide, with `opts.estimate_size` applied.+pub(crate) fn estimator_for<M: Measurer>(m: &M, opts: &Options, width: f32) -> crate::Estimator {+ let est = m.estimator(width.max(1.0));+ opts.estimate_size.map_or(est, |px| est.with_item_size(f64::from(px)))+}+/// Where the viewport is.#[derive(Copy, Clone, Debug, PartialEq, Eq)]pub enum Pos {@@ -75,6 +81,12 @@ pub struct Options {/// Most items whose heights are held one by one (older ones go back to/// estimates, far from the viewport first).pub max_measured: usize,+ /// How many items beyond the viewport the source is asked to load+ /// (TanStack Virtual's `overscan`); at least a screenful is always asked for.+ pub overscan: usize,+ /// The height assumed, in px, for an item of one line before it is+ /// measured (TanStack Virtual's `estimateSize`); `None`: the style's own.+ pub estimate_size: Option<f32>,}impl Default for Options {@@ -85,6 +97,8 @@ impl Default for Options {cache_capacity: 4096,fling_budget: Budget::Time(Duration::from_micros(500)),max_measured: 1 << 20,+ overscan: 8,+ estimate_size: None,}}}@@ -117,7 +131,7 @@ pub struct ListView {impl ListView {/// A view over `src` in a viewport `width` x `height`.pub fn new<S: ItemSource, M: Measurer>(src: &S, m: &M, width: f32, height: f32, opts: Options) -> Result<Self, IndexError> {- let index = HeightIndex::estimated(src.len(), m.estimator(width.max(1.0)), |r| src.bytes(r))?;+ let index = HeightIndex::estimated(src.len(), estimator_for(m, &opts, width), |r| src.bytes(r))?;Ok(Self {index,text: TextLayout::new(opts.cache_capacity),@@ -236,6 +250,26 @@ impl ListView {self.set_scroll_units(px_to_units(target));}+ /// Scroll to `offset` px from the top of the content (TanStack+ /// Virtual's `scrollToOffset`): estimates for what is not measured, so+ /// an offset far down lands on the item the scrollbar would show. NaN is ignored.+ pub fn scroll_to_offset(&mut self, offset: f64) {+ if offset.is_nan() {+ return;+ }+ self.goal = None;+ self.pending = 0.0;+ self.set_scroll_units(px_to_units(offset.clamp(0.0, self.scroll_extent().1)));+ }++ /// The items in the viewport after the last layout, first to last+1+ /// (TanStack Virtual's `range` without the overscan).+ #[must_use]+ pub fn visible_range(&self) -> Option<std::ops::Range<usize>> {+ let (first, last) = (self.placed.first()?, self.placed.last()?);+ Some(first.item..last.item + 1)+ }+/// Scroll to a fraction `0..=1` of the content (the scrollbar thumb being dragged).pub fn scroll_to_fraction(&mut self, f: f64) {if f.is_nan() {@@ -366,7 +400,7 @@ impl ListView {Pos::Anchor { item, .. } => self.index.height_of(item).map(|(h, _)| u64::from(h.units())),Pos::Bottom => None,};- let est = m.estimator(self.width.max(1.0));+ let est = estimator_for(m, &self.opts, self.width);self.text.clear();self.index.set_estimator(est.with_text_width(est.text_width));self.page_version = u64::MAX;diff --git a/bindings/rust/blenderui-vlist/tests/view.rs b/bindings/rust/blenderui-vlist/tests/view.rsindex a7daf6f..6dabc61 100644--- a/bindings/rust/blenderui-vlist/tests/view.rs+++ b/bindings/rust/blenderui-vlist/tests/view.rs@@ -370,3 +370,26 @@ fn a_uniform_list_needs_no_measuring() {assert!(v.index().heap_bytes() < 2_000_000);assert_eq!(v.index().measured_items(), 0);}++#[test]+fn tanstack_virtual_options_and_offsets() {+ // visible_range is the placed items; scroll_to_offset lands inside the content+ let mut c = chat(5000, Options::default());+ c.layout(&mut tw);+ let r = c.view.visible_range().unwrap();+ assert_eq!(r.start, 0);+ assert_eq!(r.end, c.view.placed().last().unwrap().item + 1);+ c.view.scroll_to_offset(2000.0);+ c.layout(&mut tw);+ let (top, total) = c.view.scroll_extent();+ assert!((top - 2000.0).abs() < 1.0 || top > 1500.0, "top {top}");+ assert!(total > 2000.0);+ c.view.scroll_to_offset(f64::NAN);+ c.view.scroll_to_offset(1e12);+ c.layout(&mut tw);+ assert!(c.view.at_bottom(), "past the end is the end");+ // estimate_size: the assumed height of an unmeasured one-line item moves the total+ let small = chat(5000, Options { estimate_size: Some(24.0), ..Options::default() });+ let big = chat(5000, Options { estimate_size: Some(96.0), ..Options::default() });+ assert!(big.view.scroll_extent().1 > small.view.scroll_extent().1 * 2.0);+}diff --git a/bindings/rust/blenderui/README.md b/bindings/rust/blenderui/README.mdindex c8b2b92..085b6de 100644--- a/bindings/rust/blenderui/README.md+++ b/bindings/rust/blenderui/README.md@@ -65,8 +65,8 @@ Register extra fonts with `blenderui::add_font`.is experimental. You need Rust 1.88+, CMake and a C compiler (the first buildcompiles BUI's C kit), and the X11 headers on Linux.-Dear ImGui on BUI is a separate crate, `blenderui-imgui`, not on crates.io-yet: use it as a git dependency.+Dear ImGui on BUI is a separate crate, [`blenderui-imgui`](https://crates.io/crates/blenderui-imgui):+`cargo add blenderui-imgui`.Guide, CSS coverage and limitations:[docs/rust.md](https://github.com/ppmpreetham/BUI/blob/main/docs/rust.md),diff --git a/bindings/rust/blenderui/examples/bench_table.rs b/bindings/rust/blenderui/examples/bench_table.rsindex af90473..6fd2f08 100644--- a/bindings/rust/blenderui/examples/bench_table.rs+++ b/bindings/rust/blenderui/examples/bench_table.rs@@ -11,7 +11,10 @@ use std::alloc::{GlobalAlloc, Layout, System};use std::cell::Cell;use std::time::Instant;+use std::sync::Arc;+use blenderui::prelude::*;+use blenderui::shadcn::{select_column, CellRender, ColumnDef, ColumnMeta, Table, TableOptions};use blenderui::table::{Cell as TableCell, CellSource, Column, DataTable, TableDelegate, TableState};struct Counting;@@ -81,6 +84,32 @@ impl Render for Painted {}}+/// A row of the shadcn layer's table: only its number; the cells are computed from it.+#[derive(Clone, Copy)]+struct Row(u32);++/// The same 1,000,000 x 20 table through shadcn's `ColumnDef` / TanStack `Table`: a checkbox+/// column, a currency column and a progress column among the numbers.+fn shadcn_table() -> Table<Row> {+ let mut columns: Vec<ColumnDef<Row>> = vec![select_column()];+ for c in 1..COLS {+ columns.push(match c {+ 1 => ColumnDef::accessor_fn("c1", |r: &Row| TableCell::F64(cell(r.0 as usize, 1) as f64 / 100.0, 2)).meta(ColumnMeta::right().usd()),+ 2 => ColumnDef::accessor_fn("c2", |r: &Row| TableCell::U64(cell(r.0 as usize, 2) % 101)).cell(CellRender::Progress),+ _ => ColumnDef::accessor_fn(format!("c{c}"), move |r: &Row| TableCell::U64(cell(r.0 as usize, c))),+ }.size(100.0));+ }+ let data: Arc<[Row]> = (0..ROWS as u32).map(Row).collect();+ Table::new(TableOptions::new(columns, data)).expect("valid columns")+}++struct Shadcn(Entity<TableState<Table<Row>>>);+impl Render for Shadcn {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ body().m_0().child(div().w(px(900.0)).h(px(500.0)).child(DataTable::new(&self.0).stripe(true)))+ }+}+/// `n` rows of 20 cell elements each in a `uniform_list` (gpui's way).struct Listed(usize);impl Render for Listed {@@ -154,6 +183,47 @@ fn main() {allocs_per_full_frame={allocs} sort_click_ms={sort:.1} rss_delta_mb={:.1}", rss_mb() - base);});}+ if which == "all" || which == "shadcn" {+ let base = rss_mb();+ Application::headless().run(move |cx| {+ let t0 = Instant::now();+ let table = shadcn_table();+ let mut handle = None;+ let win = cx.open_window(opts(), |w, cx| {+ let t = cx.new(|cx| TableState::new(table, w, cx).row_selectable(false));+ handle = Some(t);+ cx.new(|_| Shadcn(t))+ }).unwrap();+ let t = handle.unwrap();+ let build = ms(t0);+ let t1 = Instant::now();+ cx.draw(win.id);+ cx.draw(win.id);+ let first = ms(t1);+ let frames = 300;+ COUNT.set(0);+ let t2 = Instant::now();+ for _ in 0..frames {+ t.update(cx, |s, _| s.scroll_by(0.0, 37.0));+ cx.notify_all();+ cx.draw(win.id);+ }+ let per = ms(t2) / f64::from(frames);+ let allocs = COUNT.get() / frames as usize;+ // a header click sorts through the TanStack layer (typed keys, the same engine); the view refreshes after+ let t3 = Instant::now();+ cx.simulate_click(win.id, 400.0, 10.0);+ t.update(cx, |s, c| {+ if s.delegate_mut().take_dirty() {+ s.refresh(c);+ }+ });+ cx.notify_all();+ cx.draw(win.id);+ let sort = ms(t3);+ println!("shadcn rows={ROWS} cols={COLS} build_ms={build:.2} first_frame_ms={first:.2} scroll_frame_ms={per:.3} allocs_per_full_frame={allocs} sort_click_ms={sort:.1} rss_delta_mb={:.1}", rss_mb() - base);+ });+ }for (name, n, rows) in [("uniform_list", 1usize, ROWS), ("naive_2000", 2usize, 2000), ("naive_20000", 2usize, 20_000)] {if which != "all" && which != name {continue;diff --git a/bindings/rust/blenderui/examples/site_shadcn_list.rs b/bindings/rust/blenderui/examples/site_shadcn_list.rsnew file mode 100644index 0000000..0e53bf5--- /dev/null+++ b/bindings/rust/blenderui/examples/site_shadcn_list.rs@@ -0,0 +1,78 @@+//! The shadcn-style virtual list: ten million rows (`VirtualList`) next to a+//! chat (`ChatList`), written in `rsx!` / `#[component]` syntax, with a+//! status line fed by `on_range_change`.+//!+//! ```text+//! cargo run --release --example site_shadcn_list+//! ```++#[path = "site/common.rs"]+mod common;++use std::cell::Cell as StdCell;+use std::fmt::Write;+use std::sync::Arc;++use blenderui::prelude::*;+use blenderui::shadcn::*;+use blenderui::vlist::synth;++const ROWS: usize = 10_000_000;++fn row_text(i: usize, out: &mut String) {+ let words = ["render", "mesh", "shader", "node", "bake", "light"];+ let _ = write!(out, "Row {i}: ");+ for k in 0..(i * 7 % 11) + 1 {+ let _ = write!(out, "{} ", words[(i + k) % words.len()]);+ }+}++struct Page {+ rows: StdCell<Option<ListHandle>>,+ chat: Arc<[Message]>,+}++impl Render for Page {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ let rows = use_virtual_list();+ self.rows.set(Some(rows));+ let chat = self.chat.clone();+ let status = format!("{ROWS} rows, showing {}..{}", rows.range().start, rows.range().end);+ html().styled().child(body().m_0().p_4().child(rsx! {+ <div flex flex-col gap-2>+ <div flex gap-4>+ <VirtualList list={rows} count={ROWS} item={row_text} estimate_size={36.0} overscan={12} w={px(380.0)} h={px(300.0)} />+ <ChatList messages={chat} w={px(420.0)} h={px(300.0)} />+ </div>+ <div text-sm opacity-70>{status}</div>+ </div>+ }))+ }+}++fn main() {+ let shot = common::screenshot_arg();+ let app = if shot.is_some() { Application::headless() } else { Application::new() };+ app.run(move |cx| {+ let mut page = None;+ let win = cx+ .open_window(common::options(852.0, 372.0, "Virtual list"), |_, cx| {+ let p = cx.new(|_| Page { rows: StdCell::new(None), chat: synth::messages(0, 500).into() });+ page = Some(p);+ p+ })+ .unwrap();+ if let Some(path) = shot {+ for _ in 0..4 {+ cx.draw(win.id);+ }+ let rows = page.unwrap().read(cx).rows.get().expect("rendered");+ rows.scroll_to_index(6_283_185, Align::Start, cx);+ for _ in 0..6 {+ cx.draw(win.id);+ }+ let (w, h, px) = cx.draw(win.id);+ common::save(&path, w, h, &px);+ }+ });+}diff --git a/bindings/rust/blenderui/examples/site_shadcn_table.rs b/bindings/rust/blenderui/examples/site_shadcn_table.rsnew file mode 100644index 0000000..d509f5c--- /dev/null+++ b/bindings/rust/blenderui/examples/site_shadcn_table.rs@@ -0,0 +1,131 @@+//! shadcn/ui's "payments" Data Table in Blender's theme: a select column, a+//! status badge, a sortable email header with a menu, an amount formatted as+//! dollars and right-aligned, a row-actions column, a filter input, the view+//! options and the pagination footer. Written in `rsx!` / `#[component]` syntax.+//!+//! ```text+//! cargo run --release --example site_shadcn_table+//! ```++#[path = "site/common.rs"]+mod common;++use std::cell::Cell as StdCell;+use std::sync::Arc;++use blenderui::prelude::*;+use blenderui::shadcn::*;++const STATUS: [&str; 4] = ["pending", "processing", "success", "failed"];+const NAMES: [&str; 12] = ["ken99", "abe45", "monserrat44", "silas22", "carmella", "m", "example", "jason78", "nina", "omar", "lena", "tomas"];+const HOSTS: [&str; 4] = ["yahoo.com", "gmail.com", "example.com", "hotmail.com"];++/// shadcn's sample row: `{ id, amount, status, email }`.+struct Payment {+ id: String,+ status: &'static str,+ email: String,+ amount: f64,+}++impl Record for Payment {+ const FIELDS: &'static [&'static str] = &["id", "status", "email", "amount"];++ fn field(&self, field: usize) -> Cell<'_> {+ match field {+ 0 => Cell::Str(&self.id),+ 1 => Cell::Str(self.status),+ 2 => Cell::Str(&self.email),+ _ => Cell::F64(self.amount, 2),+ }+ }+}++fn payments() -> Arc<[Payment]> {+ (0..84)+ .map(|i| {+ let h = (i as u64 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15) >> 20;+ Payment {+ id: format!("{:08x}", (h as u32) ^ 0x728e_d52f),+ status: STATUS[(h >> 3) as usize % 4],+ email: format!("{}@{}", NAMES[(h >> 5) as usize % NAMES.len()], HOSTS[(h >> 9) as usize % HOSTS.len()]),+ amount: 50.0 + (h % 90_000) as f64 / 100.0,+ }+ })+ .collect()+}++/// `columns.tsx` of the shadcn recipe.+fn columns() -> Arc<[ColumnDef<Payment>]> {+ vec![+ select_column(),+ ColumnDef::accessor_key("status").header("Status").size(150.0).badge(|s| match s {+ "success" => BadgeVariant::Default,+ "failed" => BadgeVariant::Destructive,+ "processing" => BadgeVariant::Outline,+ _ => BadgeVariant::Secondary,+ }),+ ColumnDef::accessor_key("email").header(Header::menu("Email")).size(400.0),+ ColumnDef::accessor_key("amount").header("Amount").size(150.0).meta(ColumnMeta::right().usd()),+ actions_column(),+ ]+ .into()+}++struct Page {+ handle: StdCell<Option<TableHandle>>,+}++impl Render for Page {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ let table = use_table();+ self.handle.set(Some(table));+ let (columns, data) = (use_memo(columns, ()), use_memo(payments, ()));+ html().styled().child(body().m_0().p_4().child(rsx! {+ <DataTable+ table={table}+ columns={columns}+ data={data}+ filter_column="email"+ filter_placeholder="Filter emails..."+ on_row_action={|row, _, _| println!("actions for row {row}")}+ w={px(820.0)}+ h={px(340.0)}+ />+ }))+ }+}++fn main() {+ let shot = common::screenshot_arg();+ let app = if shot.is_some() { Application::headless() } else { Application::new() };+ app.run(move |cx| {+ let mut page = None;+ let win = cx+ .open_window(common::options(852.0, 372.0, "Payments"), |_, cx| {+ let p = cx.new(|_| Page { handle: StdCell::new(None) });+ page = Some(p);+ p+ })+ .unwrap();+ if let Some(path) = shot {+ for _ in 0..4 {+ cx.draw(win.id);+ }+ // a state worth a picture: two rows checked and the email menu open+ let table = page.unwrap().read(cx).handle.get().expect("rendered");+ for row in [1, 3] {+ table.dispatch(Command::TogglePageRow(row), cx);+ }+ for _ in 0..3 {+ cx.draw(win.id);+ }+ cx.simulate_click(win.id, 16.0 + 40.0 + 150.0 + 100.0, 55.0);+ for _ in 0..3 {+ cx.draw(win.id);+ }+ let (w, h, px) = cx.draw(win.id);+ common::save(&path, w, h, &px);+ }+ });+}diff --git a/bindings/rust/blenderui/src/hooks.rs b/bindings/rust/blenderui/src/hooks.rsindex 480f085..d5411a8 100644--- a/bindings/rust/blenderui/src/hooks.rs+++ b/bindings/rust/blenderui/src/hooks.rs@@ -232,6 +232,15 @@ impl<T: 'static> Signal<T> {self.update(|v| *v = value);}+ /// Change the value in place *without* re-rendering: for what a render+ /// itself refreshes (a handle to a widget's state, the latest callbacks).+ pub(crate) fn update_quiet<R>(self, f: impl FnOnce(&mut T) -> R) -> R {+ let mut v = self.take().expect("signal used after its component was dropped");+ let r = f(&mut v);+ self.put(v, false);+ r+ }+/// Leptos' read / write halves of this signal.pub fn split(self) -> (ReadSignal<T>, WriteSignal<T>) {(ReadSignal(self), WriteSignal(self))diff --git a/bindings/rust/blenderui/src/lib.rs b/bindings/rust/blenderui/src/lib.rsindex 6d480b3..6199f57 100644--- a/bindings/rust/blenderui/src/lib.rs+++ b/bindings/rust/blenderui/src/lib.rs@@ -106,6 +106,7 @@ pub mod events;pub mod geometry;pub mod html;pub mod list;+pub mod shadcn;pub mod table;pub(crate) mod sink;pub mod vlist;diff --git a/bindings/rust/blenderui/src/shadcn/mod.rs b/bindings/rust/blenderui/src/shadcn/mod.rsnew file mode 100644index 0000000..205340f--- /dev/null+++ b/bindings/rust/blenderui/src/shadcn/mod.rs@@ -0,0 +1,39 @@+//! shadcn/ui's API for the two big components: the **Data Table** (the+//! TanStack Table recipe) and a **virtual list** (TanStack Virtual's API in+//! shadcn's component style). Everything here is a thin adapter: the logic+//! is in the cores (`blenderui_table::tanstack`, `blenderui_vlist`), the+//! painting and input in [`crate::table`] and [`crate::vlist`].+//!+//! ```ignore+//! use blenderui::shadcn::*;+//!+//! // rsx! / #[component] syntax+//! rsx! { <DataTable columns={columns} data={data} filter_column="email" /> }+//! // gpui builder syntax+//! DataTable::new(columns, data).filter_column("email")+//! ```+//!+//! Not in the prelude, like [`crate::table`] and [`crate::vlist`]: it is+//! `use blenderui::shadcn::*;` when you want it.+//!+//! * [`table`]: [`DataTable`], [`ColumnDef`], [`use_table`] and the helper+//! components (`DataTableColumnHeader`, `DataTablePagination`,+//! `DataTableViewOptions`, `DataTableToolbar`).+//! * [`virtual_list`]: [`VirtualList`], [`ChatList`] and the+//! TanStack Virtual option names.++pub mod table;+pub mod virtual_list;++/// shadcn's `Input` is Blender's text field.+pub use crate::components::TextField as Input;+pub use crate::components::{Button, Checkbox};+pub use table::*;+pub use virtual_list::*;++use crate::Rgba;++/// A color of the active theme (`"menu_back.inner"` ...), or `fallback`.+pub(crate) fn theme(key: &str, fallback: Rgba) -> Rgba {+ crate::theme_color(key).map_or(fallback, |[r, g, b, a]| Rgba { r, g, b, a })+}diff --git a/bindings/rust/blenderui/src/shadcn/table/column_header.rs b/bindings/rust/blenderui/src/shadcn/table/column_header.rsnew file mode 100644index 0000000..b739213--- /dev/null+++ b/bindings/rust/blenderui/src/shadcn/table/column_header.rs@@ -0,0 +1,47 @@+//! `DataTableColumnHeader`: the sort menu of a sortable header (Asc, Desc,+//! Hide), as in shadcn's `data-table-column-header.tsx`.++use super::handle::TableHandle;+use crate::prelude::*;+use crate::shadcn::theme;++/// The menu of column `column`'s header: Asc, Desc and Hide, driving `table`.+/// The [`DataTable`](super::DataTable) opens it under a header made with+/// [`Header::menu`](super::Header::menu); it is a component of its own so it+/// can also be shown anywhere else (it closes the table's header menu when an+/// item is chosen).+#[component]+pub fn DataTableColumnHeader(table: TableHandle, column: &str) {+ let info = table.columns().into_iter().find(|c| c.id == column);+ let (can_sort, can_hide) = info.as_ref().map_or((false, false), |c| (c.can_sort, c.can_hide));+ let item = |label: &'static str, enabled: bool, id: String, run: fn(TableHandle, &str, &mut App)| {+ let (hover, text) = (theme("menu_item.inner_sel", Rgba::TRANSPARENT), theme("menu_item.text", black()));+ div()+ .px_2()+ .py_1()+ .rounded_md()+ .text_color(text)+ .when(enabled, |d| d.cursor_pointer().hover(move |s| s.bg(hover).text_color(theme("menu_item.text_sel", black()))))+ .when(!enabled, |d| d.opacity(0.4))+ .on_click(move |_: &ClickEvent, _: &mut Window, cx: &mut App| {+ if enabled {+ run(table, &id, cx);+ table.menu.set(None);+ }+ })+ .child(label)+ };+ div()+ .flex()+ .flex_col()+ .p_1()+ .rounded_md()+ .border_1()+ .border_color(theme("menu_back.outline", Rgba::TRANSPARENT))+ .bg(theme("menu_back.inner", Rgba { r: 0.1, g: 0.1, b: 0.1, a: 1.0 }))+ .text_size(px(13.0))+ .child(item("Asc", can_sort, column.to_string(), |t, id, cx| t.toggle_column_sorting(id.to_string(), Some(false), cx)))+ .child(item("Desc", can_sort, column.to_string(), |t, id, cx| t.toggle_column_sorting(id.to_string(), Some(true), cx)))+ .child(div().h(px(1.0)).my_1().bg(theme("menu_back.outline", Rgba::TRANSPARENT)))+ .child(item("Hide", can_hide, column.to_string(), |t, id, cx| t.toggle_column_visibility(id.to_string(), Some(false), cx)))+}diff --git a/bindings/rust/blenderui/src/shadcn/table/data_table.rs b/bindings/rust/blenderui/src/shadcn/table/data_table.rsnew file mode 100644index 0000000..3c863a3--- /dev/null+++ b/bindings/rust/blenderui/src/shadcn/table/data_table.rs@@ -0,0 +1,358 @@+//! [`DataTable`]: shadcn's `<DataTable columns={columns} data={data} />`.+//!+//! One component that renders the whole recipe: the toolbar (filter input and+//! view options), the table, and the pagination footer. It is generic over the+//! row type, which `#[component]` cannot be, so its props builder is written+//! out: `DataTable::__builder()` is what `rsx!` calls, `DataTable::new` is the+//! same thing for builder chains, and the type parameters `C` and `D` are+//! `()` until `columns` and `data` are given (a missing one is the usual+//! "a required prop is missing" compile error).++use std::marker::PhantomData;+use std::rc::Rc;+use std::sync::Arc;++use blenderui_table::tanstack::{ColumnDef, PaginationState, PartialState, RowSelectionState, SortingState, Table, TableOptions, TableState, VisibilityState};+use blenderui_table::Text;++use super::column_header::DataTableColumnHeader;+use super::handle::{use_table, Ops, TableHandle};+use super::link::{Callbacks, Link};+use super::pagination::DataTablePagination;+use super::toolbar::DataTableToolbar;+use crate::css::Decl;+use crate::hooks::{build, use_signal, Complete, Signal};+use crate::prelude::*;+use crate::table::{DataTable as TableElement, TableState as TableEntity};++/// Everything that is not the columns or the data.+struct Extras {+ base: Div,+ handle: Option<TableHandle>,+ initial_state: TableState,+ state: PartialState,+ filter_column: Option<Text>,+ filter_placeholder: Option<String>,+ toolbar: Option<bool>,+ view_options: bool,+ pagination: bool,+ page_sizes: Option<Vec<usize>>,+ callbacks: Callbacks,+}++/// The Data Table recipe over rows of type `T`.+///+/// ```ignore+/// // rsx!+/// rsx! { <DataTable columns={columns} data={data} filter_column="email" h={px(420.0)} /> }+/// // builder+/// DataTable::new(columns, data).filter_column("email").h(px(420.0))+/// ```+///+/// `columns` and `data` are compared by identity (an `Arc` clone is the same+/// table; a fresh `Vec` is new data), like TanStack's memoized references:+/// build them once (`use_memo`, or a field of your view) and pass them again.+pub struct DataTable<T, C = Arc<[ColumnDef<T>]>, D = Arc<[T]>> {+ columns: C,+ data: D,+ extras: Extras,+ row: PhantomData<fn() -> T>,+}++impl<T> DataTable<T, (), ()> {+ /// A table of `data` with `columns`.+ pub fn new(columns: impl Into<Arc<[ColumnDef<T>]>>, data: impl Into<Arc<[T]>>) -> DataTable<T> {+ Self::__builder().columns(columns).data(data)+ }++ #[doc(hidden)]+ #[must_use]+ pub fn __builder() -> Self {+ Self {+ columns: (),+ data: (),+ extras: Extras {+ base: div().flex().flex_col().gap_2(),+ handle: None,+ initial_state: TableState::default(),+ state: PartialState::default(),+ filter_column: None,+ filter_placeholder: None,+ toolbar: None,+ view_options: true,+ pagination: true,+ page_sizes: None,+ callbacks: Callbacks::default(),+ },+ row: PhantomData,+ }+ }+}++impl<T, D> DataTable<T, (), D> {+ /// `columns`.+ pub fn columns(self, columns: impl Into<Arc<[ColumnDef<T>]>>) -> DataTable<T, Arc<[ColumnDef<T>]>, D> {+ DataTable { columns: columns.into(), data: self.data, extras: self.extras, row: PhantomData }+ }+}++impl<T, C> DataTable<T, C, ()> {+ /// `data`.+ pub fn data(self, data: impl Into<Arc<[T]>>) -> DataTable<T, C, Arc<[T]>> {+ DataTable { columns: self.columns, data: data.into(), extras: self.extras, row: PhantomData }+ }+}++impl<T, C, D> DataTable<T, C, D> {+ /// A handle made with [`use_table`], so helper components elsewhere in+ /// the page (`DataTablePagination`, `DataTableViewOptions` ...) drive this table.+ #[must_use]+ pub fn table(mut self, handle: TableHandle) -> Self {+ self.extras.handle = Some(handle);+ self+ }++ /// `initialState`: where the uncontrolled state starts.+ #[must_use]+ pub fn initial_state(mut self, state: TableState) -> Self {+ self.extras.initial_state = state;+ self+ }++ /// Control the sorting (`state.sorting`); see `on_sorting_change`.+ #[must_use]+ pub fn sorting(mut self, v: SortingState) -> Self {+ self.extras.state.sorting = Some(v);+ self+ }++ /// Control the column filters (`state.columnFilters`).+ #[must_use]+ pub fn column_filters(mut self, v: Vec<blenderui_table::tanstack::ColumnFilter>) -> Self {+ self.extras.state.column_filters = Some(v);+ self+ }++ /// Control the global filter (`state.globalFilter`).+ #[must_use]+ pub fn global_filter(mut self, v: impl Into<String>) -> Self {+ self.extras.state.global_filter = Some(v.into());+ self+ }++ /// Control the column visibility (`state.columnVisibility`).+ #[must_use]+ pub fn column_visibility(mut self, v: VisibilityState) -> Self {+ self.extras.state.column_visibility = Some(v);+ self+ }++ /// Control the row selection (`state.rowSelection`).+ #[must_use]+ pub fn row_selection(mut self, v: RowSelectionState) -> Self {+ self.extras.state.row_selection = Some(v);+ self+ }++ /// Control the pagination (`state.pagination`).+ #[must_use]+ pub fn pagination(mut self, v: PaginationState) -> Self {+ self.extras.state.pagination = Some(v);+ self+ }++ /// Page the rows and show the pagination footer (`getPaginationRowModel`; on by default).+ #[must_use]+ pub const fn enable_pagination(mut self, on: bool) -> Self {+ self.extras.pagination = on;+ self+ }++ /// The choices of the "Rows per page" menu.+ #[must_use]+ pub fn page_sizes(mut self, sizes: Vec<usize>) -> Self {+ self.extras.page_sizes = Some(sizes);+ self+ }++ /// Show the toolbar (the default when there is a filter column or the view options).+ #[must_use]+ pub const fn toolbar(mut self, on: bool) -> Self {+ self.extras.toolbar = Some(on);+ self+ }++ /// The column the toolbar's filter input filters (`column.setFilterValue`);+ /// without one the input is the global filter.+ #[must_use]+ pub fn filter_column(mut self, id: impl Into<Text>) -> Self {+ self.extras.filter_column = Some(id.into());+ self+ }++ #[must_use]+ pub fn filter_placeholder(mut self, text: impl Into<String>) -> Self {+ self.extras.filter_placeholder = Some(text.into());+ self+ }++ /// The "View" column-visibility menu in the toolbar (on by default).+ #[must_use]+ pub const fn view_options(mut self, on: bool) -> Self {+ self.extras.view_options = on;+ self+ }++ /// `onSortingChange`.+ #[must_use]+ pub fn on_sorting_change(mut self, f: impl Fn(&SortingState) + 'static) -> Self {+ self.extras.callbacks.sorting = Some(Box::new(f));+ self+ }++ /// `onColumnFiltersChange`.+ #[must_use]+ pub fn on_column_filters_change(mut self, f: impl Fn(&Vec<blenderui_table::tanstack::ColumnFilter>) + 'static) -> Self {+ self.extras.callbacks.column_filters = Some(Box::new(f));+ self+ }++ /// `onGlobalFilterChange`.+ #[must_use]+ pub fn on_global_filter_change(mut self, f: impl Fn(&String) + 'static) -> Self {+ self.extras.callbacks.global_filter = Some(Box::new(f));+ self+ }++ /// `onColumnVisibilityChange`.+ #[must_use]+ pub fn on_column_visibility_change(mut self, f: impl Fn(&VisibilityState) + 'static) -> Self {+ self.extras.callbacks.column_visibility = Some(Box::new(f));+ self+ }++ /// `onRowSelectionChange`.+ #[must_use]+ pub fn on_row_selection_change(mut self, f: impl Fn(&RowSelectionState) + 'static) -> Self {+ self.extras.callbacks.row_selection = Some(Box::new(f));+ self+ }++ /// `onPaginationChange`.+ #[must_use]+ pub fn on_pagination_change(mut self, f: impl Fn(&PaginationState) + 'static) -> Self {+ self.extras.callbacks.pagination = Some(Box::new(f));+ self+ }++ /// A click on a row's "more" button ([`actions_column`](super::actions_column)):+ /// the index of the row in the data.+ #[must_use]+ pub fn on_row_action(mut self, f: impl Fn(usize, &mut Window, &mut App) + 'static) -> Self {+ self.extras.callbacks.row_action = Some(Box::new(f));+ self+ }+}++impl<T, C, D> Styled for DataTable<T, C, D> {+ fn decls_mut(&mut self) -> &mut Vec<Decl> {+ self.extras.base.decls_mut()+ }+}++impl<T> Complete for DataTable<T> {+ type Props = Self;+ fn finish(self) -> Self {+ self+ }+}++/// The element that fills in the table once the window can create its entity.+type EntitySlot<T> = Signal<Option<Entity<TableEntity<Table<T>>>>>;++impl<T: Send + Sync + 'static> IntoElement for DataTable<T> {+ fn into_any_element(self) -> AnyElement {+ let Self { columns, data, extras, .. } = self;+ let Extras { base, handle, initial_state, state, filter_column, filter_placeholder, toolbar, view_options, pagination, page_sizes, callbacks } = extras;+ // hooks: the same calls in the same order on every render+ let own = use_table();+ let entity: EntitySlot<T> = use_signal(None);+ let handle = handle.unwrap_or(own);++ let mut opts = TableOptions::new(columns, data).initial_state(initial_state).state(state);+ opts.paginate = pagination;++ let mut root = base;+ if toolbar.unwrap_or(filter_column.is_some() || view_options) {+ let mut b = DataTableToolbar::__builder().table(handle).view_options(view_options);+ if let Some(c) = filter_column {+ b = b.filter_column(c.to_string());+ }+ if let Some(p) = filter_placeholder {+ b = b.placeholder(p);+ }+ root = root.child(build(b));+ }+ root = root.child(+ div().relative().flex_1().min_h(px(240.0)).overflow_hidden().defer(move |window, cx, el| {+ *el = fill(std::mem::replace(el, Div::new("div")), entity, handle, opts, callbacks, window, cx);+ }),+ );+ if pagination {+ let mut b = DataTablePagination::__builder().table(handle);+ if let Some(s) = page_sizes {+ b = b.page_sizes(s);+ }+ root = root.child(build(b));+ }+ root.into_any_element()+ }+}++/// The table region: the painted table (an entity made on first use) and the+/// open header menu over it.+fn fill<T: Send + Sync + 'static>(+ slot: Div,+ entity: EntitySlot<T>,+ handle: TableHandle,+ opts: TableOptions<T>,+ callbacks: Callbacks,+ window: &mut Window,+ cx: &mut App,+) -> Div {+ let state = match entity.get() {+ Some(state) => {+ let link = Link { state, handle, callbacks };+ return match link.set_options(opts, cx) {+ Ok(()) => table_region(slot, Rc::new(link)),+ Err(e) => error(slot, &e),+ };+ }+ None => match Table::new(opts) {+ Ok(table) => cx.new(|cx| TableEntity::new(table, window, cx).row_selectable(false).col_movable(false)),+ Err(e) => return error(slot, &e),+ },+ };+ entity.set(Some(state));+ let link = Link { state, handle, callbacks };+ link.settle(cx);+ table_region(slot, Rc::new(link))+}++fn error(slot: Div, e: &dyn std::fmt::Display) -> Div {+ slot.child(format!("DataTable: {e}"))+}++fn table_region<T: Send + Sync + 'static>(slot: Div, link: Rc<Link<T>>) -> Div {+ let (state, handle) = (link.state, link.handle);+ handle.ops.update_quiet(|o| *o = Some(Rc::clone(&link) as Rc<dyn Ops>));+ let listener = Rc::clone(&link);+ let table = TableElement::new(&state).on_event(move |e, w, cx| listener.on_event(e, w, cx));+ let menu = handle.menu.get().map(|m| {+ let close = move |_: &ClickEvent, _: &mut Window, _: &mut App| handle.menu.set(None);+ div().absolute().left(px(0.0)).top(px(0.0)).w_full().h_full().on_click(close).child(+ div().absolute().left(px(m.x)).top(px(m.y)).w(px(150.0)).z_index(20).child(build(DataTableColumnHeader::__builder().table(handle).column(m.column.to_string()))),+ )+ });+ slot.child(table).children(menu)+}diff --git a/bindings/rust/blenderui/src/shadcn/table/delegate.rs b/bindings/rust/blenderui/src/shadcn/table/delegate.rsnew file mode 100644index 0000000..8f305ba--- /dev/null+++ b/bindings/rust/blenderui/src/shadcn/table/delegate.rs@@ -0,0 +1,39 @@+//! A TanStack [`Table`] as the delegate of the data table: the engine paints+//! the table's current page straight from it, so there is one source of+//! truth for the data and nothing is copied into the table.++use blenderui_table::tanstack::Table;+use blenderui_table::{Column, ColumnSort};++use crate::table::{TableDelegate, TableState};+use crate::{App, Context, Window};++impl<T: Send + Sync + 'static> TableDelegate for Table<T> {+ fn columns_count(&self, _: &App) -> usize {+ self.column_defs().len()+ }++ fn rows_count(&self, _: &App) -> usize {+ self.row_model().len()+ }++ fn column(&self, col_ix: usize, _: &App) -> Column {+ self.core_column(col_ix)+ }++ /// The table sorts its own row models (typed keys, stable, multi-column),+ /// so the engine's index list stays the identity.+ fn sort_by_mask(&self) -> bool {+ false+ }++ /// A header click: `setSorting` on the table (which may be controlled).+ fn perform_sort(&mut self, col_ix: usize, sort: ColumnSort, _: &mut Window, _: &mut Context<TableState<Self>>) {+ let Some(id) = self.column_defs().get(col_ix).map(|c| c.id.clone()) else { return };+ self.set_column_sort(&id, sort);+ }++ fn empty_text(&self) -> &str {+ "No results."+ }+}diff --git a/bindings/rust/blenderui/src/shadcn/table/handle.rs b/bindings/rust/blenderui/src/shadcn/table/handle.rsnew file mode 100644index 0000000..904b8c8--- /dev/null+++ b/bindings/rust/blenderui/src/shadcn/table/handle.rs@@ -0,0 +1,276 @@+//! [`TableHandle`]: what `useReactTable` returns. A `Copy` handle to a table+//! that the helper components ([`DataTablePagination`](super::DataTablePagination),+//! [`DataTableViewOptions`](super::DataTableViewOptions) ...) read and drive+//! without owning it, so they can sit anywhere in the page.+//!+//! The table itself lives in the [`TableState`](crate::table::TableState) entity+//! the [`DataTable`](super::DataTable) creates. Reading goes through a+//! [`Snapshot`] (a small copy of what the UI shows: counts, page, column+//! list), republished whenever it changes; writing sends a [`Command`] to the+//! entity, which needs the `cx` every event handler has.++use std::rc::Rc;++use blenderui_table::tanstack::{ColumnFilter, ColumnInfo, PaginationState, SortingState, Table};+use blenderui_table::{ColumnSort, Text};++use crate::hooks::{use_signal, Signal};+use crate::App;++/// What the UI reads from a table (`table.getState()`, `getPageCount()` ...).+#[derive(Clone, Debug, Default, PartialEq)]+pub struct Snapshot {+ /// `getAllColumns()`.+ pub columns: Vec<ColumnInfo>,+ pub sorting: SortingState,+ pub column_filters: Vec<ColumnFilter>,+ pub global_filter: String,+ pub pagination: PaginationState,+ /// `getPageCount()`.+ pub page_count: usize,+ /// Rows after filtering (`getPrePaginationRowModel().rows.length`).+ pub row_count: usize,+ /// `getCoreRowModel().rows.length`.+ pub core_row_count: usize,+ /// `getFilteredSelectedRowModel().rows.length`.+ pub selected_count: usize,+ /// Rows on the current page.+ pub page_rows: usize,+}++impl Snapshot {+ pub(crate) fn of<T: Send + Sync>(t: &Table<T>) -> Self {+ Self {+ columns: t.column_infos(),+ sorting: t.sorting().clone(),+ column_filters: t.column_filters().clone(),+ global_filter: t.global_filter().to_owned(),+ pagination: *t.pagination(),+ page_count: t.page_count(),+ row_count: t.row_count(),+ core_row_count: t.core_row_count(),+ selected_count: t.filtered_selected_row_count(),+ page_rows: t.row_model().len(),+ }+ }+}++/// A change to make to a table.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Command {+ PageIndex(usize),+ PageSize(usize),+ FirstPage,+ PreviousPage,+ NextPage,+ LastPage,+ ColumnVisibility(Text, Option<bool>),+ AllColumnsVisible(bool),+ ColumnFilter(Text, String),+ GlobalFilter(String),+ /// `Some(desc)`, or `None` to cycle ascending, descending, none.+ ColumnSorting(Text, Option<bool>),+ ClearColumnSorting(Text),+ /// The checkbox of page row `n` (the row's position on the page).+ TogglePageRow(usize),+ /// The select-all checkbox: selects the page, or deselects it when it is all selected.+ TogglePage,+ AllPageRowsSelected(bool),+ AllRowsSelected(bool),+}++impl Command {+ /// Do this to `t`.+ pub(crate) fn apply<T: Send + Sync>(self, t: &mut Table<T>) {+ match self {+ Self::PageIndex(i) => t.set_page_index(i),+ Self::PageSize(n) => t.set_page_size(n),+ Self::FirstPage => t.first_page(),+ Self::PreviousPage => t.previous_page(),+ Self::NextPage => t.next_page(),+ Self::LastPage => t.last_page(),+ Self::ColumnVisibility(id, v) => t.toggle_column_visibility(&id, v),+ Self::AllColumnsVisible(v) => t.toggle_all_columns_visible(v),+ Self::ColumnFilter(id, v) => t.set_column_filter_value(&id, v),+ Self::GlobalFilter(v) => t.set_global_filter(v),+ Self::ColumnSorting(id, desc) => t.toggle_column_sorting(&id, desc),+ Self::ClearColumnSorting(id) => t.set_column_sort(&id, ColumnSort::Default),+ Self::TogglePageRow(r) => {+ if let Some(row) = t.data_row(r) {+ t.toggle_row_selected(row, None);+ }+ }+ Self::TogglePage => {+ let all = t.is_all_page_rows_selected();+ t.toggle_all_page_rows_selected(!all);+ }+ Self::AllPageRowsSelected(v) => t.toggle_all_page_rows_selected(v),+ Self::AllRowsSelected(v) => t.toggle_all_rows_selected(v),+ }+ }+}++/// The table behind a handle: what the [`DataTable`](super::DataTable) element+/// installs once it has created the entity.+pub(crate) trait Ops {+ /// Apply `cmd`, then publish the snapshot and report the changes.+ fn run(&self, cmd: Command, cx: &mut App);+}++/// The open column-header menu: which column, and where (table coordinates).+#[derive(Clone, Debug, PartialEq)]+pub(crate) struct HeaderMenu {+ pub column: Text,+ pub x: f32,+ pub y: f32,+}++/// `useReactTable`'s result.+///+/// ```ignore+/// let table = use_table();+/// rsx! {+/// <DataTable table={table} columns={columns} data={data} pagination={false} />+/// <DataTablePagination table={table} />+/// }+/// ```+#[derive(Clone, Copy)]+pub struct TableHandle {+ pub(crate) snap: Signal<Snapshot>,+ pub(crate) ops: Signal<Option<Rc<dyn Ops>>>,+ pub(crate) menu: Signal<Option<HeaderMenu>>,+}++/// A table handle for the calling component (the same one on every render).+#[track_caller]+#[must_use]+pub fn use_table() -> TableHandle {+ TableHandle { snap: use_signal(Snapshot::default()), ops: use_signal(None), menu: use_signal(None) }+}++impl TableHandle {+ /// A copy of what the table shows now (as of the last frame).+ #[must_use]+ pub fn snapshot(self) -> Snapshot {+ self.snap.get()+ }++ /// Send `cmd` to the table (nothing happens before the table's first frame).+ pub fn dispatch(self, cmd: Command, cx: &mut App) {+ if let Some(ops) = self.ops.get() {+ ops.run(cmd, cx);+ cx.notify_all();+ }+ }++ // -- reading (`table.getState()` and friends) --------------------------------------------------------------++ #[must_use]+ pub fn page_index(self) -> usize {+ self.snap.with(|s| s.pagination.page_index)+ }++ #[must_use]+ pub fn page_size(self) -> usize {+ self.snap.with(|s| s.pagination.page_size)+ }++ #[must_use]+ pub fn page_count(self) -> usize {+ self.snap.with(|s| s.page_count)+ }++ #[must_use]+ pub fn can_previous_page(self) -> bool {+ self.page_index() > 0+ }++ #[must_use]+ pub fn can_next_page(self) -> bool {+ self.snap.with(|s| s.pagination.page_index + 1 < s.page_count)+ }++ /// `getFilteredSelectedRowModel().rows.length`.+ #[must_use]+ pub fn selected_row_count(self) -> usize {+ self.snap.with(|s| s.selected_count)+ }++ /// `getFilteredRowModel().rows.length`.+ #[must_use]+ pub fn filtered_row_count(self) -> usize {+ self.snap.with(|s| s.row_count)+ }++ /// `getAllColumns()`.+ #[must_use]+ pub fn columns(self) -> Vec<ColumnInfo> {+ self.snap.with(|s| s.columns.clone())+ }++ /// `column.getFilterValue()`.+ #[must_use]+ pub fn column_filter_value(self, id: &str) -> String {+ self.snap.with(|s| s.column_filters.iter().find(|f| f.id == id).map(|f| f.value.clone()).unwrap_or_default())+ }++ #[must_use]+ pub fn global_filter(self) -> String {+ self.snap.with(|s| s.global_filter.clone())+ }++ // -- writing -------------------------------------------------------------------------------------------------++ pub fn set_page_index(self, index: usize, cx: &mut App) {+ self.dispatch(Command::PageIndex(index), cx);+ }++ pub fn set_page_size(self, size: usize, cx: &mut App) {+ self.dispatch(Command::PageSize(size), cx);+ }++ pub fn first_page(self, cx: &mut App) {+ self.dispatch(Command::FirstPage, cx);+ }++ pub fn previous_page(self, cx: &mut App) {+ self.dispatch(Command::PreviousPage, cx);+ }++ pub fn next_page(self, cx: &mut App) {+ self.dispatch(Command::NextPage, cx);+ }++ pub fn last_page(self, cx: &mut App) {+ self.dispatch(Command::LastPage, cx);+ }++ /// `column.toggleVisibility(value)`; `None` flips it.+ pub fn toggle_column_visibility(self, id: impl Into<Text>, visible: Option<bool>, cx: &mut App) {+ self.dispatch(Command::ColumnVisibility(id.into(), visible), cx);+ }++ /// `column.setFilterValue(value)`: an empty value clears the filter.+ pub fn set_column_filter_value(self, id: impl Into<Text>, value: impl Into<String>, cx: &mut App) {+ self.dispatch(Command::ColumnFilter(id.into(), value.into()), cx);+ }++ pub fn set_global_filter(self, value: impl Into<String>, cx: &mut App) {+ self.dispatch(Command::GlobalFilter(value.into()), cx);+ }++ /// `column.toggleSorting(desc)`; `None` cycles ascending, descending, none.+ pub fn toggle_column_sorting(self, id: impl Into<Text>, desc: Option<bool>, cx: &mut App) {+ self.dispatch(Command::ColumnSorting(id.into(), desc), cx);+ }++ /// `table.toggleAllPageRowsSelected(value)`.+ pub fn toggle_all_page_rows_selected(self, selected: bool, cx: &mut App) {+ self.dispatch(Command::AllPageRowsSelected(selected), cx);+ }++ /// `table.toggleAllRowsSelected(value)`.+ pub fn toggle_all_rows_selected(self, selected: bool, cx: &mut App) {+ self.dispatch(Command::AllRowsSelected(selected), cx);+ }+}diff --git a/bindings/rust/blenderui/src/shadcn/table/link.rs b/bindings/rust/blenderui/src/shadcn/table/link.rsnew file mode 100644index 0000000..b625062--- /dev/null+++ b/bindings/rust/blenderui/src/shadcn/table/link.rs@@ -0,0 +1,121 @@+//! The link between a table entity, its [`TableHandle`] and the callbacks:+//! applies commands, keeps the view and the snapshot in step with the+//! table, and reports changes (`onSortingChange` and friends).++use blenderui_table::tanstack::{Change, PaginationState, RowSelectionState, SortingState, Table, TableError, TableOptions};+use blenderui_table::{ColumnSort, TableEvent};++use super::handle::{Command, HeaderMenu, Ops, Snapshot, TableHandle};+use crate::table::TableState;+use crate::{App, Entity, Window};++type Callback<T> = Option<Box<dyn Fn(&T)>>;++/// `onXChange` callbacks, and the row-action handler.+#[derive(Default)]+pub(crate) struct Callbacks {+ pub sorting: Callback<SortingState>,+ pub column_filters: Callback<Vec<blenderui_table::tanstack::ColumnFilter>>,+ pub global_filter: Callback<String>,+ pub column_visibility: Callback<blenderui_table::tanstack::VisibilityState>,+ pub row_selection: Callback<RowSelectionState>,+ pub pagination: Callback<PaginationState>,+ /// The "more" button of a row (the index of the row in the data).+ pub row_action: Option<Box<dyn Fn(usize, &mut Window, &mut App)>>,+}++impl Callbacks {+ fn fire(&self, change: &Change) {+ match change {+ Change::Sorting(v) => self.sorting.iter().for_each(|f| f(v)),+ Change::ColumnFilters(v) => self.column_filters.iter().for_each(|f| f(v)),+ Change::GlobalFilter(v) => self.global_filter.iter().for_each(|f| f(v)),+ Change::ColumnVisibility(v) => self.column_visibility.iter().for_each(|f| f(v)),+ Change::RowSelection(v) => self.row_selection.iter().for_each(|f| f(v)),+ Change::Pagination(v) => self.pagination.iter().for_each(|f| f(v)),+ }+ }+}++/// One table entity with everything that drives it.+pub(crate) struct Link<T: Send + Sync + 'static> {+ pub state: Entity<TableState<Table<T>>>,+ pub handle: TableHandle,+ pub callbacks: Callbacks,+}++impl<T: Send + Sync + 'static> Link<T> {+ /// Hand new options to the table (a parent re-rendered).+ pub fn set_options(&self, opts: TableOptions<T>, cx: &mut App) -> Result<(), TableError> {+ let changed = self.state.update(cx, |s, _| s.delegate_mut().set_options(opts))?;+ if changed {+ self.settle(cx);+ }+ Ok(())+ }++ /// The table changed (or may have): refresh the engine's view of it,+ /// publish the snapshot, report the changes. Always from outside any+ /// borrow of the table.+ pub fn settle(&self, cx: &mut App) {+ let (changes, snap) = self.state.update(cx, |s, c| {+ let t = s.delegate_mut();+ let (changes, snap) = (t.take_changes(), Snapshot::of(t));+ let dirty = t.take_dirty();+ let sorted = t.sorting().first().and_then(|r| t.column_index(&r.id).map(|i| (i, if r.desc { ColumnSort::Descending } else { ColumnSort::Ascending })));+ let highlights: Vec<usize> = if dirty {+ (0..t.row_model().len()).filter(|&r| t.data_row(r).is_some_and(|d| t.is_row_selected(d))).collect()+ } else {+ Vec::new()+ };+ // the engine keeps its own sort indicator when a header is clicked: ours is the truth+ s.set_sort_indicator(sorted);+ s.refresh(c);+ if dirty {+ s.set_row_highlights(highlights);+ }+ (changes, snap)+ });+ if self.handle.snap.with(|old| *old != snap) {+ self.handle.snap.set(snap);+ }+ for change in &changes {+ self.callbacks.fire(change);+ }+ }++ /// A table event (after an input the table handled).+ pub fn on_event(&self, e: &TableEvent, window: &mut Window, cx: &mut App) {+ match e {+ TableEvent::CheckRow(row, _) => self.run(Command::TogglePageRow(*row), cx),+ TableEvent::CheckAll(_) => self.run(Command::TogglePage, cx),+ TableEvent::CellAction(row, _) => {+ if let Some(f) = &self.callbacks.row_action+ && let Some(data_row) = self.state.read(cx).delegate().data_row(*row)+ {+ f(data_row, window, cx);+ }+ }+ TableEvent::HeaderMenu(col) => self.open_menu(*col, cx),+ TableEvent::Sorted(..) => self.settle(cx),+ _ => {}+ }+ window.refresh();+ }++ fn open_menu(&self, col: usize, cx: &mut App) {+ let spot = {+ let s = self.state.read(cx);+ let (g, id) = (s.geo(), s.delegate().column_defs().get(col).map(|c| c.id.clone()));+ s.layout().view_of(col).zip(id).map(|(v, id)| HeaderMenu { column: id, x: s.col_x(&g, v), y: g.groups_h + g.header_h })+ };+ self.handle.menu.set(spot);+ }+}++impl<T: Send + Sync + 'static> Ops for Link<T> {+ fn run(&self, cmd: Command, cx: &mut App) {+ self.state.update(cx, |s, _| cmd.apply(s.delegate_mut()));+ self.settle(cx);+ }+}diff --git a/bindings/rust/blenderui/src/shadcn/table/mod.rs b/bindings/rust/blenderui/src/shadcn/table/mod.rsnew file mode 100644index 0000000..4e86331--- /dev/null+++ b/bindings/rust/blenderui/src/shadcn/table/mod.rs@@ -0,0 +1,36 @@+//! shadcn/ui's Data Table: TanStack's `ColumnDef`, table state and row+//! models over the painted table engine.+//!+//! | shadcn / TanStack | here |+//! |---|---|+//! | `ColumnDef<TData>` | [`ColumnDef`] |+//! | `accessorKey: "email"` | `ColumnDef::accessor_key("email")` (the row type implements [`Record`]) |+//! | `accessorFn`, `id` | `ColumnDef::accessor_fn("id", \|row\| Cell::Str(&row.email))` |+//! | `header: "Email"` / `({ column }) => <DataTableColumnHeader .../>` | `.header("Email")` / `.header(Header::menu("Email"))` |+//! | `cell: ({ row }) => <JSX/>` | `.cell(CellRender::..)`, `.badge(..)`, `.meta(..)`: typed cells (see the docs) |+//! | `useReactTable({ data, columns, ... })` | [`use_table`] + [`DataTable`] |+//! | `<DataTable columns={columns} data={data} />` | the same in `rsx!`, or `DataTable::new(columns, data)` |+//! | `<DataTablePagination table={table} />` | [`DataTablePagination`] |+//! | `<DataTableViewOptions table={table} />` | [`DataTableViewOptions`] |+//! | `onSortingChange`, `state`, `initialState` ... | `on_sorting_change`, `sorting`, `initial_state` ... |++mod column_header;+mod data_table;+mod delegate;+mod handle;+mod link;+mod pagination;+mod toolbar;+mod view_options;++pub use blenderui_table::tanstack::{+ actions_column, select_column, Change, ColumnDef, ColumnFilter, ColumnFiltersState, ColumnInfo, ColumnMeta, Header, PaginationState, PartialState, Record,+ RowSelectionState, SortingRule, SortingState, Table, TableError, TableOptions, TableState, VisibilityState,+};+pub use blenderui_table::{BadgeVariant, Cell, CellRender, ColumnSort, NumberFormat};+pub use column_header::DataTableColumnHeader;+pub use data_table::DataTable;+pub use handle::{use_table, Command, Snapshot, TableHandle};+pub use pagination::DataTablePagination;+pub use toolbar::DataTableToolbar;+pub use view_options::DataTableViewOptions;diff --git a/bindings/rust/blenderui/src/shadcn/table/pagination.rs b/bindings/rust/blenderui/src/shadcn/table/pagination.rsnew file mode 100644index 0000000..8cc10fc--- /dev/null+++ b/bindings/rust/blenderui/src/shadcn/table/pagination.rs@@ -0,0 +1,42 @@+//! `DataTablePagination`: shadcn's `data-table-pagination.tsx`.++use super::handle::TableHandle;+use crate::prelude::*;++/// Rows per page, "Page x of y", first / previous / next / last, and "N of M+/// row(s) selected.". `page_sizes` are the choices of the "Rows per page"+/// menu (default 10, 20, 30, 40, 50).+#[component]+pub fn DataTablePagination(table: TableHandle, page_sizes: Option<Vec<usize>>) {+ let sizes = page_sizes.unwrap_or_else(|| vec![10, 20, 30, 40, 50]);+ let snap = table.snapshot();+ let selected = format!("{} of {} row(s) selected.", snap.selected_count, snap.row_count);+ let page = format!("Page {} of {}", snap.pagination.page_index + 1, snap.page_count);+ let (prev, next) = (table.can_previous_page(), table.can_next_page());+ let size = snap.pagination.page_size;+ let choices = sizes.clone();+ rsx! {+ <div flex items-center justify-between gap-4 px-2 text-sm>+ <div flex-1 whitespace-nowrap opacity-70>{selected}</div>+ <div flex items-center gap-6>+ <div flex items-center gap-2>+ <span whitespace-nowrap>"Rows per page"</span>+ <Dropdown onChange={move |e: &ChangeEvent, _: &mut Window, cx: &mut App| {+ if let Some(&n) = choices.get(e.number as usize) {+ table.set_page_size(n, cx);+ }+ }}>+ {for n in sizes { <option selected={n == size}>{n.to_string()}</option> }}+ </Dropdown>+ </div>+ <div flex w-28 items-center justify-center>{page}</div>+ <div flex items-center gap-2>+ <Button disabled={!prev} onClick={move |_: &ClickEvent, _: &mut Window, cx: &mut App| table.first_page(cx)}>"<<"</Button>+ <Button disabled={!prev} onClick={move |_: &ClickEvent, _: &mut Window, cx: &mut App| table.previous_page(cx)}>"<"</Button>+ <Button disabled={!next} onClick={move |_: &ClickEvent, _: &mut Window, cx: &mut App| table.next_page(cx)}>">"</Button>+ <Button disabled={!next} onClick={move |_: &ClickEvent, _: &mut Window, cx: &mut App| table.last_page(cx)}>">>"</Button>+ </div>+ </div>+ </div>+ }+}diff --git a/bindings/rust/blenderui/src/shadcn/table/toolbar.rs b/bindings/rust/blenderui/src/shadcn/table/toolbar.rsnew file mode 100644index 0000000..56a6ef4--- /dev/null+++ b/bindings/rust/blenderui/src/shadcn/table/toolbar.rs@@ -0,0 +1,25 @@+//! `DataTableToolbar`: the filter `Input` and the view options above a table+//! (the top row of shadcn's Data Table example).++use super::handle::TableHandle;+use super::view_options::DataTableViewOptions;+use crate::prelude::*;++/// A text field that filters column `filter_column` (`column.setFilterValue`),+/// or every column (`table.setGlobalFilter`) when no column is named, and the+/// "View" menu at the right (hide it with `view_options={false}`).+#[component]+pub fn DataTableToolbar(table: TableHandle, filter_column: Option<String>, placeholder: Option<String>, view_options: Option<bool>) {+ let current = filter_column.as_deref().map_or_else(|| table.global_filter(), |c| table.column_filter_value(c));+ let hint = placeholder.unwrap_or_else(|| filter_column.as_ref().map_or_else(|| "Filter...".to_owned(), |c| format!("Filter {c}...")));+ let on_change = move |e: &ChangeEvent, _: &mut Window, cx: &mut App| match &filter_column {+ Some(c) => table.set_column_filter_value(c.clone(), e.value.clone(), cx),+ None => table.set_global_filter(e.value.clone(), cx),+ };+ rsx! {+ <div flex items-center gap-2>+ <TextField w-64 placeholder={hint} value={current} onChange={on_change} />+ {if view_options.unwrap_or(true) { <div ml-auto><DataTableViewOptions table={table} /></div> }}+ </div>+ }+}diff --git a/bindings/rust/blenderui/src/shadcn/table/view_options.rs b/bindings/rust/blenderui/src/shadcn/table/view_options.rsnew file mode 100644index 0000000..a480fd4--- /dev/null+++ b/bindings/rust/blenderui/src/shadcn/table/view_options.rs@@ -0,0 +1,60 @@+//! `DataTableViewOptions`: shadcn's `data-table-view-options.tsx`, the+//! column-visibility dropdown.++use super::handle::TableHandle;+use crate::prelude::*;+use crate::shadcn::theme;++/// A "View" button that opens a list of the columns that can be hidden, each+/// with a check that toggles it (`column.toggleVisibility`).+#[component]+pub fn DataTableViewOptions(table: TableHandle) {+ let (open, set_open) = use_state(false);+ let (text, hover) = (theme("menu_item.text", black()), theme("menu_item.inner_sel", Rgba::TRANSPARENT));+ let accent = theme("menu_item.inner_sel", Rgba { r: 0.3, g: 0.55, b: 0.85, a: 1.0 });+ let rows = table.columns().into_iter().filter(|c| c.can_hide).map(|c| {+ let id = c.id.clone();+ let mark = div()+ .w(px(12.0))+ .h(px(12.0))+ .rounded_sm()+ .border_1()+ .border_color(text)+ .when(c.visible, |d| d.bg(accent).border_color(accent));+ div()+ .flex()+ .items_center()+ .gap_2()+ .px_2()+ .py_1()+ .rounded_md()+ .cursor_pointer()+ .hover(move |s| s.bg(hover).text_color(theme("menu_item.text_sel", black())))+ .on_click(move |_: &ClickEvent, _: &mut Window, cx: &mut App| table.toggle_column_visibility(id.clone(), None, cx))+ .child(mark)+ .child(c.title.to_string())+ });+ let panel = div()+ .absolute()+ .right(px(0.0))+ .top(px(30.0))+ .z_index(20)+ .min_w(px(160.0))+ .flex()+ .flex_col()+ .p_1()+ .rounded_md()+ .border_1()+ .border_color(theme("menu_back.outline", Rgba::TRANSPARENT))+ .bg(theme("menu_back.inner", Rgba { r: 0.1, g: 0.1, b: 0.1, a: 1.0 }))+ .text_color(text)+ .text_size(px(13.0))+ .child(div().px_2().py_1().opacity(0.6).child("Toggle columns"))+ .children(rows);+ rsx! {+ <div relative>+ <Button onClick={move || set_open(!open())}>"View"</Button>+ {if open() { panel }}+ </div>+ }+}diff --git a/bindings/rust/blenderui/src/shadcn/virtual_list.rs b/bindings/rust/blenderui/src/shadcn/virtual_list.rsnew file mode 100644index 0000000..87e06fe--- /dev/null+++ b/bindings/rust/blenderui/src/shadcn/virtual_list.rs@@ -0,0 +1,445 @@+//! A virtual list in shadcn's component style, with TanStack Virtual's names.+//! shadcn/ui has no virtual list, so this follows `@tanstack/react-virtual`:+//!+//! | TanStack Virtual | here |+//! |---|---|+//! | `count` | `count` ([`VirtualList`]); a [`ChatList`] has its `messages` |+//! | `estimateSize` | `estimate_size` (px of a one-line item before it is measured) |+//! | `overscan` | `overscan` (items beyond the viewport the source is asked for) |+//! | `getItemKey` | `get_item_key` (ascending keys) |+//! | `scrollToIndex(index, { align })` | [`ListHandle::scroll_to_index`] |+//! | `scrollToOffset(offset)` | [`ListHandle::scroll_to_offset`] |+//! | `measureElement` | [`ListHandle::measure_element`] (a height you know) |+//! | `onChange` / `range` | `on_range_change`, [`ListHandle::range`] |+//! | `getTotalSize()`, `scrollOffset` | [`ListHandle::view_info`] |+//!+//! The rows are not elements: the engine draws visible rows' wrapped text+//! straight from the source ([`blenderui_vlist`]), so a list of ten million+//! items costs what a screenful does. An item is therefore text+//! (`item(index, out)` writes it), not JSX.++use std::rc::Rc;+use std::sync::Arc;++pub use blenderui_vlist::{Align, Message};+pub use crate::vlist::ViewInfo;+use blenderui_vlist::{ChatList as ChatCore, CountSource, ItemSource, List, Options, RowList, RowStyle};++use crate::css::Decl;+use crate::hooks::{use_signal, Complete, Signal};+use crate::prelude::*;+use crate::vlist::{chat_list, theme_palette, variable_list, ListState};++/// Writes the text of item `index` into the buffer (`item`).+pub type ItemText = Box<dyn Fn(usize, &mut String)>;++/// A change to make to a list (what `scrollToIndex` and friends send).+#[derive(Clone, Debug, PartialEq)]+pub enum ListCommand {+ ScrollToIndex(usize, Align),+ ScrollToOffset(f64),+ ScrollToEnd,+ /// A height in px that is known for sure (`measureElement`).+ MeasureElement(usize, f64),+ /// A new message at the end ([`ChatList`] only).+ Push(Message),+ /// Replace the text of message `n` ([`ChatList`] only).+ Edit(usize, String),+ /// The items changed without the count changing: measure again.+ Invalidate,+}++/// A list the commands apply to.+trait Drive {+ fn apply(&mut self, cmd: ListCommand);+}++fn common<S: ItemSource, P: blenderui_vlist::Measurer + blenderui_vlist::ItemPainter + Clone>(list: &mut List<S, P>, cmd: ListCommand) {+ match cmd {+ ListCommand::ScrollToIndex(i, align) => list.view.jump_to(i, align),+ ListCommand::ScrollToOffset(px) => list.view.scroll_to_offset(px),+ ListCommand::ScrollToEnd => list.view.scroll_to_end(),+ ListCommand::MeasureElement(i, px) => list.view.set_known_height(i, px),+ ListCommand::Invalidate => {+ let style = list.style.clone();+ list.restyle(style);+ }+ ListCommand::Push(_) | ListCommand::Edit(..) => {}+ }+}++impl Drive for RowList {+ fn apply(&mut self, cmd: ListCommand) {+ common(self, cmd);+ }+}++impl Drive for ChatCore {+ fn apply(&mut self, cmd: ListCommand) {+ match cmd {+ ListCommand::Push(m) => self.push(m),+ ListCommand::Edit(i, text) => self.edit(i, &text),+ other => common(self, other),+ }+ }+}++/// The list behind a handle.+trait ListOps {+ fn run(&self, cmd: ListCommand, cx: &mut App);+ fn info(&self, cx: &App) -> ViewInfo;+}++struct ListLink<S: ItemSource + 'static, P: blenderui_vlist::Measurer + blenderui_vlist::ItemPainter + 'static> {+ state: Entity<ListState<S, P>>,+}++impl<S: ItemSource + 'static, P: blenderui_vlist::Measurer + blenderui_vlist::ItemPainter + 'static> ListOps for ListLink<S, P>+where+ List<S, P>: Drive,+{+ fn run(&self, cmd: ListCommand, cx: &mut App) {+ self.state.update(cx, |s, _| s.apply(cmd));+ }++ fn info(&self, cx: &App) -> ViewInfo {+ self.state.read(cx).view_info()+ }+}++/// `useVirtualizer`'s result: a `Copy` handle to a list.+///+/// ```ignore+/// let list = use_virtual_list();+/// rsx! { <VirtualList list={list} count={1_000_000} item={|i: usize, out: &mut String| out.push_str(&i.to_string())} /> }+/// // in a handler:+/// list.scroll_to_index(500, Align::Center, cx);+/// ```+#[derive(Clone, Copy)]+pub struct ListHandle {+ view: Signal<ViewInfo>,+ ops: Signal<Option<Rc<dyn ListOps>>>,+}++/// A list handle for the calling component (the same one on every render).+#[track_caller]+#[must_use]+pub fn use_virtual_list() -> ListHandle {+ ListHandle { view: use_signal(ViewInfo::default()), ops: use_signal(None) }+}++impl ListHandle {+ /// Send `cmd` to the list (nothing happens before its first frame).+ pub fn dispatch(self, cmd: ListCommand, cx: &mut App) {+ if let Some(ops) = self.ops.get() {+ ops.run(cmd, cx);+ cx.notify_all();+ }+ }++ /// `scrollToIndex(index, { align })`.+ pub fn scroll_to_index(self, index: usize, align: Align, cx: &mut App) {+ self.dispatch(ListCommand::ScrollToIndex(index, align), cx);+ }++ /// `scrollToOffset(offset)`, px from the top.+ pub fn scroll_to_offset(self, offset: f64, cx: &mut App) {+ self.dispatch(ListCommand::ScrollToOffset(offset), cx);+ }++ /// Scroll to the end of the list.+ pub fn scroll_to_end(self, cx: &mut App) {+ self.dispatch(ListCommand::ScrollToEnd, cx);+ }++ /// `measureElement`: item `index` is `height` px tall.+ pub fn measure_element(self, index: usize, height: f64, cx: &mut App) {+ self.dispatch(ListCommand::MeasureElement(index, height), cx);+ }++ /// Items changed without the count changing: measure again.+ pub fn invalidate(self, cx: &mut App) {+ self.dispatch(ListCommand::Invalidate, cx);+ }++ /// A new message at the end of a [`ChatList`].+ pub fn push(self, message: Message, cx: &mut App) {+ self.dispatch(ListCommand::Push(message), cx);+ }++ /// The items in the viewport as of the last range change (`range`).+ #[must_use]+ pub fn range(self) -> std::ops::Range<usize> {+ self.view.with(|v| v.range.clone())+ }++ /// The item count as of the last range change.+ #[must_use]+ pub fn count(self) -> usize {+ self.view.with(|v| v.count)+ }++ /// The list now: range, count, `scrollOffset` and `getTotalSize()`.+ #[must_use]+ pub fn view_info(self, cx: &App) -> Option<ViewInfo> {+ self.ops.get().map(|o| o.info(cx))+ }+}++/// What every list component takes besides its content.+pub struct ListExtras {+ base: Div,+ handle: Option<ListHandle>,+ options: Options,+ on_range_change: Option<Rc<dyn Fn(&ViewInfo)>>,+}++impl ListExtras {+ fn new() -> Self {+ Self { base: div().relative().overflow_hidden().size_full(), handle: None, options: Options::default(), on_range_change: None }+ }+}++/// The props every list component shares, written once.+pub trait ListProps: Sized {+ #[doc(hidden)]+ fn extras_mut(&mut self) -> &mut ListExtras;++ /// A handle from [`use_virtual_list`], to scroll and read the list.+ #[must_use]+ fn list(mut self, handle: ListHandle) -> Self {+ self.extras_mut().handle = Some(handle);+ self+ }++ /// `estimateSize`: the height in px an item of one line is assumed to+ /// have until it is measured. Read when the list is created.+ #[must_use]+ fn estimate_size(mut self, px: f32) -> Self {+ self.extras_mut().options.estimate_size = Some(px);+ self+ }++ /// `overscan`: items beyond the viewport the source is asked for. Read+ /// when the list is created.+ #[must_use]+ fn overscan(mut self, items: usize) -> Self {+ self.extras_mut().options.overscan = items;+ self+ }++ /// `onChange`: the visible range or the count changed.+ #[must_use]+ fn on_range_change(mut self, f: impl Fn(&ViewInfo) + 'static) -> Self {+ self.extras_mut().on_range_change = Some(Rc::new(f));+ self+ }++ /// Stay at the end while new items arrive (the chat default), or not.+ #[must_use]+ fn stick_to_bottom(mut self, on: bool) -> Self {+ self.extras_mut().options.stick_to_bottom = on;+ self+ }+}++macro_rules! styled_list {+ ($($ty:ident<$($g:ident),*>)*) => {$(+ impl<$($g),*> Styled for $ty<$($g),*> {+ fn decls_mut(&mut self) -> &mut Vec<Decl> {+ self.extras.base.decls_mut()+ }+ }+ impl<$($g),*> ListProps for $ty<$($g),*> {+ fn extras_mut(&mut self) -> &mut ListExtras {+ &mut self.extras+ }+ }+ )*};+}++/// A virtualized list of `count` text items (TanStack Virtual's model).+///+/// ```ignore+/// // rsx!+/// rsx! { <VirtualList count={10_000_000} item={|i: usize, out: &mut String| out.push_str("row")} overscan={8} h={px(400.0)} /> }+/// // builder+/// VirtualList::new(10_000_000, |i, out| out.push_str("row")).overscan(8).h(px(400.0))+/// ```+pub struct VirtualList<C = usize, I = ItemText> {+ count: C,+ item: I,+ key: Option<Box<dyn Fn(usize) -> u64>>,+ extras: ListExtras,+}++styled_list! { VirtualList<C, I> }++impl VirtualList<(), ()> {+ /// `count` items; item `i`'s text is what `item(i, out)` pushes to `out`.+ pub fn new(count: usize, item: impl Fn(usize, &mut String) + 'static) -> VirtualList {+ Self::__builder().count(count).item(item)+ }++ #[doc(hidden)]+ #[must_use]+ pub fn __builder() -> Self {+ Self { count: (), item: (), key: None, extras: ListExtras::new() }+ }+}++impl<I> VirtualList<(), I> {+ /// `count`.+ pub fn count(self, count: usize) -> VirtualList<usize, I> {+ VirtualList { count, item: self.item, key: self.key, extras: self.extras }+ }+}++impl<C> VirtualList<C, ()> {+ /// The text of each item: `item(index, out)` pushes it to `out`.+ pub fn item(self, item: impl Fn(usize, &mut String) + 'static) -> VirtualList<C, ItemText> {+ VirtualList { count: self.count, item: Box::new(item), key: self.key, extras: self.extras }+ }+}++impl<C, I> VirtualList<C, I> {+ /// `getItemKey`: a stable key per index, ascending with the index.+ #[must_use]+ pub fn get_item_key(mut self, key: impl Fn(usize) -> u64 + 'static) -> Self {+ self.key = Some(Box::new(key));+ self+ }+}++impl Complete for VirtualList {+ type Props = Self;+ fn finish(self) -> Self {+ self+ }+}++type ListSlot<S, P> = Signal<Option<Entity<ListState<S, P>>>>;++/// Publish range changes to the handle and the user's callback.+fn view_changed(handle: ListHandle, user: Option<Rc<dyn Fn(&ViewInfo)>>) -> impl Fn(&ViewInfo) + 'static {+ move |info: &ViewInfo| {+ if handle.view.with(|v| v != info) {+ handle.view.set(info.clone());+ }+ if let Some(f) = &user {+ f(info);+ }+ }+}++impl IntoElement for VirtualList {+ fn into_any_element(self) -> AnyElement {+ let Self { count, item, key, extras: ListExtras { base, handle, options, on_range_change } } = self;+ let own = use_virtual_list();+ let slot: ListSlot<CountSource, RowStyle> = use_signal(None);+ let handle = handle.unwrap_or(own);+ base.defer(move |_, cx, el| {+ let state = match slot.get() {+ Some(state) => {+ state.update(cx, |s, _| {+ let old = s.source.set_count(count);+ s.source.set_text(item);+ s.source.set_key(key);+ let bytes = s.source.avg_bytes();+ // an index error cannot happen below 2^40 items+ if count > old {+ let _ = s.view.appended(count - old, (count - old) as u64 * bytes);+ } else if count < old {+ s.view.removed(count, old - count, (old - count) as u64 * bytes);+ }+ });+ state+ }+ None => {+ let mut source = CountSource::new(count, item);+ source.set_key(key);+ let list = List::new(source, RowStyle::new(theme_palette()), 400.0, 300.0, options).expect("a count below 2^40 fits the index");+ let state = cx.new(|cx| ListState::new(list, cx));+ slot.set(Some(state));+ state+ }+ };+ handle.ops.update_quiet(|o| *o = Some(Rc::new(ListLink { state })));+ let select = |i: usize, list: &mut RowList| {+ let id = list.source.id_at(i);+ list.style.selected = if list.style.selected == id { None } else { id };+ };+ let taken = std::mem::replace(el, Div::new("div"));+ *el = taken.child(variable_list(&state).on_item_click(select).on_view_change(view_changed(handle, on_range_change)));+ })+ .into_any_element()+ }+}++/// A chat: a [`VirtualList`] of messages (avatars, runs, day dividers, whole-message+/// selection by click). `messages` is compared by identity: pass the same `Arc`+/// to keep the list, a new one to start another conversation; append with+/// [`ListHandle::push`].+///+/// ```ignore+/// rsx! { <ChatList messages={messages} h={px(400.0)} /> }+/// ChatList::new(messages).h(px(400.0))+/// ```+pub struct ChatList<M = Arc<[Message]>> {+ messages: M,+ extras: ListExtras,+}++styled_list! { ChatList<M> }++impl ChatList<()> {+ /// A chat of `messages`.+ pub fn new(messages: impl Into<Arc<[Message]>>) -> ChatList {+ Self::__builder().messages(messages)+ }++ #[doc(hidden)]+ #[must_use]+ pub fn __builder() -> Self {+ let mut extras = ListExtras::new();+ extras.options.start_at_end = true;+ Self { messages: (), extras }+ }++ /// `messages`.+ pub fn messages(self, messages: impl Into<Arc<[Message]>>) -> ChatList {+ ChatList { messages: messages.into(), extras: self.extras }+ }+}++impl Complete for ChatList {+ type Props = Self;+ fn finish(self) -> Self {+ self+ }+}++impl IntoElement for ChatList {+ fn into_any_element(self) -> AnyElement {+ let Self { messages, extras: ListExtras { base, handle, options, on_range_change } } = self;+ let own = use_virtual_list();+ let slot: ListSlot<blenderui_vlist::VecSource, blenderui_vlist::ChatStyle> = use_signal(None);+ let shown: Signal<Option<Arc<[Message]>>> = use_signal(None);+ let handle = handle.unwrap_or(own);+ base.defer(move |_, cx, el| {+ let fresh = shown.with(|s| s.as_ref().is_none_or(|s| !Arc::ptr_eq(s, &messages)));+ let existing = slot.get().filter(|_| !fresh);+ let state = existing.unwrap_or_else(|| {+ shown.update_quiet(|s| *s = Some(Arc::clone(&messages)));+ let list = ChatCore::from_messages(messages.to_vec(), theme_palette(), 400.0, 300.0, options);+ let state = cx.new(|cx| ListState::new(list, cx));+ slot.set(Some(state));+ state+ });+ handle.ops.update_quiet(|o| *o = Some(Rc::new(ListLink { state })));+ let taken = std::mem::replace(el, Div::new("div"));+ *el = taken.child(chat_list(&state).on_view_change(view_changed(handle, on_range_change)));+ })+ .into_any_element()+ }+}diff --git a/bindings/rust/blenderui/src/table/sink.rs b/bindings/rust/blenderui/src/table/sink.rsindex a95db02..1e21e9e 100644--- a/bindings/rust/blenderui/src/table/sink.rs+++ b/bindings/rust/blenderui/src/table/sink.rs@@ -114,4 +114,72 @@ mod tests {assert_eq!(COUNT.get(), 0, "a steady-state frame allocated");});}++ /// The shadcn layer paints through the same engine: a million rows with a+ /// checkbox, a badge, a currency, a progress bar and an actions column.+ #[derive(Clone, Copy)]+ struct Idx(u32);++ impl crate::shadcn::Record for Idx {+ const FIELDS: &'static [&'static str] = &["status", "amount", "pct"];+ fn field(&self, field: usize) -> TableCell<'_> {+ match field {+ 0 => TableCell::Str(["pending", "processing", "success", "failed"][self.0 as usize % 4]),+ 1 => TableCell::F64(f64::from(self.0 % 100_000) / 7.0, 2),+ _ => TableCell::U64(u64::from(self.0 % 101)),+ }+ }+ }++ #[test]+ fn steady_state_shadcn_table_does_not_allocate() {+ use crate::shadcn::{actions_column, select_column, BadgeVariant, CellRender, ColumnDef, ColumnMeta, Table, TableOptions};+ use std::sync::Arc;+ let columns: Arc<[ColumnDef<Idx>]> = vec![+ select_column(),+ ColumnDef::accessor_key("status").badge(|s| if s == "failed" { BadgeVariant::Destructive } else { BadgeVariant::Secondary }),+ ColumnDef::accessor_key("amount").meta(ColumnMeta::right().usd()),+ ColumnDef::accessor_key("pct").cell(CellRender::Progress),+ actions_column(),+ ]+ .into();+ let data: Arc<[Idx]> = (0..1_000_000u32).map(Idx).collect();+ Application::headless().run(|cx| {+ let table = Table::new(TableOptions::new(columns, data)).unwrap();+ assert_eq!(table.row_model().len(), 1_000_000);+ let mut handle = None;+ let win = cx+ .open_window(WindowOptions::default(), |w, cx| {+ let t = cx.new(|cx| TableState::new(table, w, cx).row_selectable(false));+ handle = Some(t);+ cx.new(|_| ShadcnView(t))+ })+ .unwrap();+ let t = handle.unwrap();+ cx.draw(win.id);+ cx.draw(win.id);+ t.update(cx, |s, _| s.scroll_by(0.0, 5_000_000.0));+ let st = t.read(cx);+ let b = st.bounds;+ assert!(b.size.width > 100.0);+ let mut p = Painter::new();+ for _ in 0..4 {+ p.reset();+ st.draw(b, &mut p);+ }+ p.reset();+ ARMED.set(true);+ COUNT.set(0);+ st.draw(b, &mut p);+ ARMED.set(false);+ assert_eq!(COUNT.get(), 0, "a steady-state frame of the shadcn table allocated");+ });+ }++ struct ShadcnView(Entity<TableState<crate::shadcn::Table<Idx>>>);+ impl Render for ShadcnView {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ body().m_0().child(div().w(px(900.0)).h(px(500.0)).child(DataTable::new(&self.0)))+ }+ }}diff --git a/bindings/rust/blenderui/src/vlist/element.rs b/bindings/rust/blenderui/src/vlist/element.rsindex 647779d..0a5a130 100644--- a/bindings/rust/blenderui/src/vlist/element.rs+++ b/bindings/rust/blenderui/src/vlist/element.rs@@ -10,7 +10,7 @@ use std::rc::Rc;use blenderui_vlist::{ChatStyle, Hit, ItemPainter, ItemSource, List, Measurer, VecSource};-use super::state::ListState;+use super::state::{ListState, ViewInfo};use crate::css::Decl;use crate::element::{canvas_with, Div};use crate::html::div;@@ -29,11 +29,12 @@ pub struct VariableList<S: ItemSource + 'static, P: Measurer + ItemPainter + 'ststate: Entity<ListState<S, P>>,base: Div,on_item_click: Option<Listener<S, P>>,+ on_view_change: Option<Rc<dyn Fn(&ViewInfo)>>,}/// The element for a list state.pub fn variable_list<S: ItemSource, P: Measurer + ItemPainter>(state: &Entity<ListState<S, P>>) -> VariableList<S, P> {- VariableList { state: *state, base: div().relative().overflow_hidden().size_full(), on_item_click: None }+ VariableList { state: *state, base: div().relative().overflow_hidden().size_full(), on_item_click: None, on_view_change: None }}/// A chat: a [`VariableList`] over a [`ChatList`] where a click selects a@@ -43,6 +44,14 @@ pub fn chat_list(state: &Entity<ListState<VecSource, ChatStyle>>) -> VariableLis}impl<S: ItemSource, P: Measurer + ItemPainter> VariableList<S, P> {+ /// The visible range or the count changed (TanStack Virtual's `onChange`):+ /// called after the frame that did it, with the list not borrowed.+ #[must_use]+ pub fn on_view_change(mut self, f: impl Fn(&ViewInfo) + 'static) -> Self {+ self.on_view_change = Some(Rc::new(f));+ self+ }+/// An item was clicked (item index). The closure may change the list.#[must_use]pub fn on_item_click(mut self, f: impl Fn(usize, &mut List<S, P>) + 'static) -> Self {@@ -59,20 +68,23 @@ impl<S: ItemSource, P: Measurer + ItemPainter> Styled for VariableList<S, P> {impl<S: ItemSource, P: Measurer + ItemPainter> IntoElement for VariableList<S, P> {fn into_any_element(self) -> AnyElement {- let VariableList { state, base, on_item_click } = self;+ let VariableList { state, base, on_item_click, on_view_change } = self;let el = base.defer(move |window, cx, el| {let id = state.read(cx).id.clone();let known = window.bounds_of(&id);let bounds = known.unwrap_or_default();let scale = window.scale_factor();- let changed = state.update(cx, |s, _| {+ let (changed, view) = state.update(cx, |s, _| {let moved = known.is_none() || s.bounds != bounds;s.sync(bounds, scale, window);- moved+ (moved, s.take_view_change())});if changed {window.refresh(); // placed for the first time or resized: lay out once more with the size}+ if let (Some(f), Some(info)) = (&on_view_change, view) {+ f(&info);+ }let (down, mv, up, wh, key) = (state, state, state, state, state);let click = on_item_click;let taken = std::mem::replace(el, Div::new("div"));diff --git a/bindings/rust/blenderui/src/vlist/mod.rs b/bindings/rust/blenderui/src/vlist/mod.rsindex c4318dc..c4adbd2 100644--- a/bindings/rust/blenderui/src/vlist/mod.rs+++ b/bindings/rust/blenderui/src/vlist/mod.rs@@ -27,11 +27,12 @@ mod element;mod state;pub use blenderui_vlist::{- Align, Budget, ChatList, ChatStyle, Hit, ItemPainter, ItemSource, List, ListView, Measurer, Message, Nav, Options, Record, VecSource,+ Align, Budget, ChatList, ChatStyle, CountSource, Hit, ItemPainter, ItemSource, List, ListView, Measurer, Message, Nav, Options, Record,+ RowList, RowStyle, VecSource,};pub use blenderui_vlist::synth;pub use element::{chat_list, variable_list, VariableList};-pub use state::ListState;+pub use state::{ListState, ViewInfo};/// The colors of the engine's current theme, for a list style's palette.#[must_use]diff --git a/bindings/rust/blenderui/src/vlist/state.rs b/bindings/rust/blenderui/src/vlist/state.rsindex b24071c..f87b956 100644--- a/bindings/rust/blenderui/src/vlist/state.rs+++ b/bindings/rust/blenderui/src/vlist/state.rs@@ -12,6 +12,18 @@ use crate::geometry::Bounds;use crate::sink::{measure, with_sink};use crate::{Context, SharedString, Window};+/// What a list shows: TanStack Virtual's `range`, `count`, `scrollOffset` and `getTotalSize()`.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct ViewInfo {+ /// The items in the viewport (empty before the first layout).+ pub range: std::ops::Range<usize>,+ pub count: usize,+ /// Px from the top of the content (estimates for what is not measured).+ pub scroll_offset: f64,+ /// The content height, px.+ pub total_size: f64,+}+/// The list.pub struct ListState<S: ItemSource + 'static, P: Measurer + ItemPainter + 'static> {list: List<S, P>,@@ -19,6 +31,8 @@ pub struct ListState<S: ItemSource + 'static, P: Measurer + ItemPainter + 'statipub(crate) bounds: Bounds<f32>,pub(crate) id: SharedString,last_frame: Option<Instant>,+ /// The range and count last reported by [`take_view_change`](Self::take_view_change).+ reported: Option<(std::ops::Range<usize>, usize)>,}impl<S: ItemSource, P: Measurer + ItemPainter> Deref for ListState<S, P> {@@ -38,7 +52,7 @@ impl<S: ItemSource, P: Measurer + ItemPainter> ListState<S, P> {/// An entity state for `list` (call inside `cx.new`).pub fn new(list: List<S, P>, cx: &mut Context<Self>) -> Self {let id = SharedString::from(format!("bui-vlist-{}", cx.entity().entity_id()));- Self { list, bounds: Bounds::default(), id, last_frame: None }+ Self { list, bounds: Bounds::default(), id, last_frame: None, reported: None }}/// Called while rendering with the list's last bounds: resize, advance@@ -70,6 +84,24 @@ impl<S: ItemSource, P: Measurer + ItemPainter> ListState<S, P> {more}+ /// What the list shows now.+ #[must_use]+ pub fn view_info(&self) -> ViewInfo {+ let (scroll_offset, total_size) = self.list.view.scroll_extent();+ ViewInfo { range: self.list.view.visible_range().unwrap_or(0..0), count: self.list.source.len(), scroll_offset, total_size }+ }++ /// The view info when the visible range or the count changed since the+ /// last call (TanStack Virtual's `onChange`), else `None`.+ pub fn take_view_change(&mut self) -> Option<ViewInfo> {+ let info = self.view_info();+ let key = (info.range.clone(), info.count);+ (self.reported.as_ref() != Some(&key)).then(|| {+ self.reported = Some(key);+ info+ })+ }+/// Draw the laid-out frame into `p` (logical px, `b` = the element's box).pub(crate) fn draw(&self, b: Bounds<f32>, p: &mut crate::Painter, scale: f32) {with_sink(p, b.origin, scale, |sink| self.list.paint(sink));diff --git a/bindings/rust/blenderui/tests/shadcn.rs b/bindings/rust/blenderui/tests/shadcn.rsnew file mode 100644index 0000000..0415d73--- /dev/null+++ b/bindings/rust/blenderui/tests/shadcn.rs@@ -0,0 +1,445 @@+//! shadcn's Data Table and the virtual list, end to end in off-screen+//! windows: the rsx! and builder syntaxes, sorting, filtering, pagination,+//! selection, visibility, controlled and uncontrolled state.++use std::cell::Cell as StdCell;+use std::rc::Rc;+use std::sync::Arc;++use blenderui::prelude::*;+use blenderui::shadcn::*;++const STATUS: [&str; 4] = ["pending", "processing", "success", "failed"];++struct Payment {+ id: String,+ status: &'static str,+ email: String,+ amount: f64,+}++impl Record for Payment {+ const FIELDS: &'static [&'static str] = &["id", "status", "email", "amount"];+ fn field(&self, field: usize) -> Cell<'_> {+ match field {+ 0 => Cell::Str(&self.id),+ 1 => Cell::Str(self.status),+ 2 => Cell::Str(&self.email),+ _ => Cell::F64(self.amount, 2),+ }+ }+}++fn payments(n: usize) -> Arc<[Payment]> {+ (0..n)+ .map(|i| Payment {+ id: format!("p{i:04}"),+ status: STATUS[i % 4],+ email: format!("user{}@example.com", (i * 37) % 100),+ amount: 10.0 + ((i * 7919) % 100_000) as f64 / 100.0,+ })+ .collect()+}++fn columns() -> Arc<[ColumnDef<Payment>]> {+ vec![+ select_column(),+ ColumnDef::accessor_key("status").header("Status").size(120.0).badge(|s| match s {+ "success" => BadgeVariant::Default,+ "failed" => BadgeVariant::Destructive,+ _ => BadgeVariant::Secondary,+ }),+ ColumnDef::accessor_key("email").header(Header::menu("Email")).size(240.0),+ ColumnDef::accessor_key("amount").header("Amount").size(120.0).meta(ColumnMeta::right().usd()),+ actions_column(),+ ]+ .into()+}++/// The table, with whichever syntax and props a test wants.+struct View {+ columns: Arc<[ColumnDef<Payment>]>,+ data: Arc<[Payment]>,+ handle: StdCell<Option<TableHandle>>,+ mode: Mode,+ changes: Rc<StdCell<usize>>,+}++#[derive(Copy, Clone)]+enum Mode {+ /// `<DataTable table columns data />`, no toolbar.+ Rsx,+ /// `DataTable::new(..)` builder chain with the toolbar.+ Builder,+ /// Controlled sorting held by the view (the signal), applied back.+ Controlled,+ /// Controlled sorting that never changes: the parent refuses.+ Refusing,+}++impl Render for View {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ let table = use_table();+ self.handle.set(Some(table));+ let (columns, data) = (self.columns.clone(), self.data.clone());+ let sorting = use_signal(SortingState::new());+ let changes = self.changes.clone();+ let inner: AnyElement = match self.mode {+ Mode::Rsx => rsx! { <DataTable table={table} columns={columns} data={data} toolbar={false} h={px(300.0)} w={px(900.0)} /> }.into_any_element(),+ Mode::Builder => DataTable::new(columns, data).table(table).filter_column("email").w(px(900.0)).h(px(380.0)).into_any_element(),+ Mode::Controlled => DataTable::new(columns, data)+ .table(table)+ .toolbar(false)+ .sorting(sorting.get())+ .on_sorting_change(move |s| sorting.set(s.clone()))+ .w(px(900.0))+ .h(px(300.0))+ .into_any_element(),+ Mode::Refusing => DataTable::new(columns, data)+ .table(table)+ .toolbar(false)+ .sorting(SortingState::new())+ .on_sorting_change(move |_| changes.set(changes.get() + 1))+ .w(px(900.0))+ .h(px(300.0))+ .into_any_element(),+ };+ body().m_0().child(inner)+ }+}++fn open(cx: &mut App, mode: Mode, n: usize) -> (WindowId, Entity<View>) {+ let opts = WindowOptions {+ window_bounds: Some(WindowBounds::Windowed(Bounds { origin: point(px(0.0), px(0.0)), size: size(px(900.0), px(420.0)) })),+ ..Default::default()+ };+ let mut view = None;+ let win = cx+ .open_window(opts, |_, cx| {+ let v = cx.new(|_| View { columns: columns(), data: payments(n), handle: StdCell::new(None), mode, changes: Rc::new(StdCell::new(0)) });+ view = Some(v);+ v+ })+ .unwrap();+ (win.id, view.unwrap())+}++fn frames(cx: &mut App, id: WindowId) -> (usize, usize, Vec<u32>) {+ // the first frames create the table and learn its size+ for _ in 0..4 {+ cx.draw(id);+ }+ cx.draw(id)+}++fn handle(cx: &App, v: &Entity<View>) -> TableHandle {+ v.read(cx).handle.get().expect("rendered")+}++fn distinct(img: &(usize, usize, Vec<u32>)) -> usize {+ let mut v = img.2.clone();+ v.sort_unstable();+ v.dedup();+ v.len()+}++fn run(theme: &str, f: impl FnOnce(&mut App)) {+ Application::headless().theme(theme).run(f);+}++// the table sits at the window's origin without a toolbar: header 22 px, rows 20 px+const HEADER_Y: f32 = 11.0;+const fn row_y(r: usize) -> f32 {+ 22.0 + 20.0 * r as f32 + 10.0+}++#[test]+fn rsx_data_table_renders_a_page() {+ run("dark", |cx| {+ let (id, v) = open(cx, Mode::Rsx, 95);+ let img = frames(cx, id);+ let t = handle(cx, &v).snapshot();+ assert_eq!((t.core_row_count, t.row_count, t.page_rows, t.page_count), (95, 95, 10, 10));+ assert_eq!(t.columns.iter().map(|c| c.id.as_ref()).collect::<Vec<_>>(), ["select", "status", "email", "amount", "actions"]);+ assert!(distinct(&img) > 40, "something was drawn: {}", distinct(&img));+ // the pagination footer is part of the recipe: it is elements, the table is not+ assert_eq!(handle(cx, &v).page_count(), 10);+ });+}++#[test]+fn builder_syntax_renders_the_same_table_with_a_toolbar() {+ run("dark", |cx| {+ let (id, v) = open(cx, Mode::Builder, 95);+ frames(cx, id);+ let h = handle(cx, &v);+ assert_eq!((h.snapshot().core_row_count, h.page_count()), (95, 10));+ // the toolbar's filter input drives the table+ h.set_column_filter_value("email", "user1@", cx);+ assert!(h.filtered_row_count() > 0 && h.filtered_row_count() < 95);+ assert_eq!(h.column_filter_value("email"), "user1@");+ h.set_column_filter_value("email", "", cx);+ assert_eq!(h.filtered_row_count(), 95);+ });+}++#[test]+fn pagination_commands() {+ run("dark", |cx| {+ let (id, v) = open(cx, Mode::Rsx, 95);+ frames(cx, id);+ let h = handle(cx, &v);+ h.next_page(cx);+ assert_eq!((h.page_index(), h.can_previous_page(), h.can_next_page()), (1, true, true));+ h.last_page(cx);+ assert_eq!((h.page_index(), h.snapshot().page_rows, h.can_next_page()), (9, 5, false));+ h.set_page_size(50, cx);+ assert_eq!((h.page_size(), h.page_count(), h.page_index()), (50, 2, 1));+ h.first_page(cx);+ assert_eq!((h.page_index(), h.snapshot().page_rows), (0, 50));+ h.set_page_index(99, cx);+ assert_eq!(h.page_index(), 1, "clamped to the last page");+ let img = frames(cx, id);+ assert!(distinct(&img) > 40);+ });+}++#[test]+fn clicks_sort_select_and_open_menus() {+ run("dark", |cx| {+ let (id, v) = open(cx, Mode::Rsx, 95);+ let before = frames(cx, id);+ let h = handle(cx, &v);+ // the status header is a plain sortable header: a click sorts ascending+ cx.simulate_click(id, 100.0, HEADER_Y);+ assert_eq!(h.snapshot().sorting, vec![SortingRule::new("status", false)]);+ cx.simulate_click(id, 100.0, HEADER_Y);+ assert_eq!(h.snapshot().sorting, vec![SortingRule::new("status", true)]);+ cx.simulate_click(id, 100.0, HEADER_Y);+ assert!(h.snapshot().sorting.is_empty(), "asc, desc, then none");+ // a checkbox cell selects its row without sorting or highlighting by itself+ cx.simulate_click(id, 20.0, row_y(1));+ assert_eq!(h.selected_row_count(), 1);+ cx.simulate_click(id, 20.0, row_y(3));+ assert_eq!(h.selected_row_count(), 2);+ cx.simulate_click(id, 20.0, row_y(1));+ assert_eq!(h.selected_row_count(), 1, "a second click deselects");+ // the header checkbox selects the page, then clears it+ cx.simulate_click(id, 20.0, HEADER_Y);+ assert_eq!(h.selected_row_count(), 10);+ cx.simulate_click(id, 20.0, HEADER_Y);+ assert_eq!(h.selected_row_count(), 0);+ // a Header::menu column opens its menu instead of sorting+ let closed = frames(cx, id);+ cx.simulate_click(id, 40.0 + 120.0 + 80.0, HEADER_Y);+ let open_menu = frames(cx, id);+ assert!(h.snapshot().sorting.is_empty());+ assert_ne!(closed.2, open_menu.2, "the menu is drawn");+ assert_ne!(before.2, open_menu.2);+ // its items sort and hide+ h.toggle_column_sorting("email", Some(true), cx);+ assert_eq!(h.snapshot().sorting, vec![SortingRule::new("email", true)]);+ h.toggle_column_visibility("email", Some(false), cx);+ assert!(!h.columns().iter().find(|c| c.id == "email").unwrap().visible);+ h.toggle_column_visibility("select", Some(false), cx);+ assert!(h.columns().iter().find(|c| c.id == "select").unwrap().visible, "enable_hiding is off for the select column");+ });+}++#[test]+fn selection_spans_pages() {+ run("dark", |cx| {+ let (id, v) = open(cx, Mode::Rsx, 95);+ frames(cx, id);+ let h = handle(cx, &v);+ cx.simulate_click(id, 20.0, HEADER_Y);+ assert_eq!(h.selected_row_count(), 10);+ h.next_page(cx);+ assert_eq!(h.selected_row_count(), 10, "the count is of all filtered rows, not of the page");+ cx.simulate_click(id, 20.0, row_y(0));+ assert_eq!(h.selected_row_count(), 11);+ h.toggle_all_rows_selected(true, cx);+ assert_eq!(h.selected_row_count(), 95);+ h.toggle_all_rows_selected(false, cx);+ assert_eq!(h.selected_row_count(), 0);+ });+}++#[test]+fn controlled_state_is_owned_by_the_parent() {+ run("dark", |cx| {+ let (id, v) = open(cx, Mode::Controlled, 95);+ frames(cx, id);+ let h = handle(cx, &v);+ cx.simulate_click(id, 100.0, HEADER_Y); // the view's signal gets [status asc] and re-renders+ frames(cx, id);+ assert_eq!(h.snapshot().sorting, vec![SortingRule::new("status", false)]);+ });+}++#[test]+fn a_controlled_field_changes_only_when_the_parent_says_so() {+ run("dark", |cx| {+ let (id, v) = open(cx, Mode::Refusing, 95);+ frames(cx, id);+ let h = handle(cx, &v);+ cx.simulate_click(id, 100.0, HEADER_Y);+ frames(cx, id);+ assert!(h.snapshot().sorting.is_empty(), "a controlled field only changes when the parent says so");+ assert_eq!(v.read(cx).changes.get(), 1, "but the change is reported");+ });+}++#[test]+fn light_and_dark_both_render() {+ run("dark", |cx| {+ let (id, v) = open(cx, Mode::Builder, 40);+ let dark = frames(cx, id);+ handle(cx, &v).toggle_all_page_rows_selected(true, cx);+ let selected = frames(cx, id);+ assert_ne!(dark.2, selected.2, "selected rows are painted");+ assert!(blenderui::set_theme("light"));+ cx.notify_all();+ let light = frames(cx, id);+ assert_ne!(selected.2, light.2, "the Blender light theme");+ assert!(distinct(&light) > 40);+ });+}++#[test]+fn bad_columns_are_reported_where_they_are_given() {+ let bad: Arc<[ColumnDef<Payment>]> = vec![ColumnDef::accessor_key("nope")].into();+ assert_eq!(Table::new(TableOptions::new(bad.clone(), payments(1))).err(), Some(TableError::UnknownKey("nope".into())));+ run("dark", |cx| {+ let (id, v) = open(cx, Mode::Rsx, 5);+ v.update(cx, |view, _| view.columns = bad);+ cx.notify_all();+ // the view shows the error instead of a table; nothing panics+ let img = frames(cx, id);+ assert!(distinct(&img) > 2);+ });+}++// -- the virtual list ---------------------------------------------------------------------------------------------------++struct Rows {+ handle: StdCell<Option<ListHandle>>,+ ranges: Rc<StdCell<usize>>,+}++impl Render for Rows {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ let list = use_virtual_list();+ self.handle.set(Some(list));+ let ranges = self.ranges.clone();+ let item = |i: usize, out: &mut String| {+ use std::fmt::Write;+ let _ = write!(out, "item {i} {}", "word ".repeat(i % 9));+ };+ body().m_0().child(+ VirtualList::new(10_000_000, item)+ .list(list)+ .estimate_size(40.0)+ .overscan(12)+ .on_range_change(move |_| ranges.set(ranges.get() + 1))+ .w(px(600.0))+ .h(px(300.0)),+ )+ }+}++#[test]+fn virtual_list_scrolls_by_index_and_offset() {+ run("dark", |cx| {+ let opts = WindowOptions {+ window_bounds: Some(WindowBounds::Windowed(Bounds { origin: point(px(0.0), px(0.0)), size: size(px(600.0), px(300.0)) })),+ ..Default::default()+ };+ let mut view = None;+ let win = cx+ .open_window(opts, |_, cx| {+ let v = cx.new(|_| Rows { handle: StdCell::new(None), ranges: Rc::new(StdCell::new(0)) });+ view = Some(v);+ v+ })+ .unwrap();+ let v = view.unwrap();+ let first = {+ for _ in 0..4 {+ cx.draw(win.id);+ }+ cx.draw(win.id)+ };+ let h = v.read(cx).handle.get().unwrap();+ assert_eq!(h.count(), 10_000_000);+ assert_eq!(h.range().start, 0);+ assert!(h.range().len() < 60, "{:?}", h.range());+ assert!(v.read(cx).ranges.get() >= 1, "onChange fired");+ let info = h.view_info(cx).unwrap();+ assert!(info.total_size > 1.0e8, "ten million items are tall: {}", info.total_size);+ h.scroll_to_index(5_000_000, Align::Start, cx);+ for _ in 0..3 {+ cx.draw(win.id);+ }+ let r = h.range();+ assert!(r.start <= 5_000_000 && r.end > 5_000_000, "{r:?}");+ let moved = cx.draw(win.id);+ assert_ne!(first.2, moved.2);+ h.scroll_to_offset(0.0, cx);+ for _ in 0..3 {+ cx.draw(win.id);+ }+ assert_eq!(h.range().start, 0);+ h.measure_element(0, 120.0, cx);+ cx.draw(win.id);+ });+}++struct Chat {+ handle: StdCell<Option<ListHandle>>,+ messages: Arc<[Message]>,+}++impl Render for Chat {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ let list = use_virtual_list();+ self.handle.set(Some(list));+ let messages = self.messages.clone();+ body().m_0().child(rsx! { <ChatList list={list} messages={messages} w={px(600.0)} h={px(300.0)} /> })+ }+}++#[test]+fn chat_list_opens_at_the_newest_message_and_takes_pushes() {+ run("dark", |cx| {+ let opts = WindowOptions {+ window_bounds: Some(WindowBounds::Windowed(Bounds { origin: point(px(0.0), px(0.0)), size: size(px(600.0), px(300.0)) })),+ ..Default::default()+ };+ let mut view = None;+ let win = cx+ .open_window(opts, |_, cx| {+ let v = cx.new(|_| Chat { handle: StdCell::new(None), messages: blenderui::vlist::synth::messages(0, 200).into() });+ view = Some(v);+ v+ })+ .unwrap();+ for _ in 0..4 {+ cx.draw(win.id);+ }+ let h = view.unwrap().read(cx).handle.get().unwrap();+ assert_eq!(h.count(), 200);+ assert_eq!(h.range().end, 200, "open at the newest message");+ h.push(blenderui::vlist::synth::message(200), cx);+ for _ in 0..3 {+ cx.draw(win.id);+ }+ assert_eq!(h.count(), 201);+ assert_eq!(h.range().end, 201, "following the new message");+ h.scroll_to_index(0, Align::Start, cx);+ for _ in 0..3 {+ cx.draw(win.id);+ }+ assert_eq!(h.range().start, 0);+ });+}diff --git a/docs/getting-started.md b/docs/getting-started.mdindex 819aa0b..f52d75f 100644--- a/docs/getting-started.md+++ b/docs/getting-started.md@@ -104,7 +104,7 @@ shared (`bui.host`).changed tiles. It follows the display's DPI (per-monitor on Windows,`Xft.dpi` on X11) and paces animations to the display's refresh rate.- **Native (macOS, experimental).** A Cocoa window (a port of Blender's GHOST- code; new, checked by CI but not yet tried by hand on a Mac) with Retina scaling. It needs the main+ code; new, checked by CI and tried by hand on an Apple Silicon Mac) with Retina scaling. It needs the mainthread. See [macos-testing.md](macos-testing.md).- **Tk (with `BUI_HOST=tk`, or where no native host works).** A stdlib `tkinter` window thatshows the kit's frame buffer and forwards input to it. The UI and the APIdiff --git a/docs/imgui.md b/docs/imgui.mdindex 5928580..7f0df32 100644--- a/docs/imgui.md+++ b/docs/imgui.md@@ -151,12 +151,13 @@ _buiimgui`) and installed with the wheel.## Rust-`blenderui-imgui` isn't on crates.io yet (only `blenderui` is), so take it from git, or-by path from a clone. Add `features = ["blender-widgets"]` for Blender's widgets.+`blenderui-imgui` is on [crates.io](https://crates.io/crates/blenderui-imgui) (`cargo add blenderui-imgui`);+you can also take it from git, or by path from a clone. Add `features = ["blender-widgets"]` for Blender's widgets.```toml[dependencies]-blenderui-imgui = { git = "https://github.com/ppmpreetham/BUI" }+blenderui-imgui = "0.2"+# or from git: blenderui-imgui = { git = "https://github.com/ppmpreetham/BUI" }# or, from a clone: blenderui-imgui = { path = "bindings/rust/blenderui-imgui" }```diff --git a/docs/macos-testing.md b/docs/macos-testing.mdindex 7aa8156..9371cdf 100644--- a/docs/macos-testing.md+++ b/docs/macos-testing.md@@ -1,7 +1,10 @@# Testing BUI on macOS-Thanks for testing BUI on a Mac. The macOS window host is new and has only-been checked by CI so far, so a person clicking around finds what CI can't.+Thanks for testing BUI on a Mac. The macOS window host is new. CI checks it, and+[Krish Kalaria](https://github.com/krishkalaria12) has tried it by hand on an Apple Silicon MacBook Air. His+report (issue #3) and fixes became pull request #4: Quit, window sizing and tkinter. More Macs find+more, especially Intel Macs and older macOS versions, because a person clicking+around finds what CI can't.This guide takes about 30–60 minutes: build from source, run the tests, try afew apps, and report back.diff --git a/docs/publishing.md b/docs/publishing.mdindex 08ac920..8f4c63a 100644--- a/docs/publishing.md+++ b/docs/publishing.md@@ -124,8 +124,8 @@ Try it without publishing: Actions > release > Run workflow, enter the tag and lbefore-all` installs the X11 headers (`libX11-devel` / `libx11-dev`), andlibX11 itself is loaded at run time, so the wheels still import on serverswithout it. (This used to be a gap; it's fixed.)-- macOS: the native Cocoa window host is new and hasn't been run on a Mac- yet. With `BUI_HOST=tk` the wheels use the stdlib Tk window instead, which+- macOS: the native Cocoa window host is new and has been tried by hand on one+ Apple Silicon Mac so far. With `BUI_HOST=tk` the wheels use the stdlib Tk window instead, whichneeds `tkinter` (for example from python.org or `brew install python-tk`).- MSVC builds work (the Rust crate and the CMake build use Visual Studio'stoolchain), but the published Windows wheels are built with MinGW.@@ -137,16 +137,20 @@ Try it without publishing: Actions > release > Run workflow, enter the tag and l`blenderui` is on [crates.io](https://crates.io/crates/blenderui)(`cargo add blenderui`). The workspace in `bindings/rust/` has eight crates;-four are published to crates.io, in dependency order, and the rest stay in-the repository:+all but the three JavaScript crates are published to crates.io, in+dependency order (a `v*` tag does it, see above), and those three stay in the+repository:| Crate | What it is | Depends on | crates.io ||---|---|---|---|| `blenderui-tailwind` | Tailwind v4 class compiler (std only) | none | Published || `blenderui-macros` | `rsx!` / `view!`, `#[component]`, `css!`, `tw!` | `blenderui-tailwind` | Published || `blenderui-sys` | FFI over the C kit; builds it with CMake | none (`cmake` at build time) | Published |-| `blenderui` | the framework | all three | Published |-| `blenderui-imgui` | Dear ImGui on BUI (`blender-widgets` feature for Blender's widgets) | `blenderui-sys` (`imgui` feature) | Not yet: use it as a git dependency |+| `blenderui-paint` | shared painting types: geometry, colors, `PaintSink`, the text cache | none | Published |+| `blenderui-table` | the data table's core | `blenderui-paint` | Published |+| `blenderui-vlist` | the variable-height list's core | `blenderui-paint` | Published |+| `blenderui` | the framework | the five above | Published |+| `blenderui-imgui` | Dear ImGui on BUI (`blender-widgets` feature for Blender's widgets) | `blenderui-sys` (`imgui` feature) | Published || `blenderui-jsview` | The JavaScript view of a window, shared by the Node.js addon and the QuickJS runtime | `blenderui` | `publish = false` || `blenderui-node` | The napi-rs addon behind `@blender-ui/native` | `blenderui`, `blenderui-jsview` | `publish = false` (ships on npm) || `blenderui-qjs` | `bui-runtime`: BUI with embedded QuickJS, for `bui build` | `blenderui`, `blenderui-jsview` | `publish = false` (ships on npm) |diff --git a/docs/rust.md b/docs/rust.mdindex 67c5bd9..afbe5e1 100644--- a/docs/rust.md+++ b/docs/rust.md@@ -33,9 +33,8 @@ capitalized Blender components.cargo add blenderui```-or, by hand, `blenderui = "0.1"` under `[dependencies]`. (The Dear ImGui crate,-`blenderui-imgui`, isn't on crates.io yet: use-`blenderui-imgui = { git = "https://github.com/ppmpreetham/BUI" }`.)+or, by hand, `blenderui = "0.2"` under `[dependencies]`. (The Dear ImGui crate is+[`blenderui-imgui`](https://crates.io/crates/blenderui-imgui): `cargo add blenderui-imgui`.)Building needs **CMake** and a **C compiler**: `blenderui-sys` compiles the Ckit with the `cmake` crate. On Windows the default Rust target@@ -475,6 +474,10 @@ let table = cx.new(|cx| TableState::new(People, window, cx));Features: sticky header and pinned columns, resize and move by dragging headers, click to sort, row (multi, Shift/Ctrl, Ctrl+A), cell and column selection, keyboard navigation, Ctrl+C as TSV, stripes, a row-number column, loading and empty states, `load_more`, Blender dark and light themes. The logic lives once, in the dependency-free `blenderui-table` crate (visible-range math and column culling, index masks and typed parallel sorts, lazy typed cells formatted without allocation, selection, keyboard navigation, column layout, a text-run cache, and the painting through a `PaintSink` trait). blenderui's `table` module is one adapter around it (`Host`, `PaintSink`, element); `bindings/rust/blenderui-table-gpui` is the same for real gpui, with gpui-component's names and a `render_td` escape hatch, outside the main workspace (it builds gpui). On real gpui, 1,000,000 x 20, it takes 1.45 ms per scrolled frame against gpui-component 0.9.0's 4.75 ms (see the website page "Data tables" for the method). `uniform_list(id, count, |range, window, cx| ...)` (gpui's signature) builds only the visible items of a list of real elements, from the same range math. Measured on 1,000,000 x 20: 0.1 ms to build, 1.1 ms per scrolled frame, about 22 ms for a header-click sort; see `examples/bench_table.rs` and the website page "Data tables". Not built yet in blenderui: element cells (`render_td`, available on gpui), a popup context menu, multi-cell ranges, JavaScript and Python wrappers.+### The shadcn Data Table++`blenderui::shadcn` puts the API of shadcn/ui's Data Table (TanStack Table's `ColumnDef`, table state and row models) on the same painted table, in `rsx!` and builder syntax: `<DataTable columns={columns} data={data} />` / `DataTable::new(columns, data)`, `ColumnDef::accessor_key` / `accessor_fn` (the row type implements `Record`), `select_column()` and `actions_column()`, `use_table()`, and the helper components `DataTableColumnHeader`, `DataTablePagination`, `DataTableViewOptions` and `DataTableToolbar`. Sorting, column and global filters, pagination, row selection and column visibility are TanStack's state, uncontrolled or controlled with `on_..._change` callbacks, over row models that are index lists. A shadcn `cell: ({ row }) => <JSX />` becomes a typed `CellRender` (text with a number format, checkbox, badge, progress, row actions) that the table paints straight from the data, so a steady frame still allocates nothing; there is no `flexRender`. The logic is in `blenderui_table::tanstack` (core, no framework); the components are in `blenderui/src/shadcn/`. Names, limits and numbers are on the website page "shadcn Data Table", and `examples/site_shadcn_table.rs` is the payments table of the recipe.+## Variable-height lists and chat`blenderui::vlist` is a virtualized list whose items have different heights (wrapped text, images), built for chat and optimal from 100 items to 10M and beyond with one design. The logic lives once, in the dependency-free `blenderui-vlist` crate (on `blenderui-paint`, which also holds the `PaintSink` trait, the theme `Palette` and the bounded `TextCache` that `blenderui-table` uses):@@ -495,6 +498,8 @@ let chat = cx.new(|cx| ListState::new(ChatList::from_messages(synth::messages(0,For items that are not messages, build a `List` from your own `ItemSource`, `Measurer` and `ItemPainter` and show it with `variable_list(&state)`. `bindings/rust/blenderui-vlist-gpui` is the same list for real gpui (outside the main workspace); its benchmark against gpui's `list` and gpui-component's `virtual_list` is in `bench/`. Measured numbers and the method are on the website page "Variable-height lists". Not built yet: selecting text across messages, a background measuring thread, damage regions, JavaScript and Python wrappers.+`blenderui::shadcn` also has `VirtualList` (`count` and an `item` closure that writes each item's text, so ten million rows cost a screenful) and `ChatList`, with TanStack Virtual's names: `estimate_size`, `overscan`, `get_item_key`, `on_range_change`, and `scroll_to_index` / `scroll_to_offset` / `measure_element` on the `ListHandle` that `use_virtual_list()` returns. They sit on `ListState` and `ItemSource` (the new `CountSource` and `RowStyle` in `blenderui-vlist`), so the file-backed source works under them. See the website page "Virtual list API" and `examples/site_shadcn_list.rs`.+## Headless rendering and tests`Application::headless()` runs the same code without a native window (and is@@ -690,7 +695,7 @@ The `gdi-text` feature uses Windows' GDI engine and system fonts.- **Images**: PNG only, nearest-neighbour scaling. `video`, `audio`,`iframe` show a placeholder.- **Windows** are native on Windows (Win32), Linux (X11) and macOS (Cocoa,- new and not yet tried by hand on a Mac; it needs the main thread). The GPU+ new, tried by hand so far on one Apple Silicon Mac; it needs the main thread). The GPUrenderer runs on Windows and Linux.- `text-align: justify` aligns left. Table columns are sized from theirwidest single-line content, a simpler version of browsers' auto layout.diff --git a/tools/gen_doc_images.py b/tools/gen_doc_images.pyindex d58b68a..cef55d2 100644--- a/tools/gen_doc_images.py+++ b/tools/gen_doc_images.py@@ -146,6 +146,8 @@ def site_rust(theme, only_example=None):("site_animation", "feature-animation"),("site_data_table", "data-table"),("site_chat", "chat-list"),+ ("site_shadcn_table", "shadcn-data-table"),+ ("site_shadcn_list", "shadcn-virtual-list"),]for ex, name in shots:if only_example and ex != only_example:diff --git a/website/WRITING.md b/website/WRITING.mdindex 27b90ee..2538a28 100644--- a/website/WRITING.md+++ b/website/WRITING.md@@ -83,8 +83,7 @@ not "JSX".`blenderui` is published on crates.io: install with `cargo add blenderui`.Never write "not published yet" or tell readers to use a git dependency for-it. The exception is `blenderui-imgui`, which isn't on crates.io yet: for-that crate only, show the git dependency.+it. The same goes for `blenderui-imgui`: `cargo add blenderui-imgui`.### No recaps, no emojidiff --git a/website/public/images/shots/shadcn-data-table-dark.png b/website/public/images/shots/shadcn-data-table-dark.pngnew file mode 100644index 0000000..55af1e6Binary files /dev/null and b/website/public/images/shots/shadcn-data-table-dark.png differdiff --git a/website/public/images/shots/shadcn-data-table-light.png b/website/public/images/shots/shadcn-data-table-light.pngnew file mode 100644index 0000000..770973dBinary files /dev/null and b/website/public/images/shots/shadcn-data-table-light.png differdiff --git a/website/public/images/shots/shadcn-virtual-list-dark.png b/website/public/images/shots/shadcn-virtual-list-dark.pngnew file mode 100644index 0000000..aa0b005Binary files /dev/null and b/website/public/images/shots/shadcn-virtual-list-dark.png differdiff --git a/website/public/images/shots/shadcn-virtual-list-light.png b/website/public/images/shots/shadcn-virtual-list-light.pngnew file mode 100644index 0000000..6b54520Binary files /dev/null and b/website/public/images/shots/shadcn-virtual-list-light.png differdiff --git a/website/src/components/landing/Coming.astro b/website/src/components/landing/Coming.astroindex 8a9309b..99d0ab0 100644--- a/website/src/components/landing/Coming.astro+++ b/website/src/components/landing/Coming.astro@@ -3,13 +3,12 @@import Icon from "../site/Icon.astro";const items = [- { title: "macOS, tested", body: "The Cocoa host is written but untested. Next: running it on a real Mac (testers welcome), then the GPU renderer and JavaScript windows there.", tag: "In progress" },+ { title: "macOS, tested", body: "The Cocoa host has been tried by hand on an Apple Silicon Mac, and that found and fixed real bugs. Next: more Macs (Intel, older macOS; testers welcome), then the GPU renderer and JavaScript windows there.", tag: "In progress" },{ title: "WebAssembly", body: "The kit in the browser: the raster blits to a <canvas>, and React and the DOM-like API run on top, unchanged.", tag: "Planned" },{ title: "egui", body: "BUI panels inside egui apps, plus a Blender-styled egui theme.", tag: "Planned" },{ title: "More languages", body: "MyGo, C#, Go, Zig, Swift, Kotlin and Lua over the same C header; Godot, Unity, Bevy and Flutter.", tag: "Planned" },{ title: "Font fallback and IME", body: "Per-glyph fallback (Blender's BLF), input methods, units in number fields and widget drag and drop.", tag: "Planned" },{ title: "Vulkan and WebGPU", body: "More GPU backends drawing the same instance stream as Direct3D 11 and OpenGL.", tag: "Planned" },- { title: "blenderui-imgui on crates.io", body: "blenderui is on crates.io already. The Dear ImGui crate is next; until then it's a git dependency.", tag: "Soon" },{ title: "More Qt", body: "Model/view classes, docks, toolbars, splitters and Qt stylesheets, on top of today's everyday subset.", tag: "In progress" },];---diff --git a/website/src/components/landing/Platforms.astro b/website/src/components/landing/Platforms.astroindex 7b52ece..ba023ac 100644--- a/website/src/components/landing/Platforms.astro+++ b/website/src/components/landing/Platforms.astro@@ -1,6 +1,6 @@----// From README.md "Platforms". Works (check) · experimental (flask): written but not yet-// tested on real hardware · partial (half circle).+// From README.md "Platforms". Works (check) · experimental (flask): written and checked by CI,+// little hands-on testing · partial (half circle).import StatusMark from "../docs/StatusMark.astro";import { repoFile } from "../../lib/docs";@@ -51,9 +51,9 @@ const rows: [string, Cell, Cell, Cell][] = [<p class="flex gap-2 border-t border-border px-5 py-3 text-[13px] leading-6 text-muted sm:px-8"><span class="mt-1"><StatusMark status="experimental" compact /></span><span>- The macOS window host is a port of Blender's Cocoa code (GHOST): written, but not yet run on a Mac. Python can use the- standard Tk window there meanwhile (<code class="font-mono">BUI_HOST=tk</code>). If you have a Mac and a free afternoon,- you could be the first: the <a class="text-link underline underline-offset-4" href={repoFile("docs/macos-testing.md")}>macOS testing guide</a>+ The macOS window host is a port of Blender's Cocoa code (GHOST): checked by CI and tried by hand on one Apple Silicon Mac so far, by <a class="text-link underline underline-offset-4" href="https://github.com/krishkalaria12">Krish Kalaria</a>, who also fixed what he found. Python can use the+ standard Tk window there meanwhile (<code class="font-mono">BUI_HOST=tk</code>). If you have another Mac (Intel, or an older macOS) and a free afternoon,+ you could be next: the <a class="text-link underline underline-offset-4" href={repoFile("docs/macos-testing.md")}>macOS testing guide</a>{" "}walks you through it.</span></p>diff --git a/website/src/components/site/Footer.astro b/website/src/components/site/Footer.astroindex 1deead4..32eb09e 100644--- a/website/src/components/site/Footer.astro+++ b/website/src/components/site/Footer.astro@@ -17,6 +17,7 @@ const groups = [title: "Packages",links: [["blenderui on PyPI", site.pypi],+ ["blenderui on crates.io", site.crates],["@blender-ui/react", site.npm],["@blender-ui/native", "https://www.npmjs.com/package/@blender-ui/native"],],diff --git a/website/src/config/site.ts b/website/src/config/site.tsindex 2d8bec6..7142f2d 100644--- a/website/src/config/site.ts+++ b/website/src/config/site.ts@@ -12,5 +12,6 @@ export const site = {blobBase: "https://github.com/ppmpreetham/BUI/blob/main/",pypi: "https://pypi.org/project/blenderui/",npm: "https://www.npmjs.com/package/@blender-ui/react",+ crates: "https://crates.io/crates/blenderui",license: "GPL-2.0-or-later",} as const;diff --git a/website/src/content/docs/concepts/window-hosts.mdx b/website/src/content/docs/concepts/window-hosts.mdxindex c4f96ae..e336327 100644--- a/website/src/content/docs/concepts/window-hosts.mdx+++ b/website/src/content/docs/concepts/window-hosts.mdx@@ -16,7 +16,7 @@ This page explains each host, how to choose one yourself, and what to expect on<StatusTable columns={["Host", "Status", "Where and what"]} rows={[["<strong>Win32</strong>", "done", "Windows. Native, written in C"],["<strong>X11</strong>", "done", "Linux (Wayland sessions through XWayland). Native, written in C"],- ["<strong>Cocoa</strong>", "experimental", "macOS. Native, written but not yet run on a Mac"],+ ["<strong>Cocoa</strong>", "experimental", "macOS. Native, tried by hand on one Apple Silicon Mac so far"],["<strong>Tk</strong>", "done", "Anywhere Python has <code>tkinter</code>. Python only; the fallback"],["<strong>Headless</strong>", "done", "Anywhere. No window: tests and screenshots"],]} />diff --git a/website/src/content/docs/imgui/rust.mdx b/website/src/content/docs/imgui/rust.mdxindex 9c71dbd..b8dd60b 100644--- a/website/src/content/docs/imgui/rust.mdx+++ b/website/src/content/docs/imgui/rust.mdx@@ -14,7 +14,13 @@ You get two layers in one crate: a **safe layer** (`&str`, `&mut T`, slices) for## Add the crate-`blenderui-imgui` isn't on crates.io yet <ComingSoon inline /> (the main `blenderui` crate is). Until it is, use a git dependency:+`blenderui-imgui` is on [crates.io](https://crates.io/crates/blenderui-imgui), next to the main `blenderui` crate:++```sh+cargo add blenderui-imgui+```++Or take it from git if you want the newest source:```toml title="Cargo.toml"[dependencies]diff --git a/website/src/content/docs/project/publishing.mdx b/website/src/content/docs/project/publishing.mdxindex 18ff868..cf45f7e 100644--- a/website/src/content/docs/project/publishing.mdx+++ b/website/src/content/docs/project/publishing.mdx@@ -18,7 +18,7 @@ BUI ships to three registries: **PyPI** (`blenderui`), **npm** (`@blender-ui/nat| --- | --- | --- | --- || PyPI | `blenderui` | `bindings/python/bui/_version.py` | Push a `v*` tag; CI builds, tests and publishes || npm | `@blender-ui/native`, `@blender-ui/react` | Each package's `package.json` | `npm publish`, by hand, native first |-| crates.io | `blenderui-tailwind`, `blenderui-macros`, `blenderui-sys`, `blenderui` | `bindings/rust/Cargo.toml` (`[workspace.package]`) | `cargo publish`, by hand, after vendoring the C sources |+| crates.io | `blenderui-tailwind`, `-macros`, `-sys`, `-paint`, `-table`, `-vlist`, `blenderui`, `blenderui-imgui` | `bindings/rust/Cargo.toml` (`[workspace.package]`) | `cargo publish`, by hand, after vendoring the C sources |## PyPI@@ -114,24 +114,24 @@ The native package ships `blenderui.win32-x64.node` and `bui-runtime.win32-x64.e## crates.io-The four crates below are on crates.io (version 0.1.0 at the time of writing), and users add them with `cargo add blenderui`. They're published in dependency order:+The eight crates below are on crates.io (version 0.2.0 at the time of writing), and users add them with `cargo add blenderui` (or `cargo add blenderui-imgui`). A tag push publishes them in dependency order:| Crate | What it is | Depends on || --- | --- | --- || `blenderui-tailwind` | Tailwind v4 class compiler (std only) | Nothing || `blenderui-macros` | `rsx!` / `view!`, `#[component]`, `css!`, `tw!` | `blenderui-tailwind` || `blenderui-sys` | FFI over the C kit; builds it with CMake | Nothing (CMake at build time) |-| `blenderui` | The framework | All three |--<Callout type="note" title="blenderui-imgui">-The Dear ImGui crate, `blenderui-imgui`, isn't on crates.io yet; its users take it as a git dependency. It isn't marked `publish = false`, so `cargo publish --workspace` would include it: publish the four crates one by one (`cargo publish -p ...`) until it's meant to go out.-</Callout>+| `blenderui-paint` | Shared painting types: geometry, colors, the `PaintSink` trait, the text cache | Nothing |+| `blenderui-table` | The data table's core (virtualization, sorting, selection) | `blenderui-paint` |+| `blenderui-vlist` | The variable-height list's core (height index, anchored scrolling, sources) | `blenderui-paint` |+| `blenderui` | The framework | The five above |+| `blenderui-imgui` | Dear ImGui on BUI | `blenderui-sys` |A published crate can't reach files outside itself, so `blenderui-sys` must carry the C sources. Its build script looks for them in three places, in order: `BUI_SOURCE_DIR` if set, the surrounding repository, then `csrc/`, the vendored copy a downloaded crate has.<Steps>-1. **Bump the version** in `bindings/rust/Cargo.toml` (`[workspace.package]`); the crates share one version. Then update the `version = "..."` of the path dependencies in `blenderui/Cargo.toml` and `blenderui-macros/Cargo.toml`.+1. **Bump the version** in `bindings/rust/Cargo.toml` (`[workspace.package]`); the crates share one version. Then update the `version = "..."` of the path dependencies in `blenderui/Cargo.toml`, `blenderui-macros/Cargo.toml`, `blenderui-imgui/Cargo.toml`, `blenderui-table/Cargo.toml` and `blenderui-vlist/Cargo.toml`. `python tools/check_versions.py vX.Y.Z` checks all of them.2. **Log in once** with `cargo login` and a crates.io API token.@@ -150,7 +150,7 @@ A published crate can't reach files outside itself, so `blenderui-sys` must carr## Known gaps before 1.0-- **macOS:** the native Cocoa host hasn't been run on a Mac yet. With `BUI_HOST=tk`, the wheels use the standard Tk window instead.+- **macOS:** the native Cocoa host has been tried by hand on one Apple Silicon Mac so far. With `BUI_HOST=tk`, the wheels use the standard Tk window instead.- **Windows wheels** are built with MinGW. MSVC builds work (the Rust crate and the CMake build use it), but aren't what's published.- **No musllinux or 32-bit wheels** yet.- **npm:** prebuilt for Windows x64 only.diff --git a/website/src/content/docs/project/roadmap.mdx b/website/src/content/docs/project/roadmap.mdxindex 1819ec6..7cc6508 100644--- a/website/src/content/docs/project/roadmap.mdx+++ b/website/src/content/docs/project/roadmap.mdx@@ -38,8 +38,7 @@ Each row has a status: **Works** when it works and is tested, **Partial** when c["Rust components", "partial", "No async resources (<code>use_resource</code>) and no generic components yet"],["Dear ImGui", "partial", "Python and safe Rust skip the <code>va_list</code>, <code>void*</code> and C-callback functions; in the Blender-widgets build, title bars, tooltips, plain popups, tables and the color picker keep ImGui's drawing"],["npm packages", "partial", "Prebuilt for Windows x64 only; on Linux, build the addon from source"],- ["macOS", "experimental", "The Cocoa window host is written but not yet run on a Mac (<a href='https://github.com/ppmpreetham/BUI/blob/main/docs/macos-testing.md'>testing guide</a>); JavaScript is headless there; no GPU renderer yet"],- ["<code>blenderui-imgui</code> on crates.io", "partial", "The main <code>blenderui</code> crate is published; the Dear ImGui crate isn't yet, so use it as a git dependency"],+ ["macOS", "experimental", "The Cocoa window host is checked by CI and has been tried by hand on one Apple Silicon Mac (<a href='https://github.com/ppmpreetham/BUI/blob/main/docs/macos-testing.md'>testing guide</a>); JavaScript is headless there; no GPU renderer yet"],]}/>diff --git a/website/src/content/docs/rust/data-table.mdx b/website/src/content/docs/rust/data-table.mdxindex 4840740..b679216 100644--- a/website/src/content/docs/rust/data-table.mdx+++ b/website/src/content/docs/rust/data-table.mdx@@ -4,7 +4,7 @@ description: A virtualized DataTable with the API of gpui-component's, drawn thesection: Rustorder: 65languages: ["rust"]-sources: ["docs/rust.md", "bindings/rust/blenderui-table/src/lib.rs", "bindings/rust/blenderui-table/src/sort.rs", "bindings/rust/blenderui-table/src/paint.rs", "bindings/rust/blenderui-table/src/state.rs", "bindings/rust/blenderui/src/table/mod.rs", "bindings/rust/blenderui/src/table/sink.rs", "bindings/rust/blenderui/src/list.rs", "bindings/rust/blenderui/tests/table.rs", "bindings/rust/blenderui/examples/site_data_table.rs", "bindings/rust/blenderui/examples/bench_table.rs", "bindings/rust/blenderui-table-gpui/src/lib.rs", "bindings/rust/blenderui-table-gpui/examples/bench_gpui.rs"]+sources: ["docs/rust.md", "bindings/rust/blenderui-table/src/lib.rs", "bindings/rust/blenderui-table/src/sort.rs", "bindings/rust/blenderui-table/src/paint.rs", "bindings/rust/blenderui-table/src/state.rs", "bindings/rust/blenderui/src/table/mod.rs", "bindings/rust/blenderui/src/table/sink.rs", "bindings/rust/blenderui/src/list.rs", "bindings/rust/blenderui/tests/table.rs", "bindings/rust/blenderui/examples/site_data_table.rs", "bindings/rust/blenderui/src/shadcn/mod.rs", "bindings/rust/blenderui-table/src/tanstack/mod.rs", "bindings/rust/blenderui/examples/bench_table.rs", "bindings/rust/blenderui-table-gpui/src/lib.rs", "bindings/rust/blenderui-table-gpui/examples/bench_gpui.rs"]---A table of a million rows is easy to ask for and hard to build: make one element per cell and the window stops responding. **`DataTable` draws only the cells you can see**, straight to the screen, the way Blender's spreadsheet editor does. Scrolling it costs about a millisecond, whether it holds a hundred rows or a million.diff --git a/website/src/content/docs/rust/overview.mdx b/website/src/content/docs/rust/overview.mdxindex 43cb912..775a3b8 100644--- a/website/src/content/docs/rust/overview.mdx+++ b/website/src/content/docs/rust/overview.mdx@@ -217,7 +217,7 @@ BUI's Rust side covers a lot, but not everything. Each page lists its own gaps;- **Images** are PNG only, with nearest-neighbour scaling. `video`, `audio` and `iframe` show a placeholder.- **Transforms:** every 2D transform draws, but clicks use the untransformed box. 3D transforms have no effect.- **Tables** size columns from their widest single-line content, a simpler version of browsers' auto layout.-- **Windows** are native on Windows (Win32), Linux (X11) and macOS (Cocoa). The Cocoa host is new and not yet tested on a Mac, and it needs the main thread. The GPU renderer runs on Windows and Linux.+- **Windows** are native on Windows (Win32), Linux (X11) and macOS (Cocoa). The Cocoa host is new and has been tried by hand on one Apple Silicon Mac so far, and it needs the main thread. The GPU renderer runs on Windows and Linux.- **Components:** async resources (`use_resource`) and generic components are <ComingSoon inline />.<Callout type="joke">diff --git a/website/src/content/docs/rust/shadcn-data-table.mdx b/website/src/content/docs/rust/shadcn-data-table.mdxnew file mode 100644index 0000000..c5a36a7--- /dev/null+++ b/website/src/content/docs/rust/shadcn-data-table.mdx@@ -0,0 +1,255 @@+---+title: shadcn Data Table+description: The API of shadcn/ui's Data Table (TanStack Table's columns, state and row models) on the painted table, in rsx! and builder syntax. Sorting, filtering, pagination, row selection and column visibility over a million rows, with typed cells instead of JSX.+section: Rust+order: 67+languages: ["rust"]+sources: ["docs/rust.md", "bindings/rust/blenderui-table/src/tanstack/mod.rs", "bindings/rust/blenderui-table/src/tanstack/column.rs", "bindings/rust/blenderui-table/src/tanstack/state.rs", "bindings/rust/blenderui-table/src/tanstack/table.rs", "bindings/rust/blenderui-table/src/column.rs", "bindings/rust/blenderui-table/src/paint.rs", "bindings/rust/blenderui-table/src/interact.rs", "bindings/rust/blenderui/src/shadcn/mod.rs", "bindings/rust/blenderui/src/shadcn/table/mod.rs", "bindings/rust/blenderui/src/shadcn/table/data_table.rs", "bindings/rust/blenderui/src/shadcn/table/handle.rs", "bindings/rust/blenderui/src/shadcn/table/link.rs", "bindings/rust/blenderui/src/shadcn/table/pagination.rs", "bindings/rust/blenderui/src/shadcn/table/view_options.rs", "bindings/rust/blenderui/src/shadcn/table/toolbar.rs", "bindings/rust/blenderui/src/shadcn/table/column_header.rs", "bindings/rust/blenderui/tests/shadcn.rs", "bindings/rust/blenderui/examples/site_shadcn_table.rs", "bindings/rust/blenderui/examples/bench_table.rs"]+---++If you know shadcn/ui's Data Table, you already know this one. **`DataTable` takes `columns` and `data`**, keeps TanStack Table's state (sorting, filters, pagination, selection, column visibility), and draws a table that stays smooth at a million rows. The columns, the helper components and the callbacks have the names from the recipe.++<Figure+ shot="shadcn-data-table"+ alt="A payments table: a select column with two rows checked and an indeterminate box in the header, a Status column of colored badges, an Email column with a sort icon whose header menu is open showing Asc, Desc and Hide, an Amount column of right-aligned dollar values and a row-actions column of three dots. Above it a filter field and a View button; below it the pagination footer: 2 of 84 row(s) selected, rows per page, Page 1 of 9 and four page buttons"+ caption="The payments table of the recipe, two rows checked and the Email header's menu open (<code>examples/site_shadcn_table.rs</code>)."+/>++## A payments table++Describe the row type once, write the columns, and put a `DataTable` in your view. This is the whole example behind the picture.++<Tabs sync="rust-syntax" label="Rust syntax">+<Tab label="rsx!">++```rust title="src/main.rs"+use std::sync::Arc;+use blenderui::prelude::*;+use blenderui::shadcn::*;++struct Payment { id: String, status: &'static str, email: String, amount: f64 }++// Rust has no reflection, so the row type lists its fields once: this is what+// makes accessor_key("email") work.+impl Record for Payment {+ const FIELDS: &'static [&'static str] = &["id", "status", "email", "amount"];+ fn field(&self, field: usize) -> Cell<'_> {+ match field {+ 0 => Cell::Str(&self.id),+ 1 => Cell::Str(self.status),+ 2 => Cell::Str(&self.email),+ _ => Cell::F64(self.amount, 2),+ }+ }+}++fn columns() -> Arc<[ColumnDef<Payment>]> {+ vec![+ select_column(),+ ColumnDef::accessor_key("status").header("Status").badge(|s| match s {+ "success" => BadgeVariant::Default,+ "failed" => BadgeVariant::Destructive,+ _ => BadgeVariant::Secondary,+ }),+ ColumnDef::accessor_key("email").header(Header::menu("Email")).size(250.0),+ ColumnDef::accessor_key("amount").header("Amount").meta(ColumnMeta::right().usd()),+ actions_column(),+ ]+ .into()+}++struct Page { columns: Arc<[ColumnDef<Payment>]>, data: Arc<[Payment]> }++impl Render for Page {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ let (columns, data) = (self.columns.clone(), self.data.clone());+ rsx! {+ <DataTable columns={columns} data={data} filter_column="email" h={px(380.0)} />+ }+ }+}+```++`<DataTable ... />` is a [component](../rsx-and-components/) like any other. A missing `columns` or `data` is the usual "a required prop is missing" compile error.++</Tab>+<Tab label="gpui builders">++```rust title="src/main.rs"+use std::sync::Arc;+use blenderui::prelude::*;+use blenderui::shadcn::*;++// Payment, its Record impl and columns() are the same as in the rsx! tab.++struct Page { columns: Arc<[ColumnDef<Payment>]>, data: Arc<[Payment]> }++impl Render for Page {+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {+ DataTable::new(self.columns.clone(), self.data.clone())+ .filter_column("email")+ .h(px(380.0))+ }+}+```++`DataTable` is a builder: `columns` and `data` come first, every other prop is a method, and the Tailwind-style methods (`h`, `w`, `p_4` ...) work on it too.++</Tab>+</Tabs>++`columns` and `data` are compared by identity, the way TanStack expects memoized references: an `Arc` that you clone is the same table, a fresh `Vec` is new data and the table sorts it again. Build them once (a field of your view, or `use_memo`) and pass them on every render.++## The recipe, name by name++| shadcn / TanStack | Rust |+| --- | --- |+| `ColumnDef<TData>` | `ColumnDef<T>` |+| `accessorKey: "email"` | `ColumnDef::accessor_key("email")` (the row type implements `Record`) |+| `accessorFn`, `id` | `ColumnDef::accessor_fn("id", \|row\| Cell::Str(&row.email))`, `.id("...")` |+| `header: "Email"` | `.header("Email")` |+| `header: ({ column }) => <DataTableColumnHeader />` | `.header(Header::menu("Email"))`, with the `DataTableColumnHeader` menu |+| `cell: ({ row }) => <JSX />` | `.cell(CellRender::..)`, `.badge(..)`, `.meta(..)` (typed cells, see below) |+| `enableSorting`, `enableHiding` | `.enable_sorting(bool)`, `.enable_hiding(bool)` |+| `size`, `minSize`, `maxSize` | `.size(px)`, `.min_size(px)`, `.max_size(px)` |+| `meta` | `.meta(ColumnMeta)`: alignment, number format, pinning |+| `select` and `actions` columns | `select_column()`, `actions_column()` |+| `useReactTable({ data, columns })` | `use_table()` and `DataTable` |+| `<DataTable columns data />` | `<DataTable columns={..} data={..} />`, `DataTable::new(columns, data)` |+| `state.sorting`, `onSortingChange` | `.sorting(SortingState)`, `.on_sorting_change(\|s\| ..)` |+| `state.columnFilters`, `onColumnFiltersChange` | `.column_filters(..)`, `.on_column_filters_change(..)` |+| `state.globalFilter`, `onGlobalFilterChange` | `.global_filter(..)`, `.on_global_filter_change(..)` |+| `state.columnVisibility`, `onColumnVisibilityChange` | `.column_visibility(..)`, `.on_column_visibility_change(..)` |+| `state.rowSelection`, `onRowSelectionChange` | `.row_selection(..)`, `.on_row_selection_change(..)` |+| `state.pagination`, `onPaginationChange` | `.pagination(PaginationState { page_index, page_size })`, `.on_pagination_change(..)` |+| `initialState` | `.initial_state(TableState)` |+| `getCoreRowModel()` | `Table::core_row_model()` |+| `getFilteredRowModel()` | `Table::filtered_row_model()` |+| `getSortedRowModel()` | `Table::sorted_row_model()` |+| `getPaginationRowModel()` | `Table::row_model()`, switched on by `.enable_pagination(true)` (the default) |+| `table.setPageIndex`, `nextPage`, `previousPage`, `setPageSize` | the same names on `TableHandle` (`table.next_page(cx)`) |+| `table.getPageCount()`, `getCanNextPage()` | `table.page_count()`, `table.can_next_page()` |+| `column.setFilterValue(v)` | `table.set_column_filter_value("email", v, cx)` |+| `column.toggleSorting(desc)` | `table.toggle_column_sorting("email", Some(desc), cx)` |+| `column.toggleVisibility(v)` | `table.toggle_column_visibility("email", Some(v), cx)` |+| `table.toggleAllPageRowsSelected(v)` | `table.toggle_all_page_rows_selected(v, cx)` |+| `<DataTablePagination table={table} />` | `<DataTablePagination table={table} />` |+| `<DataTableViewOptions table={table} />` | `<DataTableViewOptions table={table} />` |+| the toolbar with the filter `Input` | `<DataTableToolbar table={table} filter_column="email" />`, or `filter_column` on `DataTable` |+| `flexRender` | none: there is no element to render (see below) |++## Typed cells instead of JSX++The table is fast because it paints the cells in view straight from your data: there is no element per cell, a steady frame allocates nothing, and a million rows cost what a screenful does. shadcn's `cell: ({ row }) => <Badge>...</Badge>` builds an element per cell, which is exactly what this table avoids. So a cell is a **typed kind** the table knows how to paint:++| `CellRender` | Looks like | The cell value |+| --- | --- | --- |+| `Text` (the default) | the text, left, centered or right aligned | any `Cell`; numbers can be formatted with `ColumnMeta::usd()` or a `NumberFormat` (prefix, suffix, thousands grouping) |+| `Checkbox` | a Blender checkbox | a non-zero number is checked; `select_column()` reads the table's row selection |+| `Badge` | a pill, as shadcn's Badge | the text; `.badge(\|text\| BadgeVariant::..)` picks `Default`, `Secondary`, `Destructive` or `Outline` |+| `Progress` | a bar | a number from 0 to 100 |+| `Actions` | three dots, as the "more" button | none; a click calls `on_row_action(index)` with the row's index in your data |++That covers the cells of the recipe: the checkbox, the status badge, the formatted amount and the row-actions button. `flexRender` has no equivalent for the same reason, so headers are typed too: `Header::Text`, `Header::menu(title)` (the sortable header with a menu) and the select-all checkbox of `select_column()`.++<Callout type="note" title="What this cannot do">+A cell that needs real content, such as an avatar next to a name or a button that opens a dialog, is not possible in this table. React to `on_row_action` and show your own menu or dialog, or use the table of [Data tables](../data-table/) on gpui, whose `render_td` builds real elements for the cells in view only.+</Callout>++## State: uncontrolled, or controlled by you++Every piece of state works as in TanStack. Give nothing and the table keeps it. Give `initial_state` to choose where it starts. Give a value (`.sorting(..)`) and the field is **controlled**: the table only reports a change through its `on_..._change` callback and shows what you pass back.++<Tabs sync="rust-syntax" label="Rust syntax">+<Tab label="rsx!">++```rust+#[component]+fn payments_table() {+ let sorting = use_signal(SortingState::new());+ rsx! {+ <DataTable+ columns={columns()}+ data={data()}+ sorting={sorting.get()}+ on_sorting_change={move |s: &SortingState| sorting.set(s.clone())}+ />+ }+}+```++</Tab>+<Tab label="gpui builders">++```rust+DataTable::new(self.columns.clone(), self.data.clone())+ .sorting(self.sorting.clone())+ .on_sorting_change(move |s| println!("sorting is now {s:?}"))+```++</Tab>+</Tabs>++A controlled field that you never update simply never changes, which is also how you lock a table to one sort order. The callbacks are called after the change, outside the table, so they can read the table's handle.++## Helper components++The helpers take a `TableHandle`, which `use_table()` returns (`useReactTable`'s result). Pass the same handle to `DataTable` and to any helper, and they can sit anywhere in the page:++```rust+#[component]+fn payments_table() {+ let table = use_table();+ rsx! {+ <DataTableToolbar table={table} filter_column="email" />+ <DataTable table={table} columns={columns()} data={data()} toolbar={false} enable_pagination={false} />+ <DataTablePagination table={table} page_sizes={vec![10, 25, 50]} />+ }+}+```++- **`DataTableColumnHeader`** is the menu of a sortable header (Asc, Desc, Hide). `DataTable` opens it under a header made with `Header::menu(..)`.+- **`DataTablePagination`** has "Rows per page", "Page x of y", the four page buttons and "N of M row(s) selected.".+- **`DataTableViewOptions`** is the "View" button with a check per column that can be hidden.+- **`DataTableToolbar`** is a text field for `column.setFilterValue` (or the global filter without a column) and the view options.++Outside a component, the handle's methods do what TanStack's table methods do: `table.next_page(cx)`, `table.set_column_filter_value("email", "ada", cx)`, `table.toggle_all_rows_selected(true, cx)`, and `table.snapshot()` for what the table shows.++## Row models and the core++The logic is not in the element. `blenderui_table::tanstack` has `Table<T>`, `ColumnDef<T>` and the state types in the dependency-free table core, so another adapter can reuse them; the components in this page are blenderui's. `Table<T>` keeps the four row models as lists of row numbers (Blender's index mask) instead of copies: sorting a million rows uses the typed keys of the table core, filtering is a pass over the cells' text, and a page is a slice. The headless tests drive a million-row table through sorting and paging without drawing anything.++## How fast it is++Writing the table through `ColumnDef` and `Table<T>` costs a little more per frame than the delegate API, and it still paints a million rows in about a millisecond and a half. The columns are read through the closures you gave, the badge, checkbox and progress cells are painted from the same typed values, and a steady frame allocates nothing in its own drawing.++<BenchChart id="shadcn-data-table-frame" />++The 1,000,000 x 20 table of [Data tables](../data-table/), written with shadcn's `ColumnDef` and `Table` (a checkbox column, a dollar column and a progress column among the numbers), measured by `examples/bench_table.rs`. The delegate API's number is also measured before and after this change: the layer adds no cost to the table that was already there.++## Limitations++- **Cells are typed, not JSX.** See above. This is the price of the speed; there is no `flexRender`.+- **Filtering is `includesString`.** A column filter and the global filter keep the rows whose displayed text contains the value, ignoring case. There are no custom filter functions, faceted filters or range filters.+- **A header click cycles ascending, descending, none for one column.** `sorting` can hold several rules, and they all apply (the first is the most significant), but there is no shift-click to add one. Numbers do not start descending, as TanStack's `auto` does.+- **A click on a row does not select it.** Selection is the checkbox column, as in the recipe. The selected rows are highlighted in Blender's selection color.+- **The row-actions button reports a click and shows nothing.** Show your own menu from `on_row_action`.+- **Rows are identified by their index in the data** (`getRowId` is not supported), so a selection follows the index, not a key.+- **Not built:** row expansion, grouping, column ordering and column sizing as table state (dragging a header border resizes, but nothing reports it as state), faceted values, and server-side (`manual*`) pagination, sorting and filtering in the `DataTable` component. The `TableOptions` of the core has the `manual` switches.+- **A hidden column forgets a width you dragged it to**, and shows at its `size` again.+- **Icons are text**: the menus say Asc, Desc and Hide and the page buttons are `<<`, `<`, `>` and `>>`.+- **`TableHandle` calls do nothing before the table's first frame.** An unmounted `DataTable` leaves its state entity until the window closes.++## Next steps++<CardGrid>+ <Card title="Data tables" href="docs/rust/data-table/" icon="layers" kicker="Rust">+ The table underneath: delegates, a million rows, selection and sorting.+ </Card>+ <Card title="Virtual list" href="docs/rust/shadcn-virtual-list/" icon="zap" kicker="Rust">+ The same naming for a list of ten million rows or a chat.+ </Card>+ <Card title="rsx! and components" href="docs/rust/rsx-and-components/" icon="sparkles" kicker="Rust">+ How components, props and children work.+ </Card>+</CardGrid>diff --git a/website/src/content/docs/rust/shadcn-virtual-list.mdx b/website/src/content/docs/rust/shadcn-virtual-list.mdxnew file mode 100644index 0000000..5ca911f--- /dev/null+++ b/website/src/content/docs/rust/shadcn-virtual-list.mdx@@ -0,0 +1,150 @@+---+title: Virtual list API+description: A virtual list in shadcn's component style with TanStack Virtual's option names (count, estimate_size, overscan, get_item_key, scroll_to_index, scroll_to_offset, measure_element, on_range_change), plus a ChatList, over the variable-height list that holds ten million rows.+section: Rust+order: 68+languages: ["rust"]+sources: ["docs/rust.md", "bindings/rust/blenderui/src/shadcn/virtual_list.rs", "bindings/rust/blenderui/src/vlist/element.rs", "bindings/rust/blenderui/src/vlist/state.rs", "bindings/rust/blenderui-vlist/src/rows.rs", "bindings/rust/blenderui-vlist/src/view/mod.rs", "bindings/rust/blenderui-vlist/src/view/frame.rs", "bindings/rust/blenderui-vlist/src/estimate.rs", "bindings/rust/blenderui-vlist/tests/view.rs", "bindings/rust/blenderui/tests/shadcn.rs", "bindings/rust/blenderui/examples/site_shadcn_list.rs"]+---++shadcn/ui has no virtual list, so this one follows the library everyone reaches for next to it, TanStack Virtual: **`count`, `estimate_size`, `overscan`, `get_item_key`, `scroll_to_index`, `scroll_to_offset`, `measure_element` and `on_range_change`**, as props and handle methods of components written the way the shadcn ones are. Underneath is the [variable-height list](../virtual-list/), so ten million rows cost what a screenful does.++<Figure+ shot="shadcn-virtual-list"+ alt="Two lists side by side. On the left plain text rows of different heights, numbered from Row 6283185, wrapped when long, with a scrollbar thumb. On the right a chat with round colored avatars, user names and times above wrapped messages. Below, a status line: 10000000 rows, showing 6283185..6283193"+ caption="Ten million rows scrolled to row 6,283,185, next to a chat (<code>examples/site_shadcn_list.rs</code>)."+/>++## A list of ten million rows++An item is **text**: you write what item `index` says into a buffer, and the list measures, wraps and draws it. Nothing is stored per item.++<Tabs sync="rust-syntax" label="Rust syntax">+<Tab label="rsx!">++```rust title="src/main.rs"+use blenderui::prelude::*;+use blenderui::shadcn::*;++fn row(i: usize, out: &mut String) {+ out.push_str(&format!("Row {i}"));+}++#[component]+fn big_list() {+ let list = use_virtual_list();+ rsx! {+ <VirtualList+ list={list}+ count={10_000_000}+ item={row}+ estimate_size={36.0}+ overscan={12}+ on_range_change={|view: &ViewInfo| println!("showing {:?}", view.range)}+ w={px(380.0)}+ h={px(300.0)}+ />+ }+}+```++</Tab>+<Tab label="gpui builders">++```rust title="src/main.rs"+use blenderui::prelude::*;+use blenderui::shadcn::*;++VirtualList::new(10_000_000, |i, out| out.push_str(&format!("Row {i}")))+ .list(list)+ .estimate_size(36.0)+ .overscan(12)+ .on_range_change(|view| println!("showing {:?}", view.range))+ .w(px(380.0))+ .h(px(300.0))+```++</Tab>+</Tabs>++`item` runs for the items the list fetches (the ones in view and a few ahead), not for ten million. A click on a row selects it. The list is a normal element, so size it like one: give it a width and a height.++## TanStack Virtual, name by name++| TanStack Virtual | Rust |+| --- | --- |+| `count` | `count` on `VirtualList`. A `ChatList` has its `messages`. |+| `estimateSize` | `.estimate_size(px)`: the height of a one-line item before it is measured. What the list measures afterwards calibrates the estimates of the rest. |+| `overscan` | `.overscan(items)`: how many items beyond the viewport the source is asked for. |+| `getItemKey` | `.get_item_key(\|index\| key)`: stable keys, ascending with the index. They let the list find an item again after the data changes. |+| `scrollToIndex(index, { align })` | `list.scroll_to_index(index, Align::Start \| Center \| End, cx)` |+| `scrollToOffset(offset)` | `list.scroll_to_offset(px, cx)` |+| `measureElement` | `list.measure_element(index, height, cx)`: a height you know for sure. The list measures wrapped text by itself. |+| `onChange`, `range` | `.on_range_change(\|view\| ..)` and `list.range()` |+| `getTotalSize()`, `scrollOffset` | `list.view_info(cx)` (`ViewInfo`: `range`, `count`, `scroll_offset`, `total_size`) |+| `useVirtualizer` | `use_virtual_list()` |++`estimate_size`, `overscan` and `stick_to_bottom` are read when the list is created. `on_range_change` is called when the visible range or the count changes, not for every pixel of scrolling; ask `view_info` for the exact offset.++## A chat++`ChatList` is the same list with the chat's look: avatars, run headers, day dividers and whole-message selection. It opens at the newest message and follows new ones while you are at the bottom.++<Tabs sync="rust-syntax" label="Rust syntax">+<Tab label="rsx!">++```rust+#[component]+fn conversation() {+ let list = use_virtual_list();+ let messages = use_memo(|| Arc::<[Message]>::from(load_history()), ());+ rsx! { <ChatList list={list} messages={messages} w={px(420.0)} h={px(300.0)} /> }+}++// from an event handler: list.push(message, cx)+```++</Tab>+<Tab label="gpui builders">++```rust+ChatList::new(messages)+ .list(list)+ .w(px(420.0))+ .h(px(300.0))++// from an event handler: list.push(message, cx)+```++</Tab>+</Tabs>++`messages` is compared by identity. Pass the same `Arc` and the list keeps its scroll position; pass another and it starts a new conversation. Append with `list.push(message, cx)`.++## Your own source++`VirtualList` and `ChatList` build on `ItemSource` and `ListState`, so everything of [Variable-height lists](../virtual-list/) works under them: the file-backed source that holds ten million messages, the item painters, the history pages. To show one of those with these props, build the `ListState` yourself and use `variable_list(&state).on_view_change(..)`, which is where `on_range_change` comes from.++## Limitations++- **An item is text, not JSX.** The rows are painted, not built, which is why ten million of them are cheap.+- **`Align` has `Start`, `Center` and `End`.** There is no `auto`.+- **No horizontal lists, lanes, grids or sticky items.** The list is a vertical column of full-width items.+- **`measure_element` takes a height; it does not observe anything.**+- **Read-once options.** `estimate_size`, `overscan` and `stick_to_bottom` do not change after the list exists. If the items change without the count changing, call `list.invalidate(cx)`.+- **Keys must ascend with the index.** The list finds an item by key with a binary search.+- **Commands do nothing before the first frame.** The same goes for the `TableHandle` of the data table.++## Next steps++<CardGrid>+ <Card title="Variable-height lists" href="docs/rust/virtual-list/" icon="layers" kicker="Rust">+ The engine underneath: the height index, anchors, sources and the numbers.+ </Card>+ <Card title="shadcn Data Table" href="docs/rust/shadcn-data-table/" icon="sparkles" kicker="Rust">+ The same naming for tables.+ </Card>+ <Card title="Hooks and signals" href="docs/rust/hooks/" icon="zap" kicker="Rust">+ use_state, use_memo and the rest of what the handles are built from.+ </Card>+</CardGrid>diff --git a/website/src/content/docs/rust/virtual-list.mdx b/website/src/content/docs/rust/virtual-list.mdxindex 7cbedbf..9db254f 100644--- a/website/src/content/docs/rust/virtual-list.mdx+++ b/website/src/content/docs/rust/virtual-list.mdx@@ -4,7 +4,7 @@ description: A chat-grade virtualized list whose items have different heights, osection: Rustorder: 66languages: ["rust"]-sources: ["docs/rust.md", "bindings/rust/blenderui-vlist/src/lib.rs", "bindings/rust/blenderui-vlist/src/index/mod.rs", "bindings/rust/blenderui-vlist/src/index/block.rs", "bindings/rust/blenderui-vlist/src/index/fenwick.rs", "bindings/rust/blenderui-vlist/src/estimate.rs", "bindings/rust/blenderui-vlist/src/wrap.rs", "bindings/rust/blenderui-vlist/src/measure.rs", "bindings/rust/blenderui-vlist/src/source.rs", "bindings/rust/blenderui-vlist/src/log.rs", "bindings/rust/blenderui-vlist/src/list.rs", "bindings/rust/blenderui-vlist/src/chat.rs", "bindings/rust/blenderui-vlist/src/view/mod.rs", "bindings/rust/blenderui-vlist/src/view/frame.rs", "bindings/rust/blenderui-vlist/src/view/edit.rs", "bindings/rust/blenderui-vlist/tests/view.rs", "bindings/rust/blenderui-vlist/examples/bench_core.rs", "bindings/rust/blenderui-vlist/examples/bench_frames.rs", "bindings/rust/blenderui-paint/src/lib.rs", "bindings/rust/blenderui/src/vlist/mod.rs", "bindings/rust/blenderui/src/vlist/element.rs", "bindings/rust/blenderui/src/sink.rs", "bindings/rust/blenderui/tests/vlist.rs", "bindings/rust/blenderui/examples/site_chat.rs", "bindings/rust/blenderui-vlist-gpui/src/element.rs", "bindings/rust/blenderui-vlist-gpui/examples/bench_list_gpui.rs", "bindings/rust/blenderui-vlist-gpui/bench/run.mjs"]+sources: ["docs/rust.md", "bindings/rust/blenderui-vlist/src/lib.rs", "bindings/rust/blenderui-vlist/src/index/mod.rs", "bindings/rust/blenderui-vlist/src/index/block.rs", "bindings/rust/blenderui-vlist/src/index/fenwick.rs", "bindings/rust/blenderui-vlist/src/estimate.rs", "bindings/rust/blenderui-vlist/src/wrap.rs", "bindings/rust/blenderui-vlist/src/measure.rs", "bindings/rust/blenderui-vlist/src/source.rs", "bindings/rust/blenderui-vlist/src/log.rs", "bindings/rust/blenderui-vlist/src/list.rs", "bindings/rust/blenderui-vlist/src/chat.rs", "bindings/rust/blenderui-vlist/src/view/mod.rs", "bindings/rust/blenderui-vlist/src/view/frame.rs", "bindings/rust/blenderui-vlist/src/view/edit.rs", "bindings/rust/blenderui-vlist/tests/view.rs", "bindings/rust/blenderui-vlist/examples/bench_core.rs", "bindings/rust/blenderui-vlist/examples/bench_frames.rs", "bindings/rust/blenderui-paint/src/lib.rs", "bindings/rust/blenderui/src/vlist/mod.rs", "bindings/rust/blenderui/src/vlist/element.rs", "bindings/rust/blenderui/src/sink.rs", "bindings/rust/blenderui/tests/vlist.rs", "bindings/rust/blenderui/examples/site_chat.rs", "bindings/rust/blenderui/src/shadcn/virtual_list.rs", "bindings/rust/blenderui-vlist/src/rows.rs", "bindings/rust/blenderui-vlist-gpui/src/element.rs", "bindings/rust/blenderui-vlist-gpui/examples/bench_list_gpui.rs", "bindings/rust/blenderui-vlist-gpui/bench/run.mjs"]---A chat is the hard case for a list. Every message has its own height (a one-word reply, a paragraph, a screenshot), the height depends on how wide the window is, new messages arrive at the bottom while you read older ones, and history loads at the top. A list that only handles rows of equal height can't do it, and one that keeps a height for every message stops being cheap when there are ten million of them.diff --git a/website/src/content/docs/start/installation.mdx b/website/src/content/docs/start/installation.mdxindex 2536312..e38b8d5 100644--- a/website/src/content/docs/start/installation.mdx+++ b/website/src/content/docs/start/installation.mdx@@ -48,7 +48,7 @@ Or add it to `Cargo.toml` by hand:```toml title="Cargo.toml"[dependencies]-blenderui = "0.1"+blenderui = "0.2"```The first build compiles BUI's C kit for you, so you need:@@ -126,11 +126,10 @@ BUI runs the **real Dear ImGui** (1.93), so existing ImGui code compiles unchang- **Python** comes with `pip install blenderui`. Import it as `blenderui.imgui`. The very first wheels (0.1.0) were published before it; if the import fails, upgrade with `pip install -U blenderui`.- **C++**: build BUI with CMake (see the C tab) and link `bui::imgui`. You include `imgui.h` and `imgui_impl_bui.h`. The CMake option `BUI_BUILD_IMGUI` is on whenever a C++ compiler is present.- **C**: the same build gives you `cimgui.h` and `cimgui_impl_bui.h` (CMake target `bui_cimgui`).-- **Rust**: add the `blenderui-imgui` crate. It isn't on crates.io yet (only `blenderui` is), so take it from the repository as a git dependency:+- **Rust**: add the `blenderui-imgui` crate from crates.io:-```toml title="Cargo.toml"-[dependencies]-blenderui-imgui = { git = "https://github.com/ppmpreetham/BUI" }+```sh+cargo add blenderui-imgui```Want ImGui's widgets to *be* Blender's widgets? Build with `-DBUI_IMGUI_BLENDER_WIDGETS=ON` in CMake, or enable the `blender-widgets` feature of `blenderui-imgui` in Rust. The rest of the ImGui API is unchanged.diff --git a/website/src/data/bench.ts b/website/src/data/bench.tsindex efa1cb6..d23f84c 100644--- a/website/src/data/bench.ts+++ b/website/src/data/bench.ts@@ -244,6 +244,23 @@ const tablesBase = {],note: "Frame times are the whole pipeline: render, layout, paint and the software raster. One element per cell was measured at 2,000 rows (a million would need about 70 GB and over ten minutes per frame; its cost grows linearly with rows). Allocation counts come from a counting global allocator; the table's drawing allocates nothing in steady state (a unit test asserts it). The same table on real gpui against gpui-component is in the next chart.",},+ shadcnDataTable: {+ caption:+ "The shadcn layer on the painted table, 1,000,000 rows x 20 columns in a 900x500 window (examples/bench_table.rs, release build, software raster, Windows 11)",+ columns: ["", "DataTable before this change", "DataTable after", "shadcn Table<T>, typed cells"],+ numeric: [1, 2, 3],+ rows: [+ ["Runs (median of)", "5", "5", "3"],+ ["Build", "0.10 ms", "0.10 ms", "1.6 ms"],+ ["First frame", "6.7 ms", "7.0 ms", "6.9 ms"],+ ["Scroll frame", "1.39 ms", "<strong>1.26 ms</strong>", "1.53 ms"],+ ["Heap allocations per frame (whole pipeline)", "48", "<strong>48</strong>", "<strong>48</strong>"],+ ["Allocations in the table's own drawing", "0", "<strong>0</strong>", "<strong>0</strong>"],+ ["Memory added (working set)", "17.2 MB", "17.3 MB", "24.1 MB"],+ ["Sort 1,000,000 rows by a column (header click, includes the repaint)", "25.5 ms", "24.5 ms", "27.6 ms"],+ ],+ note: "Both DataTable columns are the same benchmark (the painted DataTable of the delegate API): before is the commit that precedes this change, built in a separate worktree, run alternately with the current build on the same machine; the difference is noise. The last column is the same table written with shadcn's ColumnDef and Table: a checkbox column, a dollar column and a progress column among the numbers, rows held as 4-byte row numbers whose cells are computed. Its extra build time is creating the one million row values and the row model; its extra memory is the data and the row model (a list of row numbers). The allocation counts come from a counting global allocator; unit tests assert that the table's own drawing allocates nothing in steady state, for both. Not measured: other machines, the real GPU path.",+ },vlistIndex: {caption:"Height index against a flat Vec of running totals, medians of 5 runs of a batch (bindings/rust/blenderui-vlist, examples/bench_core.rs, release build)",@@ -578,6 +595,20 @@ export const charts = {table: "dataTable",source: "bindings/rust/blenderui/examples/bench_table.rs",},+ "shadcn-data-table-frame": {+ kind: "bars",+ title: "shadcn Data Table: scroll frame, 1,000,000 rows x 20 columns",+ subtitle: "Whole frame, 900x500 window, software raster, median of 3 to 5 runs",+ unit: "ms",+ better: "lower",+ headline: { value: "1.5 ms", text: "per scrolled frame through ColumnDef and Table" },+ bars: [+ { label: "DataTable", sub: "the delegate API", value: 1.26, display: "1.26 ms", ours: true },+ { label: "shadcn Table<T>", sub: "ColumnDef, typed cells", value: 1.53, display: "1.53 ms", ours: true },+ ],+ table: "shadcnDataTable",+ source: "bindings/rust/blenderui/examples/bench_table.rs",+ },"data-table-gpui": {kind: "bars",title: "gpui: scroll frame, 1,000,000 rows x 20 columns",