Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
use crate::Document;
use crate::layout::paint_tree::{HoistedPaintChild, StackingContext};
use bitflags::bitflags;
use blitz_traits::events::{
BlitzPointerEvent, BlitzPointerId, DomEventData, HitResult, PointerCoords,
};
use blitz_traits::node_id::NodeId;
use blitz_traits::shell::ShellProvider;
use euclid::{Point2D, Rect, Size2D};
use keyboard_types::Modifiers;
use kurbo::{Affine, Rect as KurboRect};
use markup5ever::{LocalName, local_name};
use parley::{BreakReason, Cluster, ClusterSide};
use selectors::matching::ElementSelectorFlags;
use std::cell::{Cell, RefCell};
use std::fmt::Write;
use std::ops::Deref;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
#[cfg(feature = "writing-mode")]
use style::computed_values::flex_direction::T as FlexDirection;
use style::computed_values::isolation::T as Isolation;
use style::computed_values::white_space_collapse::T as WhiteSpaceCollapse;
use style::invalidation::element::restyle_hints::RestyleHint;
use style::properties::ComputedValues;
use style::properties::generated::longhands::position::computed_value::T as Position;
use style::selector_parser::RestyleDamage;
use style::servo_arc::Arc as ServoArc;
use style::shared_lock::SharedRwLock;
use style::stylesheets::UrlExtraData;
use style::values::computed::CSSPixelLength;
use style::values::computed::Display as StyloDisplay;
use style::values::computed::Rotate;
use style::values::generics::transform::{Scale, Translate};
use style::values::specified::box_::{DisplayInside, DisplayOutside};
use style_dom::ElementState;
use style_traits::values::ToCss;
use taffy::{Cache, prelude::Layout};
use thin_vec::ThinVec;
use super::stylo_data::{ComputedStyleRef, StyloData};
use super::{Attribute, DocumentData, ElementData, LayoutData};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DisplayOuter {
Block,
Inline,
None,
}
bitflags! {
#[derive(Clone, Copy, PartialEq)]
pub struct NodeFlags: u32 {
/// Whether the node is the root node of an Inline Formatting Context
const IS_INLINE_ROOT = 0b00000001;
/// Whether the node is the root node of an Table formatting context
const IS_TABLE_ROOT = 0b00000010;
/// Whether the node is "in the document" (~= has a parent and isn't a template node)
const IS_IN_DOCUMENT = 0b00000100;
}
}
impl NodeFlags {
#[inline(always)]
pub fn is_inline_root(&self) -> bool {
self.contains(Self::IS_INLINE_ROOT)
}
#[inline(always)]
pub fn is_table_root(&self) -> bool {
self.contains(Self::IS_TABLE_ROOT)
}
#[inline(always)]
pub fn is_in_document(&self) -> bool {
self.contains(Self::IS_IN_DOCUMENT)
}
#[inline(always)]
pub fn reset_construction_flags(&mut self) {
self.remove(Self::IS_INLINE_ROOT);
self.remove(Self::IS_TABLE_ROOT);
}
}
pub struct Node {
// The actual tree we belong to. This is unsafe!!
tree: *mut crate::NodeTree,
/// Our Id
pub id: NodeId,
/// Our parent's ID
pub parent: Option<NodeId>,
// What are our children?
pub children: ThinVec<NodeId>,
/// Our parent in the layout hierachy: a separate list that includes anonymous collections of inline elements
pub layout_parent: Cell<Option<NodeId>>,
/// A separate child list that includes anonymous collections of inline elements
pub layout_children: RefCell<Option<ThinVec<NodeId>>>,
/// Out-of-flow (absolutely/fixed positioned) boxes for which this node is the
/// containing block. Recorded by Taffy's out-of-flow positioning pass. The
/// `Layout.location` of these boxes is relative to this node's border box.
pub hoisted_children: RefCell<ThinVec<NodeId>>,
/// For an out-of-flow box that was hoisted by Taffy's out-of-flow positioning
/// pass, the node whose `hoisted_children` list contains it (its containing
/// block). The box's `Layout.location` is relative to this node rather than
/// to its `layout_parent`. `None` for in-flow boxes.
pub oof_containing_block: Cell<Option<NodeId>>,
/// Anonymous block boxes created for this node during layout construction.
///
/// Anonymous blocks live only in the slab (they are not part of the DOM
/// `children` list), so we track the ones we own here to be able to
/// deallocate them when this node is reconstructed.
pub anonymous_blocks: ThinVec<NodeId>,
/// The same as layout_children, but sorted by z-index
pub paint_children: RefCell<Option<ThinVec<NodeId>>>,
pub stacking_context: Option<Box<StackingContext>>,
/// The hoisted entries this node's subtree pushed into the enclosing
/// stacking context on its last (non-skipped) paint-tree build. Replayed
/// when the subtree is skipped as clean. Empty for stacking-context roots.
pub sc_contribution_cache: RefCell<ThinVec<HoistedPaintChild>>,
// Flags
pub flags: NodeFlags,
/// Node type (Element, TextNode, etc) specific data.
///
/// For element nodes this holds the [`ElementData`], which stores most of
/// the per-node style/layout state. For the document node it holds the
/// [`DocumentData`]. Access the moved fields through the forwarding methods
/// on [`Node`] (e.g. [`Node::style`], [`Node::final_layout`]).
pub data: NodeData,
}
unsafe impl Send for Node {}
unsafe impl Sync for Node {}
/// Generates forwarding accessors for fields that live on both [`ElementData`]
/// (element / anonymous block nodes) and [`DocumentData`] (the document node).
macro_rules! universal_accessors {
($($(#[$meta:meta])* $field:ident / $field_mut:ident : $ty:ty),* $(,)?) => {
impl Node {
$(
$(#[$meta])*
#[inline]
pub fn $field(&self) -> &$ty {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => &data.$field,
NodeData::Document(data) => &data.$field,
_ => panic!(concat!("`", stringify!($field), "` is not available on this node kind")),
}
}
$(#[$meta])*
#[inline]
pub fn $field_mut(&mut self) -> &mut $ty {
match &mut self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => &mut data.$field,
NodeData::Document(data) => &mut data.$field,
_ => panic!(concat!("`", stringify!($field), "` is not available on this node kind")),
}
}
)*
}
};
}
universal_accessors! {
stylo_element_data / stylo_element_data_mut: StyloData,
transform / transform_mut: Option<Box<Affine>>,
display_constructed_as / display_constructed_as_mut: StyloDisplay,
// The document node is styled/snapshotted like an element, so it also
// carries these:
element_state / element_state_mut: ElementState,
snapshot_handled / snapshot_handled_mut: AtomicBool,
// `apply_selector_flags` deposits `for_parent()` flags on the parent node,
// and the parent of the root <html> element is the document -- so the
// document has to be able to hold selector flags too.
selector_flags / selector_flags_mut: Cell<ElementSelectorFlags>,
}
impl Node {
/// This node's layout output state, or a shared default if layout has
/// never written to this node.
///
/// Panics for node kinds which do not participate in layout (text and
/// comment nodes).
#[inline]
pub fn layout_data(&self) -> &LayoutData {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.layout_data(),
NodeData::Document(data) => data.layout_data(),
_ => panic!("`layout_data` is not available on this node kind"),
}
}
/// Mutable access to this node's layout output state, allocating it if it
/// does not yet exist.
///
/// Panics for node kinds which do not participate in layout (text and
/// comment nodes).
#[inline]
pub fn layout_data_mut(&mut self) -> &mut LayoutData {
match &mut self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.layout_data_mut(),
NodeData::Document(data) => data.layout_data_mut(),
_ => panic!("`layout_data` is not available on this node kind"),
}
}
/// Mutable access to this node's layout output state, if it has been
/// allocated. Never allocates. Returns `None` for node kinds which do not
/// participate in layout.
#[inline]
pub fn try_layout_data_mut(&mut self) -> Option<&mut LayoutData> {
match &mut self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
data.layout_data.as_deref_mut()
}
NodeData::Document(data) => data.layout_data.as_deref_mut(),
_ => None,
}
}
/// Clear this node's taffy layout cache without allocating `LayoutData`
/// for nodes that have never been laid out.
#[inline]
pub fn clear_layout_cache(&mut self) {
if let Some(layout_data) = self.try_layout_data_mut() {
layout_data.cache.clear();
}
}
/// Clear this node's taffy layout cache and any cached inline
/// `content_widths`, forcing a full relayout of it on the next pass.
pub fn invalidate_layout_cache(&mut self) {
self.clear_layout_cache();
if let Some(inline_layout) = self
.data
.downcast_element_mut()
.and_then(|el| el.inline_layout_data.as_mut())
{
inline_layout.content_widths = None;
}
}
#[inline]
pub fn cache(&self) -> &Cache {
&self.layout_data().cache
}
#[inline]
pub fn cache_mut(&mut self) -> &mut Cache {
&mut self.layout_data_mut().cache
}
#[inline]
pub fn unrounded_layout(&self) -> &Layout {
&self.layout_data().unrounded_layout
}
#[inline]
pub fn unrounded_layout_mut(&mut self) -> &mut Layout {
&mut self.layout_data_mut().unrounded_layout
}
#[inline]
pub fn final_layout(&self) -> &Layout {
&self.layout_data().final_layout
}
#[inline]
pub fn final_layout_mut(&mut self) -> &mut Layout {
&mut self.layout_data_mut().final_layout
}
#[inline]
pub fn scroll_offset(&self) -> &crate::Point<f64> {
&self.layout_data().scroll_offset
}
#[inline]
pub fn scroll_offset_mut(&mut self) -> &mut crate::Point<f64> {
&mut self.layout_data_mut().scroll_offset
}
#[inline]
pub fn scrollable_overflow(&self) -> &KurboRect {
&self.layout_data().scrollable_overflow
}
#[inline]
pub fn scrollable_overflow_mut(&mut self) -> &mut KurboRect {
&mut self.layout_data_mut().scrollable_overflow
}
/// Style data from stylo, if this node kind carries it (element or document
/// nodes). Returns `None` for text/comment nodes.
#[inline]
pub fn try_stylo_element_data(&self) -> Option<&StyloData> {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
Some(&data.stylo_element_data)
}
NodeData::Document(data) => Some(&data.stylo_element_data),
_ => None,
}
}
#[inline]
pub fn try_stylo_element_data_mut(&mut self) -> Option<&mut StyloData> {
match &mut self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
Some(&mut data.stylo_element_data)
}
NodeData::Document(data) => Some(&mut data.stylo_element_data),
_ => None,
}
}
/// The `dirty_descendants` flag, if this node kind carries it (element or
/// document nodes). Returns `None` for text/comment nodes.
#[inline]
fn dirty_descendants_flag(&self) -> Option<&AtomicBool> {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
Some(&data.dirty_descendants)
}
NodeData::Document(data) => Some(&data.dirty_descendants),
_ => None,
}
}
/// The `damaged_descendants` flag, if this node kind carries it (element or
/// document nodes). Returns `None` for text/comment nodes.
#[inline]
fn damaged_descendants_flag(&self) -> Option<&AtomicBool> {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
Some(&data.damaged_descendants)
}
NodeData::Document(data) => Some(&data.damaged_descendants),
_ => None,
}
}
/// The document's shared style lock. Only available on element and
/// document nodes.
#[inline]
pub fn guard(&self) -> &SharedRwLock {
let guard = match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.guard.as_ref(),
NodeData::Document(data) => data.guard.as_ref(),
_ => None,
};
guard.expect("`guard` is not available on this node kind")
}
#[inline]
pub fn has_snapshot(&self) -> bool {
match &self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.has_snapshot,
NodeData::Document(data) => data.has_snapshot,
_ => false,
}
}
#[inline]
pub fn set_has_snapshot(&mut self, value: bool) {
match &mut self.data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => data.has_snapshot = value,
NodeData::Document(data) => data.has_snapshot = value,
_ => {}
}
}
#[inline]
pub fn before(&self) -> Option<NodeId> {
self.element_data().and_then(|data| data.before)
}
#[inline]
pub fn after(&self) -> Option<NodeId> {
self.element_data().and_then(|data| data.after)
}
}
impl Node {
pub(crate) fn new(
tree: *mut crate::NodeTree,
id: NodeId,
guard: SharedRwLock,
mut data: NodeData,
) -> Self {
// Store a handle to the document's shared style lock on the node data.
// Both element and document nodes are styled by stylo and so need it.
match &mut data {
NodeData::Element(data) | NodeData::AnonymousBlock(data) => {
data.guard = Some(guard);
}
NodeData::Document(data) => data.guard = Some(guard),
_ => {}
}
Self {
tree,
id,
parent: None,
children: ThinVec::new(),
layout_parent: Cell::new(None),
oof_containing_block: Cell::new(None),
layout_children: RefCell::new(None),
hoisted_children: RefCell::new(ThinVec::new()),
anonymous_blocks: ThinVec::new(),
paint_children: RefCell::new(None),
stacking_context: None,
sc_contribution_cache: RefCell::new(ThinVec::new()),
flags: NodeFlags::empty(),
data,
}
}
/// raea: the transform in 3D (docs/blitz-bevy.feature B3 H5), seen through the containing block's `perspective`
/// and, inside a 3D rendering context, after `context` (its parent's matrix from the context root's parent):
/// flattened onto the page, an affine where it is one (`transform`), else a projective layer, and whether the
/// element faces away (the Projection). The third is the matrix its children's context continues from, when it is
/// `transform-style: preserve-3d`.
pub fn set_transform(
&mut self,
scale: f32,
perspective: Option<&crate::stylo_to_kurbo::Mat4>,
context: Option<&crate::stylo_to_kurbo::Mat4>,
) -> (Option<Affine>, Option<crate::stylo_to_kurbo::Projection>, Option<crate::stylo_to_kurbo::Mat4>) {
use crate::stylo_to_kurbo::{IDENTITY4, Projection, det3, det4, mul4, project, translate4};
let mut projection = None;
let mut children = None;
let mut root = None;
// raea: a participant with no transform of its own that is static, shows its back and makes no stacking context
// isn't a plane of the 3D context: its content paints in its parent's plane, in that stacking context's phases
// (Appendix E), as Chrome draws it (preserve3d-and-flattening-z-order-005: a later sibling's block background
// goes under an earlier one's inline content). A positioned one keeps its plane, sorted in paint order
// (z-order-003), as does a hidden back face (transform3d-backface-visibility-006)
let flat_participant = context.is_some()
&& self.primary_styles().is_some_and(|s| {
s.clone_position() == style::computed_values::position::T::Static
&& s.clone_z_index().is_auto()
&& s.get_box().backface_visibility == style::computed_values::backface_visibility::T::Visible
&& !crate::stylo_to_kurbo::preserves_3d(&s)
})
&& !self.is_stacking_context_root(false);
let transform = self.primary_styles().and_then(|s| {
let layout = self.final_layout();
let size = layout.size;
let reference_box = Rect::new(
Point2D::new(CSSPixelLength::new(0.0), CSSPixelLength::new(0.0)),
Size2D::new(
CSSPixelLength::new(size.width),
CSSPixelLength::new(size.height),
),
);
let own = crate::stylo_to_kurbo::resolve_3d_transform(s.get_box(), reference_box);
let preserve = crate::stylo_to_kurbo::preserves_3d(&s);
if own.is_none() && (context.is_none() || flat_participant) && !preserve {
return None;
}
// in the parent's space, seen through its perspective (which acts after the box's offset), then from the
// 3D context's root's parent
let (lx, ly) = (layout.location.x as f64, layout.location.y as f64);
let placed = mul4(&translate4(lx, ly, 0.0), &own.unwrap_or(IDENTITY4));
let mut full = perspective.map_or(placed, |p| mul4(p, &placed));
if let Some(c) = context {
full = mul4(c, &full);
}
if preserve {
children = Some(full);
// an element starting a 3D rendering context is a plane of it too (css-transforms-2 §6: it establishes
// and participates in the context): its corners in its parent's space, as its planes' are, so the
// painter splits and sorts it with them
if context.is_none() {
let (cx, cy) = (layout.size.width as f64 / 2.0, layout.size.height as f64 / 2.0);
let (z, w) = (full[2][0] * cx + full[2][1] * cy + full[2][3], full[3][0] * cx + full[3][1] * cy + full[3][3]);
let depth = if w > 1e-9 { z / w } else { z };
root = quad_of(&full, layout.size.width as f64, layout.size.height as f64).map(|q| (depth, q));
}
}
if own.is_none() && context.is_none() {
return None;
}
let h = project(&full);
let d4 = det4(&full);
let (cx, cy) = (size.width as f64 / 2.0, size.height as f64 / 2.0);
let (z, w) = (full[2][0] * cx + full[2][1] * cy + full[2][3], full[3][0] * cx + full[3][1] * cy + full[3][3]);
let depth = if w > 1e-9 { z / w } else { z };
let back_facing = d4 != 0.0 && det3(&h) / d4 < 0.0;
let scale = scale as f64;
let affine = h[6].abs() < 1e-12 && h[7].abs() < 1e-12 && h[8] > 0.0;
// Resolved in CSS pixels, then put in device-pixel space (S * T * S^-1): translation components are scaled,
// linear components are not.
let flat = |h: &[f64; 9]| {
let w = h[8];
Affine::new([h[0] / w, h[3] / w, h[1] / w, h[4] / w, h[2] / w * scale, h[5] / w * scale])
};
// S * H * S^-1 with S = diag(scale, scale, 1)
let device = |h: &[f64; 9]| [h[0], h[1], h[2] * scale, h[3], h[4], h[5] * scale, h[6] / scale, h[7] / scale, h[8]];
if context.is_some() {
let quad = quad_of(&full, size.width as f64, size.height as f64);
projection = Some(Projection { h: (!affine).then(|| device(&h)), back_facing, in_context: true, context: affine.then(|| flat(&h)), depth, quad });
return None;
}
// the offset taken back out (T(-loc) on the page: x and y less w times it): the painter places the box first
let h = [h[0] - lx * h[6], h[1] - lx * h[7], h[2] - lx * h[8], h[3] - ly * h[6], h[4] - ly * h[7], h[5] - ly * h[8], h[6], h[7], h[8]];
if affine {
if back_facing {
projection = Some(Projection { h: None, back_facing, in_context: false, context: None, depth, quad: None });
}
let t = flat(&h);
(t != Affine::IDENTITY).then_some(t)
} else {
projection = Some(Projection { h: Some(device(&h)), back_facing, in_context: false, context: None, depth, quad: None });
None
}
});
if let Some((depth, quad)) = root {
let p = projection.get_or_insert(Projection { h: None, back_facing: false, in_context: false, context: None, depth, quad: None });
p.quad = Some(quad);
}
let slot = self.transform_mut();
match (slot.as_deref_mut(), transform) {
(Some(existing), Some(new)) => *existing = new,
(None, Some(new)) => *slot = Some(Box::new(new)),
(_, None) => *slot = None,
}
(transform, projection, children)
}
pub fn pe_by_index(&self, index: usize) -> Option<NodeId> {
match index {
0 => self.after(),
1 => self.before(),
_ => panic!("Invalid pseudo element index"),
}
}
pub fn set_pe_by_index(&mut self, index: usize, value: Option<NodeId>) {
let Some(data) = self.element_data_mut() else {
return;
};
match index {
0 => data.after = value,
1 => data.before = value,
_ => panic!("Invalid pseudo element index"),
}
}
pub(crate) fn display_style(&self) -> Option<StyloDisplay> {
let display = self.primary_styles().as_ref()?.clone_display();
Some(
if self.element_data().is_some_and(|el| el.is_button_input()) {
stylo_taffy::convert::button_input_display(display)
} else {
display
},
)
}
pub fn is_or_contains_block(&self) -> bool {
let style = self.primary_styles();
let style = style.as_ref();
// Ignore out-of-flow items
let position = style
.map(|s| s.clone_position())
.unwrap_or(Position::Relative);
let is_in_flow = matches!(
position,
Position::Static | Position::Relative | Position::Sticky
);
if !is_in_flow {
return false;
}
// Floated boxes do not break up the inline flow: they participate in the
// inline formatting context as out-of-flow inline boxes
let is_floating = style
.map(|s| s.clone_float().is_floating())
.unwrap_or(false);
if is_floating {
return false;
}
let display = self.display_style().unwrap_or(StyloDisplay::inline());
match display.outside() {
DisplayOutside::None => false,
DisplayOutside::Block => true,
_ => {
if display.inside() == DisplayInside::Flow {
self.children
.iter()
.copied()
.any(|child_id| self.tree()[child_id].is_or_contains_block())
} else {
false
}
}
}
}
pub fn is_whitespace_node(&self) -> bool {
match &self.data {
NodeData::Text(data) => data.content.chars().all(|c| c.is_ascii_whitespace()),
_ => false,
}
}
/// Whether this is an empty or whitespace-only text node whose whitespace may be collapsed
/// away under the `white-space-collapse` it inherits from its parent.
pub fn is_collapsible_whitespace_node(&self) -> bool {
let NodeData::Text(data) = &self.data else {
return false;
};
if data.content.is_empty() {
return true;
}
if !data.content.chars().all(|c| c.is_ascii_whitespace()) {
return false;
}
let white_space_collapse = self
.parent
.and_then(|parent_id| self.with(parent_id).primary_styles())
.map(|style| style.clone_white_space_collapse());
match white_space_collapse {
Some(WhiteSpaceCollapse::Preserve | WhiteSpaceCollapse::BreakSpaces) => false,
Some(WhiteSpaceCollapse::PreserveBreaks) => !data.content.contains('\n'),
Some(WhiteSpaceCollapse::Collapse) | None => true,
}
}
pub fn is_focussable(&self) -> bool {
self.data
.downcast_element()
.map(|el| el.is_focussable)
.unwrap_or(false)
}
pub fn set_restyle_hint(&mut self, hint: RestyleHint) {
if let Some(stylo_element_data) = self.try_stylo_element_data_mut() {
if let Some(mut element_data) = stylo_element_data.get_mut() {
element_data.hint.insert(hint);
}
}
// Mark all ancestors as having dirty descendants so the style traversal
// will visit this node's subtree
self.mark_ancestors_dirty();
}
/// Returns whether this node has any descendants that need restyling.
pub fn has_dirty_descendants(&self) -> bool {
self.dirty_descendants_flag()
.is_some_and(|flag| flag.load(Ordering::Relaxed))
}
/// Sets the dirty_descendants flag on this node.
pub fn set_dirty_descendants(&self) {
if let Some(flag) = self.dirty_descendants_flag() {
flag.store(true, Ordering::Relaxed);
}
}
/// Clears the dirty_descendants flag on this node.
pub fn unset_dirty_descendants(&self) {
if let Some(flag) = self.dirty_descendants_flag() {
flag.store(false, Ordering::Relaxed);
}
}
/// Marks all ancestors of this node as having dirty descendants.
/// This propagates the dirty flag up the tree so that the style traversal
/// knows to visit the subtree containing this node.
pub fn mark_ancestors_dirty(&self) {
let mut current_id = self.parent;
while let Some(parent_id) = current_id {
let parent = &self.tree()[parent_id];
// If this ancestor already has dirty_descendants set, we can stop
// because all further ancestors must also have it set
if let Some(flag) = parent.dirty_descendants_flag() {
if flag.swap(true, Ordering::Relaxed) {
break;
}
}
current_id = parent.parent;
}
}
/// Returns whether this node or any of its descendants may carry damage.
pub fn has_damaged_descendants(&self) -> bool {
self.damaged_descendants_flag()
.is_some_and(|flag| flag.load(Ordering::Relaxed))
}
/// Clears the damaged_descendants flag on this node.
pub fn unset_damaged_descendants(&self) {
if let Some(flag) = self.damaged_descendants_flag() {
flag.store(false, Ordering::Relaxed);
}
}
/// Marks this node and all of its ancestors as (potentially) carrying
/// damage, so that the damage propagation pass visits this node's subtree.
///
/// The invariant is: if a node carries damage (or needs damage-phase
/// processing such as pseudo-element style syncing), then it and all of
/// its ancestors have `damaged_descendants` set.
pub fn mark_damaged(&self) {
if let Some(flag) = self.damaged_descendants_flag() {
if flag.swap(true, Ordering::Relaxed) {
return;
}
}
let mut current_id = self.parent;
while let Some(parent_id) = current_id {
let parent = &self.tree()[parent_id];
// If this ancestor already has damaged_descendants set, we can stop
// because all further ancestors must also have it set
if let Some(flag) = parent.damaged_descendants_flag() {
if flag.swap(true, Ordering::Relaxed) {
break;
}
}
current_id = parent.parent;
}
}
// pub fn damage_mut(&mut self) -> Option<&mut RestyleDamage> {
// self.stylo_element_data
// .get_mut()
// .map(|mut data: ElementDataMut<'a>| &'a mut data.damage)
// }
pub fn damage(&self) -> Option<RestyleDamage> {
self.try_stylo_element_data()
.and_then(|stylo| stylo.get().map(|data| data.damage))
}
pub fn set_damage(&mut self, damage: RestyleDamage) {
if let Some(stylo) = self.try_stylo_element_data_mut() {
if let Some(mut data) = stylo.get_mut() {
data.damage = damage;
}
}
}
pub fn insert_damage(&mut self, damage: RestyleDamage) {
if let Some(stylo) = self.try_stylo_element_data_mut() {
if let Some(mut data) = stylo.get_mut() {
data.damage |= damage;
}
}
if !damage.is_empty() {
self.mark_damaged();
}
}
pub fn remove_damage(&mut self, damage: RestyleDamage) {
if let Some(stylo) = self.try_stylo_element_data_mut() {
if let Some(mut data) = stylo.get_mut() {
data.damage.remove(damage);
}
}
}
pub fn clear_damage_mut(&mut self) {
if let Some(stylo) = self.try_stylo_element_data_mut() {
if let Some(mut data) = stylo.get_mut() {
data.damage = RestyleDamage::empty();
}
}
}
// State changes (hover/focus/active/disabled) do not set a restyle hint.
// Invalidation is driven by element snapshots: the style traversal diffs the
// snapshotted (pre-change) state against the current state and invalidates
// only the elements matched by selectors that depend on the changed state
// bits. Ancestors are marked dirty so the traversal reaches this node.
pub fn hover(&mut self) {
if let Some(data) = self.element_data_mut() {
data.element_state.insert(ElementState::HOVER);
}
self.mark_ancestors_dirty();
}
pub fn unhover(&mut self) {
if let Some(data) = self.element_data_mut() {
data.element_state.remove(ElementState::HOVER);
}
self.mark_ancestors_dirty();
}
pub fn is_hovered(&self) -> bool {
self.element_data()
.is_some_and(|data| data.element_state.contains(ElementState::HOVER))
}
pub fn focus(&mut self, shell_provider: Arc<dyn ShellProvider>) {
if let Some(data) = self.element_data_mut() {
data.element_state
.insert(ElementState::FOCUS | ElementState::FOCUSRING);
}
self.mark_ancestors_dirty();
// If focussing a text input, enable IME and set IME area
if self
.element_data()
.and_then(|elem| elem.text_input_data())
.is_some()
{
shell_provider.set_ime_enabled(true);
let mut pos = self.absolute_position(0.0, 0.0);
pos.x += self.final_layout().content_box_x();
pos.y += self.final_layout().content_box_y();
let width = self.final_layout().content_box_width();
let height = self.final_layout().content_box_height();
shell_provider.set_ime_cursor_area(pos.x, pos.y, width, height);
}
}
pub fn blur(&mut self, shell_provider: Arc<dyn ShellProvider>) {
if let Some(data) = self.element_data_mut() {
data.element_state
.remove(ElementState::FOCUS | ElementState::FOCUSRING);
}
self.mark_ancestors_dirty();
// If blurring a text input, disable IME
if self
.element_data()
.and_then(|elem| elem.text_input_data())
.is_some()
{
shell_provider.set_ime_enabled(false);
}
}
pub fn is_focussed(&self) -> bool {
self.element_data()
.is_some_and(|data| data.element_state.contains(ElementState::FOCUS))
}
pub fn active(&mut self) {
if let Some(data) = self.element_data_mut() {
data.element_state.insert(ElementState::ACTIVE);
}
self.mark_ancestors_dirty();
}
pub fn unactive(&mut self) {
if let Some(data) = self.element_data_mut() {
data.element_state.remove(ElementState::ACTIVE);
}
self.mark_ancestors_dirty();
}
pub fn is_active(&self) -> bool {
self.element_data()
.is_some_and(|data| data.element_state.contains(ElementState::ACTIVE))
}
// Marks the node as disabled if it can be.
// It does not disable any children which should be disabled as well (relevant for the `select` element).
pub fn disable(&mut self) {
if let Some(data) = self.element_data_mut() {
if data.can_be_disabled() {
data.element_state.insert(ElementState::DISABLED);
data.element_state.remove(ElementState::ENABLED);
}
}
self.mark_ancestors_dirty();
}
// Marks the node as enabled if it can be.
// It does not enable any children which should be enabled as well (relevant for the `select` element).
pub fn enable(&mut self) {
if let Some(data) = self.element_data_mut() {
if data.can_be_disabled() {
data.element_state.insert(ElementState::ENABLED);
data.element_state.remove(ElementState::DISABLED);
}
}
self.mark_ancestors_dirty();
}
pub fn subdoc(&self) -> Option<&dyn Document> {
self.element_data().and_then(|el| el.sub_doc_data())
}
pub fn subdoc_mut(&mut self) -> Option<&mut dyn Document> {
self.element_data_mut().and_then(|el| el.sub_doc_data_mut())
}
/// raea: how many characters a text field's maxlength lets in now (what's selected is replaced), or None when it
/// has no maxlength
pub fn text_input_room(&self) -> Option<usize> {
let el = self.element_data()?;
let max: usize = el.attr(local_name!("maxlength"))?.trim().parse().ok()?;
let input = el.text_input_data()?;
let text = input.editor.raw_text();
let len = text.chars().count();
let sel = input.editor.raw_selection().text_range();
let selected = text.get(sel).map_or(0, |s| s.chars().count());
Some(max.saturating_sub(len - selected))
}
pub fn text_input_v_centering_offset(&self, scale: f64) -> f64 {
// For single-line inputs, add an offset to vertically center the text input layout
// within the content box of it's node.
if let Some(input_data) = self
.data
.downcast_element()
.and_then(|el| el.text_input_data())
{
if !input_data.is_multiline {
let content_box_height = self.final_layout().content_box_height();
let input_height = input_data.editor.try_layout().unwrap().height() / scale as f32;
let y_offset = ((content_box_height - input_height) / 2.0).max(0.0);
return y_offset as f64;
}
}
0.0
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum NodeKind {
Document,
Element,
AnonymousBlock,
Text,
Comment,
}
/// The different kinds of nodes in the DOM.
#[derive(Debug, Clone)]
pub enum NodeData {
/// The `Document` itself - the root node of a HTML document.
Document(Box<DocumentData>),
/// An element with attributes.
Element(Box<ElementData>),
/// An anonymous block box
AnonymousBlock(Box<ElementData>),
/// A text node.
Text(TextNodeData),
/// A comment.
Comment {
/// The textual content of the comment
contents: String,
},
// /// A `DOCTYPE` with name, public id, and system id. See
// /// [document type declaration on wikipedia][https://en.wikipedia.org/wiki/Document_type_declaration]
// Doctype { name: String, public_id: String, system_id: String },
// /// A Processing instruction.
// ProcessingInstruction { target: String, contents: String },
}
impl NodeData {
pub fn downcast_element(&self) -> Option<&ElementData> {
match self {
Self::Element(data) => Some(data),
Self::AnonymousBlock(data) => Some(data),
_ => None,
}
}
pub fn downcast_element_mut(&mut self) -> Option<&mut ElementData> {
match self {
Self::Element(data) => Some(data),
Self::AnonymousBlock(data) => Some(data),
_ => None,
}
}
pub fn is_element_with_tag_name(&self, name: &impl PartialEq<LocalName>) -> bool {
let Some(elem) = self.downcast_element() else {
return false;
};
*name == elem.name.local
}
pub fn attrs(&self) -> Option<&[Attribute]> {
Some(&self.downcast_element()?.attrs)
}
pub fn attr(&self, name: impl PartialEq<LocalName>) -> Option<&str> {
self.downcast_element()?.attr(name)
}
/// raea: a bevy_ui <Text>'s block (sdk/render's `data-raea-bevy-text`): laid out, filled and drawn as bevy_text
/// does (its size in whole pixels, a run's box over the line box)
pub fn is_bevy_text(&self) -> bool {
self.attr(LocalName::from("data-raea-bevy-text")).is_some()
}
/// raea: a bevy_ui GlobalZIndex (sdk/render's `global_z_index`): its z-index ranks it in the root's stacking context
pub fn is_bevy_global_z(&self) -> bool {
self.attr(LocalName::from("data-raea-bevy-global-z")).is_some()
}
/// raea: a bevy_ui IgnoreScroll (sdk/render's `ignore_scroll`, `data-raea-bevy-ignore-scroll` "x", "y" or "xy"):
/// the axes on which it keeps its place while its parent scrolls
pub fn bevy_ignore_scroll(&self) -> Option<(bool, bool)> {
let v = self.attr(LocalName::from("data-raea-bevy-ignore-scroll"))?;
Some((v.contains('x'), v.contains('y')))
}
/// raea: a bevy_ui scroller (sdk/render's `scroll_position`, `data-raea-bevy-scroll`): its physical px per CSS px,
/// to which bevy_ui floors its scroll offset
pub fn bevy_scroll_scale(&self) -> Option<f64> {
self.attr(LocalName::from("data-raea-bevy-scroll"))?.split(' ').next()?.parse().ok().filter(|s: &f64| *s > 0.0)
}
/// raea: the ScrollPosition a bevy_ui scroller was given (`data-raea-bevy-scroll` "scale x y", CSS px), unclamped
pub fn bevy_scroll_asked(&self) -> Option<(f32, f32)> {
let mut it = self.attr(LocalName::from("data-raea-bevy-scroll"))?.split(' ').skip(1).map(|v| v.parse().ok());
Some((it.next()??, it.next()??))
}
pub fn has_attr(&self, name: impl PartialEq<LocalName>) -> bool {
self.downcast_element()
.is_some_and(|elem| elem.has_attr(name))
}
pub fn kind(&self) -> NodeKind {
match self {
NodeData::Document(_) => NodeKind::Document,
NodeData::Element(_) => NodeKind::Element,
NodeData::AnonymousBlock(_) => NodeKind::AnonymousBlock,
NodeData::Text(_) => NodeKind::Text,
NodeData::Comment { .. } => NodeKind::Comment,
}
}
}
#[derive(Debug, Clone)]
pub struct TextNodeData {
/// The textual content of the text node
pub content: String,
}
impl TextNodeData {
pub fn new(content: String) -> Self {
Self { content }
}
}
/*
-> Computed styles
-> Layout
-----> Needs to happen only when styles are computed
*/
// type DomRefCell<T> = RefCell<T>;
// pub struct DomData {
// // ... we can probs just get away with using the html5ever types directly. basically just using the servo dom, but without the bindings
// local_name: html5ever::LocalName,
// tag_name: html5ever::QualName,
// namespace: html5ever::Namespace,
// prefix: DomRefCell<Option<html5ever::Prefix>>,
// attrs: DomRefCell<Vec<Attr>>,
// // attrs: DomRefCell<Vec<Dom<Attr>>>,
// id_attribute: DomRefCell<Option<Atom>>,
// is: DomRefCell<Option<LocalName>>,
// // style_attribute: DomRefCell<Option<Arc<Locked<PropertyDeclarationBlock>>>>,
// // attr_list: MutNullableDom<NamedNodeMap>,
// // class_list: MutNullableDom<DOMTokenList>,
// state: Cell<ElementState>,
// }
impl Node {
/// raea: this node is a bevy_ui <Text>'s block (NodeData::is_bevy_text)
pub fn is_bevy_text(&self) -> bool {
self.data.is_bevy_text()
}
pub fn is_bevy_global_z(&self) -> bool {
self.data.is_bevy_global_z()
}
/// raea: NodeData::bevy_ignore_scroll
pub fn bevy_ignore_scroll(&self) -> Option<(bool, bool)> {
self.data.bevy_ignore_scroll()
}
/// raea: NodeData::bevy_scroll_scale
pub fn bevy_scroll_scale(&self) -> Option<f64> {
self.data.bevy_scroll_scale()
}
/// raea: NodeData::bevy_scroll_asked
pub fn bevy_scroll_asked(&self) -> Option<(f32, f32)> {
self.data.bevy_scroll_asked()
}
pub fn tree(&self) -> &crate::NodeTree {
unsafe { &*self.tree }
}
#[track_caller]
pub fn with(&self, id: NodeId) -> &Node {
self.tree().get(id).unwrap()
}
pub fn print_tree(&self, level: usize) {
println!(
"{} {} {:?} {} {:?}",
" ".repeat(level),
self.id,
self.parent,
self.node_debug_str().replace('\n', ""),
self.children
);
// println!("{} {:?}", " ".repeat(level), self.children);
for child_id in self.children.iter() {
let child = self.with(*child_id);
child.print_tree(level + 1)
}
}
// Get the index of the current node in the parents child list
pub fn index_of_child(&self, child_id: NodeId) -> Option<usize> {
self.children.iter().position(|id| *id == child_id)
}
// Get the index of the current node in the parents child list
pub fn child_index(&self) -> Option<usize> {
self.tree()[self.parent?]
.children
.iter()
.position(|id| *id == self.id)
}
// Get the nth node in the parents child list
pub fn forward(&self, n: usize) -> Option<&Node> {
let child_idx = self.child_index().unwrap_or(0);
self.tree()[self.parent?]
.children
.get(child_idx + n)
.map(|id| self.with(*id))
}
pub fn backward(&self, n: usize) -> Option<&Node> {
let child_idx = self.child_index().unwrap_or(0);
if child_idx < n {
return None;
}
self.tree()[self.parent?]
.children
.get(child_idx - n)
.map(|id| self.with(*id))
}
pub fn is_element(&self) -> bool {
matches!(self.data, NodeData::Element { .. })
}
pub fn is_anonymous(&self) -> bool {
matches!(self.data, NodeData::AnonymousBlock { .. })
}
pub fn is_text_node(&self) -> bool {
matches!(self.data, NodeData::Text { .. })
}
pub fn element_data(&self) -> Option<&ElementData> {
match self.data {
NodeData::Element(ref data) => Some(data),
NodeData::AnonymousBlock(ref data) => Some(data),
_ => None,
}
}
pub fn element_data_mut(&mut self) -> Option<&mut ElementData> {
match self.data {
NodeData::Element(ref mut data) => Some(data),
NodeData::AnonymousBlock(ref mut data) => Some(data),
_ => None,
}
}
pub fn text_data(&self) -> Option<&TextNodeData> {
match self.data {
NodeData::Text(ref data) => Some(data),
_ => None,
}
}
pub fn text_data_mut(&mut self) -> Option<&mut TextNodeData> {
match self.data {
NodeData::Text(ref mut data) => Some(data),
_ => None,
}
}
pub fn node_debug_str(&self) -> String {
let mut s = String::new();
match &self.data {
NodeData::Document(_) => write!(s, "DOCUMENT"),
// NodeData::Doctype { name, .. } => write!(s, "DOCTYPE {name}"),
NodeData::Text(data) => {
let bytes = data.content.as_bytes();
write!(
s,
"TEXT {}",
std::str::from_utf8(bytes.split_at(10.min(bytes.len())).0)
.unwrap_or("INVALID UTF8")
)
}
NodeData::Comment { .. } => write!(s, "COMMENT"),
NodeData::AnonymousBlock(_) => write!(s, "AnonymousBlock"),
NodeData::Element(data) => {
let name = &data.name;
let class = self.attr(local_name!("class")).unwrap_or("");
let id = self.attr(local_name!("id")).unwrap_or("");
let display = self.display_constructed_as().to_css_string();
write!(s, "<{}", name.local).unwrap();
if !id.is_empty() {
write!(s, " #{id}").unwrap();
}
if !class.is_empty() {
if class.contains(' ') {
write!(s, " class=\"{class}\"").unwrap()
} else {
write!(s, " .{class}").unwrap()
}
}
write!(s, "> ({display})")
} // NodeData::ProcessingInstruction { .. } => write!(s, "ProcessingInstruction"),
}
.unwrap();
s
}
pub fn attrs(&self) -> Option<&[Attribute]> {
Some(&self.element_data()?.attrs)
}
pub fn attr(&self, name: LocalName) -> Option<&str> {
let attr = self.attrs()?.iter().find(|id| id.name.local == name)?;
Some(&attr.value)
}
pub fn primary_styles(&self) -> Option<impl Deref<Target = ServoArc<ComputedValues>>> {
self.try_stylo_element_data()
.and_then(|stylo| stylo.primary_styles())
}
/// A lazy Taffy style backed by this node's primary stylo style.
///
/// Panics if the node has no computed styles: layout always runs after
/// styling, and the only unstyled nodes (text, comments, descendants of
/// `display: none`) are never queried by Taffy.
pub fn layout_style(&self) -> stylo_taffy::TaffyStyloStyle<ComputedStyleRef<'_>> {
let styles = self
.try_stylo_element_data()
.and_then(|stylo| stylo.computed_styles())
.expect("layout_style() called on a node without computed styles");
let mut flags = stylo_taffy::StyleFlags::empty();
if let Some(el) = self.data.downcast_element() {
// raea: form controls too, which CSS Sizing counts as compressible replaced elements: a `display: block`
// button or input is as wide as its content, as in Chrome, not stretched across its container. Only in
// flow, though: a grid or flex item control stretches as any other item does (an artifact's grid of option
// buttons, docs/blitz-bevy.feature B5c), where a replaced item's `normal` would be `start`
let parent_lays_out_items = self
.layout_parent
.get()
.or(self.parent)
.and_then(|p| self.with(p).primary_styles())
.is_some_and(|s| matches!(s.clone_display().inside(), DisplayInside::Grid | DisplayInside::Flex));
if crate::layout::replaced::is_replaced_element(&el.name.local)
|| (matches!(&*el.name.local, "button" | "input" | "select" | "textarea") && !parent_lays_out_items)
{
flags |= stylo_taffy::StyleFlags::IS_REPLACED;
}
if el.name.local == local_name!("button") {
flags |= stylo_taffy::StyleFlags::IS_BUTTON;
}
if el.is_button_input() {
flags |= stylo_taffy::StyleFlags::IS_BUTTON_INPUT;
}
if let Some(inline_layout) = el.inline_layout_data.as_deref() {
flags |= inline_layout.span_cb_flags;
}
// raea: transform-style: preserve-3d on a transformable element contains absolute and fixed boxes, as a
// transform and a perspective do (css-transforms-2 §2; WPT transform-style-stacking-context): stylo_taffy
// 0.3.0-beta.4's establishes_fixed_containing_block leaves it out
if crate::stylo_to_kurbo::preserves_3d(&styles) && self.is_transformable() {
flags |= stylo_taffy::StyleFlags::SPAN_ABSOLUTE_CB | stylo_taffy::StyleFlags::SPAN_FIXED_CB;
}
}
#[cfg(feature = "writing-mode")]
{
// Own-layout_wm by default: the node's own algorithm reads its style in its own axes
let layout_wm = styles.writing_mode;
stylo_taffy::TaffyStyloStyle::new_in(styles, flags, layout_wm)
}
#[cfg(not(feature = "writing-mode"))]
{
stylo_taffy::TaffyStyloStyle::new(styles, flags)
}
}
/// The node's style for Taffy, expressed in the axes of the writing mode `layout_wm` (the writing
/// mode of the box laying this node out). Used for the child-style getters.
#[cfg(feature = "writing-mode")]
pub fn layout_style_in(
&self,
layout_wm: stylo_taffy::WritingMode,
) -> stylo_taffy::TaffyStyloStyle<ComputedStyleRef<'_>> {
let mut style = self.layout_style();
style.layout_wm = layout_wm;
style
}
/// Whether the node has any `contain` value, which blocks `writing-mode` propagation from
/// `<body>` to the root (css-writing-modes-3 §8).
#[cfg(feature = "writing-mode")]
pub(crate) fn has_containment(&self) -> bool {
self.primary_styles()
.is_some_and(|style| !style.clone_contain().is_empty())
}
/// Whether the node is a flex container with a column `flex-direction`, i.e. aligns its
/// children's `align-self` in its inline axis.
#[cfg(feature = "writing-mode")]
pub(crate) fn is_column_flex_container(&self) -> bool {
self.primary_styles().is_some_and(|s| {
s.clone_display().inside() == DisplayInside::Flex
&& !self.element_data().is_some_and(|el| el.is_button_input())
&& matches!(
s.get_position().flex_direction,
FlexDirection::Column | FlexDirection::ColumnReverse
)
})
}
/// The node's computed `writing-mode` (horizontal-tb for nodes without styles)
#[cfg(feature = "writing-mode")]
pub fn writing_mode(&self) -> stylo_taffy::WritingMode {
self.primary_styles()
.map(|s| s.writing_mode)
.unwrap_or(stylo_taffy::WritingMode::empty())
}
/// The node's `display` as a [`taffy::Display`]. Returns [`taffy::Display::Block`]
/// for nodes without computed styles (e.g. text nodes).
pub fn taffy_display(&self) -> taffy::Display {
self.primary_styles()
.map(|style| {
let display = style.clone_display();
if self.element_data().is_some_and(|el| el.is_button_input())
&& !matches!(
display.inside(),
DisplayInside::None | DisplayInside::Contents
)
{
taffy::Display::FlowRoot
} else {
stylo_taffy::convert::display(display)
}
})
.unwrap_or(taffy::Display::Block)
}
/// The node's `position` as a [`taffy::Position`]. Returns [`taffy::Position::Static`]
/// for nodes without computed styles (e.g. text nodes).
pub fn taffy_position(&self) -> taffy::Position {
self.primary_styles()
.map(|s| stylo_taffy::convert::position(s.get_box().position))
.unwrap_or(taffy::Position::Static)
}
/// Whether the node is an out-of-flow box that Taffy positions from its containing
/// block's hoisted child list rather than from its parent (`display: none` boxes
/// generate no box and are never hoisted).
pub fn is_out_of_flow(&self) -> bool {
self.primary_styles().is_some_and(|s| {
let box_style = s.get_box();
stylo_taffy::convert::position(box_style.position).is_out_of_flow()
&& stylo_taffy::convert::display(box_style.display) != taffy::Display::None
})
}
pub fn text_content(&self) -> String {
let mut out = String::new();
self.write_text_content(&mut out);
out
}
fn write_text_content(&self, out: &mut String) {
match &self.data {
NodeData::Text(data) => {
out.push_str(&data.content);
}
NodeData::Element(..) | NodeData::AnonymousBlock(..) => {
for child_id in self.children.iter() {
self.with(*child_id).write_text_content(out);
}
}
_ => {}
}
}
pub fn flush_style_attribute(&mut self, url_extra_data: &UrlExtraData) {
if let NodeData::Element(ref mut elem_data) = self.data {
if let Some(guard) = elem_data.guard.clone() {
elem_data.flush_style_attribute(&guard, url_extra_data);
}
}
}
/// The `order` sort key of this node within a flex/grid container's
/// `layout_children`. The list is stable-sorted by this key when the
/// container's children are constructed (`collect_layout_children`) and
/// re-collected when a child's `order` changes (`REORDER_CHILDREN` damage).
///
/// ::before/::after pseudos are flex/grid items and honor `order`. They
/// sit first/last in the constructed list, and the sort is stable, so
/// ties keep ::before first and ::after last. Out-of-flow children are
/// not flex/grid items, so they key as 0 and keep source order.
pub fn order(&self) -> i32 {
self.primary_styles()
.filter(|s| !matches!(s.get_box().position, Position::Absolute | Position::Fixed))
.map(|s| s.clone_order())
.unwrap_or(0)
}
pub fn z_index(&self) -> i32 {
self.primary_styles()
.map(|s| s.clone_z_index().integer_or(0))
.unwrap_or(0)
}
// https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_positioned_layout/Stacking_context#features_creating_stacking_contexts
pub fn is_stacking_context_root(&self, is_flex_or_grid_item: bool) -> bool {
let Some(style) = self.primary_styles() else {
return false;
};
let position = style.clone_position();
let has_z_index = !style.clone_z_index().is_auto();
if style.clone_opacity() != 1.0 {
return true;
}
let position_based = match position {
Position::Fixed | Position::Sticky => true,
Position::Relative | Position::Absolute => has_z_index,
Position::Static => has_z_index && is_flex_or_grid_item,
};
if position_based {
return true;
}
let box_style = style.get_box();
if !box_style.transform.0.is_empty()
|| !matches!(box_style.rotate, Rotate::None)
|| !matches!(box_style.scale, Scale::None)
|| !matches!(box_style.translate, Translate::None)
{
return true;
}
if self.applies_atomic_paint_effect() {
return true;
}
// raea: on a transformable element, `transform-style: preserve-3d` and a `perspective` each make one
// (css-transforms-2 §§ 2, 3.1; WPT transform-style-stacking-context), not on a non-replaced inline
// (perspective-untransformable-no-stacking-context)
if (crate::stylo_to_kurbo::preserves_3d(&style) || !matches!(box_style.perspective, style::values::generics::box_::GenericPerspective::None)) && self.is_transformable() {
return true;
}
if style.get_box().isolation == Isolation::Isolate {
return true;
}
// TODO: mix-blend-mode
// TODO: contain
false
}
/// raea: whether transforms apply to it (css-transforms-1 "transformable element"): not a non-replaced inline box
pub(crate) fn is_transformable(&self) -> bool {
let Some(style) = self.primary_styles() else { return false };
let display = style.clone_display();
let inline = display.outside() == style::values::specified::box_::DisplayOutside::Inline && display.inside() == DisplayInside::Flow;
!inline || self.element_data().is_some_and(|el| crate::layout::replaced::is_replaced_element(&el.name.local))
}
/// Whether this node's styles apply an atomic paint effect (opacity, filter,
/// clip-path, mask) to its subtree.
pub(crate) fn applies_atomic_paint_effect(&self) -> bool {
use style::values::computed::basic_shape::ClipPath;
use style::values::generics::image::GenericImage;
let Some(style) = self.primary_styles() else {
return false;
};
if style.clone_opacity() != 1.0 {
return true;
}
let effects = style.get_effects();
if !effects.filter.0.is_empty() {
return true;
}
if !matches!(style.clone_clip_path(), ClipPath::None) {
return true;
}
style
.get_svg()
.mask_image
.0
.iter()
.any(|image| !matches!(image, GenericImage::None))
}
/// Takes an (x, y) position (relative to the *parent's* top-left corner) and returns:
/// - None if the position is outside of this node's bounds
/// - Some(HitResult) if the position is within the node but doesn't match any children
/// - The result of recursively calling child.hit() on the the child element that is
/// positioned at that position if there is one.
///
/// Hit testing may run between a DOM mutation and the next `resolve`, so the
/// paint lists and inline layouts it walks can still name nodes the mutation
/// dropped; those are skipped.
///
/// TODO: z-index
/// (If multiple children are positioned at the position then a random one will be recursed into)
pub fn hit(&self, x: f32, y: f32, scale: f64) -> Option<HitResult> {
self.hit_inner(x, y, scale, &mut None)
}
/// raea: whether this box's overflow clip cuts the point away (the point from its border box, unscrolled):
/// outside its padding box on an axis it clips. The root element clips nothing (its overflow is the viewport's).
fn clips_away(&self, x: f32, y: f32) -> bool {
use style::values::computed::Overflow;
let is_root_element = self.parent.and_then(|p| self.tree().get(p)).is_some_and(|p| p.parent.is_none());
if is_root_element {
return false;
}
let Some(styles) = self.primary_styles() else { return false };
let cx = !matches!(styles.clone_overflow_x(), Overflow::Visible);
let cy = !matches!(styles.clone_overflow_y(), Overflow::Visible);
let (size, b) = (self.final_layout().size, self.final_layout().border);
(cx && (x < b.left || x > size.width - b.right)) || (cy && (y < b.top || y > size.height - b.bottom))
}
/// raea: whether a hoisted child (a z-index's, hit from its stacking-context root, this node) is cut away at
/// the point (in this node's coordinates, as the hoisted children's positions are): by this node's own clip
/// (`cut`) or by one of the boxes between along its containing blocks, the clips blitz-paint draws it under
/// (`hoisted_clips`). A box whose containing blocks never reach this node is painted from above it, under none
/// of these clips (blitz-paint's `from_above`), and is never cut here. Transforms on the boxes between are not
/// read, as the painter's clips don't read them.
fn hoisted_cut(&self, child: NodeId, x: f32, y: f32, cut: bool) -> bool {
let tree = self.tree();
let mut between = Vec::new();
let mut current = tree.get(child).and_then(|n| n.containing_block());
loop {
match current {
Some(id) if id == self.id => break,
Some(id) => {
between.push(id);
current = tree.get(id).and_then(|n| n.containing_block());
}
None => return false,
}
}
if cut {
return true;
}
between.iter().any(|&id| {
let Some(node) = tree.get(id) else { return false };
// its border box from this node: its place and those of the boxes it's in, less what they're scrolled by
let at = node.final_layout().location;
let (mut ax, mut ay) = (at.x, at.y);
let mut up = node.containing_block();
while let Some(a) = up.filter(|a| *a != self.id) {
let Some(an) = tree.get(a) else { break };
let (l, sc) = (an.final_layout().location, an.scroll_offset());
ax += l.x - sc.x as f32;
ay += l.y - sc.y as f32;
up = an.containing_block();
}
node.clips_away(x - ax, y - ay)
})
}
/// [`hit`](Self::hit), also resolving the innermost overlay scrollbar
/// thumb under the point into `scrollbar` during the same descent (so
/// thumb hit-testing shares the exact coordinate handling — transforms
/// included — of every other hit test).
pub(crate) fn hit_inner(
&self,
x: f32,
y: f32,
scale: f64,
scrollbar: &mut Option<crate::node::ScrollbarRef>,
) -> Option<HitResult> {
use style::computed_values::pointer_events::T as PointerEvents;
use style::computed_values::visibility::T as Visibility;
// Don't hit on visbility:hidden elements
if let Some(style) = self.primary_styles() {
if matches!(
style.clone_visibility(),
Visibility::Hidden | Visibility::Collapse
) {
return None;
}
}
// pointer-events:none makes this element transparent to hits, but its
// descendants are still tested (one may restore pointer-events:auto).
let pointer_events_none = self
.primary_styles()
.is_some_and(|style| style.clone_pointer_events() == PointerEvents::None);
let mut x = x - self.final_layout().location.x + self.scroll_offset().x as f32;
let mut y = y - self.final_layout().location.y + self.scroll_offset().y as f32;
if let Some(t) = self.transform().as_deref() {
let p = t.inverse() * kurbo::Point::new(x as f64 * scale, y as f64 * scale);
x = (p.x / scale) as f32;
y = (p.y / scale) as f32;
}
let size = self.final_layout().size;
let matches_self = !(x < 0.0
|| x > size.width + self.scroll_offset().x as f32
|| y < 0.0
|| y > size.height + self.scroll_offset().y as f32);
let overflow_rect = self.final_layout().scrollable_overflow_rect;
let matches_content = !(x < 0.0
|| x > overflow_rect.right + self.scroll_offset().x as f32
|| y < 0.0
|| y > overflow_rect.bottom + self.scroll_offset().y as f32);
let matches_hoisted_content = match &self.stacking_context {
Some(sc) => {
// Both the point (after the scroll adjustment above) and the
// bbox are in this node's unscrolled content coordinates.
let bbox = sc.hoisted_content_bbox(self.tree(), self.id, scale);
x >= bbox.left && x <= bbox.right && y >= bbox.top && y <= bbox.bottom
}
None => false,
};
// `scrollable_overflow` is stored in device (scaled) pixels, whereas the
// coordinates here are in CSS pixels, so unscale it before comparing.
let overflow = *self.scrollable_overflow();
let matches_overflow = x >= (overflow.x0 / scale) as f32
&& x <= (overflow.x1 / scale) as f32
&& y >= (overflow.y0 / scale) as f32
&& y <= (overflow.y1 / scale) as f32;
if !matches_self && !matches_content && !matches_hoisted_content && !matches_overflow {
return None;
}
// raea: a box that clips its overflow takes no pointer for what it cuts away, as it draws none of it
// (blitz-paint's `should_clip`). Blitz tested the children wherever they overflowed to, so a press on the
// page around a zoomed canvas landed on the card that would have lain there.
let cut = self.clips_away(x - self.scroll_offset().x as f32, y - self.scroll_offset().y as f32);
// Descendants overwrite, so the innermost scroll container's thumb
// wins. Thumb coords are border-box relative (unscrolled).
if matches_self
&& let Some(sb) = self.scrollbar_at_local(
(x - self.scroll_offset().x as f32) as f64,
(y - self.scroll_offset().y as f32) as f64,
)
{
*scrollbar = Some(sb);
}
let content_box_offset = taffy::Point {
x: self.final_layout().padding.left + self.final_layout().border.left,
y: self.final_layout().padding.top + self.final_layout().border.top,
};
// raea: children (inline-level boxes placed by the inline layout included) are at their places from this
// node's border box; only its own text is laid out from its content box (Blitz moved the point into the
// content box for both, so a padded line's inline-block buttons were hit off by the padding)
// Positive z_index hoisted children
if matches_hoisted_content {
if let Some(hoisted) = &self.stacking_context {
for hoisted_child in hoisted.pos_z_hoisted_children().rev() {
let Some(child) = self.tree().get(hoisted_child.node_id) else {
continue;
};
if self.hoisted_cut(hoisted_child.node_id, x, y, cut) {
continue;
}
let pos = hoisted_child.position(self.tree(), self.id);
let x = x - pos.x;
let y = y - pos.y;
if let Some(hit) = child.hit_inner(x, y, scale, scrollbar) {
return Some(hit);
}
}
}
}
// Call `.hit()` on each child in turn. If any return `Some` then return that value. Else return `Some(self.id).
for child_id in self.paint_children.borrow().iter().flatten().rev() {
if cut {
break;
}
let Some(child) = self.tree().get(*child_id) else {
continue;
};
let child_position = child.taffy_position();
let mut child_x = x;
let mut child_y = y;
if child_position.is_out_of_flow() {
// Fixed-position children of the root element are positioned
// against the viewport and do not scroll with it. (A fixed box
// whose containing block is a transformed ancestor scrolls with
// that ancestor like any other out-of-flow box.)
if child_position == taffy::Position::Fixed && self.containing_block().is_none() {
child_x -= self.scroll_offset().x as f32;
child_y -= self.scroll_offset().y as f32;
let viewport_scroll = self.tree().viewport_scroll();
child_x -= viewport_scroll.x as f32;
child_y -= viewport_scroll.y as f32;
}
}
if let Some(hit) = child.hit_inner(child_x, child_y, scale, scrollbar) {
return Some(hit);
}
}
// Negative z_index hoisted children
if matches_hoisted_content {
if let Some(hoisted) = &self.stacking_context {
for hoisted_child in hoisted.neg_z_hoisted_children().rev() {
let Some(child) = self.tree().get(hoisted_child.node_id) else {
continue;
};
if self.hoisted_cut(hoisted_child.node_id, x, y, cut) {
continue;
}
let pos = hoisted_child.position(self.tree(), self.id);
let x = x - pos.x;
let y = y - pos.y;
if let Some(hit) = child.hit_inner(x, y, scale, scrollbar) {
return Some(hit);
}
}
}
}
// Inline children
if self.flags.is_inline_root() {
let element_data = &self.element_data().unwrap();
if let Some(ild) = element_data.inline_layout_data.as_ref() {
let layout = &ild.layout;
let scale = layout.scale();
let x = x - content_box_offset.x;
let y = y - content_box_offset.y - ild.block_offset;
if let Some((cluster, _side)) =
Cluster::from_point_exact(layout, x * scale, y * scale)
{
let node_id = cluster.style().brush.id;
if let Some(text_node) = self.tree().get(node_id)
&& !text_node.primary_styles().is_some_and(|style| {
style.clone_pointer_events() == PointerEvents::None
})
{
return Some(HitResult {
node_id,
x,
y,
is_text: true,
});
}
}
}
}
// Self (this node)
if matches_self && !pointer_events_none {
return Some(HitResult {
node_id: self.id,
x,
y,
is_text: false,
});
}
None
}
/// Find the inline root ancestor of this node (or self if this is an inline root).
/// Returns None if no inline root ancestor exists.
pub fn inline_root_ancestor(&self) -> Option<&Node> {
let mut node = self;
loop {
if node.flags.is_inline_root() {
return Some(node);
}
let id = node.layout_parent.get()?;
// raea: a layout parent freed since (a reconstruction's old anonymous block): no inline root (#108)
node = self.tree().get(id)?;
}
}
/// Get the text byte offset at a given point, using coordinates already transformed
/// to be relative to this inline root's content box.
/// Returns Some(byte_offset) if the point hits text, None otherwise.
pub fn text_offset_at_point(&self, x: f32, y: f32) -> Option<usize> {
if !self.flags.is_inline_root() {
return None;
}
let element_data = self.element_data()?;
let inline_layout = element_data.inline_layout_data.as_ref()?;
let layout = &inline_layout.layout;
let scale = layout.scale();
let y = y - inline_layout.block_offset;
// Use Parley's cluster hit testing (from_point is more forgiving than from_point_exact)
let (cluster, side) = Cluster::from_point(layout, x * scale, y * scale)?;
// Determine byte offset based on which side of the cluster was clicked
// For LTR text: left side = start of cluster, right side = end of cluster
// For RTL text: left side = end of cluster, right side = start of cluster
// Also, explicit line breaks should always use start to avoid cursor appearing on next line
let is_leading = side == ClusterSide::Left;
let offset = if cluster.is_rtl() {
if is_leading {
cluster.text_range().end
} else {
cluster.text_range().start
}
} else {
// LTR text
if is_leading || cluster.is_line_break() == Some(BreakReason::Explicit) {
cluster.text_range().start
} else {
cluster.text_range().end
}
};
Some(offset)
}
/// Whether this node is a non-atomic inline element: one that has no layout box of its
/// own because it is flattened into the containing inline root's text layout as a style
/// span.
pub fn is_non_atomic_inline(&self) -> bool {
let Some(element) = self.element_data() else {
return false;
};
if self.flags.is_inline_root()
|| crate::layout::replaced::is_inline_box_element(&element.name.local)
{
return false;
}
self.primary_styles().is_some_and(|styles| {
let display = styles.clone_display();
display.outside() == DisplayOutside::Inline && display.inside() == DisplayInside::Flow
})
}
/// The node whose box this node's `Layout.location` is relative to: the
/// `oof_containing_block` for a hoisted out-of-flow box, otherwise the
/// `layout_parent`.
pub fn containing_block(&self) -> Option<NodeId> {
self.oof_containing_block
.get()
.or_else(|| self.layout_parent.get())
}
/// Computes the Document-relative coordinates of the `Node`
pub fn absolute_position(&self, x: f32, y: f32) -> crate::util::Point<f32> {
let x = x + self.final_layout().location.x - self.scroll_offset().x as f32;
let y = y + self.final_layout().location.y - self.scroll_offset().y as f32;
// Recurse up the positioning hierarchy
self.containing_block()
.map(|i| self.with(i).absolute_position(x, y))
.unwrap_or(crate::util::Point { x, y })
}
/// Whether this node can act as an [`offset_parent`](Self::offset_parent): a positioned
/// element, or one of the elements that always qualify (`body`, `td`, `th`).
pub fn is_offset_parent(&self) -> bool { // raea: pub, for the layout snapshot's offsetParent (raea-sys-page)
let Some(styles) = self.primary_styles() else {
return false;
};
if styles.get_box().position != Position::Static {
return true;
}
self.data.is_element_with_tag_name(&local_name!("body"))
|| self.data.is_element_with_tag_name(&local_name!("td"))
|| self.data.is_element_with_tag_name(&local_name!("th"))
}
/// Whether this node is a non-positioned `body` element. When such an element is the
/// `offsetParent`, `offsetLeft`/`offsetTop` are measured from the initial containing
/// block origin rather than from the `body`'s padding edge.
pub(crate) fn is_static_body(&self) -> bool {
self.data.is_element_with_tag_name(&local_name!("body"))
&& self
.primary_styles()
.is_some_and(|styles| styles.get_box().position == Position::Static)
}
/// The nearest layout ancestor that [is an offset parent](Self::is_offset_parent), as in
/// CSSOM View's `offsetParent`.
pub fn offset_parent(&self) -> Option<&Node> {
let mut node = self;
loop {
node = self.with(node.containing_block()?);
if node.is_offset_parent() {
return Some(node);
}
}
}
/// The per-line-box fragment boxes of a non-atomic inline element, in CSS pixels relative
/// to the border box of its inline root.
///
/// Returns `None` for nodes that have their own layout box.
pub fn inline_fragment_boxes(&self) -> Option<impl Iterator<Item = taffy::Rect<f32>> + '_> {
use parley::PositionedLayoutItem;
if !self.is_non_atomic_inline() {
return None;
}
let inline_root = self.inline_root_ancestor()?;
let inline_layout = inline_root.element_data()?.inline_layout_data.as_ref()?;
let layout = &inline_layout.layout;
let scale = layout.scale();
// Walk up the DOM parent chain from `id` to check whether it is (or is
// inside) the target node, stopping at the inline root.
let inline_root_id = inline_root.id;
let is_in_target = move |mut id: NodeId| -> bool {
loop {
if id == self.id {
return true;
}
if id == inline_root_id {
return false;
}
// raea: a run's node may be gone (removed since the inline layout was built): not the target's
match self.tree().get(id).and_then(|n| n.parent) {
Some(parent) => id = parent,
None => return false,
}
}
};
// raea: in a bevy_ui <Text>'s block (data-raea-bevy-text, layout/inline.rs) a run's box is bevy_text's run
// bounds (pipeline.rs RunGeometry): its whole advance across the line box, as TextBackgroundColor fills it
let bevy = inline_root.is_bevy_text();
let root_layout = inline_root.unrounded_layout();
let content_box_inset = root_layout.padding + root_layout.border;
let origin_x = content_box_inset.left;
let origin_y = content_box_inset.top + inline_layout.block_offset;
fn union(acc: &mut Option<taffy::Rect<f32>>, left: f32, top: f32, right: f32, bottom: f32) {
*acc = Some(match *acc {
Some(rect) => taffy::Rect {
left: rect.left.min(left),
top: rect.top.min(top),
right: rect.right.max(right),
bottom: rect.bottom.max(bottom),
},
None => taffy::Rect {
left,
top,
right,
bottom,
},
});
}
// raea: the element's vertical border and padding, which Chrome's box has around its content area
let (pad_top, pad_bottom) = self.primary_styles().map_or((0.0, 0.0), |s| {
let px = |l: &style::values::computed::LengthPercentage| l.to_length().map_or(0.0, |v| v.px());
let (p, b) = (s.get_padding(), s.get_border());
// (a border whose style is none or hidden is 0 wide, whatever its width says: medium's 3px otherwise)
let shown = |st: style::values::computed::BorderStyle| !matches!(st, style::values::computed::BorderStyle::None | style::values::computed::BorderStyle::Hidden);
let side = |w: &style::values::computed::BorderSideWidth, st| if shown(st) { w.0.to_f32_px() } else { 0.0 };
(
px(&p.padding_top.0) + side(&b.border_top_width, b.border_top_style),
px(&p.padding_bottom.0) + side(&b.border_bottom_width, b.border_bottom_style),
)
});
let target = self.id;
// One rect per line box: the union of all of the target's fragments on that line
Some(layout.lines().filter_map(move |line| {
let line_metrics = line.metrics();
let mut line_rect: Option<taffy::Rect<f32>> = None;
// raea: the box's block extent as Chrome's: its own text's content area (the font's ascent and descent
// about the baseline), not the line box; a child's text where it has none of its own on the line
let mut own_y: Option<(f32, f32)> = None;
let mut any_y: Option<(f32, f32)> = None;
let mut spacer_y: Option<(f32, f32)> = None;
// raea: where the line's content ends without its trailing spaces, which Chrome's fragments leave out
let end = match line.items().last() {
Some(PositionedLayoutItem::GlyphRun(last)) => {
let ws: f32 = last.run().visual_clusters().collect::<Vec<_>>().into_iter().rev().take_while(|c| c.is_space_or_nbsp() || c.is_hard_line_break()).map(|c| c.advance()).sum();
// (a space parley removed at the line's end is a glyph run of its own with no width: nothing to take off)
last.offset() + last.advance() - ws.min(last.advance())
}
_ => f32::INFINITY,
};
for item in line.items() {
match item {
PositionedLayoutItem::GlyphRun(glyph_run) => {
let brush = glyph_run.style().brush.id;
if !is_in_target(brush) {
continue;
}
let x0 = glyph_run.offset();
let x1 = (x0 + glyph_run.advance()).min(end.max(x0));
// raea: the content area of the run's style, its first available font's ascent and descent rounded
// each to whole pixels (Blink's AscentDescentWithHacks), not a fallback face's: a Helvetica span's
// ▌ from Hiragino Sans is as tall as its Helvetica text
let (ascent, descent) = glyph_run.style_content_area();
let (y0, y1) = (glyph_run.baseline() - ascent.round(), glyph_run.baseline() + descent.round());
let (x1, y0, y1) = match bevy {
true => (x0 + glyph_run.advance(), line_metrics.block_min_coord, line_metrics.block_max_coord),
false => (x1, y0, y1),
};
let grow = |a: &mut Option<(f32, f32)>| *a = Some(a.map_or((y0, y1), |(p, q)| (p.min(y0), q.max(y1))));
if brush == target {
grow(&mut own_y);
}
grow(&mut any_y);
union(&mut line_rect, x0, y0, x1, y1);
}
PositionedLayoutItem::InlineBox(inline_box) => {
// a spacer: the target's own border and padding, or anything's inside it
if let Some(sp) = crate::layout::Spacer::of(inline_box.id) {
let ours = if sp.node == target { !sp.margin } else { is_in_target(sp.node) };
if ours {
let y = line_metrics.baseline;
union(&mut line_rect, inline_box.x, y, inline_box.x + inline_box.width, y);
}
// raea: an element with no text on the line is its own font's content area about the
// baseline (Chrome's), not the line box
if sp.node == target && !sp.margin && spacer_y.is_none() {
spacer_y = layout.inline_box_content_area(inline_box.id).map(|(a, d)| (line_metrics.baseline - a.round(), line_metrics.baseline + d.round()));
}
continue;
}
if !is_in_target(NodeId::from_u64(inline_box.id)) {
continue;
}
let x0 = inline_box.x;
let y0 = inline_box.y;
union(
&mut line_rect,
x0,
y0,
x0 + inline_box.width,
y0 + inline_box.height,
);
}
}
}
line_rect.map(|mut rect| {
match own_y.or(any_y).or(spacer_y) {
Some((y0, y1)) => {
rect.top = y0;
rect.bottom = y1;
}
None if rect.top == rect.bottom => {
rect.top = line_metrics.block_min_coord;
rect.bottom = line_metrics.block_max_coord;
}
None => {}
}
taffy::Rect {
left: origin_x + rect.left / scale,
top: origin_y + rect.top / scale - pad_top,
right: origin_x + rect.right / scale,
bottom: origin_y + rect.bottom / scale + pad_bottom,
}
})
}))
}
/// CSSOM View's `offsetLeft`/`offsetTop`: the offset of this node's border box from the
/// padding edge of its [`offset_parent`](Self::offset_parent).
pub fn offset_top_left(&self) -> crate::util::Point<f32> {
let mut x = 0.0;
let mut y = 0.0;
let mut current = self;
// Non-atomic inlines have no layout box of their own: start from the first
// fragment box (relative to the inline root's border box) and continue the
// walk from the inline root.
if let Some(mut fragments) = self.inline_fragment_boxes() {
if let Some(first) = fragments.next() {
x += first.left;
y += first.top;
}
let Some(inline_root) = self.inline_root_ancestor() else {
return crate::util::Point { x, y };
};
if inline_root.is_offset_parent() && !inline_root.is_static_body() {
let border = inline_root.final_layout().border;
return crate::util::Point {
x: x - border.left,
y: y - border.top,
};
}
current = inline_root;
}
loop {
let layout = current.final_layout();
x += layout.location.x;
y += layout.location.y;
let Some(parent_id) = current.containing_block() else {
break;
};
let parent = self.with(parent_id);
if parent.is_offset_parent() && !parent.is_static_body() {
let border = parent.final_layout().border;
x -= border.left;
y -= border.top;
break;
}
current = parent;
}
crate::util::Point { x, y }
}
/// CSSOM View's `clientWidth`: the width of the padding box (border box minus
/// borders and scrollbar)
pub fn client_width(&self) -> f32 {
let layout = self.final_layout();
layout.size.width - layout.border.left - layout.border.right - layout.scrollbar_size.width
}
/// CSSOM View's `clientHeight`: the height of the padding box (border box minus
/// borders and scrollbar)
pub fn client_height(&self) -> f32 {
let layout = self.final_layout();
layout.size.height - layout.border.top - layout.border.bottom - layout.scrollbar_size.height
}
/// CSSOM View's `scrollWidth`: the width of the node's content, including
/// content not visible due to overflow
pub fn scroll_width(&self) -> f32 {
self.client_width()
.max(self.final_layout().scrollable_overflow_rect.right)
}
/// CSSOM View's `scrollHeight`: the height of the node's content, including
/// content not visible due to overflow
pub fn scroll_height(&self) -> f32 {
self.client_height()
.max(self.final_layout().scrollable_overflow_rect.bottom)
}
/// Does the node generate any boxes? (e.g. `getClientRects()` returns an empty
/// list for boxless nodes, such as `display: none`, `display: contents`, or
/// detached elements)
pub fn has_boxes(&self) -> bool {
self.flags.is_in_document()
&& !self.display_style().is_some_and(|display| {
matches!(
display.inside(),
style::values::specified::box_::DisplayInside::None
| style::values::specified::box_::DisplayInside::Contents
)
})
}
/// Creates a synthetic click event
pub fn synthetic_click_event(&self, mods: Modifiers) -> DomEventData {
DomEventData::Click(self.synthetic_click_event_data(mods))
}
pub fn synthetic_click_event_data(&self, mods: Modifiers) -> BlitzPointerEvent {
let absolute_position = self.absolute_position(0.0, 0.0);
let x = absolute_position.x + (self.final_layout().size.width / 2.0);
let y = absolute_position.y + (self.final_layout().size.height / 2.0);
BlitzPointerEvent {
id: BlitzPointerId::Mouse,
is_primary: true,
coords: PointerCoords {
page_x: x,
page_y: y,
// TODO: should these be different?
screen_x: x,
screen_y: y,
client_x: x,
client_y: y,
},
mods,
button: Default::default(),
buttons: Default::default(),
details: Default::default(),
element: Default::default(),
active_pointers: Default::default(),
}
}
}
/// It might be wrong to expose this since what does *equality* mean outside the dom?
impl PartialEq for Node {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for Node {}
impl std::fmt::Debug for Node {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// FIXME: update to reflect changes to fields
f.debug_struct("NodeData")
.field("parent", &self.parent)
.field("id", &self.id)
.field("is_inline_root", &self.flags.is_inline_root())
.field("children", &self.children)
.field("layout_children", &self.layout_children.borrow())
// .field("style", &self.style)
.field("node", &self.data)
.field("stylo_element_data", &self.try_stylo_element_data())
// .field("unrounded_layout", &self.unrounded_layout)
// .field("final_layout", &self.final_layout)
.finish()
}
}
#[cfg(test)]
mod test {
use style_dom::ElementState;
use crate::{Attribute, BaseDocument, DocumentConfig, ElementData, NodeData, qual_name};
#[test]
fn create_node_with_disabled_attr() {
let mut document = BaseDocument::new(DocumentConfig::default());
let node = document.create_node(NodeData::Element(Box::new(ElementData::new(
qual_name!("button"),
vec![Attribute {
name: qual_name!("disabled"),
value: "".into(),
}],
))));
let node = document.get_node(node).unwrap();
assert!(
node.element_state().contains(ElementState::DISABLED),
"form node is disabled"
);
assert!(
!node.element_state().contains(ElementState::ENABLED),
"form node is not enabled"
);
}
#[test]
fn ignore_disabled_attr_content() {
let mut document = BaseDocument::new(DocumentConfig::default());
let node = document.create_node(NodeData::Element(Box::new(ElementData::new(
qual_name!("button"),
vec![Attribute {
name: qual_name!("disabled"),
value: "false".into(),
}],
))));
let node = document.get_node(node).unwrap();
assert!(
node.element_state().contains(ElementState::DISABLED),
"form node is disabled"
);
assert!(
!node.element_state().contains(ElementState::ENABLED),
"form node is not enabled"
);
}
#[test]
fn create_node_with_ignored_disable() {
let mut document = BaseDocument::new(DocumentConfig::default());
let node = document.create_node(NodeData::Element(Box::new(ElementData::new(
qual_name!("a"),
vec![Attribute {
name: qual_name!("disabled"),
value: "".into(),
}],
))));
let node = document.get_node(node).unwrap();
assert!(
!node.element_state().contains(ElementState::DISABLED),
"Non form node cannot be disabled"
);
assert!(
!node.element_state().contains(ElementState::ENABLED),
"Non form node cannot be enabled"
);
}
#[test]
fn create_empty_enabled_node() {
let mut document = BaseDocument::new(DocumentConfig::default());
let node = document.create_node(NodeData::Element(Box::new(ElementData::new(
qual_name!("button"),
vec![],
))));
let node = document.get_node(node).unwrap();
assert!(
node.element_state().contains(ElementState::ENABLED),
"Button should be enabled by default"
);
}
}
/// raea: a box's corners (top left, top right, bottom right, bottom left) through `full`, x, y and z over w; None when
/// one is at or behind the viewer (Projection's quad).
fn quad_of(full: &crate::stylo_to_kurbo::Mat4, bw: f64, bh: f64) -> Option<[[f64; 3]; 4]> {
let corner = |x: f64, y: f64| {
let r = |i: usize| full[i][0] * x + full[i][1] * y + full[i][3];
let w = r(3);
(w > 1e-9).then(|| [r(0) / w, r(1) / w, r(2) / w])
};
match [corner(0.0, 0.0), corner(bw, 0.0), corner(bw, bh), corner(0.0, bh)] {
[Some(a), Some(b), Some(c), Some(d)] => Some([a, b, c, d]),
_ => None,
}
}