# Custom elements and custom layers Status: built through step 6 of Implementation order; step 7, the window's root role and multiple windows, is in progress in `docs/todo.md`. The `proto/webview` branch prototyped the custom layer and the custom element, and embeds a `WKWebView` with them in `example/webview`. The goal is one delivery path: an element the application defines, such as a web view, and a built-in element such as `div` go through the same traits. **Decided** marks what the design settled; **Proposed** marks recommendations that still need a decision; **Open** marks questions without a recommendation yet. Elements and custom layers, built-in or not, register through the extension API, designed in `docs/plan/extension-api.md`. `docs/plan/text-engine.md` covers why `text` did not fit this plan until phase 2 rebuilt it. ## What the prototype has What `proto/webview` had when this plan started. `custom_element` and `Element::Custom` are gone: element definitions replaced them. The compositor, in `crates/native/src/compositor.rs`: ```rust pub trait CustomLayer: fmt::Debug { fn attach(&self, host: &CustomLayerHost) -> Result<(), SurfaceError>; fn layout(&self, host: &CustomLayerHost) -> Result<(), SurfaceError> { Ok(()) } fn detach(&self, host: &CustomLayerHost); } ``` - A `Layer` shows one in `custom`, above its background and image and below its sublayers. Custom layers compare by `Rc` identity. - `CustomLayerHost` carries the layer key, its `LayerPlacement` (frame and visible clip in window coordinates), the scale factor, a `NativeLayer` to draw in (`CoreAnimation` or `Headless`), and the window's raw handle. - The changeset runs `DetachCustom` first, then `AttachCustom` and `LayoutCustom` once the tree is built. Detaching is tied to dropping the host, so removal, reset, and a dropped surface always detach. The application layer, in `crates/burokku`: - `BurokkuBuilder::custom_element(name, create)` registers a name that `app.createElement(name)` turns into `Element::Custom`, which owns one `CustomElement` instance per element. - `CustomElement: CustomLayer` adds `attribute_changed`, called by `setAttribute` and `removeAttribute`. - The element takes `div` styles, lays out like a `div`, accepts no children, and the scene draws its content box as `PaintItem::Custom`. Prototype limits: the `WKWebView` is a native view above the whole layer tree, so nothing draws over it and it ignores `border-radius`. It relies on `setClipsToBounds`, which is macOS 14+. It takes pointer and keyboard input directly, so hit testing, hover, and focus never see it. Registration rejects only today's built-in names, and the definitions live in `UITreeBindingState`, out of reach of the tree's content checks. The TypeScript types do not know custom tag names. ## Layers: built-ins stay data **Decided.** Solid color, image, clip, and shape stay plain data that the reconciler diffs and each surface maps natively. `CustomLayer` is the one extension point, for what that data cannot express. Turning built-ins into trait objects was rejected because: - They are the protocol every platform implements natively: `CALayer`, Windows composition visuals, and GSK render nodes. A trait-based built-in needs per-platform code outside `crates/native/src/platform/`, or a host API that recreates today's ops. - GSK rebuilds immutable render nodes each frame, which data fits and imperative attach/detach does not. - The tree is rebuilt every frame: data diffs field by field, while trait objects cost an `Rc` per layer and need downcasts to diff. - `MemorySurface` and the scene tests compare trees by value. - The macOS surface batches background, image, radii, and border into one platform layer. ### Painting with built-in data **Proposed.** A custom element may paint its content box with the same data built-ins use, solid color, image, shape, and text, through its instance's `paint` hook; see Traits. This is the portable path: every surface already maps that data, and the scene tests compare it by value. A `` draws its bars this way with no platform code. A custom layer stays for content only native code can draw, such as a web view or a video. **Built** (`ui_tree/paint.rs`): `ElementInstance::paint(&self, list: &mut PaintList<'_>)` and `custom_layer(&self) -> Option>`. - `PaintList` takes the compositor's own data, in logical pixels from the content box's top-left: `fill(rect, color)`, `shape(rect, color, shape)` with `LayerShape`'s radii and border, and `image(rect, Rc)`. `bounds()` is the content box. - `text(&handle)` shapes the handle's paragraph, one the instance created while collecting, to the content box's width and draws it from the content box's top-left, above the other items, in bands keyed `TEXT` and `TEXT_BAND` (#134). Public since #183, as the whole paragraph surface is; see Absorbing children. - The scene calls `paint` for every laid-out element with an instance, after its background and border, and culls each item by its own rectangle. Items are not clipped to the content box. An item whose rectangle is not finite or has a negative size, or a shape with a corner radius or a border width that is, is skipped instead of failing the frame. - Each item is a layer keyed `CONTENT + index`, so an unchanged image keeps its platform image. The custom layer fills the content box above the items, keyed `CUSTOM`, while the content box is shown. ### Custom layers on every platform `CustomLayer` is imperative: the surface calls `attach`, `layout`, and `detach`, and the layer keeps native objects in between. That fits retained trees: CoreAnimation layers, Windows composition visuals, and GTK widgets. GSK render nodes, rebuilt each frame, are not one. `NativeLayer` has only `CoreAnimation` and `Headless` so far. **Proposed.** On GTK, a custom layer draws through a child widget. A web view has no other way: WebKitGTK's web view is a widget that keeps its own state, takes its own input, and redraws itself by queuing a draw, and its content is reachable only through the widget tree. - The host gives each custom layer a container widget, as it gives a `CALayer` on macOS, and the custom layer puts its widget inside: a web view, a `GtkPicture` showing a video's paintable, or a widget of its own. - If the GTK surface is a widget that builds its render nodes in `snapshot`, it draws the container with `gtk_widget_snapshot_child` at its place in paint order, under the element's clip, rounded corners included. This avoids the macOS overlay's stacking and clipping limits. - The content owns its redraws: a widget queues a draw, and a paintable invalidates its contents. Neither needs `request_paint`. A redraw runs the surface's `snapshot` again, so the surface reuses the render nodes of unchanged layers instead of rebuilding the tree. - Input reaches a child widget by its rectangle, even where engine content is drawn above it. Content that takes no input, such as a video, turns off `can-target`, so input reaches the engine. A hook that returns a render node each frame is not needed: anything it could draw, a widget can draw, and it could not host a web view. Windows adds a `NativeLayer` variant carrying the layer's visual. A web view there hosts WebView2 in a child window or, through its composition controller, in that visual. ## Elements: one delivery path **Decided.** Built-in elements and custom elements use the same traits. **Proposed.** Split each element into a definition and an instance: | Part | Holds | Example | |---|---|---| | Definition, per tag | name, style type, layout role, content model, JavaScript prototype, compositing mode | `div` is a definition with no instance state | | Instance, per element | lifecycle, measuring, painted content, attribute handling | a web view is mostly instance | Registering `div` then means registering a definition through the extension API, the same way an application registers a web view. Trait objects fit elements where they did not fit layers: an element persists across frames, so it is allocated once and changes are tracked by revision, not found by comparing values. Only the per-frame reads, such as style getters during layout and paint, pay for dynamic dispatch. ### Concerns every element answers | # | Concern | Notes | |---|---|---| | 1 | Lifecycle | **Decided** as a trait. **Proposed**: `connected` and `disconnected`, separate from the custom layer's attach and detach, which in the prototype also run when culling skips an element scrolled out of view. Give the instance an `ElementContext`: its node, event dispatch, `request_layout`, `request_paint`. The tree's `NodeLifecycle` (`docs/ui-tree/lifecycle.md`) already records these events. See ElementContext and handles, and Instance lifetime. | | 2 | Layout | **Decided** as a trait. The role is static per definition: a container (block, flex, grid) lays out its children, and a leaf measures itself; see Measuring. `text` is a leaf that absorbs its children; see Absorbing children. The window is the root; see Window. The container mode may switch; see Style. | | 3 | Style | See below. | | 4 | Content model | Which children are accepted, today `NodeKind::accepts`, and how: as boxes, not at all, or absorbed into the element's own content. Also which parents the element may appear in. Separate from layout. See Content model. | | 5 | Paint | Box decorations are shared. Content is none, text, image, built-in data from the instance, or a custom layer. Overlays such as scroll thumbs belong here. | | 6 | Compositing mode | In the layer tree, or a native overlay like the web view. The scene and stacking need to know which. See Native overlays. | | 7 | Interaction | Hit testing, focusability and default tab order, default actions, cursor, text input and IME. Native overlays take input directly; see Native overlays. | | 8 | Script surface | Prototype, element-specific properties, methods, and events, attribute reflection, generated TypeScript types. The prototype's custom elements get the bare `Element` prototype. See Script surface. | | 9 | Native resources | Per-window objects such as a web view's content view, `CustomLayerHost::window` in the prototype. Moving between windows and scale changes. | | 10 | Headless behavior | Every element must run under the test backend; native elements need a fallback. See Testing. | | 11 | Accessibility | Later; leave a slot. | ### Traits **Proposed** shape, roughly: ```rust pub trait ElementDefinition { fn name(&self) -> &str; fn role(&self) -> LayoutRole; // Container, Leaf, or Root (window) fn content_model(&self) -> ContentModel; // see Content model fn compositing(&self) -> Compositing; // InTree or NativeOverlay fn create_style(&self) -> Box; // S::default(); see Defaults fn create_instance(&self) -> Option>; // None for `div` } pub trait ElementInstance { fn connected(&mut self, cx: &mut ElementContext<'_>) {} fn disconnected(&mut self, cx: &mut ElementContext<'_>) {} fn attribute_changed( &mut self, cx: &mut ElementContext<'_>, name: &str, value: Option<&str>, ) -> Result { Ok(Dirty::Clean) } fn frame(&mut self, cx: &mut ElementContext<'_>, now: Instant) {} // after request_frame fn measure(&self, input: MeasureInput) -> Measured { Measured::default() } // leaves fn paint(&self, content: ContentBox, out: &mut PaintList) {} // built-in data fn custom_layer(&self) -> Option> { None } // Absorbing elements add `collect` and `subtree_changed`; see Absorbing children. } ``` - The element owns its instance as a `Box`, so hooks that change it take `&mut self`, as the absorbing hook `collect` does. The compositor still holds custom layers as `Rc` compared by identity: the instance hands one out through `custom_layer` and keeps its own `Rc` to drive it, as the web view does to load a page. This replaces the prototype's one `Rc` serving both roles. - `measure` and `paint` take `&self`: they run during layout and scene building, with the tree borrowed. - Built-ins implement the same traits; `div` has no instance. **Built so far** (`ui_tree/instance.rs`): - `ElementDefinition::create_instance` defaults to `None`, and `ElementInstance` has `connected`, `disconnected`, and `attribute_changed`. The tree calls them itself, synchronously, as it changes; see `docs/ui-tree/lifecycle.md`. `remove_subtree` disconnects a connected element's instance before dropping it. - `ElementContext` has the node, `request_layout`, and `request_paint`, which bump the node's style revisions like a style change of that level once the hook returns. - `attribute_changed` returns `Result`. The tree calls it before storing the value, so a refused value leaves the attribute as it was and `setAttribute` throws `InvalidAttributeValueError`. - `measure`, `paint`, `custom_layer`, handles, `dispatch_event`, and `frame` are built; see Measuring, Painting with built-in data, ElementContext and handles, and Script surface. ### Registry **Proposed.** - The registry lives in the `UITree`, built before the app starts and fixed after. The tree needs it for its content checks, while the prototype keeps definitions in `UITreeBindingState`. - `ElementTag` becomes a small id into the registry. Built-ins register first, through the extension API like custom elements, so matches on built-in tags become id comparisons. - **Decided**: element names are not checked. Any name registers, and only a name already registered, Burokku's own included, fails startup. **Built so far** (`ui_tree/definition.rs`): - `ElementDefinition` has `name`, `class_name` (the JavaScript constructor, `Element` unless overridden), `role` (`Root`, `Container`, or `Leaf`), `content_model`, `compositing` (see Native overlays), `create_style`, and `create_instance`. - `ElementTag` is a `u16` id. Burokku's own types register first, so `ElementTag::WINDOW`, `DIV`, `FLEX`, `GRID`, and `TEXT` are constants. - The registry lives in the `UITree`. The built-in UI tree extension registers the five definitions, and assembly installs the registry before any node or script exists. - Applications register element types with `Registry::element`, under any name. `burokku::element` re-exports what an implementation needs, including the compositor's custom layer and layer data types. - An `Element` is its tag and a `Box`. Code that knows the type reads the style as its own type with `Element::style_as`, as the window's size and text collection do. `Node` and `Element` no longer derive `Clone` or `PartialEq`, and `UITree::set_element` is gone. - Layout dispatches on the role: `Root` is the window, `Container` lays out its children, and `Leaf` measures itself, `text` through its paragraph and any other leaf through its instance; see Measuring. ### Content model **Proposed.** A content model answers both directions, as `docs/ui-tree/rules.md` does today: - **Children:** which ones the element accepts, and whether they are boxes or absorbed. - **Parents:** where the element may appear: `window` only under the app, an `