The headless browser for AI agents and web scraping
Converge container query layout
SGavrl02f5d233d3ae
diff --git a/crates/obscura-render/src/css.rs b/crates/obscura-render/src/css.rsindex aa87e530..50089b3e 100644--- a/crates/obscura-render/src/css.rs+++ b/crates/obscura-render/src/css.rs@@ -13,7 +13,7 @@ use std::collections::HashMap;use crate::LayoutStyle;-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]struct ContainerConditionId(u32);impl ContainerConditionId {@@ -37,16 +37,31 @@ struct ContainerQuery {#[derive(Clone, Debug, PartialEq)]enum ContainerQueryExpr {Feature(ContainerSizeFeature),+ /// Syntactically valid future/general-enclosed syntax has Kleene+ /// `unknown` truth. Retaining it prevents one unknown comma arm from+ /// discarding supported alternatives in the same `@container` rule.+ Unknown,Not(Box<ContainerQueryExpr>),And(Vec<ContainerQueryExpr>),Or(Vec<ContainerQueryExpr>),}#[derive(Clone, Copy, Debug, PartialEq, Eq)]-enum ContainerQueryAxis { Width, InlineSize }+enum ContainerQueryAxis {+ Width,+ Height,+ InlineSize,+ BlockSize,+}#[derive(Clone, Copy, Debug, PartialEq, Eq)]-enum ContainerQueryComparison { Min, Max }+enum ContainerQueryComparison {+ Min,+ Max,+ GreaterThan,+ LessThan,+ Equal,+}#[derive(Clone, Copy, Debug, PartialEq)]struct ContainerSizeFeature {@@ -81,6 +96,373 @@ struct PseudoRule {container_condition_id: ContainerConditionId,}+#[derive(Clone, Debug)]+pub(crate) struct ContainerBox {+ pub(crate) container_type: crate::ContainerType,+ /// Axes on which size containment actually applies to the generated box.+ /// This can be `Normal` even when computed `container-type` is non-normal+ /// (for example a non-atomic inline or an internal table box).+ pub(crate) available_type: crate::ContainerType,+ pub(crate) names: Vec<String>,+ pub(crate) content_width: f32,+ pub(crate) content_height: f32,+ pub(crate) font_size: f32,+}++impl PartialEq for ContainerBox {+ fn eq(&self, other: &Self) -> bool {+ if self.container_type != other.container_type+ || self.available_type != other.available_type+ || self.names != other.names+ {+ return false;+ }+ match self.available_type {+ crate::ContainerType::Normal => true,+ crate::ContainerType::InlineSize => {+ self.content_width == other.content_width+ && self.font_size == other.font_size+ }+ crate::ContainerType::Size => {+ self.content_width == other.content_width+ && self.content_height == other.content_height+ && self.font_size == other.font_size+ }+ }+ }+}++#[derive(Clone, Debug, Default, PartialEq)]+pub(crate) struct ContainerSnapshot {+ pub(crate) boxes: HashMap<NodeId, ContainerBox>,+ pub(crate) root_font_size: f32,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum ContainerQueryTruth {+ True,+ False,+ Unknown,+}++impl ContainerQueryTruth {+ fn and(self, other: Self) -> Self {+ match (self, other) {+ (Self::False, _) | (_, Self::False) => Self::False,+ (Self::True, Self::True) => Self::True,+ _ => Self::Unknown,+ }+ }++ fn or(self, other: Self) -> Self {+ match (self, other) {+ (Self::True, _) | (_, Self::True) => Self::True,+ (Self::False, Self::False) => Self::False,+ _ => Self::Unknown,+ }+ }++ fn not(self) -> Self {+ match self {+ Self::True => Self::False,+ Self::False => Self::True,+ Self::Unknown => Self::Unknown,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+enum ContainerQuerySubjectKind {+ Element,+ OriginatingPseudo,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+struct ContainerQueryCacheKey {+ subject: NodeId,+ condition: ContainerConditionId,+ kind: ContainerQuerySubjectKind,+}++#[derive(Clone, Debug, PartialEq, Eq)]+struct ContainerQueryDecision {+ truth: ContainerQueryTruth,+ selected_containers: Vec<Option<NodeId>>,+}++#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub(crate) struct ContainerDecisionSignature {+ decisions: HashMap<ContainerQueryCacheKey, ContainerQueryDecision>,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub(crate) struct ContainerQueryStats {+ pub(crate) evaluations: usize,+ pub(crate) cache_hits: usize,+ pub(crate) ancestor_steps: usize,+}++pub(crate) struct ContainerQueryEvaluator<'a> {+ tree: &'a DomTree,+ snapshot: &'a ContainerSnapshot,+ cache: HashMap<ContainerQueryCacheKey, ContainerQueryDecision>,+ stats: ContainerQueryStats,+}++impl<'a> ContainerQueryEvaluator<'a> {+ pub(crate) fn new(tree: &'a DomTree, snapshot: &'a ContainerSnapshot) -> Self {+ Self {+ tree,+ snapshot,+ cache: HashMap::new(),+ stats: ContainerQueryStats::default(),+ }+ }++ pub(crate) fn finish(self) -> (ContainerDecisionSignature, ContainerQueryStats) {+ (+ ContainerDecisionSignature {+ decisions: self.cache,+ },+ self.stats,+ )+ }++ fn condition_matches(+ &mut self,+ sheet: &Stylesheet,+ subject: NodeId,+ condition: ContainerConditionId,+ kind: ContainerQuerySubjectKind,+ ) -> bool {+ self.evaluate_condition_chain(sheet, subject, condition, kind).truth+ == ContainerQueryTruth::True+ }++ fn evaluate_condition_chain(+ &mut self,+ sheet: &Stylesheet,+ subject: NodeId,+ condition: ContainerConditionId,+ kind: ContainerQuerySubjectKind,+ ) -> ContainerQueryDecision {+ if condition == ContainerConditionId::NONE {+ return ContainerQueryDecision {+ truth: ContainerQueryTruth::True,+ selected_containers: Vec::new(),+ };+ }+ let key = ContainerQueryCacheKey {+ subject,+ condition,+ kind,+ };+ if let Some(decision) = self.cache.get(&key) {+ self.stats.cache_hits += 1;+ return decision.clone();+ }+ self.stats.evaluations += 1;+ let node = &sheet.container_conditions[condition.0 as usize];+ let mut own_truth = ContainerQueryTruth::False;+ let mut selected_containers = Vec::with_capacity(node.alternatives.len());+ for query in &node.alternatives {+ let (truth, selected) = self.evaluate_query(subject, kind, query);+ own_truth = own_truth.or(truth);+ selected_containers.push(selected);+ if own_truth == ContainerQueryTruth::True {+ break;+ }+ }+ if own_truth == ContainerQueryTruth::False {+ let decision = ContainerQueryDecision {+ truth: ContainerQueryTruth::False,+ selected_containers,+ };+ self.cache.insert(key, decision.clone());+ return decision;+ }+ let parent =+ self.evaluate_condition_chain(sheet, subject, node.parent, kind);+ selected_containers.extend(parent.selected_containers);+ let decision = ContainerQueryDecision {+ truth: own_truth.and(parent.truth),+ selected_containers,+ };+ self.cache.insert(key, decision.clone());+ decision+ }++ fn evaluate_query(+ &mut self,+ subject: NodeId,+ kind: ContainerQuerySubjectKind,+ query: &ContainerQuery,+ ) -> (ContainerQueryTruth, Option<NodeId>) {+ let required_axes = query+ .condition+ .as_ref()+ .map(container_query_required_axes)+ .unwrap_or_default();+ let mut candidate = match kind {+ ContainerQuerySubjectKind::Element => {+ self.tree.get_node(subject).and_then(|node| node.parent)+ }+ ContainerQuerySubjectKind::OriginatingPseudo => Some(subject),+ };+ while let Some(id) = candidate {+ self.stats.ancestor_steps += 1;+ let parent = self.tree.get_node(id).and_then(|node| node.parent);+ if let Some(container) = self.snapshot.boxes.get(&id) {+ let supports_axis = match container.container_type {+ crate::ContainerType::Normal => {+ !required_axes.inline && !required_axes.block+ }+ crate::ContainerType::InlineSize => !required_axes.block,+ crate::ContainerType::Size => true,+ };+ let name_matches = query+ .name+ .as_ref()+ .map_or(true, |name| container.names.iter().any(|item| item == name));+ if supports_axis && name_matches {+ let axis_available = match container.available_type {+ crate::ContainerType::Normal => {+ !required_axes.inline && !required_axes.block+ }+ crate::ContainerType::InlineSize => !required_axes.block,+ crate::ContainerType::Size => true,+ };+ if !axis_available {+ return (ContainerQueryTruth::Unknown, Some(id));+ }+ let truth = query.condition.as_ref().map_or(+ ContainerQueryTruth::True,+ |condition| {+ evaluate_container_query_expr(+ condition,+ container,+ self.snapshot.root_font_size,+ )+ },+ );+ return (truth, Some(id));+ }+ }+ candidate = parent;+ }+ (ContainerQueryTruth::False, None)+ }+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+struct ContainerQueryRequiredAxes {+ inline: bool,+ block: bool,+}++fn container_query_required_axes(expr: &ContainerQueryExpr) -> ContainerQueryRequiredAxes {+ match expr {+ ContainerQueryExpr::Feature(feature) => match feature.axis {+ ContainerQueryAxis::Width | ContainerQueryAxis::InlineSize => {+ ContainerQueryRequiredAxes {+ inline: true,+ block: false,+ }+ }+ ContainerQueryAxis::Height | ContainerQueryAxis::BlockSize => {+ ContainerQueryRequiredAxes {+ inline: false,+ block: true,+ }+ }+ },+ ContainerQueryExpr::Unknown => ContainerQueryRequiredAxes::default(),+ ContainerQueryExpr::Not(inner) => container_query_required_axes(inner),+ ContainerQueryExpr::And(items) | ContainerQueryExpr::Or(items) => {+ items.iter().fold(+ ContainerQueryRequiredAxes::default(),+ |mut axes, item| {+ let item = container_query_required_axes(item);+ axes.inline |= item.inline;+ axes.block |= item.block;+ axes+ },+ )+ }+ }+}++fn evaluate_container_query_expr(+ expr: &ContainerQueryExpr,+ container: &ContainerBox,+ root_font_size: f32,+) -> ContainerQueryTruth {+ match expr {+ ContainerQueryExpr::Feature(feature) => {+ let actual = match feature.axis {+ ContainerQueryAxis::Width | ContainerQueryAxis::InlineSize => {+ container.content_width+ }+ ContainerQueryAxis::Height | ContainerQueryAxis::BlockSize => {+ container.content_height+ }+ };+ let threshold = match feature.length {+ ContainerQueryLength::Px(value) => value,+ ContainerQueryLength::Em(value) => value * container.font_size,+ ContainerQueryLength::Rem(value) => value * root_font_size,+ };+ if !actual.is_finite() || !threshold.is_finite() {+ return ContainerQueryTruth::Unknown;+ }+ let matches = match feature.comparison {+ ContainerQueryComparison::Min => actual >= threshold,+ ContainerQueryComparison::Max => actual <= threshold,+ ContainerQueryComparison::GreaterThan => actual > threshold,+ ContainerQueryComparison::LessThan => actual < threshold,+ ContainerQueryComparison::Equal => actual == threshold,+ };+ if matches {+ ContainerQueryTruth::True+ } else {+ ContainerQueryTruth::False+ }+ }+ ContainerQueryExpr::Unknown => ContainerQueryTruth::Unknown,+ ContainerQueryExpr::Not(inner) => {+ evaluate_container_query_expr(inner, container, root_font_size).not()+ }+ ContainerQueryExpr::And(items) => {+ let mut truth = ContainerQueryTruth::True;+ for item in items {+ truth = truth.and(evaluate_container_query_expr(+ item,+ container,+ root_font_size,+ ));+ if truth == ContainerQueryTruth::False {+ break;+ }+ }+ truth+ }+ ContainerQueryExpr::Or(items) => {+ let mut truth = ContainerQueryTruth::False;+ for item in items {+ truth = truth.or(evaluate_container_query_expr(+ item,+ container,+ root_font_size,+ ));+ if truth == ContainerQueryTruth::True {+ break;+ }+ }+ truth+ }+ }+}+/// An indexed set of author rules ready for fast per-element matching.pub struct Stylesheet {rules: Vec<Rule>,@@ -104,9 +486,48 @@ pub struct Stylesheet {impl Stylesheet {/// Until Stage B supplies completed container geometry, preserved/// conditional rules remain inactive rather than using viewport geometry.- fn container_condition_is_active(&self, id: ContainerConditionId) -> bool {+ fn container_condition_is_active(+ &self,+ id: ContainerConditionId,+ subject: NodeId,+ kind: ContainerQuerySubjectKind,+ evaluator: &mut Option<&mut ContainerQueryEvaluator<'_>>,+ ) -> bool {debug_assert!((id.0 as usize) < self.container_conditions.len());- id == ContainerConditionId::NONE+ if id == ContainerConditionId::NONE {+ return true;+ }+ evaluator.as_deref_mut().is_some_and(|evaluator| {+ evaluator.condition_matches(self, subject, id, kind)+ })+ }++ pub(crate) fn has_container_queries(&self) -> bool {+ self.rules+ .iter()+ .any(|rule| rule.container_condition_id != ContainerConditionId::NONE)+ || self+ .before_rules+ .iter()+ .chain(&self.after_rules)+ .any(|rule| rule.container_condition_id != ContainerConditionId::NONE)+ }++ pub(crate) fn container_condition_depth(&self) -> usize {+ self.container_conditions+ .iter()+ .skip(1)+ .map(|node| {+ let mut depth = 1usize;+ let mut parent = node.parent;+ while parent != ContainerConditionId::NONE {+ depth += 1;+ parent = self.container_conditions[parent.0 as usize].parent;+ }+ depth+ })+ .max()+ .unwrap_or(0)}/// Parse and index a set of raw CSS sources (the text of each `<style>`@@ -207,15 +628,60 @@ impl Stylesheet {props: &HashMap<String, String>,host_style: &LayoutStyle,) -> (Option<LayoutStyle>, Option<LayoutStyle>) {- let build = |rules: &[PseudoRule], matcher: &mut Matcher| {- let mut matched: Vec<(u32, usize, &PseudoRule)> = rules- .iter()- .filter(|rule| {- self.container_condition_is_active(rule.container_condition_id)- && matcher.matches(tree, nid, &rule.sel)- })- .map(|rule| (rule.sel.specificity(), rule.order, rule))- .collect();+ self.pseudo_styles_internal(+ tree,+ matcher,+ nid,+ props,+ host_style,+ None,+ )+ }++ pub(crate) fn pseudo_styles_with_container_queries(+ &self,+ tree: &DomTree,+ matcher: &mut Matcher,+ nid: NodeId,+ props: &HashMap<String, String>,+ host_style: &LayoutStyle,+ evaluator: &mut ContainerQueryEvaluator<'_>,+ ) -> (Option<LayoutStyle>, Option<LayoutStyle>) {+ self.pseudo_styles_internal(+ tree,+ matcher,+ nid,+ props,+ host_style,+ Some(evaluator),+ )+ }++ fn pseudo_styles_internal(+ &self,+ tree: &DomTree,+ matcher: &mut Matcher,+ nid: NodeId,+ props: &HashMap<String, String>,+ host_style: &LayoutStyle,+ mut evaluator: Option<&mut ContainerQueryEvaluator<'_>>,+ ) -> (Option<LayoutStyle>, Option<LayoutStyle>) {+ let mut build = |rules: &[PseudoRule], matcher: &mut Matcher| {+ let mut matched: Vec<(u32, usize, &PseudoRule)> = Vec::new();+ for rule in rules {+ // Container lookup is an ancestor walk. Keep it behind the+ // selector match so unrelated pseudo rules remain cheap.+ if matcher.matches(tree, nid, &rule.sel)+ && self.container_condition_is_active(+ rule.container_condition_id,+ nid,+ ContainerQuerySubjectKind::OriginatingPseudo,+ &mut evaluator,+ )+ {+ matched.push((rule.sel.specificity(), rule.order, rule));+ }+ }if matched.is_empty() {return None;}@@ -307,6 +773,60 @@ impl Stylesheet {style: &mut LayoutStyle,parent_props: &HashMap<String, String>,inline_css: Option<&str>,+ ) -> Option<HashMap<String, String>> {+ self.apply_internal(+ tree,+ matcher,+ nid,+ id,+ classes,+ local,+ style,+ parent_props,+ inline_css,+ None,+ )+ }++ pub(crate) fn apply_with_container_queries(+ &self,+ tree: &DomTree,+ matcher: &mut Matcher,+ nid: NodeId,+ id: Option<&str>,+ classes: &[String],+ local: &str,+ style: &mut LayoutStyle,+ parent_props: &HashMap<String, String>,+ inline_css: Option<&str>,+ evaluator: &mut ContainerQueryEvaluator<'_>,+ ) -> Option<HashMap<String, String>> {+ self.apply_internal(+ tree,+ matcher,+ nid,+ id,+ classes,+ local,+ style,+ parent_props,+ inline_css,+ Some(evaluator),+ )+ }++ fn apply_internal(+ &self,+ tree: &DomTree,+ matcher: &mut Matcher,+ nid: NodeId,+ id: Option<&str>,+ classes: &[String],+ local: &str,+ style: &mut LayoutStyle,+ parent_props: &HashMap<String, String>,+ inline_css: Option<&str>,+ mut evaluator: Option<&mut ContainerQueryEvaluator<'_>>,) -> Option<HashMap<String, String>> {// (specificity, order, rule index) for each matching rule.let mut matched: Vec<(u32, usize, usize)> = Vec::new();@@ -314,8 +834,15 @@ impl Stylesheet {if let Some(idxs) = bucket {for &i in idxs {let rule = &self.rules[i];- if self.container_condition_is_active(rule.container_condition_id)- && matcher.matches(tree, nid, &rule.sel)+ // Container lookup is an ancestor walk. Keep it behind+ // selector matching and cache the result per condition.+ if matcher.matches(tree, nid, &rule.sel)+ && self.container_condition_is_active(+ rule.container_condition_id,+ nid,+ ContainerQuerySubjectKind::Element,+ &mut evaluator,+ ){matched.push((rule.sel.specificity(), rule.order, i));}@@ -849,45 +1376,54 @@ fn parse_stylesheet_for_viewport_preserving_containers(/// the inner rules only when the query holds for a desktop 1280px viewport.fn flush_at_rule(at: &str,- sel: &str,+ _sel: &str,inner: &str,rules: &mut Vec<ParsedRule>,viewport: (f32, f32),container_conditions: &mut Vec<ContainerConditionNode>,container_condition_id: ContainerConditionId,) {- if at.starts_with("media") {- if media_query_applies_for_viewport(sel, viewport) {+ if let Some(prelude) = at_rule_prelude(at, "media") {+ if media_query_applies_for_viewport(prelude, viewport) {rules.extend(parse_stylesheet_for_viewport_preserving_containers(- inner, viewport, container_conditions, container_condition_id,+ inner,+ viewport,+ container_conditions,+ container_condition_id,));}- } else if at.starts_with("supports") {- if supports_condition_applies(sel) {+ } else if let Some(prelude) = at_rule_prelude(at, "supports") {+ if supports_condition_applies(prelude) {rules.extend(parse_stylesheet_for_viewport_preserving_containers(- inner, viewport, container_conditions, container_condition_id,+ inner,+ viewport,+ container_conditions,+ container_condition_id,));}- } else if at.starts_with("container") {- let prelude = at["container".len()..].trim();+ } else if let Some(prelude) = at_rule_prelude(at, "container") {if let Some(alternatives) = parse_container_query_list(prelude) {- let Ok(raw_id) = u32::try_from(container_conditions.len()) else { return };+ let Ok(raw_id) = u32::try_from(container_conditions.len()) else {+ return;+ };let id = ContainerConditionId(raw_id);container_conditions.push(ContainerConditionNode {parent: container_condition_id,alternatives,});rules.extend(parse_stylesheet_for_viewport_preserving_containers(- inner, viewport, container_conditions, id,+ inner,+ viewport,+ container_conditions,+ id,));}- } else if at.starts_with("property") {+ } else if let Some(name) = at_rule_prelude(at, "property") {// `@property --x { syntax:..; initial-value: V }` declares a custom// property and its default. Register the initial-value as a `:root`// declaration so `var(--x)` resolves when nothing else sets it. Tailwind// v4 and modern frameworks define theme tokens this way; dropping them// left those `var()`s (page/section backgrounds, colors) unresolved.- let name = at["property".len()..].trim();if name.starts_with("--") {for decl in inner.split(';') {if let Some((k, v)) = decl.split_once(':') {@@ -895,13 +1431,16 @@ fn flush_at_rule(rules.push(ParsedRule {selector: ":root".to_string(),declarations: format!("{}: {}", name, v.trim()),- container_condition_id,+ // Registrations are global name-defining rules.+ // CSS Conditional 5 deliberately does not gate+ // them on an enclosing container query.+ container_condition_id: ContainerConditionId::NONE,});}}}}- } else if at.starts_with("layer") {+ } else if at_rule_prelude(at, "layer").is_some() {// Cascade layers: `@layer name { ... }` wraps ordinary rules. We do not// model layer priority (real CSS ranks unlayered above layered and// later layers above earlier); just flatten the body in source order so@@ -912,13 +1451,43 @@ fn flush_at_rule(// `@layer a, b;` ordering-statement form has no block and is discarded// by parse_stylesheet's top-level `;` handling.rules.extend(parse_stylesheet_for_viewport_preserving_containers(- inner, viewport, container_conditions, container_condition_id,+ inner,+ viewport,+ container_conditions,+ container_condition_id,));}// Other at-rules (@font-face, @keyframes, @import, ...) carry no// layout-relevant rules for us, so drop them.}+/// Return the prelude after an exact ASCII-insensitive at-rule name.+///+/// The hand parser stores the text after `@`, so a prefix test would both+/// reject `@CONTAINER` and misclassify unknown rules such as+/// `@containerfoo`. The boundary accepts punctuation because whitespace is+/// optional before a parenthesized prelude.+fn at_rule_prelude<'a>(at: &'a str, expected: &str) -> Option<&'a str> {+ let prefix = at.get(..expected.len())?;+ if !prefix.eq_ignore_ascii_case(expected) {+ return None;+ }+ let rest = &at[expected.len()..];+ if rest.chars().next().is_some_and(|character| {+ character.is_ascii_alphanumeric()+ || matches!(character, '_' | '-' | '\\')+ || !character.is_ascii()+ }) {+ return None;+ }+ let mut rest = rest.trim_start();+ while let Some(comment) = rest.strip_prefix("/*") {+ let end = comment.find("*/")?;+ rest = comment[end + 2..].trim_start();+ }+ Some(rest.trim_end())+}+fn parse_container_query_list(prelude: &str) -> Option<Vec<ContainerQuery>> {let queries = split_media_query_list(prelude).into_iter()@@ -958,31 +1527,90 @@ fn parse_container_query_name(input: &str) -> Option<String> {return None;}let lower = ident.to_ascii_lowercase();- if matches!(lower.as_str(), "none" | "not" | "and" | "or") {+ if is_reserved_container_custom_ident(&lower) {return None;}Some(ident.to_string())}+fn is_reserved_container_custom_ident(lower: &str) -> bool {+ matches!(+ lower,+ "none"+ | "not"+ | "and"+ | "or"+ | "default"+ | "initial"+ | "inherit"+ | "unset"+ | "revert"+ | "revert-layer"+ )+}++const MAX_CONTAINER_QUERY_DEPTH: usize = 64;+fn parse_container_query_expr(input: &str) -> Option<ContainerQueryExpr> {+ parse_container_query_expr_at_depth(input, 0)+}++fn parse_container_query_expr_at_depth(input: &str, depth: usize) -> Option<ContainerQueryExpr> {+ if depth >= MAX_CONTAINER_QUERY_DEPTH {+ return None;+ }let input = input.trim();- if let Some(parts) = split_supports_operator(input, "or") {+ let or_parts = split_supports_operator(input, "or");+ let and_parts = split_supports_operator(input, "and");+ // One grammar level is either a homogeneous AND chain or a homogeneous OR+ // chain. Authors must parenthesize any mixture.+ if or_parts.is_some() && and_parts.is_some() {+ return None;+ }+ if let Some(parts) = or_parts {return Some(ContainerQueryExpr::Or(- parts.into_iter().map(parse_container_query_expr).collect::<Option<_>>()?,+ parts+ .into_iter()+ .map(|part| parse_container_query_in_parens(part, depth + 1))+ .collect::<Option<_>>()?,));}- if let Some(parts) = split_supports_operator(input, "and") {+ if let Some(parts) = and_parts {return Some(ContainerQueryExpr::And(- parts.into_iter().map(parse_container_query_expr).collect::<Option<_>>()?,+ parts+ .into_iter()+ .map(|part| parse_container_query_in_parens(part, depth + 1))+ .collect::<Option<_>>()?,));}if let Some(rest) = strip_ascii_keyword(input, "not") {- return Some(ContainerQueryExpr::Not(Box::new(parse_container_query_expr(rest)?)));+ return Some(ContainerQueryExpr::Not(Box::new(+ parse_container_query_in_parens(rest, depth + 1)?,+ )));+ }+ parse_container_query_in_parens(input, depth + 1)+}++fn parse_container_query_in_parens(input: &str, depth: usize) -> Option<ContainerQueryExpr> {+ if depth >= MAX_CONTAINER_QUERY_DEPTH {+ return None;}let inner = enclosing_parenthesized(input)?;- parse_container_size_feature(inner)- .map(ContainerQueryExpr::Feature)- .or_else(|| parse_container_query_expr(inner))+ if let Some(feature) = parse_container_size_feature(inner) {+ return Some(feature);+ }+ parse_container_query_expr_at_depth(inner, depth + 1).or_else(|| {+ is_general_enclosed_container_query(inner).then_some(ContainerQueryExpr::Unknown)+ })+}++fn is_general_enclosed_container_query(input: &str) -> bool {+ let mut input = cssparser::ParserInput::new(input.trim());+ let mut parser = cssparser::Parser::new(&mut input);+ matches!(+ parser.next(),+ Ok(cssparser::Token::Ident(_)) | Ok(cssparser::Token::Function(_))+ )}fn strip_ascii_keyword<'a>(input: &'a str, keyword: &str) -> Option<&'a str> {@@ -995,20 +1623,129 @@ fn strip_ascii_keyword<'a>(input: &'a str, keyword: &str) -> Option<&'a str> {.map(|_| rest.trim_start())}-fn parse_container_size_feature(input: &str) -> Option<ContainerSizeFeature> {- let (name, value) = input.split_once(':')?;- let (comparison, axis) = match name.trim().to_ascii_lowercase().as_str() {- "min-width" => (ContainerQueryComparison::Min, ContainerQueryAxis::Width),- "max-width" => (ContainerQueryComparison::Max, ContainerQueryAxis::Width),- "min-inline-size" => (ContainerQueryComparison::Min, ContainerQueryAxis::InlineSize),- "max-inline-size" => (ContainerQueryComparison::Max, ContainerQueryAxis::InlineSize),- _ => return None,- };- Some(ContainerSizeFeature {- axis,- comparison,- length: parse_container_query_length(value)?,- })+fn parse_container_size_feature(input: &str) -> Option<ContainerQueryExpr> {+ if let Some(axis) = parse_container_query_axis(input) {+ return Some(ContainerQueryExpr::Feature(ContainerSizeFeature {+ axis,+ comparison: ContainerQueryComparison::GreaterThan,+ length: ContainerQueryLength::Px(0.0),+ }));+ }+ if let Some((name, value)) = input.split_once(':') {+ let (comparison, axis) = match name.trim().to_ascii_lowercase().as_str() {+ "min-width" => (ContainerQueryComparison::Min, ContainerQueryAxis::Width),+ "max-width" => (ContainerQueryComparison::Max, ContainerQueryAxis::Width),+ "width" => (ContainerQueryComparison::Equal, ContainerQueryAxis::Width),+ "min-height" => (ContainerQueryComparison::Min, ContainerQueryAxis::Height),+ "max-height" => (ContainerQueryComparison::Max, ContainerQueryAxis::Height),+ "height" => (ContainerQueryComparison::Equal, ContainerQueryAxis::Height),+ "min-inline-size" => (ContainerQueryComparison::Min, ContainerQueryAxis::InlineSize),+ "max-inline-size" => (ContainerQueryComparison::Max, ContainerQueryAxis::InlineSize),+ "inline-size" => (ContainerQueryComparison::Equal, ContainerQueryAxis::InlineSize),+ "min-block-size" => (ContainerQueryComparison::Min, ContainerQueryAxis::BlockSize),+ "max-block-size" => (ContainerQueryComparison::Max, ContainerQueryAxis::BlockSize),+ "block-size" => (ContainerQueryComparison::Equal, ContainerQueryAxis::BlockSize),+ _ => return None,+ };+ return Some(ContainerQueryExpr::Feature(ContainerSizeFeature {+ axis,+ comparison,+ length: parse_container_query_length(value)?,+ }));+ }++ let (operands, operators) = split_container_range(input)?;+ let make_feature =+ |axis: ContainerQueryAxis, operator: &str, value: &str, axis_on_left: bool| {+ let comparison = match (operator, axis_on_left) {+ (">=", true) | ("<=", false) => ContainerQueryComparison::Min,+ ("<=", true) | (">=", false) => ContainerQueryComparison::Max,+ (">", true) | ("<", false) => ContainerQueryComparison::GreaterThan,+ ("<", true) | (">", false) => ContainerQueryComparison::LessThan,+ ("=", _) => ContainerQueryComparison::Equal,+ _ => return None,+ };+ Some(ContainerQueryExpr::Feature(ContainerSizeFeature {+ axis,+ comparison,+ length: parse_container_query_length(value)?,+ }))+ };+ match (operands.as_slice(), operators.as_slice()) {+ ([left, right], [operator]) => {+ if let Some(axis) = parse_container_query_axis(left) {+ make_feature(axis, operator, right, true)+ } else {+ let axis = parse_container_query_axis(right)?;+ make_feature(axis, operator, left, false)+ }+ }+ ([lower, middle, upper], [lower_operator, upper_operator]) => {+ // Chained ranges must point consistently through the feature:+ // `10px < width <= 20px` or the fully reversed equivalent.+ // Equality is valid only in a single comparison, and a mixed+ // direction such as `10px < width > 20px` is not a range.+ let forward = matches!(*lower_operator, "<" | "<=")+ && matches!(*upper_operator, "<" | "<=");+ let reverse = matches!(*lower_operator, ">" | ">=")+ && matches!(*upper_operator, ">" | ">=");+ if !forward && !reverse {+ return None;+ }+ let axis = parse_container_query_axis(middle)?;+ Some(ContainerQueryExpr::And(vec![+ make_feature(axis, lower_operator, lower, false)?,+ make_feature(axis, upper_operator, upper, true)?,+ ]))+ }+ _ => None,+ }+}++fn parse_container_query_axis(input: &str) -> Option<ContainerQueryAxis> {+ match input.trim().to_ascii_lowercase().as_str() {+ "width" => Some(ContainerQueryAxis::Width),+ "height" => Some(ContainerQueryAxis::Height),+ "inline-size" => Some(ContainerQueryAxis::InlineSize),+ "block-size" => Some(ContainerQueryAxis::BlockSize),+ _ => None,+ }+}++fn split_container_range(input: &str) -> Option<(Vec<&str>, Vec<&str>)> {+ let mut operands = Vec::new();+ let mut operators = Vec::new();+ let mut start = 0usize;+ let bytes = input.as_bytes();+ let mut index = 0usize;+ while index < bytes.len() {+ if matches!(bytes[index], b'<' | b'>' | b'=') {+ let end = if bytes.get(index + 1) == Some(&b'=') {+ index + 2+ } else {+ index + 1+ };+ let operand = input[start..index].trim();+ if operand.is_empty() {+ return None;+ }+ operands.push(operand);+ operators.push(&input[index..end]);+ start = end;+ index = end;+ continue;+ }+ index += 1;+ }+ if operators.is_empty() || operators.len() > 2 {+ return None;+ }+ let operand = input[start..].trim();+ if operand.is_empty() {+ return None;+ }+ operands.push(operand);+ Some((operands, operators))}fn parse_container_query_length(input: &str) -> Option<ContainerQueryLength> {@@ -1463,16 +2200,29 @@ fn denest(let pre = prelude.trim();if let Some(at) = pre.strip_prefix('@') {// A nested at-rule keeps the enclosing selector for its body.- if at.starts_with("media") {- if media_query_applies_for_viewport(pre, viewport) {- denest(sel, &inner, rules, viewport, container_conditions, container_condition_id);+ if let Some(prelude) = at_rule_prelude(at, "media") {+ if media_query_applies_for_viewport(prelude, viewport) {+ denest(+ sel,+ &inner,+ rules,+ viewport,+ container_conditions,+ container_condition_id,+ );}- } else if at.starts_with("supports") {- if supports_condition_applies(pre) {- denest(sel, &inner, rules, viewport, container_conditions, container_condition_id);+ } else if let Some(prelude) = at_rule_prelude(at, "supports") {+ if supports_condition_applies(prelude) {+ denest(+ sel,+ &inner,+ rules,+ viewport,+ container_conditions,+ container_condition_id,+ );}- } else if at.starts_with("container") {- let prelude = at["container".len()..].trim();+ } else if let Some(prelude) = at_rule_prelude(at, "container") {if let Some(alternatives) = parse_container_query_list(prelude) {if let Ok(raw_id) = u32::try_from(container_conditions.len()) {let id = ContainerConditionId(raw_id);@@ -1483,8 +2233,15 @@ fn denest(denest(sel, &inner, rules, viewport, container_conditions, id);}}- } else if at.starts_with("layer") {- denest(sel, &inner, rules, viewport, container_conditions, container_condition_id);+ } else if at_rule_prelude(at, "layer").is_some() {+ denest(+ sel,+ &inner,+ rules,+ viewport,+ container_conditions,+ container_condition_id,+ );}} else if !pre.is_empty() {let full = combine_selectors(sel, pre);@@ -1849,6 +2606,649 @@ mod tests {assert_eq!(parse_stylesheet(css).len(), 1);}+ #[test]+ fn container_at_rule_keyword_is_ascii_insensitive_and_exact() {+ assert_eq!(+ at_rule_prelude("CoNtAiNeR (min-width:1px)", "container"),+ Some("(min-width:1px)")+ );+ assert_eq!(+ at_rule_prelude("container/**/(min-width:1px)", "container"),+ Some("(min-width:1px)")+ );+ assert!(at_rule_prelude("containerfoo (min-width:1px)", "container").is_none());+ assert!(at_rule_prelude("container-type (min-width:1px)", "container").is_none());++ let css = r#"+ @CONTAINER (min-width:1px) {+ .top-level { width:1px }+ }+ .host {+ @CoNtAiNeR (min-width:2px) { width:2px }+ @containerfoo (min-width:3px) { height:3px }+ }+ .comment-host {+ @CONTAINER/**/(min-width:5px) { height:5px }+ }+ @containerfoo (min-width:4px) {+ .unknown-prefix { width:4px }+ }+ "#;+ let mut conditions = condition_arena_root();+ let parsed = parse_stylesheet_for_viewport_preserving_containers(+ css,+ (1280.0, 720.0),+ &mut conditions,+ ContainerConditionId::NONE,+ );+ assert_eq!(conditions.len(), 4);+ assert_eq!(parsed.len(), 3, "unknown prefix at-rules must be dropped");+ assert!(parsed.iter().any(|rule| rule.selector == ".top-level"));+ assert!(parsed+ .iter()+ .any(|rule| { rule.selector == ".host" && rule.declarations.contains("width:2px") }));+ assert!(parsed.iter().any(|rule| {+ rule.selector == ".comment-host" && rule.declarations.contains("height:5px")+ }));+ assert!(!parsed.iter().any(|rule| {+ rule.selector == ".unknown-prefix" || rule.declarations.contains("height:3px")+ }));+ }++ #[test]+ fn global_at_rules_inside_container_are_not_conditioned() {+ let css = r#"+ @container (min-width:10000px) {+ @property --cq-token {+ syntax: "<length>";+ inherits: false;+ initial-value: 17px;+ }+ .conditional { width:999px }+ }+ "#;+ let mut conditions = condition_arena_root();+ let parsed = parse_stylesheet_for_viewport_preserving_containers(+ css,+ (1280.0, 720.0),+ &mut conditions,+ ContainerConditionId::NONE,+ );+ assert_eq!(conditions.len(), 2);+ let registration = parsed+ .iter()+ .find(|rule| rule.selector == ":root")+ .expect("@property initial value should be registered");+ assert_eq!(+ registration.container_condition_id,+ ContainerConditionId::NONE+ );+ assert!(registration.declarations.contains("--cq-token: 17px"));+ let conditional = parsed+ .iter()+ .find(|rule| rule.selector == ".conditional")+ .expect("ordinary conditional rule should remain indexed");+ assert_eq!(conditional.container_condition_id, ContainerConditionId(1));+ assert_eq!(+ parse_stylesheet(css),+ vec![(":root".into(), "--cq-token: 17px".into())]+ );+ }++ #[test]+ fn container_boolean_grammar_rejects_mixed_operators() {+ for invalid in [+ "(min-width:1px) and (max-width:2px) or (min-inline-size:3px)",+ "not (min-width:1px) and (max-width:2px)",+ "(min-width:1px) or not (max-width:2px)",+ ] {+ assert!(+ parse_container_query_expr(invalid).is_none(),+ "invalid boolean grammar was accepted: {invalid}"+ );+ }+ assert!(matches!(+ parse_container_query_expr(+ "(min-width:1px) and ((max-width:2px) or (min-inline-size:3px))"+ ),+ Some(ContainerQueryExpr::And(_))+ ));+ assert!(matches!(+ parse_container_query_expr("not ((min-width:1px) and (max-inline-size:2px))"),+ Some(ContainerQueryExpr::Not(_))+ ));+ }++ #[test]+ fn container_custom_ident_rejects_css_wide_and_default() {+ for reserved in [+ "none",+ "not",+ "and",+ "or",+ "default",+ "initial",+ "inherit",+ "unset",+ "revert",+ "revert-layer",+ ] {+ assert!(+ parse_container_query_name(reserved).is_none(),+ "reserved custom-ident was accepted: {reserved}"+ );+ if reserved != "not" {+ assert!(+ parse_container_query(&format!("{reserved} (min-width:1px)")).is_none(),+ "reserved query name was accepted: {reserved}"+ );+ }+ }+ assert!(+ matches!(+ parse_container_query("not (min-width:1px)"),+ Some(ContainerQuery {+ name: None,+ condition: Some(ContainerQueryExpr::Not(_)),+ })+ ),+ "`not` is reserved as a name but valid as the unary query operator"+ );+ for valid in ["auto", "normal", "container", "--card", "main"] {+ assert_eq!(+ parse_container_query_name(valid).as_deref(),+ Some(valid),+ "valid query name was rejected: {valid}"+ );+ }+ }++ #[test]+ fn unknown_comma_arm_does_not_drop_supported_arm() {+ let queries = parse_container_query_list("(future(foo)), main (min-width:1px)")+ .expect("general-enclosed arm is valid unknown syntax");+ assert_eq!(queries.len(), 2);+ assert_eq!(queries[0].condition, Some(ContainerQueryExpr::Unknown));+ assert_eq!(queries[1].name.as_deref(), Some("main"));+ assert!(matches!(+ queries[1].condition,+ Some(ContainerQueryExpr::Feature(_))+ ));++ let mut conditions = condition_arena_root();+ let parsed = parse_stylesheet_for_viewport_preserving_containers(+ "@container (future(foo)), main (min-width:1px) {.card{display:grid}}",+ (1280.0, 720.0),+ &mut conditions,+ ContainerConditionId::NONE,+ );+ assert_eq!(parsed.len(), 1);+ assert_eq!(conditions[1].alternatives.len(), 2);+ }++ #[test]+ fn container_query_recursion_depth_is_bounded() {+ let nested = format!(+ "{}min-width:1px{}",+ "(".repeat(MAX_CONTAINER_QUERY_DEPTH + 16),+ ")".repeat(MAX_CONTAINER_QUERY_DEPTH + 16)+ );+ assert!(parse_container_query_expr(&nested).is_none());+ }++ #[test]+ fn supports_accepts_container_css_wide_values() {+ for property in ["container", "container-name", "container-type"] {+ for keyword in ["initial", "inherit", "unset", "revert", "revert-layer"] {+ assert!(+ supports_condition_applies(&format!("({property}:{keyword})")),+ "{property}:{keyword} is a valid whole-value CSS-wide declaration"+ );+ }+ }+ }++ fn evaluate_container_styles(+ tree: &DomTree,+ sheet: &Stylesheet,+ target: NodeId,+ snapshot: &ContainerSnapshot,+ ) -> (LayoutStyle, ContainerDecisionSignature, ContainerQueryStats) {+ let node = tree.get_node(target).unwrap();+ let element = node.as_element().unwrap();+ let id = node.get_attribute("id");+ let classes: Vec<String> = node+ .get_attribute("class")+ .map(|value| value.split_whitespace().map(str::to_string).collect())+ .unwrap_or_default();+ let mut matcher = tree.matcher();+ let mut evaluator = ContainerQueryEvaluator::new(tree, snapshot);+ let mut style = LayoutStyle::default();+ sheet.apply_with_container_queries(+ tree,+ &mut matcher,+ target,+ id,+ &classes,+ element.local.as_ref(),+ &mut style,+ &HashMap::new(),+ None,+ &mut evaluator,+ );+ let (signature, stats) = evaluator.finish();+ (style, signature, stats)+ }++ fn container_box(+ container_type: crate::ContainerType,+ names: &[&str],+ content_width: f32,+ font_size: f32,+ ) -> ContainerBox {+ ContainerBox {+ container_type,+ available_type: container_type,+ names: names.iter().map(|name| (*name).to_string()).collect(),+ content_width,+ content_height: 100.0,+ font_size,+ }+ }++ #[test]+ fn container_evaluator_honors_tailwind_threshold_and_cache() {+ let tree = obscura_dom::parse_html(+ r#"<div id="container"><div id="target"></div></div>"#,+ );+ let container = tree.get_element_by_id("container").unwrap();+ let target = tree.get_element_by_id("target").unwrap();+ let sheet = Stylesheet::parse(+ &tree,+ &[r#"+ #target { width:1px; height:1px }+ @container (min-width:28rem) {+ #target { width:2px }+ #target { height:2px }+ }+ "#+ .to_string()],+ );++ let snapshot = |width| {+ let mut snapshot = ContainerSnapshot {+ root_font_size: 16.0,+ ..Default::default()+ };+ snapshot.boxes.insert(+ container,+ container_box(crate::ContainerType::InlineSize, &[], width, 16.0),+ );+ snapshot+ };+ let (below, _, _) =+ evaluate_container_styles(&tree, &sheet, target, &snapshot(447.0));+ assert_eq!(below.width, crate::Dimension::Px(1.0));+ assert_eq!(below.height, crate::Dimension::Px(1.0));++ let (at, _, stats) =+ evaluate_container_styles(&tree, &sheet, target, &snapshot(448.0));+ assert_eq!(at.width, crate::Dimension::Px(2.0));+ assert_eq!(at.height, crate::Dimension::Px(2.0));+ assert_eq!(stats.evaluations, 1);+ assert!(stats.cache_hits >= 1);+ }++ #[test]+ fn container_evaluator_matches_selector_before_ancestor_lookup() {+ let tree = obscura_dom::parse_html(+ r#"<div id="container"><div id="target"></div></div>"#,+ );+ let container = tree.get_element_by_id("container").unwrap();+ let target = tree.get_element_by_id("target").unwrap();+ let sheet = Stylesheet::parse(+ &tree,+ &[r#"+ @container (min-width:1px) {+ div[data-never-present] { width:999px }+ }+ "#+ .to_string()],+ );+ let mut snapshot = ContainerSnapshot {+ root_font_size: 16.0,+ ..Default::default()+ };+ snapshot.boxes.insert(+ container,+ container_box(crate::ContainerType::InlineSize, &[], 500.0, 16.0),+ );+ let (_, signature, stats) =+ evaluate_container_styles(&tree, &sheet, target, &snapshot);+ assert_eq!(stats.evaluations, 0);+ assert_eq!(stats.ancestor_steps, 0);+ assert!(signature.decisions.is_empty());+ }++ #[test]+ fn container_evaluator_selects_nearest_eligible_named_ancestor() {+ let tree = obscura_dom::parse_html(+ r#"<div id="outer"><div id="inner"><div id="target"></div></div></div>"#,+ );+ let outer = tree.get_element_by_id("outer").unwrap();+ let inner = tree.get_element_by_id("inner").unwrap();+ let target = tree.get_element_by_id("target").unwrap();+ let sheet = Stylesheet::parse(+ &tree,+ &[r#"+ #target { width:1px; height:1px }+ @container shell (min-width:500px) { #target { width:11px } }+ @container (min-width:500px) { #target { height:22px } }+ "#+ .to_string()],+ );+ let mut snapshot = ContainerSnapshot {+ root_font_size: 16.0,+ ..Default::default()+ };+ snapshot.boxes.insert(+ outer,+ container_box(+ crate::ContainerType::InlineSize,+ &["shell"],+ 600.0,+ 16.0,+ ),+ );+ snapshot.boxes.insert(+ inner,+ container_box(+ crate::ContainerType::InlineSize,+ &["other"],+ 300.0,+ 16.0,+ ),+ );+ let (style, _, stats) =+ evaluate_container_styles(&tree, &sheet, target, &snapshot);+ assert_eq!(style.width, crate::Dimension::Px(11.0));+ assert_eq!(style.height, crate::Dimension::Px(1.0));+ assert!(stats.ancestor_steps >= 3);+ }++ #[test]+ fn container_query_em_uses_container_font_and_rem_uses_root_font() {+ let tree = obscura_dom::parse_html(+ r#"<div id="container"><div id="target"></div></div>"#,+ );+ let container = tree.get_element_by_id("container").unwrap();+ let target = tree.get_element_by_id("target").unwrap();+ let sheet = Stylesheet::parse(+ &tree,+ &[r#"+ #target { width:1px; height:1px }+ @container (min-width:30em) { #target { width:3px } }+ @container (min-width:30rem) { #target { height:3px } }+ "#+ .to_string()],+ );+ let mut snapshot = ContainerSnapshot {+ root_font_size: 20.0,+ ..Default::default()+ };+ snapshot.boxes.insert(+ container,+ container_box(crate::ContainerType::InlineSize, &[], 400.0, 10.0),+ );+ let (style, _, _) =+ evaluate_container_styles(&tree, &sheet, target, &snapshot);+ assert_eq!(style.width, crate::Dimension::Px(3.0));+ assert_eq!(style.height, crate::Dimension::Px(1.0));+ }++ #[test]+ fn container_snapshot_compares_only_axes_exposed_by_container_type() {+ let mut inline_a =+ container_box(crate::ContainerType::InlineSize, &[], 400.0, 16.0);+ let mut inline_b = inline_a.clone();+ inline_a.content_height = 100.0;+ inline_b.content_height = 900.0;+ assert_eq!(inline_a, inline_b);++ let mut size_a = container_box(crate::ContainerType::Size, &[], 400.0, 16.0);+ let mut size_b = size_a.clone();+ size_a.content_height = 100.0;+ size_b.content_height = 900.0;+ assert_ne!(size_a, size_b);+ }++ #[test]+ fn nested_container_conditions_select_independent_containers() {+ let tree = obscura_dom::parse_html(+ r#"<div id="outer"><div id="inner"><div id="target"></div></div></div>"#,+ );+ let outer = tree.get_element_by_id("outer").unwrap();+ let inner = tree.get_element_by_id("inner").unwrap();+ let target = tree.get_element_by_id("target").unwrap();+ let sheet = Stylesheet::parse(+ &tree,+ &[r#"+ #target { width:1px }+ @container outer (min-width:500px) {+ @container inner (min-width:200px) {+ #target { width:9px }+ }+ }+ "#+ .to_string()],+ );+ let snapshot = |inner_width| {+ let mut snapshot = ContainerSnapshot {+ root_font_size: 16.0,+ ..Default::default()+ };+ snapshot.boxes.insert(+ outer,+ container_box(+ crate::ContainerType::InlineSize,+ &["outer"],+ 600.0,+ 16.0,+ ),+ );+ snapshot.boxes.insert(+ inner,+ container_box(+ crate::ContainerType::InlineSize,+ &["inner"],+ inner_width,+ 16.0,+ ),+ );+ snapshot+ };+ let (matching, _, _) =+ evaluate_container_styles(&tree, &sheet, target, &snapshot(200.0));+ assert_eq!(matching.width, crate::Dimension::Px(9.0));+ let (failing, _, _) =+ evaluate_container_styles(&tree, &sheet, target, &snapshot(199.0));+ assert_eq!(failing.width, crate::Dimension::Px(1.0));+ }++ #[test]+ fn unknown_container_alternative_does_not_mask_true_alternative() {+ let tree = obscura_dom::parse_html(+ r#"<div id="container"><div id="target"></div></div>"#,+ );+ let container = tree.get_element_by_id("container").unwrap();+ let target = tree.get_element_by_id("target").unwrap();+ let sheet = Stylesheet::parse(+ &tree,+ &[r#"+ #target { width:1px }+ @container (future(foo)), (min-width:100px) {+ #target { width:7px }+ }+ "#+ .to_string()],+ );+ let mut snapshot = ContainerSnapshot {+ root_font_size: 16.0,+ ..Default::default()+ };+ snapshot.boxes.insert(+ container,+ container_box(crate::ContainerType::InlineSize, &[], 100.0, 16.0),+ );+ let (style, _, _) =+ evaluate_container_styles(&tree, &sheet, target, &snapshot);+ assert_eq!(style.width, crate::Dimension::Px(7.0));+ }++ #[test]+ fn container_query_boolean_evaluation_uses_kleene_truth_tables() {+ let container =+ container_box(crate::ContainerType::InlineSize, &[], 200.0, 16.0);+ let min_width = |threshold| {+ ContainerQueryExpr::Feature(ContainerSizeFeature {+ axis: ContainerQueryAxis::Width,+ comparison: ContainerQueryComparison::Min,+ length: ContainerQueryLength::Px(threshold),+ })+ };+ assert_eq!(+ evaluate_container_query_expr(+ &ContainerQueryExpr::Or(vec![+ min_width(100.0),+ ContainerQueryExpr::Unknown,+ ]),+ &container,+ 16.0,+ ),+ ContainerQueryTruth::True+ );+ assert_eq!(+ evaluate_container_query_expr(+ &ContainerQueryExpr::And(vec![+ min_width(300.0),+ ContainerQueryExpr::Unknown,+ ]),+ &container,+ 16.0,+ ),+ ContainerQueryTruth::False+ );+ assert_eq!(+ evaluate_container_query_expr(+ &ContainerQueryExpr::Or(vec![+ min_width(300.0),+ ContainerQueryExpr::Unknown,+ ]),+ &container,+ 16.0,+ ),+ ContainerQueryTruth::Unknown+ );+ assert_eq!(+ evaluate_container_query_expr(+ &ContainerQueryExpr::Not(Box::new(ContainerQueryExpr::Unknown)),+ &container,+ 16.0,+ ),+ ContainerQueryTruth::Unknown+ );+ }++ #[test]+ fn container_range_syntax_supports_strict_inclusive_and_chained_queries() {+ let container =+ container_box(crate::ContainerType::Size, &[], 200.0, 16.0);+ for query in [+ "(width)",+ "(width > 199px)",+ "(width>=200px)",+ "(199px < width)",+ "(199px < width <= 200px)",+ "(height = 100px)",+ "(block-size >= 100px)",+ ] {+ let expression =+ parse_container_query_expr(query).expect("valid range query");+ assert_eq!(+ evaluate_container_query_expr(&expression, &container, 16.0),+ ContainerQueryTruth::True,+ "{query}"+ );+ }+ for query in [+ "(width > 200px)",+ "(width < 200px)",+ "(200px < width < 300px)",+ "(height > 100px)",+ ] {+ let expression =+ parse_container_query_expr(query).expect("valid range query");+ assert_eq!(+ evaluate_container_query_expr(&expression, &container, 16.0),+ ContainerQueryTruth::False,+ "{query}"+ );+ }+ for invalid in [+ "(100px < width > 200px)",+ "(200px > width < 100px)",+ "(100px = width = 100px)",+ "(100px < width = 200px)",+ ] {+ assert!(+ parse_container_query_expr(invalid).is_none(),+ "invalid mixed/equality chain parsed: {invalid}"+ );+ }+ }++ #[test]+ fn block_axis_query_requires_size_container() {+ let tree = obscura_dom::parse_html(+ r#"<div id="container"><div id="target"></div></div>"#,+ );+ let container = tree.get_element_by_id("container").unwrap();+ let target = tree.get_element_by_id("target").unwrap();+ let sheet = Stylesheet::parse(+ &tree,+ &[r#"+ #target { width:1px }+ @container (height >= 100px) { #target { width:8px } }+ "#+ .to_string()],+ );+ let snapshot = |container_type| {+ let mut snapshot = ContainerSnapshot {+ root_font_size: 16.0,+ ..Default::default()+ };+ snapshot.boxes.insert(+ container,+ container_box(container_type, &[], 300.0, 16.0),+ );+ snapshot+ };+ let (inline_only, _, _) = evaluate_container_styles(+ &tree,+ &sheet,+ target,+ &snapshot(crate::ContainerType::InlineSize),+ );+ assert_eq!(inline_only.width, crate::Dimension::Px(1.0));+ let (size, _, _) = evaluate_container_styles(+ &tree,+ &sheet,+ target,+ &snapshot(crate::ContainerType::Size),+ );+ assert_eq!(size.width, crate::Dimension::Px(8.0));+ }+#[test]fn nested_container_rules_form_a_parent_condition_chain() {let css = "@container shell (min-width:40rem){\diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rsindex 6cbc7236..06a4d92e 100644--- a/crates/obscura-render/src/dom.rs+++ b/crates/obscura-render/src/dom.rs@@ -791,6 +791,7 @@ fn cascade_walk(matcher: &mut obscura_dom::selector::Matcher,styles: &mut HashMap<NodeId, crate::LayoutStyle>,parent_props: &std::rc::Rc<HashMap<String, String>>,+ container_evaluator: &mut Option<&mut crate::css::ContainerQueryEvaluator<'_>>,quirks_mode: bool,viewport: (f32, f32),inherited_cell_padding: Option<f32>,@@ -883,21 +884,48 @@ fn cascade_walk(.get_attribute("class").map(|c| c.split_whitespace().map(|s| s.to_string()).collect()).unwrap_or_default();- if let Some(m) = sheet.apply(- tree,- matcher,- id,- node_id,- &classes,- elem.local.as_ref(),- &mut style,- parent_props,- node.get_attribute("style"),- ) {+ let effective_props = if let Some(evaluator) = container_evaluator.as_deref_mut() {+ sheet.apply_with_container_queries(+ tree,+ matcher,+ id,+ node_id,+ &classes,+ elem.local.as_ref(),+ &mut style,+ parent_props,+ node.get_attribute("style"),+ evaluator,+ )+ } else {+ sheet.apply(+ tree,+ matcher,+ id,+ node_id,+ &classes,+ elem.local.as_ref(),+ &mut style,+ parent_props,+ node.get_attribute("style"),+ )+ };+ if let Some(m) = effective_props {this_props = std::rc::Rc::new(m);}let (before_pseudo, after_pseudo) =- sheet.pseudo_styles(tree, matcher, id, &this_props, &style);+ if let Some(evaluator) = container_evaluator.as_deref_mut() {+ sheet.pseudo_styles_with_container_queries(+ tree,+ matcher,+ id,+ &this_props,+ &style,+ evaluator,+ )+ } else {+ sheet.pseudo_styles(tree, matcher, id, &this_props, &style)+ };style.before_content = before_pseudo.as_ref().filter(|pseudo| pseudo.position != Some(taffy::Position::Absolute))@@ -923,6 +951,7 @@ fn cascade_walk(matcher,styles,&this_props,+ container_evaluator,quirks_mode,viewport,descendant_cell_padding,@@ -972,12 +1001,63 @@ pub fn layout_dom_with_resources(layout_dom_with_web_fonts(tree, viewport, intrinsic, &fonts)}+const CONTAINER_LAYOUT_SAFETY_LIMIT: usize = 512;++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum ContainerLayoutTermination {+ NoQueries,+ GeometryStable,+ SignatureStable,+ OscillationFallback,+ PassCapFallback,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+struct ContainerLayoutTelemetry {+ passes: usize,+ termination: ContainerLayoutTermination,+ query: crate::css::ContainerQueryStats,+}++fn container_iteration_termination<T: PartialEq>(+ geometry_stable: bool,+ signature: &T,+ previous_signature: Option<&T>,+) -> Option<ContainerLayoutTermination> {+ if geometry_stable {+ Some(ContainerLayoutTermination::GeometryStable)+ } else if previous_signature == Some(signature) {+ Some(ContainerLayoutTermination::SignatureStable)+ } else {+ None+ }+}+pub(crate) fn layout_dom_with_web_fonts(tree: &DomTree,viewport: (f32, f32),intrinsic: &HashMap<NodeId, (f32, f32)>,fonts: &[crate::inline::WebFont],) -> DomLayout {+ layout_dom_with_web_fonts_measured(tree, viewport, intrinsic, fonts).0+}++fn layout_dom_with_web_fonts_measured(+ tree: &DomTree,+ viewport: (f32, f32),+ intrinsic: &HashMap<NodeId, (f32, f32)>,+ fonts: &[crate::inline::WebFont],+) -> (DomLayout, ContainerLayoutTelemetry) {+ layout_dom_with_web_fonts_pass_limit(tree, viewport, intrinsic, fonts, None)+}++fn layout_dom_with_web_fonts_pass_limit(+ tree: &DomTree,+ viewport: (f32, f32),+ intrinsic: &HashMap<NodeId, (f32, f32)>,+ fonts: &[crate::inline::WebFont],+ pass_limit: Option<usize>,+) -> (DomLayout, ContainerLayoutTelemetry) {let timing = std::env::var("OBSCURA_RENDER_TIMING").is_ok();// Collect the text of every <style> block in document order.@@ -996,10 +1076,170 @@ pub(crate) fn layout_dom_with_web_fonts(let sheet = crate::css::Stylesheet::parse_for_viewport(tree, &css_sources, viewport);let t_parse = t0.elapsed();+ let (mut laid, _, mut query, mut cascade_time) = layout_dom_once(+ tree,+ viewport,+ intrinsic,+ fonts,+ &sheet,+ None,+ );+ if !sheet.has_container_queries() {+ if timing {+ let (r, i, c, l, u) = sheet.debug_stats();+ eprintln!("[timing] parse+index={:?} cascade={:?} rules={} id_keys={} class_keys={} local_keys={} universal={} cq_passes=1 cq_termination=no-queries", t_parse, cascade_time, r, i, c, l, u);+ }+ return (+ laid,+ ContainerLayoutTelemetry {+ passes: 1,+ termination: ContainerLayoutTermination::NoQueries,+ query,+ },+ );+ }++ let mut snapshot = container_snapshot(tree, &laid);+ let mut previous_candidate: Option<(+ DomLayout,+ crate::css::ContainerDecisionSignature,+ )> = None;+ let mut seen_signatures = Vec::new();+ let mut passes = 1;+ let mut termination = ContainerLayoutTermination::PassCapFallback;+ // Gecko permits at most one CQ-triggered update per container element in+ // one flush and processes ancestors before descendants. Our whole-tree+ // passes need the same order of growth: a chain can legitimately reveal+ // one deeper query container per pass. Scale the useful bound with DOM+ // ancestry and nested conditional depth, retaining a high safety limit+ // against adversarial non-convergence. Hitting it is visible telemetry and+ // uses the conservative fallback below, never a silently stale layout.+ let max_dom_depth = tree+ .descendants(tree.document())+ .into_iter()+ .filter(|id| tree.get_node(*id).is_some_and(|node| node.is_element()))+ .map(|id| {+ let mut depth = 0usize;+ let mut cursor = Some(id);+ while let Some(node) = cursor.and_then(|cursor| tree.get_node(cursor)) {+ depth += usize::from(node.is_element());+ cursor = node.parent;+ }+ depth+ })+ .max()+ .unwrap_or(1);+ let max_passes = pass_limit.unwrap_or_else(|| {+ (max_dom_depth + sheet.container_condition_depth() + 2)+ .clamp(4, CONTAINER_LAYOUT_SAFETY_LIMIT)+ });+ let mut needs_fallback = false;+ for pass in 2..=max_passes {+ let (next, signature, pass_query, pass_cascade) = layout_dom_once(+ tree,+ viewport,+ intrinsic,+ fonts,+ &sheet,+ Some(&snapshot),+ );+ passes = pass;+ query.evaluations += pass_query.evaluations;+ query.cache_hits += pass_query.cache_hits;+ query.ancestor_steps += pass_query.ancestor_steps;+ cascade_time += pass_cascade;+ let next_snapshot = container_snapshot(tree, &next);+ let signature = signature.expect("container pass must produce a signature");+ if let Some(reason) = container_iteration_termination(+ next_snapshot == snapshot,+ &signature,+ previous_candidate+ .as_ref()+ .map(|(_, signature)| signature),+ ) {+ termination = reason;+ // Equal adjacent signatures prove that the *previous* candidate's+ // applied decisions match an evaluation of its own final+ // snapshot. Returning `next` here would be off by one and could+ // expose styles evaluated against geometry it no longer has.+ laid = if reason == ContainerLayoutTermination::SignatureStable {+ previous_candidate+ .take()+ .expect("stable signature requires a previous candidate")+ .0+ } else {+ next+ };+ break;+ }+ if seen_signatures.contains(&signature) {+ termination = ContainerLayoutTermination::OscillationFallback;+ needs_fallback = true;+ break;+ }+ seen_signatures.push(signature.clone());+ previous_candidate = Some((next, signature));+ snapshot = next_snapshot;+ if pass == max_passes {+ needs_fallback = true;+ }+ }++ if needs_fallback {+ // Author-controlled CSS must never crash rendering, but neither may+ // we return a layout whose conditional declarations contradict the+ // geometry used to choose them. Disable the unstable conditional+ // rules for this render and expose the downgrade in telemetry.+ let (fallback, _, fallback_query, fallback_cascade) = layout_dom_once(+ tree,+ viewport,+ intrinsic,+ fonts,+ &sheet,+ None,+ );+ laid = fallback;+ passes += 1;+ query.evaluations += fallback_query.evaluations;+ query.cache_hits += fallback_query.cache_hits;+ query.ancestor_steps += fallback_query.ancestor_steps;+ cascade_time += fallback_cascade;+ }++ if timing {+ let (r, i, c, l, u) = sheet.debug_stats();+ eprintln!("[timing] parse+index={:?} cascade_total={:?} rules={} id_keys={} class_keys={} local_keys={} universal={} cq_passes={} cq_termination={:?} cq_evaluations={} cq_cache_hits={} cq_ancestor_steps={}", t_parse, cascade_time, r, i, c, l, u, passes, termination, query.evaluations, query.cache_hits, query.ancestor_steps);+ }+ (+ laid,+ ContainerLayoutTelemetry {+ passes,+ termination,+ query,+ },+ )+}++fn layout_dom_once(+ tree: &DomTree,+ viewport: (f32, f32),+ intrinsic: &HashMap<NodeId, (f32, f32)>,+ fonts: &[crate::inline::WebFont],+ sheet: &crate::css::Stylesheet,+ snapshot: Option<&crate::css::ContainerSnapshot>,+) -> (+ DomLayout,+ Option<crate::css::ContainerDecisionSignature>,+ crate::css::ContainerQueryStats,+ std::time::Duration,+) {let t1 = std::time::Instant::now();let mut matcher = tree.matcher();let mut styles: HashMap<NodeId, crate::LayoutStyle> = HashMap::new();let root_props = std::rc::Rc::new(HashMap::new());+ let mut evaluator =+ snapshot.map(|snapshot| crate::css::ContainerQueryEvaluator::new(tree, snapshot));+ let mut evaluator_ref = evaluator.as_mut();// A real preorder walk (not a flat descendants() scan) so the matcher's// ancestor bloom filter tracks the current path: push before recursing// into children, pop on the way back out. This is what lets descendant@@ -1020,15 +1260,20 @@ pub(crate) fn layout_dom_with_web_fonts(&mut matcher,&mut styles,&root_props,+ &mut evaluator_ref,quirks_mode,viewport,None,false,);- if timing {- let (r, i, c, l, u) = sheet.debug_stats();- eprintln!("[timing] parse+index={:?} cascade={:?} rules={} id_keys={} class_keys={} local_keys={} universal={}", t_parse, t1.elapsed(), r, i, c, l, u);- }+ let cascade_time = t1.elapsed();+ let (signature, query_stats) = evaluator.map_or_else(+ || (None, crate::css::ContainerQueryStats::default()),+ |evaluator| {+ let (signature, stats) = evaluator.finish();+ (Some(signature), stats)+ },+ );grow_trailing_auto_cells(tree, &mut styles);// The leaf context is the index of a cosmic-text inline formatting@@ -2689,20 +2934,90 @@ pub(crate) fn layout_dom_with_web_fonts(}).collect();- DomLayout {- rects,- styles,- clip_rects,- translates,- text_runs,- #[cfg(feature = "paint")]- text_engine: engine,- #[cfg(feature = "paint")]- ifc_items: ifc_items.whole,- #[cfg(feature = "paint")]- run_ifc_items: ifc_items.runs,- generated_boxes,+ (+ DomLayout {+ rects,+ styles,+ clip_rects,+ translates,+ text_runs,+ #[cfg(feature = "paint")]+ text_engine: engine,+ #[cfg(feature = "paint")]+ ifc_items: ifc_items.whole,+ #[cfg(feature = "paint")]+ run_ifc_items: ifc_items.runs,+ generated_boxes,+ },+ signature,+ query_stats,+ cascade_time,+ )+}++fn container_snapshot(+ tree: &DomTree,+ layout: &DomLayout,+) -> crate::css::ContainerSnapshot {+ let root_font_size = tree+ .descendants(tree.document())+ .into_iter()+ .find(|id| tree.get_node(*id).is_some_and(|node| node.is_element()))+ .and_then(|id| layout.styles.get(&id))+ .and_then(|style| style.font_size)+ .filter(|size| size.is_finite() && *size > 0.0)+ .unwrap_or(16.0);+ let mut snapshot = crate::css::ContainerSnapshot {+ root_font_size,+ ..Default::default()+ };+ for (&id, style) in &layout.styles {+ let available_type = if style.internal_flex_container || style.is_table_box {+ crate::ContainerType::Normal+ } else {+ effective_container_type(style)+ };+ if (style.container_type == crate::ContainerType::Normal+ && style.container_names.is_empty())+ || style.display == crate::Display::None+ || style.display_contents+ {+ continue;+ }+ let rect = layout.rects.get(&id);+ // An inline box that computes to `container-type` is still the+ // nearest matching query container even when size containment cannot+ // apply to it. Inline layout may flatten that box and omit a DOM rect,+ // but dropping it from the snapshot would incorrectly let the query+ // fall through to a farther ancestor. Its queried axes are+ // unavailable, so the placeholder geometry is intentionally unused.+ if rect.is_none() && available_type != crate::ContainerType::Normal {+ continue;+ }+ let horizontal_edges =+ style.border.left + style.border.right + style.padding.left + style.padding.right;+ let vertical_edges =+ style.border.top + style.border.bottom + style.padding.top + style.padding.bottom;+ snapshot.boxes.insert(+ id,+ crate::css::ContainerBox {+ container_type: style.container_type,+ available_type,+ names: style.container_names.clone(),+ content_width: rect+ .map(|rect| (rect.width - horizontal_edges).max(0.0))+ .unwrap_or(0.0),+ content_height: rect+ .map(|rect| (rect.height - vertical_edges).max(0.0))+ .unwrap_or(0.0),+ font_size: style+ .font_size+ .filter(|size| size.is_finite() && *size > 0.0)+ .unwrap_or(16.0),+ },+ );}+ snapshot}/// HTML table auto-layout approximation: for each `<tr>`, the last `<td>`/@@ -5034,6 +5349,129 @@ fn build_table(Some(table_node)}+/// Effective size-query containment for this generated box.+///+/// CSS size containment has no effect on a non-atomic inline box. Keeping the+/// check centralized also prevents such an inline from being exposed as a+/// size-query container by `container_snapshot`.+fn effective_container_type(style: &crate::LayoutStyle) -> crate::ContainerType {+ if style.display == crate::Display::Inline && !style.is_inline_block {+ crate::ContainerType::Normal+ } else {+ style.container_type+ }+}++/// Does this auto inline-size use shrink-to-fit/content sizing rather than+/// filling a definite containing block?+fn container_auto_inline_size_is_intrinsic(+ tree: &DomTree,+ id: NodeId,+ style: &crate::LayoutStyle,+ styles: &HashMap<NodeId, crate::LayoutStyle>,+) -> bool {+ if style.is_inline_block || style.float.is_some() {+ return true;+ }+ if matches!(style.position, Some(taffy::Position::Absolute)) {+ // An absolutely positioned auto width is fill-available only when+ // both inline insets are definite.+ return style.inset[1].is_none() || style.inset[3].is_none();+ }++ let mut parent = tree.get_node(id).and_then(|node| node.parent);+ let parent_style = loop {+ let Some(parent_id) = parent else { return false };+ let Some(parent_style) = styles.get(&parent_id) else {+ return false;+ };+ if parent_style.display_contents {+ parent = tree.get_node(parent_id).and_then(|node| node.parent);+ continue;+ }+ break parent_style;+ };+ match parent_style.display {+ crate::Display::Flex => {+ let row = !matches!(+ parent_style.flex_direction,+ Some(+ taffy::FlexDirection::Column+ | taffy::FlexDirection::ColumnReverse+ )+ );+ if row {+ true+ } else {+ style+ .align_self+ .unwrap_or(+ parent_style+ .align_items+ .unwrap_or(taffy::AlignItems::STRETCH),+ )+ != taffy::AlignSelf::STRETCH+ }+ }+ crate::Display::Grid => {+ style+ .justify_self+ .unwrap_or(+ parent_style+ .justify_items+ .unwrap_or(taffy::JustifyItems::STRETCH),+ )+ != taffy::AlignSelf::STRETCH+ }+ crate::Display::Inline => true,+ _ => false,+ }+}++/// Apply the used-size part of `container-type`'s implicit size containment.+///+/// The default contain-intrinsic-size is zero. Fill-available block boxes keep+/// their normal auto inline size, which is already descendant-independent.+/// Shrink-to-fit boxes instead receive a zero intrinsic inline size, and a+/// `size` container with auto block-size receives a zero intrinsic block size.+/// Descendants remain in the layout tree and may visibly overflow; size+/// containment is not paint containment and must not clip them.+fn apply_container_size_containment(+ tree: &DomTree,+ id: NodeId,+ style: &crate::LayoutStyle,+ styles: &HashMap<NodeId, crate::LayoutStyle>,+ taffy_style: &mut taffy::Style,+) {+ let kind = effective_container_type(style);+ if kind == crate::ContainerType::Normal {+ return;+ }++ if matches!(style.min_width, crate::Dimension::Auto) {+ taffy_style.min_size.width = taffy::Dimension::length(0.0);+ }+ let ratio_transfers_inline_size =+ style.aspect_ratio.is_some() && !matches!(style.height, crate::Dimension::Auto);+ if matches!(style.width, crate::Dimension::Auto)+ && !ratio_transfers_inline_size+ && container_auto_inline_size_is_intrinsic(tree, id, style, styles)+ {+ taffy_style.size.width = taffy::Dimension::length(0.0);+ }++ if kind == crate::ContainerType::Size {+ if matches!(style.min_height, crate::Dimension::Auto) {+ taffy_style.min_size.height = taffy::Dimension::length(0.0);+ }+ let ratio_transfers_block_size =+ style.aspect_ratio.is_some() && !matches!(style.width, crate::Dimension::Auto);+ if matches!(style.height, crate::Dimension::Auto) && !ratio_transfers_block_size {+ taffy_style.size.height = taffy::Dimension::length(0.0);+ }+ }+}+fn build(tree: &DomTree,id: NodeId,@@ -5062,6 +5500,7 @@ fn build(}let mut taffy_style = to_taffy_style(style);+ apply_container_size_containment(tree, id, style, styles, &mut taffy_style);// A non-stretched flex item in a column flex container uses fit-content// for its auto inline size. In a nested flex layout taffy can retain the@@ -6365,6 +6804,7 @@ fn max_definite_descendant_width(tree: &DomTree, id: NodeId, styles: &HashMap<Nofn establishes_block_formatting_context(style: &crate::LayoutStyle) -> bool {matches!(style.display, crate::Display::Flex | crate::Display::Grid)+ || effective_container_type(style) != crate::ContainerType::Normal|| style.flow_root|| style.overflow_hidden|| style.is_inline_block@@ -6938,6 +7378,343 @@ mod tests {);}+ #[test]+ fn container_query_uses_final_content_box_geometry() {+ let tree = parse_html(+ r#"<html><head><style>+ #container {+ box-sizing:border-box;+ container-type:inline-size;+ width:500px;+ padding:20px;+ border:10px solid;+ }+ #target { width:1px; height:1px }+ @container (width >= 440px) { #target { width:44px } }+ @container (width > 499px) { #target { width:50px } }+ </style></head><body>+ <div id="container"><div id="target"></div></div>+ </body></html>"#,+ );+ let (laid, telemetry) =+ layout_dom_with_web_fonts_measured(&tree, (1280.0, 720.0), &HashMap::new(), &[]);+ let container = tree.get_element_by_id("container").unwrap();+ let target = tree.get_element_by_id("target").unwrap();+ assert!((laid.rects[&container].width - 500.0).abs() < 0.1);+ assert_eq!(laid.styles[&target].width, crate::Dimension::Px(44.0));+ assert_eq!(telemetry.passes, 2);+ assert_eq!(+ telemetry.termination,+ ContainerLayoutTermination::GeometryStable+ );+ }++ #[test]+ fn container_query_named_and_unnamed_lookup_choose_different_ancestors() {+ let tree = parse_html(+ r#"<html><head><style>+ #outer { container: shell / inline-size; width:600px }+ #inner { container: other / inline-size; width:300px }+ #target { width:1px; height:1px }+ @container shell (min-width:500px) { #target { width:11px } }+ @container (min-width:500px) { #target { height:22px } }+ </style></head><body>+ <div id="outer"><div id="inner"><div id="target"></div></div></div>+ </body></html>"#,+ );+ let laid = layout_dom(&tree, (1280.0, 720.0));+ let target = tree.get_element_by_id("target").unwrap();+ assert_eq!(laid.styles[&target].width, crate::Dimension::Px(11.0));+ assert_eq!(laid.styles[&target].height, crate::Dimension::Px(1.0));+ }++ #[test]+ fn nested_container_queries_select_independent_ancestors() {+ let tree = parse_html(+ r#"<html><head><style>+ #outer { container: outer / inline-size; width:600px }+ #inner { container: inner / inline-size; width:200px }+ #target { width:1px }+ @container outer (min-width:500px) {+ @container inner (min-width:200px) {+ #target { width:19px }+ }+ }+ </style></head><body>+ <div id="outer"><div id="inner"><div id="target"></div></div></div>+ </body></html>"#,+ );+ let laid = layout_dom(&tree, (1280.0, 720.0));+ let target = tree.get_element_by_id("target").unwrap();+ assert_eq!(laid.styles[&target].width, crate::Dimension::Px(19.0));+ }++ #[test]+ fn container_query_pseudo_can_select_its_originating_element() {+ let tree = parse_html(+ r#"<html><head><style>+ #container { container-type:inline-size; width:300px }+ @container (min-width:300px) {+ #container::before { content:"active"; display:block }+ }+ </style></head><body><div id="container"></div></body></html>"#,+ );+ let laid = layout_dom(&tree, (1280.0, 720.0));+ let container = tree.get_element_by_id("container").unwrap();+ assert_eq!(+ laid.styles[&container]+ .before_pseudo+ .as_ref()+ .and_then(|pseudo| pseudo.before_content.as_deref()),+ Some("active")+ );+ }++ #[test]+ fn container_type_zeroes_shrink_to_fit_inline_intrinsic_widths() {+ let tree = parse_html(+ r#"<style>+ html,body{margin:0}+ #host{width:600px}+ .container{container-type:inline-size}+ .wide{width:240px;height:30px}+ #inline-block{display:inline-block}+ #inline-flex{display:inline-flex}+ #inline-grid{display:inline-grid}+ </style>+ <div id="host">+ <div id="inline-block" class="container"><div class="wide"></div></div>+ <div id="inline-flex" class="container"><div class="wide"></div></div>+ <div id="inline-grid" class="container"><div class="wide"></div></div>+ </div>"#,+ );+ let laid = layout_dom(&tree, (600.0, 300.0));+ for name in ["inline-block", "inline-flex", "inline-grid"] {+ let id = tree.get_element_by_id(name).unwrap();+ let rect = laid.rects[&id];+ assert!(+ rect.width.abs() < 0.01,+ "{name} descendants leaked into contained intrinsic width: {rect:?}"+ );+ assert!(+ rect.height >= 29.9,+ "inline-size containment must retain content-driven block size: {rect:?}"+ );+ }+ }++ #[test]+ fn size_container_auto_block_size_ignores_descendants() {+ let tree = parse_html(+ r#"<style>+ html,body{margin:0}+ .container{width:200px}+ .child{height:80px}+ #inline-only{container-type:inline-size}+ #both{container-type:size}+ </style>+ <div id="inline-only" class="container"><div class="child"></div></div>+ <div id="both" class="container"><div class="child"></div></div>"#,+ );+ let laid = layout_dom(&tree, (600.0, 300.0));+ let inline_only = laid.rects[&tree.get_element_by_id("inline-only").unwrap()];+ let both = laid.rects[&tree.get_element_by_id("both").unwrap()];+ assert!((inline_only.height - 80.0).abs() < 0.01, "{inline_only:?}");+ assert!(+ both.height.abs() < 0.01,+ "size containment must use the zero contain-intrinsic block size: {both:?}"+ );+ }++ #[test]+ fn container_type_establishes_a_float_containing_formatting_context() {+ let tree = parse_html(+ r#"<style>+ html,body{margin:0}+ #container{container-type:inline-size;width:200px}+ #float{float:left;width:50px;height:40px}+ </style>+ <div id="container"><div id="float"></div></div>"#,+ );+ let laid = layout_dom(&tree, (600.0, 200.0));+ let container = laid.rects[&tree.get_element_by_id("container").unwrap()];+ assert!(+ (container.height - 40.0).abs() < 0.01,+ "query container must contain its descendant float: {container:?}"+ );+ }++ #[test]+ fn ineligible_nearest_inline_container_does_not_fall_through() {+ let tree = parse_html(+ r#"<style>+ #outer{container-type:inline-size;width:500px}+ #inner{display:inline;container-type:inline-size}+ #target{width:1px}+ @container (min-width:400px){#target{width:99px}}+ </style>+ <div id="outer"><span id="inner"><span id="target"></span></span></div>"#,+ );+ let laid = layout_dom(&tree, (600.0, 200.0));+ let target = tree.get_element_by_id("target").unwrap();+ assert_eq!(+ laid.styles[&target].width,+ crate::Dimension::Px(1.0),+ "the unavailable nearest query axis must be unknown, not select the outer container"+ );+ }++ #[test]+ fn ineligible_nearest_table_container_does_not_fall_through() {+ let tree = parse_html(+ r#"<style>+ #outer{container-type:inline-size;width:500px}+ #inner{display:table;container-type:inline-size;width:300px}+ #target{width:1px}+ @container (min-width:400px){#target{width:99px}}+ </style>+ <div id="outer"><div id="inner"><div id="target"></div></div></div>"#,+ );+ let laid = layout_dom(&tree, (600.0, 200.0));+ let inner = tree.get_element_by_id("inner").unwrap();+ let target = tree.get_element_by_id("target").unwrap();+ assert!(+ laid.styles[&inner].is_table_box,+ "the internal block approximation lost authored table provenance"+ );+ assert_eq!(+ laid.styles[&target].width,+ crate::Dimension::Px(1.0),+ "an unavailable nearest table query axis must not fall through to the outer container"+ );+ }++ #[test]+ fn formerly_oscillating_inline_container_settles_consistently() {+ let tree = parse_html(+ r#"<style>+ #container{display:inline-block;container-type:inline-size}+ #child{width:200px;height:10px}+ @container (min-width:100px){#child{width:50px}}+ </style>+ <div id="container"><div id="child"></div></div>"#,+ );+ let (laid, telemetry) =+ layout_dom_with_web_fonts_measured(&tree, (600.0, 200.0), &HashMap::new(), &[]);+ let container = laid.rects[&tree.get_element_by_id("container").unwrap()];+ let child = tree.get_element_by_id("child").unwrap();+ assert!(container.width.abs() < 0.01, "{container:?}");+ assert_eq!(laid.styles[&child].width, crate::Dimension::Px(200.0));+ assert!(matches!(+ telemetry.termination,+ ContainerLayoutTermination::GeometryStable+ | ContainerLayoutTermination::SignatureStable+ ));+ }++ #[test]+ fn pass_cap_uses_visible_conservative_fallback_without_panicking() {+ let tree = parse_html(+ r#"<style>+ #c0{container:c0/inline-size;width:100px}+ #target{width:1px}+ @container c0 (min-width:100px){+ #c1{container:c1/inline-size;width:100px}+ }+ @container c1 (min-width:100px){#target{width:99px}}+ </style>+ <div id="c0"><div id="c1"><div id="target"></div></div></div>"#,+ );+ let (laid, telemetry) = layout_dom_with_web_fonts_pass_limit(+ &tree,+ (600.0, 200.0),+ &HashMap::new(),+ &[],+ Some(2),+ );+ let target = tree.get_element_by_id("target").unwrap();+ assert_eq!(laid.styles[&target].width, crate::Dimension::Px(1.0));+ assert_eq!(+ telemetry.termination,+ ContainerLayoutTermination::PassCapFallback+ );+ assert_eq!(telemetry.passes, 3);+ }++ #[test]+ fn ten_level_container_activation_propagates_without_fixed_pass_truncation() {+ let mut css = String::from(+ "#c0{container:c0/inline-size;width:100px}#target{width:1px}",+ );+ for level in 0..10 {+ css.push_str(&format!(+ "@container c{level} (min-width:100px){{#c{}{{container:c{}/inline-size;width:100px}}}}",+ level + 1,+ level + 1+ ));+ }+ css.push_str(+ "@container c10 (min-width:100px){#target{width:77px}}",+ );+ let mut body = String::new();+ for level in 0..=10 {+ body.push_str(&format!("<div id=\"c{level}\">"));+ }+ body.push_str("<div id=\"target\"></div>");+ for _ in 0..=10 {+ body.push_str("</div>");+ }+ let tree = parse_html(&format!("<style>{css}</style>{body}"));+ let (laid, telemetry) =+ layout_dom_with_web_fonts_measured(&tree, (800.0, 600.0), &HashMap::new(), &[]);+ let target = tree.get_element_by_id("target").unwrap();+ assert_eq!(laid.styles[&target].width, crate::Dimension::Px(77.0));+ assert!(+ telemetry.passes > 8,+ "deep propagation unexpectedly truncated: {telemetry:?}"+ );+ assert!(!matches!(+ telemetry.termination,+ ContainerLayoutTermination::PassCapFallback+ | ContainerLayoutTermination::OscillationFallback+ ));+ }++ #[test]+ fn layout_without_container_queries_keeps_one_pass_fast_path() {+ let tree = parse_html(+ r#"<html><head><style>#target{width:25px}</style></head>+ <body><div id="target"></div></body></html>"#,+ );+ let (_, telemetry) =+ layout_dom_with_web_fonts_measured(&tree, (800.0, 600.0), &HashMap::new(), &[]);+ assert_eq!(+ telemetry,+ ContainerLayoutTelemetry {+ passes: 1,+ termination: ContainerLayoutTermination::NoQueries,+ query: crate::css::ContainerQueryStats::default(),+ }+ );+ }++ #[test]+ fn container_convergence_classifies_self_consistent_stability() {+ assert_eq!(+ container_iteration_termination(true, &3, Some(&2)),+ Some(ContainerLayoutTermination::GeometryStable)+ );+ assert_eq!(+ container_iteration_termination(false, &3, Some(&3)),+ Some(ContainerLayoutTermination::SignatureStable)+ );+ assert_eq!(+ container_iteration_termination(false, &3, Some(&2)),+ None+ );+ assert_eq!(CONTAINER_LAYOUT_SAFETY_LIMIT, 512);+ }+#[test]fn declarative_shadow_style_does_not_leak_into_document_cascade() {let tree = parse_html(diff --git a/crates/obscura-render/src/lib.rs b/crates/obscura-render/src/lib.rsindex c7f3ff92..1ca01574 100644--- a/crates/obscura-render/src/lib.rs+++ b/crates/obscura-render/src/lib.rs@@ -222,6 +222,13 @@ pub struct LayoutStyle {/// layout such as table cells, rather than the computed CSS display./// Descendants are not CSS flex items in these containers.pub internal_flex_container: bool,+ /// The computed inner display is `table`.+ ///+ /// Taffy has no table display mode, so authored table boxes are represented+ /// by block/grid-compatible layout styles. Keep this provenance for CSS+ /// features such as container-query axis availability that depend on the+ /// computed display rather than our internal layout approximation.+ pub(crate) is_table_box: bool,/// The HTML UA sheet's vendor `text-align` behavior for `<center>`./// Unlike ordinary `text-align:center`, it also centers fixed-width block/// descendants while leaving auto-width blocks fill-available.diff --git a/crates/obscura-render/src/style.rs b/crates/obscura-render/src/style.rsindex 52bf54d1..057b30e1 100644--- a/crates/obscura-render/src/style.rs+++ b/crates/obscura-render/src/style.rs@@ -554,20 +554,27 @@ fn apply_value(style: &mut LayoutStyle, name: &str, value: &str) {| "contents") {style.internal_flex_container = false;+ style.is_table_box = false;style.is_inline_block = false;style.flow_root = false;}match value {"none" => style.display = crate::Display::None,"flex" => style.display = crate::Display::Flex,- "inline-flex" => style.display = crate::Display::Flex,+ "inline-flex" => {+ style.display = crate::Display::Flex;+ style.is_inline_block = true;+ }"inline" => style.display = crate::Display::Inline,"inline-block" => {style.display = crate::Display::Inline;style.is_inline_block = true;}"grid" => style.display = crate::Display::Grid,- "inline-grid" => style.display = crate::Display::Grid,+ "inline-grid" => {+ style.display = crate::Display::Grid;+ style.is_inline_block = true;+ }"block" => style.display = crate::Display::Block,"flow-root" => {style.display = crate::Display::Block;@@ -580,11 +587,13 @@ fn apply_value(style: &mut LayoutStyle, name: &str, value: &str) {"table" => {style.display = crate::Display::Block;style.flow_root = true;+ style.is_table_box = true;}"inline-table" => {style.display = crate::Display::Inline;style.is_inline_block = true;style.flow_root = true;+ style.is_table_box = true;}"contents" => {// `display:contents` can override an earlier `display:none`@@ -4481,11 +4490,17 @@ mod tests {let table = compute_style("div", Some("display:none; display:table"));assert_eq!(table.display, Display::Block);assert!(table.flow_root);+ assert!(table.is_table_box);let inline_table = compute_style("div", Some("display:block; display:inline-table"));assert_eq!(inline_table.display, Display::Inline);assert!(inline_table.is_inline_block);assert!(inline_table.flow_root);+ assert!(inline_table.is_table_box);++ let reset_table = compute_style("div", Some("display:table; display:grid"));+ assert_eq!(reset_table.display, Display::Grid);+ assert!(!reset_table.is_table_box);}#[test]