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:
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
Layershows one incustom, above its background and image and below its sublayers. Custom layers compare byRcidentity. CustomLayerHostcarries the layer key, itsLayerPlacement(frame and visible clip in window coordinates), the scale factor, aNativeLayerto draw in (CoreAnimationorHeadless), and the window's raw handle.- The changeset runs
DetachCustomfirst, thenAttachCustomandLayoutCustomonce 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 thatapp.createElement(name)turns intoElement::Custom, which owns oneCustomElementinstance per element.CustomElement: CustomLayeraddsattribute_changed, called bysetAttributeandremoveAttribute.- The element takes
divstyles, lays out like adiv, accepts no children, and the scene draws its content box asPaintItem::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 outsidecrates/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
Rcper layer and need downcasts to diff. MemorySurfaceand 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 <chart> 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<Rc<dyn CustomLayer>>.
PaintListtakes the compositor's own data, in logical pixels from the content box's top-left:fill(rect, color),shape(rect, color, shape)withLayerShape's radii and border, andimage(rect, Rc<LayerImage>).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 keyedTEXTandTEXT_BAND(#134). Public since #183, as the whole paragraph surface is; see Absorbing children.- The scene calls
paintfor 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, keyedCUSTOM, 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
CALayeron macOS, and the custom layer puts its widget inside: a web view, aGtkPictureshowing 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 withgtk_widget_snapshot_childat 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'ssnapshotagain, 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:
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<dyn ElementStyle>; // S::default(); see Defaults
fn create_instance(&self) -> Option<Box<dyn ElementInstance>>; // 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<Dirty, AttributeError> { 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<Rc<dyn CustomLayer>> { 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 hookcollectdoes. The compositor still holds custom layers asRc<dyn CustomLayer>compared by identity: the instance hands one out throughcustom_layerand keeps its ownRcto drive it, as the web view does to load a page. This replaces the prototype's oneRc<dyn CustomElement>serving both roles. measureandpainttake&self: they run during layout and scene building, with the tree borrowed.- Built-ins implement the same traits;
divhas no instance.
Built so far (ui_tree/instance.rs):
ElementDefinition::create_instancedefaults toNone, andElementInstancehasconnected,disconnected, andattribute_changed. The tree calls them itself, synchronously, as it changes; seedocs/ui-tree/lifecycle.md.remove_subtreedisconnects a connected element's instance before dropping it.ElementContexthas the node,request_layout, andrequest_paint, which bump the node's style revisions like a style change of that level once the hook returns.attribute_changedreturnsResult<Dirty, InvalidAttribute>. The tree calls it before storing the value, so a refused value leaves the attribute as it was andsetAttributethrowsInvalidAttributeValueError.measure,paint,custom_layer, handles,dispatch_event, andframeare 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 inUITreeBindingState. ElementTagbecomes 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):
ElementDefinitionhasname,class_name(the JavaScript constructor,Elementunless overridden),role(Root,Container, orLeaf),content_model,compositing(see Native overlays),create_style, andcreate_instance.ElementTagis au16id. Burokku's own types register first, soElementTag::WINDOW,DIV,FLEX,GRID, andTEXTare 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::elementre-exports what an implementation needs, including the compositor's custom layer and layer data types. - An
Elementis its tag and aBox<dyn ElementStyle>. Code that knows the type reads the style as its own type withElement::style_as, as the window's size and text collection do.NodeandElementno longer deriveCloneorPartialEq, andUITree::set_elementis gone. - Layout dispatches on the role:
Rootis the window,Containerlays out its children, andLeafmeasures itself,textthrough 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:
windowonly under the app, an<option>only inside a<select>.
A child is inserted only when both agree. By default a custom element may
appear in any container that takes boxes, so div, flex, grid, and
window accept it without listing it. rules.md then describes the built-in
models.
Built: ContentModel { children, parents }. Children::None takes
nothing; Children::Boxes takes any element whose parents are
Parents::Boxes; Children::Absorbs { text, elements } takes raw text if text is set and the named element types,
absorbed. Parents::App appears only under the app root. Absorbing is the
absorbing parent's choice, so text, whose parents are Boxes, may also sit
inside another text, which names it.
Measuring #
Proposed. A leaf measures itself through measure, which layout calls as
Taffy's measure function.
- Input, in our own types: the known width and height, if any, and the available space on each axis. Output: the size, and optionally the first baseline for baseline alignment.
- It runs inside layout with the tree borrowed, so it calls no JavaScript and changes nothing. It returns the same result for the same input until the element requests layout, because Taffy caches it.
- An element with an intrinsic ratio, such as an image, applies it from the known dimension.
- A natural size that changes later, such as a decoded image or a loaded page,
goes through
ElementContext::request_layout, which bumps the node's layout revision like a style change. This answers, for custom elements, the question indocs/interaction/engine_state.mdof engine state that changes layout: the instance asks for layout and never changes it fromreconcile.
Built (ui_tree/measure.rs): ElementInstance::measure(&self, context: &mut MeasureContext<'_>, input: MeasureInput) -> Measured, as
docs/plan/text-engine-implementation.md asks. The context measures a
paragraph the instance holds, through MeasureContext::measure_paragraph,
which takes the handle and an AvailableSpace and returns Measured
(#134, public since #183).
MeasureInputhas the known width and height and the available space on each axis, all in the content box: layout converts Taffy's border box known size.Measuredis the content size and the first baseline from the content box's top.- Layout gives every
Leafelement buttextaLayoutRole::Leafnode that measures through its instance, or measures nothing without one. Its children get no layout nodes.textkeeps its paragraph role until the text rebuild. - A size that is not finite or is negative reads as zero, and such a baseline as none, instead of failing the frame.
- A change at
Reflow, from a style,request_layout, orattribute_changed, bumps the node's layout revision, so its Taffy cache is dropped and it measures again; otherwise Taffy's cache answers.
ElementContext and handles #
Proposed.
- Hooks get an
ElementContext: the element's node,request_layout,request_paint,request_frame,dispatch_event, andhandle. - A hook never gets the tree or a JavaScript context. Its requests are queued
and applied after it returns, so a hook cannot re-enter the tree or
JavaScript. The prototype already releases its borrow before calling
attribute_changed; this makes that the rule for every hook. handlereturns anElementHandlefor native callbacks to keep, such as a navigation delegate. It holds the node's generational id and does nothing once the node is freed.- Decided:
dispatch_eventalways queues its event as a script task, never running JavaScript inside a hook or native callback. A cancelable event such asnavigateis refused through a callback that receives whether a listener canceled it. request_frameruns the instance'sframehook before the next frame, likerequestAnimationFrame, for content the engine animates. Content that animates natively, such as a playing video, needs no frames.
Built (ui_tree/handle.rs): ElementContext::handle returns an
ElementHandle with the node, request_layout, and request_paint. Its
requests go to a queue the tree owns and the handle reaches weakly, and the
first one since the host's last turn wakes the event loop. The host applies
them at the start of its next turn, dropping those for freed nodes, except
settled promises. A handle does nothing once its tree is gone.
dispatch_event and request_frame are built with the script surface; see
Script surface.
Instance lifetime #
Proposed.
createElementcreates the instance. It is dropped when its node is freed, which reclamation does once nothing in the tree or JavaScript holds it.- A disconnected element that JavaScript still holds keeps its instance, so a
web view taken out of the tree and put back keeps its page.
disconnectedis where an instance may release heavy resources if it chooses. - The compositor keeps its
Rcto a custom layer until it detaches it, so an instance may be dropped before its layer detaches. - A failed
attachorlayoutdoes not fail the frame: the element draws nothing in that frame, and the error reaches JavaScript as anerrorevent on the element. A panic in a hook is an application bug and propagates. NodeandElementstop derivingClone. TodaysetPropertyclones the whole element to learn whether anything changed, which would share or copy an instance; see Dirty state and caches.
Script surface #
Decided. An element's script surface comes through the extension API,
registered with the element; see docs/plan/extension-api.md.
Proposed.
- An extension registers a QuickJS class for its element, and the element's
JavaScript object gets that class's prototype, above
Element's. The class's methods reach the element's instance through a lookup the extension API provides. - A method may be async and return a Promise that the instance settles through
its handle, as
evaluateon a web view would. Built; see below. - Each event the element dispatches declares its payload, whether it bubbles,
and whether it can be canceled. Decided: the definition lists its
events, and the payload is
event.detail. - When TypeScript types for custom elements come (see Deferred), the extension ships them with its class: the tag name, the element interface, its events, and its style map entries.
attribute_changedreturns a result, so a bad value throws fromsetAttribute, and a dirty level, so changing a web view'ssrcdoes not lay out again. Attributes set before the element is connected still arrive at once, as in the prototype.- Element definitions come from Rust only. An extension's scripts may build on them, and composing elements in JavaScript is the frameworks' job.
Built so far: events (ui_tree/handle.rs,
js_bindings/events/custom.rs). ElementDefinition::events lists
ElementEvent { name, bubbles, cancelable }, and dispatching any other name
fails with UndeclaredEvent. ElementContext::dispatch_event and
ElementHandle::dispatch_event queue the event with an rquickjs IntoJs
payload, and ElementHandle::dispatch_event_then calls back with whether a
listener canceled it, or false if it could not fire. The host runs each as a script
task in order with focus requests. Script gets a BurokkuCustomEvent whose
detail is the payload; see docs/ui-tree/elements.md.
Classes (js_bindings/class.rs): Burokku creates the global constructor
an element type's class_name names, extending Element, unless a global of
that name exists. ElementDefinition::define_class adds the type's methods
and getters to its prototype with rquickjs, once in each new script context
and before any script. They reach the instance through
burokku::element::with_instance, which downcasts it to the type's own and
gives an ElementContext, and throws TypeError: Illegal invocation on any
other object. The extension API's class::<C>() and the registry lookup
from Shared state are not needed for this: the class hangs off the
definition, and the lookup is with_instance.
Frames (ui_tree/instance.rs, host/render.rs):
ElementContext::request_frame and ElementHandle::request_frame queue the
element for the next frame, once however often it asks, and the host
requests a redraw. The redraw runs each queued element's
ElementInstance::frame(context, now) before layout, so what it requests
draws in that frame and needs no other. Frames therefore follow the window's
redraws, not the host's turns. An element that is not connected by then
misses the frame, so a removed element does not keep the host drawing.
Async methods (js_bindings/promise.rs): burokku::element::element_promise
makes a Promise for a method to return and a PromiseResolver for the
instance to keep. The Promise's resolving functions wait in a table in the
script context, since a value kept in Rust must not outlive the runtime.
resolve(value) and reject(message) queue the settlement on the element's
handle queue, in order with its events, and the host settles it as a script
task even if the element was freed since. A resolver dropped unsettled
rejects its promise. All of a handle's script requests now wait in one queue
in the binding state, one task each. Requests the JS task queue has no room
for wait there for a later turn instead of being dropped, since a dropped
settlement would leave its promise pending forever.
Native overlays #
The compositing mode for content that must live in the window's native view
hierarchy, such as a WKWebView, which renders and takes input only as an
NSView.
Decided:
- Declaration.
ElementDefinition::compositing()returnsCompositing::InTree, the default, orNativeOverlay. It is fixed per type, like the role. - Pointer. Hit testing puts the overlay's visible rectangle on top. The pointer there hovers the element and its ancestors, so enter and leave events fire, but the engine sends no move, down, up, click, or wheel events; the native view gets those.
- Focus. When the native view takes keyboard focus, the engine moves focus
to the element and fires
focus;element.focus()gives the native view keyboard focus. Tabbing past the native view's last control returns to the engine's sequential order, and when the engine focuses something else, the window takes keyboard focus back. The element joins tab order only with atabindex, like other elements. The cursor belongs to the native view while the pointer is over it. - Warning. When anything later in paint order intersects an overlay's visible rectangle, such as a fixed element, a later sibling, or a scroll thumb, Burokku warns on stderr like its other warnings: once for each overlay and each element painted over it, until that overlap ends.
Proposed.
- Stacking. Overlays sit above the whole layer tree, in paint order among themselves.
- Clipping. A rectangle only: the clip of the scroll containers around it.
No
border-radius, and later noclip-path,opacity, ortransform. - Placement.
LayoutCustomruns on every frame the placement changes, including frames where only a scroll offset changed, and in the same commit as the layer tree, so the overlay does not lag behind scrolling or resizing. - Later. Hosting the content inside the layer tree removes the stacking
and clipping limits where the platform allows it, as WebView2's composition
controller does on Windows and a child widget drawn in the surface's
snapshotdoes on GTK.
Built so far:
CompositingandElementDefinition::compositing(ui_tree/definition.rs), exported byburokku::element.- The scene plan records, while it walks paint order, each overlay's visible rectangle and every later item that intersects one: backgrounds, borders, painted items, in-tree custom layers, text, and scroll thumbs. Text counts its laid-out glyphs, not its box. Later overlays are not reported over earlier ones. The host prints the pairs a presented frame has and the previous one did not, naming each element by its tag and node.
- Overlays' content boxes are hit regions above every other, and a hit says
whether it is one (
scene.rs).PointerState::plan_inputturns input over an overlay into hover when no press that began in the engine and no capture owns the pointer, so boundary events fire and nothing else does. - Overlays are focusable without a
tabindex(interaction/focus.rs).ElementInstance::focusruns when the engine moves focus to an element, but not for focus its handle reported.ElementHandle::focus,focus_next, andfocus_previousqueue requests that the host runs as script tasks, so they fire focus events. Tab order moves on from a focused element outside it as from atabindexof 0 at its place, for the engine's Tab as well. The binding state notes when focus lands on an overlay, and once focus has left it at the end of a host turn, the host callsWindow::take_keyboard_focus, which makes the content view first responder on macOS.
Absorbing children #
Decided. In layout, a paragraph is a leaf: the layout reconciler gives a
text element one layout node, measured through its shaped paragraph, and
its descendants get none. What makes text special is that it absorbs its
whole subtree into its own content, its text runs. Absorbing elements get a
lifecycle of their own.
Layout role and the way children are handled are separate choices:
| Children are boxes | No children | Children are absorbed | |
|---|---|---|---|
| Container | div, flex, grid |
||
| Leaf | web view, image | text |
Absorbing is a general capability, not a text special case: a <select>
collecting <option>s or a custom <chart> collecting <series> would work
the same way.
An inline atom, such as an icon inside a paragraph, is a further case: placed by the paragraph, but measured and painted by itself. It is deferred.
Proposed lifecycle:
-
What gets absorbed. The content model declares which children are allowed and that they are absorbed. Absorbed nodes get no layout box, paint items, or stacking of their own. Today any other child of a
textis an error (TextError::InvalidParagraphChild). -
Ownership. Each absorbed node maps to the element absorbing it, today
text_ownerin layout, and the outermost wins: a<text>inside another<text>is a run, not a paragraph (TextError::ExpectedParagraph). Event targets, hit testing, andgetBoundingClientRectfor absorbed nodes answer through this mapping. -
Role changes when nodes move. Whether a
<text>is the paragraph or an absorbed run depends on its parent, so moving it changes its role. Moving it into another<text>drops its paragraph caches and layout node; moving it out creates them. The layout reconciler recomputes this from the tree each pass today; in the lifecycle, the tree'smovedandconnectedevents (NodeLifecycle) trigger it. -
Changes flow upward. A style's dirty state is otherwise local. Under an absorbing element, a change anywhere in the absorbed subtree makes the absorbing element dirty: a child added, removed, or moved, text data changed, or an absorbed run's style changed. The dirty levels still apply: new text or a font change reflows (re-shapes), while a run's color change can be repaint only.
textdoes this today: its instance compares the revisions of what it absorbs (CollectedSubtree), and a color change collects asRepaint. -
Hooks. On the instance, roughly:
fn collect(&mut self, subtree: AbsorbedSubtree<'_>); // rebuild content from descendants, in order fn subtree_changed(&self, change: SubtreeChange) -> Dirty { Dirty::Reflow } // optional finer classificationThe collected content feeds the leaf's measuring and painting, as shaped paragraphs do now. Collecting again on any change stays the default; the classification hook is an optimization.
-
Custom elements use the same hooks, so a custom element can absorb its children too.
Built (ui_tree/absorb.rs), items 2, 3, 5, and 6 (#132):
- The tree keeps each node's owner, the outermost element absorbing it, as
it keeps the connected flag: every change of parent updates the moved
subtree, stopping at the first node whose owner did not change.
UITree::ownerandNode::ownerread it. Layout no longer keepstext_owner. ElementInstance::owner_changed(context, owner)tells an element when it is absorbed into another, alone or with an ancestor, and when it is released, in tree order, sotextcan drop or create its paragraph. It hears this beforeconnectedordisconnectedin the same change, so an element absorbed as it connects never builds what it would drop.ElementInstance::collect(context, subtree) -> Dirtyrebuilds the element's content.AbsorbedSubtreegives the owner's node and walks the absorbed nodes in tree order, each element as a start and an end around its content, so styles can inherit. Only an element that is not absorbed collects, and what it returns applies as an attribute change's level does. Collecting takes the instance out of its node, so the hook reads the tree without borrowing it mutably, and never gets the tree itself. The walk checks each child's parent link and stops at a node it has seen, so a corrupt child list, which only a bug in the tree produces, ends it with anAbsorbErrorinstead of looping or panicking (#145).
Built, item 4 (#133):
- A change marks the element that collects it, its owner, which walks no ancestors since the tree keeps owners: text set on an absorbed text node, any change recorded on an absorbed element (a style change, an attribute change its instance says invalidates something, or a request its own instance makes from a hook or a handle), and an absorbed node added, removed, moved, or reordered. A move marks the owner it left and the one it joined, and every absorbing element it releases, the moved node or one inside it, collects its own content. A style change to the owner itself marks it too.
UITree::collect_markedrunscollecton each marked element that still exists. The host calls it after theframehooks in every redraw, including one that only draws again, and before every layout. Whatcollectreturns applies to the owner:Reflowbumps its layout revision asrequest_layoutdoes, andRepaintonly draws again.textcollects through its instance since text step 2a. A new absorbing element is marked when it is created, so even an empty one collects before its first frame.
Built, the engine lent (#134, public since #183): in Collect,
InstanceGive::state_with_paragraphs lends the instance with Paragraphs,
which other events lend as None. Paragraphs::create gives a
ParagraphHandle, and Paragraphs::update replaces its content from a
ParagraphInput, the text with its runs in ComputedTextStyles, which the
instance builds from the AbsorbedSubtree. Measuring and painting take the
handle; see Measuring and Painting with built-in data. Burokku's own text
is built on this alone, in features/text. Dropping an instance drops its
ParagraphHandle, which frees the paragraph at the engine's next use.
Window #
Before step 7, in ui/host/window.rs and ui/host/events.rs:
- An app has exactly one window:
WindowSpec::from_ui_treerejects more. - The style accepts
width,height, andbackground-color.widthandheightrequest the window size: the initial size, and a resize whenever they change (apply_same_window_update). Layout forces the window's box to the native viewport. Thetitleattribute sets the native title and updates it when it changes. - The OS close button makes the host close the window and exit the app. JavaScript never hears about it.
- Losing focus cancels the pointer. Gaining focus, occlusion, and modifier
changes are ignored. The size reaches JavaScript only through
ResizeObserver.
Decided.
- Multiple windows will be supported, so nothing may assume one root.
titlestays an attribute andbackground-colorstays style. Other window setup goes through functions.- Size.
widthandheightare attributes, positive numbers in logical pixels, that give the size a new window opens at: 800 by 600 when missing or invalid. Changing them later does not resize an open window. Script resizes it withresizeTo(width, height)on the window element, which works whateverresizesays. The CSSresizeproperty decides whether the user can resize the window:both, the default, ornone. Other values are rejected while native windows only turn resizing on or off. Layout always follows the native size, and a user's resize reaches script as throughResizeObservertoday. - Close and reopen. The close button fires a cancelable
closeevent on the window element. Unless a listener callspreventDefault, the window closes but its element stays in the tree, asclose()does, so the app keeps running andopen()can reopen it. Connecting the element opens a window; disconnecting it closes the window and removes it for good;close()closes the window but keeps the element;open()reopens it. - No window left: the app exits when no window element is connected to the
app root. A closed window is still a connected element, so
close()keeps the app alive; detaching the last window element exits, as today. #120 tracks an app choosing to keep running with no window element at all. - Internal capabilities:
windowmay use capabilities the extension API does not offer, since it is the app's entry point.
Built (ui/host/window.rs): the width and height attributes give the
size a new window opens at. The window's style has background-color and
resize, which window sync applies to the native window
(Window::set_resizable) without laying out or painting again. resizeTo and
a closed flag both live on the window's instance (ui_tree/window.rs),
one of the two among Burokku's own elements, with text's. resizeTo records the request with a
serial, so window sync resizes the open window for each new request, even to
the size it asked for last; a request before the window opens sets the size it
opens at, and a rejected native resize applies nothing from that update while
the next tree change tries again. close() sets the closed flag and open()
clears it; window sync closes the native window when the element is closed
(WindowChange::Closed), tearing down its renderer and resetting the GPU, but
keeps the element so the app does not exit, and recreates the window on open.
The close button fires close through an ElementHandle on the window
(UITree::element_handle), so it is queued like an instance's event; unless a
listener cancels it, the host closes the element on its next turn, as close()
does. If script cannot run, the event reports not canceled, so the window still
closes.
Proposed.
- A root role. A window is neither a container nor a leaf. It is the root
of layout, with its size from the native window, and of stacking,
position: fixed, hit testing, and focus. The app accepts only windows. - A native window lifecycle. Connecting the element creates a native
window, with graphics set up asynchronously; disconnecting it closes the
window. This is separate from layer attach and detach. The close button
fires a
closeevent (see Decided), so the tree stays the source of truth instead of the host exiting on its own. - Size. Decided above: the attributes open the window,
resizeToresizes it, andresizedecides whether the user can. - Other native state reported back. Focus, occlusion and minimize, move, and scale factor reach JavaScript as events, with getters for the current state.
- The setup functions. Minimum and maximum size, position, decorations,
fullscreen, always-on-top, and the window's kind (panel, popup, utility),
plus
focus()andminimize().close()andopen()are built (see Decided). Calls made before the native window exists are kept and applied when it is created. - Multiple windows. Each window has its own layout, scene, compositor, hit
testing, and focus. A custom element moved to another window detaches from
one and attaches to the other, re-creating its native resources there; a
web view moves to the other window's content view. The prototype's
CustomLayerHost::windowis already per surface. - Per-window platform services. Cursor (the host already tracks one), IME, files dropped on the window, context menus, and dialogs attached as sheets belong either to the window or to the app. Not part of step 7: #119 proposes a rule.
- No windows left. Decided above: the app exits when no window element is connected, though a closed element keeps it alive. macOS apps often keep running with no window element at all, so #120 tracks a way to choose.
- Custom roots, later. If
windowis a definition like any other, popovers, tray menus, and overlay panels could be custom roots.windowcreates native windows through internal capabilities, so an extension's custom root needs the extension API to offer them; seedocs/plan/extension-api.md.
Style #
Decided. Style is scoped per element type through a trait, not global like
CSS. There are no selectors, no cascade, no inheritance across elements, no
inherit, initial, or unset keywords, and no currentColor. State styling
such as hover and focus comes from framework hooks (React, Solid) setting
properties, not from pseudo-classes. Style stays on the main thread.
The trait #
Proposed shape. It finishes today's traits::Styles, whose
apply_to_taffy exposes Taffy and whose static supports_property keeps it
from being a trait object:
pub trait ElementStyle {
// Scoped parsing: only what this element type accepts.
fn supports_property(&self, name: &str) -> bool;
fn set_property(&mut self, name: &str, value: &str) -> Result<(), StyleError>;
fn remove_property(&mut self, name: &str);
fn revisions(&self) -> StyleRevisions;
// What layout needs, in our own types. Taffy conversion stays internal.
fn box_model(&self) -> BoxModel; // size, min/max, margin, padding, border widths
fn positioning(&self) -> Positioning; // position, inset, z-index
fn overflow(&self) -> Overflow;
fn item(&self) -> ItemLayout; // how a flex or grid parent places this element
fn container(&self) -> ContainerLayout<'_> { ContainerLayout::Block } // how it places its children
// What painting needs.
fn decoration(&self) -> BoxDecoration;
fn text(&self) -> Option<&TextStyle> { None }
}
- The non-Taffy readers (
overflow,position,z_index, background, border) go through the trait instead of matching everyElementvariant. - Style types compose shared parts, as
FlexStyle { common, … }does today. Default methods delegate to the sharedCommonStyle. - Setting a property an element type does not accept fails loudly instead of being ignored.
- Item properties (
flex-grow,align-self,grid-column) are the one shared group every child carries, because they depend on the parent's layout mode. - Built so far: layout reads the shared properties through
common()and the container mode throughcontainer(), and builds Taffy's style from them inlayout/style.rs. The container properties are parts of their own,FlexContainerandGridContainer, so an element that switches modes can hold both.
Switching the layout mode #
Decided. An element type may switch its container mode: container() is
computed from its own style, so a custom element can offer a display
property that picks block, flex, or grid. div, flex, and grid stay
single-mode types.
- Switching between block, flex, and grid only changes layout; the layout
reconciler already handles
div,flex, andgridin one arm. - The role (container or leaf) stays static, because changing it rebuilds the layout topology and changes which children are accepted.
- Proposed: such an element type accepts the properties of every mode it
can enter, stored even while unused, so the order of
setPropertycalls does not matter.
Defaults #
Decided. A style type implements Default, and its values are the
defaults. removeProperty resets that one property to its Default value.
- The composed type's
Defaultwins over a shared part's. DefaultneedsSized, so it is a bound on registration (S: ElementStyle + Default), not a supertrait of a trait used asdyn.
Custom element styles #
Decided. A custom element defines its own style properties, used from JavaScript like any other. Scoping prevents two extensions' properties from colliding.
Proposed: a custom style may add names but not redefine shared ones such as
width. Each custom property declares its parser (built from the shared value
parsers), its default, and its dirty level, from which the TypeScript style
map entry can be generated.
Relative units #
Decided. The current setup supports no relative units: no em, no rem,
and no currentColor. With no inheritance either, every style is read
directly: layout methods need no resolve context, percentages stay Taffy's
job, and nothing outside a style can make it dirty.
em and rem are deferred. When they come, only text accepts them, in text
properties, and the text run resolution handles them: TextStyle::resolve
resolves each nested run against its parent run and the outermost against the
defaults. font-size parses only px today, so that means storing a
FontSize::{Px, Em, Rem} and multiplying in resolve, and deciding what 2em
on the outermost run means.
Dirty state and caches #
Decided. A style records its own dirty state: setProperty and
removeProperty record the change, and the cache policy reads it.
| Level | Meaning | Examples |
|---|---|---|
| Clean | Nothing changed | setting the current value |
| Repaint | Draw again, keep layout | background-color, text color, z-index |
| Reflow | Lay out and draw again | width, padding, position, font size and family |
-
Levels are ordered; several changes before a frame keep the highest.
-
Proposed: record changes as per-level revision counters, not a flag that is cleared, because several caches read style at different times: Taffy style reuse in
layout/reconcile.rs, text shaping, the scene, and resize observers. Each cache remembers the revision it last used. This splits today's singleNodeRevisions::style, which makes a hover background change rebuild the Taffy style and re-run layout.pub struct StyleRevisions { pub layout: u64, pub paint: u64 } -
Proposed: split the tree's revision the same way.
setPropertyalso bumpsUITree::revision, which keys layout, so per-node counters alone still lay out again after a hover color change. A paint-level change bumps a paint revision folded into the frame revision, asInteraction::frame_revisionfolds in scroll and focus. -
Proposed: attributes get a dirty level too, so a web view's
srcdoes not lay out again. Custom ones return it fromattribute_changed. Every built-in attribute isClean, since neither layout nor the scene reads one: window sync compares a window'stitlewith the one it last applied, and focus readstabindexwhen it moves. -
Changes that do not come from
setPropertyuse the same counters: a parent switching layout mode, and a custom element's natural size changing throughElementContext. -
With the style recording its own changes,
setPropertyno longer clones the element and compares it with the original to learn whether anything changed, asui_tree/content.rsdoes today. Elements can then hold instances that do not clone.
Stacking contexts #
Decided to cover in the design. The style trait reports facts, position,
inset, and z-index, and the engine owns the rule in
scene/stacking.rs: an element starts a stacking context when it is fixed, or
has a non-auto z-index and is positioned or a flex or grid item.
- The flex or grid item check reads the parent's current
container()mode, not its tag, so it covers custom flex containers and switching elements. - A
z-indexchange re-sorts paint order without layout; apositionchange needs both; a parent switching mode changes its children's stacking. Paint order is rebuilt every frame today, so reading the current mode is enough. - Later self-only triggers (
opacity,transform,filter) need one layer per stacking context to apply, which the layer tree does not group by yet. - Native overlays sit outside stacking; the stacking pass is where to warn when something should paint above one.
Still to settle #
- Shorthands:
padding,margin,border,flex,inset, andgrid-areaexpand to longhands, and removing a shorthand removes them all. WhethergetPropertyValueexists, which needs serialization. - Shared value parsers for lengths, percentages, and colors, used by built-in and custom styles alike.
Testing #
Proposed.
- Every definition runs under the test backend. On the memory surface a custom
layer gets
NativeLayer::Headless, and the presented layer tree records it by identity, so tests assert where it is attached and placed, not what it draws. - A native overlay has no native view in tests. Its element still lays out, paints its box decorations, and receives its hooks.
- A recording custom element in
crates/burokku's tests checks hook order: creation, attributes,connected, attach, layout, detach,disconnected, and drop. Elements with platform code, such as the web view, test that code in their own crate.
Implementation order #
Decided. Two phases. First the elements and the extension API are
rebuilt; then the text engine is rebuilt on top of them, as
docs/plan/text-engine.md describes. Phase 2's steps 1 and 2 are built.
Steps for the first phase, one stacked pull request per step. Steps 1 to 6 are built, and step 7 is in progress. Each step keeps the existing tests passing unchanged and updates the docs it affects.
- Custom layers in the compositor, from
proto/webview:CustomLayer,CustomLayerHost, the changeset ops, and the macOS and memory surfaces. Native crate only. - The style trait:
ElementStylereplacestraits::Stylesand the per-variant matches inElement, with dirty levels and split revisions. The one visible change: paint-only changes stop laying out again. - The extension API, with definitions and the registry. Built-ins register
through it, including the JavaScript the plugins install today, with tag
ids and content models in both directions.
textregisters as a definition but keeps today's pipeline behind it. Updatesdocs/ui-tree/rules.md. - Instances:
ElementInstance,ElementContext, handles, lifecycle, attributes, measuring through a leaf role in layout, and painting with built-in data or a custom layer. Applications can register custom elements. Updatesdocs/ui-tree/lifecycle.md. - Native overlays: pointer, focus, and the stacking warning.
- The script surface.
- The window's root role, then multiple windows.
The second phase, the text engine, follows docs/plan/text-engine.md.
Deferred #
emandrem, intextonly; see Relative units.display: noneandvisibility: no parser supports them yet. They fit the design without changes, provided "connected" stays separate from "drawn".opacity,transform,filter,clip-path, and roundedoverflowclipping.transitionandanimation.pointer-events,cursor, anduser-select.directionand writing modes.background-imageand other asset references.- Accessibility.
- TypeScript types for custom tag names.
- Inline atoms inside
text, such as an icon in a paragraph; see Absorbing children. - Custom layout algorithms, such as a virtual list or masonry. Container modes stay block, flex, and grid.
Open questions #
- Window: which platform services belong to a window or the app (item 7, #119), and how an app keeps running with no window (item 8, #120).
- Shorthands,
getPropertyValue, and shared value parsers; see Still to settle.