Element types and instances #
Defined in crates/core/src/ui/ui_tree/definition.rs and
crates/core/src/ui/ui_tree/instance.rs, and exported for applications by
burokku::element.
An element type has two parts:
| Part | Trait | How many | Holds |
|---|---|---|---|
| Definition | ElementDefinition |
one per type, registered once | the name, JavaScript class, kind, and how to create an instance; its kind's trait names the style |
| Instance | ElementInstance |
one per element, made by the definition | the element's own state, such as a native view |
Burokku's own div, flex, grid, text, and input are definitions
like any other, each of one kind. window is one too, but its kind is its
own, which no other type can name. window, text, and input have
instances:
the window's keeps
its resizeTo requests and whether it is closed, and text's keeps the
paragraph it collects from what it absorbs. text is built on this public
API alone, as a built-in extension in features/text. An application's type
that keeps no state needs none, and is then style and attributes only, like
a div.
div, flex, and grid come from the burokku-containers crate, one
container of each kind, written on this public API alone as the reference
for a container of an application's own. The engine declares none of them;
its own tests declare stand-ins and register them.
Declaring an element type #
struct WebViewElement;
impl ElementDefinition for WebViewElement {
type Kind = kind::Leaf<Self>;
fn name(&self) -> &'static str {
"web-view"
}
// A WKWebView is an NSView above the layer tree.
fn compositing(&self) -> Compositing {
Compositing::NativeOverlay
}
fn events(&self) -> &'static [ElementEvent] {
&[ElementEvent {
name: "navigate",
bubbles: false,
cancelable: true,
}]
}
fn create_instance(&self) -> Option<Box<dyn ElementInstance>> {
Some(Box::new(WebView {
view: NativeWebView::new(),
}))
}
}
impl Leaf for WebViewElement {
type Style = CommonStyle;
}
| Item | Answers | Notes |
|---|---|---|
Kind |
how the element takes part in layout, which children it takes, and its style | one of the markers in kind with Self; see Its kind |
name |
the tag createElement takes |
unique among registered types |
class_name |
the JavaScript constructor whose prototype the element gets | defaults to Element; see Its class |
define_class |
adds the element's methods and getters to its class | adds nothing by default; see Its class |
compositing |
where its custom layer draws | InTree by default, or NativeOverlay; see Native overlays |
events |
the events its instance dispatches | none by default; see Events |
create_instance |
a new element's instance | defaults to None |
Its kind #
Kind names one of four markers, each with Self, and each takes only a
type that implements its trait. The trait names the style, so a type cannot
name a kind whose rules it does not meet: kind::Flex<Self> on a type that
is not a FlexContainer does not compile.
Kind |
Trait | Its elements | Its Style |
|---|---|---|---|
kind::Leaf<Self> |
Leaf |
measure themselves through their instance, and text through its paragraph; what they take as children is absorbed into their own content |
a BoxStyle |
kind::Block<Self> |
BlockContainer |
lay out their children as blocks, like div |
a BoxStyle |
kind::Flex<Self> |
FlexContainer |
lay out their children as a flex container, like flex |
a FlexContainerStyle |
kind::Grid<Self> |
GridContainer |
lay out their children as a grid container, like grid |
a GridContainerStyle |
- Styles. A kind's style trait gives what its layout reads.
BoxStyle::commongives theCommonStyleevery box has, which is aBoxStyleitself. AFlexContainerStylealso gives itsFlexPropertiesthroughflex, and aGridContainerStyleitsGridPropertiesthroughgrid;burokku-containers'DivStyle,FlexStyle, andGridStylecomposeCommonStylewith what their kind reads. Each style also parses its properties, asStyleProperties, and starts fromDefault. The kind alone decides how an element lays out its children: no property switches it between blocks, flex, and grid. - Where it appears. Every element but the window appears wherever boxes may: inside the window and every container, which take them all. The window appears only under the app, the only element that may, since its kind is its own. See rules.md.
- Stacking. The window is the root stacking context, and its parent's
kind decides how a child's
z-indexstacks it. A child of a flex or grid container is an item: with az-indexother thanauto, it forms a stacking context even when it is static. In the window or a block container, only a positioned child'sz-indexapplies. A parent's style plays no part: a block container whose style has flex properties still stacks its children as blocks. Absorbed children are part of their leaf's content and do not stack on their own.
A Leaf also says what only a leaf has:
Leaf method |
Answers | Notes |
|---|---|---|
children |
which children it takes | Children::None by default, or Children::Absorbs raw text and the named types into its own content |
editable |
whether the user edits its text | false by default; input is. An editable element takes focus and its turn in tab order as with a tabindex of 0, the text selection stays inside it and shows a caret there, and the engine applies the platform's text and editing commands to the raw text it absorbs as their defaults, after beforeinput and before input; see interaction.md |
single_line |
whether an editable element's text is one line | false by default; input's is, and its instance shapes it without wrapping, whatever text-wrap says. Text the platform inserts into it, typed, pasted, or committed by an IME, and a value script sets, loses its line breaks, every character the text engine breaks a line at (\r, \n, U+2028, and U+2029), as the HTML text input's value sanitization strips them, and beforeinput carries the text as it goes in |
The registry reads a leaf's answers once, when the type registers, and never asks again. A type's kind never changes, and an element never changes type.
Registering #
An extension registers the type before the application starts:
Burokku::builder()
.extension(|registry: &mut Registry<'_>| {
registry.element(WebViewElement);
Ok(())
})
.script("app.createElement('web-view')")
.run()?;
Names are not checked. Two types with one name, Burokku's own included, stop
the application with ExtensionError::Elements.
Burokku's own types register first. Their order fixes the ElementTag
constants.
Its class #
A type that script should call into names its own class and adds to it:
impl ElementDefinition for WebViewElement {
fn class_name(&self) -> &'static str {
"WebView"
}
fn define_class<'js>(
&self,
context: &Ctx<'js>,
prototype: &Object<'js>,
) -> rquickjs::Result<()> {
let reload = Function::new(context.clone(), |this: This<Object<'js>>| {
with_instance(&this, |step: DispatchStep<'_, Instance<WebView>>| {
step.skip_take()
.skip_action()
.give(|cx, ()| cx.state().view.reload())
})
})?;
prototype.set("reload", reload)?;
prototype.prop(
"url",
Accessor::new_get(|this: This<Object<'js>>| {
with_instance(&this, |step: DispatchStep<'_, Instance<WebView>>| {
step.take(|cx| Some(cx.state().view.url()))
.skip_action()
.give(|_cx, url| url)
})
}),
)
}
// …
}
- The class. Burokku creates the global constructor
class_namenames, extendingElement, unless a global of that name exists. Like Burokku's own element classes, it cannot be called withnew;createElementgives the element its prototype. - Adding to it.
define_classruns once in each new script context, before any script. It adds to the class's prototype with rquickjs, whichburokku::runtime::rquickjsre-exports. A type that keeps the defaultclass_namewould add to every element's class, so it names its own first. - Reaching the instance.
with_instancegives the function aDispatchStepchain over the element's instance as its own type, the oneevent_dispatchgets, with no event:takereads the instance, andgivechanges it and asks for what the element needs, which applies once the chain ends. It runs with the tree borrowed, so it runs no script. Called on any other object, including an element of another type, it throwsTypeError: Illegal invocation, as a DOM method does.
A method whose answer comes later, from native work, returns a Promise:
let evaluate = Function::new(
context.clone(),
|this: This<Object<'js>>, source: String| -> rquickjs::Result<Promise<'js>> {
let (promise, resolver) = element_promise(&this)?;
with_instance(&this, |step: DispatchStep<'_, Instance<WebView>>| {
step.skip_take().skip_action().give(|cx, ()| {
cx.state().view.evaluate(source, move |result| match result {
Ok(value) => resolver.resolve(value),
Err(error) => resolver.reject(error.to_string()),
});
})
})?;
Ok(promise)
},
)?;
element_promisemakes the Promise and aPromiseResolver, which the instance or its native callback keeps until the work finishes. Call it beforewith_instance, which holds the tree it needs. It checks only thatthisis a node;with_instancechecks the rest.- The resolver is not
Send. Work that finishes on another thread hands its result back to the main thread to settle it. resolve(value)takes any rquickjsIntoJsvalue, which reaches script as an event'sdetaildoes; a value that cannot convert rejects the promise instead.reject(message)rejects it with anError.- The promise settles as a script task on the host's next turn, in order with the element's other handle requests, even if the element was freed since, as script may still hold the promise.
- A resolver dropped unsettled rejects its promise, so script never waits forever on an instance that was dropped or forgot it.
Declaring its instance #
An instance reacts to what the engine tells it the way a
feature slot does: each InstanceEvent reaches
event_dispatch as one DispatchStep chain, whose take reads the
instance, whose action it skips, and whose give changes it and asks the
engine for what the element needs. What the engine asks of it with the tree
borrowed, measuring and painting, stays a method that changes nothing. Every
method has a default, so an instance overrides only what it needs, and a
chain it leaves unfinished ignores the event.
/// `NativeWebView` stands for the platform code: a `CustomLayer` that loads
/// pages, reports their height, and takes keyboard focus.
#[derive(Debug)]
struct WebView {
view: Rc<NativeWebView>,
}
impl ElementInstance for WebView {
fn event_dispatch(step: DispatchStep<'_, Instance<Self>>, event: InstanceEvent<'_>) {
match event {
InstanceEvent::Connected => {
step.skip_take().skip_action().give(|cx, ()| {
cx.state().view.resume_loading();
// The callbacks outlive the chain, so they keep handles.
let handle = cx.handle();
cx.state().view.on_height_change(move || handle.request_layout());
let handle = cx.handle();
cx.state().view.on_navigate(move |url, decide| {
// A listener calling preventDefault() refuses the
// navigation.
handle
.dispatch_event_then("navigate", url, move |canceled| {
decide(!canceled)
})
.expect("web-view declares navigate");
});
});
}
InstanceEvent::Disconnected => {
step.skip_take()
.skip_action()
.give(|cx, ()| cx.state().view.stop_loading());
}
InstanceEvent::AttributeChanged { name: "src", value } => {
step.skip_take().skip_action().give(|cx, ()| match value {
Some("") => cx.refuse(InvalidAttribute("src is empty".into())),
value => cx.state().view.load(value),
});
}
InstanceEvent::Focused => {
step.skip_take()
.skip_action()
.give(|cx, ()| cx.state().view.take_keyboard_focus());
}
_ => {}
}
}
fn measure(&self, _context: &mut MeasureContext<'_>, input: MeasureInput) -> Measured {
Measured {
width: input.known_width.unwrap_or(300.0),
height: input.known_height.unwrap_or(self.view.height()),
first_baseline: None,
}
}
fn custom_layer(&self) -> Option<Rc<dyn CustomLayer>> {
Some(Rc::clone(&self.view) as Rc<dyn CustomLayer>)
}
}
crates/core/src/element.rs holds a smaller example, <color-swatch>,
which is compiled as a doctest.
InstanceEvent |
Sent when | Carries |
|---|---|---|
Connected |
the element joined the app tree, alone or with an ancestor | |
Disconnected |
the element left the app tree, alone, with an ancestor, or removed while attached | |
OwnerChanged |
the element was absorbed into another element's content, or no longer is, alone or with an ancestor | the outermost element absorbing it, or None |
Collect |
before the next frame, when the element absorbs its children, is not absorbed itself, and something it absorbs changed | nothing: take reads the nodes with absorbed() |
AttributeChanged |
an attribute is about to change or be removed, connected or not | the name, and the new value or None |
Focused |
the engine moved focus to the element, from script, tab order, or a press | |
Frame |
the next frame is being built, and the element asked for it | the frame's Instant |
| Method | Called | Gets | Returns |
|---|---|---|---|
measure(&self) |
layout measures a Leaf; cached until the element requests layout |
MeasureContext, MeasureInput |
the content box size and first baseline |
paint(&self) |
the scene builds a frame | PaintList |
|
custom_layer(&self) |
the scene builds a frame | a native layer over the content box, or None |
Each chain runs synchronously, inside the call that caused its event.
- Lifecycle.
ConnectedandDisconnectedcome in tree order as the tree updates its connected flags, to each node's instance before its slots. Moving an element within the app tree sends neither. Removing a connected subtree disconnects its instances before dropping them. - Attributes.
AttributeChangedcomes before the value is stored. Agivethat callsrefuseleaves the attribute as it was, andsetAttributethrowsInvalidAttributeValueError. Whatgiverequests is recorded like a style change: nothing changes nothing,request_paintdraws again, andrequest_layoutlays out again. Setting an attribute to its current value sends nothing. - Collecting.
takereads what the element absorbs withabsorbed(), which onlyCollectgives, and returns what it read;givekeeps it and requests what the new content invalidates.give'sstate_with_paragraphslendsParagraphswith the instance, inCollectalone:creategives aParagraphHandlethe instance keeps, andupdatereplaces its content from aParagraphInput, the text with its runs inComputedTextStyles. Burokku's owntextshapes its paragraph there, from the raw text and nestedtextelements it absorbs. - Focus.
Focusedcomes before thefocusevent fires, so that a native view of the element's own can take keyboard focus. Focusing the element that has focus already sends nothing, and neither does focus that came through the handle'sfocus, since the native view took it itself. - Frames.
Framecomes once for eachrequest_frame, at the start of the next frame, before layout, so what its chain requests draws in that frame. LikerequestAnimationFrame, one request is one frame, however many times it was made: an instance that animates requests the following frame from itsFramechain, and frames follow the window's redraws. An element that is not connected when the frame comes misses it, so an animation that should survive being moved out and back requests a frame again onConnected. - Measuring. Input and output are in logical pixels of the content box.
measuremust return the same result for the same input until the element requests layout. A size that is not finite or is negative reads as zero.MeasureContext::measure_paragraphmeasures a paragraph the instance holds at anAvailableSpace, asMeasured, so a leaf that is one paragraph returns what it gets. - Painting.
PaintListtakes fills, shapes, and images, positioned from the content box's top-left. They draw above the element's background and border and below its children, and are not clipped to the content box.text(&handle)draws a paragraph the instance holds, shaped to the content box's width, above them. The pointer over its lines hits the element, also where they reach past its box. The custom layer covers the content box above them, and the surface attaches it while a frame shows the content box.
measure, paint, and custom_layer take &self: they run with the tree
borrowed, so they change nothing.
Native overlays #
Some native content draws and takes input only as a native view of its own,
such as a WKWebView, which is an NSView. Its custom layer adds that view
above the whole layer tree, and its type says so with
Compositing::NativeOverlay. Nothing in the layer tree can draw over the
view, and it ignores rounded corners; only the scroll clip around it applies.
Hit testing puts an overlay's visible rectangle above everything else, since
its view is. The pointer there hovers the element and its ancestors, so
pointerenter and pointerleave fire, but no other pointer, mouse, or wheel
event reaches script: the native view takes them. A press that began outside
the overlay, a pointer capture, or a trackpad gesture keeps the pointer until
it ends, as the platform keeps sending a drag to the view it began in.
Burokku warns on stderr when something paints over an overlay's visible rectangle, such as a later sibling, a fixed element, or a scroll thumb, once for each overlay and each element until that overlap ends. Overlays stack among themselves in paint order, so one overlay over another is fine.
An overlay takes focus from script, a press, or its view even without a
tabindex, and joins tab order only with one. Keyboard focus moves between
the engine and the native view both ways:
- When the engine focuses the element, its instance hears
Focusedand gives the native view keyboard focus. - When the native view takes keyboard focus itself, as from a click, its
callback calls the handle's
focus. The element gains focus andfocusfires, but the instance does not hearFocused. - When Tab or Shift+Tab leaves the native view's controls, its callback calls
the handle's
focus_nextorfocus_previous. Focus moves on through tab order from the element's place, as from an element with atabindexof 0. - When focus leaves the element for one that is not a native overlay, such as by script, by Tab from the engine or out of the view, or by its removal, the window takes keyboard focus back from the native view at the end of the host turn: the focus chain asks for it, and so does the host's focus fixup for a removed element. Focus moving on to another overlay leaves keyboard focus with that overlay's view.
Take, give, and handles #
An instance's chain runs with the tree borrowed, so it cannot change the
tree in the middle of a mutation, or run JavaScript. Its take reads, and
its give writes and asks the engine for what the element needs, which
applies once the chain ends.
InstanceTake |
Reads |
|---|---|
state() |
the instance |
node() |
the element's NodeId |
event() |
the event, or None in a chain from with_instance |
absorbed() |
the nodes the element absorbs, for Collect only |
InstanceGive |
Does |
|---|---|
state() |
the instance, to change |
node() |
the element's NodeId |
request_layout() |
lays the element out again once the chain ends |
request_paint() |
draws it again once the chain ends, keeping its layout |
request_frame() |
sends Frame once before the next frame |
dispatch_event(name, detail) |
fires a declared event once script can run; see Events |
refuse(reason) |
for AttributeChanged, keeps the attribute as it was |
handle() |
an ElementHandle for code that outlives the chain |
An ElementHandle has the same node, request_layout, request_paint,
request_frame, and dispatch_event, for native callbacks, and
dispatch_event_then, which reports whether a listener canceled the event.
It also has focus, focus_next, and focus_previous for a native view's
keyboard focus; see Native overlays. Its requests queue on the tree, and the
first one since the host last applied them wakes the event loop. The host
applies them at the start of its next prepare_to_wait. Focus requests,
events, and settled promises run script, so they then run as script tasks,
waiting for a later turn while the JS task queue is full. A request for a
freed node is dropped, except a settled promise, which script may still hold.
A handle whose tree is gone does nothing.
Events #
An element type lists the events its instance dispatches in events, each
an ElementEvent with its name and whether it bubbles and is
cancelable. Dispatching a name the type does not list fails with
UndeclaredEvent.
use rquickjs::{IntoJs, Null};
#[derive(IntoJs)]
struct Navigation {
url: String,
}
handle.dispatch_event("load", Null)?;
handle.dispatch_event_then("navigate", Navigation { url }, |canceled| {
decide(!canceled);
})?;
- Always queued. An event fires as a script task on the host's next turn,
in order with the handle's other script requests, never inside the chain or
native callback that dispatched it. An event dispatched from a chain that
script caused, such as on
AttributeChangedfromsetAttribute, fires after that script. - Payload. The payload is any rquickjs
IntoJsvalue, which script reads asevent.detail, like aCustomEvent's. Strings, numbers,Vecs, and maps convert as rquickjs converts them, and a struct converts to an object with#[derive(IntoJs)], which needsrquickjswith itsmacrofeature as a dependency. An event without a payload passesNull, which reads asnull;()andNoneread asundefined. It is converted only when something listens. - Target. The event fires at the element, then at its ancestors if it bubbles. A disconnected element gets no event.
- Outcome.
dispatch_event_thencalls back with whether a listener calledpreventDefault(), which only a cancelable event allows. An event that cannot fire, because the element is disconnected or freed or the application has ended, calls back withfalse, so a native callback that must answer, such as a navigation decision, always gets an answer.
In TypeScript, such an event is a BurokkuCustomEvent<Detail, Type>.
Elements of application types are typed as plain elements, so a listener
narrows the event it receives.
Lifetime #
createElement definition.create_instance()
setAttribute AttributeChanged (also while detached)
appendChild Connected (once in the app tree)
next frame measure, paint, custom layer attach
removeChild Disconnected
next frame custom layer detach
garbage collection instance dropped (when reclamation frees the node)
application ends instance dropped (before the script runtime stops)
The element owns its instance and drops it when its node is freed. A
disconnected element that JavaScript still holds keeps its instance, and may
connect again. Release heavy resources on Disconnected and keep what
reconnecting needs.
When the application ends, the host drops every instance, connected or not,
after the tree features hear Shutdown and the slots are detached, and
before it lets the script runtime stop. An instance may therefore keep a
script value, such as a callback in an rquickjs Persistent, which must not
outlive the runtime. It hears no event first. Script that runs after that,
such as an extension's shutdown hook, finds no instance.
Instances and engine state #
Both refer to nodes, but they serve different code. The engine's own state
that refers to many nodes, such as interaction and JavaScript wrappers, does
not hear anything from the tree: the script binding cleans it up at the one
place each change is made, as lifecycle.md describes.
ElementInstance is for one element's state, and is public.
| Engine state | ElementInstance |
|
|---|---|---|
| Visibility | pub(crate), for the engine |
pub, for applications |
| How many | one per subsystem, for the whole tree | one per element whose type has an instance |
| Owner | the script binding or the host, outside the tree | the element, inside the tree |
| Moves | after_mutation, once per moved subtree root, after the mutation |
Connected and Disconnected, sent during the mutation, once per element with an instance, in tree order |
| Frees | nothing: its NodeRefs to freed nodes read as None |
Drop |
| Sees | the tree | its chain's InstanceTake, never the whole tree |
after_parent_change works out whether a node was and is connected, and tells
the instances. Engine state covers every node, including text nodes and
divs, which have no instance, so it is not an instance itself.
| To | Use |
|---|---|
| keep one element's native view, decode its image, or refuse its attribute values | ElementInstance |
| keep state on nodes of any type, dropped with each node | FeatureSlot |
| keep engine state that refers to many nodes | a field of Interaction or the binding, cleaned up as lifecycle.md describes, with EngineState if it affects painting |
| keep a feature's state for the whole tree | never a field of Interaction or UITree; see Who owns state |
| react to the tree from script | DOM events and observers |